auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public ExtendedJSONObject getObsoleteIds() { <END> String s = sharedPrefs.getString(HealthReportConstants.PREF_OBSOLETE_DOCUMENT_IDS_TO_DELETION_ATTEMPTS_REMAINING, null); if (s == null) { return new ExtendedJSONObject(); } try { return ExtendedJSONObject.parseJSONObject(s); } catch (Exception e) { Logger.warn(LOG_TAG, "Got exception getting obsolete ids.", e); return new ExtendedJSONObject(); } }</code><technical_language>Is reason this is ExtendedJSONObject</technical_language>

Target:
protected ExtendedJSONObject getObsoleteIds() { String s = sharedPrefs.getString(HealthReportConstants.PREF_OBSOLETE_DOCUMENT_IDS_TO_DELETION_ATTEMPTS_REMAINING, null); if (s == null) { String lastId = sharedPrefs.getString(HealthReportConstants.PREF_LAST_UPLOAD_DOCUMENT_ID, null); if (lastId == null) { return new ExtendedJSONObject(); } ExtendedJSONObject ids = new ExtendedJSONObject(); ids.put(lastId, HealthReportConstants.DELETION_ATTEMPTS_PER_OBSOLETE_DOCUMENT_ID); setObsoleteIds(ids); return ids; } try { return ExtendedJSONObject.parseJSONObject(s); } catch (Exception e) { Logger.warn(LOG_TAG, "Got exception getting obsolete ids.", e); return new ExtendedJSONObject(); } }
Source:
<code>protected List<Block> parseContent(RssMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { if (content == null) { <START> content = StringUtils.EMPTY; <END> } return this.getMacroContentParser().parse(content, context, false, context.isInline()).getChildren(); }</code><technical_language>I doubt checkstyle this much. feel need do this parse() starts a StringUtils.isEmpty check</technical_language>

Target:
protected List<Block> parseContent(RssMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { return this.getMacroContentParser().parse(content, context, false, context.isInline()).getChildren(); }
Source:
<code>public LogOffset append(int partition, M message) { ExcerptAppender appender = partitions.get(partition).acquireAppender(); if (codec != null) { appender.writeDocument(w -> w.write().bytes(codec.encode(message))); } else { <START> appender.writeDocument(w -> w.write("msg").object(message)); <END> } long offset = appender.lastIndexAppended(); LogOffset ret = new LogOffsetImpl(name, partition, offset); if (log.isDebugEnabled()) { log.debug(String.format("append to %s, value: %s", ret, message)); } return ret; }</code><technical_language>Please put "msg" in a constant</technical_language>

Target:
public LogOffset append(int partition, M message) { ExcerptAppender appender = partitions.get(partition).acquireAppender(); if (NO_CODEC.equals(codec)) { appender.writeDocument(w -> w.write(MSG_KEY).object(message)); } else { appender.writeDocument(w -> w.write().bytes(codec.encode(message))); } long offset = appender.lastIndexAppended(); LogOffset ret = new LogOffsetImpl(name, partition, offset); if (log.isDebugEnabled()) { log.debug(String.format("append to %s, value: %s", ret, message)); } return ret; }
Source:
<code>private String getInstalledVdsIdIfExists(SSHClient client) { try { ByteArrayOutputStream out = new ConstraintByteArrayOutputStream(256); client.executeCommand(Config.<String> getValue(ConfigValues.GetVdsmIdByVdsmToolCommand), null, out, null); return new String(out.toByteArray(), Charset.forName("UTF-8")); } catch (Exception e) { log.warn( <START> "Failed to initiate vdsm-id request on host with message {}", <END> e.getMessage() ); return null; } }</code><technical_language>Failed initiate vdsm-id request host: {}</technical_language>

Target:
private String getInstalledVdsIdIfExists(SSHClient client) { try { ByteArrayOutputStream out = new ConstraintByteArrayOutputStream(256); client.executeCommand(Config.<String> getValue(ConfigValues.GetVdsmIdByVdsmToolCommand), null, out, null); return new String(out.toByteArray(), Charset.forName("UTF-8")); } catch (Exception e) { log.warn( "Failed to initiate vdsm-id request on host: {}", e.getMessage() ); log.debug("Exception", e); return null; } }
Source:
<code>public void showError(@StringRes final int errorResId, @Nullable final Icon icon, @StringRes final int actionTextResId, @Nullable final View.OnClickListener actionListener) { if (baseFragment.isResumed()) { AlertDialogFragment.newInstance(0, errorResId, actionListener == null ? null : new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { actionListener.onClick(((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE)); } } <START> ).show(baseFragment.getFragmentManager(), null); <END> } }</code><technical_language>reason getFragmentManager() previously passed getChildFragmentManager()</technical_language>

Target:
public void showError(@StringRes final int errorResId, @Nullable final Icon icon, @StringRes final int actionTextResId, @Nullable final View.OnClickListener actionListener) { if (baseFragment.isResumed()) { AlertDialogFragment.newInstance(0, errorResId, actionListener == null ? null : new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { actionListener.onClick(((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE)); } } ).show(baseFragment.getChildFragmentManager(), null); } }
Source:
<code>public void exit() { try { client.logout(creds); } catch (Exception e) { throw Throwables.propagate(e); } <START> client.getInputProtocol().getTransport().close(); <END> client.getOutputProtocol().getTransport().close(); }</code><technical_language>Place lines try block</technical_language>

Target:
public void exit() { try { client.logout(creds); client.getInputProtocol().getTransport().close(); client.getOutputProtocol().getTransport().close(); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
<code>public CompletionStage<Void> preload() { long stamp = acquireReadLock(); NonBlockingStore<Object, Object> nonBlockingStore = getStoreLocked(storeStatus -> <START> storeStatus.config.preload()); <END> if (nonBlockingStore == null) { releaseReadLock(stamp); return CompletableFutures.completedNull(); } Publisher<MarshallableEntry<Object, Object>> publisher = nonBlockingStore.publishEntries( IntSets.immutableRangeSet(segmentCount), null, true); long start = timeService.time(); final long maxEntries = getMaxEntries(); final long flags = getFlagsForStateInsertion(); AdvancedCache<?,?> tmpCache = this.cache.wired().withStorageMediaType(); DataConversion keyDataConversion = tmpCache.getKeyDataConversion(); DataConversion valueDataConversion = tmpCache.getValueDataConversion(); return Flowable.fromPublisher(publisher) .doFinally(() -> releaseReadLock(stamp)) .take(maxEntries) .concatMapSingle(me -> preloadKey(flags, me, keyDataConversion, valueDataConversion)) .count() .toCompletionStage() .thenAccept(insertAmount -> { this.preloaded = insertAmount < maxEntries; log.debugf("Preloaded %d keys in %s", insertAmount, Util.prettyPrintTime(timeService.timeDuration(start, MILLISECONDS))); }); }</code><technical_language>Nitpick: s/storeStatus/store easily fit line</technical_language>

Target:
public CompletionStage<Void> preload() { long stamp = acquireReadLock(); NonBlockingStore<Object, Object> nonBlockingStore = getStoreLocked(status -> status.config.preload()); if (nonBlockingStore == null) { releaseReadLock(stamp); return CompletableFutures.completedNull(); } Publisher<MarshallableEntry<Object, Object>> publisher = nonBlockingStore.publishEntries( IntSets.immutableRangeSet(segmentCount), null, true); long start = timeService.time(); final long maxEntries = getMaxEntries(); final long flags = getFlagsForStateInsertion(); AdvancedCache<?,?> tmpCache = this.cache.wired().withStorageMediaType(); DataConversion keyDataConversion = tmpCache.getKeyDataConversion(); DataConversion valueDataConversion = tmpCache.getValueDataConversion(); return Flowable.fromPublisher(publisher) .doFinally(() -> releaseReadLock(stamp)) .take(maxEntries) .concatMapSingle(me -> preloadEntry(flags, me, keyDataConversion, valueDataConversion)) .count() .toCompletionStage() .thenAccept(insertAmount -> { this.preloaded = insertAmount < maxEntries; log.debugf("Preloaded %d keys in %s", insertAmount, Util.prettyPrintTime(timeService.timeDuration(start, MILLISECONDS))); }); }
Source:
<code>private long milliTime() { <START> return System.nanoTime() / 1000000l; <END> }</code><technical_language>suggestion return System.currentTimeMillis();</technical_language>

Target:
private long milliTime() { return System.currentTimeMillis(); }
Source:
<code>public void testSerializeNullableString() { String randomString = getRandomString(10); ByteBuffer outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); Utils.serializeNullableString(outputBuffer, randomString); outputBuffer.flip(); int length = outputBuffer.getInt(); assertTrue("Input string length " + randomString.getBytes().length + " didn't match output string length " + length, (randomString.getBytes().length == length)); byte[] output = new byte[length]; outputBuffer.get(output); <START> assertTrue("Output buffer shouldn't have any remaining " + outputBuffer.remaining(), outputBuffer.remaining() == 0); <END> String outputString = new String(output); assertEquals("Output string \"" + outputString + "\" didn't match input string \"" + randomString + "\"", outputString, randomString); randomString = null; outputBuffer = ByteBuffer.allocate(4); Utils.serializeNullableString(outputBuffer, randomString); outputBuffer.flip(); length = outputBuffer.getInt(); assertTrue("Input string length 0 didn't match output string length " + length, (0 == length)); output = new byte[length]; outputBuffer.get(output); assertTrue("Output buffer shouldn't have any remaining " + outputBuffer.remaining(), outputBuffer.remaining() == 0); outputString = new String(output); assertTrue("Output string \"" + outputString + "\" expected to be empty", (outputString.equals(""))); }</code><technical_language>outputBuffer.hasRemaining() instead of outputBuffer.remaining() == 0</technical_language>

Target:
public void testSerializeNullableString() { String randomString = getRandomString(10); ByteBuffer outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); Utils.serializeNullableString(outputBuffer, randomString); outputBuffer.flip(); int length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match ", randomString.getBytes().length, length); byte[] output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); String outputString = new String(output); assertEquals("Input and output strings don't match", randomString, outputString); randomString = null; outputBuffer = ByteBuffer.allocate(4); Utils.serializeNullableString(outputBuffer, randomString); outputBuffer.flip(); length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match", 0, length); output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); outputString = new String(output); assertEquals("Output string \"" + outputString + "\" expected to be empty", outputString, ""); }
Source:
<code>public Map<String, String> deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException { Object environment = jsonParser.readValueAs(Object.class); try { if (environment instanceof Map) { return (Map<String, String>) environment; } if (environment instanceof List) { return ((List<String>) environment).stream() .collect(Collectors.toMap(item -> item.split("=")[0], item -> item.split("=")[1])); } } catch (Exception e) { <START> throw new RuntimeException(format("Unsupported value '%s'.", environment.toString())); <END> } if (environment instanceof String) { if (((String) environment).isEmpty()) { return new HashMap<>(); } throw new RuntimeException(format("Unsupported value '%s'.", environment.toString())); } throw new RuntimeException(format("Unsupported type '%s'.", environment.getClass())); }</code><technical_language>is avoid throwing of another type of exception is declared in overridden method</technical_language>

Target:
public Map<String, String> deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException { Object environment = jsonParser.readValueAs(Object.class); if (environment instanceof Map) { return (Map<String, String>) environment; } try { if (environment instanceof List) { return parseArrayEnvironment((List<String>) environment); } } catch (IllegalArgumentException ie) { throw ctxt.mappingException(ie.getMessage()); } catch (Exception e) { throw ctxt.mappingException(format(UNSUPPORTED_VALUE_MESSAGE, environment)); } if (environment instanceof String) { if (((String) environment).isEmpty()) { return new HashMap<>(); } throw ctxt.mappingException(format(UNSUPPORTED_VALUE_MESSAGE, environment)); } throw ctxt.mappingException(format("Unsupported type '%s'.", environment.getClass())); }
Source:
<code>DataSegment uploadDataSegment( DataSegment segment, final int binaryVersion, final long size, final File compressedSegmentData, final String azurePath ) throws StorageException, IOException, URISyntaxException { azureStorage.uploadBlob(compressedSegmentData, config.getContainer(), azurePath); final DataSegment outSegment = segment .withSize(size) .withLoadSpec(this.makeLoadSpec(new URI(azurePath))) .withBinaryVersion(binaryVersion); <START> log.info("Deleting file [%s]", compressedSegmentData); <END> compressedSegmentData.delete(); return outSegment; }</code><technical_language>change log level debug? worth info level</technical_language>

Target:
DataSegment uploadDataSegment( DataSegment segment, final int binaryVersion, final long size, final File compressedSegmentData, final String azurePath ) throws StorageException, IOException, URISyntaxException { azureStorage.uploadBlob(compressedSegmentData, config.getContainer(), azurePath); final DataSegment outSegment = segment .withSize(size) .withLoadSpec(this.makeLoadSpec(new URI(azurePath))) .withBinaryVersion(binaryVersion); log.debug("Deleting file [%s]", compressedSegmentData); compressedSegmentData.delete(); return outSegment; }
Source:
<code>private RunResult runDelivery(ShardProcessingSession session) { ShardIndex index = session.shardIndex(); Page<InboxMessage> startingPage = inboxStorage.readAll(index, pageSize); Optional<Page<InboxMessage>> maybePage = Optional.of(startingPage); boolean continueAllowed = true; List<DeliveryStage> stages = new ArrayList<>(); Iterable<CatchUp> catchUpJobs = ImmutableList.copyOf(catchUpStorage.readAll()); while (continueAllowed && maybePage.isPresent()) { <START> Page<InboxMessage> currentPage = maybePage.get(); <END> ImmutableList<InboxMessage> messages = currentPage.contents(); if (!messages.isEmpty()) { DeliveryAction action = new GroupByTargetAndDeliver(deliveries); Conveyor conveyor = new Conveyor(messages, deliveredMessages); List<Station> stations = conveyorStationsFor(catchUpJobs, action); DeliveryStage stage = launch(conveyor, stations, index); continueAllowed = monitorTellsToContinue(stage); stages.add(stage); } if (continueAllowed) { if(messages.size() < pageSize) { catchUpJobs = ImmutableList.copyOf(catchUpStorage.readAll()); } maybePage = currentPage.next(); } } int totalMessagesDelivered = stages.stream() .map(DeliveryStage::getMessagesDelivered) .reduce(0, Integer::sum); return new RunResult(totalMessagesDelivered, !continueAllowed); }</code><technical_language>Please consider simplifying body of cycle extracting if branch a method</technical_language>

Target:
private RunResult runDelivery(ShardProcessingSession session) { ShardIndex index = session.shardIndex(); Page<InboxMessage> startingPage = inboxStorage.readAll(index, pageSize); Optional<Page<InboxMessage>> maybePage = Optional.of(startingPage); boolean shouldContinue = true; List<DeliveryStage> stages = new ArrayList<>(); Iterable<CatchUp> catchUpJobs = refreshCatchUpJobs(); while (shouldContinue && maybePage.isPresent()) { Page<InboxMessage> currentPage = maybePage.get(); ImmutableList<InboxMessage> messages = currentPage.contents(); if (!messages.isEmpty()) { DeliveryStage stage = deliverMessages(messages, index, catchUpJobs); stages.add(stage); shouldContinue = monitorTellsToContinueAfter(stage); } if (shouldContinue) { if(messages.size() < pageSize) { catchUpJobs = refreshCatchUpJobs(); } maybePage = currentPage.next(); } } int totalMessagesDelivered = stages.stream() .map(DeliveryStage::getMessagesDelivered) .reduce(0, Integer::sum); return new RunResult(totalMessagesDelivered, !shouldContinue); }
Source:
<code>public String toString() { <START> return "[id: " + this.id + " entryType: " + this.entryType + " size: " + this.size + "]"; <END> }</code><technical_language>minor: need this. qualifiers</technical_language>

Target:
public String toString() { return "[id: " + id + " entryType: " + entryType + " size: " + size + "]"; }
Source:
<code>public void startRuntime() { String tempDir = AppConstants.getInstance().getString("log.dir", null); <START> v8 = V8.createV8Runtime("J2V8Javascript", tempDir); <END> }</code><technical_language>Setting alias temp directory important. this optional argument? overwrite alias needed (i.e. improve performance). Right instances cached name</technical_language>

Target:
public void startRuntime() { v8 = V8.createV8Runtime(); }
Source:
<code>private Map<String, List<String>> findPKUpdates() throws OrmException, SQLException { Map<String, List<String>> corrections = new <START> HashMap<>(); <END> ReviewDb db = dbFactory.open(); try { DatabaseMetaData meta = conn.getMetaData(); JavaSchemaModel jsm = new JavaSchemaModel(ReviewDb.class); for (RelationModel rm : jsm.getRelations()) { String tableName = rm.getRelationName(); List<String> relationPK = relationPK(rm); List<String> tablePK = dbTablePK(meta, tableName); if (!relationPK.equals(tablePK)) { corrections.put(tableName, relationPK); } } return corrections; } finally { db.close(); } }</code><technical_language>Eh, TreeMap here. a tables broken primary keys. more sense process in name order in a random order implied hashing function hashtable's internal structure</technical_language>

Target:
private Map<String, List<String>> findPKUpdates() throws OrmException, SQLException { Map<String, List<String>> corrections = new TreeMap<>(); ReviewDb db = dbFactory.open(); try { DatabaseMetaData meta = conn.getMetaData(); JavaSchemaModel jsm = new JavaSchemaModel(ReviewDb.class); for (RelationModel rm : jsm.getRelations()) { String tableName = rm.getRelationName(); List<String> expectedPK = relationPK(rm); List<String> actualPK = dbTablePK(meta, tableName); if (!expectedPK.equals(actualPK)) { corrections.put(tableName, expectedPK); } } return corrections; } finally { db.close(); } }
Source:
<code>public void updateResponseAsReference(ExecuteResponseDocument res, String reqID, String mimeType) throws ExceptionReport { prepareGenerator(); OutputDataType output = prepareOutput(res); <START> InputStream stream; <END> OutputReferenceType outReference = output.addNewReference(); if (schema != null) { outReference.setSchema(schema); } if (encoding != null) { outReference.setEncoding(encoding); } if (mimeType != null) { outReference.setMimeType(mimeType); } IDatabase db = DatabaseFactory.getDatabase(); try { if (encoding == null || encoding.equals("") || encoding.equalsIgnoreCase(IOHandler.DEFAULT_ENCODING)){ stream = generator.generateStream(super.obj, mimeType, schema); } else if (encoding.equalsIgnoreCase(IOHandler.ENCODING_BASE64)){ stream = generator.generateBase64Stream(super.obj, mimeType, schema); } else { throw new ExceptionReport("Unable to generate encoding " + encoding, ExceptionReport.NO_APPLICABLE_CODE); } } catch (IOException e){ LOGGER.error(e.getMessage(), e); throw new ExceptionReport("Error while generating Complex Data out of the process result", ExceptionReport.NO_APPLICABLE_CODE, e); } String storeReference = db.storeComplexValue(reqID, id, stream, COMPLEX_DATA_TYPE, mimeType); storeReference = storeReference.replace("#", "%23"); outReference.setHref(storeReference); this.mimeType = "text/xml"; }</code><technical_language>Is this closed anywhere</technical_language>

Target:
public void updateResponseAsReference(ExecuteResponseDocument res, String reqID, String mimeType) throws ExceptionReport { prepareGenerator(); OutputDataType output = prepareOutput(res); InputStream stream = null; OutputReferenceType outReference = output.addNewReference(); if (schema != null) { outReference.setSchema(schema); } if (encoding != null) { outReference.setEncoding(encoding); } if (mimeType != null) { outReference.setMimeType(mimeType); } IDatabase db = DatabaseFactory.getDatabase(); try { if (encoding == null || encoding.equals("") || encoding.equalsIgnoreCase(IOHandler.DEFAULT_ENCODING)){ stream = generator.generateStream(super.obj, mimeType, schema); } else if (encoding.equalsIgnoreCase(IOHandler.ENCODING_BASE64)){ stream = generator.generateBase64Stream(super.obj, mimeType, schema); } else { throw new ExceptionReport("Unable to generate encoding " + encoding, ExceptionReport.NO_APPLICABLE_CODE); } String storeReference = db.storeComplexValue(reqID, id, stream, COMPLEX_DATA_TYPE, mimeType); storeReference = storeReference.replace("#", "%23"); outReference.setHref(storeReference); } catch (IOException e){ LOGGER.error(e.getMessage(), e); throw new ExceptionReport("Error while generating Complex Data out of the process result", ExceptionReport.NO_APPLICABLE_CODE, e); } finally { IOUtils.closeQuietly(stream); } this.mimeType = "text/xml"; }
Source:
<code>public Future<Void> close() { final Promise<Void> closeDonePromise = new DefaultPromise<>(this.executor); this.allChannels.close().addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(final Future<Void> future) { ApnsChannelPool.this.isClosed = true; final Promise<Void> cancelFuturePromise = new DefaultPromise<>(ApnsChannelPool.this.executor); final int numOfFuturesToCancel = pendingCreateChannelFutures.size(); if (numOfFuturesToCancel > 0) { final AtomicInteger numOfCanceledFutures = new AtomicInteger(0); for (Future<Channel> f : pendingCreateChannelFutures) { <START> f.addListener(new GenericFutureListener<Future<? super Channel>>() { <END> @Override public void operationComplete(Future<? super Channel> future) { if (numOfCanceledFutures.incrementAndGet() == numOfFuturesToCancel) { cancelFuturePromise.setSuccess(null); } } }); } } else { cancelFuturePromise.setSuccess(null); } cancelFuturePromise.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { if (ApnsChannelPool.this.channelFactory instanceof Closeable) { ((Closeable) ApnsChannelPool.this.channelFactory).close(); } for (final Promise<Channel> acquisitionPromise : ApnsChannelPool.this.pendingAcquisitionPromises) { acquisitionPromise.tryFailure(POOL_CLOSED_EXCEPTION); } closeDonePromise.setSuccess(null); } }); } }); return closeDonePromise; }</code><technical_language>If reading this right (and I missing something!), _cancelling_ futures, right? waiting for finish own</technical_language>

