public static void toCRAWDAD(LinkTrace links, OutputStream out, double timeMul)
      throws IOException {

    StatefulReader<LinkEvent, Link> linkReader = links.getReader();
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
    Map<Link, Long> activeContacts = new AdjacencyMap.Links<Long>();

    linkReader.seek(links.minTime());
    for (Link l : linkReader.referenceState()) activeContacts.put(l, links.minTime());
    while (linkReader.hasNext()) {
      for (LinkEvent lev : linkReader.next()) {
        Link l = lev.link();
        if (lev.isUp()) {
          activeContacts.put(l, linkReader.time());
        } else {
          double b = activeContacts.get(l) * timeMul;
          double e = linkReader.time() * timeMul;
          activeContacts.remove(l);
          bw.write(l.id1() + "\t" + l.id2() + "\t" + b + "\t" + e + "\n");
        }
      }
    }
    linkReader.close();
    bw.close();
  }
Ejemplo n.º 2
0
  /** Sorts the static LinkedList mainlineLinks in the order they appear on the freeway */
  private LinkedList<Link> recursiveLinkSort(LinkedList<Link> links2) {

    if (links2.size() == 1) {

      return links2;

    } else {

      boolean swapMade = false;
      ListIterator<Link> itr1 = links2.listIterator();
      while (itr1.hasNext()) {
        Link temp = itr1.next();
        int tempindex = itr1.nextIndex();
        // if this loop makes any switches, set the flag to true
        if (links2.getFirst().getUpNode().getNodeID() == temp.getDownNode().getNodeID()) {
          swapMade = true;
          links2.addFirst(temp);
          links2.remove(tempindex);
          return this.recursiveLinkSort(links2);
        }
      }

      if (!swapMade) {
        // assign last n-1 links to links3
        LinkedList<Link> links3 = new LinkedList<Link>();
        Link temp = links2.getFirst();
        links2.removeFirst();
        links3 = this.recursiveLinkSort(links2);
        links3.addFirst(temp);
        return links3;
      } else {
        return links2;
      }
    }
  }
Ejemplo n.º 3
0
  private static Set<Link> getLinks(ArrayList<String> linkList, Entry entry) {
    Set<Link> existingLinks = entry.getLinks();
    Set<Link> links = new HashSet<>();

    if (existingLinks == null) existingLinks = new HashSet<>();

    if (linkList == null) return existingLinks;

    for (int i = 0; i < linkList.size(); i++) {
      String currentItem = linkList.get(i);
      Link link;

      if (existingLinks.size() > i) {
        link = (Link) existingLinks.toArray()[i];
      } else {
        link = new Link();
        existingLinks.add(link);
      }
      link.setLink(currentItem);
      link.setEntry(entry);
      links.add(link);
    }

    return links;
  }
Ejemplo n.º 4
0
  /**
   * Translates the link structure into the cell structure depending on healthy detector locations
   */
  public void createCellStructure() {

    int i = 0;

    while (i < mainlineLinks.size() - 1) {

      if (mainlineLinks.get(i).isHasDetector()
          & mainlineLinks.get(i).getDetectorML().getHealthStatus() == 100) {
        Cell c = new Cell((int) totalTimeInHours * 60 / 5);
        c.addLink(mainlineLinks.get(i));
        c.setDetectorML(mainlineLinks.get(i).getDetectorML());
        c.setDetectorHOV(mainlineLinks.get(i).getDetectorHOV());
        while (!mainlineLinks.get(i + 1).isHasDetector() & i < mainlineLinks.size() - 2
            | (mainlineLinks.get(i + 1).isHasDetector()
                & mainlineLinks.get(i + 1).getDetectorML().getHealthStatus() != 100)) {
          c.addLink(mainlineLinks.get(i + 1));
          i++;
        }
        // Onramps and Offramps in the Cell
        for (Link l : c.getLinks()) {

          c.addToOnrampPerLink(l.getUpNode().getInLinks().size() - 1);
          c.addToOfframpPerLink(l.getDownNode().getOutLinks().size() - 1);

          for (int linkID : l.getUpNode().getInLinks()) {
            if (links.get(linkID).getLinkType().equals("onramp")) {
              if (links.get(linkID).getDetectorML().getFlowData().isEmpty()
                  | links.get(linkID).getDetectorML().getHealthStatus() != 100) {
                c.addToImputeOR(true);
                c.appendZeroColumnToMeasuredOnrampFlow();
              } else {
                c.appendColumnToMeasuredOnrampFlow(
                    links.get(linkID).getDetectorML().getFlowDataArray());
                c.addToImputeOR(false);
              }
            }
          }
          for (int linkID : l.getDownNode().getOutLinks()) {
            if (links.get(linkID).getLinkType().equals("offramp")) {
              if (links.get(linkID).getDetectorML().getFlowData().isEmpty()
                  | links.get(linkID).getDetectorML().getHealthStatus() != 100) {
                c.addToImputeFR(true);
                c.appendZeroColumnToMeasuredOfframpFlow();
              } else {
                c.appendColumnToMeasuredOfframpFlow(
                    links.get(linkID).getDetectorML().getFlowDataArray());
                c.addToImputeFR(false);
              }
            }
          }
        }

        cells.add(c);
      }

      i++;
    }
    i = 0;
  }
    public NodeData(
        Controller parent,
        Link profileLink,
        String demandStr,
        Double knob,
        Double dpdt,
        Scenario scenario) {

      this.knob = knob;
      this.myNode = profileLink.getBegin_node();
      meas = profileLink;
      feeds = new ArrayList<Link>();
      not_feeds = new ArrayList<Link>();

      //  incoming link sets
      for (int i = 0; i < myNode.getnIn(); i++) {
        Link link = myNode.getInput_link()[i];
        if (link.isFreeway() || link.isHov()) feeds.add(link);
        else not_feeds.add(link);
      }

      // outgoing link sets
      not_meas = new ArrayList<Link>();
      for (int j = 0; j < myNode.getnOut(); j++) {
        Link link = myNode.getOutput_link()[j];
        if (meas != link) not_meas.add(link);
      }

      if (meas == null) return;

      // find the demand profile for the offramp
      measured_flow_profile_veh =
          new BeatsTimeProfileDouble(demandStr, ",", dpdt, 0d, scenario.get.simdtinseconds());
      measured_flow_profile_veh.multiplyscalar(scenario.get.simdtinseconds());

      //            alpha_tilde = new Double[myNode.nIn];

      // create the actuator
      edu.berkeley.path.beats.jaxb.Actuator jaxbA = new edu.berkeley.path.beats.jaxb.Actuator();
      edu.berkeley.path.beats.jaxb.ScenarioElement se =
          new edu.berkeley.path.beats.jaxb.ScenarioElement();
      edu.berkeley.path.beats.jaxb.ActuatorType at =
          new edu.berkeley.path.beats.jaxb.ActuatorType();
      se.setId(myNode.getId());
      se.setType("node");
      at.setId(-1);
      at.setName("cms");
      jaxbA.setId(-1);
      jaxbA.setScenarioElement(se);
      jaxbA.setActuatorType(at);
      cms = new ActuatorCMS(scenario, jaxbA, new BeatsActuatorImplementation(jaxbA, scenario));
      cms.populate(null, null);
      cms.setMyController(parent);
    }
