auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private MimeMessage makeMessageWithSubjectAndText(String subjectKeyInPropertiesFile, String textKeyInPropertiesFile, String ... textParameters) { MimeMessage message = new MimeMessage(session); String subject = loadedProperties.getProperty(subjectKeyInPropertiesFile, ""); StringBuffer text = new StringBuffer(); text.append(loadedProperties.getProperty("defaultBegin", "")); String mainContentFormat = loadedProperties.getProperty(textKeyInPropertiesFile, ""); text.append(String.format(mainContentFormat, (Object[]) textParameters)); text.append(loadedProperties.getProperty("defaultEnd", "")); if (!supportMailAddress.equals("")) { text.append(loadedProperties.getProperty("unsubscribeNoticeBefore", "")); text.append(" "); text.append(supportMailAddress); text.append(loadedProperties.getProperty("unsubscribeNoticeAfter", "")); } try { message.setSubject(subject); message.setText(text.toString()); } catch (MessagingException mex) { log.error(mex.getMessage()); } return message; }

Target:
private MimeMessage makeMessageWithSubjectAndText(String subjectKeyInPropertiesFile, String textKeyInPropertiesFile, String ... textParameters) { MimeMessage message = new MimeMessage(session); String subject = loadedProperties.getProperty(subjectKeyInPropertiesFile, ""); StringBuilder text = new StringBuilder(); text.append(loadedProperties.getProperty("defaultBegin", "")); String mainContentFormat = loadedProperties.getProperty(textKeyInPropertiesFile, ""); try { String formattedContent = String.format(mainContentFormat, (Object[]) textParameters); text.append(formattedContent); } catch (IllegalFormatException e) { log.error(String.format("Could not format notification email content for keys %s and %s", subjectKeyInPropertiesFile, textKeyInPropertiesFile), e); text.append(mainContentFormat); } text.append(loadedProperties.getProperty("defaultEnd", "")); if (!supportMailAddress.equals("")) { text.append(loadedProperties.getProperty("unsubscribeNoticeBefore", "")); text.append(" "); text.append(supportMailAddress); text.append(loadedProperties.getProperty("unsubscribeNoticeAfter", "")); } try { message.setSubject(subject); message.setText(text.toString()); } catch (MessagingException mex) { log.error(mex.getMessage()); } return message; }
Source:
private void setClanTag(String newValue) { if (StringUtils.isEmpty(newValue)) { clanMenu.setVisible(false); } else { Runnable setMenuItems = new Runnable() { @Override public void run() { clan = clanService.getClanByTag(player.getClan()); if (clan != null) { MenuItem page = new MenuItem(i18n.get("clan.visitPage")); page.setOnAction(event -> { platformService.showDocument(baseClanWebsite + clan.getClanId()); }); if (playerService.isOnline(clan.getLeaderName())) { MenuItem toLeader = new MenuItem(i18n.get("clan.toLeader")); toLeader.setOnAction(event -> { onClanTagClicked(); }); clanMenu.getItems().addAll(FXCollections.observableArrayList(toLeader, page)); } else { clanMenu.getItems().addAll(FXCollections.observableArrayList(page)); } } } }; executorService.submit(setMenuItems); clanMenu.setText(String.format(CLAN_TAG_FORMAT, newValue)); clanMenu.setVisible(true); } }

Target:
private void setClanTag(String newValue) { if (StringUtils.isEmpty(newValue)) { clanMenu.setVisible(false); return; } Optional.ofNullable(usernameLabel.getTooltip()).ifPresent(tooltip -> usernameLabel.setTooltip(null)); Optional.ofNullable(clanMenu.getTooltip()).ifPresent(tooltip -> clanMenu.setTooltip(null)); clanMenu.setText(String.format(CLAN_TAG_FORMAT, newValue)); clanMenu.setVisible(true); }
Source:
public static QueryType sqlQueryType(String sqlQuery) { String query = sqlQuery.substring(0, sqlQuery.indexOf(" ")).toUpperCase(); ; switch (query) { case "UPDATE": sqlQueryType = QueryType.UPDATE; break; case "SELECT": sqlQueryType = QueryType.SELECT; break; case "DELETE": sqlQueryType = QueryType.DELETE; break; case "INSERT": sqlQueryType = QueryType.INSERT; break; } return sqlQueryType; }

Target:
public static QueryType sqlQueryType(String sqlQuery) { String query = sqlQuery.substring(0, sqlQuery.indexOf(" ")).toUpperCase(); switch (query) { case "UPDATE": sqlQueryType = QueryType.UPDATE; break; case "SELECT": sqlQueryType = QueryType.SELECT; break; case "DELETE": sqlQueryType = QueryType.DELETE; break; case "INSERT": sqlQueryType = QueryType.INSERT; break; } return sqlQueryType; }
Source:
public Set<Issue> getAllIssues() { final Set<Issue> issues = new HashSet<>(); for (final RuleInspector inspector : all()) { for (Check check : inspector.getChecks()) { if (check.hasIssues()) { issues.addAll(check.getIssues()); } } } for (final Check generalCheck : generalChecks) { if (generalCheck.hasIssues()) { issues.addAll(generalCheck.getIssues()); } } return issues; }

Target:
public Set<Issue> getAllIssues() { final Set<Issue> issues = new HashSet<>(); all().stream() .flatMap(inspector -> inspector.getChecks().stream()) .filter(Check::hasIssues) .map(Check::getIssues) .forEach(issues::addAll); for (final Check generalCheck : generalChecks) { if (generalCheck.hasIssues()) { issues.addAll(generalCheck.getIssues()); } } return issues; }
Source:
public void initialize( IndexDescriptor descriptor, IndexSamplingConfig samplingConfig ) { assert state == State.NONE; layout = layout( descriptor ); treeKey = layout.newKey(); treeValue = layout.newValue(); schemaIndex = new NativeSchemaIndex<>( pageCache, fs, indexFile, layout, monitor, descriptor, indexId ); if ( uniqueSampler( descriptor ) ) { uniqueSampler = new UniqueIndexSampler(); } else { generalSampler = new DefaultNonUniqueIndexSampler( samplingConfig.sampleSizeLimit() ); } state = State.INIT; }

