auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
@Test public void secretListingBatch_failure() throws Exception { Request get = clientRequest(String.format("/automation/v2/secrets/batch/%d-%d", -1, 3)).get().build(); Response httpResponse = mutualSslClient.newCall(get).execute(); assertThat(httpResponse.code()).isEqualTo(400); get = clientRequest(String.format("/automation/v2/secrets/batch/%d-%d", 0, -3)).get().build(); httpResponse = mutualSslClient.newCall(get).execute(); assertThat(httpResponse.code()).isEqualTo(404); }

Target:
@Test public void secretListingBatch_failure() throws Exception { Request get = clientRequest(String.format("/automation/v2/secrets?idx=%d&num=%d&newestFirst=%s", -1, 3, false)).get().build(); Response httpResponse = mutualSslClient.newCall(get).execute(); assertThat(httpResponse.code()).isEqualTo(400); get = clientRequest(String.format("/automation/v2/secrets?idx=%d&num=%d&newestFirst=%s", 0, -3, true)).get().build(); httpResponse = mutualSslClient.newCall(get).execute(); assertThat(httpResponse.code()).isEqualTo(400); get = clientRequest(String.format("/automation/v2/secrets/v2?idx=%d&num=%d&newestFirst=%s", -1, 3, false)).get().build(); httpResponse = mutualSslClient.newCall(get).execute(); assertThat(httpResponse.code()).isEqualTo(400); get = clientRequest(String.format("/automation/v2/secrets/v2?idx=%d&num=%d&newestFirst=%s", 0, -3, true)).get().build(); httpResponse = mutualSslClient.newCall(get).execute(); assertThat(httpResponse.code()).isEqualTo(400); }
Source:
public int compareTo(StoreKey o) { BlobId other = (BlobId) o; int result = version.compareTo(other.version); if (result == 0) { result = flag.compareTo(other.flag); if (result == 0) { result = datacenterId.compareTo(other.datacenterId); if (result == 0) { result = accountId.compareTo(other.accountId); if (result == 0) { result = containerId.compareTo(other.containerId); if (result == 0) { result = partitionId.compareTo(other.partitionId); if (result == 0) { result = uuid.compareTo(other.uuid); } } } } } } return result; }

Target:
public int compareTo(StoreKey o) { BlobId other = (BlobId) o; int result = version.compareTo(other.version); if (result == 0) { switch (version) { case BLOB_ID_V1: result = partitionId.compareTo(other.partitionId); if (result == 0) { result = uuid.compareTo(other.uuid); } break; case BLOB_ID_V2: result = flag.compareTo(other.flag); if (result == 0) { result = datacenterId.compareTo(other.datacenterId); if (result == 0) { result = accountId.compareTo(other.accountId); if (result == 0) { result = containerId.compareTo(other.containerId); if (result == 0) { result = partitionId.compareTo(other.partitionId); if (result == 0) { result = uuid.compareTo(other.uuid); } } } } } break; default: throw new IllegalArgumentException("Unrecognized blobId version " + version); } } return result; }
Source:
public void jobSucceeded(final UUID reportId, final Organization organization, final Instant scheduled, final Report.Result result) { assertIsOpen(); if (!(result instanceof DefaultReportResult)) { throw new UnsupportedOperationException("Unsupported result type"); } final DefaultReportResult resultImpl = (DefaultReportResult) result; updateExecutionState( reportId, organization, scheduled, ReportExecution.State.SUCCESS, execution -> { execution.setCompletedAt(Instant.now()); execution.setResult(resultImpl); } ); }

Target:
public void jobSucceeded(final UUID reportId, final Organization organization, final Instant scheduled, final Report.Result result) { assertIsOpen(); updateExecutionState( reportId, organization, scheduled, ReportExecution.State.SUCCESS, result, null ); }
Source:
public static IPackageFragment[] getPackageAndSubpackages(IPackageFragment pack) throws JavaModelException { if (pack.isDefaultPackage()) return new IPackageFragment[] { pack }; IPackageFragmentRoot root= (IPackageFragmentRoot) pack.getParent(); ArrayList<IPackageFragment> subpackages= new ArrayList<>(); subpackages.add(pack); String prefix= pack.getElementName() + '.'; for (IJavaElement allPackage : root.getChildren()) { IPackageFragment currentPackage = (IPackageFragment) allPackage; if (currentPackage.getElementName().startsWith(prefix)) subpackages.add(currentPackage); } return subpackages.toArray(new IPackageFragment[subpackages.size()]); }

Target:
public static IPackageFragment[] getPackageAndSubpackages(IPackageFragment pack) throws JavaModelException { if (pack.isDefaultPackage()) return new IPackageFragment[] { pack }; IPackageFragmentRoot root= (IPackageFragmentRoot) pack.getParent(); ArrayList<IPackageFragment> subpackages= new ArrayList<>(); subpackages.add(pack); String prefix= pack.getElementName() + '.'; for (IJavaElement packageFragment : root.getChildren()) { IPackageFragment currentPackage = (IPackageFragment) packageFragment; if (currentPackage.getElementName().startsWith(prefix)) subpackages.add(currentPackage); } return subpackages.toArray(new IPackageFragment[subpackages.size()]); }
Source:
protected String createPayload(Volume.Request.CreatePayload payload) { dataCenterId = payload.dataCenterId(); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("size", payload.size()); if (payload.name() != null) properties.put("name", payload.name()); if (payload.bus() != null) properties.put("bus", payload.bus()); if (payload.type() != null) properties.put("type", payload.type()); if (payload.imagePassword() != null) properties.put("imagePassword", payload.imagePassword()); if (payload.image() != null) properties.put("image", payload.image()); else if (payload.licenceType() != null) properties.put("licenceType", payload.licenceType()); requestBuilder.put("properties", properties); return (new Gson()).toJson(requestBuilder); }