Target:
public Future<Void> close() { final Promise<Void> closeDonePromise = new DefaultPromise<>(this.executor); this.allChannels.close().addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(final Future<Void> future) { ApnsChannelPool.this.isClosed = true; final Promise<Void> waitForPendingCreateChannelFuturesPromise = new DefaultPromise<>(ApnsChannelPool.this.executor); final PromiseCombiner combiner = new PromiseCombiner(ApnsChannelPool.this.executor); for (final Future<Channel> f : pendingCreateChannelFutures) { combiner.add(f); } combiner.finish(waitForPendingCreateChannelFuturesPromise); waitForPendingCreateChannelFuturesPromise.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { if (ApnsChannelPool.this.channelFactory instanceof Closeable) { ((Closeable) ApnsChannelPool.this.channelFactory).close(); } for (final Promise<Channel> acquisitionPromise : ApnsChannelPool.this.pendingAcquisitionPromises) { acquisitionPromise.tryFailure(POOL_CLOSED_EXCEPTION); } closeDonePromise.setSuccess(null); } }); } }); return closeDonePromise; }
Source:
<code>public void addPages() { page = new EFactoryNewFileWizardPage(selection); <START> initialObjectCreationpage = new ESONInitialObjectCreationPage("Whatever"); <END> addPage(page); addPage(initialObjectCreationpage); }</code><technical_language>"Whatever" here, is this a left over, final</technical_language>

