auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SuccessResponse updateInstanceTags( @ApiParam(value = "Instance name", required = true, example = "Server_a.b.com_20000 | Broker_my.broker.com_30000") @PathParam("instanceName") String instanceName, @ApiParam(value = "Comma separated tags list", required = true) @QueryParam("tags") String tags) { <START> LOGGER.info("Instance update request received for instance: {}", instanceName); <END> if (tags == null) { throw new ControllerApplicationException(LOGGER, "Must provide tags to update", Response.Status.BAD_REQUEST); } PinotResourceManagerResponse response = pinotHelixResourceManager.updateInstanceTags(instanceName, tags); if (!response.isSuccessful()) { throw new ControllerApplicationException(LOGGER, "Failure to update instance tags. Reason: " + response.getMessage(), Response.Status.INTERNAL_SERVER_ERROR); } return new SuccessResponse("Instance successfully updated"); }</code><technical_language>log tags</technical_language>

Target:
public SuccessResponse updateInstanceTags( @ApiParam(value = "Instance name", required = true, example = "Server_a.b.com_20000 | Broker_my.broker.com_30000") @PathParam("instanceName") String instanceName, @ApiParam(value = "Comma separated tags list", required = true) @QueryParam("tags") String tags) { LOGGER.info("Instance update request received for instance: and tags: {}", instanceName, tags); if (tags == null) { throw new ControllerApplicationException(LOGGER, "Must provide tags to update", Response.Status.BAD_REQUEST); } PinotResourceManagerResponse response = pinotHelixResourceManager.updateInstanceTags(instanceName, tags); if (!response.isSuccessful()) { throw new ControllerApplicationException(LOGGER, "Failure to update instance: " + instanceName + " with tags: " + tags + ". Reason: " + response.getMessage(), Response.Status.INTERNAL_SERVER_ERROR); } return new SuccessResponse("Successfully updated tags for instance: " + instanceName + " tags: " + tags); }
Source:
<code><START> public void multigetSliceChecksLimit() throws TException, LimitExceededException { <END> client.multiget_slice("get", TEST_TABLE, ImmutableList.of(ROW_KEY), SLICE_PREDICATE, ConsistencyLevel.ANY); verify(qosClient, times(1)).executeRead(any(), any(), any()); verifyNoMoreInteractions(qosClient); }</code><technical_language>nit, test method names improved</technical_language>

Target:
public void multigetSliceChecksLimit() throws TException, LimitExceededException { client.multiget_slice("get", TEST_TABLE, ImmutableList.of(ROW_KEY), SLICE_PREDICATE, ConsistencyLevel.ANY); verify(qosClient, times(1)).executeRead(any(), any()); verifyNoMoreInteractions(qosClient); }
Source:
<code>public void onCreate() { PRNGFixes.apply(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); if (!sp.getBoolean("default_user_pw_set", false)) { sp.edit().putBoolean("default_user_pw_set", true).commit(); <START> char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); <END> StringBuilder sb = new StringBuilder(); SecureRandom random = new SecureRandom(); for (int i = 0; i < 20; i++) sb.append(chars[random.nextInt(chars.length)]); String user = Build.MODEL.replaceAll("[^a-zA-Z0-9 ]", ""); Log.i(TAG, "Generated GUI username and password (username is " + user + ")"); sp.edit().putString("gui_user", user) .putString("gui_password", sb.toString()).commit(); } mDeviceStateHolder = new DeviceStateHolder(SyncthingService.this); registerReceiver(mDeviceStateHolder, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); new StartupTask().execute(); }</code><technical_language>include lowercase some special symbols</technical_language>

Target:
public void onCreate() { PRNGFixes.apply(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); if (!sp.getBoolean("default_user_pw_set", false)) { sp.edit().putBoolean("default_user_pw_set", true).commit(); char[] chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); StringBuilder sb = new StringBuilder(); SecureRandom random = new SecureRandom(); for (int i = 0; i < 20; i++) sb.append(chars[random.nextInt(chars.length)]); String user = Build.MODEL.replaceAll("[^a-zA-Z0-9 ]", ""); Log.i(TAG, "Generated GUI username and password (username is " + user + ")"); sp.edit().putString("gui_user", user) .putString("gui_password", sb.toString()).commit(); } mDeviceStateHolder = new DeviceStateHolder(SyncthingService.this); registerReceiver(mDeviceStateHolder, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); new StartupTask().execute(); }
Source:
<code>public void writeEventValue(@NonNull final IEvent event, final T value) { SharedPreferences.Editor editor = sharedPreferences.edit(); if (value.getClass().equals(String.class)) { editor.putString(event.getTrackingKey(), (String) value); } else if (value.getClass().equals(Boolean.class)) { editor.putBoolean(event.getTrackingKey(), (Boolean) value); } else if (value.getClass().equals(Long.class)) { editor.putLong(event.getTrackingKey(), (Long) value); } else if (value.getClass().equals(Integer.class)) { editor.putInt(event.getTrackingKey(), (Integer) value); } else if (value.getClass().equals(Float.class)) { editor.putLong(event.getTrackingKey(), (Long) value); <START> } <END> editor.apply(); }</code><technical_language>throw exception if T is of expected type</technical_language>

Target:
public void writeEventValue(@NonNull final IEvent event, final T value) { SharedPreferences.Editor editor = sharedPreferences.edit(); if (value.getClass().equals(String.class)) { editor.putString(event.getTrackingKey(), (String) value); } else if (value.getClass().equals(Boolean.class)) { editor.putBoolean(event.getTrackingKey(), (Boolean) value); } else if (value.getClass().equals(Long.class)) { editor.putLong(event.getTrackingKey(), (Long) value); } else if (value.getClass().equals(Integer.class)) { editor.putInt(event.getTrackingKey(), (Integer) value); } else if (value.getClass().equals(Float.class)) { editor.putLong(event.getTrackingKey(), (Long) value); } else { throw new IllegalArgumentException("Event value must be one of String, Boolean, Long, Integer or Float"); } editor.apply(); }
Source:
<code><START> public LinkedHashMap<String, String> getAPIPacketParameters() { <END> LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("Device Request ID", String.valueOf(requestID)); parameters.put("Transport", HexUtils.prettyHexString(HexUtils.integerToHexString(transport, 1))); parameters.put("Flags", HexUtils.prettyHexString(HexUtils.integerToHexString(flags, 1))); if (target != null) { parameters.put("Target length", String.valueOf(target.length())); parameters.put("Target", target); } else parameters.put("Target length", "0"); if (requestData != null) parameters.put("Data", HexUtils.prettyHexString(HexUtils.byteArrayToHexString(requestData))); return parameters; }</code><technical_language>For consistency, I format parameters of packets hexadecimal string interpreted (when necessary)</technical_language>