Target:
protected String createPayload(Volume.Request.CreatePayload payload) { checkNotNull(payload.dataCenterId(), "dataCenterId"); dataCenterId = payload.dataCenterId(); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("size", payload.size()); if (payload.name() != null) properties.put("name", payload.name()); if (payload.bus() != null) properties.put("bus", payload.bus()); if (payload.type() != null) properties.put("type", payload.type()); if (payload.imagePassword() != null) properties.put("imagePassword", payload.imagePassword()); if (payload.image() != null) properties.put("image", payload.image()); else if (payload.licenceType() != null) properties.put("licenceType", payload.licenceType()); requestBuilder.put("properties", properties); return jsonBinder.toJson(requestBuilder); }
Source:
private static List<HostAddress> getHostAddresses(BlockLocation blockLocation) { ImmutableList.Builder<HostAddress> builder = ImmutableList.builder(); String[] hosts; try { hosts = blockLocation.getHosts(); } catch (IOException e) { throw new UncheckedIOException(e); } for (String host : hosts) { builder.add(HostAddress.fromString(host)); } return builder.build(); }

Target:
private static List<HostAddress> getHostAddresses(BlockLocation blockLocation) { String[] hosts; try { hosts = blockLocation.getHosts(); } catch (IOException e) { throw new UncheckedIOException(e); } return Arrays.stream(hosts) .map(HostAddress::fromString) .collect(toImmutableList()); }
Source:
public void publish(String topic, Integer qos, byte[] payload) throws MqttPersistenceException, MqttException { MqttMessage message = null; if (client == null || !client.isConnected()) { connect(url); } message = new MqttMessage(payload); message.setQos(qos); String time = new Timestamp(System.currentTimeMillis()).toString(); log.info("Publishing at: " + time + " to topic \"" + topic + "\" qos " + qos); client.publish(topic, message, "Pub sample context", this); }

Target:
public void publish(String topic, Integer qos, byte[] payload) throws MqttPersistenceException, MqttException { MqttMessage message = null; if (client == null || !client.isConnected()) { connect(url); } message = new MqttMessage(payload); message.setQos(qos); String time = new Timestamp(System.currentTimeMillis()).toString(); log.info("Publishing at: " + time + " to topic \"" + topic + "\" qos " + qos); client.publish(topic, message, userContext, this); }
Source:
public PrestoThriftService anyHostClient() { return new RetryingService(() -> (DefaultPrestoThriftService) original.anyHostClient(), retry); }

Target:
public PrestoThriftService anyHostClient() { return new RetryingService(original::anyHostClient, retry, stats); }
Source:
public ExecutePlanningResult executePlanning(PlanningItemList planningItemList, String userId) { if (config.isRest()) { final String uri = TASK_ASSIGNING_RUNTIME_URI + "/" + TASK_ASSIGNING_EXECUTE_PLANNING_URI + "?user=" + userId; return makeHttpPostRequestAndCreateCustomResponse(RestURI.build(loadBalancer.getUrl(), uri, Collections.emptyMap()), planningItemList, ExecutePlanningResult.class); } else { throw new KieServicesException("JMS protocol is not implemented for this service."); } }

Target:
public PlanningExecutionResult executePlanning(PlanningItemList planningItemList, String userId) { if (config.isRest()) { final String uri = TASK_ASSIGNING_RUNTIME_URI + "/" + TASK_ASSIGNING_EXECUTE_PLANNING_URI + "?user=" + userId; return makeHttpPostRequestAndCreateCustomResponse(RestURI.build(loadBalancer.getUrl(), uri, Collections.emptyMap()), planningItemList, PlanningExecutionResult.class); } else { throw new KieServicesException("JMS protocol is not implemented for this service."); } }
Source:
protected String getServerAddress(final Server server) { final String ipAddress = (UtilMethods.isSet(server.getHost()) && !server.getHost().equals("localhost")) ? server.getHost() : server.getIpAddress(); final String port = Integer.toString(server.getEsTransportTcpPort()); return ipAddress + ":" + port; }

Target:
protected String getServerAddress(final Server server) { final String ipAddress = (UtilMethods.isSet(server.getHost()) && !server.getHost().equals("localhost")) ? server.getHost() : server.getIpAddress(); final String port = Integer.toString(server.getEsTransportTcpPort()); return ipAddress + StringPool.COLON + port; }
Source:
ParseObject getParent() { if(parent == null){ return null; } if(parent.get() == null){ return ParseDecoder.get().decodePointer(parentClassName, parentObjectId); } return parent.get(); }

Target:
ParseObject getParent() { if(parent == null){ return null; } if(parent.get() == null){ return ParseObject.createWithoutData(parentClassName, parentObjectId); } return parent.get(); }
Source:
public void showFailure() { setCenter(failurePanel); }

Target:
public void showFailure() { closeDetailsView(); setCenter(failurePanel); }
Source:
public void init() { Map<String, Class<? extends Check>> checks = new HashMap<>(); checks.put("allow all", com.yahoo.elide.security.checks.prefab.Role.ALL.class); checks.put("allow all", com.yahoo.elide.security.checks.prefab.Role.ALL.class); dictionary = new EntityDictionary(checks); dictionary.bindEntity(Book.class); dictionary.bindEntity(Author.class); dictionary.bindEntity(Publisher.class); dictionary.bindEntity(Pseudonym.class); dictionary.bindEntity(Address.class); }

Target:
public void init() { Map<String, Class<? extends Check>> checks = new HashMap<>(); checks.put("allow all", com.yahoo.elide.security.checks.prefab.Role.ALL.class); dictionary = new EntityDictionary(checks); dictionary.bindEntity(Book.class); dictionary.bindEntity(Author.class); dictionary.bindEntity(Publisher.class); dictionary.bindEntity(Pseudonym.class); dictionary.bindEntity(Address.class); }
Source:
CompletionStage<Void> forget(Xid externalXid) { Xid xid = convertXid(externalXid); if (trace) log.tracef("forget called for xid %s", xid); if (isRecoveryEnabled()) { return recoveryManager.removeRecoveryInformation(null, xid, null, false) .exceptionally(t -> { log.warnExceptionRemovingRecovery(t); XAException xe = new XAException(XAException.XAER_RMERR); xe.initCause(t); throw CompletableFutures.asCompletionException(xe); }); } else { if (trace) log.trace("Recovery not enabled"); } return CompletableFutures.completedNull(); }

