auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testJoinerConfigWithDuplicateOutputFields() { String selectedFields = "film.film_id, film.film_name, " + "filmActor.actor_name as name, filmCategory.category_name as name"; JoinerConfig config = new JoinerConfig("film.film_id=filmActor.film_id=filmCategory.film_id&" + "film.film_name=filmActor.film_name=filmCategory.film_name", selectedFields, "film,filmActor,filmCategory"); Joiner joiner = new Joiner(config); Map<String, Schema> inputSchemas = ImmutableMap.of("film", filmSchema, "filmActor", filmActorSchema, "filmCategory", filmCategorySchema); FailureCollector collector = new MockFailureCollector(); String caughtException = ""; try { joiner.init(inputSchemas, collector); joiner.getOutputSchema(inputSchemas, collector); } catch (Exception e) { <START> caughtException = e.getMessage(); <END> } Assert.assertEquals(validationExceptionMessage, caughtException); Assert.assertEquals(1, collector.getValidationFailures().size()); Assert.assertEquals(1, collector.getValidationFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, SELECTED_FIELDS); expectedCause.addAttribute(stage, mockStage); Assert.assertEquals(expectedCause, collector.getValidationFailures().get(0).getCauses().get(0)); }</code><technical_language>catch ValidationException get failures there</technical_language>

Target:
public void testJoinerConfigWithDuplicateOutputFields() { String selectedFields = "film.film_id, film.film_name, " + "filmActor.actor_name as name, filmCategory.category_name as name"; JoinerConfig config = new JoinerConfig("film.film_id=filmActor.film_id=filmCategory.film_id&" + "film.film_name=filmActor.film_name=filmCategory.film_name", selectedFields, "film,filmActor,filmCategory"); Joiner joiner = new Joiner(config); Map<String, Schema> inputSchemas = ImmutableMap.of("film", filmSchema, "filmActor", filmActorSchema, "filmCategory", filmCategorySchema); FailureCollector collector = new MockFailureCollector(); try { joiner.init(inputSchemas, collector); joiner.getOutputSchema(inputSchemas, collector); Assert.fail(); } catch (ValidationException e) { Assert.assertEquals(1, e.getFailures().size()); Assert.assertEquals(1, e.getFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, JoinerConfig.SELECT_FIELDS); expectedCause.addAttribute(STAGE, MOCK_STAGE); Assert.assertEquals(expectedCause, e.getFailures().get(0).getCauses().get(0)); } }
Source:
<code>public ConfigInfos validateConfigs( final @PathParam("connectorType") String connType, final Map<String, String> connectorConfig ) throws Throwable { String includedConnType = connectorConfig.get(ConnectorConfig.CONNECTOR_CLASS_CONFIG); if (includedConnType != null && !normalizedPluginName(includedConnType).endsWith(normalizedPluginName(connType))) { throw new BadRequestException( "Included connector type " + includedConnType + " does not match request type " + connType ); } FutureCallback<ConfigInfos> validationCallback = new FutureCallback<>(); herder.validateConnectorConfig(connectorConfig, validationCallback); <START> return validationCallback.get(); <END> }</code><technical_language>a good idea timeout block indefinitely</technical_language>

Target:
public ConfigInfos validateConfigs( final @PathParam("connectorType") String connType, final Map<String, String> connectorConfig ) throws Throwable { String includedConnType = connectorConfig.get(ConnectorConfig.CONNECTOR_CLASS_CONFIG); if (includedConnType != null && !normalizedPluginName(includedConnType).endsWith(normalizedPluginName(connType))) { throw new BadRequestException( "Included connector type " + includedConnType + " does not match request type " + connType ); } FutureCallback<ConfigInfos> validationCallback = new FutureCallback<>(); herder.validateConnectorConfig(connectorConfig, validationCallback, false); try { return validationCallback.get(ConnectorsResource.REQUEST_TIMEOUT_MS, TimeUnit.SECONDS); } catch (TimeoutException e) { throw new ConnectRestException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "Request timed out"); } catch (InterruptedException e) { throw new ConnectRestException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "Request interrupted"); } }
Source:
<code>public void testSimple() throws IOException { String hostport = emulator.getContainerIpAddress() + ":" + emulator.getMappedPort(8085); ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext().build(); try { TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel)); CredentialsProvider credentialsProvider = NoCredentialsProvider.create(); TopicAdminClient topicClient = TopicAdminClient.create( TopicAdminSettings.newBuilder() .setTransportChannelProvider(channelProvider) .setCredentialsProvider(credentialsProvider) .build()); Topic topic = Topic.newBuilder().setName("projects/my-project-id/topics/my-topic-id").build(); topicClient.createTopic(topic); Publisher publisher = Publisher.newBuilder(topic.getName()).build(); PubsubMessage message = PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8("test message")).build(); ApiFuture<String> future = publisher.publish(message); ApiFutures.addCallback(future, new ApiFutureCallback<String>() { @Override public void onFailure(Throwable t) { } @Override public void onSuccess(String result) { assertThat(result).isNotNull(); } }, MoreExecutors.directExecutor()); } finally { channel.shutdown(); } <START> assertThat(emulator.getMappedPort(8085)).isNotNull(); <END> }</code><technical_language>Is this assertion useful this point in time</technical_language>

