auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
BufferAndBacklog pollBuffer() { synchronized (buffers) { if (isBlockedByCheckpoint) { return null; } Buffer buffer = null; if (buffers.isEmpty()) { flushRequested = false; } while (!buffers.isEmpty()) { BufferConsumerWithPartialRecordLength bufferConsumerWithPartialRecordLength = buffers.peek(); BufferConsumer bufferConsumer = requireNonNull(bufferConsumerWithPartialRecordLength).getBufferConsumer(); buffer = buildSliceBuffer(bufferConsumerWithPartialRecordLength); checkState(bufferConsumer.isFinished() || buffers.size() == 1, "When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue."); if (buffers.size() == 1) { flushRequested = false; } if (bufferConsumer.isFinished()) { requireNonNull(buffers.poll()).getBufferConsumer().close(); decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer()); } if (buffer.readableBytes() > 0) { break; } buffer.recycleBuffer(); buffer = null; if (!bufferConsumer.isFinished()) { break; } } if (buffer == null) { return null; } if (buffer.getDataType().isBlockingUpstream()) { isBlockedByCheckpoint = true; } updateStatistics(buffer); return new BufferAndBacklog( buffer, getBuffersInBacklog(), isDataAvailableUnsafe() ? getNextBufferTypeUnsafe() : Buffer.DataType.NONE, sequenceNumber++); } }

Target:
BufferAndBacklog pollBuffer() { synchronized (buffers) { if (isBlockedByCheckpoint) { return null; } Buffer buffer = null; if (buffers.isEmpty()) { flushRequested = false; } while (!buffers.isEmpty()) { BufferConsumerWithPartialRecordLength bufferConsumerWithPartialRecordLength = buffers.peek(); BufferConsumer bufferConsumer = bufferConsumerWithPartialRecordLength.getBufferConsumer(); buffer = buildSliceBuffer(bufferConsumerWithPartialRecordLength); checkState(bufferConsumer.isFinished() || buffers.size() == 1, "When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue."); if (buffers.size() == 1) { flushRequested = false; } if (bufferConsumer.isFinished()) { requireNonNull(buffers.poll()).getBufferConsumer().close(); decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer()); } if (buffer.readableBytes() > 0) { break; } buffer.recycleBuffer(); buffer = null; if (!bufferConsumer.isFinished()) { break; } } if (buffer == null) { return null; } if (buffer.getDataType().isBlockingUpstream()) { isBlockedByCheckpoint = true; } updateStatistics(buffer); return new BufferAndBacklog( buffer, getBuffersInBacklog(), isDataAvailableUnsafe() ? getNextBufferTypeUnsafe() : Buffer.DataType.NONE, sequenceNumber++); } }
Source:
private boolean setKeyMaterial(ReferenceCountedOpenSslEngine engine, String alias) throws SSLException { OpenSslKeyMaterial keyMaterial = null; try { keyMaterial = provider.chooseKeyMaterial(engine.alloc, alias); if (keyMaterial != null) { return engine.setKeyMaterial(keyMaterial); } return true; } catch (SSLException e) { throw e; } catch (Exception e) { throw new SSLException(e); } finally { if (keyMaterial != null) { keyMaterial.release(); } } }

Target:
private boolean setKeyMaterial(ReferenceCountedOpenSslEngine engine, String alias) throws SSLException { OpenSslKeyMaterial keyMaterial = null; try { keyMaterial = provider.chooseKeyMaterial(engine.alloc, alias); return keyMaterial == null || engine.setKeyMaterial(keyMaterial); } catch (SSLException e) { throw e; } catch (Exception e) { throw new SSLException(e); } finally { if (keyMaterial != null) { keyMaterial.release(); } } }
Source:
protected Expression createProducerExpression() { final Class<?> type; switch (configuration.getOperation()) { case NONE: type = configuration.getEntityType(); break; case EXECUTE: type = Query.class; break; case FETCH: type = ResultQuery.class; break; default: type = null; } boolean isSQLQuery = !ObjectHelper.isEmpty(configuration.getQuery()); if (type == null || isSQLQuery) { return new Expression() { @Override public <T> T evaluate(Exchange exchange, Class<T> type) { return exchange.getMessage().getBody(type); }; }; } else { return new Expression() { public Object evaluate(Exchange exchange, Class asType) { Object answer = exchange.getIn().getBody(type); if (answer == null) { Object defaultValue = exchange.getIn().getBody(); if (defaultValue != null) { throw RuntimeCamelException.wrapRuntimeCamelException(new NoTypeConversionAvailableException(defaultValue, type)); } answer = exchange.getContext().getInjector().newInstance(type); } return answer; } }; } }

Target:
protected Expression createProducerExpression() { final Class<?> type; switch (configuration.getOperation()) { case NONE: type = configuration.getEntityType(); break; case EXECUTE: type = Query.class; break; case FETCH: type = ResultQuery.class; break; default: throw new UnsupportedOperationException("Operation: " + configuration.getOperation()); } return new Expression() { public Object evaluate(Exchange exchange, Class asType) { Object answer = exchange.getIn().getBody(type); if (answer == null) { Object defaultValue = exchange.getIn().getBody(); if (defaultValue != null) { throw RuntimeCamelException.wrapRuntimeCamelException(new NoTypeConversionAvailableException(defaultValue, type)); } answer = exchange.getContext().getInjector().newInstance(type); } return answer; } }; }
Source:
private byte[] addToCache(final String sequenceName, final byte[] bases) { for (int i = 0; i < bases.length; i++) { bases[i] = StringUtil.toUpperCase(bases[i]); } cacheW.put(sequenceName, new WeakReference<byte[]>(bases)); return bases; }

