auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void execute() throws MojoExecutionException { Log log = getLog(); ClassLoader cl = getMavenRuntimeClasspathClassLoader(); Properties userProps = loadPropertiesFromFile(cl, CHECKSTYLE_PROPERTIES_FILE); String ruleset = CHECKSTYLE_RULESET_DIR + "/" + rulesetType + ".xml"; String key = CHECKSTYLE_RULESET_USER_PROPERTY; URL rulesetLocation = cl.getResource(ruleset); String absoluteLocation = rulesetLocation.toString(); log.debug("Config file found at " + absoluteLocation); userProps.setProperty(key, absoluteLocation); <START> Dependency dep = dependency(SMARTHOME_TOOLS_GROUP_ID, SMARTHOME_TOOLS_ARTIFACT_ID, mavenProject.getVersion()); <END> Dependency checktyle = dependency("com.puppycrawl.tools", "checkstyle", "7.2"); Xpp3Dom config = configuration(element("sourceDirectory", mavenProject.getBasedir().toString())); executeCheck(MAVEN_CHECKSTYLE_PLUGIN_GROUP_ID, MAVEN_CHECKSTYLE_PLUGIN_ARTIFACT_ID, checkstyleMavenVersion, MAVEN_CHECKSTYLE_PLUGIN_GOAL, config, dep,checktyle); log.debug("Checkstyle execution has been finished."); }</code><technical_language>This is a subtle bug: This maven version of project is this plugin - I e.g. openHAB2-addons, version 2.1.0-SNAPSHOT, plugin fail error (since find static-code-analysis in version 2.1.0-SNAPSHOT instead of 0.9.0-SNAPSHOT). bug for other mojos</technical_language>

Target:
public void execute() throws MojoExecutionException { Log log = getLog(); ClassLoader cl = getMavenRuntimeClasspathClassLoader(); Properties userProps = loadPropertiesFromFile(cl, CHECKSTYLE_PROPERTIES_FILE); String ruleset = CHECKSTYLE_RULESET_DIR + "/" + rulesetType + ".xml"; String key = CHECKSTYLE_RULESET_USER_PROPERTY; URL rulesetLocation = cl.getResource(ruleset); String absoluteLocation = rulesetLocation.toString(); log.debug("Config file found at " + absoluteLocation); userProps.setProperty(key, absoluteLocation); Dependency checktyle = dependency("com.puppycrawl.tools", "checkstyle", "7.2"); Dependency[] allDependencies = getDependencies(checkstylePlugins, checktyle); Xpp3Dom config = configuration(element("sourceDirectory", mavenProject.getBasedir().toString())); executeCheck(MAVEN_CHECKSTYLE_PLUGIN_GROUP_ID, MAVEN_CHECKSTYLE_PLUGIN_ARTIFACT_ID, checkstyleMavenVersion, MAVEN_CHECKSTYLE_PLUGIN_GOAL, config, allDependencies); log.debug("Checkstyle execution has been finished."); }
Source:
<code>public void addEvent(ITimeEvent event) { if (!(event instanceof <START> TimeLineEvent)) <END> { throw new IllegalArgumentException("Need to be a TimeLineEvent"); } super.addEvent(event); }</code><technical_language>a ITimeLineEvent interface</technical_language>

Target:
public void addEvent(ITimeEvent event) { if (!(event instanceof TimeLineEvent)) { throw new IllegalArgumentException("Needs to be a TimeLineEvent"); } super.addEvent(event); }
Source:
<code>public boolean equals(final Object o) { if (!super.equals(o)) { return false; } <START> final ArrayOfDoublesSketchMultiPostAggregator that = (ArrayOfDoublesSketchMultiPostAggregator) o; <END> return fields.equals(that.fields); }</code><technical_language>breaks symmetry of equals() subject ClassCastException</technical_language>

Target:
public boolean equals(final Object o) { if (!super.equals(o)) { return false; } if (o == null || getClass() != o.getClass()) { return false; } final ArrayOfDoublesSketchMultiPostAggregator that = (ArrayOfDoublesSketchMultiPostAggregator) o; return fields.equals(that.fields); }
Source:
<code>public void verifyTOCsectionLinkWorks(int numberOfTheSection) { WebElement sectionTOClink = tableOfContentsSectionsList.get(numberOfTheSection-1); String sectionID = sectionTOClink.getAttribute("href").substring(getCurrentUrl().length()); WebElement sectionOnArticle = driver.findElement(By.cssSelector(sectionID)); int sectionYbefore = sectionOnArticle.getLocation().getY(); <START> tableOfContentsSectionsList.get(numberOfTheSection-1).click(); <END> int sectionYafter = sectionOnArticle.getLocation().getY(); Assertion.assertNotEquals(sectionYbefore, sectionYafter); Assertion.assertTrue(sectionYafter < 5); PageObjectLogging.log("verifyTOCsectionLinkWorks", "choosen section "+sectionID+" was scrolled up", true); }</code><technical_language>assigned sectionTOClink WebElement variable. click this WebElement</technical_language>

Target:
public void verifyTOCsectionLinkWorks(int numberOfTheSection) { WebElement sectionTOClink = tableOfContentsSectionsList.get(numberOfTheSection-1); String sectionID = sectionTOClink.getAttribute("href").substring(getCurrentUrl().length()); WebElement sectionOnArticle = driver.findElement(By.cssSelector(sectionID)); int sectionYbefore = sectionOnArticle.getLocation().getY(); sectionTOClink.click(); int sectionYafter = sectionOnArticle.getLocation().getY(); Assertion.assertNotEquals(sectionYbefore, sectionYafter); Assertion.assertTrue(sectionYafter < 5); PageObjectLogging.log("verifyTOCsectionLinkWorks", "choosen section "+sectionID+" was scrolled up", true); }
Source:
<code>public void removeBrick(Guid brickId) { getCallsHandler().executeModification("DeleteGlusterVolumeBrick", <START> getCustomMapSqlParameterSource().addValue("id", brickId.getUuid())); <END> }</code><technical_language>needed cal getUuid() guids? i remember need/use</technical_language>

