auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ImportVmFromExternalSourceModel(VmImportGeneralModel vmImportGeneralModel, VmImportDiskListModel importDiskListModel, VmImportInterfaceListModel vmImportInterfaceListModel, ClusterListModel<Void> cluster, QuotaListModel clusterQuota) { super(vmImportGeneralModel, importDiskListModel, vmImportInterfaceListModel, cluster, clusterQuota); getStorage().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { ListModel<StorageDomain> list = (ListModel<StorageDomain>)sender; ImportVmData importVmData = (ImportVmData) getItems().toArray()[0]; if (list.getSelectedItem().getStorageType().isBlockDomain() && importVmData.getVm().getOrigin() == OriginType.KVM) { setMessage(constants.kvmBlockDomainWraning()); } else { setMessage(""); } } }); }

Target:
public ImportVmFromExternalSourceModel(VmImportGeneralModel vmImportGeneralModel, VmImportDiskListModel importDiskListModel, VmImportInterfaceListModel vmImportInterfaceListModel, ClusterListModel<Void> cluster, QuotaListModel clusterQuota) { super(vmImportGeneralModel, importDiskListModel, vmImportInterfaceListModel, cluster, clusterQuota); getStorage().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { @SuppressWarnings("unchecked") ListModel<StorageDomain> list = (ListModel<StorageDomain>)sender; if (list.getSelectedItem().getStorageType().isBlockDomain() && containsKvmOrigin()) { setMessage(constants.kvmBlockDomainWraning()); } else { setMessage(""); } } }); }
Source:
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; }

Target:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { try { (new BugzillaXmlRpcOperation<Integer>(this) { @Override public Integer execute() throws XmlRpcException { call(monitor, XML_USER_LOGOUT); return -1; } }).execute(); } catch (XmlRpcException e) { e.printStackTrace(); throw e; } finally { userID = -1; token = null; } return; }
Source:
public SingleThreadedEventHandlingStrategy(SessionConnector connector, int queueLowerWatermark, int queueUpperWatermark) { sessionConnector = connector; eventQueue = new LinkedBlockingQueue<>(); queueTracker = WatermarkTracker.newMulti(eventQueue, queueLowerWatermark, queueUpperWatermark, evt -> evt.quickfixSession, qfSession -> { final IoSession ioSession = lookupIoSession(qfSession); if (ioSession != null && ioSession.isReadSuspended()) { ioSession.resumeRead(); LOG.info("{}: inbound queue size < lower watermark ({}), socket reads resumed", qfSession.getSessionID(), queueLowerWatermark); } }, qfSession -> { final IoSession ioSession = lookupIoSession(qfSession); if (ioSession != null && !ioSession.isReadSuspended()) { ioSession.suspendRead(); LOG.info("{}: inbound queue size > upper watermark ({}), socket reads suspended", qfSession.getSessionID(), queueUpperWatermark); } }); }

Target:
public SingleThreadedEventHandlingStrategy(SessionConnector connector, int queueLowerWatermark, int queueUpperWatermark) { sessionConnector = connector; eventQueue = new LinkedBlockingQueue<>(); queueTracker = newMultiSessionWatermarkTracker(eventQueue, queueLowerWatermark, queueUpperWatermark, evt -> evt.quickfixSession); }
Source:
protected void executeQueryCommand() { Disk diskFromDao = getDbFacade().getDiskDao().get(getParameters().getEntityId()); if (diskFromDao != null) { log.info("The disk already exist in the DB, hence, should not be fetched from Cinder."); getQueryReturnValue().setReturnValue(null); return; } Volume Volume = getVolumeProviderProxy().getVolumeById(getParameters().getEntityId().toString()); Guid storageDomainId = getParameters().getId(); CinderDisk unregisteredDisk = CinderBroker.volumeToCinderDisk(Volume, storageDomainId); getQueryReturnValue().setReturnValue(unregisteredDisk); }

Target:
protected void executeQueryCommand() { Disk diskFromDao = getDbFacade().getDiskDao().get(getParameters().getEntityId()); if (diskFromDao != null) { log.info("The disk already exist in the DB, hence, should not be fetched from Cinder. ID: '{}', Alias: '{}'", diskFromDao.getId(), diskFromDao.getDiskAlias()); getQueryReturnValue().setReturnValue(null); return; } String volumeId = getParameters().getEntityId().toString(); Volume volume = getVolumeProviderProxy().getVolumeById(volumeId); if (volume == null) { log.info("The volume doesn't exist in Cinder. ID: '{}'", volumeId); getQueryReturnValue().setReturnValue(null); return; } Guid storageDomainId = getParameters().getId(); CinderDisk unregisteredDisk = CinderBroker.volumeToCinderDisk(volume, storageDomainId); getQueryReturnValue().setReturnValue(unregisteredDisk); }
Source:
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException { try { MinioClient minioClient = new MinioClient( "<LINK_1>", "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"); if (minioClient.bucketExists("my-bucketname")) { System.out.println("my-bucketname already exists"); } else { minioClient.makeBucket(MakeBucketArgs.builder().bucket("my-bucketname").build()); System.out.println("my-bucketname is created successfully"); } if (minioClient.bucketExists("my-bucketname2")) { System.out.println("my-bucketname2 already exists"); } else { minioClient.makeBucket( MakeBucketArgs.builder().bucket("my-bucketname2").region("us-west-1").build()); System.out.println("my-bucketname2 is created successfully"); } if (minioClient.bucketExists("my-bucketname3")) { System.out.println("my-bucketname3 already exists"); } else { minioClient.makeBucket( MakeBucketArgs.builder() .bucket("my-bucketname3") .region("us-west-1") .objectLock(true) .build()); System.out.println("my-bucketname3 is created successfully"); } } catch (MinioException e) { System.out.println("Error occurred: " + e); } }