Target:
private byte[] addToCache(final String sequenceName, final byte[] bases) { cacheW.put(sequenceName, new WeakReference<byte[]>(bases)); return bases; }
Source:
public double parRate(PricingEnvironment env, SwapProduct product) { ExpandedSwap swap = product.expand(); List<ExpandedSwapLeg> legs = swap.getLegs(); ExpandedSwapLeg fixedLeg = null; int fixedLegIndex = 0; for (int i = 0; i < legs.size(); i++) { if (legs.get(i).getType() == SwapLegType.FIXED) { fixedLeg = legs.get(i); fixedLegIndex = i; break; } } ArgChecker.notNull(fixedLeg, "no fixed leg found"); @SuppressWarnings("null") Currency ccyFixedLeg = fixedLeg.getCurrency(); ToDoubleBiFunction<PricingEnvironment, PaymentEvent> eventFn = paymentEventPricer::presentValue; double otherLegsConvertedPv = 0.0; for (int i = 0; i < legs.size(); i++) { if (i != fixedLegIndex) { double pvLocal = legValue(env, legs.get(i), paymentPeriodPricer::presentValue, paymentEventPricer::presentValue); otherLegsConvertedPv += (pvLocal * env.fxRate(legs.get(i).getCurrency(), ccyFixedLeg)); } } double fixedLegEventsPv = fixedLeg.getPaymentEvents().stream() .filter(p -> !p.getPaymentDate().isBefore(env.getValuationDate())) .mapToDouble(e -> eventFn.applyAsDouble(env, e)) .sum(); double pvbpFixedLeg = pvbp(env, fixedLeg); return -(otherLegsConvertedPv + fixedLegEventsPv) / pvbpFixedLeg; }

Target:
public double parRate(PricingEnvironment env, SwapProduct product) { ExpandedSwap swap = product.expand(); List<ExpandedSwapLeg> legs = swap.getLegs(); ExpandedSwapLeg fixedLeg = null; for(ExpandedSwapLeg leg: legs) { if (leg.getType() == SwapLegType.FIXED) { fixedLeg = leg; break; } } ArgChecker.notNull(fixedLeg, "no fixed leg found"); @SuppressWarnings("null") Currency ccyFixedLeg = fixedLeg.getCurrency(); double otherLegsConvertedPv = 0.0; for (ExpandedSwapLeg leg: legs) { if (leg != fixedLeg) { double pvLocal = legValue(env, leg, paymentPeriodPricer::presentValue, paymentEventPricer::presentValue); otherLegsConvertedPv += (pvLocal * env.fxRate(leg.getCurrency(), ccyFixedLeg)); } } double fixedLegEventsPv = fixedLeg.getPaymentEvents().stream() .filter(p -> !p.getPaymentDate().isBefore(env.getValuationDate())) .mapToDouble(e -> paymentEventPricer.presentValue(env, e)) .sum(); double pvbpFixedLeg = pvbp(env, fixedLeg); return -(otherLegsConvertedPv + fixedLegEventsPv) / pvbpFixedLeg; }
Source:
public Response getAllRefunds(UriInfo uriInfo, Long accountId, Long pageNumber, Long displaySize) { List<Pair<String, Long>> queryParams = ImmutableList.of( Pair.of("page", pageNumber), Pair.of("display_size", displaySize)); return validateQueryParams(queryParams) .map(ResponseUtil::badRequestResponse) .orElseGet(() -> { ChargeSearchParams searchParams = new ChargeSearchParams() .withGatewayAccountId(accountId) .withDisplaySize(displaySize != null ? displaySize : 0) .withPage(pageNumber != null ? pageNumber : 1); return search(searchParams, uriInfo); }); }

Target:
public Response getAllRefunds(UriInfo uriInfo, Long accountId, Long pageNumber, Long displaySize) { List<Pair<String, Long>> queryParams = ImmutableList.of( Pair.of("page", pageNumber), Pair.of("display_size", displaySize)); refundSearchStrategy = new RefundSearchStrategy(refundDao); List<String> errors = validateQueryParams(queryParams); if (errors.isEmpty()) { SearchParams searchParams = new SearchParams() .withGatewayAccountId(accountId) .withDisplaySize(calculateDisplaySize(displaySize)) .withPage(pageNumber != null ? pageNumber : 1); return refundSearchStrategy.search(searchParams, uriInfo); } else { return badRequestResponse(errors); } }
Source:
public Deallocator allocate(final PublisherPackSlice slice) { if (loadedSlices.contains(slice)) throw new IllegalStateException("Slice " + slice + " already allocated"); size.addAndGet(slice.getSize()); for (PublisherPackSlice s : loadedSlices) { if (size.get() <= capacity) break; try { s.store(); } catch (IOException e) { e.printStackTrace(); } } loadedSlices.add(slice); return new Deallocator() { public void deallocate() { if (!loadedSlices.remove(slice)) throw new IllegalStateException("Slice " + slice + " already deallocated"); size.addAndGet(-slice.getSize()); } }; }

Target:
public Deallocator allocate(final PublisherPackSlice slice) throws PublisherException { if (loadedSlices.contains(slice)) throw new IllegalStateException("Slice " + slice + " already allocated"); size.addAndGet(slice.getSize()); synchronized (this) { for (PublisherPackSlice s : loadedSlices) { if (size.get() <= capacity) break; try { s.store(); } catch (IOException e) { throw new PublisherException( "Error deallocating pack slice " + slice, e); } } } loadedSlices.add(slice); return new Deallocator() { public void deallocate() throws PublisherException { if (!loadedSlices.remove(slice)) throw new PublisherException("Slice " + slice + " already deallocated"); size.addAndGet(-slice.getSize()); } }; }
Source:
public boolean match(Event value) { if (null == value) { return false; } if (null == expression || expression.isEmpty()) { return true; } String[] expressions = expression.split(","); for (int i = 0; i < expressions.length; i++) { if (!processExpression(expressions[i], value)) { return false; } } return true; }

Target:
public boolean match(Event value) { if (null == value) { return false; } if (null == expression || expression.isEmpty()) { return true; } List<String> expressions = new ArrayList<>(); int j = 0; for (int i = 0; i < expression.length(); i++) { if (expression.charAt(i) == ',' && (i == 0 || (i > 0 && expression.charAt(i - 1) != '\\'))) { expressions.add(cleanComma.matcher(expression.substring(j, i).trim()).replaceAll(",")); j = i + 1; } } expressions.add(cleanComma.matcher(expression.substring(j).trim()).replaceAll(",")); for (String expression : expressions) { if (!processExpression(expression, value)) { return false; } } return true; }
Source:
private boolean handleHttpProxyPreferenceChange(Preference preference, String newValue) { if (newValue.equals("")) { preference.setSummary(getString(R.string.do_not_use_proxy) + " " + getString(R.string.generic_example) + ": " + getString(R.string.http_proxy_address_example)); return true; } else if (newValue.matches("^http://" + "(((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|" + "((([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])))" + ":(\\d{1,5})$")) { preference.setSummary(getString(R.string.use_proxy) + " " + newValue); return true; } else { Toast.makeText(getActivity(), R.string.toast_invalid_http_proxy_address, Toast.LENGTH_SHORT) .show(); return false; } }