Target:
CompletionStage<Void> forget(Xid externalXid) { Xid xid = convertXid(externalXid); if (trace) log.tracef("forget called for xid %s", xid); if (isRecoveryEnabled()) { return recoveryManager.removeRecoveryInformation(null, xid, null, false) .exceptionally(t -> { log.warnExceptionRemovingRecovery(t); XAException xe = new XAException(XAException.XAER_RMERR); xe.initCause(t); throw new CompletionException(xe); }); } else { if (trace) log.trace("Recovery not enabled"); } return CompletableFutures.completedNull(); }
Source:
public CompileToJarStepFactory configure( @Nullable JvmLibraryArg args, JavacOptions javacOptions, BuildRuleResolver buildRuleResolver, ToolchainProvider toolchainProvider) { CoreArg kotlinArgs = Objects.requireNonNull((CoreArg) args); return new KotlincToJarStepFactory( kotlinBuckConfig.getKotlinc(), kotlinBuckConfig.getKotlinHomeLibraries(), kotlinArgs.getExtraKotlincArguments(), kotlinArgs.getAnnotationProcessingTool().orElse(AnnotationProcessingTool.KAPT), kotlinArgs.getKaptApOptions(), extraClasspathProviderSupplier.apply(toolchainProvider), getJavac(buildRuleResolver, args), javacOptions); }

Target:
public CompileToJarStepFactory configure( @Nullable JvmLibraryArg args, JavacOptions javacOptions, BuildRuleResolver buildRuleResolver, ToolchainProvider toolchainProvider) { CoreArg kotlinArgs = Objects.requireNonNull((CoreArg) args); return new KotlincToJarStepFactory( kotlinBuckConfig.getKotlinc(), kotlinBuckConfig.getKotlinHomeLibraries(), kotlinArgs.getExtraKotlincArguments(), kotlinArgs.getFriendPaths(), kotlinArgs.getAnnotationProcessingTool().orElse(AnnotationProcessingTool.KAPT), kotlinArgs.getKaptApOptions(), extraClasspathProviderSupplier.apply(toolchainProvider), getJavac(buildRuleResolver, args), javacOptions); }
Source:
private static String urlDecode(String str) { try { return (str == null)? null : URLDecoder.decode(str, UTF_8); } catch(UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 is not supported on this system", e); } }

Target:
private static String urlDecode(String str) { try { return str == null ? null : URLDecoder.decode(str, UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 is not supported on this system", e); } }
Source:
private <T extends HttpResponse> Promise<T> intercept(Promise<T> promise, Action<? super HttpResponse> action, Action<? super Throwable> errorAction) { return promise.onError(Exception.class, t -> { errorAction.execute(t); throw t; }) .next(r -> ExecController.require() .fork() .eventLoop(Execution.current().getEventLoop()) .start(e -> action.execute(r) ) ); }

Target:
private <T extends HttpResponse> Promise<T> intercept(Promise<T> promise, Action<? super HttpResponse> action, Action<? super Throwable> errorAction) { return promise.wiretap(r -> { if (r.isError()) { ExecController.require() .fork() .eventLoop(Execution.current().getEventLoop()) .start(e -> errorAction.execute(r.getThrowable()) ); } }) .next(r -> ExecController.require() .fork() .eventLoop(Execution.current().getEventLoop()) .start(e -> action.execute(r) ) ); }
Source:
private static InfinispanModel getModelVersion(ModelTestControllerVersion controllerVersion) { switch (controllerVersion) { case EAP_6_4_0: case EAP_6_4_7: return InfinispanModel.VERSION_1_6_0; case EAP_7_0_0: return InfinispanModel.VERSION_4_0_0; case EAP_7_1_0: return InfinispanModel.VERSION_5_0_0; case EAP_7_2_0_TEMP: return InfinispanModel.VERSION_8_0_0; default: throw new IllegalArgumentException(); } }

Target:
private static InfinispanModel getModelVersion(ModelTestControllerVersion controllerVersion) { switch (controllerVersion) { case EAP_6_4_0: case EAP_6_4_7: return InfinispanModel.VERSION_1_6_0; case EAP_7_0_0: return InfinispanModel.VERSION_4_0_0; case EAP_7_1_0: return InfinispanModel.VERSION_5_0_0; case EAP_7_2_0: return InfinispanModel.VERSION_8_0_0; default: throw new IllegalArgumentException(); } }
Source:
private JavacEnvironment createEnvironment(String path, String source) throws IOException { List<JavaFileObject> inputFiles = new ArrayList<>(); inputFiles.add(MemoryFileObject.createJavaFile(path, source)); return createEnvironment(Collections.emptyList(), inputFiles, false, null); }

Target:
private JavacEnvironment createEnvironment(String path, String source) throws IOException { List<JavaFileObject> inputFiles = new ArrayList<>(); inputFiles.add(MemoryFileObject.createJavaFile(path, source)); return createEnvironment(Collections.emptyList(), inputFiles, false); }
Source:
public void setSelectableItems(List<FilterDropdownRecordWidget<ListType>> resultDisplayItems) { hasResults = !(resultDisplayItems.size() == 0); this.resultDisplayItems = resultDisplayItems; if (hasResults) { mainPanel.clear(); int count = 0; for (final FilterDropdownRecordWidget<ListType> displayItem : this.resultDisplayItems) { if (count > 0) { SimplePanel recordsSplitter = new SimplePanel(); recordsSplitter.setHeight("1px"); recordsSplitter.setStyleName("itemSplitter"); mainPanel.add(recordsSplitter); } mainPanel.add(displayItem); displayItem.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { displayItem.setSelectedState(true); } }); displayItem.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { displayItem.setSelectedState(false); } }); count++; } } else { addInfoMessages(); } }

Target:
public void setSelectableItems(List<FilterDropdownRecordWidget<ListType>> resultDisplayItems) { hasResults = !(resultDisplayItems.size() == 0); this.resultDisplayItems = resultDisplayItems; if (hasResults) { mainPanel.clear(); int count = 0; for (final FilterDropdownRecordWidget<ListType> displayItem : this.resultDisplayItems) { if (count > 0) { SimplePanel recordsSplitter = new SimplePanel(); recordsSplitter.setStyleName("itemSplitter"); mainPanel.add(recordsSplitter); } mainPanel.add(displayItem); displayItem.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { displayItem.setSelectedState(true); } }); displayItem.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { displayItem.setSelectedState(false); } }); count++; } } else { addInfoMessages(); } }
Source:
public DiskWriteModel getDisk(int deviceId) { return fDisks.computeIfAbsent(deviceId, dev -> new DiskWriteModel(dev, checkNotNull(getStateSystemBuilder()))); }

