@EventHandler(priority = EventPriority.MONITOR)
  public void onPlayerMove(PlayerMoveEvent event) {

    // BAD BAD BAD test code
    //	hwh.randomlyRegisterWorld(event.getPlayer().getWorld());

    Location to = event.getTo();
    int newY = to.getBlockY();
    if (newY < HigherWorldsHack.SHARE_HEIGHT) {
      Player p = event.getPlayer();
      World w = worldStack.get(event.getTo().getWorld());
      if (w == null) return;
      Location toTeleportTo =
          new Location(w, to.getX(), HigherWorldsHack.transformPosUp(newY), to.getZ());
      HigherWorldsHack.HWH_LOGGER.log(
          Level.WARNING, "Player moved from " + to + " to " + toTeleportTo);
      p.teleport(toTeleportTo);
    } else if (newY > HigherWorldsHack.WORLD_HEIGHT - HigherWorldsHack.SHARE_HEIGHT) {
      Player p = event.getPlayer();
      World w = worldStack.inverse().get(event.getTo().getWorld());
      if (w == null) return;
      Location toTeleportTo =
          new Location(w, to.getX(), HigherWorldsHack.transformPosDown(newY), to.getZ());
      HigherWorldsHack.HWH_LOGGER.log(
          Level.WARNING, "Player moved from " + to + " to " + toTeleportTo);
      p.teleport(toTeleportTo);
    }
  }
  /**
   * get a Target instance. A target consists of a reference name and an EvalNode corresponding to
   * the reference name. According to evaluation state, it returns different EvalNodes. If the
   * expression corresponding to the reference name is evaluated, it just returns {@link FieldEval}
   * (i.e., a column reference). Otherwise, it returns the original EvalNode of the expression.
   *
   * @param referenceName The reference name to get EvalNode
   * @param unevaluatedForm If TRUE, it always return the annotated EvalNode of the expression.
   * @return
   */
  public Target getTarget(String referenceName, boolean unevaluatedForm) {
    String normalized = referenceName;
    int refId = nameToIdMap.get(normalized);

    if (!unevaluatedForm
        && evaluationStateMap.containsKey(refId)
        && evaluationStateMap.get(refId)) {
      EvalNode evalNode = idToEvalMap.get(refId);

      // If the expression is already evaluated, it should use the FieldEval to access a field
      // value.
      // But, if this reference name is not primary name, it cannot use the reference name.
      // It changes the given reference name to the primary name.
      if (isEvaluated(normalized) && !isPrimaryName(refId, referenceName)) {
        return new Target(
            new FieldEval(getPrimaryName(refId), evalNode.getValueType()), referenceName);
      }

      EvalNode referredEval;
      if (evalNode.getType() == EvalType.CONST) {
        referredEval = evalNode;
      } else {
        referredEval = new FieldEval(idToNamesMap.get(refId).get(0), evalNode.getValueType());
      }
      return new Target(referredEval, referenceName);

    } else {
      if (idToEvalMap.containsKey(refId)) {
        return new Target(idToEvalMap.get(refId), referenceName);
      } else {
        return null;
      }
    }
  }
 @SuppressWarnings({
   "rawtypes",
   "unchecked"
 }) // I can't parameterize this either; it scares the compiler
 private static <T extends VariantData<U, T, ?>, U extends CatalogType> T getItemData(
     ItemStack item, Class<T> type, BiMap<U, Integer> map) {
   int damage = item.getDurability();
   if (!map.containsValue(damage)) {
     throw new UnsupportedOperationException();
   }
   // no idea why a typecast is necessary here but excluding it makes javac angry
   @SuppressWarnings("RedundantCast")
   T data =
       (T)
           Pore.getGame()
               .getRegistry()
               .createItemBuilder()
               .itemType(MaterialConverter.asItem(item.getType()))
               .quantity(1)
               .build()
               .getOrCreate(type)
               .get();
   data.type().set(map.inverse().get(damage));
   return data;
 }
  @Test
  public void testBasicNoRulesExchange() {
    GiftExchangeDefinition def = new GiftExchangeDefinition();
    User joe = makeUser("Joe");
    User bob = makeUser("Bob");
    User sue = makeUser("Sue");
    User ann = makeUser("Ann");

    def.setParticipants(Arrays.asList(joe, bob, sue, ann));

    IllegalPairRule joeAnn = new IllegalPairRule(joe, ann);
    def.setIllegalPairs(Arrays.asList(joeAnn));

    Set<BiMap<User, User>> allMappings = def.getAllMappings();
    for (BiMap<User, User> mapping : allMappings) {
      System.out.println(mapping);
      assertFalse(mapping.get(joe) == ann);
    }
    System.out.println("---------------------------------------------");

    IllegalPairRule bobJoe = new IllegalPairRule(bob, joe);
    def.setIllegalPairs(Arrays.asList(bobJoe, joeAnn));
    allMappings = def.getAllMappings();

    for (BiMap<User, User> mapping : allMappings) {
      System.out.println(mapping);
      assertFalse(mapping.get(joe).equals(ann));
      assertFalse(mapping.get(bob).equals(joe));
    }
  }
 @Override
 public boolean add(TravelingItem item) {
   if (delegate.containsValue(item)) return false;
   item.setContainer(container);
   delegate.put(item.id, item);
   return true;
 }
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    String request = packet.content().toString(CharsetUtil.UTF_8);
    if (logger.isDebugEnabled())
      logger.debug("Sender " + packet.sender() + " sent request:" + request);

    if (!sessionList.inverse().containsKey(packet.sender())) {
      String session = UUID.randomUUID().toString();
      String localAddress = ctx.channel().localAddress().toString();
      String remoteAddress = ctx.channel().remoteAddress().toString();
      SubscriptionManagerFactory.getInstance()
          .add(session, session, outputType, localAddress, remoteAddress);
      sessionList.put(session, packet.sender());
      if (logger.isDebugEnabled())
        logger.debug("Added Sender " + packet.sender() + ", session:" + session);
      ctx.channel()
          .writeAndFlush(
              new DatagramPacket(
                  Unpooled.copiedBuffer(
                      Util.getWelcomeMsg().toString() + "\r\n", CharsetUtil.UTF_8),
                  packet.sender()));
    }

    Map<String, Object> headers = getHeaders(sessionList.inverse().get(packet.sender()));
    producer.sendBodyAndHeaders(request, headers);
  }
  public void addBootstrapToken(Token token, InetAddress endpoint) {
    assert token != null;
    assert endpoint != null;

    lock.writeLock().lock();
    try {
      InetAddress oldEndPoint = null;

      oldEndPoint = bootstrapTokens.get(token);
      if (oldEndPoint != null && !oldEndPoint.equals(endpoint))
        throw new RuntimeException(
            "Bootstrap Token collision between "
                + oldEndPoint
                + " and "
                + endpoint
                + " (token "
                + token);

      oldEndPoint = tokenToEndPointMap.get(token);
      if (oldEndPoint != null && !oldEndPoint.equals(endpoint))
        throw new RuntimeException(
            "Bootstrap Token collision between "
                + oldEndPoint
                + " and "
                + endpoint
                + " (token "
                + token);

      bootstrapTokens.inverse().remove(endpoint);
      bootstrapTokens.put(token, endpoint);
    } finally {
      lock.writeLock().unlock();
    }
  }
 public IdEObject getByOid(long oid) {
   IdEObject result = objectsToCommitFirst.inverse().get(oid);
   if (result == null) {
     return objectsToCommitSecond.inverse().get(oid);
   }
   return result;
 }