Ejemplo n.º 6
0
Archivo: Macro.java Proyecto: bramk/bnd
  protected String replace(String key, Link link) {
    if (link != null && link.contains(key)) return "${infinite:" + link.toString() + "}";

    if (key != null) {
      key = key.trim();
      if (key.length() > 0) {
        Processor source = domain;
        String value = null;

        if (key.indexOf(';') < 0) {
          Instruction ins = new Instruction(key);
          if (!ins.isLiteral()) {
            SortedList<String> sortedList = SortedList.fromIterator(domain.iterator());
            StringBuilder sb = new StringBuilder();
            String del = "";
            for (String k : sortedList) {
              if (ins.matches(k)) {
                String v = replace(k, new Link(source, link, key));
                if (v != null) {
                  sb.append(del);
                  del = ",";
                  sb.append(v);
                }
              }
            }
            return sb.toString();
          }
        }
        while (value == null && source != null) {
          value = source.getProperties().getProperty(key);
          source = source.getParent();
        }

        if (value != null) return process(value, new Link(source, link, key));

        value = doCommands(key, link);
        if (value != null) return process(value, new Link(source, link, key));

        if (key != null && key.trim().length() > 0) {
          value = System.getProperty(key);
          if (value != null) return value;
        }
        if (!flattening && !key.equals("@"))
          domain.warning("No translation found for macro: " + key);
      } else {
        domain.warning("Found empty macro key");
      }
    } else {
      domain.warning("Found null macro key");
    }
    return "${" + key + "}";
  }
Ejemplo n.º 7
0
 private ModelMap getQuote(Link link, UID source, boolean mark) {
   ModelMap map = new ModelMap();
   String quote = link.getQuote() != null ? link.getQuote() : ((Item) source).getContent();
   if (mark) {
     quote =
         link.getTaggedQuote() != null
             ? link.getTaggedQuote()
             : ((Item) source).getTaggedContent();
   }
   map.put("quote", quote);
   map.put("uri", source.getUri());
   return map;
 }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
   */
  protected Control createContents(Composite parent) {
    Composite comp = SWTFactory.createComposite(parent, 1, 1, GridData.FILL_BOTH, 0, 0);
    link = new Link(comp, SWT.NONE);
    link.setLayoutData(new GridData(GridData.END, GridData.CENTER, true, false));
    link.setFont(comp.getFont());
    link.setText(PDEUIMessages.CompilersPreferencePage_configure_project_specific_settings);
    link.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            HashSet set = new HashSet();
            try {
              IJavaProject[] projects =
                  JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
              IProject project = null;
              for (int i = 0; i < projects.length; i++) {
                project = projects[i].getProject();
                try {
                  if (project.hasNature(PDE.PLUGIN_NATURE)
                      && fBlock.hasProjectSpecificSettings(project)) {
                    set.add(projects[i]);
                  }
                } catch (CoreException ce) {
                  // do nothing ignore the project
                }
              }
            } catch (JavaModelException jme) {
              // ignore
            }
            ProjectSelectionDialog psd = new ProjectSelectionDialog(getShell(), set);
            if (psd.open() == IDialogConstants.OK_ID) {
              HashMap data = new HashMap();
              data.put(NO_LINK, Boolean.TRUE);
              PreferencesUtil.createPropertyDialogOn(
                      getShell(),
                      ((IJavaProject) psd.getFirstResult()).getProject(),
                      "org.eclipse.pde.internal.ui.properties.compilersPropertyPage", //$NON-NLS-1$
                      new String[] {"org.eclipse.pde.internal.ui.properties.compilersPropertyPage"},
                      data)
                  .open(); //$NON-NLS-1$
            }
          }
        });
    fBlock =
        new PDECompilersConfigurationBlock(null, (IWorkbenchPreferenceContainer) getContainer());
    fBlock.createControl(comp);

    // Initialize with data map in case applyData was called before createContents
    applyData(fPageData);

    return comp;
  }
Ejemplo n.º 9
0
  @Override
  public boolean equals(final Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof Track)) {
      return false;
    }

    final Track track = (Track) o;

    if (explicit != track.explicit) {
      return false;
    }
    if (length != track.length) {
      return false;
    }
    if (trackNumber != track.trackNumber) {
      return false;
    }
    if (album != null ? !album.equals(track.album) : track.album != null) {
      return false;
    }
    if (artists != null ? !artists.equals(track.artists) : track.artists != null) {
      return false;
    }
    if (cover != null ? !cover.equals(track.cover) : track.cover != null) {
      return false;
    }
    if (title != null ? !title.equals(track.title) : track.title != null) {
      return false;
    }

    return true;
  }
Ejemplo n.º 10
0
Archivo: Macro.java Proyecto: bramk/bnd
    public boolean contains(String key) {
      if (this.key.equals(key)) return true;

      if (previous == null) return false;

      return previous.contains(key);
    }
 /** @see org.eclipse.jface.preference.PreferencePage#applyData(java.lang.Object) */
 public void applyData(Object data) {
   if (data instanceof Map) {
     fPageData = (Map) data;
     if (link != null && fPageData.containsKey(NO_LINK)) {
       link.setVisible(!Boolean.TRUE.equals(((Map) data).get(NO_LINK)));
     }
   }
 }
Ejemplo n.º 12
0
 protected BasketItem(INetworkLink link) {
   super(
       link,
       NetworkLibrary.resource().getResource("basket").getValue(),
       NetworkLibrary.resource().getResource("basketSummaryEmpty").getValue(),
       new UrlInfoCollection<UrlInfo>(),
       Accessibility.ALWAYS,
       FLAGS_DEFAULT & ~FLAGS_GROUP);
   myBooksInBasketOption = new ZLStringListOption(Link.getSiteName(), "Basket", null);
 }
Ejemplo n.º 13
0
 @Override
 public int hashCode() {
   int result = title != null ? title.hashCode() : 0;
   result = 31 * result + (artists != null ? artists.hashCode() : 0);
   result = 31 * result + (album != null ? album.hashCode() : 0);
   result = 31 * result + trackNumber;
   result = 31 * result + length;
   result = 31 * result + (cover != null ? cover.hashCode() : 0);
   result = 31 * result + (explicit ? 1 : 0);
   return result;
 }
