auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void call(final Subscriber<? super T> child) { final Worker worker = scheduler.createWorker(); child.add(worker); SkipTimedSubscriber<T> subscriber = new SkipTimedSubscriber<T>(child); worker.schedule(subscriber, time, unit); source.unsafeSubscribe(subscriber); }

Target:
public void call(final Subscriber<? super T> child) { final Worker worker = scheduler.createWorker(); SkipTimedSubscriber<T> subscriber = new SkipTimedSubscriber<T>(child); subscriber.add(worker); child.add(subscriber); worker.schedule(subscriber, time, unit); source.unsafeSubscribe(subscriber); }
Source:
protected void processResponse(Map<String, Object> response) { Map<String, Object> result = getMap(response, "result"); if (result.containsKey("System.ScreenSaverActive")) { Object o = result.get("System.ScreenSaverActive"); if(o!=null && o instanceof Boolean) { screenSaverActive=(Boolean)o; } } }

Target:
protected void processResponse(Map<String, Object> response) { Map<String, Object> result = getMap(response, "result"); if (result.containsKey(SYSTEM_SCREEN_SAVER_ACTIVE)) { Object o = result.get(SYSTEM_SCREEN_SAVER_ACTIVE); if (o != null && o instanceof Boolean) { screenSaverActive = (Boolean) o; } } }
Source:
public Collection<Space> getSpaces() { log.info("Getting all spaces units"); return target.path("spaces").request().get(new GenericType<Collection<Space>>() { }); }

Target:
public Collection<Space> getSpaces() { log.info("Getting all spaces"); return target.path("spaces").request().get(new GenericType<Collection<Space>>() { }); }
Source:
public ConnectorPageSource pageSource(ConnectorTransactionHandle transactionHandle, ConnectorSession session, TupleDomain<Integer> constraint) { String metadataSqlQuery = getColumnRangesMetadataSqlQuery(sourceTable, indexedRaptorColumns); List<Type> columnTypes = tableMetadata.getColumns().stream() .map(ColumnMetadata::getType) .collect(toImmutableList()); PageListBuilder pageListBuilder = new PageListBuilder(columnTypes); try (Connection connection = dbi.open().getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(metadataSqlQuery)) { if (resultSet.next()) { pageListBuilder.beginRow(); for (int i = 0; i < columnTypes.size(); ++i) { Type columnType = columnTypes.get(i); if (columnType.equals(BIGINT) || columnType.equals(DATE) || columnType.equals(TIMESTAMP)) { long value = resultSet.getLong(i + 1); if (!resultSet.wasNull()) { columnType.writeLong(pageListBuilder.nextBlockBuilder(), value); } else { pageListBuilder.nextBlockBuilder().appendNull(); } } else if (columnType.equals(BOOLEAN)) { boolean value = resultSet.getBoolean(i + 1); if (!resultSet.wasNull()) { BOOLEAN.writeBoolean(pageListBuilder.nextBlockBuilder(), value); } else { pageListBuilder.nextBlockBuilder().appendNull(); } } else { throw new VerifyException("Unknown or unsupported column type: " + columnType); } } } } catch (SQLException | DBIException e) { throw metadataError(e); } return new FixedPageSource(pageListBuilder.build()); }

Target:
public ConnectorPageSource pageSource(ConnectorTransactionHandle transactionHandle, ConnectorSession session, TupleDomain<Integer> constraint) { String metadataSqlQuery = getColumnRangesMetadataSqlQuery(sourceTable, indexedRaptorColumns); List<Type> columnTypes = tableMetadata.getColumns().stream() .map(ColumnMetadata::getType) .collect(toImmutableList()); PageListBuilder pageListBuilder = new PageListBuilder(columnTypes); try (Connection connection = dbi.open().getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(metadataSqlQuery)) { if (resultSet.next()) { pageListBuilder.beginRow(); for (int i = 0; i < columnTypes.size(); ++i) { BlockBuilder blockBuilder = pageListBuilder.nextBlockBuilder(); Type columnType = columnTypes.get(i); if (columnType.equals(BIGINT) || columnType.equals(DATE) || columnType.equals(TIMESTAMP)) { long value = resultSet.getLong(i + 1); if (!resultSet.wasNull()) { columnType.writeLong(blockBuilder, value); } else { blockBuilder.appendNull(); } } else if (columnType.equals(BOOLEAN)) { boolean value = resultSet.getBoolean(i + 1); if (!resultSet.wasNull()) { BOOLEAN.writeBoolean(blockBuilder, value); } else { blockBuilder.appendNull(); } } else { throw new VerifyException("Unknown or unsupported column type: " + columnType); } } } } catch (SQLException | DBIException e) { throw metadataError(e); } return new FixedPageSource(pageListBuilder.build()); }
Source:
synchronized void updateLease(Lease newLease) { Preconditions.checkArgument(lease.leaderTime().isComparableWith(newLease.leaderTime()), "Lock leases can only be refreshed by lease owners"); if (this.lease.expiry().isBefore(newLease.expiry())) { this.lease = newLease; } }

Target:
synchronized void updateLease(Lease newLease) { Preconditions.checkArgument(lease.leaderTime().isComparableWith(newLease.leaderTime()), "Lock leases can only be refreshed by lease owners. Current leader id: {}, new leader id: {}", SafeArg.of("currentLeaderId", lease.leaderTime().id()), SafeArg.of("newLeaderId", newLease.leaderTime().id())); if (this.lease.expiry().isBefore(newLease.expiry())) { this.lease = newLease; } }
Source:
private String extractOrderBy(Class<?> entityClass, Map<Path, Sorting.SortOrder> sortClauses, SQLSchema schema, Query query) { if (sortClauses.isEmpty()) { return ""; } return " ORDER BY " + sortClauses.entrySet().stream() .map((entry) -> { Path path = entry.getKey(); path = expandJoinToPath(path); Sorting.SortOrder order = entry.getValue(); Path.PathElement last = path.lastElement().get(); String orderByType = FilterPredicate.getTypeAlias(last.getType()) + "." + getColumnName(entityClass, last.getFieldName()); if (last.getType() == entityClass) { Metric currentMetric = schema.getMetric(getColumnName(entityClass, last.getFieldName())); if (currentMetric != null && query.getMetrics().keySet().contains(currentMetric)) { orderByType = currentMetric.getMetricExpression(query.getMetrics().get(currentMetric)); } } return orderByType + (order.equals(Sorting.SortOrder.desc) ? " DESC" : " ASC"); }).collect(Collectors.joining(",")); }

