auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public boolean matches(ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) { <END> final String value = context.getEnvironment(). getProperty("ot.server.low-resource-monitor.enabled", "true"); return "true".equals(value); }</code><technical_language>I disagree this default. recommend change Boolean.parseBoolean</technical_language>

Target:
public boolean matches(ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) { final String value = context.getEnvironment(). getProperty("ot.server.low-resource-monitor.enabled", "false"); return Boolean.parseBoolean(value); }
Source:
<code>protected void executeVdsBrokerCommand() { String volumeName = getParameters().getVolumeName(); String snapshotName = getParameters().getSnapshotName(); String description = getParameters().getDescription() == null ? "" : getParameters().getDescription(); <START> boolean force = getParameters().getForce() ? true : false; <END> uuidReturn = getBroker().glusterSnapshotCreate(volumeName, snapshotName, description, force); proceedProxyReturnValue(); if (getVDSReturnValue().getSucceeded()) { setReturnValue(Guid.createGuidFromStringDefaultEmpty(uuidReturn.mUuid)); } }</code><technical_language>getForce() returns boolean do need double check</technical_language>

Target:
protected void executeVdsBrokerCommand() { String volumeName = getParameters().getVolumeName(); String snapshotName = getParameters().getSnapshotName(); String description = getParameters().getDescription() == null ? "" : getParameters().getDescription(); boolean force = getParameters().getForce(); uuidReturn = getBroker().glusterSnapshotCreate(volumeName, snapshotName, description, force); proceedProxyReturnValue(); if (getVDSReturnValue().getSucceeded()) { setReturnValue(Guid.createGuidFromStringDefaultEmpty(uuidReturn.mUuid)); } }
Source:
<code>public void testUrlWithNonExistSchema() throws Exception { String url = "jdbc:splice://localhost:1527/splicedb;create=true;user=%s;password=%s;schema=" <START> + "nonexist"; <END> try (Connection connection = SpliceNetConnection.getConnectionAs(url, SpliceNetConnection.DEFAULT_USER, SpliceNetConnection.DEFAULT_USER_PASSWORD)) { Assert.fail("Connect to non exist schema should fail"); } catch (SQLException e) { Assert.assertEquals("Upexpected failure: "+ e.getMessage(), e.getSQLState(), SQLState.LANG_SCHEMA_DOES_NOT_EXIST); } }</code><technical_language>remove "create=true" too</technical_language>

Target:
public void testUrlWithNonExistSchema() throws Exception { String url = "jdbc:splice://localhost:1527/splicedb;user=%s;password=%s;schema=nonexist"; try (Connection connection = SpliceNetConnection.getConnectionAs(url, SpliceNetConnection.DEFAULT_USER, SpliceNetConnection.DEFAULT_USER_PASSWORD)) { Assert.fail("Connect to non exist schema should fail"); } catch (SQLException e) { Assert.assertEquals("Upexpected failure: "+ e.getMessage(), e.getSQLState(), SQLState.LANG_SCHEMA_DOES_NOT_EXIST); } }
Source:
<code>public void update() { FBO readOnlyGBufferFbo = displayResolutionDependentFBOs.get(READONLY_GBUFFER); <START> FBO refractiveReflectiveFbo = displayResolutionDependentFBOs.get(REFRACTIVE_REFLECTIVE); <END> readOnlyGBufferFbo.attachDepthBufferTo(refractiveReflectiveFbo); }</code><technical_language>do this</technical_language>

Target:
public void update() { readOnlyGBufferFbo = displayResolutionDependentFBOs.get(READONLY_GBUFFER); refractiveReflectiveFbo = displayResolutionDependentFBOs.get(REFRACTIVE_REFLECTIVE); readOnlyGBufferFbo.attachDepthBufferTo(refractiveReflectiveFbo); }
Source:
<code>void updateInfo() { DirectionsGenerator gen = new DirectionsGenerator(itinerary.legs, getActivity().getApplicationContext()); List<Direction> directions = gen.getDirections(); Direction direction_data[] = directions.toArray(new Direction[directions.size()]); DirectionExpandableListAdapter adapter = new DirectionExpandableListAdapter( getActivity(), R.layout.list_direction_item, R.layout.list_subdirection_item, direction_data); mDirectionsListView.setAdapter(adapter); mDirectionsListView.setGroupIndicator(null); <START> mRealtimeService.onItinerarySelected(itinerary, rank); <END> }</code><technical_language>want move this onPause(), notification start user leaves view of trip planning results. In some cases, currently notified time I tap tabs for trip plan result, is confusing</technical_language>

Target:
void updateInfo() { DirectionsGenerator gen = new DirectionsGenerator(itinerary.legs, getActivity().getApplicationContext()); List<Direction> directions = gen.getDirections(); Direction direction_data[] = directions.toArray(new Direction[directions.size()]); DirectionExpandableListAdapter adapter = new DirectionExpandableListAdapter( getActivity(), R.layout.list_direction_item, R.layout.list_subdirection_item, direction_data); mDirectionsListView.setAdapter(adapter); mDirectionsListView.setGroupIndicator(null); if(Application.getPrefs() .getBoolean(getString(R.string.preference_key_trip_plan_notifications), true)) { mRealtimeService.onItinerarySelected(itinerary); } }
Source:
<code>private FileList listFiles(PluginTask task) { LOGGER.info("Start listing file with prefix [{}]", task.getPathPrefix()); try { AmazonS3 client = newS3Client(task); String bucketName = task.getBucket(); if (task.getPathPrefix().equals("/")) { LOGGER.info("Listing files with prefix \"/\". This doesn't mean all files in a bucket. If you intend to read all files, use \"path_prefix: ''\" (empty string) instead."); } FileList.Builder builder = new FileList.Builder(task); listS3FilesByPrefix(builder, client, bucketName, task.getPathPrefix(), task.getLastPath(), task.getSkipGlacierObjects()); LOGGER.info("Found total files", builder.size()); return builder.build(); } catch (AmazonServiceException ex) { if (ex.getErrorType().equals(AmazonServiceException.ErrorType.Client)) { if (ex.getStatusCode() != 400 || "ExpiredToken".equalsIgnoreCase(ex.getErrorCode())) { throw new ConfigException(ex); } } throw ex; } catch (InterruptedException | RetryGiveupException ex) { <START> throw new AmazonServiceException(ex.getMessage()); <END> } }</code><technical_language>I wrap exception a library exception is a good idea, is prone for falsehood assumptions (this AmazonServiceException exception requestId, errorCode, statusCode,...). Also, this lost original stacktrace. If re-throw unchecked exception here, I a simple RuntimeException(ex) is sufficient retain information exception chain</technical_language>