Target:
public void addPages() { page = new EFactoryNewFileWizardPage(selection); initialObjectCreationpage = new ESONInitialObjectCreationPage("InitialObject"); addPage(page); addPage(initialObjectCreationpage); }
Source:
<code>public void rollbackMigration(PartitionMigrationEvent event) { if (DESTINATION == event.getMigrationEndpoint()) { removeRecordStoresHavingLesserBackupCountThan(event.getPartitionId(), event.getCurrentReplicaIndex()); <START> getMetaDataGenerator().removeUuidAndSequence(event.getPartitionId()); <END> } mapServiceContext.reloadOwnedPartitions(); }</code><technical_language>Do need remove reservations if member is longer replica rollback, for record stores</technical_language>

Target:
public void rollbackMigration(PartitionMigrationEvent event) { if (DESTINATION == event.getMigrationEndpoint()) { removeWbqCountersHavingLesserBackupCountThan(event.getPartitionId(), event.getCurrentReplicaIndex()); removeRecordStoresHavingLesserBackupCountThan(event.getPartitionId(), event.getCurrentReplicaIndex()); getMetaDataGenerator().removeUuidAndSequence(event.getPartitionId()); } mapServiceContext.reloadOwnedPartitions(); }
Source:
<code>private void resizeIfPossible(Tag tag) { if (size >= MAX_TAGS) { final String msg = String.format("Cannot add Tag %s - Maximum number of tags (%d) reached.", tag, MAX_TAGS); <START> throw new IllegalStateException(msg); <END> } Object[] prevBuf = buf; init(size * 2); for (int i = 1; i < prevBuf.length; i += 2) { Tag t = (Tag) prevBuf[i]; if (t != null) { add(t); } } add(tag); }</code><technical_language>concern is in rare event more MAX_TAGS worked get exception break application flow</technical_language>