Ejemplo n.º 14
0
  @Override
  protected void initFlow(HierarchicalConfiguration flowCfg) {
    // int node = flowCfg.getInt("[@node]");

    int inLink = flowCfg.getInt("[@inLink]", -1);
    int outLink = flowCfg.getInt("[@outLink]", -1);

    // int next = flowCfg.getInt("[@next]");
    int no = flowCfg.getInt("[@no]", 0);

    Node node;
    Node next;

    if (inLink != -1) {
      Link link = idToLinkMap.get(Id.create(inLink, Link.class));

      node = link.getFromNode();
      next = link.getToNode();
    } else {
      Link link = idToLinkMap.get(Id.create(outLink, Link.class));

      node = link.getToNode();
      next = link.getFromNode();
    }

    int nodeId = Integer.parseInt(node.getId().toString());
    int nextId = Integer.parseInt(next.getId().toString());

    flows[nodeId] = new MATSimFlow(nodeId, inLink, outLink, nextId, no);
  }
  @Override
  protected void populate(Object jaxbO) {

    edu.berkeley.path.beats.jaxb.Controller jaxbC = (edu.berkeley.path.beats.jaxb.Controller) jaxbO;

    node_data = new HashMap<Long, NodeData>();

    for (Row row : jaxbController.getTable().get(0).getRow()) {

      Link link = null;
      String demandString = "";
      double dpdt = Double.NaN;
      double knob = Double.NaN;

      for (Column col : row.getColumn()) {

        switch ((int) col.getId()) {
          case 0:
            link = getMyScenario().get.linkWithId(Integer.parseInt(col.getContent()));
            break;

          case 1:
            demandString = col.getContent();
            break;

          case 2:
            dpdt = Double.parseDouble(col.getContent());
            break;

          case 3:
            knob = Double.parseDouble(col.getContent());
            break;
        }
      }

      if (!demandString.isEmpty() && link != null && !Double.isNaN(knob) && !Double.isNaN(dpdt))
        node_data.put(link.getId(), new NodeData(this, link, demandString, knob, dpdt, myScenario));
    }
  }
Ejemplo n.º 16
0
  public static String format(Link link) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("type", link.type());
    map.put("label", link.label());
    map.put("pair", link.pair().label());

    if (link.factory().contains(GraphFactory.Family.directed)) {
      map.put("reverse", link.reverse().label());
    }

    if (link.factory().contains(GraphFactory.Family.fractal)) {
      map.put("inverse", link.inverse().label());
      map.put("down", link.down());
    }
    return format(map);
  }
Ejemplo n.º 17
0
  @Before
  public void setup() {
    nw = new Network();
    nw.setName("test network");

    dp = new DensityMap();

    nw.setNodes(new ArrayList<edu.berkeley.path.model_elements_base.Node>());
    nw.setLinks(new ArrayList<edu.berkeley.path.model_elements_base.Link>());

    Node nd1;
    Node nd2;
    Link ln;

    nd1 = new Node();
    nd1.setId(1L);
    nd1.setName("one");
    nd1.setType("Highway");
    nw.getNodes().add(nd1);

    nd2 = new Node();
    nd2.setId(2L);
    nd2.setName("two");
    nd2.setType("Highway");
    nw.getNodes().add(nd2);

    ln = new Link();
    ln.setId(3L);
    ln.setName("three");
    ln.setType("Highway");
    ln.setLaneCount(4.0);
    ln.setLength(1000.0);

    ln.setBegin(nd1);
    ln.setEnd(nd2);

    nw.getLinks().add(ln);
  }
    public void deploy(double current_time_in_seconds) {

      int i, j;
      for (i = 0; i < myNode.nIn; i++) {
        Link inlink = myNode.input_link[i];
        if (feeds.contains(inlink)) {

          for (j = 0; j < myNode.nOut; j++) {
            Link outlink = myNode.output_link[j];

            // measured gets beta
            if (meas == outlink) cms.set_split(inlink.getId(), meas.getId(), beta);

            // not measured scaled to 1-beta
            else cms.set_split(inlink.getId(), outlink.getId(), 1d - beta);
            //                            cms.set_split(inlink.getId(), outlink.getId(),
            // myNode.getSplitRatio(i, j)*(1d-beta)/alpha_tilde[i]);
          }
        }
      }

      cms.deploy(current_time_in_seconds);
    }
Ejemplo n.º 19
0
 @RequestMapping("related")
 @Model
 @ResponseBody
 public Collection<ModelMap> getRelated(@RequestParam String uri) {
   Set<UID> related = new LinkedHashSet<UID>();
   for (Link link : linkDao.getRelated(uri)) {
     if (!ABBREVIATION.equals(link.getType()) && link.getQuote() == null) {
       if (link.getUid1().getUri().equals(uri)) {
         related.add(link.getUid2());
       } else {
         related.add(link.getUid1());
       }
     }
   }
   return convertToPlainObjects(
       related,
       new ValueObjectUtils.Modifier<UID>() {
         @Override
         public void modify(UID entity, ModelMap map) {
           map.remove("content");
         }
       });
 }
Ejemplo n.º 20
0
 /** Reads the network geometry from mainScenario and populates the mainlineLinks list */
 public void createMainlineLinkStructureFromMainScenario(int routeID) {
   for (int i = 0;
       i < this.mainScenario.getNetworkList().getNetwork().get(0).getLinkList().getLink().size();
       i++) {
     if (routeID != 0) {
       int routeIndex = 0;
       // find the route index
       for (routeIndex = 0;
           routeIndex < this.mainScenario.getRoutes().getRoute().size();
           routeIndex++) {
         if (Integer.parseInt(this.mainScenario.getRoutes().getRoute().get(routeIndex).getId())
             == routeID) {
           break;
         }
       }
       // go over the route and see if the link belongs to the given route
       boolean linkInRoute = false;
       for (int k = 0;
           k
               < this.mainScenario
                   .getRoutes()
                   .getRoute()
                   .get(routeIndex)
                   .getLinkReferences()
                   .getLinkReference()
                   .size();
           k++) {
         if (this.mainScenario
             .getRoutes()
             .getRoute()
             .get(routeIndex)
             .getLinkReferences()
             .getLinkReference()
             .get(k)
             .getId()
             .contentEquals(
                 this.mainScenario
                     .getNetworkList()
                     .getNetwork()
                     .get(0)
                     .getLinkList()
                     .getLink()
                     .get(i)
                     .getId())) {
           linkInRoute = true;
           break;
         }
       }
       if (!linkInRoute) {
         continue;
       }
     }
     // collect only mainline links in the links list
     if (this.mainScenario
         .getNetworkList()
         .getNetwork()
         .get(0)
         .getLinkList()
         .getLink()
         .get(i)
         .getType()
         .equals("freeway")) {
       Link l = new Link();
       boolean hasDetector = false;
       Detector detectorML = new Detector();
       l.setLinkID(
           Integer.parseInt(
               this.mainScenario
                   .getNetworkList()
                   .getNetwork()
                   .get(0)
                   .getLinkList()
                   .getLink()
                   .get(i)
                   .getId()));
       l.setUpNode(
           nodes.get(
               Integer.parseInt(
                   this.mainScenario
                       .getNetworkList()
                       .getNetwork()
                       .get(0)
                       .getLinkList()
                       .getLink()
                       .get(i)
                       .getBegin()
                       .getNodeId())));
       l.setDownNode(
           nodes.get(
               Integer.parseInt(
                   this.mainScenario
                       .getNetworkList()
                       .getNetwork()
                       .get(0)
                       .getLinkList()
                       .getLink()
                       .get(i)
                       .getEnd()
                       .getNodeId())));
       l.setUpLinks(l.getUpNode().getInLinks());
       l.setDownLinks(l.getDownNode().getOutLinks());
       l.setLength(
           this.mainScenario
               .getNetworkList()
               .getNetwork()
               .get(0)
               .getLinkList()
               .getLink()
               .get(i)
               .getLength()
               .doubleValue());
       l.setLanesML(
           this.mainScenario
               .getNetworkList()
               .getNetwork()
               .get(0)
               .getLinkList()
               .getLink()
               .get(i)
               .getLanes()
               .intValue());
       for (int key : detectors.keySet()) {
         if (detectors.get(key).getLinkAssoc() == l.getLinkID()) {
           hasDetector = true;
           detectorML = detectors.get(key);
         }
       }
       l.setHasDetector(hasDetector);
       l.setDetectorML(detectorML);
       mainlineLinks.add(l);
     }
   }
   // sort mainline links
   mainlineLinks = this.recursiveLinkSort(mainlineLinks);
 }
