auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void proposeLeadershipOrWaitForBackoff(LeadershipState currentState) throws InterruptedException { if (pingLeader()) { Thread.sleep(updatePollingRateInMs); return; } boolean learnedNewState = updateLearnedStateFromPeers(currentState.greatestLearnedValue()); if (learnedNewState) { return; } long backoffTime = (long) (randomWaitBeforeProposingLeadership * Math.random()); log.debug("Waited for ms before proposing leadership", SafeArg.of("waitTimeMs", backoffTime)); Thread.sleep(backoffTime); proposeLeadershipAfter(currentState.greatestLearnedValue()); }

Target:
private void proposeLeadershipOrWaitForBackoff(LeadershipState currentState) throws InterruptedException { if (pingLeader()) { Thread.sleep(updatePollingRateInMs); return; } boolean learnedNewState = updateLearnedStateFromPeers(currentState.greatestLearnedValue()); if (learnedNewState) { return; } long backoffTime = (long) (randomWaitBeforeProposingLeadership * Math.random()); log.debug("Waiting for ms before proposing leadership", SafeArg.of("waitTimeMs", backoffTime)); Thread.sleep(backoffTime); proposeLeadershipAfter(currentState.greatestLearnedValue()); }
Source:
private Plugin loadPlugin(File jarFile) throws IOException, ClassNotFoundException { Manifest jarManifest = new JarFile(jarFile).getManifest(); ClassLoader jarClassLoader = URLClassLoader.newInstance(getPluginURLs(jarFile), PluginLoader.class.getClassLoader()); Attributes attrs = jarManifest.getMainAttributes(); String pluginName = attrs.getValue("Gerrit-Plugin"); String moduleName = attrs.getValue("Gerrit-SshModule"); Class<?> moduleClass = jarClassLoader.loadClass(moduleName); return new Plugin(pluginName, moduleClass); }

Target:
private Plugin loadPlugin(File jarFile) throws IOException, ClassNotFoundException { Manifest jarManifest = new JarFile(jarFile).getManifest(); ClassLoader parentLoader = PluginLoader.class.getClassLoader(); ClassLoader jarClassLoader = URLClassLoader.newInstance(getPluginURLs(jarFile), parentLoader); Attributes attrs = jarManifest.getMainAttributes(); String pluginName = attrs.getValue("Gerrit-Plugin"); String moduleName = attrs.getValue("Gerrit-SshModule"); Class<?> moduleClass = Class.forName(moduleName, false, jarClassLoader); return new Plugin(pluginName, moduleClass); }
Source:
public static void main(final String args[]) throws IOException, SignatureException { if (args.length < 2) { System.out.println("Usage: bucketname foldername"); return; } final String bucketname = args[0]; String foldername = args[1]; if (!foldername.endsWith("/")) { foldername += "/"; } try (final Ds3Client client = Ds3ClientBuilder.fromEnv().withHttps(false).build()) { final PutObjectResponse putObjectResponse = client.putObject(new PutObjectRequest(bucketname, foldername, new EmptySeekableByteChannel(), 0L)); } catch (final UnknownHostException e) { System.out.println("Invalid Endpoint Server Name or IP Address"); } catch (final FailedRequestUsingMgmtPortException e) { System.out.println("Attempted data access on management port -- check endpoint"); } catch (final FailedRequestException e) { if (e.getStatusCode() == 403) { System.out.println("ERROR: Invalid Access ID or Secret Key"); } else if (e.getStatusCode() == 409) { System.out.println("ERROR: Object Exists"); } else { System.out.println("BlackPearl returned an unexpected status code"); } } catch (final IOException e) { System.out.println("Encountered a networking error"); } }

Target:
public static void main(final String args[]) throws IOException, SignatureException { if (args.length < 2) { System.out.println("Usage: bucketname foldername"); return; } final String bucketname = args[0]; String foldername = args[1]; if (!foldername.endsWith("/")) { foldername += "/"; } try (final Ds3Client client = Ds3ClientBuilder.fromEnv().withHttps(false).build()) { final PutObjectResponse putObjectResponse = client.putObject(new PutObjectRequest(bucketname, foldername, new EmptySeekableByteChannel(), 0L)); final Ds3ClientHelpers helper = Ds3ClientHelpers.wrap(client); final Iterable<Contents> objects = helper.listObjects(bucketname, foldername); for (final Contents object : objects) { System.out.println("Created folder: " + object.getKey() ); } } catch (final UnknownHostException e) { System.out.println("Invalid Endpoint Server Name or IP Address"); } catch (final FailedRequestUsingMgmtPortException e) { System.out.println("Attempted data access on management port -- check endpoint"); } catch (final FailedRequestException e) { if (e.getStatusCode() == 403) { System.out.println("ERROR: Invalid Access ID or Secret Key"); } else if (e.getStatusCode() == 409) { System.out.println("ERROR: Object Exists"); } else { System.out.println("BlackPearl returned an unexpected status code"); } } catch (final IOException e) { System.out.println("Encountered a networking error"); } }
Source:
public void onChange(Entity oldEntity, Entity newEntity) throws FalconException{ if (oldEntity.getEntityType() != EntityType.PROCESS){ return; } Process newProcess = (Process) newEntity; if (newProcess.getSla() == null || newProcess.getSla().getShouldEndIn() == null){ backlogMetricStore.deleteEntityInstance(newProcess.getName()); entityBacklogs.remove(newProcess); Process process = EntityUtil.getEntity(oldEntity.getEntityType(), oldEntity.getName()); for(Cluster cluster : process.getClusters().getClusters()){ dropMetric(cluster.getName(), process); } }if (newProcess.getSla() != null){ addToBacklog(newEntity); } }

