auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); <START> cursor.moveToFirst(); <END> int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); File imageFile = new File(picturePath); final String attachmentName = getApplication().getString(R.string.attachment) + "_" + System.currentTimeMillis() + ".png"; progressDialog.setTitle(getApplication().getString(R.string.apply_edit_message)); progressDialog.setMessage(getApplication().getString(R.string.wait)); progressDialog.show(); ListenableFuture<Attachment> addResult = mSelectedArcGISFeature.addAttachmentAsync(imageFile, "image/png", attachmentName); addResult.addDoneListener(new Runnable() { @Override public void run() { final ListenableFuture<Void> tableResult = mServiceFeatureTable.updateFeatureAsync(mSelectedArcGISFeature); tableResult.addDoneListener(new Runnable() { @Override public void run() { applyServerEdits(); } }); } }); } }</code><technical_language>need check cursor is null java if (cursor != null && cursor.moveToFirst()) { // proceed }</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); if (cursor != null && cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); File imageFile = new File(picturePath); final String attachmentName = getApplication().getString(R.string.attachment) + "_" + System.currentTimeMillis() + ".png"; progressDialog.setTitle(getApplication().getString(R.string.apply_edit_message)); progressDialog.setMessage(getApplication().getString(R.string.wait)); progressDialog.show(); ListenableFuture<Attachment> addResult = mSelectedArcGISFeature.addAttachmentAsync(imageFile, "image/png", attachmentName); addResult.addDoneListener(new Runnable() { @Override public void run() { final ListenableFuture<Void> tableResult = mServiceFeatureTable.updateFeatureAsync(mSelectedArcGISFeature); tableResult.addDoneListener(new Runnable() { @Override public void run() { applyServerEdits(); } }); } }); } } }
Source:
<code>public final String getDescription() { StringBuilder sb = new StringBuilder("rel#"); sb = sb.append(id).append(':').append(digest); <START> return sb.toString(); <END> }</code><technical_language>If this is called recomputeDigest(), get a description string original implementation. Is want</technical_language>

Target:
public final String getDescription() { return this.toString(); }
Source:
<code>public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } final LocalizedMessage localizedMessage = (LocalizedMessage) object; return severityLevel == localizedMessage.severityLevel <START> && Objects.equals(lineNo, localizedMessage.lineNo) <END> && Objects.equals(columnNo, localizedMessage.columnNo) && Objects.equals(columnCharIndex, localizedMessage.columnCharIndex) && Objects.equals(tokenType, localizedMessage.tokenType) && Objects.equals(moduleId, localizedMessage.moduleId) && Objects.equals(key, localizedMessage.key) && Objects.equals(bundle, localizedMessage.bundle) && Objects.equals(sourceClass, localizedMessage.sourceClass) && Objects.equals(customMessage, localizedMessage.customMessage) && Arrays.equals(args, localizedMessage.args); }</code><technical_language>@rnveach , interesting update: fix style issue, code is consistent in view break style consistency. this is forcing suppress smth else. original violation is performance issue fix .... damaging existing style bee good. i suppress original issue code consistency</technical_language>

Target:
public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } final LocalizedMessage localizedMessage = (LocalizedMessage) object; return Objects.equals(lineNo, localizedMessage.lineNo) && Objects.equals(columnNo, localizedMessage.columnNo) && Objects.equals(columnCharIndex, localizedMessage.columnCharIndex) && Objects.equals(tokenType, localizedMessage.tokenType) && Objects.equals(severityLevel, localizedMessage.severityLevel) && Objects.equals(moduleId, localizedMessage.moduleId) && Objects.equals(key, localizedMessage.key) && Objects.equals(bundle, localizedMessage.bundle) && Objects.equals(sourceClass, localizedMessage.sourceClass) && Objects.equals(customMessage, localizedMessage.customMessage) && Arrays.equals(args, localizedMessage.args); }
Source:
<code>public void execute(String[] args, Console console) { if (args.length > 0) { String subCommand = args[0]; switch (subCommand) { case SUBCMD_SAY: if (args.length > 1) { say((String[]) ArrayUtils.subarray(args, 1, args.length), console); } else { console.println("Specify text to say (e.g. 'say hello')"); } return; case SUBCMD_INTERPRET: if (args.length > 1) { interpret((String[]) ArrayUtils.subarray(args, 1, args.length), console); } else { console.println("Specify text to interpret (e.g. 'interpret turn all lights off')"); } return; case SUBCMD_VOICES: Locale locale = localeProvider.getLocale(); Voice v = voiceManager.getDefaultVoice(); if (v == null) { TTSService tts = voiceManager.getTTS(); if (tts != null) { v = voiceManager.getPreferredVoice(tts.getAvailableVoices()); } } final Voice defaultVoice = v; VoiceHelper.withSortedVoices(voiceManager.getTTSs().stream(), locale, (ttsService, voice) -> { <START> console.println(String.format("%s%s - %s - %s (%s)", voice.equals(defaultVoice) ? "*" : "", <END> ttsService.getLabel(locale), voice.getLocale().getDisplayName(locale), voice.getLabel(), voice.getUID())); }); return; default: break; } } else { printUsage(console); } }</code><technical_language>picking: align output more human readable prepend "* " (asterisks whitespace) for default voice " " (two whitespaces) else</technical_language>