Target:
private boolean handleHttpProxyPreferenceChange(Preference preference, String newValue) { if (newValue.equals("")) { preference.setSummary(getString(R.string.do_not_use_proxy) + " " + getString(R.string.generic_example) + ": " + getString(R.string.http_proxy_address_example)); return true; } else if (newValue.matches("^http://.*:\\d{1,5}$")) { preference.setSummary(getString(R.string.use_proxy) + " " + newValue); return true; } else { Toast.makeText(getActivity(), R.string.toast_invalid_http_proxy_address, Toast.LENGTH_SHORT) .show(); return false; } }
Source:
public void initializeSSLSocketFactory() throws Exception { try { SSLFactory sslFactory = new SSLFactory(sslConfig); SSLContext sslContext = sslFactory.getSSLContext(); this.sslSocketFactory = sslContext.getSocketFactory(); this.sslSocketFactoryInitializationCount.inc(); } catch (Exception e) { this.sslSocketFactoryInitializationErrorCount.inc(); logger.error("SSLSocketFactory Initialization Error ", e); throw e; } }

Target:
private void initializeSSLSocketFactory() throws Exception { try { SSLFactory sslFactory = new SSLFactory(sslConfig); SSLContext sslContext = sslFactory.getSSLContext(); this.sslSocketFactory = sslContext.getSocketFactory(); this.sslSocketFactoryInitializationCount.inc(); } catch (Exception e) { this.sslSocketFactoryInitializationErrorCount.inc(); logger.error("SSLSocketFactory Initialization Error ", e); throw e; } }
Source:
public Map<String, String> buildVocabularyVersionMap() { final List<VocabularyV5> allVersions = vocabularyRepository.findAll(); return allVersions.stream() .collect(HashMap::new, (m, v) -> m.put(v.getId(), v.getVersion()), HashMap::putAll); }

Target:
private Map<String, String> buildVocabularyVersionMap() { final List<VocabularyV5> allVersions = vocabularyRepository.findAll(); return allVersions.stream() .collect(HashMap::new, (m, v) -> m.put(v.getId(), v.getVersion()), HashMap::putAll); }
Source:
private static BagitFileValues parseValues(final Path bagitFile) throws UnparsableVersionException, IOException, InvalidBagMetadataException{ logger.debug("Reading file", bagitFile); final List<SimpleImmutableEntry<String, String>> pairs = KeyValueReader.readKeyValuesFromFile(bagitFile, ":", StandardCharsets.UTF_8); final BagitFileValues values = new BagitFileValues(); String version = ""; Charset encoding = StandardCharsets.UTF_8; for(final SimpleImmutableEntry<String, String> pair : pairs){ if("BagIt-Version".equals(pair.getKey())){ version = pair.getValue(); logger.debug("BagIt-Version is [{}]", version); values.version = parseVersion(version); } if("Tag-File-Character-Encoding".equals(pair.getKey())){ encoding = Charset.forName(pair.getValue()); logger.debug("Tag-File-Character-Encoding is [{}]", encoding); values.encoding = encoding; } if("Payload-Byte-Count".equals(pair.getKey())){ logger.debug("Payload-Byte-Count is [{}]", pair.getKey()); values.payloadByteCount = Long.valueOf(pair.getValue()); } if("Payload-File-Count".equals(pair.getKey())){ logger.debug("Payload-File-Count is [{}]", pair.getKey()); values.payloadFileCount = Long.valueOf(pair.getValue()); } } return values; }

Target:
public static BagitFileValues parseValues(final Path bagitFile) throws UnparsableVersionException, IOException, InvalidBagMetadataException{ logger.debug("Reading file", bagitFile); final List<SimpleImmutableEntry<String, String>> pairs = KeyValueReader.readKeyValuesFromFile(bagitFile, ":", StandardCharsets.UTF_8); Version version = null; Charset encoding = StandardCharsets.UTF_8; Long payloadByteCount = null; Long payloadFileCount = null; for(final SimpleImmutableEntry<String, String> pair : pairs){ if("BagIt-Version".equals(pair.getKey())){ version = parseVersion(pair.getValue()); } if("Tag-File-Character-Encoding".equals(pair.getKey())){ encoding = Charset.forName(pair.getValue()); } if("Payload-Byte-Count".equals(pair.getKey())){ payloadByteCount = Long.valueOf(pair.getValue()); } if("Payload-File-Count".equals(pair.getKey())){ payloadFileCount = Long.valueOf(pair.getValue()); } logger.debug("[{}] is [{}]", pair.getKey(), pair.getValue()); } return new BagitFileValues(version, encoding, payloadByteCount, payloadFileCount); }
Source:
public void testTaskCreate() { AnnotationConfigApplicationContext createContext = new AnnotationConfigApplicationContext(); createContext.register(TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class); final Appender mockAppender = TestVerifierUtils.getMockAppender(); createContext.refresh(); this.listener = createContext.getBean(TaskLifecycleListener.class); TestVerifierUtils.verifyLogEntryExists(mockAppender, "Creating: TaskExecution{executionId='" + listener.getTaskExecution().getExecutionId()); assertEquals("Create should report that exit code is zero", 0, listener.getTaskExecution().getExitCode()); }

Target:
public void testTaskCreate() { final Appender mockAppender = TestVerifierUtils.getMockAppender(); context.refresh(); this.listener = context.getBean(TaskLifecycleListener.class); TestVerifierUtils.verifyLogEntryExists(mockAppender, "Creating: TaskExecution{executionId='" + listener.getTaskExecution().getExecutionId()); assertEquals("Create should report that exit code is zero", 0, listener.getTaskExecution().getExitCode()); }
Source:
public MantaConnectionFactory(final ConfigContext config, final KeyPair keyPair, final ThreadLocalSigner signer, final MantaConnectionFactoryConfigurator connectionFactoryConfigurator) { Validate.notNull(config, "Configuration context must not be null"); this.config = config; if (connectionFactoryConfigurator != null) { this.connectionManager = connectionFactoryConfigurator.getConnectionManager(); this.httpClientBuilder = connectionFactoryConfigurator.getHttpClientBuilder(); this.connectionManagerShared = true; } else { this.connectionManager = buildConnectionManager(); this.httpClientBuilder = createStandardBuilder(); this.connectionManagerShared = false; } configureHttpClientBuilderDefaults(keyPair, signer); }