Target:
private void initialize( IndexDescriptor descriptor, IndexSamplingConfig samplingConfig ) { assert state == State.NONE; layout = layout( descriptor ); treeKey = layout.newKey(); treeValue = layout.newValue(); schemaIndex = new NativeSchemaIndex<>( pageCache, fs, indexFile, layout, monitor, descriptor, indexId ); if ( isUnique( descriptor ) ) { uniqueSampler = new UniqueIndexSampler(); } else { generalSampler = new DefaultNonUniqueIndexSampler( samplingConfig.sampleSizeLimit() ); } state = State.INIT; }
Source:
private ConfigKey getKeystorePassKey() throws SQLException { String keyStorePassVersion = appConfig.getString(KEYSTORE_PASS_VERSION); if (keyStorePassVersion == null) { keyStorePassVersion = DEFAULT_KEYSTORE_PASS_VERSION; } ConfigKey keyStorePassKey = ConfigKeyFactory.getInstance().generateBlankConfigKey("keystorePass", "String"); keyStorePassKey.setVersion(keyStorePassVersion); return getConfigDAO().getKey(keyStorePassKey); }

Target:
private ConfigKey getKeystorePassKey() throws SQLException { String keyStorePassVersion = appConfig.getString(KEYSTORE_PASS_VERSION); if (keyStorePassVersion == null) { keyStorePassVersion = DEFAULT_KEYSTORE_PASS_VERSION; } ConfigKey keyStorePassKey = ConfigKeyFactory.getInstance().generateBlankConfigKey("keystorePass", "String"); keyStorePassKey.setVersion(keyStorePassVersion); return getConfigKey(keyStorePassKey); }
Source:
@Override public void sendRequest(Request request) { if (null == request.getType()) request.setType(Type.CON); top.sendRequest(request); request.setAcknowledged(true); }

Target:
@Override public void sendRequest(Request request) { if (null == request.getType()) { request.setType(Type.CON); } top.sendRequest(request); request.setAcknowledged(true); }
Source:
protected boolean mustCheckName(DetailAST ast) { boolean checkName = true; if (ignoreOverridden && isOverriddenMethod(ast) || ast.getParent().getType() == TokenTypes.LITERAL_CATCH || CheckUtil.isReceiverParameter(ast) || !matchAccessModifiers(getAccessModifier(ast)) || ast.getParent().getType() == TokenTypes.LAMBDA) { checkName = false; } return checkName; }

Target:
protected boolean mustCheckName(DetailAST ast) { boolean checkName = true; if (ignoreOverridden && isOverriddenMethod(ast) || ast.getParent().getType() == TokenTypes.LITERAL_CATCH || ast.getParent().getParent().getType() == TokenTypes.LAMBDA || CheckUtil.isReceiverParameter(ast) || !matchAccessModifiers(getAccessModifier(ast))) { checkName = false; } return checkName; }
Source:
public IterationResult advance0() { currentRows = null; while (recordIterator.tryAdvance()) { HeapRow row = prepareRow(recordIterator.getKey(), recordIterator.getValue()); if (row != null) { if (currentRows == null) { currentRows = new ArrayList<>(BATCH_SIZE); } currentRows.add(row); if (currentRows.size() == BATCH_SIZE) { break; } } } if (!map.getMapServiceContext().getService().validateMigrationStamp(migrationStamp)) { throw QueryException.error(SqlErrorCode.PARTITION_MIGRATED, "Map scan failed due to concurrent partition migration " + "(result consistency cannot be guaranteed)"); } if (map.isDestoyed()) { throw QueryException.error(SqlErrorCode.MAP_DESTROYED, "IMap has been destroyed concurrently: " + mapName); } boolean done = !recordIterator.hasNext(); return done ? IterationResult.FETCHED_DONE : IterationResult.FETCHED; }

Target:
public IterationResult advance0() { currentRows = null; while (recordIterator.tryAdvance()) { HeapRow row = prepareRow(recordIterator.getKey(), recordIterator.getValue()); if (row != null) { if (currentRows == null) { currentRows = new ArrayList<>(BATCH_SIZE); } currentRows.add(row); if (currentRows.size() == BATCH_SIZE) { break; } } } boolean done = !recordIterator.hasNext(); if (!map.getMapServiceContext().getService().validateMigrationStamp(migrationStamp)) { throw QueryException.error(SqlErrorCode.PARTITION_MIGRATED, "Map scan failed due to concurrent partition migration " + "(result consistency cannot be guaranteed)"); } if (map.isDestroyed()) { throw QueryException.error(SqlErrorCode.MAP_DESTROYED, "IMap has been destroyed concurrently: " + mapName); } return done ? IterationResult.FETCHED_DONE : IterationResult.FETCHED; }
Source:
private void printSystemInformation(StringBuilder stringBuilder) { try { long totalMemory = Runtime.getRuntime().totalMemory() / 1024; long freeMemory = Runtime.getRuntime().freeMemory() / 1024; long maxMemory = Runtime.getRuntime().maxMemory() / 1024; String used_Memory = totalMemory - freeMemory + " KB"; String available_Memory = (maxMemory - (totalMemory - freeMemory)) + " KB"; OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); String processCpuLoad = Double.toString(mbean.getProcessCpuLoad()); String systemCpuLoad = Double.toString(mbean.getSystemCpuLoad()); stringBuilder.append("System State Information -------").append(System.lineSeparator()); stringBuilder.append("Used Memory : " + used_Memory).append(System.lineSeparator()); stringBuilder.append("Available Memory : " + available_Memory).append(System.lineSeparator()); stringBuilder.append("CPU Process Load : " + processCpuLoad).append(System.lineSeparator()); stringBuilder.append("CPU System Load : " + systemCpuLoad).append(System.lineSeparator()); } catch (Exception e) { } }

