auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
String getBrowserAcceptHeader(EpdqTemplateData templateData) { String acceptHeader = super.getBrowserAcceptHeader(templateData); if (acceptHeader.length() > BROWSER_ACCEPT_MAX_LENGTH) { return DEFAULT_BROWSER_ACCEPT_HEADER; } return super.getBrowserAcceptHeader(templateData); }

Target:
String getBrowserAcceptHeader(EpdqTemplateData templateData) { String acceptHeader = super.getBrowserAcceptHeader(templateData); return acceptHeader.length() > BROWSER_ACCEPT_MAX_LENGTH ? DEFAULT_BROWSER_ACCEPT_HEADER : acceptHeader; }
Source:
public void testNotEnoughForMultipleDiskAndDomainsSecondDomainFails() { ArrayList<DiskImage> imagesDisks = mockMultipleSourceImagesForDomain(4, STORAGE_DOMAIN_ID, 4); imagesDisks.addAll(mockMultipleSourceImagesForDomain(4, STORAGE_DOMAIN_ID2, 4)); doReturn(imagesDisks).when(cmd).getSourceImages(); mockStorageDomainDAOGetForStoragePool(22, STORAGE_DOMAIN_ID); mockStorageDomainDAOGetForStoragePool(10, STORAGE_DOMAIN_ID2); assertFalse("Validation should fail. Second domain should not have enough free space for request.", cmd.isEnoughSpaceToMergeSnapshots()); }

Target:
public void testNotEnoughForMultipleDiskAndDomainsSecondDomainFails() { List<DiskImage> imagesDisks = mockMultipleSourceImagesForDomain(4, STORAGE_DOMAIN_ID, IMAGE_ACTUAL_SIZE_GB); imagesDisks.addAll(mockMultipleSourceImagesForDomain(4, STORAGE_DOMAIN_ID2, IMAGE_ACTUAL_SIZE_GB)); doReturn(imagesDisks).when(cmd).getSourceImages(); mockStorageDomainDAOGetForStoragePool(22, STORAGE_DOMAIN_ID); mockStorageDomainDAOGetForStoragePool(10, STORAGE_DOMAIN_ID2); assertFalse("Validation should fail. Second domain should not have enough free space for request.", cmd.isEnoughSpaceToMergeSnapshots()); }
Source:
public boolean hideLayerGroup(LayerGroupInfo layerGroup) { for(PublishedInfo subLayer: layerGroup.getLayers()) { if(subLayer instanceof LayerInfo) { if(hideLayer((LayerInfo)subLayer)) return true; } else if (subLayer instanceof LayerGroupInfo) { if(hideLayerGroup((LayerGroupInfo)subLayer)) return true; } } if (layerGroup.getWorkspace() == null) { if (LocalWorkspace.get() != null) { if (catalog.getLayerGroupByName(LocalWorkspace.get(), layerGroup.getName()) != null) { return true; } } return false; } return hideWorkspace(layerGroup.getWorkspace()); }

Target:
public boolean hideLayerGroup(LayerGroupInfo layerGroup) { if (layerGroup.getWorkspace() == null) { if (LocalWorkspace.get() != null) { if (catalog.getLayerGroupByName(LocalWorkspace.get(), layerGroup.getName()) != null) { return true; } } return false; } return hideWorkspace(layerGroup.getWorkspace()); }
Source:
public boolean applyDetermination(ScriptPath path, ObjectTag determinationObj) { if (!isDefaultDetermination(determinationObj)) { String determination = determinationObj.toString(); String lower = CoreUtilities.toLowerCase(determination); if (lower.startsWith("reload_speed:")) { ElementTag newBulletSpread = new ElementTag(lower.substring("reload_speed:".length())); if (!newBulletSpread.isDouble()) { Debug.echoError("Determination for 'reload_speed' must be a valid number."); return false; } event.setReloadSpeed(newBulletSpread.asDouble()); return true; } else if (lower.startsWith("reload_time:")) { ElementTag newBulletSpread = new ElementTag(lower.substring("reload_time:".length())); if (!newBulletSpread.isInt()) { Debug.echoError("Determination for 'reload_time' must be a valid number."); return false; } event.setReloadDuration(newBulletSpread.asInt()); return true; } else if (lower.startsWith("reload_sounds:")) { String newReloadSounds = determination.substring("reload_sounds:".length()); if (CoreUtilities.toLowerCase(newReloadSounds).equals("none")) { newReloadSounds = ""; } event.setSounds(newReloadSounds); return true; } } return super.applyDetermination(path, determinationObj); }

Target:
public boolean applyDetermination(ScriptPath path, ObjectTag determinationObj) { if (!isDefaultDetermination(determinationObj)) { String determination = determinationObj.toString(); String lower = CoreUtilities.toLowerCase(determination); if (lower.startsWith("reload_speed:")) { ElementTag newReloadSpeed = new ElementTag(lower.substring("reload_speed:".length())); if (!newReloadSpeed.isDouble()) { Debug.echoError("Determination for 'reload_speed' must be a valid number."); return false; } event.setReloadSpeed(newReloadSpeed.asDouble()); return true; } else if (lower.startsWith("reload_time:")) { String time = lower.substring("reload_time:".length()); if (!DurationTag.matches(time)) { Debug.echoError("Determination for 'reload_time' must be a valid DurationTag."); return false; } DurationTag newReloadtime = DurationTag.valueOf(lower.substring("reload_time:".length()), getTagContext(path)); event.setReloadDuration(newReloadtime.getTicksAsInt()); return true; } else if (lower.startsWith("reload_sounds:")) { String newReloadSounds = determination.substring("reload_sounds:".length()); if (CoreUtilities.toLowerCase(newReloadSounds).equals("none")) { newReloadSounds = ""; } event.setSounds(newReloadSounds); return true; } } return super.applyDetermination(path, determinationObj); }
Source:
public CorfuReplicationDiscoveryService(@Nonnull ServerContext serverContext, @Nonnull CorfuReplicationClusterManagerAdapter clusterManagerAdapter, @Nonnull CompletableFuture<CorfuInterClusterReplicationServerNode> serverCallback) { this.executorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("discovery-service-executor").build()); this.clusterManagerAdapter = clusterManagerAdapter; this.logReplicationNodeId = serverContext.getNodeId(); this.serverContext = serverContext; this.localEndpoint = serverContext.getLocalEndpoint(); this.serverCallback = serverCallback; this.isLeader = false; this.eventQueue = new LinkedBlockingQueue<>(); this.shutdown = false; this.executorService.submit(this::run); }