Target:
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException { try { MinioClient minioClient = new MinioClient( "<LINK_1>", "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"); if (!minioClient.bucketExists("my-bucketname")) { minioClient.makeBucket(MakeBucketArgs.builder().bucket("my-bucketname").build()); System.out.println("my-bucketname is created successfully"); } if (!minioClient.bucketExists("my-bucketname-in-eu")) { minioClient.makeBucket( MakeBucketArgs.builder().bucket("my-bucketname-in-eu").region("eu-west-1").build()); System.out.println("my-bucketname-in-eu is created successfully"); } if (!minioClient.bucketExists("my-bucketname-in-eu-with-object-lock")) { minioClient.makeBucket( MakeBucketArgs.builder() .bucket("my-bucketname-in-eu-with-object-lock") .region("eu-west-1") .objectLock(true) .build()); System.out.println("my-bucketname-in-eu-with-object-lock is created successfully"); } } catch (MinioException e) { System.out.println("Error occurred: " + e); } }
Source:
public void testXmlHttpDigest() { String cp = "REST_XML_DIGEST"; RestConnectionProfileWizard.openWizard(cp) .setConnectionUrl("<LINK_0>") .setType(RestConnectionProfileWizard.TYPE_XML) .setAuth(RestConnectionProfileWizard.AUTH_TYPE_DIGEST, "user", "user") .testConnection() .finish(); String sourceModel = "RestXmlDigestSource"; String viewModel = "RestXmlDigestView"; RestImportWizard.openWizard() .setProfileName(cp) .nextPage() .setProject(PROJECT_NAME) .setSourceModelName(sourceModel) .setViewModelName(viewModel) .setProcedureName(PROCEDURE_NAME) .nextPage() .setJndiName(sourceModel + "DS") .nextPage() .setRootPath("schedule/day/broadcasts/broadcast") .setColumns("pid","start","end","programme/title") .finish(); String vdb = "RestXmlDigestVdb"; VdbWizard.openVdbWizard() .setLocation(PROJECT_NAME) .setName(vdb) .addModel(PROJECT_NAME, viewModel) .finish(); ServersViewExt.getInstance().refreshServer(teiidServer.getName()); modelExplorer.deployVdb(PROJECT_NAME, vdb); TeiidJDBCHelper jdbchelper = new TeiidJDBCHelper(teiidServer, vdb); assertEquals(16, jdbchelper.getNumberOfResults("exec " + viewModel + "." + PROCEDURE_NAME + "()")); }

Target:
public void testXmlHttpDigest() { String sourceModel = "RestXmlDigestSource"; String viewModel = "RestXmlDigestView"; RestImportWizard.openWizard() .setProfileName(ConnectionProfileConstants.REST_XML_SECURE) .nextPage() .setProject(PROJECT_NAME) .setSourceModelName(sourceModel) .setViewModelName(viewModel) .setProcedureName(PROCEDURE_NAME) .nextPage() .setJndiName(sourceModel + "DS") .nextPage() .setRootPath("schedule/day/broadcasts/broadcast") .setColumns("pid","start","end","programme/title") .finish(); String vdb = "RestXmlDigestVdb"; VdbWizard.openVdbWizard() .setLocation(PROJECT_NAME) .setName(vdb) .addModel(PROJECT_NAME, viewModel) .finish(); ServersViewExt.getInstance().refreshServer(teiidServer.getName()); modelExplorer.deployVdb(PROJECT_NAME, vdb); TeiidJDBCHelper jdbchelper = new TeiidJDBCHelper(teiidServer, vdb); assertEquals(16, jdbchelper.getNumberOfResults("exec " + viewModel + "." + PROCEDURE_NAME + "()")); }
Source:
private String getBaseUri() { String interfaceName = clientInterface.getName(); String property = String.format(REST_URI_FORMAT, interfaceName); String baseURI = null; try { baseURI = ConfigFacade.getOptionalValue(property, String.class).orElse(null); } catch (NoSuchElementException ex) { } if (baseURI == null) { property = String.format(REST_URL_FORMAT, interfaceName); baseURI = ConfigFacade.getOptionalValue(property, String.class).orElse(null); } if (baseURI == null) { RegisterRestClient anno = clientInterface.getAnnotation(RegisterRestClient.class); if (anno != null) { String annoUri = anno.baseUri(); if (annoUri != null && !"".equals(anno.baseUri())) { baseURI = annoUri; } } } if (baseURI == null) { throw new IllegalStateException("Unable to determine base URI from configuration for " + interfaceName); } return baseURI; }

Target:
private String getBaseUri() { String interfaceName = clientInterface.getName(); String baseURI = ConfigFacade .getOptionalValue(String.format(REST_URI_FORMAT, interfaceName), String.class) .orElseGet(() -> ConfigFacade.getOptionalValue(String.format(REST_URL_FORMAT, interfaceName), String.class).orElse(null)); if (baseURI == null) { RegisterRestClient anno = clientInterface.getAnnotation(RegisterRestClient.class); if (anno != null) { String annoUri = anno.baseUri(); if (annoUri != null && !"".equals(anno.baseUri())) { baseURI = annoUri; } } } if (baseURI == null) { throw new IllegalStateException("Unable to determine base URI from configuration for " + interfaceName); } return baseURI; }
Source:
public List<OntClass> listClasses(Resource res) { List<String> types = res.listProperties(RDF.type).toList().stream() .map(st -> st.getObject().asResource().getURI()) .collect(Collectors.toList()); return ontology.listClasses().toList().stream() .filter(cls -> types.contains(cls.getURI())) .collect(Collectors.toList()); }