Target:
private String extractOrderBy(Class<?> entityClass, Map<Path, Sorting.SortOrder> sortClauses, SQLSchema schema, Query query) { if (sortClauses.isEmpty()) { return ""; } return " ORDER BY " + sortClauses.entrySet().stream() .map((entry) -> { Path path = entry.getKey(); path = expandJoinToPath(path); Sorting.SortOrder order = entry.getValue(); Path.PathElement last = path.lastElement().get(); String orderByType = FilterPredicate.getTypeAlias(last.getType()) + "." + getColumnName(entityClass, last.getFieldName()); if (last.getType() == entityClass) { Metric currentMetric = schema.getMetric(getColumnName(entityClass, last.getFieldName())); if (currentMetric != null && query.getMetrics().containsKey(currentMetric)) { orderByType = currentMetric.getMetricExpression(query.getMetrics().get(currentMetric)); } } return orderByType + (order.equals(Sorting.SortOrder.desc) ? " DESC" : " ASC"); }).collect(Collectors.joining(",")); }
Source:
public void onNext(T t) { long idx = index.get(); if (idx == Long.MAX_VALUE) { return; } if (!index.compareAndSet(idx, idx + 1)) { return; } Subscription s = task.get(); if (s != null) { s.unsubscribe(); } actual.onNext(t); consumed++; startTimeout(idx + 1); }

Target:
public void onNext(T t) { long idx = index.get(); if (idx == Long.MAX_VALUE || !index.compareAndSet(idx, idx + 1)) { return; } Subscription s = task.get(); if (s != null) { s.unsubscribe(); } consumed++; actual.onNext(t); startTimeout(idx + 1); }
Source:
public double[] getVotesForInstance(Instance inst) { double v[] = new double[C+1]; try { NearestNeighbourSearch search; if (this.nearestNeighbourSearchOption.getChosenIndex()== 0) { search = new LinearNNSearch(this.window); } else { search = new KDTree(); search.setInstances(this.window); } if (this.window.numInstances()>0) { Instances neighbours = search.kNearestNeighbours(inst,Math.min(kOption.getValue(),this.window.numInstances())); if(inst.classAttribute().isNumeric() && regressionOption.isSet()){ double[] result = new double[1]; double sum = 0; int num = neighbours.numInstances(); if(medianOption.isSet()){ double[] classValues = new double[num]; for(int i=0;i<num;i++){ classValues[i] = neighbours.instance(i).classValue(); } Arrays.sort(classValues); if(classValues.length%2==1){ result[0] = classValues[num/2]; }else{ result[0] = (classValues[num/2 - 1] + classValues[num/2]) / 2; } return result; }else{ for(int i=0;i<num;i++){ sum += neighbours.instance(i).classValue(); } result[0] = sum / num; return result; } }else{ for (int i = 0; i < neighbours.numInstances(); i++) { v[(int) neighbours.instance(i).classValue()]++; } } } } catch(Exception e) { return new double[inst.numClasses()]; } return v; }

Target:
public double[] getVotesForInstance(Instance inst) { double v[] = new double[C+1]; try { NearestNeighbourSearch search; if (this.nearestNeighbourSearchOption.getChosenIndex()== 0) { search = new LinearNNSearch(this.window); } else { search = new KDTree(); search.setInstances(this.window); } if (this.window.numInstances()>0) { Instances neighbours = search.kNearestNeighbours(inst,Math.min(kOption.getValue(),this.window.numInstances())); if(inst.classAttribute().isNumeric()){ double[] result = new double[1]; double sum = 0; int num = neighbours.numInstances(); if(medianOption.isSet()){ double[] classValues = new double[num]; for(int i=0;i<num;i++){ classValues[i] = neighbours.instance(i).classValue(); } Arrays.sort(classValues); if(classValues.length%2==1){ result[0] = classValues[num/2]; }else{ result[0] = (classValues[num/2 - 1] + classValues[num/2]) / 2; } return result; }else{ for(int i=0;i<num;i++){ sum += neighbours.instance(i).classValue(); } result[0] = sum / num; return result; } }else{ for (int i = 0; i < neighbours.numInstances(); i++) { v[(int) neighbours.instance(i).classValue()]++; } } } } catch(Exception e) { return new double[inst.numClasses()]; } return v; }
Source:
public void drawScreen( final int mouseX, final int mouseY, final float btn ) { this.updateCPUButtonText(); this.start.enabled = !( this.ccc.isNoCPU() || this.isSimulation() ); this.selectCPU.enabled = !this.isSimulation(); final int gx = ( this.width - this.xSize ) / 2; final int gy = ( this.height - this.ySize ) / 2; this.tooltip = -1; final int offY = 23; int y = 0; int x = 0; for( int z = 0; z <= 4 * 5; z++ ) { final int minX = gx + 9 + x * 67; final int minY = gy + 22 + y * offY; if( minX < mouseX && minX + 67 > mouseX ) { if( minY < mouseY && minY + offY - 2 > mouseY ) { this.tooltip = z; break; } } x++; if( x > 2 ) { y++; x = 0; } } super.drawScreen( mouseX, mouseY, btn ); }

