auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean canFlipToNextPage() { List<String> tracesToScan = new ArrayList<String>(); for (TreeItem traceFamily : treeView.getItems()) { for (TreeItem traceType : traceFamily.getItems()) { if (traceType.getChecked()) { tracesToScan.add(traceType.getText()); } } } ((BatchImportTraceWizard) getWizard()).setTracesToScan(tracesToScan); if( tracesToScan.isEmpty()){ <START> setErrorMessage("Please Select at least one trace type"); <END> } else{ setErrorMessage(null); } return super.canFlipToNextPage() && !tracesToScan.isEmpty(); }</code><technical_language>externalized string</technical_language>

Target:
public boolean canFlipToNextPage() { List<String> tracesToScan = new ArrayList<String>(); String elements[] = (String[]) fProvider.getElements(null); for (String traceFamily : elements) { final String[] children = (String[]) fProvider.getChildren(traceFamily); if (children != null) { for (String traceType : children) { if (fTreeView.getChecked(traceType)) { tracesToScan.add(traceType); } } } } ((BatchImportTraceWizard) getWizard()).setTraceTypesToScan(tracesToScan); if (tracesToScan.isEmpty()) { setErrorMessage(Messages.ImportTraceWizardPageSelectTraceType_2); } else { setErrorMessage(null); } return super.canFlipToNextPage() && !tracesToScan.isEmpty(); }
Source:
<code>public SendEventBatchPartitionTest(EventHubsPerfStressOptions options) throws Exception { super(options); partitionSender = eventHubClient.createPartitionSender(String.valueOf(options.getPartitionId())).get(); BatchOptions batchOptions = new BatchOptions(); if (options.getBatchSize() != null) { batchOptions.maxMessageSize = options.getBatchSize(); } if (options.getPartitionKey() != null) { batchOptions.partitionKey = options.getPartitionKey(); } eventDataBatch = partitionSender.createBatch(batchOptions); for (int i = 0; i < options.getEvents(); i++) { <START> if (!eventDataBatch.tryAdd(EventData.create("Static Event".getBytes(StandardCharsets.UTF_8)))) { <END> throw new Exception(String.format("Batch can only fit %d number of messages with batch size of %d ", options.getCount(), options.getSize())); } } }</code><technical_language>creation of event data done once</technical_language>

Target:
public SendEventBatchPartitionTest(EventHubsPerfStressOptions options) throws Exception { super(options); batchOptions = new BatchOptions(); BatchOptions batchOptions = new BatchOptions(); if (options.getBatchSize() != null) { batchOptions.maxMessageSize = options.getBatchSize(); } if (options.getPartitionKey() != null) { batchOptions.partitionKey = options.getPartitionKey(); } }
Source:
<code>protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitShortVarDeclaration(@NotNull GoShortVarDeclaration o) { super.visitShortVarDeclaration(o); visitVarDefinitionList(o, o.getVarDefinitionList()); } @Override public void visitRecvStatement(@NotNull GoRecvStatement o) { super.visitRecvStatement(o); visitVarDefinitionList(o, o.getVarDefinitionList()); } @Override public void visitRangeClause(@NotNull GoRangeClause o) { <START> super.visitRangeClause(o); <END> visitVarDefinitionList(o, o.getVarDefinitionList()); } private void visitVarDefinitionList(@NotNull PsiElement o, @NotNull List<GoVarDefinition> list) { GoVarDefinition first = ContainerUtil.getFirstItem(list); GoVarDefinition last = ContainerUtil.getLastItem(list); if (first == null || last == null) return; if (hasNonNewVariables(list)) { TextRange textRange = TextRange.create(first.getStartOffsetInParent(), last.getStartOffsetInParent() + last.getTextLength()); holder.registerProblem(o, textRange, "No new variables on left side of :=", new MyLocalQuickFixBase()); } } }; }</code><technical_language>easier invoke checkCanceld in visitVarDefinitionList remove supers</technical_language>

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitShortVarDeclaration(@NotNull GoShortVarDeclaration o) { visitVarDefinitionList(o, o.getVarDefinitionList()); } @Override public void visitRecvStatement(@NotNull GoRecvStatement o) { visitVarDefinitionList(o, o.getVarDefinitionList()); } @Override public void visitRangeClause(@NotNull GoRangeClause o) { visitVarDefinitionList(o, o.getVarDefinitionList()); } private void visitVarDefinitionList(@NotNull PsiElement o, @NotNull List<GoVarDefinition> list) { ProgressManager.checkCanceled(); GoVarDefinition first = ContainerUtil.getFirstItem(list); GoVarDefinition last = ContainerUtil.getLastItem(list); if (first == null || last == null) return; if (hasNonNewVariables(list)) { TextRange textRange = TextRange.create(first.getStartOffsetInParent(), last.getStartOffsetInParent() + last.getTextLength()); holder.registerProblem(o, textRange, "No new variables on left side of :=", new MyLocalQuickFixBase()); } } }; }
Source:
<code>public CompletableFuture<Void> truncateTable(TableName tableName, boolean preserveSplits) { return CompletableFuture.supplyAsync(() -> { <START> DropRowRangeRequest.Builder dropBuilder = DropRowRangeRequest.newBuilder().setDeleteAllDataFromTable(true); <END> dropBuilder.setName(bigtableInstanceName.toTableNameStr(tableName.getNameAsString())); return dropBuilder; }).thenCompose( d -> FutureUtils.toCompletableFuture(bigtableTableAdminClient.dropRowRangeAsync(d.build()))) .thenApply(r -> null); }</code><technical_language>I create a DropRowRangeRequest of CompletableFuture, return: FutureUtils.toCompletableFuture(bigtableTableAdminClient.dropRowRangeAsync(request)) .thenApply(r -> null);</technical_language>

