auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void uploadPicture() { uploadPictureSubmit.click(); browser.selenium.waitForPageToLoad("10000"); ThreadHelper.waitFor(1000); }

Target:
public void uploadPicture() { uploadPictureSubmit.click(); browser.selenium.waitForPageToLoad("10000"); }
Source:
public static JcloudsSpecParser parse(String spec, boolean dryrun) { JcloudsSpecParser result = new JcloudsSpecParser(); int split = spec.indexOf(':'); if (split<0) { if (spec.equalsIgnoreCase(JCLOUDS)) { if (dryrun) return null; throw new IllegalArgumentException("Cannot use '"+spec+"' as a location ID; it is insufficient. "+ "Try jclouds:aws-ec2 (for example)."); } result.providerOrApi = spec; result.parameter = null; } else { result.providerOrApi = spec.substring(0, split); result.parameter = spec.substring(split+1); while (result.providerOrApi.equalsIgnoreCase(JCLOUDS)) { result.providerOrApi = result.parameter; result.parameter = null; split = result.providerOrApi.indexOf(':'); if (split>=0) { result.parameter = result.providerOrApi.substring(split+1); result.providerOrApi = result.providerOrApi.substring(0, split); } } } if (result.parameter==null && AWS_REGIONS.contains(result.providerOrApi)) { result.parameter = result.providerOrApi; result.providerOrApi = "aws-ec2"; if (!dryrun) log.warn("Use of deprecated location '"+result.parameter+"'; in future refer to with explicit provider '"+result.providerOrApi+":"+result.parameter+"'"); } return result; }

Target:
public static JcloudsSpecParser parse(String spec, boolean dryrun) { JcloudsSpecParser result = new JcloudsSpecParser(); int split = spec.indexOf(':'); if (split<0) { if (spec.equalsIgnoreCase(JCLOUDS)) { if (dryrun) return null; throw new IllegalArgumentException("Cannot use '"+spec+"' as a location ID; it is insufficient. "+ "Try jclouds:aws-ec2 (for example)."); } result.providerOrApi = spec; result.parameter = null; } else { result.providerOrApi = spec.substring(0, split); result.parameter = spec.substring(split+1); int numJcloudsPrefixes = 0; while (result.providerOrApi.equalsIgnoreCase(JCLOUDS)) { numJcloudsPrefixes++; result.providerOrApi = result.parameter; result.parameter = null; split = result.providerOrApi.indexOf(':'); if (split>=0) { result.parameter = result.providerOrApi.substring(split+1); result.providerOrApi = result.providerOrApi.substring(0, split); } } if (!dryrun && numJcloudsPrefixes > 1) { log.warn("Use of deprecated location spec '"+spec+"'; in future use a single \"jclouds\" prefix"); } } if (result.parameter==null && AWS_REGIONS.contains(result.providerOrApi)) { result.parameter = result.providerOrApi; result.providerOrApi = "aws-ec2"; if (!dryrun) log.warn("Use of deprecated location '"+result.parameter+"'; in future refer to with explicit provider '"+result.providerOrApi+":"+result.parameter+"'"); } return result; }
Source:
public void close() { isOpened = false; try { executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { } try { producer.close(); } catch(Exception e) { log.error("failed to close kafka producer", e); } }

Target:
public void close() { isOpened = false; try { metadataWaitingQueue.offer(SHUTDOWN_POISON_MSG); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { } try { producer.close(); } catch(Exception e) { log.error("failed to close kafka producer", e); } }
Source:
private PolicyInstance initPolicyInstance() throws InitialisationException { if (policyContext == null) { initPolicyContext(); } return policyContext.getRegistry().lookupByType(PolicyInstance.class).get(); }

Target:
private PolicyInstance initPolicyInstance() { return policyContext.getRegistry().lookupByType(PolicyInstance.class).get(); }
Source:
private static List<String> extractInfo(String str) { StringBuilder idEdited = new StringBuilder(); StringBuilder valEdited = new StringBuilder(); int strlen = str.length(); boolean foundSpace = false; boolean foundDigit = false; for (int i = 0; i < strlen; i++) { if (!foundDigit) if (Character.isLetter(str.charAt(i))) foundDigit = true; if (foundDigit) { if (Character.isWhitespace(str.charAt(i))) { if (!foundSpace) { foundSpace = true; } else break; } else { if (foundSpace) { valEdited.append(str.charAt(i)); } else { idEdited.append(str.charAt(i)); } } } } List<String> objec = new ArrayList<>(); objec.add(idEdited.toString()); objec.add(valEdited.toString()); return objec; }

Target:
private static List<String> extractInfo(String str) { int beg = 0; int end = 0; int len = str.length(); List<String> parts = new ArrayList<>(); while (end < len && !Character.isSpaceChar(str.charAt(end))) end++; parts.add(str.substring(beg,end)); while (end < len && Character.isSpaceChar(str.charAt(end))) end++; beg = end; while (end < len && !Character.isSpaceChar(str.charAt(end))) end++; parts.add(str.substring(beg,end)); return parts; }
Source:
public boolean hasNext() { if (isNextMatchCalculated) { return true; } if (currentPlan == null) { return false; } try { boolean foundMatch = currentPlan.execute(frame); while ((!foundMatch) && planIterator.hasNext()) { foundMatch = selectNextPlan() && currentPlan.execute(frame); } if (foundMatch) { isNextMatchCalculated = true; } return foundMatch; } catch (LocalSearchException e) { throw new RuntimeException(e); } }

Target:
public boolean hasNext() { if (isNextMatchCalculated) { return true; } if (currentPlan == null) { return false; } try { boolean foundMatch = currentPlan.execute(frame); while ((!foundMatch) && planIterator.hasNext()) { foundMatch = selectNextPlan() && currentPlan.execute(frame); } isNextMatchCalculated = foundMatch; return foundMatch; } catch (LocalSearchException e) { throw new RuntimeException(e); } }
Source:
public void start(final Stage initialStage) { logger.info("TerasologyLauncher is starting"); logSystemInformation(); initProxy(); initLanguage(); final Task<LauncherConfiguration> launcherInitTask = new LauncherInitTask(initialStage); showSplashStage(initialStage, launcherInitTask); Thread initThread = new Thread(launcherInitTask); initThread.setName("Launcher init thread"); launcherInitTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(final WorkerStateEvent workerStateEvent) { try { LauncherConfiguration config = launcherInitTask.getValue(); if (config == null) { throw new LauncherStartFailedException("Launcher configuration was `null`."); } else if (config instanceof NullLauncherConfiguration) { logger.info("Closing the launcher ... (empty configuration, probably due to update)"); Platform.exit(); } else { showMainStage(config); } } catch (IOException | LauncherStartFailedException e) { openCrashReporterAndExit(e); } } }); launcherInitTask.setOnFailed(event -> {openCrashReporterAndExit(new RuntimeException("FUUU"));}); initThread.start(); }