Target:
public LinkedHashMap<String, String> getAPIPacketParameters() { LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("Device Request ID", HexUtils.prettyHexString(HexUtils.integerToHexString(requestID, 1)) + " (" + requestID + ")"); parameters.put("Transport", HexUtils.prettyHexString(HexUtils.integerToHexString(transport, 1))); parameters.put("Flags", HexUtils.prettyHexString(HexUtils.integerToHexString(flags, 1))); if (target != null) { parameters.put("Target length", HexUtils.prettyHexString(HexUtils.integerToHexString(target.length(), 1)) + " (" + target.length() + ")"); parameters.put("Target", HexUtils.prettyHexString(HexUtils.byteArrayToHexString(target.getBytes())) + " (" + target + ")"); } else parameters.put("Target length", HexUtils.prettyHexString(HexUtils.integerToHexString(0, 1)) + " (0)"); if (requestData != null) parameters.put("Data", HexUtils.prettyHexString(HexUtils.byteArrayToHexString(requestData))); return parameters; }
Source:
<code>private String columnDefinitionsString(ResultHandler.ComparableColumnDefinitions cd) { StringBuilder sb = new StringBuilder(); if (cd == null) <START> { <END> sb.append("NULL"); } else if (cd.wasFailed()) { sb.append("FAILED"); } else { for (ResultHandler.ComparableDefinition def : cd) { sb.append(def.toString()); } } return sb.toString(); }</code><technical_language>Redundant braces</technical_language>

Target:
private String columnDefinitionsString(ResultHandler.ComparableColumnDefinitions cd) { StringBuilder sb = new StringBuilder(); if (cd == null) sb.append("NULL"); else if (cd.wasFailed()) sb.append("FAILED"); else { for (ResultHandler.ComparableDefinition def : cd) { sb.append(def.toString()); } } return sb.toString(); }
Source:
<code>public void setMenuItems(@Nullable List<CarMenuItem> items) { mMenuItems = items; mAllMenuItems.clear(); mAlwaysItemCount = 0; if (mMenuItems == null) { requestLayout(); return; } <START> for (int i = 0; i < mMenuItems.size(); i++) { <END> CarMenuItem item = mMenuItems.get(i); View action = null; if (item.getDisplayBehavior() == CarMenuItem.DisplayBehavior.ALWAYS || item.getDisplayBehavior() == CarMenuItem.DisplayBehavior.IF_ROOM) { action = item.isCheckable() ? createCheckableAction(item) : createAction(item); } if (item.getDisplayBehavior() == CarMenuItem.DisplayBehavior.ALWAYS) { mAlwaysItemCount++; } mAllMenuItems.add(new InflatedMenuItem(item, action)); } requestLayout(); }</code><technical_language>Noticied need index, change this a for-each loop</technical_language>

Target:
public void setMenuItems(@Nullable List<CarMenuItem> items) { mMenuItems = items; mAllMenuItems.clear(); mAlwaysItemCount = 0; if (mMenuItems == null) { requestLayout(); return; } for (CarMenuItem item : mMenuItems) { View action; switch (item.getDisplayBehavior()) { case ALWAYS: mAlwaysItemCount++; case IF_ROOM: action = item.isCheckable() ? createCheckableAction(item) : createAction(item); break; case NEVER: action = null; break; default: throw new IllegalStateException( "Unknown display behavior: " + item.getDisplayBehavior()); } mAllMenuItems.add(new InflatedMenuItem(item, action)); } requestLayout(); }
Source:
<code>private void handleFindNewFansMessage(final String remoteAddr) { Toaster.iToast(this, R.string.finding_new_fans); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { <START> Toaster.eToast(this, "Bluetooth adapter is null"); <END> return; } BluetoothDevice remoteDevice = adapter.getRemoteDevice(remoteAddr); MessageThread found = null; for (MessageThread thread : this.messageThreads) { if (thread.isRemoteDevice(remoteDevice)) { found = thread; break; } } if (found == null) { Toaster.eToast(this, "Unknown remote device."); return; } this.discoveryInitiator = found; adapter.startDiscovery(); }</code><technical_language>want this a string in strings.xml. If shown user in xml file. In fact want error.xml error messages</technical_language>

Target:
private void handleFindNewFansMessage(final String remoteAddr) { Toaster.iToast(this, R.string.finding_new_fans); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice remoteDevice = adapter.getRemoteDevice(remoteAddr); MessageThread found = null; for (MessageThread thread : this.messageThreads) { if (thread.isRemoteDevice(remoteDevice)) { found = thread; break; } } if (found == null) { Log.wtf(TAG, "Unknown remote device: " + remoteAddr); return; } this.discoveryInitiator = found; adapter.startDiscovery(); }
Source:
<code>private void parseRewind(final ReceiveCommand cmd) { RevCommit newObject; try { newObject = rp.getRevWalk().parseCommit(cmd.getNewId()); } catch (IncorrectObjectTypeException notCommit) { newObject = null; } catch (IOException err) { log.error("Invalid object " + cmd.getNewId().name() + " for " + cmd.getRefName() + " forced update", err); reject(cmd, "invalid object"); return; } RefControl ctl = projectControl.controlForRef(cmd.getRefName()); if (newObject != null) { validateNewCommits(ctl, cmd); if (cmd.getResult() != ReceiveCommand.Result.NOT_ATTEMPTED) { return; } } if (ctl.canForceUpdate()) { } else { <START> cmd.setResult(ReceiveCommand.Result.REJECTED_NONFASTFORWARD); <END> reject(cmd, "For non-fast forward updates, '" + PermissionRule.FORCE_PUSH + "' privilege is needed"); } }</code><technical_language>This line is unnecessary. reject() set status of reference a non-standard error type include text. text is long, is status display created Git client big. negative this change. Git native protocol a specific client server want accept a non-fast-forward push, bypassing "improve" error message. I prefer a change Git client elaborated server standard non-fast-forward error code. some description text printed out ReceivePack message stream tells user push is failing</technical_language>

