auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void failed(Throwable cause) { try (SetThreadName ignored = new SetThreadName("TaskInfoFetcher-%s", taskId)) { lastUpdateNanos.set(System.nanoTime()); try { if (!isDone(getTaskInfo())) { errorTracker.requestFailed(cause); } } catch (Error e) { onFail.accept(e); throw e; } catch (RuntimeException e) { onFail.accept(e); updateTaskInfo(taskInfo.get().withTaskStatus(failWith(taskInfo.get().getTaskStatus(), FAILED, ImmutableList.of(toFailure(cause))))); } } }

Target:
public void failed(Throwable cause) { try (SetThreadName ignored = new SetThreadName("TaskInfoFetcher-%s", taskId)) { lastUpdateNanos.set(System.nanoTime()); try { if (!isDone(getTaskInfo())) { errorTracker.requestFailed(cause); } } catch (Error e) { onFail.accept(e); throw e; } catch (RuntimeException e) { onFail.accept(e); } } }
Source:
public void boot(boolean create,Properties startParams) throws StandardException{ Configuration.setConfiguration(null); SConfiguration config = SIDriver.driver().getConfiguration(); if (startParams == null) { startParams = new Properties(); } if (System.getProperty("derby.drda.timeSlice") == null) System.setProperty("derby.drda.timeSlice","60000"); String logStatementText = System.getProperty("derby.language.logStatementText"); if (logStatementText == null) { if (config.debugLogStatementContext()) { System.setProperty("com.splicemachine.enableLegacyAsserts", Boolean.TRUE.toString()); startParams.put("derby.language.logStatementText", Boolean.TRUE.toString()); } else { startParams.put("derby.language.logStatementText", Boolean.FALSE.toString()); } } if (config.debugDumpClassFile()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpClassFile"); } if (config.debugDumpBindTree()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpBindTree"); } if (config.debugDumpOptimizedTree()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpOptimizedTree"); } configureAuthentication(); create=Boolean.TRUE.equals(EngineLifecycleService.isCreate.get()); if(create){ SpliceLogUtils.info(LOG,"Creating the Splice Machine database"); }else{ SpliceLogUtils.info(LOG,"Booting the Splice Machine database"); } super.boot(create,startParams); }

Target:
public void boot(boolean create,Properties startParams) throws StandardException{ Configuration.setConfiguration(null); SConfiguration config = SIDriver.driver().getConfiguration(); if (startParams == null) { startParams = new Properties(); } if (System.getProperty("derby.drda.timeSlice") == null) System.setProperty("derby.drda.timeSlice","60000"); String logStatementText = System.getProperty("derby.language.logStatementText"); if (logStatementText == null) { startParams.put("derby.language.logStatementText", Boolean.toString(config.debugLogStatementContext())); } if (config.debugDumpClassFile()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpClassFile"); } if (config.debugDumpBindTree()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpBindTree"); } if (config.debugDumpOptimizedTree()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpOptimizedTree"); } configureAuthentication(); create=Boolean.TRUE.equals(EngineLifecycleService.isCreate.get()); if(create){ SpliceLogUtils.info(LOG,"Creating the Splice Machine database"); }else{ SpliceLogUtils.info(LOG,"Booting the Splice Machine database"); } super.boot(create,startParams); }
Source:
protected boolean isDataStall() { boolean result = false; if (!mNetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) && (SystemClock.elapsedRealtime() - getLastProbeTime() < mDataStallMinEvaluateTime)) { return false; } if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_DNS)) { if (mDnsStallDetector.isDataStallSuspected(mConsecutiveDnsTimeoutThreshold, mDataStallValidDnsTimeThreshold)) { result = true; logNetworkEvent(NetworkEvent.NETWORK_CONSECUTIVE_DNS_TIMEOUT_FOUND); } } if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_TCP)) { if (getTcpSocketTracker().getSentSinceLastRecv() > 0) { result = false; } else if (getTcpSocketTracker().isDataStallSuspected()) { result = true; } } if (VDBG_STALL) { log("isDataStall: result=" + result + ", consecutive dns timeout count=" + mDnsStallDetector.getConsecutiveTimeoutCount() + ", tcp packets received=" + getTcpSocketTracker().getSentSinceLastRecv() + ", tcp fail rate=" + getTcpSocketTracker().getLatestPacketFailRate()); } return result; }

Target:
protected boolean isDataStall() { Boolean result = null; if (!mNetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) && (SystemClock.elapsedRealtime() - getLastProbeTime() < mDataStallMinEvaluateTime)) { return false; } if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_TCP)) { if (getTcpSocketTracker().getSentSinceLastRecv() > 0) { result = false; } if ((result == null) && getTcpSocketTracker().isDataStallSuspected()) { result = true; } } if ((result == null) && dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_DNS)) { if (mDnsStallDetector.isDataStallSuspected(mConsecutiveDnsTimeoutThreshold, mDataStallValidDnsTimeThreshold)) { result = true; logNetworkEvent(NetworkEvent.NETWORK_CONSECUTIVE_DNS_TIMEOUT_FOUND); } } if (VDBG_STALL) { log("isDataStall: result=" + result + ", consecutive dns timeout count=" + mDnsStallDetector.getConsecutiveTimeoutCount() + ", tcp packets received=" + getTcpSocketTracker().getSentSinceLastRecv() + ", tcp fail rate=" + getTcpSocketTracker().getLatestPacketFailRate()); } return (result == null) ? false : result; }
Source:
public InetAddress getLocalAddress() throws IOException { return InetAddress.getByName( new RqHeaders.Base(this).header("X-Takes-LocalAddress") .iterator().next() ); }

Target:
public InetAddress getLocalAddress() throws IOException { return InetAddress.getByName( new RqHeaders.Smart(new RqHeaders.Base(this)) .single("X-Takes-LocalAddress") ); }
Source:
protected boolean isVmLeaseExistsOnStorageDomain(Guid leaseStorageDomainId) { ActionReturnValue retVal = runInternalAction(ActionType.GetVmLeaseInfo, new VmLeaseParameters(getStoragePoolId(), leaseStorageDomainId, getParameters().getVmId())); if (retVal.getSucceeded() && retVal.getActionReturnValue() != null) { log.info("Managed to fetch VM '{}' lease info from storage domains '{}', '{}'", getParameters().getVmId(), leaseStorageDomainId, retVal.getActionReturnValue()); getVm().setLeaseInfo(retVal.getActionReturnValue()); return true; } return false; }

