List of usage examples for java.util ArrayList forEach
@Override public void forEach(Consumer<? super E> action)
From source file:treeNormalizer.structure.internal.treeBucketNode.java
/** * fgt neue Eltern ein//from ww w . j av a2 s . c om * * @param parents die neuen Eltern */ public void addParents(ArrayList<treeBucketNode> parents) { parents.forEach((parent) -> { addParent(parent); }); }
From source file:treeNormalizer.structure.internal.treeBucketNode.java
/** * fgt eine Menge von Referenzen ein//from w ww . ja v a2 s. c om * * @param nodeReferences die Referenzen */ public void addNodeReferences(ArrayList<nodeReference> nodeReferences) { nodeReferences.forEach((ref) -> { addNodeReference(ref); }); }
From source file:se.trixon.mapollage.Operation.java
private void addPath() { Collections.sort(mLineNodes, (LineNode o1, LineNode o2) -> o1.getDate().compareTo(o2.getDate())); mPathFolder = KmlFactory.createFolder().withName(Dict.PATH_GFX.toString()); mPathGapFolder = KmlFactory.createFolder().withName(Dict.PATH_GAP_GFX.toString()); String pattern = getPattern(mProfilePath.getSplitBy()); SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); TreeMap<String, ArrayList<LineNode>> map = new TreeMap<>(); mLineNodes.forEach((node) -> {//from w w w .j av a 2 s . c o m String key = dateFormat.format(node.getDate()); if (!map.containsKey(key)) { map.put(key, new ArrayList<>()); } map.get(key).add(node); }); //Add paths for (ArrayList<LineNode> nodes : map.values()) { if (nodes.size() > 1) { Placemark path = mPathFolder.createAndAddPlacemark().withName(LineNode.getName(nodes)); Style pathStyle = path.createAndAddStyle(); pathStyle.createAndSetLineStyle().withColor("ff0000ff").withWidth(mProfilePath.getWidth()); LineString line = path.createAndSetLineString().withExtrude(false).withTessellate(true); nodes.forEach((node) -> { line.addToCoordinates(node.getLon(), node.getLat()); }); } } //Add path gap ArrayList<LineNode> previousNodes = null; for (ArrayList<LineNode> nodes : map.values()) { if (previousNodes != null) { Placemark path = mPathGapFolder.createAndAddPlacemark() .withName(LineNode.getName(previousNodes, nodes)); Style pathStyle = path.createAndAddStyle(); pathStyle.createAndSetLineStyle().withColor("ff00ffff").withWidth(mProfilePath.getWidth()); LineString line = path.createAndSetLineString().withExtrude(false).withTessellate(true); LineNode prevLast = previousNodes.get(previousNodes.size() - 1); LineNode currentFirst = nodes.get(0); line.addToCoordinates(prevLast.getLon(), prevLast.getLat()); line.addToCoordinates(currentFirst.getLon(), currentFirst.getLat()); } previousNodes = nodes; } }
From source file:org.hawkular.inventory.impl.tinkerpop.sql.SqlGraphProvider.java
@Override public void ensureIndices(TransactionalGraph graph, IndexSpec... indexSpecs) { try {/* w w w .j a v a 2 s.c o m*/ SqlGraph sqlg = (SqlGraph) graph; sqlg.createSchemaIfNeeded(); Set<String> vertexIndices = sqlg.getIndexedKeys(Vertex.class); Set<String> edgeIndices = sqlg.getIndexedKeys(Edge.class); ArrayList<IndexSpec> specs = new ArrayList<>(Arrays.asList(indexSpecs)); BiConsumer<IndexSpec, Consumer<IndexSpec.Property>> indexChecker = (is, indexMutator) -> { IndexSpec.Property prop = is.getProperties().iterator().next(); if (!prop.isUnique()) { return; } Set<String> indices = is.getElementType().equals(Edge.class) ? edgeIndices : vertexIndices; if (indices.contains(prop.getName())) { return; } indexMutator.accept(prop); }; Iterator<IndexSpec> it = specs.iterator(); while (it.hasNext()) { IndexSpec is = it.next(); if (is.getProperties().stream().filter(IndexSpec.Property::isUnique).count() > 1) { throw new IllegalArgumentException( "SQL Graph doesn't support unique indices over multiple " + "properties"); } it.remove(); indexChecker.accept(is, prop -> sqlg.createKeyIndex(prop.getName(), is.getElementType(), (Parameter[]) null)); } //now remove those that are defined but no longer needed specs.forEach( is -> indexChecker.accept(is, prop -> sqlg.dropKeyIndex(prop.getName(), is.getElementType()))); sqlg.commit(); } catch (SQLException | IOException e) { throw new IllegalStateException("Could not create the database schema and indices.", e); } }
From source file:pah9qdmoviereviews.MovieReviewsFXMLController.java
public void ready(Stage stage, Scene scene) { this.stage = stage; this.scene = scene; movieReviewManager = new NYTMoviewReviewManager(); movieReviewManager.addPropertyChangeSupport(((evt) -> { switch (evt.getPropertyName()) { case "Exception": Platform.runLater(() -> displayExceptionAlert((Exception) evt.getNewValue())); break; case "Add Movie Review": Platform.runLater(() -> { movieReviews.add((NYTMovieReview) evt.getNewValue()); this.foundText.setText(("Found " + movieReviews.size() + " results for " + searchString + ".")); });//from w ww .ja va 2 s .c o m break; case "Clear Movie Reviews": Platform.runLater(() -> movieReviews.clear()); break; case "Completed": if (movieReviews.isEmpty()) this.foundText.setText("No reviews found for " + searchString); break; default: Platform.runLater( () -> displayExceptionAlert(new Exception("Invalid Property Change Support Property"))); break; } })); movieReviews = FXCollections.observableArrayList(); listView.setItems(movieReviews); listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<NYTMovieReview>() { @Override public void changed(ObservableValue<? extends NYTMovieReview> observable, NYTMovieReview oldValue, NYTMovieReview newValue) { detailsBox.getChildren().clear(); movieImage.setImage(null); if (newValue != null) { DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH); String pictureLink = newValue.getPictureLink(); if (pictureLink != null && !pictureLink.isEmpty()) { reviewBox.getChildren().remove(0); reviewBox.getChildren().add(0, movieImage); movieImage.setImage(new Image(pictureLink)); } else { reviewBox.getChildren().remove(0); reviewBox.getChildren().add(0, missingImageText); movieImage.setImage(null); } ArrayList<Label> labelArray = new ArrayList<>(); if (!newValue.getDisplayTitle().isEmpty()) { Label titleLabel = new Label(newValue.getDisplayTitle()); titleLabel.fontProperty().set(Font.font(20)); labelArray.add(titleLabel); } if (!newValue.getSummary().isEmpty()) { labelArray.add(new Label("Summary: " + newValue.getSummary())); } if (!newValue.getMpaaRating().isEmpty()) { labelArray.add(new Label("MPAA Rating: " + newValue.getMpaaRating())); } if (newValue.getPublicationDate() != null) { labelArray.add( new Label("Publication Date: " + dateFormat.format(newValue.getPublicationDate()))); } if (newValue.getOpeningDate() != null) { labelArray.add(new Label("Opening Date: " + dateFormat.format(newValue.getOpeningDate()))); } labelArray.forEach((label) -> { label.wrapTextProperty().set(true); }); detailsBox.getChildren().addAll(labelArray); Button openButton = new Button("Open Review"); openButton.setOnAction((event) -> { try { Desktop.getDesktop().browse(new URI(newValue.getArticleLink())); } catch (Exception ex) { displayExceptionAlert(ex); } }); detailsBox.getChildren().add(openButton); } } }); HBox.setMargin(missingImageText, new Insets(15, 15, 15, 15)); searchTextField.setOnKeyPressed((event) -> { if (event.getCode() == KeyCode.ENTER) { loadReviews(searchTextField.getText()); } }); // searchTextField.textProperty().addListener((observable, oldValue, newValue) -> { // if(newValue != null && !newValue.isEmpty()) // loadReviews(newValue); // }); }
From source file:utybo.branchingstorytree.swing.OpenBSTGUI.java
private JMenu createShortMenu() { JMenu shortMenu = new JMenu(); addDarkModeCallback(b -> {/* w w w . ja va 2 s .c o m*/ shortMenu.setBackground(b ? OPENBST_BLUE.darker().darker() : OPENBST_BLUE.brighter()); shortMenu.setForeground(b ? Color.WHITE : OPENBST_BLUE); }); shortMenu.setBackground(OPENBST_BLUE.brighter()); shortMenu.setForeground(OPENBST_BLUE); shortMenu.setText(Lang.get("banner.title")); shortMenu.setIcon(new ImageIcon(Icons.getImage("Logo", 16))); JMenuItem label = new JMenuItem(Lang.get("menu.title")); label.setEnabled(false); shortMenu.add(label); shortMenu.addSeparator(); shortMenu.add( new JMenuItem(new AbstractAction(Lang.get("menu.open"), new ImageIcon(Icons.getImage("Open", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { openStory(VisualsUtils.askForFile(OpenBSTGUI.this, Lang.get("file.title"))); } })); shortMenu.addSeparator(); shortMenu.add(new JMenuItem( new AbstractAction(Lang.get("menu.create"), new ImageIcon(Icons.getImage("Add Property", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { doNewEditor(); } })); JMenu additionalMenu = new JMenu(Lang.get("menu.advanced")); shortMenu.add(additionalMenu); additionalMenu.add(new JMenuItem( new AbstractAction(Lang.get("menu.package"), new ImageIcon(Icons.getImage("Open Archive", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { new PackageDialog(instance).setVisible(true); } })); additionalMenu.add(new JMenuItem( new AbstractAction(Lang.get("langcheck"), new ImageIcon(Icons.getImage("LangCheck", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final Map<String, String> languages = new Gson() .fromJson(new InputStreamReader( OpenBST.class.getResourceAsStream( "/utybo/branchingstorytree/swing/lang/langs.json"), StandardCharsets.UTF_8), new TypeToken<Map<String, String>>() { }.getType()); languages.remove("en"); languages.remove("default"); JComboBox<String> jcb = new JComboBox<>(new Vector<>(languages.keySet())); JPanel panel = new JPanel(); panel.add(new JLabel(Lang.get("langcheck.choose"))); panel.add(jcb); int result = JOptionPane.showOptionDialog(OpenBSTGUI.this, panel, Lang.get("langcheck"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (result == JOptionPane.OK_OPTION) { Locale selected = new Locale((String) jcb.getSelectedItem()); if (!Lang.getMap().keySet().contains(selected)) { try { Lang.loadTranslationsFromFile(selected, OpenBST.class .getResourceAsStream("/utybo/branchingstorytree/swing/lang/" + languages.get(jcb.getSelectedItem().toString()))); } catch (UnrespectedModelException | IOException e1) { LOG.warn("Failed to load translation file", e1); } } ArrayList<String> list = new ArrayList<>(); Lang.getLocaleMap(Locale.ENGLISH).forEach((k, v) -> { if (!Lang.getLocaleMap(selected).containsKey(k)) { list.add(k + "\n"); } }); StringBuilder sb = new StringBuilder(); Collections.sort(list); list.forEach(s -> sb.append(s)); JDialog dialog = new JDialog(OpenBSTGUI.this, Lang.get("langcheck")); dialog.getContentPane().setLayout(new MigLayout()); dialog.getContentPane().add(new JLabel(Lang.get("langcheck.result")), "pushx, growx, wrap"); JTextArea area = new JTextArea(); area.setLineWrap(true); area.setWrapStyleWord(true); area.setText(sb.toString()); area.setEditable(false); area.setBorder(BorderFactory.createLoweredBevelBorder()); JScrollPane jsp = new JScrollPane(area); jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); dialog.getContentPane().add(jsp, "pushx, pushy, growx, growy"); dialog.setSize((int) (Icons.getScale() * 300), (int) (Icons.getScale() * 300)); dialog.setLocationRelativeTo(OpenBSTGUI.this); dialog.setModalityType(ModalityType.APPLICATION_MODAL); dialog.setVisible(true); } } })); additionalMenu.add(new JMenuItem( new AbstractAction(Lang.get("menu.debug"), new ImageIcon(Icons.getImage("Code", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { DebugInfo.launch(OpenBSTGUI.this); } })); JMenu includedFiles = new JMenu("Included BST files"); for (Entry<String, String> entry : OpenBST.getInternalFiles().entrySet()) { JMenuItem jmi = new JMenuItem(entry.getKey()); jmi.addActionListener(ev -> { String path = "/bst/" + entry.getValue(); InputStream is = OpenBSTGUI.class.getResourceAsStream(path); ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(OpenBSTGUI.this, "Extracting...", is); new Thread(() -> { try { File f = File.createTempFile("openbstinternal", ".bsp"); FileOutputStream fos = new FileOutputStream(f); IOUtils.copy(pmis, fos); openStory(f); } catch (final IOException e) { LOG.error("IOException caught", e); showException(Lang.get("file.error").replace("$e", e.getClass().getSimpleName()) .replace("$m", e.getMessage()), e); } }).start(); }); includedFiles.add(jmi); } additionalMenu.add(includedFiles); shortMenu.addSeparator(); JMenu themesMenu = new JMenu(Lang.get("menu.themes")); shortMenu.add(themesMenu); themesMenu.setIcon(new ImageIcon(Icons.getImage("Color Wheel", 16))); ButtonGroup themesGroup = new ButtonGroup(); JRadioButtonMenuItem jrbmi; jrbmi = new JRadioButtonMenuItem(Lang.get("menu.themes.dark")); if (0 == selectedTheme) { jrbmi.setSelected(true); } jrbmi.addActionListener(e -> switchLaF(0, DARK_THEME)); themesMenu.add(jrbmi); themesGroup.add(jrbmi); jrbmi = new JRadioButtonMenuItem(Lang.get("menu.themes.light")); if (1 == selectedTheme) { jrbmi.setSelected(true); } jrbmi.addActionListener(e -> switchLaF(1, LIGHT_THEME)); themesMenu.add(jrbmi); themesGroup.add(jrbmi); jrbmi = new JRadioButtonMenuItem(Lang.get("menu.themes.debug")); if (2 == selectedTheme) { jrbmi.setSelected(true); } jrbmi.addActionListener(e -> switchLaF(2, DEBUG_THEME)); themesMenu.add(jrbmi); themesGroup.add(jrbmi); JMenu additionalLightThemesMenu = new JMenu(Lang.get("menu.themes.morelight")); int j = 3; for (Map.Entry<String, LookAndFeel> entry : ADDITIONAL_LIGHT_THEMES.entrySet()) { int jf = j; jrbmi = new JRadioButtonMenuItem(entry.getKey()); if (j == selectedTheme) jrbmi.setSelected(true); jrbmi.addActionListener(e -> switchLaF(jf, entry.getValue())); additionalLightThemesMenu.add(jrbmi); themesGroup.add(jrbmi); j++; } themesMenu.add(additionalLightThemesMenu); JMenu additionalDarkThemesMenu = new JMenu(Lang.get("menu.themes.moredark")); for (Map.Entry<String, LookAndFeel> entry : ADDITIONAL_DARK_THEMES.entrySet()) { int jf = j; jrbmi = new JRadioButtonMenuItem(entry.getKey()); if (j == selectedTheme) jrbmi.setSelected(true); jrbmi.addActionListener(e -> switchLaF(jf, entry.getValue())); additionalDarkThemesMenu.add(jrbmi); themesGroup.add(jrbmi); j++; } themesMenu.add(additionalDarkThemesMenu); shortMenu.add(new JMenuItem( new AbstractAction(Lang.get("menu.about"), new ImageIcon(Icons.getImage("About", 16))) { /** * */ private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { new AboutDialog(instance).setVisible(true); } })); return shortMenu; }
From source file:org.hyperledger.fabric.sdkintegration.End2endMTIT.java
public void runFabricTest(final SampleStore sampleStore) throws Exception { //////////////////////////// // Setup client //Create instance of client. HFClient client = HFClient.createNewInstance(); client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite()); //////////////////////////// //Construct and run the channels final Collection<CompletableFuture<BlockEvent.TransactionEvent>> futures = new ArrayList<>(2); // CompletableFuture<BlockEvent.TransactionEvent>[] ii = new CompletableFuture[2]; SampleOrg sampleOrg1 = testConfig.getIntegrationTestsSampleOrg("peerOrg1"); Channel fooChannel = constructChannel(FOO_CHANNEL_NAME, client, sampleOrg1); futures.add(installInstantiate(fooChannel, client, sampleOrg1)); SampleOrg sampleOrg2 = testConfig.getIntegrationTestsSampleOrg("peerOrg2"); Channel barChannel = constructChannel(BAR_CHANNEL_NAME, client, sampleOrg2); futures.add(installInstantiate(barChannel, client, sampleOrg2)); final CompletableFuture<Void> voidCompletableFuture = CompletableFuture .allOf(futures.toArray(new CompletableFuture[futures.size()])); voidCompletableFuture.thenApply(avoid -> { ArrayList<Thread> threads = new ArrayList<>(); TestPair[] testPairs = { new TestPair(fooChannel, sampleOrg1), new TestPair(barChannel, sampleOrg2) }; for (int i = 0; i < WORKER_COUNT; ++i) { Thread thread = new Thread(new Worker(i, client, testPairs)); thread.setName("TCW_" + i); thread.setDaemon(true);//from ww w . j a va2 s .c o m thread.start(); threads.add(thread); try { Thread.sleep(random.nextInt(3000)); // stage them to be doing different tasks } catch (InterruptedException e) { e.printStackTrace(); } } threads.forEach(t -> { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); return null; }).get(); // voidCompletableFuture.thenApply(() -> futures.stream() // .map(CompletableFuture::join) // .collect(Collectors.toList()) // ); // // CompletableFuture<BlockEvent.TransactionEvent>.allOf (futures.toArray()) // .thenApply(() -> futures.stream() // .map(CompletableFuture::join) // .collect(Collectors.toList()) // ); // //let bar channel just shutdown so we have both scenarios. // // out("\nTraverse the blocks for chain %s ", barChannel.getName()); // // blockWalker(client, barChannel); // // assertFalse(barChannel.isShutdown()); // assertTrue(barChannel.isInitialized()); out("That's all folks!"); }
From source file:com.rinke.solutions.pinball.PinDmdEditor.java
void updateAnimationMapKey(String oldKey, String newKey) { ArrayList<Animation> tmp = new ArrayList<Animation>(); if (!oldKey.equals(newKey)) { animations.values().forEach(ani -> tmp.add(ani)); animations.clear();//from ww w . j a v a 2 s . c o m tmp.forEach(ani -> animations.put(ani.getDesc(), ani)); } }
From source file:sh.isaac.convert.rxnorm.standard.RxNormMojo.java
/** * Process CUI rows./* w w w .ja va2s . co m*/ * * @param conceptData the concept data * @throws IOException Signals that an I/O exception has occurred. * @throws SQLException the SQL exception * @throws PropertyVetoException the property veto exception */ private void processCUIRows(ArrayList<RXNCONSO> conceptData) throws IOException, SQLException, PropertyVetoException { final String rxCui = conceptData.get(0).rxcui; final HashSet<String> uniqueTTYs = new HashSet<>(); final HashSet<String> uniqueSABs = new HashSet<>(); // ensure all the same CUI, gather the TTYs involved conceptData.stream().map((row) -> { uniqueTTYs.add(row.tty); return row; }).map((row) -> { uniqueSABs.add(row.sab); return row; }).filter((row) -> (!row.rxcui.equals(rxCui))).forEachOrdered((_item) -> { throw new RuntimeException("Oops"); }); ComponentReference cuiConcept; if ((uniqueSABs.size() == 1) && uniqueSABs.iterator().next().equals(this.sctSab)) { // This is a SCT only concept - we don't want to create it. But we might need to put some relationships or associations here. final String sctId = conceptData.get(0).code; if (sctId == null) { throw new RuntimeException("Unexpected"); } cuiConcept = ComponentReference.fromConcept(this.sctIdToUUID.get(sctId)); // Add the RxCUI UUID this.importUtil.addUUID(cuiConcept.getPrimordialUuid(), createCUIConceptUUID(rxCui)); // TODO need to look at what else I should be grabbing - the RXCUI for example should be attached. What else? } else { // just creating the reference here, with the UUID - because we don't know if it should be active or inactive yet. // create the real concept later. cuiConcept = ComponentReference.fromConcept(createCUIConceptUUID(rxCui)); long conceptTime = Integer.MAX_VALUE; // Activate the concept if any description is active Status conceptState = Status.INACTIVE; this.importUtil.addStringAnnotation(cuiConcept, rxCui, this.ptUMLSAttributes.getProperty("RXCUI").getUUID(), Status.ACTIVE); final ArrayList<ValuePropertyPairWithSAB> cuiDescriptions = new ArrayList<>(); final HashSet<String> sabs = new HashSet<>(); for (final RXNCONSO atom : conceptData) { if (atom.sab.equals(this.sctSab)) { continue; } // Add attributes from SAT table this.descSat.clearParameters(); this.descSat.setString(1, rxCui); this.descSat.setString(2, atom.rxaui); final ArrayList<RXNSAT> satData; boolean disableDescription; Long descriptionTime; try (ResultSet rs = this.descSat.executeQuery()) { satData = new ArrayList<>(); disableDescription = false; descriptionTime = null; while (rs.next()) { final RXNSAT current = new RXNSAT(rs); satData.add(current); if ("RXN_OBSOLETED".equals(current.atn)) { disableDescription = true; } if ("RXN_ACTIVATED".equals(current.atn)) { try { final long time = this.dateParse.parse(current.atv).getTime(); descriptionTime = time; if (time < conceptTime) { conceptTime = time; } } catch (final ParseException e) { throw new RuntimeException("Can't parse date?"); } } } } final ValuePropertyPairWithSAB desc = new ValuePropertyPairWithSAB(atom.str, this.ptDescriptions.getProperty(atom.tty), atom.sab, satData); if (disableDescription) { desc.setDisabled(true); } else { // if any description is active, concept is still active conceptState = Status.ACTIVE; } if (descriptionTime != null) { desc.setTime(descriptionTime); } desc.setUUID(ConverterUUID.createNamespaceUUIDFromStrings(cuiConcept.getPrimordialUuid().toString(), atom.rxaui)); // used for sorting description to figure out what to use for FULLY_QUALIFIED_NAME cuiDescriptions.add(desc); desc.addStringAttribute(this.ptUMLSAttributes.getProperty("RXAUI").getUUID(), atom.rxaui); desc.addUUIDAttribute(this.ptUMLSAttributes.getProperty("SAB").getUUID(), this.ptSABs.getProperty(atom.sab).getUUID()); if (StringUtils.isNotBlank(atom.code) && !atom.code.equals("NOCODE")) { desc.addStringAttribute(this.ptUMLSAttributes.getProperty("CODE").getUUID(), atom.code); } if (StringUtils.isNotBlank(atom.saui)) { desc.addStringAttribute(this.ptUMLSAttributes.getProperty("SAUI").getUUID(), atom.saui); } if (StringUtils.isNotBlank(atom.scui)) { desc.addStringAttribute(this.ptUMLSAttributes.getProperty("SCUI").getUUID(), atom.scui); } if (StringUtils.isNotBlank(atom.suppress)) { desc.addUUIDAttribute(this.ptUMLSAttributes.getProperty("SUPPRESS").getUUID(), this.suppress.get(atom.suppress)); } if (StringUtils.isNotBlank(atom.cvf)) { if (atom.cvf.equals("4096")) { desc.addRefsetMembership(this.cpcRefsetConcept.getPrimordialUuid()); } else { throw new RuntimeException("Unexpected value in RXNCONSO cvf column '" + atom.cvf + "'"); } } if (!atom.lat.equals("ENG")) { ConsoleUtil.printErrorln("Non-english lang settings not handled yet!"); } // TODO - at this point, sometime in the future, we make make attributes out of the relationships that occur between the AUIs // and store them on the descriptions, since OTF doesn't allow relationships between descriptions // TODO am I supposed to be using sabs? sabs.add(atom.sab); } // sanity check on descriptions - make sure we only have one that is of type synonym with the preferred flag final ArrayList<String> items = new ArrayList<>(); cuiDescriptions.stream() .filter((vpp) -> ((vpp.getProperty().getPropertySubType() >= BPT_Descriptions.SYNONYM) && (vpp.getProperty().getPropertySubType() <= (BPT_Descriptions.SYNONYM + 20)))) .forEachOrdered((vpp) -> { items.add(vpp.getProperty().getSourcePropertyNameFQN() + " " + vpp.getProperty().getPropertySubType()); }); // Numbers come from the rankings down below in makeDescriptionType(...) final HashSet<String> ranksLookedAt = new HashSet<>(); ranksLookedAt.add("204"); ranksLookedAt.add("206"); ranksLookedAt.add("210"); ranksLookedAt.add("208"); ranksLookedAt.add("212"); boolean oneNotInList = false; if (items.size() > 1) { for (final String s : items) { if (!ranksLookedAt.contains(s.substring(s.length() - 3, s.length()))) { oneNotInList = true; break; } } } if (oneNotInList) { ConsoleUtil.printErrorln( "Need to rank multiple synonym types that are each marked preferred, determine if ranking is appropriate!"); items.forEach((s) -> { ConsoleUtil.printErrorln(s); }); } final List<SemanticChronology> addedDescriptions = this.importUtil.addDescriptions(cuiConcept, cuiDescriptions); if (addedDescriptions.size() != cuiDescriptions.size()) { throw new RuntimeException("oops"); } final HashSet<String> uniqueUMLSCUI = new HashSet<>(); for (int i = 0; i < cuiDescriptions.size(); i++) { final SemanticChronology desc = addedDescriptions.get(i); final ValuePropertyPairWithSAB descPP = cuiDescriptions.get(i); final BiFunction<String, String, Boolean> functions = (atn, atv) -> { // Pull these up to the concept. if ("UMLSCUI".equals(atn)) { uniqueUMLSCUI.add(atv); return true; } return false; }; // TODO should I be passing in item code here? processSAT(ComponentReference.fromChronology(desc), descPP.getSatData(), null, descPP.getSab(), functions); } // pulling up the UMLS CUIs. // uniqueUMLSCUI is populated during processSAT uniqueUMLSCUI.forEach((umlsCui) -> { final UUID itemUUID = ConverterUUID.createNamespaceUUIDFromString("UMLSCUI" + umlsCui); this.importUtil.addStringAnnotation(cuiConcept, itemUUID, umlsCui, this.ptTermAttributes.getProperty("UMLSCUI").getUUID(), Status.ACTIVE); }); ValuePropertyPairWithAttributes.processAttributes(this.importUtil, cuiDescriptions, addedDescriptions); // there are no attributes in rxnorm without an AUI. // try // { this.importUtil.addRefsetMembership(cuiConcept, this.allCUIRefsetConcept.getPrimordialUuid(), Status.ACTIVE, null); // } // catch (RuntimeException e) // { // if (e.toString().contains("duplicate UUID")) // { // //ok - this can happen due to multiple merges onto an existing SCT concept // } // else // { // throw e; // } // } // add semantic types this.semanticTypeStatement.clearParameters(); this.semanticTypeStatement.setString(1, rxCui); final ResultSet rs = this.semanticTypeStatement.executeQuery(); processSemanticTypes(cuiConcept, rs); if (conceptTime < 0) { throw new RuntimeException("oops"); } this.importUtil.createConcept(cuiConcept.getPrimordialUuid(), conceptTime, conceptState, null); } final HashSet<UUID> parents = new HashSet<>(); this.cuiRelStatementForward.clearParameters(); this.cuiRelStatementForward.setString(1, rxCui); parents.addAll(addRelationships(cuiConcept, REL.read(null, this.cuiRelStatementForward.executeQuery(), true, this.allowedCUIsForSABs, this.skippedRelForNotMatchingCUIFilter, true, (string -> reverseRel(string))))); this.cuiRelStatementBackward.clearParameters(); this.cuiRelStatementBackward.setString(1, rxCui); parents.addAll(addRelationships(cuiConcept, REL.read(null, this.cuiRelStatementBackward.executeQuery(), false, this.allowedCUIsForSABs, this.skippedRelForNotMatchingCUIFilter, true, (string -> reverseRel(string))))); // Have to add multiple parents at once, no place to keep all the other details. Load those as associations for now. if (parents.size() > 0) { ComponentReference.fromChronology(this.importUtil.addParent(cuiConcept, null, parents.toArray(new UUID[parents.size()]), null, null)); } }
From source file:structuredPredictionNLG.SFX.java
/** * * @param di/*from w w w . j av a 2s .com*/ * @param wordSequence * @return */ @Override public String postProcessWordSequence(DatasetInstance di, ArrayList<Action> wordSequence) { HashSet<ArrayList<Action>> matched = new HashSet<>(); ArrayList<Action> processedWordSequence = new ArrayList<>(); wordSequence.forEach((act) -> { processedWordSequence.add(new Action(act)); }); if (!processedWordSequence.isEmpty() && processedWordSequence.get(processedWordSequence.size() - 1).getWord().equals(Action.TOKEN_END) && processedWordSequence.get(processedWordSequence.size() - 1).getAttribute() .equals(Action.TOKEN_END)) { processedWordSequence.remove(processedWordSequence.size() - 1); } if (getPunctuationPatterns().containsKey(di.getMeaningRepresentation().getPredicate())) { getPunctuationPatterns().get(di.getMeaningRepresentation().getPredicate()).keySet() .forEach((surrounds) -> { int beforeNulls = 0; if (surrounds.get(0) == null) { beforeNulls++; } if (surrounds.get(1) == null) { beforeNulls++; } for (int i = 0 - beforeNulls; i < processedWordSequence.size(); i++) { boolean matches = true; int m = 0; for (int s = 0; s < surrounds.size(); s++) { if (surrounds.get(s) != null) { if (i + s < processedWordSequence.size()) { if (!processedWordSequence.get(i + s).getWord().equals(surrounds.get(s) .getWord()) /*|| !cleanActionList.get(i).getAttribute().equals(surrounds.get(s).getAttribute())*/) { matches = false; s = surrounds.size(); } else { m++; } } else { matches = false; s = surrounds.size(); } } else if (s < 2 && i + s >= 0) { matches = false; s = surrounds.size(); } else if (s >= 2 && i + s < processedWordSequence.size()) { matches = false; s = surrounds.size(); } } if (matches && m > 0) { matched.add(surrounds); processedWordSequence.add(i + 2, getPunctuationPatterns() .get(di.getMeaningRepresentation().getPredicate()).get(surrounds)); } } }); } boolean isLastPunct = true; if (processedWordSequence.contains(new Action("and", ""))) { for (int i = processedWordSequence.size() - 1; i > 0; i--) { if (processedWordSequence.get(i).getWord().equals(",") && isLastPunct) { isLastPunct = false; processedWordSequence.get(i).setWord("and"); } else if (processedWordSequence.get(i).getWord().equals("and") && isLastPunct) { isLastPunct = false; } else if (processedWordSequence.get(i).getWord().equals("and") && !isLastPunct) { processedWordSequence.get(i).setWord(","); } } } ArrayList<Action> cleanActionList = new ArrayList<>(); processedWordSequence.stream().filter((action) -> (!action.getWord().equals(Action.TOKEN_START) && !action.getWord().equals(Action.TOKEN_END))).forEachOrdered((action) -> { cleanActionList.add(action); }); String predictedWordSequence = " "; boolean previousIsTokenX = false; for (Action action : cleanActionList) { if (action.getWord().startsWith(Action.TOKEN_X)) { predictedWordSequence += " " + di.getMeaningRepresentation().getDelexicalizationMap().get(action.getWord()); previousIsTokenX = true; } else { if (action.getWord().equals("-ly") && previousIsTokenX) { predictedWordSequence += "ly"; } else if (action.getWord().equals("s") && previousIsTokenX) { predictedWordSequence += action.getWord(); } else { predictedWordSequence += " " + action.getWord(); } previousIsTokenX = false; } } predictedWordSequence = predictedWordSequence.trim(); if (di.getMeaningRepresentation().getPredicate().startsWith("?") && !predictedWordSequence.endsWith("?")) { if (predictedWordSequence.endsWith(".")) { predictedWordSequence = predictedWordSequence.substring(0, predictedWordSequence.length() - 1); } predictedWordSequence = predictedWordSequence.trim() + "?"; } else if (!predictedWordSequence.endsWith(".") && !predictedWordSequence.endsWith("?")) { /*if (predictedWordSequence.endsWith("?")) { predictedWordSequence = predictedWordSequence.substring(0, predictedWordSequence.length() - 1); }*/ predictedWordSequence = predictedWordSequence.trim() + "."; } predictedWordSequence = predictedWordSequence.replaceAll(" the the ", " the ").replaceAll("\\?", " \\? ") .replaceAll(":", " : ").replaceAll("\\.", " \\. ").replaceAll(",", " , ").replaceAll(" ", " ") .trim(); predictedWordSequence = predictedWordSequence.replaceAll(" , \\. ", " \\. ") .replaceAll(" and \\. ", " \\. ").replaceAll(" , \\? ", " \\? ").replaceAll(" and \\? ", " \\? ") .replaceAll(" ,\\. ", " \\. ").replaceAll(" and\\. ", " \\. ").replaceAll(" ,\\? ", " \\? ") .replaceAll(" and\\? ", " \\? ").trim(); /*for (String comp : sillyCompositeWordsInData.keySet()) { predictedWordSequence = predictedWordSequence.replaceAll(comp, sillyCompositeWordsInData.get(comp)); }*/ if (predictedWordSequence.startsWith(",") || predictedWordSequence.startsWith(".") || predictedWordSequence.startsWith("?")) { predictedWordSequence = predictedWordSequence.substring(1).trim(); } if (predictedWordSequence.startsWith(",")) { System.out.println(wordSequence); System.out.println(matched); } return predictedWordSequence; }