Target:
public void removeBrick(Guid brickId) { getCallsHandler().executeModification("DeleteGlusterVolumeBrick", getCustomMapSqlParameterSource().addValue("id", brickId)); }
Source:
<code>@Test public void unacknowledgedPingFailsConnection() { client = client.newBuilder() .pingInterval(500, TimeUnit.MILLISECONDS) .build(); final CountDownLatch latch = new CountDownLatch(1); webServer.enqueue(new MockResponse().withWebSocketUpgrade(new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { try { latch.await(); } catch (InterruptedException e) { throw new AssertionError(e); } } })); long openAtNanos = System.nanoTime(); newWebSocket(); clientListener.assertOpen(); clientListener.assertFailure(SocketTimeoutException.class, "sent ping but didn't receive pong within 500ms (after 0 successful ping/pongs)"); latch.countDown(); long elapsedUntilFailure = System.nanoTime() - openAtNanos; assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo((double) 1000, offset( <START> 250d)); <END> }</code><technical_language>nit: this wrapping is awkward</technical_language>

Target:
@Test public void unacknowledgedPingFailsConnection() { client = client.newBuilder() .pingInterval(500, TimeUnit.MILLISECONDS) .build(); final CountDownLatch latch = new CountDownLatch(1); webServer.enqueue(new MockResponse().withWebSocketUpgrade(new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { try { latch.await(); } catch (InterruptedException e) { throw new AssertionError(e); } } })); long openAtNanos = System.nanoTime(); newWebSocket(); clientListener.assertOpen(); clientListener.assertFailure(SocketTimeoutException.class, "sent ping but didn't receive pong within 500ms (after 0 successful ping/pongs)"); latch.countDown(); long elapsedUntilFailure = System.nanoTime() - openAtNanos; assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)) .isCloseTo(1000L, offset(250L)); }
Source:
<code>protected void recycle() { _metaData = null; _originalURI = null; if (_context != null) throw new IllegalStateException("Request in context!"); if (_inputState == INPUT_READER) { try { int r = _reader.read(); while (r != -1) { r = _reader.read(); } } catch (Exception e) { LOG.ignore(e); _reader = null; } } _dispatcherType = null; setAuthentication(Authentication.NOT_CHECKED); getHttpChannelState().recycle(); if (_async != null) _async.reset(); _async = null; _asyncNotSupportedSource = null; _handled = false; _attributes = Attributes.unwrap(_attributes); if (ServletAttributes.class.equals(_attributes.getClass())) _attributes.clearAttributes(); else <START> _attributes = new ServletAttributes(); <END> _contentType = null; _characterEncoding = null; _contextPath = null; if (_cookies != null) _cookies.reset(); _cookiesExtracted = false; _context = null; _newContext = false; _pathInfo = null; _queryEncoding = null; _requestedSessionId = null; _requestedSessionIdFromCookie = false; _secure = false; _session = null; _sessionHandler = null; _scope = null; _servletPath = null; _timeStamp = 0; _queryParameters = null; _contentParameters = null; _parameters = null; _contentParamsExtracted = false; _inputState = INPUT_NONE; _multiParts = null; _remote = null; _sessions = null; _input.recycle(); _requestAttributeListeners.clear(); }</code><technical_language>reset null</technical_language>

Target:
protected void recycle() { _metaData = null; _originalURI = null; if (_context != null) throw new IllegalStateException("Request in context!"); if (_inputState == INPUT_READER) { try { int r = _reader.read(); while (r != -1) { r = _reader.read(); } } catch (Exception e) { LOG.ignore(e); _reader = null; } } _dispatcherType = null; setAuthentication(Authentication.NOT_CHECKED); getHttpChannelState().recycle(); if (_async != null) _async.reset(); _async = null; _asyncNotSupportedSource = null; _handled = false; _attributes = Attributes.unwrap(_attributes); if (_attributes != null) { if (ServletAttributes.class.equals(_attributes.getClass())) _attributes.clearAttributes(); else _attributes = null; } _contentType = null; _characterEncoding = null; _contextPath = null; if (_cookies != null) _cookies.reset(); _cookiesExtracted = false; _context = null; _newContext = false; _pathInfo = null; _queryEncoding = null; _requestedSessionId = null; _requestedSessionIdFromCookie = false; _secure = false; _session = null; _sessionHandler = null; _scope = null; _servletPath = null; _timeStamp = 0; _queryParameters = null; _contentParameters = null; _parameters = null; _contentParamsExtracted = false; _inputState = INPUT_NONE; _multiParts = null; _remote = null; _sessions = null; _input.recycle(); _requestAttributeListeners.clear(); }
Source:
<code>public void setUp() { SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository); final int osId = 0; Map<Integer, Map<Version, List<DisplayType>>> displayTypeMap = new HashMap<>(); displayTypeMap.put(osId, new HashMap<Version, List<DisplayType>>()); displayTypeMap.get(osId).put(null, Arrays.asList(DisplayType.qxl)); when(osRepository.getDisplayTypes()).thenReturn(displayTypeMap); mockVdsGroup(); try { <START> xmlOvfData = new String(Files.readAllBytes(Paths.get(VM_OVF_XML_DATA))); <END> } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>simplified a bit apache commons readFileToString</technical_language>

Target:
public void setUp() { SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository); final int osId = 0; Map<Integer, Map<Version, List<DisplayType>>> displayTypeMap = new HashMap<>(); displayTypeMap.put(osId, new HashMap<Version, List<DisplayType>>()); displayTypeMap.get(osId).put(null, Arrays.asList(DisplayType.qxl)); when(osRepository.getDisplayTypes()).thenReturn(displayTypeMap); mockVdsGroup(); setXmlOvfData(); }
Source:
<code>protected void expandRepositoryGroup(ExecutionEvent event, RepositoryGroup group) throws ExecutionException { <START> IWorkbenchPart part = HandlerUtil.getActivePartChecked(event); <END> if (part instanceof RepositoriesView) { ((RepositoriesView) part).expandNodeForGroup(group); } }</code><technical_language>I if view exists want update. Get view event PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findViewReference(RepositoriesView.VIEW_ID).getView(false)</technical_language>