Target:
protected boolean isVmLeaseExistsOnStorageDomain(Guid leaseStorageDomainId) { ActionReturnValue retVal = runInternalAction(ActionType.GetVmLeaseInfo, new VmLeaseParameters(getStoragePoolId(), leaseStorageDomainId, getParameters().getVmId())); if (retVal.getSucceeded() && retVal.getActionReturnValue() != null) { log.info("Managed to fetch VM '{}' lease info from the storage domain '{}': '{}'", getParameters().getVmId(), leaseStorageDomainId, retVal.getActionReturnValue()); getVm().setLeaseInfo(retVal.getActionReturnValue()); return true; } return false; }
Source:
public void complete(Predicate<SubscriptionQueryMessage<?, ?, ?>> filter) { registeringSubscriptionQueryReadSafe(filter, () -> updateHandlers.keySet() .stream() .filter(filter) .forEach(query -> { UpdateHandler<?, ?> updateHandler = updateHandlers.get(query); updateHandlers.remove(query); updateHandler.onCompleted(); })); }

Target:
public void complete(Predicate<SubscriptionQueryMessage<?, ?, ?>> filter) { updateHandlers.keySet() .stream() .filter(filter) .forEach(query -> Optional.ofNullable(updateHandlers.get(query)) .ifPresent(updateHandler -> { try { updateHandler.complete(); } catch (Exception e) { emitError(query, e, updateHandler); } })); }
Source:
private void updateConditionSets(List<Expression> expressions, TagNode node) { Optional<String> condition = node.getAttributes().stream() .map(Attribute::getName) .filter(text -> text.contains(SLY_TEST)) .findFirst(); if (condition.isPresent() && !condition.get().equals(SLY_TEST)) { condition = Optional.of(condition.get().substring(14)); namedConditions.add(condition.get()); } else { unnamedConditions.addAll(expressions.stream() .map(Expression::getRawText) .map(text -> text.replaceAll("[${}]", "")) .filter(text -> !namedConditions.contains(text)) .collect(Collectors.toSet())); } }

Target:
private void updateConditionSets(List<Expression> expressions, TagNode node) { String condition = node.getAttributes().stream() .map(Attribute::getName) .filter(text -> text.contains(SLY_TEST)) .findFirst() .orElse(""); if (!SLY_TEST.equals(condition) && SLY_TEST_LENGTH < condition.length()) { condition = condition.substring(SLY_TEST_LENGTH); namedConditions.add(condition); } else { unnamedConditions.addAll(clearExpressions(expressions).stream() .filter(text -> !namedConditions.contains(text)) .collect(Collectors.toSet())); } }
Source:
public String stemWord(String word) { word = word.toLowerCase(eoLocale); String suffix = word; if (isExceptionOrNumber(suffix)) { return word; } int localMinStemLength = Math.max(minStemLength, firstVowelPos(suffix) + 1); int pluralDirectOffset = calcPluralDirectOffset(suffix); if (pluralDirectOffset > 0) { suffix = suffix.substring(0, suffix.length() - pluralDirectOffset); if (pluralDirectChecks.contains(suffix) || stemmerExceptions.contains(suffix)) { return suffix; } } suffix = findLongestSuffix(suffix, word, minStemLength + pluralDirectOffset); int stemLength = 0; if (!suffix.equals("")) { stemLength = word.length() - suffix.length() - pluralDirectOffset; if (suffix.charAt(0) == '-' && suffix.length() + pluralDirectOffset < word.length()) { return word.substring(0, stemLength); } } if (stemLength < localMinStemLength) { return word; } return word.substring(0, stemLength); }