Target:
public void drawScreen( final int mouseX, final int mouseY, final float btn ) { this.updateCPUButtonText(); this.start.enabled = !( this.ccc.hasNoCPU() || this.isSimulation() ); this.selectCPU.enabled = !this.isSimulation(); final int gx = ( this.width - this.xSize ) / 2; final int gy = ( this.height - this.ySize ) / 2; this.tooltip = -1; final int offY = 23; int y = 0; int x = 0; for( int z = 0; z <= 4 * 5; z++ ) { final int minX = gx + 9 + x * 67; final int minY = gy + 22 + y * offY; if( minX < mouseX && minX + 67 > mouseX ) { if( minY < mouseY && minY + offY - 2 > mouseY ) { this.tooltip = z; break; } } x++; if( x > 2 ) { y++; x = 0; } } super.drawScreen( mouseX, mouseY, btn ); }
Source:
private boolean clearContextRelationships(CompileContext compileContext, Long identity, Class endNodeType, DirectedRelationship directedRelationship) { if (directedRelationship.direction().equals(Direction.INCOMING)) { LOGGER.debug("context-del: ({})<-[:{}]-()", identity, directedRelationship.type()); return compileContext.deregisterIncomingRelationships(identity, directedRelationship.type(), endNodeType, metaData.isRelationshipEntity(endNodeType.getName())); } else if (directedRelationship.direction().equals(Direction.OUTGOING)) { LOGGER.debug("context-del: ({})-[:{}]->()", identity, directedRelationship.type()); return compileContext.deregisterOutgoingRelationships(identity, directedRelationship.type(), endNodeType); } else { LOGGER.debug("context-del: ({})<-[:{}]-()", identity, directedRelationship.type()); LOGGER.debug("context-del: ({})-[:{}]->()", identity, directedRelationship.type()); boolean clearedIncoming = compileContext .deregisterIncomingRelationships(identity, directedRelationship.type(), endNodeType, metaData.isRelationshipEntity(endNodeType.getName())); boolean clearedOutgoing = compileContext .deregisterOutgoingRelationships(identity, directedRelationship.type(), endNodeType); return clearedIncoming || clearedOutgoing; } }

Target:
private boolean clearContextRelationships(CompileContext compileContext, Long identity, Class endNodeType, DirectedRelationship directedRelationship) { switch (directedRelationship.direction()) { case INCOMING: LOGGER.debug("context-del: ({})<-[:{}]-()", identity, directedRelationship.type()); return compileContext.deregisterIncomingRelationships(identity, directedRelationship.type(), endNodeType, metaData.isRelationshipEntity(endNodeType.getName())); case OUTGOING: LOGGER.debug("context-del: ({})-[:{}]->()", identity, directedRelationship.type()); return compileContext.deregisterOutgoingRelationships(identity, directedRelationship.type(), endNodeType); default: LOGGER.debug("context-del: ({})<-[:{}]-()", identity, directedRelationship.type()); LOGGER.debug("context-del: ({})-[:{}]->()", identity, directedRelationship.type()); boolean clearedIncoming = compileContext .deregisterIncomingRelationships(identity, directedRelationship.type(), endNodeType, metaData.isRelationshipEntity(endNodeType.getName())); boolean clearedOutgoing = compileContext .deregisterOutgoingRelationships(identity, directedRelationship.type(), endNodeType); return clearedIncoming || clearedOutgoing; } }
Source:
public void matches(PlanMatchPattern pattern) { RuleApplication ruleApplication = applyRule(); TypeProvider types = ruleApplication.types; if (!ruleApplication.wasRuleApplied()) { fail(String.format( "%s did not fire for:\n%s", rule.getClass().getName(), formatPlan(plan, types))); } PlanNode actual = ruleApplication.getTransformedPlan(); if (actual == plan) { fail(String.format( "%s: rule fired but return the original plan:\n%s", rule.getClass().getName(), formatPlan(plan, types))); } if (!ImmutableSet.copyOf(plan.getOutputSymbols()).equals(ImmutableSet.copyOf(actual.getOutputSymbols()))) { fail(String.format( "%s: output schema of transformed and original plans are not equivalent\n" + "\texpected: %s\n" + "\tactual: %s", rule.getClass().getName(), plan.getOutputSymbols(), actual.getOutputSymbols())); } inTransaction(session -> { assertPlan(session, metadata, ruleApplication.statsProvider, new Plan(actual, types, emptyMap(), emptyMap()), ruleApplication.lookup, pattern); return null; }); }

Target:
public void matches(PlanMatchPattern pattern) { RuleApplication ruleApplication = applyRule(); TypeProvider types = ruleApplication.types; if (!ruleApplication.wasRuleApplied()) { fail(String.format( "%s did not fire for:\n%s", rule.getClass().getName(), formatPlan(plan, types))); } PlanNode actual = ruleApplication.getTransformedPlan(); if (actual == plan) { fail(String.format( "%s: rule fired but return the original plan:\n%s", rule.getClass().getName(), formatPlan(plan, types))); } if (!ImmutableSet.copyOf(plan.getOutputSymbols()).equals(ImmutableSet.copyOf(actual.getOutputSymbols()))) { fail(String.format( "%s: output schema of transformed and original plans are not equivalent\n" + "\texpected: %s\n" + "\tactual: %s", rule.getClass().getName(), plan.getOutputSymbols(), actual.getOutputSymbols())); } inTransaction(session -> { assertPlan(session, metadata, ruleApplication.statsProvider, new Plan(actual, types, StatsAndCosts.empty()), ruleApplication.lookup, pattern); return null; }); }
Source:
private static void validateReplicationFactor(String configName, short factor) { if (factor != TopicAdmin.NO_REPLICATION_FACTOR && factor < 1) { throw new ConfigException(configName, factor, "Replication factor must be positive, or -1 to use the broker's default"); } }

Target:
private static void validateReplicationFactor(String configName, short factor) { if (factor != TopicAdmin.NO_REPLICATION_FACTOR && factor < 1) { throw new ConfigException(configName, factor, "Replication factor must be positive and not larger than the number of brokers in the Kafka cluster, or -1 to use the broker's default"); } }
Source:
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AbstractMessageChannel) { if (logger.isDebugEnabled()) { logger.debug("Applying global interceptors on channel '" + beanName + "'"); } this.addMatchingInterceptors((AbstractMessageChannel) bean, beanName); } return bean; }

Target:
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ChannelInterceptorAware && bean instanceof MessageChannel) { if (logger.isDebugEnabled()) { logger.debug("Applying global interceptors on channel '" + beanName + "'"); } this.addMatchingInterceptors((ChannelInterceptorAware) bean, beanName); } return bean; }
Source:
public void handleMessage (Message message) { try { byte[] body = base64.decode(message.getBody()); ByteArrayInputStream bais = new ByteArrayInputStream(body); LittleEndianDataInputStream data = new LittleEndianDataInputStream(bais); char[] header = new char[6]; for (int i = 0; i < 6; i++) { header[i] = (char) data.readByte(); } if (!"ORIGIN".equals(new String(header))) { error = true; LOG.error("Origin not in proper format for query %s"); return; } int version = data.readInt(); if (version != ORIGIN_VERSION) { error = true; LOG.error("Origin version mismatch for query %s, expected {}, found {}", ORIGIN_VERSION, version); } int x = data.readInt(); int y = data.readInt(); int iterations = data.readInt(); ByteArrayOutputStream originData = new ByteArrayOutputStream(iterations * 4); LittleEndianDataOutputStream origin = new LittleEndianDataOutputStream(originData); for (int i = 0, prev = 0; i < iterations; i++) { int current = data.readInt(); origin.writeInt(current - prev); prev = current; } origin.close(); synchronized (this) { if (buffer == null) this.initialize(iterations); long offset = DATA_OFFSET + (y * request.width + x) * 4 * iterations; buffer.seek(offset); buffer.write(originData.toByteArray()); if (++nComplete == nTotal && !error) finish(); } } catch (Exception e) { error = true; LOG.error("Error assembling results for query %s", request.jobId, e); return; } }

