auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String getAllCriteriaWithNumber(String criterionNumber) { List<CertificationCriterionDTO> allCriteriaWithNumber = criteriaDao.getAllByNumber(criterionNumber); String criteriaNumbers = ""; for (CertificationCriterionDTO criterion : allCriteriaWithNumber) { if (!StringUtils.isEmpty(criteriaNumbers)) { criteriaNumbers += " or "; } criteriaNumbers += Util.formatCriteriaNumber(criterion); } return criteriaNumbers; }

Target:
public String getAllCriteriaWithNumber(String criterionNumber) { List<CertificationCriterionDTO> allCriteriaWithNumber = criteriaDao.getAllByNumber(criterionNumber); List<String> allCriteriaNumbers = allCriteriaWithNumber.stream() .map(criterion -> Util.formatCriteriaNumber(criterion)) .collect(Collectors.toList()); return allCriteriaNumbers.stream().collect(Collectors.joining(" or ")); }
Source:
public PinotColumnHandle( @JsonProperty("columnName") String columnName, @JsonProperty("dataType") Type dataType, @JsonProperty("type") PinotColumnType type) { this.columnName = requireNonNull(columnName, "column name"); this.dataType = requireNonNull(dataType, "data type name"); this.type = requireNonNull(type, "type is null"); }

Target:
public PinotColumnHandle( @JsonProperty("columnName") String columnName, @JsonProperty("dataType") Type dataType, @JsonProperty("type") PinotColumnType type) { this.columnName = requireNonNull(columnName, "column name is null"); this.dataType = requireNonNull(dataType, "data type name is null"); this.type = requireNonNull(type, "type is null"); }
Source:
public void createAndTriggerReplicationWithNoIamAuth() throws Exception { mockWebServer.enqueue(JSON_OK); CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer) .build(); c.replication() .source(sourceDbUrl) .target(targetDbUrl) .trigger(); RecordedRequest[] requests = takeN(mockWebServer, 1); assertEquals(requests[0].getPath(), "/_replicate"); String body = requests[0].getBody().readString(Charset.forName("UTF-8")); assertThat("The replication document should contain the correct source", body, containsString("\"source\":\"" + sourceDbUrl + "\"")); assertThat("The replication document should contain the correct target", body, containsString("\"target\":\"" + targetDbUrl + "\"")); }

Target:
public void createAndTriggerReplicationWithNoIamAuth() throws Exception { server.enqueue(JSON_OK); CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server) .build(); c.replication() .source(sourceDbUrl) .target(targetDbUrl) .trigger(); RecordedRequest[] requests = takeN(server, 1); assertEquals(requests[0].getPath(), "/_replicate"); String body = requests[0].getBody().readUtf8(); assertThat("The replication document should contain the correct source", body, containsString("\"source\":\"" + sourceDbUrl + "\"")); assertThat("The replication document should contain the correct target", body, containsString("\"target\":\"" + targetDbUrl + "\"")); }
Source:
private void reflowAsync() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { getParentSection().getTaskEditorPage().reflow(); } }); }

Target:
private void reflowAsync() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { reflow(); } }); }
Source:
public void testAddUserToGroup() throws RedmineException { final Group template = new Group(); template.setName("testAddUserToGroup " + System.currentTimeMillis()); final Group group = mgr.createGroup(template); try { final User newUser = mgr.createUser(generateRandomUser()); try { mgr.addUserToGroup(newUser, group); mgr.addUserToGroup(newUser, group); final List<Group> userGroups = mgr.getUserById(newUser.getId()).getGroups(); assertTrue(userGroups.size() > 0); } finally { mgr.deleteUser(newUser.getId()); } } finally { mgr.deleteGroup(group); } }

Target:
public void testAddUserToGroup() throws RedmineException { final Group template = new Group(); template.setName("testAddUserToGroup " + System.currentTimeMillis()); final Group group = mgr.createGroup(template); try { final User newUser = mgr.createUser(generateRandomUser()); try { mgr.addUserToGroup(newUser, group); final List<Group> userGroups = mgr.getUserById(newUser.getId()).getGroups(); assertTrue(userGroups.size() == 1); assertTrue(group.getName().equals(userGroups.get(0).getName())); } finally { mgr.deleteUser(newUser.getId()); } } finally { mgr.deleteGroup(group); } }
Source:
public byte[] getFileContent(Long userEntityId, String fileId) throws IOException { if (userEntityId == null || fileId == null) { logger.severe(String.format("Invalid fetch parameters: file %s of user %d", fileId, userEntityId)); return new byte[0]; } SystemSetting fileFolderSetting = systemSettingDAO.findByKey(SETTING_FILEFOLDER); if (fileFolderSetting != null && !StringUtils.isBlank(fileFolderSetting.getValue())) { java.io.File answerFile = Paths.get(fileFolderSetting.getValue(), userEntityId.toString(), fileId).toFile(); if (answerFile.exists()) { return Files.readAllBytes(answerFile.toPath()); } } logger.warning(String.format("Failed to retrieve file %s of user %d", fileId, userEntityId)); return new byte[0]; }

Target:
public byte[] getFileContent(Long userEntityId, String fileId) throws IOException { if (userEntityId == null || fileId == null) { logger.severe(String.format("Invalid fetch parameters: file %s of user %d", fileId, userEntityId)); throw new IllegalArgumentException("Invalid fetch parameters"); } SystemSetting fileFolderSetting = systemSettingDAO.findByKey(SETTING_FILEFOLDER); if (fileFolderSetting == null || StringUtils.isBlank(fileFolderSetting.getValue())) { throw new IOException("File answer storage folder not set"); } java.io.File answerFile = Paths.get(fileFolderSetting.getValue(), userEntityId.toString(), fileId).toFile(); if (answerFile.exists()) { return Files.readAllBytes(answerFile.toPath()); } else { logger.warning(String.format("File %s of user %d not found", fileId, userEntityId)); throw new FileNotFoundException(); } }
Source:
public void testAllBlockComments() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(BlockCommentListenerCheck.class); final String path = getPath("InputFullOfBlockComments.java"); if (new FileText(new File(path), StandardCharsets.UTF_8.name()) .getFullText().chars().anyMatch(character -> character == '\r')) { lineSeparator = "\r\n"; } else { lineSeparator = "\n"; } final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify(checkConfig, path, expected); Assert.assertTrue("All comments should be empty", ALL_COMMENTS.isEmpty()); }