Target:
public void onChange(Entity oldEntity, Entity newEntity) throws FalconException{ if (oldEntity.getEntityType() != EntityType.PROCESS){ return; } Process newProcess = (Process) newEntity; if (newProcess.getSla() == null || newProcess.getSla().getShouldEndIn() == null){ backlogMetricStore.deleteEntityInstance(newProcess.getName()); entityBacklogs.remove(newProcess); Process process = EntityUtil.getEntity(oldEntity.getEntityType(), oldEntity.getName()); for(Cluster cluster : process.getClusters().getClusters()){ dropMetric(cluster.getName(), process); } }else{ addToBacklog(newEntity); } }
Source:
public void rescheduleForRescan() { if ( shouldSchedule && !hasMore ) { lockAnd( t -> { for ( RemoteRepository repo : repoQueue ) { if ( repo.isPrefetchRescan() ) { String rescanTime = repo.getPrefetchRescanTimestamp(); if ( StringUtils.isBlank( rescanTime ) || isNowAfter( rescanTime ) ) { repo.setPrefetchRescanTimestamp( getNextRescanTimeFromNow( config.getRescanIntervalSeconds() ) ); logger.trace( "repo's current rescan time: {}", rescanTime ); logger.trace( "repo's next rescan time: {}", repo.getPrefetchRescanTimestamp() ); final boolean isScheduledRescan = StringUtils.isNotBlank( rescanTime ) && isNowAfter( rescanTime ); if ( isScheduledRescan ) { List<RescanablePath> rootPaths = buildPaths( repo, true ); logger.trace( "Schedule rescan enabled resources: repo: {}, paths {}", repo, rootPaths ); scheduleRepo( repo, rootPaths ); } } break; } } return null; } ); } }

Target:
public void rescheduleForRescan() { if ( shouldSchedule && !hasMore ) { lockAnd( t -> { for ( RemoteRepository repo : repoQueue ) { if ( repo.isPrefetchRescan() ) { String rescanTime = repo.getPrefetchRescanTimestamp(); logger.trace( "repo's current rescan time: {}", rescanTime ); if ( StringUtils.isBlank( rescanTime ) || isNowAfter( rescanTime ) ) { repo.setPrefetchRescanTimestamp( getNextRescanTimeFromNow( config.getRescanIntervalSeconds() ) ); try { storeDataManager.storeArtifactStore( repo, new ChangeSummary( ChangeSummary.SYSTEM_USER, "Update store for prefetch rescan update" ), false, false, new EventMetadata() ); } catch ( IndyDataException e ) { logger.error( String.format( "Can not update store in prefetching rescan for repo: %s", repo ), e ); } logger.trace( "Rescan time set. Repo's next rescan time: {}", repo.getPrefetchRescanTimestamp() ); final boolean isScheduledRescan = StringUtils.isNotBlank( rescanTime ) && isNowAfter( rescanTime ); if ( isScheduledRescan ) { List<RescanablePath> rootPaths = buildPaths( repo, true ); logger.trace( "Schedule rescan enabled resources: repo: {}, paths {}", repo, rootPaths ); scheduleRepo( repo, rootPaths ); } } break; } } return null; } ); } }
Source:
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException { Array array = rs.getArray(columnName); return (array == null || rs.wasNull()) ? null : array.getArray(); }

Target:
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException { Array array = rs.getArray(columnName); return array == null ? null : array.getArray(); }
Source:
private static Multimap<String, String> loadGroups(String groupFilePath) throws ManageUsersException { try { Multimap<String, String> groupsMap = TreeMultimap.create(); String line = null; try (BufferedReader reader = new BufferedReader(new FileReader(groupFilePath))) { while ((line = reader.readLine()) != null) { if (!line.trim().isEmpty()) { String[] u2g = line.split(":"); if (u2g.length == 2) { groupsMap.put(u2g[0].trim(), u2g[1].trim()); } } } } return groupsMap; } catch (IOException e) { exitWithErrorMessage("could not read group file : " + groupFilePath, null, e); } return null; }

Target:
private static Multimap<String, String> loadGroups(String groupFilePath) throws ManageUsersException { Multimap<String, String> groupsMap = TreeMultimap.create(); String line = null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(groupFilePath)))) { while ((line = reader.readLine()) != null) { if (!line.trim().isEmpty()) { String[] u2g = line.split(":"); if (u2g.length == 2) { groupsMap.put(u2g[0].trim(), u2g[1].trim()); } } } } catch (IOException e) { exitWithErrorMessage("could not read group file : " + groupFilePath, null, e); } return groupsMap; }
Source:
private void showLogs(IPod pod, ExecutionEvent event) { if(pod == null){ MessageDialog.openError(HandlerUtil.getActiveShell(event), "No pod selected", "No pod was selected to retrieve a log."); return; } if(!ArrayUtils.contains(STATES, pod.getStatus())) { MessageDialog.openError(HandlerUtil.getActiveShell(event), "Logs Unavailable", NLS.bind("The log is unavailable while the pod is in {0} state.", pod.getStatus())); return; } Collection<IContainer> containers = pod.getContainers(); String containerName = null; if(containers.size() > 1) { List<String> names = containers.stream().map(c->c.getName()).collect(Collectors.toList()); Collections.sort(names); ElementListSelectionDialog dialog = new ElementListSelectionDialog(HandlerUtil.getActiveShell(event), new LabelProvider()); dialog.setElements(names.toArray()); dialog.setTitle("Pod Containers"); dialog.setMessage("Which container logs do you need?"); dialog.setMultipleSelection(false); int result = dialog.open(); if(Window.CANCEL == result) { return; } containerName = (String) dialog.getFirstResult(); }else if (containers.size() == 1){ containerName = containers.iterator().next().getName(); } new PodLogsJob(pod, containerName).schedule(); }