Target:
public void start(final Stage initialStage) { logger.info("TerasologyLauncher is starting"); logSystemInformation(); initProxy(); initLanguage(); final Task<LauncherConfiguration> launcherInitTask = new LauncherInitTask(initialStage); showSplashStage(initialStage, launcherInitTask); Thread initThread = new Thread(launcherInitTask); initThread.setName("Launcher init thread"); launcherInitTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(final WorkerStateEvent workerStateEvent) { try { LauncherConfiguration config = launcherInitTask.getValue(); if (config == null) { throw new LauncherStartFailedException("Launcher configuration was `null`."); } else if (config instanceof NullLauncherConfiguration) { logger.info("Closing the launcher ... (empty configuration, probably due to update)"); Platform.exit(); } else { showMainStage(config); } } catch (IOException | LauncherStartFailedException e) { openCrashReporterAndExit(e); } } }); launcherInitTask.setOnFailed(event -> { Throwable throwable = event.getSource().getException(); Exception exception; if (throwable instanceof Exception) { exception = (Exception) throwable; } else { exception = new Exception("Wrapped throwable, see deeper", throwable); } openCrashReporterAndExit(exception); }); initThread.start(); }
Source:
public JDBCStatusStoreLoader(GeoServerDataDirectory dd) throws IOException { dataDir = dd; try { Properties params = getParameters(); store = DataStoreFinder.getDataStore(params); } catch (IOException e) { e.printStackTrace(); } }

Target:
public JDBCStatusStoreLoader(GeoServerDataDirectory dd) throws IOException { dataDir = dd; try { Properties params = getParameters(); store = DataStoreFinder.getDataStore(params); } catch (IOException e) { LOGGER.info("can't find or create JDBC Status store configuration file"); LOGGER.log(Level.FINE, "no config file?", e); } }
Source:
public void testReferenceContainmentMultiMove2WayLtR() throws IOException { final Resource left = input.getReferenceContainmentMultiMoveLeft(); final Resource right = input.getReferenceContainmentMultiMoveRight(); final IComparisonScope scope = new DefaultComparisonScope(left, right, null); Comparison comparison = EMFCompare.builder().build().compare(scope); final List<Diff> differences = comparison.getDifferences(); assertSame(Integer.valueOf(1), Integer.valueOf(differences.size())); final String featureName = "containmentRef1"; final Diff diff = Iterators.find(differences.iterator(), and(fromSide(DifferenceSource.LEFT), moved( "root.value2", featureName))); mergerRegistry.getHighestRankingMerger(diff).copyLeftToRight(diff, new BasicMonitor()); final EObject targetNode = getNodeNamed(right, "value2"); assertNotNull(targetNode); final EObject sourceNode = getNodeNamed(left, "value2"); assertNotNull(sourceNode); final EStructuralFeature feature = targetNode.eClass().getEStructuralFeature(featureName); assertNotNull(feature); comparison = EMFCompare.builder().build().compare(scope); assertSame(Integer.valueOf(0), Integer.valueOf(comparison.getDifferences().size())); }

Target:
public void testReferenceContainmentMultiMove2WayLtR() throws IOException { final Resource left = input.getReferenceContainmentMultiMoveLeft(); final Resource right = input.getReferenceContainmentMultiMoveRight(); final IComparisonScope scope = new DefaultComparisonScope(left, right, null); Comparison comparison = EMFCompare.builder().build().compare(scope); final List<Diff> differences = comparison.getDifferences(); assertSame(Integer.valueOf(1), Integer.valueOf(differences.size())); final String featureName = "containmentRef1"; final Diff diff = Iterators.find(differences.iterator(), and(fromSide(DifferenceSource.LEFT), moved( "root.value2", featureName))); mergerRegistry.getHighestRankingMerger(diff).copyLeftToRight(diff, new BasicMonitor()); final EObject targetNode = getNodeNamed(right, "value2"); assertNotNull(targetNode); final EObject targetContainerNode = getNodeNamed(right, "root"); assertNotNull(targetContainerNode); assertEquals(targetContainerNode, targetNode.eContainer()); final EObject sourceNode = getNodeNamed(left, "value2"); assertNotNull(sourceNode); final EObject sourceContainerNode = getNodeNamed(left, "root"); assertNotNull(sourceContainerNode); assertEquals(sourceContainerNode, sourceNode.eContainer()); comparison = EMFCompare.builder().build().compare(scope); assertSame(Integer.valueOf(0), Integer.valueOf(comparison.getDifferences().size())); }
Source:
public int compare(T a, T b) { if (a == b) { return 0; } else if (a == null) { return -1; } else if (b == null) { return 1; } throw DataUtils.newUnsupportedOperationException("Can not compare"); }

Target:
public int compare(T a, T b) { throw DataUtils.newUnsupportedOperationException("Can not compare"); }
Source:
public static Id parse(final String str) { final Id r = new Id(); String preparedStr = str; if (preparedStr.endsWith("/")) { preparedStr = preparedStr.substring(0, preparedStr.length() - 1); } r.fromString(preparedStr); return r; }