Target:
public String stemWord(String word) { if (word == null) { return word; } word = word.toLowerCase(eoLocale); if (isExceptionOrNumber(word)) { return word; } String suffix = word; int localMinStemLength = Math.max(minStemLength, firstVowelPos(suffix) + 1); int pluralDirectOffset = calcPluralDirectOffset(suffix); if (pluralDirectOffset > 0) { suffix = suffix.substring(0, suffix.length() - pluralDirectOffset); if (pluralDirectChecks.contains(suffix) || stemmerExceptions.contains(suffix)) { return suffix; } } suffix = findLongestSuffix(suffix, word, localMinStemLength, pluralDirectOffset); int stemLength = 0; if (!suffix.isEmpty()) { stemLength = word.length() - suffix.length() - pluralDirectOffset; if (suffix.charAt(0) == '-' && suffix.length() + pluralDirectOffset < word.length()) { return word.substring(0, stemLength); } } if (stemLength < localMinStemLength) { return word; } return word.substring(0, stemLength); }
Source:
public WorkflowResource(HttpClient client, SessionFactory sessionFactory, PermissionsInterface permissionsInterface, EntryResource entryResource, DockstoreWebserviceConfiguration configuration) { super(client, sessionFactory, configuration, Workflow.class); this.toolDAO = new ToolDAO(sessionFactory); this.labelDAO = new LabelDAO(sessionFactory); this.fileFormatDAO = new FileFormatDAO(sessionFactory); this.permissionsInterface = permissionsInterface; this.entryResource = entryResource; elasticManager = new ElasticManager(); zenodoUrl = configuration.getZenodoUrl(); zenodoClientID = configuration.getZenodoClientID(); zenodoClientSecret = configuration.getZenodoClientSecret(); dockstoreUrl = URIHelper.createBaseUrl(configuration.getExternalConfig().getScheme(), configuration.getExternalConfig().getHostname(), configuration.getExternalConfig().getUiPort()); try { dockstoreGA4GHBaseUrl = ToolsImplCommon.baseURL(configuration); } catch (URISyntaxException e) { LOG.error("Could create Dockstore base URL. Error is " + e.getMessage(), e); throw new CustomWebApplicationException("Could create Dockstore base URL. " + "Error is " + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } MetadataResourceHelper.setConfig(configuration); }

Target:
public WorkflowResource(HttpClient client, SessionFactory sessionFactory, PermissionsInterface permissionsInterface, EntryResource entryResource, DockstoreWebserviceConfiguration configuration) { super(client, sessionFactory, configuration, Workflow.class); this.toolDAO = new ToolDAO(sessionFactory); this.labelDAO = new LabelDAO(sessionFactory); this.fileFormatDAO = new FileFormatDAO(sessionFactory); this.permissionsInterface = permissionsInterface; this.entryResource = entryResource; elasticManager = new ElasticManager(); zenodoUrl = configuration.getZenodoUrl(); zenodoClientID = configuration.getZenodoClientID(); zenodoClientSecret = configuration.getZenodoClientSecret(); dockstoreUrl = URIHelper.createBaseUrl(configuration.getExternalConfig().getScheme(), configuration.getExternalConfig().getHostname(), configuration.getExternalConfig().getUiPort()); try { dockstoreGA4GHBaseUrl = ToolsImplCommon.baseURL(configuration); } catch (URISyntaxException e) { LOG.error("Could create Dockstore base URL. Error is " + e.getMessage(), e); throw new CustomWebApplicationException("Could create Dockstore base URL. " + "Error is " + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
Source:
public ContentDirectoryMonitor( CamelContext camelContext, AttributeRegistry attributeRegistry, int maxRetries, int delayBetweenRetries, Executor configurationExecutor, Security security) { this.camelContext = Objects.requireNonNull(camelContext, "CamelContext cannot be null"); this.attributeRegistry = attributeRegistry; this.maxRetries = maxRetries; this.delayBetweenRetries = delayBetweenRetries; this.configurationExecutor = configurationExecutor; this.security = security; systemSubjectBinder = new SystemSubjectBinder(security); setBlacklist(); }

Target:
public ContentDirectoryMonitor( CamelContext camelContext, AttributeRegistry attributeRegistry, int maxRetries, int delayBetweenRetries, Executor configurationExecutor, Security security) { this.camelContext = Objects.requireNonNull(camelContext, "camelContext cannot be null"); this.attributeRegistry = attributeRegistry; this.maxRetries = maxRetries; this.delayBetweenRetries = delayBetweenRetries; this.configurationExecutor = configurationExecutor; this.security = security; systemSubjectBinder = new SystemSubjectBinder(security); setBlacklist(); }
Source:
public boolean hasEqualExtents(Grid comparisonGrid){ if (this.zoom != comparisonGrid.zoom || this.west != comparisonGrid.west || this.north != comparisonGrid.north || this.width != comparisonGrid.width || this.height != comparisonGrid.height) return false; else return true; }

Target:
public boolean hasEqualExtents(Grid comparisonGrid){ return this.zoom == comparisonGrid.zoom && this.west == comparisonGrid.west && this.north == comparisonGrid.north && this.width == comparisonGrid.width && this.height == comparisonGrid.height; }
Source:
protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .addProperty(SearchConfig.DIRECTORY_TYPE, SearchConfig.HEAP); return TestCacheManagerFactory.createCacheManager(builder); }

Target:
protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable(); return TestCacheManagerFactory.createCacheManager(builder); }
Source:
private void runGroupsQuery(JSONArray resultArray, String queryString, String formattedInput, int maxResults) throws Exception { List<String> queryResult = runQuery(queryString, formattedInput, maxResults); for (String groupName : queryResult) { Group group = this.groupManager.getGroup(groupName); List<AttachmentReference> attachmentRefs = this.bridge.getAttachmentReferences(group.getReference()); String avatarURL = ""; if (attachmentRefs.size() > 0) { avatarURL = this.bridge.getAttachmentURL(attachmentRefs.get(0), true); } else { XWikiContext xcontext = this.xcontextProvider.get(); XWiki xwiki = xcontext.getWiki(); avatarURL = xwiki.getSkinFile("icons/xwiki/noavatargroup.png", xcontext); } JSONObject o = createObject(groupName, group.getReference().getName(), avatarURL, GROUP); resultArray.put(o); if (resultArray.length() == maxResults) { break; } } }

Target:
private void runGroupsQuery(JSONArray resultArray, String queryString, String formattedInput, int maxResults) throws Exception { List<String> queryResult = runQuery(queryString, formattedInput, maxResults); for (String groupName : queryResult) { Group group = this.groupManager.getGroup(groupName); List<AttachmentReference> attachmentRefs = this.bridge.getAttachmentReferences(group.getReference()); String avatarURL = ""; if (attachmentRefs.size() > 0) { avatarURL = this.bridge.getAttachmentURL(attachmentRefs.get(0), true); } else { XWikiContext xcontext = this.xcontextProvider.get(); XWiki xwiki = xcontext.getWiki(); avatarURL = xwiki.getSkinFile("icons/xwiki/noavatargroup.png", xcontext); } JSONObject o = createObject(groupName, group.getReference().getName(), avatarURL, GROUP); resultArray.put(o); } }
Source:
public void findEdgesInShape(final GHIntHashSet edgeIds, final Shape shape, EdgeFilter filter) { GHPoint center = shape.getCenter(); QueryResult qr = locationIndex.findClosest(center.getLat(), center.getLon(), filter); if (!qr.isValid()) throw new IllegalArgumentException("Shape " + shape + " does not cover graph"); if (shape.contains(qr.getSnappedPoint().lat, qr.getSnappedPoint().lon)) edgeIds.add(qr.getClosestEdge().getEdge()); final boolean isPolygon = shape instanceof Polygon; BreadthFirstSearch bfs = new BreadthFirstSearch() { final NodeAccess na = graph.getNodeAccess(); final Shape localShape = shape; @Override protected boolean goFurther(int nodeId) { if (isPolygon) { BBox bbox = localShape.getBounds(); double lat = na.getLatitude(nodeId); double lon = na.getLongitude(nodeId); return lat <= bbox.maxLat && lat >= bbox.minLat && lon <= bbox.maxLon && lon >= bbox.minLon; } return localShape.contains(na.getLatitude(nodeId), na.getLongitude(nodeId)); } @Override protected boolean checkAdjacent(EdgeIteratorState edge) { if (localShape.contains(na.getLatitude(edge.getAdjNode()), na.getLongitude(edge.getAdjNode()))) { edgeIds.add(edge.getEdge()); return true; } return isPolygon; } }; bfs.start(graph.createEdgeExplorer(filter), qr.getClosestNode()); }

Target:
public void findEdgesInShape(final GHIntHashSet edgeIds, final Shape shape, EdgeFilter filter) { GHPoint center = shape.getCenter(); QueryResult qr = locationIndex.findClosest(center.getLat(), center.getLon(), filter); if (!qr.isValid()) throw new IllegalArgumentException("Shape " + shape + " does not cover graph"); if (shape.contains(qr.getSnappedPoint().lat, qr.getSnappedPoint().lon)) edgeIds.add(qr.getClosestEdge().getEdge()); final boolean isPolygon = shape instanceof Polygon; BreadthFirstSearch bfs = new BreadthFirstSearch() { final NodeAccess na = graph.getNodeAccess(); final Shape localShape = shape; @Override protected boolean goFurther(int nodeId) { if (isPolygon) return isInsideBBox(nodeId); return localShape.contains(na.getLatitude(nodeId), na.getLongitude(nodeId)); } @Override protected boolean checkAdjacent(EdgeIteratorState edge) { int adjNodeId = edge.getAdjNode(); if (localShape.contains(na.getLatitude(adjNodeId), na.getLongitude(adjNodeId))) { edgeIds.add(edge.getEdge()); return true; } return isPolygon && isInsideBBox(adjNodeId); } private boolean isInsideBBox(int nodeId) { BBox bbox = localShape.getBounds(); double lat = na.getLatitude(nodeId); double lon = na.getLongitude(nodeId); return lat <= bbox.maxLat && lat >= bbox.minLat && lon <= bbox.maxLon && lon >= bbox.minLon; } }; bfs.start(graph.createEdgeExplorer(filter), qr.getClosestNode()); }
Source:
private void subscribeUpstreamChains(Context downstreamContext) { innerFlux.subscriberContext(downstreamContext).subscribe(); upstreamFlux.subscriberContext(downstreamContext).subscribe(); }

Target:
private void subscribeUpstreamChains(Context downstreamContext) { innerFlux.subscriberContext(downstreamContext) .doOnError(e -> LOGGER.error("Exception during foreach execution: " + e.getCause())) .subscribe(); upstreamFlux.subscriberContext(downstreamContext).subscribe(); }
Source:
public StoreConfig(VerifiableProperties verifiableProperties) { storeKeyFactory = verifiableProperties.getString("store.key.factory", "com.github.ambry.shared.BlobIdFactory"); storeDataFlushIntervalSeconds = verifiableProperties.getLong("store.data.flush.interval.seconds", 60); storeIndexMaxMemorySizeBytes = verifiableProperties.getInt("store.index.max.memory.size.bytes", 20*1024*1024); storeDataFlushDelaySeconds = verifiableProperties.getInt("store.data.flush.delay.seconds", 5); storeIndexMaxNumberOfInmemElements = verifiableProperties.getInt("store.index.max.number.of.inmem.elements", 10000); storeIndexBloomMaxFalsePositiveProbability = verifiableProperties.getDoubleInRange( "store.index.bloom.max.false.positive.probability", 0.01, 0.0, 1.0); storeMaxNumberOfEntriesToReturnFromJournal = verifiableProperties.getInt( "store.max.number.of.entries.to.return.from.journal", 5000); }

Target:
public StoreConfig(VerifiableProperties verifiableProperties) { storeKeyFactory = verifiableProperties.getString("store.key.factory", "com.github.ambry.shared.BlobIdFactory"); storeDataFlushIntervalSeconds = verifiableProperties.getLong("store.data.flush.interval.seconds", 60); storeIndexMaxMemorySizeBytes = verifiableProperties.getInt("store.index.max.memory.size.bytes", 20*1024*1024); storeDataFlushDelaySeconds = verifiableProperties.getInt("store.data.flush.delay.seconds", 5); storeIndexMaxNumberOfInmemElements = verifiableProperties.getInt("store.index.max.number.of.inmem.elements", 10000); storeIndexBloomMaxFalsePositiveProbability = verifiableProperties.getDoubleInRange( "store.index.bloom.max.false.positive.probability", 0.01, 0.0, 1.0); storeMaxNumberOfEntriesToReturnFromJournal = verifiableProperties.getIntInRange( "store.max.number.of.entries.to.return.from.journal", 5000, 1, 10000); }
Source:
private CalculationTasks(List<CalculationTask> tasks, List<Column> columns) { this.columns = ImmutableList.copyOf(columns); this.tasks = ImmutableList.copyOf(tasks); long taskCount = tasks.stream() .flatMap(task -> task.getCells().stream()) .count(); int columnCount = columns.size(); if (taskCount != 0) { if (columnCount == 0) { throw new IllegalArgumentException("There must be at least one column"); } if (taskCount % columnCount != 0) { throw new IllegalArgumentException( Messages.format( "Number of tasks ({}) must be exactly divisible by the number of columns ({})", taskCount, columnCount)); } } int targetCount = (int) taskCount / columnCount; CalculationTarget[] targets = new CalculationTarget[targetCount]; for (CalculationTask task : tasks) { int rowIndex = task.getRowIndex(); if (targets[rowIndex] == null) { targets[rowIndex] = task.getTarget(); } else if (targets[rowIndex] != task.getTarget()) { throw new IllegalArgumentException("Tasks define two different targets for the same row"); } } this.targets = ImmutableList.copyOf(targets); }

Target:
private CalculationTasks(List<CalculationTask> tasks, List<Column> columns) { this.columns = ImmutableList.copyOf(columns); this.tasks = ImmutableList.copyOf(tasks); long cellCount = tasks.stream() .flatMap(task -> task.getCells().stream()) .count(); int columnCount = columns.size(); if (cellCount != 0) { if (columnCount == 0) { throw new IllegalArgumentException("There must be at least one column"); } if (cellCount % columnCount != 0) { throw new IllegalArgumentException( Messages.format( "Number of cells ({}) must be exactly divisible by the number of columns ({})", cellCount, columnCount)); } } int targetCount = (int) cellCount / columnCount; CalculationTarget[] targets = new CalculationTarget[targetCount]; for (CalculationTask task : tasks) { int rowIdx = task.getRowIndex(); if (targets[rowIdx] == null) { targets[rowIdx] = task.getTarget(); } else if (targets[rowIdx] != task.getTarget()) { throw new IllegalArgumentException(Messages.format( "Tasks define two different targets for row {}: and {}", rowIdx, targets[rowIdx], task.getTarget())); } } this.targets = ImmutableList.copyOf(targets); }
Source:
public Response addCustomizedStateAggregationConfig(@PathParam("clusterId") String clusterId, String content) { HelixZkClient zkClient = getHelixZkClient(); if (!ZKUtil.isClusterSetup(clusterId, zkClient)) { return notFound("Cluster is not properly setup!"); } HelixAdmin admin = getHelixAdmin(); ZNRecord record; try { record = toZNRecord(content); } catch (IOException e) { _logger.error("Failed to deserialize user's input " + content + ", Exception: " + e); return badRequest("Input is not a vaild ZNRecord!"); } try { CustomizedStateAggregationConfig customizedStateAggregationConfig = new CustomizedStateAggregationConfig.Builder(record).build(); admin.addCustomizedStateAggregationConfig(clusterId, customizedStateAggregationConfig); } catch (HelixException ex) { _logger.error("Error in adding a CustomizedStateAggregationConfig to cluster: " + clusterId, ex); return badRequest(ex.getMessage()); } catch (Exception ex) { _logger.error("Cannot add CustomizedStateAggregationConfig to cluster: " + clusterId, ex); return serverError(ex); } return OK(); }

Target:
public Response addCustomizedStateAggregationConfig(@PathParam("clusterId") String clusterId, String content) { if (!doesClusterExist(clusterId)) { return notFound(String.format("Cluster %s does not exist", clusterId)); } HelixAdmin admin = getHelixAdmin(); ZNRecord record; try { record = toZNRecord(content); } catch (IOException e) { return badRequest("Input is not a vaild ZNRecord!"); } try { CustomizedStateAggregationConfig customizedStateAggregationConfig = new CustomizedStateAggregationConfig.Builder(record).build(); admin.addCustomizedStateAggregationConfig(clusterId, customizedStateAggregationConfig); } catch (Exception ex) { _logger.error("Cannot add CustomizedStateAggregationConfig to cluster: Exception: {}", clusterId, ex); return serverError(ex); } return OK(); }
Source:
public void updateDevicesHashes(List<Pair<Guid, String>> vmHashes) { getCallsHandler().executeStoredProcAsBatch("SetHashByVmGuid", vmHashes, pair -> getCustomMapSqlParameterSource() .addValue("v_vm_guid", pair.getFirst()) .addValue("v_hash", pair.getSecond())); }

Target:
public void updateDevicesHashes(List<Pair<Guid, String>> vmHashes) { getCallsHandler().executeStoredProcAsBatch("SetHashByVmGuid", vmHashes, pair -> getCustomMapSqlParameterSource() .addValue("vm_guid", pair.getFirst()) .addValue("hash", pair.getSecond())); }
Source:
protected void processRecord(ComputationContext context, Record record) { KeyValueStore kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(BULK_KV_STORE_NAME); try { String bulkActionId = record.getKey(); BulkCommand command = BulkCommandHelper.getBulkCommandJson(record.getData()); if (!kvStore.compareAndSet(bulkActionId + STATE, SCHEDULED.toString(), BUILDING.toString())) { log.error("Discard record: " + record + " because it's already building"); return; } try (CloseableCoreSession session = CoreInstance.openCoreSession(command.getRepository(), command.getUsername())) { ScrollResult<String> scroll = session.scroll(command.getQuery(), scrollBatchSize, scrollKeepAliveSeconds); long documentCount = 0; while (scroll.hasResults()) { List<String> docIds = scroll.getResults(); documentIds.addAll(docIds); if (documentIds.size() >= recordBatchSize) { produceRecord(context, command.getAction(), bulkActionId, record.getData()); } documentCount += docIds.size(); scroll = session.scroll(scroll.getScrollId()); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } while (!documentIds.isEmpty()) { produceRecord(context, command.getAction(), bulkActionId, record.getData()); } kvStore.put(bulkActionId + STATE, COMPLETED.toString()); kvStore.put(bulkActionId + SCROLLED_DOCUMENT_COUNT, documentCount); } } catch (NuxeoException e) { log.error("Discard invalid record: " + record, e); } }

Target:
protected void processRecord(ComputationContext context, Record record) { KeyValueStore kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(BULK_KV_STORE_NAME); try { String bulkId = record.getKey(); BulkCommand command = BulkCommands.fromBytes(record.getData()); if (!kvStore.compareAndSet(bulkId + STATE, SCHEDULED.toString(), SCROLLING_RUNNING.toString())) { log.error("Discard record: " + record + " because it's already building"); context.askForCheckpoint(); return; } try (CloseableCoreSession session = CoreInstance.openCoreSession(command.getRepository(), command.getUsername())) { ScrollResult<String> scroll = session.scroll(command.getQuery(), scrollBatchSize, scrollKeepAliveSeconds); long documentCount = 0; long bucketNumber = 0; while (scroll.hasResults()) { List<String> docIds = scroll.getResults(); documentIds.addAll(docIds); while (documentIds.size() >= bucketSize) { bucketNumber++; produceBucket(context, command.getAction(), bulkId, bucketNumber * bucketSize); } documentCount += docIds.size(); scroll = session.scroll(scroll.getScrollId()); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } if (!documentIds.isEmpty()) { produceBucket(context, command.getAction(), bulkId, documentCount); } kvStore.put(bulkId + STATE, RUNNING.toString()); kvStore.put(bulkId + SCROLLED_DOCUMENT_COUNT, documentCount); } } catch (NuxeoException e) { log.error("Discard invalid record: " + record, e); } }
Source:
public void concatenates() { final List<String> alist = new ArrayList<String>(2); final String aone = "a1"; final String atwo = "a2"; alist.add(aone); alist.add(atwo); final List<String> blist = new ArrayList<String>(2); final String bone = "b1"; final String btwo = "b2"; blist.add(bone); blist.add(btwo); MatcherAssert.assertThat( new Concat<String>(alist, blist), Matchers.hasItems(aone, atwo, bone, btwo) ); }

Target:
public void concatenates() { MatcherAssert.assertThat( Joiner.on(" ").join( new Concat<String>( Arrays.asList("one", "two"), Arrays.asList("three", "four") ) ), Matchers.equalTo("one two three four") ); }
Source:
public RefUpdate.Result save(CommitBuilder cb) throws IOException { if (added.isEmpty()) { return RefUpdate.Result.NO_CHANGE; } if (reader == null) { load(); } DirCache dc = newDirCache(); DirCacheEditor editor = dc.editor(); try (ObjectInserter inserter = db.newObjectInserter()) { for (Map.Entry<String, List<PushCertificate>> e : added.entrySet()) { String refName = e.getKey(); List<InputStream> streams = new ArrayList<>(e.getValue().size() + 1); long len = readExisting(refName, streams); len += joinCertificates(e.getValue(), streams); final ObjectId blobId = inserter.insert( OBJ_BLOB, len, new UnionInputStream(streams.toArray(new InputStream[0]))); editor.add(new PathEdit(pathName(refName)) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.REGULAR_FILE); ent.setObjectId(blobId); } }); } editor.finish(); cb.setTreeId(dc.writeTree(inserter)); if (commit != null) { cb.setParentId(commit); } else { cb.setParentIds(Collections.<ObjectId> emptyList()); } ObjectId newCommit = inserter.insert(OBJ_COMMIT, cb.build()); inserter.flush(); RefUpdate ru = db.updateRef(REF_NAME); ru.setExpectedOldObjectId(commit); ru.setNewObjectId(newCommit); ru.setRefLogIdent(cb.getCommitter()); RefUpdate.Result result = ru.update(new RevWalk(inserter.newReader())); if (result == RefUpdate.Result.NEW || result == RefUpdate.Result.FAST_FORWARD) { added.clear(); } return result; } finally { close(); } }