Target:
private void showLogs(IPod pod, ExecutionEvent event) { if(pod == null){ MessageDialog.openError(HandlerUtil.getActiveShell(event), "No pod selected", "No pod was selected to retrieve a log."); return; } if(!ArrayUtils.contains(STATES, pod.getStatus())) { MessageDialog.openError(HandlerUtil.getActiveShell(event), "Logs Unavailable", NLS.bind("The log is unavailable while the pod is in {0} state.", pod.getStatus())); return; } Collection<IContainer> containers = pod.getContainers(); if(containers.isEmpty()) { MessageDialog.openError(HandlerUtil.getActiveShell(event), "Logs Unavailable", "There are no containers from which to retrieve logs"); return; } String containerName = null; if(containers.size() > 1) { List<String> names = containers.stream().map(c->c.getName()).collect(Collectors.toList()); Collections.sort(names); ElementListSelectionDialog dialog = new ElementListSelectionDialog(HandlerUtil.getActiveShell(event), new LabelProvider()); dialog.setElements(names.toArray()); dialog.setTitle("Pod Containers"); dialog.setMessage("Select a pod container"); dialog.setMultipleSelection(false); int result = dialog.open(); if(Window.CANCEL == result) { return; } containerName = (String) dialog.getFirstResult(); }else if (containers.size() == 1){ containerName = containers.iterator().next().getName(); } new PodLogsJob(pod, containerName).schedule(); }
Source:
public void placeNewOrder(Market m, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { Order newOrder; if (orderType == OrderType.BUY) { newOrder = new BuyOrder(symbol, volume, price, this); if ((double)volume * price > cashInHand) { throw new StockMarketExpection("Not enough cash in hand to place buy order."); } } else { newOrder = new SellOrder(symbol, volume, price, this); boolean ownsStock = false; for (Order order: position) { if (order.getStockSymbol() == newOrder.getStockSymbol()) { ownsStock = true; if (order.getSize() < newOrder.getSize()) { throw new StockMarketExpection("You do not own enough stock to place this order."); } } } if (ownsStock == false) { throw new StockMarketExpection("You must own the stock to sell it."); } } boolean alreadyPlacedOrder = false; for (Order order: ordersPlaced) { if (order.getStockSymbol() == newOrder.getStockSymbol()) alreadyPlacedOrder = true; } if (alreadyPlacedOrder) { throw new StockMarketExpection("Cannot place two orders for the same stock."); } ordersPlaced.add(newOrder); m.addOrder(newOrder); }

Target:
public void placeNewOrder(Market m, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { Order newOrder; if (orderType == OrderType.BUY) { newOrder = new BuyOrder(symbol, volume, price, this); if ((double)volume * price > cashInHand) { throw new StockMarketExpection("Not enough cash in hand to place buy order."); } } else { newOrder = new SellOrder(symbol, volume, price, this); boolean ownsStock = false; for (Order order: possession) { if (order.getStockSymbol() == newOrder.getStockSymbol()) { ownsStock = true; if (order.getSize() < newOrder.getSize()) { throw new StockMarketExpection("You do not own enough stock to place this order."); } } } if (ownsStock == false) { throw new StockMarketExpection("You must own the stock to sell it."); } } boolean alreadyPlacedOrder = false; for (Order order: ordersPlaced) { if (order.getStockSymbol() == newOrder.getStockSymbol()) alreadyPlacedOrder = true; } if (alreadyPlacedOrder) { throw new StockMarketExpection("Cannot place two orders for the same stock."); } ordersPlaced.add(newOrder); m.addOrder(newOrder); }
Source:
private Collection<OperatorState> createOperatorState(OperatorID... operatorIds) { Random random = new Random(0x42); Collection<OperatorState> operatorStates = new ArrayList<>(operatorIds.length); for (OperatorID operatorId : operatorIds) { final OperatorState operatorState = new OperatorState(operatorId, 1, 42); final OperatorSubtaskState subtaskState = new OperatorSubtaskState( new OperatorStreamStateHandle(Collections.emptyMap(), new ByteStreamStateHandle("foobar", new byte[0])), null, null, null, singleton(createNewInputChannelStateHandle(10, random)), singleton(createNewResultSubpartitionStateHandle(10, random))); operatorState.putState(0, subtaskState); operatorStates.add(operatorState); } return operatorStates; }

Target:
private Collection<OperatorState> createOperatorState(OperatorID... operatorIds) { Random random = new Random(); Collection<OperatorState> operatorStates = new ArrayList<>(operatorIds.length); for (OperatorID operatorId : operatorIds) { final OperatorState operatorState = new OperatorState(operatorId, 1, 42); final OperatorSubtaskState subtaskState = new OperatorSubtaskState( new OperatorStreamStateHandle(Collections.emptyMap(), new ByteStreamStateHandle("foobar", new byte[0])), null, null, null, singleton(createNewInputChannelStateHandle(10, random)), singleton(createNewResultSubpartitionStateHandle(10, random))); operatorState.putState(0, subtaskState); operatorStates.add(operatorState); } return operatorStates; }
Source:
protected Map<String, String> build( String localModuleId, Node moduleBody, Set<String> knownGoogProvides) { Map<String, String> aliasMap = new HashMap<>(); if (localModuleId == null) { return aliasMap; } for (Node statement : moduleBody.children()) { if (isImportAssignment(statement)) { String importedModuleId = statement.getFirstFirstChild().getChildAtIndex(1).getString(); String variableName = statement.getFirstChild().getString(); String exportedSymbolName = buildWholeModuleExportSymbolName(importedModuleId); aliasMap.put(buildWholeModuleExportSymbolName(localModuleId), exportedSymbolName); aliasMap.put(buildNamedExportSymbolName(localModuleId, variableName), exportedSymbolName); } else if (isImportDestructuringAssignment(statement)) { String importedModuleId = statement.getFirstChild().getChildAtIndex(1).getChildAtIndex(1).getString(); for (Node destructured : statement.getFirstFirstChild().children()) { String originalName = destructured.getString(); String variableName; if (destructured.getFirstChild() != null) { variableName = destructured.getFirstChild().getString(); } else { variableName = originalName; } String exportedSymbolName = buildNamedExportSymbolName(importedModuleId, originalName); aliasMap.put(buildWholeModuleExportSymbolName(localModuleId), exportedSymbolName); aliasMap.put(buildNamedExportSymbolName(localModuleId, variableName), exportedSymbolName); } } } return aliasMap; }

Target:
protected Map<String, String> build( String localModuleId, Node moduleBody, Set<String> knownGoogProvides) { Map<String, String> aliasMap = new HashMap<>(); if (localModuleId == null) { return aliasMap; } for (Node statement : moduleBody.children()) { if (isImportAssignment(statement)) { String importedModuleId = statement.getFirstFirstChild().getChildAtIndex(1).getString(); String variableName = statement.getFirstChild().getString(); String exportedSymbolName = buildWholeModuleExportSymbolName(importedModuleId); aliasMap.putAll( buildNamedAndWholeModuleMappings(localModuleId, variableName, exportedSymbolName)); } else if (isImportDestructuringAssignment(statement)) { String importedModuleId = statement.getFirstChild().getChildAtIndex(1).getChildAtIndex(1).getString(); for (Node destructured : statement.getFirstFirstChild().children()) { String originalName = destructured.getString(); String variableName; if (destructured.getFirstChild() != null) { variableName = destructured.getFirstChild().getString(); } else { variableName = originalName; } String exportedSymbolName = buildNamedExportSymbolName(importedModuleId, originalName); aliasMap.putAll( buildNamedAndWholeModuleMappings(localModuleId, variableName, exportedSymbolName)); } } } return aliasMap; }
Source:
public void run() { mUserAccountRepository.logout( new IRepositoryCallback<Void>() { @Override public void onSuccess(Void result) { mMainExecutor.run(new Runnable() { @Override public void run() { mCallback.onLogoutSuccess(); } }); } @Override public void onError(final Throwable throwable) { mMainExecutor.run(new Runnable() { @Override public void run() { mCallback.onLogoutError(throwable.getMessage()); } }); } }); }

Target:
public void run() { mUserAccountRepository.logout( new IRepositoryCallback<Void>() { @Override public void onSuccess(Void result) { notifyOnLogoutSucces(); } @Override public void onError(Throwable throwable) { notifyOnLogoutError(throwable); } }); }
Source:
public Set<Resource> getHasSelfImplyingProperty(final URI property) { return hasSelfByProperty.get(property); }

Target:
public Set<Resource> getHasSelfImplyingProperty(final URI property) { final Set<Resource> types = new HashSet<>(); final Set<Resource> baseTypes = hasSelfByProperty.get(property); if (baseTypes != null) { types.addAll(baseTypes); for (final Resource baseType : baseTypes) { if (baseType instanceof URI) { types.addAll(findParents(subClassOfGraph, (URI) baseType)); } } } return types; }
Source:
private <T extends ObjectId> void findAllImpl(PackList packList, Collection<T> pending, List<FoundObject<T>> r) { DfsPackFile[] packs = packList.packs; int lastIdx = 0; DfsPackFile lastPack = packs[lastIdx]; boolean noGarbage = avoidUnreachable; OBJECT_SCAN: for (Iterator<T> it = pending.iterator(); it.hasNext();) { T t = it.next(); try { long p = lastPack.findOffset(this, t); if (0 < p) { r.add(new FoundObject<T>(t, lastIdx, lastPack, p)); it.remove(); continue; } } catch (IOException e) { } for (int i = 0; i < packs.length; i++) { if (i == lastIdx) continue; DfsPackFile pack = packs[i]; if (noGarbage && pack.isGarbage()) continue; try { long p = pack.findOffset(this, t); if (0 < p) { r.add(new FoundObject<T>(t, i, pack, p)); it.remove(); lastIdx = i; lastPack = pack; continue OBJECT_SCAN; } } catch (IOException e) { } } } last = lastPack; }

Target:
private <T extends ObjectId> void findAllImpl(PackList packList, Collection<T> pending, List<FoundObject<T>> r) { DfsPackFile[] packs = packList.packs; if (packs.length == 0) { return; } int lastIdx = 0; DfsPackFile lastPack = packs[lastIdx]; boolean noGarbage = avoidUnreachable; OBJECT_SCAN: for (Iterator<T> it = pending.iterator(); it.hasNext();) { T t = it.next(); try { long p = lastPack.findOffset(this, t); if (0 < p) { r.add(new FoundObject<T>(t, lastIdx, lastPack, p)); it.remove(); continue; } } catch (IOException e) { } for (int i = 0; i < packs.length; i++) { if (i == lastIdx) continue; DfsPackFile pack = packs[i]; if (noGarbage && pack.isGarbage()) continue; try { long p = pack.findOffset(this, t); if (0 < p) { r.add(new FoundObject<T>(t, i, pack, p)); it.remove(); lastIdx = i; lastPack = pack; continue OBJECT_SCAN; } } catch (IOException e) { } } } last = lastPack; }
Source:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type, LUNs lun, Guid storagePoolId) { if (Guid.isNullOrEmpty(storagePoolId)) { return new Pair<>(true, null); } if (FeatureSupported.refreshLunSupported(DbFacade.getInstance() .getStoragePoolDao() .get(storagePoolId) .getCompatibilityVersion())) { VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.forValue(type), new StorageServerConnectionManagementVDSParameters(vdsId, storagePoolId, StorageType.FCP, Arrays.asList(getFCPConnection()))); boolean isSuccess = returnValue.getSucceeded(); EngineFault engineFault = null; if (!isSuccess && returnValue.getVdsError() != null) { engineFault = new EngineFault(); engineFault.setError(returnValue.getVdsError().getCode()); } return new Pair<>(isSuccess, engineFault); } else { return new Pair<>(true, null); } }

