auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Response getAssignmentPage(@PathParam("courseCode") String courseCode, @PathParam("editionCode") String editionCode, @PathParam("assignmentId") Long assignmentId) throws IOException { CourseEdition course = courses.find(courseCode, editionCode); if(!(currentUser.isAdmin() || currentUser.isAssisting(course))) { throw new UnauthorizedException(); } Assignment assignment = assignmentsDAO.find(course, assignmentId); List<Delivery> userDeliveries = assignedTAs.getLastDeliveries(assignment, currentUser); List<Delivery> lastDeliveries = deliveriesDAO.getLastDeliveries(assignment); AssignmentStats assignmentStats; <START> if(currentUser.isAdmin()) { <END> assignmentStats = deliveriesBackend.getAssignmentStats(assignment, lastDeliveries); } else { lastDeliveries.removeAll(userDeliveries); assignmentStats = deliveriesBackend.getAssignmentStats(userDeliveries); } Map<String, Object> parameters = Maps.newHashMap(); parameters.put("user", currentUser); parameters.put("course", course); parameters.put("assignment", assignment); parameters.put("assignmentStats", assignmentStats); parameters.put("deliveryStates", Delivery.State.values()); parameters.put("lastDeliveries", lastDeliveries); parameters.put("userDeliveries", userDeliveries); List<Locale> locales = Collections.list(request.getLocales()); return display(templateEngine.process("courses/assignments/assignment-view.ftl", locales, parameters)); }</code><technical_language>Yup :)</technical_language>

Target:
public Response getAssignmentPage(@PathParam("courseCode") String courseCode, @PathParam("editionCode") String editionCode, @PathParam("assignmentId") Long assignmentId) throws IOException { CourseEdition course = courses.find(courseCode, editionCode); if(!(currentUser.isAdmin() || currentUser.isAssisting(course))) { throw new UnauthorizedException(); } Assignment assignment = assignmentsDAO.find(course, assignmentId); List<Delivery> currentUserDeliveries = assignedTAs.getLastDeliveries(assignment, currentUser); List<Delivery> allLastDeliveries = deliveriesDAO.getLastDeliveries(assignment); List<Delivery> filteredDeliveries = deliveriesDAO.getLastDeliveries(assignment); filteredDeliveries.removeAll(currentUserDeliveries); AssignmentStats userStats = deliveriesBackend.getAssignmentStats(currentUserDeliveries); AssignmentStats lastStats = deliveriesBackend.getAssignmentStats(assignment, allLastDeliveries); Map<String, Object> parameters = Maps.newHashMap(); parameters.put("user", currentUser); parameters.put("course", course); parameters.put("assignment", assignment); parameters.put("userStats", userStats); parameters.put("lastStats", lastStats); parameters.put("deliveryStates", Delivery.State.values()); parameters.put("userDeliveries", currentUserDeliveries); parameters.put("lastDeliveries", allLastDeliveries); parameters.put("filteredDeliveries", filteredDeliveries); List<Locale> locales = Collections.list(request.getLocales()); return display(templateEngine.process("courses/assignments/assignment-view.ftl", locales, parameters)); }
Source:
<code>private static void assertDoesNotThrow(Executable executable, Object messageOrSupplier) { try { executable.execute(); } catch (Throwable t) { <START> String message = buildPrefix(nullSafeGet(messageOrSupplier)) + "Unexpected exception thrown: " <END> + t.getClass().getName() + addThrowableMessage(t); throw new AssertionFailedError(message, t); } }</code><technical_language>This line String message = buildPrefix(nullSafeGet(messageOrSupplier)) + "Unexpected exception thrown: " is duplicated below. Merge a new private createMessage(messageOrSupplier, t) a createAssertionFailedError(messageOrSupplier, t)</technical_language>

Target:
private static void assertDoesNotThrow(Executable executable, Object messageOrSupplier) { try { executable.execute(); } catch (Throwable t) { throw createAssertionFailedError(messageOrSupplier, t); } }
Source:
<code>public List<InetSocketAddress> getAllAddresses() { <START> return new LinkedList<>(addresses); <END> }</code><technical_language>unmodifiableSet() instead</technical_language>

Target:
public Set<InetSocketAddress> getAllAddresses() { return Collections.unmodifiableSet(addresses); }
Source:
<code>public EmailBuilder subject(final String val) { subject = val; String suffix = ""; if (!StringUtils.isEmpty(System.getenv("emailSubjectSuffix"))) { suffix = " [" + System.getenv("emailSubjectSuffix") + "]"; <START> subject = subject + " " + suffix; <END> } return this; }</code><technical_language>I this'll add spaces previous subject [</technical_language>

Target:
public EmailBuilder subject(final String val) { subject = val; String suffix = ""; if (!StringUtils.isEmpty(env.getProperty("emailSubjectSuffix"))) { suffix = env.getProperty("emailSubjectSuffix"); subject = subject + " " +suffix; } return this; }
Source:
<code>private Path getXDGConfigHome(FS fs) { String configHomePath = <START> SystemReader.getInstance() <END> .getenv(Constants.XDG_CONFIG_HOME); if (StringUtils.isEmptyOrNull(configHomePath)) { configHomePath = new File(fs.userHome(), ".config") .getAbsolutePath(); } if (!StringUtils.isEmptyOrNull(configHomePath)) { Path xdgHomePath = null; try { xdgHomePath = Paths.get(configHomePath); Files.createDirectories(xdgHomePath); return xdgHomePath; } catch (IOException | InvalidPathException e) { LOG.error(JGitText.get().createXDGConfigHomeFailed, xdgHomePath, e); } } return null; }</code><technical_language>this? call getenv()</technical_language>