Target:
protected void expandRepositoryGroup(ExecutionEvent event, RepositoryGroup group) throws ExecutionException { if (group != null) { RepositoriesView view = null; IWorkbenchPart part = HandlerUtil.getActivePartChecked(event); if (part instanceof RepositoriesView) { view = ((RepositoriesView) part); } else { view = getRepositoriesView(); } if (view != null) { view.expandNodeForGroup(group); } } }
Source:
<code>public String getAlgorithm() { <START> return "ECDSA-SK"; <END> }</code><technical_language>Please this a public literal constant of this class</technical_language>

Target:
public String getAlgorithm() { return ALGORITHM; }
Source:
<code>protected void initFieldMaps() { try { initMiningFieldMap(); initOutputFieldMap(); <START> } catch(Exception e) { <END> logger.error(e.getMessage()); } }</code><technical_language>Please catch general Exception class, this catch exceptions want catched. E.g. NullPointerException</technical_language>

Target:
protected void initFieldMaps() throws IllegalArgumentException { initMiningFieldMap(); initOutputFieldMap(); }
Source:
<code>public boolean isReady() { long readyTimestamp = ((FileSystemDataset<E>)dataset).getReadyTimestamp(getConstraints()); <START> return readyTimestamp != -1; <END> }</code><technical_language>this readyTimestamp > 0</technical_language>

Target:
public boolean isReady() { if (signalManager != null) { long readyTimestamp = signalManager.getReadyTimestamp(getConstraints()); return readyTimestamp != -1; } return false; }
Source:
<code>public void checkProperties(Properties properties) { <START> properties.setProperty("log4j.shutdownCallbackRegistry", "io.druid.common.config.Log4jShutdown"); <END> properties.setProperty("log4j.shutdownHookEnabled", "true"); }</code><technical_language>this depend class generate name that</technical_language>

Target:
public void checkProperties(Properties properties) { if (!properties.contains("log4j.shutdownCallbackRegistry")) { properties.setProperty("log4j.shutdownCallbackRegistry", "io.druid.common.config.Log4jShutdown"); } if (!properties.contains("log4j.shutdownHookEnabled")) { properties.setProperty("log4j.shutdownHookEnabled", "true"); } }
Source:
<code>public void createControl(Composite parent) { super.createControl(parent); final Composite control = (Composite) this.getControl(); control.setLayout(new GridLayout(2, false)); control.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); <START> final Table selectedFiles = new Table(control, SWT.NONE); <END> selectedFiles.clearAll(); selectedFiles.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); Composite buttonArea = new Composite(control, SWT.None); buttonArea.setLayout(new RowLayout()); ((RowLayout) buttonArea.getLayout()).type = SWT.VERTICAL; buttonArea.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); Button addFile = new Button(buttonArea, SWT.PUSH); addFile.setText(Messages.ImportTraceWizardPageSelectDirectories_0); addFile.addSelectionListener(new AddFileHandler()); Button addDirectory = new Button(buttonArea, SWT.PUSH); addDirectory.setText(Messages.ImportTraceWizardPageSelectDirectories_1); addDirectory.addSelectionListener(new AddDirectoryHandler()); Button removeFile = new Button(buttonArea, SWT.PUSH); removeFile.setText(Messages.ImportTraceWizardPageSelectDirectories_2); removeFile.addSelectionListener(new RemoveFileHandler(selectedFiles)); this.setTitle(Messages.ImportTraceWizardPageSelectDirectories_3); }</code><technical_language>se (SWT.H_SCROLL | SWT.V_SCROLL) instead of SWT.NONE style constructing table</technical_language>

Target:
public void createControl(Composite parent) { super.createControl(parent); final Composite control = (Composite) this.getControl(); control.setLayout(new GridLayout(2, false)); control.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); final Table selectedFiles = new Table(control, SWT.H_SCROLL | SWT.V_SCROLL); selectedFiles.clearAll(); selectedFiles.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); selectedFiles.setLinesVisible(true); Composite buttonArea = new Composite(control, SWT.None); buttonArea.setLayout(new GridLayout()); buttonArea.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); Button addFile = new Button(buttonArea, SWT.PUSH); addFile.setText(Messages.ImportTraceWizardAddFile); addFile.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); addFile.addSelectionListener(new AddFileHandler()); addFile.setAlignment(SWT.LEFT); Button addDirectory = new Button(buttonArea, SWT.PUSH); addDirectory.setText(Messages.ImportTraceWizardAddDirectory); addDirectory.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); addDirectory.addSelectionListener(new AddDirectoryHandler()); addDirectory.setAlignment(SWT.LEFT); Button removeFile = new Button(buttonArea, SWT.PUSH); removeFile.setText(Messages.ImportTraceWizardRemove); removeFile.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); removeFile.addSelectionListener(new RemoveFileHandler(selectedFiles)); removeFile.setAlignment(SWT.LEFT); this.setTitle(Messages.ImportTraceWizardDirectoryCaption); }
Source:
<code>public Object apply(ConfigResource resource) throws AuthException, BadRequestException, ResourceConflictException { <START> List<TopMenu.MenuEntry> enties = Lists.newArrayList(); <END> for (TopMenu extension : extensions) { enties.addAll(extension.getEntries()); } return enties; }</code><technical_language>entries</technical_language>

Target:
public Object apply(ConfigResource resource) throws AuthException, BadRequestException, ResourceConflictException { List<TopMenu.MenuEntry> entries = Lists.newArrayList(); for (TopMenu extension : extensions) { entries.addAll(extension.getEntries()); } return entries; }
Source:
<code>public Response update(T entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); if (baseClass.equals(Device.class)) { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); } <START> if (baseClass.equals(User.class)) { <END> User before = Context.getPermissionsManager().getUser(entity.getId()); Context.getPermissionsManager().checkUserUpdate(getUserId(), before, (User) entity); } Context.getPermissionsManager().checkPermission(baseClass, getUserId(), entity.getId()); Context.getManager(baseClass).updateItem(entity); if (baseClass.equals(Group.class) || baseClass.equals(Device.class)) { Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); } if (baseClass.equals(User.class) && Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); }</code><technical_language>Please else shorten optimise code</technical_language>