Target:
public MantaConnectionFactory(final ConfigContext config, final KeyPair keyPair, final ThreadLocalSigner signer, final MantaConnectionFactoryConfigurator connectionFactoryConfigurator) { Validate.notNull(config, "Configuration context must not be null"); this.config = config; if (connectionFactoryConfigurator != null) { this.connectionManager = null; this.httpClientBuilder = connectionFactoryConfigurator.getHttpClientBuilder(); } else { this.connectionManager = buildConnectionManager(); this.httpClientBuilder = createStandardBuilder(); } configureHttpClientBuilderDefaults(keyPair, signer); }
Source:
public void bufferExactFailingSupplier() { Scheduler.Worker w = new TestScheduler().createWorker(); TestObserver<List<Integer>> observer = new TestObserver<List<Integer>>(); BufferExactBoundedObserver<Integer, List<Integer>> buf = new BufferExactBoundedObserver<Integer, List<Integer>>(observer, ArrayListSupplier.<Integer>asCallable(), 100, TimeUnit.MILLISECONDS, 10, false, w); buf.onError(new Throwable()); buf.onComplete(); }

Target:
public void bufferExactFailingSupplier() { Observable.empty() .buffer(1, TimeUnit.SECONDS, Schedulers.computation(), 10, new Callable<List<Object>>() { @Override public List<Object> call() throws Exception { throw new TestException(); } }, false) .test() .awaitDone(1, TimeUnit.SECONDS) .assertFailure(TestException.class) ; }
Source:
private String generateSequenceId() { if (!Sirius.isFrameworkEnabled(Sequences.FRAMEWORK_SEQUENCES)) { throw Exceptions.handle() .to(Mongo.LOG) .withSystemErrorMessage( "Can not generate sequential id for entity of type %s, as the framework %s is not active!", getTypeName(), Sequences.FRAMEWORK_SEQUENCES) .handle(); } return String.valueOf(sequences.generateId(getTypeName())); }

Target:
private String generateSequenceId() { if (sequences == null) { throw Exceptions.handle() .to(Mongo.LOG) .withSystemErrorMessage( "Can not generate sequential id for entity of type %s, as the framework %s is not active!", getTypeName(), Sequences.FRAMEWORK_SEQUENCES) .handle(); } return String.valueOf(sequences.generateId(getTypeName())); }
Source:
protected UberallsClient getUberallsClient(Logger logger, String gitUrl, String branch) { if (uberallsClient != null) { return uberallsClient; } return new UberallsClient( getDescriptor().getUberallsURL(), logger, gitUrl, branch ); }

Target:
protected UberallsClient getUberallsClient(Logger logger, String gitUrl, String branch) { if (uberallsClient != null) { return uberallsClient; } setUberallsClient(new UberallsClient( getDescriptor().getUberallsURL(), logger, gitUrl, branch )); return uberallsClient; }
Source:
public static void setup() { topLimitSwitch.send(new BooleanOutput() { public void set(boolean value) { if (value && elevatorSpeed.get() > 0) { elevatorSpeed.set(0.0f); } } }); bottomLimitSwitch.send(new BooleanOutput() { public void set(boolean value) { if (value && elevatorSpeed.get() < 0) { elevatorSpeed.set(0.0f); } } }); raisingInput.send(new BooleanOutput() { public void set(boolean value) { if (value) { elevatorControl.set(value); } } }); loweringInput.send(new BooleanOutput() { public void set(boolean value) { if (value) { elevatorControl.set(!value); } } }); }

Target:
public static void setup() { elevatorSpeed.setWhen(0.0f, EventMixing.filterEvent(topLimitSwitch, true, Igneous.globalPeriodic)); elevatorSpeed.setWhen(0.0f, EventMixing.filterEvent(bottomLimitSwitch, true, Igneous.globalPeriodic)); elevatorControl.setTrueWhen(raisingInput); elevatorControl.setFalseWhen(loweringInput); elevatorSpeed.set(0.0f); }
Source:
ReturnStmpVisitor(IASTFunctionDefinition func) { shouldVisitStatements = true; shouldVisitDeclarations = true; shouldVisitExpressions = true; this.func = func; this.hasret = false; IASTPointerOperator[] ptr = func.getDeclarator().getPointerOperators(); if (ptr.length > 0 && ptr[0] instanceof ICPPASTReferenceOperator) { analizer = new ReturnTypeAnalizer(RET_TYPE.BY_REF); } else if (ptr.length > 0 && ptr[0] instanceof IASTPointer) { analizer = new ReturnTypeAnalizer(RET_TYPE.BY_PTR); } else analizer = null; }

Target:
ReturnStmpVisitor(IASTFunctionDefinition func) { shouldVisitStatements = true; shouldVisitDeclarations = true; shouldVisitExpressions = true; this.func = func; this.hasret = false; IBinding binding = func.getDeclarator().getName().resolveBinding(); if (binding instanceof IFunction) { IType retType = SemanticUtil.getNestedType(((IFunction) binding).getType().getReturnType(), SemanticUtil.TDEF); if (retType instanceof ICPPReferenceType) { analyzer = new ReturnTypeAnalyzer(RetType.BY_REF); } else if (retType instanceof IPointerType) { analyzer = new ReturnTypeAnalyzer(RetType.BY_PTR); } else analyzer = null; } else analyzer = null; }
Source:
HardDeleteThread() { this.throttler = new Throttler(config.storeHardDeleteBytesPerSec, throttlerCheckIntervalMs, true, SystemTime.getInstance()); }

Target:
HardDeleteThread() { this.throttler = new Throttler(config.storeHardDeleteBytesPerSec, throttlerCheckIntervalMs, true, time); }
Source:
public void emitTuples() { if (windowId > lastCompletedWId) { if (pendingMessage != null) { super.emitTuples(); } else { processMessage(pendingMessage); pendingMessage = null; } } }

Target:
public void emitTuples() { if (windowId > lastCompletedWId) { if (pendingMessage == null) { super.emitTuples(); } else { processMessage(pendingMessage); pendingMessage = null; } } }
Source:
private void restartPythonProcess() { PythonInterpreter python = getPythonInterpreter(); logger.info("-----------> " + python); python.close(); python.open(); }