Target:
public void handleMessage (Message message) { try { byte[] body = base64.decode(message.getBody()); ByteArrayInputStream bais = new ByteArrayInputStream(body); Origin origin = Origin.read(bais); if (buffer != null && origin.accessibilityPerIteration.length != this.nIterations) { LOG.error("Origin {}, has iterations, expected {}", origin.x, origin.y, origin.accessibilityPerIteration.length, this.nIterations); error = true; } ByteArrayOutputStream pixelByteOutputStream = new ByteArrayOutputStream(origin.accessibilityPerIteration.length * 4); LittleEndianDataOutputStream pixelDataOutputStream = new LittleEndianDataOutputStream(pixelByteOutputStream); for (int i = 0, prev = 0; i < origin.accessibilityPerIteration.length; i++) { int current = origin.accessibilityPerIteration[i]; pixelDataOutputStream.writeInt(current - prev); prev = current; } pixelDataOutputStream.close(); synchronized (this) { if (buffer == null) this.initialize(origin.accessibilityPerIteration.length); long offset = DATA_OFFSET + (origin.y * request.width + origin.x) * 4 * nIterations; buffer.seek(offset); buffer.write(pixelByteOutputStream.toByteArray()); if (++nComplete == nTotal && !error) finish(); } } catch (Exception e) { error = true; LOG.error("Error assembling results for query {}", request.jobId, e); return; } }
Source:
public String stopVM(final Connect conn, final String vmName, final boolean forceStop) { DomainState state = null; Domain dm = null; s_logger.debug("Try to stop the vm at first"); String ret = stopVMInternal(conn, vmName, forceStop); if (ret == Script.ERR_TIMEOUT) { ret = stopVMInternal(conn, vmName, true); } else if (ret != null) { for (int i = 0; i < 3; i++) { try { dm = conn.domainLookupByName(vmName); state = dm.getInfo().state; break; } catch (final LibvirtException e) { s_logger.debug("Failed to get vm status:" + e.getMessage()); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } if (state == null) { s_logger.debug("Can't get vm's status, assume it's dead already"); return null; } if (state != DomainState.VIR_DOMAIN_SHUTOFF) { s_logger.debug("Try to destroy the vm"); ret = stopVMInternal(conn, vmName, true); if (ret != null) { return ret; } } } return null; }

Target:
public String stopVM(final Connect conn, final String vmName, final boolean forceStop) { DomainState state = null; Domain dm = null; s_logger.debug("Try to stop the vm at first"); if (forceStop) { return stopVMInternal(conn, vmName, true); } String ret = stopVM(conn, vmName, false); if (ret == Script.ERR_TIMEOUT) { ret = stopVMInternal(conn, vmName, true); } else if (ret != null) { for (int i = 0; i < 3; i++) { try { dm = conn.domainLookupByName(vmName); state = dm.getInfo().state; break; } catch (final LibvirtException e) { s_logger.debug("Failed to get vm status:" + e.getMessage()); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } if (state == null) { s_logger.debug("Can't get vm's status, assume it's dead already"); return null; } if (state != DomainState.VIR_DOMAIN_SHUTOFF) { s_logger.debug("Try to destroy the vm"); ret = stopVMInternal(conn, vmName, true); if (ret != null) { return ret; } } } return null; }
Source:
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!EjbDeploymentMarker.isEjbDeployment(deploymentUnit)) { return; } final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final Collection<ComponentDescription> componentDescriptions = eeModuleDescription.getComponentDescriptions(); HashMap<String,HashSet<String>> ejbClassTypes = new HashMap(); ejbClassTypes.put("isStateful",new HashSet<>()); ejbClassTypes.put("isStateless",new HashSet<>()); ejbClassTypes.put("isSingleton",new HashSet<>()); if (componentDescriptions != null) { for (ComponentDescription componentDescription : componentDescriptions) { if (componentDescription instanceof SessionBeanComponentDescription) { if(!checkBeanTypeSpecViolation(ejbClassTypes,(SessionBeanComponentDescription)componentDescription)) this.setupJNDIBindings((EJBComponentDescription) componentDescription, deploymentUnit); else EjbLogger.DEPLOYMENT_LOGGER.typeSpecViolation(((EJBComponentDescription)componentDescription).getEJBClassName()); } } } if (appclient) { for (final ComponentDescription component : deploymentUnit.getAttachmentList(Attachments.ADDITIONAL_RESOLVABLE_COMPONENTS)) { this.setupJNDIBindings((EJBComponentDescription) component, deploymentUnit); } } }

Target:
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!EjbDeploymentMarker.isEjbDeployment(deploymentUnit)) { return; } final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final Collection<ComponentDescription> componentDescriptions = eeModuleDescription.getComponentDescriptions(); Map<String, SessionBeanComponentDescription> sessionBeanComponentDescriptions = new HashMap<>(); if (componentDescriptions != null) { for (ComponentDescription componentDescription : componentDescriptions) { if (componentDescription instanceof SessionBeanComponentDescription) { SessionBeanComponentDescription sessionBeanComponentDescription = (SessionBeanComponentDescription) componentDescription; String ejbClassName = sessionBeanComponentDescription.getEJBClassName(); SessionBeanComponentDescription existingDescription = sessionBeanComponentDescriptions.putIfAbsent(ejbClassName, sessionBeanComponentDescription); if ((existingDescription == null) || existingDescription.getSessionBeanType() == sessionBeanComponentDescription.getSessionBeanType()) { this.setupJNDIBindings(sessionBeanComponentDescription, deploymentUnit); } else { EjbLogger.DEPLOYMENT_LOGGER.typeSpecViolation(ejbClassName); } } } } if (appclient) { for (final ComponentDescription component : deploymentUnit.getAttachmentList(Attachments.ADDITIONAL_RESOLVABLE_COMPONENTS)) { this.setupJNDIBindings((EJBComponentDescription) component, deploymentUnit); } } }
Source:
public Integer replayObserverFromIndex(Integer idx, SubjectObserver<? super T> observer) { int i = idx; while (i < index.get()) { accept(observer, i); i++; } return i; }