Target:
public Set<OntClass> listClasses(Resource res) { Set<OntClass> classes = new HashSet<>(); OntClass cls = ontology.getOntClass(res.listProperties(RDF.type) .toList().get(0).getObject().asResource().getURI()); classes.add(cls); classes.addAll(cls.listSuperClasses().toSet()); return classes; }
Source:
public void testEliminateCrossJoin() { tester.assertThat(new EliminateCrossJoins()) .setSystemProperty(REORDER_JOINS, "true") .on(crossJoinAndJoin(INNER)) .matches( join(INNER, ImmutableList.of(aliases -> new EquiJoinClause(new Symbol("cySymbol"), new Symbol("bySymbol"))), join(INNER, ImmutableList.of(aliases -> new EquiJoinClause(new Symbol("axSymbol"), new Symbol("cxSymbol"))), any(), any() ), any() ) ); }

Target:
public void testEliminateCrossJoin() { tester().assertThat(new EliminateCrossJoins()) .setSystemProperty(REORDER_JOINS, "true") .on(crossJoinAndJoin(INNER)) .matches( join(INNER, ImmutableList.of(aliases -> new EquiJoinClause(new Symbol("cySymbol"), new Symbol("bySymbol"))), join(INNER, ImmutableList.of(aliases -> new EquiJoinClause(new Symbol("axSymbol"), new Symbol("cxSymbol"))), any(), any() ), any() ) ); }
Source:
public FormValidation doTestConnection(@QueryParameter("slackTeamDomain") final String teamDomain, @QueryParameter("slackToken") final String authToken, @QueryParameter("slackRoom") final String room, @QueryParameter("slackBuildServerUrl") final String buildServerUrl) throws FormException { try { SlackService testSlackService = new StandardSlackService(StringUtils.isEmpty(teamDomain) ? this.teamDomain : teamDomain, StringUtils.isEmpty(authToken) ? this.token : authToken, StringUtils.isEmpty(room) ? this.room : room); String message = "Slack/Jenkins plugin: you're all set on " + (StringUtils.isEmpty(buildServerUrl) ? this.buildServerUrl : buildServerUrl); boolean success = testSlackService.publish(message, "green"); return success ? FormValidation.ok("Success") : FormValidation.error("Failure"); } catch (Exception e) { return FormValidation.error("Client error : " + e.getMessage()); } }

Target:
public FormValidation doTestConnection(@QueryParameter("slackTeamDomain") final String teamDomain, @QueryParameter("slackToken") final String authToken, @QueryParameter("slackRoom") final String room, @QueryParameter("slackBuildServerUrl") final String buildServerUrl) throws FormException { try { String targetDomain = teamDomain; if (StringUtils.isEmpty(targetDomain)) { targetDomain = this.teamDomain; } String targetToken = authToken; if (StringUtils.isEmpty(targetToken)) { targetToken = this.token; } String targetRoom = room; if (StringUtils.isEmpty(targetRoom)) { targetRoom = this.room; } String targetBuildServerUrl = buildServerUrl; if (StringUtils.isEmpty(targetBuildServerUrl)) { targetBuildServerUrl = this.buildServerUrl; } SlackService testSlackService = getSlackService(targetDomain, targetToken, targetRoom); String message = "Slack/Jenkins plugin: you're all set on " + targetBuildServerUrl; boolean success = testSlackService.publish(message, "green"); return success ? FormValidation.ok("Success") : FormValidation.error("Failure"); } catch (Exception e) { return FormValidation.error("Client error : " + e.getMessage()); } }
Source:
public void onError(Throwable e) { try { log.warn("Fetching data failed", e); generator.close(); } catch (IOException e1) { log.error("Failed to close " + generator.getClass().getName()); } }

Target:
public void onError(Throwable e) { try { log.warn("Fetching data failed", e); generator.close(); } catch (IOException e1) { log.error("Failed to close " + generator.getClass().getName()); } finally { latch.countDown(); } }
Source:
Optional<String> getLatestCloneName(String topologyName, Collection<Topology> topologies) { String prefix = getTopologyClonePrefix(topologyName); return topologies.stream() .filter(t -> t.getName().startsWith(prefix)) .map(Topology::getName) .max((t1, t2) -> getCloneNum(t1) - getCloneNum(t2)); }

Target:
Optional<String> getLatestCloneName(String topologyName, Collection<Topology> topologies) { return Utils.getLatestName( topologies.stream().map(Topology::getName).collect(Collectors.toSet()), Utils.getPrefix(topologyName, CLONE_SUFFIX), CLONE_SUFFIX); }
Source:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); ClientRegistration clientRegistration = context.getClientRegistration(); OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (!AuthorizationGrantType.PASSWORD.equals(clientRegistration.getAuthorizationGrantType()) || authorizedClient != null) { return null; } String username = context.getAttribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME); String password = context.getAttribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME); if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) { return null; } OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, username, password); OAuth2AccessTokenResponse tokenResponse = this.accessTokenResponseClient.getTokenResponse(passwordGrantRequest); return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()); }

Target:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); ClientRegistration clientRegistration = context.getClientRegistration(); OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (!AuthorizationGrantType.PASSWORD.equals(clientRegistration.getAuthorizationGrantType())) { return null; } String username = context.getAttribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME); String password = context.getAttribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME); if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) { return null; } if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) { return null; } if (authorizedClient != null && hasTokenExpired(authorizedClient.getAccessToken()) && authorizedClient.getRefreshToken() != null) { return null; } OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, username, password); OAuth2AccessTokenResponse tokenResponse = this.accessTokenResponseClient.getTokenResponse(passwordGrantRequest); return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()); }
Source:
public String apply(ProjectResource rsrc, Input input) throws Exception { Project project = rsrc.getControl().getProject(); databaseDeleteHandler.delete(project); filesystemDeleteHandler.delete(project, input == null ? false : input.preserve); cacheDeleteHandler.delete(project); return String.format("The project \"%s\" was successfully deleted", rsrc.getName()); }