Target:
private void restartPythonProcess() { PythonInterpreter python = getPythonInterpreter(); python.close(); python.open(); }
Source:
public SpinExecutorService(int maxTasks) { tasks = PlatformDependent.newFixedMpscQueue(maxTasks); executorThread = new Thread(new Runnable() { @Override public void run() { final Queue<Runnable> tasks = SpinExecutorService.this.tasks; while (true) { final Runnable task = tasks.poll(); if (task != null) { if (task == POISON_PILL) { return; } else { task.run(); } } } } }); executorThread.start(); }

Target:
public SpinExecutorService(int maxTasks) { tasks = PlatformDependent.newFixedMpscQueue(maxTasks); executorThread = new Thread(new Runnable() { @Override public void run() { final Queue<Runnable> tasks = SpinExecutorService.this.tasks; Runnable task; while ((task = tasks.poll()) != POISON_PILL) { if (task != null) { task.run(); } } } }); executorThread.start(); }
Source:
public ImmutableList<K> keys() { K[] pairs = ((K[]) new Object[this.length]); int[] i = new int[1]; this.forEach(x -> pairs[i[0]++] = x.left()); return ImmutableList.from(pairs); }

Target:
public ImmutableSet<K> keys() { return new ImmutableSet<>(this.map(F.constant(Unit.unit))); }
Source:
EventStore eventStore() { return this.boundedContext() .eventBus() .eventStore(); }

Target:
EventStore eventStore() { return boundedContext() .eventBus() .eventStore(); }
Source:
public String getMessage(NetworkItemModel<?> op1, NetworkItemModel<?> op2) { return appendDetachNetworkSuggestion(getVerb(getNotInSyncNetwork(op2)), op2); }

Target:
public String getMessage(NetworkItemModel<?> op1, NetworkItemModel<?> op2) { return appendDetachNetworkSuggestion(getVerb(op1), op2); }
Source:
public void dispose() { mSimRecords.unregisterForRecordsLoaded(this); mSimCard.unregisterForAbsent(this); this.removeMessages(EVENT_SIM_LOADED); this.removeMessages(EVENT_SIM_ABSENT); mSimRecords = null; mSimCard = null; }

Target:
public void dispose() { mSimRecords.unregisterForRecordsLoaded(this); mSimCard.unregisterForAbsent(this); mCmdIf.unSetOnStkSessionEnd(this); mCmdIf.unSetOnStkProactiveCmd(this); mCmdIf.unSetOnStkEvent(this); mCmdIf.unSetOnStkCallSetUp(this); this.removeCallbacksAndMessages(null); mSimRecords = null; mSimCard = null; }
Source:
Type(String name, Repetition repetition, OriginalType originalType, ID id) { super(); name = checkNotNull(name, "name"); if (name.charAt(0) == '`') { name = name.substring(1, name.length() - 1).replace("``", "`"); } this.repetition = checkNotNull(repetition, "repetition"); this.name = name; this.originalType = originalType; this.id = id; }

Target:
Type(String name, Repetition repetition, OriginalType originalType, ID id) { super(); name = checkNotNull(name, "name"); this.repetition = checkNotNull(repetition, "repetition"); this.name = name; this.originalType = originalType; this.id = id; }
Source:
public static void checkShouldRefreshFeeds(Context context) { long interval = 0; if(UserPreferences.getUpdateInterval() > 0) { interval = UserPreferences.getUpdateInterval(); } else if(UserPreferences.getUpdateTimeOfDay().length > 0){ interval = TimeUnit.DAYS.toMillis(1); } if(interval == 0) { return; } SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE); long lastRefresh = prefs.getLong(PREF_LAST_REFRESH, 0); Log.d(TAG, "last refresh: " + Converter.getDurationStringLocalized(context, System.currentTimeMillis() - lastRefresh) + " ago"); if(lastRefresh <= System.currentTimeMillis() - interval) { DBTasks.refreshAllFeeds(context, null, null); } }

Target:
public static void checkShouldRefreshFeeds(Context context) { long interval = 0; if(UserPreferences.getUpdateInterval() > 0) { interval = UserPreferences.getUpdateInterval(); } else if(UserPreferences.getUpdateTimeOfDay().length > 0){ interval = TimeUnit.DAYS.toMillis(1); } if(interval == 0) { return; } SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE); long lastRefresh = prefs.getLong(PREF_LAST_REFRESH, 0); Log.d(TAG, "last refresh: " + Converter.getDurationStringLocalized(context, System.currentTimeMillis() - lastRefresh) + " ago"); if(lastRefresh <= System.currentTimeMillis() - interval) { DBTasks.refreshAllFeeds(context, null); } }
Source:
private void lookupDatabase() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", config.getNativeClientResource() ); mongoDb = (MongoDatabase) jndiService.locate( config.getNativeClientResource() ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( config.getNativeClientResource() ); } this.jndiService = null; }

Target:
private void lookupDatabase() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", config.getNativeClientResource() ); mongoDb = (MongoDatabase) jndiService.locate( config.getNativeClientResource() ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( config.getNativeClientResource() ); } }
Source:
public ModelAndView editCollectionFormGenerator(HttpServletRequest request, @RequestParam(value="collectionId") Long collectionId) { CollectedSample collectedSample = collectedSampleRepository.findCollectedSampleById(collectionId); CollectedSampleBackingForm form = new CollectedSampleBackingForm(collectedSample); ModelAndView mv = new ModelAndView("collections/editCollectionForm"); mv.addObject("editCollectionForm", form); mv.addObject("refreshUrl", getUrl(request)); addEditSelectorOptions(mv.getModelMap()); Map<String, Map<String, Object>> formFields = utilController.getFormFieldsForForm("collectedSample"); mv.addObject("collectionFields", formFields); return mv; }