Target:
public CompletableFuture<Void> truncateTable(TableName tableName, boolean preserveSplits) { if (!preserveSplits) { LOG.info("truncate will preserveSplits. The passed in variable is ignored."); } DropRowRangeRequest.Builder deleteRequest = DropRowRangeRequest.newBuilder().setDeleteAllDataFromTable(true); return FutureUtils.toCompletableFuture( bigtableTableAdminClient.dropRowRangeAsync(deleteRequest.setName(bigtableInstanceName.toTableNameStr(tableName.getNameAsString())).build())) .thenApply(r -> null); }
Source:
<code>public Block copyPositions(List<Integer> positions) { int[] newOffsets = new int[positions.size() + 1]; boolean[] newRowIsNull = new boolean[positions.size()]; List<Integer> columnBlockPositions = new ArrayList<>(positions.size()); int newPosition = 0; <START> for (int position : positions) { <END> if (isNull(position)) { newRowIsNull[newPosition] = true; newOffsets[newPosition + 1] = newOffsets[newPosition]; } else { newOffsets[newPosition + 1] = newOffsets[newPosition] + 1; columnBlockPositions.add(getColumnBlockOffset(position)); } newPosition++; } Block[] newColumnBlocks = new Block[numColumns]; for (int i = 0; i < numColumns; i++) { newColumnBlocks[i] = getColumnBlock(i).copyPositions(columnBlockPositions); } return new RowBlock(0, positions.size(), newRowIsNull, newOffsets, newColumnBlocks); }</code><technical_language>Write this a for-i loop. for (int i = 0; i < newPositionCount; i++) { int position = positions.get(i); ... }</technical_language>

Target:
public Block copyPositions(List<Integer> positions) { int newPositionCount = positions.size(); int[] newOffsets = new int[newPositionCount + 1]; boolean[] newRowIsNull = new boolean[newPositionCount]; List<Integer> fieldBlockPositions = new ArrayList<>(newPositionCount); for (int i = 0; i < newPositionCount; i++) { int position = positions.get(i); if (isNull(position)) { newRowIsNull[i] = true; newOffsets[i + 1] = newOffsets[i]; } else { newOffsets[i + 1] = newOffsets[i] + 1; fieldBlockPositions.add(getFieldBlockOffset(position)); } } Block[] newBlocks = new Block[numFields]; for (int i = 0; i < numFields; i++) { newBlocks[i] = getFieldBlocks()[i].copyPositions(fieldBlockPositions); } return new RowBlock(0, positions.size(), newRowIsNull, newOffsets, newBlocks); }
Source:
<code>protected static PrivateKey getPrivateKeyFromFile(String filename) throws Exception { byte[] keyBytes = Files.readAllBytes(new File(filename).toPath()); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); <START> KeyFactory kf = KeyFactory.getInstance("RSA"); <END> return kf.generatePrivate(spec); }</code><technical_language>cipher suite configurable</technical_language>

Target:
private static PrivateKey getPrivateKeyFromFile(String filename) throws Exception { byte[] keyBytes = Files.readAllBytes(new File(filename).toPath()); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance(algorithm); return kf.generatePrivate(spec); }
Source:
<code>default AbstractPlanNode inputRelNodeToPlanNode(RelNode node, int childOrdinal) { VoltDBPRel inputNode = getInputNode(node, childOrdinal); <START> assert (inputNode != null); <END> return inputNode.toPlanNode(); }</code><technical_language>Objects.requireNotNull()</technical_language>

Target:
default AbstractPlanNode inputRelNodeToPlanNode(RelNode node, int childOrdinal) { VoltDBPRel inputNode = getInputNode(node, childOrdinal); Objects.requireNonNull(inputNode); return inputNode.toPlanNode(); }
Source:
<code><START> public synchronized void stop() { <END> if (state == State.STARTING || state == State.RUNNING) { setState(State.STOPPING); watcherThread.interrupt(); } }</code><technical_language>I some improvement done here.Is required define method synchronised.Can ReentrantReadWriteLock get write lock here? resulted in performance improvement</technical_language>

Target:
public void stop() { if (compareAndSetState( new State[]{State.RUNNING, State.STARTING}, State.STOPPING)) { watcherThread.interrupt(); } }
Source:
<code>protected List<LUNs> getLUNsFromVgInfo(String vgId) { List<LUNs> luns = new ArrayList<>(); VDSReturnValue returnValue; try { returnValue = runVdsCommand(VDSCommandType.GetVGInfo, new GetVGInfoVDSCommandParameters(getParameters().getVdsId(), vgId)); } catch (RuntimeException e) { <START> log.error("Could not get info for VG ID '{}'. Error message: {}", <END> vgId, e.getMessage()); return luns; } luns.addAll((ArrayList<LUNs>) returnValue.getReturnValue()); return luns; }</code><technical_language>s/. Error message//</technical_language>

Target:
protected List<LUNs> getLUNsFromVgInfo(String vgId) { List<LUNs> luns = new ArrayList<>(); VDSReturnValue returnValue; try { returnValue = runVdsCommand(VDSCommandType.GetVGInfo, new GetVGInfoVDSCommandParameters(getParameters().getVdsId(), vgId)); } catch (RuntimeException e) { log.error("Could not get info for VG ID '{}': {}", vgId, e.getMessage()); log.debug("Exception", e); return luns; } luns.addAll((ArrayList<LUNs>) returnValue.getReturnValue()); return luns; }
Source:
<code>private void handleAck(long deliveryTag, boolean channelLocallyTransacted) throws IOException { boolean isLocallyTransacted = channelLocallyTransacted || (isChannelTransacted() && TransactionSynchronizationManager.getResource(this.connectionFactory) == null); try { if (this.ackRequired) { <START> if (this.messagesPerAck > 0) { <END> synchronized (this) { this.deliveryTag = deliveryTag; this.pendingAcks++; this.lastDeliveryComplete = System.currentTimeMillis(); ackIfNecessary(this.lastDeliveryComplete); } } else if (!isChannelTransacted() || isLocallyTransacted) { getChannel().basicAck(deliveryTag, false); } } if (isLocallyTransacted) { RabbitUtils.commitIfNecessary(getChannel()); } } catch (Exception e) { this.logger.error("Error acking", e); } }</code><technical_language>I this > 1 well. Literally default 0 is fully equal 1 - perform basicAck() message</technical_language>