Target:
private Path getXDGConfigHome(FS fs) { String configHomePath = getenv(Constants.XDG_CONFIG_HOME); if (StringUtils.isEmptyOrNull(configHomePath)) { configHomePath = new File(fs.userHome(), ".config") .getAbsolutePath(); } Path xdgHomePath = null; try { xdgHomePath = Paths.get(configHomePath); Files.createDirectories(xdgHomePath); return xdgHomePath; } catch (IOException | InvalidPathException e) { LOG.error(JGitText.get().createXDGConfigHomeFailed, xdgHomePath, e); } return null; }
Source:
<code>public static void writeKuraExtendedConfig( NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) throws KuraException { NetInterfaceStatus netInterfaceStatus = null; boolean gotNetConfigIP4 = false; List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig .getNetInterfaceAddresses(); <START> if (netInterfaceAddressConfigs != null && !netInterfaceAddressConfigs.isEmpty()) { <END> for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs(); if (netConfigs != null && !netConfigs.isEmpty()) { for (int i = 0; i < netConfigs.size(); i++) { NetConfig netConfig = netConfigs.get(i); if (netConfig instanceof NetConfigIP4) { netInterfaceStatus = ((NetConfigIP4) netConfig).getStatus(); gotNetConfigIP4 = true; } } } } } if (!gotNetConfigIP4) { netInterfaceStatus = NetInterfaceStatus.netIPv4StatusDisabled; } s_logger.debug("Setting NetInterfaceStatus to " + netInterfaceStatus + " for " + netInterfaceConfig.getName()); Properties kuraExtendedProps = KuranetConfig.getProperties(); if (!kuraExtendedProps.isEmpty()) { StringBuilder sb = new StringBuilder().append("net.interface.").append(netInterfaceConfig.getName()) .append(".config.ip4.status"); kuraExtendedProps.put(sb.toString(), netInterfaceStatus.toString()); try { KuranetConfig.storeProperties(kuraExtendedProps); } catch (IOException e) { s_logger.error("Failed to store properties in the kuranet.conf file ", e); throw KuraException.internalError(e.getMessage()); } } }</code><technical_language>empty check unneeded</technical_language>

Target:
public static void writeKuraExtendedConfig( NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) throws KuraException { NetInterfaceStatus netInterfaceStatus = null; boolean gotNetConfigIP4 = false; List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig .getNetInterfaceAddresses(); if (netInterfaceAddressConfigs != null) { for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs(); if (netConfigs != null) { for (int i = 0; i < netConfigs.size(); i++) { NetConfig netConfig = netConfigs.get(i); if (netConfig instanceof NetConfigIP4) { netInterfaceStatus = ((NetConfigIP4) netConfig).getStatus(); gotNetConfigIP4 = true; } } } } } if (!gotNetConfigIP4) { netInterfaceStatus = NetInterfaceStatus.netIPv4StatusDisabled; } s_logger.debug("Setting NetInterfaceStatus to " + netInterfaceStatus + " for " + netInterfaceConfig.getName()); Properties kuraExtendedProps = KuranetConfig.getProperties(); if (!kuraExtendedProps.isEmpty()) { StringBuilder sb = new StringBuilder().append("net.interface.").append(netInterfaceConfig.getName()) .append(".config.ip4.status"); kuraExtendedProps.put(sb.toString(), netInterfaceStatus.toString()); try { KuranetConfig.storeProperties(kuraExtendedProps); } catch (IOException e) { s_logger.error("Failed to store properties in the kuranet.conf file.", e); throw KuraException.internalError(e.getMessage()); } } }
Source:
<code>public TestableDataRetrieverTask(Bank bank) { <START> super(Mockito.mock(MainActivity.class), 5); <END> this.banks = new Bank[] { bank }; this.dialog = Mockito.mock(ProgressDialog.class); }</code><technical_language>Do mind extracting 5 a constant a name BANK_ID improve readability</technical_language>

Target:
public TestableDataRetrieverTask(Bank bank) { super(Mockito.mock(MainActivity.class), BANK_ID); this.banks = new Bank[] { bank }; this.dialog = Mockito.mock(ProgressDialog.class); }
Source:
<code>public FunctionLanguage getFunctionLanguage() { <START> throw new UnsupportedOperationException( <END> "This CatalogFunction is a InlineCatalogFunction. This method should not be called."); }</code><technical_language>support this method? I straightforward pass language function originated. For JAVA if I correct</technical_language>

Target:
public FunctionLanguage getFunctionLanguage() { return FunctionLanguage.JAVA; }
Source:
<code>private void ignoreVariable(VariableTree variableTree) { Symbol symbol = variableTree.symbol(); if (isCloseableOrAutoCloseableSubtype(symbol.type())) { <START> executionState.markValueAs(symbol, new CloseableState.Ignored(variableTree)); <END> } }</code><technical_language>is useless test marking ignored, symbol marked. Note symbol pass "isSymbolRelevant" test, is equivalent</technical_language>

Target:
private void ignoreVariable(VariableTree variableTree) { executionState.markValueAs(variableTree.symbol(), new CloseableState.Ignored(variableTree)); }
Source:
<code>public String format(LoggingEvent loggingEvent) { GelfMessage gelfMessage = gelfMessageAssembler.createGelfMessage(new Log4jLogEvent(loggingEvent)); <START> return gelfMessage.toJson("") + System.lineSeparator(); <END> }</code><technical_language>considered Layout#LINE_SEP? System.lineSeparator() is Java 1.7</technical_language>

Target:
public String format(LoggingEvent loggingEvent) { GelfMessage gelfMessage = gelfMessageAssembler.createGelfMessage(new Log4jLogEvent(loggingEvent)); return gelfMessage.toJson("") + Layout.LINE_SEP; }
Source:
<code>public static void activate(final IDiagramEdgeEditPart self) { final DiagramEventBroker broker = DiagramEdgeEditPartOperation.getDiagramEventBroker(self); final RoutingStyle rstyle = (RoutingStyle) self.getNotationView().getStyle(NotationPackage.eINSTANCE.getRoutingStyle()); broker.addNotificationListener(rstyle, self.getEAdapterRoutingStyle()); final IPermissionAuthority auth = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(self.getEditingDomain().getResourceSet()); auth.addAuthorityListener(self.getEditPartAuthorityListener()); EditPartAuthorityListener editModeUpdater = self.getEditPartAuthorityListener(); <START> if (editModeUpdater.shouldRefresh()) { editModeUpdater.refreshEditMode(); } <END> }</code><technical_language>this is done DiagramElementEditPartOperation.activate(this), AbstractDiagramEdgeEditPart</technical_language>