Target:
public void testSimple() throws IOException { String hostport = emulator.getContainerIpAddress() + ":" + emulator.getMappedPort(8085); ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext().build(); try { TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel)); NoCredentialsProvider credentialsProvider = NoCredentialsProvider.create(); String topicId = "my-topic-id"; createTopic(topicId, channelProvider, credentialsProvider); String subscriptionId = "my-subscription-id"; createSubscription(subscriptionId, topicId, channelProvider, credentialsProvider); Publisher publisher = Publisher.newBuilder(TopicName.of(PROJECT_ID, topicId)) .setChannelProvider(channelProvider) .setCredentialsProvider(credentialsProvider) .build(); PubsubMessage message = PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8("test message")).build(); publisher.publish(message); SubscriberStubSettings subscriberStubSettings = SubscriberStubSettings.newBuilder() .setTransportChannelProvider(channelProvider) .setCredentialsProvider(credentialsProvider) .build(); try (SubscriberStub subscriber = GrpcSubscriberStub.create(subscriberStubSettings)) { PullRequest pullRequest = PullRequest.newBuilder() .setMaxMessages(1) .setSubscription(ProjectSubscriptionName.format(PROJECT_ID, subscriptionId)) .build(); PullResponse pullResponse = subscriber.pullCallable().call(pullRequest); assertThat(pullResponse.getReceivedMessagesList()).hasSize(1); assertThat(pullResponse.getReceivedMessages(0).getMessage().getData().toStringUtf8()).isEqualTo("test message"); } } finally { channel.shutdown(); } }
Source:
<code>public DenseHll toDense() { DenseHll result = new DenseHll(indexBitLength); int overflowIndex = 0; for (int hashIndex = 0; hashIndex < numberOfHashes; hashIndex++) { short shortHash = shortHashes[hashIndex]; int bucket = extractIndex(indexBitLength, shortHash); int zeros = numberOfLeadingZeros(toLongHash(shortHash), indexBitLength); <START> if (zeros > (Short.SIZE - indexBitLength)) { <END> zeros = Short.SIZE - indexBitLength; while (overflowIndex < numberOfOverflows) { short overflow = overflows[overflowIndex]; int overflowBucket = extractIndex(indexBitLength, overflow); if (overflowBucket > bucket) { break; } overflowIndex++; if (overflowBucket == bucket) { zeros += extractValue(overflow) + 1; break; } } } result.insert(bucket, zeros + 1); } return result; }</code><technical_language>Introduce a variable for expression purpose clear</technical_language>

Target:
public DenseHll toDense() { DenseHll result = new DenseHll(indexBitLength); int overflowIndex = 0; for (int hashIndex = 0; hashIndex < numberOfHashes; hashIndex++) { short shortHash = shortHashes[hashIndex]; int bucket = extractIndex(indexBitLength, shortHash); int zeros = numberOfLeadingZeros(toLongHash(shortHash), indexBitLength); int valueBits = Short.SIZE - indexBitLength; if (zeros > valueBits) { zeros = valueBits; while (overflowIndex < numberOfOverflows) { short overflow = overflows[overflowIndex]; int overflowBucket = extractIndex(indexBitLength, overflow); if (overflowBucket > bucket) { break; } overflowIndex++; if (overflowBucket == bucket) { zeros += extractValue(overflow) + 1; break; } } } result.insert(bucket, zeros + 1); } return result; }
Source:
<code>public void createNonAdminAccess() throws Exception { ObjectMapper mapper = new ObjectMapper(); BitstreamFormatRest bitstreamFormatRest = this.createRandomMockBitstreamRest(false); context.turnOffAuthorisationSystem(); EPerson user = EPersonBuilder.createEPerson(context) .withNameInMetadata("first", "last") .withEmail("testaze@gmail.com") .withPassword(password) .withLanguage(I18nUtil.getDefaultLocale().getLanguage()) .build(); context.restoreAuthSystemState(); String token = getAuthToken(user.getEmail(), password); getClient(token).perform(post("/api/core/bitstreamformats/") .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) <START> .andExpect(status().isForbidden()); <END> }</code><technical_language>add a check bitstreamformat created</technical_language>

Target:
public void createNonAdminAccess() throws Exception { ObjectMapper mapper = new ObjectMapper(); BitstreamFormatRest bitstreamFormatRest = this.createRandomMockBitstreamRest(false); context.turnOffAuthorisationSystem(); EPerson user = EPersonBuilder.createEPerson(context) .withNameInMetadata("first", "last") .withEmail("testaze@gmail.com") .withPassword(password) .withLanguage(I18nUtil.getDefaultLocale().getLanguage()) .build(); context.restoreAuthSystemState(); String token = getAuthToken(user.getEmail(), password); getClient(token).perform(post("/api/core/bitstreamformats/") .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isForbidden()); getClient().perform(get("/api/core/bitstreamformats/")) .andExpect(status().isOk()) .andExpect(jsonPath("$.page.totalElements", is(DEFAULT_AMOUNT_FORMATS))); }
Source:
<code>public Locale getLocale() { <START> return Locale.forLanguageTag(player.language.replace('_', '-')); <END> }</code><technical_language>thinking of this here, add, TextUtils something, this language mapping function? I a hunch need fixing/tuning in future, replace ~4 instances of :) I this I mapping player.language a Locale, include forLanguageTag in function body</technical_language>

Target:
public Locale getLocale() { return TextUtils.getLocaleByMinecraftTag(player.language); }
Source:
<code>protected void onClose() throws IOException { final boolean ok; try { <START> ok = client.completePendingCommand() || client.getReplyCode() == 426; <END> } finally { getAbstractFileSystem().putClient(client); } if (!ok) { throw new FileSystemException("vfs.provider.ftp/finish-get.error", getName()); } }</code><technical_language>this fix is right, constant FTPReply.TRANSFER_ABORTED, a magic number</technical_language>

Target:
protected void onClose() throws IOException { final boolean ok; try { ok = client.completePendingCommand() || client.getReplyCode() == FTPReply.TRANSFER_ABORTED; } finally { getAbstractFileSystem().putClient(client); } if (!ok) { throw new FileSystemException("vfs.provider.ftp/finish-get.error", getName()); } }
Source:
<code>public Function<Row, Row> makePostComputeManipulatorFn(MovingAverageQuery query, MetricManipulationFn fn) { return new Function<Row, Row>() { @Override public Row apply(Row result) { MapBasedRow mRow = (MapBasedRow) result; <START> final Map<String, Object> values = new HashMap(mRow.getEvent()); <END> for (AggregatorFactory agg : query.getAggregatorSpecs()) { Object aggVal = values.get(agg.getName()); if (aggVal != null) { values.put(agg.getName(), fn.manipulate(agg, aggVal)); } else { values.put(agg.getName(), null); } } for (AveragerFactory<?, ?> avg : query.getAveragerSpecs()) { Object aggVal = values.get(avg.getName()); if (aggVal != null) { values.put(avg.getName(), fn.manipulate(new AveragerFactoryWrapper(avg, avg.getName() + "_"), aggVal)); } else { values.put(avg.getName(), null); } } return new MapBasedRow(result.getTimestamp(), values); } }; }</code><technical_language>new HashMap<>(mRow.getEvent());</technical_language>