Target:
private void handleAck(long deliveryTag, boolean channelLocallyTransacted) throws IOException { boolean isLocallyTransacted = channelLocallyTransacted || (isChannelTransacted() && TransactionSynchronizationManager.getResource(this.connectionFactory) == null); try { if (this.ackRequired) { if (this.messagesPerAck > 1) { synchronized (this) { this.deliveryTag = deliveryTag; this.pendingAcks++; this.lastDeliveryComplete = System.currentTimeMillis(); ackIfNecessary(this.lastDeliveryComplete); } } else if (!isChannelTransacted() || isLocallyTransacted) { getChannel().basicAck(deliveryTag, false); } } if (isLocallyTransacted) { RabbitUtils.commitIfNecessary(getChannel()); } } catch (Exception e) { this.logger.error("Error acking", e); } }
Source:
<code>@Override public void cancel(String name) { A.notNull(name, "name"); if (log.isInfoEnabled()) log.info("Canceling service[name=" + name + ']'); boolean res; try { IgniteClusterImpl cluster = ctx.cluster().get(); IgniteCompute compute = cluster.compute(); ClusterNode srv = U.randomServerNode(ctx); <START> res = compute.execute(new VisorCancelServiceTask(), <END> new VisorTaskArgument<>(srv.id(), new VisorCancelServiceTaskArg(name), false)); } catch (Exception e) { throw new RuntimeException(e); } if (!res) throw new RuntimeException("Service not found or can't be canceled[name=" + name + ']'); }</code><technical_language>run this task current node</technical_language>