Target:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type, LUNs lun, Guid storagePoolId) { if (Guid.isNullOrEmpty(storagePoolId) || !FeatureSupported.refreshLunSupported(DbFacade.getInstance() .getStoragePoolDao() .get(storagePoolId) .getCompatibilityVersion())) { return new Pair<>(true, null); } VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.forValue(type), new StorageServerConnectionManagementVDSParameters(vdsId, storagePoolId, StorageType.FCP, Arrays.asList(getFCPConnection()))); boolean isSuccess = returnValue.getSucceeded(); EngineFault engineFault = null; if (!isSuccess && returnValue.getVdsError() != null) { engineFault = new EngineFault(); engineFault.setError(returnValue.getVdsError().getCode()); } return new Pair<>(isSuccess, engineFault); }
Source:
private static Cluster createClusterWithNoCpuName() { Cluster group = new Cluster(); group.setName("Default"); group.setCpuName(""); group.setId(DEFAULT_CLUSTER_ID); group.setCompatibilityVersion(VERSION_1_1); group.setStoragePoolId(DC_ID1); group.setArchitecture(ArchitectureType.undefined); group.setClusterPolicyId(Guid.newGuid()); group.setMaxVdsMemoryOverCommit(100); group.setBiosType(BiosType.CLUSTER_DEFAULT); return group; }