Target:
public DiskWriteModel getDisk(int deviceId) { return fDisks.computeIfAbsent(deviceId, diskId -> new DiskWriteModel(diskId, checkNotNull(getStateSystemBuilder()))); }
Source:
public String getStateTypeName() { return checkNotNull(Messages.FlameGraph_Depth); }

Target:
public String getStateTypeName() { return Objects.requireNonNull(Messages.FlameGraph_Depth); }
Source:
public SystemOption get() { try { ConfigValues config = ConfigValues.valueOf(id); GetSystemOptionParameters parameters = new GetSystemOptionParameters(config); String version = ParametersHelper.getParameter(httpHeaders, uriInfo, "version"); if (version != null && !version.isEmpty()) { parameters.setOptionVersion(version); } QueryReturnValue result = runQuery(QueryType.GetSystemOption, parameters); if (result.getReturnValue() == null) { return handleError(new EntityNotFoundException(id), true); } return LinkHelper.addLinks(SystemOptionsMapper.map(result.getReturnValue(), id)); } catch (IllegalArgumentException ex) { return handleError(new EntityNotFoundException(id), true); } }

Target:
public SystemOption get() { ConfigValues config; try { config = ConfigValues.valueOf(id); } catch (IllegalArgumentException ex) { throw new WebApplicationException(Response.Status.NOT_FOUND); } GetSystemOptionParameters parameters = new GetSystemOptionParameters(config); String version = ParametersHelper.getParameter(httpHeaders, uriInfo, VERSION); if (version != null && !version.isEmpty()) { parameters.setOptionVersion(version); } QueryReturnValue result = runQuery(QueryType.GetSystemOption, parameters); if (result.getReturnValue() == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return LinkHelper.addLinks(SystemOptionsMapper.map(result.getReturnValue(), id)); }
Source:
public void contextInitialized(final ServletContextEvent event) { try { Manifests.append(event.getServletContext()); } catch (final IOException ex) { throw new IllegalStateException(ex); } final Base base; if (StringUtils.startsWith( Manifests.read("Thindeck-DynamoKey"), "${" )) { base = new MnBase(); } else { base = new DyBase(this.dynamo()); } event.getServletContext().setAttribute(Base.class.getName(), base); this.daemons.add(new RoutineTxns(base)); }

Target:
public void contextInitialized(final ServletContextEvent event) { try { Manifests.append(event.getServletContext()); } catch (final IOException ex) { throw new IllegalStateException(ex); } final Base base; if (Manifests.read("Thindeck-DynamoKey").startsWith("${")) { base = new MnBase(); } else { base = new DyBase(this.dynamo()); } event.getServletContext().setAttribute(Base.class.getName(), base); this.daemons.add(new RoutineTxns(base)); }
Source:
private void populateFilters() { this.testingCheck = new LeftCheckBox(tr("Testing")); this.testingCheck.selectedProperty().bindBidirectional(filter.containTestingApplicationsProperty()); this.requiresPatchCheck = new LeftCheckBox(tr("Requires patch")); this.requiresPatchCheck.selectedProperty().bindBidirectional(filter.containRequiresPatchApplicationsProperty()); this.commercialCheck = new LeftCheckBox(tr("Commercial")); this.commercialCheck.selectedProperty().bindBidirectional(filter.containCommercialApplicationsProperty()); this.commercialCheck.setSelected(true); this.operatingSystemCheck = new LeftCheckBox(tr("Show all Operating Systems")); this.operatingSystemCheck.selectedProperty().bindBidirectional(filter.containAllOSCompatibleApplications()); this.operatingSystemCheck.setSelected(false); this.filterGroup = new LeftGroup("Filters", testingCheck, requiresPatchCheck, commercialCheck, operatingSystemCheck); }

Target:
private void populateFilters() { this.testingCheck = new LeftCheckBox(tr("Testing")); this.testingCheck.selectedProperty().bindBidirectional(filter.containTestingApplicationsProperty()); this.requiresPatchCheck = new LeftCheckBox(tr("Requires patch")); this.requiresPatchCheck.selectedProperty().bindBidirectional(filter.containRequiresPatchApplicationsProperty()); this.commercialCheck = new LeftCheckBox(tr("Commercial")); this.commercialCheck.selectedProperty().bindBidirectional(filter.containCommercialApplicationsProperty()); this.commercialCheck.setSelected(true); this.operatingSystemCheck = new LeftCheckBox(tr("All Operating Systems")); this.operatingSystemCheck.selectedProperty().bindBidirectional(filter.containAllOSCompatibleApplications()); this.operatingSystemCheck.setSelected(false); this.filterGroup = new LeftGroup("Filters", testingCheck, requiresPatchCheck, commercialCheck, operatingSystemCheck); }
Source:
public void extractLowBitsTo(HLLRegister dest) { for (Entry<Integer, Byte> entry : getSparseMap().entrySet()) { int idx = entry.getKey(); byte lr = entry.getValue(); if (lr != 0) { dest.add((1 << (p + lr - 1)) | idx); } } }

Target:
public void extractLowBitsTo(HLLRegister dest) { for (Entry<Integer, Byte> entry : getSparseMap().entrySet()) { int idx = entry.getKey(); byte lr = entry.getValue(); if (lr != 0) { dest.add((1L << (p + lr - 1)) | idx); } } }
Source:
private void completeAllExceptionally(Throwable t) { List<Data> completed; synchronized (futures) { completed = new ArrayList<>(futures.size()); completed.addAll(futures.values()); } for (Data data : completed) { data.cancelFuture.cancel(false); data.completeExceptionally(t); } }

Target:
private void completeAllExceptionally(Throwable t) { List<Data> completed; synchronized (futures) { completed = new ArrayList<>(futures.values()); } for (Data data : completed) { data.cancelFuture.cancel(false); data.completeExceptionally(t); } }
Source:
public Response doImport(Action action) { validateParameters(action, "storageDomain.id|name"); ImportRepoImageParameters importParameters = new ImportRepoImageParameters(); importParameters.setSourceRepoImageId(id); importParameters.setSourceStorageDomainId(getStorageDomainId()); importParameters.setStoragePoolId(getDataCenterId(getStorageDomainId(action))); importParameters.setStorageDomainId(getStorageDomainId(action)); if (action.isSetImportAsTemplate()) { if (action.isImportAsTemplate()) { validateParameters(action, "cluster.id|name"); importParameters.setClusterId(getClusterId(action)); if (action.isSetTemplate() && action.getTemplate().isSetName()) { importParameters.setTemplateName(action.getTemplate().getName()); } } importParameters.setImportAsTemplate(action.isImportAsTemplate()); } if (action.isSetName()) { importParameters.setDiskAlias(action.getName()); } return doAction(VdcActionType.ImportRepoImage, importParameters, action); }

Target:
public Response doImport(Action action) { validateParameters(action, "storageDomain.id|name"); ImportRepoImageParameters importParameters = new ImportRepoImageParameters(); importParameters.setSourceRepoImageId(id); importParameters.setSourceStorageDomainId(getStorageDomainId()); importParameters.setStoragePoolId(getDataCenterId(getStorageDomainId(action))); importParameters.setStorageDomainId(getStorageDomainId(action)); if (action.isSetImportAsTemplate()) { if (action.isImportAsTemplate()) { validateParameters(action, "cluster.id|name"); importParameters.setClusterId(getClusterId(action)); if (action.isSetTemplate() && action.getTemplate().isSetName()) { importParameters.setTemplateName(action.getTemplate().getName()); } } importParameters.setImportAsTemplate(action.isImportAsTemplate()); } if (action.isSetDisk() && action.getDisk().isSetAlias()) { importParameters.setDiskAlias(action.getDisk().getAlias()); } return doAction(VdcActionType.ImportRepoImage, importParameters, action); }
Source:
public void testDestroy() throws Exception { final ManagedInstance managedInstance = mock(ManagedInstance.class); final Object control = mock(Object.class); final Consumer<Object> consumer = mock(Consumer.class); InstanceUtils.destroy(managedInstance, control, consumer); verify(consumer, times(1)).accept(eq(control)); verify(managedInstance, times(1)).destroy(eq(control)); }

Target:
public void testDestroy() { final ManagedInstance managedInstance = mock(ManagedInstance.class); final Object control = mock(Object.class); final Consumer<Object> consumer = mock(Consumer.class); InstanceUtils.destroy(managedInstance, control, consumer); verify(consumer, times(1)).accept(eq(control)); verify(managedInstance, times(1)).destroy(eq(control)); }
Source:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length < 1) { return false; } final Player player = getPlayer(args[0]); if (player == null) { playerMsg(TFM_Command.PLAYER_NOT_FOUND); return true; } else if (args.length > 1) { final String reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); smite(sender, player, reason); return true; } else { sender.sendMessage(ChatColor.RED + "You must supply a reason in order to smite someone."); return true; } }

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length < 1) { return false; } final Player player = getPlayer(args[0]); if (player == null) { playerMsg(TFM_Command.PLAYER_NOT_FOUND); return true; } else if (args.length > 1) { final String reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); smite(sender, player, reason); return true; } else { sender.sendMessage(ChatColor.GREEN + "You must supply a reason in order to smite someone."); return true; } }
Source:
private void loadFile(File file) throws ConfigurationException { Configuration config = null; try { config = Configuration.loadFile(file); } catch (IOException exception) { throw new ConfigurationException( "Can't load object configuration file \"" + file.getAbsolutePath() + "\".", exception); } String name = config.getString(ExtensionManagerKeys.name.getKeyName()); Boolean enabled = config.getBoolean(ExtensionManagerKeys.enabled.getKeyName(), false); if (!enabled.booleanValue()) { log.debug("The extension \"{}\" is disabled", name); return; } if (configurationNames.contains(name)) { log.error("An extension with the name \"{}\" is already loaded", name); return; } configurationNames.add(name); String position = config.getString(ExtensionManagerKeys.position.getKeyName()); if (position != null) { if (position.equalsIgnoreCase("first")) { if (!firstDetected) { orderedConfigurationNames.add(0, name); orderedConfigurations.add(0, config); firstDetected = true; } else { log.error("There is already an extension that is marked as the first. \"{}\" cannot be set as first", name); } } else if (position.equals("last")) { if (!lastDetected) { orderedConfigurationNames.add(name); orderedConfigurations.add(config); lastDetected = true; } else { log.error("There is already an extension that is marked as the last. \"{}\" cannot be set as last", name); } } } }