Target:
public static Id parse(final String str) { final Id r = new Id(); r.fromString(str); return r; }
Source:
public static MerlinsBeard from(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); AndroidVersion androidVersion = new AndroidVersion(); ResponseCodeValidator validator = new ResponseCodeValidator.DefaultEndpointResponseCodeValidator(); EndpointPinger pinger = EndpointPinger.withCustomEndpointAndValidation(Endpoint.from(ENDPOINT), validator); Ping ping = new Ping(Endpoint.defaultEndpoint(), new EndpointPinger.ResponseCodeFetcher(), validator); return new MerlinsBeard(connectivityManager, androidVersion, pinger, ping); }

Target:
public static MerlinsBeard from(Context context) { return new MerlinsBeard.Builder() .build(context); }
Source:
private void updateStoragePoolFormatType() { final storage_pool storagePool = getStoragePool(); final Guid spId = storagePool.getId(); final Version spVersion = storagePool.getcompatibility_version(); final Version oldSpVersion = _oldStoragePool.getcompatibility_version(); if (Version.OpEquality(spVersion, oldSpVersion)) { return; } StorageFormatType targetFormat = StorageFormatType.V1; if (spVersion.compareTo(Version.v3_0) == 0) { targetFormat = StorageFormatType.V2; } else if (spVersion.compareTo(Version.v3_1) == 0) { targetFormat = StorageFormatType.V3; } StorageType spType = storagePool.getstorage_pool_type(); if (targetFormat == StorageFormatType.V2 && spType != StorageType.ISCSI && spType != StorageType.FCP) { return; } storagePool.setStoragePoolFormatType(targetFormat); getStoragePoolDAO().updatePartial(storagePool); updateMemberDomainsFormat(targetFormat); if (storagePool.getstatus() != StoragePoolStatus.Up) { return; } if (getStoragePool().getstatus() == StoragePoolStatus.Up) { runVdsCommand(VDSCommandType.UpgradeStoragePool, new UpgradeStoragePoolVDSCommandParameters(spId, targetFormat)); } }

Target:
private void updateStoragePoolFormatType() { final storage_pool storagePool = getStoragePool(); final Guid spId = storagePool.getId(); final Version spVersion = storagePool.getcompatibility_version(); final Version oldSpVersion = _oldStoragePool.getcompatibility_version(); final StorageFormatType targetFormat; if (Version.OpEquality(spVersion, oldSpVersion)) { return; } if (spVersion.compareTo(Version.v3_0) == 0) { targetFormat = StorageFormatType.V2; } else if (spVersion.compareTo(Version.v3_1) == 0) { targetFormat = StorageFormatType.V3; } else { targetFormat = StorageFormatType.V1; } StorageType spType = storagePool.getstorage_pool_type(); if (targetFormat == StorageFormatType.V2 && spType != StorageType.ISCSI && spType != StorageType.FCP) { return; } storagePool.setStoragePoolFormatType(targetFormat); TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getStoragePoolDAO().updatePartial(storagePool); updateMemberDomainsFormat(targetFormat); return null; } }); if (_oldStoragePool.getstatus() == StoragePoolStatus.Up) { runVdsCommand(VDSCommandType.UpgradeStoragePool, new UpgradeStoragePoolVDSCommandParameters(spId, targetFormat)); } }
Source:
@Nullable public TcpDiscoveryNode nextNode(@Nullable Collection<TcpDiscoveryNode> excluded) { assert locNode.internalOrder() > 0 : locNode; assert excluded == null || excluded.isEmpty() || !excluded.contains(locNode) : excluded; rwLock.readLock().lock(); try { Iterator<TcpDiscoveryNode> filtered = serverNodes(excluded, locNode).iterator(); if (filtered.hasNext()) { return filtered.next(); } else { filtered = serverNodes(excluded).iterator(); if (filtered.hasNext()) { TcpDiscoveryNode firstNode = filtered.next(); if (firstNode.equals(locNode)) return null; else return firstNode; } else return null; } } finally { rwLock.readLock().unlock(); } }

Target:
@Nullable public TcpDiscoveryNode nextNode(@Nullable Collection<TcpDiscoveryNode> excluded) { assert locNode.internalOrder() > 0 : locNode; assert excluded == null || excluded.isEmpty() || !excluded.contains(locNode) : excluded; rwLock.readLock().lock(); try { return notSyncNextNode(excluded); } finally { rwLock.readLock().unlock(); } }
Source:
public static IInputValidator getRemoteNameInputValidator( final StoredConfig config, final boolean errorOnEmptyName) { return new IInputValidator() { @Override public String isValid(String newText) { if (newText.length() == 0) { if (errorOnEmptyName) return UIText.ValidationUtils_PleaseEnterNameMessage; else return null; } if (config.getNames(RepositoriesView.REMOTE, newText).size() > 0) { return NLS.bind( UIText.ValidationUtils_RemoteAlreadyExistsMessage, newText); } return null; } }; }

Target:
public static IInputValidator getRemoteNameInputValidator( final StoredConfig config, final boolean errorOnEmptyName) { return new IInputValidator() { @Override public String isValid(String newText) { if (newText.length() == 0) { if (errorOnEmptyName) return UIText.ValidationUtils_PleaseEnterNameMessage; else return null; } if (!Repository.isValidRefName(Constants.R_REMOTES + newText)) { return NLS.bind( UIText.ValidationUtils_InvalidRemoteNameMessage, newText); } if (config.getNames(RepositoriesView.REMOTE, newText).size() > 0) { return NLS.bind( UIText.ValidationUtils_RemoteAlreadyExistsMessage, newText); } return null; } }; }
Source:
HTMLOptGroupElement makeOptionGroup(final String groupTitle, final List<DataType> dataTypes, final Function<DataType, String> dataTypeConsumer) { final HTMLOptGroupElement optionGroup = makeHTMLOptGroupElement(); optionGroup.label = groupTitle; dataTypes.stream() .sorted(DATA_TYPE_COMPARATOR) .forEach(dataType -> { final HTMLOptionElement option = makeOption(dataType, dataTypeConsumer); optionGroup.appendChild(option); }); return optionGroup; }