Target:
public Object apply(ProjectResource rsrc, Input input) throws Exception { Project project = rsrc.getControl().getProject(); databaseDeleteHandler.delete(project); filesystemDeleteHandler.delete(project, input == null ? false : input.preserve); cacheDeleteHandler.delete(project); return Response.none(); }
Source:
public void perform(GraphRewrite event, EvaluationContext context, ArchiveModel originalArchive) { if (!originalArchive.getDuplicateArchives().iterator().hasNext()) { return; } ArchiveModel originalParentArchive = originalArchive.getParentArchive(); FileModel originalArchiveParentFile = originalArchive.getParentFile(); originalArchive.setParentFile(null); originalArchive.setParentArchive(null); GraphService<DuplicateArchiveModel> duplicateArchiveService = event.getGraphContext().service(DuplicateArchiveModel.class); DuplicateArchiveModel duplicateArchive = duplicateArchiveService.create(); duplicateArchive.setOriginalArchive(originalArchive); duplicateArchive.setSHA1Hash(originalArchive.getSHA1Hash()); duplicateArchive.setFilePath(originalArchive.getFilePath()); duplicateArchive.setArchiveName(originalArchive.getArchiveName()); duplicateArchive.setFileName(originalArchive.getFileName()); duplicateArchive.setParentArchive(originalParentArchive); duplicateArchive.setParentFile(originalArchiveParentFile); }

Target:
public void perform(GraphRewrite event, EvaluationContext context, ArchiveModel originalArchive) { if (!originalArchive.getDuplicateArchives().iterator().hasNext()) { return; } ArchiveModel originalParentArchive = originalArchive.getParentArchive(); FileModel originalArchiveParentFile = originalArchive.getParentFile(); originalArchive.setParentFile(null); originalArchive.setParentArchive(null); GraphService<DuplicateArchiveModel> duplicateArchiveService = event.getGraphContext().service(DuplicateArchiveModel.class); DuplicateArchiveModel duplicateArchive = duplicateArchiveService.create(); duplicateArchive.setCanonicalArchive(originalArchive); duplicateArchive.setSHA1Hash(originalArchive.getSHA1Hash()); duplicateArchive.setFilePath(originalArchive.getFilePath()); duplicateArchive.setArchiveName(originalArchive.getArchiveName()); duplicateArchive.setFileName(originalArchive.getFileName()); duplicateArchive.setParentArchive(originalParentArchive); duplicateArchive.setParentFile(originalArchiveParentFile); }
Source:
private void addFunctionBlock(FunctionEntry entry) { try { FunctionBlock fb = new FunctionBlock(entry.getName(), entry.asHaskellObject(new Context()), parent); addBlock(fb); } catch (IOException e) { e.printStackTrace(); } }

Target:
private void addFunctionBlock(FunctionEntry entry) { try { Type type = entry.asHaskellObject(new Context()); FunctionBlock fb = new FunctionBlock(entry.getName(), type, parent); addBlock(fb); } catch (IOException e) { e.printStackTrace(); } }
Source:
public ScheduledFuture scheduleTask() { return scheduler.scheduleWithFixedDelay(() -> { try { if (!table.getEntity(currentJMVersion.get(), processorId).getIsLeader()) { LOG.info("Not the leader anymore. Shutting down LeaderBarrierCompleteScheduler."); scheduler.shutdownNow(); barrierTimeout.getAndSet(true); listener.onStateChange(); } LOG.info("Leader checking for barrier state"); Iterable<ProcessorEntity> tableList = table.getEntitiesWithPartition(nextJMVersion); Set<String> tableProcessors = new HashSet<>(); for (ProcessorEntity entity : tableList) { tableProcessors.add(entity.getRowKey()); } LOG.info("blobProcessorSet = {}", blobProcessorSet); LOG.info("tableProcessors = {}", tableProcessors); if ((System.currentTimeMillis() - startTime) > (BARRIER_TIMEOUT_SEC * 1000)) { barrierTimeout.getAndSet(true); listener.onStateChange(); } else if (blobProcessorSet.equals(tableProcessors)) { listener.onStateChange(); } } catch (Exception e) { errorHandler.accept("Exception in LeaderBarrierCompleteScheduler. Stopping the processor..."); } }, BARRIER_REACHED_DELAY_SEC, BARRIER_REACHED_DELAY_SEC, TimeUnit.SECONDS); }

Target:
public ScheduledFuture scheduleTask() { return scheduler.scheduleWithFixedDelay(() -> { try { if (!table.getEntity(currentJMVersion.get(), processorId).getIsLeader()) { LOG.info("Not the leader anymore. Shutting down LeaderBarrierCompleteScheduler."); barrierTimeout.getAndSet(true); listener.onStateChange(); } else { LOG.info("Leader checking for barrier state"); Iterable<ProcessorEntity> tableList = table.getEntitiesWithPartition(nextJMVersion); Set<String> tableProcessors = new HashSet<>(); for (ProcessorEntity entity : tableList) { tableProcessors.add(entity.getRowKey()); } LOG.info("List of live processors as seen on the blob = {}", blobProcessorSet); LOG.info("List of live processors as seen in the table = {}", tableProcessors); if ((System.currentTimeMillis() - startTime) > (BARRIER_TIMEOUT_SEC * 1000)) { barrierTimeout.getAndSet(true); listener.onStateChange(); } else if (blobProcessorSet.equals(tableProcessors)) { listener.onStateChange(); } } } catch (Exception e) { errorHandler.accept("Exception in LeaderBarrierCompleteScheduler. Stopping the processor..."); } }, BARRIER_REACHED_DELAY_SEC, BARRIER_REACHED_DELAY_SEC, TimeUnit.SECONDS); }
Source:
private MethodInvocation createInvocation(AST ast, Expression operand, String operator) { if (fSetter.isEmpty() || fGetter.isEmpty()) { return null; } Expression receiver= getReceiver(operand); InfixExpression argument= ast.newInfixExpression(); MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(fSetter)); if (receiver != null) invocation.setExpression((Expression)fRewriter.createCopyTarget(receiver)); invocation.arguments().add(argument); if ("++".equals(operator)) { argument.setOperator(InfixExpression.Operator.PLUS); } else if ("--".equals(operator)) { argument.setOperator(InfixExpression.Operator.MINUS); } else { Assert.isTrue(false, "Should not happen"); } fReferencingSetter= true; MethodInvocation getter= ast.newMethodInvocation(); getter.setName(ast.newSimpleName(fGetter)); if (receiver != null) getter.setExpression((Expression)fRewriter.createCopyTarget(receiver)); argument.setLeftOperand(getter); argument.setRightOperand(ast.newNumberLiteral("1")); fReferencingGetter= true; return invocation; }