Target:
public Function<Row, Row> makePostComputeManipulatorFn(MovingAverageQuery query, MetricManipulationFn fn) { return new Function<Row, Row>() { @Override public Row apply(Row result) { MapBasedRow mRow = (MapBasedRow) result; final Map<String, Object> values = new HashMap<>(mRow.getEvent()); for (AggregatorFactory agg : query.getAggregatorSpecs()) { Object aggVal = values.get(agg.getName()); if (aggVal != null) { values.put(agg.getName(), fn.manipulate(agg, aggVal)); } else { values.put(agg.getName(), null); } } for (AveragerFactory<?, ?> avg : query.getAveragerSpecs()) { Object aggVal = values.get(avg.getName()); if (aggVal != null) { values.put(avg.getName(), fn.manipulate(new AveragerFactoryWrapper<>(avg, avg.getName() + "_"), aggVal)); } else { values.put(avg.getName(), null); } } return new MapBasedRow(result.getTimestamp(), values); } }; }
Source:
<code>public void setData(byte data, boolean applyPhysics) { chunk.setMetaData(x & 0xf, z & 0xf, y & 0x7f, data); if (applyPhysics) { <START> } <END> BlockChangeMessage bcmsg = new BlockChangeMessage(x, y, z, getTypeId(), data); for (GlowPlayer p : getWorld().getRawPlayers()) { p.sendBlockChange(bcmsg); } }</code><technical_language>I water depend physics for change flow data values for levels</technical_language>

Target:
public void setData(byte data, boolean applyPhysics) { byte oldData = getData(); chunk.setMetaData(x & 0xf, z & 0xf, y & 0x7f, data); if (applyPhysics) { applyPhysics(getType(), getTypeId(), oldData, data); } BlockChangeMessage bcmsg = new BlockChangeMessage(x, y, z, getTypeId(), data); for (GlowPlayer p : getWorld().getRawPlayers()) { p.sendBlockChange(bcmsg); } }
Source:
<code>public static LocalQueryRunner createLocalQueryRunner() { Session defaultSession = testSessionBuilder() .setCatalog("local") .setSchema(TINY_SCHEMA_NAME) <START> .build(); <END> LocalQueryRunner localQueryRunner = new LocalQueryRunner(defaultSession); localQueryRunner.createCatalog( defaultSession.getCatalog().get(), new TpchConnectorFactory(1), ImmutableMap.of()); localQueryRunner.getMetadata().addFunctions(CUSTOM_FUNCTIONS); SessionPropertyManager sessionPropertyManager = localQueryRunner.getMetadata().getSessionPropertyManager(); sessionPropertyManager.addSystemSessionProperties(TEST_SYSTEM_PROPERTIES); sessionPropertyManager.addConnectorSessionProperties(new ConnectorId(TESTING_CATALOG), TEST_CATALOG_PROPERTIES); return localQueryRunner; }</code><technical_language>revert PUSH_PARTIAL_AGGREGATION_THROUGH_JOIN is default</technical_language>

Target:
public static LocalQueryRunner createLocalQueryRunner() { Session defaultSession = testSessionBuilder() .setCatalog("local") .setSchema(TINY_SCHEMA_NAME) .setSystemProperty(PUSH_PARTIAL_AGGREGATION_THROUGH_JOIN, "true") .build(); LocalQueryRunner localQueryRunner = new LocalQueryRunner(defaultSession); localQueryRunner.createCatalog( defaultSession.getCatalog().get(), new TpchConnectorFactory(1), ImmutableMap.of()); localQueryRunner.getMetadata().addFunctions(CUSTOM_FUNCTIONS); SessionPropertyManager sessionPropertyManager = localQueryRunner.getMetadata().getSessionPropertyManager(); sessionPropertyManager.addSystemSessionProperties(TEST_SYSTEM_PROPERTIES); sessionPropertyManager.addConnectorSessionProperties(new ConnectorId(TESTING_CATALOG), TEST_CATALOG_PROPERTIES); return localQueryRunner; }
Source:
<code>public boolean removeLock(final long lockId) { return connector.retryWithHandle( new HandleCallback<Boolean>() { @Override public Boolean withHandle(Handle handle) throws Exception { return handle.createStatement( String.format( "DELETE FROM %s WHERE id = :id", lockTable ) ) .bind("id", lockId) <START> .execute() == 1; <END> } } ); }</code><technical_language>This right. If succeeded in delete simply failed register confirmation, this failed if deleted time</technical_language>

Target:
public void removeLock(final long lockId) { connector.retryWithHandle( new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { handle.createStatement(String.format("DELETE FROM %s WHERE id = :id", lockTable)) .bind("id", lockId) .execute(); return null; } } ); }
Source:
<code>protected boolean manageLeftClick(final int canvasX, final int canvasY) { <START> final Point2D ap = convertDOMToGridCoordinate(scenarioGrid, <END> new Point2D(canvasX, canvasY)); final Integer uiColumnIndex = getUiColumnIndex(scenarioGrid, ap.getX()); if (uiColumnIndex == null) { return false; } ScenarioGridColumn scenarioGridColumn = (ScenarioGridColumn) scenarioGrid.getModel().getColumns().get(uiColumnIndex); if (scenarioGridColumn == null) { return false; } if (!manageHeaderLeftClick(uiColumnIndex, scenarioGridColumn, ap)) { final Integer uiRowIndex = CoordinateUtilities.getUiRowIndex(scenarioGrid, ap.getY()); if (uiRowIndex == null) { return false; } else { return manageGridLeftClick(uiRowIndex, uiColumnIndex, scenarioGridColumn); } } else { return true; } }</code><technical_language>please change name more descriptive</technical_language>