Target:
private void resizeIfPossible(Tag tag) { if (size < MAX_TAGS) { Object[] prevBuf = buf; init(size * 2); for (int i = 1; i < prevBuf.length; i += 2) { Tag t = (Tag) prevBuf[i]; if (t != null) { add(t); } } add(tag); } else { final String msg = String.format("Cannot add Tag %s - Maximum number of tags (%d) reached.", tag, MAX_TAGS); LOGGER.error(msg); } }
Source:
<code>private Element addFilesToDuplicationElement(Document doc, Element duplication, Match match) { Mark mark; for (Iterator<Mark> iterator = match.iterator(); iterator.hasNext();) { mark = iterator.next(); final Element file = doc.createElement("file"); file.setAttribute("line", String.valueOf(mark.getBeginLine())); file.setAttribute("path", mark.getFilename()); file.setAttribute("endline", String.valueOf(mark.getEndLine())); final int beginCol = mark.getBeginColumn(); final int endCol = mark.getEndColumn(); if (beginCol != -1) { <START> file.setAttribute("column", String.valueOf(mark.getBeginColumn())); <END> } if (endCol != -1) { file.setAttribute("endcolumn", String.valueOf(mark.getEndColumn())); } duplication.appendChild(file); } return duplication; }</code><technical_language>suggestion file.setAttribute("column", String.valueOf(beginCol));</technical_language>