Target:
public Integer replayObserverFromIndex(Integer idx, SubjectObserver<? super T> observer) { int i = idx; while (i < get()) { accept(observer, i); i++; } return i; }
Source:
public MaximumRetriesExceededException(Retryable task, Throwable cause) { super(task.getName() + " failed after maximum retries" + task.finalMessage == null ? "" : ": " + task.finalMessage, cause); if (task instanceof RetryableTaskReturnsThrows) { finalResult = ((RetryableTaskReturnsThrows) task).getResult(); } }

Target:
public MaximumRetriesExceededException(Retryable task, Throwable cause) { super(task.getName() + " failed after maximum retries", cause); finalMessage = task.finalMessage; finalData = task.finalData; }
Source:
public void itReturnsProperPagination() throws Exception { DocumentModel docEntry = dirSession.getEntry("test1"); docEntry.setPropertyValue("vocabulary:id", "newtest"); docEntry.setPropertyValue("vocabulary:label", "newlabel"); assertNull(dirSession.getEntry("newtest")); String jsonEntry = getDirectoryEntryAsJson(docEntry); try (CloseableClientResponse response = getResponse(RequestType.POST, "/directory/" + TESTDIRNAME, jsonEntry)) { assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); } nextTransaction(); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); int maxResults = 5; queryParams.putSingle("pageSize", String.valueOf(maxResults)); queryParams.putSingle("maxResults", String.valueOf(maxResults)); try (CloseableClientResponse response = getResponse(RequestType.GET, "/directory/" + TESTDIRNAME, queryParams)) { String json = response.getEntity(String.class); JsonNode jsonNode = mapper.readTree(json); JsonNode entriesNode = jsonNode.get("entries"); assertTrue(entriesNode.isArray()); ArrayNode entriesArrayNode = (ArrayNode) entriesNode; assertEquals(maxResults, entriesArrayNode.size()); } }

Target:
public void itReturnsProperPagination() throws Exception { DocumentModel docEntry = dirSession.getEntry("foo"); String jsonEntry = getDirectoryEntryAsJson(docEntry); assertNotNull(jsonEntry); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); int maxResults = 5; queryParams.putSingle("pageSize", String.valueOf(maxResults)); queryParams.putSingle("maxResults", String.valueOf(maxResults)); try (CloseableClientResponse response = getResponse(RequestType.GET, "/directory/" + TESTDIRNAME, queryParams)) { String json = response.getEntity(String.class); JsonNode jsonNode = mapper.readTree(json); JsonNode entriesNode = jsonNode.get("entries"); assertTrue(entriesNode.isArray()); ArrayNode entriesArrayNode = (ArrayNode) entriesNode; assertEquals(maxResults, entriesArrayNode.size()); } }
Source:
private void readAndPrintFile(String fileName) { File file = new File(fileName); BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); String line = br.readLine(); while (line != null) { log(" " + line, Project.MSG_INFO); line = br.readLine(); } } catch(IOException ex) { LOGGER.error(ex.getMessage(), ex); } finally { if (br != null) { try { br.close(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } } }

Target:
private void readAndPrintFile(String fileName) { try { Files.readAllLines(Paths.get(fileName)).forEach(line -> log(" " + line, Project.MSG_INFO)); } catch (IOException ex) { LOGGER.error(ex.getMessage(), ex); } }
Source:
public void testExternalUserCache() { assertThat(userDetailsService instanceof ConfigurableProviderManager).isTrue(); assertThat(strongboxUserManager.findByUsername(TEST_USER)).isNull(); assertThat(userDetailsService.loadUserByUsername(TEST_USER)).isNotNull(); User externalUser = strongboxUserManager.findByUsername(TEST_USER); assertThat(externalUser).isNotNull(); User externalUserToSave = externalUser; assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(() -> orientDbUserService.save(externalUserToSave)) .withMessageMatching("Can't modify external users."); String newPassword = UUID.randomUUID().toString(); UserDto userToUpdate = new UserDto(); userToUpdate.setUsername(TEST_USER); userToUpdate.setPassword(newPassword); yamlUserService.updateAccountDetailsByUsername(new EncodedPasswordUser(userToUpdate, passwordEncoder)); UserEntry externalUserEntry = (UserEntry) orientDbUserService.findByUsername(TEST_USER); externalUserEntry.setLastUpdate(null); entityManager.persist(externalUserEntry); assertThat(userDetailsService.loadUserByUsername(TEST_USER)).isNotNull(); externalUser = strongboxUserManager.findByUsername(TEST_USER); assertThat(externalUser).isNotNull(); assertThat(passwordEncoder.matches(newPassword, externalUser.getPassword())).isTrue(); }

Target:
public void testExternalUserCache() { assertThat(userDetailsService).isInstanceOf(ConfigurableProviderManager.class); assertThat(strongboxUserManager.findByUsername(TEST_USER)).isNull(); assertThat(userDetailsService.loadUserByUsername(TEST_USER)).isNotNull(); User externalUser = strongboxUserManager.findByUsername(TEST_USER); assertThat(externalUser).isNotNull(); User externalUserToSave = externalUser; assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(() -> orientDbUserService.save(externalUserToSave)) .withMessageMatching("Can't modify external users."); String newPassword = UUID.randomUUID().toString(); UserDto userToUpdate = new UserDto(); userToUpdate.setUsername(TEST_USER); userToUpdate.setPassword(newPassword); yamlUserService.updateAccountDetailsByUsername(new EncodedPasswordUser(userToUpdate, passwordEncoder)); UserEntry externalUserEntry = (UserEntry) orientDbUserService.findByUsername(TEST_USER); externalUserEntry.setLastUpdate(null); entityManager.persist(externalUserEntry); assertThat(userDetailsService.loadUserByUsername(TEST_USER)).isNotNull(); externalUser = strongboxUserManager.findByUsername(TEST_USER); assertThat(externalUser).isNotNull(); assertThat(passwordEncoder.matches(newPassword, externalUser.getPassword())).isTrue(); }
Source:
public static void main(String[] args) { try { MessageQueue msgQueue = new MessageQueue(); LOGGER.info("All the TaskGenerators started."); Runnable taskRunnable1 = new TaskGenerator(msgQueue, 5); Runnable taskRunnable2 = new TaskGenerator(msgQueue, 1); Runnable taskRunnable3 = new TaskGenerator(msgQueue, 2); Thread taskGenerator1 = new Thread(taskRunnable1, "Task_Generator_1"); Thread taskGenerator2 = new Thread(taskRunnable2, "Task_Generator_2"); Thread taskGenerator3 = new Thread(taskRunnable3, "Task_Generator_3"); taskGenerator1.start(); taskGenerator2.start(); taskGenerator3.start(); LOGGER.info("Service Executor started."); Runnable srvRunnable = new ServiceExecutor(msgQueue); Thread srvExec = new Thread(srvRunnable, "Service_Executor_Thread"); srvExec.start(); } catch (Exception e) { LOGGER.error(e.getMessage()); } }

Target:
public static void main(String[] args) { ExecutorService executor = null; try { MessageQueue msgQueue = new MessageQueue(); LOGGER.info("Submitting TaskGenerators and ServiceExecutor threads."); Runnable taskRunnable1 = new TaskGenerator(msgQueue, 5); Runnable taskRunnable2 = new TaskGenerator(msgQueue, 1); Runnable taskRunnable3 = new TaskGenerator(msgQueue, 2); Runnable srvRunnable = new ServiceExecutor(msgQueue); executor = Executors.newFixedThreadPool(2); executor.submit(taskRunnable1); executor.submit(taskRunnable2); executor.submit(taskRunnable3); executor.submit(srvRunnable); LOGGER.info("Intiating shutdown. Executor will shutdown only after all the Threads are completed."); executor.shutdown(); if ( !executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS) ) { LOGGER.info("Executor was shut down and Exiting."); executor.shutdownNow(); } } catch (InterruptedException ie) { LOGGER.error(ie.getMessage()); } catch (Exception e) { LOGGER.error(e.getMessage()); } }
Source:
public void init() { load(FileSystems.getDefault().getPath(EngineLocalConfig.getInstance().getUsrDir().getAbsolutePath(), "osinfo.conf.d")); load(FileSystems.getDefault().getPath(EngineLocalConfig.getInstance().getEtcDir().getAbsolutePath(), "osinfo.conf.d")); }