Target:
protected boolean manageLeftClick(final int canvasX, final int canvasY) { final Point2D gridClickPoint = convertDOMToGridCoordinate(scenarioGrid, new Point2D(canvasX, canvasY)); final Integer uiColumnIndex = getUiColumnIndex(scenarioGrid, gridClickPoint.getX()); if (uiColumnIndex == null) { return false; } ScenarioGridColumn scenarioGridColumn = (ScenarioGridColumn) scenarioGrid.getModel().getColumns().get(uiColumnIndex); if (scenarioGridColumn == null) { return false; } if (!manageHeaderLeftClick(uiColumnIndex, scenarioGridColumn, gridClickPoint)) { final Integer uiRowIndex = getUiRowIndex(scenarioGrid, gridClickPoint.getY()); if (uiRowIndex == null) { return false; } else { return manageGridLeftClick(uiRowIndex, uiColumnIndex, scenarioGridColumn); } } else { return true; } }
Source:
<code>public static Map<TopicPartition, ListOffsetsResultInfo> fetchEndOffsets(final Collection<TopicPartition> partitions, final Admin adminClient, final Duration timeout) { final Map<TopicPartition, ListOffsetsResultInfo> endOffsets; try { final KafkaFuture<Map<TopicPartition, ListOffsetsResultInfo>> future = adminClient.listOffsets( partitions.stream().collect(Collectors.toMap(Function.identity(), tp -> OffsetSpec.latest()))) .all(); if (timeout == null) { endOffsets = future.get(); } else { endOffsets = future.get(timeout.toMillis(), TimeUnit.MILLISECONDS); } } catch (final TimeoutException | RuntimeException | InterruptedException | ExecutionException e) { <START> LOG.warn("listOffsets request failed due to ", e); <END> throw new StreamsException("Unable to obtain end offsets from kafka", e); } return endOffsets; }</code><technical_language>suggestion LOG.warn("listOffsets request failed.", e); Thanks! (minor suggestion log message more typical)</technical_language>

Target:
public static Map<TopicPartition, ListOffsetsResultInfo> fetchEndOffsets(final Collection<TopicPartition> partitions, final Admin adminClient, final Duration timeout) { final Map<TopicPartition, ListOffsetsResultInfo> endOffsets; try { final KafkaFuture<Map<TopicPartition, ListOffsetsResultInfo>> future = adminClient.listOffsets( partitions.stream().collect(Collectors.toMap(Function.identity(), tp -> OffsetSpec.latest()))) .all(); if (timeout == null) { endOffsets = future.get(); } else { endOffsets = future.get(timeout.toMillis(), TimeUnit.MILLISECONDS); } } catch (final TimeoutException | RuntimeException | InterruptedException | ExecutionException e) { LOG.warn("listOffsets request failed.", e); throw new StreamsException("Unable to obtain end offsets from kafka", e); } return endOffsets; }
Source:
<code>private void broadcastBlockBreakAnimation(GlowBlock block, int destroyStage) { <START> if (block == null) return; <END> GlowChunk.Key key = new GlowChunk.Key(block.getChunk().getX(), block.getChunk().getZ()); block.getWorld().getRawPlayers().stream().filter(player1 -> player1.canSeeChunk(key)).forEach(player2 -> { if (player2 != this) { player2.sendBlockBreakAnimation(player2, block.getLocation(), destroyStage); } }); }</code><technical_language>this work a precondition</technical_language>

Target:
private void broadcastBlockBreakAnimation(GlowBlock block, int destroyStage) { GlowChunk.Key key = new GlowChunk.Key(block.getChunk().getX(), block.getChunk().getZ()); block.getWorld().getRawPlayers().stream() .filter(player -> player.canSeeChunk(key) && player != this) .forEach(player -> player.sendBlockBreakAnimation(block.getLocation(), destroyStage)); }
Source:
<code>public Map<Object, Object> loadInitialData() { Map<Object, Object> result = null; FSDataInputStream in = null; BufferedReader bin = null; try { result = Maps.newHashMap(); in = fs.open(filePath); bin = new BufferedReader(new InputStreamReader(in)); String line; int linesCount = 0; while ((line = bin.readLine()) != null) { <START> if ( numInitCachedLines > 0 && linesCount >= numInitCachedLines) { <END> break; } try { Map<String, Object> tuple = extractFields(line); if (tuple != null && !tuple.isEmpty()) { result.put(getKey(tuple), getValue(tuple)); } } catch (Exception parseExp) { logger.info("Unable to parse line {}", line); } ++linesCount; } } catch (IOException e) { throw new RuntimeException(e); } finally { if (bin != null) { IOUtils.closeQuietly(bin); } if (in != null) { IOUtils.closeQuietly(in); } } logger.debug("loading initial data, size: {}", result.size()); return result; }</code><technical_language>this added while condition</technical_language>