Target:
public ModelAndView editCollectionFormGenerator(HttpServletRequest request, @RequestParam(value="collectionId") Long collectionId) { CollectedSample collectedSample = collectedSampleRepository.findCollectedSampleById(collectionId); CollectedSampleBackingForm form = new CollectedSampleBackingForm(collectedSample); form.getCollectedSampleIntegerProps(); ModelAndView mv = new ModelAndView("collections/editCollectionForm"); mv.addObject("editCollectionForm", form); mv.addObject("refreshUrl", getUrl(request)); addEditSelectorOptions(mv.getModelMap()); Map<String, Map<String, Object>> formFields = utilController.getFormFieldsForForm("collectedSample"); mv.addObject("collectionFields", formFields); return mv; }
Source:
public boolean preProcess(BindContext context) { Consumer consumer = context.getConsumer(); Map<String, Entitlement> entitlements = context.getEntitlementMap(); Map<String, PoolQuantity> poolQuantities = context.getPoolQuantities(); Set<String> stackIds = new HashSet<>(); for (PoolQuantity poolQuantity : poolQuantities.values()) { if (poolQuantity.getPool().isStacked()) { stackIds.add(poolQuantity.getPool().getStackId()); } } ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer); for (Entry<String, Entitlement> entitlementEntry : entitlements.entrySet()) { String poolId = entitlementEntry.getKey(); Entitlement entitlement = entitlementEntry.getValue(); entitlement.setPool(poolQuantities.get(poolId).getPool()); } if (!stackIds.isEmpty() && !ctype.isType(ConsumerTypeEnum.SHARE) && !ctype.isManifest()) { subPoolsForStackIds = poolCurator.getSubPoolForStackIds(consumer, stackIds); if (CollectionUtils.isNotEmpty(subPoolsForStackIds)) { poolManager.updatePoolsFromStackWithoutDeletingStack(consumer, subPoolsForStackIds, entitlements.values()); } } else { subPoolsForStackIds = new ArrayList<>(); } delayedPoolOp.appendDelayedOp( enforcer.postEntitlement(poolManager, consumer, context.getOwner(), entitlements, subPoolsForStackIds, false, poolQuantities)); for (Entitlement entitlement : entitlements.values()) { entitlement.setPool(null); } return true; }

Target:
public boolean preProcess(BindContext context) { Consumer consumer = context.getConsumer(); Map<String, Entitlement> entitlements = context.getEntitlementMap(); Map<String, PoolQuantity> poolQuantities = context.getPoolQuantities(); Set<String> stackIds = new HashSet<>(); for (PoolQuantity poolQuantity : poolQuantities.values()) { if (poolQuantity.getPool().isStacked()) { stackIds.add(poolQuantity.getPool().getStackId()); } } ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer); for (Entry<String, Entitlement> entitlementEntry : entitlements.entrySet()) { String poolId = entitlementEntry.getKey(); Entitlement entitlement = entitlementEntry.getValue(); entitlement.setPool(poolQuantities.get(poolId).getPool()); } if (!stackIds.isEmpty() && !ctype.isType(ConsumerTypeEnum.SHARE) && !ctype.isManifest()) { subPoolsForStackIds = poolCurator.getSubPoolForStackIds(consumer, stackIds); if (CollectionUtils.isNotEmpty(subPoolsForStackIds)) { poolManager.updatePoolsFromStackWithoutDeletingStack(consumer, subPoolsForStackIds, entitlements.values()); } } else { subPoolsForStackIds = new ArrayList<>(); } poolOperationCallback.appendCallback(enforcer.postEntitlement(poolManager, consumer, context.getOwner(), entitlements, subPoolsForStackIds, false, poolQuantities )); for (Entitlement entitlement : entitlements.values()) { entitlement.setPool(null); } return true; }
Source:
protected void emitContent(String content) throws IOException { if (isEmptyContent(content)) { content = prefix + " "; } content = content.replaceAll("(\\r|\\n)+", " "); super.emitContent(content); }

Target:
protected void emitContent(String content) throws IOException { if (Strings.isNullOrEmpty(content)) { content = " "; } content = content.replaceAll("(\\r|\\n)+", " "); super.emitContent(content); }
Source:
public boolean isInQualifier(BitSet bitSet) throws StandardException { if (bitSet == null) return false; InListOperatorNode sourceInList=getSourceInList(); if(sourceInList==null) return false; for (Object o : sourceInList.getLeftOperandList()) { ValueNode lo = (ValueNode) o; if (!(lo instanceof ColumnReference)) return false; ColumnReference colRef = (ColumnReference) lo; int colNum = colRef.getColumnNumber(); if (!bitSet.get(colNum)) return false; } ValueNodeList rightOperandList=sourceInList.getRightOperandList(); for(Object o:rightOperandList){ if(!(o instanceof ConstantNode)) { if (o instanceof ListValueNode) { if (!((ListValueNode)o).allConstantsNodesInList()) return false; } return false; } } return true; }

Target:
public boolean isInQualifier(BitSet bitSet) throws StandardException { if (bitSet == null) return false; InListOperatorNode sourceInList=getSourceInList(); if(sourceInList==null) return false; for (Object o : sourceInList.getLeftOperandList()) { ValueNode lo = (ValueNode) o; if (!(lo instanceof ColumnReference)) return false; ColumnReference colRef = (ColumnReference) lo; int colNum = colRef.getColumnNumber(); if (!bitSet.get(colNum)) return false; } ValueNodeList rightOperandList=sourceInList.getRightOperandList(); for(Object o:rightOperandList){ if(!(o instanceof ConstantNode)) { if (o instanceof ListValueNode) { if (!((ListValueNode)o).allConstantsNodesInList()) return false; } else return false; } } return true; }
Source:
private void relinquishLeadership(HelixManager manager, ControllerManagerHelper controllerHelper) { long start = System.currentTimeMillis(); LOG.info(manager.getInstanceName() + " tries to relinquish leadership for cluster: " + manager .getClusterName()); controllerHelper.stopControllerTimerTasks(); controllerHelper.removeListenersFromController(_controller); manager.getHelixDataAccessor().getBaseDataAccessor().reset(); LOG.info("{} relinquishes leadership for cluster: {}, took: {}", manager.getInstanceName(), manager.getClusterName(), System.currentTimeMillis() - start); }

Target:
private void relinquishLeadership(HelixManager manager, ControllerManagerHelper controllerHelper) { long start = System.currentTimeMillis(); LOG.info(manager.getInstanceName() + " tries to relinquish leadership for cluster: " + manager .getClusterName()); controllerHelper.stopControllerTimerTasks(); controllerHelper.removeListenersFromController(_controller); manager.getHelixDataAccessor().getBaseDataAccessor().reset(); LOG.info("{} relinquishes leadership for cluster: {}, took: {}ms", manager.getInstanceName(), manager.getClusterName(), System.currentTimeMillis() - start); }
Source:
public static void configureTransactionManager(ModelControllerClient mcc, HashMap<String, String> serverProperties) throws Exception { TransactionsJBossASClient client = new TransactionsJBossASClient(mcc); client.setDefaultTransactionTimeout(600); LOG.info("Default transaction timeout set to 600 seconds."); final HashMap<String, String> transactionNodeIdDefault = new HashMap(); transactionNodeIdDefault.put(ServerProperties.PROP_JBOSS_HA_NODE_ID, "1"); String nodeId = buildExpression(ServerProperties.PROP_JBOSS_HA_NODE_ID, transactionNodeIdDefault, true, false, false); client.setTransactionNodeId(nodeId); LOG.info("Set high availability nodeId to " + nodeId); }