Target:
public static void activate(final IDiagramEdgeEditPart self) { final DiagramEventBroker broker = DiagramEdgeEditPartOperation.getDiagramEventBroker(self); final RoutingStyle rstyle = (RoutingStyle) self.getNotationView().getStyle(NotationPackage.eINSTANCE.getRoutingStyle()); broker.addNotificationListener(rstyle, self.getEAdapterRoutingStyle()); final IPermissionAuthority auth = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(self.getEditingDomain().getResourceSet()); EditPartAuthorityListener editPartAuthorityListener = self.getEditPartAuthorityListener(); auth.addAuthorityListener(editPartAuthorityListener); if (editPartAuthorityListener.shouldRefresh()) { editPartAuthorityListener.refreshEditMode(); } }
Source:
<code>public void execute(SensorContext context) { if (rules.length == 0) { LOG.debug("Skipping execution of eslint-based rules because none of them are activated"); return; } try { eslintBridgeServer.startServerLazily(context); Iterable<InputFile> inputFiles = getInputFiles(context); startProgressReport(inputFiles); for (InputFile inputFile : inputFiles) { if (inputFile.filename().endsWith(".vue")) { LOG.debug("Skipping analysis of Vue.js file {}", inputFile.uri()); } else { analyze(inputFile, context); } progressReport.nextFile(); } progressReport.stop(); } catch (NodeCommandException e) { <START> LOG.debug(e.getMessage()); <END> if (analysisWarnings != null) { analysisWarnings.addUnique("Some JavaScript rules were not executed. " + e.getMessage()); } } catch (Exception e) { LOG.error("Failure during analysis, " + eslintBridgeServer.getCommandInfo(), e); } finally { progressReport.cancel(); } }</code><technical_language>log thing? of a solution</technical_language>

Target:
public void execute(SensorContext context) { if (rules.length == 0) { LOG.debug("Skipping execution of eslint-based rules because none of them are activated"); return; } try { eslintBridgeServer.startServerLazily(context); Iterable<InputFile> inputFiles = getInputFiles(context); startProgressReport(inputFiles); for (InputFile inputFile : inputFiles) { if (inputFile.filename().endsWith(".vue")) { LOG.debug("Skipping analysis of Vue.js file {}", inputFile.uri()); } else { analyze(inputFile, context); } progressReport.nextFile(); } progressReport.stop(); } catch (ServerAlreadyFailedException e) { LOG.debug("Skipping start of eslint-bridge server due to the failure during first analysis"); LOG.debug("Skipping execution of eslint-based rules due to the problems with eslint-bridge server"); } catch (NodeCommandException e) { LOG.error(e.getMessage(), e); if (analysisWarnings != null) { analysisWarnings.addUnique("Some JavaScript rules were not executed. " + e.getMessage()); } } catch (Exception e) { LOG.error("Failure during analysis, " + eslintBridgeServer.getCommandInfo(), e); } finally { progressReport.cancel(); } }
Source:
<code>public void loadEmptyPage(TabPosition position) { PageTitle title = new PageTitle(Constants.EMPTY_PAGE_TITLE, app.getWikiSite()); <START> HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_MAIN_PAGE); <END> loadPage(title, historyEntry, position); }</code><technical_language>empty source</technical_language>

Target:
public void loadEmptyPage(TabPosition position) { PageTitle title = new PageTitle(Constants.EMPTY_PAGE_TITLE, app.getWikiSite()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); loadPage(title, historyEntry, position); }
Source:
<code>public static void readInputStreamAndValidateSize(InputStream inputStream, long expectedLength) throws IOException { int readVal = 0; long numRead = 0; do { readVal = inputStream.read(); numRead++; } while (readVal != -1); numRead--; <START> Assert.assertEquals(expectedLength, numRead); <END> }</code><technical_language>message</technical_language>

Target:
public static void readInputStreamAndValidateSize(InputStream inputStream, long expectedLength) throws IOException { int readVal = 0; long numRead = 0; do { readVal = inputStream.read(); numRead++; } while (readVal != -1); numRead--; Assert.assertEquals("Unexpected inputstream read length", expectedLength, numRead); }
Source:
<code>protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException { final String attrName = operation.require(ModelDescriptionConstants.NAME).asString(); ProtocolServerMetrics metric = ProtocolServerMetrics.getStat(attrName); if (metric == null) { context.getFailureDescription().set(String.format("Unknown metric %s", attrName)); } else { final ServiceController<?> controller = context.getServiceRegistry(false) .getService(EndpointUtils.getServiceName(operation, name)); RestService service = (RestService) controller.getService(); ModelNode result = new ModelNode(); switch (metric) { case BYTES_READ: result.set(service.getTransport().getTotalBytesRead()); break; case BYTES_WRITTEN: <START> result.set(service.getTransport().getTotalBytesWritten()); <END> break; case TRANSPORT_RUNNING: result.set(service.getValue().getTransportStatus() == ComponentStatus.RUNNING); break; } context.getResult().set(result); } context.stepCompleted(); }</code><technical_language>need get Transport RestServer. reason above</technical_language>