Target:
private void printSystemInformation(StringBuilder stringBuilder) { try { long totalMemory = Runtime.getRuntime().totalMemory() / 1024; long freeMemory = Runtime.getRuntime().freeMemory() / 1024; long maxMemory = Runtime.getRuntime().maxMemory() / 1024; String usedMemory = totalMemory - freeMemory + " KB"; String availableMemory = (maxMemory - (totalMemory - freeMemory)) + " KB"; String processCpuLoad = Double.toString(this.mbean.getProcessCpuLoad()); String systemCpuLoad = Double.toString(this.mbean.getSystemCpuLoad()); stringBuilder.append("System State Information -------").append(System.lineSeparator()); stringBuilder.append("Used Memory : " + usedMemory).append(System.lineSeparator()); stringBuilder.append("Available Memory : " + availableMemory).append(System.lineSeparator()); stringBuilder.append("CPU Process Load : " + processCpuLoad).append(System.lineSeparator()); stringBuilder.append("CPU System Load : " + systemCpuLoad).append(System.lineSeparator()); } catch (Exception e) { } }
Source:
private static boolean meetConditions(List<ExpressionTree> operandList) { int operandsNum = operandList.size(); int literalsNum = stringLiteralsNumber(operandList); if (operandsNum > 2 && literalsNum > 0) { int shortLiteralsNum = smallLiteralsNumber(operandList); boolean isOneLiteralTreeOperandsCase = operandsNum == 3 && literalsNum == 1; boolean atLeastHalfLongLiterals = shortLiteralsNum <= literalsNum / 2.; boolean notTooManyNonLiterals = literalsNum - (operandsNum - literalsNum) >= -1; return !isOneLiteralTreeOperandsCase && atLeastHalfLongLiterals && notTooManyNonLiterals; } return false; }

Target:
private static boolean meetConditions(List<ExpressionTree> operandList) { int operandsNum = operandList.size(); int literalsNum = stringLiteralsNumber(operandList); if (operandsNum > 2 && literalsNum > 0) { int shortLiteralsNum = smallLiteralsNumber(operandList); boolean isOneLiteralThreeOperandsCase = operandsNum == 3 && literalsNum == 1; boolean atLeastHalfLongLiterals = shortLiteralsNum <= literalsNum / 2.; boolean notTooManyNonLiterals = literalsNum - (operandsNum - literalsNum) >= -1; return !isOneLiteralThreeOperandsCase && atLeastHalfLongLiterals && notTooManyNonLiterals; } return false; }
Source:
public void testInvokeOccurBusinessexception01() throws Throwable { BusinessException occurException = new BusinessException("testing businessexception"); when(mockMethodInvocation.proceed()).thenThrow(occurException); try { testTarget.invoke(mockMethodInvocation); fail("don't occur BusinessException."); } catch (BusinessException e) { assertThat(e, is(occurException)); verify(mockExceptionLogger, times(1)).warn(occurException); verify(mockExceptionLogger, times(1)).warn((Exception) anyObject()); } }

Target:
public void testInvokeOccurBusinessexception01() throws Throwable { BusinessException occurException = new BusinessException("testing businessexception"); when(mockMethodInvocation.proceed()).thenThrow(occurException); try { testTarget.invoke(mockMethodInvocation); fail("didn't occured BusinessException."); } catch (BusinessException e) { assertThat(e, is(occurException)); verify(mockExceptionLogger, times(1)).warn(occurException); verify(mockExceptionLogger, times(1)).warn((Exception) anyObject()); } }
Source:
public void addCallsite(String eventName, String funcName, long ip, String fileName, long lineNumber) { final CTFCallsite cs = new CTFCallsite(eventName, funcName, ip, fileName, lineNumber); LinkedList<CTFCallsite> csl = callsitesByName.get(eventName); if (csl == null) { csl = new LinkedList<CTFCallsite>(); callsitesByName.put(eventName, csl); } ListIterator<CTFCallsite> iter = csl.listIterator(); int index = 0; for (; index < csl.size(); index++) { if (iter.next().compareTo(cs) < 0) { break; } } csl.add(cs); callsitesByIP.add(cs); }

Target:
public void addCallsite(String eventName, String funcName, long ip, String fileName, long lineNumber) { final CTFCallsite cs = new CTFCallsite(eventName, funcName, ip, fileName, lineNumber); LinkedList<CTFCallsite> csl = callsitesByName.get(eventName); if (csl == null) { csl = new LinkedList<CTFCallsite>(); callsitesByName.put(eventName, csl); } ListIterator<CTFCallsite> iter = csl.listIterator(); int index = 0; for (; index < csl.size(); index++) { if (iter.next().compareTo(cs) < 0) { break; } } csl.add(index, cs); callsitesByIP.add(cs); }
Source:
public void testUploadPackFactory() throws Exception { ObjectId master = remote.branch("master").commit().create(); final AtomicInteger rejected = new AtomicInteger(); TestProtocol<User> proto = registerProto(new UploadPackFactory<User>() { @Override public UploadPack create(User req, Repository db) throws ServiceNotAuthorizedException { if (!"user2".equals(req.name)) { rejected.incrementAndGet(); throw new ServiceNotAuthorizedException(); } return new UploadPack(db); } }, new DefaultReceive()); URIish user1Uri = proto.register(new User("user1"), remote.getRepository()); URIish user2Uri = proto.register(new User("user2"), remote.getRepository()); try (Git git = new Git(local.getRepository())) { try { git.fetch() .setRemote(user1Uri.toString()) .setRefSpecs(MASTER) .call(); fail("accepted invalid remote"); } catch (InvalidRemoteException expected) { } assertEquals(1, rejected.get()); assertNull(local.getRepository().exactRef("refs/heads/master")); git.fetch() .setRemote(user2Uri.toString()) .setRefSpecs(MASTER) .call(); assertEquals(1, rejected.get()); assertEquals(master, local.getRepository().exactRef("refs/heads/master").getObjectId()); } }

Target:
public void testUploadPackFactory() throws Exception { ObjectId master = remote.branch("master").commit().create(); final AtomicInteger rejected = new AtomicInteger(); TestProtocol<User> proto = registerProto(new UploadPackFactory<User>() { @Override public UploadPack create(User req, Repository db) throws ServiceNotAuthorizedException { if (!"user2".equals(req.name)) { rejected.incrementAndGet(); throw new ServiceNotAuthorizedException(); } return new UploadPack(db); } }, new DefaultReceive()); URIish user1Uri = proto.register(new User("user1"), remote.getRepository()); URIish user2Uri = proto.register(new User("user2"), remote.getRepository()); try (Git git = new Git(local.getRepository())) { try { git.fetch() .setRemote(user1Uri.toString()) .setRefSpecs(MASTER) .call(); fail("accepted not permitted fetch"); } catch (InvalidRemoteException expected) { } assertEquals(1, rejected.get()); assertNull(local.getRepository().exactRef("refs/heads/master")); git.fetch() .setRemote(user2Uri.toString()) .setRefSpecs(MASTER) .call(); assertEquals(1, rejected.get()); assertEquals(master, local.getRepository().exactRef("refs/heads/master").getObjectId()); } }
Source:
private static void checkNotCancelledAfter( CompletableFuture<?> cancellationFuture, long milli) throws ExecutionException, InterruptedException { mainThreadExecutor.schedule(() -> {}, milli, TimeUnit.MILLISECONDS).get(); try { cancellationFuture.get(milli, TimeUnit.MILLISECONDS); fail("The future must not have been cancelled"); } catch (TimeoutException e) { assertThat(cancellationFuture.isDone(), is(false)); } }