Target:
private void parseRewind(final ReceiveCommand cmd) { RevCommit newObject; try { newObject = rp.getRevWalk().parseCommit(cmd.getNewId()); } catch (IncorrectObjectTypeException notCommit) { newObject = null; } catch (IOException err) { log.error("Invalid object " + cmd.getNewId().name() + " for " + cmd.getRefName() + " forced update", err); reject(cmd, "invalid object"); return; } RefControl ctl = projectControl.controlForRef(cmd.getRefName()); if (newObject != null) { validateNewCommits(ctl, cmd); if (cmd.getResult() != ReceiveCommand.Result.NOT_ATTEMPTED) { return; } } if (ctl.canForceUpdate()) { } else { cmd.setResult(ReceiveCommand.Result.REJECTED_NONFASTFORWARD, " need '" + PermissionRule.FORCE_PUSH + "' privilege."); } }
Source:
<code>@Override public void reportProcessingUpdate( final ReportProgressEvent reportProgressEvent ) { final int page; if ( asyncReportListener.getRequestedPage() > 0 ) { page = Math.max( asyncReportListener.getRequestedPage() + 2, reportProgressEvent.getPage() ); } else { page = acceptedPage + 2; } <START> final boolean requestedPageIsStored = reportProgressEvent.getPage() == page; <END> if ( reportProgressEvent.getActivity() == ReportProgressEvent.GENERATING_CONTENT && requestedPageIsStored ) { try { persistContent( key, produceReportContent( proc, targetRepository ) ); } catch ( final Exception e ) { logger.error( "Can't persist" ); } asyncReportListener.updateGenerationStatus( page - 1 ); asyncReportListener.setStatus( AsyncExecutionStatus.CONTENT_AVAILABLE ); } }</code><technical_language>get multiple progress events page. wise a flag remembers page persisted. This persist a page-set once. Adding a new member variable for "lastAcceptedPageWritten" checking accepted-page save storing content multiple times</technical_language>

Target:
@Override public void reportProcessingUpdate( final ReportProgressEvent reportProgressEvent ) { final int page; if ( asyncReportListener.getRequestedPage() > 0 ) { page = Math.max( asyncReportListener.getRequestedPage() + 2, reportProgressEvent.getPage() ); } else { page = acceptedPage + 2; } final boolean needToStorePages = reportProgressEvent.getPage() == page && reportProgressEvent.getPage() > lastAcceptedPageWritten; if ( reportProgressEvent.getActivity() == ReportProgressEvent.GENERATING_CONTENT && needToStorePages ) { try { persistContent( key, produceReportContent( proc, targetRepository ) ); lastAcceptedPageWritten = page; asyncReportListener.updateGenerationStatus( page - 1 ); asyncReportListener.setStatus( AsyncExecutionStatus.CONTENT_AVAILABLE ); } catch ( final Exception e ) { logger.error( "Can't persist" ); } } }
Source:
<code><START> public Optional<String> getExtension() { <END> return Optional.fromNullable(extension); }</code><technical_language>of getters in a POJO this return type private member variables expose. In this case, recommend extension, dateformat, frequencyOverride Optional<>s (in member variable types getter types). Jackson YAML deserialization automatically care of setting a missing field empty Optional<> in resulting Java object</technical_language>

Target:
public Optional<String> getExtension() { return extension; }
Source:
<code>public WallboardBody() { addStyleName("wallboard-board"); setSizeFull(); contentLayout = new CssLayout(); contentLayout.setSizeFull(); contentLayout.addComponent(new Label("Nothing to display")); if (debugEnabled) { addComponent(debugLabel); } addComponent(contentLayout); progressIndicator = new ProgressIndicator(); progressIndicator.setWidth("100%"); progressIndicator.setPollingInterval(250); progressIndicator.setVisible(true); addComponent(progressIndicator); setExpandRatio(contentLayout, 0.95f); setExpandRatio(progressIndicator, 0.05f); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { final UI ui = getUI(); if (ui != null) { <START> getUI().accessSynchronously(new Runnable() { <END> @Override public void run() { advanceTimer(); } }); } } }, 250, 250); addDetachListener(new DetachListener() { @Override public void detach(DetachEvent detachEvent) { timer.cancel(); } }); }</code><technical_language>suggestion ui.accessSynchronously(new Runnable() {</technical_language>

Target:
public WallboardBody() { addStyleName("wallboard-board"); setSizeFull(); contentLayout = new CssLayout(); contentLayout.setSizeFull(); contentLayout.addComponent(new Label("Nothing to display")); if (debugEnabled) { addComponent(debugLabel); } addComponent(contentLayout); setExpandRatio(contentLayout, 1.0f); progressIndicator = new ProgressIndicator(); progressIndicator.setWidth("100%"); progressIndicator.setPollingInterval(250); progressIndicator.setVisible(false); addComponent(progressIndicator); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { final UI ui = getUI(); if (ui != null) { ui.accessSynchronously(new Runnable() { @Override public void run() { advanceTimer(); } }); } } }, 250, 250); addDetachListener(new DetachListener() { @Override public void detach(DetachEvent detachEvent) { timer.cancel(); } }); }
Source:
<code>private void running() { try { while( fState == TimerThreadState.RUNNING ) { long timeout = getWaitTimeout(); QueueEntry entry = fQueue.peek(); if ( entry != null ) { long commandTimeout = getTimeoutForCommand( entry.fCommandToken.getCommand() ); if ( DEBUG ) { String commandText = entry.fCommandToken.getCommand().toString(); if ( commandText.endsWith( "\n" ) ) commandText = commandText.substring( 0, commandText.length() - 1 ); printDebugMessage( String.format( "Processing command '%s', command timeout is %d", commandText, Long.valueOf( commandTimeout ) ) ); } long currentTime = System.currentTimeMillis(); long elapsedTime = currentTime - entry.fTimestamp; if ( commandTimeout <= elapsedTime ) { processTimedOutCommand( entry.fCommandToken ); fQueue.remove( entry ); QueueEntry nextEntry = fQueue.peek(); if ( nextEntry != null ) { setTimeStamp( currentTime, nextEntry ); } } else { timeout = Math.min( timeout, commandTimeout - elapsedTime ); if ( DEBUG ) { String commandText = entry.fCommandToken.getCommand().toString(); if ( commandText.endsWith( "\n" ) ) commandText = commandText.substring( 0, commandText.length() - 1 ); printDebugMessage( String.format( "Setting timeout %d for command '%s'", Long.valueOf( timeout ), commandText ) ); } } } synchronized( TimerThread.this ) { wait( timeout ); } <START> if ( isInterrupted() ) { <END> } } } catch( InterruptedException e ) { } }</code><technical_language>Remove empty if statement</technical_language>