Target:
@Override public void cancel(String name) { A.notNull(name, "name"); if (log.isInfoEnabled()) log.info("Canceling service[name=" + name + ']'); try { IgniteClusterImpl cluster = ctx.cluster().get(); IgniteCompute compute = cluster.compute(); boolean res = compute.execute(new VisorCancelServiceTask(), new VisorTaskArgument<>(ctx.localNodeId(), new VisorCancelServiceTaskArg(name), false)); if (!res) throw new RuntimeException("Service not found or can't be canceled[name=" + name + ']'); } catch (IgniteException e) { throw new RuntimeException(e); } }
Source:
<code>private void addMasterJulLogRecords(Container result) { result.add(new LogRecordContent("nodes/master/logs/all_memory_buffer.log") { @Override public Iterable<LogRecord> getLogRecords() { return SupportPlugin.getInstance().getAllLogRecords(); } }); final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { LOGGER.log(Level.WARNING, "Cannot add master logs to the bundle. Jenkins instance is not ready"); return; } final File[] logFiles = jenkins.getRootDir().listFiles(ROTATED_LOGFILE_FILTER); if (logFiles == null) { LOGGER.log(Level.WARNING, "Cannot add master logs to the bundle. Cannot access log files"); return; } <START> for (File file : logFiles){ <END> result.add(new FileContent("nodes/master/logs/" + file.getName(), file)); } }</code><technical_language>bug: this appears changing implementation incorrect for apparent reason. I want java for (File file : ArrayUtil.fromList(SupportPlugin.getRootDirectory().listFiles(new LogFilenameFilter())) {</technical_language>

Target:
private void addMasterJulLogRecords(Container result) { result.add(new LogRecordContent("nodes/master/logs/all_memory_buffer.log") { @Override public Iterable<LogRecord> getLogRecords() { return SupportPlugin.getInstance().getAllLogRecords(); } }); final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { LOGGER.log(Level.WARNING, "Cannot add master logs to the bundle. Jenkins instance is not ready"); return; } final File[] julLogFiles = SupportPlugin.getRootDirectory().listFiles(new LogFilenameFilter()); if (julLogFiles == null) { LOGGER.log(Level.WARNING, "Cannot add master java.util.logging logs to the bundle. Cannot access log files"); return; } for (File file : julLogFiles){ result.add(new FileContent("nodes/master/logs/" + file.getName(), file)); } }
Source:
<code>public void onLifespanFinished(Iterable<Lifespan> newlyCompletedDriverGroups) { checkState(initialScheduled); <START> SettableFuture<?> newDriverGroupReady = this.newDriverGroupReady; <END> synchronized (this) { for (Lifespan newlyCompletedDriverGroup : newlyCompletedDriverGroups) { checkArgument(!newlyCompletedDriverGroup.isTaskWide()); recentlyCompletedDriverGroups.add(newlyCompletedDriverGroup); } } newDriverGroupReady.set(null); }</code><technical_language>pretty setting of this local variable happen synchronized block, location set happening (not state machine), otherwise, observe stale value. Also, merge this change commit creates classes</technical_language>

Target:
public void onLifespanFinished(Iterable<Lifespan> newlyCompletedDriverGroups) { checkState(initialScheduled); SettableFuture<?> newDriverGroupReady; synchronized (this) { for (Lifespan newlyCompletedDriverGroup : newlyCompletedDriverGroups) { checkArgument(!newlyCompletedDriverGroup.isTaskWide()); recentlyCompletedDriverGroups.add(newlyCompletedDriverGroup); } newDriverGroupReady = this.newDriverGroupReady; } newDriverGroupReady.set(null); }
Source:
<code>public MessageTemplate() { super(); <START> } <END></code><technical_language>constructors another</technical_language>

Target:
public MessageTemplate() { tags = new ArrayList<>(); }
Source:
<code>public ImmutableList<Double> initialGuesses(MarketData marketData) { ImmutableList.Builder<Double> result = ImmutableList.builder(); for (CurveDefinition defn : curveDefinitions) { <START> if (defn instanceof ParameterizedFunctionalCurveDefinition) { <END> ParameterizedFunctionalCurveDefinition casted = (ParameterizedFunctionalCurveDefinition) defn; result.addAll(casted.getInitialGuess().toList().iterator()); } else { ValueType valueType = defn.getYValueType(); for (CurveNode node : defn.getNodes()) { result.add(node.initialGuess(marketData, valueType)); } } } return result.build(); }</code><technical_language>A method initialGuess(MarketData marketData) created in CurveDefinition. For ParameterizedFunctionalCurveDefinition implemented; for other return array resulting loop nodes. cast necessary anymore</technical_language>

Target:
public ImmutableList<Double> initialGuesses(MarketData marketData) { ImmutableList.Builder<Double> result = ImmutableList.builder(); for (CurveDefinition defn : curveDefinitions) { result.addAll(defn.initialGuess(marketData)); } return result.build(); }
Source:
<code>public List<PTCreditNote> findByReferencedDocument(UID uidCompany, UID uidInvoice) { <START> JPAGenericInvoiceEntity invoice = this.queryInvoice().uid.eq(uidInvoice.toString()).findOne(); <END> List<JPAPTCreditNoteEntryEntity> referencingEntries = this.queryCreditNoteEntry().reference.equalTo((JPAPTInvoiceEntity) invoice).findList(); List<Integer> referencingEntryIDs = new ArrayList<>(); for (JPAPTCreditNoteEntryEntity referencingEntry : referencingEntries) { referencingEntryIDs.add(referencingEntry.getID()); } List<JPAGenericInvoiceEntity> referencingDocuments = this.queryInvoice().business.uid.eq(uidCompany.toString()).entries .filterMany(this.queryGenericInvoiceEntry().setIdIn(referencingEntryIDs).getExpressionList()) .findList(); List<PTCreditNote> referencingCreditNotes = new ArrayList<>(); for (JPAGenericInvoiceEntity referencingInvoice : referencingDocuments) { if (referencingInvoice instanceof JPAPTCreditNoteEntity) { referencingCreditNotes.add((JPAPTCreditNoteEntity) referencingInvoice); } } return referencingCreditNotes; }</code><technical_language>need aware of nulls here</technical_language>

Target:
public List<PTCreditNote> findByReferencedDocument(UID uidCompany, UID uidInvoice) { JPAGenericInvoiceEntity invoice = this.queryInvoice().uid.eq(uidInvoice.toString()).findOne(); if (invoice == null) { return new ArrayList<>(); } List<JPAPTCreditNoteEntryEntity> referencingEntries = this.queryCreditNoteEntry().reference.equalTo((JPAPTInvoiceEntity) invoice).findList(); List<Integer> referencingEntryIDs = new ArrayList<>(); for (JPAPTCreditNoteEntryEntity referencingEntry : referencingEntries) { referencingEntryIDs.add(referencingEntry.getID()); } List<JPAGenericInvoiceEntity> referencingDocuments = this.queryInvoice().business.uid.eq(uidCompany.toString()).entries .filterMany(this.queryGenericInvoiceEntry().setIdIn(referencingEntryIDs).getExpressionList()) .findList(); List<PTCreditNote> referencingCreditNotes = new ArrayList<>(); for (JPAGenericInvoiceEntity referencingInvoice : referencingDocuments) { if (referencingInvoice instanceof JPAPTCreditNoteEntity) { referencingCreditNotes.add((JPAPTCreditNoteEntity) referencingInvoice); } } return referencingCreditNotes; }
Source:
<code>private void addPluginActionButtons(List<ActionButtonDefinition<?>> pluginActionButtonList) { if (hasActionPanelPresenterWidget()) { for(ActionButtonDefinition<?> buttonDef: pluginActionButtonList) { getActionPanelPresenterWidget().addActionButton((ActionButtonDefinition) buttonDef, <START> (int) buttonDef.getPriority()); <END> } } }</code><technical_language>This effectively limits action button priority integers, is this want</technical_language>

Target:
private void addPluginActionButtons(List<ActionButtonDefinition<?>> pluginActionButtonList) { if (hasActionPanelPresenterWidget()) { for(ActionButtonDefinition<?> buttonDef: pluginActionButtonList) { getActionPanelPresenterWidget().addActionButton((ActionButtonDefinition) buttonDef); } } }
Source:
<code>private SSLConnectionSocketFactory createSslConnectionSocketFactory() { SSLConnectionSocketFactory sslConnFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), <START> new String[] {"TLSv1.2"}, null, <END> SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sslConnFactory; }</code><technical_language>"TLSv1.2" extracted a class-level constant. Also, please rename rest of constants, of uppercase letters. Thank you</technical_language>

Target:
private SSLConnectionSocketFactory createSslConnectionSocketFactory() { SSLConnectionSocketFactory sslConnFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), new String[] {TLS_V1_2}, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sslConnFactory; }
Source:
<code>public Registration updateRegistration(RegistrationUpdate update) { try (Jedis j = pool.getResource()) { byte[] ep = j.get(toRegIdKey(update.getRegistrationId())); if (ep == null) { return null; } byte[] data = j.get(toEndpointKey(ep)); if (data == null) { return null; } Registration r = deserializeReg(data); byte[] lockValue = null; byte[] lockKey = toLockKey(r.getEndpoint()); try { lockValue = RedisLock.acquire(j, lockKey); Registration clientUpdated = update.updateClient(r); <START> j.set(toEndpointKey(clientUpdated.getEndpoint()), serializeReg(clientUpdated)); <END> return clientUpdated; } finally { RedisLock.release(j, lockKey, lockValue); } } }</code><technical_language>clientUpdated</technical_language>

Target:
public Registration updateRegistration(RegistrationUpdate update) { try (Jedis j = pool.getResource()) { byte[] ep = j.get(toRegIdKey(update.getRegistrationId())); if (ep == null) { return null; } byte[] data = j.get(toEndpointKey(ep)); if (data == null) { return null; } Registration r = deserializeReg(data); byte[] lockValue = null; byte[] lockKey = toLockKey(r.getEndpoint()); try { lockValue = RedisLock.acquire(j, lockKey); Registration updatedRegistration = update.update(r); j.set(toEndpointKey(updatedRegistration.getEndpoint()), serializeReg(updatedRegistration)); return updatedRegistration; } finally { RedisLock.release(j, lockKey, lockValue); } } }
Source:
<code>@Override public void cacheMaxSize(int maxSize) { <START> for (EventListener listener : eventListeners) { <END> listener.cacheMaxSize(maxSize); } }</code><technical_language>indexed loop for of avoid allocating iterator</technical_language>