Target:
private FileList listFiles(PluginTask task) { LOGGER.info("Start listing file with prefix [{}]", task.getPathPrefix()); try { AmazonS3 client = newS3Client(task); String bucketName = task.getBucket(); if (task.getPathPrefix().equals("/")) { LOGGER.info("Listing files with prefix \"/\". This doesn't mean all files in a bucket. If you intend to read all files, use \"path_prefix: ''\" (empty string) instead."); } FileList.Builder builder = new FileList.Builder(task); listS3FilesByPrefix(builder, client, bucketName, task.getPathPrefix(), task.getLastPath(), task.getSkipGlacierObjects()); LOGGER.info("Found total files", builder.size()); return builder.build(); } catch (AmazonServiceException ex) { if (ex.getErrorType().equals(AmazonServiceException.ErrorType.Client)) { if (ex.getStatusCode() != 400 || "ExpiredToken".equalsIgnoreCase(ex.getErrorCode())) { throw new ConfigException(ex); } } throw ex; } catch (InterruptedException | RetryGiveupException ex) { throw new RuntimeException(ex); } }
Source:
<code>private Long getDeviceId(UserVmVO vm, Long deviceId) { <START> int maxDataVolumesSupported = getMaxDataVolumesSupported(vm); <END> List<VolumeVO> vols = _volsDao.findByInstance(vm.getId()); if (deviceId != null) { if (deviceId.longValue() > maxDataVolumesSupported || deviceId.longValue() == 3) { throw new RuntimeException("deviceId should be 1,2,4-" + maxDataVolumesSupported); } for (VolumeVO vol : vols) { if (vol.getDeviceId().equals(deviceId)) { throw new RuntimeException("deviceId " + deviceId + " is used by vm" + vm.getId()); } } } else { List<String> devIds = new ArrayList<String>(); for (int i = 1; i < maxDataVolumesSupported; i++) { devIds.add(String.valueOf(i)); } devIds.remove("3"); for (VolumeVO vol : vols) { devIds.remove(vol.getDeviceId().toString().trim()); } deviceId = Long.parseLong(devIds.iterator().next()); } return deviceId; }</code><technical_language>Is enough max-data-volumes-supported max device id, device id 3 is used? (or is reserved) E.g. assume getMaxDataVolumesSupported(vm) returns 6. device ids ok in case? 1, 2, 4, 5, 6 (since maxDataVolumesSupported is 6) is a total of 5 data volumes, maxDataVolumesSupported renamed maxDeviceId assigned a of getMaxDataVolumesSupported(vm) + 1 account for unused/reserved id 3</technical_language>

Target:
private Long getDeviceId(UserVmVO vm, Long deviceId) { int maxDeviceId = getMaxDataVolumesSupported(vm) - 1; List<VolumeVO> vols = _volsDao.findByInstance(vm.getId()); if (deviceId != null) { if (deviceId.longValue() <= 0 || deviceId.longValue() > maxDeviceId || deviceId.longValue() == 3) { throw new RuntimeException("deviceId should be 1,2,4-" + maxDeviceId); } for (VolumeVO vol : vols) { if (vol.getDeviceId().equals(deviceId)) { throw new RuntimeException("deviceId " + deviceId + " is used by vm " + vm.getId()); } } } else { List<String> devIds = new ArrayList<String>(); for (int i = 1; i <= maxDeviceId; i++) { devIds.add(String.valueOf(i)); } devIds.remove("3"); for (VolumeVO vol : vols) { devIds.remove(vol.getDeviceId().toString().trim()); } if (devIds.isEmpty()) { throw new RuntimeException("All device Ids are used by vm " + vm.getId()); } deviceId = Long.parseLong(devIds.iterator().next()); } return deviceId; }
Source:
<code>public void createPartControl(Composite aParent) { super.createPartControl(aParent); <START> } <END></code><technical_language>!false == true, I need setting mapper</technical_language>

Target:
public void createPartControl(Composite aParent) { super.createPartControl(aParent); getCommonViewer().setMapper(new ResourceToItemsMapper(getCommonViewer())); }
Source:
<code>public boolean isCancelled() { <START> return false; <END> }</code><technical_language>If this returns false setCancelled is pretty dang useless...</technical_language>

Target:
public boolean isCancelled() { return cancelled; }
Source:
<code>public void queueEvent(Event event) { if (eventFilter.shouldFilter(event)) { log.debug("Filtering event {}", event); return; } modeManager.throwRestEasyExceptionIfInSuspendMode(); log.debug("Queuing event: {}", event); try { <START> initializeMessageSending(); <END> ClientMessage message = session.createMessage(true); String eventString = mapper.writeValueAsString(event); message.getBodyBuffer().writeString(eventString); producer.send(message); } catch (Exception e) { log.error("Error while trying to send event", e); } }</code><technical_language>this wrap/hide session variable accessible instance variable, is returned this method, similar ThreadLocal stores</technical_language>