Target:
public CorfuReplicationDiscoveryService(@Nonnull ServerContext serverContext, @Nonnull CorfuReplicationClusterManagerAdapter clusterManagerAdapter, @Nonnull CompletableFuture<CorfuInterClusterReplicationServerNode> serverCallback) { this.executorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("discovery-service-executor").build()); this.clusterManagerAdapter = clusterManagerAdapter; this.logReplicationNodeId = serverContext.getNodeId(); this.serverContext = serverContext; this.localEndpoint = serverContext.getLocalEndpoint(); this.serverCallback = serverCallback; this.shutdown = false; this.isLeader = new AtomicBoolean(); this.eventQueue = new LinkedBlockingQueue<>(); }
Source:
private String getLastCmd() { CliSessionState cliss = (CliSessionState) SessionState.get(); Scanner scanner = null; try { scanner = new Scanner(new File(cliss.fileName)); } catch (FileNotFoundException e) { LOG.error("Can't find Hive script", e); } if (scanner == null) { return null; } Pattern delim = Pattern.compile(";"); scanner.useDelimiter(delim); String lastLine = null; while (scanner.hasNext()) { String line = StringUtils.trim(scanner.next().replaceAll("\\n", "")); if (!line.startsWith("--") && !StringUtils.isEmpty(line)) { lastLine = line; } } return lastLine; }

Target:
private String getLastCmd() { CliSessionState cliss = (CliSessionState) SessionState.get(); Scanner scanner = null; try { scanner = new Scanner(new File(cliss.fileName)); } catch (FileNotFoundException e) { LOG.error("Can't find Hive script", e); } if (scanner == null) { return null; } Pattern delim = Pattern.compile(";"); scanner.useDelimiter(delim); String lastLine = null; while (scanner.hasNext()) { String line = StringUtils.trim(scanner.next().replaceAll("\\n", "")); if (line.length() != 0 && !line.startsWith("--")) { lastLine = line; } } return lastLine; }
Source:
protected void setSeries(String seriesName, double[] seriesValues) { if (seriesValues == null) { throw new IllegalArgumentException("Series values cannot be null"); } String seriesType = getSeriesType(seriesName); fModelBuilder.addYSeries( new YSeries( seriesType, getSeriesColor(seriesName), getWidth(seriesName), getSeriesStyle(seriesType), seriesName, seriesValues)); }

Target:
protected void setSeries(String seriesName, double[] seriesValues) { if (seriesName == null) { throw new IllegalArgumentException("seriesName cannot be null"); } if (seriesValues == null) { throw new IllegalArgumentException("Series values cannot be null"); } String seriesType = getSeriesType(seriesName); fModelBuilder.addYSeries( new YSeries( seriesType, getSeriesColor(seriesName), getWidth(seriesName), getSeriesStyle(seriesType), seriesName, seriesValues)); }
Source:
protected Object getValueUnchecked(String fieldName) { requestScope.queueTriggers(this, CRUDAction.READ); requestScope.queueTriggers(this, fieldName, CRUDAction.READ, Optional.empty()); runTriggers(OnReadPreSecurity.class, "", Optional.empty()); runTriggers(OnReadPreSecurity.class, fieldName, Optional.empty()); return getValue(getObject(), fieldName, requestScope); }

Target:
protected Object getValueUnchecked(String fieldName) { requestScope.queueTriggers(this, CRUDAction.READ); requestScope.queueTriggers(this, fieldName, CRUDAction.READ, Optional.empty()); runTriggers(OnReadPreSecurity.class, CLASS_NO_FIELD); runTriggers(OnReadPreSecurity.class, fieldName); return getValue(getObject(), fieldName, requestScope); }
Source:
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("id", id) .add("resourceId", resourceId) .add("tunnelIps", tunnelIps) .add("managementIp", managementIp) .add("managementPort", managementPort) .add("managementProtocol", managementProtocol) .add("remoteMacEntries", remoteMacEntries) .toString(); }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("id", id) .add("type", type) .add("resourceId", resourceId) .add("tunnelIps", tunnelIps) .add("managementIp", managementIp) .add("managementPort", managementPort) .add("managementProtocol", managementProtocol) .add("remoteMacEntries", remoteMacEntries) .toString(); }
Source:
public Set<String> getChoiceAuthoritiesNames() { if (authorityNames.isEmpty()) { loadChoiceAuthorityConfigurations(); } return authorityNames; }

Target:
public Set<String> getChoiceAuthoritiesNames() { if (authorities.keySet().isEmpty()) { loadChoiceAuthorityConfigurations(); } return authorities.keySet(); }
Source:
public void handlePostEntitlement(PoolManager manager, Consumer consumer, Map<String, Entitlement> entitlements) { Map<String, Integer> stackIdCounts = new HashMap<String, Integer>(); for (Entitlement entitlement : entitlements.values()) { if (entitlement.getPool().isStacked()) { String stackId = entitlement.getPool().getStackId(); Integer count = stackIdCounts.containsKey(stackId) ? stackIdCounts.get(stackId) : 0; stackIdCounts.put(stackId, count + 1); } } Set<String> uniqueStackIds = new HashSet<String>(); Map<String, Entitlement> uniqueEnts = new HashMap<String, Entitlement>(); Map<String, Entitlement> nonUniqueEnts = new HashMap<String, Entitlement>(); for (Entry<String, Entitlement> entry : entitlements.entrySet()) { Pool p = entry.getValue().getPool(); if (p.isStacked() && stackIdCounts.get(p.getStackId()) > 1) { nonUniqueEnts.put(entry.getKey(), entry.getValue()); } else { uniqueEnts.put(entry.getKey(), entry.getValue()); if (p.isStacked()) { uniqueStackIds.add(p.getStackId()); } } } handlePostEntitlement(manager, consumer, uniqueEnts, uniqueStackIds); for (Entry<String, Entitlement> entry: nonUniqueEnts.entrySet()) { Entitlement ent = entry.getValue(); Map<String, Entitlement> entMap = new HashMap<String, Entitlement>(); entMap.put(entry.getKey(), ent); Set<String> stackIdSet = new HashSet<String>(); if (ent.getPool().isStacked()) { stackIdSet.add(ent.getPool().getStackId()); } handlePostEntitlement(manager, consumer, entMap, stackIdSet); } }