Target:
public void init() { load(FileSystems.getDefault().getPath(EngineLocalConfig.getInstance().getEtcDir().getAbsolutePath(), "/conf/osinfo.conf.d")); loadPreferencesFromProperties(); }
Source:
public static int minNonNullValueSize(int nonNullCount) { return max(nonNullCount + 1, 1025); }

Target:
public static int minNonNullValueSize(int nonNullCount) { return max(nonNullCount, MAX_BATCH_SIZE) + 1; }
Source:
public GdbMemoryBlock(DsfMemoryBlockRetrieval retrieval, IMemoryDMContext context, String modelId, String expression, BigInteger address, int word_size, long length, String memorySpaceID) { super(retrieval, context, modelId, expression, address, word_size, length); fMemorySpaceID = (memorySpaceID != null && memorySpaceID.length() > 0) ? memorySpaceID : null; assert memorySpaceID == null || memorySpaceID.length() > 0; }

Target:
public GdbMemoryBlock(DsfMemoryBlockRetrieval retrieval, IMemoryDMContext context, String modelId, String expression, BigInteger address, int word_size, long length, String memorySpaceID) { super(retrieval, context, modelId, expression, address, word_size, length); fMemorySpaceID = (memorySpaceID != null && !memorySpaceID.isEmpty()) ? memorySpaceID : null; assert memorySpaceID == null || !memorySpaceID.isEmpty(); if(memorySpaceID != null) { assert(context instanceof IMemorySpaceDMContext); assert memorySpaceID.equals(((IMemorySpaceDMContext) context).getMemorySpaceId()); } else { if (context instanceof IMemorySpaceDMContext) { assert ((IMemorySpaceDMContext) context).getMemorySpaceId() == null; } } }
Source:
void onClickRecipientExpander() { recipientMvpView.setCcVisibility(true); recipientMvpView.setBccVisibility(true); if(defaultBccAddress != null) addBccAddresses(defaultBccAddress); updateRecipientExpanderVisibility(); }

Target:
void onClickRecipientExpander() { recipientMvpView.setCcVisibility(true); recipientMvpView.setBccVisibility(true); if ( defaultBccAddress != null ) { addBccAddresses(defaultBccAddress); } updateRecipientExpanderVisibility(); }
Source:
public void testOrClause() { String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getName() + ";\n" + "import " + HardSoftScoreHolder.class.getName() + ";\n" + "global HardSoftScoreHolder scoreHolder;\n" + "rule R1\n" + "when\n" + " Person( age > 20 )\n" + " or\n" + " Person( name == \"John\")\n" + "then\n" + " scoreHolder.addSoftConstraintMatch(kcontext, -1);\n" + "end"; KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL) .build() .newKieSession(); ksession.getGlobals().set("scoreHolder",new HardSoftScoreHolder(true)); Person john = new Person("John", 25); ksession.insert(john); int fired = ksession.fireAllRules(); assertEquals(1, fired); }

Target:
public void testOrClause() { String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getName() + ";\n" + "import " + HardSoftScoreHolderMock.class.getName() + ";\n" + "global HardSoftScoreHolderMock scoreHolderMock;\n" + "rule R1\n" + "when\n" + " Person( age > 20 )\n" + " or\n" + " Person( name == \"John\")\n" + "then\n" + " scoreHolderMock.addSoftConstraintMatch(kcontext, -1);\n" + "end"; KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL) .build() .newKieSession(); ksession.getGlobals().set("scoreHolderMock", new HardSoftScoreHolderMock()); Person john = new Person("John", 25); ksession.insert(john); int fired = ksession.fireAllRules(); assertEquals(1, fired); }
Source:
public UserDevfileImpl updateUserDevfile(UserDevfile update) throws ConflictException, NotFoundException, ServerException { requireNonNull(update); UserDevfileImpl result = userDevfileDao.update(new UserDevfileImpl(update)); LOG.info( "UserDevfile '{}' with id '{}' update by user '{}'", result.getName(), result.getId(), EnvironmentContext.getCurrent().getSubject().getUserName()); eventService.publish(new DevfileUpdatedEvent(result)); return result; }