Target:
public Map<Object, Object> loadInitialData() { Map<Object, Object> result; try ( FSDataInputStream in = fs.open(filePath); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); ) { result = Maps.newHashMap(); String line; int linesCount = 0; while ((line = bin.readLine()) != null && (numInitCachedLines < 0 || linesCount < numInitCachedLines)) { try { Map<String, Object> tuple = extractFields(line); if (tuple != null && !tuple.isEmpty()) { result.put(getKey(tuple), getValue(tuple)); } } catch (Exception parseExp) { throw new RuntimeException(parseExp); } ++linesCount; } } catch (IOException e) { throw new RuntimeException(e); } logger.debug("loading initial data, size: {}", result.size()); return result; }
Source:
<code>public Exchange get(CamelContext camelContext, String key) { try { debug("Getting exchange for key '{}'", key); return toExchange(camelContext, mongoRepo.tryLockAndGet(key, SECONDS.toMillis(waitForLockSec))); } catch (LockWaitTimeoutException e) { throw new RepositoryLockWaitException(format( <START> "Failed to acquire the lock for the key '%s' within timeout of %ds", <END> key, waitForLockSec)); } catch (PessimisticException | MongoException e) { LOGGER.warn("Failed to get the key: ", e); throw new RepositoryUnreachableException(e); } }</code><technical_language>![MINOR](<LINK_0> Define a constant instead of duplicating this literal "Failed acquire lock for key '%s' timeout of %ds" 3 times. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public Exchange get(CamelContext camelContext, String key) { try { debug("Getting exchange for key '{}'", key); return toExchange(camelContext, mongoRepo.tryLockAndGet(key, SECONDS.toMillis(waitForLockSec))); } catch (LockWaitTimeoutException e) { throw new RepositoryLockWaitException(format( "Failed to acquire the lock for the key '%s' within timeout of %ds", key, waitForLockSec), e); } catch (PessimisticException | MongoException e) { LOGGER.warn("Failed to get the key: ", e); throw new RepositoryUnreachableException(e); } }
Source:
<code>protected void addAttributesTo(Map<PropertyDescriptorField, String> attributes) { super.addAttributesTo(attributes); <START> attributes.put(MIN, lowerLimit.toString()); <END> attributes.put(MAX, upperLimit.toString()); }</code><technical_language>asString(...) convert a String representation? I thought I this identical method implementation in another class, AbstractNumericProperty? Java 8 yet? interface default methods reduce duplication? I a robust mental visual of interface class hierarchies yet, if this is a practical/useful suggestion</technical_language>

Target:
protected void addAttributesTo(Map<PropertyDescriptorField, String> attributes) { super.addAttributesTo(attributes); module.addAttributesTo(attributes); }
Source:
<code>private void setRepairLogTruncationHandle(long newHandle, boolean isForLeader) { if (newHandle > m_repairLogTruncationHandle) { m_repairLogTruncationHandle = newHandle; <START> if (m_isLeader || (!m_isLeader && isForLeader)) { <END> if (m_defaultConsistencyReadLevel == ReadLevel.SAFE) { m_bufferedReadLog.releaseBufferedReads(m_mailbox, m_repairLogTruncationHandle); } scheduleRepairLogTruncateMsg(); } } else { if (tmLog.isDebugEnabled()) { tmLog.debug("Updating truncation point from " + TxnEgo.txnIdToString(m_repairLogTruncationHandle) + "to" + TxnEgo.txnIdToString(newHandle)+ " isLeader:" + m_isLeader + " isForLeader:" + isForLeader); } } }</code><technical_language>Simplify " if (m_isLeader || isForLeader)"</technical_language>

Target:
private void setRepairLogTruncationHandle(long newHandle, boolean isForLeader) { if (newHandle > m_repairLogTruncationHandle) { m_repairLogTruncationHandle = newHandle; if (m_isLeader || isForLeader) { if (m_defaultConsistencyReadLevel == ReadLevel.SAFE) { m_bufferedReadLog.releaseBufferedReads(m_mailbox, m_repairLogTruncationHandle); } scheduleRepairLogTruncateMsg(); } } else { if (tmLog.isDebugEnabled()) { tmLog.debug("Updating truncation point from " + TxnEgo.txnIdToString(m_repairLogTruncationHandle) + "to" + TxnEgo.txnIdToString(newHandle)+ " isLeader:" + m_isLeader + " isForLeader:" + isForLeader); } } }
Source:
<code>public void ensureChannelCount(int capacity) throws IOException { if (totalSize.get() < capacity) { synchronized(this){ if (totalSize.get() < capacity) { ImmutableList.Builder<Channel> channelsBuilder = ImmutableList.builder(); List<Channel> current = channels.get(); channelsBuilder.addAll(current); int unreservedCapacity = capacity - reservedChannelCount; for (int i = current.size(); i < unreservedCapacity; i++) { channelsBuilder.add(factory.create()); } <START> channels.set(channelsBuilder.build()); <END> totalSize.set(capacity); } } } }</code><technical_language>do ImmutableList is faster? requires building making a copy</technical_language>

Target:
public void ensureChannelCount(int capacity) throws IOException { if (totalSize.get() < capacity) { synchronized(this){ if (totalSize.get() < capacity) { List<Channel> newChannelList = new ArrayList<>(channels.get()); int unreservedCapacity = capacity - reservedChannelCount; while(newChannelList.size() < unreservedCapacity) { newChannelList.add(factory.create()); } setChannels(newChannelList); totalSize.set(capacity); } } } }
Source:
<code>private boolean isAccessible( Type mapperToImplement, Type usedMapper, ExecutableElement method ) { if ( method.getModifiers().contains( Modifier.PRIVATE ) ) { return false; } <START> else if ( method.getModifiers().contains( Modifier.PROTECTED ) ) { <END> return mapperToImplement.isAssignableTo( usedMapper ); } else if ( !method.getModifiers().contains( Modifier.PUBLIC ) ) { return mapperToImplement.getPackageName().equals( usedMapper.getPackageName()); } return true; }</code><technical_language>Other classes in package access protected methods well</technical_language>

Target:
private boolean isAccessible( Type mapperToImplement, Type usedMapper, ExecutableElement method ) { if ( method.getModifiers().contains( Modifier.PRIVATE ) ) { return false; } else if ( method.getModifiers().contains( Modifier.PROTECTED ) ) { return mapperToImplement.isAssignableTo( usedMapper ) || mapperToImplement.getPackageName().equals( usedMapper.getPackageName() ); } else if ( !method.getModifiers().contains( Modifier.PUBLIC ) ) { return mapperToImplement.getPackageName().equals( usedMapper.getPackageName() ); } return true; }
Source:
<code>public Object execute(final ExecutionEvent event) throws ExecutionException { final Repository repository = getRepository(true, event); if (repository == null) return null; if (!canMerge(repository, event)) return null; MergeTargetSelectionDialog mergeTargetSelectionDialog = new MergeTargetSelectionDialog( getShell(event), repository); if (mergeTargetSelectionDialog.open() == IDialogConstants.OK_ID) { final String refName = mergeTargetSelectionDialog.getRefName(); String jobname = NLS.bind(UIText.MergeAction_JobNameMerge, refName); Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { new MergeOperation(repository, refName) .execute(monitor); } catch (final CoreException e) { Activator .handleError( "Merge impossible, Unsupported Operation", null, true); } return Status.OK_STATUS; } }; <START> job.setUser(true); <END> job.schedule(); } return null; }</code><technical_language>code 2b083c3f21a3553b6211c978b744f2259c8fd9ca is missing</technical_language>

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { final Repository repository = getRepository(true, event); if (repository == null) return null; if (!canMerge(repository, event)) return null; MergeTargetSelectionDialog mergeTargetSelectionDialog = new MergeTargetSelectionDialog( getShell(event), repository); if (mergeTargetSelectionDialog.open() == IDialogConstants.OK_ID) { final String refName = mergeTargetSelectionDialog.getRefName(); String jobname = NLS.bind(UIText.MergeAction_JobNameMerge, refName); final MergeOperation op = new MergeOperation(repository, refName); Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { op.execute(monitor); } catch (final CoreException e) { return e.getStatus(); } return Status.OK_STATUS; } }; job.setUser(true); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent cevent) { IStatus result = cevent.getJob().getResult(); if (result.getSeverity() == IStatus.CANCEL) { Display.getDefault().asyncExec(new Runnable() { public void run() { try { MessageDialog .openInformation( getShell(event), UIText.MergeAction_MergeCanceledTitle, UIText.MergeAction_MergeCanceledMessage); } catch (ExecutionException e) { Activator .handleError( UIText.MergeAction_MergeCanceledMessage, null, true); } } }); } else if (!result.isOK()) { Activator.handleError(result.getMessage(), result .getException(), true); } else { Display.getDefault().asyncExec(new Runnable() { public void run() { try { MessageDialog .openInformation( getShell(event), UIText.MergeAction_MergeResultTitle, op.getResult().toString()); } catch (ExecutionException e) { Activator.handleError(op.getResult() .toString(), null, true); } } }); } } }); job.schedule(); } return null; }
Source:
<code>public List<Pair<PublicKey, String>> getIdentities() throws IOException { byte cmd = SshAgentConstants.SSH2_AGENTC_REQUEST_IDENTITIES; byte okcmd = SshAgentConstants.SSH2_AGENT_IDENTITIES_ANSWER; <START> if (FactoryManager.AGENT_FORWARDING_TYPE_IETF.equals(channelType)) { <END> cmd = SshAgentConstants.SSH_AGENT_LIST_KEYS; okcmd = SshAgentConstants.SSH_AGENT_KEY_LIST; } Buffer buffer = createBuffer(cmd, 1); buffer = request(prepare(buffer)); int type = buffer.getUByte(); if (type != okcmd) { throw new SshException("Bad agent identities answer: " + SshAgentConstants.getCommandMessageName(type)); } int nbIdentities = buffer.getInt(); if (nbIdentities > 1024) { throw new SshException("Bad identities count: " + nbIdentities); } List<Pair<PublicKey, String>> keys = new ArrayList<>(nbIdentities); for (int i = 0; i < nbIdentities; i++) { PublicKey key = buffer.getPublicKey(); String comment = buffer.getString(); if (log.isDebugEnabled()) { log.debug("getIdentities() key type={}, comment={}, fingerprint={}", KeyUtils.getKeyType(key), comment, KeyUtils.getFingerPrint(key)); } keys.add(new Pair<>(key, comment)); } return keys; }</code><technical_language>_int_ instead of _byte_ allow for values > 127..</technical_language>