Target:
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException { final String attrName = operation.require(ModelDescriptionConstants.NAME).asString(); ProtocolServerMetrics metric = ProtocolServerMetrics.getStat(attrName); if (metric == null) { context.getFailureDescription().set(String.format("Unknown metric %s", attrName)); } else { final ServiceController<?> controller = context.getServiceRegistry(false) .getService(EndpointUtils.getServiceName(operation, name)); RestService service = (RestService) controller.getService(); RestServer server = service.getValue(); ModelNode result = new ModelNode(); switch (metric) { case BYTES_READ: result.set(server.getTransport().getTotalBytesRead()); break; case BYTES_WRITTEN: result.set(server.getTransport().getTotalBytesWritten()); break; case TRANSPORT_RUNNING: result.set(server.getTransportStatus() == ComponentStatus.RUNNING); break; } context.getResult().set(result); } context.stepCompleted(); }
Source:
<code>public Volume detachVolumeViaDestroyVM(long vmId, long volumeId) { <START> <END> Volume result = orchestrateDetachVolumeFromVM(vmId, volumeId); return result; }</code><technical_language>Extra new line removed other places</technical_language>

Target:
public Volume detachVolumeViaDestroyVM(long vmId, long volumeId) { return orchestrateDetachVolumeFromVM(vmId, volumeId); }
Source:
<code>default JsonArray getJsonArray(JsonObject jsonObject) throws DataException { try { return jsonObject.getJsonArray(this.toString()); <START> } catch (RuntimeException e) { <END> throw new DataException("Not possible to retrieve JsonArray value for key " + this.toString() + ". Exception: " + e.getMessage()); } }</code><technical_language>catch RuntimeException based class here? I ClassCastException is official thrown</technical_language>

Target:
default JsonArray getJsonArray(JsonObject jsonObject) throws DataException { try { return jsonObject.getJsonArray(this.toString()); } catch (ClassCastException | NullPointerException e) { throw new DataException("Not possible to retrieve JsonArray value for key " + this.toString() + ". Exception: " + e.getMessage()); } }
Source:
<code>protected ConnectedAnalysisConfiguration prepareAnalysisConfig(Path projectBaseDir, List<ClientInputFile> inputFiles, Map<String, String> mergedExtraProps) { <START> SonarLintLogger.get().debug("Connected mode (using configuration of '" + binding.projectKey() + "' in server '" + binding.connectionId() + "')"); <END> return ConnectedAnalysisConfiguration.builder() .setProjectKey(binding.projectKey()) .setBaseDir(projectBaseDir) .addInputFiles(inputFiles) .putAllExtraProperties(mergedExtraProps) .build(); }</code><technical_language>suggestion SonarLintLogger.get().debug("Connected mode (using configuration of '" + binding.projectKey() + "' in connection '" + binding.connectionId() + "')");</technical_language>