Ejemplo n.º 21
0
  public void writeDemandsAndSplitRatiosToSpreadSheet(String outFilename)
      throws BiffException, IOException, RowsExceededException, WriteException,
          IndexOutOfBoundsException {

    Workbook existingWorkbook = Workbook.getWorkbook(new File(outFilename));
    WritableWorkbook workbookCopy =
        Workbook.createWorkbook(new File("Aimsun\\output.xls"), existingWorkbook);

    // add labels first row
    workbookCopy.getSheet(0).addCell(new Label(15, 0, "Split Ratios"));
    workbookCopy.getSheet(0).addCell(new Label(16, 0, "Offramp Flows"));
    workbookCopy.getSheet(0).addCell(new Label(17, 0, "Demands"));
    workbookCopy.getSheet(0).addCell(new Label(18, 0, "Flows"));
    workbookCopy.getSheet(0).addCell(new Label(19, 0, "Speeds"));
    int rowIndex = 1;
    for (Cell c : splitCells) {

      // find row index
      while (true) {
        NumberCell nc2 = (NumberCell) workbookCopy.getSheet(0).getCell(0, rowIndex);
        if (nc2.getValue() == c.getDetectorML().getSensorID()) {
          break;
        }
        rowIndex++;
      }

      // fill in mainline data columns
      for (int k = rowIndex; k < rowIndex + totalTimeInHours * 60 / 5; k++) {

        workbookCopy.getSheet(0).addCell(new Number(18, k, c.getFlowCompare().get(k - rowIndex)));
        workbookCopy.getSheet(0).addCell(new Number(19, k, c.getVelocity().get(k - rowIndex)));
      }
      rowIndex = 1;

      // if the cell has onramp, find the detector id and fill corresponding columns (assumption:
      // cells have at most one on-ramp or off-ramp)
      int onrampLinkID = 0;
      if (c.getLinks().getFirst().getUpLinks().size() > 1) {
        // By our assumption (above), there are at most 2 upstream links for each mainline link
        onrampLinkID = c.getLinks().getFirst().getUpLinks().get(0);
        for (Link mlLink : mainlineLinks) {
          if (mlLink.getLinkID() == onrampLinkID) {
            onrampLinkID = c.getLinks().getFirst().getUpLinks().get(1);
            break;
          }
        }
        // find associated detector
        int onrampDetId = 0;
        for (int key : detectors.keySet()) {
          if (detectors.get(key).getLinkAssoc() == onrampLinkID) {
            onrampDetId = detectors.get(key).getSensorID();
          }
        }

        if (onrampDetId == 0) continue;

        // find row index
        while (true) {
          NumberCell nc2 = (NumberCell) workbookCopy.getSheet(0).getCell(0, rowIndex);
          if (nc2.getValue() == onrampDetId) {
            break;
          }
          rowIndex++;
        }
        for (int k = rowIndex; k < rowIndex + totalTimeInHours * 60 / 5; k++) {

          workbookCopy.getSheet(0).addCell(new Number(17, k, c.getOnRampInput().get(k - rowIndex)));
          workbookCopy.getSheet(0).addCell(new Number(18, k, c.getOnRampInput().get(k - rowIndex)));
        }
        rowIndex = 1;
      }

      // if the cell has offramp, find the detector id and fill corresponding columns (assumption:
      // cells have at most one on-ramp or off-ramp)
      int offrampLinkID = 0;
      if (c.getLinks().getLast().getDownLinks().size() > 1) {
        // By our assumption (above), there are at most 2 upstream links for each mainline link
        offrampLinkID = c.getLinks().getLast().getDownLinks().get(0);
        for (Link mlLink : mainlineLinks) {
          if (mlLink.getLinkID() == offrampLinkID) {
            offrampLinkID = c.getLinks().getLast().getDownLinks().get(1);
            break;
          }
        }

        // find associated detector
        int offrampDetId = 0;
        for (int key : detectors.keySet()) {
          if (detectors.get(key).getLinkAssoc() == offrampLinkID) {
            offrampDetId = detectors.get(key).getSensorID();
          }
        }

        if (offrampDetId == 0) continue;

        // find row index
        while (true) {
          NumberCell nc2 = (NumberCell) workbookCopy.getSheet(0).getCell(0, rowIndex);
          if (nc2.getValue() == offrampDetId) {
            break;
          }
          rowIndex++;
        }

        for (int k = rowIndex; k < rowIndex + totalTimeInHours * 60 / 5; k++) {

          workbookCopy.getSheet(0).addCell(new Number(15, k, c.getBeta().get(k - rowIndex)));
          workbookCopy.getSheet(0).addCell(new Number(16, k, c.getOffRampFlow().get(k - rowIndex)));
          workbookCopy.getSheet(0).addCell(new Number(18, k, c.getOffRampFlow().get(k - rowIndex)));
        }

        rowIndex = 1;
      }

      // rowIndex += totalTimeInHours*60/5;
      rowIndex = 1;
    }

    workbookCopy.write();
    workbookCopy.close();
    existingWorkbook.close();
  }