Target:
public Response update(T entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); if (baseClass.equals(Device.class)) { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); } else if (baseClass.equals(User.class)) { User before = Context.getPermissionsManager().getUser(entity.getId()); Context.getPermissionsManager().checkUserUpdate(getUserId(), before, (User) entity); } Context.getPermissionsManager().checkPermission(baseClass, getUserId(), entity.getId()); Context.getManager(baseClass).updateItem(entity); if (baseClass.equals(Group.class) || baseClass.equals(Device.class)) { Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); } else if (baseClass.equals(User.class) && Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); }
Source:
<code>public void setLimitRate(String limitRate) { String unit = limitRate.substring(limitRate.length() - 1, limitRate.length()).toLowerCase(); int value = Integer.parseInt(limitRate.substring(0, limitRate.length() - 1).toLowerCase()); switch (unit) { case "m": value = value * 1000; break; case "g": value = value * 1000 * 1000; break; default: break; } <START> this.limitRate = value * 1024 / 8; <END> }</code><technical_language>strange 1024 1000 multiplier mixed up</technical_language>

Target:
public void setLimitRate(String limitRate) { String unit = limitRate.substring(limitRate.length() - 1, limitRate.length()).toLowerCase(); int value = Integer.parseInt(limitRate.substring(0, limitRate.length() - 1).toLowerCase()); switch (unit) { case "k": this.limitRate = value * ONE_KILOBYTE_IN_CPS; break; case "m": this.limitRate = value * ONE_KILOBYTE_IN_CPS * 1000; break; case "g": this.limitRate = value * ONE_KILOBYTE_IN_CPS * 1000000; break; default: break; } }
Source:
<code>public void removeListener() { if (mLocationManager == null) { return; } mLocationManager.removeGpsStatusListener(mSatelliteListener); enableLocationListener(false, mGpsLocationListener); enableLocationListener(false, mNetworkLocationListener); <START> mLocationManager = null; <END> }</code><technical_language>In branch I mLocationManager final in this class, I planning merge that. I understand setting location manager null, is a reason? @cascheberg I apologize for slow reviews, @crankycoder I this week. Stumbler need update this fix, need figure out users reporting stumbler pausing starting</technical_language>

Target:
public void removeListener() { if (mLocationManager == null) { return; } mLocationManager.removeGpsStatusListener(mSatelliteListener); enableLocationListener(false, mGpsLocationListener); enableLocationListener(false, mNetworkLocationListener); }
Source:
<code>public long getLastExtentIndexId() throws Exception{ long lastIndex; Connection connection = connect(); PreparedStatement getLastIndex; try { getLastIndex = connection.prepareStatement( "SELECT MAX(" + EXTENT_INDEX_ID + ") AS " + EXTENT_INDEX_ID + " FROM " + EXTENT_TABLE); } catch (SQLiteException e) { throw new SQLiteException(e.getMessage() + ". SQL query was: SELECT MAX(" + EXTENT_INDEX_ID + ") AS " + EXTENT_INDEX_ID + " FROM " + EXTENT_TABLE, e.getResultCode()); } ResultSet results = getLastIndex.executeQuery(); if (results.next()) { lastIndex = results.getLong(EXTENT_INDEX_ID); } else { lastIndex = 0; LOGGER.log(Level.FINEST,"[" + getName() + "] no products in extentSummary table; using index 0"); } <START> getLastIndex.close(); END> return lastIndex; }</code><technical_language>try/finally, try resources prepared statement is closed</technical_language>

Target:
public long getLastExtentIndexId() throws Exception{ long lastIndex; Connection connection = connect(); String sql = "SELECT MAX(" + EXTENT_INDEX_ID + ") AS " + EXTENT_INDEX_ID + " FROM " + EXTENT_TABLE; try (PreparedStatement getLastIndex = connection.prepareStatement(sql)) { ResultSet results = getLastIndex.executeQuery(); if (results.next()) { lastIndex = results.getLong(EXTENT_INDEX_ID); } else { lastIndex = 0; LOGGER.log(Level.FINEST, "[" + getName() + "] no products in extentSummary table; using index 0"); } } catch (SQLiteException e) { throw new SQLiteException(e.getMessage() + ". SQL query was: " + sql, e.getResultCode()); } return lastIndex; }
Source:
<code>public void commitMeasurements() { if (!filter.noMeasurementsAvailable()) { double runningAverage = filter.calculateRunningAverage(); mBeacon.setRunningAverageRssi(runningAverage); <START> LogManager.d(TAG, "calculated new runningAverageRssi: %s", runningAverage); <END> } else { LogManager.d(TAG, "No measurements available to calculate running average"); } }</code><technical_language>setSampleExpirationMilliseconds needs retained for compatibility. I suggest change check if filter is instance of RunningAverageRssiFilter, if so, call a method set equivalent class. If is not, log a warning this do nothing</technical_language>

Target:
public void commitMeasurements() { if (!filter.noMeasurementsAvailable()) { double runningAverage = filter.calculateRssi(); mBeacon.setRunningAverageRssi(runningAverage); LogManager.d(TAG, "calculated new runningAverageRssi: %s", runningAverage); } else { LogManager.d(TAG, "No measurements available to calculate running average"); } }
Source:
<code>private List<Interval> getUnionSortedIntervals(List<List<Interval>> intervals) { <START> if (intervals.isEmpty()) { <END> return null; } return getUnionSortedIntervals(intervals, 0, intervals.size()); }</code><technical_language>possible, return null case</technical_language>