Target:
private static void checkNotCancelledAfter( CompletableFuture<?> cancellationFuture, long milli) throws ExecutionException, InterruptedException { mainThreadExecutor.schedule(() -> {}, milli, TimeUnit.MILLISECONDS).get(); try { assertThat(cancellationFuture.isDone(), is(false)); cancellationFuture.get(milli, TimeUnit.MILLISECONDS); fail("The future must not have been cancelled"); } catch (TimeoutException e) { assertThat(cancellationFuture.isDone(), is(false)); } }
Source:
private void collectPhysicalFieldsTypes(List<SqlNode> derivedColumns) { for (SqlNode derivedColumn : derivedColumns) { if (derivedColumn instanceof SqlRegularColumn) { SqlRegularColumn regularColumn = (SqlRegularColumn) derivedColumn; String name = regularColumn.getName().getSimple(); if (columns.containsKey(name)) { throw new ValidationException(String.format( "A column named '%s' already exists in the base table.", name)); } SqlDataTypeSpec type = regularColumn.getType(); boolean nullable = type.getNullable() == null ? true : type.getNullable(); RelDataType relType = type.deriveType(sqlValidator, nullable); nonComputedFieldNamesToTypes.put(name, relType); } else if (derivedColumn instanceof SqlMetadataColumn) { SqlMetadataColumn metadataColumn = (SqlMetadataColumn) derivedColumn; String name = metadataColumn.getName().getSimple(); if (columns.containsKey(name)) { throw new ValidationException(String.format( "A column named '%s' already exists in the base table.", name)); } RelDataType relType = metadataColumn.getType() .deriveType(sqlValidator, metadataColumn.getType().getNullable()); nonComputedFieldNamesToTypes.put(name, relType); } } }

Target:
private void collectPhysicalFieldsTypes(List<SqlNode> derivedColumns) { for (SqlNode derivedColumn : derivedColumns) { if (derivedColumn instanceof SqlRegularColumn) { SqlRegularColumn regularColumn = (SqlRegularColumn) derivedColumn; String name = regularColumn.getName().getSimple(); if (columns.containsKey(name)) { throw new ValidationException(String.format( "A column named '%s' already exists in the base table.", name)); } SqlDataTypeSpec type = regularColumn.getType(); boolean nullable = type.getNullable() == null ? true : type.getNullable(); RelDataType relType = type.deriveType(sqlValidator, nullable); physicalFieldNamesToTypes.put(name, relType); } } }
Source:
public boolean answerSplitNodeQuestion(String nodeName) throws UnsupportedOperationException { if (nodeName.equals(PurapWorkflowConstants.REQUIRES_IMAGE_ATTACHMENT)) { return requiresAccountsPayableReviewRouting(); } if (nodeName.equals(PurapWorkflowConstants.PURCHASE_WAS_RECEIVED)) { return shouldWaitForReceiving(); } if (nodeName.equals(PurapWorkflowConstants.VENDOR_IS_EMPLOYEE_OR_NONRESIDENT)) { return isVendorEmployeeOrNonresident(); } if (nodeName.equals(CUPurapWorkflowConstants.TREASURY_MANAGER)) { return isWireOrForeignDraft(); } if (nodeName.equals(PurapWorkflowConstants.IS_DOCUMENT_AUTO_APPROVED)) { return isAutoApprovedIndicator(); } throw new UnsupportedOperationException("Cannot answer split question for this node you call \"" + nodeName + "\""); }

Target:
public boolean answerSplitNodeQuestion(String nodeName) throws UnsupportedOperationException { if (nodeName.equals(PurapWorkflowConstants.REQUIRES_IMAGE_ATTACHMENT)) { return requiresAccountsPayableReviewRouting(); } if (nodeName.equals(PurapWorkflowConstants.PURCHASE_WAS_RECEIVED)) { return shouldWaitForReceiving(); } if (nodeName.equals(PurapWorkflowConstants.VENDOR_IS_EMPLOYEE_OR_NONRESIDENT) || "VendorIsEmployeeOrNonResidentAlien".equals(nodeName)) { return isVendorEmployeeOrNonresident(); } if (nodeName.equals(CUPurapWorkflowConstants.TREASURY_MANAGER)) { return isWireOrForeignDraft(); } if (nodeName.equals(PurapWorkflowConstants.IS_DOCUMENT_AUTO_APPROVED)) { return isAutoApprovedIndicator(); } throw new UnsupportedOperationException("Cannot answer split question for this node you call \"" + nodeName + "\""); }
Source:
public void validateTrialInstanceValue(final List<MeasurementVariable> conditions, final Map<String, List<Message>> errorMessages) { for (final MeasurementVariable varCondition : conditions) { if (varCondition.getTermId() == TermId.TRIAL_INSTANCE_FACTOR.getId()) { final Optional<Message> message = Util.validateVariableValues(varCondition, varCondition.getValue()); if (message.isPresent()) { if (errorMessages.containsKey(Constants.INVALID_TRIAL)) { errorMessages.get(Constants.INVALID_TRIAL).add(message.get()); } else { errorMessages.put(Constants.INVALID_TRIAL, Arrays.asList(message.get())); } } } } }