Ejemplo n.º 22
0
  /**
   * XML Circuit constructor
   *
   * @param file the file that contains the XML description of the circuit
   * @param g the graphics that will paint the node
   * @throws CircuitLoadingException if the internal circuit can not be loaded
   */
  public CircuitUI(File file, Graphics g) throws CircuitLoadingException {
    this("");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    Document doc;
    Element root;

    Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>();

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.parse(file);
    } catch (SAXException sxe) {
      throw new CircuitLoadingException("SAX exception raised, invalid XML file.");
    } catch (ParserConfigurationException pce) {
      throw new CircuitLoadingException(
          "Parser exception raised, parser configuration is invalid.");
    } catch (IOException ioe) {
      throw new CircuitLoadingException("I/O exception, file cannot be loaded.");
    }

    root = (Element) doc.getElementsByTagName("Circuit").item(0);
    this.setName(root.getAttribute("name"));

    NodeList nl = root.getElementsByTagName("Node");
    Element e;
    Node n;
    Class cl;

    for (int i = 0; i < nl.getLength(); ++i) {
      e = (Element) nl.item(i);

      try {
        cl = Class.forName(e.getAttribute("class"));
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      try {
        n = ((Node) cl.newInstance());
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      this.nodes.add(n);
      n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y")));

      if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name"));

      if (n instanceof giraffe.ui.CompositeNode) {
        try {
          ((CompositeNode) n)
              .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g);
        } catch (Exception exc) {
          /* try to load from the lib */
          ((CompositeNode) n)
              .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g);
        }
      }

      NodeList nlist = e.getElementsByTagName("Anchor");
      Element el;

      for (int j = 0; j < nlist.getLength(); ++j) {
        el = (Element) nlist.item(j);

        Anchor a = n.getAnchor(new Integer(el.getAttribute("id")));
        NodeList linklist = el.getElementsByTagName("Link");
        Element link;
        Link l;

        for (int k = 0; k < linklist.getLength(); ++k) {
          link = (Element) linklist.item(k);
          int id = new Integer(link.getAttribute("id"));
          int index = new Integer(link.getAttribute("index"));

          if (id >= this.linkID) linkID = id + 1;

          if (linkstable.containsKey(id)) {
            l = linkstable.get(id);
            l.addLinkedAnchorAt(a, index);
            a.addLink(l);
          } else {
            l = new Link(id);
            l.addLinkedAnchorAt(a, index);
            this.links.add(l);
            linkstable.put(id, l);
            a.addLink(l);
          }
        }
      }
    }
  }
  public List<HoldingsTree> fetchHoldingsTreeForBib(int bibId) throws Exception {
    List<HoldingsTree> holdingsTrees = new ArrayList<HoldingsTree>();

    holdingsPreparedStatement.setInt(1, bibId);
    ResultSet resultSet = holdingsPreparedStatement.executeQuery();
    Map<String, HoldingsTree> map = new HashMap<>();
    Map<String, ExtentOfOwnership> extentOfOwnershipMap = new HashMap<>();
    Set<String> uriSet = null;
    Set<String> noteSet = null;
    Set<String> donorSet = null;
    Set<String> coverageSet = null;
    Set<String> perpetualSet = null;
    Set<String> extentOfOwnershipNoteSet = null;
    Set<String> linkSet = null;

    while (resultSet.next()) {
      String holdingsType = resultSet.getString("HOLDINGS_TYPE");
      String id = resultSet.getString("HOLDINGS_ID");
      OleHoldings oleHoldings = null;
      if (map.containsKey(id)) {
        oleHoldings = map.get(id).getHoldings().getContentObject();
      } else {
        oleHoldings = new OleHoldings();
        Location location =
            getLocationDetails(
                resultSet.getString("LOCATION"), resultSet.getString("LOCATION_LEVEL"));
        oleHoldings.setLocation(location);
        oleHoldings.setHoldingsType(holdingsType);
        CallNumber callNumber = new CallNumber();
        callNumber.setNumber(resultSet.getString("CALL_NUMBER"));
        callNumber.setPrefix(resultSet.getString("CALL_NUMBER_PREFIX"));
        ShelvingOrder shelvingOrder = new ShelvingOrder();
        if (resultSet.getString("SHELVING_ORDER") != null
            && !"null".equals(resultSet.getString("SHELVING_ORDER"))) {
          shelvingOrder.setCodeValue(resultSet.getString("SHELVING_ORDER"));
          shelvingOrder.setFullValue(resultSet.getString("SHELVING_ORDER"));
        }
        callNumber.setShelvingOrder(shelvingOrder);
        ShelvingScheme shelvingScheme = new ShelvingScheme();
        if (resultSet.getString("CALL_NUMBER_TYPE_ID") != null) {
          String[] strings =
              callNumberType.get(resultSet.getString("CALL_NUMBER_TYPE_ID")).split("[|]");
          shelvingScheme.setCodeValue(strings[0]);
          shelvingScheme.setFullValue(strings[1]);
        }
        callNumber.setShelvingScheme(shelvingScheme);
        oleHoldings.setCallNumber(callNumber);
        oleHoldings.setCopyNumber(resultSet.getString("COPY_NUMBER"));
        HoldingsTree holdingsTree = new HoldingsTree();

        Holdings holdings = null;

        if (holdingsType.equalsIgnoreCase(PHoldings.PRINT)) {
          holdings = new PHoldings();

          if (resultSet.getString("RECEIPT_STATUS_ID") != null) {
            oleHoldings.setReceiptStatus(resultSet.getString("RECEIPT_STATUS_ID"));
          }
          extentOfOwnershipNoteSet = new HashSet<>();
          donorSet = coverageSet = perpetualSet = null;
        } else {
          holdings = new EHoldings();
          oleHoldings.setAccessStatus(resultSet.getString("ACCESS_STATUS"));
          oleHoldings.setImprint(resultSet.getString("IMPRINT"));
          Platform platform = new Platform();
          platform.setPlatformName(resultSet.getString("PLATFORM"));
          platform.setAdminUrl(resultSet.getString("ADMIN_URL"));
          platform.setAdminUserName(resultSet.getString("ADMIN_USERNAME"));
          platform.setAdminPassword(resultSet.getString("ADMIN_PASSWORD"));
          oleHoldings.setPlatform(platform);

          oleHoldings.setPublisher(resultSet.getString("PUBLISHER"));
          HoldingsAccessInformation holdingsAccessInformation = new HoldingsAccessInformation();

          holdingsAccessInformation.setProxiedResource(resultSet.getString("PROXIED_RESOURCE"));
          holdingsAccessInformation.setAccessUsername(resultSet.getString("ACCESS_USERNAME"));
          holdingsAccessInformation.setAccessPassword(resultSet.getString("ACCESS_PASSWORD"));
          holdingsAccessInformation.setNumberOfSimultaneousUser(
              resultSet.getString("NUMBER_SIMULT_USERS"));
          holdingsAccessInformation.setAccessLocation(resultSet.getString("CODE"));
          holdingsAccessInformation.setAuthenticationType(
              resultSet.getString("AUTHENTICATION_TYPE_ID"));
          oleHoldings.setHoldingsAccessInformation(holdingsAccessInformation);
          String statisticalSearchId = resultSet.getString("STAT_SEARCH_CODE_ID");
          if (StringUtils.isNotEmpty(statisticalSearchId)) {
            String[] strings = statisticalSearchCodeMap.get(statisticalSearchId).split("[|]");
            StatisticalSearchingCode statisticalSearchingCode = new StatisticalSearchingCode();
            statisticalSearchingCode.setCodeValue(strings[0]);
            statisticalSearchingCode.setFullValue(strings[1]);
            oleHoldings.setStatisticalSearchingCode(statisticalSearchingCode);
          }
          oleHoldings.setLocalPersistentLink(resultSet.getString("LOCAL_PERSISTENT_URI"));
          oleHoldings.setSubscriptionStatus(resultSet.getString("SUBSCRIPTION_STATUS"));
          oleHoldings.setInterLibraryLoanAllowed(Boolean.valueOf(resultSet.getString("ALLOW_ILL")));
          coverageSet = new HashSet<>();
          perpetualSet = new HashSet<>();
          donorSet = new HashSet<>();
          ExtentOfOwnership extentOfOwnership = new ExtentOfOwnership();
          Coverages coverages = new Coverages();
          PerpetualAccesses perpetualAccesses = new PerpetualAccesses();
          extentOfOwnership.setCoverages(coverages);
          extentOfOwnership.setPerpetualAccesses(perpetualAccesses);
          oleHoldings.getExtentOfOwnership().add(extentOfOwnership);
        }
        holdings.setHoldingsType(holdingsType);
        holdings.setId("who-" + id);
        holdings.setContentObject(oleHoldings);
        holdings.setCreatedBy(resultSet.getString("CREATED_BY"));
        holdings.setCreatedOn(resultSet.getString("DATE_CREATED"));
        if (resultSet.getString("STAFF_ONLY") != null) {
          holdings.setStaffOnly(
              (resultSet.getString("STAFF_ONLY").equalsIgnoreCase("Y")
                  ? Boolean.TRUE
                  : Boolean.FALSE));
        }
        holdings.setUpdatedBy(resultSet.getString("UPDATED_BY"));
        holdings.setUpdatedOn(resultSet.getString("DATE_UPDATED"));
        holdings.setLastUpdated(resultSet.getString("DATE_UPDATED"));

        uriSet = new HashSet<>();
        noteSet = new HashSet<>();
        linkSet = new HashSet<>();
        List<Item> itemList = fetchItemForHoldings(Integer.parseInt(id));
        holdingsTree.setHoldings(holdings);
        holdingsTree.getItems().addAll(itemList);

        map.put(id, holdingsTree);

        holdingsTrees.add(holdingsTree);
      }

      if (StringUtils.isNotEmpty(holdingsType) && holdingsType.equalsIgnoreCase(PHoldings.PRINT)) {
        if (uriSet.add(resultSet.getString("HOLDINGS_URI_ID"))) {
          Uri uri = new Uri();
          uri.setValue(resultSet.getString("TEXT"));
          oleHoldings.getUri().add(uri);
        }
        ExtentOfOwnership extentOfOwnership = null;
        if (extentOfOwnershipMap.containsKey(resultSet.getString("EXT_OWNERSHIP_ID"))) {
          extentOfOwnership = extentOfOwnershipMap.get(resultSet.getString("EXT_OWNERSHIP_ID"));
        } else {
          extentOfOwnership = new ExtentOfOwnership();
          if (StringUtils.isNotEmpty(resultSet.getString("EXT_OWNERSHIP_TYPE_ID"))) {
            String[] strings =
                extentOfOwnershipTypeMap
                    .get(resultSet.getString("EXT_OWNERSHIP_TYPE_ID"))
                    .split("[|]");
            extentOfOwnership.setType(strings[1]);
          }
          extentOfOwnershipMap.put(resultSet.getString("EXT_OWNERSHIP_ID"), extentOfOwnership);
          oleHoldings.getExtentOfOwnership().add(extentOfOwnership);
        }
        String extOwnershipNoteId = resultSet.getString("EXT_OWNERSHIP_NOTE_ID");
        if (extentOfOwnershipNoteSet != null
            && StringUtils.isNotEmpty(extOwnershipNoteId)
            && extentOfOwnershipNoteSet.add(resultSet.getString("EXT_OWNERSHIP_NOTE_ID"))) {
          Note note = new Note();
          note.setValue(resultSet.getString(83));
          note.setType(resultSet.getString(82));

          extentOfOwnership.getNote().add(note);
        }
      } else {
        if (linkSet.add(resultSet.getString("HOLDINGS_URI_ID"))) {
          Link link = new Link();
          link.setUrl(resultSet.getString("URI"));
          link.setText(resultSet.getString("TEXT"));
          oleHoldings.getLink().add(link);
        }
        if (oleHoldings.getExtentOfOwnership() != null
            && oleHoldings.getExtentOfOwnership().size() > 0) {
          if (coverageSet != null && coverageSet.add(resultSet.getString("HOLDINGS_COVERAGE_ID"))) {
            Coverage coverage = new Coverage();
            coverage.setCoverageStartIssue(resultSet.getString("COVERAGE_START_ISSUE"));
            coverage.setCoverageStartDate(resultSet.getString("COVERAGE_START_DATE"));
            coverage.setCoverageStartVolume(resultSet.getString("COVERAGE_START_VOLUME"));
            coverage.setCoverageEndIssue(resultSet.getString("HOLDINGS_COVERAGE_ID"));
            coverage.setCoverageEndDate(resultSet.getString("COVERAGE_END_DATE"));
            coverage.setCoverageEndVolume(resultSet.getString("COVERAGE_END_VOLUME"));
            oleHoldings.getExtentOfOwnership().get(0).getCoverages().getCoverage().add(coverage);
          }

          if (perpetualSet != null
              && perpetualSet.add(resultSet.getString("HOLDINGS_PERPETUAL_ACCESS_ID"))) {
            PerpetualAccess perpetualAccess = new PerpetualAccess();
            perpetualAccess.setPerpetualAccessStartDate(
                resultSet.getString("PERPETUAL_ACCESS_START_DATE"));
            perpetualAccess.setPerpetualAccessStartIssue(
                resultSet.getString("PERPETUAL_ACCESS_START_ISSUE"));
            perpetualAccess.setPerpetualAccessStartVolume(
                resultSet.getString("PERPETUAL_ACCESS_START_VOLUME"));
            perpetualAccess.setPerpetualAccessEndDate(
                resultSet.getString("PERPETUAL_ACCESS_END_DATE"));
            perpetualAccess.setPerpetualAccessEndVolume(
                resultSet.getString("PERPETUAL_ACCESS_END_VOLUME"));
            perpetualAccess.setPerpetualAccessEndIssue(
                resultSet.getString("PERPETUAL_ACCESS_END_ISSUE"));
            oleHoldings
                .getExtentOfOwnership()
                .get(0)
                .getPerpetualAccesses()
                .getPerpetualAccess()
                .add(perpetualAccess);
          }
        }
        if (donorSet != null && donorSet.add(resultSet.getString("HOLDINGS_DONOR_ID"))) {
          DonorInfo donorInfo = new DonorInfo();
          donorInfo.setDonorCode(resultSet.getString("DONOR_CODE"));
          donorInfo.setDonorNote(resultSet.getString("DONOR_NOTE"));
          donorInfo.setDonorPublicDisplay(resultSet.getString("DONOR_DISPLAY_NOTE"));
          oleHoldings.getDonorInfo().add(donorInfo);
        }
      }

      if (noteSet.add(resultSet.getString("HOLDINGS_NOTE_ID"))) {
        Note note = new Note();
        note.setValue(resultSet.getString("NOTE"));
        note.setType(resultSet.getString("TYPE"));
        oleHoldings.getNote().add(note);
      }
    }
    resultSet.close();
    return holdingsTrees;
  }