Target:
public void handlePostEntitlement(PoolManager manager, Consumer consumer, Map<String, Entitlement> entitlements) { Map<String, Integer> stackIdCounts = new HashMap<String, Integer>(); for (Entitlement entitlement : entitlements.values()) { if (entitlement.getPool().isStacked()) { String stackId = entitlement.getPool().getStackId(); Integer count = stackIdCounts.containsKey(stackId) ? stackIdCounts.get(stackId) : 0; stackIdCounts.put(stackId, count + 1); } } Set<String> uniqueStackIds = new HashSet<String>(); Map<String, Entitlement> uniqueEnts = new HashMap<String, Entitlement>(); Map<String, Entitlement> nonUniqueEnts = new HashMap<String, Entitlement>(); for (Entry<String, Entitlement> entry : entitlements.entrySet()) { Pool p = entry.getValue().getPool(); if (p.isStacked() && stackIdCounts.get(p.getStackId()) > 1) { nonUniqueEnts.put(entry.getKey(), entry.getValue()); } else { uniqueEnts.put(entry.getKey(), entry.getValue()); if (p.isStacked()) { uniqueStackIds.add(p.getStackId()); } } } if (!uniqueEnts.isEmpty()) { handlePostEntitlement(manager, consumer, uniqueEnts, uniqueStackIds); } for (Entry<String, Entitlement> entry: nonUniqueEnts.entrySet()) { Entitlement ent = entry.getValue(); Map<String, Entitlement> entMap = new HashMap<String, Entitlement>(); entMap.put(entry.getKey(), ent); Set<String> stackIdSet = new HashSet<String>(); if (ent.getPool().isStacked()) { stackIdSet.add(ent.getPool().getStackId()); } handlePostEntitlement(manager, consumer, entMap, stackIdSet); } }
Source:
private static void merge(AggregatedCalledFunction destination, AggregatedCalledFunction source) { long sourceDuration = source.getDuration(); long sourceSelfTime = source.getSelfTime(); destination.addToDuration(sourceDuration); destination.addToSelfTime(sourceSelfTime); destination.fStatistics.update(source.fStatistics.getMaxSegment(),source.fStatistics.getMinSegment(), sourceSelfTime); mergeChildren(destination, source); }

Target:
private static void merge(AggregatedCalledFunction destination, AggregatedCalledFunction source) { long sourceDuration = source.getDuration(); long sourceSelfTime = source.getSelfTime(); destination.addToDuration(sourceDuration); destination.addToSelfTime(sourceSelfTime); destination.fStatistics.update(source.fStatistics.getMaxSegment(), source.fStatistics.getMinSegment(), sourceDuration, sourceSelfTime); mergeChildren(destination, source); }
Source:
public boolean hasChange(int changeFlag) { TreeItem[] selection = viewer.getTree().getItems(); TreeItem firstSelectedItem = selection.length > 0 ? selection[0] : null; switch (changeFlag) { case NEXT_CHANGE: return getNextDiff(thisOrFirstItem(firstSelectedItem)) != null; case PREVIOUS_CHANGE: return getPreviousDiff(thisOrFirstItem(firstSelectedItem)) != null; case NEXT_UNRESOLVED_CHANGE: return getNextUnresolvedDiff(thisOrFirstItem(firstSelectedItem)) != null; case FIRST_CHANGE: TreeItem firstItemInTree = getFirstItemInTree(); return firstItemInTree != null && getNextDiff(firstItemInTree) != null; default: throw new IllegalStateException(); } }

Target:
public boolean hasChange(int changeFlag) { TreeItem[] selection = viewer.getTree().getItems(); TreeItem firstSelectedItem = selection.length > 0 ? selection[0] : null; switch (changeFlag) { case NEXT_CHANGE: return getNextDiff(thisOrFirstItem(firstSelectedItem)) != null; case PREVIOUS_CHANGE: return getPreviousDiff(thisOrFirstItem(firstSelectedItem)) != null; case NEXT_UNRESOLVED_CHANGE: return getNextUnresolvedDiff(thisOrFirstItem(firstSelectedItem)) != null; case FIRST_CHANGE: return getNextDiff(getFirstItemInTree()) != null; default: throw new IllegalStateException(); } }
Source:
public static final String QueryFullProcessImageName(HANDLE hProcess, int dwFlags) { char[] path = new char[WinDef.MAX_PATH]; IntByReference lpdwSize = new IntByReference(path.length); if (Kernel32.INSTANCE.QueryFullProcessImageName(hProcess, 0, path, lpdwSize)) return new String(path).substring(0, lpdwSize.getValue()); return null; }

Target:
public static final String QueryFullProcessImageName(HANDLE hProcess, int dwFlags) { char[] path = new char[WinDef.MAX_PATH]; IntByReference lpdwSize = new IntByReference(path.length); if (Kernel32.INSTANCE.QueryFullProcessImageName(hProcess, 0, path, lpdwSize)) return new String(path).substring(0, lpdwSize.getValue()); throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); }
Source:
public void async(Runnable runnable) { Thread asyncTask = new Thread(() -> { readWriteLock.writeLock().lock(); try { runnable.run(); } finally { readWriteLock.writeLock().unlock(); } }); asyncTask.start(); }