Target:
private static Cluster createClusterWithNoCpuName() { Cluster group = new Cluster(); group.setName("Default"); group.setCpuName(""); group.setId(DEFAULT_CLUSTER_ID); group.setCompatibilityVersion(VERSION_1_1); group.setStoragePoolId(DC_ID1); group.setArchitecture(ArchitectureType.undefined); group.setClusterPolicyId(Guid.newGuid()); group.setMaxVdsMemoryOverCommit(100); return group; }
Source:
public Object getMetadata(@NonNull String section, @NonNull String key) { if (section != null && key != null) { return impl.getMetadata(section, key); } else { error("getMetadata"); return null; } }

Target:
public Object getMetadata(@NonNull String section, @NonNull String key) { if (section != null && key != null) { return impl.getMetadata(section, key); } else { logNull("getMetadata"); return null; } }
Source:
public void adjust(Mechanism mechanism) { if (mechanism.matches("max_fuse_ticks") && entity.getBukkitEntity() instanceof Creeper && mechanism.requireInteger()) { ((Creeper) entity.getBukkitEntity()).setMaxFuseTicks(mechanism.getValue().asInt()); } }

Target:
public void adjust(Mechanism mechanism) { if (mechanism.matches("max_fuse_ticks") && mechanism.requireInteger()) { ((Creeper) entity.getBukkitEntity()).setMaxFuseTicks(mechanism.getValue().asInt()); } }
Source:
public Header.Reader headerReader( Function<ByteBuffer,String> onError ) { return headerBytes -> { byte state = headerBytes.get(); if ( state == BYTE_FAILED ) { this.failureMessage = "Unexpectedly trying to read the header of a failed index: " + onError.apply( headerBytes ); } else { this.failureMessage = null; int typeId = headerBytes.getInt(); SpatialIndexType indexType = SpatialIndexType.get( typeId ); if ( indexType == null ) { this.failureMessage = "Unknown spatial index type in index header: " + typeId; } indexType.readHeader( SpaceFillingCurveSettings.this, headerBytes ); } }; }

Target:
public Header.Reader headerReader( Function<ByteBuffer,String> onError ) { return headerBytes -> { byte state = headerBytes.get(); if ( state == BYTE_FAILED ) { this.failureMessage = "Unexpectedly trying to read the header of a failed index: " + onError.apply( headerBytes ); } else { int typeId = headerBytes.getInt(); SpatialIndexType indexType = SpatialIndexType.get( typeId ); if ( indexType == null ) { markAsFailed( "Unknown spatial index type in index header: " + typeId ); } else { markAsSucceeded(); indexType.readHeader( SpaceFillingCurveSettings.this, headerBytes ); } } }; }
Source:
protected void updateReadOnlyChangeability() { DiskInterface diskInterface = getDiskInterface().getSelectedItem(); if (diskInterface == DiskInterface.IDE) { getIsReadOnly().setChangeProhibitionReason(CONSTANTS.cannotEnableIdeInterfaceForReadOnlyDisk()); getIsReadOnly().setIsChangable(false); getIsReadOnly().setEntity(false); return; } boolean isVirtIoScsiLun = Boolean.FALSE.equals(getIsInternal().getEntity()) && diskInterface == DiskInterface.VirtIO_SCSI; if (isVirtIoScsiLun) { getIsReadOnly().setChangeProhibitionReason(CONSTANTS.cannotEnableVirtIoScsiInterfaceForLunReadOnlyDisk()); getIsReadOnly().setIsChangable(false); getIsReadOnly().setEntity(false); return; } getIsReadOnly().setIsChangable(isEditEnabled()); }

Target:
protected void updateReadOnlyChangeability() { DiskInterface diskInterface = getDiskInterface().getSelectedItem(); if (diskInterface == DiskInterface.IDE) { getIsReadOnly().setChangeProhibitionReason(CONSTANTS.cannotEnableIdeInterfaceForReadOnlyDisk()); getIsReadOnly().setIsChangable(false); getIsReadOnly().setEntity(false); return; } boolean isDirectLUN = Boolean.FALSE.equals(getIsInternal().getEntity()); if (diskInterface == DiskInterface.VirtIO_SCSI && isDirectLUN) { getIsReadOnly().setChangeProhibitionReason(CONSTANTS.cannotEnableVirtIoScsiInterfaceForLunReadOnlyDisk()); getIsReadOnly().setIsChangable(false); getIsReadOnly().setEntity(false); return; } getIsReadOnly().setIsChangable(isEditEnabled()); }
Source:
public static FinishedSpanHandler create(List<FinishedSpanHandler> handlers, AtomicBoolean noop) { if (handlers.isEmpty()) return FinishedSpanHandler.NOOP; if (handlers.size() == 1) { FinishedSpanHandler onlyHandler = handlers.get(0); return onlyHandler == FinishedSpanHandler.NOOP ? onlyHandler : new Single(onlyHandler, noop); } int i = 0; boolean alwaysSampleLocal = false, supportsOrphans = false; FinishedSpanHandler[] copy = new FinishedSpanHandler[handlers.size()]; for (FinishedSpanHandler handler : handlers) { if (handler.alwaysSampleLocal()) alwaysSampleLocal = true; if (handler.supportsOrphans()) supportsOrphans = true; copy[i++] = handler; } return new Multiple(copy, noop, alwaysSampleLocal, supportsOrphans); }

Target:
public static FinishedSpanHandler create(List<FinishedSpanHandler> handlers, AtomicBoolean noop) { if (handlers.isEmpty()) return FinishedSpanHandler.NOOP; if (handlers.size() == 1) { FinishedSpanHandler onlyHandler = handlers.get(0); return onlyHandler == FinishedSpanHandler.NOOP ? onlyHandler : new Single(onlyHandler, noop); } boolean alwaysSampleLocal = false, supportsOrphans = false; for (FinishedSpanHandler handler : handlers) { if (handler.alwaysSampleLocal()) alwaysSampleLocal = true; if (handler.supportsOrphans()) supportsOrphans = true; } return new Multiple(handlers, noop, alwaysSampleLocal, supportsOrphans); }
Source:
protected InputStream getAsInputStreamFromClassLoader(String filename) { ClassLoader cl = getClass().getClassLoader(); InputStream is; try { is = cl == null ? null : cl.getResourceAsStream(filename); } catch (RuntimeException re) { is = null; } if (is == null) { try { is = getClass().getClassLoader().getResourceAsStream(filename); } catch (RuntimeException re) { is = null; } } return is; }