Ejemplo n.º 24
0
  @RequestMapping(value = "/", method = RequestMethod.GET)
  @Model
  public ModelMap get(
      @RequestParam("name") String termName, @RequestParam(required = false) boolean mark) {
    termName = termName.replace("_", " ");
    TermsMap.TermProvider provider = termsMap.getTermProvider(termName);
    if (provider == null) {
      throw new QuietException(format("Термин `%s` отсутствует", termName));
    }

    if (provider.hasMainTerm()) {
      provider = provider.getMainTermProvider();
    }

    ModelMap modelMap = new ModelMap(); // (ModelMap) getModelMap(term);

    Term term = provider.getTerm();

    modelMap.put("uri", term.getUri());
    modelMap.put("name", term.getName());
    if (mark) {
      if (term.getTaggedShortDescription() == null && term.getShortDescription() != null) {
        term.setTaggedShortDescription(termsMarker.mark(term.getShortDescription()));
        termDao.save(term);
      }
      if (term.getTaggedDescription() == null && term.getDescription() != null) {
        term.setTaggedDescription(termsMarker.mark(term.getDescription()));
        termDao.save(term);
      }
      modelMap.put("shortDescription", term.getTaggedShortDescription());
      modelMap.put("description", term.getTaggedDescription());
    } else {
      modelMap.put("shortDescription", term.getShortDescription());
      modelMap.put("description", term.getDescription());
    }

    // LINKS

    List<ModelMap> quotes = new ArrayList<ModelMap>();
    Set<UID> related = new LinkedHashSet<UID>();
    Set<UID> aliases = new LinkedHashSet<UID>();

    UID code = null;
    List<Link> links = linkDao.getAllLinks(term.getUri());
    for (Link link : links) {
      UID source = link.getUid1().getUri().equals(term.getUri()) ? link.getUid2() : link.getUid1();
      if (link.getQuote() != null || source instanceof Item) {
        quotes.add(getQuote(link, source, mark));
      } else if (ABBREVIATION.equals(link.getType()) || ALIAS.equals(link.getType())) {
        aliases.add(source);
      } else if (CODE.equals(link.getType())) {
        code = source;
      } else {
        related.add(source);
      }
    }

    // Нужно также включить цитаты всех синонимов и сокращений и кода
    Set<UID> aliasesQuoteSources = new HashSet<UID>(aliases);
    if (code != null) {
      aliasesQuoteSources.add(code);
    }
    for (UID uid : aliasesQuoteSources) {
      List<Link> aliasLinksWithQuote = linkDao.getAllLinks(uid.getUri());
      for (Link link : aliasLinksWithQuote) {
        UID source = link.getUid1().getUri().equals(uid.getUri()) ? link.getUid2() : link.getUid1();
        if (link.getQuote() != null || source instanceof Item) {
          quotes.add(getQuote(link, source, mark));
        } else if (ABBREVIATION.equals(link.getType())
            || ALIAS.equals(link.getType())
            || CODE.equals(link.getType())) {
          // Синонимы синонимов :) по идее их не должно быть, но если вдруг...
          // как минимум один есть и этот наш основной термин
          if (!source.getUri().equals(term.getUri())) {
            aliases.add(source);
          }
        } else {
          related.add(source);
        }
      }
    }
    sort(
        quotes,
        new Comparator<ModelMap>() {
          @Override
          public int compare(ModelMap o1, ModelMap o2) {
            return ((String) o1.get("uri")).compareTo((String) o2.get("uri"));
          }
        });

    modelMap.put("code", code);
    modelMap.put("quotes", quotes);
    modelMap.put("related", toPlainObjectWithoutContent(related));
    modelMap.put("aliases", toPlainObjectWithoutContent(aliases));
    modelMap.put("categories", searchController.inCategories(termName));

    return modelMap;
  }