Target:
private void loadFile(File file) throws ConfigurationException { Configuration config = null; try { config = Configuration.loadFile(file); String name = config.getString(NAME); ExtensionEntry alreadyLoded = loadedEntries.get(name); if (alreadyLoded != null) { throw new ConfigurationException("Could not load the configuration file \"" + file.getAbsolutePath() + "\". The configuration file + \"" + alreadyLoded.file.getAbsolutePath() + "\" already has the name " + name); } ExtensionEntry entry = new ExtensionEntry(file, config.getBoolean(ENABLED, true), name, config.getString(SERVICE), config); loadedEntries.put(entry.name, entry); } catch (IOException exception) { throw new ConfigurationException( "Can't load object configuration file \"" + file.getAbsolutePath() + "\".", exception); } }
Source:
public boolean canDeleteTask(TaskRepository repository, ITask task) { return true; }

Target:
public boolean canDeleteTask(TaskRepository repository, ITask task) { return hasRichEditor(repository); }
Source:
public void getAttributesByIdsAndHolders() throws Exception { System.out.println(CLASS_NAME + "getAttributesByIdsAndHolders"); Attribute groupAttr = setUpGroupAttribute(); Attribute memberGroupAttr = setUpMemberGroupAttribute(); AttributeDefinition memberGroupAttrDef = setUpMemberGroupAttributeDefinition(); AttributeDefinition groupResourceAttrDef = setUpGroupResourceAttributeDefinition(); cacheManager.setAttribute(groupAttr, groupHolder, null); cacheManager.setAttribute(memberGroupAttr, memberHolder, groupHolder); List<Integer> attributeIds = new ArrayList<>(); attributeIds.add(groupAttr.getId()); attributeIds.add(memberGroupAttr.getId()); attributeIds.add(memberGroupAttrDef.getId()); attributeIds.add(groupResourceAttrDef.getId()); List<Attribute> attrs = cacheManager.getAttributesByIds(attributeIds, memberHolder, groupHolder); assertTrue("result should contain member-group attribute", attrs.contains(memberGroupAttr)); assertTrue("result should contain member-group attribute definition", attrs.contains(new Attribute(memberGroupAttrDef))); assertTrue("it should return 2 attributes", attrs.size() == 2); }