Target:
private Element addFilesToDuplicationElement(Document doc, Element duplication, Match match) { Mark mark; for (Iterator<Mark> iterator = match.iterator(); iterator.hasNext();) { mark = iterator.next(); final Element file = doc.createElement("file"); file.setAttribute("line", String.valueOf(mark.getBeginLine())); file.setAttribute("path", mark.getFilename()); file.setAttribute("endline", String.valueOf(mark.getEndLine())); final int beginCol = mark.getBeginColumn(); final int endCol = mark.getEndColumn(); if (beginCol != -1) { file.setAttribute("column", String.valueOf(beginCol)); } if (endCol != -1) { file.setAttribute("endcolumn", String.valueOf(endCol)); } duplication.appendChild(file); } return duplication; }
Source:
<code>public boolean isAttached(DialogField editor) { if (fAttachedDialogFields != null) { for (DialogField <START> fAttachedDialogField : <END> fAttachedDialogFields) { if (fAttachedDialogField == editor) { return true; } } } return false; }</code><technical_language>rename dialogField</technical_language>

Target:
public boolean isAttached(DialogField editor) { if (fAttachedDialogFields != null) { for (DialogField dialogField : fAttachedDialogFields) { if (dialogField == editor) { return true; } } } return false; }
Source:
<code><START> public String draw () throws Exception { <END> StringBuffer sb = new StringBuffer(); if ( this.containers != null ) { for ( String container: this.containers ) { if ( this.preview ) { sb.append( PreviewTemplateUtil.getMockBodyContent() ); } else { sb.append( "#parseContainer('" ).append( container ).append( "')" ); } } } return sb.toString(); }</code><technical_language>logic in a object, concern separated</technical_language>

Target:
public String draw () throws Exception { final StringBuilder sb = new StringBuilder(); if ( this.containers != null ) { for ( final String container: this.containers ) { if ( this.preview ) { sb.append( PreviewTemplateUtil.getMockBodyContent() ); } else { sb.append( "#parseContainer('" ).append( container ).append( "')" ); } } } return sb.toString(); }
Source:
<code>private void removeTagCacheEntry(TagCacheEntry entry) { if (entry.parent == null) { return; } Map newParentChildren = new HashMap(); newParentChildren.putAll(entry.parent.children); newParentChildren.remove(entry.path.lastSegment()); entry.parent.children = newParentChildren; <START> if (entry.parent.getTags().isEmpty() && entry.children.isEmpty()) { <END> removeTagCacheEntry(entry.parent); } }</code><technical_language>condition "entry.parent.children.isEmpty()"</technical_language>

Target:
private void removeTagCacheEntry(TagCacheEntry entry) { if (entry.parent == null) { return; } Map newParentChildren = new HashMap(); newParentChildren.putAll(entry.parent.children); newParentChildren.remove(entry.path.lastSegment()); entry.parent.children = newParentChildren; if (entry.parent.isEmpty()) { removeTagCacheEntry(entry.parent); } }
Source:
<code>public CloseableHttpResponse exportAsPMML(int modelId) throws MLHttpClientException { CloseableHttpResponse response; try { response = doHttpGet("/api/models/" + modelId + "/export?mode=pmml"); return response; } catch (MLHttpClientException e) { <START> throw new MLHttpClientException("Failed to download model as PMML", e); <END> } }</code><technical_language>print modelId in error msg</technical_language>