Target:
private List<Interval> getUnionSortedIntervals(List<List<Interval>> intervals) { return getUnionSortedIntervals(intervals, 0, intervals.size()); }
Source:
<code>public Dataverse getDataverse() { if (datasetVersion != null) { return datasetVersion.getDataset().getOwner(); } else if (parentDatasetFieldCompoundValue != null) { return parentDatasetFieldCompoundValue.getParentDatasetField().getDataverse(); } else if (template != null) { return template.getDataverse(); } else { <START> System.out.print("getDataverseException: " + this.datasetFieldType.getDisplayName()); <END> System.out.print("getDataverseException Compound: " + this.getCompoundDisplayValue()); System.out.print("getDataverseException Regular: " + this.getDisplayValue()); throw new IllegalStateException("DatasetField is in an illegal state: no dataset version, compound value, or template is set as its parent."); } }</code><technical_language>logger instead</technical_language>

Target:
public Dataverse getDataverse() { if (datasetVersion != null) { return datasetVersion.getDataset().getOwner(); } else if (parentDatasetFieldCompoundValue != null) { return parentDatasetFieldCompoundValue.getParentDatasetField().getDataverse(); } else if (template != null) { return template.getDataverse(); } else { throw new IllegalStateException("DatasetField is in an illegal state: no dataset version, compound value, or template is set as its parent."); } }
Source:
<code><START> public static void setUp() { <END> final String password = PASSWORD_ENCODER.encode(PASSWORD); final Map<String, Object> properties1 = new HashMap<>(); properties1.put(USERNAME, GOOD_USERNAME); properties1.put(FIRSTNAME, FIRSTNAME_VALUE); CommonProfile profile = new CommonProfile(); profile.build(IDPERSON1, properties1); inMemoryProfileService.create(profile, PASSWORD); final Map<String, Object> properties2 = new HashMap<>(); properties2.put(USERNAME, MULTIPLE_USERNAME); profile = new CommonProfile(); profile.build(IDPERSON2, properties2); inMemoryProfileService.create(profile, PASSWORD); final Map<String, Object> properties3 = new HashMap<>(); properties3.put(USERNAME, MULTIPLE_USERNAME); properties3.put(PASSWORD, password); profile = new CommonProfile(); profile.build(IDPERSON3, properties3); inMemoryProfileService.create(profile, PASSWORD); }</code><technical_language>a simple @Before a non-static InMemoryProfileService 100% is interferences tests :)</technical_language>

Target:
public void setUp() { inMemoryProfileService = new InMemoryProfileService<CommonProfile>(x -> new CommonProfile()); inMemoryProfileService.setPasswordEncoder(PASSWORD_ENCODER); final String password = PASSWORD_ENCODER.encode(PASSWORD); final Map<String, Object> properties1 = new HashMap<>(); properties1.put(USERNAME, GOOD_USERNAME); properties1.put(FIRSTNAME, FIRSTNAME_VALUE); CommonProfile profile = new CommonProfile(); profile.build(IDPERSON1, properties1); inMemoryProfileService.create(profile, PASSWORD); final Map<String, Object> properties2 = new HashMap<>(); properties2.put(USERNAME, MULTIPLE_USERNAME); profile = new CommonProfile(); profile.build(IDPERSON2, properties2); inMemoryProfileService.create(profile, PASSWORD); final Map<String, Object> properties3 = new HashMap<>(); properties3.put(USERNAME, MULTIPLE_USERNAME); properties3.put(PASSWORD, password); profile = new CommonProfile(); profile.build(IDPERSON3, properties3); inMemoryProfileService.create(profile, PASSWORD); }
Source:
<code>public Response postDownloadDatafiles(String fileIds, @QueryParam("gbrecs") boolean gbrecs, @QueryParam("key") String apiTokenParam, @Context UriInfo uriInfo, @Context HttpHeaders headers, @Context HttpServletResponse response) throws WebApplicationException { <START> fileIds = fileIds.substring(8); END> return downloadDatafiles(fileIds, gbrecs, apiTokenParam, uriInfo, headers, response); }</code><technical_language>I playing this curl a NullPointerException fileIds null (and a 500 error). Some error checking nice</technical_language>

Target:
public Response postDownloadDatafiles(String fileIds, @QueryParam("gbrecs") boolean gbrecs, @QueryParam("key") String apiTokenParam, @Context UriInfo uriInfo, @Context HttpHeaders headers, @Context HttpServletResponse response) throws WebApplicationException { return downloadDatafiles(fileIds, gbrecs, apiTokenParam, uriInfo, headers, response); }
Source:
<code>public List<BibEntry> linkAssociatedFiles(List<BibEntry> entries, NamedCompound ce) { List<BibEntry> changedEntries = new ArrayList<>(); List<IOException> fileExceptions = new ArrayList<>(); for (BibEntry entry : entries) { List<LinkedFile> linkedFiles = new ArrayList<>(); try { linkedFiles = findAssociatedNotLinkedFiles(entry); } catch (IOException e) { fileExceptions.add(e); LOGGER.error("Problem finding files", e); } if (ce != null) { <START> if (!fileExceptions.isEmpty()) { END> errorDialog.notify(Localization.lang("Problem finding files")); } for (LinkedFile linkedFile : linkedFiles) { String newVal = FileFieldWriter.getStringRepresentation(linkedFile); String oldVal = entry.getField(StandardField.FILE).orElse(null); UndoableFieldChange fieldChange = new UndoableFieldChange(entry, StandardField.FILE, oldVal, newVal); ce.addEdit(fieldChange); DefaultTaskExecutor.runInJavaFXThread(() -> { entry.addFile(linkedFile); }); } changedEntries.add(entry); } } return changedEntries; }</code><technical_language>I propose move this succeeded methoid : <LINK_0></technical_language>