Target:
public void validateTrialInstanceValue(final List<MeasurementVariable> conditions, final Map<String, List<Message>> errorMessages) { for (final MeasurementVariable varCondition : conditions) { if (varCondition.getTermId() == TermId.TRIAL_INSTANCE_FACTOR.getId()) { final Optional<Message> message = Util.validateVariableValues(varCondition, varCondition.getValue()); if (message.isPresent()) { errorMessages.putIfAbsent(Constants.INVALID_TRIAL, new ArrayList<>()); errorMessages.get(Constants.INVALID_TRIAL).add(message.get()); } } } }
Source:
public J strip() { String[] methods = getFieldNames(); String[] jsonMethods = p.getFieldNames(); System.out.println(methods); return (J)this; }

Target:
public J strip() { List<String> names = Arrays.asList(getFieldNames()); for (String jsonName : p.getFieldNames()) { if (!names.contains(jsonName)) { p.<JsCache>cast().delete(jsonName); } } return (J)this; }
Source:
@Override public synchronized boolean cancel( final boolean mayInterruptIfRunning ) { return canceled.compareAndSet( false, true ); }

Target:
@Override public boolean cancel( final boolean mayInterruptIfRunning ) { return canceled.compareAndSet( false, true ); }
Source:
public SecurityConfigurationMapping() { map = Maps.newHashMap(); }

Target:
public SecurityConfigurationMapping() { table = HashBasedTable.create(); }
Source:
public void printHelp() { Builder<String> builder = Stream.builder(); map.forEach((k,v) -> builder.accept(k + "\t" + v.getRight())); System.out.println(" avaliable values:"); builder.build().forEach(s -> {System.out.println(" " + s);} ); }

Target:
public void printHelp() { System.out.println(" available values:"); map.entrySet().stream() .map((e) -> MessageFormat.format(" %s\t%s", e.getKey(), e.getValue().getRight())) .forEach(System.out::println); }
Source:
public void testCreateInvalidConfigAeadWithAuth() throws Exception { IpSecConfig ipSecConfig = buildBasicIpSecConfig(); for (int direction : directions) { ipSecConfig.setAuthentication(direction, authAlgo); try { ipSecConfig.setAuthenticatedEncryption(direction, aeadAlgo); } catch (IllegalArgumentException expected) { } } try { mIpSecService.createTransportModeTransform(ipSecConfig, new Binder()); fail( "IpSecService should have thrown an error on authentication being" + " enabled with authenticated encryption"); } catch (IllegalArgumentException expected) { } }

Target:
public void testCreateInvalidConfigAeadWithAuth() throws Exception { IpSecConfig ipSecConfig = new IpSecConfig(); addDefaultSpisAndRemoteAddrToIpSecConfig(ipSecConfig); for (int direction : DIRECTIONS) { ipSecConfig.setAuthentication(direction, AUTH_ALGO); try { ipSecConfig.setAuthenticatedEncryption(direction, AEAD_ALGO); } catch (IllegalArgumentException expected) { } } try { mIpSecService.createTransportModeTransform(ipSecConfig, new Binder()); fail( "IpSecService should have thrown an error on authentication being" + " enabled with authenticated encryption"); } catch (IllegalArgumentException expected) { } }
Source:
private void pullItems(GlowBlock block, TEHopper hopper) { GlowBlock source = block.getRelative(BlockFace.UP); if (source.getType() == null || source.getType() == Material.AIR) { GlowItem item = getFirstDroppedItem(source.getLocation()); if (item == null) { return; } ItemStack stack = item.getItemStack(); HashMap<Integer, ItemStack> add = hopper.getInventory().addItem(stack); if (add.size() > 0) { item.setItemStack(add.get(0)); } else { item.remove(); } } else if (source.getTileEntity() != null && source.getTileEntity() instanceof TEContainer) { TEContainer sourceContainer = (TEContainer) source.getTileEntity(); if (sourceContainer.getInventory() == null || sourceContainer.getInventory().getContents().length == 0) { return; } ItemStack item = getFirstItem(sourceContainer); if (item == null) { return; } ItemStack clone = item.clone(); clone.setAmount(1); if (hopper.getInventory().addItem(clone).size() > 0) { return; } if (item.getAmount() - 1 == 0) { sourceContainer.getInventory().remove(item); } else { item.setAmount(item.getAmount() - 1); } } }

Target:
private void pullItems(GlowBlock block, TEHopper hopper) { GlowBlock source = block.getRelative(BlockFace.UP); MaterialData data = source.getState().getData(); if (!source.getType().isSolid() || (data instanceof Step && !((Step) data).isInverted()) || (data instanceof WoodenStep && !((WoodenStep) data).isInverted()) || (data instanceof Sign) || (data instanceof Rails)) { GlowItem item = getFirstDroppedItem(source.getLocation()); if (item == null) { return; } ItemStack stack = item.getItemStack(); HashMap<Integer, ItemStack> add = hopper.getInventory().addItem(stack); if (add.size() > 0) { item.setItemStack(add.get(0)); } else { item.remove(); } } else if (source.getTileEntity() != null && source.getTileEntity() instanceof TEContainer) { TEContainer sourceContainer = (TEContainer) source.getTileEntity(); if (sourceContainer.getInventory() == null || sourceContainer.getInventory().getContents().length == 0) { return; } ItemStack item = getFirstItem(sourceContainer); if (item == null) { return; } ItemStack clone = item.clone(); clone.setAmount(1); if (hopper.getInventory().addItem(clone).size() > 0) { return; } if (item.getAmount() - 1 == 0) { sourceContainer.getInventory().remove(item); } else { item.setAmount(item.getAmount() - 1); } } }
Source:
public EventProducer(TransportProvider transportProvider, CheckpointProvider checkpointProvider, Properties config, boolean customCheckpointing, Consumer<EventProducer> onUnrecoverableError, int generation) { Validate.notNull(transportProvider, "null transport provider"); Validate.notNull(checkpointProvider, "null checkpoint provider"); Validate.notNull(config, "null config"); _checkpointRWLock = new ReentrantReadWriteLock( true); _transportProvider = transportProvider; _checkpointProvider = checkpointProvider; _checkpointPolicy = customCheckpointing ? CheckpointPolicy.CUSTOM : CheckpointPolicy.DATASTREAM; _safeCheckpoints = new ConcurrentHashMap<>(); _onUnrecoverableError = onUnrecoverableError; _generation = generation; _producerId = PRODUCER_ID_SEED.getAndIncrement(); _logger = LoggerFactory.getLogger(String.format("%s:%s", MODULE, _producerId)); _checkpointHandler = new CheckpointHandler(config); _availabilityThresholdSlaMs = Integer.parseInt(config.getProperty(AVAILABILITY_THRESHOLD_SLA_MS, DEFAULT_AVAILABILITY_THRESHOLD_SLA_MS)); _logger.info( String.format("Created event producer with customCheckpointing=%s, sendCallback=%s", customCheckpointing, onUnrecoverableError != null)); _dynamicMetricsManager = DynamicMetricsManager.getInstance(); }