Target:
void cacheMaxSize(int maxSize) { int numListeners = eventListeners.size(); for (int i = 0; i < numListeners; i++) { EventListener listener = eventListeners.get(i); listener.cacheMaxSize(maxSize); } }
Source:
<code>final void initComponents() { enableOSXFullscreen(this); setLayout(new BorderLayout()); setResizable(true); setIconImage(ImageUtility.readSystemImage("chess_logo")); setJMenuBar(ChessActions.createJMenuBar()); setPreferredSize(new Dimension(685, 450)); InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "close"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.SHIFT_DOWN_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "fullscreen"); ActionMap actionMap = getRootPane().getActionMap(); actionMap.put("close", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { onWindowCloseKeyboardRequest(); } }); actionMap.put("fullscreen", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { } }); <START> setPreferredSize(new Dimension(685, 450)); <END> setMinimumSize(new Dimension(685, 450)); this.addComponentListener(new ComponentAdapter(){ public void componentResized(ComponentEvent e){ Dimension d = getSize(); Dimension minD = getMinimumSize(); if(d.width<minD.width) d.width=minD.width; if(d.height<minD.height) d.height=minD.height; setSize(d); } }); doInitComponents(); }</code><technical_language>add this stuff ChessFrame child frame size</technical_language>

Target:
final void initComponents() { enableOSXFullscreen(this); setLayout(new BorderLayout()); setResizable(true); setIconImage(ImageUtility.readSystemImage("chess_logo")); setJMenuBar(ChessActions.createJMenuBar()); setPreferredSize(new Dimension(685, 450)); InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "close"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.SHIFT_DOWN_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "fullscreen"); ActionMap actionMap = getRootPane().getActionMap(); actionMap.put("close", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { onWindowCloseKeyboardRequest(); } }); actionMap.put("fullscreen", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { } }); doInitComponents(); }
Source:
<code>public List<ProjectBuildingResult> build( List<File> pomFiles, boolean recursive, ProjectBuildingRequest request ) throws ProjectBuildingException { List<ProjectBuildingResult> results = new ArrayList<>(); List<InterimResult> interimResults = new ArrayList<>(); ReactorModelPool.Builder poolBuilder = new ReactorModelPool.Builder(); ReactorModelPool modelPool = poolBuilder.build(); InternalConfig config = new InternalConfig( request, modelPool, useGlobalModelCache() ? getModelCache() : new ReactorModelCache() ); Map<String, MavenProject> projectIndex = new HashMap<>( 256 ); boolean noErrors = build( results, interimResults, projectIndex, pomFiles, new LinkedHashSet<>(), true, recursive, <START> config, poolBuilder ); <END> ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); try { noErrors = build( results, new ArrayList<>(), projectIndex, interimResults, request, new HashMap<>(), config.session ) && noErrors; } finally { Thread.currentThread().setContextClassLoader( oldContextClassLoader ); } if ( !noErrors ) { throw new ProjectBuildingException( results ); } return results; }</code><technical_language>do pass reuse builder? I feeling misusing a build a caching factory</technical_language>

Target:
public List<ProjectBuildingResult> build( List<File> pomFiles, boolean recursive, ProjectBuildingRequest request ) throws ProjectBuildingException { List<ProjectBuildingResult> results = new ArrayList<>(); List<InterimResult> interimResults = new ArrayList<>(); ReactorModelPool.Builder poolBuilder = new ReactorModelPool.Builder(); final ReactorModelPool modelPool = poolBuilder.build(); if ( Features.buildConsumer().isActive() ) { final TransformerContext context = new TransformerContext() { @Override public String getUserProperty( String key ) { return request.getUserProperties().getProperty( key ); } @Override public Model getRawModel( Path p ) { return modelPool.get( p ); } @Override public Model getRawModel( String groupId, String artifactId ) { return modelPool.get( groupId, artifactId, null ); } }; request.getRepositorySession().getData().set( TransformerContext.KEY, context ); } InternalConfig config = new InternalConfig( request, modelPool, useGlobalModelCache() ? getModelCache() : new ReactorModelCache() ); Map<String, MavenProject> projectIndex = new HashMap<>( 256 ); boolean noErrors = build( results, interimResults, projectIndex, pomFiles, new LinkedHashSet<>(), true, recursive, config, poolBuilder ); ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); try { noErrors = build( results, new ArrayList<>(), projectIndex, interimResults, request, new HashMap<>(), config.session ) && noErrors; } finally { Thread.currentThread().setContextClassLoader( oldContextClassLoader ); } if ( !noErrors ) { throw new ProjectBuildingException( results ); } return results; }
Source:
<code><START> public void connect(Context context, LostApiClient.ConnectionCallbacks callbacks) { <END> this.context = context; Intent intent = new Intent(context, FusedLocationProviderService.class); context.startService(intent); if (callbacks != null) { connectionCallbacks.add(callbacks); } intent = new Intent(context, FusedLocationProviderService.class); context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); }</code><technical_language>connect is called update connectState ConnectState.CONNECTING</technical_language>