Target:
public LinkFilesResult linkAssociatedFiles(List<BibEntry> entries, NamedCompound ce) { LinkFilesResult result = new LinkFilesResult(); for (BibEntry entry : entries) { List<LinkedFile> linkedFiles = new ArrayList<>(); try { linkedFiles = findAssociatedNotLinkedFiles(entry); } catch (IOException e) { result.addFileException(e); LOGGER.error("Problem finding files", e); } if (ce != null) { boolean changed = false; for (LinkedFile linkedFile : linkedFiles) { String newVal = FileFieldWriter.getStringRepresentation(linkedFile); String oldVal = entry.getField(StandardField.FILE).orElse(null); UndoableFieldChange fieldChange = new UndoableFieldChange(entry, StandardField.FILE, oldVal, newVal); ce.addEdit(fieldChange); changed = true; DefaultTaskExecutor.runInJavaFXThread(() -> { entry.addFile(linkedFile); }); } if (changed) { result.addBibEntry(entry); } } } return result; }
Source:
<code>private void rewriteGoogScope(Node n) { Node blockOfScopeContents = n.getLastChild().getLastChild().getLastChild(); blockOfScopeContents.detachFromParent(); Node insertAfterThisNode = n; @Nullable Node nodeToMove = blockOfScopeContents.getFirstChild(); while (nodeToMove != null) { @Nullable Node nodeToCheck = maybeRewriteAlias(nodeToMove); <START> if (null != nodeToCheck) { <END> nodeToMove = nodeToCheck; continue; } Node nextNodeToMove = nodeToMove.getNext(); nodeToMove.detachFromParent(); n.getParent().addChildAfter(nodeToMove, insertAfterThisNode); insertAfterThisNode = nodeToMove; nodeToMove = nextNodeToMove; } n.detachFromParent(); compiler.reportCodeChange(); }</code><technical_language>nit: reverse check nodeToCheck != null</technical_language>

Target:
private void rewriteGoogScope(Node n) { Node blockOfScopeContents = n.getLastChild().getLastChild().getLastChild(); blockOfScopeContents.detachFromParent(); Node insertAfterThisNode = n; @Nullable Node nodeToMove = blockOfScopeContents.getFirstChild(); while (nodeToMove != null) { @Nullable Node nodeToCheck = maybeRewriteAlias(nodeToMove); if (nodeToCheck != null) { nodeToMove = nodeToCheck; continue; } Node nextNodeToMove = nodeToMove.getNext(); nodeToMove.detachFromParent(); n.getParent().addChildAfter(nodeToMove, insertAfterThisNode); insertAfterThisNode = nodeToMove; nodeToMove = nextNodeToMove; } n.detachFromParent(); compiler.reportCodeChange(); }
Source:
<code>public void <START> testNormalizeWithUnicode() <END> { assertNormalized("föö/.bàr/*[<>|^~/bé\\z", "föö/bàr/bé-z"); }</code><technical_language>unicode characters in strings escaped \u L320</technical_language>

Target:
public void testNormalizeWithUnicode() { assertNormalized("f\u00f6\u00f6/.b\u00e0r ", "\u5165\u53e3_entrance;/\u51fa\u53e3_ex-it"); }
Source:
<code>private int countFailedTests(TaskResult taskResult){ int failed = 0; for (Submission submission: taskResult.getSubmissions()){ for (TestResult testResult: submission.getTestResults()){ <START> failed = testResult.isGreen() ? failed : failed + 1; <END> } } return failed; }</code><technical_language>prefer java for (...) { for (...) { if (!testResult.isGreen()) { failed++; } } } Streams: java return taskResult.getSubmissions().streamParallel() .map(Submission::getTestResults) .mapToInt(rs -> rs.streamParallel().mapToInt(r -> r.isGreen() ? 0 : 1).sum()) .sum();</technical_language>

Target:
private int countFailedTests(TaskResult taskResult){ int failed = 0; for (Submission submission: taskResult.getSubmissions()){ for (TestResult testResult: submission.getTestResults()){ if (!testResult.isGreen()){ failed++; } } } return failed; }
Source:
<code>public boolean shouldInvoke(C context) { cleanupExpiredSuppressions(); if (cache.containsKey(context)) return false; Suppression<C> suppression = new Suppression<>(context, System.nanoTime() + ttlNanos); if (cache.putIfAbsent(context, suppression) != null) return false; suppressions.offer(suppression); <START> while (suppressions.size() > maximumSize) { <END> tryClearOneSuppression(); } return true; }</code><technical_language>This is a bit scary, in a bad case, maximumSize wants protect against, threads spinning this</technical_language>

Target:
public boolean shouldInvoke(C context) { cleanupExpiredSuppressions(); if (cache.containsKey(context)) return false; Suppression<C> suppression = new Suppression<>(ticker, context, ticker.read() + ttlNanos); if (cache.putIfAbsent(context, suppression) != null) return false; suppressions.offer(suppression); if (suppressions.size() > cardinality) removeOneSuppression(); return true; }
Source:
<code>private void processReplaceCommand(final ReplaceCommand command, final InvocationContext ctx, final Object valueReplaced, TransactionContext transactionContext) { <START> Object key = extractValue(command.getKey()); <END> if (valueReplaced != null && command.isSuccessful() && shouldModifyIndexes(command, ctx, key)) { final boolean usingSkipIndexCleanupFlag = usingSkipIndexCleanup(command); Object p2 = extractValue(command.getNewValue()); final boolean newValueIsIndexed = updateKnownTypesIfNeeded(p2); if (!usingSkipIndexCleanupFlag) { final Object p1 = extractValue(command.getOldValue()); final boolean originalIsIndexed = updateKnownTypesIfNeeded(p1); if (p1 != null && originalIsIndexed) { transactionContext = transactionContext == null ? makeTransactionalEventContext() : transactionContext; removeFromIndexes(p1, key, transactionContext); } } if (newValueIsIndexed) { transactionContext = transactionContext == null ? makeTransactionalEventContext() : transactionContext; updateIndexes(usingSkipIndexCleanupFlag, p2, key, transactionContext); } } }</code><technical_language>move extractValue if</technical_language>