Beispiel #9
0
  @Override
  protected void runTask() {
    DateTime start = new DateTime(DateTimeZones.UTC);
    log.info("C4 EPG Update initiated");

    DayRange dayRange = rangeGenerator.generate(new LocalDate(DateTimeZones.UTC));

    BiMap<String, Channel> channelMap = c4AtomApi.getChannelMap();
    int total = Iterables.size(dayRange) * channelMap.size();
    int processed = 0;
    UpdateProgress progress = UpdateProgress.START;

    for (Map.Entry<String, Channel> channelEntry : channelMap.entrySet()) {
      for (LocalDate scheduleDay : dayRange) {
        reportStatus(progressReport("Processing", processed++, total, progress));
        progress =
            progress.reduce(
                channelDayUpdater.update(
                    channelEntry.getKey(), channelEntry.getValue(), scheduleDay));
      }
    }

    reportStatus(progressReport("Processed", processed++, total, progress));
    String runTime =
        new Period(start, new DateTime(DateTimeZones.UTC)).toString(PeriodFormat.getDefault());
    log.info("C4 EPG Update finished in " + runTime);

    if (progress.hasFailures()) {
      throw new IllegalStateException(
          String.format("Completed with %s failures", progress.getFailures()));
    }
  }
 @Override
 public T apply(F from) {
   final T result = map.get(from);
   Preconditions.checkArgument(
       result != null || map.containsKey(from), "Key '%s' not present in map", from);
   return result;
 }
  /**
   * Store an end-point to host ID mapping. Each ID must be unique, and cannot be changed after the
   * fact.
   *
   * @param hostId
   * @param endpoint
   */
  public void updateHostId(UUID hostId, InetAddress endpoint) {
    assert hostId != null;
    assert endpoint != null;

    lock.writeLock().lock();
    try {
      InetAddress storedEp = endpointToHostIdMap.inverse().get(hostId);
      if (storedEp != null) {
        if (!storedEp.equals(endpoint) && (FailureDetector.instance.isAlive(storedEp))) {
          throw new RuntimeException(
              String.format(
                  "Host ID collision between active endpoint %s and %s (id=%s)",
                  storedEp, endpoint, hostId));
        }
      }

      UUID storedId = endpointToHostIdMap.get(endpoint);
      if ((storedId != null) && (!storedId.equals(hostId)))
        logger.warn("Changing {}'s host ID from {} to {}", endpoint, storedId, hostId);

      endpointToHostIdMap.forcePut(endpoint, hostId);
    } finally {
      lock.writeLock().unlock();
    }
  }