Target:
private void running() { try { while( getTimerThreadState() == TimerThreadState.RUNNING ) { long timeout = getWaitTimeout(); QueueEntry entry = fQueue.peek(); if ( entry != null ) { long commandTimeout = getTimeoutForCommand( entry.fCommandToken.getCommand() ); if ( DEBUG ) { String commandText = entry.fCommandToken.getCommand().toString(); if ( commandText.endsWith( "\n" ) ) commandText = commandText.substring( 0, commandText.length() - 1 ); printDebugMessage( String.format( "Processing command '%s', command timeout is %d", commandText, Long.valueOf( commandTimeout ) ) ); } long currentTime = System.currentTimeMillis(); long elapsedTime = currentTime - entry.fTimestamp; if ( commandTimeout <= elapsedTime ) { processTimedOutCommand( entry.fCommandToken ); fQueue.remove( entry ); QueueEntry nextEntry = fQueue.peek(); if ( nextEntry != null ) { setTimeStamp( currentTime, nextEntry ); } } else { timeout = Math.min( timeout, commandTimeout - elapsedTime ); if ( DEBUG ) { String commandText = entry.fCommandToken.getCommand().toString(); if ( commandText.endsWith( "\n" ) ) commandText = commandText.substring( 0, commandText.length() - 1 ); printDebugMessage( String.format( "Setting timeout %d for command '%s'", Long.valueOf( timeout ), commandText ) ); } } } synchronized( TimerThread.this ) { wait( timeout ); } } } catch( InterruptedException e ) { } }
Source:
<code>public boolean isSelected(File basedir, String filename, File file) throws BuildException { String parentName = file.getParent(); if (parentName.length() > baseDirPathLength) { <START> String parentRelativeName = parentName.substring(baseDirPathLength + File.separator.length()); <END> if (alreadyDeselected.contains(parentRelativeName)) { alreadyDeselected.add(filename); return false; } } if (file.isDirectory()) { try { if (baseDirFP.isDescendant(filename)) { return true; } else { alreadyDeselected.add(filename); return false; } } catch (IOException | InterruptedException e) { return true; } } else { return true; } }</code><technical_language>file separator length 1? access File.separatorChar is length 1</technical_language>

Target:
public boolean isSelected(File basedir, String filename, File file) throws BuildException { String parentName = file.getParent(); if (parentName.length() > baseDirPathLength) { String parentRelativeName = parentName.substring(baseDirPathLength + 1); if (alreadyDeselected.contains(parentRelativeName)) { alreadyDeselected.add(filename); return false; } } if (file.isDirectory()) { try { if (baseDirFP.isDescendant(filename)) { return true; } else { alreadyDeselected.add(filename); return false; } } catch (IOException | InterruptedException e) { return true; } } else { return true; } }
Source:
<code>public void onActionModeShown(ActionMode mode) { <START> if (model.getPage() == null) { <END> return; } shareHandler.onTextSelected(mode); }</code><technical_language>minor: introducing a method exit point extra line, I recommend inverting logic moving shareHandler invocation here</technical_language>

Target:
public void onActionModeShown(ActionMode mode) { if (model.getPage() != null) { shareHandler.onTextSelected(mode); } }
Source:
<code>private Map<String, List<Endorsement>> groupEndorsementsByTechnology( List<Endorsement> endorsementsList) { Map<String, List<Endorsement>> groupedEndorsements = new HashMap<String, List<Endorsement>>(); for (Endorsement endorsement : endorsementsList) { String key = endorsement.getTechnologyEntity().getName(); List<Endorsement> group = groupedEndorsements.get(key); if (group == null) { group = new ArrayList<Endorsement>(); } group.add(endorsement); <START> groupedEndorsements.put(key, group); <END> } return groupedEndorsements; }</code><technical_language>@Surerus put this line 'if (group == null) '</technical_language>

Target:
private Map<String, List<Endorsement>> groupEndorsementsByTechnology( List<Endorsement> endorsementsList) { Map<String, List<Endorsement>> groupedEndorsements = new HashMap<String, List<Endorsement>>(); for (Endorsement endorsement : endorsementsList) { String key = endorsement.getTechnologyEntity().getName(); List<Endorsement> group = groupedEndorsements.get(key); if (group == null) { group = new ArrayList<Endorsement>(); groupedEndorsements.put(key, group); } group.add(endorsement); } return groupedEndorsements; }
Source:
<code>public List<T> get() { <START> try { <END> for (final ServiceReference<T> ref : this.serviceReferences) { final T service = this.bundleContext.getService(ref); if (service != null) { this.acquiredServices.put(service, ref); } } } catch (final Exception ex) { logger.warn(message.errorRetrievingService(), ex); } return unmodifiableList(new ArrayList<>(this.acquiredServices.keySet())); }</code><technical_language>Calling get method multiple times counter incremented multiple times. close method release once. this implementation unbalanced me</technical_language>