Target:
public EventProducer(TransportProvider transportProvider, CheckpointProvider checkpointProvider, Properties config, boolean customCheckpointing, Consumer<EventProducer> onUnrecoverableError, int generation) { Validate.notNull(transportProvider, "null transport provider"); Validate.notNull(checkpointProvider, "null checkpoint provider"); Validate.notNull(config, "null config"); _checkpointRWLock = new ReentrantReadWriteLock( true); _transportProvider = transportProvider; _checkpointProvider = checkpointProvider; _checkpointPolicy = customCheckpointing ? CheckpointPolicy.CUSTOM : CheckpointPolicy.DATASTREAM; _safeCheckpoints = new ConcurrentHashMap<>(); _onUnrecoverableError = onUnrecoverableError; _generation = generation; _producerId = PRODUCER_ID_SEED.getAndIncrement(); _logger = LoggerFactory.getLogger(String.format("%s:%s:%d", MODULE, _producerId, _generation)); _checkpointHandler = new CheckpointHandler(config); _availabilityThresholdSlaMs = Integer.parseInt(config.getProperty(AVAILABILITY_THRESHOLD_SLA_MS, DEFAULT_AVAILABILITY_THRESHOLD_SLA_MS)); _logger.info( String.format("Created event producer with customCheckpointing=%s, sendCallback=%s", customCheckpointing, onUnrecoverableError != null)); _dynamicMetricsManager = DynamicMetricsManager.getInstance(); }
Source:
public static void setup() throws Exception { ClientFactory.setTestClient(stubClient); DatadogGlobalConfiguration cfg = DatadogUtilities.getDatadogGlobalDescriptor(); ExtensionList.clearLegacyInstances(); cfg.setCollectBuildLogs(false); EnvVars env = new EnvVars(); env.put("DD_TEST", "bar"); j.createOnlineSlave(new LabelAtom("test"), env); }

Target:
public static void setup() throws Exception { ClientFactory.setTestClient(stubClient); DatadogGlobalConfiguration cfg = DatadogUtilities.getDatadogGlobalDescriptor(); ExtensionList.clearLegacyInstances(); cfg.setCollectBuildLogs(false); j.createOnlineSlave(new LabelAtom("test")); }
Source:
public TmfTimeViewAlignmentInfo getTimeViewAlignmentInfo() { if (fLanes.size() == 0) { return null; } return new TmfTimeViewAlignmentInfo(fLanes.get(0).getChartViewer().getControl().getShell(), fSashForm.toDisplay(0, 0), getTimeAxisOffset()); }

Target:
public TmfTimeViewAlignmentInfo getTimeViewAlignmentInfo() { if (fLanes.size() == 0) { return null; } return fLanes.get(0).getTimeViewAlignmentInfo(); }
Source:
public Maybe<Channel> fromKey(String key) { for (Channel channel : channels.get()) { if (Objects.nonNull(channel.getKey()) && channel.getKey().equals(key)) { return Maybe.just(channel); } } return Maybe.nothing(); }

Target:
public Maybe<Channel> fromKey(String key) { for (Channel channel : channels.get()) { if (Objects.equals(channel.getKey(), key)) { return Maybe.just(channel); } } return Maybe.nothing(); }
Source:
public CompletableFuture<S> writeMessage(S message) throws WriteFailedException { final CompletableFuture<S> future = new CompletableFuture<>(); byte[] bytes = sinkModule.marshalSingleMessage(message); String uuid = UUID.randomUUID().toString(); Long key = offHeapQueue.writeMessage(sinkModule.getId(), bytes); offHeapFutureMap.put(key, future); firstWrite.countDown(); return future; }

Target:
public CompletableFuture<S> writeMessage(S message) throws WriteFailedException { final CompletableFuture<S> future = new CompletableFuture<>(); byte[] bytes = sinkModule.marshalSingleMessage(message); Long key = offHeapQueue.writeMessage(sinkModule.getId(), bytes); offHeapFutureMap.put(key, future); firstWrite.countDown(); return future; }
Source:
public FormValidation doCheckUrl(@QueryParameter String value) { if (value.isEmpty()) { return FormValidation.warning(Messages.Jenkins_EmptyRootUrl()); } if(value.startsWith("http://localhost")) return FormValidation.warning(Messages.Mailer_Localhost_Error()); return FormValidation.ok(); }

Target:
public FormValidation doCheckUrl(@QueryParameter String value) { if (StringUtils.isBlank(value)) { return FormValidation.warning(Messages.Jenkins_EmptyRootUrl()); } if(value.startsWith("http://localhost")) return FormValidation.warning(Messages.Mailer_Localhost_Error()); return FormValidation.ok(); }
Source:
private ByteBuffer createWorld() { final var address = "127.0.0.1"; final var activity = "Converting Apollo"; ByteBuffer world = ByteBuffer.allocate(Short.BYTES + Integer.BYTES + address.length() + activity .length() + Byte.BYTES + Byte.BYTES + Byte.BYTES + Short.BYTES); world.putShort((short) 1); world.putInt(0); BufferUtil.writeString(world, address); BufferUtil.writeString(world, activity); world.put((byte) 0); world.putShort((short) 2000); world.flip(); ByteBuffer list = ByteBuffer.allocate(Short.BYTES + world.remaining()); list.putShort((short) 1); list.put(world); return list.flip(); }