Target:
private MethodInvocation createInvocation(AST ast, Expression operand, String operator) { if (fSetter.isEmpty() || fGetter.isEmpty()) { return null; } Expression receiver= getReceiver(operand); MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(fSetter)); if (receiver != null) invocation.setExpression((Expression)fRewriter.createCopyTarget(receiver)); InfixExpression argument= ast.newInfixExpression(); invocation.arguments().add(argument); if ("++".equals(operator)) { argument.setOperator(InfixExpression.Operator.PLUS); } else if ("--".equals(operator)) { argument.setOperator(InfixExpression.Operator.MINUS); } else { Assert.isTrue(false, "Should not happen"); } MethodInvocation getter= ast.newMethodInvocation(); getter.setName(ast.newSimpleName(fGetter)); if (receiver != null) getter.setExpression((Expression)fRewriter.createCopyTarget(receiver)); argument.setLeftOperand(getter); argument.setRightOperand(ast.newNumberLiteral("1")); fReferencingGetter= true; fReferencingSetter= true; return invocation; }
Source:
public void testRedefinitionZeppelinContext() { if (getSparkVersionNumber() > 11) { String redefinitionCode = "z = 1\n"; String restoreCode = "z = _zc\n"; String validCode = "z.input(\"test\")\n"; assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret(validCode, context).code()); assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret(redefinitionCode, context).code()); assertEquals(InterpreterResult.Code.ERROR, pySparkInterpreter.interpret(validCode, context).code()); assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret(restoreCode, context).code()); assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret(validCode, context).code()); } }

Target:
public void testRedefinitionZeppelinContext() { if (getSparkVersionNumber() > 11) { String redefinitionCode = "z = 1\n"; String restoreCode = "z = __zeppelin__\n"; String validCode = "z.input(\"test\")\n"; assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret(validCode, context).code()); assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret(redefinitionCode, context).code()); assertEquals(InterpreterResult.Code.ERROR, pySparkInterpreter.interpret(validCode, context).code()); assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret(restoreCode, context).code()); assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret(validCode, context).code()); } }
Source:
public void componentNotFound() { showMessage("Component was not found."); }

Target:
public void componentNotFound() { showMessage(i18n.componentNotFound()); }
Source:
public static synchronized Path handleIngestUrl( final String ingestUrl, final Properties configProperties) throws IOException { if (urlHandlerList == null) { final Iterator<IngestUrlHandlerSpi> handlers = new SPIServiceRegistry(IngestUrlHandlerSpi.class).load(IngestUrlHandlerSpi.class); urlHandlerList = new ArrayList<>(); while (handlers.hasNext()) { urlHandlerList.add(handlers.next()); } } for (final IngestUrlHandlerSpi h : urlHandlerList) { final Path path = h.handlePath(ingestUrl, configProperties); if (path != null) { return path; } } return null; }

Target:
public static synchronized Path handleIngestUrl( final String ingestUrl, final Properties configProperties) throws IOException { if (urlHandlerList == null) { final Iterator<IngestUrlHandlerSpi> handlers = new SPIServiceRegistry(IngestUrlHandlerSpi.class).load(IngestUrlHandlerSpi.class); urlHandlerList = Lists.newArrayList(handlers); } for (final IngestUrlHandlerSpi h : urlHandlerList) { final Path path = h.handlePath(ingestUrl, configProperties); if (path != null) { return path; } } return null; }
Source:
public EnterpriseBeanProxyMethodHandler(SessionBean<T> bean, SessionObjectReference reference) { this.bean = bean; this.manager = bean.getBeanManager(); this.beanId = bean.getIdentifier(); this.reference = reference; BeanLogger.LOG.createdSessionBeanProxy(bean); }

Target:
private EnterpriseBeanProxyMethodHandler(SessionBean<T> bean, SessionObjectReference reference) { this.bean = bean; this.manager = bean.getBeanManager(); this.beanId = bean.getIdentifier(); Map<Class<?>, Class<?>> typeToBusinessInterfaceMap = new HashMap<Class<?>, Class<?>>(); discoverBusinessInterfaces(typeToBusinessInterfaceMap, bean.getEjbDescriptor().getRemoteBusinessInterfacesAsClasses()); discoverBusinessInterfaces(typeToBusinessInterfaceMap, bean.getEjbDescriptor().getLocalBusinessInterfacesAsClasses()); this.typeToBusinessInterfaceMap = ImmutableMap.copyOf(typeToBusinessInterfaceMap); if (reference == null) { this.reference = bean.createReference(); BeanLogger.LOG.createdSessionBeanProxy(bean); } else { this.reference = reference; BeanLogger.LOG.activatedSessionBeanProxy(bean); } }
Source:
@Test public void testDistinctWithFilterAndGroupBy() { final String sql = "SELECT deptno, SUM(comm), COUNT(DISTINCT comm),\n" + "COUNT(DISTINCT sal) FILTER (WHERE sal > 1000)\n" + "FROM emp\n" + "GROUP BY deptno"; HepProgram program = new HepProgramBuilder() .addRuleInstance(AggregateExpandDistinctAggregatesRule.INSTANCE) .build(); sql(sql).with(program).check(); }