Target:
public void testAllBlockComments() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(BlockCommentListenerCheck.class); final String path = getPath("InputFullOfBlockComments.java"); lineSeparator = CheckUtil.getLineSeparatorForFile(path, StandardCharsets.UTF_8); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify(checkConfig, path, expected); Assert.assertTrue("All comments should be empty", ALL_COMMENTS.isEmpty()); }
Source:
private void alter_table_core(final String catName, final String dbname, final String name, final Table newTable, final EnvironmentContext envContext) throws InvalidOperationException, MetaException { startFunction("alter_table", ": " + TableName.getQualified(catName, dbname, name) + " newtbl=" + newTable.getTableName()); if (newTable.getParameters() == null || newTable.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) { newTable.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(System .currentTimeMillis() / 1000)); } if (newTable.getSd() != null) { String newLocation = newTable.getSd().getLocation(); if (org.apache.commons.lang.StringUtils.isNotEmpty(newLocation)) { Path tblPath = wh.getDnsPath(new Path(newLocation)); newTable.getSd().setLocation(tblPath.toString()); } } if (!newTable.isSetCatName()) { newTable.setCatName(catName); } boolean success = false; Exception ex = null; try { Table oldt = get_table_core(catName, dbname, name); firePreEvent(new PreAlterTableEvent(oldt, newTable, this)); if (newTable.getDbName() == null) { throw new InvalidOperationException("Unable to alter table" + dbname + "." + name + " as new db name is null"); } alterHandler.alterTable(getMS(), wh, catName, dbname, name, newTable, envContext, this); success = true; } catch (NoSuchObjectException e) { ex = e; throw new InvalidOperationException(e.getMessage()); } catch (MetaException | InvalidOperationException e) { ex = e; throw e; } catch (Exception e) { ex = e; throw newMetaException(e); } finally { endFunction("alter_table", success, ex, name); } }

Target:
private void alter_table_core(final String catName, final String dbname, final String name, final Table newTable, final EnvironmentContext envContext) throws InvalidOperationException, MetaException { startFunction("alter_table", ": " + TableName.getQualified(catName, dbname, name) + " newtbl=" + newTable.getTableName()); if (newTable.getParameters() == null || newTable.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) { newTable.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(System .currentTimeMillis() / 1000)); } if (newTable.getSd() != null) { String newLocation = newTable.getSd().getLocation(); if (org.apache.commons.lang.StringUtils.isNotEmpty(newLocation)) { Path tblPath = wh.getDnsPath(new Path(newLocation)); newTable.getSd().setLocation(tblPath.toString()); } } if (!newTable.isSetCatName()) { newTable.setCatName(catName); } boolean success = false; Exception ex = null; try { Table oldt = get_table_core(catName, dbname, name); firePreEvent(new PreAlterTableEvent(oldt, newTable, this)); alterHandler.alterTable(getMS(), wh, catName, dbname, name, newTable, envContext, this); success = true; } catch (NoSuchObjectException e) { ex = e; throw new InvalidOperationException(e.getMessage()); } catch (MetaException | InvalidOperationException e) { ex = e; throw e; } catch (Exception e) { ex = e; throw newMetaException(e); } finally { endFunction("alter_table", success, ex, name); } }
Source:
public void update(AccessPoint ap) { AccessPointEntity entity = datastore.findOne(AccessPointEntity.class, Filter.where("_id").is(ap.id)); if (entity != null) { datastore.save(adapt(ap, entity.getOperatorId())); } }

Target:
public void update(AccessPoint ap) { datastore.save(adapt(ap)); }
Source:
void setStatus(final String status) { getEventList().add(Pair.create(EventStrings.CRYPTOGRAPHY_STATUS, status)); }

Target:
void setStatus(final String status) { setEvent(EventStrings.CRYPTOGRAPHY_STATUS, status); }
Source:
private int findObjectsNeedingDelta(ObjectToPack[] list, int cnt, int type) { FIND: for (ObjectToPack otp : objectsLists[type]) { ObjectToPack base = otp.getDeltaBase(); if (base != null) { int d = 0; do { if (d < base.getChainLength()) continue FIND; base.setChainLength(++d); base = base.getDeltaBase(); } while (base != null && base != otp); continue; } if (otp.isDoNotDelta()) continue; if (otp.isDeltaRepresentation()) continue; otp.setWeight(0); list[cnt++] = otp; } return cnt; }

Target:
private int findObjectsNeedingDelta(ObjectToPack[] list, int cnt, int type) throws IOException { for (ObjectToPack otp : objectsLists[type]) { ObjectToPack b = otp.getDeltaBase(); if (b != null) { otp.setVisited(); int d = 0; do { if (d < b.getChainLength()) break; b.setChainLength(++d); if (b.visited()) { reselectNonDelta(b); break; } b.setVisited(); b = b.getDeltaBase(); } while (b != null); for (b = otp; b != null && b.visited(); b = b.getDeltaBase()) b.clearVisited(); continue; } if (otp.isDoNotDelta()) continue; if (otp.isDeltaRepresentation()) continue; otp.setWeight(0); list[cnt++] = otp; } return cnt; }
Source:
boolean requestRunway (PushOne op) { synchronized (stateLock) { if (op.wasCanceled()) { return true; } if (inflight.get(op.getURI()) != null) { return false; } pending.remove(op.getURI()); inFlight.put(e.getURI(), e); } }