Target:
public void getAttributesByIdsAndHolders() throws Exception { System.out.println(CLASS_NAME + "getAttributesByIdsAndHolders"); Attribute groupAttr = setUpGroupAttribute(); Attribute memberGroupAttr = setUpMemberGroupAttribute(); AttributeDefinition memberGroupAttrDef = setUpMemberGroupAttributeDefinition(); AttributeDefinition groupResourceAttrDef = setUpGroupResourceAttributeDefinition(); cacheManager.setAttribute(groupAttr, groupHolder, null); cacheManager.setAttribute(memberGroupAttr, memberHolder, groupHolder); List<Integer> attributeIds = new ArrayList<>(); attributeIds.add(groupAttr.getId()); attributeIds.add(memberGroupAttr.getId()); attributeIds.add(memberGroupAttrDef.getId()); attributeIds.add(groupResourceAttrDef.getId()); List<Attribute> attrs = cacheManager.getAttributesByIds(attributeIds, memberHolder, groupHolder); assertTrue("result should contain member-group attribute", attrs.contains(memberGroupAttr)); assertTrue("result should contain member-group attribute definition", attrs.contains(memberGroupAttrDef)); assertTrue("it should return 2 attributes", attrs.size() == 2); }
Source:
private RoutesBean getRoutesWithRouteNameQuery(SearchQueryBean query) throws ServiceException { SearchResult<AgencyAndId> result = searchForRoutes(query); List<RouteBean> routeBeans = new ArrayList<RouteBean>(); CoordinateBounds bounds = query.getBounds(); for (AgencyAndId id : result.getResults()) { STRtree tree = getStopsTreeForRouteId(id); if (tree == null) { _log.warn("stop tree not found for routeId=" + id); continue; } Envelope env = new Envelope(bounds.getMinLon(), bounds.getMaxLon(), bounds.getMinLat(), bounds.getMaxLat()); HasItemsVisitor v = new HasItemsVisitor(); tree.query(env, v); if (v.hasItems()) { RouteBean routeBean = _routeBeanService.getRouteForId(id); routeBeans.add(routeBean); } } boolean limitExceeded = BeanServiceSupport.checkLimitExceeded(routeBeans, query.getMaxCount()); return constructResult(routeBeans, limitExceeded); }

Target:
private RoutesBean getRoutesWithRouteNameQuery(SearchQueryBean query) throws ServiceException { SearchResult<AgencyAndId> result = searchForRoutes(query); List<RouteBean> routeBeans = new ArrayList<RouteBean>(); CoordinateBounds bounds = query.getBounds(); for (AgencyAndId id : result.getResults()) { STRtree tree = _stopTreesByRouteId.get(id); if (tree == null) { _log.warn("stop tree not found for routeId=" + id); continue; } Envelope env = new Envelope(bounds.getMinLon(), bounds.getMaxLon(), bounds.getMinLat(), bounds.getMaxLat()); HasItemsVisitor v = new HasItemsVisitor(); tree.query(env, v); if (v.hasItems()) { RouteBean routeBean = _routeBeanService.getRouteForId(id); routeBeans.add(routeBean); } } boolean limitExceeded = BeanServiceSupport.checkLimitExceeded(routeBeans, query.getMaxCount()); return constructResult(routeBeans, limitExceeded); }
Source:
public UsageStatisticsReporting get() { synchronized (mutexForReportingUsageData) { UsageStatisticsReporting loaded = getUsageStatisticsReportingInfo(); if (loaded.canReport()) { reportingStartedTime = new DateTime(); } return loaded; } }