Target:
public RefUpdate.Result save(CommitBuilder cb) throws IOException { if (added.isEmpty()) { return RefUpdate.Result.NO_CHANGE; } if (reader == null) { load(); } DirCache dc = newDirCache(); DirCacheEditor editor = dc.editor(); try (ObjectInserter inserter = db.newObjectInserter()) { for (Map.Entry<String, List<PushCertificate>> e : added.entrySet()) { String refName = e.getKey(); List<InputStream> streams = new ArrayList<>(e.getValue().size() + 1); long len = readExisting(refName, streams); len += joinCertificates(e.getValue(), streams); final ObjectId blobId = inserter.insert( OBJ_BLOB, len, new UnionInputStream(streams.toArray(new InputStream[0]))); editor.add(new PathEdit(pathName(refName)) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.REGULAR_FILE); ent.setObjectId(blobId); } }); } editor.finish(); cb.setTreeId(dc.writeTree(inserter)); if (commit != null) { cb.setParentId(commit); } else { cb.setParentIds(Collections.<ObjectId> emptyList()); } ObjectId newCommit = inserter.insert(OBJ_COMMIT, cb.build()); inserter.flush(); RefUpdate ru = db.updateRef(REF_NAME); ru.setExpectedOldObjectId(commit); ru.setNewObjectId(newCommit); ru.setRefLogIdent(cb.getCommitter()); RefUpdate.Result result; try (ObjectReader insReader = inserter.newReader(); RevWalk rw = new RevWalk(insReader)) { result = ru.update(rw); } if (result == RefUpdate.Result.NEW || result == RefUpdate.Result.FAST_FORWARD) { added.clear(); } return result; } finally { close(); } }
Source:
public Iterator<Object[]> init() { if (isClosed()) return Collections.emptyIterator(); cctx = ectx.parent().kernal().cache().context().cacheContext(cacheId = desc.cacheId()); if (!cctx.group().sharedGroup()) cacheId = UNDEFINED_CACHE_ID; GridDhtPartitionTopology top = cctx.topology(); top.readLock(); try { GridDhtTopologyFuture fut = top.topologyVersionFuture(); AffinityTopologyVersion topVer = ectx.parent().topologyVersion(); if (!fut.isDone() || fut.topologyVersion().compareTo(topVer) != 0) throw new ClusterTopologyException("Failed to execute query. Retry on stable topology."); if (cctx.isPartitioned()) reservePartitioned(top); else reserveReplicated(top); } catch (Throwable e) { U.closeQuiet(this); throw e; } finally { top.readUnlock(); } return this; }