Target:
public void async(Runnable runnable) { String workerName = "async-file-store-cleanup-task-" + workerCounter.getAndIncrement(); GridWorker worker = new GridWorker(igniteInstanceName, workerName, log) { @Override protected void body() { readWriteLock.writeLock().lock(); try { runnable.run(); } finally { readWriteLock.writeLock().unlock(); workers.remove(this); } } }; workers.add(worker); Thread asyncTask = new IgniteThread(worker); asyncTask.start(); }
Source:
public List<@NonNull Integer> getSubAttributes(int quark, boolean recursive) throws AttributeNotFoundException { return getAttributeTree().getSubAttributes(quark, recursive); }

Target:
public List<Integer> getSubAttributes(int quark, boolean recursive) throws AttributeNotFoundException { return getAttributeTree().getSubAttributes(quark, recursive); }
Source:
private List<BootstrapTask> getIncompleteTasks() throws SQLException { ArrayList<BootstrapTask> list = new ArrayList<>(); try ( Connection cx = maxwellConnectionPool.getConnection() ) { PreparedStatement s = cx.prepareStatement("select * from bootstrap where is_complete = 0 and client_id = ? and (started_at is null or started_at <= now()) order by -started_at desc, id"); s.setString(1, this.clientID); ResultSet rs = s.executeQuery(); while (rs.next()) { list.add(BootstrapTask.valueOf(rs)); } } return list; }

Target:
private List<BootstrapTask> getIncompleteTasks() throws SQLException { ArrayList<BootstrapTask> list = new ArrayList<>(); try ( Connection cx = maxwellConnectionPool.getConnection() ) { PreparedStatement s = cx.prepareStatement("select * from bootstrap where is_complete = 0 and client_id = ? and (started_at is null or started_at <= now()) order by isnull(started_at), started_at asc, id asc"); s.setString(1, this.clientID); ResultSet rs = s.executeQuery(); while (rs.next()) { list.add(BootstrapTask.valueOf(rs)); } } return list; }
Source:
private OpenTok(int apiKey, String apiSecret) { this(apiKey, apiSecret, defaultApiUrl); }

Target:
public OpenTok(int apiKey, String apiSecret) { this.apiKey = apiKey; this.apiSecret = apiSecret.trim(); this.client = new HttpClient.Builder(apiKey, apiSecret).build(); }
Source:
public String get() { return baseProducer.randomElement("L", "M", "N", "P", "R", "T", "V", "W", "X", "Y") + randomNumeric(8); }

Target:
public String get() { return baseProducer.randomElement(ID_CARD_TYPE_LETTERS) + randomNumeric(8); }
Source:
public boolean onBackPressed() { if (tocHandler != null && tocHandler.isVisible()) { tocHandler.hide(); return true; } if (closeFindInPage()) { return true; } if (pageLoadStrategy.onBackPressed()) { return true; } else if (tabList.size() > 1) { tabList.remove(tabList.size() - 1); pageLoadStrategy.setBackStack(getCurrentTab().getBackStack()); pageLoadStrategy.loadPageFromBackStack(); tabsProvider.enterTabMode(); return true; } if (tabsProvider.onBackPressed()) { return true; } return false; }

Target:
public boolean onBackPressed() { if (tocHandler != null && tocHandler.isVisible()) { tocHandler.hide(); return true; } if (closeFindInPage()) { return true; } if (pageLoadStrategy.onBackPressed()) { return true; } if (tabList.size() > 1) { tabList.remove(tabList.size() - 1); pageLoadStrategy.setBackStack(getCurrentTab().getBackStack()); pageLoadStrategy.loadPageFromBackStack(); tabsProvider.enterTabMode(); return true; } return tabsProvider.onBackPressed(); }
Source:
private void runInternal() { try { operationSelector.start(); while (!stage.isTerminated()) { boolean started = stage.isStarted(); if (started) { txRemainingOperations = 0; if (ongoingTx != null) { endTransactionAndRegisterStats(null); } stats.begin(); this.started = started; break; } Operation operation = operationSelector.next(random); try { logic.run(operation); if (delayBetweenRequests > 0) sleep(delayBetweenRequests); } catch (OperationLogic.RequestException e) { } catch (InterruptedException e) { log.trace("Stressor interrupted.", e); interrupt(); } } completion.start(); int i = 0; while (!stage.isTerminated()) { Operation operation = operationSelector.next(random); if (!completion.moreToRun()) break; try { logic.run(operation); if (delayBetweenRequests > 0) sleep(delayBetweenRequests); } catch (OperationLogic.RequestException e) { } catch (InterruptedException e) { log.trace("Stressor interrupted.", e); interrupt(); } i++; completion.logProgress(i); } } finally { if (txRemainingOperations > 0) { endTransactionAndRegisterStats(null); } } }