Target:
boolean requestRunway (PushOne op) { synchronized (stateLock) { if (op.wasCanceled()) { return true; } if (inFlight.get(op.getURI()) != null) { return false; } pending.remove(op.getURI()); inFlight.put(op.getURI(), op); } return true; }
Source:
private Object fetchObject(RequestScope requestScope, Class recordType, Optional<List<String>> ids, Optional<String> sort, Optional<String> offset, Optional<String> first, Optional<String> filters) { if(!ids.isPresent()) { List<PersistentResource> records = new ArrayList<>(PersistentResource. loadRecords(recordType, requestScope)); return records; } else { List<String> idList = ids.get(); if(idList.isEmpty()) { throw new IllegalArgumentException("Empty list passed to ids"); } HashSet recordSet = new HashSet(); for (String id : idList) { recordSet.add(PersistentResource.loadRecord(recordType, id, requestScope)); } return recordSet; } }

Target:
private Object fetchObject(RequestScope requestScope, Class recordType, Optional<List<String>> ids, Optional<String> sort, Optional<String> offset, Optional<String> first, Optional<String> filters) { if(!ids.isPresent()) { List<PersistentResource> records = new ArrayList<>(PersistentResource. loadRecords(recordType, requestScope, Optional.empty())); return records; } else { List<String> idList = ids.get(); if(idList.isEmpty()) { throw new BadRequestException("Empty list passed to ids"); } Optional<FilterExpression> filterExpression; EntityDictionary dictionary = requestScope.getDictionary(); Class<?> idType = dictionary.getIdType(recordType); String idField = dictionary.getIdFieldName(recordType); String entityTypeName = dictionary.getJsonAliasFor(recordType); filterExpression = Optional.of(new FilterPredicate( new FilterPredicate.PathElement( recordType, entityTypeName, idType, idField), Operator.IN, new ArrayList<>(idList))); return PersistentResource.loadRecords(recordType, requestScope, filterExpression); } }
Source:
public void Test() { Collection<Cat> cats = Lists.newArrayList(); cats.add(new Cat(Optional.<String>absent())); cats.add(new Cat(Optional.of("persan"))); Cat c = alias(Cat.class); for (Cat cat : from(c, cats) .where($(c.getPedigree()).eq(Optional.of("persan"))) .list($(c))) { assertTrue(cat.getPedigree().isPresent()); assertEquals("persan", cat.getPedigree().get()); } }

Target:
public void Test() { Collection<Cat> cats = Lists.newArrayList(); cats.add(new Cat(Optional.<String>absent())); cats.add(new Cat(Optional.of("persian"))); Cat c = alias(Cat.class); for (Cat cat : from(c, cats) .where($(c.getPedigree()).eq(Optional.of("persian"))) .list($(c))) { assertTrue(cat.getPedigree().isPresent()); assertEquals("persian", cat.getPedigree().get()); } }
Source:
public String toString() { return String.format("%30s: fboId %s (%sx%s)", this.getClass().getSimpleName(), fbo.getId(), fbo.width(), fbo.height()); }

Target:
public String toString() { return String.format("%30s: %s (fboId: %s) (%sx%s)", this.getClass().getSimpleName(), fbo.getName(), fbo.getId(), fbo.width(), fbo.height()); }
Source:
public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); List<String> tempList; if (constraint != null) tempList = autoCompleter.completeByPart(constraint.toString()); else tempList = new ArrayList<>(); filterResults.values = tempList; filterResults.count = tempList.size(); return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { clear(); if (results != null && results.count > 0) { addAll((List) results.values); notifyDataSetChanged(); } else notifyDataSetInvalidated(); } }; }

Target:
public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); List<String> tempList; if (constraint != null) tempList = autoCompleter.completeByPart(constraint.toString()); else tempList = new ArrayList<>(); filterResults.values = tempList; filterResults.count = tempList.size(); return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { clear(); if (results != null && results.count > 0) { addAll((List) results.values); notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } }; }
Source:
public List<RemoteServerData> getServerList() { return UnmodifiableList.decorate(remoteServerDataList); }

Target:
public List<RemoteServerData> getServerList() { return Collections.unmodifiableList(remoteServerDataList); }
Source:
public static Version increment(Version version) { final Version result = create(version.getNumber() + 1, currentTime()); return result; }

Target:
public static Version increment(Version version) { checkNotNull(version); final Version result = create(version.getNumber() + 1, getCurrentTime()); return result; }
Source:
public void testSetupInvalidChildFromBaseClass() throws Exception { final TestBean testBean = new TestBean(); final DefaultConfiguration conf = new DefaultConfiguration("testConf"); final Field field = AutomaticBean.class.getDeclaredField("configuration"); field.setAccessible(true); field.set(testBean, conf); try { testBean.setupChild(conf); fail("expecting checkstyle exception"); } catch (CheckstyleException ex) { assertEquals("expected exception", "testConf is not allowed as a child in testConf", ex.getMessage()); } }

Target:
public void testSetupInvalidChildFromBaseClass() throws Exception { final TestBean testBean = new TestBean(); final DefaultConfiguration parentConf = new DefaultConfiguration("parentConf"); final DefaultConfiguration childConf = new DefaultConfiguration("childConf"); final Field field = AutomaticBean.class.getDeclaredField("configuration"); field.setAccessible(true); field.set(testBean, parentConf); try { testBean.setupChild(childConf); fail("expecting checkstyle exception"); } catch (CheckstyleException ex) { assertEquals("expected exception", "childConf is not allowed as a child in parentConf", ex.getMessage()); } }
Source:
private void fillFieldsFromMetadataFile(FileformatInterface myRdf) throws PreferencesException { if (myRdf != null) { for (AdditionalField field : this.additionalFields) { if (field.isUghbinding() && field.getShowDependingOnDoctype()) { DocStructInterface myTempStruct = myRdf.getDigitalDocument().getLogicalDocStruct(); if (field.getDocstruct().equals("firstchild")) { try { myTempStruct = myRdf.getDigitalDocument().getLogicalDocStruct().getAllChildren().get(0); } catch (RuntimeException e) { logger.error(e.getMessage(), e); } } if (field.getDocstruct().equals("boundbook")) { myTempStruct = myRdf.getDigitalDocument().getPhysicalDocStruct(); } try { if (field.getMetadata().equals("ListOfCreators")) { StringBuilder authors = new StringBuilder(); if (myTempStruct.getAllPersons() != null) { for (PersonInterface p : myTempStruct.getAllPersons()) { authors.append(p.getLastName()); if (StringUtils.isNotBlank(p.getFirstName())) { authors.append(", "); authors.append(p.getFirstName()); } authors.append("; "); } if (authors.toString().endsWith("; ")) { authors.substring(0, authors.length() - 2); } } field.setValue(authors.toString()); } else { MetadataTypeInterface mdt = UghHelper.getMetadataType( serviceManager.getRulesetService().getPreferences(this.prozessKopie.getRuleset()), field.getMetadata()); MetadataInterface md = UghHelper.getMetadata(myTempStruct, mdt); if (md != null) { field.setValue(md.getValue()); } } } catch (UghHelperException e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung(e.getMessage(), ""); } } } } }