Target:
public void queueEvent(Event event) { if (eventFilter.shouldFilter(event)) { log.debug("Filtering event {}", event); return; } modeManager.throwRestEasyExceptionIfInSuspendMode(); log.debug("Queuing event: {}", event); try { if (messageSender == null) { messageSender = new EventMessageSender(this.connection); } messageSender.queueMessage(mapper.writeValueAsString(event)); } catch (Exception e) { log.error("Error while trying to send event", e); } }
Source:
<code>private void setupPointTransform( AffineTransform tempTransform, Point centroid, TextStyle2D textStyle, LabelPainter painter) { tempTransform.translate(centroid.getX(), centroid.getY()); double rotation = textStyle.getRotation(); if (Double.isNaN(rotation) || Double.isInfinite(rotation)) { rotation = 0.0; } tempTransform.rotate(rotation); Rectangle2D textBounds = painter.getLabelBounds(); double displacementX = (textStyle.getAnchorX() * (-textBounds.getWidth())) + textStyle.getDisplacementX(); double displacementY = (textStyle.getAnchorY() * (textBounds.getHeight())) - textStyle.getDisplacementY() - textBounds.getHeight() <START> + ((painter.lines.size() == 1) <END> ? painter.getLineHeight() : painter.getLastLineHeight()); tempTransform.translate(displacementX, displacementY); }</code><technical_language>I right area fix, change works fine for y anchor equals 0, for top alignment. if bottom alignment asked line significantly smaller instead? Try following, change y anchor 1, string "Espace\nabcd ef", result is this (with code changes in): ![selezione_577](<LINK_0> code change instead: ![image](<LINK_1> I code sensitive anchor value, for cases a human visible alignment is evident: - if anchorY is 1 (or close, a tolerance), line height - if anchorY is 0 (or close, a tolerance), line height - for other value, average line height instead, care for 0.5 anchor case better, others verifiable</technical_language>

Target:
private void setupPointTransform( AffineTransform tempTransform, Point centroid, TextStyle2D textStyle, LabelPainter painter) { tempTransform.translate(centroid.getX(), centroid.getY()); double rotation = textStyle.getRotation(); if (Double.isNaN(rotation) || Double.isInfinite(rotation)) { rotation = 0.0; } tempTransform.rotate(rotation); Rectangle2D textBounds = painter.getLabelBounds(); double displacementX = (textStyle.getAnchorX() * (-textBounds.getWidth())) + textStyle.getDisplacementX(); double displacementY = (textStyle.getAnchorY() * (textBounds.getHeight())) - textStyle.getDisplacementY() - textBounds.getHeight() + ((painter.lines.size() == 1) ? painter.getLineHeight() : painter.getLineHeightForAnchorY(textStyle.getAnchorY())); tempTransform.translate(displacementX, displacementY); }
Source:
<code>private Map<String, String> parseConfig(String[] fertilizerList, ImmutableMap.Builder<ItemStack, Integer> fertilizerMap){ Map<String, String> configEntries = new HashMap<>(); for(String entry : fertilizerList){ String[] spited = entry.split(";"); if(spited.length < 2){ <START> Log.error("Foretsry failed to parse a entry of the fertilizer config."); <END> continue; } String itemName = spited[0]; ItemStack fertilizerItem = ItemStackUtil.parseItemStackString(itemName, OreDictionary.WILDCARD_VALUE); if(fertilizerItem == null || fertilizerItem.isEmpty()){ Log.error("Foretsry failed to parse a entry of the fertilizer config, because the item doesn't exists."); continue; } String value = spited[1]; int fertilizerValue = Integer.parseInt(value); if(fertilizerValue > 0) { fertilizerMap.put(fertilizerItem, fertilizerValue); } configEntries.put(itemName, value); } return configEntries; }</code><technical_language>Foretsry typo</technical_language>

Target:
private Map<String, String> parseConfig(String[] fertilizerList, ImmutableMap.Builder<ItemStack, Integer> fertilizerMap){ Map<String, String> configEntries = new HashMap<>(); for(String entry : fertilizerList){ String[] spited = entry.split(";"); if(spited.length < 2){ Log.error("Forestry failed to parse a entry of the fertilizer config."); continue; } String itemName = spited[0]; ItemStack fertilizerItem = ItemStackUtil.parseItemStackString(itemName, OreDictionary.WILDCARD_VALUE); if(fertilizerItem == null || fertilizerItem.isEmpty()){ Log.error("Forestry failed to parse a entry of the fertilizer config, because the item doesn't exists."); continue; } String value = spited[1]; int fertilizerValue = Integer.parseInt(value); if(fertilizerValue > 0) { fertilizerMap.put(fertilizerItem, fertilizerValue); } configEntries.put(itemName, value); } return configEntries; }
Source:
<code>public static String prettyPrintTime(long time, TimeUnit unit) { long nanos = unit.toNanos(time); <START> if (nanos < 10000) return nanos + " ns"; <END> long micros = unit.toMicros(time); if (micros < 10000) return micros + " us"; long millis = unit.toMillis(time); if (millis < 1000) return millis + " ms"; NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); double toPrint = ((double) millis) / 1000; if (toPrint < 300) { return nf.format(toPrint) + " seconds"; } toPrint = toPrint / 60; if (toPrint < 120) { return nf.format(toPrint) + " minutes"; } toPrint = toPrint / 60; return nf.format(toPrint) + " hours"; }</code><technical_language>1000</technical_language>

Target:
public static String prettyPrintTime(long time, TimeUnit unit) { NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); if (unit.toNanos(time) < 1000) return nf.format(convert(time, unit, TimeUnit.NANOSECONDS)) + " ns"; if (unit.toMicros(time) < 1000) return nf.format(convert(time, unit, TimeUnit.MICROSECONDS)) + " us"; if (unit.toMillis(time) < 1000) return nf.format(convert(time, unit, TimeUnit.MILLISECONDS)) + " ms"; if (unit.toSeconds(time) < 300) return nf.format(convert(time, unit, TimeUnit.SECONDS)) + " seconds"; if (unit.toMinutes(time) < 120) return nf.format(convert(time, unit, TimeUnit.MINUTES)) + " minutes"; return nf.format(convert(time, unit, TimeUnit.HOURS)) + " hours"; }
Source:
<code>private RequestController suspendedRCWithQueuedTasks(int i, Runnable whenExecuted) { RequestController _ret = new RequestController(false); <START> _ret.suspended(() -> { <END> }); for (int taskNo = 0; taskNo < TASKS_QTY; taskNo++) { _ret.queueTask(null, null, task -> whenExecuted.run(), 0, null, false, false); } return _ret; }</code><technical_language>please rename _ret variables ? remaining request I merge this PR. thanks</technical_language>