Target:
@Test public void testDistinctWithFilterAndGroupBy() { final String sql = "SELECT deptno, SUM(comm), COUNT(DISTINCT sal) FILTER (WHERE sal > 1000)\n" + "FROM emp\n" + "GROUP BY deptno"; HepProgram program = new HepProgramBuilder() .addRuleInstance(AggregateExpandDistinctAggregatesRule.INSTANCE) .build(); sql(sql).with(program).check(); }
Source:
public void configure(JobConf job) { InitializationProperties props = new InitializationProperties(); props.setZookeepers(job.get("io.fluo.zookeeper.connect")); props.setZookeeperRoot(job.get("io.fluo.zookeeper.root")); props.setAccumuloInstance(job.get("io.fluo.accumulo.instance")); props.setAccumuloUser(job.get("io.fluo.accumulo.user")); props.setAccumuloPassword(job.get("io.fluo.accumulo.password")); nodeSize = job.getInt("trie.node.size", 4); LoaderExecutorProperties lep = new LoaderExecutorProperties(props); try { le = new LoaderExecutor(lep); } catch (Exception e) { e.printStackTrace(); } }

Target:
public void configure(JobConf job) { InitializationProperties props = new InitializationProperties(); props.setZookeepers(job.get(Constants.FLUO_PREFIX + ".zookeeper.connect")); props.setZookeeperRoot(job.get(Constants.FLUO_PREFIX + ".zookeeper.root")); props.setAccumuloInstance(job.get(Constants.FLUO_PREFIX + ".accumulo.instance")); props.setAccumuloUser(job.get(Constants.FLUO_PREFIX + ".accumulo.user")); props.setAccumuloPassword(job.get(Constants.FLUO_PREFIX + ".accumulo.password")); nodeSize = job.getInt("trie.node.size", 4); LoaderExecutorProperties lep = new LoaderExecutorProperties(props); try { le = new LoaderExecutor(lep); } catch (Exception e) { e.printStackTrace(); } }
Source:
private void setupImportObservedButton( final View view ) { final Button importObservedButton = (Button) view.findViewById( R.id.import_observed_button ); final SharedPreferences prefs = getActivity().getSharedPreferences(ListFragment.SHARED_PREFS, 0); final String authname = prefs.getString(ListFragment.PREF_AUTHNAME, null); if (null == authname) { importObservedButton.setEnabled(false); } else if (MainActivity.getMainActivity().isTransferring()) { importObservedButton.setEnabled(false); } else { importObservedButton.setOnClickListener(new OnClickListener() { @Override public void onClick(final View buttonView) { MainActivity.createConfirmation(getActivity(), DataFragment.this.getString(R.string.data_import_observed), MainActivity.DATA_TAB_POS, IMPORT_DIALOG); } }); } }

Target:
private void setupImportObservedButton( final View view ) { final Button importObservedButton = (Button) view.findViewById( R.id.import_observed_button ); final SharedPreferences prefs = getActivity().getSharedPreferences(ListFragment.SHARED_PREFS, 0); final String authname = prefs.getString(ListFragment.PREF_AUTHNAME, null); if (null == authname) { importObservedButton.setEnabled(false); } else if (MainActivity.getMainActivity().isTransferring()) { importObservedButton.setEnabled(false); } importObservedButton.setOnClickListener(new OnClickListener() { @Override public void onClick(final View buttonView) { MainActivity.createConfirmation(getActivity(), DataFragment.this.getString(R.string.data_import_observed), MainActivity.DATA_TAB_POS, IMPORT_DIALOG); } }); }
Source:
private void deleteExecutionDir(final int executionId) { LOGGER.debug("Deleting execution directory for " + executionId); synchronized (this.executionDirDeletionSync) { final Path flowExecutionDir = Paths.get(this.executionDirectory.toPath().toString(), String.valueOf(executionId)); try { FileUtils.deleteDirectory(flowExecutionDir.toFile()); } catch (final IOException e) { LOGGER.warn("Error when deleting directory " + flowExecutionDir.toAbsolutePath() + ".", e); } } }

Target:
private void deleteExecutionDir(final int executionId) { LOGGER.info("Deleting execution directory for " + executionId); synchronized (this.executionDirDeletionSync) { LOGGER.info("Starting execution directory deletion for " + executionId); final Path flowExecutionDir = Paths.get(this.executionDirectory.toPath().toString(), String.valueOf(executionId)); try { FileUtils.deleteDirectory(flowExecutionDir.toFile()); } catch (final IOException e) { LOGGER.warn("Error when deleting directory " + flowExecutionDir.toAbsolutePath() + ".", e); } } }
Source:
public long getItemId(int position) { return getItemAtPosition(position)._id; }

Target:
public long getItemId(int position) { if (isValidPosition(position)) { return getItemAtPosition(position)._id; } else { return NO_POSITION; } }
Source:
public void add(Object obj) throws IOException { if (obj == null) { addValues(null); } else if (obj instanceof int[]) { addValues(Ints.asList((int[]) obj)); } else if (obj instanceof List) { addValues((List<Integer>) obj); } else { throw new IAE("unsupported object type"); } }

Target:
public void add(Object obj) throws IOException { if (obj == null) { addValues(null); } else if (obj instanceof int[]) { addValues(Ints.asList((int[]) obj)); } else if (obj instanceof List) { addValues((List<Integer>) obj); } else { throw new IAE("unsupported multi-value type: " + obj.getClass()); } }
Source:
public Set<String> getPendingDocumentIds() throws CouchbaseLiteException { if (config.getReplicatorType().equals(ReplicatorConfiguration.ReplicatorType.PULL)) { throw new CouchbaseLiteException( "Pending Document IDs are not supported on pull-only replicators.", Log.LOGGING_DOMAINS_TO_C4.get(DOMAIN), CBLError.Code.UNSUPPORTED); } final C4Replicator repl; synchronized (lock) { repl = c4repl; } if (repl == null) { Log.i(DOMAIN, "%s: Call to getPendingDocumentIds with unstarted replicator", this); return Collections.emptySet(); } final Set<String> pending; try { pending = c4repl.getPendingDocIDs(); } catch (LiteCoreException e) { Log.w(DOMAIN, "Error while fetching pending documentIds: %d/%d", e.domain, e.code); return Collections.emptySet(); } return (pending.size() <= 0) ? Collections.emptySet() : Collections.unmodifiableSet(pending); }