Target:
public Iterator<Object[]> init() throws IgniteCheckedException { if (isClosed()) return Collections.emptyIterator(); GridCacheContext<?, ?> cctx = desc.cacheContext(); if (!cctx.gate().enterIfNotStopped()) { close(); throw new CacheStoppedException(cctx.name()); } try { GridDhtPartitionTopology top = cctx.topology(); top.readLock(); try { GridDhtTopologyFuture fut = top.topologyVersionFuture(); AffinityTopologyVersion topVer = ectx.parent().topologyVersion(); if (!fut.isDone() || fut.topologyVersion().compareTo(topVer) != 0) throw new ClusterTopologyCheckedException("Failed to execute query. Retry on stable topology."); if (cctx.isPartitioned()) reservePartitioned(top); else reserveReplicated(top); } finally { top.readUnlock(); } cacheId = cctx.cacheId(); return this; } catch (Exception e) { Commons.close(this, e); throw e; } finally { cctx.gate().leave(); } }
Source:
public SecurityGroupExtensionProvider(NeutronSecurityGroupExtension neutronSecurityGroupExtension, NovaSecurityGroupExtension novaSecurityGroupExtension) { this.neutronSecurityGroupExtension = neutronSecurityGroupExtension; this.novaSecurityGroupExtension = novaSecurityGroupExtension; }