Target:
private void fillFieldsFromMetadataFile(FileformatInterface myRdf) throws PreferencesException { if (myRdf != null) { for (AdditionalField field : this.additionalFields) { if (field.isUghbinding() && field.getShowDependingOnDoctype()) { DocStructInterface myTempStruct = myRdf.getDigitalDocument().getLogicalDocStruct(); if (field.getDocstruct().equals("firstchild")) { try { myTempStruct = myRdf.getDigitalDocument().getLogicalDocStruct().getAllChildren().get(0); } catch (RuntimeException e) { logger.error(e.getMessage(), e); } } if (field.getDocstruct().equals("boundbook")) { myTempStruct = myRdf.getDigitalDocument().getPhysicalDocStruct(); } try { if (field.getMetadata().equals("ListOfCreators")) { field.setValue(getAuthors(myTempStruct.getAllPersons())); } else { MetadataTypeInterface mdt = UghHelper.getMetadataType( serviceManager.getRulesetService().getPreferences(this.prozessKopie.getRuleset()), field.getMetadata()); MetadataInterface md = UghHelper.getMetadata(myTempStruct, mdt); if (md != null) { field.setValue(md.getValue()); } } } catch (UghHelperException e) { Helper.setErrorMessage(e.getMessage(), logger, e); } } } } }
Source:
public void testGetChangedAttributesWithComments() { TaskAttribute attributeComment = newData.getRoot().createAttribute("custom"); attributeComment.setValue("1"); attributeComment.getMetaData().setType(TaskAttribute.TYPE_COMMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); assertEquals(new ArrayList<>(diff.getNewComments()).get(0).getTaskAttribute(), attributeComment); }

Target:
public void testGetChangedAttributesWithComments() { TaskAttribute attributeComment = newData.getRoot().createAttribute("custom"); attributeComment.setValue("1"); attributeComment.getMetaData().setType(TaskAttribute.TYPE_COMMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); assertEquals(1, diff.getNewComments().size()); assertEquals(attributeComment, diff.getNewComments().iterator().next().getTaskAttribute()); }
Source:
public void onUpdateToFirstVersion(OrienteerWebApplication app, ODatabaseDocument db) { OSchemaHelper helper = OSchemaHelper.bind(db); helper.oClass(WIDGET_OCLASS_NAME, OWidgetsModule.OCLASS_WIDGET) .oProperty(OPROPERTY_PIVOT_TABLE_CONFIG, OType.STRING, 100).assignVisualization("textarea") .oProperty(OPROPERTY_PIVOT_CUSTOM_SQL, OType.STRING, 200).assignVisualization("textarea"); }

Target:
public void onUpdateToFirstVersion(OrienteerWebApplication app, ODatabaseDocument db) { OSchemaHelper helper = OSchemaHelper.bind(db); helper.oClass(WIDGET_OCLASS_NAME, OWidgetsModule.OCLASS_WIDGET) .oProperty(OPROPERTY_PIVOT_TABLE_CONFIG, OType.STRING, 100).assignVisualization("textarea"); }
Source:
public int compareTo(QC t) { SampleQC s = (SampleQC) t; if (getId() != 0L && t.getId() != 0L) { if (getId() < s.getId()) return -1; if (getId() > s.getId()) return 1; } else if (getQcType() != null && s.getQcType() != null && getResults() != null && s.getResults() != null && getQcDate() != null && s.getQcDate() != null) { int type = getQcType().compareTo(s.getQcType()); if (type != 0) return type; int results = getResults().compareTo(s.getResults()); if (results != 0) return results; int creator = getQcDate().compareTo(s.getQcDate()); if (creator != 0) return creator; } return 0; }

Target:
public int compareTo(QC t) { SampleQC s = (SampleQC) t; int compare = super.compareTo(t); if (compare != 0) { return compare; } else if (getResults() != null && s.getResults() != null) { compare = getResults().compareTo(s.getResults()); return compare; } return compare; }
Source:
public void testPreHandle_not_call_afterPropertiesSet() throws Exception { testTarget.preHandle(mockRequest, mockResponse, null); assertThat(mockRequest.getAttributeNames().hasMoreElements(), is(false)); }

Target:
public void testPreHandle_not_call_afterPropertiesSet() throws Exception { boolean actualReturnValue = testTarget.preHandle(mockRequest, mockResponse, null); assertThat(mockRequest.getAttributeNames().hasMoreElements(), is(false)); assertThat(actualReturnValue, is(true)); }
Source:
private int unlockAndCountExceptions(RemoteLockService lockService, List<Future<LockRefreshToken>> futures) { final int[] exceptionCounter = {0}; futures.forEach(future -> { try { LockRefreshToken token = future.get(); if (token != null) { lockService.unlock(token); } } catch (Exception e) { assertThat(e).hasMessageContaining(TOO_MANY_REQUESTS_CODE); exceptionCounter[0]++; } }); return exceptionCounter[0]; }