Target:
public void connect(Context context, LostApiClient.ConnectionCallbacks callbacks) { if (connectState == ConnectState.IDLE) { this.context = context; connectState = ConnectState.CONNECTING; Intent intent = new Intent(context, FusedLocationProviderService.class); context.startService(intent); intent = new Intent(context, FusedLocationProviderService.class); context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); } if (callbacks != null) { connectionCallbacks.add(callbacks); } }
Source:
<code>public void updateTableStatistics(String databaseName, String tableName, Function<PartitionStatistics, PartitionStatistics> update) { PartitionStatistics currentStatistics = getTableStatistics(databaseName, tableName); PartitionStatistics updatedStatistics = update.apply(currentStatistics); if (!updatedStatistics.getColumnStatistics().isEmpty()) { <START> throw new PrestoException(NOT_SUPPORTED, "glue metastore does not support column level statistics"); <END> } Table table = getTableOrElseThrow(databaseName, tableName); try { TableInput tableInput = GlueInputConverter.convertTable(table); tableInput.setParameters(updateStatisticParameters(table.getParameters(), updatedStatistics.getBasicStatistics())); glueClient.updateTable(new UpdateTableRequest() .withDatabaseName(databaseName) .withTableInput(tableInput)); } catch (EntityNotFoundException e) { throw new TableNotFoundException(new SchemaTableName(databaseName, tableName)); } catch (AmazonServiceException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }</code><technical_language>Nit: capitalize "Glue"</technical_language>

Target:
public void updateTableStatistics(String databaseName, String tableName, Function<PartitionStatistics, PartitionStatistics> update) { PartitionStatistics currentStatistics = getTableStatistics(databaseName, tableName); PartitionStatistics updatedStatistics = update.apply(currentStatistics); if (!updatedStatistics.getColumnStatistics().isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "Glue metastore does not support column level statistics"); } Table table = getTableOrElseThrow(databaseName, tableName); try { TableInput tableInput = GlueInputConverter.convertTable(table); tableInput.setParameters(updateStatisticsParameters(table.getParameters(), updatedStatistics.getBasicStatistics())); glueClient.updateTable(new UpdateTableRequest() .withDatabaseName(databaseName) .withTableInput(tableInput)); } catch (EntityNotFoundException e) { throw new TableNotFoundException(new SchemaTableName(databaseName, tableName)); } catch (AmazonServiceException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }
Source:
<code>public void shouldFailOnMultipleConcurrentSaves() throws Exception { final String key = "shouldFailOnMultipleConcurrentSaves"; final AtomicLong counter = new AtomicLong(); final AtomicLong optimisticLockCounter = new AtomicLong(); ExecutorService pool = Executors.newFixedThreadPool(5); Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { long counterValue = counter.incrementAndGet(); String data = "value-" + counterValue; VersionedData messageData = new VersionedData(key, data); try { versionedDataRepository.save(messageData); } catch (OptimisticLockingFailureException e) { optimisticLockCounter.incrementAndGet(); } return null; } }; Collection<Callable<Void>> tasks = Collections.nCopies(5, task); List<Future<Void>> futures = pool.invokeAll(tasks); for (Future future : futures) { future.get(5, TimeUnit.SECONDS); } <START> versionedDataRepository.delete(key); <END> assertEquals(4, optimisticLockCounter.intValue()); }</code><technical_language>delete beginning of test? test cases (one a pre-existing version of doc exists => update, other is deleteIfExist => insert)</technical_language>

Target:
public void shouldFailOnMultipleConcurrentSaves() throws Exception { final String key = testName.getMethodName(); remove(key); final AtomicLong counter = new AtomicLong(); final AtomicLong optimisticLockCounter = new AtomicLong(); Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { long counterValue = counter.incrementAndGet(); VersionedData messageData = new VersionedData(key, "value-" + counterValue); try { versionedDataRepository.save(messageData); } catch (OptimisticLockingFailureException e) { optimisticLockCounter.incrementAndGet(); } return null; } }; AsyncUtils.executeConcurrently(5, task); assertEquals(4, optimisticLockCounter.intValue()); }
Source:
<code>public byte[] readFileToByteArray(File file) throws IOException { InputStream in = null; try { in = org.apache.commons.io.FileUtils.openInputStream(file); return org.apache.commons.io.IOUtils.toByteArray(in); } finally { org.apache.commons.io.IOUtils.closeQuietly(in); <START> } <END> }</code><technical_language>closeQuietly is nonsense, do it. Simpler write: InputStream in = org.apache.commons.io.FileUtils.openInputStream(file); try { return org.apache.commons.io.IOUtils.toByteArray(in); } finally { in.close(); } -source 7 simplified try (InputStream in = org.apache.commons.io.FileUtils.openInputStream(file)) { return org.apache.commons.io.IOUtils.toByteArray(in); }</technical_language>

Target:
public byte[] readFileToByteArray(File file) throws IOException { InputStream in = org.apache.commons.io.FileUtils.openInputStream(file); try { return org.apache.commons.io.IOUtils.toByteArray(in); } finally { in.close(); } }
Source:
<code>private static String checkName(String origName) { String newName = BaseNoGui.sanitizeName(origName); if (!newName.equals(origName)) { String msg = tr("The sketch name had to be modified. Sketch names can only consist of\n" + <START> "ASCII characters and numbers, no spaces, and be less than 64 characters long."); <END> System.out.println(msg); } return newName; }</code><technical_language>Is this correct? ASCII characters include 128 defined ASCII characters, actual limits smaller: <LINK_0> this message spell out requirements exactly: A letter number, letters, numbers, dashes, dots underscores (underscores listed in whitelist, else is replaced underscore, making underscore implicitly allowed). Maximum length is 63 characters</technical_language>

Target:
private static String checkName(String origName) { String newName = BaseNoGui.sanitizeName(origName); if (!newName.equals(origName)) { String msg = tr("The sketch name had to be modified.\n" + "Sketch names must start with a letter or number, followed by letters,\n" + "numbers, dashes, dots and underscores. Maximum length is 63 characters."); System.out.println(msg); } return newName; }
Source:
<code><START> public void onMatchmakerSearchStopped() { if (inMatchmakerQueue.get()) { fafService.stopSearchMatchmaker(); inMatchmakerQueue.set(false); } } <END></code><technical_language>I suggest debug logging of cases</technical_language>