Target:
public CloseableHttpResponse exportAsPMML(int modelId) throws MLHttpClientException { CloseableHttpResponse response; try { response = doHttpGet("/api/models/" + modelId + "/export?mode=pmml"); return response; } catch (MLHttpClientException e) { throw new MLHttpClientException("Failed to download model as PMML for model [id] "+ modelId, e); } }
Source:
<code>public void testExtractIpv4AddressEmptyString() { <START> assertThat(VdsBrokerObjectsBuilder.extractAddress(ImmutableMap.of(ADDR, "")), <END> nullValue()); }</code><technical_language>a common style in this file VdsProperties.ADDR</technical_language>

Target:
public void testExtractIpv4AddressEmptyString() { assertThat(VdsBrokerObjectsBuilder.extractAddress(ImmutableMap.of(VdsProperties.ADDR, "")), nullValue()); }
Source:
<code>@Override public TResult current() { if (curAccumulator == null) { curAccumulator = accumulatorInitializer.apply(); } TResult result = null; TSource o = enumerator.current(); <START> TKey prevKey = keySelector.apply(o); <END> curAccumulator = accumulatorAdder.apply(curAccumulator, o); while (enumerator.moveNext()) { o = enumerator.current(); TKey curKey = keySelector.apply(o); if (comparator.compare(prevKey, curKey) != 0) { result = resultSelector.apply(prevKey, curAccumulator); curAccumulator = accumulatorInitializer.apply(); break; } else { curAccumulator = accumulatorAdder.apply(curAccumulator, o); } prevKey = curKey; } if (result == null) { result = resultSelector.apply(prevKey, curAccumulator); curAccumulator = null; } return result; }</code><technical_language>I this implementation of current respect this part of contract: This method move position of enumerator, consecutive calls {@code current} return object {@code moveNext} {@code reset} is called. I impression consecutive calls current return results. I logic transferred part of moveNext, "current object" saved; finally current do processing, returning "current object" saved moveNext process, that</technical_language>

Target:
@Override public TResult current() { if (isLastMoveNextFalse) { throw new NoSuchElementException(); } return curResult; }
Source:
<code>public boolean isSingleton() { <START> return false; <END> }</code><technical_language>is this singleton</technical_language>

Target:
public boolean isSingleton() { return true; }
Source:
<code>public void testConfigJvmHeapMemory() { MemorySize jvmHeapMemory = MemorySize.parse("50m"); Configuration conf = new Configuration(); conf.set(JobManagerOptions.JVM_HEAP_MEMORY, jvmHeapMemory); JobManagerProcessSpec jobManagerProcessSpec = JobManagerProcessUtils.processSpecFromConfig(conf); assertThat(jobManagerProcessSpec.getJvmHeapMemorySize(), is(jvmHeapMemory)); <START> MatcherAssert.assertThat( <END> testLoggerResource.getMessages(), hasItem(containsString("The configured or derived JVM heap memory size (50.000mb (52428800 bytes)) is less than its recommended minimum value (128 mb)"))); jvmHeapMemory = MemorySize.parse("150m"); conf.set(JobManagerOptions.JVM_HEAP_MEMORY, jvmHeapMemory); conf.set(JobManagerOptions.JOB_STORE_CACHE_SIZE, 200L * 1024L * 1024L); jobManagerProcessSpec = JobManagerProcessUtils.processSpecFromConfig(conf); assertThat(jobManagerProcessSpec.getJvmHeapMemorySize(), is(jvmHeapMemory)); MatcherAssert.assertThat( testLoggerResource.getMessages(), hasItem(containsString("The configured or derived JVM heap memory size (jobmanager.memory.heap.size: 150.000mb (157286400 bytes)) is less than the configured or default size " + "of the job store cache (jobstore.cache-size: 200.000mb (209715200 bytes))"))); }</code><technical_language>I for readability, logging test a separate test case</technical_language>

Target:
public void testConfigJvmHeapMemory() { MemorySize jvmHeapSize = MemorySize.parse("50m"); Configuration conf = new Configuration(); conf.set(JobManagerOptions.JVM_HEAP_MEMORY, jvmHeapSize); JobManagerProcessSpec JobManagerProcessSpec = JobManagerProcessUtils.processSpecFromConfig(conf); assertThat(JobManagerProcessSpec.getJvmHeapMemorySize(), is(jvmHeapSize)); }
Source:
<code>protected void collectSubstitutionsPaths(ISourceContainer[] containers, Map<String, String> entries) { for (ISourceContainer container : containers) { if (container instanceof MapEntrySourceContainer) { MapEntrySourceContainer sourceSubContainer = (MapEntrySourceContainer) container; IPath from = sourceSubContainer.getBackendPath(); IPath to = sourceSubContainer.getLocalPath(); if (from != null && to != null) { entries.put(from.toOSString(), to.toOSString()); } } <START> if (container.isComposite()) { <END> ISourceContainer[] childContainers; try { childContainers = container.getSourceContainers(); } catch (CoreException e) { childContainers = new ISourceContainer[0]; } if (container instanceof MappingSourceContainer) { MappingSourceContainer mappingSourceContainer = (MappingSourceContainer) container; if (mappingSourceContainer.isMappingWithBackendEnabled()) { collectSubstitutionsPaths(childContainers, entries); } else { } } else { collectSubstitutionsPaths(childContainers, entries); } } } }</code><technical_language>a big deal, if in else MapEntrySourceContainer children</technical_language>