Target:
private InputStream getAsInputStreamFromClassLoader(String filename) { ClassLoader cl = getClass().getClassLoader(); InputStream is; try { is = cl == null ? null : cl.getResourceAsStream(filename); } catch (RuntimeException re) { is = null; } if (is == null) { try { is = getClass().getClassLoader().getResourceAsStream(filename); } catch (RuntimeException re) { is = null; } } return is; }
Source:
public AsyncFSStorageAgent(String path, Configuration conf) { super(path, conf); try { File tempFile = File.createTempFile("chkp", null); tempFile.delete(); tempFile.mkdir(); this.localBasePath = tempFile.getAbsolutePath(); } catch (IOException ex) { throw new RuntimeException(ex); } logger.info("using as the basepath for checkpointing.", this.localBasePath); this.conf = conf == null ? new Configuration() : conf; }

Target:
public AsyncFSStorageAgent(String path, Configuration conf) { super(path, conf); try { this.localBasePath = Files.createTempDirectory("chkp").toString(); } catch (IOException ex) { throw new RuntimeException(ex); } logger.info("using as the basepath for checkpointing.", this.localBasePath); this.conf = conf == null ? new Configuration() : conf; }
Source:
public void testDoubleComparison() { List<Double> values = ImmutableList.of( Double.NEGATIVE_INFINITY, -456.78, -123.45, -0.0, 0.0, 123.45, 456.78, Double.POSITIVE_INFINITY, Double.NaN); List<Double> sorted = values.stream() .sorted(comparingLong(FloatingPointUtil::doubleToSortableLong)) .collect(toList()); assertEquals(sorted, values); }

Target:
public void testDoubleComparison() { List<Double> expected = ImmutableList.of( Double.NEGATIVE_INFINITY, -456.78, -123.45, -0.0, 0.0, 123.45, 456.78, Double.POSITIVE_INFINITY, Double.NaN); List<Double> values = new ArrayList<>(expected); shuffle(values); values.sort(comparingLong(FloatingPointUtil::doubleToSortableLong)); assertEquals(values, expected); }
Source:
public Property(String humanName, ExecutableElement element) { this.methodName = element.getSimpleName().toString(); this.humanName = humanName; this.element = element; type = TypeName.get(element.getReturnType()); annotations = buildAnnotations(element); typeAdapter = getAnnotationValue(element, GsonTypeAdapter.class); TypeMirror returnType = element.getReturnType(); instanceOfOptional = !TypeKind.TYPEVAR.equals(returnType.getKind()) && (MoreTypes.isTypeOf(Optional.class, returnType) || MoreTypes.isTypeOf(com.google.common.base.Optional.class, returnType)); }

Target:
public Property(String humanName, ExecutableElement element) { this.methodName = element.getSimpleName().toString(); this.humanName = humanName; this.element = element; type = TypeName.get(element.getReturnType()); annotations = buildAnnotations(element); typeAdapter = getAnnotationValue(element, GsonTypeAdapter.class); instanceOfOptional = isOptional(element.getReturnType()); }
Source:
public UpdateRequest processPreUpdate( UpdateRequest input, Map<String, Metacard> existingMetacards) throws StopProcessingException { Function<Metacard, Metacard> oldMetacard = update -> Optional.ofNullable(existingMetacards.get(update.getId())).orElse(null); List<Metacard> newMetacards = input.getUpdates().stream().map(Map.Entry::getValue).collect(Collectors.toList()); if (newMetacards.stream().anyMatch(m -> isOwnerChanged(oldMetacard.apply(m), m))) { throw new StopProcessingException(FAILURE_OWNER_CANNOT_CHANGE); } if (newMetacards .stream() .filter( newVersionOfMetacard -> isAccessControlUpdated( oldMetacard.apply(newVersionOfMetacard), newVersionOfMetacard)) .filter(Objects::nonNull) .map(oldMetacard) .filter(subjectIsNotOwner) .anyMatch(subjectIsNotAccessAdmin)) { throw new StopProcessingException(FAILURE_NOT_ADMIN_OR_OWNER); } return input; }

Target:
public UpdateRequest processPreUpdate( UpdateRequest input, Map<String, Metacard> existingMetacards) throws StopProcessingException { Map<String, Metacard> filteredExistingMetacards = existingMetacards .values() .stream() .filter(hasIntrigueTag) .collect(Collectors.toMap(Metacard::getId, Function.identity())); Function<Metacard, Metacard> oldMetacard = update -> Optional.ofNullable(update.getId()).map(filteredExistingMetacards::get).orElse(null); List<Metacard> newMetacards = input.getUpdates().stream().map(Map.Entry::getValue).collect(Collectors.toList()); if (newMetacards.stream().anyMatch(m -> isOwnerChanged(oldMetacard.apply(m), m))) { throw new StopProcessingException(FAILURE_OWNER_CANNOT_CHANGE); } if (newMetacards .stream() .filter( newVersionOfMetacard -> isAccessControlUpdated( oldMetacard.apply(newVersionOfMetacard), newVersionOfMetacard)) .filter(Objects::nonNull) .map(oldMetacard) .filter(Objects::nonNull) .filter(subjectIsNotOwner) .anyMatch(subjectIsNotAccessAdmin)) { throw new StopProcessingException(FAILURE_NOT_ADMIN_OR_OWNER); } return input; }
Source:
private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { final Map<AliasedMappedProperty, Object> columnToValue = new TreeMap<AliasedMappedProperty, Object>(new AliasedMappedPropertyComparator()); final boolean useUnsetForNullValue = !shouldSaveNullFields(options) && manager.protocolVersionAsInt >= 4; final boolean includeColumnsWithNullValue = shouldSaveNullFields(options) || useUnsetForNullValue; for (AliasedMappedProperty col : mapper.allColumns) { Object value = col.mappedProperty.getValue(entity); if (!col.mappedProperty.isComputed() && (includeColumnsWithNullValue || value != null)) { columnToValue.put(col, value); } } return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, columnToValue.keySet(), options), new Function<PreparedStatement, BoundStatement>() { @Override public BoundStatement apply(PreparedStatement input) { BoundStatement bs = input.bind(); int i = 0; for (Map.Entry<AliasedMappedProperty, Object> entry : columnToValue.entrySet()) { AliasedMappedProperty mapper = entry.getKey(); Object value = entry.getValue(); setObject(bs, i++, value, mapper, useUnsetForNullValue); } if (mapper.writeConsistency != null) bs.setConsistencyLevel(mapper.writeConsistency); for (Option option : options.values()) { option.validate(QueryType.SAVE, manager); i = option.apply(bs, i); } return bs; } }); }