Target:
public void onMatchmakerSearchStopped() { if (inMatchmakerQueue.get()) { fafService.stopSearchMatchmaker(); inMatchmakerQueue.set(false); log.debug("Matchmaker search stopped"); } else { log.debug("Matchmaker search has already been stopped, ignoring call"); } }
Source:
<code>public void testLockedStreamBlocked() throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException { for (int i = 0; i < 10; i++) { cache.put(i, "value" + i); } CyclicBarrier barrier = new CyclicBarrier(2); int key = 4; Future<Object> putFuture = fork(() -> { TransactionManager tm = cache.getAdvancedCache().getTransactionManager(); try { tm.begin(); try { Object prev = cache.put(key, "value" + key + "-new"); barrier.await(10, TimeUnit.SECONDS); barrier.await(10, TimeUnit.SECONDS); tm.commit(); return prev; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) { tm.rollback(); } } } catch (NotSupportedException | SystemException e) { throw new RuntimeException(e); } }); barrier.await(10, TimeUnit.SECONDS); LockedStream<Object, Object> stream = cache.getAdvancedCache().lockedStream(); Future<?> forEachFuture = fork(() -> stream.filter(e -> e.getKey().equals(key)).forEach((c, e) -> assertEquals("value" + key + "-new", c.put(e.getKey(), String.valueOf(e.getValue() + "-other"))))); <START> try { <END> forEachFuture.get(50, TimeUnit.MILLISECONDS); fail("Test should have thrown TimeoutException"); } catch (TimeoutException e) { } barrier.await(10, TimeUnit.SECONDS); forEachFuture.get(10, TimeUnit.MINUTES); assertEquals("value" + key, putFuture.get(10, TimeUnit.SECONDS)); assertEquals("value" + key + "-new-other", cache.get(key)); LockManager lockManager = cache.getAdvancedCache().getComponentRegistry().getComponent(LockManager.class); assertEquals(0, lockManager.getNumberOfLocksHeld()); }</code><technical_language>expectException</technical_language>

Target:
public void testLockedStreamBlocked() throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException { for (int i = 0; i < 10; i++) { cache.put(i, "value" + i); } CyclicBarrier barrier = new CyclicBarrier(2); int key = 4; Future<Object> putFuture = fork(() -> TestingUtil.withTx(cache.getAdvancedCache().getTransactionManager(), () -> { Object prev = cache.put(key, "value" + key + "-new"); barrier.await(10, TimeUnit.SECONDS); barrier.await(10, TimeUnit.SECONDS); return prev; })); barrier.await(10, TimeUnit.SECONDS); LockedStream<Object, Object> stream = cache.getAdvancedCache().lockedStream(); Future<?> forEachFuture = fork(() -> stream.filter(e -> e.getKey().equals(key)).forEach((c, e) -> assertEquals("value" + key + "-new", c.put(e.getKey(), String.valueOf(e.getValue() + "-other"))))); Exceptions.expectException(TimeoutException.class, () -> forEachFuture.get(50, TimeUnit.MILLISECONDS)); barrier.await(10, TimeUnit.SECONDS); forEachFuture.get(10, TimeUnit.MINUTES); assertEquals("value" + key, putFuture.get(10, TimeUnit.SECONDS)); assertEquals("value" + key + "-new-other", cache.get(key)); LockManager lockManager = cache.getAdvancedCache().getComponentRegistry().getComponent(LockManager.class); assertEquals(0, lockManager.getNumberOfLocksHeld()); }
Source:
<code>private void createListOfClustersByProvider(List<Cluster> clusters) { listOfClustersByProvider = new HashMap<>(); clusters.stream() .map(Cluster::getDefaultNetworkProviderId) .distinct() <START> .forEach(providerId <END> -> listOfClustersByProvider.put(providerId, getClusterIdsFilteredByProviderId(clusters, providerId))); }</code><technical_language>'Collectors.toMap'</technical_language>

Target:
private void createListOfClustersByProvider(List<Cluster> clusters) { listOfClustersByProvider = clusters.stream() .map(Cluster::getDefaultNetworkProviderId) .distinct() .collect(Collectors.toMap(providerId -> providerId, providerId -> getClusterIdsFilteredByProviderId(clusters, providerId))); }
Source:
<code>public void testIsSymlink_onWindows_junction() throws Exception { Assume.assumeTrue(Functions.isWindows()); tmp.newFolder("targetDir"); File d = tmp.newFolder("dir"); Process p = new ProcessBuilder() .directory(d) .command("cmd.exe", "/C", "mklink /J junction ..\\targetDir") .start(); <START> assertThat("unable to create junction", p.waitFor(), is(0)); <END> assertTrue(Util.isSymlink(new File(d, "junction"))); }</code><technical_language>please assume - this is test failing test prep</technical_language>

Target:
public void testIsSymlink_onWindows_junction() throws Exception { Assume.assumeTrue("Uses Windows-specific features", Functions.isWindows()); tmp.newFolder("targetDir"); File d = tmp.newFolder("dir"); Process p = new ProcessBuilder() .directory(d) .command("cmd.exe", "/C", "mklink /J junction ..\\targetDir") .start(); Assume.assumeThat("unable to create junction", p.waitFor(), is(0)); assertTrue(Util.isSymlink(new File(d, "junction"))); }
Source:
<code>public String getUsage() { StringBuilder help = new StringBuilder(String.format("Options:%n")); for(String arg : getUsageArguments()) { ParserArgument argument = this.arguments.get(arg); help.append( String.format( <START> " --%s%n %s%n%n", <END> arg + (argument.getType() != ArgumentType.no_argument ? "=[" + argument.getMetavar() + "]" : ""), argument.getHelp() ) ); } return String.format("%1$s%n%2$s%n%n%3$s%4$s%n", properties.getProperty( prefix + ".help.usage", (String)defaultProperties.get("help.usage") ), properties.getProperty( prefix + ".help.header", (String) defaultProperties.get("help.header") ), help.toString(), properties.getProperty( prefix + ".help.footer", (String) defaultProperties.get("help.footer") ) ); }</code><technical_language>please show new line text: ( " --%s%n" + " %s%n" + "%n" ),</technical_language>

Target:
public String getUsage() { StringBuilder help = new StringBuilder(String.format("Options:%n")); for(String arg : getUsageArguments()) { ParserArgument argument = this.arguments.get(arg); help.append( String.format( " --%s%n" + " %s%n" + "%n", arg + (argument.getType() != ArgumentType.no_argument ? "=[" + argument.getMetavar() + "]" : ""), argument.getHelp() ) ); } return String.format("%1$s%n%2$s%n%n%3$s%4$s%n", properties.getProperty( prefix + ".help.usage", (String)defaultProperties.get("help.usage") ), properties.getProperty( prefix + ".help.header", (String) defaultProperties.get("help.header") ), help.toString(), properties.getProperty( prefix + ".help.footer", (String) defaultProperties.get("help.footer") ) ); }
Source:
<code>public <T> T get(final String key, final Class<T> clazz) { @SuppressWarnings("unchecked") <START> final T value = (T) properties.get(key); <END> return value; }</code><technical_language>Put suppress warnings annotation method change direct returning getted avoid temporary store return value</technical_language>