Target:
public Stream<T> get() { if (this.isClosed.get()) { throw new IllegalStateException(message.alreadyClosed()); } serviceTracker.ifPresent(t -> { if (isTrackerOpened.compareAndSet(false, true)) { t.open(); } if (shouldWait) { final long timeoutInMillis = timeUnit.toMillis(timeout); try { t.waitForService(timeoutInMillis); } catch (final InterruptedException e) { } } final ServiceReference<T>[] refs = t.getServiceReferences(); if (nonNull(refs)) { serviceReferences.addAll(Arrays.stream(refs).collect(Collectors.toList())); } }); try { this.serviceReferences.stream().filter(this::isNotAcquired).forEach(this::acquireService); } catch (final Exception ex) { logger.error(message.errorRetrievingService(), ex); } return this.acquiredServices.values().stream(); }
Source:
<code>public NullnessJspecifySamplesTest(List<File> testFiles) { super( testFiles, org.checkerframework.checker.nullness.NullnessChecker.class, <START> "nullness", <END> Collections.singletonList("../../jspecify/build/libs/jspecify-0.1.0-SNAPSHOT.jar"), "-Anomsgtext"); }</code><technical_language>This "../../../jspecify/samples"</technical_language>

Target:
public NullnessJspecifySamplesTest(List<File> testFiles) { super( testFiles, org.checkerframework.checker.nullness.NullnessChecker.class, "../../../jspecify/samples", Collections.singletonList("../../jspecify/build/libs/jspecify-0.1.0-SNAPSHOT.jar"), "-Anomsgtext"); }
Source:
<code>protected DatanodeDetails chooseNodeFromNetworkTopology( NetworkTopology networkTopology, DatanodeDetails anchor, List<DatanodeDetails> excludedNodes) { if (networkTopology == null) { return null; } if (excludedNodes == null) { return (DatanodeDetails)networkTopology.chooseRandom( <START> anchor.getNetworkFullPath(), new ArrayList<>()); <END> } Collection<Node> excluded = new ArrayList<>(); excluded.add(anchor); Node pick; Node pick1 = networkTopology.chooseRandom( anchor.getNetworkLocation(), excluded); if (pick1 == null) { return null; } Node pick2 = networkTopology.chooseRandom( anchor.getNetworkLocation(), excluded); if (pick2 == null) { pick = pick1; } else { pick = (networkTopology.getDistanceCost(anchor, pick1) > networkTopology.getDistanceCost(anchor, pick2)) ? pick2 : pick1; } DatanodeDetails pickedNode = (DatanodeDetails) pick; excludedNodes.add(pickedNode); return pickedNode; }</code><technical_language>anchor.getNetworkFullPath -> anchor.getNetworkLocation</technical_language>

Target:
protected DatanodeDetails chooseNodeFromNetworkTopology( NetworkTopology networkTopology, DatanodeDetails anchor, List<DatanodeDetails> excludedNodes) { Preconditions.checkArgument(networkTopology != null); Collection<Node> excluded = new ArrayList<>(); if (excludedNodes != null && excludedNodes.size() != 0) { excluded.addAll(excludedNodes); } excluded.add(anchor); Node pick = networkTopology.chooseRandom( anchor.getNetworkLocation(), excluded); DatanodeDetails pickedNode = (DatanodeDetails) pick; if (excludedNodes != null) { excludedNodes.add(pickedNode); } return pickedNode; }
Source:
<code>public static URL getResourceRoot(String name) throws IOException { URL url = ResourceLoader.class.getResource("/" + name); if (url == null) { <START> try { <END> return new URL("modjar://worldedit/" + name); } catch (Exception e) { } throw new IOException("Could not find " + name); } return url; }</code><technical_language>other method delegate this one, vice versa if easier? repeat modjar hack</technical_language>

Target:
public static URL getResourceRoot(String name) throws IOException { URL url = ResourceLoader.class.getResource("/" + name); if (url == null) { return getResourceForgeHack(name); } return url; }
Source:
<code>public TableLayout getLayout(Session session, TableHandle handle) { ConnectorId connectorId = handle.getConnectorId(); CatalogMetadata catalogMetadata = getCatalogMetadata(session, connectorId); ConnectorMetadata metadata = catalogMetadata.getMetadataFor(connectorId); ConnectorTransactionHandle transaction = catalogMetadata.getTransactionHandleFor(connectorId); <START> return fromConnectorLayout(connectorId, transaction, metadata.getTableLayout(session.toConnectorSession(connectorId), resolveTableLayout(session, handle))); <END> }</code><technical_language>Ditto interfaces</technical_language>

Target:
public TableLayout getLayout(Session session, TableHandle handle) { ConnectorId connectorId = handle.getConnectorId(); CatalogMetadata catalogMetadata = getCatalogMetadata(session, connectorId); ConnectorMetadata metadata = catalogMetadata.getMetadataFor(connectorId); return fromConnectorLayout(connectorId, handle.getConnectorHandle(), handle.getTransaction(), metadata.getTableLayout(session.toConnectorSession(connectorId), resolveTableLayout(session, handle))); }
Source:
<code><START> public StatusDTO setKeycloakRealm(String keycloakRealm) { <END> this.keycloakRealm = keycloakRealm; return this; }</code><technical_language>This returning a KeycloakStatusDTO</technical_language>