Target:
public List<Pair<PublicKey, String>> getIdentities() throws IOException { int cmd = SshAgentConstants.SSH2_AGENTC_REQUEST_IDENTITIES; int okcmd = SshAgentConstants.SSH2_AGENT_IDENTITIES_ANSWER; if (FactoryManager.AGENT_FORWARDING_TYPE_IETF.equals(channelType)) { cmd = SshAgentConstants.SSH_AGENT_LIST_KEYS; okcmd = SshAgentConstants.SSH_AGENT_KEY_LIST; } Buffer buffer = createBuffer((byte) cmd, 1); buffer = request(prepare(buffer)); int type = buffer.getUByte(); if (type != okcmd) { throw new SshException("Bad agent identities answer: " + SshAgentConstants.getCommandMessageName(type)); } int nbIdentities = buffer.getInt(); if (nbIdentities > 1024) { throw new SshException("Bad identities count: " + nbIdentities); } List<Pair<PublicKey, String>> keys = new ArrayList<>(nbIdentities); for (int i = 0; i < nbIdentities; i++) { PublicKey key = buffer.getPublicKey(); String comment = buffer.getString(); if (log.isDebugEnabled()) { log.debug("getIdentities() key type={}, comment={}, fingerprint={}", KeyUtils.getKeyType(key), comment, KeyUtils.getFingerPrint(key)); } keys.add(new Pair<>(key, comment)); } return keys; }
Source:
<code>private void loadIntoBuilder(I id) { Optional<S> existingState = load(id); <START> if (existingState.isPresent()) { <END> AbstractStatefulReactor.this.builder = (B) existingState.get() .toBuilder(); } else { AbstractStatefulReactor.this.builder = newStateBuilderWith(id); } }</code><technical_language>Consider a ternary expression here</technical_language>

Target:
private void loadIntoBuilder(I id) { Optional<S> existingState = load(id); AbstractStatefulReactor.this.builder = existingState.isPresent() ? (B) existingState.get() .toBuilder() : newStateBuilderWith(id); }
Source:
<code>private void mockSimpleConsumer(TopicMetadataResponse metadataResponse, OffsetResponse offsetResponse, FetchResponse fetchResponse) { <START> _simpleConsumer = EasyMock.createNiceMock(SimpleConsumer.class); <END> _mocks.add(_simpleConsumer); EasyMock.expect(_simpleConsumer.send((TopicMetadataRequest)EasyMock.anyObject())).andReturn(metadataResponse).times(1); EasyMock.expect(_simpleConsumer.getOffsetsBefore((OffsetRequest)EasyMock.anyObject())).andReturn(offsetResponse).anyTimes(); _simpleConsumer.close(); EasyMock.expectLastCall().andVoid().anyTimes(); EasyMock.expect(_simpleConsumer.clientId()).andReturn(KAFKA_CLIENT_ID).times(1); EasyMock.expect(_simpleConsumer.fetch((FetchRequest)EasyMock.anyObject())).andReturn(fetchResponse).times(1); }</code><technical_language>I prefer createMock is more strict. add consumer.host(), consumer.port() in mocked consumer object</technical_language>

Target:
private void mockSimpleConsumer(TopicMetadataResponse metadataResponse, OffsetResponse offsetResponse, FetchResponse fetchResponse) { _simpleConsumer = EasyMock.createMock(SimpleConsumer.class); _mocks.add(_simpleConsumer); EasyMock.expect(_simpleConsumer.send((TopicMetadataRequest)EasyMock.anyObject())).andReturn(metadataResponse).times(1); EasyMock.expect(_simpleConsumer.getOffsetsBefore((OffsetRequest)EasyMock.anyObject())).andReturn(offsetResponse).anyTimes(); _simpleConsumer.close(); EasyMock.expectLastCall().andVoid().anyTimes(); EasyMock.expect(_simpleConsumer.clientId()).andReturn(KAFKA_CLIENT_ID).times(1); EasyMock.expect(_simpleConsumer.fetch((FetchRequest)EasyMock.anyObject())).andReturn(fetchResponse).times(1); EasyMock.expect(_simpleConsumer.host()).andReturn("dummyHost").anyTimes(); EasyMock.expect(_simpleConsumer.port()).andReturn(8888).anyTimes(); }
Source:
<code>private Constraint characterConflict(ConstraintFactory cf) { return cf.from(ScrabbleCell.class) .filter(sc -> sc.getCharacterSet().size() >= 2) <START> .penalize("Character confict", HardMediumSoftScore.ONE_HARD, sc -> 1 - sc.getCharacterSet().size()); <END> }</code><technical_language>@Christopher-Chianelli This is score corruption is be. DRL this: scoreHolder.addHardConstraintMatch(kcontext, 1 - $size); number 0 less. is in DRL, need input *a negative number* penalize. In CS, penalize() call, expects *a positive number*. I if invert logic of match weigher here, this score corruption away</technical_language>