Target:
public <T> T get(final String key, final Class<T> clazz) { return (T) properties.get(key); }
Source:
<code>private MongoCodeListEntryImportJob(ProcessContext process) { super(fileParameter, ignoreEmptyParameter, importModeParameter, MongoCodeListEntry.class, getDictionary(), process); <START> codeList = (MongoCodeList) process.require(codeListParameter); <END> }</code><technical_language>interface instead of concrete class</technical_language>

Target:
private MongoCodeListEntryImportJob(ProcessContext process) { super(fileParameter, ignoreEmptyParameter, importModeParameter, MongoCodeListEntry.class, getDictionary(), process); codeList = process.require(codeListParameter); }
Source:
<code>public int compareTo(RealmInteger o) { <START> long otherVal = o.val; <END> return (val == otherVal) ? 0 : ((val > otherVal) ? 1 : -1); }</code><technical_language>null check o</technical_language>

Target:
public int compareTo(RealmInteger o) { long otherValue = o.value; return (value == otherValue) ? 0 : ((value > otherValue) ? 1 : -1); }
Source:
<code>public Object[] factory() { return new Object[] { new WriteSkewGetGroupKeysTest(TestCacheFactory.PRIMARY_OWNER).totalOrder(false).isolationLevel(IsolationLevel.REPEATABLE_READ), new WriteSkewGetGroupKeysTest(TestCacheFactory.PRIMARY_OWNER).totalOrder(true).isolationLevel(IsolationLevel.REPEATABLE_READ), new WriteSkewGetGroupKeysTest(TestCacheFactory.BACKUP_OWNER).totalOrder(false).isolationLevel(IsolationLevel.REPEATABLE_READ), new WriteSkewGetGroupKeysTest(TestCacheFactory.BACKUP_OWNER).totalOrder(true).isolationLevel(IsolationLevel.REPEATABLE_READ), new WriteSkewGetGroupKeysTest(TestCacheFactory.NON_OWNER).totalOrder(false).isolationLevel(IsolationLevel.REPEATABLE_READ), <START> new WriteSkewGetGroupKeysTest(TestCacheFactory.NON_OWNER).totalOrder(true).isolationLevel(IsolationLevel.REPEATABLE_READ), <END> }; }</code><technical_language>this set in constructor</technical_language>

Target:
public Object[] factory() { return new Object[] { new WriteSkewGetGroupKeysTest(TestCacheFactory.PRIMARY_OWNER).totalOrder(false), new WriteSkewGetGroupKeysTest(TestCacheFactory.PRIMARY_OWNER).totalOrder(true), new WriteSkewGetGroupKeysTest(TestCacheFactory.BACKUP_OWNER).totalOrder(false), new WriteSkewGetGroupKeysTest(TestCacheFactory.BACKUP_OWNER).totalOrder(true), new WriteSkewGetGroupKeysTest(TestCacheFactory.NON_OWNER).totalOrder(false), new WriteSkewGetGroupKeysTest(TestCacheFactory.NON_OWNER).totalOrder(true), }; }
Source:
<code>private static boolean doesDescriptorMatchType(String descriptor, Class<?> type) { while (type != null) { <START> if (doesTypeMatch(descriptor, type)) { <END> return true; } type = type.getSuperclass(); } return false; }</code><technical_language>add empty line function declaration content if content is more line, SDN (where I a lot)</technical_language>

Target:
private static boolean doesDescriptorMatchType(String descriptor, Class<?> type) { while (type != null) { if (doesDescriptorMatchTypeOrInterface(descriptor, type)) { return true; } type = type.getSuperclass(); } return false; }
Source:
<code><START> public static File downloadFileFrom(Release release) throws IOException { <END> URL url = new URL(release.getDownloadURL()); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); File file = new File(NamingUtils.buildNameFrom(release)); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); return file; }</code><technical_language>need move method some other class</technical_language>

Target:
public static File downloadFileFrom(Release release) throws IOException { File file = new File(NamingUtils.buildNameFrom(release)); if (!file.exists()) { obtainNewJarFrom(release, file); } return file; }
Source:
<code>public static PAutomaton<PAutomatonState<String, String>, String> of(String s) { <START> ArrayList<Transition<PAutomatonState<String, String>, String>> rules = new ArrayList<>(); <END> ArrayList<PAutomatonState<String, String>> states = new ArrayList<>(); String[] stringTransitions = s.split("\\s*;\\s*"); int n = stringTransitions.length - 2; PAutomatonState<String,String> initialState = PAutomatonState.of(stringTransitions[n]); String[] finalStatesStrings = stringTransitions[n+1].trim().split("\\s+"); for (String state : finalStatesStrings) { states.add(PAutomatonState.ofString(state)); } for (int i = 0; i < n; i++) { Transition<PAutomatonState<String, String>, String> rule = Transition.of(stringTransitions[i]); rules.add(rule); } return new PAutomaton<>(rules, initialState, states); }</code><technical_language>List<...> rules = ..</technical_language>

Target:
public static PAutomaton<PAutomatonState<String, String>, String> of(String s) { List<Transition<PAutomatonState<String, String>, String>> rules = new ArrayList<>(); List<PAutomatonState<String, String>> states = new ArrayList<>(); String[] stringTransitions = s.split("\\s*;\\s*"); int n = stringTransitions.length - 2; PAutomatonState<String,String> initialState = PAutomatonState.of(stringTransitions[n]); String[] finalStatesStrings = stringTransitions[n+1].trim().split("\\s+"); for (String state : finalStatesStrings) { states.add(PAutomatonState.ofString(state)); } for (int i = 0; i < n; i++) { Transition<PAutomatonState<String, String>, String> rule = Transition.of(stringTransitions[i]); rules.add(rule); } return new PAutomaton<>(rules, initialState, states); }