Target:
protected void collectSubstitutionsPaths(ISourceContainer[] containers, Map<String, String> entries) { for (ISourceContainer container : containers) { if (container instanceof MapEntrySourceContainer) { MapEntrySourceContainer sourceSubContainer = (MapEntrySourceContainer) container; IPath from = sourceSubContainer.getBackendPath(); IPath to = sourceSubContainer.getLocalPath(); if (from != null && to != null) { entries.put(from.toOSString(), to.toOSString()); } } else if (container.isComposite()) { ISourceContainer[] childContainers; try { childContainers = container.getSourceContainers(); } catch (CoreException e) { childContainers = new ISourceContainer[0]; } if (container instanceof MappingSourceContainer) { MappingSourceContainer mappingSourceContainer = (MappingSourceContainer) container; if (mappingSourceContainer.isMappingWithBackendEnabled()) { collectSubstitutionsPaths(childContainers, entries); } else { } } else { collectSubstitutionsPaths(childContainers, entries); } } } }
Source:
<code>public Result emailSignIn() { SignIn signInRequest = parseJson(request(), SignIn.class); if (isBlank(signInRequest.getStudyId())) { throw new BadRequestException("Study identifier is required."); } Study study = studyService.getStudy(signInRequest.getStudyId()); verifySupportedVersionOrThrowException(study); CriteriaContext context = getCriteriaContext(study.getStudyIdentifier()); UserSession session = null; try { session = authenticationService.emailSignIn(context, signInRequest); } catch(ConsentRequiredException e) { <START> logAuthenticationSuccess(e.getUserSession()); <END> throw e; } logAuthenticationSuccess(session); return okResult(UserSessionInfo.toJSON(session)); }</code><technical_language>log authentication success failed sign in? method name a misleading</technical_language>

Target:
public Result emailSignIn() { SignIn signInRequest = parseJson(request(), SignIn.class); if (isBlank(signInRequest.getStudyId())) { throw new BadRequestException("Study identifier is required."); } Study study = studyService.getStudy(signInRequest.getStudyId()); verifySupportedVersionOrThrowException(study); CriteriaContext context = getCriteriaContext(study.getStudyIdentifier()); UserSession session = null; try { session = authenticationService.emailSignIn(context, signInRequest); } catch(ConsentRequiredException e) { setCookieAndRecordMetrics(e.getUserSession()); throw e; } setCookieAndRecordMetrics(session); return okResult(UserSessionInfo.toJSON(session)); }
Source:
<code>public static Polygon randomPolygon(boolean hasAlt) { org.apache.lucene.geo.Polygon lucenePolygon = GeoTestUtil.nextPolygon(); <START> while(area(lucenePolygon) == 0) { <END> lucenePolygon = GeoTestUtil.nextPolygon(); } if (lucenePolygon.numHoles() > 0) { org.apache.lucene.geo.Polygon[] luceneHoles = lucenePolygon.getHoles(); List<LinearRing> holes = new ArrayList<>(); for (int i = 0; i < lucenePolygon.numHoles(); i++) { org.apache.lucene.geo.Polygon poly = luceneHoles[i]; holes.add(linearRing(poly.getPolyLons(), poly.getPolyLats(), hasAlt)); } return new Polygon(linearRing(lucenePolygon.getPolyLons(), lucenePolygon.getPolyLats(), hasAlt), holes); } return new Polygon(linearRing(lucenePolygon.getPolyLons(), lucenePolygon.getPolyLats(), hasAlt)); }</code><technical_language>randomValueOtherThanMany(p -> area(p) == 0, GeoTestUtil::nextPolygon); do this kind of thing. faster have, is more common</technical_language>

Target:
public static Polygon randomPolygon(boolean hasAlt) { org.apache.lucene.geo.Polygon lucenePolygon = randomValueOtherThanMany(p -> area(p) == 0, GeoTestUtil::nextPolygon); if (lucenePolygon.numHoles() > 0) { org.apache.lucene.geo.Polygon[] luceneHoles = lucenePolygon.getHoles(); List<LinearRing> holes = new ArrayList<>(); for (int i = 0; i < lucenePolygon.numHoles(); i++) { org.apache.lucene.geo.Polygon poly = luceneHoles[i]; holes.add(linearRing(poly.getPolyLons(), poly.getPolyLats(), hasAlt)); } return new Polygon(linearRing(lucenePolygon.getPolyLons(), lucenePolygon.getPolyLats(), hasAlt), holes); } return new Polygon(linearRing(lucenePolygon.getPolyLons(), lucenePolygon.getPolyLats(), hasAlt)); }
Source:
<code>public boolean isKeyFrame(RawPacket pkt) { byte[] buf = pkt.getBuffer(); int off = pkt.getOffset(); int len = pkt.getLength(); if (frameMarkingsExtensionId != -1) { <START> RawPacket.HeaderExtensions hes = pkt.getHeaderExtensions(); <END> while (hes.hasNext()) { RawPacket.HeaderExtension he = hes.next(); if (he.getExtId() == frameMarkingsExtensionId) { return FrameMarkingHeaderExtension.isKeyframe(he); } } if (logger.isDebugEnabled()) { logger.debug("Packet with no frame marking, while frame marking" + " is enabled."); } } REDBlock redBlock = getPayloadBlock(buf, off, len); if (redBlock == null || redBlock.getLength() == 0) { return false; } final byte vp8PT = getDynamicRTPPayloadType(Constants.VP8), h264PT = getDynamicRTPPayloadType(Constants.H264); if (redBlock.getPayloadType() == vp8PT) { return org.jitsi.impl.neomedia.codec.video.vp8.DePacketizer .isKeyFrame(buf, redBlock.getOffset(), redBlock.getLength()); } else if (redBlock.getPayloadType() == h264PT) { return org.jitsi.impl.neomedia.codec.video.h264.DePacketizer .isKeyFrame( redBlock.getBuffer(), redBlock.getOffset(), redBlock.getLength()); } else { return false; } }</code><technical_language>in order for recommendation work, getHeaderExtensions() static</technical_language>