Ejemplo n.º 25
0
 public void analsysNDPHost(Host node, Host host) {
   if (host.getNdpHash() == null)
     host.setNdpHash(snmp.getNDPTable(host.getIpAddress(), host.getCommunity()));
   // 判断该NDP中是否包含node的MAC地址,若包含,则说明node是跟该设备直接连接关系
   Hashtable hostNDPHash = host.getNdpHash();
   if (host.getMac() == null) {
     String descr = (String) hostNDPHash.get(node.getMac());
     IfEntity nodeIfEntity = node.getIfEntityByDesc(descr);
     Link link = new Link();
     link.setStartId(node.getId());
     link.setStartIndex(nodeIfEntity.getIndex());
     link.setStartIp(node.getIpAddress());
     link.setStartPhysAddress(node.getMac()); // 记录下起点的mac
     link.setStartDescr(descr);
     link.setEndIp(host.getIpAddress());
     DiscoverEngine.getInstance().addHost(host, link);
   } else {
     if (node.getNdpHash() != null) {
       if (node.getNdpHash().containsKey(host.getMac())) {
         String hostdesc = (String) node.getNdpHash().get(host.getMac());
         String descr = (String) hostNDPHash.get(node.getMac());
         IfEntity nodeIfEntity = node.getIfEntityByDesc(descr);
         IfEntity hostIfEntity = host.getIfEntityByDesc(hostdesc);
         Link link = new Link();
         link.setStartId(node.getId());
         link.setStartIndex(nodeIfEntity.getIndex());
         link.setStartIp(node.getIpAddress());
         link.setStartPhysAddress(node.getMac()); // 记录下起点的mac
         link.setStartDescr(descr);
         link.setEndIndex(hostIfEntity.getIndex());
         link.setEndIp(host.getIpAddress());
         link.setEndPhysAddress(hostIfEntity.getPhysAddress());
         link.setEndDescr(hostdesc);
         DiscoverEngine.getInstance().addHost(host, link);
       } else {
         String descr = (String) hostNDPHash.get(node.getMac());
         IfEntity nodeIfEntity = node.getIfEntityByDesc(descr);
         Link link = new Link();
         link.setStartId(node.getId());
         link.setStartIndex(nodeIfEntity.getIndex());
         link.setStartIp(node.getIpAddress());
         link.setStartPhysAddress(node.getMac()); // 记录下起点的mac
         link.setStartDescr(descr);
         link.setEndIp(host.getIpAddress());
         DiscoverEngine.getInstance().addHost(host, link);
       }
     } else {
       String descr = (String) hostNDPHash.get(node.getMac());
       IfEntity nodeIfEntity = node.getIfEntityByDesc(descr);
       Link link = new Link();
       link.setStartId(node.getId());
       link.setStartIndex(nodeIfEntity.getIndex());
       link.setStartIp(node.getIpAddress());
       link.setStartPhysAddress(node.getMac()); // 记录下起点的mac
       link.setStartDescr(descr);
       link.setEndIp(host.getIpAddress());
       DiscoverEngine.getInstance().addHost(host, link);
     }
   }
 }
Ejemplo n.º 26
0
 @Override
 public String getStringId() {
   return "@Basket:" + Link.getSiteName();
 }