Target:
private void runInternal() { boolean counted = false; try { operationSelector.start(); while (!stage.isTerminated()) { boolean started = stage.isStarted(); if (started) { txRemainingOperations = 0; if (ongoingTx != null) { endTransactionAndRegisterStats(null); } break; } else { if (!counted) { threadCountDown.countDown(); counted = true; } Operation operation = operationSelector.next(random); try { logic.run(operation); if (delayBetweenRequests > 0) sleep(delayBetweenRequests); } catch (OperationLogic.RequestException e) { } catch (InterruptedException e) { log.trace("Stressor interrupted.", e); interrupt(); } } } stats.begin(); this.started = true; completion.start(); int i = 0; while (!stage.isTerminated()) { Operation operation = operationSelector.next(random); if (!completion.moreToRun()) break; try { logic.run(operation); if (delayBetweenRequests > 0) sleep(delayBetweenRequests); } catch (OperationLogic.RequestException e) { } catch (InterruptedException e) { log.trace("Stressor interrupted.", e); interrupt(); } i++; completion.logProgress(i); } } finally { if (txRemainingOperations > 0) { endTransactionAndRegisterStats(null); } } }
Source:
public void testNoNPEWhenClientBreaksConnection() throws Exception { final File f = setupFile("file.pdf", TestUtils.randomUnicodeString(1000000)); server.requestHandler(req -> { vertx.executeBlocking(future -> { try { Thread.sleep(100); } catch (InterruptedException e) { } future.complete(); }, false, res -> { req.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/pdf"); try { req.response().sendFile(f.getAbsolutePath(), event -> { if (event.failed()) { testComplete(); } else { fail("It should not reach this point"); } }); } catch (NullPointerException e) { fail("It should not throw NPE"); } }); }); server.listen(onSuccess(server -> { vertx.createNetClient().connect(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, socket -> { socket.result().write("GET / HTTP/1.1\r\n\r\n").close(); }); })); await(); }

Target:
public void testNoNPEWhenClientBreaksConnection() throws Exception { final File f = setupFile("file.pdf", TestUtils.randomUnicodeString(1000000)); server.requestHandler(req -> { req.connection().closeHandler(v -> { req.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/pdf"); try { req.response().sendFile(f.getAbsolutePath(), event -> { if (event.failed()) { testComplete(); } else { fail("It should not reach this point"); } }); } catch (NullPointerException e) { fail("It should not throw NPE"); } }); }); server.listen(onSuccess(server -> { vertx.createNetClient().connect(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, socket -> { socket.result().write("GET / HTTP/1.1\r\n\r\n").close(); }); })); await(); }
Source:
public void appendMessage(String message) { if (message == null) { return; } messagePanel.add(new HTML(StringUtils.addHtmlLineBreaks(message))); }

Target:
public void appendMessage(String message) { if (message == null) { return; } messagePanel.add(new Label(message)); }
Source:
private boolean removeTimestampedSnapshot(String basePath, Repository repository, int numberToKeep, int keepPeriod) throws ProviderImplementationException, IOException, XmlPullParserException, ParseException { String storageId = repository.getStorage() .getId(); File file = new File(basePath); LayoutProvider layoutProvider = getLayoutProvider(repository, layoutProviderRegistry); Metadata metadata = mavenMetadataManager.readMetadata(Paths.get(basePath)); if (metadata != null && metadata.getVersioning() != null) { Map<Integer, String> mapToRemove = getRemovingSnapshots(metadata, numberToKeep, keepPeriod); if (!mapToRemove.isEmpty()) { List<String> removingSnapshots = new ArrayList<>(); new ArrayList<>(mapToRemove.values()).forEach(e -> removingSnapshots.add(metadata.getArtifactId() .concat("-") .concat(e) .concat(".jar")) ); List<File> list = Arrays.asList(file.listFiles()); list.stream() .filter(File::isFile) .filter(e -> ArtifactUtils.isArtifact(e.getPath()) && removingSnapshots.contains(e.getName())) .forEach(e -> { try { layoutProvider.delete(storageId, repository.getId(), e.getPath(), true); String artifactName = e.getName(); artifactName = artifactName.substring(0, artifactName.lastIndexOf(".")); String pomPath = Paths.get(e.getParent(), artifactName) .toString() .concat(".pom"); layoutProvider.delete(storageId, repository.getId(), pomPath, true); } catch (IOException e1) { logger.error(e1.getMessage(), e1); } }); return true; } } return false; }

Target:
private boolean removeTimestampedSnapshot(String basePath, Repository repository, int numberToKeep, int keepPeriod) throws ProviderImplementationException, IOException, XmlPullParserException, ParseException { String storageId = repository.getStorage() .getId(); File file = new File(basePath); LayoutProvider layoutProvider = getLayoutProvider(repository, layoutProviderRegistry); Metadata metadata = mavenMetadataManager.readMetadata(Paths.get(basePath)); if (metadata != null && metadata.getVersioning() != null) { Map<Integer, String> mapToRemove = getRemovableTimestampedSnapshots(metadata, numberToKeep, keepPeriod); if (!mapToRemove.isEmpty()) { List<String> removingSnapshots = new ArrayList<>(); new ArrayList<>(mapToRemove.values()).forEach(e -> removingSnapshots.add(metadata.getArtifactId() .concat("-") .concat(e) .concat(".jar")) ); List<File> list = Arrays.asList(file.listFiles()); list.stream() .filter(File::isFile) .filter(e -> ArtifactUtils.isArtifact(e.getPath()) && removingSnapshots.contains(e.getName())) .forEach(e -> { try { layoutProvider.delete(storageId, repository.getId(), e.getPath(), true); String artifactName = e.getName(); artifactName = artifactName.substring(0, artifactName.lastIndexOf('.')); String pomPath = Paths.get(e.getParent(), artifactName) .toString() .concat(".pom"); layoutProvider.delete(storageId, repository.getId(), pomPath, true); } catch (IOException e1) { logger.error(e1.getMessage(), e1); } }); return true; } } return false; }
Source:
public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(context); if (hasVersioning) { XWikiDocument doc = context.getDoc(); if (doc != null) { XWikiDocumentArchive documentArchive = doc.getDocumentArchive(); if (documentArchive == null) { doc.setDocumentArchive(new XWikiDocumentArchive()); } } this.getVersioningStore(context).resetRCSArchive(this, true, context); } }

Target:
public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(context); if (hasVersioning) { this.loadArchive(context); this.getVersioningStore(context).resetRCSArchive(this, true, context); } }
Source:
private void validateMeasurementHasNotBeenCreated(final Observation observation, final Observation existingObservation, final List<ObjectError> errors) { final List<Measurement> measurements = observation.getMeasurements(); int counter = 0; for (final Measurement measurement : measurements) { final Measurement existingMeasurement = existingObservation.getMeasurement(measurement.getMeasurementIdentifier()); if (existingMeasurement == null) { final String []array = {"measurement.already.inserted"}; final List<String> object = new ArrayList<>(); final ObjectMapper objectMapper = new ObjectMapper(); try { object.add(objectMapper.writeValueAsString(measurement)); } catch (final JsonProcessingException e) { throw new ApiRuntimeException("Error mapping measurement to JSON", e); } final FieldError objectError = new FieldError("Observation", "Measurements [" + counter + "]", null, false, array, object.toArray(), "Error processing measurement"); errors.add(objectError); counter++; } } }

Target:
private void validateMeasurementHasNotBeenCreated(final Observation observation, final Observation existingObservation, final List<ObjectError> errors) { final List<Measurement> measurements = observation.getMeasurements(); int counter = 0; for (final Measurement measurement : measurements) { final Measurement existingMeasurement = existingObservation.getMeasurement(measurement.getMeasurementIdentifier()); if (existingMeasurement == null) { final String []errorMessage = {"measurement.already.inserted"}; final List<String> object = new ArrayList<>(); final ObjectMapper objectMapper = new ObjectMapper(); try { object.add(objectMapper.writeValueAsString(measurement)); } catch (final JsonProcessingException e) { throw new ApiRuntimeException("Error mapping measurement to JSON", e); } final FieldError objectError = new FieldError("Observation", "Measurements [" + counter + "]", null, false, errorMessage, object.toArray(), "Error processing measurement"); errors.add(objectError); counter++; } } }
Source:
public void testAccessControl() throws Exception{ String iDOfCourseOfStudent = dataBundle.students.get("student1InCourse1").course; String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; verifyAccessibleForStudentsOfTheSameCourse(submissionParams); verifyAccessibleForStudentsOfDifferentCourse(submissionParams); }

Target:
public void testAccessControl() throws Exception { String iDOfCourseOfStudent = dataBundle.students .get("student1InCourse1").course; String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; ______TS("Student of same course can access"); verifyAccessibleForStudentsOfTheSameCourse(submissionParams); ______TS("Admin can access to Masquerade as student"); verifyAccessibleForAdminToMasqueradeAsStudent(submissionParams); ______TS("Unaccessible without login"); verifyUnaccessibleWithoutLogin(submissionParams); iDOfCourseOfStudent = dataBundle.students.get("student2InCourse1").course; submissionParams = new String[] { Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; ______TS("Student of different course can not access"); verifyUnaccessibleForStudentsOfOtherCourses(submissionParams); ______TS("UnregisteredUsers cannot access"); verifyUnaccessibleForUnregisteredUsers(submissionParams); }
Source:
public void status(ObjectNode obj) { countSuccesses++; assertNotNull(obj); assertNotNull(obj.path("Timestamp")); assertNotNull(obj.path("Current status")); }

Target:
public void status(ObjectNode obj) { countSuccesses++; assertNotNull(obj); assertNotNull(obj.get("Timestamp")); assertNotNull(obj.get("Current status")); if (!obj.path("Current status").isMissingNode() && obj.get("Current status").textValue().equals("Batch Success Recorded.")) { assertNotNull(obj.get("Estimated total bytes in the CSV file")); assertNotNull(obj.get("Bytes read so far")); assertNotNull(obj.get("Success Batch Number")); assertNotNull(obj.get("Batch running since last log")); assertNotNull(obj.get("Total successes")); } }
Source:
private void collided(SolGame game) { shouldBeRemoved = true; Vector2 position = body.getPosition(); buildEffect(game, config.collisionEffect, DrawableLevel.PART_FG_1, position, false); buildEffect(game, config.collisionEffectBackground, DrawableLevel.PART_FG_0, position, false); if (config.collisionEffectBackground != null) { game.getPartMan().blinks(position, game, config.collisionEffectBackground.size); } if(ship.getPilot().isPlayer() && obstacle instanceof SolShip) ship.changeDisposition(((SolShip) obstacle).getFactionID()); game.getSoundManager().play(game, config.collisionSound, null, this); }

Target:
private void collided(SolGame game) { shouldBeRemoved = true; Vector2 position = body.getPosition(); buildEffect(game, config.collisionEffect, DrawableLevel.PART_FG_1, position, false); buildEffect(game, config.collisionEffectBackground, DrawableLevel.PART_FG_0, position, false); if (config.collisionEffectBackground != null) { game.getPartMan().blinks(position, game, config.collisionEffectBackground.size); } if (ship.getPilot().isPlayer() && obstacle instanceof SolShip) { ship.changeDisposition(((SolShip) obstacle).getFactionID()); } game.getSoundManager().play(game, config.collisionSound, null, this); }
Source:
protected void executeCommand() { final VDS vds = getVds(); EngineLock monitoringLock = new EngineLock(Collections.singletonMap(getParameters().getVdsId().toString(), new Pair<String, String>(LockingGroup.VDS_INIT.name(), "")), null); log.infoFormat("Before acquiring lock in order to prevent monitoring for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); getLockManager().acquireLockWait(monitoringLock); log.infoFormat("Lock acquired, from now a monitoring of host will be skipped for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); try { ResourceManager.getInstance().GetVdsManager(getVdsId()).refreshCapabilities(new AtomicBoolean(), getVds()); setSucceeded(true); } catch (Exception e) { setSucceeded(false); } finally { getLockManager().releaseLock(monitoringLock); log.infoFormat("Get Capabilities finished. Lock released. Monitoring can run now for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); } }

Target:
protected void executeCommand() { EngineLock monitoringLock = aquireMonitorLock(); try { ResourceManager.getInstance().GetVdsManager(getVdsId()).refreshHost(getVds()); setSucceeded(true); } finally { releaseMonitorLock(monitoringLock, "Get Capabilities"); } }
Source:
public synchronized V getValue() { if (value.get() == null || isExpired()) { return refreshValue(); } return value.get(); }

Target:
public synchronized V getValue() { V cachedValue = value.get(); if (cachedValue == null || isExpired()) { return refreshValue(); } return cachedValue; }
Source:
protected String generateNewIdOfLength(ConfigBag setup, int len) { Object context = setup.peek(CloudLocationConfig.CALLER_CONTEXT); Entity entity = null; if (context instanceof Entity) entity = (Entity) context; StringShortener shortener = Strings.shortener().separator("-"); shortener.append("system", "brooklyn"); shortener.append("timeStamp", Long.toString(System.currentTimeMillis() / 1000L, 16)); String user = System.getProperty("user.name"); if (!"brooklyn".equals(user)) shortener.append("user", user); if (entity!=null) { Application app = entity.getApplication(); if (app!=null) { shortener.append("app", shortName(app)) .append("appId", app.getId()); } shortener.append("entity", shortName(entity)) .append("entityId", entity.getId()); } else if (context!=null) { shortener.append("context", context.toString()); } shortener.truncate("user", 12) .truncate("app", 16) .truncate("entity", 16) .truncate("appId", 4) .truncate("entityId", 4) .truncate("context", 12); shortener.canTruncate("user", 8) .canTruncate("app", 5) .canTruncate("entity", 5) .canTruncate("system", 2) .canTruncate("app", 3) .canTruncate("entity", 3) .canRemove("app") .canTruncate("user", 4) .canRemove("entity") .canTruncate("context", 4) .canTruncate("timeStamp", 8) .canRemove("user") .canTruncate("appId", 2) .canRemove("appId"); String s = shortener.getStringOfMaxLength(len); return sanitize(s).toLowerCase(); }

Target:
protected String generateNewIdOfLength(ConfigBag setup, int len) { Object context = setup.peek(CloudLocationConfig.CALLER_CONTEXT); Entity entity = null; if (context instanceof Entity) entity = (Entity) context; StringShortener shortener = Strings.shortener().separator("-"); shortener.append("system", "brooklyn"); shortener.append("timeStamp", Long.toString(System.currentTimeMillis() / 1000L, Character.MAX_RADIX)); String user = System.getProperty("user.name"); if (!"brooklyn".equals(user)) shortener.append("user", user); if (entity!=null) { Application app = entity.getApplication(); if (app!=null) { shortener.append("app", shortName(app)) .append("appId", app.getId()); } shortener.append("entity", shortName(entity)) .append("entityId", entity.getId()); } else if (context!=null) { shortener.append("context", context.toString()); } shortener.truncate("user", 12) .truncate("app", 16) .truncate("entity", 16) .truncate("appId", 4) .truncate("entityId", 4) .truncate("context", 12); shortener.canTruncate("user", 8) .canTruncate("app", 5) .canTruncate("entity", 5) .canTruncate("system", 2) .canTruncate("app", 3) .canTruncate("entity", 3) .canRemove("app") .canTruncate("user", 4) .canRemove("entity") .canTruncate("context", 4) .canTruncate("timeStamp", 6) .canRemove("user") .canTruncate("appId", 2) .canRemove("appId"); String s = shortener.getStringOfMaxLength(len); return sanitize(s).toLowerCase(); }
Source:
private LiteralSuggestion getLatLonSuggestions(String query) { Matcher matcher = PATTERN_LAT_LON.matcher(query); List<Double> numbers = new ArrayList<>(); while (matcher.find()) { numbers.add(Double.parseDouble(matcher.group())); } if (numbers.isEmpty() || numbers.size() == 1) { return null; } List<LatLon> latLonList = getLatLonList(numbers); String name = "Lat/Lon: " + latLonList.stream().map(LatLon::toString).collect(Collectors.joining(", ")); return new LiteralSuggestion("LITERAL", name, latLonList); }

Target:
private LiteralSuggestion getLatLonSuggestions(String query) { Matcher matcher = PATTERN_LAT_LON.matcher(query); List<Double> numbers = new ArrayList<>(); while (matcher.find()) { numbers.add(Double.parseDouble(matcher.group())); } if (numbers.size() <= 1) { return null; } List<LatLon> latLonList = getLatLonList(numbers); String name = "Lat/Lon: " + latLonList.stream().map(LatLon::toString).collect(Collectors.joining(", ")); return new LiteralSuggestion("LITERAL", name, latLonList); }
Source:
public Collection<E> getValues() { if (parts == null) { ArrayList<E> sortedParts = new ArrayList<>(globalContext.getParts(type)); sortedParts.sort((o1, o2) -> { if (o1 == o2) { return 0; } if (o2 == null) { return -1; } if (o1 == null) { return 1; } return o1.getPriority() - o2.getPriority(); }); parts = sortedParts; } return Collections.unmodifiableCollection(parts); }

Target:
public Collection<E> getValues() { if (parts == null) { List<E> sortedParts = new ArrayList<>(globalContext.getParts(type)); sortedParts.sort(Comparator.comparingInt(Priorized::getPriority)); parts = sortedParts; } return Collections.unmodifiableCollection(parts); }
Source:
public boolean isEmpty() { return this.shadow$isEmpty(); }

Target:
public boolean itemstack$isEmpty() { return this.shadow$isEmpty(); }
Source:
public void faultySoftwareInfoFormsTest() { final DataForm dataForm = new DataForm(Type.result); FormField.Builder builder = FormField.builder(FormField.FORM_TYPE); builder.setType(FormField.Type.hidden); builder.addValue("faulty_formtype"); dataForm.addField(builder.build()); assertThrows(IllegalArgumentException.class, () -> { SoftwareInfoForm.getBuilder().setDataForm(dataForm).build(); }); final DataForm dataFormWithoutFormType = new DataForm(Type.result); assertThrows(IllegalArgumentException.class, () -> { SoftwareInfoForm.getBuilder().setDataForm(dataFormWithoutFormType).build(); }); }

Target:
public void faultySoftwareInfoFormsTest() { DataForm.Builder dataFormbuilder = DataForm.builder(Type.result); TextSingleFormField formField = FormField.buildHiddenFormType("faulty_formtype"); dataFormbuilder.addField(formField); assertThrows(IllegalArgumentException.class, () -> { SoftwareInfoForm.getBuilder().setDataForm(dataFormbuilder.build()).build(); }); DataForm.Builder builderWithoutFormType = DataForm.builder(Type.result); assertThrows(IllegalArgumentException.class, () -> { SoftwareInfoForm.getBuilder().setDataForm(builderWithoutFormType.build()).build(); }); }
Source:
public AbstractSiteMap parseSiteMap(String contentType, byte[] content, URL url) throws UnknownFormatException, IOException { String mimeType = mimeTypeDetector.normalize(contentType, content); if (mimeTypeDetector.isXml(mimeType)) { return processXml(url, content); } else if (mimeTypeDetector.isText(mimeType)) { return processText(url, content); } else if (mimeTypeDetector.isGzip(mimeType)) { try (InputStream decompressed = new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(content)))) { String compressedType = mimeTypeDetector.detect(decompressed); if (mimeTypeDetector.isXml(compressedType)) { return processGzippedXML(url, content); } else if (mimeTypeDetector.isText(compressedType)) { return processText(url, decompressed); } } catch (Exception e) { String msg = String.format("Failed to detect embedded MediaType of gzipped sitemap '%s'", url); throw new UnknownFormatException(msg, e); } } String msg = String.format("Can't parse a sitemap with MediaType '%s' from '%s'", contentType, url); throw new UnknownFormatException(msg); }

Target:
public AbstractSiteMap parseSiteMap(String contentType, byte[] content, URL url) throws UnknownFormatException, IOException { String mimeType = mimeTypeDetector.normalize(contentType, content); if (mimeTypeDetector.isXml(mimeType)) { return processXml(url, content); } else if (mimeTypeDetector.isText(mimeType)) { return processText(url, content); } else if (mimeTypeDetector.isGzip(mimeType)) { try (InputStream decompressed = new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(content)))) { String compressedType = mimeTypeDetector.detect(decompressed); if (mimeTypeDetector.isXml(compressedType)) { return processGzippedXML(url, content); } else if (mimeTypeDetector.isText(compressedType)) { return processText(url, decompressed); } } catch (Exception e) { String msg = String.format(Locale.ROOT, "Failed to detect embedded MediaType of gzipped sitemap '%s'", url); throw new UnknownFormatException(msg, e); } } String msg = String.format(Locale.ROOT, "Can't parse a sitemap with MediaType '%s' from '%s'", contentType, url); throw new UnknownFormatException(msg); }
Source:
private void setUpScrollListener() { historyList.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); ((MainActivity) requireActivity()).updateToolbarElevation(historyList.canScrollVertically(SCROLL_DIRECTION_UP)); } }); }

Target:
private void setUpScrollListener() { historyList.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); ((MainActivity) requireActivity()).updateToolbarElevation(historyList.computeVerticalScrollOffset() != 0); } }); }
Source:
protected void update(IAction action, ISelection s) { getAction().setEnabled(DebugPlugin.getDefault().getBreakpointManager().hasBreakpoints()); }