Target:
private RequestController suspendedRCWithQueuedTasks(int i, Runnable whenExecuted) { RequestController requestController = new RequestController(false); requestController.suspended(() -> { }); for (int taskNo = 0; taskNo < TASKS_QTY; taskNo++) { requestController.queueTask(null, null, task -> whenExecuted.run(), 0, null, false, false); } return requestController; }
Source:
<code>private void setPointShapeProperty(String newValue) { int pointShape = Integer.parseInt(newValue); <START> if (chartDataModel instanceof MockScatterChartDataModel) { <END> ((MockScatterChartDataModel)chartDataModel).changePointShape(pointShape); } }</code><technical_language>want support this line charts well, consider moving definition of changePointShape superclass a default behavior of nothing, line scatter chart types do behavior</technical_language>

Target:
private void setPointShapeProperty(String newValue) { int pointShape = Integer.parseInt(newValue); if (chartDataModel instanceof MockPointChartDataModel) { ((MockPointChartDataModel) chartDataModel).changePointShape(pointShape); } }
Source:
<code>public Producer<String, String> takeProducer() { rwLock.readLock().lock(); try { if (null != activeProducer) { useCount.get(activeProducer).incrementAndGet(); return activeProducer; } } finally { rwLock.readLock().unlock(); } rwLock.writeLock().lock(); try { if (null != activeProducer) { useCount.get(activeProducer).incrementAndGet(); return activeProducer; } <START> activeProducer = new KafkaProducer<>(kafkaLocationManager.getKafkaProducerProperties()); <END> useCount.put(activeProducer, new AtomicInteger(1)); return activeProducer; } finally { rwLock.writeLock().unlock(); } }</code><technical_language>life easier if logged a new broker is created deleted in line 70</technical_language>

Target:
public Producer<String, String> takeProducer() { Producer<String, String> result = takeUnderLock(false); if (null == result) { result = takeUnderLock(true); } useCountMetric.inc(); return result; }
Source:
<code>public LogisticRegSummary decode(final byte[] data) { final ByteArrayInputStream bais = new ByteArrayInputStream(data); final LinearModel model; final int count; final int posNum; <START> final int negNum; <END> try (final DataInputStream dais = new DataInputStream(bais)) { count = dais.readInt(); posNum = dais.readInt(); negNum = dais.readInt(); model = sparseLinearModelCodec.decodeFromStream(dais); } catch (final IOException e) { throw new RuntimeException(e.getCause()); } return new LogisticRegSummary(model, count, posNum, negNum); }</code><technical_language>declared try block, return statement</technical_language>

Target:
public LogisticRegSummary decode(final byte[] data) { try (final DataInputStream dais = new DataInputStream(new ByteArrayInputStream(data))) { final int count = dais.readInt(); final int posNum = dais.readInt(); final int negNum = dais.readInt(); final LinearModel model = sparseLinearModelCodec.decodeFromStream(dais); return new LogisticRegSummary(model, count, posNum, negNum); } catch (final IOException e) { throw new RuntimeException(e.getCause()); } }
Source:
<code>public ParameterMetadataImpl( Map<Integer,OrdinalParameterDescriptor> ordinalDescriptorMap, Map<String, NamedParameterDescriptor> namedDescriptorMap) { this.ordinalDescriptorMap = ordinalDescriptorMap == null ? Collections.emptyMap() : Collections.unmodifiableMap( ordinalDescriptorMap ); <START> this.ordinalDescriptorValueCache = ordinalDescriptorMap == null <END> ? Collections.emptySet() : Collections.unmodifiableSet(new HashSet<>(this.ordinalDescriptorMap.values())); this.namedDescriptorMap = namedDescriptorMap == null ? Collections.emptyMap() : Collections.unmodifiableMap( namedDescriptorMap ); this.namedDescriptorValueCache = namedDescriptorMap == null ? Collections.emptySet() : Collections.unmodifiableSet(new HashSet<>(this.namedDescriptorMap.values())); if (ordinalDescriptorMap != null && ! ordinalDescriptorMap.isEmpty() ) { final List<Integer> sortedPositions = new ArrayList<>( ordinalDescriptorMap.keySet() ); sortedPositions.sort( ComparableComparator.INSTANCE ); int lastPosition = -1; for ( Integer sortedPosition : sortedPositions ) { if ( lastPosition == -1 ) { lastPosition = sortedPosition; continue; } if ( sortedPosition != lastPosition + 1 ) { throw new QueryException( String.format( Locale.ROOT, "Unexpected gap in ordinal parameter labels [%s -> %s] : [%s]", lastPosition, sortedPosition, StringHelper.join( ",", sortedPositions.iterator() ) ) ); } lastPosition = sortedPosition; } } }</code><technical_language>this.ordinalDescriptorMap test if is empty. remark for one</technical_language>