Ejemplo n.º 27
0
  /**
   * Updates the entry based on the field that is specified. Mainly created for use by the bulk
   * import auto update
   *
   * @param entry entry to be updated
   * @param plasmid should be set if updating strain with plasmid
   * @param value value to be set
   * @param field to set
   * @return updated entry array containing both entry and plasmid. if plasmid is null only entry is
   *     returned
   */
  public static Entry[] infoToEntryForField(
      Entry entry, Entry plasmid, String value, EntryField field) {
    switch (field) {
      case PI:
        {
          entry.setPrincipalInvestigator(value);
          if (plasmid != null) plasmid.setPrincipalInvestigator(value);
          break;
        }

      case PI_EMAIL:
        {
          entry.setPrincipalInvestigatorEmail(value);
          break;
        }

      case FUNDING_SOURCE:
        {
          entry.setFundingSource(value);
          if (plasmid != null) plasmid.setFundingSource(value);
          break;
        }

      case IP:
        entry.setIntellectualProperty(value);
        if (plasmid != null) plasmid.setIntellectualProperty(value);
        break;

      case BIO_SAFETY_LEVEL:
        Integer level = BioSafetyOption.intValue(value);
        if (level == null) {
          if (value.contains("1")) level = 1;
          else if (value.contains("2")) level = 2;
          else break;
        }
        entry.setBioSafetyLevel(level);
        if (plasmid != null) {
          plasmid.setBioSafetyLevel(level);
        }
        break;

      case NAME:
        entry.setName(value);
        break;

      case ALIAS:
        entry.setAlias(value);
        break;

      case KEYWORDS:
        entry.setKeywords(value);
        break;

      case SUMMARY:
        entry.setShortDescription(value);
        break;

      case NOTES:
        entry.setLongDescription(value);
        break;

      case REFERENCES:
        entry.setReferences(value);
        break;

      case LINKS:
        HashSet<Link> links = new HashSet<>();
        Link link = new Link();
        link.setLink(value);
        link.setEntry(entry);
        links.add(link);
        entry.setLinks(links);
        break;

      case STATUS:
        entry.setStatus(value);
        if (plasmid != null) plasmid.setStatus(value);
        break;

      case SELECTION_MARKERS:
        HashSet<SelectionMarker> markers = new HashSet<>();
        SelectionMarker marker = new SelectionMarker(value, entry);
        markers.add(marker);
        entry.setSelectionMarkers(markers);
        break;

      case PARENTAL_STRAIN:
      case GENOTYPE_OR_PHENOTYPE:
      case PLASMIDS:
        entry = infoToStrainForField(entry, value, field);
        break;

      case BACKBONE:
      case ORIGIN_OF_REPLICATION:
      case CIRCULAR:
      case PROMOTERS:
      case REPLICATES_IN:
        entry = infoToPlasmidForField(entry, value, field);
        break;

      case HOMOZYGOSITY:
      case ECOTYPE:
      case HARVEST_DATE:
      case GENERATION:
      case SENT_TO_ABRC:
      case PLANT_TYPE:
      case PARENTS:
        entry = infoToSeedForField(entry, value, field);
        break;
      default:
        break;
    }
    if (plasmid == null) return new Entry[] {entry};

    return new Entry[] {entry, plasmid};
  }
Ejemplo n.º 28
0
  public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    int found = 0;
    ArrayList<Link> links = new ArrayList<Link>();
    ArrayList<Integer> gateways = new ArrayList<Integer>();
    int N = in.nextInt(); // the total number of nodes in the level, including the gateways
    int L = in.nextInt(); // the number of links
    int E = in.nextInt(); // the number of exit gateways
    for (int i = 0; i < L; i++) {
      int N1 = in.nextInt(); // N1 and N2 defines a link between these nodes
      int N2 = in.nextInt();
      links.add(new Link(N1, N2));
    }
    for (int i = 0; i < E; i++) {
      int EI = in.nextInt(); // the index of a gateway node
      gateways.add(new Integer(EI));
    }

    // game loop
    while (true) {
      found = 0;
      int SI =
          in.nextInt(); // The index of the node on which the Skynet agent is positioned this turn
      for (Link l : links) {
        if ((l.a == SI || l.b == SI) && (l.active == 1)) {
          // System.err.println(SI+" "+l.a+" "+l.b+" "+l.active+" a");
          for (int g : gateways) {
            System.err.println("g :" + g);
            if ((l.a == SI && g == l.b) || (l.b == SI && g == l.a)) {
              System.err.println(SI + " " + l.a + " " + l.b + " " + l.active + " a");
              System.out.println(l.a + " " + l.b);
              l.active = 0;
              found = 1;
              break;
            }
          }
        }
      }
      if (found == 0) {
        for (Link l : links) {
          // System.err.println(SI+" "+l.a+" "+l.b+" "+l.active+" b");
          if (l.active == 1 && (l.b == SI || l.a == SI)) {
            System.err.println(SI + " " + l.a + " " + l.b + " " + l.active + " c");
            System.out.println(l.a + " " + l.b);
            found = 1;
            l.active = 0;
            break;
          }
        }
      }

      if (found == 0) {
        for (Link l : links) {
          for (int g : gateways) {
            if (l.active == 1 && (l.b == g || l.a == g)) {
              System.err.println(SI + " " + l.a + " " + l.b + " " + l.active + " b");
              System.out.println(l.a + " " + l.b);
              found = 1;
              l.active = 0;
              break;
            }
          }
          if (found == 1) {
            break;
          }
        }
      }

      if (found == 0) {
        for (Link l : links) {
          if (l.active == 1) {
            System.err.println(SI + " " + l.a + " " + l.b + " " + l.active + " d");
            System.out.println(l.a + " " + l.b);
            found = 1;
            l.active = 0;
            break;
          }
        }
      }
      // Write an action using System.out.println()
      // To debug: System.err.println("Debug messages...");

      // System.out.println("0 1"); // Example: 0 1 are the indices of the nodes you wish to sever
      // the link between
    }
  }
Ejemplo n.º 29
0
 public void addLink(String url, String rel) {
   Link link = new Link();
   link.setLink(url);
   link.setRel(rel);
   this.links.add(link);
 }
    public void update(Clock clock) {

      int i, j;
      int e = 0;

      if (measured_flow_profile_veh.sample(false, clock))
        current_flow_veh = measured_flow_profile_veh.getCurrentSample() * knob;

      if (BeatsMath.equals(current_flow_veh, 0d)) {
        beta = 0d;
        return;
      }

      // Sf: total demand from "feeds"
      Double Sf = 0d;
      for (Link link : feeds) Sf += BeatsMath.sum(link.get_out_demand_in_veh(e));

      // compute demand to non-measured, total $+phi, and from feed links phi
      ArrayList<Double> beta_array = new ArrayList<Double>();

      // compute sr normalization factor for feeding links
      //            for(i=0;i<myNode.getInput_link().length;i++) {
      //                if (!feeds.contains( myNode.input_link[i]))
      //                    continue;
      //                alpha_tilde[i] = 0d;
      //                for (j = 0; j < myNode.nOut; j++)
      //                    if(not_meas.contains( myNode.output_link[j]))
      //                        alpha_tilde[i] += myNode.getSplitRatio(i, j);
      //            }

      // freeflow case
      beta_array.add(0d);
      beta_array.add(current_flow_veh / Sf);

      // rest
      for (j = 0; j < myNode.nOut; j++) {
        Link outlink = myNode.output_link[j];

        // case for the measured
        if (not_meas.contains(outlink)) {

          double dem_non_feed = 0d; // demand on j from non-feeding links
          double dem_feed = 0d; // demand on j from feeding links

          for (i = 0; i < myNode.nIn; i++) {
            Link inlink = myNode.input_link[i];
            //                        Double alpha_ij = myNode.getSplitRatio(i,j);
            Double Si = BeatsMath.sum(inlink.get_out_demand_in_veh(e));
            if (feeds.contains(inlink)) dem_feed += Si; // alpha_ij * Si / alpha_tilde[i];
            else // otherwise add to total
            dem_non_feed += 0d; // alpha_ij * Si;
          }

          Double R = outlink.get_available_space_supply_in_veh(e);

          double num = current_flow_veh * (dem_non_feed + dem_feed);
          double den = Sf * R + dem_feed * current_flow_veh;

          beta_array.add(den > 0 ? num / den : Double.POSITIVE_INFINITY);
        }
      }

      beta = Math.min(BeatsMath.max(beta_array), 1d);
    }