Target:
public KeycloakStatusDTO setKeycloakRealm(String keycloakRealm) { this.keycloakRealm = keycloakRealm; return this; }
Source:
<code>private void processGetBlobResponse(GetRequestInfo getRequestInfo, GetResponse getResponse) throws IOException, MessageFormatException { ServerErrorCode getError = getResponse.getError(); if (getError == ServerErrorCode.No_Error) { int partitionsInResponse = getResponse.getPartitionResponseInfoList().size(); if (partitionsInResponse != 1) { chunkException = new RouterException( "Unexpected number of partition responses, expected: 1, " + "received: " + partitionsInResponse, RouterErrorCode.UnexpectedInternalError); } else { getError = getResponse.getPartitionResponseInfoList().get(0).getErrorCode(); if (getError == ServerErrorCode.No_Error) { handleBody(getResponse.getInputStream()); chunkOperationTracker.onResponse(getRequestInfo.replicaId, true); if (RouterUtils.isRemoteReplica(routerConfig, getRequestInfo.replicaId)) { logger.trace("Cross colo request successful for remote replica in ", getRequestInfo.replicaId.getDataNodeId().getDatacenterName()); routerMetrics.crossColoSuccessCount.inc(); } } else { processServerError(getError); if (getError == ServerErrorCode.Blob_Deleted || getError == ServerErrorCode.Blob_Expired) { chunkCompleted = true; <START> retainExceptionOnSuccess = true; <END> } else { onErrorResponse(getRequestInfo.replicaId); } } } } else { onErrorResponse(getRequestInfo.replicaId); } }</code><technical_language>sync @pnarayanan flow here. if this statement is required</technical_language>

Target:
private void processGetBlobResponse(GetRequestInfo getRequestInfo, GetResponse getResponse) throws IOException, MessageFormatException { ServerErrorCode getError = getResponse.getError(); if (getError == ServerErrorCode.No_Error) { int partitionsInResponse = getResponse.getPartitionResponseInfoList().size(); if (partitionsInResponse != 1) { chunkException = new RouterException( "Unexpected number of partition responses, expected: 1, " + "received: " + partitionsInResponse, RouterErrorCode.UnexpectedInternalError); } else { getError = getResponse.getPartitionResponseInfoList().get(0).getErrorCode(); if (getError == ServerErrorCode.No_Error) { handleBody(getResponse.getInputStream()); chunkOperationTracker.onResponse(getRequestInfo.replicaId, true); if (RouterUtils.isRemoteReplica(routerConfig, getRequestInfo.replicaId)) { logger.trace("Cross colo request successful for remote replica in ", getRequestInfo.replicaId.getDataNodeId().getDatacenterName()); routerMetrics.crossColoSuccessCount.inc(); } } else { processServerError(getError); if (getError == ServerErrorCode.Blob_Deleted || getError == ServerErrorCode.Blob_Expired) { chunkCompleted = true; } else { onErrorResponse(getRequestInfo.replicaId); } } } } else { onErrorResponse(getRequestInfo.replicaId); } }
Source:
<code>protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { <START> builder.stateTransfer().chunkSize(2).timeout(2000).maxRetries(2); <END> }</code><technical_language>Ouch, default MAX_RETRIES is 30??? 2 is excessive in a test :)</technical_language>

Target:
protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { builder.stateTransfer().chunkSize(2).timeout(2000).maxRetries(1); }
Source:
<code>public void clearDependencies() { super.clearDependencies(); taskSourceRdd = null; inputRdds = null; taskProcessor = null; <START> } <END></code><technical_language>a implicit "sublist" is done code a bit difficult follow (similar argument getTaskSourceIterator). sense do partitions.subList(1, ...) in compute</technical_language>

Target:
public void clearDependencies() { super.clearDependencies(); shuffleInputFragmentIds = null; shuffleInputRdds = null; taskSourceRdd = null; taskProcessor = null; }
Source:
<code>private List<String> getColumnMetadata(String parent, JsonNode propertiesNode) { List<String> metadata = new ArrayList<>(); Iterator<Entry<String, JsonNode>> iterator = propertiesNode.fields(); while (iterator.hasNext()) { Entry<String, JsonNode> entry = iterator.next(); String key = entry.getKey(); JsonNode value = entry.getValue(); <START> String childKey = null; <END> if (parent == null || parent.isEmpty()) { childKey = key; } else { childKey = parent.concat(".").concat(key); } if (value.isObject()) { metadata.addAll(getColumnMetadata(childKey, value)); continue; } if (!value.isArray()) { metadata.add(childKey.concat(":").concat(value.textValue())); } } return metadata; }</code><technical_language>unnecessary null initialization</technical_language>

Target:
private List<String> getColumnMetadata(String parent, JsonNode propertiesNode) { List<String> metadata = new ArrayList<>(); Iterator<Entry<String, JsonNode>> iterator = propertiesNode.fields(); while (iterator.hasNext()) { Entry<String, JsonNode> entry = iterator.next(); String key = entry.getKey(); JsonNode value = entry.getValue(); String childKey; if (parent == null || parent.isEmpty()) { childKey = key; } else { childKey = parent.concat(".").concat(key); } if (value.isObject()) { metadata.addAll(getColumnMetadata(childKey, value)); continue; } if (!value.isArray()) { metadata.add(childKey.concat(":").concat(value.textValue())); } } return metadata; }
Source:
<code>public static void executeBuild() throws Exception { System.setProperty("verifier.forkMode", "auto"); verifier = new RepoRefLocationP2RepositoryIntegrationTest().getVerifier("/p2Repository.repositoryRef.location", false); verifier.getCliOptions().add("-Dtest-data-repo=" + ResourceUtil.P2Repositories.ECLIPSE_OXYGEN.toString()); <START> verifier.executeGoal("verify"); <END> verifier.verifyErrorFreeLog(); p2Repo = P2RepositoryTool.forEclipseRepositoryModule(new File(verifier.getBasedir())); }</code><technical_language>Do need verify? package enough</technical_language>

Target:
public static void executeBuild() throws Exception { System.setProperty("verifier.forkMode", "auto"); verifier = new RepoRefLocationP2RepositoryIntegrationTest().getVerifier("/p2Repository.repositoryRef.location", false); verifier.getCliOptions().add("-Dtest-data-repo=" + ResourceUtil.P2Repositories.ECLIPSE_OXYGEN.toString()); verifier.executeGoal("package"); verifier.verifyErrorFreeLog(); p2Repo = P2RepositoryTool.forEclipseRepositoryModule(new File(verifier.getBasedir())); }
Source:
<code>private DatasetExportService getExportFileStrategy(final String fileType) { if (DatasetResource.CSV.equalsIgnoreCase(fileType.trim())) { return this.datasetCSVExportServiceImpl; <START> } else if (DatasetResource.XLS.equalsIgnoreCase(fileType.trim())) { <END> return this.datasetExcelExportServiceImpl; } else if (DatasetResource.KSU_CSV.equalsIgnoreCase(fileType.trim())) { return this.datasetKSUCSVExportServiceImpl; } else if (DatasetResource.KSU_XLS.equalsIgnoreCase(fileType.trim())) { return this.datasetKSUExcelExportServiceImpl; } return null; }</code><technical_language>Extract fileType.trim() local variable</technical_language>