Target:
public Set<String> getPendingDocumentIds() throws CouchbaseLiteException { if (config.getReplicatorType().equals(ReplicatorConfiguration.ReplicatorType.PULL)) { throw new CouchbaseLiteException( "Pending Document IDs are not supported on pull-only replicators.", Log.LOGGING_DOMAINS_TO_C4.get(DOMAIN), CBLError.Code.UNSUPPORTED); } final C4Replicator repl; synchronized (lock) { repl = c4repl; } if (repl == null) { Log.i(DOMAIN, "%s: Call to getPendingDocumentIds with unstarted replicator", this); return Collections.emptySet(); } final Set<String> pending; try { pending = c4repl.getPendingDocIDs(); } catch (LiteCoreException e) { throw CBLStatus.convertException(e, "Failed fetching pending documentIds"); } return (pending.size() <= 0) ? Collections.emptySet() : Collections.unmodifiableSet(pending); }
Source:
public void start(ComponentContext context) { super.start(context); configs.forEach(this::createStreamIfNotExists); processorDescriptors.forEach(this::initProcessor); if (! componentListenerAdded) { Framework.getRuntime().getComponentManager().addListener(new ComponentsLifeCycleListener()); componentListenerAdded = true; } }

Target:
public void start(ComponentContext context) { super.start(context); configs.forEach(this::createStreamIfNotExists); processorDescriptors.forEach(this::initProcessor); Framework.getRuntime().getComponentManager().addListener(new ComponentsLifeCycleListener()); }
Source:
public Response act(final Request req) throws IOException { final Request transformed = this.rqtransformer.transform(req); final Response response = this.origin.act(transformed); return this.rstransformer.transform(response); }

Target:
public Response act(final Request req) throws IOException { final RqHref.Base base = new RqHref.Base(req); final String home = new RqHref.Smart(base).home().bare(); final String dest = String.format( "http://%s/%s", this.host, base.href().toString().substring(home.length()) ); return this.response(home, dest, this.request(req, dest).fetch()); }
Source:
private List<Comment> sortUnorderedMockQuery(Set<Comment> unorderedRresult, ModelQuery query) { final List<QueryOrderConstraint> orderConstraints = query.getOrderConstraints(); List<Comment> result = new ArrayList<Comment>(unorderedRresult); Collections.sort(result, new Comparator<Comment>() { public int compare(Comment t1, Comment t2) { for (QueryOrderConstraint orderConstraint : orderConstraints) { int compareResult; Enum field = orderConstraint.getField(); String fieldName = field != null ? field.toString() : "id"; Object o1 = field != null ? t1.getField(fieldName) : t1.getId(); Object o2 = field != null ? t2.getField(fieldName) : t2.getId(); if (o1 instanceof java.lang.Long) { compareResult = ((Long) o1).compareTo((Long) o2); } else if (o1 instanceof java.lang.Integer) { compareResult = ((Integer) o1).compareTo((Integer) o2); } else if (o1 instanceof java.lang.Double) { compareResult = ((Double) o1).compareTo((Double) o2); } else if (o1 instanceof java.lang.Boolean) { compareResult = ((Boolean) o1).compareTo((Boolean) o2); } else if (o1 instanceof java.lang.String) { compareResult = ((String) o1).compareTo((String) o2); } else { compareResult = Integer.compare(o1.hashCode(), o2.hashCode()); } int orderDirection = (orderConstraint.getOrder() == QueryOrder.ASC) ? 1 : -1; compareResult = compareResult * orderDirection; if (compareResult == 0) { continue; } else if (compareResult < 0) { return -1; } else { return 1; } } return 0; } }); return result; }