Target:
public boolean isKeyFrame(RawPacket pkt) { if (!RTPPacketPredicate.INSTANCE.test(pkt)) { return false; } byte[] buf = pkt.getBuffer(); int off = pkt.getOffset(); int len = pkt.getLength(); if (frameMarkingsExtensionId != -1) { RawPacket.HeaderExtensions hes = pkt.getHeaderExtensions(); while (hes.hasNext()) { RawPacket.HeaderExtension he = hes.next(); if (he.getExtId() == frameMarkingsExtensionId) { return FrameMarkingHeaderExtension.isKeyframe(he); } } if (logger.isDebugEnabled()) { logger.debug("Packet with no frame marking, while frame marking" + " is enabled."); } } REDBlock redBlock = getPayloadBlock(buf, off, len); if (redBlock == null || redBlock.getLength() == 0) { return false; } final byte vp8PT = getDynamicRTPPayloadType(Constants.VP8), h264PT = getDynamicRTPPayloadType(Constants.H264); if (redBlock.getPayloadType() == vp8PT) { return org.jitsi.impl.neomedia.codec.video.vp8.DePacketizer .isKeyFrame(buf, redBlock.getOffset(), redBlock.getLength()); } else if (redBlock.getPayloadType() == h264PT) { return org.jitsi.impl.neomedia.codec.video.h264.DePacketizer .isKeyFrame( redBlock.getBuffer(), redBlock.getOffset(), redBlock.getLength()); } else { return false; } }
Source:
<code>protected void trackScriptEnd(Resource statusResource, String status, String output) { try { ModifiableValueMap properties = statusResource.adaptTo(ModifiableValueMap.class); properties.put(SCRIPT_STATUS, status); properties.put(SCRIPT_DATE_END, Calendar.getInstance()); <START> if (output != null) { <END> properties.put(SCRIPT_OUTPUT, output); } statusResource.getResourceResolver().commit(); } catch (PersistenceException e) { logger.error("On-deploy script status node could not be updated: - status: {}", statusResource.getPath(), status); throw new OnDeployEarlyTerminationException(e); } }</code><technical_language>This properties.put(SCRIPT_OUTPUT, output) if output is null want a successful re-run of a script overwrite field if currently a in it</technical_language>

Target:
protected void trackScriptEnd(Resource statusResource, String status, String output) { try { ModifiableValueMap properties = statusResource.adaptTo(ModifiableValueMap.class); properties.put(SCRIPT_STATUS, status); properties.put(SCRIPT_DATE_END, Calendar.getInstance()); properties.put(SCRIPT_OUTPUT, output); statusResource.getResourceResolver().commit(); } catch (PersistenceException e) { logger.error("On-deploy script status node could not be updated: - status: {}", statusResource.getPath(), status); throw new OnDeployEarlyTerminationException(e); } }
Source:
<code>public Long getDbGeneration(Guid id) { return getCallsHandler().executeRead("GetDbGeneration", <START> new ParameterizedRowMapper<Long>() { <END> @Override public Long mapRow(ResultSet rs, int rowNum) throws SQLException { return rs.getLong(1); }; } , getCustomMapSqlParameterSource() .addValue("vm_guid", id)); }</code><technical_language>move this createLondMapper in BaseDAODbFacade</technical_language>

Target:
public Long getDbGeneration(Guid id) { return getCallsHandler().executeRead("GetDbGeneration", createLongMapper() , getCustomMapSqlParameterSource() .addValue("vm_guid", id)); }
Source:
<code>private IBinding resolveBindingPromiscuous() { if (fBinding == null) { try { CPPSemantics.disablePromiscuousBindingResolution(); resolveBindingNormal(); } finally { CPPSemantics.enablePromiscuousBindingResolution(); } } if (!(fBinding instanceof ProblemBinding)) { return fBinding; } ProblemBinding problem = (ProblemBinding) fBinding; if <START> (problem.getPromiscuousBinding() <END> == null) { IBinding promiscuous = resolveBindingNormal(); problem.setPromiscuousBinding(promiscuous); fBinding = problem; } return problem.getPromiscuousBinding(); }</code><technical_language>write: IBinding promiscuous = problem.getPromiscuousBinding(); if (promiscuous == null) { ... } return promiscuous;</technical_language>

Target:
private IBinding resolveBindingPromiscuous() { if (fBinding == null) { try { CPPSemantics.disablePromiscuousBindingResolution(); resolveBindingNormal(); } finally { CPPSemantics.enablePromiscuousBindingResolution(); } } if (!(fBinding instanceof ProblemBinding)) { return fBinding; } ProblemBinding problem = (ProblemBinding) fBinding; IBinding promiscuous = problem.getPromiscuousBinding(); if (promiscuous == null) { promiscuous = resolveBindingNormal(); problem.setPromiscuousBinding(promiscuous); fBinding = problem; } return promiscuous; }
Source:
<code>List<Tool> refreshToolsForUser(Long userId, String organization, String repository) { refreshBitbucketToken(userId); List<Token> tokens = tokenDAO.findByUserId(userId); Token quayToken = Token.extractToken(tokens, TokenType.QUAY_IO); Token githubToken = Token.extractToken(tokens, TokenType.GITHUB_COM); Token bitbucketToken = Token.extractToken(tokens, TokenType.BITBUCKET_ORG); Token gitlabToken = Token.extractToken(tokens, TokenType.GITLAB_COM); checkTokens(quayToken, githubToken, bitbucketToken, gitlabToken); if (quayToken == null) { throw new CustomWebApplicationException("Missing required Quay.io token", HttpStatus.SC_BAD_REQUEST); } QuayImageRegistry registry = new QuayImageRegistry(quayToken); <START> return new ArrayList<>( <END> registry.refreshTool(userId, userDAO, toolDAO, tagDAO, fileDAO, fileFormatDAO, client, githubToken, bitbucketToken, gitlabToken, organization, eventDAO, dashboardPrefix, repository)); }</code><technical_language>do wrap ArrayList return registry.refreshTool(... directly</technical_language>

Target:
List<Tool> refreshToolsForUser(Long userId, String organization, String repository) { refreshBitbucketToken(userId); List<Token> tokens = tokenDAO.findByUserId(userId); Token quayToken = Token.extractToken(tokens, TokenType.QUAY_IO); Token githubToken = Token.extractToken(tokens, TokenType.GITHUB_COM); Token bitbucketToken = Token.extractToken(tokens, TokenType.BITBUCKET_ORG); Token gitlabToken = Token.extractToken(tokens, TokenType.GITLAB_COM); checkTokens(quayToken, githubToken, bitbucketToken, gitlabToken); if (quayToken == null) { throw new CustomWebApplicationException("Missing required Quay.io token", HttpStatus.SC_BAD_REQUEST); } QuayImageRegistry registry = new QuayImageRegistry(quayToken); return registry.refreshTool(userId, userDAO, toolDAO, tagDAO, fileDAO, fileFormatDAO, client, githubToken, bitbucketToken, gitlabToken, organization, eventDAO, dashboardPrefix, repository); }