Target:
public static void configureTransactionManager(ModelControllerClient mcc, HashMap<String, String> serverProperties) throws Exception { TransactionsJBossASClient client = new TransactionsJBossASClient(mcc); client.setDefaultTransactionTimeout(600); LOG.info("Default transaction timeout set to 600 seconds."); final HashMap<String, String> transactionNodeIdDefault = new HashMap(); transactionNodeIdDefault.put(ServerProperties.PROP_JBOSS_HA_NODE_ID, "1"); String nodeId = buildExpression(ServerProperties.PROP_JBOSS_HA_NODE_ID, transactionNodeIdDefault, true, false, false); client.setTransactionNodeId(nodeId); }
Source:
public void destroy() { if(null != FormEditorContext.getActiveEditorHelper() && FormEditorContext.getActiveEditorHelper().equals(editorHelper)) { FormEditorContext.setActiveEditorHelper(null); } editorFieldLayoutComponents.destroyAll(); }

Target:
public void destroy() { if (Objects.equals(FormEditorContext.getActiveEditorHelper(), editorHelper)) { FormEditorContext.setActiveEditorHelper(null); } editorFieldLayoutComponents.destroyAll(); }
Source:
public boolean add(JobTaskMoveAssignment assignment) { List<JobKey> jobKeysToTargetHost = moveAssignmentList.stream() .filter(moveAssignment -> moveAssignment.getTargetUUID().equals(assignment.getTargetUUID())) .map(moveAssignment -> moveAssignment.getJobKey()) .collect(Collectors.toList()); if(!jobKeysToTargetHost.contains(assignment.getJobKey())) { bytesUsed += taskSizer.estimateTrueSize(spawn.getTask(assignment.getJobKey())); return this.moveAssignmentList.add(assignment); } return false; }

Target:
public boolean add(JobTaskMoveAssignment assignment) { boolean isJobKeyPresent = this.moveAssignmentList.stream() .anyMatch(moveAssignment -> moveAssignment.getJobKey().equals(assignment.getJobKey()) && moveAssignment.getTargetUUID() != null && moveAssignment.getTargetUUID().equals(assignment.getTargetUUID())); if(!isJobKeyPresent) { bytesUsed += taskSizer.estimateTrueSize(spawn.getTask(assignment.getJobKey())); this.moveAssignmentList.add(assignment); return true; } return false; }
Source:
public void update(CruiseConfig preprocessedConfig) throws Exception { ElasticProfile existingProfile = findExistingProfile(preprocessedConfig); preprocessedConfig.server().getElasticConfig().getProfiles().remove(existingProfile); }

Target:
public void update(CruiseConfig preprocessedConfig) throws Exception { ElasticProfile existingProfile = findExistingProfile(preprocessedConfig); if (existingProfile == null) { throw new ElasticProfileNotFoundException(); } preprocessedConfig.server().getElasticConfig().getProfiles().remove(existingProfile); }
Source:
public void commitTransaction() throws ProducerFencedException { verifyProducerState(); verifyTransactionsInitialized(); verifyNoTransactionInFlight(); if (this.commitTransactionException != null) { throw this.commitTransactionException; } if (this.producerFencedOnCommitTxn) { throw new ProducerFencedException("Producer is fenced"); } flush(); this.sent.addAll(this.uncommittedSends); if (!this.uncommittedConsumerGroupOffsets.isEmpty()) this.consumerGroupOffsets.add(this.uncommittedConsumerGroupOffsets); this.uncommittedSends.clear(); this.uncommittedConsumerGroupOffsets = new HashMap<>(); this.transactionCommitted = true; this.transactionAborted = false; this.transactionInFlight = false; ++this.commitCount; }

Target:
public void commitTransaction() throws ProducerFencedException { verifyProducerState(); verifyTransactionsInitialized(); verifyTransactionInFlight(); if (this.commitTransactionException != null) { throw this.commitTransactionException; } flush(); this.sent.addAll(this.uncommittedSends); if (!this.uncommittedConsumerGroupOffsets.isEmpty()) this.consumerGroupOffsets.add(this.uncommittedConsumerGroupOffsets); this.uncommittedSends.clear(); this.uncommittedConsumerGroupOffsets = new HashMap<>(); this.transactionCommitted = true; this.transactionAborted = false; this.transactionInFlight = false; ++this.commitCount; }
Source:
protected void afterRunInternal() { for (EventDescriptor descriptor : unpublishedEvents) { mapEventPublisher.publishEvent(descriptor.caller, descriptor.mapName, descriptor.eventType, descriptor.dataKey, descriptor.oldValue, descriptor.dataValue); } invalidateNearCache(invalidationKeys); disposeDeferredBlocks = true; super.afterRunInternal(); }

Target:
protected void afterRunInternal() { invalidateNearCache(invalidationKeys); super.afterRunInternal(); }
Source:
public void resetIndex(long index, long timestamp) { currentOperation = OperationType.COMMAND; operationIndex = index; currentIndex = index; commitIndex = index; currentTimestamp = timestamp; }

Target:
public void resetIndex(long index, long timestamp) { currentOperation = OperationType.COMMAND; operationIndex = index; currentIndex = index; currentTimestamp = timestamp; setCommitIndex(index); service.tick(new WallClockTimestamp(currentTimestamp)); }
Source:
private RMContainer createContainer( Resource request, ApplicationAttemptId appAttemptId) { RMContainer container = mock(RMContainer.class); Container containerInner = mock(Container.class); ContainerId id = mock(ContainerId.class); when(id.getContainerId()).thenReturn(containerNum); when(containerInner.getResource()). thenReturn(Resources.clone(request)); when(containerInner.getId()).thenReturn(id); when(containerInner.getExecutionType()). thenReturn(ExecutionType.GUARANTEED); when(container.getApplicationAttemptId()).thenReturn(appAttemptId); when(container.getContainerId()).thenReturn(id); when(container.getContainer()).thenReturn(containerInner); when(container.getExecutionType()).thenReturn(ExecutionType.GUARANTEED); when(container.getAllocatedResource()). thenReturn(Resources.clone(request)); containers.add(container); containerNum++; return container; }