Target:
SecurityGroupExtensionProvider(NeutronSecurityGroupExtension neutronSecurityGroupExtension, NovaSecurityGroupExtension novaSecurityGroupExtension) { this.neutronSecurityGroupExtension = neutronSecurityGroupExtension; this.novaSecurityGroupExtension = novaSecurityGroupExtension; }
Source:
public void returnsBlockingTimeoutWithConnectorWithIdleTimeouts() throws IOException { assertThat(BlockingTimeouts.getBlockingTimeout(OBJECT_MAPPER, getConfigurationFromResource( "lock/one-specified-timeout.yml"))) .isEqualTo(BlockingTimeouts.scaleForErrorMargin(86400 * MILLIS_PER_SECOND)); }

Target:
public void returnsBlockingTimeoutWithConnectorWithIdleTimeouts() throws IOException { assertThat(BlockingTimeouts.getBlockingTimeout(OBJECT_MAPPER, getConfigurationFromResource( "lock/one-specified-timeout.yml"))) .isEqualTo(BlockingTimeouts.scaleForErrorMargin(SECONDS_IN_ONE_DAY * MILLIS_PER_SECOND, ERROR_MARGIN)); }
Source:
public ExecutorSelector(List<String> filterList, Map<String,Integer> comparatorList) { super(null == filterList || filterList.size() == 0 ? null : new ExecutorFilter(filterList), null == comparatorList || comparatorList.size() == 0 ? null : new ExecutorComparator(comparatorList)); }

Target:
public ExecutorSelector(List<String> filterList, Map<String,Integer> comparatorList) { super(null == filterList || filterList.isEmpty() ? null : new ExecutorFilter(filterList), null == comparatorList || comparatorList.isEmpty() ? null : new ExecutorComparator(comparatorList)); }
Source:
public static Iterable<Object[]> constructorFeeder() { return ImmutableList.of( new Object[]{LockGranularity.TIME_CHUNK, false}, new Object[]{LockGranularity.TIME_CHUNK, true}, new Object[]{LockGranularity.SEGMENT, false}, new Object[]{LockGranularity.SEGMENT, true} ); }