Target:
public ParameterMetadataImpl( Map<Integer,OrdinalParameterDescriptor> ordinalDescriptorMap, Map<String, NamedParameterDescriptor> namedDescriptorMap) { this.ordinalDescriptorMap = ordinalDescriptorMap == null ? Collections.emptyMap() : Collections.unmodifiableMap( ordinalDescriptorMap ); this.ordinalDescriptorValueCache = this.ordinalDescriptorMap.isEmpty() ? Collections.emptySet() : Collections.unmodifiableCollection( this.ordinalDescriptorMap.values() ); this.namedDescriptorMap = namedDescriptorMap == null ? Collections.emptyMap() : Collections.unmodifiableMap( namedDescriptorMap ); this.namedDescriptorValueCache = this.namedDescriptorMap.isEmpty() ? Collections.emptySet() : Collections.unmodifiableCollection( this.namedDescriptorMap.values() ); if (ordinalDescriptorMap != null && ! ordinalDescriptorMap.isEmpty() ) { final List<Integer> sortedPositions = new ArrayList<>( ordinalDescriptorMap.keySet() ); sortedPositions.sort( ComparableComparator.INSTANCE ); int lastPosition = -1; for ( Integer sortedPosition : sortedPositions ) { if ( lastPosition == -1 ) { lastPosition = sortedPosition; continue; } if ( sortedPosition != lastPosition + 1 ) { throw new QueryException( String.format( Locale.ROOT, "Unexpected gap in ordinal parameter labels [%s -> %s] : [%s]", lastPosition, sortedPosition, StringHelper.join( ",", sortedPositions.iterator() ) ) ); } lastPosition = sortedPosition; } } }
Source:
<code>protected static void openEditor(final IWorkbenchPage page, final EditorHandle handle, final IBuild build, final boolean partial) { <START> Display.getDefault().syncExec(new Runnable() { <END> public void run() { if (!page.getWorkbenchWindow().getShell().isDisposed()) { BuildEditorInput input = new BuildEditorInput(build, partial); try { IEditorPart part = page.openEditor(input, BuildsUiConstants.ID_EDITOR_BUILDS); handle.setPart(part); handle.setStatus(Status.OK_STATUS); } catch (PartInitException e) { IStatus status = new Status(IStatus.ERROR, BuildsUiPlugin.ID_PLUGIN, "Unexpected error while opening build", e); StatusHandler.log(status); handle.setStatus(status); } } } }); }</code><technical_language>this code executed UI thread? syncExec() needed</technical_language>

Target:
protected static void openEditor(final IWorkbenchPage page, final EditorHandle handle, final IBuild build, final boolean partial) { BuildEditorInput input = new BuildEditorInput(build, partial); try { IEditorPart part = page.openEditor(input, BuildsUiConstants.ID_EDITOR_BUILDS); handle.setPart(part); handle.setStatus(Status.OK_STATUS); } catch (PartInitException e) { IStatus status = new Status(IStatus.ERROR, BuildsUiPlugin.ID_PLUGIN, "Unexpected error while opening build", e); StatusHandler.log(status); handle.setStatus(status); } }
Source:
<code>public void tearDown() { <START> System.out.println("Stopping the worker.."); <END> workerApplicationContext.close(); }</code><technical_language>system.outs</technical_language>

Target:
public void tearDown() throws Exception { this.workerApplicationContext.close(); this.brokerService.stop(); }
Source:
<code>public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (targetChannel.isRequestWritten()) { if (msg instanceof HttpResponse) { targetRespMsg = setUpCarbonMessage(ctx, msg); if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor(). executeAtTargetResponseReceiving(targetRespMsg); } if (this.httpResponseFuture != null) { try { httpResponseFuture.notifyHttpListener(targetRespMsg); } catch (Exception e) { LOG.error("Error while notifying response to listener ", e); } } else { LOG.error("Cannot correlate callback with request callback is null"); } } else { if (targetRespMsg != null) { HttpContent httpContent = (HttpContent) msg; targetRespMsg.addHttpContent(httpContent); if (msg instanceof LastHttpContent) { <START> if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { <END> HTTPTransportContextHolder.getInstance().getHandlerExecutor(). executeAtTargetResponseSending(targetRespMsg); } targetChannel.getChannel().pipeline().remove(Constants.IDLE_STATE_HANDLER); connectionManager.returnChannel(targetChannel); } } } } else { if (msg instanceof HttpResponse) { LOG.warn("Received a response for an obsolete request"); } ReferenceCountUtil.release(msg); } }</code><technical_language>a practice, get of "HTTPTransportContextHolder.getInstance().getHandlerExecutor()" a variable, variable that, lookup twice. expensive operation, still, for readability, if in critical path, performance wise, if lookup expensive</technical_language>

Target:
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (targetChannel.isRequestWritten()) { if (msg instanceof HttpResponse) { targetRespMsg = setUpCarbonMessage(ctx, msg); if (handlerExecutor != null) { handlerExecutor.executeAtTargetResponseReceiving(targetRespMsg); } if (this.httpResponseFuture != null) { try { httpResponseFuture.notifyHttpListener(targetRespMsg); } catch (Exception e) { LOG.error("Error while notifying response to listener ", e); } } else { LOG.error("Cannot correlate callback with request callback is null"); } } else { if (targetRespMsg != null) { HttpContent httpContent = (HttpContent) msg; targetRespMsg.addHttpContent(httpContent); if (Util.isLastHttpContent(httpContent)) { if (handlerExecutor != null) { handlerExecutor.executeAtTargetResponseSending(targetRespMsg); } targetChannel.getChannel().pipeline().remove(Constants.IDLE_STATE_HANDLER); connectionManager.returnChannel(targetChannel); } } } } else { if (msg instanceof HttpResponse) { LOG.warn("Received a response for an obsolete request"); } ReferenceCountUtil.release(msg); } }
Source:
<code>public static <T> ReplaySubject<T> create(int capacity) { final ReplayState<T, Integer> state; if (capacity <= 0 || capacity > 1) { state = new UnboundedReplayState<T>(capacity); } else { <START> state = new SingleValueReplayState<T>(capacity); <END> } SubjectSubscriptionManager<T> ssm = new SubjectSubscriptionManager<T>(); ssm.onStart = new Action1<SubjectObserver<T>>() { @Override public void call(SubjectObserver<T> o) { int lastIndex = state.replayObserverFromIndex(0, o); o.index(lastIndex); } }; ssm.onTerminated = new Action1<SubjectObserver<T>>() { @Override public void call(SubjectObserver<T> o) { Integer idx = o.index(); if (idx == null) { idx = 0; } state.replayObserverFromIndex(idx, o); } }; return new ReplaySubject<T>(ssm, ssm, state); }</code><technical_language>This unnecessary case replicates unbounded replay behavior default capacity 2</technical_language>