Target:
private RMContainer createContainer( Resource request, ApplicationAttemptId appAttemptId) { RMContainer container = mock(RMContainer.class); Container containerInner = mock(Container.class); ContainerId id = mock(ContainerId.class); when(id.getContainerId()).thenReturn((long)containers.size()); when(containerInner.getResource()). thenReturn(Resources.clone(request)); when(containerInner.getId()).thenReturn(id); when(containerInner.getExecutionType()). thenReturn(ExecutionType.GUARANTEED); when(container.getApplicationAttemptId()).thenReturn(appAttemptId); when(container.getContainerId()).thenReturn(id); when(container.getContainer()).thenReturn(containerInner); when(container.getExecutionType()).thenReturn(ExecutionType.GUARANTEED); when(container.getAllocatedResource()). thenReturn(Resources.clone(request)); containers.add(container); return container; }
Source:
public void addContents(@NonNull Container container) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins != null) { File dir = jenkins.getRootDir(); File[] files = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".xml") && !name.equals("credentials.xml"); } }); if (files != null) { for (int i = 0; i < files.length; i++) { File configFile = files[i]; if (configFile.exists()) { try { File patchedXmlFile = SecretHandler.findSecrets(configFile); container.add(new FileContent("jenkins-root-configuration-files/" + configFile.getName(), patchedXmlFile)); } catch (Exception e) { logger.log(Level.WARNING, "could not add the {0} configuration file to the support bundle because of: {1}", new Object[]{configFile.getName(), e}); } } } } } }

Target:
public void addContents(@NonNull Container container) { Jenkins jenkins = Helper.getActiveInstance(); if (jenkins != null) { File dir = jenkins.getRootDir(); File[] files = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".xml") && !name.equals("credentials.xml") && !name.equals("config.xml"); } }); if (files != null) { for (File configFile : files) { if (configFile.exists()) { try { File patchedXmlFile = SecretHandler.findSecrets(configFile); container.add(new FileContent("jenkins-root-configuration-files/" + configFile.getName(), patchedXmlFile)); } catch (IOException | ParserConfigurationException | XMLStreamException | SAXException | TransformerException e) { LOGGER.log(Level.WARNING, "could not add the {0} configuration file to the support bundle because of: {1}", new Object[]{configFile.getName(), e}); } } } } else { LOGGER.log(Level.WARNING, "Cannot list files in Jenkins root, probably something is wrong with the path"); } } }
Source:
public static void makeBucket_test1() throws Exception { if (!mintEnv) { System.out.println("Test: makeBucket(String bucketName)"); } long startTime = System.currentTimeMillis(); try { String name = getRandomName(); client.makeBucket(name); client.removeBucket(name); if (mintEnv) { System.out.println( mintLog("makeBucket(String bucketName)", null, System.currentTimeMillis() - startTime, pass, null, null, null)); } } catch (Exception e) { if (mintEnv) { System.out.println( mintLog("makeBucket(String bucketName)", null, System.currentTimeMillis() - startTime, failed, null, null, e)); } throw e; } }

Target:
public static void makeBucket_test1() throws Exception { if (!mintEnv) { System.out.println("Test: makeBucket(String bucketName)"); } long startTime = System.currentTimeMillis(); try { String name = getRandomName(); client.makeBucket(name); client.removeBucket(name); mintSuccessLog("makeBucket(String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog("makeBucket(String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } }
Source:
public void openNotification() throws Exception { driver.closeApp(); driver.openNotifications(); WebDriverWait wait = new WebDriverWait(driver, 20); assertNotEquals(0, wait.until(input -> { List<AndroidElement> result = input .findElements(id("com.android.systemui:id/carrier_label")); if (result.size() == 0) { return null; } return result; }).size()); }

Target:
public void openNotification() throws Exception { driver.closeApp(); driver.openNotifications(); WebDriverWait wait = new WebDriverWait(driver, 20); assertNotEquals(0, wait.until(input -> { List<AndroidElement> result = input .findElements(id("com.android.systemui:id/carrier_label")); return result.isEmpty() ? null : result; }).size()); }
Source:
private long getOffsetFromStorageForPartition(int partition) { long offset; Map<Integer, Long> metadataOffsets = getOffsetsFromMetadataStorage(); if (metadataOffsets.get(partition) != null) { offset = metadataOffsets.get(partition); log.debug("Getting offset [%,d] from metadata storage for partition [%d]", offset, partition); long latestKafkaOffset = getOffsetFromKafkaForPartition(partition, false); if (offset > latestKafkaOffset) { throw new ISE( "Offset in metadata storage [%,d] > latest Kafka offset [%,d] for partition[%d] dataSource[%s]. If your " + "Kafka offsets have been reset, you will need to use the supervisor reset API to remove the old entry.", offset, latestKafkaOffset, partition, dataSource ); } } else { offset = getOffsetFromKafkaForPartition(partition, ioConfig.isUseEarliestOffset()); log.debug("Getting offset [%,d] from Kafka for partition [%d]", offset, partition); } return offset; }

Target:
private long getOffsetFromStorageForPartition(int partition) { long offset; Map<Integer, Long> metadataOffsets = getOffsetsFromMetadataStorage(); if (metadataOffsets.get(partition) != null) { offset = metadataOffsets.get(partition); log.debug("Getting offset [%,d] from metadata storage for partition [%d]", offset, partition); long latestKafkaOffset = getOffsetFromKafkaForPartition(partition, false); if (offset > latestKafkaOffset) { throw new ISE( "Offset in metadata storage [%,d] > latest Kafka offset [%,d] for partition[%d] dataSource[%s]. If these " + "messages are no longer available (perhaps you deleted and re-created your Kafka topic) you can use the " + "supervisor reset API to restart ingestion.", offset, latestKafkaOffset, partition, dataSource ); } } else { offset = getOffsetFromKafkaForPartition(partition, ioConfig.isUseEarliestOffset()); log.debug("Getting offset [%,d] from Kafka for partition [%d]", offset, partition); } return offset; }