Target:
public static Iterable<Object[]> constructorFeeder() { return ImmutableList.of( new Object[]{LockGranularity.TIME_CHUNK, false}, new Object[]{LockGranularity.TIME_CHUNK, true}, new Object[]{LockGranularity.SEGMENT, true} ); }
Source:
public void nodesRemoved(Collection<DiscoveryDruidNode> nodesDisappeared) { synchronized (lock) { List<DiscoveryDruidNode> nodesRemoved = new ArrayList<>(); for (DiscoveryDruidNode node : nodesDisappeared) { DiscoveryDruidNode prev = nodes.remove(node.getDruidNode().getHostAndPortToUse()); if (prev != null) { nodesRemoved.add(node); } else { log.warn("Node[%s] disappeared but was unknown for service listener [%s].", node, service); } } if (!nodesRemoved.isEmpty()) { Collection<DiscoveryDruidNode> unmodifiableNodesRemoved = Collections.unmodifiableCollection(nodesRemoved); for (Listener listener : listeners) { try { listener.nodesRemoved(unmodifiableNodesRemoved); } catch (Exception ex) { log.error(ex, "Listener[%s].nodesRemoved(%s) threw exception. Ignored.", listener, nodesRemoved); } } } } }

Target:
public void nodesRemoved(Collection<DiscoveryDruidNode> nodesDisappeared) { synchronized (lock) { List<DiscoveryDruidNode> nodesRemoved = new ArrayList<>(); for (DiscoveryDruidNode node : nodesDisappeared) { DiscoveryDruidNode prev = nodes.remove(node.getDruidNode().getHostAndPortToUse()); if (prev != null) { nodesRemoved.add(node); } else { log.warn("Node[%s] disappeared but was unknown for service listener [%s].", node, service); } } if (nodesRemoved.isEmpty()) { return; } Collection<DiscoveryDruidNode> unmodifiableNodesRemoved = Collections.unmodifiableCollection(nodesRemoved); for (Listener listener : listeners) { try { listener.nodesRemoved(unmodifiableNodesRemoved); } catch (Exception ex) { log.error(ex, "Listener[%s].nodesRemoved(%s) threw exception. Ignored.", listener, nodesRemoved); } } } }
Source:
public String toString() { return "KafkaTuningConfig{" + "maxRowsInMemory=" + maxRowsInMemory + ", maxRowsPerSegment=" + maxRowsPerSegment + ",maxBytesInMemory=" + maxBytesInMemory + ", intermediatePersistPeriod=" + intermediatePersistPeriod + ", basePersistDirectory=" + basePersistDirectory + ", maxPendingPersists=" + maxPendingPersists + ", indexSpec=" + indexSpec + ", reportParseExceptions=" + reportParseExceptions + ", handoffConditionTimeout=" + handoffConditionTimeout + ", resetOffsetAutomatically=" + resetOffsetAutomatically + ", segmentWriteOutMediumFactory=" + segmentWriteOutMediumFactory + ", intermediateHandoffPeriod=" + intermediateHandoffPeriod + '}'; }

Target:
public String toString() { return "KafkaTuningConfig{" + "maxRowsInMemory=" + maxRowsInMemory + ", maxRowsPerSegment=" + maxRowsPerSegment + ", maxBytesInMemory=" + maxBytesInMemory + ", intermediatePersistPeriod=" + intermediatePersistPeriod + ", basePersistDirectory=" + basePersistDirectory + ", maxPendingPersists=" + maxPendingPersists + ", indexSpec=" + indexSpec + ", reportParseExceptions=" + reportParseExceptions + ", handoffConditionTimeout=" + handoffConditionTimeout + ", resetOffsetAutomatically=" + resetOffsetAutomatically + ", segmentWriteOutMediumFactory=" + segmentWriteOutMediumFactory + ", intermediateHandoffPeriod=" + intermediateHandoffPeriod + ", logParseExceptions=" + logParseExceptions + ", maxParseExceptions=" + maxParseExceptions + ", maxSavedParseExceptions=" + maxSavedParseExceptions + '}'; }
Source:
public static String listUsers(final IEssentials ess, final List<User> users, final String seperator) { final StringBuilder groupString = new StringBuilder(); Collections.sort(users); boolean needComma = false; for (User user : users) { if (needComma) { groupString.append(seperator); } needComma = true; if (user.isAfk()) { groupString.append(tl("listAfkTag")); } if (user.isHidden()) { groupString.append(tl("listHiddenTag")); } user.setDisplayNick(); if (ess.getSettings().realNamesOnList() && !ChatColor.stripColor(user.getDisplayName()).equals(user.getName())) { groupString.append(user.getDisplayName() + " (" + user.getName() + ")"); } else { groupString.append(user.getDisplayName()); } groupString.append("\u00a7f"); } return groupString.toString(); }

Target:
public static String listUsers(final IEssentials ess, final List<User> users, final String seperator) { final StringBuilder groupString = new StringBuilder(); Collections.sort(users); boolean needComma = false; for (User user : users) { if (needComma) { groupString.append(seperator); } needComma = true; if (user.isAfk()) { groupString.append(tl("listAfkTag")); } if (user.isHidden()) { groupString.append(tl("listHiddenTag")); } user.setDisplayNick(); groupString.append(user.getDisplayName()); if (ess.getSettings().realNamesOnList() && !ChatColor.stripColor(user.getDisplayName()).equals(user.getName())) { groupString.append(" (").append(user.getName()).append(")"); } groupString.append("\u00a7f"); } return groupString.toString(); }
Source:
public void terminate() { initializer.terminate("ws-master"); }

Target:
public void terminate() { initializer.terminate("workspace/output"); }
Source:
public void shouldSequenceEmpty() { final Seq<Lazy<Integer>> testee = Stream.empty(); final Lazy<Seq<Integer>> sequence = Lazy.sequence(testee); assertThat(sequence.get()).isEqualTo(Stream.empty()); }