Target:
protected void update(IAction action, ISelection s) { super.update(action, s); getAction().setEnabled(DebugPlugin.getDefault().getBreakpointManager().hasBreakpoints()); }
Source:
public static int getHeaderBlockEndColumnIndex(final List<GridColumn<?>> allColumns, final GridColumn.HeaderMetaData headerMetaData, final int headerRowIndex, final int headerColumnIndex) { int candidateHeaderColumnIndex = headerColumnIndex; if (candidateHeaderColumnIndex == allColumns.size() - 1) { return candidateHeaderColumnIndex; } if (candidateHeaderColumnIndex >= allColumns.size()) { return candidateHeaderColumnIndex - 1; } while (candidateHeaderColumnIndex < allColumns.size() - 1) { final GridColumn candidateColumn = allColumns.get(candidateHeaderColumnIndex + 1); final List<GridColumn.HeaderMetaData> candidateHeaderMetaData = candidateColumn.getHeaderMetaData(); if (candidateHeaderMetaData.size() - 1 < headerRowIndex) { break; } if (!Objects.equals(candidateHeaderMetaData.get(headerRowIndex), headerMetaData)) { break; } candidateHeaderColumnIndex++; } return candidateHeaderColumnIndex; }

Target:
public static int getHeaderBlockEndColumnIndex(final List<GridColumn<?>> allColumns, final GridColumn.HeaderMetaData headerMetaData, final int headerRowIndex, final int headerColumnIndex) { int candidateHeaderColumnIndex = headerColumnIndex; if (candidateHeaderColumnIndex >= allColumns.size() - 1) { return allColumns.size() - 1; } while (candidateHeaderColumnIndex < allColumns.size() - 1) { final GridColumn candidateColumn = allColumns.get(candidateHeaderColumnIndex + 1); final List<GridColumn.HeaderMetaData> candidateHeaderMetaData = candidateColumn.getHeaderMetaData(); if (candidateHeaderMetaData.size() - 1 < headerRowIndex) { break; } if (!Objects.equals(candidateHeaderMetaData.get(headerRowIndex), headerMetaData)) { break; } candidateHeaderColumnIndex++; } return candidateHeaderColumnIndex; }
Source:
private void doBushGrowth(Vector3i position, BushDefinitionComponent bushComponent, int stages) { EntityRef newBush = null; Map.Entry<String, GrowthStage> stage = null; if (!isInLastStage(bushComponent) || stages < 0) { bushComponent.currentStage += stages; stage = getGrowthStage(bushComponent, bushComponent.currentStage); worldProvider.setBlock(position, blockManager.getBlock(stage.getKey())); newBush = blockEntityRegistry.getBlockEntityAt(position); newBush.addOrSaveComponent(bushComponent); } if( newBush != null && stage.getValue().maxTime > 0 && stage.getValue().minTime > 0) { resetDelay(newBush, stage.getValue().minTime, stage.getValue().maxTime); } }

Target:
private void doBushGrowth(Vector3i position, BushDefinitionComponent bushComponent, int stages) { if (!isInLastStage(bushComponent) || stages < 0) { bushComponent.currentStage += stages; Map.Entry<String, GrowthStage> stage = getGrowthStage(bushComponent, bushComponent.currentStage); worldProvider.setBlock(position, blockManager.getBlock(stage.getKey())); EntityRef newBush = blockEntityRegistry.getBlockEntityAt(position); newBush.addOrSaveComponent(bushComponent); if (stage.getValue().maxTime > 0 && stage.getValue().minTime > 0) { resetDelay(newBush, stage.getValue().minTime, stage.getValue().maxTime); } } }