Target:
public UsageStatisticsReporting get() { UsageStatisticsReporting loaded = usageStatisticsReportingSqlMapDao.load(); loaded.setDataSharingServerUrl(systemEnvironment.getGoDataSharingServerUrl()); boolean canReport = !isDevelopmentServer() && dataSharingSettingsService.get().allowSharing() && !isToday(loaded.lastReportedAt()) && !isReportingInProgress(); loaded.canReport(canReport); return loaded; }
Source:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { userID = -1; token = null; (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { try { bugzillaClient.authenticate(monitor); } catch (CoreException e) { e.printStackTrace(); } Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); return; }

Target:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); userID = -1; token = null; return; }
Source:
public String metrics() { if (!this.delegate.isEnabled()) { return getDisabledResponse().toString(); } ResponseEntity<String> result = this.delegate.invoke(); return result.getBody(); }

Target:
public ResponseEntity<String> metrics() { if (!this.delegate.isEnabled()) { return (ResponseEntity<String>) getDisabledResponse(); } ResponseEntity<String> result = this.delegate.invoke(); return result; }
Source:
void reloadAccountabilityConfiguration(InputStream defaultConfigInputStream) { File tempFile = new File(configDirectory + "/wineryAccountability.yml"); if (!configFile.exists()) { copyDefaultConfigFile(); } else { try { FileUtils.copyInputStreamToFile(defaultConfigInputStream, tempFile); } catch (IOException e) { LOGGER.debug("Error copying default file.", e); } YAMLConfiguration defaultAccountabilityConfiguration; try (FileReader reader = new FileReader(tempFile)) { String accountabilityPrefix = "accountability"; defaultAccountabilityConfiguration = new YAMLConfiguration(); defaultAccountabilityConfiguration.read(reader); YAMLConfiguration currentConfiguration = this.getConfiguration(); Iterator<String> accountabilityAttributes = defaultAccountabilityConfiguration.getKeys(accountabilityPrefix); accountabilityAttributes.forEachRemaining(key -> { currentConfiguration.setProperty(key, defaultAccountabilityConfiguration.getString(key)); }); this.save(); defaultConfigInputStream.close(); } catch (ConfigurationException | IOException ex) { LOGGER.debug("Error while reading configuration file.", ex); } tempFile.delete(); } }

Target:
void reloadAccountabilityConfiguration(InputStream defaultConfigInputStream) { File tempFile = new File(configDirectory + "/wineryAccountability.yml"); if (!configFile.exists()) { copyDefaultConfigFile(); } else { try { FileUtils.copyInputStreamToFile(defaultConfigInputStream, tempFile); } catch (IOException e) { LOGGER.debug("Error copying default file.", e); } YAMLConfiguration defaultAccountabilityConfiguration; try (FileReader reader = new FileReader(tempFile)) { String accountabilityPrefix = "accountability"; defaultAccountabilityConfiguration = new YAMLConfiguration(); defaultAccountabilityConfiguration.read(reader); YAMLConfiguration currentConfiguration = this.getConfiguration(); Iterator<String> accountabilityAttributes = defaultAccountabilityConfiguration.getKeys(accountabilityPrefix); accountabilityAttributes.forEachRemaining(key -> { currentConfiguration.setProperty(key, defaultAccountabilityConfiguration.getString(key)); }); this.save(); } catch (ConfigurationException | IOException ex) { LOGGER.debug("Error while reading configuration file.", ex); } tempFile.delete(); } }
Source:
public void onRestart() { super.onRestart(); Restart=true; initializeView(); }

Target:
public void onRestart() { super.onRestart(); restart=true; initializeView(); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getLabel() == null) ? 0 : getLabel().hashCode()); return result; }

Target:
public int hashCode() { return LABEL.hashCode(); }
Source:
private void runEventLoopUntilEmpty() { Display display = Display.getCurrent(); while (display.readAndDispatch()) { } display.sleep(); return; }