Target:
private Constraint characterConflict(ConstraintFactory cf) { return cf.from(ScrabbleCell.class) .filter(sc -> sc.getCharacterSet().size() >= 2) .penalize("Character confict", HardMediumSoftScore.ONE_HARD, sc -> sc.getCharacterSet().size() - 1); }
Source:
<code>public void visitNode(Tree tree) { MethodTree methodTree = (MethodTree) tree; <START> if (hasSemantic() && "equals".equals(methodTree.symbol().name()) && methodTree.parameters().size() == 1 && <END> NullableAnnotationUtils.isAnnotatedNonNull(methodTree.parameters().get(0).symbol())) { reportIssue(methodTree.parameters().get(0), "\"equals\" method parameters should not be marked \"@Nonnull\"."); } }</code><technical_language>need check type of parameter well, match methods called equals() override Object.equals(Object o)</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; List<VariableTree> params = methodTree.parameters(); if ("equals".equals(methodTree.symbol().name()) && params.size() == 1) { VariableTree variable = params.get(0); if (variable.type().symbolType().is("java.lang.Object") && NullableAnnotationUtils.isAnnotatedNonNull(variable.symbol())) { reportIssue(variable, "\"equals\" method parameters should not be marked \"@Nonnull\"."); } } }
Source:
<code>private void validatePipelineTemplateVersion(String version) { if (StringUtils.isEmpty(version)) { <START> throw new InvalidRequestException("The provided version is empty or null"); <END> } if (!version.matches(VALID_TEMPLATE_VERSION_REGEX)) { throw new InvalidRequestException(String.format("The provided version %s contains illegal characters." + " Pipeline template versions must match %s", version, VALID_TEMPLATE_VERSION_REGEX)); } }</code><technical_language>I thought empty OK, point latest</technical_language>

Target:
private void validatePipelineTemplateVersion(String version) { if (!version.matches(VALID_TEMPLATE_VERSION_REGEX)) { throw new InvalidRequestException(String.format("The provided version %s contains illegal characters." + " Pipeline template versions must match %s", version, VALID_TEMPLATE_VERSION_REGEX)); } }
Source:
<code>public void export(final TransactionBase fluoTx, final String queryId, final VisibilityBindingSet result) throws ResultExportException { checkNotNull(fluoTx); checkNotNull(queryId); checkNotNull(result); try { <START> final String pcjId = fluoTx.gets(queryId, FluoQueryColumns.RYA_PCJ_ID); <END> String msg = "out to kafta topic: queryId=" + queryId + " pcjId=" + pcjId + " result=" + result; System.out.println(msg); ProducerRecord<String, VisibilityBindingSet> rec = new ProducerRecord<String, VisibilityBindingSet>( queryId, result); producer.send(rec); System.out.println("producer.send(rec) completed"); } catch (final Throwable e) { throw new ResultExportException("A result could not be exported to Kafka.", e); } }</code><technical_language>White space</technical_language>

Target:
public void export(final TransactionBase fluoTx, final String queryId, final VisibilityBindingSet result) throws ResultExportException { checkNotNull(fluoTx); checkNotNull(queryId); checkNotNull(result); try { final String pcjId = fluoTx.gets(queryId, FluoQueryColumns.RYA_PCJ_ID); String msg = "out to kafta topic: queryId=" + queryId + " pcjId=" + pcjId + " result=" + result; log.info(msg); ProducerRecord<String, VisibilityBindingSet> rec = new ProducerRecord<String, VisibilityBindingSet>( queryId, result); producer.send(rec); log.debug("producer.send(rec) completed"); } catch (final Throwable e) { throw new ResultExportException("A result could not be exported to Kafka.", e); } }
Source:
<code>public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj instanceof EvalParameters) { EvalParameters evalParameters = (EvalParameters) obj; return Arrays.equals(params, evalParameters.params) && numOutcomes == evalParameters.numOutcomes && correctionConstant == evalParameters.correctionConstant && constantInverse == evalParameters.constantInverse && correctionParam == evalParameters.correctionParam; } else { return false; <START> } <END> }</code><technical_language>Rewrite if (obj instanceOf EvalParmeters) { ... return ... } return obj == this;</technical_language>

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof EvalParameters) { EvalParameters evalParameters = (EvalParameters) obj; return Arrays.equals(params, evalParameters.params) && numOutcomes == evalParameters.numOutcomes && correctionConstant == evalParameters.correctionConstant && constantInverse == evalParameters.constantInverse && correctionParam == evalParameters.correctionParam; } return false; }
Source:
<code>public static void generateKitchenSink(final TinkerGraph graph) { final GraphTraversalSource g = graph.traversal(); g.addV("loops").property(T.id, 1000).property("name", "loop").as("me"). addE("self").to("me"). iterate(); final String LABEL = "message_passing_test"; final String EDGE_LABEL = "msg_pass_test_edge"; final String PROPERTY_IN = "propertyin"; <START> Vertex a = graph.addVertex(T.id, 2000, T.label, LABEL, PROPERTY_IN, "a"); <END> Vertex b = graph.addVertex(T.id, 2001, T.label, LABEL, PROPERTY_IN, "b"); a.addEdge(EDGE_LABEL, b); a.addEdge(EDGE_LABEL, a); }</code><technical_language>of sample graphs need a "name" property of some sort. build is currently failing for me. please "final" Vertex variables</technical_language>