Target:
private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { final Map<AliasedMappedProperty, Object> columnToValue = new TreeMap<AliasedMappedProperty, Object>(); final boolean useUnsetForNullValue = !shouldSaveNullFields(options) && manager.protocolVersionAsInt >= 4; final boolean includeColumnsWithNullValue = shouldSaveNullFields(options) || useUnsetForNullValue; for (AliasedMappedProperty col : mapper.allColumns) { Object value = col.mappedProperty.getValue(entity); if (!col.mappedProperty.isComputed() && (includeColumnsWithNullValue || value != null)) { columnToValue.put(col, value); } } return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, columnToValue.keySet(), options), new Function<PreparedStatement, BoundStatement>() { @Override public BoundStatement apply(PreparedStatement input) { BoundStatement bs = input.bind(); int i = 0; for (Map.Entry<AliasedMappedProperty, Object> entry : columnToValue.entrySet()) { AliasedMappedProperty mapper = entry.getKey(); Object value = entry.getValue(); setObject(bs, i++, value, mapper, useUnsetForNullValue); } if (mapper.writeConsistency != null) bs.setConsistencyLevel(mapper.writeConsistency); for (Option option : options.values()) { option.validate(QueryType.SAVE, manager); i = option.apply(bs, i); } return bs; } }); }
Source:
private LambdaEvent createBasicEvent(String repository, String gitReference, String username, String installationId, LambdaEvent.LambdaEventType type) { LambdaEvent lambdaEvent = new LambdaEvent(); lambdaEvent.setRepository(repository); lambdaEvent.setReference(gitReference); lambdaEvent.setUsername(username); lambdaEvent.setType(type); lambdaEvent.setInstallationId(installationId); Optional<User> user = Optional.ofNullable(userDAO.findByGitHubUsername(username)); user.ifPresent(lambdaEvent::setUser); return lambdaEvent; }

Target:
private LambdaEvent createBasicEvent(String repository, String gitReference, String username, String installationId, LambdaEvent.LambdaEventType type) { LambdaEvent lambdaEvent = new LambdaEvent(); lambdaEvent.setRepository(repository); lambdaEvent.setReference(gitReference); lambdaEvent.setGithubUsername(username); lambdaEvent.setType(type); User user = userDAO.findByGitHubUsername(username); if (user != null) { lambdaEvent.setUser(user); } return lambdaEvent; }
Source:
public void setSealedState(boolean isSealed) { this.isSealed = isSealed; }

Target:
void setSealedState(boolean isSealed) { this.isSealed = isSealed; }
Source:
@OnClick void onClick(View view) { if (callback != null && entry != null && card != null) { callback.onSelectPage(card, entry, TransitionUtil.getSharedElements(getContext(), titleView, subtitleView, imageView)); } }

Target:
@OnClick void onClick(View view) { if (callback != null && entry != null && card != null) { callback.onSelectPage(card, entry, TransitionUtil.getSharedElements(getContext(), imageView)); } }
Source:
public TestNumberedScoreBoardEventProviderImpl(TestScoreBoardEventProvider parent, int number) { super(parent, number, TestScoreBoardEventProvider.NChild.NUMBERED, TestNumberedScoreBoardEventProvider.class, Value.class, Child.class); if (parent instanceof TestNumberedScoreBoardEventProvider) { setCopy(Value.RO_DIRECT_COPY, parent, TestNumberedScoreBoardEventProvider.Value.INT, true); setCopy(Value.RW_DIRECT_COPY, parent, TestNumberedScoreBoardEventProvider.Value.INT, false); } else { setCopy(Value.RO_DIRECT_COPY, parent, TestScoreBoardEventProvider.Value.INT, true); setCopy(Value.RW_DIRECT_COPY, parent, TestScoreBoardEventProvider.Value.INT, false); } }

Target:
public TestNumberedScoreBoardEventProviderImpl(TestScoreBoardEventProvider parent, int number) { super(parent, number, TestScoreBoardEventProvider.NChild.NUMBERED, TestNumberedScoreBoardEventProvider.class, Value.class, Child.class); setCopy(Value.RO_DIRECT_COPY, parent, TestScoreBoardEventProvider.Value.INT, true); setCopy(Value.RW_DIRECT_COPY, parent, TestScoreBoardEventProvider.Value.INT, false); }
Source:
public List<TransactionSigner> getTransactionSigners() { return signers; }

Target:
public List<TransactionSigner> getTransactionSigners() { lock.lock(); try { return ImmutableList.copyOf(signers); } finally { lock.unlock(); } }
Source:
private boolean replaceFilePathsWithBytes(ModelNode request) throws CommandFormatException, IOException { boolean didReplacement = false; ModelNode opDesc = request.clone(); String opName = opDesc.get("operation").asString(); opDesc.get("operation").set("read-operation-description"); opDesc.get("name").set(opName); ModelNode response = execute(opDesc, false); ModelNode requestProps = response.get("result", "request-properties"); for (Property prop : requestProps.asPropertyList()) { if (ModelType.valueOf(prop.getValue().get("type").asString()) == ModelType.BYTES) { String filePath = request.get(prop.getName()).asString(); File localFile = new File(filePath); try { request.get(prop.getName()).set(Util.readBytes(localFile)); didReplacement = true; } catch (OperationFormatException e) { throw new CommandFormatException(e); } } } return didReplacement; }