Beispiel #12
0
 @Override
 public int enumerateLabel(String label) {
   if (!labelEnumeration.containsKey(label)) {
     labelEnumeration.put(label, nextLabel);
     nextLabel++;
   }
   return labelEnumeration.get(label);
 }
Beispiel #13
0
 public static BiMap<Combo, Integer> getComboTuneMap() {
   int mod = getAsciiTuneMods();
   BiMap<Combo, Integer> map = HashBiMap.create();
   for (Map.Entry<Integer, Integer> entry : getAsciTuneMap().entrySet()) {
     map.put(new Combo(mod, entry.getKey()), entry.getValue());
   }
   return map;
 }
 /**
  * Create a predicate with a name associated to it. If the same name is passed again to this
  * method, the old predicate will be returned (guaranteeing uniqueness of predicate<->name
  * mapping).
  *
  * @param pName An arbitary name for a predicate.
  * @return A region representing a predicate
  */
 public Region createPredicate(String pName) {
   Region result = regionMap.get(pName);
   if (result == null) {
     result = delegate.createPredicate();
     regionMap.put(pName, result);
   }
   return result;
 }
 public String toString() {
   return "unevaluated="
       + nameToIdMap.size()
       + ", evaluated="
       + idToEvalMap.size()
       + ", renamed="
       + aliasedColumnMap.size();
 }
  @SuppressWarnings("unchecked")
  public ByteBuffer serialize() {
    if (serialized != null) {
      return serialized.duplicate();
    }

    ByteBufferOutputStream out = new ByteBufferOutputStream();

    int i = 0;
    for (Component c : components) {
      Serializer<?> s = serializerForPosition(i);
      ByteBuffer cb = c.getBytes(s);
      if (cb == null) {
        cb = ByteBuffer.allocate(0);
      }

      if (dynamic) {
        String comparator = comparatorForPosition(i);
        if (comparator == null) {
          comparator = c.getComparator();
        }
        if (comparator == null) {
          comparator = BYTESTYPE.getTypeName();
        }
        int p = comparator.indexOf("(reversed=true)");
        boolean desc = false;
        if (p >= 0) {
          comparator = comparator.substring(0, p);
          desc = true;
        }
        if (aliasToComparatorMapping.inverse().containsKey(comparator)) {
          byte a = aliasToComparatorMapping.inverse().get(comparator);
          if (desc) {
            a = (byte) Character.toUpperCase((char) a);
          }
          out.writeShort((short) (0x8000 | a));
        } else {
          out.writeShort((short) comparator.length());
          out.write(comparator.getBytes(Charsets.UTF_8));
        }
        // if (comparator.equals(BYTESTYPE.getTypeName()) && (cb.remaining() ==
        // 0)) {
        // log.warn("Writing zero-length BytesType, probably an error");
        // }
      }
      out.writeShort((short) cb.remaining());
      out.write(cb.slice());
      if ((i == (components.size() - 1)) && (equality != ComponentEquality.EQUAL)) {
        out.write(equality.toByte());
      } else {
        out.write(c.getEquality().toByte());
      }
      i++;
    }

    serialized = out.getByteBuffer();
    return serialized.duplicate();
  }
  /** Adds an expression and returns a reference name. */
  public String addExpr(Expr expr) throws PlanningException {
    if (idToExprBiMap.inverse().containsKey(expr)) {
      int refId = idToExprBiMap.inverse().get(expr);
      return idToNamesMap.get(refId).get(0);
    }

    String generatedName = plan.generateUniqueColumnName(expr);
    return addExpr(expr, generatedName);
  }