Target:
protected ConnectedAnalysisConfiguration prepareAnalysisConfig(Path projectBaseDir, List<ClientInputFile> inputFiles, Map<String, String> mergedExtraProps) { SonarLintLogger.get().debug("Connected mode (using configuration of '" + binding.projectKey() + "' in connection '" + binding.connectionId() + "')"); return ConnectedAnalysisConfiguration.builder() .setProjectKey(binding.projectKey()) .setBaseDir(projectBaseDir) .addInputFiles(inputFiles) .putAllExtraProperties(mergedExtraProps) .build(); }
Source:
<code>public RoadAccess getAccess(String highwayTag, TransportationMode transportationMode, RoadAccess _default) { if (transportationMode == TransportationMode.MOTOR_VEHICLE) { if (highwayTag.equals("track")) <START> return RoadAccess.FORESTRY; <END> } return super.getAccess(highwayTag, transportationMode, _default); }</code><technical_language>this Agricultural? [This](<LINK_0> page proposes destination</technical_language>

Target:
public RoadAccess getAccess(String highwayTag, TransportationMode transportationMode, RoadAccess _default) { if (transportationMode == TransportationMode.MOTOR_VEHICLE) { if (highwayTag.equals("track")) return RoadAccess.DESTINATION; } return super.getAccess(highwayTag, transportationMode, _default); }
Source:
<code>protected XingUser doInBackground(Activity... params) { XingApi api = new XingApi.Builder() .consumerKey(BuildConfig.OAUTH_CONSUMER_KEY) .consumerSecret(BuildConfig.OAUTH_CONSUMER_SECRET) .accessToken(Prefs.getInstance(ProfileActivity.this).getOauthToken()) .accessSecret(Prefs.getInstance(ProfileActivity.this).getOauthSecret()) .apiEndpoint("<LINK_0>") .logLevel(Level.BODY) .build(); UserProfilesResource profilesResource = api.resource(UserProfilesResource.class); ProfileEditingResource editingResource = api.resource(ProfileEditingResource.class); Response<XingUser, Object> response = null; try { editingResource.updateUserGeneralInformation() .formField("academic_title", "Ing.").enqueue(new Callback<String, String>() { @Override public void onResponse(Response<String, String> response) { if (response.isSuccess()) <START> Log.i("Update res", response.raw().toString()); <END> } @Override public void onFailure(Throwable t) { Log.e("Error", t.getLocalizedMessage(), t); } }); response = profilesResource.getYourProfile().execute(); Response<List<SearchResult>, Object> xingUsers = profilesResource.findUsersByKeyword("Rocco Bruno") .queryParam("user_fields", "display_name, id") .execute(); XingUser ss = xingUsers.body().get(0).getSearchResultItem(); Log.d("Search ResultUser", ss.toString()); Log.d("Search Request", xingUsers.body().toString()); return response.body(); } catch (Exception e) { e.printStackTrace(); } if (response != null) { return response.body(); } else { return null; } }</code><technical_language>ether in line if... of surrounded brackets</technical_language>

Target:
protected XingUser doInBackground(Activity... params) { XingApi api = new XingApi.Builder() .consumerKey(BuildConfig.OAUTH_CONSUMER_KEY) .consumerSecret(BuildConfig.OAUTH_CONSUMER_SECRET) .accessToken(Prefs.getInstance(ProfileActivity.this).getOauthToken()) .accessSecret(Prefs.getInstance(ProfileActivity.this).getOauthSecret()) .apiEndpoint("<LINK_0>") .logLevel(Level.BODY) .build(); UserProfilesResource profilesResource = api.resource(UserProfilesResource.class); ProfileEditingResource editingResource = api.resource(ProfileEditingResource.class); Response<XingUser, Object> response = null; try { editingResource.updateUserGeneralInformation() .formField("academic_title", "Ing.").enqueue(new Callback<String, String>() { @Override public void onResponse(Response<String, String> response) { if (response.isSuccess()) { Log.i("Update res", response.raw().toString()); } } @Override public void onFailure(Throwable t) { Log.e("Error", t.getLocalizedMessage(), t); } }); response = profilesResource.getYourProfile().execute(); Response<List<SearchResult>, Object> xingUsers = profilesResource.findUsersByKeyword("Rocco Bruno") .queryParam("user_fields", "display_name, id") .execute(); XingUser ss = xingUsers.body().get(0).getSearchResultItem(); Log.d("Search ResultUser", ss.toString()); Log.d("Search Request", xingUsers.body().toString()); return response.body(); } catch (Exception e) { e.printStackTrace(); } if (response != null) { return response.body(); } else { return null; } }
Source:
<code>public boolean startsWith(Path path) { if (path.getFileSystem() != this.parentFileSystem) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElements = ((AzurePath) path).splitToElements(); if (otherPathElements.length > thisPathElements.length) { return false; } for (int i = 0; i < otherPathElements.length; i++) { <START> if (!otherPathElements[i].equals(thisPathElements[i])) { <END> return false; } } return true; }</code><technical_language>I sense normalize comparing</technical_language>

Target:
public boolean startsWith(Path path) { if (!path.getFileSystem().equals(this.parentFileSystem)) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElements = ((AzurePath) path).splitToElements(); if (otherPathElements.length > thisPathElements.length) { return false; } for (int i = 0; i < otherPathElements.length; i++) { if (!otherPathElements[i].equals(thisPathElements[i])) { return false; } } return true; }
Source:
<code>public Change insert() throws OrmException, IOException { ReviewDb db = dbProvider.get(); ChangeUpdate update = updateFactory.create(change, change.getCreatedOn()); db.changes().beginTransaction(change.getId()); try { ChangeUtil.insertAncestors(db, patchSet.getId(), commit); db.patchSets().insert(Collections.singleton(patchSet)); db.changes().insert(Collections.singleton(change)); LabelTypes labelTypes = refControl.getProjectControl().getLabelTypes(); approvalsUtil.addReviewers(db, update, labelTypes, change, patchSet, patchSetInfo, reviewers, Collections.<Account.Id> emptySet()); if (changeMessage != null) { db.changeMessages().insert(Collections.singleton(changeMessage)); } db.commit(); } finally { db.rollback(); } CheckedFuture<?, IOException> f = <START> mergeabilityChecker.updateAndIndexAsync(change); update.commit(); <END> gitRefUpdated.fire(change.getProject(), patchSet.getRefName(), ObjectId.zeroId(), commit); if (runHooks) { hooks.doPatchsetCreatedHook(change, patchSet, db); } if (sendMail) { try { CreateChangeSender cm = createChangeSenderFactory.create(change); cm.setFrom(change.getOwner()); cm.setPatchSet(patchSet, patchSetInfo); cm.addReviewers(reviewers); cm.addExtraCC(extraCC); cm.send(); } catch (Exception err) { log.error("Cannot send email for new change " + change.getId(), err); } } f.checkedGet(); return change; }</code><technical_language>this ordering wrong? update needs commit index change</technical_language>

Target:
public Change insert() throws OrmException, IOException { ReviewDb db = dbProvider.get(); ChangeUpdate update = updateFactory.create(change, change.getCreatedOn()); db.changes().beginTransaction(change.getId()); try { ChangeUtil.insertAncestors(db, patchSet.getId(), commit); db.patchSets().insert(Collections.singleton(patchSet)); db.changes().insert(Collections.singleton(change)); LabelTypes labelTypes = refControl.getProjectControl().getLabelTypes(); approvalsUtil.addReviewers(db, update, labelTypes, change, patchSet, patchSetInfo, reviewers, Collections.<Account.Id> emptySet()); if (changeMessage != null) { db.changeMessages().insert(Collections.singleton(changeMessage)); } db.commit(); } finally { db.rollback(); } update.commit(); CheckedFuture<?, IOException> f = mergeabilityChecker.updateAndIndexAsync(change); gitRefUpdated.fire(change.getProject(), patchSet.getRefName(), ObjectId.zeroId(), commit); if (runHooks) { hooks.doPatchsetCreatedHook(change, patchSet, db); } if (sendMail) { try { CreateChangeSender cm = createChangeSenderFactory.create(change); cm.setFrom(change.getOwner()); cm.setPatchSet(patchSet, patchSetInfo); cm.addReviewers(reviewers); cm.addExtraCC(extraCC); cm.send(); } catch (Exception err) { log.error("Cannot send email for new change " + change.getId(), err); } } f.checkedGet(); return change; }
Source:
<code>public String getResourceContent(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is == null) { return FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); } return IOUtils.toString(is, DEFAULT_ENCODING); <START> } catch (Exception e) { <END> } } return null; }</code><technical_language>is reason catch exceptions this</technical_language>