Target:
public static void generateKitchenSink(final TinkerGraph graph) { final GraphTraversalSource g = graph.traversal(); g.addV("loops").property(T.id, 1000).property("name", "loop").as("me"). addE("self").to("me"). iterate(); final String LABEL = "message_passing_test"; final String EDGE_LABEL = "msg_pass_test_edge"; final String PROPERTY_IN = "name"; final Vertex a = graph.addVertex(T.id, 2000, T.label, LABEL, PROPERTY_IN, "a"); final Vertex b = graph.addVertex(T.id, 2001, T.label, LABEL, PROPERTY_IN, "b"); a.addEdge(EDGE_LABEL, b); a.addEdge(EDGE_LABEL, a); }
Source:
<code>private void migrate() throws SQLException { if(!validateDatabase(false)) <START> throw new SchemaMigrationException("Target database is empty, please consider executing with \"create\" option"); <END> flyway.migrate(); }</code><technical_language>Target database is empty previous versions found, "create" option</technical_language>

Target:
private void migrate() throws SQLException { try (Connection connection = flyway.getDataSource().getConnection()) { if (isDatabaseEmpty(connection)) throw new SchemaMigrationException("Target database is empty and no previous versions found, use the \"create\" option."); } flyway.migrate(); }
Source:
<code>void setup() { b1 = new BibEntry(); <START> b2 = new BibEntry(); <END> bList = new ArrayList<>(); b2.setField(StandardField.DOI, "10.1007/s11616-005-0142-4"); b2.setField(StandardField.CITING, "test"); b2.setField(StandardField.CITEDBY, "test"); bList.add(b1); bList.add(b2); }</code><technical_language>Please withField suggestion b2 = new BibEntry() .withField(StandardField.DOI, "10.1007/s11616-005-0142-4");</technical_language>

Target:
void setup() { bibEntry = new BibEntry().withField(StandardField.DOI, "10.1007/s11616-005-0142-4") .withField(StandardField.CITING, "test") .withField(StandardField.CITEDBY, "test"); bList = new ArrayList<>(); bList.add(new BibEntry()); bList.add(bibEntry); }
Source:
<code>public void testBAMThroughCRAMRoundTripViaPath() throws IOException, NoSuchAlgorithmException { final File TEST_DATA_DIR = new File("src/test/resources/htsjdk/samtools/cram"); final File originalBAMInputFile = new File(TEST_DATA_DIR, "CEUTrio.HiSeq.WGS.b37.NA12878.20.first.8000.bam"); final File referenceFile = new File(TEST_DATA_DIR, "human_g1k_v37.20.subset.fasta"); List<SAMRecord> originalBAMRecords = getSAMRecordsFromFile(originalBAMInputFile, referenceFile); for (int i = 0; i < originalBAMRecords.size(); i++) { originalBAMRecords.get(i).setIndexingBin(null); } <START> final File tempCRAMFile = File.createTempFile("testBAMThroughCRAMRoundTrip", CramIO.CRAM_FILE_EXTENSION); <END> tempCRAMFile.deleteOnExit(); SAMFileHeader samHeader = getFileHeader(originalBAMInputFile, referenceFile); writeRecordsToPath(originalBAMRecords, tempCRAMFile, referenceFile, samHeader); List<SAMRecord> cramRecords = getSAMRecordsFromFile(tempCRAMFile, referenceFile); Assert.assertEquals(cramRecords.size(), originalBAMRecords.size()); for (int i = 0; i < originalBAMRecords.size(); i++) { Assert.assertEquals(originalBAMRecords.get(i), cramRecords.get(i)); } }</code><technical_language>for Path tests __Jimfs__ (in-memory filesystem)</technical_language>

Target:
public void testBAMThroughCRAMRoundTripViaPath() throws IOException, NoSuchAlgorithmException { final File TEST_DATA_DIR = new File("src/test/resources/htsjdk/samtools/cram"); final File originalBAMInputFile = new File(TEST_DATA_DIR, "CEUTrio.HiSeq.WGS.b37.NA12878.20.first.8000.bam"); final File referenceFile = new File(TEST_DATA_DIR, "human_g1k_v37.20.subset.fasta"); List<SAMRecord> originalBAMRecords = getSAMRecordsFromFile(originalBAMInputFile, referenceFile); for (int i = 0; i < originalBAMRecords.size(); i++) { originalBAMRecords.get(i).setIndexingBin(null); } try (FileSystem jimfs = Jimfs.newFileSystem(Configuration.unix())) { final Path tempCRAM = jimfs.getPath("testBAMThroughCRAMRoundTrip" + CramIO.CRAM_FILE_EXTENSION); SAMFileHeader samHeader = getFileHeader(originalBAMInputFile, referenceFile); writeRecordsToPath(originalBAMRecords, tempCRAM, referenceFile, samHeader); List<SAMRecord> cramRecords = getSAMRecordsFromPath(tempCRAM, referenceFile); Assert.assertEquals(cramRecords.size(), originalBAMRecords.size()); for (int i = 0; i < originalBAMRecords.size(); i++) { Assert.assertEquals(originalBAMRecords.get(i), cramRecords.get(i)); } } }
Source:
<code>public Method getOnOpenMethod(Object webSocketEndpoint) { Method[] methods = webSocketEndpoint.getClass().getMethods(); <START> for (Method method : methods) { <END> if (method.isAnnotationPresent(OnOpen.class)) { return method; } } return null; }</code><technical_language>for loop throw a NPE if methods variable null</technical_language>

Target:
public Optional<Method> getOnOpenMethod(Object webSocketEndpoint) { Method[] methods = webSocketEndpoint.getClass().getMethods(); Method returnMethod = null; for (Method method : methods) { if (method.isAnnotationPresent(OnOpen.class)) { returnMethod = method; break; } } return Optional.ofNullable(returnMethod); }
Source:
<code>private void initializeVcfDataSource() { if ( INTERVAL_ITERATOR ) { vcfFileReader = new VCFFileReader(VCF, true); if (!vcfFileReader.isQueryable()) { <START> throw new PicardException("Cannot query VCF File! VCF Files must be queryable!"); <END> } } else { vcfIterator = new PeekableIterator<>( VCF == null ? Collections.emptyIterator() : new VCFFileReader(VCF, true).iterator()); } }</code><technical_language>"...Please index input VCF re-run."</technical_language>

Target:
private void initializeVcfDataSource() { if ( INTERVAL_ITERATOR ) { vcfFileReader = new VCFFileReader(VCF, true); if (!vcfFileReader.isQueryable()) { throw new PicardException("Cannot query VCF File! VCF Files must be queryable! Please index input VCF and re-run."); } } else { vcfIterator = new PeekableIterator<>( VCF == null ? Collections.emptyIterator() : new VCFFileReader(VCF, true).iterator()); } }