Target:
private void runEventLoopUntilEmpty() { Display display = Display.getCurrent(); while (display.readAndDispatch()) { } return; }
Source:
@Test public void testToastMSGIsDisplayed() throws InterruptedException { WebDriverWait wait = new WebDriverWait(driver, 10); driver.startActivity("io.appium.android.apis", ".view.PopupMenu1"); MobileElement popUpElement = driver.findElement(MobileBy.AccessibilityId("Make a Popup!")); popUpElement.click(); driver.findElement(By.xpath(". wait.until(ExpectedConditions .presenceOfElementLocated(By.xpath(" popUpElement.click(); driver.findElement(By.xpath(". wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(" popUpElement.click(); driver.findElement(By.xpath(". wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(" driver.findElement(By.xpath(". wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(" }

Target:
@Test public void testToastMSGIsDisplayed() throws InterruptedException { final WebDriverWait wait = new WebDriverWait(driver, 10); driver.startActivity("io.appium.android.apis", ".view.PopupMenu1"); MobileElement popUpElement = driver.findElement(MobileBy.AccessibilityId("Make a Popup!")); popUpElement.click(); driver.findElement(By.xpath(". assertNotNull(wait.until(ExpectedConditions.presenceOfElementLocated( By.xpath(" popUpElement.click(); driver.findElement(By.xpath(". assertNotNull(wait.until(ExpectedConditions .presenceOfElementLocated(By.xpath(" popUpElement.click(); driver.findElement(By.xpath(". assertNotNull(wait.until(ExpectedConditions .presenceOfElementLocated(By.xpath(" driver.findElement(By.xpath(". assertNotNull(wait.until(ExpectedConditions .presenceOfElementLocated(By.xpath(" }
Source:
private String taskSensorPrefix(final String threadId, final String taskId) { return threadSensorPrefix(threadId) + SENSOR_PREFIX_DELIMITER + "task" + SENSOR_PREFIX_DELIMITER + taskId; }

Target:
private String taskSensorPrefix(final String threadId, final String taskId) { return threadSensorPrefix(threadId) + SENSOR_PREFIX_DELIMITER + SENSOR_TASK_LABEL + SENSOR_PREFIX_DELIMITER + taskId; }
Source:
public Builder(String portletUrl) { super(); this.portletUrl = portletUrl; localJs = new ArrayList<>(); localCss = new ArrayList<>(); remoteJs = new ArrayList<>(); remoteCss = new ArrayList<>(); localRawJs = new ArrayList<>(); localRawCss = new ArrayList<>(); this.isThemeEnabled = true; this.isCordovaEnabled = false; this.webType = WebType.LIFERAY_AUTHENTICATED; }

Target:
public Builder(String portletUrl) { super(); }
Source:
private String createQuery(FileTypesByExtension.SearchFilterInterface filter) { if (filter.getFilter().isEmpty()) { return ""; } String query = "(dir_type = " + TskData.TSK_FS_NAME_TYPE_ENUM.REG.getValue() + ")" + (UserPreferences.hideKnownFilesInViewsTree() ? " AND (known IS NULL OR known != " + TskData.FileKnown.KNOWN.getFileKnownValue() + ")" : " ") + " AND (NULL "; if (skCase.getDatabaseType().equals(TskData.DbType.POSTGRESQL)) { query += "OR LOWER(name) ~ '(\\"; query += StringUtils.join(filter.getFilter(), "|\\"); query += ")$'"; } else { for (String s : filter.getFilter()) { query += "OR LOWER(name) LIKE '%" + s.toLowerCase() + "'"; } } query += ')'; return query; }

Target:
private String createQuery(FileTypesByExtension.SearchFilterInterface filter) { if (filter.getFilter().isEmpty()) { throw new IllegalArgumentException("Empty filter list passed to createQuery()"); } String query = "(dir_type = " + TskData.TSK_FS_NAME_TYPE_ENUM.REG.getValue() + ")" + (UserPreferences.hideKnownFilesInViewsTree() ? " AND (known IS NULL OR known != " + TskData.FileKnown.KNOWN.getFileKnownValue() + ")" : " ") + " AND (NULL "; if (skCase.getDatabaseType().equals(TskData.DbType.POSTGRESQL)) { query += "OR LOWER(name) ~ '(\\"; query += StringUtils.join(filter.getFilter().stream() .map(String::toLowerCase).collect(Collectors.toList()), "|\\"); query += ")$'"; } else { for (String s : filter.getFilter()) { query += "OR LOWER(name) LIKE '%" + s.toLowerCase() + "'"; } } query += ')'; return query; }
Source:
public List<Container> search(Collection<? extends HasMetadata> list) { return list.stream() .filter(this::matchMeta) .flatMap(this::findContainers) .filter(this::matchContainer) .collect(toList()); }

Target:
public List<Container> search(Collection<? extends HasMetadata> list) { return list.stream() .filter(this::matchMetadata) .flatMap(this::findContainers) .filter(this::matchContainer) .collect(toList()); }
Source:
public void postCollectionAdminGroupCreateAdminGroupUnProcessablePermanent() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); groupRest.setPermanent(true); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/adminGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); }

Target:
public void postCollectionAdminGroupCreateAdminGroupUnProcessablePermanent() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); groupRest.setPermanent(true); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/adminGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/adminGroup")) .andExpect(status().isNoContent()); }
Source:
public void shouldNotWriteMoreThanOneOnCancelTaskWhenDefined() throws Exception { String xml = "<cruise schemaVersion='30'>\n" + "<server artifactsdir='artifactsDir' >" + "</server>" + "<pipelines>\n" + "<pipeline name='pipeline1' template='abc'>\n" + " <materials>\n" + " <svn url ='svnurl' username='foo' password='password'/>" + " </materials>\n" + "</pipeline>\n" + "</pipelines>\n" + "<templates>\n" + " <pipeline name='abc'>\n" + " <stage name='stage1'>" + " <jobs>" + " <job name='job1'>" + " <tasks>" + " <exec command=\"rake\">\n" + " <arg>all_test</arg>\n" + " <oncancel>\n" + " <ant target='kill' />\n" + " <ant target='kill' />\n" + " </oncancel>\n" + " </exec>" + " </tasks>" + " </job>" + " </jobs>" + " </stage>" + " </pipeline>\n" + "</templates>\n" + "</cruise>"; try { CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(IOUtils.toInputStream(xml)).config; xmlWriter.write(cruiseConfig, output, false); fail("Should not allow user to write more than one oncancel task"); } catch (Exception e) { assertThat(e.getMessage(), containsString("Invalid content was found starting with element 'ant'. No child element is expected at this point.")); } }

Target:
public void shouldNotWriteMoreThanOneOnCancelTaskWhenDefined() throws Exception { String xml = "<cruise schemaVersion='76'>\n" + "<server artifactsdir='artifactsDir' >" + "</server>" + "<pipelines>\n" + "<pipeline name='pipeline1' template='abc'>\n" + " <materials>\n" + " <svn url ='svnurl' username='foo' password='password'/>" + " </materials>\n" + "</pipeline>\n" + "</pipelines>\n" + "<templates>\n" + " <pipeline name='abc'>\n" + " <stage name='stage1'>" + " <jobs>" + " <job name='job1'>" + " <tasks>" + " <exec command=\"rake\">\n" + " <arg>all_test</arg>\n" + " <oncancel>\n" + " <ant target='kill' />\n" + " <ant target='kill' />\n" + " </oncancel>\n" + " </exec>" + " </tasks>" + " </job>" + " </jobs>" + " </stage>" + " </pipeline>\n" + "</templates>\n" + "</cruise>"; thrown.expectMessage("Invalid content was found starting with element 'ant'. No child element is expected at this point."); CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(IOUtils.toInputStream(xml)).config; xmlWriter.write(cruiseConfig, output, false); }