Target:
private int unlockAndCountExceptions(RemoteLockService lockService, List<Future<LockRefreshToken>> futures) { AtomicInteger exceptionCounter = new AtomicInteger(0); futures.forEach(future -> { try { LockRefreshToken token = future.get(); if (token != null) { lockService.unlock(token); } } catch (Exception e) { assertThat(e).hasMessageContaining(TOO_MANY_REQUESTS_CODE); exceptionCounter.getAndIncrement(); } }); return exceptionCounter.get(); }
Source:
public void setBytes(byte[] bytes) { this.bytes = bytes; this.hash = Arrays.hashCode(bytes); }

Target:
void setBytes(byte[] bytes) { this.bytes = bytes; this.hash = Arrays.hashCode(bytes); }
Source:
private String getBrowserScreenHeight(EpdqTemplateData templateData) { var screenHeight = templateData.getAuthCardDetails().getJsScreenHeight().orElse(DEFAULT_BROWSER_SCREEN_HEIGHT); if (isCreatable(screenHeight) && BROWSER_SCREEN_HEIGHT_RANGE.contains(parseInt(screenHeight))) { return screenHeight; } else { return DEFAULT_BROWSER_SCREEN_HEIGHT; } }

Target:
private String getBrowserScreenHeight(EpdqTemplateData templateData) { return templateData.getAuthCardDetails().getJsScreenHeight() .filter(screenHeight -> NUMBER_FROM_0_TO_999999.matcher(screenHeight).matches()) .map(Integer::parseInt) .filter(screenHeight -> screenHeight >= 0 && screenHeight <= 999999) .map(screenHeight -> Integer.toString(screenHeight)) .orElse(DEFAULT_BROWSER_SCREEN_HEIGHT); }
Source:
public FilteredRequest(HttpServletRequest request, String serverName) { super(request); if (request instanceof FilteredRequest) { FilteredRequest filteredRequest = (FilteredRequest) request; contextPath = filteredRequest.contextPath; requestUri = filteredRequest.requestUri; requestUrl = filteredRequest.requestUrl; } else { URL baseUrl = toBaseUrl(serverName); contextPath = isExternalRequest(baseUrl) ? SystemBaseUrl.EXTERNAL.getRootContext().replaceFirst("/$", "") : ""; requestUri = contextPath + request.getRequestURI(); requestUrl = (baseUrl == null) ? serverName.replaceFirst("/$", "") + requestUri : baseUrl.toString() + requestUri; } }

Target:
public FilteredRequest(HttpServletRequest request, String serverName) { super(request); if (request instanceof FilteredRequest) { FilteredRequest filteredRequest = (FilteredRequest) request; contextPath = filteredRequest.contextPath; requestUri = filteredRequest.requestUri; requestUrl = filteredRequest.requestUrl; } else { URL baseUrl = toBaseUrl(serverName); contextPath = isExternalUrl(baseUrl) ? SystemBaseUrl.EXTERNAL.getRootContext().replaceFirst("/$", "") : ""; requestUri = contextPath + request.getRequestURI(); requestUrl = (baseUrl == null) ? serverName.replaceFirst("/$", "") + requestUri : baseUrl.toString() + requestUri; } }
Source:
public void complete() { this.ownerProductCurator.saveAll(this.ownerProductEntities, false, true); for (Map.Entry<Owner, Map<String, String>> entry : this.ownerProductUuidMap.entrySet()) { this.ownerProductCurator.updateOwnerProductReferences(entry.getKey(), entry.getValue()); } this.ownerProductUuidMap.clear(); this.ownerProductEntities.clear(); }

Target:
public void complete() { this.ownerProductCurator.saveAll(this.ownerProductEntities, false, false); this.ownerProductCurator.flush(); for (Map.Entry<Owner, Map<String, String>> entry : this.ownerProductUuidMap.entrySet()) { this.ownerProductCurator.updateOwnerProductReferences(entry.getKey(), entry.getValue()); } this.ownerProductUuidMap.clear(); this.ownerProductEntities.clear(); }
Source:
public void normalize(List<String> normalized) { String releaseOrTarget = null; if (release != null) { normalized.add("--release"); normalized.add(release); releaseOrTarget = release; } else { if (source != null) { normalized.add("-source"); normalized.add(source); } if (target != null) { normalized.add("-target"); normalized.add(target); releaseOrTarget = target; } } if (parameters && Optional.ofNullable(releaseOrTarget).map(Ints::tryParse).orElse(8) >= 8) { normalized.add("-parameters"); } }

Target:
public void normalize(List<String> normalized) { int targetedJavaVersion = 8; if (release != null) { normalized.add("--release"); normalized.add(release); targetedJavaVersion = Integer.parseInt(release); } else { if (source != null) { normalized.add("-source"); normalized.add(source); } if (target != null) { normalized.add("-target"); normalized.add(target); targetedJavaVersion = Integer.parseInt(target); } } if (parameters && targetedJavaVersion >= 8) { normalized.add("-parameters"); } }
Source:
public void parse(String[] args) throws ParseException { List<String> tcArgs = new ArrayList<>(); boolean found = false; for (String arg : args) { if (arg.equals("--cli")) { found = true; continue; } if (found) { tcArgs.add(arg); } } CommandLineParser cmdLineParser = new PosixParser(); try { fLineParser = cmdLineParser.parse(fOptions, tcArgs.toArray(new String[tcArgs.size()]), false); } catch(ParseException e) { System.out.println(Messages.CliParser_ErrorParsingArguments); System.out.println(e); System.out.println(); printHelpText(); throw e; } }