Target:
public void execute(String[] args, Console console) { if (args.length > 0) { String subCommand = args[0]; switch (subCommand) { case SUBCMD_SAY: if (args.length > 1) { say((String[]) ArrayUtils.subarray(args, 1, args.length), console); } else { console.println("Specify text to say (e.g. 'say hello')"); } return; case SUBCMD_INTERPRET: if (args.length > 1) { interpret((String[]) ArrayUtils.subarray(args, 1, args.length), console); } else { console.println("Specify text to interpret (e.g. 'interpret turn all lights off')"); } return; case SUBCMD_VOICES: Locale locale = localeProvider.getLocale(); Voice defaultVoice = getDefaultVoice(); for (Voice voice : voiceManager.getAllVoices()) { TTSService ttsService = voiceManager.getTTS(voice.getUID().split(":")[0]); if (ttsService != null) { console.println(String.format("%s %s - %s - %s (%s)", voice.equals(defaultVoice) ? "*" : " ", ttsService.getLabel(locale), voice.getLocale().getDisplayName(locale), voice.getLabel(), voice.getUID())); } } return; default: break; } } else { printUsage(console); } }
Source:
<code>public void whenStreamTimeoutReachedPossibleToCommit() throws Exception { publishEvent(eventType.getName(),"{\"foo\":\"bar\"}"); publishEvent(eventType.getName(),"{\"foo\":\"bar\"}"); final TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), "stream_limit=1&stream_timeout=1") .start(); waitFor(() -> Assert.assertFalse(client.getBatches().isEmpty()), TimeUnit.SECONDS.toMillis(1), 100); final SubscriptionCursor toCommit = client.getBatches().get(0).getCursor(); client.close(); <START> <END> final int statusCode = commitCursors( subscription.getId(), Collections.singletonList(toCommit), client.getSessionId()); Assert.assertEquals(SC_NO_CONTENT, statusCode); }</code><technical_language>want wait a bit connection close is finished</technical_language>

Target:
public void whenStreamTimeoutReachedPossibleToCommit() throws Exception { final TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), "batch_limit=1&stream_limit=2&stream_timeout=1") .start(); waitFor(() -> assertThat(client.getSessionId(), not(equalTo(SESSION_ID_UNKNOWN)))); publishEvent(eventType.getName(),"{\"foo\":\"bar\"}"); waitFor(() -> Assert.assertFalse(client.getBatches().isEmpty()), TimeUnit.SECONDS.toMillis(2), 100); final SubscriptionCursor toCommit = client.getBatches().get(0).getCursor(); client.close(); Thread.sleep(TimeUnit.SECONDS.toMillis(1)); final int statusCode = commitCursors( subscription.getId(), Collections.singletonList(toCommit), client.getSessionId()); Assert.assertEquals(SC_NO_CONTENT, statusCode); }
Source:
<code>public CurrencyAmount minus(CurrencyAmount amountToSubtract) { <START> ArgChecker.notNull(amountToSubtract, "amountToAdd"); <END> ArgChecker.isTrue(amountToSubtract.getCurrency().equals(currency), "Unable to subtract amounts in different currencies"); return minus(amountToSubtract.getAmount()); }</code><technical_language>Copy-paste error in arg nonNull</technical_language>

Target:
public CurrencyAmount minus(CurrencyAmount amountToSubtract) { ArgChecker.notNull(amountToSubtract, "amountToSubtract"); ArgChecker.isTrue(amountToSubtract.getCurrency().equals(currency), "Unable to subtract amounts in different currencies"); return minus(amountToSubtract.getAmount()); }
Source:
<code>public static String formatWaypointInfo(final Waypoint waypoint) { final List<String> infos = new ArrayList<>(3); final WaypointType waypointType = waypoint.getWaypointType(); if (waypointType != WaypointType.OWN && waypointType != null) { infos.add(waypointType.getL10n()); } <START> if (waypoint.getPrefix().toUpperCase().startsWith(Waypoint.PREFIX_OWN.toUpperCase())) { <END> infos.add(CgeoApplication.getInstance().getString(R.string.waypoint_custom)); } else { if (StringUtils.isNotBlank(waypoint.getPrefix())) { infos.add(waypoint.getPrefix()); } if (StringUtils.isNotBlank(waypoint.getLookup())) { infos.add(waypoint.getLookup()); } } return StringUtils.join(infos, SEPARATOR); }</code><technical_language>I feel comfortable assuming getPrefix() returns null. establish adding necessary NonNull annotations</technical_language>

Target:
public static String formatWaypointInfo(final Waypoint waypoint) { final List<String> infos = new ArrayList<>(3); final WaypointType waypointType = waypoint.getWaypointType(); if (waypointType != WaypointType.OWN && waypointType != null) { infos.add(waypointType.getL10n()); } if (waypoint.isUserDefined()) { infos.add(CgeoApplication.getInstance().getString(R.string.waypoint_custom)); } else { if (StringUtils.isNotBlank(waypoint.getPrefix())) { infos.add(waypoint.getPrefix()); } if (StringUtils.isNotBlank(waypoint.getLookup())) { infos.add(waypoint.getLookup()); } } return StringUtils.join(infos, SEPARATOR); }
Source:
<code>private List<DiscoverySelector> getSelectorsFromSuppliedSelectors(BundleDescriptor bd) { List<DiscoverySelector> selectors = new ArrayList<>(); Bundle bundle = bd.getBundle(); Bundle host = BundleUtils.getHost(bundle) .get(); Set<String> testCases = BundleUtils.testCases(bundle) .collect(toSet()); classSelectors.stream() .map(ClassSelector::getClassName) .filter(testCases::contains) .forEach(className -> { try { Class<?> testClass = host.loadClass(className); unresolvedClasses.remove(className); info(() -> "removing resolved class: " + testClass + ", that leaves: " + unresolvedClasses); if (resolvedClasses.add(testClass)) { selectors.add(selectClass(testClass)); } } catch (ClassNotFoundException cnfe) { info(() -> "Unresolved class: " + className + ", bundle: " + bundle.getSymbolicName(), cnfe); } }); methodSelectors.stream() <START> .filter(x -> testCases.contains(x.getClassName())) <END> .forEach(selector -> { try { Class<?> testClass = host.loadClass(selector.getClassName()); if (!resolvedClasses.contains(testClass)) { selectors .add(selectMethod(testClass, selector.getMethodName(), selector.getMethodParameterTypes())); unresolvedClasses.remove(selector.getClassName()); } } catch (ClassNotFoundException cnfe) { info(() -> "Unresolved class: " + selector.getClassName() + ", bundle: " + bundle.getSymbolicName(), cnfe); } }); info(() -> "Selectors: " + selectors); return selectors; }</code><technical_language>Please meaningful variable names. x is unhelpful in reading code</technical_language>