Target:
public static <T> ReplaySubject<T> create(int capacity) { final ReplayState<T, Integer> state; if (capacity <= 0 || capacity > 1) { state = new UnboundedReplayState<T>(capacity); } else { state = new SingleItemReplayState<T>(); } SubjectSubscriptionManager<T> ssm = new SubjectSubscriptionManager<T>(); ssm.onStart = new Action1<SubjectObserver<T>>() { @Override public void call(SubjectObserver<T> o) { int lastIndex = state.replayObserverFromIndex(0, o); o.index(lastIndex); } }; ssm.onTerminated = new Action1<SubjectObserver<T>>() { @Override public void call(SubjectObserver<T> o) { Integer idx = o.index(); if (idx == null) { idx = 0; } state.replayObserverFromIndex(idx, o); } }; return new ReplaySubject<T>(ssm, ssm, state); }
Source:
<code>public static void setup() { data = new DummyPOJO(); laggards = new DummyLaggards(); try { laggards.clazz = Class.forName("com.datatorrent.lib.laggards.LaggardsTest$DummyPOJO"); } catch (ClassNotFoundException e) { <START> logger.error("CLASS NOT FOUND: com.datatorrent.lib.laggards.LaggardsTest$DummyPOJO"); <END> } }</code><technical_language>throw runtime exception</technical_language>