Target:
private DatasetExportService getExportFileStrategy(final String fileType) { final String trimmedFileType = fileType.trim(); if (DatasetResource.CSV.equalsIgnoreCase(trimmedFileType)) { return this.datasetCSVExportServiceImpl; } else if (DatasetResource.XLS.equalsIgnoreCase(trimmedFileType)) { return this.datasetExcelExportServiceImpl; } else if (DatasetResource.KSU_CSV.equalsIgnoreCase(trimmedFileType)) { return this.datasetKsuCSVExportServiceImpl; } else if (DatasetResource.KSU_XLS.equalsIgnoreCase(trimmedFileType)) { return this.datasetKsuExcelExportServiceImpl; } return null; }
Source:
<code><START> private LinkedList<Event> computeEventCounts(ObjectStream<Event> eventStream, <END> Map<String, Integer> predicatesInOut, int cutoff) throws IOException { Set<String> predicateSet = new HashSet<>(); Map<String, Integer> counter = new HashMap<>(); LinkedList<Event> events = new LinkedList<>(); Event ev; while ((ev = eventStream.read()) != null) { events.addLast(ev); update(ev.getContext(), predicateSet, counter, cutoff); } predCounts = new int[predicateSet.size()]; int index = 0; for (Iterator<String> pi = predicateSet.iterator(); pi.hasNext(); index++) { String predicate = pi.next(); predCounts[index] = counter.get(predicate); predicatesInOut.put(predicate, index); } return events; }</code><technical_language>change method signature return interface List opposed a concrete class</technical_language>

Target:
private List<Event> computeEventCounts(ObjectStream<Event> eventStream, Map<String, Integer> predicatesInOut, int cutoff) throws IOException { Set<String> predicateSet = new HashSet<>(); Map<String, Integer> counter = new HashMap<>(); List<Event> events = new LinkedList<>(); Event ev; while ((ev = eventStream.read()) != null) { events.add(ev); update(ev.getContext(), predicateSet, counter, cutoff); } predCounts = new int[predicateSet.size()]; int index = 0; for (Iterator<String> pi = predicateSet.iterator(); pi.hasNext(); index++) { String predicate = pi.next(); predCounts[index] = counter.get(predicate); predicatesInOut.put(predicate, index); } return events; }
Source:
<code>public static int getPercentCompleteSMAState(IAtsObject atsObject) throws OseeCoreException { if (atsObject instanceof IAtsAction) { IAtsAction action = (IAtsAction) atsObject; if (AtsCore.getWorkItemService().getTeams(action).size() == 1) { return getPercentCompleteSMAState(AtsCore.getWorkItemService().getFirstTeam(action)); } else { <START> double percent = 0; <END> int items = 0; for (IAtsTeamWorkflow team : AtsCore.getWorkItemService().getTeams(action)) { if (!AtsCore.getWorkItemService().getWorkData(team).isCancelled()) { percent += getPercentCompleteSMAState(team); items++; } } if (items > 0) { Double rollPercent = percent / items; return rollPercent.intValue(); } } return 0; } if (atsObject instanceof IAtsWorkItem) { return getPercentCompleteSMAState(atsObject, AtsCore.getWorkItemService().getCurrentState((IAtsWorkItem) atsObject)); } return 0; }</code><technical_language>Initialize 0.0</technical_language>

Target:
public static int getPercentCompleteSMAState(IAtsObject atsObject) throws OseeCoreException { int percent = 0; if (atsObject instanceof IAtsAction) { IAtsAction action = (IAtsAction) atsObject; if (AtsCore.getWorkItemService().getTeams(action).size() == 1) { return getPercentCompleteSMAState(AtsCore.getWorkItemService().getFirstTeam(action)); } else { int items = 0; for (IAtsTeamWorkflow team : AtsCore.getWorkItemService().getTeams(action)) { if (!AtsCore.getWorkItemService().getWorkData(team).isCancelled()) { percent += getPercentCompleteSMAState(team); items++; } } if (items > 0) { Double rollPercent = new Double(percent) / items; percent = rollPercent.intValue(); } } } else if (atsObject instanceof IAtsWorkItem) { return getPercentCompleteSMAState(atsObject, AtsCore.getWorkItemService().getCurrentState((IAtsWorkItem) atsObject)); } return percent; }
Source:
<code>public URI uploadPackage() throws UploaderException { if (!isLocalFileExists(topologyPackageLocation)) { throw new UploaderException( <START> String.format("Topology file %s does not exist", topologyPackageLocation)); <END> } if (!controller.exists(destTopologyDirectoryURI)) { LOG.info("The destination directory does not exist; creating it."); if (!controller.mkdirs(destTopologyDirectoryURI)) { throw new UploaderException( String.format("Failed to create directory: %s", destTopologyDirectoryURI)); } } else { LOG.info("Target topology file " + packageURI.toString() + " exists, overwriting..."); } LOG.info("Uploading topology " + topologyPackageLocation + " package to target hdfs " + packageURI.toString()); if (!controller.copyFromLocalFile(topologyPackageLocation, packageURI.toString())) { throw new UploaderException( String.format("Failed to upload the package to: %s", packageURI.toString())); } return packageURI; }</code><technical_language>more context here: "Expected topology package file uploaded %s exist" for massaging in other uploaders below</technical_language>