Target:
private List<DiscoverySelector> getSelectorsFromSuppliedSelectors(BundleDescriptor bd) { List<DiscoverySelector> selectors = new ArrayList<>(); Bundle bundle = bd.getBundle(); Bundle host = BundleUtils.getHost(bundle) .get(); Set<String> testCases = BundleUtils.testCases(bundle) .collect(toSet()); classSelectors.stream() .map(ClassSelector::getClassName) .filter(testCases::contains) .forEach(className -> { try { Class<?> testClass = host.loadClass(className); unresolvedClasses.remove(className); info(() -> "removing resolved class: " + testClass + ", that leaves: " + unresolvedClasses); if (resolvedClasses.add(testClass)) { selectors.add(selectClass(testClass)); } } catch (ClassNotFoundException cnfe) { info(() -> "Unresolved class: " + className + ", bundle: " + bundle.getSymbolicName(), cnfe); } }); methodSelectors.stream() .filter(selector -> testCases.contains(selector.getClassName())) .forEach(selector -> { try { Class<?> testClass = host.loadClass(selector.getClassName()); if (!resolvedClasses.contains(testClass)) { selectors .add(selectMethod(testClass, selector.getMethodName(), selector.getMethodParameterTypes())); unresolvedClasses.remove(selector.getClassName()); } } catch (ClassNotFoundException cnfe) { info(() -> "Unresolved class: " + selector.getClassName() + ", bundle: " + bundle.getSymbolicName(), cnfe); } }); info(() -> "Selectors: " + selectors); return selectors; }
Source:
<code>public IVariable[] getVariables(int offset, int length) throws DebugException { if (offset >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_6, new IndexOutOfBoundsException(Integer.toString(offset))); } if <START> ((offset + length - 1) >= <END> getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_8, new IndexOutOfBoundsException(Integer.toString(offset))); } IVariable[] variables = new IVariable[length]; int index = offset; for (int i = 0; i < length; i++) { variables[i] = new JDIArrayEntryVariable(getJavaDebugTarget(), getArrayReference(), index, fLogicalParent); index++; } return variables; }</code><technical_language>This is caused problem. Please change message</technical_language>

Target:
public IVariable[] getVariables(int offset, int length) throws DebugException { if (offset >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_6, new IndexOutOfBoundsException(Integer.toString(offset))); } if ((offset + length - 1) >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_8, new IndexOutOfBoundsException(Integer.toString(offset + length - 1))); } IVariable[] variables = new IVariable[length]; int index = offset; for (int i = 0; i < length; i++) { variables[i] = new JDIArrayEntryVariable(getJavaDebugTarget(), getArrayReference(), index, fLogicalParent); index++; } return variables; }
Source:
<code>public void testGetDocContent_customAuthenticatedUsers() throws Exception { options = TestObjectFactory.newConfigOptions( <START> ImmutableMap.<String, String>of( <END> "filenet.authenticatedUsersGroup", "cn=AuthenticatedUsers,ou=users,dc=example,dc=com")); testGetDocContent_authenticatedUsers("AuthenticatedUsers@example.com"); }</code><technical_language>need <String, String> here</technical_language>

Target:
public void testGetDocContent_customAuthenticatedUsers() throws Exception { options = TestObjectFactory.newConfigOptions( ImmutableMap.of( "filenet.authenticatedUsersGroup", "cn=AuthenticatedUsers,ou=users,dc=example,dc=com")); testGetDocContent_authenticatedUsers("AuthenticatedUsers@example.com"); }
Source:
<code>public int kafkaPartition(RowMap r, int numPartitions) { int partition = Math.abs(hashFunc.hashCode(this.getHashString(r)) % numPartitions); System.out.println("partition:" + partition); <START> return partition; <END> }</code><technical_language>get rid of this</technical_language>