Target:
private ByteBuffer createWorld() { final var address = "127.0.0.1"; final var activity = "Converting Apollo"; ByteBuffer world = ByteBuffer.allocate(Short.BYTES + Integer.BYTES + address.length() + activity .length() + Byte.BYTES + Byte.BYTES + Byte.BYTES + Short.BYTES); world.putShort((short) 1); world.putInt(0); BufferUtil.writeString(world, address); BufferUtil.writeString(world, activity); world.put((byte) 0); world.putShort((short) 100); world.flip(); ByteBuffer list = ByteBuffer.allocate(Short.BYTES + world.remaining()); list.putShort((short) 1); list.put(world); return list.flip(); }
Source:
public void spec203_blackbox_mustNotCallMethodsOnSubscriptionOrPublisherInOnComplete() throws Throwable { blackboxSubscriberWithoutSetupTest(new BlackboxTestStageTestRun() { @Override public void run(BlackboxTestStage stage) throws Throwable { final Subscription subs = new Subscription() { @Override public void request(long n) { final Throwable thr = new Throwable(); for (StackTraceElement stackElem : thr.getStackTrace()) { if (stackElem.getMethodName().equals("onComplete")) { env.flop(String.format("Subscription::request MUST NOT be called from Subscriber::onComplete! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } @Override public void cancel() { final Throwable thr = new Throwable(); for (StackTraceElement stackElem : thr.getStackTrace()) { if (stackElem.getMethodName().equals("onComplete")) { env.flop(String.format("Subscription::cancel MUST NOT be called from Subscriber::onComplete! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } }; final Subscriber<T> sub = createSubscriber(); sub.onSubscribe(subs); sub.onComplete(); env.verifyNoAsyncErrors(); } }); }

Target:
public void spec203_blackbox_mustNotCallMethodsOnSubscriptionOrPublisherInOnComplete() throws Throwable { blackboxSubscriberWithoutSetupTest(new BlackboxTestStageTestRun() { @Override public void run(BlackboxTestStage stage) throws Throwable { final Subscription subs = new Subscription() { @Override public void request(long n) { final Optional<StackTraceElement> onCompleteStackTraceElement = env.findCallerMethodInStackTrace("onComplete"); if (onCompleteStackTraceElement.isDefined()) { final StackTraceElement stackElem = onCompleteStackTraceElement.get(); env.flop(String.format("Subscription::request MUST NOT be called from Subscriber::onComplete (Rule 2.3)! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } @Override public void cancel() { final Optional<StackTraceElement> onCompleteStackElement = env.findCallerMethodInStackTrace("onComplete"); if (onCompleteStackElement.isDefined()) { final StackTraceElement stackElem = onCompleteStackElement.get(); env.flop(String.format("Subscription::cancel MUST NOT be called from Subscriber::onComplete (Rule 2.3)! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } }; final Subscriber<T> sub = createSubscriber(); sub.onSubscribe(subs); sub.onComplete(); env.verifyNoAsyncErrors(); } }); }
Source:
private void updateQuota(StoragePool datacenter) { if (datacenter.getQuotaEnforcementType().equals(QuotaEnforcementTypeEnum.DISABLED) || !getDiskStorageType().getEntity().isInternal()) { getQuota().setIsAvailable(false); return; } getQuota().setIsAvailable(true); StorageDomain storageDomain = getStorageDomain().getSelectedItem(); if (storageDomain == null) { return; } IdQueryParameters parameters = new IdQueryParameters(storageDomain.getId()); Frontend.getInstance().runQuery(VdcQueryType.GetAllRelevantQuotasForStorage, parameters, new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object innerModel, Object innerReturnValue) { ArrayList<Quota> quotaList = ((VdcQueryReturnValue) innerReturnValue).getReturnValue(); final Guid diskQuota = getDisk() != null ? ((DiskImage) getDisk()).getQuotaId() : null; final Guid vmQuota = getVm() != null ? getVm().getQuotaId() : null; final Guid defaultQuota = diskQuota != null ? diskQuota : vmQuota; if (quotaList != null && !quotaList.isEmpty()) { Collections.sort(quotaList, new Comparator<Quota>() { @Override public int compare(Quota quota1, Quota quota2) { if (quota1 == quota2) { return 0; } if (quota1.getId().equals(defaultQuota)) { return -1; } if (quota2.getId().equals(defaultQuota)) { return 1; } return QuotaComparator.NAME.compare(quota1, quota2); } }); getQuota().setItems(quotaList); if (quotaList.get(0).getId().equals(defaultQuota)) { return; } } if (diskQuota != null) { Quota quota = new Quota(); quota.setId(diskQuota); quota.setQuotaName(getDiskImage().getQuotaName()); if (quotaList == null){ quotaList = new ArrayList<>(); } quotaList.add(quota); getQuota().setItems(quotaList); getQuota().setSelectedItem(quota); } } })); }

Target:
private void updateQuota(StoragePool datacenter) { if (datacenter.getQuotaEnforcementType().equals(QuotaEnforcementTypeEnum.DISABLED) || !getDiskStorageType().getEntity().isInternal()) { getQuota().setIsAvailable(false); return; } getQuota().setIsAvailable(true); StorageDomain storageDomain = getStorageDomain().getSelectedItem(); if (storageDomain == null) { return; } final Guid diskQuota = getDisk() != null ? ((DiskImage) getDisk()).getQuotaId() : null; final Guid vmQuota = getVm() != null ? getVm().getQuotaId() : null; final Guid defaultQuota = diskQuota != null ? diskQuota : vmQuota; AsyncDataProvider.getInstance().getAllRelevantQuotasForStorageSorted(new AsyncQuery( new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { List<Quota> quotaList = (List<Quota>) returnValue; if (quotaList != null && !quotaList.isEmpty()) { getQuota().setItems(quotaList); if (quotaList.get(0).getId().equals(defaultQuota)) { return; } } if (diskQuota != null) { Quota quota = new Quota(); quota.setId(diskQuota); quota.setQuotaName(getDiskImage().getQuotaName()); if (quotaList == null) { quotaList = new ArrayList<>(); } quotaList.add(quota); getQuota().setItems(quotaList); getQuota().setSelectedItem(quota); } } }), storageDomain.getId(), defaultQuota); }
Source:
private static int determineContentStart(String s) { int start = TEXTBLOCK_DELIMITER.length(); boolean lineTerminator = false; while (start < s.length() && Character.isWhitespace(s.charAt(start))) { if (s.charAt(start) == '\r' || s.charAt(start) == '\n') { lineTerminator = true; } else if (lineTerminator) { break; } start++; } return start; }

Target:
private static int determineContentStart(String s) { int start = TEXTBLOCK_DELIMITER.length(); while (start < s.length() && Character.isWhitespace(s.charAt(start))) { if (s.charAt(start) == '\n') { return start + 1; } start++; } return start; }
Source:
protected void assertRequestObjectType(final Class<?> expected, final Serializable requestObject) throws ProtocolAdapterException { if (!expected.isInstance(requestObject)) { throw new ProtocolAdapterException( String.format("The request object has an incorrect type. %s excepted but %s was found.", expected.getCanonicalName(), requestObject.getClass().getCanonicalName())); } }

Target:
protected void assertRequestObjectType(final Class<?> expected, final Serializable requestObject) throws ProtocolAdapterException { if (!expected.isInstance(requestObject)) { throw new ProtocolAdapterException( String.format("The request object has an incorrect type. %s expected but %s was found.", expected.getCanonicalName(), requestObject.getClass().getCanonicalName())); } }
Source:
private static Range create(BigInteger bigFrom, BigInteger bigTo) { if (ignoreOverflow) { bigFrom = bigFrom.max(BIG_LONG_MIN_VALUE); bigTo = bigTo.min(BIG_LONG_MAX_VALUE); } else { BigInteger bigWidth = bigTo.subtract(bigFrom).add(BigInteger.ONE); if (bigWidth.compareTo(BIG_LONG_WIDTH) > 0) { return EVERYTHING; } } long longFrom = bigFrom.longValue(); long longTo = bigTo.longValue(); return createRangeOrEverything(longFrom, longTo); }

Target:
private static Range create(BigInteger bigFrom, BigInteger bigTo) { if (ignoreOverflow) { bigFrom = bigFrom.max(BIG_LONG_MIN_VALUE); bigTo = bigTo.min(BIG_LONG_MAX_VALUE); } else { BigInteger bigWidth = bigTo.subtract(bigFrom).add(BigInteger.ONE); if (bigWidth.compareTo(BIG_LONG_WIDTH) > 0) { return EVERYTHING; } } long longFrom = bigFrom.longValue(); long longTo = bigTo.longValue(); return createOrElse(longFrom, longTo, EVERYTHING); }
Source:
private static Number parseValue(String s, Class dataType) throws ParseException { if (Date.class.isAssignableFrom(dataType)) { long period = TimeParser.parsePeriod(s); return period; } else { throw new IllegalArgumentException("Unsupported value type " + dataType); } }

Target:
private static Number parseValue(String s, Class dataType) throws ParseException { if (Date.class.isAssignableFrom(dataType)) { return TimeParser.parsePeriod(s); } throw new IllegalArgumentException("Unsupported value type " + dataType); }
Source:
public void onNewTxForLastBlock(Block block, Tx tx) { Preconditions.checkArgument(block == getLastBlock().orElseThrow()); block.getTxs().add(tx); daoState.getTxMap().put(tx.getId(), tx); }

Target:
public void onNewTxForLastBlock(Block block, Tx tx) { assertDaoStateChange(); getLastBlock().ifPresent(lastBlock -> { if (block == lastBlock) { block.addTx(tx); daoState.addToTxCache(tx); } else { log.warn("Block for parsing does not match last block. That might happen in edge cases at reorgs. " + "Received block={}", block); } }); }
Source:
private static boolean validateNotAFloat(Object value) { boolean valid = true; if (value instanceof Float) { valid = false; logger.log(Level.SEVERE, "Float value encountered in query"); } return valid; }

Target:
private static boolean validateNotAFloat(Object value) { boolean valid = true; if (value instanceof Float) { valid = false; logger.log(Level.SEVERE, "Float value found in query: %f - Use Double instead.", value); } return valid; }
Source:
public Object getElementForNodeId(int id) { verifyThreadAccess(); return mObjectIdMapper.getObjectForId(id); }

Target:
public @Nullable Object getElementForNodeId(int id) { return mObjectIdMapper.getObjectForId(id); }
Source:
public Set<String> getDependentFields() { return Sets.newHashSet(); }

Target:
public Set<String> getDependentFields() { return Collections.emptySet(); }
Source:
public void verifyEditText(String targetText) { waitForValueToBePresentInElementsAttributeByElement( textArea, "value", targetText); Assertion.assertEquals(targetText, getEditText()); PageObjectLogging.log("verifyEditText", "verifying the summary shows " + targetText, true); }

Target:
public void verifyEditText(String targetText) { waitForValueToBePresentInElementsAttributeByElement( editArea, "value", targetText); Assertion.assertEquals(targetText, getEditText()); PageObjectLogging.log( "verifyEditText", "The summary shows " + targetText, true); }
Source:
public void lookupBarcode(String barcode) { barcodeInput.click(); barcodeInput.clear(); barcodeInput.sendKeys(barcode); barcodeInput.sendKeys(Keys.ESCAPE); barcodeLookupButton.click(); waitExplicitly(1000); if (!getDriver().findElements(By.id("ok")).isEmpty()) { WebElement okButton = getDriver().findElement(By.id("ok")); okButton.click(); } waitUntil(elementToBeClickable(barcodeLookupButton)); }

Target:
public void lookupBarcode(String barcode) { barcodeInput.click(); barcodeInput.clear(); barcodeInput.sendKeys(barcode); barcodeInput.sendKeys(Keys.ESCAPE); barcodeLookupButton.click(); waitUntil(elementDoesNotExist(By.id("ajaxLoader"))); WebElement okButton = findElementIfExists(By.id("ok")); if (okButton != null) { okButton.click(); } else { waitUntil(elementToBeClickable(barcodeLookupButton)); } }
Source:
public SslContext getSslContext() { if (sslContext == null) { synchronized (this) { if (sslContext == null) { sslContext = SslConfiguration.buildSslContext(this.settings); } } } return sslContext; }

Target:
public SslContext getSslContext() { var localRef = sslContext; if (localRef == null) { synchronized (this) { localRef = sslContext; if (localRef == null) { sslContext = localRef = SslConfiguration.buildSslContext(this.settings); } } } return localRef; }
Source:
public FixedAssetFinancialAccount act( final FinancialAccount financialAccount) { return fixedAssetFinancialAccountContributions.newAccount(this.fixedAsset, financialAccount); }

Target:
public FixedAssetFinancialAccount act( final FinancialAccount financialAccount) { return fixedAssetFinancialAccountService.newAccount(this.fixedAsset, financialAccount); }