Target:
private List<Comment> sortUnorderedMockQuery(Set<Comment> unorderedRresult, ModelQuery query) { final List<OrderCriterion> orderCriteria = query.getOrderCriteria(); List<Comment> result = new ArrayList<Comment>(unorderedRresult); Collections.sort(result, new Comparator<Comment>() { public int compare(Comment t1, Comment t2) { for (OrderCriterion orderCriterion : orderCriteria) { int compareResult; Enum field = orderCriterion.getField(); String fieldName = field != null ? field.toString() : "id"; Object o1 = field != null ? t1.getField(fieldName) : t1.getId(); Object o2 = field != null ? t2.getField(fieldName) : t2.getId(); if (o1 instanceof java.lang.Comparable) { compareResult = ((Comparable) o1).compareTo((Comparable) o2); } else { compareResult = Integer.valueOf(o1.hashCode()).compareTo(Integer.valueOf(o2.hashCode())); } int orderDirection = (orderCriterion.getOrder() == QueryOrder.ASC) ? 1 : -1; compareResult = compareResult * orderDirection; if (compareResult == 0) { continue; } else if (compareResult < 0) { return -1; } else { return 1; } } return 0; } }); return result; }
Source:
public String decrypt(String cipheredText, String passphrase) { Preconditions.checkNotNull(cipheredText); Preconditions.checkNotNull(passphrase); try { JsonNode json = MAPPER.readTree(ICrypto.decode(cipheredText)); return newEncryptor(passphrase).decrypt(json.get(CIPHERED_TEXT_KEY).asText()); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public String decrypt(String cipheredText, String passphrase) { try { JsonNode json = MAPPER.readTree(Crypto.decode(cipheredText)); return newEncryptor(passphrase).decrypt(json.get(CIPHERED_TEXT_KEY).asText()); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private void addNewPatientIdentifier(Config config, Patient patient, Identifier newIdentifier) { String uuid = patientResource.getPatientIdentifierTypeUuidByName(config, newIdentifier.getIdentifierType().getName()); List<Location> locations = locationService.getLocations(config.getName(), "Unknown Location"); newIdentifier.getIdentifierType().setUuid(uuid); newIdentifier.setLocation(locations.get(0)); patientResource.addPatientIdentifier(config, patient.getUuid(), newIdentifier); }

Target:
private void addNewPatientIdentifier(Config config, Patient patient, Identifier newIdentifier) { String uuid = patientResource.getPatientIdentifierTypeUuidByName(config, newIdentifier.getIdentifierType().getName()); if (uuid == null) { LOGGER.warn("The identifier type with name is not supported", newIdentifier.getIdentifierType().getName()); } else { newIdentifier.getIdentifierType().setUuid(uuid); patientResource.addPatientIdentifier(config, patient.getUuid(), newIdentifier); } }
Source:
public void testFailedSink() throws Exception { stream("http | filter --expression=payload=='good' |" + getTestSink(sink)); send("HTTP", "BAD"); assertReceived(); }

Target:
public void testFailedSink() throws Exception { stream(Source.HTTP + XD_DELIMETER + " filter --expression=payload=='good' " + XD_DELIMETER + sink); send("HTTP", "BAD"); assertReceived(); }
Source:
public String getLabel() { return "New Dialog"; }

Target:
public String getLabel() { return Messages.DialogTask_label; }
Source:
public List<OrganizationHistory> addLastVisited(String organizationId) { try { UIOrganization uiOrganization = organizationService.getOrganizationFromKernel(organizationId); String userId = userInfoService.currentUser().getUserId(); UserOrganizationsHistory userOrganizationsHistories = new UserOrganizationsHistory(); Optional<UserOrganizationsHistory> optionalUserOrganizationsHistory = userOrganizationsHistoryRepository.findById(userId); if (optionalUserOrganizationsHistory.isPresent()) { userOrganizationsHistories = optionalUserOrganizationsHistory.get(); } else { userOrganizationsHistories.setUserId(userId); } List<OrganizationHistory> organizationHistories = userOrganizationsHistories.getOrganizationsHistory(); Collections.sort(organizationHistories); OrganizationHistory newOrganizationHistory = new OrganizationHistory(); for (OrganizationHistory organizationHistory : organizationHistories) { if (organizationHistory.getOrganizationId().equals(organizationId)) { organizationHistory.setDate(new Date()); userOrganizationsHistoryRepository.save(userOrganizationsHistories); return organizationHistories; } } newOrganizationHistory.setOrganizationId(organizationId); newOrganizationHistory.setDate(new Date()); newOrganizationHistory.setName(uiOrganization.getName()); if (organizationHistories.size() < MAX_ORGANIZATION_HISTORY) { organizationHistories.add(newOrganizationHistory); } else { organizationHistories.set(0, newOrganizationHistory); } userOrganizationsHistoryRepository.save(userOrganizationsHistories); return organizationHistories; }catch(Exception e){ return null; } }

Target:
public List<OrganizationHistory> addLastVisited(String organizationId){ UIOrganization uiOrganization = organizationService.getOrganizationFromKernel(organizationId); String userId = userInfoService.currentUser().getUserId(); UserOrganizationsHistory userOrganizationsHistories = userOrganizationsHistoryRepository .findById(userId).orElse(new UserOrganizationsHistory(userId)); List<OrganizationHistory> organizationHistories = userOrganizationsHistories.getOrganizationsHistory(); Collections.sort(organizationHistories); for (OrganizationHistory organizationHistory : organizationHistories) { if (organizationHistory.getDcOrganizationId().equals(organizationId)) { organizationHistory.setDate(new Date()); userOrganizationsHistoryRepository.save(userOrganizationsHistories); return organizationHistories; } } organizationHistories = updateOrganizationHistories(organizationId, uiOrganization.getName(), organizationHistories); userOrganizationsHistoryRepository.save(userOrganizationsHistories); return organizationHistories; }
Source:
public void testGetPropsStandardFormat() throws Exception { final String key1 = "bluetooth.hciattach"; final String value1 = "true"; final String key2 = "bluetooth.status"; final String value2 = "off"; String format = "[%s]: [%s] \n"; String response = String.format(format, key1, value1) + String.format(format, key2, value2); server.add("serial-123"); server.expectShell("serial-123", "getprop").returns(response); JadbDevice device = connection.getDevices().get(0); Map<String, String> props = new PropertyManager(device).getprop(); assertNotNull(props.get(key1)); assertEquals(props.get(key1), value1); assertNotNull(props.get(key2)); assertEquals(props.get(key2), value2); }

Target:
public void testGetPropsStandardFormat() throws Exception { Map<String, String> expected = new HashMap<>(); expected.put("bluetooth.hciattach", "true"); expected.put("bluetooth.status", "off"); String response = "[bluetooth.status]: [off] \n" + "[bluetooth.hciattach]: [true]"; server.expectShell(DEVICE_SERIAL, "getprop").returns(response); Map<String, String> actual = new PropertyManager(device).getprop(); assertEquals(expected, actual); }
Source:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(processVolumesInCurrentCluster(getGlusterVolumeDao().getById(getParameters().getId()), getGlusterVolumeDao().getById(getParameters().getSlaveVolumeId()), prepareSessionMap(getGeoRepDao().getAllSessions()))); }

Target:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(GlusterGeoRepUtil.getInstance().getNonEligibilityReasons(getGlusterVolumeDao().getById(getParameters().getId()), getGlusterVolumeDao().getById(getParameters().getSlaveVolumeId()))); }