Target:
public static void setup() { data = new DummyPOJO(); laggards = new DummyLaggards(); laggards.clazz = DummyPOJO.class; }
Source:
<code>public ChannelGroup transform(org.atlasapi.media.entity.simple.ChannelGroup simple) { Platform complex = new Platform(); <START> if (Strings.isNullOrEmpty(simple.getId())) { <END> complex.setId(idCodec.decode(simple.getId()).longValue()); } complex.setPublisher(getPublisher(simple.getPublisherDetails())); complex.addTitle(simple.getTitle()); complex.setAvailableCountries(Countries.fromCodes(simple.getAvailableCountries())); return complex; }</code><technical_language>I this negated if (!Strings.isNullOrEmpty(simple.getId())) { adds null ignores null</technical_language>

Target:
public ChannelGroup transform(org.atlasapi.media.entity.simple.ChannelGroup simple) { Platform complex = new Platform(); if (!Strings.isNullOrEmpty(simple.getId())) { complex.setId(idCodec.decode(simple.getId()).longValue()); } complex.setPublisher(extractPublisher(simple.getPublisherDetails())); complex.addTitle(simple.getTitle()); complex.setAvailableCountries(Countries.fromCodes(simple.getAvailableCountries())); return complex; }
Source:
<code>private String makeUrl(ContainerPort port, String protocol, String path, String hostname) { if (protocol == null) { if (port.getType() == null) { protocol = "tcp"; } else { protocol = port.getType(); } } if (path == null) { path = ""; } else if (!path.startsWith("/")) { path = '/' + path; } int serverPort = port.getPublicPort() != 0 ? port.getPublicPort() : port.getPrivatePort(); <START> return protocol + "://" + hostname + ':' + serverPort + path; <END> }</code><technical_language>UriBuilder here</technical_language>

Target:
private String makeUrl(ContainerPort port, String protocol, String path, String hostname) throws InternalInfrastructureException { if (protocol == null) { if (port.getType() == null) { protocol = "tcp"; } else { protocol = port.getType(); } } if (path == null) { path = ""; } else if (!path.startsWith("/")) { path = '/' + path; } int serverPort = port.getPublicPort() != 0 ? port.getPublicPort() : port.getPrivatePort(); try { return new URI(protocol, null, hostname, serverPort, path, null, null).toString(); } catch (URISyntaxException e) { throw new InternalInfrastructureException( "Constructing of URI of server failed. Error: " + e.getLocalizedMessage()); } }
Source:
<code>public String create(Request request, Response response) { final BasicEnvironmentConfig environmentConfigToCreate = (BasicEnvironmentConfig) buildEntityFromRequestBody(request); final HttpLocalizedOperationResult operationResult = new HttpLocalizedOperationResult(); if (!environmentConfigToCreate.getAllErrors().isEmpty()) { operationResult.unprocessableEntity("Error parsing environment config from the request"); <START> return handleCreateOrUpdateResponse(request, response, environmentConfigToCreate, operationResult); <END> } haltIfEntityWithSameNameExists(environmentConfigToCreate); environmentConfigService.createEnvironment(environmentConfigToCreate, currentUsername(), operationResult); setEtagHeader(environmentConfigToCreate, response); return handleCreateOrUpdateResponse(request, response, environmentConfigToCreate, operationResult); }</code><technical_language>maybe, this check of request-body validation</technical_language>

Target:
public String create(Request request, Response response) { final BasicEnvironmentConfig environmentConfigToCreate = (BasicEnvironmentConfig) buildEntityFromRequestBody(request); final HttpLocalizedOperationResult operationResult = new HttpLocalizedOperationResult(); haltIfEntityWithSameNameExists(environmentConfigToCreate); if (!environmentConfigToCreate.getAllErrors().isEmpty()) { operationResult.unprocessableEntity("Error parsing environment config from the request"); return handleCreateOrUpdateResponse(request, response, environmentConfigToCreate, operationResult); } environmentConfigService.createEnvironment(environmentConfigToCreate, currentUsername(), operationResult); setEtagHeader(environmentConfigToCreate, response); return handleCreateOrUpdateResponse(request, response, environmentConfigToCreate, operationResult); }
Source:
<code>public void run() { try { while (run || !queue.isEmpty()) { Event event = queue.poll(100, <START> TimeUnit.MILLISECONDS); <END> if (event == null) { continue; } List<Event> events = new ArrayList<>(bufferSize); events.add(event); queue.drainTo(events, bufferSize - 1); this.sender.push(events); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }</code><technical_language>static import</technical_language>

Target:
public void run() { try { while (run || !queue.isEmpty()) { Event event = queue.poll(100, MILLISECONDS); if (event == null) { continue; } List<Event> events = new ArrayList<>(bufferSize); events.add(event); queue.drainTo(events, bufferSize - 1); this.sender.push(events); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
Source:
<code>protected void assertTenantOrParentTenant(TenantAware tenantAware) { if (tenantAware == null) { return; } if (!tenantAware.getTenant().is(currentTenant()) && !tenantAware.getTenant() <START> .is(currentTenant().getParent().getValue())) { <END> throw Exceptions.createHandled().withNLSKey("BizController.invalidTenant").handle(); } }</code><technical_language>getParent().getId()</technical_language>

Target:
protected void assertTenantOrParentTenant(TenantAware tenantAware) { if (tenantAware == null) { return; } if (!tenantAware.getTenant().is(currentTenant()) && tenantAware.getTenant().getId() != currentTenant().getParent().getId()) { throw Exceptions.createHandled().withNLSKey("BizController.invalidTenant").handle(); } }
Source:
<code>private void initStore() { ColumnChunkPageWriteStore columnChunkPageWriteStore = new ColumnChunkPageWriteStore(compressor, <START> schema, props.getAllocator(), props.getColumnIndexTruncateLength()); <END> pageStore = columnChunkPageWriteStore; bloomFilterWriteStore = columnChunkPageWriteStore; columnStore = props.newColumnWriteStore(schema, pageStore, bloomFilterWriteStore); MessageColumnIO columnIO = new ColumnIOFactory(validating).getColumnIO(schema); this.recordConsumer = columnIO.getRecordWriter(columnStore); writeSupport.prepareForWrite(recordConsumer); }</code><technical_language>a regression in merge: checksum flag is missing</technical_language>

Target:
private void initStore() { ColumnChunkPageWriteStore columnChunkPageWriteStore = new ColumnChunkPageWriteStore(compressor, schema, props.getAllocator(), props.getColumnIndexTruncateLength(), props.getPageWriteChecksumEnabled()); pageStore = columnChunkPageWriteStore; bloomFilterWriteStore = columnChunkPageWriteStore; columnStore = props.newColumnWriteStore(schema, pageStore, bloomFilterWriteStore); MessageColumnIO columnIO = new ColumnIOFactory(validating).getColumnIO(schema); this.recordConsumer = columnIO.getRecordWriter(columnStore); writeSupport.prepareForWrite(recordConsumer); }
Source:
<code>public static Set<DistributionModuleGroup> getModuleGroups() { Set<DistributionModuleGroup> hs = new HashSet<>(); hs.add(new DistributionModuleGroup(CDH5120Constant.HDFS_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(CDH5120Constant.MAPREDUCE_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(CDH5120Constant.MAPREDUCE_PARQUET_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(CDH5120Constant.MAPREDUCE_PARQUET_MRREQUIRED_MODULE_GROUP.getModuleName(), true, null)); <START> ComponentCondition conditionUseNavigator = new SimpleComponentCondition(new BasicExpression( <END> MRConstant.USE_CLOUDERA_NAVIGATOR)); hs.add(new DistributionModuleGroup(CDH5120Constant.TALEND_CLOUDERA_CDH_5_12_NAVIGATOR.getModuleName(), true, conditionUseNavigator)); return hs; }</code><technical_language>add navigator's dependencies this is supported</technical_language>

Target:
public static Set<DistributionModuleGroup> getModuleGroups() { Set<DistributionModuleGroup> hs = new HashSet<>(); hs.add(new DistributionModuleGroup(CDH5120Constant.HDFS_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(CDH5120Constant.MAPREDUCE_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(CDH5120Constant.MAPREDUCE_PARQUET_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(CDH5120Constant.MAPREDUCE_PARQUET_MRREQUIRED_MODULE_GROUP.getModuleName(), true, null)); END_CLOUDERA_CDH_5_12_NAVIGATOR.getModuleName(), return hs; }
Source:
<code>public String getRegionName() { List<String> rg = getRegionNames(); if (rg.size() == 0) { rg.add(file.getName()); } String ls = rg.get(0); if (ls.lastIndexOf('_') != -1) { if (!ls.endsWith(".obf") || !ls.matches(".*\\d+.*")) { return ls.substring(0, ls.lastIndexOf('_')).replace('_', ' '); <START> } else if (ls.matches("[a-zA-Z_-]+([0-9]+_*){3}[.a-z]+")){ <END> String res = ls.substring(0, (ls.length() - 13)); return res.substring(0, res.lastIndexOf('_')).replace('_', ' '); } } return ls; }</code><technical_language>Please remove regex ambiguous numbers "13" ? code easy read & verify is totally cumbersome</technical_language>

Target:
public String getRegionName() { List<String> rg = getRegionNames(); if (rg.size() == 0) { rg.add(file.getName()); } String ls = rg.get(0); if (ls.lastIndexOf('_') != -1) { if (ls.matches(".*([0-9]+_*){3}\\.obf")) { Pattern osmDiffDateEnding = Pattern.compile("_([0-9]+_*){3}\\.obf"); Matcher m = osmDiffDateEnding.matcher(ls); if (m.find()) { ls = ls.substring(0, m.start()); } return ls.substring(0, ls.lastIndexOf('_')).replace('_', ' '); } else { if (ls.contains(".")) { ls = ls.substring(0, ls.indexOf(".")); } if (ls.endsWith("_2")) { ls = ls.substring(0, ls.length() - "_2".length()); } return ls.substring(0, ls.lastIndexOf('_')).replace('_', ' '); } } return ls; }
Source:
<code>protected Position handlePosition(Position position) { Collection<Attribute> attributes = Context.getAttributesManager().getItems( Context.getAttributesManager().getAllDeviceItems(position.getDeviceId())); for (Attribute attribute : attributes) { if (attribute.getAttribute() != null) { Object result = null; try { result = computeAttribute(attribute, position); } catch (JexlException error) { Log.warning(error); } if (result != null) { try { switch (attribute.getType()) { case "number": <START> if (attribute.getAttribute().equals(false)) { <END> position.getAttributes().remove(attribute.getAttribute()); } else { position.getAttributes().put(attribute.getAttribute(), (Number) result); } break; case "boolean": position.getAttributes().put(attribute.getAttribute(), (Boolean) result); break; default: if (attribute.getAttribute().equals(false)) { position.getAttributes().remove(attribute.getAttribute()); } else { position.getAttributes().put(attribute.getAttribute(), result.toString()); } } } catch (ClassCastException error) { Log.warning(error); } } else { position.getAttributes().remove(attribute.getAttribute()); } } } return position; }</code><technical_language>equal false if a number? I missing something? question for default case well</technical_language>

Target:
protected Position handlePosition(Position position) { Collection<Attribute> attributes = Context.getAttributesManager().getItems( Context.getAttributesManager().getAllDeviceItems(position.getDeviceId())); for (Attribute attribute : attributes) { if (attribute.getAttribute() != null) { Object result = null; try { result = computeAttribute(attribute, position); } catch (JexlException error) { Log.warning(error); return position; } if (result != null) { try { switch (attribute.getType()) { case "number": if (attribute.getAttribute().equals(false) || attribute.getAttribute().equals(true)) { throw new IllegalArgumentException( "Number Attribute Type was returned Boolean instead of Number"); } else { position.getAttributes().put(attribute.getAttribute(), (Number) result); } break; case "boolean": position.getAttributes().put(attribute.getAttribute(), (Boolean) result); break; default: if (attribute.getAttribute().equals(false) || attribute.getAttribute().equals(true)) { throw new IllegalArgumentException( "Default Attribute Type was returned Boolean instead of String"); } else { position.getAttributes().put(attribute.getAttribute(), result.toString()); } } } catch (ClassCastException | IllegalArgumentException error) { Log.warning(error); } } else { position.getAttributes().remove(attribute.getAttribute()); } } } return position; }
Source:
<code>public void setEnvironmentalVariables(final Map<String, String> envVbles) { <START> configure(); <END> String envVblesAsString = ""; if (envVbles != null) { for (Map.Entry<String, String> envVble : envVbles.entrySet()) { envVblesAsString += String.format("%s=%s\n", envVble.getKey(), envVble.getValue()); } } this.properties.set(envVblesAsString); save(); }</code><technical_language>this do configure save</technical_language>

Target:
public void setEnvironmentalVariables(final Map<String, String> envVbles) { String envVblesAsString = ""; if (envVbles != null) { for (Map.Entry<String, String> envVble : envVbles.entrySet()) { envVblesAsString += String.format("%s=%s\n", envVble.getKey(), envVble.getValue()); } } this.properties.set(envVblesAsString); }
Source:
<code>public COL get() { if (parsed==null) { synchronized (this) { if (parsed==null) { try { load(); } catch (IOException e) { <START> throw new RuntimeException(e); <END> } } } } return parsed; }</code><technical_language>preferable create a new method error propagation</technical_language>

Target:
public COL get() { if (parsed==null) { synchronized (this) { if (parsed==null) { load(); } } } return parsed; }
Source:
<code>public void close(Duration timeout) { long waitTimeMs = timeout.toMillis(); if (waitTimeMs < 0) throw new IllegalArgumentException("The timeout cannot be negative."); waitTimeMs = Math.min(TimeUnit.DAYS.toMillis(365), waitTimeMs); long now = time.milliseconds(); long newHardShutdownTimeMs = now + waitTimeMs; long prev = INVALID_SHUTDOWN_TIME; while (true) { if (hardShutdownTimeMs.compareAndSet(prev, newHardShutdownTimeMs)) { if (prev == INVALID_SHUTDOWN_TIME) { log.debug("Initiating close operation."); } else { log.debug("Moving hard shutdown time forward."); } client.wakeup(); break; } prev = hardShutdownTimeMs.get(); if (prev < newHardShutdownTimeMs) { log.debug("Hard shutdown time is already earlier than requested."); newHardShutdownTimeMs = prev; break; } } if (log.isDebugEnabled()) { long deltaMs = Math.max(0, newHardShutdownTimeMs - time.milliseconds()); log.debug("Waiting for the I/O thread to exit. Hard shutdown in ms.", deltaMs); } try { if (Thread.currentThread() != thread) { <START> thread.join(); <END> } log.debug("Kafka admin client closed."); } catch (InterruptedException e) { log.debug("Interrupted while joining I/O thread", e); Thread.currentThread().interrupt(); } }</code><technical_language>passing close timeout join</technical_language>

Target:
public void close(Duration timeout) { long waitTimeMs = timeout.toMillis(); if (waitTimeMs < 0) throw new IllegalArgumentException("The timeout cannot be negative."); waitTimeMs = Math.min(TimeUnit.DAYS.toMillis(365), waitTimeMs); long now = time.milliseconds(); long newHardShutdownTimeMs = now + waitTimeMs; long prev = INVALID_SHUTDOWN_TIME; while (true) { if (hardShutdownTimeMs.compareAndSet(prev, newHardShutdownTimeMs)) { if (prev == INVALID_SHUTDOWN_TIME) { log.debug("Initiating close operation."); } else { log.debug("Moving hard shutdown time forward."); } client.wakeup(); break; } prev = hardShutdownTimeMs.get(); if (prev < newHardShutdownTimeMs) { log.debug("Hard shutdown time is already earlier than requested."); newHardShutdownTimeMs = prev; break; } } if (log.isDebugEnabled()) { long deltaMs = Math.max(0, newHardShutdownTimeMs - time.milliseconds()); log.debug("Waiting for the I/O thread to exit. Hard shutdown in ms.", deltaMs); } try { if (Thread.currentThread() != thread) { thread.join(waitTimeMs); } log.debug("Kafka admin client closed."); } catch (InterruptedException e) { log.debug("Interrupted while joining I/O thread", e); Thread.currentThread().interrupt(); } }
Source:
<code>public Map<String, Object> getProperties() { <START> return UnmodifiableMap.decorate(properties); <END> }</code><technical_language>is benefit compared Collections.unmodifiableMap</technical_language>

Target:
public Map<String, Object> getProperties() { return Collections.unmodifiableMap(properties); }
Source:
<code>public MissingOverride() { <START> this.ignoreInterfaceOverrides = false; <END> }</code><technical_language>default (i.e., false) in place replacing this constructor implementation this(ErrorProneFlags.empty());</technical_language>

Target:
public MissingOverride() { this(ErrorProneFlags.empty()); }