Target:
private void processReplaceCommand(final ReplaceCommand command, final InvocationContext ctx, final Object valueReplaced, TransactionContext transactionContext) { if (valueReplaced != null && command.isSuccessful()) { Object key = extractValue(command.getKey()); if (shouldModifyIndexes(command, ctx, key)) { final boolean usingSkipIndexCleanupFlag = usingSkipIndexCleanup(command); Object p2 = extractValue(command.getNewValue()); final boolean newValueIsIndexed = updateKnownTypesIfNeeded(p2); if (!usingSkipIndexCleanupFlag) { final Object p1 = extractValue(command.getOldValue()); final boolean originalIsIndexed = updateKnownTypesIfNeeded(p1); if (p1 != null && originalIsIndexed) { transactionContext = transactionContext == null ? makeTransactionalEventContext() : transactionContext; removeFromIndexes(p1, key, transactionContext); } } if (newValueIsIndexed) { transactionContext = transactionContext == null ? makeTransactionalEventContext() : transactionContext; updateIndexes(usingSkipIndexCleanupFlag, p2, key, transactionContext); } } } }
Source:
<code>private S fetchFromSchemaRegistry(String topic, String id) { try { S schema = registry.getSchemaByID(topic, id); return schema; <START> } catch (SchemaNotFoundException e) { <END> addFetchToFailureHistory(id); throw new SchemaNotFoundException(e); } }</code><technical_language>I underlying registry/restClient return SchemaRegistryClientException instead of SchemaNotFoundException in this case</technical_language>

Target:
private synchronized S fetchFromSchemaRegistry(String topic, String id) { try { S schema = registry.getSchemaByID(topic, id); return schema; } catch (SchemaNotFoundException e) { addFetchToFailureHistory(id); throw e; } }
Source:
<code>private void createCodebookAnnotations(JCas aJCas, List<String> headers, CSVRecord record) throws CollectionException { AnnotationFS codebookAnnotation; for (int i = 2; i < record.size() - 1; i++) { Type codebook = aJCas.getTypeSystem().getType(headers.get(i)); if (codebook == null) <START> throw new CollectionException(); END> codebookAnnotation = aJCas.getCas().createAnnotation(codebook, 0, aJCas.getDocumentText().length() - 1); codebookAnnotation.setFeatureValueFromString(codebook.getFeatureByBaseName("code"), record.get(i)); aJCas.addFsToIndexes(codebookAnnotation); } }</code><technical_language>Throw IOException a useful error message</technical_language>

Target:
private void createCodebookAnnotations(JCas aJCas, List<String> headers, CSVRecord record) throws IOException { AnnotationFS codebookAnnotation; for (int i = 2; i < record.size() - 1; i++) { Type codebook = aJCas.getTypeSystem().getType(headers.get(i)); if (codebook == null) throw new IOException("Codebook Type with name '" + headers.get(i) + "' is not registered in the typesystem!"); codebookAnnotation = aJCas.getCas().createAnnotation(codebook, 0, aJCas.getDocumentText().length() - 1); codebookAnnotation.setFeatureValueFromString(codebook.getFeatureByBaseName("code"), record.get(i)); aJCas.addFsToIndexes(codebookAnnotation); } }
Source:
<code>public RegistryResponseType processRequest(AdhocQueryRequest msg, AssertionType assertion) { LOG.debug("Running through AdapterDeferredResponseOptionProxyWebServiceUnsecuredImpl"); RegistryResponseType response = null; try { if (msg == null) { throw new IllegalArgumentException("Request Message must be provided"); } response = (RegistryResponseType) invokeClientPort(msg, assertion); } catch (final Exception ex) { <START> response = AdapterResponseHelper.createRegistryResponseTypeWithXdsQueryFailure(ERROR_MSG); <END> throw new ErrorEventException(ex, response, ERROR_MSG); } return response; }</code><technical_language>existing helper method</technical_language>