Target:
HTMLOptGroupElement makeOptionGroup(final String groupTitle, final List<DataType> dataTypes, final Function<DataType, String> dataTypeConsumer) { final HTMLOptGroupElement optionGroup = makeHTMLOptGroupElement(); optionGroup.label = groupTitle; dataTypes.stream() .forEach(dataType -> { final HTMLOptionElement option = makeOption(dataType, dataTypeConsumer); optionGroup.appendChild(option); }); return optionGroup; }
Source:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addSelfLink(); return description; } if (rep instanceof DefaultRepresentation || rep instanceof FullRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("name"); description.addProperty("description"); description.addProperty("identifierType"); description.addSelfLink(); if (rep instanceof DefaultRepresentation) { description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } } return description; }

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addSelfLink(); return description; } else if (rep instanceof DefaultRepresentation || rep instanceof FullRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("name"); description.addProperty("description"); description.addProperty("identifierType"); description.addSelfLink(); if (rep instanceof DefaultRepresentation) { description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } } return description; }
Source:
protected List<? extends Module> getModules() { return ImmutableList.<Module>of( new Module() { @Override public void configure(Binder binder) { binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/middlemanager"); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8091); IndexingServiceModuleHelper.configureTaskRunnerConfigs(binder); binder.bind(NodeTypeConfig.class).toInstance(new NodeTypeConfig("middlemanager")); JsonConfigProvider.bind(binder, "druid.indexer.task", TaskConfig.class); JsonConfigProvider.bind(binder, "druid.worker", WorkerConfig.class); binder.bind(TaskRunner.class).to(ForkingTaskRunner.class); binder.bind(ForkingTaskRunner.class).in(LazySingleton.class); binder.bind(ChatHandlerProvider.class).toProvider(Providers.<ChatHandlerProvider>of(null)); binder.bind(WorkerTaskMonitor.class).in(ManageLifecycle.class); binder.bind(WorkerCuratorCoordinator.class).in(ManageLifecycle.class); LifecycleModule.register(binder, WorkerTaskMonitor.class); binder.bind(JettyServerInitializer.class).toInstance(new MiddleManagerJettyServerInitializer()); Jerseys.addResource(binder, WorkerResource.class); LifecycleModule.register(binder, Server.class); } @Provides @LazySingleton public Worker getWorker(@Self DruidNode node, WorkerConfig config) { return new Worker( node.getHostAndPort(), config.getIp(), config.getCapacity(), config.getVersion() ); } }, new IndexingServiceFirehoseModule(), new IndexingServiceTaskLogsModule() ); }

Target:
protected List<? extends Module> getModules() { return ImmutableList.<Module>of( new Module() { @Override public void configure(Binder binder) { binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/middlemanager"); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8091); IndexingServiceModuleHelper.configureTaskRunnerConfigs(binder); binder.bind(NodeTypeConfig.class).toInstance(new NodeTypeConfig("middleManager")); JsonConfigProvider.bind(binder, "druid.indexer.task", TaskConfig.class); JsonConfigProvider.bind(binder, "druid.worker", WorkerConfig.class); binder.bind(TaskRunner.class).to(ForkingTaskRunner.class); binder.bind(ForkingTaskRunner.class).in(LazySingleton.class); binder.bind(ChatHandlerProvider.class).toProvider(Providers.<ChatHandlerProvider>of(null)); binder.bind(WorkerTaskMonitor.class).in(ManageLifecycle.class); binder.bind(WorkerCuratorCoordinator.class).in(ManageLifecycle.class); LifecycleModule.register(binder, WorkerTaskMonitor.class); binder.bind(JettyServerInitializer.class).toInstance(new MiddleManagerJettyServerInitializer()); Jerseys.addResource(binder, WorkerResource.class); LifecycleModule.register(binder, Server.class); } @Provides @LazySingleton public Worker getWorker(@Self DruidNode node, WorkerConfig config) { return new Worker( node.getHostAndPort(), config.getIp(), config.getCapacity(), config.getVersion() ); } }, new IndexingServiceFirehoseModule(), new IndexingServiceTaskLogsModule() ); }
Source:
private static boolean isClassController(Symbol.MethodSymbol methodSymbol) { SymbolMetadata parentClassOwner = methodSymbol.owner().metadata(); return parentClassOwner.isAnnotatedWith("org.springframework.stereotype.Controller"); }

Target:
private static boolean isClassController(Symbol.MethodSymbol methodSymbol) { return methodSymbol.owner().metadata().isAnnotatedWith("org.springframework.stereotype.Controller"); }
Source:
private ProducerConnectionContext init() throws JMSException, NamingException { InitialContext namingContext = new InitialContext(); TopicConnectionFactory tcf = (TopicConnectionFactory) namingContext.lookup( configuration.getConnectionFactoryJndiName()); ConnectionContextFactory ccf = new ConnectionContextFactory(tcf); ProducerConnectionContext producerConnectionContext = ccf.createProducerConnectionContext( new Endpoint(Endpoint.Type.TOPIC, configuration.getInventoryChangesTopicName())); return producerConnectionContext; }

Target:
private void init() throws JMSException { if (producerConnectionContext == null) { producerConnectionContext = connectionContextFactory.createProducerConnectionContext( new Endpoint(Endpoint.Type.TOPIC, topicName)); } }
Source:
public void update(float delta) { float animDelta = delta; if (animDelta > 0.1f) { animDelta = 0.1f; } if(animDelta == 0.0f) { animDelta = 0.035f; } flyIn.update(animDelta); flyOut.update(animDelta); }

Target:
public void update(float delta) { float animDelta = delta; if (animDelta > 0.1f) { animDelta = 0.1f; } if (animDelta < 0.0001f) { animDelta = PAUSED_ANIMATION_FRAME_TICK_TIME; } flyIn.update(animDelta); flyOut.update(animDelta); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(filePath.toString()); getPosition().ifPresent(position -> { builder.append(" ["); builder.append(position.getLine()); builder.append(':'); builder.append(position.getColumn()); builder.append(']'); }); return builder.toString(); }

Target:
public String toString() { return new ToStringBuilder(this) .append("file", file) .append("filePosition", filePosition) .toString(); }
Source:
public List<String> getGlobalStoresPrefixList() throws JSONException { UserAccount userAccount = getUserAccountManager().getCurrentUser(); String communityId = userAccount!=null?userAccount.getCommunityId():null; List<String> globalDBNames = DBOpenHelper.getGlobalDatabasePrefixList(context,getUserAccountManager().getCurrentUser(),communityId); return globalDBNames; }

Target:
public List<String> getGlobalStoresPrefixList(){ UserAccount userAccount = getUserAccountManager().getCurrentUser(); String communityId = userAccount!=null?userAccount.getCommunityId():null; List<String> globalDBNames = DBOpenHelper.getGlobalDatabasePrefixList(context,getUserAccountManager().getCurrentUser(),communityId); return globalDBNames; }
Source:
private boolean isLatestFormRecord(AndroidCommCarePlatform platform) { if (formDefId != -1) { Vector<Integer> formsForOurNamespace = FormDefRecord.getFormDefIdsByJrFormId(platform.getFormDefStorage(), namespace); if (formsForOurNamespace.size() == 1) { return true; } else if (formsForOurNamespace.size() > 1) { int maxFormResourceVersion = -1; for (int i = 0; i < formsForOurNamespace.size(); i++) { FormDefRecord formDefRecordItem = platform.getFormDefStorage().read(formsForOurNamespace.get(i)); if (formDefRecordItem.getResourceVersion() > maxFormResourceVersion) { maxFormResourceVersion = formDefRecordItem.getResourceVersion(); } } FormDefRecord currentFormDefRecord = platform.getFormDefStorage().read(formDefId); return maxFormResourceVersion == currentFormDefRecord.getResourceVersion(); } } return false; }

Target:
private boolean isLatestFormRecord(AndroidCommCarePlatform platform) { if (formDefId != -1) { return getLatestFormDefId(platform) == formDefId; } return false; }
Source:
public void should_fail_with_good_message_when_vararg_has_message_containing_assertion_is_failing() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatThrownBy(raisingException("boom")).hasMessageContaining("bam", "boom")) .withMessageContaining("Expecting:") .withMessageContaining("<\"boom\">") .withMessageContaining("<[\"bam\", \"boom\"]>").withMessageContaining("but could not find:") .withMessageContaining("<[\"bam\"]>"); }

Target:
public void should_fail_with_good_message_when_vararg_has_message_containing_assertion_is_failing() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatThrownBy(raisingException("boom")).hasMessageContaining("bam") .hasMessageContainingAll("boom", "Expecting:", "<\"boom\">", "<[\"bam\", \"boom\"]>", "but could not find:", "<[\"bam\"]>")); }
Source:
private static Set<String> getExternalResourceSet(Configuration config) { return new HashSet<>(ConfigUtils.decodeListFromConfig(config, ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, x -> x)); }

Target:
private static Set<String> getExternalResourceSet(Configuration config) { return new HashSet<>(config.get(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST)); }
Source:
public void shouldNotAllowToPersistNullItemsPrice() { Item saved = null; try { saved = itemRepository.save(new Item()); } catch (Exception e) { assertThat(saved).isNull(); assertThat(e).hasStackTraceContaining("must not be null"); } }

Target:
public void shouldNotAllowToPersistNullItemsPrice() { assertThatThrownBy(() -> itemRepository.save(new Item())) .hasRootCauseInstanceOf(ConstraintViolationException.class) .hasStackTraceContaining("must not be null"); }
Source:
public void shouldUnVoidAVisit() throws Exception { Visit visit = service.getVisitByUuid(RestTestConstants1_9.VISIT_UUID); visit = service.voidVisit(visit, "some random reason"); Assert.assertTrue(visit.isVoided()); String json = "{\"deleted\": \"false\"}"; SimpleObject response = deserialize(handle(newPostRequest(getURI() + "/" + getUuid(), json))); visit = service.getVisitByUuid(getUuid()); Assert.assertFalse(visit.isVoided()); Assert.assertEquals("false", PropertyUtils.getProperty(response, "voided").toString()); }

Target:
public void shouldUnVoidAVisit() throws Exception { Visit visit = service.getVisitByUuid(RestTestConstants1_9.VISIT_UUID); service.voidVisit(visit, "some random reason"); visit = service.getVisitByUuid(RestTestConstants1_9.VISIT_UUID); Assert.assertTrue(visit.isVoided()); String json = "{\"deleted\": \"false\"}"; SimpleObject response = deserialize(handle(newPostRequest(getURI() + "/" + getUuid(), json))); visit = service.getVisitByUuid(getUuid()); Assert.assertFalse(visit.isVoided()); Assert.assertEquals("false", PropertyUtils.getProperty(response, "voided").toString()); }
Source:
public Tool getToolFromNamespaceAndRepo(final String organization, final String repository) { throw new CustomWebApplicationException("Unsupported operation, only Quay.io is supported for now", HttpStatus.SC_BAD_REQUEST); }

Target:
public Tool getToolFromNamespaceAndRepo(final String organization, final String repository) { return unsupportedOperation(); }
Source:
protected boolean modifierFunction(ImmutableBytesWritable ptr, int length, int offset, byte[] arrayBytes, PDataType baseType, int arrayLength, Integer maxLength, Expression arrayExp) { SortOrder sortOrder = arrayExp.getSortOrder(); if (ptr.getLength() == 0 || arrayBytes.length == 0) { ptr.set(arrayBytes, offset, length); return true; } PhoenixArray array = (PhoenixArray) getDataType().toObject(arrayBytes, offset, length, getDataType(), sortOrder, maxLength, null); Object toCompare = baseType.toObject(ptr, sortOrder); if(baseType.isFixedWidth()) { toCompare = baseType.pad(toCompare, array.getMaxLength()); } int dimensions = array.getDimensions(); List<Object> values = new ArrayList<>(); for (int i = 0; i < dimensions; i++) { Object element = array.getElement(i); if (element != null && element.equals(toCompare) || (element.getClass().isArray() && ArrayUtils.isEquals(element, toCompare))) { if (getDataType().isFixedWidth()) { values.add(null); } } else { values.add(element); } } PhoenixArray newArray = PArrayDataType.instantiatePhoenixArray(baseType, values.toArray(new Object[values.size()])); if (baseType.isFixedWidth() && maxLength != null && maxLength != newArray.getMaxLength()) { newArray = new PhoenixArray(newArray, maxLength); } ptr.set(getDataType().toBytes(newArray, sortOrder)); return true; }

Target:
protected boolean modifierFunction(ImmutableBytesWritable ptr, int length, int offset, byte[] arrayBytes, PDataType baseType, int arrayLength, Integer maxLength, Expression arrayExp) { SortOrder sortOrder = arrayExp.getSortOrder(); if (ptr.getLength() == 0 || arrayBytes.length == 0) { ptr.set(arrayBytes, offset, length); return true; } PArrayDataTypeEncoder arrayDataTypeEncoder = new PArrayDataTypeEncoder(baseType, sortOrder); if (getRHSBaseType().equals(PChar.INSTANCE)) { int unpaddedCharLength = StringUtil.getUnpaddedCharLength(ptr.get(), ptr.getOffset(), ptr.getLength(), sortOrder); ptr.set(ptr.get(), offset, unpaddedCharLength); } for (int arrayIndex = 0; arrayIndex < arrayLength; arrayIndex++) { ImmutableBytesWritable ptr2 = new ImmutableBytesWritable(arrayBytes, offset, length); PArrayDataTypeDecoder.positionAtArrayElement(ptr2, arrayIndex, baseType, maxLength); if (baseType.compareTo(ptr2, sortOrder, ptr, sortOrder, baseType) != 0) { arrayDataTypeEncoder.appendValue(ptr2.get(), ptr2.getOffset(), ptr2.getLength()); } } ptr.set(arrayDataTypeEncoder.encode()); return true; }
Source:
private void testStudentProfile(StudentProfile studentProfile) { assertNotNull(studentProfile); assertNotNull(studentProfile.getPictureUrl()); assertEquals(pictureUrl, studentProfile.getPictureUrl()); assertEquals(inputStudent.name, studentProfile.getName()); assertEquals(inputStudentProfile.shortName, studentProfile.getShortName()); assertEquals(inputStudentProfile.gender.name(), studentProfile.getGender().toString()); assertEquals(inputStudentProfile.email, studentProfile.getEmail()); assertEquals(inputStudentProfile.institute, studentProfile.getInstitute()); assertEquals(inputStudentProfile.nationality, studentProfile.getNationality()); assertEquals(inputStudentProfile.moreInfo, studentProfile.getMoreInfo()); }

Target:
private void testStudentProfile(StudentProfile studentProfile) { assertNotNull(studentProfile); assertNotNull(studentProfile.getPictureUrl()); assertEquals(pictureUrl, studentProfile.getPictureUrl()); assertEquals(inputStudent.name, studentProfile.getName()); assertEquals(inputStudentProfile.shortName, studentProfile.getShortName()); assertEquals(inputStudentProfile.gender, studentProfile.getGender()); assertEquals(inputStudentProfile.email, studentProfile.getEmail()); assertEquals(inputStudentProfile.institute, studentProfile.getInstitute()); assertEquals(inputStudentProfile.nationality, studentProfile.getNationality()); assertEquals(inputStudentProfile.moreInfo, studentProfile.getMoreInfo()); }
Source:
public void testPushImageToPrivateAuthedRegistryWithoutAuth() throws Exception { final String containerId = startAuthedRegistry(client); final DefaultDockerClient client = DefaultDockerClient.fromEnv().build(); final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); client.build(Paths.get(dockerDirectory), LOCAL_IMAGE); boolean correctExceptionThrown = false; try { client.push(LOCAL_IMAGE); } catch (ImagePushFailedException e) { if (e.getMessage().contains("no basic auth credentials")) { correctExceptionThrown = true; } } assertTrue(correctExceptionThrown); stopAndRemoveContainer(client, containerId); }

Target:
public void testPushImageToPrivateAuthedRegistryWithoutAuth() throws Exception { registryContainerId = startAuthedRegistry(client); final DefaultDockerClient client = DefaultDockerClient.fromEnv().build(); final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); client.build(Paths.get(dockerDirectory), LOCAL_IMAGE); exception.expect(ImagePushFailedException.class); exception.expectMessage("no basic auth credentials"); client.push(LOCAL_IMAGE); }
Source:
public void invalidPropertiesFormat() { VmDevice device = new VmDevice(); device.setType(VmDeviceGeneralType.DISK); device.setCustomProperties("bootable"); DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateDeviceProperties(Version.v3_3, device); assertFalse(errors.isEmpty()); assertTrue(errors.get(0).getReason() == ValidationFailureReason.SYNTAX_ERROR); }

Target:
public void invalidPropertiesFormat() { VmDevice device = new VmDevice(); device.setType(VmDeviceGeneralType.DISK); device.setCustomProperties("bootable"); DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateDeviceProperties(Version.v3_3, device); assertFalse(errors.isEmpty()); assertEquals(ValidationFailureReason.SYNTAX_ERROR, errors.get(0).getReason()); }
Source:
public void checkIndentation() { final DetailAST firstChild = getMainAst().getFirstChild(); final boolean isSwitchExpressionLambda = firstChild == null; if (!isSwitchExpressionLambda && getLineStart(firstChild) == expandedTabsColumnNo(firstChild)) { final int firstChildColumnNo = expandedTabsColumnNo(firstChild); final IndentLevel level = getIndent(); if (isNonAcceptableIndent(firstChildColumnNo, level)) { isLambdaCorrectlyIndented = false; logError(firstChild, "arguments", firstChildColumnNo, level); } } final int mainAstColumnNo = expandedTabsColumnNo(getMainAst()); final boolean isLineWrappedLambda = mainAstColumnNo == getLineStart(getMainAst()); if (isLineWrappedLambda) { checkLineWrappedLambda(isSwitchExpressionLambda, mainAstColumnNo); } }

Target:
public void checkIndentation() { final DetailAST mainAst = getMainAst(); final DetailAST firstChild = mainAst.getFirstChild(); final boolean isSwitchRuleLambda = firstChild == null; if (!isSwitchRuleLambda && getLineStart(firstChild) == expandedTabsColumnNo(firstChild)) { final int firstChildColumnNo = expandedTabsColumnNo(firstChild); final IndentLevel level = getIndent(); if (isNonAcceptableIndent(firstChildColumnNo, level)) { isLambdaCorrectlyIndented = false; logError(firstChild, "arguments", firstChildColumnNo, level); } } final int mainAstColumnNo = expandedTabsColumnNo(mainAst); final boolean isLineWrappedLambda = mainAstColumnNo == getLineStart(mainAst); if (isLineWrappedLambda) { checkLineWrappedLambda(isSwitchRuleLambda, mainAstColumnNo); } }
Source:
private String getType(Contentlet contentlet) { return contentlet != null && contentlet.isHost() ? SITE_EVENT_SUFFIX : contentlet.getStructure().getName().replace(" ", "_").toUpperCase(); }

Target:
private String getType(Contentlet contentlet) { if (contentlet.isHost()){ return SITE_EVENT_SUFFIX; }else if (contentlet.getStructure() != null && contentlet.getStructure().getName() != null){ return contentlet.getStructure().getName().replace(" ", "_").toUpperCase(); }else{ throw new IllegalStateException("The Content type is null"); } }
Source:
private void replaceEnvironmentVariables(JsonNode node) { final Iterator<Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { final Entry<String, JsonNode> field = fields.next(); final String fieldName = field.getKey(); final String textValue = field.getValue().textValue(); if (!Strings.isNullOrEmpty(textValue)) { final Pattern pattern = Pattern.compile("\\$\\{(\\w+)\\}"); final Matcher matcher = pattern.matcher(textValue); if (matcher.find()) { final String envVariableName = matcher.group(1) == null ? matcher.group(2) : matcher.group(1); final String envVariableValue = System.getenv(envVariableName); if (!Strings.isNullOrEmpty(envVariableValue)) { ((ObjectNode) node).put(fieldName, envVariableValue); } } } } for (JsonNode child : node) { replaceEnvironmentVariables(child); } }

Target:
private void replaceEnvironmentVariables(JsonNode node) { final Iterator<Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { final Entry<String, JsonNode> field = fields.next(); final String fieldName = field.getKey(); final String textValue = field.getValue().textValue(); if (!Strings.isNullOrEmpty(textValue)) { final Matcher matcher = ENV_VAR_PATTERN.matcher(textValue); if (matcher.matches()) { final String envVariableName = matcher.group(1); if (System.getenv().containsKey(envVariableName)) { final String envVariableValue = System.getenv(envVariableName); ((ObjectNode) node).put(fieldName, envVariableValue); } } } } for (JsonNode child : node) { replaceEnvironmentVariables(child); } }
Source:
public static LocalPaxosComponents createWithBlockingMigration( TimelockPaxosMetrics metrics, PaxosUseCase paxosUseCase, Path legacyLogDirectory, DataSource sqliteDataSource, UUID leaderUuid, boolean canCreateNewClients) { LocalPaxosComponents components = new LocalPaxosComponents(metrics, paxosUseCase, legacyLogDirectory, sqliteDataSource, leaderUuid, canCreateNewClients); Path legacyClientDir = paxosUseCase.logDirectoryRelativeToDataDirectory(legacyLogDirectory); PersistentNamespaceLoader namespaceLoader = new DiskNamespaceLoader(legacyClientDir); namespaceLoader.getAllPersistedNamespaces().forEach(components::getOrCreateComponents); components.getOrCreateComponents(PaxosUseCase.PSEUDO_LEADERSHIP_CLIENT); return components; }

Target:
public static LocalPaxosComponents createWithBlockingMigration( TimelockPaxosMetrics metrics, PaxosUseCase paxosUseCase, Path legacyLogDirectory, DataSource sqliteDataSource, UUID leaderUuid, boolean canCreateNewClients) { LocalPaxosComponents components = new LocalPaxosComponents(metrics, paxosUseCase, legacyLogDirectory, sqliteDataSource, leaderUuid, canCreateNewClients); Path legacyClientDir = paxosUseCase.logDirectoryRelativeToDataDirectory(legacyLogDirectory); PersistentNamespaceLoader namespaceLoader = new DiskNamespaceLoader(legacyClientDir); namespaceLoader.getAllPersistedNamespaces().forEach(components::getOrCreateComponents); return components; }
Source:
public void addType(String typeId) { entityHelper.checkEntityTypeExists(typeId); EntityType entityType = dataService.getEntityType(entityHelper.getEntityTypeIdFromType(typeId)); if (!mutableAclClassService.getAclClassTypes().contains(typeId)) { mutableAclClassService.createAclClass(typeId, EntityIdentityUtils.toIdType(entityType)); dataService .findAll(entityType.getId()) .forEach( entity -> { try { mutableAclService.createAcl(new EntityIdentity(entity)); } catch (AlreadyExistsException e) { LOG.warn( "Acl for entity '{}' of type '{}' already exists", entity.getIdValue(), entityType.getIdValue()); } }); } else { throw new AclClassAlreadyExistsException(typeId); } }

Target:
public void addType(String typeId) { entityHelper.checkEntityTypeExists(typeId); entityHelper.checkIsNotSystem(typeId); EntityType entityType = dataService.getEntityType(entityHelper.getEntityTypeIdFromType(typeId)); if (mutableAclClassService.getAclClassTypes().contains(typeId)) { throw new AclClassAlreadyExistsException(typeId); } mutableAclClassService.createAclClass(typeId, EntityIdentityUtils.toIdType(entityType)); dataService .findAll(entityType.getId()) .forEach( entity -> { try { mutableAclService.createAcl(new EntityIdentity(entity)); } catch (AlreadyExistsException e) { throw new AclAlreadyExistsException(typeId, entityType.getId()); } }); }
Source:
private void loadFromCompilation() { List<Section> sections = new ArrayList<>(); sections.add(new Section()); String normalizedTitle = OfflineManager.instance().getNormalizedTitle(model.getTitle().getDisplayText()); PageTitle newTitle = TextUtils.isEmpty(normalizedTitle) ? model.getTitle() : new PageTitle(normalizedTitle, model.getTitle().getWikiSite()); Page page = new Page(newTitle, sections, new PageProperties(newTitle)); model.setPage(page); editHandler.setPage(model.getPage()); leadImagesHandler.beginLayout(new LeadImagesHandler.OnLeadImageLayoutListener() { @Override public void onLayoutComplete(int sequence) { if (!fragment.isAdded() || !sequenceNumber.inSync(sequence)) { return; } toolbarHideHandler.setFadeEnabled(leadImagesHandler.isLeadImageEnabled()); loadContentsFromCompilation(); } }, sequenceNumber.get()); if (webView.getVisibility() != View.VISIBLE) { webView.setVisibility(View.VISIBLE); } refreshView.setRefreshing(false); if (fragment.callback() != null) { fragment.callback().onPageUpdateProgressBar(true, true, 0); } }

Target:
private void loadFromCompilation() { String normalizedTitle = OfflineManager.instance().getNormalizedTitle(model.getTitle().getDisplayText()); PageTitle newTitle = TextUtils.isEmpty(normalizedTitle) ? model.getTitle() : new PageTitle(normalizedTitle, model.getTitle().getWikiSite()); Page page = new Page(newTitle, new ArrayList<Section>(), new PageProperties(newTitle)); model.setPage(page); editHandler.setPage(model.getPage()); leadImagesHandler.beginLayout(new LeadImagesHandler.OnLeadImageLayoutListener() { @Override public void onLayoutComplete(int sequence) { if (!fragment.isAdded() || !sequenceNumber.inSync(sequence)) { return; } toolbarHideHandler.setFadeEnabled(leadImagesHandler.isLeadImageEnabled()); loadContentsFromCompilation(); } }, sequenceNumber.get()); if (webView.getVisibility() != View.VISIBLE) { webView.setVisibility(View.VISIBLE); } refreshView.setRefreshing(false); if (fragment.callback() != null) { fragment.callback().onPageUpdateProgressBar(true, true, 0); } }
Source:
public int run() throws Exception { dbInjector = createDbInjector(MULTI_USER); manager.add(dbInjector); manager.start(); dbInjector.injectMembers(this); Project.NameKey project = new Project.NameKey(projectName); Repository git = gitManager.openRepository(project); try { PrologJar jarMaker = new PrologJar(config, site, git); return jarMaker.run() ? 0 : 1; } finally { git.close(); } }

Target:
public int run() throws Exception { dbInjector = createDbInjector(SINGLE_USER); manager.add(dbInjector); manager.start(); dbInjector.injectMembers(this); Project.NameKey project = new Project.NameKey(projectName); Repository git = gitManager.openRepository(project); try { PrologJar jarMaker = new PrologJar(config, site, git); jarMaker.run(); return 0; } finally { git.close(); } }
Source:
public MatchAttributeWithValue(String attributeName, String attributeRegex) { super("match attribute"); this.attributeName = attributeName; this.attributeRegex = Pattern.compile(attributeRegex, DOTALL); }

Target:
public MatchAttributeWithValue(String attributeName, String attributeRegex) { super("match attribute"); this.attributeName = attributeName; this.attributeRegex = Pattern.compile(attributeRegex); }
Source:
protected Void call() throws Volume.VolumeException, InterruptedException { try { vault.lock(false); } catch (Volume.VolumeException e) { LOG.debug("Regular lock of failed.", vault.getDisplayName(), e); var decision = askUserForAction(); switch (decision) { case FORCE -> vault.lock(true); case CANCEL -> cancel(false); default -> throw new IllegalArgumentException("Unknown decision " + decision); } } return null; }

Target:
protected Void call() throws Volume.VolumeException, InterruptedException { try { vault.lock(false); } catch (Volume.VolumeException e) { LOG.debug("Regular lock of failed.", vault.getDisplayName(), e); var decision = askUserForAction(); switch (decision) { case FORCE -> vault.lock(true); case CANCEL -> cancel(false); } } return null; }
Source:
public GroupRest getAdminGroup(@Nullable HttpServletRequest request, UUID communityId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Community community = communityService.find(context, communityId); if (community == null) { throw new ResourceNotFoundException("No such community: " + communityId); } Group administrators = community.getAdministrators(); if (!authorizeService.isAdmin(context) && !authorizeService.authorizeActionBoolean(context, community, Constants.ADMIN, true)) { throw new AccessDeniedException("The current user was not allowed to retrieve the AdminGroup for" + " community: " + communityId); } if (administrators == null) { return null; } return converter.toRest(administrators, projection); } catch (SQLException e) { throw new RuntimeException(e); } }

Target:
public GroupRest getAdminGroup(@Nullable HttpServletRequest request, UUID communityId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Community community = communityService.find(context, communityId); if (community == null) { throw new ResourceNotFoundException("No such community: " + communityId); } try { AuthorizeUtil.authorizeManageAdminGroup(context, community); } catch (AuthorizeException e) { throw new AccessDeniedException("The current user was not allowed to retrieve the AdminGroup for" + " community: " + communityId); } Group administrators = community.getAdministrators(); if (administrators == null) { return null; } return converter.toRest(administrators, projection); } catch (SQLException e) { throw new RuntimeException(e); } }