Target:
public void parse(String[] args) throws ParseException { List<String> tcArgs = new ArrayList<>(); boolean found = false; boolean addNext = false; for (String arg : args) { if (arg.equals(CLI_ARGS_PREFIX)) { found = true; continue; } if (found) { tcArgs.add(arg); } else if (arg.equals("--open")) { System.out.println(Messages.CliParser_WarningCliPrefix); tcArgs.add(arg); addNext = true; } else if (addNext) { tcArgs.add(arg); addNext = false; } } CommandLineParser cmdLineParser = new PosixParser(); try { CommandLine cmdLine = cmdLineParser.parse(fOptions, tcArgs.toArray(new String[tcArgs.size()]), false); if (cmdLine != null) { fLineParser = new CliCommandLine(cmdLine); } } catch(ParseException e) { System.out.println(Messages.CliParser_ErrorParsingArguments); System.out.println(e); System.out.println(); printHelpText(); throw e; } }
Source:
public void testInitialAndAddMore() throws Exception { WatchServiceDirectoryScanner scanner = new WatchServiceDirectoryScanner(folder.getRoot().getAbsolutePath()); scanner.start(); List<File> files = scanner.listFiles(folder.getRoot()); assertEquals(3, files.size()); assertTrue(files.contains(top1)); assertTrue(files.contains(foo1)); assertTrue(files.contains(bar1)); File top2 = this.folder.newFile(); File foo2 = File.createTempFile("foo", ".txt", this.foo); File bar2 = File.createTempFile("bar", ".txt", this.bar); File baz = new File(this.foo, "baz"); baz.mkdir(); File baz1 = File.createTempFile("baz", ".txt", baz); files = scanner.listFiles(folder.getRoot()); int n = 0; List<File> accum = new ArrayList<File>(files); while (n++ < 300 && accum.size() != 4) { Thread.sleep(100); files = scanner.listFiles(folder.getRoot()); accum.addAll(files); } assertEquals(4, accum.size()); assertTrue(accum.contains(top2)); assertTrue(accum.contains(foo2)); assertTrue(accum.contains(bar2)); assertTrue(accum.contains(baz1)); List<File> filesForOverflow = new ArrayList<File>(512); for (int i = 0; i < 512; i++) { filesForOverflow.add(this.folder.newFile("" + i)); } files = scanner.listFiles(folder.getRoot()); assertEquals(512, files.size()); for (File fileForOverFlow : filesForOverflow) { files.contains(fileForOverFlow); } File baz2 = File.createTempFile("baz2", ".txt", baz); files = scanner.listFiles(folder.getRoot()); assertEquals(1, files.size()); assertTrue(files.contains(baz2)); scanner.stop(); }

Target:
public void testInitialAndAddMore() throws Exception { WatchServiceDirectoryScanner scanner = new WatchServiceDirectoryScanner(folder.getRoot().getAbsolutePath()); scanner.start(); List<File> files = scanner.listFiles(folder.getRoot()); assertEquals(3, files.size()); assertTrue(files.contains(top1)); assertTrue(files.contains(foo1)); assertTrue(files.contains(bar1)); File top2 = this.folder.newFile(); File foo2 = File.createTempFile("foo", ".txt", this.foo); File bar2 = File.createTempFile("bar", ".txt", this.bar); File baz = new File(this.foo, "baz"); baz.mkdir(); File baz1 = File.createTempFile("baz", ".txt", baz); files = scanner.listFiles(folder.getRoot()); int n = 0; Set<File> accum = new HashSet<File>(files); while (n++ < 300 && accum.size() != 4) { Thread.sleep(100); files = scanner.listFiles(folder.getRoot()); accum.addAll(files); } assertEquals(4, accum.size()); assertTrue(accum.contains(top2)); assertTrue(accum.contains(foo2)); assertTrue(accum.contains(bar2)); assertTrue(accum.contains(baz1)); List<File> filesForOverflow = new ArrayList<File>(600); for (int i = 0; i < 600; i++) { filesForOverflow.add(this.folder.newFile("" + i)); } n = 0; while (n++ < 300 && accum.size() < 604) { Thread.sleep(100); files = scanner.listFiles(folder.getRoot()); accum.addAll(files); } assertEquals(604, accum.size()); for (File fileForOverFlow : filesForOverflow) { accum.contains(fileForOverFlow); } File baz2 = File.createTempFile("baz2", ".txt", baz); n = 0; while (n++ < 300 && accum.size() < 605) { Thread.sleep(100); files = scanner.listFiles(folder.getRoot()); accum.addAll(files); } assertTrue(accum.contains(baz2)); scanner.stop(); }
Source:
private static void enablePowerMockSupport() { HotSwapAgent.addTransformer(new BendJavassistToMyWillTransformer( new Glob("javassist/*"), JavassistInputStreamInterceptorAdapater.inputStreamAdapterSupplier(JavassistCoverageInterceptor.class))); }

Target:
private static void enablePowerMockSupport() { HotSwapAgent.addTransformer(new BendJavassistToMyWillTransformer( Glob.toGlobPredicate(Collections.singleton("javassist/*")), JavassistInputStreamInterceptorAdapater.inputStreamAdapterSupplier(JavassistCoverageInterceptor.class))); }
Source:
public static Function<Object, DateTime> createObjectTimestampParser( final String format ) { final Function<String, DateTime> stringFun = createTimestampParser(format); final Function<Number, DateTime> numericFun = createNumericTimestampParser(format); return o -> { Preconditions.checkNotNull(o, "null timestamp"); if (o instanceof Number && isNumericFormat(format)) { return numericFun.apply((Number) o); } else { return stringFun.apply(o.toString()); } }; }

Target:
public static Function<Object, DateTime> createObjectTimestampParser( final String format ) { final Function<String, DateTime> stringFun = createTimestampParser(format); final Function<Number, DateTime> numericFun = createNumericTimestampParser(format); final boolean isNumericFormat = isNumericFormat(format); return o -> { Preconditions.checkNotNull(o, "null timestamp"); if (o instanceof Number && isNumericFormat) { return numericFun.apply((Number) o); } else { return stringFun.apply(o.toString()); } }; }
Source:
public void canCreateBlob() throws Exception { final String content = "Content of the blob"; final String body = blob().toString(); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_CREATED, body) ).next(new MkAnswer.Simple(HttpURLConnection.HTTP_OK, body)).start(); final RtBlobs blobs = new RtBlobs( new ApacheRequest(container.home()), repo() ); final Blob blob = blobs.create(content, "utf-8"); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( new Blob.Smart(blob).url(), Matchers.equalTo("http://localhost/1") ); container.stop(); }