Target:
public URI uploadPackage() throws UploaderException { if (!isLocalFileExists(topologyPackageLocation)) { throw new UploaderException( String.format("Expected topology package file to be uploaded does not exist at '%s'", topologyPackageLocation)); } if (!controller.exists(destTopologyDirectoryURI)) { LOG.info(String.format( "The destination directory does not exist. Creating it now at URI '%s'", destTopologyDirectoryURI)); if (!controller.mkdirs(destTopologyDirectoryURI)) { throw new UploaderException( String.format("Failed to create directory for topology package at URI '%s'", destTopologyDirectoryURI)); } } else { LOG.info(String.format("Target topology file already exists at '%s'. Overwriting it now", packageURI.toString())); } LOG.info(String.format("Uploading topology package at '%s' to target HDFS at '%s'", topologyPackageLocation, packageURI.toString())); if (!controller.copyFromLocalFile(topologyPackageLocation, packageURI.toString())) { throw new UploaderException( String.format("Failed to upload the topology package at '%s' to: '%s'", topologyPackageLocation, packageURI.toString())); } return packageURI; }
Source:
<code>public AbstractDiscoveryStrategy(ResourceLoader resourceLoader, Bootstrap bootstrap, Set<Class<? extends Annotation>> initialBeanDefiningAnnotations) { <START> this(); <END> this.setResourceLoader(resourceLoader); this.setBootstrap(bootstrap); this.setInitialBeanDefiningAnnotations(initialBeanDefiningAnnotations); }</code><technical_language>is need call this() this keyword for setters..</technical_language>

Target:
public AbstractDiscoveryStrategy(ResourceLoader resourceLoader, Bootstrap bootstrap, Set<Class<? extends Annotation>> initialBeanDefiningAnnotations) { handlers = new LinkedList<BeanArchiveHandler>(); setResourceLoader(resourceLoader); setBootstrap(bootstrap); setInitialBeanDefiningAnnotations(initialBeanDefiningAnnotations); }
Source:
<code>protected void handleError(final Exception e, final DeviceMessageMetadata deviceMessageMetadata, final String errorMessage) { LOGGER.info("handeling error: for message type: {}", e.getMessage(), deviceMessageMetadata.getMessageType()); final OsgpException osgpException = this.ensureOsgpException(e, errorMessage); <START> this.webServiceResponseMessageSender.send( <END> ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()) .withResult(ResponseMessageResultType.NOT_OK).withOsgpException(osgpException) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
protected void handleError(final Exception e, final DeviceMessageMetadata deviceMessageMetadata, final String errorMessage) { LOGGER.info("handeling error: for message type: {}", e.getMessage(), deviceMessageMetadata.getMessageType()); final OsgpException osgpException = this.ensureOsgpException(e, errorMessage); final ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()) .withResult(ResponseMessageResultType.NOT_OK).withOsgpException(osgpException) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>private void createFooterButton() { final Button closeButton = createButton(coreLocale.close(), "window-edit-configurations-close", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onCloseClicked(); } }); closeButton.addDomHandler(new BlurHandler() { @Override public void onBlur(BlurEvent blurEvent) { selectElementText(filterInputField.getElement()); } }, BlurEvent.getType()); addButtonToFooter(closeButton); <START> Element dummyFocusElement = DOM.createSpan(); <END> dummyFocusElement.setTabIndex(0); getFooter().getElement().appendChild(dummyFocusElement); }</code><technical_language>Whats benefit of this solution</technical_language>

Target:
private void createFooterButton() { final Button closeButton = createButton(coreLocale.close(), "window-edit-configurations-close", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onCloseClicked(); } }); closeButton.addDomHandler(new BlurHandler() { @Override public void onBlur(BlurEvent blurEvent) { selectText(filterInputField.getElement()); } }, BlurEvent.getType()); addButtonToFooter(closeButton); Element dummyFocusElement = DOM.createSpan(); dummyFocusElement.setTabIndex(0); getFooter().getElement().appendChild(dummyFocusElement); }
Source:
<code>public DMNIncludedModel create(final Path dmnModelPath, final Path includedModelPath) throws DMNIncludeModelCouldNotBeCreatedException { <START> throw new DMNIncludeModelCouldNotBeCreatedException(); <END> }</code><technical_language>message consuming constructor: java throw new DMNIncludeModelCouldNotBeCreatedException("Can in kogito");</technical_language>

Target:
public DMNIncludedModel create(final Path dmnModelPath, final Path includedModelPath) throws DMNIncludeModelCouldNotBeCreatedException { throw new DMNIncludeModelCouldNotBeCreatedException("Not available in kogito"); }
Source:
<code>private void createZip(List<BinaryContent> binaryContents, File dumpLocation, Metacard metacard) throws CatalogTransformerException, IOException { File zipPath = new File(getOutputFile(dumpLocation, metacard).getAbsolutePath() + ".zip"); try { ZipFile zipFile = new ZipFile(zipPath); int index = 1; for (BinaryContent binaryContent : binaryContents) { <START> ZipParameters p = new ZipParameters(); <END> p.setSourceExternalStream(true); p.setFileNameInZip(String.format("%d%s", index++, generateExtension())); zipFile.addStream(binaryContent.getInputStream(), p); } } catch (ZipException e) { throw new CatalogTransformerException( String.format("unable to create zip file: %s", zipPath.getAbsolutePath()), e); } }</code><technical_language>recommend naming this zipParameters more meaningful</technical_language>

Target:
private void createZip(List<BinaryContent> binaryContents, File dumpLocation, Metacard metacard) throws CatalogTransformerException, IOException { File zipPath = new File(getOutputFile(dumpLocation, metacard).getAbsolutePath() + ".zip"); try { ZipFile zipFile = new ZipFile(zipPath); int index = 1; for (BinaryContent binaryContent : binaryContents) { ZipParameters zipParameters = new ZipParameters(); zipParameters.setSourceExternalStream(true); zipParameters.setFileNameInZip(String.format("%d%s", index++, generateExtension())); zipFile.addStream(binaryContent.getInputStream(), zipParameters); } } catch (ZipException e) { throw new CatalogTransformerException( String.format("unable to create zip file: %s", zipPath.getAbsolutePath()), e); } }