Beispiel #18
0
  private void exportApplicationsForOrg(Entry<UUID, String> orgIdAndName, String queryString)
      throws Exception {

    LOG.info("organization: {} / {}", orgIdAndName.getValue(), orgIdAndName.getKey());

    String orgName = orgIdAndName.getValue();

    BiMap<UUID, String> applications =
        managementService.getApplicationsForOrganization(orgIdAndName.getKey());
    for (Entry<UUID, String> appIdAndName : applications.entrySet()) {

      String appName = appIdAndName.getValue();
      appName = appName.substring(appName.indexOf('/') + 1);

      LOG.info("application {} / {}", appName, appIdAndName.getKey());

      EntityManager em = emf.getEntityManager(appIdAndName.getKey());
      Map<String, String[]> cfm = getCollectionFieldMap();

      // Loop through the collections of the Application
      Set<String> collections = em.getApplicationCollections();
      for (String collectionName : collections) {

        // set up for retrieving only the necessary properties
        String entityType = InflectionUtils.singularize(collectionName);
        String[] props = cfm.get(entityType);
        Collection<String> properties =
            new ArrayList<String>(BASE_ATTRIBUTES.length + (props != null ? props.length : 0));
        properties.addAll(Arrays.asList(BASE_ATTRIBUTES));
        if (props != null) {
          properties.addAll(Arrays.asList(props));
        }

        Query query = Query.fromQL(queryString);
        query.setLimit(MAX_ENTITY_FETCH);
        query.setResultsLevel(Level.REFS);
        Results results = em.searchCollection(em.getApplicationRef(), collectionName, query);

        while (results.size() > 0) {

          List<Entity> entities = em.getPartialEntities(results.getIds(), properties);

          for (Entity entity : entities) {
            write(orgName, appName, entity, em);
          }

          if (results.getCursor() == null) {
            break;
          }

          query.setCursor(results.getCursor());
          results = em.searchCollection(em.getApplicationRef(), collectionName, query);
        }
      }
    }
  }
Beispiel #19
0
  public InetAddress getFirstEndpoint() {
    assert tokenToEndPointMap.size() > 0;

    lock.readLock().lock();
    try {
      return tokenToEndPointMap.get(sortedTokens.get(0));
    } finally {
      lock.readLock().unlock();
    }
  }