Target:
public void canCreateBlob() throws Exception { final String content = "Content of the blob"; final String body = blob().toString(); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_CREATED, body) ).next(new MkAnswer.Simple(HttpURLConnection.HTTP_OK, body)).start(); final RtBlobs blobs = new RtBlobs( new ApacheRequest(container.home()), repo() ); try { final Blob blob = blobs.create(content, "utf-8"); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( new Blob.Smart(blob).url(), Matchers.equalTo("http://localhost/1") ); } finally { container.stop(); } }
Source:
public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { if (!isItemValidForSlot(slot, stack)) { return stack; } ItemStack returnStack = ItemStack.EMPTY; if (stack.getCount() > getSlotLimit(slot)) { returnStack = stack.copy(); returnStack.setCount(stack.getCount() - getSlotLimit(slot)); stack.setCount(getSlotLimit(slot)); } if (!simulate) { setInventorySlotContents(slot, stack); } return returnStack; }

Target:
public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { if (!isItemValidForSlot(slot, stack)) { return stack; } ItemStack slotStack = stack.splitStack(getSlotLimit(slot)); if (!simulate) { setInventorySlotContents(slot, slotStack); } return stack; }
Source:
public ChartDataEntity getEntityById(Long entityId) throws EntityRetrievalException { ChartDataEntity entity = null; String queryStr = "from ChartDataEntity " + "where (chart_data_id = :entityid)"; Query query = entityManager.createQuery(queryStr, ChartDataEntity.class ); query.setParameter("entityid", entityId); List<ChartDataEntity> result = query.getResultList(); if (result.size() > 1){ throw new EntityRetrievalException("Data error. Duplicate certificaiton body id in database."); } else if(result.size() == 1) { entity = result.get(0); } return entity; }

Target:
public ChartDataEntity getEntityById(Long entityId) throws EntityRetrievalException { ChartDataEntity entity = null; String queryStr = "from ChartDataEntity " + "where (chart_data_id = :entityid)"; Query query = entityManager.createQuery(queryStr, ChartDataEntity.class ); query.setParameter("entityid", entityId); List<ChartDataEntity> result = query.getResultList(); if (result.size() > 1){ throw new EntityRetrievalException("Data error. Duplicate certificaton body id in database."); } else if(result.size() == 1) { entity = result.get(0); } return entity; }
Source:
private static <T> ColumnMapper<T> primitiveMapper(ColumnGetter<T> getter) { return (r, i, ctx) -> { T value = getter.get(r, i); if (r.wasNull() && !ctx.getConfig(ColumnMappers.class).getNullPrimitivesToDefaults()) { throw new UnableToProduceResultException("a Java primitive value was attempted to be mapped from a database null value"); } else { return value; } }; }

Target:
private static <T> ColumnMapper<T> primitiveMapper(ColumnGetter<T> getter) { return (r, i, ctx) -> { T value = getter.get(r, i); if (r.wasNull() && !ctx.getConfig(ColumnMappers.class).getCoalesceNullPrimitivesToDefaults()) { String msg = String.format("Database null values are not allowed for Java primitives by the current configuration:" + " could not map column %s (%s)." + " Change your result type to a boxed primitive to resolve.", i, r.getMetaData().getColumnLabel(i)); throw new UnableToProduceResultException(msg); } else { return value; } }; }
Source:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mContext = getActivity().getApplicationContext(); mDataBaseAdapter = new DataBaseAdapter(getActivity()); mDataBaseAdapter.createDatabase(); mDataBaseAdapter.open(); mItemAdapter = new ATMItemListAdapter(mContext, ((MainActivity) getActivity()).getLocationTracker()); setListAdapter(mItemAdapter); getLoaderManager().initLoader(0, null, this); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); }

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mContext = getActivity().getApplicationContext(); mDataBaseAdapter = new DataBaseAdapter(getActivity()); mDataBaseAdapter.createDatabase(); mDataBaseAdapter.open(); mItemAdapter = new ATMItemListAdapter(mContext, ((MainActivity) getActivity()).getLocationTracker()); setListAdapter(mItemAdapter); getLoaderManager().initLoader(0, null, this); }
Source:
public static String getCpu() { return CPU.name().toLowerCase(LOCALE); }

Target:
public static String getCpu() { return CPU.toString(); }
Source:
protected CLIReturnCode execute() throws Exception { boolean errorOccurred = false; final Set<String> hs = new HashSet<>(); hs.addAll(views); ViewOptionHandler voh = new ViewOptionHandler(null, null, null); for(String view_s : hs) { View view = null; try { view = voh.getView(view_s); if (view == null) { throw new IllegalArgumentException("View name is empty"); } view.checkPermission(View.DELETE); ViewGroup group = view.getOwner(); if (!group.canDelete(view)) { throw new IllegalStateException(String.format("%s does not allow to delete '%s' view", group.getDisplayName(), view.getViewName())); } group.deleteView(view); } catch (Exception e) { if(hs.size() == 1) { throw e; } stderr.println(view_s + ": " + e.getMessage()); errorOccurred = true; } } if (errorOccurred) { throw new AbortException(CLI_LISTPARAM_SUMMARY_ERROR_TEXT); } return CLIReturnCodeStandard.OK; }