Target:
public RegistryResponseType processRequest(AdhocQueryRequest msg, AssertionType assertion) { LOG.debug("Running through AdapterDeferredResponseOptionProxyWebServiceUnsecuredImpl"); RegistryResponseType response = null; try { if (msg == null) { throw new IllegalArgumentException("Request Message must be provided"); } response = (RegistryResponseType) invokeClientPort(msg, assertion); } catch (final Exception ex) { response = AdapterResponseHelper.createFailureWithMessage(ERROR_MSG); throw new ErrorEventException(ex, response, ERROR_MSG); } return response; }
Source:
<code>public Sequence<Row> runQueryOnSegments(final List<File> segmentDirs, final Query query) { <START> final List<AbstractSegment> segments = Lists.transform( <END> segmentDirs, new Function<File, AbstractSegment>() { @Override public AbstractSegment apply(File segmentDir) { try { return new QueryableIndexSegment("", indexIO.loadIndex(segmentDir)); } catch (IOException ex) { throw Throwables.propagate(ex); } } } ); try { return runQueryOnSegmentsObjs(segments, query); } finally { for(Segment segment: segments) { CloseQuietly.close(segment); } } }</code><technical_language>changes required? I keeping Segment fine (and more correct, 'cause totally chooses implement Segment AbstractSegment)</technical_language>

Target:
public Sequence<Row> runQueryOnSegments(final List<File> segmentDirs, final Query query) { final List<Segment> segments = Lists.transform( segmentDirs, new Function<File, Segment>() { @Override public Segment apply(File segmentDir) { try { return new QueryableIndexSegment("", indexIO.loadIndex(segmentDir)); } catch (IOException ex) { throw Throwables.propagate(ex); } } } ); try { return runQueryOnSegmentsObjs(segments, query); } finally { for(Segment segment: segments) { CloseQuietly.close(segment); } } }
Source:
<code>public void canRetrieveFromAccount() { GenericAccount account = new GenericAccount(); account.setDataGroups(Sets.newHashSet("group1","group2")); account.setNotifyByEmail(true); account.setExternalId("testExternalID"); account.setLanguages(TestUtils.newLinkedHashSet("en","de")); account.setSharingScope(SharingScope.ALL_QUALIFIED_RESEARCHERS); account.setTimeZone(DateTimeZone.forOffsetHours(-7)); String result = ParticipantOption.DATA_GROUPS.fromAccount(account); assertTrue(result.contains("group1")); assertTrue(result.contains("group2")); result = ParticipantOption.EMAIL_NOTIFICATIONS.fromAccount(account); <START> assertEquals("true", result); <END> result = ParticipantOption.EXTERNAL_IDENTIFIER.fromAccount(account); assertEquals("testExternalID", result); result = ParticipantOption.LANGUAGES.fromAccount(account); assertEquals("en,de", result); result = ParticipantOption.SHARING_SCOPE.fromAccount(account); assertEquals(SharingScope.ALL_QUALIFIED_RESEARCHERS.name(), result); result = ParticipantOption.TIME_ZONE.fromAccount(account); assertEquals("-07:00", result); }</code><technical_language>test a non-default for this test</technical_language>

Target:
public void canRetrieveFromAccount() { GenericAccount account = new GenericAccount(); account.setDataGroups(Sets.newHashSet("group1","group2")); account.setNotifyByEmail(false); account.setExternalId("testExternalID"); account.setLanguages(TestUtils.newLinkedHashSet("en","de")); account.setSharingScope(SharingScope.ALL_QUALIFIED_RESEARCHERS); account.setTimeZone(DateTimeZone.forOffsetHours(-7)); String result = ParticipantOption.DATA_GROUPS.fromAccount(account); assertTrue(result.contains("group1")); assertTrue(result.contains("group2")); result = ParticipantOption.EMAIL_NOTIFICATIONS.fromAccount(account); assertEquals("false", result); result = ParticipantOption.EXTERNAL_IDENTIFIER.fromAccount(account); assertEquals("testExternalID", result); result = ParticipantOption.LANGUAGES.fromAccount(account); assertEquals("en,de", result); result = ParticipantOption.SHARING_SCOPE.fromAccount(account); assertEquals(SharingScope.ALL_QUALIFIED_RESEARCHERS.name(), result); result = ParticipantOption.TIME_ZONE.fromAccount(account); assertEquals("-07:00", result); }
Source:
<code>public void shutdown() { wantShutdown = true; <START> if ((channel != null) && channel.isConnected()) { <END> try { ChannelFuture closeFuture = channel.getCloseFuture(); channel.close(); closeFuture.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } bootstrap.releaseExternalResources(); }</code><technical_language>Unsynchronized access channel</technical_language>

Target:
public void shutdown() { wantShutdown = true; synchronized(channelSync) { if ((channel != null) && channel.isConnected()) { try { ChannelFuture closeFuture = channel.getCloseFuture(); channel.close(); closeFuture.await(); } catch (InterruptedException e) { log.log(Level.WARNING, "Got exception during shutdown", e); } } bootstrap.releaseExternalResources(); } }
Source:
<code>protected void onConstructorFound(NewClassTree newClassTree) { Optional<Symbol> variable = lookupInitializedSymbol(newClassTree); <START> if (!variable.isPresent()) { <END> variable = lookupAssignedSymbol(newClassTree); } variable .filter(Symbol::isVariableSymbol) .map(Symbol::owner) .filter(Symbol::isMethodSymbol) .filter(ReuseRandomCheck::isNotConstructorOrStaticMain) .ifPresent(owner -> reportIssue(newClassTree.identifier(), "Save and re-use this \"Random\".")); }</code><technical_language>This replaced : lookupInitializedSymbol(newClassTree).map(Optional::of).orElseGet(() -> lookupAssignedSymbol(newClassTree) )</technical_language>

Target:
protected void onConstructorFound(NewClassTree newClassTree) { if (assignedToLocalVariablesNotInConstructorOrStaticMain(newClassTree)) { reportIssue(newClassTree.identifier(), "Save and re-use this \"Random\"."); } }
Source:
<code>private NumberPicker createNumberPicker() { NumberPicker picker = new NumberPicker(getActivity()); picker.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT, CENTER)); picker.setMinValue(0); picker.setMaxValue(5); picker.setValue(mValue); picker.setWrapSelectorWheel(false); <START> Log.d("folder fragment", "create number picker "+mValue); <END> return picker; }</code><technical_language>remove debug logs in this fragment, reason in keeping them</technical_language>

Target:
private NumberPicker createNumberPicker() { NumberPicker picker = new NumberPicker(getActivity()); picker.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT, CENTER)); picker.setMinValue(0); picker.setMaxValue(5); picker.setValue(mValue); picker.setWrapSelectorWheel(false); return picker; }
Source:
<code>public static Boolean shouldReplicate(ReplicationSpec replicationSpec, Table tableHandle, HiveConf hiveConf) { if (replicationSpec == null) { replicationSpec = new ReplicationSpec(); } if (replicationSpec.isNoop() || tableHandle == null) { return false; } if (tableHandle.isNonNative()) { return false; } <START> if (!hiveConf.getBoolVar(HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES) && <END> MetaStoreUtils.isExternalTable(tableHandle.getTTable()) && !replicationSpec.isMetadataOnly() && replicationSpec.isInReplicationScope()) { return false; } if (replicationSpec.isInReplicationScope()) { boolean isAcidTable = AcidUtils.isTransactionalTable(tableHandle); if (isAcidTable) { return hiveConf.getBoolVar(HiveConf.ConfVars.REPL_DUMP_INCLUDE_ACID_TABLES); } return !tableHandle.isTemporary(); } return true; }</code><technical_language>move this check if block for replicationSpec.isInReplicationScope()</technical_language>

Target:
public static Boolean shouldReplicate(ReplicationSpec replicationSpec, Table tableHandle, HiveConf hiveConf) { if (replicationSpec == null) { replicationSpec = new ReplicationSpec(); } if (replicationSpec.isNoop() || tableHandle == null) { return false; } if (tableHandle.isNonNative()) { return false; } if (replicationSpec.isInReplicationScope()) { if (!hiveConf.getBoolVar(HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES) && MetaStoreUtils.isExternalTable(tableHandle.getTTable()) && !replicationSpec.isMetadataOnly()) { return false; } boolean isAcidTable = AcidUtils.isTransactionalTable(tableHandle); if (isAcidTable) { return hiveConf.getBoolVar(HiveConf.ConfVars.REPL_DUMP_INCLUDE_ACID_TABLES); } return !tableHandle.isTemporary(); } return true; }