Target:
public String getResourceContent(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toString(is, DEFAULT_ENCODING); } } } return FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); }
Source:
<code>public ExperimentModel getExperimentByTypeInstanceId(final Integer experimentType, final Integer instanceId) { try { final Criteria criteria = this.getSession().createCriteria(this.getPersistentClass()); criteria.add(Restrictions.eq("geoLocation.locationId", instanceId)); criteria.add(Restrictions.eq("typeId", experimentType)); final List<ExperimentModel> list = criteria.list(); if (list != null && !list.isEmpty()) { return list.get(0); } } catch (final HibernateException e) { <START> final String message = "Error at getExperimentByProjectIdAndLocation=" + instanceId <END> + " query at ExperimentDao: " + e.getMessage(); ExperimentDao.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return null; }</code><technical_language>Modify error message as: Errot getExperimentByTypeInstanceId</technical_language>

Target:
public ExperimentModel getExperimentByTypeInstanceId(final Integer experimentType, final Integer instanceId) { try { final Criteria criteria = this.getSession().createCriteria(this.getPersistentClass()); criteria.add(Restrictions.eq("geoLocation.locationId", instanceId)); criteria.add(Restrictions.eq("typeId", experimentType)); final List<ExperimentModel> list = criteria.list(); if (list != null && !list.isEmpty()) { return list.get(0); } } catch (final HibernateException e) { final String message = "Error at getExperimentByTypeInstanceId=" + instanceId + " query at ExperimentDao: " + e.getMessage(); ExperimentDao.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return null; }
Source:
<code>private void initDevice() throws FunctionalException { try { this.device = this.domainHelperService.findDlmsDevice(this.deviceIdentification, this.ipAddress); <START> } catch (final ProtocolAdapterException e) { <END> throw new RecoverKeyException(e.getMessage(), e); } if (this.device == null) { throw new IllegalArgumentException("Device " + this.deviceIdentification + " not found."); } }</code><technical_language>line 99: instead of throwing IllegalArgumentException throw a FunctionException !</technical_language>

Target:
private void initDevice() throws FunctionalException { try { this.device = this.domainHelperService.findDlmsDevice(this.deviceIdentification, this.ipAddress); } catch (final ProtocolAdapterException e) { throw new RecoverKeyException(e.getMessage(), e); } }
Source:
<code>public void testHasConstraintsForMethod() { MethodDescriptor parameterConstrainedDescriptor = Executables.parameterConstrainedMethod(); assertFalse( parameterConstrainedDescriptor.hasConstraints(), "Should have no contraints" ); MethodDescriptor returnValueConstrainedDescriptor = Executables.returnValueConstrainedMethod(); assertFalse( returnValueConstrainedDescriptor.hasConstraints(), "Should have no contraints" ); MethodDescriptor crossParameterConstrainedDescriptor = Executables.crossParameterConstrainedMethod(); assertTrue( crossParameterConstrainedDescriptor.hasConstraints(), <START> "Should have contraints" <END> ); }</code><technical_language>con_s_traints other tests. cut&paste ;-)</technical_language>

Target:
public void testHasConstraintsForMethod() { MethodDescriptor parameterConstrainedDescriptor = Executables.parameterConstrainedMethod(); assertFalse( parameterConstrainedDescriptor.hasConstraints(), "Should have no constraints" ); MethodDescriptor returnValueConstrainedDescriptor = Executables.returnValueConstrainedMethod(); assertFalse( returnValueConstrainedDescriptor.hasConstraints(), "Should have no constraints" ); MethodDescriptor crossParameterConstrainedDescriptor = Executables.crossParameterConstrainedMethod(); assertTrue( crossParameterConstrainedDescriptor.hasConstraints(), "Should have constraints" ); }
Source:
<code>public boolean isVisible(ChatType type) { <START> switch ((EntityPlayer.EnumChatVisibility) (Object) this) { <END> case FULL: return true; case SYSTEM: return type == ChatTypes.SYSTEM || type == ChatTypes.ACTION_BAR; case HIDDEN: return false; default: throw new IllegalStateException("unknown type " + this); } }</code><technical_language>This cached in constructor</technical_language>

Target:
public boolean isVisible(ChatType type) { checkNotNull(type, "type"); return this.visibleChatTypes.contains(type); }
Source:
<code>public void close() { if (closed) { return; } boolean wasInTransaction = isInTransaction() && forceEndTransactions && config.get().get(Handles.class).isForceEndTransactions(); extensionMethod.remove(); config.remove(); if (wasInTransaction) { rollback(); } Throwable suppressed = null; try { statementBuilder.close(getConnection()); } catch (Throwable t) { suppressed = t; <START> } finally { <END> try { connection.close(); if (wasInTransaction) { TransactionException txe = new TransactionException("Improper transaction handling detected: A Handle with an open " + "transaction was closed. Transactions must be explicitly committed or rolled back " + "before closing the Handle. " + "Jdbi has rolled back this transaction automatically. " + "This check may be disabled by calling getConfig(Handles.class).setForceEndTransactions(false)."); if (suppressed != null) { txe.addSuppressed(suppressed); } throw txe; } } catch (SQLException e) { CloseException ce = new CloseException("Unable to close Connection", e); if (suppressed != null) { ce.addSuppressed(suppressed); } throw ce; } finally { LOG.trace("Handle released", this); closed = true; } } }</code><technical_language>I putting a finally this code block is redundant. This block reached</technical_language>

Target:
public void close() { if (closed) { return; } boolean wasInTransaction = isInTransaction() && forceEndTransactions && config.get().get(Handles.class).isForceEndTransactions(); extensionMethod.remove(); config.remove(); if (wasInTransaction) { rollback(); } Throwable suppressed = null; try { statementBuilder.close(getConnection()); } catch (Throwable t) { suppressed = t; } try { connection.close(); if (wasInTransaction) { TransactionException txe = new TransactionException("Improper transaction handling detected: A Handle with an open " + "transaction was closed. Transactions must be explicitly committed or rolled back " + "before closing the Handle. " + "Jdbi has rolled back this transaction automatically. " + "This check may be disabled by calling getConfig(Handles.class).setForceEndTransactions(false)."); if (suppressed != null) { txe.addSuppressed(suppressed); } throw txe; } } catch (SQLException e) { CloseException ce = new CloseException("Unable to close Connection", e); if (suppressed != null) { ce.addSuppressed(suppressed); } throw ce; } finally { LOG.trace("Handle released", this); closed = true; } }
Source:
<code>public static List<Object> mapDataRow(Entity entity) { List<Object> dataRow = new ArrayList<>(); for (Attribute attribute : entity.getEntityType().getAttributes()) { <START> if (attribute.getExpression() != null || attribute.getMappedBy() != null) { <END> dataRow.add(null); } else if (attribute.getDataType() != AttributeType.COMPOUND) { if (isSingleReferenceType(attribute)) { Entity value = entity.getEntity(attribute.getName()); dataRow.add(value != null ? value.getIdValue() : null); } else if (isMultipleReferenceType(attribute)) { Iterable<Entity> values = entity.getEntities(attribute.getName()); String ids = Streams.stream(values) .map(Entity::getIdValue) .map(Object::toString) .collect(joining(",")); dataRow.add(ids); } else { Object value = entity.get(attribute.getName()); dataRow.add(value); } } } return dataRow; }</code><technical_language>suggestion if (attribute.hasExpression() || attribute.isMappedBy()) {</technical_language>

Target:
public static List<Object> mapDataRow(Entity entity) { List<Object> dataRow = new ArrayList<>(); for (Attribute attribute : entity.getEntityType().getAtomicAttributes()) { if (attribute.hasExpression() || attribute.isMappedBy()) { dataRow.add(null); } else { if (isSingleReferenceType(attribute)) { Entity value = entity.getEntity(attribute.getName()); dataRow.add(value != null ? value.getIdValue() : null); } else if (isMultipleReferenceType(attribute)) { Iterable<Entity> values = entity.getEntities(attribute.getName()); String ids = Streams.stream(values) .map(Entity::getIdValue) .map(Object::toString) .collect(joining(",")); dataRow.add(ids); } else { Object value = entity.get(attribute.getName()); dataRow.add(value); } } } return dataRow; }
Source:
<code>public static ResourceProviderMetaData create(final String resourceType, final List<String> locations, final List<String> apiVersions) { ResourceProviderMetaData.Builder builder = ResourceProviderMetaData.builder() .resourceType(resourceType) .locations(locations == null ? null : ImmutableList.copyOf(locations)) <START> .apiVersions(apiVersions == null ? null : ImmutableList.copyOf(apiVersions)); <END> return builder.build(); }</code><technical_language>If fields nullable, annotate fields accordingly</technical_language>

Target:
public static ResourceProviderMetaData create(final String resourceType, final List<String> locations, final List<String> apiVersions) { ResourceProviderMetaData.Builder builder = ResourceProviderMetaData.builder() .resourceType(resourceType) .locations(locations == null ? ImmutableList.<String>of() : ImmutableList.copyOf(locations)) .apiVersions(apiVersions == null ? ImmutableList.<String>of() : ImmutableList.copyOf(apiVersions)); return builder.build(); }
Source:
<code>private void migrateProperties(SecureStore currentStore, SecureStore newStore) { log.info("Migrate entries"); for (EntryKey key : currentStore.list()) { String[] value = currentStore.getList(key.section, key.subsection, key.name); if (value != null) { newStore.setList(key.section, key.subsection, key.name, Arrays.asList(value)); } else { String msg = <START> String.format("Cannot migrate entry for ", key.section); <END> if (key.subsection != null) { msg = msg + String.format("[%s]", key.subsection); } msg = msg + String.format(".%s", key.name); throw new RuntimeException(msg); } } }</code><technical_language>Bug: Format-string method String.format(String, Object[]) called format string "Cannot migrate entry for " wants 0 arguments is 1</technical_language>

Target:
private void migrateProperties(SecureStore currentStore, SecureStore newStore) { log.info("Migrate entries"); for (EntryKey key : currentStore.list()) { String[] value = currentStore.getList(key.section, key.subsection, key.name); if (value != null) { newStore.setList(key.section, key.subsection, key.name, Arrays.asList(value)); } else { String msg = String.format("Cannot migrate entry for %s", key.section); if (key.subsection != null) { msg = msg + String.format("[%s]", key.subsection); } msg = msg + String.format(".%s", key.name); throw new RuntimeException(msg); } } }
Source:
<code>public U getRequiredUser() { <START> return getUserOrThrowException(getCurrentUser()); <END> }</code><technical_language>getCurrentUser().orElseThrow(this::createMissingUserException);</technical_language>

Target:
public U getRequiredUser() { return getCurrentUser().orElseThrow(this::createMissingUserException); }
Source:
<code>public static RealmAsyncTask loginAsync(final SyncCredentials credentials, final String authenticationUrl, final Callback callback) { if (Looper.myLooper() == null) { throw new IllegalStateException("Asynchronous login is only possible from looper threads."); } final Handler handler = new Handler(Looper.myLooper()); ThreadPoolExecutor networkPoolExecutor = SyncManager.NETWORK_POOL_EXECUTOR; Future<?> authenticateRequest = networkPoolExecutor.submit(new Runnable() { @Override public void run() { try { SyncUser user = login(credentials, authenticationUrl); postSuccess(user); } catch (ObjectServerError e) { postError(e); } } private void postError(final ObjectServerError error) { if (callback != null) { handler.post(new Runnable() { @Override public void run() { try { callback.onError(error); } catch (Exception e) { <START> RealmLog.info("onError has thrown an exception but ignoring it: %s", e.getMessage()); <END> e.printStackTrace(); } } }); } } private void postSuccess(final SyncUser user) { if (callback != null) { handler.post(new Runnable() { @Override public void run() { callback.onSuccess(user); } }); } } }); return new RealmAsyncTaskImpl(authenticateRequest, networkPoolExecutor); }</code><technical_language>"but is ignoring it." io.realm.internal.Util.getStackTrace(Throwable) instead of e.getMessage(). show entire stack trace in logcat</technical_language>

Target:
public static RealmAsyncTask loginAsync(final SyncCredentials credentials, final String authenticationUrl, final Callback callback) { if (Looper.myLooper() == null) { throw new IllegalStateException("Asynchronous login is only possible from looper threads."); } final Handler handler = new Handler(Looper.myLooper()); ThreadPoolExecutor networkPoolExecutor = SyncManager.NETWORK_POOL_EXECUTOR; Future<?> authenticateRequest = networkPoolExecutor.submit(new Runnable() { @Override public void run() { try { SyncUser user = login(credentials, authenticationUrl); postSuccess(user); } catch (ObjectServerError e) { postError(e); } } private void postError(final ObjectServerError error) { if (callback != null) { handler.post(new Runnable() { @Override public void run() { try { callback.onError(error); } catch (Exception e) { RealmLog.info("onError has thrown an exception but is ignoring it: %s", Util.getStackTrace(e)); } } }); } } private void postSuccess(final SyncUser user) { if (callback != null) { handler.post(new Runnable() { @Override public void run() { callback.onSuccess(user); } }); } } }); return new RealmAsyncTaskImpl(authenticateRequest, networkPoolExecutor); }
Source:
<code>public void test_TempResourceAPI_TempResourceEnabledProperty() throws Exception{ final boolean tempResourceEnabledOriginalValue = Config.getBooleanProperty(TempFileAPI.TEMP_RESOURCE_ENABLED, true); try { final TempFileResource resource = new TempFileResource(); final HttpServletRequest request = mockRequest(); final String fileName = "test.png"; final HttpServletResponse response = new MockHttpResponse(); Config.setProperty(TempFileAPI.TEMP_RESOURCE_ENABLED, false); final Date date = new Date(); <START> final FormDataContentDisposition fileMetaData = FormDataContentDisposition.name("testData") <END> .fileName(fileName).creationDate(date) .modificationDate(date).readDate(date).size(1222).build(); final Response jsonResponse = resource .uploadTempResource(request, response, inputStream(), fileMetaData); assertEquals(Status.FORBIDDEN.getStatusCode(), jsonResponse.getStatus()); }finally { Config.setProperty(TempFileAPI.TEMP_RESOURCE_ENABLED, tempResourceEnabledOriginalValue); } }</code><technical_language>I part of this logic line 366 line 375 is repeated in test reused. In general I a property is set time (in this case Config.setProperty(TempFileAPI.TEMP_RESOURCE_ENABLED, false)), a parameter</technical_language>

Target:
public void test_TempResourceAPI_TempResourceEnabledProperty(){ final boolean tempResourceEnabledOriginalValue = Config.getBooleanProperty(TempFileAPI.TEMP_RESOURCE_ENABLED, true); try { final String fileName = "test.png"; Config.setProperty(TempFileAPI.TEMP_RESOURCE_ENABLED, false); final BodyPart filePart1 = new StreamDataBodyPart(fileName, inputStream()); final MultiPart multipartEntity = new FormDataMultiPart() .bodyPart(filePart1); final Response jsonResponse = resource.uploadTempResourceMulti(request, response, (FormDataMultiPart) multipartEntity); assertEquals(Status.FORBIDDEN.getStatusCode(), jsonResponse.getStatus()); }finally { Config.setProperty(TempFileAPI.TEMP_RESOURCE_ENABLED, tempResourceEnabledOriginalValue); } }
Source:
<code>public Optional<Element> getElementAt(final double x, final double y) { final Optional<Shape> shape = getCanvas().getShapeAt(x, y); <START> if (shape.isPresent()) { <END> final Element element = GraphUtils.getNode(getGraphExecutionContext(), shape.get().getUUID()); return Optional.of(element); } return Optional.empty(); }</code><technical_language>aware, Optional a nice fluent API. This like: return shape.map(s -> { final Element element = GraphUtils.getNode(getGraphExecutionContext(), s.get().getUUID()); return Optional.of(element); }).orElse(Optional.empty()); I guess a matter of preference; nicer me</technical_language>

Target:
public Optional<Element> getElementAt(final double x, final double y) { final Optional<Shape> shape = getCanvas().getShapeAt(x, y); return shape.flatMap(s -> Optional.of(GraphUtils.getNode(getGraphExecutionContext(), s.getUUID()))); }
Source:
<code>public boolean equals(Object obj) { if (this == <START> obj) <END> return true; if (obj == null) return false; if (!(obj instanceof TemplatePersistenceData)) return false; TemplatePersistenceData other= (TemplatePersistenceData) obj; return Objects.equals(uniqueIdForEquals, other.getUniqueIdForEquals()); }</code><technical_language>Please curly braces for conditionals</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof TemplatePersistenceData)) { return false; } TemplatePersistenceData other= (TemplatePersistenceData) obj; return Objects.equals(uniqueIdForEquals, other.getUniqueIdForEquals()); }
Source:
<code>@Test public void getPerformanceDataTest() { driver.startActivity("io.appium.android.apis", ".ApiDemos"); List<String> supportedPerformanceDataTypes = driver.getSupportedPerformanceDataTypes(); <START> for(int i = 0 ; i < supportedPerformanceDataTypes.size() ; ++ i){ <END> String dataType = supportedPerformanceDataTypes.get(i); List<List<Object>> valueTable = driver.getPerformanceData("com.example.android.apis", dataType, 60000); int valueTableHeadLength = valueTable.get(0).size(); for(int j = 1 ; j < valueTable.size() ; ++ j){ assert(valueTableHeadLength == valueTable.get(j).size()); } } }</code><technical_language>for .. in here</technical_language>

Target:
@Test public void getPerformanceDataTest() throws Exception { driver.startActivity("io.appium.android.apis", ".ApiDemos"); List<String> supportedPerformanceDataTypes = driver.getSupportedPerformanceDataTypes(); for (int i = 0 ; i < supportedPerformanceDataTypes.size() ; ++ i) { String dataType = supportedPerformanceDataTypes.get(i); List<List<Object>> valueTable = driver.getPerformanceData("com.example.android.apis", dataType, 60000); for ( int j = 1 ; j < valueTable.size() ; ++ j) { assertEquals(valueTable.subList(0,0).size(), valueTable.subList(j, j).size()); } } }