Target:
protected CLIReturnCode execute() throws Exception { boolean errorOccurred = false; final Set<String> hs = new HashSet<>(); hs.addAll(views); ViewOptionHandler voh = new ViewOptionHandler(null, null, null); for(String view_s : hs) { View view = null; try { view = voh.getView(view_s); if (view == null) { throw new IllegalArgumentException("View name is empty"); } view.checkPermission(View.DELETE); ViewGroup group = view.getOwner(); if (!group.canDelete(view)) { throw new IllegalStateException(String.format("%s does not allow to delete '%s' view", group.getDisplayName(), view.getViewName())); } group.deleteView(view); } catch (Exception e) { if(hs.size() == 1) { throw e; } stderr.println(view_s + ": " + e.getMessage()); errorOccurred = true; } } if (errorOccurred) { throw new AbortException(CLI_LISTPARAM_SUMMARY_ERROR_TEXT); } return StandardCLIReturnCode.OK; }
Source:
private void initUnregisteredVM() { VM vmFromConfiguration = null; OvfHelper ovfHelper = new OvfHelper(); ovfEntityData = getUnregisteredOVFDataDao().getByEntityIdAndStorageDomain(getParameters().getContainerId(), getParameters().getStorageDomainId()); if (ovfEntityData != null) { try { vmFromConfiguration = ovfHelper.readVmFromOvf(ovfEntityData.getOvfData()); } catch (OvfReaderException e) { log.errorFormat("failed to parse a given ovf configuration: \n" + ovfEntityData.getOvfData(), e); } vmFromConfiguration.setVdsGroupId(getParameters().getVdsGroupId()); getParameters().setVm(vmFromConfiguration); getParameters().setDestDomainId(ovfEntityData.getStorageDomainId()); getParameters().setSourceDomainId(ovfEntityData.getStorageDomainId()); } }

Target:
private void initUnregisteredVM() { VM vmFromConfiguration = null; OvfHelper ovfHelper = new OvfHelper(); ovfEntityData = getUnregisteredOVFDataDao().getByEntityIdAndStorageDomain(getParameters().getContainerId(), getParameters().getStorageDomainId()); if (ovfEntityData != null) { try { vmFromConfiguration = ovfHelper.readVmFromOvf(ovfEntityData.getOvfData()); vmFromConfiguration.setVdsGroupId(getParameters().getVdsGroupId()); getParameters().setVm(vmFromConfiguration); getParameters().setDestDomainId(ovfEntityData.getStorageDomainId()); getParameters().setSourceDomainId(ovfEntityData.getStorageDomainId()); } catch (OvfReaderException e) { log.errorFormat("failed to parse a given ovf configuration: \n" + ovfEntityData.getOvfData(), e); } } }
Source:
public static IndexType fromValue(final Object value) { for (IndexType indexType : values()) { if (indexType.type.equals(value) || indexType.name().equals(value)) { return indexType; } } throw new IllegalArgumentException("No enum value found for " + value); }

Target:
public static IndexType fromValue(final Object value) { for (IndexType indexType : values()) { if (indexType.type.equals(value)) { return indexType; } } throw new IllegalArgumentException("No enum value found for " + value); }
Source:
public boolean logTransactionMergeFailure() { return this.logTransactionMergeFailure; }

Target:
public int logTransactionMergeFailure() { return this.logTransactionMergeFailure; }
Source:
public void visitNode(Tree tree) { if (tree.is(Kind.SCRIPT)) { check(ControlFlowGraph.build((ScriptTree) tree)); } else if (tree.is(Kind.METHOD, Kind.GENERATOR_METHOD)) { MethodDeclarationTree methodTree = (MethodDeclarationTree) tree; check(ControlFlowGraph.build(methodTree.body())); } else { FunctionTree functionTree = (FunctionTree) tree; if (functionTree.body().is(Kind.BLOCK)) { check(ControlFlowGraph.build((BlockTree) functionTree.body())); } } }

Target:
public void visitNode(Tree tree) { if (tree.is(Kind.SCRIPT)) { check(ControlFlowGraph.build((ScriptTree) tree)); } else { FunctionTree functionTree = (FunctionTree) tree; if (functionTree.body().is(Kind.BLOCK)) { check(ControlFlowGraph.build((BlockTree) functionTree.body())); } } }
Source:
public User createAccount(String userName, String password) throws IOException { User user = User.getById(userName, true); if (password.startsWith(JBCRYPT_HEADER)) { user.addProperty(Details.fromHashedPassword(password)); } else { user.addProperty(Details.fromPlainPassword(password)); } return user; }

Target:
public User createAccount(String userName, String password) throws IOException { User user = User.getById(userName, true); user.addProperty(Details.fromPlainPassword(password)); return user; }
Source:
public String toString() { return singleBenchmarkResult.toString() + "_" + problemStatisticType.toString(); }

Target:
public String toString() { return singleBenchmarkResult + "_" + problemStatisticType; }
Source:
public SimpleDialogPanel() { infoIconStyle = RESOURCES.iconStyle(); infoIconStyle.ensureInjected(); setWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); infoAnchor.addStyleName(infoIconStyle.infoIconColor()); addAttachHandler(event -> { setDraggable(isAttached()); }); }

Target:
public SimpleDialogPanel() { infoIconStyle = RESOURCES.iconStyle(); infoIconStyle.ensureInjected(); setWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); infoAnchor.addStyleName(infoIconStyle.infoIconColor()); addAttachHandler(event -> setDraggable(isAttached())); }
Source:
public int getColumnCount() { return columnNames.size(); }

Target:
public int getColumnCount() { return results[0].length; }
Source:
public String toString() { return String.format("%s, deviceList=%s", super.toString(), getDeviceList()); }

Target:
public String toString() { return String.format("%s, deviceList=%s, force=%b", super.toString(), getDeviceList(), isForce()); }
Source:
<T> RFuture<T> tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) { internalLockLeaseTime = unit.toMillis(leaseTime); return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command, "redis.call('hincrby', KEYS[1], ARGV[2], 1); " + "redis.call('pexpire', KEYS[1], ARGV[1]); " + "return redis.call('pttl', KEYS[1]);", Collections.<Object>singletonList(getName()), internalLockLeaseTime, getLockName(threadId)); }

Target:
<T> RFuture<T> tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) { internalLockLeaseTime = unit.toMillis(leaseTime); return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command, "redis.call('hincrby', KEYS[1], ARGV[2], 1); " + "redis.call('pexpire', KEYS[1], ARGV[1]); " + "return nil; " + "return redis.call('pttl', KEYS[1]);", Collections.<Object>singletonList(getName()), internalLockLeaseTime, getLockName(threadId)); }