Target:
public UserDevfile updateUserDevfile(UserDevfile update) throws ConflictException, NotFoundException, ServerException { requireNonNull(update); Optional<UserDevfile> result = userDevfileDao.update(update); UserDevfile devfile = result.orElseThrow( () -> new NotFoundException( format("Devfile with id '%s' doesn't exist", update.getId()))); LOG.debug( "UserDevfile '{}' with id '{}' update by user '{}'", devfile.getName(), devfile.getId(), EnvironmentContext.getCurrent().getSubject().getUserName()); eventService.publish(new DevfileUpdatedEvent(devfile)); return devfile; }
Source:
public Builder addOptions(Map<String,String> options) { options.forEach((key, value) -> addOption(key, value)); return this; }

Target:
public Builder addOptions(Map<String,String> options) { options.forEach(this::addOption); return this; }
Source:
public Scheduler getScheduler() { return SchedulerFactory.singleton().createOrGetParallelScheduler("mongo", 10); }

Target:
public Scheduler getScheduler() { LOGGER.info("maxConcurrency is {}", maxConcurrency); return SchedulerFactory.singleton().createOrGetParallelScheduler(MongoDbInterpreter.class.getName() + this.hashCode(), maxConcurrency); }
Source:
public AvroParquetFileWriter(LogFilePath logFilePath, CompressionCodec codec) throws IOException { Path path = new Path(logFilePath.getLogFilePath()); LOG.debug("Creating Brand new Writer for path {}", path); CompressionCodecName codecName = CompressionCodecName .fromCompressionCodec(codec != null ? codec.getClass() : null); topic = logFilePath.getTopic(); Schema schema; if (!schemaOverride.isEmpty()) { schema = schemaRegistryClient.getSchema(schemaOverride); } else { try { schema = schemaRegistryClient.getSchema(topic); } catch (IllegalStateException exc) { topic += schemaSuffix; schema = schemaRegistryClient.getSchema(topic); } } writer = AvroParquetWriter.builder(path) .withSchema(schema) .withCompressionCodec(codecName) .build(); }

Target:
public AvroParquetFileWriter(LogFilePath logFilePath, CompressionCodec codec) throws IOException { Path path = new Path(logFilePath.getLogFilePath()); LOG.debug("Creating Brand new Writer for path {}", path); CompressionCodecName codecName = CompressionCodecName .fromCompressionCodec(codec != null ? codec.getClass() : null); topic = logFilePath.getTopic(); Schema schema = getSchema(topic); datumReader = new SpecificDatumReader<>(schema); writer = AvroParquetWriter.builder(path) .withSchema(schema) .withCompressionCodec(codecName) .build(); }
Source:
public void testConstructorNotAndModifiedSince() throws SearchException, IOException, ImapAsyncClientException { final ExtendedSearchSequence searchSeq = new ExtendedSearchSequence(); final ExtendedModifiedSinceTerm extendedModifiedSinceTerm = new ExtendedModifiedSinceTerm(1L); final BodyTerm bodyTerm = new BodyTerm("test"); final AndTerm andTerm = new AndTerm(bodyTerm, extendedModifiedSinceTerm); final NotTerm notTerm = new NotTerm(andTerm); final Argument args = new Argument(); args.append(searchSeq.generateSequence(notTerm)); final String searchStr = args.toString(); Assert.assertEquals(searchStr, "NOT (BODY test MODSEQ 1)", "result mismatched."); }

Target:
public void testConstructorNotAndModifiedSince() throws SearchException, IOException { final ExtendedSearchSequence searchSeq = new ExtendedSearchSequence(); final ExtendedModifiedSinceTerm extendedModifiedSinceTerm = new ExtendedModifiedSinceTerm(1L); final BodyTerm bodyTerm = new BodyTerm("test"); final AndTerm andTerm = new AndTerm(bodyTerm, extendedModifiedSinceTerm); final NotTerm notTerm = new NotTerm(andTerm); final Argument args = new Argument(); args.append(searchSeq.generateSequence(notTerm)); final String searchStr = args.toString(); Assert.assertEquals(searchStr, "NOT (BODY test MODSEQ 1)", "generateSequence() mismatched."); }
Source:
public boolean perform(final GridWidget gridWidget, final boolean isShiftKeyDown, final boolean isControlKeyDown) { final boolean needToRedraw = super.perform(gridWidget, isShiftKeyDown, isControlKeyDown); final GridData model = gridWidget.getModel(); if (model.getSelectedCells().size() == 1) { final GridData.SelectedCell selectedCell = model.getSelectedCells().get(0); final GridCellValue<?> value = model.getCell(selectedCell.getRowIndex(), ColumnIndexUtilities.findUiColumnIndex(model.getColumns(), selectedCell.getColumnIndex())).getValue(); if (value instanceof ExpressionCellValue) { final Optional<BaseExpressionGrid> grid = ((ExpressionCellValue) value).getValue(); grid.ifPresent(baseExpressionGrid -> { gridLayer.select(baseExpressionGrid); baseExpressionGrid.selectFirstCell(); }); } } return needToRedraw; }

Target:
public boolean perform(final GridWidget gridWidget, final boolean isShiftKeyDown, final boolean isControlKeyDown) { final boolean changesToBeRendered = super.perform(gridWidget, isShiftKeyDown, isControlKeyDown); final GridData model = gridWidget.getModel(); final GridData.SelectedCell selectedCell = model.getSelectedCells().get(0); final GridCellValue<?> value = model.getCell(selectedCell.getRowIndex(), ColumnIndexUtilities.findUiColumnIndex(model.getColumns(), selectedCell.getColumnIndex())).getValue(); if (value instanceof ExpressionCellValue) { final Optional<BaseExpressionGrid> grid = ((ExpressionCellValue) value).getValue(); grid.ifPresent(baseExpressionGrid -> { gridLayer.select(baseExpressionGrid); baseExpressionGrid.selectFirstCell(); }); } return changesToBeRendered; }
Source:
private boolean isHtmlSpace(int ch) { return ch <= 0x20 && (HTML_SPACE_CHAR_BITMASK & (1L << ch)) != 0; }