Target:
public int kafkaPartition(RowMap r, int numPartitions) { return Math.abs(hashFunc.hashCode(this.getHashString(r)) % numPartitions); }
Source:
<code>public Object execute(ExecutionEvent event) { final IWorkbenchPart activePart = HandlerUtil.getActivePart(event); if(activePart instanceof CommonNavigator) { final CommonViewer viewer = ((CommonNavigator)activePart).getCommonViewer(); final ITreeSelection selection = (ITreeSelection) viewer.getSelection(); for (TreePath treePath : selection.getPaths()) { final IDockerConnection conn = (IDockerConnection) treePath .getLastSegment(); if (!conn.isOpen()) { final Job openConnectionJob = new Job( CommandMessages.getFormattedString( "command.enableconnection", conn.getUri())) { @Override protected IStatus run(IProgressMonitor monitor) { try { conn.open(true); } catch (DockerException e) { Activator .logErrorMessage( CommandMessages.getString( "command.enableconnection.failure"), e); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; openConnectionJob <START> .addJobChangeListener(new <END> JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { if (event.getResult().isOK()) { Display.getDefault().asyncExec( () -> viewer.refresh(conn)); } } }); openConnectionJob.schedule(); } } } return null; }</code><technical_language>Again, I try avoid JobChangeListener, conn.open(true)</technical_language>

Target:
public Object execute(ExecutionEvent event) { final IWorkbenchPart activePart = HandlerUtil.getActivePart(event); if(activePart instanceof CommonNavigator) { final CommonViewer viewer = ((CommonNavigator)activePart).getCommonViewer(); final ITreeSelection selection = (ITreeSelection) viewer.getSelection(); for (TreePath treePath : selection.getPaths()) { final IDockerConnection conn = (IDockerConnection) treePath .getLastSegment(); if (!conn.isOpen()) { final Job openConnectionJob = new Job( CommandMessages.getFormattedString( "command.enableconnection", conn.getUri())) { @Override protected IStatus run(IProgressMonitor monitor) { try { conn.open(true); Display.getDefault() .asyncExec(() -> viewer.refresh(conn)); } catch (DockerException e) { Activator .logErrorMessage( CommandMessages.getString( "command.enableconnection.failure"), e); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; openConnectionJob.schedule(); } } } return null; }
Source:
<code>public void checkInitialized(final int zoom, NativeOsmandLibrary library, int leftX, int rightX, int bottomY, int topY) { if(library == null) { return; } boolean useLive = context.getSettings().USE_OSM_LIVE_FOR_ROUTING.get(); for (String mapName : files.keySet()) { BinaryMapIndexReader fr = files.get(mapName); if (fr != null && (fr.containsMapData(leftX, topY, rightX, bottomY, zoom) || fr.containsRouteData(leftX, topY, rightX, bottomY, zoom))) { <START> if (!Algorithms.isEmpty(fr.getCountryName())) { <END> TransliterationHelper.setCountry(fr.getCountryName()); } if (!nativeFiles.contains(mapName)) { long time = System.currentTimeMillis(); nativeFiles.add(mapName); if (!library.initMapFile(fr.getFile().getAbsolutePath(), useLive)) { continue; } log.debug("Native resource " + mapName + " initialized " + (System.currentTimeMillis() - time) + " ms"); } } } }</code><technical_language>if files map data is japan is japan</technical_language>

Target:
public void checkInitialized(final int zoom, NativeOsmandLibrary library, int leftX, int rightX, int bottomY, int topY) { if(library == null) { return; } boolean containsJapanMapData = false; boolean useLive = context.getSettings().USE_OSM_LIVE_FOR_ROUTING.get(); for (String mapName : files.keySet()) { BinaryMapIndexReader fr = files.get(mapName); if (fr != null && (fr.containsMapData(leftX, topY, rightX, bottomY, zoom) || fr.containsRouteData(leftX, topY, rightX, bottomY, zoom))) { if (!nativeFiles.contains(mapName)) { long time = System.currentTimeMillis(); nativeFiles.add(mapName); if (!library.initMapFile(fr.getFile().getAbsolutePath(), useLive)) { continue; } log.debug("Native resource " + mapName + " initialized " + (System.currentTimeMillis() - time) + " ms"); } if (fr.getCountryName().equals("Japan")) { containsJapanMapData = true; } } } if (containsJapanMapData) { TransliterationHelper.setCountryName("Japan"); } else { TransliterationHelper.setCountryName(""); } }
Source:
<code>public CompletionStage<Iterable<NodeInfo>> refreshNodeList() { if (closeFuture.isDone()) { return CompletableFutures.failedFuture(new IllegalStateException("closed")); } LOG.debug("[{}] Refreshing node list", logPrefix); DriverChannel channel = controlConnection.channel(); InetSocketAddress controlAddress = (InetSocketAddress) channel.remoteAddress(); savePort(channel); CompletionStage<AdminResult> localQuery = query(channel, "SELECT * FROM system.local"); CompletionStage<AdminResult> peersV2Query = query(channel, "SELECT * FROM system.peers_v2"); <START> CompletableFuture<AdminResult> peersQ = new CompletableFuture<>(); <END> peersV2Query.whenComplete( (r, t) -> { if (t != null) { this.isSchemaV2 = false; query(channel, "SELECT * FROM system.peers") .whenComplete( (r2, t2) -> { peersQ.complete(r2); }); } else { peersQ.complete(r); } }); return localQuery.thenCombine( peersQ, (controlNodeResult, peersResult) -> { List<NodeInfo> nodeInfos = new ArrayList<>(); nodeInfos.add( nodeInfoBuilder(controlNodeResult.iterator().next(), controlAddress).build()); for (AdminRow row : peersResult) { nodeInfos.add(asNodeInfo(row)); } return nodeInfos; }); }</code><technical_language>Nit: name this Query other variables</technical_language>

Target:
public CompletionStage<Iterable<NodeInfo>> refreshNodeList() { if (closeFuture.isDone()) { return CompletableFutures.failedFuture(new IllegalStateException("closed")); } LOG.debug("[{}] Refreshing node list", logPrefix); DriverChannel channel = controlConnection.channel(); InetSocketAddress controlAddress = (InetSocketAddress) channel.remoteAddress(); savePort(channel); CompletionStage<AdminResult> localQuery = query(channel, "SELECT * FROM system.local"); CompletionStage<AdminResult> peersV2Query = query(channel, "SELECT * FROM system.peers_v2"); CompletableFuture<AdminResult> peersQuery = new CompletableFuture<>(); peersV2Query .whenComplete( (r, t) -> { if (t != null) { this.isSchemaV2 = false; CompletableFutures.completeFrom( query(channel, "SELECT * FROM system.peers"), peersQuery); } else { peersQuery.complete(r); } }) .exceptionally(UncaughtExceptions::log); return localQuery.thenCombine( peersQuery, (controlNodeResult, peersResult) -> { List<NodeInfo> nodeInfos = new ArrayList<>(); nodeInfos.add( nodeInfoBuilder(controlNodeResult.iterator().next(), controlAddress).build()); for (AdminRow row : peersResult) { nodeInfos.add(asNodeInfo(row)); } return nodeInfos; }); }
Source:
<code>protected Map<String, Queue> getQueueNamesToQueues() { HashMap<String, Queue> map = new HashMap<>(); <START> if (this.queues.size() > 0) { <END> this.queues.stream() .filter(q -> StringUtils.hasText(q.getName()) || StringUtils.hasText(q.getDeclaredName())) .forEach(q -> map.put(StringUtils.hasText(q.getName()) ? q.getName() : q.getDeclaredName(), q)); } return map; }</code><technical_language>I need this if if stream() List. is a .collect(Collectors.toMap(...))</technical_language>

Target:
protected Map<String, Queue> getQueueNamesToQueues() { return this.queues.stream() .collect(Collectors.toMap(Queue::getActualName, q -> q)); }
Source:
<code>private String getFooter() { try { <START> return getDriver().findElement(By.cssSelector("footer.small")).getText(); <END> } catch (Exception e) { return null; } }</code><technical_language>Catching exceptions in tests is bad! happen: - element expected existing, a false warning is logged. - element present while expected, test passes behaviour is intended is hard read more importantly, error prone. Try: java getDriver().findElements(By.id("btn-close")).stream().findAny().isPresent();</technical_language>

Target:
private Optional<String> getFooter() { return getDriver().findElements(By.cssSelector("footer.small")).stream().findAny().map(WebElement::getText); }
Source:
<code>public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { GarbageCollectionStatus details = bookieServer.getBookie().getLedgerStorage().getGarbageCollectionStatus(); String jsonResponse = JsonUtil.toJson(details); <START> LOG.debug("output body:" + jsonResponse); <END> response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Only support Get method to get GC details."); return response; } }</code><technical_language>suggestion if (LOG.isDebugEnabled()) { LOG.debug("output body: {}", jsonResponse); }</technical_language>

Target:
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { List<GarbageCollectionStatus> details = bookieServer.getBookie() .getLedgerStorage().getGarbageCollectionStatus(); String jsonResponse = JsonUtil.toJson(details); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Only support GET method to retrieve GC details." + " If you want to trigger gc, send a POST to gc endpoint."); return response; } }
Source:
<code>public ResponseEntity removeStorage(@ApiParam(value = "The storageId", required = true) @PathVariable final String storageId, @ApiParam(value = "Whether to force delete and remove the storage from the file system") @RequestParam(name = "force", defaultValue = "false") final boolean force) throws IOException, JAXBException { if (configurationManagementService.getStorage(storageId) != null) { try { repositoryIndexManager.closeIndexersForStorage(storageId); if (force) { storageManagementService.removeStorage(storageId); } configurationManagementService.removeStorage(storageId); logger.debug("Removed storage " + storageId + "."); return ResponseEntity.ok(ResponseStatusEnum.OK.value()); } catch (IOException | JAXBException e) { logger.error(e.getMessage(), e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) <START> .body(ResponseStatusEnum.FAILED.value()); <END> } } else { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body("Storage " + storageId + " not found."); } }</code><technical_language>removed actual text response here</technical_language>

Target:
public ResponseEntity removeStorage(@ApiParam(value = "The storageId", required = true) @PathVariable final String storageId, @ApiParam(value = "Whether to force delete and remove the storage from the file system") @RequestParam(name = "force", defaultValue = "false") final boolean force) throws IOException, JAXBException { if (configurationManagementService.getStorage(storageId) != null) { try { repositoryIndexManager.closeIndexersForStorage(storageId); if (force) { storageManagementService.removeStorage(storageId); } configurationManagementService.removeStorage(storageId); logger.debug("Removed storage " + storageId + "."); return ResponseEntity.ok("The storage was removed successfully."); } catch (IOException | JAXBException e) { logger.error(e.getMessage(), e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Failed to remove storage " + storageId + "!"); } } else { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body("Storage " + storageId + " not found."); } }
Source:
<code>public void testName() throws Exception { String name = "Foobar"; <START> assertThat(simpleObject.getName()).isNull(); <END> simpleObject.setName(name); assertThat(simpleObject.getName()).isEqualTo(name); }</code><technical_language>assertNull(simpleObject.getName()) here</technical_language>

Target:
public void testName() throws Exception { String name = "Foobar"; assertNull(simpleObject.getName()); simpleObject.setName(name); assertEquals(name, simpleObject.getName()); }
Source:
<code>public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { ServerAuthDialogBinding binding = ServerAuthDialogBinding.inflate(requireActivity().getLayoutInflater()); dialogView = binding.getRoot(); SharedPreferences generalSharedPreferences = preferencesProvider.getGeneralSharedPreferences(); binding.usernameEdit.setText(generalSharedPreferences.getString(GeneralKeys.KEY_USERNAME, "")); binding.passwordEdit.setText(generalSharedPreferences.getString(GeneralKeys.KEY_PASSWORD, "")); return new AlertDialog.Builder(requireContext()) <START> .setTitle(R.string.server_requires_auth) <END> .setView(dialogView) .setPositiveButton(R.string.ok, (dialogInterface, i) -> { generalSharedPreferences.edit() .putString(GeneralKeys.KEY_USERNAME, binding.usernameEdit.getText().toString()) .putString(GeneralKeys.KEY_PASSWORD, binding.passwordEdit.getText().toString()) .apply(); }) .create(); }</code><technical_language>for manual update case, this include string server_auth_credentials server needs credentials</technical_language>

Target:
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { ServerAuthDialogBinding binding = ServerAuthDialogBinding.inflate(requireActivity().getLayoutInflater()); dialogView = binding.getRoot(); SharedPreferences generalSharedPreferences = preferencesProvider.getGeneralSharedPreferences(); binding.usernameEdit.setText(generalSharedPreferences.getString(GeneralKeys.KEY_USERNAME, "")); binding.passwordEdit.setText(generalSharedPreferences.getString(GeneralKeys.KEY_PASSWORD, "")); return new AlertDialog.Builder(requireContext()) .setTitle(R.string.server_requires_auth) .setMessage(requireContext().getString(R.string.server_auth_credentials, generalSharedPreferences.getString(GeneralKeys.KEY_SERVER_URL, ""))) .setView(dialogView) .setPositiveButton(R.string.ok, (dialogInterface, i) -> { generalSharedPreferences.edit() .putString(GeneralKeys.KEY_USERNAME, binding.usernameEdit.getText().toString()) .putString(GeneralKeys.KEY_PASSWORD, binding.passwordEdit.getText().toString()) .apply(); }) .create(); }
Source:
<code>public DropwizardTestSupport(Class<? extends Application<C>> applicationClass, C configuration) { if (configuration == null) { throw new IllegalArgumentException("Can not pass null configuration for explicitly configured instance"); } this.applicationClass = applicationClass; configPath = ""; <START> configOverrides = Collections.emptySet(); <END> customPropertyPrefix = Optional.absent(); this.configuration = configuration; explicitConfig = true; }</code><technical_language>ImmutableSet.of() in order consistent other constructor</technical_language>

Target:
public DropwizardTestSupport(Class<? extends Application<C>> applicationClass, C configuration) { if (configuration == null) { throw new IllegalArgumentException("Can not pass null configuration for explicitly configured instance"); } this.applicationClass = applicationClass; configPath = ""; configOverrides = ImmutableSet.of(); customPropertyPrefix = Optional.absent(); this.configuration = configuration; explicitConfig = true; }
Source:
<code>private Long appendWithOffset(long offset, boolean isControlRecord, long timestamp, ByteBuffer key, ByteBuffer value, Header[] headers) { try { if (isControlRecord != isControlBatch) throw new IllegalArgumentException("Control records can only be appended to control batches"); if (lastOffset != null && offset <= lastOffset) throw new IllegalArgumentException(String.format("Illegal offset %s following previous offset %s " + "(Offsets must increase monotonically).", offset, lastOffset)); if (timestamp < 0 && timestamp != RecordBatch.NO_TIMESTAMP) throw new IllegalArgumentException("Invalid negative timestamp " + timestamp); if (magic < RecordBatch.MAGIC_VALUE_V2 && headers != null && headers.length > 0) throw new IllegalArgumentException("Magic v" + magic + " does not support record headers"); if (firstTimestamp == null) { if (deleteHorizonSet()) <START> firstTimestamp = deleteHorizonMs; <END> else firstTimestamp = timestamp; } if (magic > RecordBatch.MAGIC_VALUE_V1) { appendDefaultRecord(offset, timestamp, key, value, headers); return null; } else { return appendLegacyRecord(offset, timestamp, key, value, magic); } } catch (IOException e) { throw new KafkaException("I/O exception when writing to the append stream, closing", e); } }</code><technical_language>updating firstTimestamp a record appended. create empty batch delete horizon set? I expect constructor initialize firstTimestamp deleteHorizonMs if is greater 0</technical_language>

Target:
private Long appendWithOffset(long offset, boolean isControlRecord, long timestamp, ByteBuffer key, ByteBuffer value, Header[] headers) { try { if (isControlRecord != isControlBatch) throw new IllegalArgumentException("Control records can only be appended to control batches"); if (lastOffset != null && offset <= lastOffset) throw new IllegalArgumentException(String.format("Illegal offset %s following previous offset %s " + "(Offsets must increase monotonically).", offset, lastOffset)); if (timestamp < 0 && timestamp != RecordBatch.NO_TIMESTAMP) throw new IllegalArgumentException("Invalid negative timestamp " + timestamp); if (magic < RecordBatch.MAGIC_VALUE_V2 && headers != null && headers.length > 0) throw new IllegalArgumentException("Magic v" + magic + " does not support record headers"); if (firstTimestamp == null) firstTimestamp = timestamp; if (magic > RecordBatch.MAGIC_VALUE_V1) { appendDefaultRecord(offset, timestamp, key, value, headers); return null; } else { return appendLegacyRecord(offset, timestamp, key, value, magic); } } catch (IOException e) { throw new KafkaException("I/O exception when writing to the append stream, closing", e); } }
Source:
<code>private String createUploadUrl() { try { String blobId = ResourceId.generateId().asString(); String fileName = fileName(); String mimeType = MimeTypeUtil.mimeTypeFromFileName(fileName); attachment.get().setMimeType(mimeType); attachment.get().setFilename(fileName); attachment.get().setBlobId(blobId); return "/service/blob/credentials/" + blobId; } catch (Exception e) { Log.error(e.getMessage(), e); <START> Window.alert(I18N.CONSTANTS.failedToCreateUploadUrl()); <END> throw e; } }</code><technical_language>this error message is useful for users. report upload failed? add more details in logging. Is a retry path</technical_language>

Target:
private String createUploadUrl() { String blobId = ResourceId.generateId().asString(); String fileName = fileName(); String mimeType = MimeTypeUtil.mimeTypeFromFileName(fileName, "application/octet-stream"); attachment.setMimeType(mimeType); attachment.setFilename(fileName); attachment.setBlobId(blobId); return "/service/blob/credentials/" + blobId + "/" + resourceId.asString() + "/" + fileName; }
Source:
<code>public String getRule() { <START> return "Whenever an opponent draws a card except the first one they draw in each of their draw steps" + super.getRule(); <END> }</code><technical_language>put ability text instead of calling super if add a comma "steps"</technical_language>

Target:
public String getRule() { return "Whenever an opponent draws a card except the first one they draw in each of their draw steps, create a 1/1 green Snake creature token."; }
Source:
<code>public void writeRound(long seq, V round) { lock.writeLock().lock(); try { currentLog.writeRound(seq, round); experimentalLog.writeRound(seq, round); <START> } finally { <END> lock.writeLock().unlock(); } }</code><technical_language>This is a bit nasty, prefer lock(); try { current.write(seq, round); try { experiment.write(seq, round); } catch (RuntimeException ex) { log.warn("I wrote current experimental, please careful future errors for sequence number {}", SafeArg.of(seq), ex); // intentionally succeed, want degrade service } } finally { unlock(); }</technical_language>

Target:
public void writeRound(long seq, V round) { lock.writeLock().lock(); try { currentLog.writeRound(seq, round); try { experimentalLog.writeRound(seq, round); } catch (RuntimeException e) { log.warn("Succeeded writing round for sequence number to the current log, but failed to write to " + "experimental. This may cause future verification for this round to fail.", SafeArg.of("sequence", seq), e); } } finally { lock.writeLock().unlock(); } }
Source:
<code>public void close() { try { fileReftableStack().explicitClose(); } catch (IOException e) { <START> <END> } }</code><technical_language>log exception</technical_language>

Target:
public void close() { try { fileReftableStack().explicitClose(); } catch (IOException e) { LOG.error(e.getMessage(), e); } }
Source:
<code><START> public static void enable() { <END> if (CLIENT_STATS == null) { CLIENT_STATS = new MetricRegistry(); } }</code><technical_language>synchronize, this is called safe I missed</technical_language>

Target:
public synchronized static void enable() { if (CLIENT_STATS == null) { CLIENT_STATS = new MetricRegistry(); } }
Source:
<code>public void setCurrentFilePaths(List<String> filePaths) throws OrmException { PatchSet ps = currentPatchSet(); if (ps != null) { <START> files.put(Integer.valueOf(ps.getPatchSetId()), <END> ImmutableList.copyOf(filePaths)); } }</code><technical_language>This is redundant, auto-boxing work fine IIRC JGit warn auto-boxing in Gerrit</technical_language>

Target:
public void setCurrentFilePaths(List<String> filePaths) throws OrmException { PatchSet ps = currentPatchSet(); if (ps != null) { files.put(ps.getPatchSetId(), ImmutableList.copyOf(filePaths)); } }
Source:
<code>public void before_ConflictTests() throws Exception { sprocBody = IOUtils.toString( getClass().getClassLoader().getResourceAsStream("conflict-resolver-sproc"), "UTF-8"); globalClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .endpointDiscoveryEnabled(false) .directMode() .buildAsyncClient(); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager((RxDocumentClientImpl) globalClient.getContextClient()); DatabaseAccount databaseAccount = globalEndpointManager.getLatestDatabaseAccount(); Iterator<DatabaseAccountLocation> locationIterator = databaseAccount.getWritableLocations().iterator(); regionalClients = new ArrayList<>(); while (locationIterator.hasNext()) { DatabaseAccountLocation accountLocation = locationIterator.next(); CosmosAsyncClient regionalClient = new CosmosClientBuilder() <START> .endpoint(accountLocation.getEndpoint()) <END> .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .endpointDiscoveryEnabled(false) .directMode() .buildAsyncClient(); regionalClients.add(regionalClient); } }</code><technical_language>pass regional account endpoint CosmosClientBuilder. instead pass global account endpoint set preferred region local region of interest</technical_language>

Target:
public void before_ConflictTests() throws Exception { sprocBody = IOUtils.toString( getClass().getClassLoader().getResourceAsStream("conflict-resolver-sproc"), "UTF-8"); globalClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .endpointDiscoveryEnabled(false) .directMode() .buildAsyncClient(); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager((RxDocumentClientImpl) globalClient.getContextClient()); DatabaseAccount databaseAccount = globalEndpointManager.getLatestDatabaseAccount(); Iterator<DatabaseAccountLocation> locationIterator = databaseAccount.getWritableLocations().iterator(); regionalClients = new ArrayList<>(); while (locationIterator.hasNext()) { DatabaseAccountLocation accountLocation = locationIterator.next(); List<String> prefferedLocations = new ArrayList<>(); prefferedLocations.add(accountLocation.getName()); CosmosAsyncClient regionalClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .preferredRegions(prefferedLocations) .directMode() .buildAsyncClient(); regionalClients.add(regionalClient); } }
Source:
<code>private boolean isUMLMetaModel(URI normalizedURI) { URI noFragmentURI = normalizedURI.trimFragment(); String[] segments = noFragmentURI.segments(); return <START> segments.length > 0 && segments[segments.length - 1].equals("UML.metamodel.uml"); END> }</code><technical_language>check for full URI? this full URI name constant? Thanks</technical_language>

Target:
private boolean isUMLMetaModel(URI normalizedURI) { URI noFragmentURI = normalizedURI.trimFragment(); return PLATFORM_UML_METAMODEL_URI.equals(noFragmentURI.toString()); }
Source:
<code>public void testGetStorageDomainIdWithNoPermissions() { Guid storagePoolId = getQueryParameters().getStoragePoolId(); storage_pool pool = new storage_pool(); pool.setId(storagePoolId); StoragePoolDAO storagePoolDAOMock = mock(StoragePoolDAO.class); when(storagePoolDAOMock.get( storagePoolId, getUser().getUserId(), getQueryParameters().isFiltered())).thenReturn(pool); <START> when(getQuery().getDbFacade().getStoragePoolDAO()).thenReturn(null); <END> verifyNoMoreInteractions(getQuery().getDbFacade()); assertNull("No storage domains should have been returned", null); }</code><technical_language>I this code is in earlier test, extracted for easier read, return parameter</technical_language>

Target:
public void testGetStorageDomainIdWithNoPermissions() { mockStoragePoolDAO(null); verifyNoMoreInteractions(getQuery().getDbFacade()); assertNull("No storage domains should have been returned", getQuery().getStorageDomainId()); }
Source:
<code>public static void copySecretsToJob(Properties props, Map<String, String> jobSecrets) { checkRequiredPropertiesAreDefined(props); resolveMetadata(props); String secret = props.getProperty(CONFIG_PWD); if (secret != null) { <START> jobSecrets.put(CONFIG_PWD, secret); <END> } }</code><technical_language>expert..but this is adding passwords plain text</technical_language>

Target:
public static void copySecretsToJob(Properties props, Map<String, String> jobSecrets) throws HiveException, IOException { checkRequiredPropertiesAreDefined(props); resolveMetadata(props); String secret = props.getProperty(CONFIG_PWD); if (secret != null) { jobSecrets.put(CONFIG_PWD, secret); } }
Source:
<code>public static MessageDTO jsonNodeToMessage(JsonNode jsonNode) { ObjectMapper mapper = new ObjectMapper(); final MessageDTO messageDTO = mapper.convertValue(jsonNode, MessageDTO.class); <START> return messageDTO; <END> }</code><technical_language>need for temp variable - return mapper.convertValue(...)'s result</technical_language>

Target:
public static MessageDTO jsonNodeToMessage(JsonNode jsonNode) { return OBJECT_MAPPER.convertValue(jsonNode, MessageDTO.class); }
Source:
<code>private boolean tryCollectLoot(SolObject obj, SolGame game) { if (!(obj instanceof Loot)) { return false; } if (!myPilot.collectsItems()) { return false; } Loot loot = (Loot) obj; if (loot.getOwner() == this) { return false; } SolItem i = loot.getItem(); if (i == null) { return false; } i.setEquipped(0); if (i instanceof MoneyItem) { myMoney += i.getPrice(); return true; } ItemContainer c = shouldTrade(i, game) ? myTradeContainer.getItems() : myItemContainer; boolean canAdd = c.canAdd(i); if (canAdd) { c.add(i); <START> if (c == myItemContainer && myPilot.getMapHint().equals("Merc")) { <END> } } return canAdd; }</code><technical_language>I noticed this change a NullPointerException crash, Pilot.getMapHint return null. Examples of map hint is set null: <LINK_1> <LINK_4> <LINK_3> <LINK_0> This issue is handled in BeaconHandler class: <LINK_2> Personally, I suggest changing line similar (untested code): java String mapHint = myPilot.getMapHint(); if (c == myItemContainer && mapHint != null && mapHint.equals("Merc")) previous code crash access of strings directly. I hope this helps, able trigger crash destroying a ship in-game collecting "loot"</technical_language>

Target:
private boolean tryCollectLoot(SolObject obj, SolGame game) { if (!(obj instanceof Loot)) { return false; } if (!myPilot.collectsItems()) { return false; } Loot loot = (Loot) obj; if (loot.getOwner() == this) { return false; } SolItem i = loot.getItem(); if (i == null) { return false; } i.setEquipped(0); if (i instanceof MoneyItem) { myMoney += i.getPrice(); return true; } ItemContainer c = shouldTrade(i, game) ? myTradeContainer.getItems() : myItemContainer; boolean canAdd = c.canAdd(i); if (canAdd) { c.add(i); if (c == myItemContainer && Objects.equals(myPilot.getMapHint(), "Merc")) { } } return canAdd; }
Source:
<code>public void echoFail() throws TException { try { client.echoFail(KITTY_MSG); <START> Assert.fail(); <END> } catch (Exception e) { Assert.assertEquals(TApplicationException.class.getName(), e.getClass().getName()); } echoPass(); }</code><technical_language>Message test failed, please</technical_language>

Target:
public void echoFail() throws TException { try { client.echoFail(KITTY_MSG); Assert.fail("Thrift client did not throw an expected exception"); } catch (Exception e) { Assert.assertEquals(TApplicationException.class.getName(), e.getClass().getName()); } echoPass(); }
Source:
<code>public void testToString() { <START> assertEquals("value", StringUtility.toString("value")); <END> assertEquals("valueWhenNull", StringUtility.toString(null, "valueWhenNull")); assertEquals("5", StringUtility.toString(Integer.valueOf(5), "valueWhenNull")); Object o = new Object() { @Override public String toString() { return "object"; } }; assertEquals("object", StringUtility.toString(o)); }</code><technical_language>This test test case StringUtility.toString(null)</technical_language>

Target:
public void testToString() { assertEquals("value", StringUtility.toString("value")); assertEquals("valueWhenNull", StringUtility.toString(null, "valueWhenNull")); assertEquals("5", StringUtility.toString(Integer.valueOf(5), "valueWhenNull")); Object o = new Object() { @Override public String toString() { return "object"; } }; assertEquals("object", StringUtility.toString(o)); assertNull(StringUtility.toString(null)); assertNull(StringUtility.toString(null, null)); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserConfig other = (UserConfig) o; return new EqualsBuilder() .append(configurableRuleValues, other.configurableRuleValues) .append(userDictName, other.userDictName) .append(userSpecificSpellerWords, other.userSpecificSpellerWords) .isEquals(); <START> } <END></code><technical_language>This is in hashCode, is purpose? maxSpellingSuggestions is in hashCode here</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserConfig other = (UserConfig) o; return new EqualsBuilder() .append(maxSpellingSuggestions, other.maxSpellingSuggestions) .append(configurableRuleValues, other.configurableRuleValues) .append(userDictName, other.userDictName) .append(userSpecificSpellerWords, other.userSpecificSpellerWords) .isEquals(); }