Target:
private boolean replaceFilePathsWithBytes(ModelNode request) throws CommandFormatException, IOException { boolean didReplacement = false; ModelNode opDesc = request.clone(); String opName = opDesc.get("operation").asString(); opDesc.get("operation").set("read-operation-description"); opDesc.get("name").set(opName); ModelNode response = execute(opDesc, false); ModelNode requestProps = response.get("result", "request-properties"); for (Property prop : requestProps.asPropertyList()) { ModelNode typeDesc = prop.getValue().get("type"); if (typeDesc.getType() == ModelType.TYPE && typeDesc.asType() == ModelType.BYTES) { String filePath = request.get(prop.getName()).asString(); File localFile = new File(filePath); try { request.get(prop.getName()).set(Util.readBytes(localFile)); didReplacement = true; } catch (OperationFormatException e) { throw new CommandFormatException(e); } } } return didReplacement; }
Source:
public Block[] getSequenceBlocks(int start, int length) { int sequenceLength = 2 * length; BlockBuilder samplesBuilder = DOUBLE.createBlockBuilder(null, sequenceLength); BlockBuilder weightsBuilder = DOUBLE.createBlockBuilder(null, sequenceLength); for (int weight = 1; weight < 3; ++weight) { for (int i = start; i < start + length; i++) { DOUBLE.writeDouble(samplesBuilder, Double.valueOf(i)); DOUBLE.writeDouble(weightsBuilder, Double.valueOf(weight)); } } return new Block[] { createRLEBlock(TestReservoirAggregation.SIZE, sequenceLength), samplesBuilder.build(), weightsBuilder.build() }; }

Target:
public Block[] getSequenceBlocks(int start, int length) { int positionCount = 2 * length; BlockBuilder samples = DOUBLE.createBlockBuilder(null, positionCount); BlockBuilder weights = DOUBLE.createBlockBuilder(null, positionCount); for (int weight = 1; weight < 3; weight++) { for (int i = start; i < start + length; i++) { DOUBLE.writeDouble(samples, i); DOUBLE.writeDouble(weights, weight); } } return new Block[] { createRLEBlock(MAX_SAMPLES, positionCount), samples.build(), weights.build() }; }
Source:
protected void startMachines() throws InfrastructureException { KubernetesEnvironment k8sEnv = getContext().getEnvironment(); List<Service> createdServices = new ArrayList<>(); for (Service service : k8sEnv.getServices().values()) { createdServices.add(namespace.services().create(service)); } List<Ingress> readyIngresses = createAndWaitReady(k8sEnv.getIngresses().values()); if (failFastOnUnrecoverableEvents) { namespace.pods().watchContainers(new UnrecoverableEventHanler()); } final KubernetesServerResolver serverResolver = new KubernetesServerResolver(createdServices, readyIngresses); doStartMachine(serverResolver); }

Target:
protected void startMachines() throws InfrastructureException { KubernetesEnvironment k8sEnv = getContext().getEnvironment(); List<Service> createdServices = new ArrayList<>(); for (Service service : k8sEnv.getServices().values()) { createdServices.add(namespace.services().create(service)); } List<Ingress> readyIngresses = createAndWaitReady(k8sEnv.getIngresses().values()); namespace.pods().watchContainers(new MachineLogsPublisher()); if (!Strings.isNullOrEmpty(unrecoverableEvents)) { namespace.pods().watchContainers(new UnrecoverableEventHanler()); } final KubernetesServerResolver serverResolver = new KubernetesServerResolver(createdServices, readyIngresses); doStartMachine(serverResolver); }
Source:
private boolean operationHasRepresentationParam(Operation o) { boolean ret = false; for (Parameter p : o.getParameters()) { if (p.getName().equals("v")) { ret = true; } } return ret; }

Target:
private boolean operationHasRepresentationParam(Operation o) { boolean ret = false; for (Parameter p : o.getParameters()) { if (p.getName().equals("v")) { ret = !ret; } } return ret; }
Source:
public void searchesBouts() throws Exception { final String urn = "urn:test:2"; final MkBase base = new MkBase(); final Aliases aliases = base.user(new URN(urn)).aliases(); aliases.add("test2"); final Inbox inbox = aliases.iterate().iterator().next().inbox(); final Bout firstbout = inbox.bout(inbox.start()); final String firsttitle = "bout1 title"; firstbout.rename(firsttitle); final Bout secbout = inbox.bout(inbox.start()); final String sectitle = "bout2 title"; secbout.rename(sectitle); firstbout.messages().post("hello"); secbout.messages().post("world"); final String body = new RsPrint( new TkAuth( new TkInbox(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, String.format( "/search?q=%s", "r" ) ) ) ).printBody(); MatcherAssert.assertThat( body, Matchers.containsString(sectitle) ); MatcherAssert.assertThat( body, Matchers.not(Matchers.containsString(firsttitle)) ); }

Target:
public void searchesBouts() throws Exception { final String urn = "urn:test:2"; final MkBase base = new MkBase(); final Aliases aliases = base.user(new URN(urn)).aliases(); aliases.add("test2"); final Inbox inbox = aliases.iterate().iterator().next().inbox(); final Bout first = inbox.bout(inbox.start()); final String firsttitle = "bout1 title"; first.rename(firsttitle); final Bout second = inbox.bout(inbox.start()); final String secondtitle = "bout2 title"; second.rename(secondtitle); first.messages().post("hello"); second.messages().post("world"); final String body = new RsPrint( new TkAuth( new TkInbox(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, String.format( "/search?q=%s", "r" ) ) ) ).printBody(); MatcherAssert.assertThat( body, Matchers.containsString(secondtitle) ); MatcherAssert.assertThat( body, Matchers.not(Matchers.containsString(firsttitle)) ); }
Source:
public Class<?> createExtensionClass(Class<?> cls, QName qname, ClassLoader loader) { try { return ClassLoaderUtils.loadClass(cls.getName() + "Extensibility", ExtensionClassLoader.class); } catch (ClassNotFoundException e) { } return null; }

Target:
public Class<?> createExtensionClass(Class<?> cls, QName qname, ClassLoader loader) { return findClass(cls.getName() + "Extensibility", ExtensionClassLoader.class); }
Source:
public void accept(final FeedRangeVisitor visitor) { if (visitor == null) { throw new NullPointerException("visitor"); } visitor.visit(this); }

Target:
public void accept(final FeedRangeVisitor visitor) { checkNotNull(visitor, "Argument 'visitor' must not be null"); visitor.visit(this); }