Target:
public void shouldSequenceEmpty() { final List<Lazy<Integer>> testee = List.empty(); final Lazy<Seq<Integer>> sequence = Lazy.sequence(testee); assertThat(sequence.get()).isEqualTo(Vector.empty()); }
Source:
public static void initSessionAndResetTestSchema() throws Exception { String testFolder = CassPersistenceTest.class.getResource("/").getPath(); System.setProperty(JBOSS_DATA_DIR, testFolder); externalCassandra = (null != System.getProperty(EXTERNAL_CASSANDRA)); if (!externalCassandra) { System.out.print("Starting embedded Cassandra for unit testing..."); EmbeddedCassandra.start(); } else { System.out.print("Using External Cassandra for unit testing..."); } keyspace = AlertProperties.getProperty("hawkular-alerts.cassandra-keyspace", "hawkular_alerts_test"); Session session = CassCluster.getSession(true); definitionsService = StandaloneAlerts.getDefinitionsService(); alertsService = StandaloneAlerts.getAlertsService(); actionsService = StandaloneAlerts.getActionsService(); }

Target:
public static void initSessionAndResetTestSchema() throws Exception { String testFolder = CassPersistenceTest.class.getResource("/").getPath(); System.setProperty(JBOSS_DATA_DIR, testFolder); externalCassandra = (null != System.getProperty(EXTERNAL_CASSANDRA)); if (!externalCassandra) { System.out.print("Starting embedded Cassandra for unit testing..."); EmbeddedCassandra.start(); } else { System.out.print("Using External Cassandra for unit testing..."); } keyspace = "hawkular_alerts_test"; System.setProperty("hawkular-alerts.cassandra-keyspace", keyspace); CassCluster.getSession(true); definitionsService = StandaloneAlerts.getDefinitionsService(); alertsService = StandaloneAlerts.getAlertsService(); actionsService = StandaloneAlerts.getActionsService(); }
Source:
public synchronized long getTimestamp(final int offset) { HistogramScaledData scaledData = fScaledData; if (scaledData != null) { return fScaledData.fFirstBucketTime + Math.round(scaledData.fBucketDuration * offset); } return 0; }

Target:
public synchronized long getTimestamp(final int offset) { HistogramScaledData scaledData = fScaledData; if (scaledData != null) { return scaledData.fFirstBucketTime + Math.round(scaledData.fBucketDuration * offset); } return 0; }
Source:
public void write(Object object) throws IOException { result.totalCount++; commitCount++; if (null == factory) { factory = (IndexedRecordConverter<Object, ? extends IndexedRecord>) SnowflakeAvroRegistry.get() .createIndexedRecordConverter(object.getClass()); } IndexedRecord input = factory.convertToAvro(object); try { if (usePreparedStatement) { PreparedStatement pstmt = (PreparedStatement) statement; SnowflakePreparedStatementUtils.fillPreparedStatement(pstmt, rowProperties.preparedStatementTable); pstmt.execute(); rs = pstmt.getResultSet(); pstmt.clearParameters(); } else { rs = statement.executeQuery(rowProperties.query.getValue()); } handleSuccess(input); } catch (SQLException e) { if (dieOnError) { throw new IOException(e); } LOGGER.error(I18N_MESSAGES.getMessage("error.queryExecution"), e); handleReject(input, e); } try { if (rowProperties.connection.getReferencedComponentId() == null && commitCount == commitEvery) { connection.commit(); commitCount = 0; } } catch (SQLException e) { if (dieOnError) { throw new IOException(e); } LOGGER.error(I18N_MESSAGES.getMessage("error.performCommit"), e); } }

Target:
public void write(Object object) throws IOException { commitCount++; IndexedRecord input = (IndexedRecord) object; try { if (rowProperties.usePreparedStatement()) { PreparedStatement pstmt = (PreparedStatement) statement; SnowflakePreparedStatementUtils.fillPreparedStatement(pstmt, rowProperties.preparedStatementTable); if (rowProperties.propagateQueryResultSet()) { pstmt.execute(); rs = pstmt.getResultSet(); } else { pstmt.addBatch(); } pstmt.clearParameters(); } else { if (rowProperties.propagateQueryResultSet()) { rs = statement.executeQuery(sink.getQuery()); } else { statement.addBatch(sink.getQuery()); } } handleSuccess(input); } catch (SQLException e) { if (rowProperties.dieOnError.getValue()) { throw new IOException(e); } LOGGER.error(I18N_MESSAGES.getMessage("error.queryExecution"), e); handleReject(input, e); } try { if (rowProperties.connection.getReferencedComponentId() == null && commitCount == rowProperties.commitCount.getValue()) { statement.executeBatch(); connection.commit(); commitCount = 0; } } catch (SQLException e) { if (rowProperties.dieOnError.getValue()) { throw new IOException(e); } LOGGER.error(I18N_MESSAGES.getMessage("error.performCommit"), e); } }
Source:
public void onApproachGround(PlayerMoveEvent e) { Player player = e.getPlayer(); ItemStack helmet = e.getPlayer().getInventory().getChestplate(); if (!SlimefunUtils.isItemSimilar(helmet, SlimefunItems.BEE_WINGS, true) && !Slimefun.hasUnlocked(e.getPlayer(), helmet, true)) return; if (!player.isGliding()) return; if (getDistanceToGround(player) == 0) return; if (getDistanceToGround(player) <= 6) player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 30, 0)); }

Target:
public void onApproachGround(PlayerMoveEvent e) { Player player = e.getPlayer(); if (e.getTo().getBlockY() == e.getFrom().getBlockY()) { return; } if (!player.isGliding()) return; if (player.isOnGround()) return; if (player.hasPotionEffect(PotionEffectType.SLOW_FALLING)) return; ItemStack chestplate = player.getInventory().getChestplate(); if (!SlimefunUtils.isItemSimilar(chestplate, SlimefunItems.BEE_WINGS, true) || !Slimefun.hasUnlocked(player, chestplate, true)) { return; } Location loc = player.getLocation(); int distanceToHighestBlock = (loc.getBlockY() - player.getWorld().getHighestBlockYAt(loc, HeightMap.WORLD_SURFACE)); if (distanceToHighestBlock < 0) { int distanceToGround = getDistanceToGround(loc.getBlock(), 6); if (distanceToGround < 1) return; player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 40, 0)); return; } else if (distanceToHighestBlock <= 6) { player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 40, 0)); } }
Source:
public synchronized Collection<MetaAnnotation> getAnnotations() { final Annotation[] array; if (_annotationsCache != null) { array = _annotationsCache; } else { array = _annotationsCache = method.getAnnotations(); } return Arrays.stream(array).map(JavaReflectionAnnotation::new).collect(Collectors.toList()); }

Target:
public Collection<MetaAnnotation> getAnnotations() { return Arrays.stream(method.getAnnotations()).map(JavaReflectionAnnotation::new).collect(toList()); }