Beispiel #20
0
 public boolean hasSkill(Class<? extends SkillInstance> clazz) {
   SkillName sn = clazz.getAnnotation(SkillName.class);
   if (sn == null) {
     return false;
   }
   if (!skillsNamesClass.containsKey(sn.value())) {
     return false;
   }
   return clazz.isInstance(skillsNamesClass.get(sn.value()));
 }
  // Task: create collection to translate Polish-English words in two ways
  public static void main(String[] args) {
    ENGLISH_WORD[] englishWords = ENGLISH_WORD.values();
    String[] russianWords = {"jeden", "dwa", "trzy", "kula", "snieg"};

    // Create Multiset
    BiMap<ENGLISH_WORD, String> biMap = EnumHashBiMap.create(ENGLISH_WORD.class);
    // Create English-Polish dictionary
    int i = 0;
    for (ENGLISH_WORD englishWord : englishWords) {
      biMap.put(englishWord, russianWords[i]);
      i++;
    }

    // Print count words
    System.out.println(biMap); // print {ONE=jeden, TWO=dwa, THREE=trzy, BALL=kula, SNOW=snieg}
    // Print all unique words
    System.out.println(biMap.keySet()); // print [ONE, TWO, THREE, BALL, SNOW]
    System.out.println(biMap.values()); // print [jeden, dwa, trzy, kula, snieg]

    // Print translate by words
    System.out.println("one = " + biMap.get(ENGLISH_WORD.ONE)); // print one = jeden
    System.out.println("two = " + biMap.get(ENGLISH_WORD.TWO)); // print two = dwa
    System.out.println("kula = " + biMap.inverse().get("kula")); // print kula = BALL
    System.out.println("snieg = " + biMap.inverse().get("snieg")); // print snieg = SNOW
    System.out.println("empty = " + biMap.get("empty")); // print empty = null

    // Print count word's pair
    System.out.println(biMap.size()); // print 5
  }
  /**
   * It marks the expression identified by the reference name as <code>evaluated</code>. In
   * addition, it adds an EvanNode for the expression identified by the reference.
   *
   * @param referenceName The reference name to be marked as 'evaluated'.
   * @param evalNode EvalNode to be added.
   */
  public void markAsEvaluated(String referenceName, EvalNode evalNode) throws PlanningException {
    String normalized = referenceName;

    int refId = nameToIdMap.get(normalized);
    evaluationStateMap.put(refId, true);
    idToEvalMap.put(refId, evalNode);

    String originalName = checkAndGetIfAliasedColumn(normalized);
    if (originalName != null) {
      aliasedColumnMap.put(originalName, normalized);
    }
  }
  /**
   * Renders the page-to-page navigation graph into the file {@code navgraph.gv} in the {@code
   * .errai} cache directory.
   */
  private void renderNavigationToDotFile(BiMap<String, MetaClass> pages) {
    final File dotFile = new File(RebindUtils.getErraiCacheDir().getAbsolutePath(), "navgraph.gv");
    PrintWriter out = null;
    try {
      out = new PrintWriter(dotFile);
      out.println("digraph Navigation {");
      final MetaClass transitionToType = MetaClassFactory.get(TransitionTo.class);
      final MetaClass transitionAnchorType = MetaClassFactory.get(TransitionAnchor.class);
      final MetaClass transitionAnchorFactoryType =
          MetaClassFactory.get(TransitionAnchorFactory.class);
      for (Map.Entry<String, MetaClass> entry : pages.entrySet()) {
        String pageName = entry.getKey();
        MetaClass pageClass = entry.getValue();

        // entry for the node itself
        out.print("\"" + pageName + "\"");

        Page pageAnnotation = pageClass.getAnnotation(Page.class);
        List<Class<? extends PageRole>> roles = Arrays.asList(pageAnnotation.role());
        if (roles.contains(DefaultPage.class)) {
          out.print(" [penwidth=3]");
        }
        out.println();

        for (MetaField field : getAllFields(pageClass)) {
          if (field.getType().getErased().equals(transitionToType)
              || field.getType().getErased().equals(transitionAnchorType)
              || field.getType().getErased().equals(transitionAnchorFactoryType)) {
            MetaType targetPageType = field.getType().getParameterizedType().getTypeParameters()[0];
            String targetPageName = pages.inverse().get(targetPageType);

            // entry for the link between nodes
            out.println(
                "\""
                    + pageName
                    + "\" -> \""
                    + targetPageName
                    + "\" [label=\""
                    + field.getName()
                    + "\"]");
          }
        }
      }
      out.println("}");
    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
Beispiel #24
0
 public void setString(int columnIndex, String value) {
   Integer reuseIndex = stringReferences.get(value);
   if (reuseIndex != null) {
     bufferSlice.setInt(getOffset(columnIndex), reuseIndex);
   } else {
     int index = stringReferences.size();
     stringReferences.put(value, index);
     bufferSlice.setInt(getOffset(columnIndex), index);
     stringReferenceSize +=
         value.length() * 2 + 4; // assuming size of char = size of byte * 2 + length
   }
   clearNull(columnIndex);
 }
Beispiel #25
0
  public void removeEndpoint(InetAddress endpoint) {
    assert endpoint != null;

    lock.writeLock().lock();
    try {
      bootstrapTokens.inverse().remove(endpoint);
      tokenToEndPointMap.inverse().remove(endpoint);
      leavingEndPoints.remove(endpoint);
      sortedTokens = sortTokens();
    } finally {
      lock.writeLock().unlock();
    }
  }
 /** {@inheritDoc} */
 public BiMap<EObject, EObject> computeMatches(
     Collection<EObject> values1, Collection<EObject> values2) {
   BiMap<EObject, EObject> result = HashBiMap.create();
   Map<Object, EObject> matchingElements = computeIds(values2);
   for (EObject obj : values1) {
     Object id1 = idFunction.apply(obj);
     EObject match = matchingElements.get(id1);
     if (match != null && values2.contains(match)) {
       result.put(obj, match);
     }
   }
   return result;
 }
Beispiel #27
0
  public static void main(String[] args) {

    // 注意BiMap的key和value都不能重复,否则inverse之后就不能保证键值一一对应了
    BiMap<String, Integer> users = HashBiMap.create();

    users.put("bandery", 10);
    users.put("ryan", 11);
    users.put("liuyan", 12);

    // 反转,key变成value,value变成key
    System.out.println(users.inverse().get(10));

    // 会有异常,key和value都不能重复
    // System.out.println(users.inverse().get(11));
    // 异常,"bandery"已经存在
    // users.put("bandery", 1);

    // 如果想插入的话,可以用forcePut强制插入,但在这之前会将相同的K或者V对应
    // 的键值对删除

    // 这样会把之前的bandery-10删除
    users.forcePut("bandery", 13);

    // 这样会把之前的ryan-11和liuyan-12都删除
    users.forcePut("ryan", 12);

    // 当然还有putAll方法
    Map<String, Integer> toadd = HashBiMap.create();
    toadd.put("aaa", 111111);
    toadd.put("bbb", 22222);
    users.putAll(toadd);
  }
Beispiel #28
0
 @SuppressWarnings("unchecked")
 public <T extends SkillInstance> T getSkill(Class<T> clazz) {
   SkillName sn = clazz.getAnnotation(SkillName.class);
   if (sn == null) {
     return null;
   }
   if (!skillsNamesClass.containsKey(sn.value())) {
     return null;
   }
   SkillInstance skill = skillsNamesClass.get(sn.value());
   if (!clazz.isInstance(skill)) {
     return null;
   }
   return (T) skill;
 }
 private HistoricalTimeSeriesInfoDocument loadTimeSeries(ExternalIdBundle idBundle) {
   ReferenceDataProvider referenceDataProvider =
       ((BloombergToolContext) getToolContext()).getBloombergReferenceDataProvider();
   if (idBundle.getExternalId(ExternalSchemes.BLOOMBERG_BUID) == null
       && idBundle.getExternalId(ExternalSchemes.BLOOMBERG_TICKER) != null) {
     // For some reason loading some series by TICKER fails, but BUID works
     BiMap<String, ExternalIdBundle> map =
         BloombergDataUtils.convertToBloombergBuidKeys(
             Collections.singleton(idBundle), referenceDataProvider);
     if (map.size() != 1) {
       throw new OpenGammaRuntimeException("Failed to get buid");
     }
     for (String key : map.keySet()) {
       ReferenceDataResult buidResult =
           referenceDataProvider.getFields(
               Collections.singleton(key),
               Collections.singleton(BloombergConstants.FIELD_ID_BBG_UNIQUE));
       String buid =
           buidResult
               .getResult(key)
               .getFieldData()
               .getString(BloombergConstants.FIELD_ID_BBG_UNIQUE);
       idBundle = idBundle.withExternalId(ExternalSchemes.bloombergTickerSecurityId(buid));
     }
   }
   ExternalIdBundle searchBundle =
       idBundle.withoutScheme(
           ExternalSchemes
               .ISIN); // For things which move country, e.g. ISIN(VALE5 BZ Equity) == ISIN(RIODF
   // US Equity)
   Map<ExternalId, UniqueId> timeSeries =
       getToolContext()
           .getHistoricalTimeSeriesLoader()
           .addTimeSeries(
               searchBundle.getExternalIds(),
               "CMPL",
               "PX_LAST",
               LocalDate.now().minusYears(1),
               null);
   if (timeSeries.size() != 1) {
     throw new OpenGammaRuntimeException(
         "Failed to load time series " + idBundle + " " + timeSeries);
   }
   for (UniqueId uid : timeSeries.values()) {
     return getToolContext().getHistoricalTimeSeriesMaster().get(uid);
   }
   throw new OpenGammaRuntimeException("Unexpected state");
 }
  private int regionToDot(Region r, StringBuilder str, Map<Region, Integer> cache) {
    if (cache.containsKey(r)) { // use same region again
      return cache.get(r);

    } else {
      Triple<Region, Region, Region> triple = delegate.getIfThenElse(r);

      // create node with label
      String predName = regionMap.inverse().get(triple.getFirst());
      nodeCounter += 1; // one more node is created
      int predNum = nodeCounter;
      str.append(predNum).append(" [label=\"").append(predName).append("\"];\n");

      // create arrow for true branch
      Region trueBranch = triple.getSecond();
      int trueTarget = regionToDot(trueBranch, str, cache);
      str.append(predNum).append(" -> ").append(trueTarget).append(" [style=filled];\n");

      // create arrow for false branch
      Region falseBranch = triple.getThird();
      int falseTarget = regionToDot(falseBranch, str, cache);
      str.append(predNum).append(" -> ").append(falseTarget).append(" [style=dotted];\n");

      cache.put(r, predNum);
      return predNum;
    }
  }