Target:
private boolean isHtmlSpace(int ch) { switch (ch) { case ' ': case '\t': case '\n': case '\u000c': case '\r': return true; default: return false; } }
Source:
private void cancel() { sourceListModel.setWindow(null); sourceListModel.setConfirmWindow(null); sourceListModel.getSearchCommand().execute(); }

Target:
private void cancel() { sourceListModel.setWindow(null); }
Source:
public TypedExpression invoke(Statement statement) { logger.debug("RHS phase on:\t\t" + printConstraint(statement)); Context ctx = new Context(); TypedExpression typedExpression = statement.accept(this, ctx); if (typedExpression == null) { throw new MvelCompilerException("Type check of " + printConstraint(statement) + " failed."); } logger.debug("RHS phase completed"); return typedExpression; }

Target:
public TypedExpression invoke(Statement statement) { logger.debug("LHS phase on:\t\t" + printConstraint(statement)); Context ctx = new Context(); TypedExpression typedExpression = statement.accept(this, ctx); if (typedExpression == null) { throw new MvelCompilerException("Type check of " + printConstraint(statement) + " failed."); } logger.debug("LHS phase completed"); return typedExpression; }
Source:
public void stop(BundleContext context) throws Exception { try { Job.getJobManager().join(LUCENE_JOB_FAMILY, null); plugin = null; } finally { super.stop(context); } }

Target:
public void stop(BundleContext context) throws Exception { try { Job.getJobManager().join(LUCENE_JOB_FAMILY, null); } finally { plugin = null; super.stop(context); } }
Source:
public void testLpad() { String lpad = StringUtils.lpad("abc", 7, "de"); Assert.assertEquals("dedeabc", lpad); lpad = StringUtils.lpad("abc", 6, "de"); Assert.assertEquals("dedabc", lpad); lpad = StringUtils.lpad("abc", 2, "de"); Assert.assertEquals("ab", lpad); lpad = StringUtils.lpad("abc", 0, "de"); Assert.assertEquals("", lpad); lpad = StringUtils.lpad("abc", -1, "de"); Assert.assertNull(lpad); lpad = StringUtils.lpad("abc", 10, ""); Assert.assertEquals("abc", lpad); lpad = StringUtils.lpad("abc", 1, ""); Assert.assertEquals("a", lpad); }

Target:
public void testLpad() { String lpad = StringUtils.lpad("abc", 7, "de"); Assert.assertEquals("dedeabc", lpad); lpad = StringUtils.lpad("abc", 6, "de"); Assert.assertEquals("dedabc", lpad); lpad = StringUtils.lpad("abc", 2, "de"); Assert.assertEquals("ab", lpad); lpad = StringUtils.lpad("abc", 0, "de"); Assert.assertEquals("", lpad); lpad = StringUtils.lpad("abc", -1, "de"); Assert.assertEquals("", lpad); lpad = StringUtils.lpad("abc", 10, ""); Assert.assertEquals("abc", lpad); lpad = StringUtils.lpad("abc", 1, ""); Assert.assertEquals("a", lpad); }
Source:
public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new UnsupportedOperationException("Not Yet Implemented!"); }

Target:
public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new UnsupportedOperationException("@RegisterContainerMapper is not supported on parameters"); }
Source:
private static Collection<Unit> findRolledTargets( final List<Unit> availableTargets, final DiceRoll dice) { final List<Die> rolls = dice.getRolls(); final List<Unit> hitTargets = new ArrayList<>(); for (int i = 0; i < rolls.size(); i++) { if (rolls.get(i).getType() == DieType.HIT) { hitTargets.add(availableTargets.get(i)); } } return hitTargets; }

Target:
private static Collection<Unit> findRolledTargets( final List<Unit> availableTargets, final DiceRoll dice) { Preconditions.checkArgument( availableTargets.size() == dice.getRolls().size(), "findRolledTargets needs one roll per target"); return IntStream.range(0, dice.getRolls().size()) .filter(rollIdx -> dice.getRolls().get(rollIdx).getType() == DieType.HIT) .mapToObj(availableTargets::get) .collect(Collectors.toList()); }
Source:
public void txnCanCommitIfOverwrittenAndRetry() throws Exception { CorfuRuntime rt = getNewRuntime(getRuntime().getParameters()) .parseConfigurationString(getDefaultConfigurationString()); rt.connect(); OptimisticTXBegin(); put("k1", "v1"); put("k2", "v2"); AtomicInteger counter = new AtomicInteger(0); addClientRule(getRuntime(), new TestRule().matches(corfuMsg -> { if (corfuMsg.getMsgType().equals(CorfuMsgType.WRITE) && counter.getAndAdd(1) == 0) { Token token = rt.getSequencerView().query().getToken(); rt.getAddressSpaceView().read(token.getSequence()); } return true; })); assertThatCode(this::TXEnd).doesNotThrowAnyException(); }

Target:
public void txnCanCommitIfOverwrittenAndRetry() throws Exception { CorfuRuntime rt = getNewRuntime(getRuntime().getParameters()) .parseConfigurationString(getDefaultConfigurationString()); rt.connect(); OptimisticTXBegin(); put("k1", "v1"); put("k2", "v2"); long currentTail = rt.getSequencerView().query().getToken().getSequence(); rt.getAddressSpaceView().read(currentTail + 1); assertThatCode(this::TXEnd).doesNotThrowAnyException(); assertThat(rt.getSequencerView().query().getToken().getSequence()).isEqualTo(currentTail + 2); assertThat(get("k1")).isEqualTo("v1"); assertThat(get("k2")).isEqualTo("v2"); }
Source:
public String getUrlName() { if (getProject() != null && getProject().getLastCompletedBuild() != null && getProject().isBuildable()) { return getProject().getLastCompletedBuild().getNumber() + "/rebuild"; } else { return "build?delay=0sec"; } }

Target:
public String getUrlName() { boolean isBuildable = getProject() != null && getProject().isBuildable(); boolean hasCompletedBuild = getProject().getLastCompletedBuild() != null; if (isBuildable) { if (hasCompletedBuild) { return getProject().getLastCompletedBuild().getNumber() + "/rebuild"; } else { return "build?delay=0sec"; } } else { return null; } }