auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ChannelFuture doResolveAndConnect0(final Channel channel, SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) { try { final EventLoop eventLoop = channel.eventLoop(); AddressResolver<SocketAddress> resolver; try { resolver = this.resolver.getResolver(eventLoop); } catch (Throwable e) { <START> channel.close(); <END> throw e; } if (!resolver.isSupported(remoteAddress) || resolver.isResolved(remoteAddress)) { doConnect(remoteAddress, localAddress, promise); return promise; } final Future<SocketAddress> resolveFuture = resolver.resolve(remoteAddress); if (resolveFuture.isDone()) { final Throwable resolveFailureCause = resolveFuture.cause(); if (resolveFailureCause != null) { channel.close(); promise.setFailure(resolveFailureCause); } else { doConnect(resolveFuture.getNow(), localAddress, promise); } return promise; } resolveFuture.addListener(new FutureListener<SocketAddress>() { @Override public void operationComplete(Future<SocketAddress> future) throws Exception { if (future.cause() != null) { channel.close(); promise.setFailure(future.cause()); } else { doConnect(future.getNow(), localAddress, promise); } } }); } catch (Throwable cause) { promise.tryFailure(cause); } return promise; }</code><technical_language>@blindpirate I this changed to: try { ... } catch (Throwable cause) { channel.close(); promise.setFailure(e); return; }</technical_language>

Target:
private ChannelFuture doResolveAndConnect0(final Channel channel, SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) { try { final EventLoop eventLoop = channel.eventLoop(); AddressResolver<SocketAddress> resolver; try { resolver = this.resolver.getResolver(eventLoop); } catch (Throwable cause) { channel.close(); return promise.setFailure(cause); } if (!resolver.isSupported(remoteAddress) || resolver.isResolved(remoteAddress)) { doConnect(remoteAddress, localAddress, promise); return promise; } final Future<SocketAddress> resolveFuture = resolver.resolve(remoteAddress); if (resolveFuture.isDone()) { final Throwable resolveFailureCause = resolveFuture.cause(); if (resolveFailureCause != null) { channel.close(); promise.setFailure(resolveFailureCause); } else { doConnect(resolveFuture.getNow(), localAddress, promise); } return promise; } resolveFuture.addListener(new FutureListener<SocketAddress>() { @Override public void operationComplete(Future<SocketAddress> future) throws Exception { if (future.cause() != null) { channel.close(); promise.setFailure(future.cause()); } else { doConnect(future.getNow(), localAddress, promise); } } }); } catch (Throwable cause) { promise.tryFailure(cause); } return promise; }
Source:
<code>public void convertWithCustomAvroSkipBytesConverter() { int offset = 2; byte[] simpleRecordAsOffsetBytes = Arrays.copyOfRange(simpleRecord1AsBytes, 5 - offset, simpleRecord1AsBytes.length); Schema schema = SimpleRecord.getClassSchema(); KafkaSerDe.AvroSkipBytesConverter conv = new KafkaSerDe.AvroSkipBytesConverter(schema, offset); <START> AvroGenericRecordWritable simpleRecord1Writable = conv.getWritable(simpleRecordAsOffsetBytes); Assert.assertNotNull(simpleRecord1Writable); Assert.assertEquals(SimpleRecord.class, simpleRecord1Writable.getRecord().getClass()); SimpleRecord simpleRecord1Deserialized = (SimpleRecord) simpleRecord1Writable.getRecord(); Assert.assertNotNull(simpleRecord1Deserialized); Assert.assertEquals(simpleRecord1, simpleRecord1Deserialized); <END> }</code><technical_language>This repeated code methods above. Refactor it</technical_language>

Target:
public void convertWithCustomAvroSkipBytesConverter() throws SerDeException { Integer offset = 2; int recordLength = simpleRecordConfluentBytes.length; byte[] simpleRecordAsOffsetBytes = Arrays.copyOfRange(simpleRecordConfluentBytes, 5 - offset, recordLength); Properties tbl = new Properties(); tbl.setProperty(AvroSerdeUtils.AvroTableProperties.AVRO_SERDE_TYPE.getPropName(), "SKIP"); tbl.setProperty(AvroSerdeUtils.AvroTableProperties.AVRO_SERDE_SKIP_BYTES.getPropName(), offset.toString()); runConversionTest(tbl, simpleRecordAsOffsetBytes); }
Source:
<code>public File(FileService svc, XmlDataHandler dh) { super(svc, dh); <START> authorEntry = new Author(getService(), new XmlDataHandler((Node)this.getDataHandler().getData(), <END> ConnectionsConstants.nameSpaceCtx, (XPathExpression)AtomXPath.author.getPath())); modifierEntry = new Modifier(getService(), new XmlDataHandler((Node)this.getDataHandler().getData(), ConnectionsConstants.nameSpaceCtx, (XPathExpression)AtomXPath.modifier.getPath())); }</code><technical_language>move specific getter instantiate this time a call is made</technical_language>

Target:
public File(FileService svc, XmlDataHandler dh) { super(svc, dh); }
Source:
<code>public RFC5424MessageConverter() { <START> this.parser = new RFC5424SyslogParser(); <END> }</code><technical_language>this(new RFC5424SyslogParser()); is minor live this</technical_language>

Target:
public RFC5424MessageConverter() { this(new RFC5424SyslogParser()); }
Source:
<code>public Set<String> getLoadedNetworkIds() { <START> if (cachedNetworks == null) return Collections.emptySet(); <END> else return cachedNetworks.asMap().keySet(); }</code><technical_language>Is this possible? createCache called in constructor, no</technical_language>

Target:
public Set<String> getLoadedNetworkIds() { return cache.asMap().keySet(); }
Source:
<code>public Builder(final String transactionalId, final long producerId, final short producerEpoch, final List<TopicPartition> partitions) { super(ApiKeys.ADD_PARTITIONS_TO_TXN); Map<String, List<Integer>> partitionMap = new HashMap<>(); for (TopicPartition topicPartition : partitions) { String topicName = topicPartition.topic(); <START> List<Integer> subPartitions = partitionMap.getOrDefault(topicName, <END> new ArrayList<>()); subPartitions.add(topicPartition.partition()); partitionMap.put(topicName, subPartitions); } AddPartitionsToTxnTopicCollection topics = new AddPartitionsToTxnTopicCollection(); for (Map.Entry<String, List<Integer>> partitionEntry : partitionMap.entrySet()) { topics.add(new AddPartitionsToTxnTopic() .setName(partitionEntry.getKey()) .setPartitions(partitionEntry.getValue())); } this.data = new AddPartitionsToTxnRequestData() .setTransactionalId(transactionalId) .setProducerId(producerId) .setProducerEpoch(producerEpoch) .setTopics(topics); }</code><technical_language>nit: map#compute replace getOrDefault + put</technical_language>

Target:
public Builder(final String transactionalId, final long producerId, final short producerEpoch, final List<TopicPartition> partitions) { super(ApiKeys.ADD_PARTITIONS_TO_TXN); Map<String, List<Integer>> partitionMap = new HashMap<>(); for (TopicPartition topicPartition : partitions) { String topicName = topicPartition.topic(); partitionMap.compute(topicName, (key, subPartitions) -> { if (subPartitions == null) { subPartitions = new ArrayList<>(); } subPartitions.add(topicPartition.partition()); return subPartitions; }); } AddPartitionsToTxnTopicCollection topics = new AddPartitionsToTxnTopicCollection(); for (Map.Entry<String, List<Integer>> partitionEntry : partitionMap.entrySet()) { topics.add(new AddPartitionsToTxnTopic() .setName(partitionEntry.getKey()) .setPartitions(partitionEntry.getValue())); } this.data = new AddPartitionsToTxnRequestData() .setTransactionalId(transactionalId) .setProducerId(producerId) .setProducerEpoch(producerEpoch) .setTopics(topics); }
Source:
<code>private void createBranch(final String textForBranch, boolean doCheckout, RevCommit commit, IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, UIText.FetchGerritChangePage_CreatingBranchTaskName, 10); CreateLocalBranchOperation bop = new CreateLocalBranchOperation( repository, textForBranch, commit); <START> bop.execute(progress.newChild(8)); <END> if (doCheckout) { CheckoutResult result; try { result = checkout(textForBranch, progress.newChild(1)); } catch (OperationCanceledException | InterruptedException e1) { return; } if (result.getStatus() == Status.CONFLICTS) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog( shell, UIText.BranchResultDialog_CheckoutConflictsTitle, UIText.AbstractRebaseCommandHandler_cleanupDialog_text, repository, result.getConflictList()); cleanupUncomittedChangesDialog.open(); if (cleanupUncomittedChangesDialog.shouldContinue()) { try { checkout(textForBranch, progress.newChild(1)); } catch (InterruptedException e) { Activator.logError(e.getMessage(), e); } } }); } else { progress.setWorkRemaining(0); } } monitor.worked(1); }</code><technical_language>Is creating local branch 80% of work? Typically checking out more time, it</technical_language>

Target:
private void createBranch(final String textForBranch, boolean doCheckout, RevCommit commit, IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, UIText.FetchGerritChangePage_CreatingBranchTaskName, 10); CreateLocalBranchOperation bop = new CreateLocalBranchOperation( repository, textForBranch, commit); bop.execute(progress.newChild(2)); if (doCheckout) { checkout(textForBranch, progress.newChild(8)); } monitor.worked(1); }
Source:
<code><START> public void handleGetStatusResponse(final com.alliander.osgp.dto.valueobjects.DeviceStatusDto deviceStatusDto, <END> final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleResponse for MessageType: {}", messageType); final GetStatusResponse response = new GetStatusResponse(); response.setOsgpException(exception); response.setResult(deviceResult); if (deviceResult == ResponseMessageResultType.NOT_OK || exception != null) { LOGGER.error("Device Response not ok.", exception); } else { final DeviceStatus status = this.domainCoreMapper.map(deviceStatusDto, DeviceStatus.class); try { final Device dev = this.deviceDomainService.searchDevice(deviceIdentification); if (LightMeasurementDevice.LMD_TYPE.equals(dev.getDeviceType())) { this.handleLmd(status, response); } else { this.handleSsld(deviceIdentification, status, response); } } catch (final FunctionalException e) { LOGGER.error("Caught FunctionalException", e); } } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(response.getResult()) .withOsgpException(response.getOsgpException()).withDataObject(response.getDeviceStatusMapped()) .build()); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Method 7 parameters, is greater 6 authorized. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public void handleGetStatusResponse(final com.alliander.osgp.dto.valueobjects.DeviceStatusDto deviceStatusDto, final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleResponse for MessageType: {}", messageType); final GetStatusResponse response = new GetStatusResponse(); response.setOsgpException(exception); response.setResult(deviceResult); if (deviceResult == ResponseMessageResultType.NOT_OK || exception != null) { LOGGER.error("Device Response not ok.", exception); } else { final DeviceStatus status = this.domainCoreMapper.map(deviceStatusDto, DeviceStatus.class); try { final Device dev = this.deviceDomainService.searchDevice(deviceIdentification); if (LightMeasurementDevice.LMD_TYPE.equals(dev.getDeviceType())) { this.handleLmd(status, response); } else { this.handleSsld(deviceIdentification, status, response); } } catch (final FunctionalException e) { LOGGER.error("Caught FunctionalException", e); } } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(response.getResult()) .withOsgpException(response.getOsgpException()).withDataObject(response.getDeviceStatusMapped()) .build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
<code>public void close() { if (network != null) { try { log.info(String.format("Removing network: %s", network.getName())); <START> dockerClient.removeNetworkCmd(network.getId()).exec(); <END> } catch (DockerException ex) { log.severe(String.format("Could not remove network: %s", network)); throw new EnvironmentException("Could not remove network: " + network, ex); } } if (dockerClient != null) { try { dockerClient.close(); } catch (IOException ex) { log.severe("Could not close docker client"); throw new EnvironmentException("Could not close docker client", ex); } } }</code><technical_language>Is a chance dockerClient null? a if-null a lines checking dockerClient. sense check well</technical_language>

Target:
public void close() { if (network != null) { try { log.info(String.format("Removing network: %s", network.getName())); dockerClient.removeNetworkCmd(network.getId()).exec(); } catch (DockerException ex) { log.severe(String.format("Could not remove network: %s", network)); throw new EnvironmentException("Could not remove network: " + network, ex); } } try { dockerClient.close(); } catch (IOException ex) { log.severe("Could not close docker client"); throw new EnvironmentException("Could not close docker client", ex); } }
Source:
<code>private synchronized boolean updateTables() { final List<String> tables; try { tables = JdbcUtils.getTables(cachedConnectionProvider.getValidConnection(), schemaPattern, tableTypes); log.debug("Got the following tables: " + Arrays.toString(tables.toArray())); } catch (SQLException e) { log.error("Error while trying to get updated table list, ignoring and waiting for next table poll interval", e); cachedConnectionProvider.closeQuietly(); return false; } final List<String> filteredTables; if (whitelist != null) { filteredTables = new ArrayList<>(tables.size()); for (String table : tables) { if (whitelist.contains(table)) { filteredTables.add(table); } } } else if (blacklist != null) { filteredTables = new ArrayList<>(tables.size()); for (String table : tables) { if (!blacklist.contains(table)) { filteredTables.add(table); } } } else { filteredTables = tables; } if (!filteredTables.equals(this.tables)) { if (filteredTables.isEmpty()) { <START> log.debug("Based on the supplied filtering rules, there are no matching tables to read from: "); <END> } else { log.debug("Based on the supplied filtering rules, the tables available to read from include: " + Arrays.toString(filteredTables.toArray())); } List<String> previousTables = this.tables; this.tables = filteredTables; notifyAll(); return previousTables != null; } return false; }</code><technical_language>Nit: need : end of this log message</technical_language>

Target:
private synchronized boolean updateTables() { final List<String> tables; try { tables = JdbcUtils.getTables(cachedConnectionProvider.getValidConnection(), schemaPattern, tableTypes); log.debug("Got the following tables: {}", tables); } catch (SQLException e) { log.error("Error while trying to get updated table list, ignoring and waiting for next table poll interval", e); cachedConnectionProvider.closeQuietly(); return false; } final List<String> filteredTables; if (whitelist != null) { filteredTables = new ArrayList<>(tables.size()); for (String table : tables) { if (whitelist.contains(table)) { filteredTables.add(table); } } } else if (blacklist != null) { filteredTables = new ArrayList<>(tables.size()); for (String table : tables) { if (!blacklist.contains(table)) { filteredTables.add(table); } } } else { filteredTables = tables; } if (!filteredTables.equals(this.tables)) { if (filteredTables.isEmpty()) { log.debug("Based on the supplied filtering rules, there are no matching tables to read from"); } else { log.debug("Based on the supplied filtering rules, the tables available to read from include: {}", tables); } List<String> previousTables = this.tables; this.tables = filteredTables; notifyAll(); return previousTables != null; } return false; }
Source:
<code>public Mono<Void> runAsync() { CompletableFuture<Void> completeTask = CompletableFuture.runAsync(() -> { }); return Mono.fromFuture(receiver.receiveBatchAsync(options.getMessagesToReceive()) .thenComposeAsync(iMessages -> { for (IMessage message : iMessages) { <START> completeTask.thenComposeAsync(ignore -> receiver.completeAsync(message.getLockToken())); <END> } return completeTask; })); }</code><technical_language>This is a danging async operation. wait is complete. check other instances of this</technical_language>

Target:
public Mono<Void> runAsync() { return Mono.fromFuture(receiver.receiveBatchAsync(options.getMessagesToReceive()) .thenComposeAsync(iMessages -> CompletableFuture.allOf(iMessages .stream() .map(x -> receiver.completeAsync(x.getLockToken())).toArray(CompletableFuture[]::new)))); }
Source:
<code>public long symbolCharsAddressOf(int symbolIndex) { if (symbolIndex < symbolCount) { long offset = offsetMem.getLong(SymbolMapWriter.keyToOffset(symbolIndex)); return charMem.addressOf(offset); <START> } else if (symbolIndex == symbolCount) { <END> long offset = offsetMem.getLong(SymbolMapWriter.keyToOffset(symbolCount - 1)); long symLen = charMem.getInt(offset); offset += symLen * Character.BYTES + Integer.BYTES; return charMem.addressOf(offset); } return -1; }</code><technical_language>For "overflown" symbol index return high address of underlying memory</technical_language>

Target:
public long symbolCharsAddressOf(int symbolIndex) { if (symbolIndex < symbolCount) { long offset = offsetMem.getLong(SymbolMapWriter.keyToOffset(symbolIndex)); return charMem.addressOf(offset); } else if (symbolIndex == symbolCount) { return charMem.addressOf(charMem.getGrownLength()); } return -1; }
Source:
<code>public DistributedControlTransportOptionHandler(CmdLineParser parser, OptionDef option, Setter<String> setter) throws IOException { <START> super(parser, option, setter, "classpath*:/META-INF/spring-xd/transports/*-admin.xml"); <END> }</code><technical_language>a private constant for common prefix ("classpath*:/META-INF/spring-xd") duplicate for of</technical_language>

Target:
public DistributedControlTransportOptionHandler(CmdLineParser parser, OptionDef option, Setter<String> setter) throws IOException { super(parser, option, setter, CONFIGURATION_ROOT + "transports/*-admin.xml"); }
Source:
<code><START> public <T extends Obj> ObjUpdateException(T obj, Throwable cause) { <END> super("Can't update metadata object: " + obj.getClass().getSimpleName(), cause); }</code><technical_language>Updatable well</technical_language>

Target:
public <T extends Updatable> ObjUpdateException(T obj, Throwable cause) { super("Can't update metadata object: " + obj.getClass().getSimpleName(), cause); }
Source:
<code>public void setUp() throws Exception { super.setUp(); <START> if (USE_DOMAIN_SOCKETS) { <END> assertTrue("Native transport not enabled", USE_NATIVE_TRANSPORT); tmp = TestUtils.tmpFile("vertx", ".sock"); testAddress = SocketAddress.domainSocketAddress(tmp.getAbsolutePath()); } else { testAddress = SocketAddress.inetSocketAddress(1234, "localhost"); } testDir = testFolder.newFolder(); }</code><technical_language>need this work HTTP server domain sockets HTTP client, a simple test is necessary</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); testDir = testFolder.newFolder(); }
Source:
<code>public Response createAssignment(RoleAssignmentDTO ra, @PathParam("identifier") String id, @QueryParam("key") String apiKey) { try { Dataset dataset = findDatasetOrDie(id); RoleAssignee assignee = findAssignee(ra.getAssignee()); if (assignee == null) { return error(Response.Status.BAD_REQUEST, "Assignee not found"); } DataverseRole theRole; Dataverse dv = dataset.getOwner(); theRole = null; while ((theRole == null) && (dv != null)) { for (DataverseRole aRole : rolesSvc.availableRoles(dv.getId())) { if (aRole.getAlias().equals(ra.getRole())) { theRole = aRole; break; } } dv = dv.getOwner(); } if (theRole == null) { <START> return error(Status.BAD_REQUEST, "Can't find role named '" + ra.getRole() + "' in dataverse " + dataset.getOwner()); <END> } String privateUrlToken = null; return ok( json(execCommand(new AssignRoleCommand(assignee, theRole, dataset, createDataverseRequest(findUserOrDie()), privateUrlToken)))); } catch (WrappedResponse ex) { logger.log(Level.WARNING, "Can''t create assignment: {0}", ex.getMessage()); return ex.getResponse(); } }</code><technical_language>I new-ish rule is touch APIs put English in a bundle</technical_language>

Target:
public Response createAssignment(RoleAssignmentDTO ra, @PathParam("identifier") String id, @QueryParam("key") String apiKey) { try { Dataset dataset = findDatasetOrDie(id); RoleAssignee assignee = findAssignee(ra.getAssignee()); if (assignee == null) { return error(Response.Status.BAD_REQUEST, BundleUtil.getStringFromBundle("datasets.api.grant.role.assignee.not.found.error")); } DataverseRole theRole; Dataverse dv = dataset.getOwner(); theRole = null; while ((theRole == null) && (dv != null)) { for (DataverseRole aRole : rolesSvc.availableRoles(dv.getId())) { if (aRole.getAlias().equals(ra.getRole())) { theRole = aRole; break; } } dv = dv.getOwner(); } if (theRole == null) { List<String> args = Arrays.asList(ra.getRole(), dataset.getOwner().getDisplayName()); return error(Status.BAD_REQUEST, BundleUtil.getStringFromBundle("datasets.api.grant.role.not.found.error", args)); } String privateUrlToken = null; return ok( json(execCommand(new AssignRoleCommand(assignee, theRole, dataset, createDataverseRequest(findUserOrDie()), privateUrlToken)))); } catch (WrappedResponse ex) { List<String> args = Arrays.asList(ex.getMessage()); logger.log(Level.WARNING, BundleUtil.getStringFromBundle("datasets.api.grant.role.cant.create.assignment.error", args)); return ex.getResponse(); } }
Source:
<code>public void run() { try { try { log.debug("Start event notification service iteration"); firstMatchSimpleFilter.clearFilterEntries(); firstMatchSimpleFilter.addFilterEntries(eventsManager.getAuditLogEventSubscribers()); firstMatchSimpleFilter.addFilterEntries( configurationFilters ); String dbDownSubscribers = prop.getProperty(NotificationProperties.FAILED_QUERIES_NOTIFICATION_RECIPIENTS, true); if (!StringUtils.isEmpty(dbDownSubscribers)) { for (String subscriber : dbDownSubscribers.split(",")) { FilterEntry.createEntry( EventsManager.DATABASE_UNREACHABLE, false, EventNotificationMethod.EMAIL.name(), subscriber); } <START> } <END> for (AuditLogEvent event : eventsManager.getAuditLogEvents()) { firstMatchSimpleFilter.processEvent(event); eventsManager.updateAuditLogEventProcessed(event.getId()); } deleteObsoleteHistoryData(); log.debug("Finished event notification service iteration"); } catch (SQLException se) { distributeDbDownEvent(); throw se; } } catch (Throwable t) { log.error(String.format("Failed to run the service."), t); } }</code><technical_language>this configurationFilters filtered exclude *</technical_language>

Target:
public void run() { try { try { log.debug("Start event notification service iteration"); firstMatchSimpleFilter.clearFilterEntries(); firstMatchSimpleFilter.addFilterEntries(eventsManager.getAuditLogEventSubscribers()); String dbDownSubscribers = prop.getProperty(NotificationProperties.FAILED_QUERIES_NOTIFICATION_RECIPIENTS, true); if (!StringUtils.isEmpty(dbDownSubscribers)) { for (String subscriber : dbDownSubscribers.split(",")) { new FirstMatchSimpleFilter.FilterEntry( EventsManager.DATABASE_UNREACHABLE, false, EventNotificationMethod.EMAIL.name(), subscriber); } } firstMatchSimpleFilter.addFilterEntries( configurationFilters ); for (AuditLogEvent event : eventsManager.getAuditLogEvents()) { firstMatchSimpleFilter.processEvent(event); eventsManager.updateAuditLogEventProcessed(event.getId()); } deleteObsoleteHistoryData(); log.debug("Finished event notification service iteration"); } catch (SQLException se) { distributeDbDownEvent(); throw se; } } catch (Throwable t) { log.error(String.format("Failed to run the service."), t); } }
Source:
<code>public NutchJob(Configuration conf) throws IOException { <START> super(conf, "NutchJob"); <END> }</code><technical_language>this Job named "NutchJob"</technical_language>

Target:
public NutchJob(Configuration conf) { super(conf, NutchJob.class); }
Source:
<code>AttributeMapping(String searchDn, String filter, String ldapName) { Assert.checkNotNullParam("ldapName", ldapName); this.searchDn = searchDn; this.filter = filter; <START> this.ldapName = ldapName.toUpperCase(Locale.ENGLISH); <END> }</code><technical_language>Locale.ROOT</technical_language>

Target:
AttributeMapping(String searchDn, String filter, String ldapName) { Assert.checkNotNullParam("ldapName", ldapName); this.searchDn = searchDn; this.filter = filter; this.ldapName = ldapName.toUpperCase(Locale.ROOT); }
Source:
<code>public void getEventsForTransactionsReturnsSnapshotWithOldEvents() { setupInitialState(); eventCache.processGetCommitTimestampsUpdate(COMMIT_UPDATE, SUCCESS); eventCache.removeTransactionStateFromCache(START_TS); verifyStage(); eventCache.processStartTransactionsUpdate(TIMESTAMPS_2, SUCCESS_2); verifyStage(); TransactionsLockWatchUpdate results = eventCache.getUpdateForTransactions(TIMESTAMPS_2, Optional.empty()); assertThat(results.clearCache()).isTrue(); assertThat(results.startTsToSequence()).containsExactlyInAnyOrderEntriesOf( ImmutableMap.of(16L, LockWatchVersion.of(LEADER, 7L))); assertThat(results.events()).containsExactly( LockWatchCreatedEvent.builder(ImmutableSet.of(REFERENCE), <START> ImmutableSet.of(DESCRIPTOR, DESCRIPTOR_2)).build(4L), <END> UNLOCK_EVENT, LOCK_EVENT, LOCK_EVENT_2); }</code><technical_language>assuming this is of no-compression this change in next PR</technical_language>

Target:
public void getEventsForTransactionsReturnsSnapshotWithOldEvents() { eventCache = createEventCache(3); setupInitialState(); eventCache.processGetCommitTimestampsUpdate(COMMIT_UPDATE, SUCCESS); eventCache.removeTransactionStateFromCache(START_TS); verifyStage(); eventCache.processStartTransactionsUpdate(TIMESTAMPS_2, SUCCESS_2); verifyStage(); TransactionsLockWatchUpdate results = eventCache.getUpdateForTransactions(TIMESTAMPS_2, Optional.empty()); assertThat(results.clearCache()).isTrue(); assertThat(results.startTsToSequence()).containsExactlyInAnyOrderEntriesOf( ImmutableMap.of(16L, LockWatchVersion.of(LEADER, 7L))); assertThat(results.events()).containsExactly( LockWatchCreatedEvent.builder(ImmutableSet.of(REFERENCE), ImmutableSet.of(DESCRIPTOR, DESCRIPTOR_2)).build(4L), UNLOCK_EVENT, LOCK_EVENT, LOCK_EVENT_2); }
Source:
<code>public synchronized JsonElement callMethod(SonyAudioMethod method) throws IOException { try { method.id = nextMessageId; String message = mapper.toJson(method); commandLatch = new CountDownLatch(1); commandResponse = null; nextMessageId++; sendMessage(message); if (commandLatch.await(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { logger.debug("callMethod returns {}", commandResponse.toString()); return commandResponse.get("result"); } else { <START> logger.error("Timeout during callMethod({}, {})", method.method, message); <END> throw new IOException("Timeout during callMethod"); } } catch (Exception e) { throw new IOException("Error during callMethod", e); } }</code><technical_language>Wait, if get due a timeout, I consider this a "normal" situation a software bug - therefore, log debug status ends OFFLINE message</technical_language>

Target:
public synchronized JsonElement callMethod(SonyAudioMethod method) throws IOException { try { method.id = nextMessageId; String message = mapper.toJson(method); logger.debug("callMethod send {}", message); commandLatch = new CountDownLatch(1); commandResponse = null; nextMessageId++; sendMessage(message); if (commandLatch.await(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { logger.debug("callMethod returns {}", uri.toString(), commandResponse.toString()); return commandResponse.get("result"); } else { logger.debug("Timeout during callMethod({}, {})", method.method, message); throw new IOException("Timeout during callMethod"); } } catch (InterruptedException e) { throw new IOException("Timeout in callMethod"); } }
Source:
<code>public List<SQLNotNullConstraint> getNotNullConstraints(String db_name, String tbl_name) throws MetaException { try { return getNotNullConstraintsInternal(db_name, tbl_name, true, true); } catch (NoSuchObjectException e) { <START> throw new MetaException(e.getMessage()); <END> } }</code><technical_language>instead of e.getMessage() org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable) capture full stack trace</technical_language>

Target:
public List<SQLNotNullConstraint> getNotNullConstraints(String db_name, String tbl_name) throws MetaException { try { return getNotNullConstraintsInternal(db_name, tbl_name, true, true); } catch (NoSuchObjectException e) { throw new MetaException(ExceptionUtils.getStackTrace(e)); } }
Source:
<code>public synchronized void dropView(final String view) throws DatabaseEngineException { Statement drop = null; try { drop = conn.createStatement(); final String query = format("DROP VIEW %s", quotize(view, escapeCharacter())); logger.trace(query); drop.executeUpdate(query); } catch (final SQLException ex) { throw new DatabaseEngineException("Error dropping view", ex); } finally { try { if (drop != null) { <START> drop.close(); <END> } } catch (final Exception e) { logger.trace("Error closing statement.", e); } } }</code><technical_language>try-with-resources is a cleaner safer close resources</technical_language>

Target:
public synchronized void dropView(final String view) throws DatabaseEngineException { try (final Statement statement = conn.createStatement()) { final String query = format("DROP VIEW %s", quotize(view, escapeCharacter())); logger.trace(query); statement.executeUpdate(query); } catch (final SQLException ex) { throw new DatabaseEngineException("Error dropping view", ex); } }
Source:
<code>public Collection<Class<? extends DataProvider>> getRequiredDataProviders(String identifier) { StepEngineSettings.VisualizationSetting settings = visualizationSettingsMap.get(identifier); String visualizationClassName = settings.getVisualizationClassName(); <START> return StreamSupport.stream(ServiceLoader.load(Visualization.Factory.class).spliterator(), false) .filter(factory -> visualizationClassName.equals(factory.getVisualizationClass().getName())) .findFirst().orElseThrow(() -> new RuntimeException("Failed: No Visualization.Factory found for " + identifier + " and " + visualizationClassName) ).getRequiredDataProviders(settings); <END> }</code><technical_language>extract locating Visualization.Factory another method is in getVisualizationInternal well</technical_language>

Target:
public Collection<Class<? extends DataProvider>> getRequiredDataProviders(String identifier) { StepEngineSettings.VisualizationSetting settings = visualizationSettingsMap.get(identifier); String visualizationClassName = settings.getVisualizationClassName(); return getVisualizationFactory(identifier, visualizationClassName).getRequiredDataProviders(settings); }
Source:
<code>public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { UpdatePartitionColumnStatMessage upcsm = deserializer.getUpdatePartitionColumnStatMessage(context.dmd.getPayload()); ColumnStatistics colStats = upcsm.getColumnStatistics(); ColumnStatisticsDesc colStatsDesc = colStats.getStatsDesc(); <START> colStatsDesc.setDbName(context.dbName); <END> if (!context.isTableNameEmpty()) { colStatsDesc.setTableName(context.tableName); } if (!context.isDbNameEmpty()) { updatedMetadata.set(context.dmd.getEventTo().toString(), context.dbName, context.tableName, null); } return Collections.singletonList(TaskFactory.get(new ColumnStatsUpdateWork(colStats), context.hiveConf)); }</code><technical_language>Need set if !context.isDbNameEmpty()</technical_language>

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { UpdatePartitionColumnStatMessage upcsm = deserializer.getUpdatePartitionColumnStatMessage(context.dmd.getPayload()); ColumnStatistics colStats = upcsm.getColumnStatistics(); ColumnStatisticsDesc colStatsDesc = colStats.getStatsDesc(); if (!context.isTableNameEmpty()) { colStatsDesc.setTableName(context.tableName); } if (!context.isDbNameEmpty()) { colStatsDesc.setDbName(context.dbName); updatedMetadata.set(context.dmd.getEventTo().toString(), context.dbName, context.tableName, null); } return Collections.singletonList(TaskFactory.get(new ColumnStatsUpdateWork(colStats), context.hiveConf)); }
Source:
<code>public ImmutableBoundedValue<Double> walkSpeed() { <START> return new ImmutableSpongeBoundedValue<>(Keys.WALKING_SPEED, this.walkSpeed, 0.1d, doubleComparator(), Double.MIN_VALUE, Double.MAX_VALUE); <END> }</code><technical_language>send this instance variable return it</technical_language>

Target:
public ImmutableBoundedValue<Double> walkSpeed() { return walkSpeedValue; }
Source:
<code>public void variables() throws Exception { List<String> arrayList = new ArrayList<>(); arrayList.add("bar"); arrayList.add("zip"); CoreEvent in = eventBuilder(muleContext).message(of(arrayList)).build(); process(simpleForeach, in); assertSimpleProcessedMessages(); assertThat(variables.keySet(), hasSize(2)); assertThat(variables.keySet(), hasItems(DEFAULT_ROOT_MESSAGE_VARIABLE, DEFAULT_COUNTER_VARIABLE)); assertThat(variables.get(DEFAULT_ROOT_MESSAGE_VARIABLE).getDataType(), is(assignableTo(MULE_MESSAGE))); assertThat(variables.get(DEFAULT_ROOT_MESSAGE_VARIABLE).getValue(), equalTo(in.getMessage())); assertThat(variables.get(DEFAULT_COUNTER_VARIABLE).getDataType(), <START> equalTo(DataType.builder().type(Number.class).build())); <END> assertThat(variables.get(DEFAULT_COUNTER_VARIABLE).getValue(), equalTo(2)); }</code><technical_language>constant for NUMBER instead of building</technical_language>

Target:
public void variables() throws Exception { List<String> arrayList = new ArrayList<>(); arrayList.add("bar"); arrayList.add("zip"); CoreEvent in = eventBuilder(muleContext).message(of(arrayList)).build(); process(simpleForeach, in); assertSimpleProcessedMessages(); assertThat(variables.keySet(), hasSize(2)); assertThat(variables.keySet(), hasItems(DEFAULT_ROOT_MESSAGE_VARIABLE, DEFAULT_COUNTER_VARIABLE)); assertThat(variables.get(DEFAULT_ROOT_MESSAGE_VARIABLE).getDataType(), is(assignableTo(MULE_MESSAGE))); assertThat(variables.get(DEFAULT_ROOT_MESSAGE_VARIABLE).getValue(), equalTo(in.getMessage())); assertThat(variables.get(DEFAULT_COUNTER_VARIABLE).getDataType(), equalTo(NUMBER)); assertThat(variables.get(DEFAULT_COUNTER_VARIABLE).getValue(), equalTo(2)); }
Source:
<code>private void handleSelectorEvents(List<ResponseInfo> responseInfoList) { <START> logger.trace("Handling selector events at " + time.milliseconds()); <END> for (String connId : selector.connected()) { logger.trace("Checking in connection back to connection tracker for connectionId " + connId); connectionTracker.checkInConnection(connId); } for (String connId : selector.disconnected()) { logger.trace( "Connection disconnected for connectionId " + connId + " and hence removing it from connection tracker"); connectionTracker.removeConnection(connId); RequestMetadata requestMetadata = connectionIdToRequestInFlight.remove(connId); if (requestMetadata != null) { responseInfoList.add( new ResponseInfo(requestMetadata.requestInfo.getRequest(), NetworkClientErrorCode.NetworkError, null)); } } for (NetworkReceive recv : selector.completedReceives()) { String connId = recv.getConnectionId(); logger.trace("Receive completed for connectionId " + connId + " and checking in the connection back to connection tracker"); connectionTracker.checkInConnection(connId); RequestMetadata requestMetadata = connectionIdToRequestInFlight.remove(connId); responseInfoList.add( new ResponseInfo(requestMetadata.requestInfo.getRequest(), null, recv.getReceivedBytes().getPayload())); requestMetadata.onResponseReceive(); } }</code><technical_language>useful I</technical_language>

Target:
private void handleSelectorEvents(List<ResponseInfo> responseInfoList) { for (String connId : selector.connected()) { logger.trace("Checking in connection back to connection tracker for connectionId ", connId); connectionTracker.checkInConnection(connId); } for (String connId : selector.disconnected()) { logger.trace("Connection disconnected for connectionId and hence removing it from connection tracker", connId); connectionTracker.removeConnection(connId); RequestMetadata requestMetadata = connectionIdToRequestInFlight.remove(connId); if (requestMetadata != null) { responseInfoList.add( new ResponseInfo(requestMetadata.requestInfo.getRequest(), NetworkClientErrorCode.NetworkError, null)); } } for (NetworkReceive recv : selector.completedReceives()) { String connId = recv.getConnectionId(); logger.trace("Receive completed for connectionId and checking in the connection back to connection tracker", connId); connectionTracker.checkInConnection(connId); RequestMetadata requestMetadata = connectionIdToRequestInFlight.remove(connId); responseInfoList.add( new ResponseInfo(requestMetadata.requestInfo.getRequest(), null, recv.getReceivedBytes().getPayload())); requestMetadata.onResponseReceive(); } }
Source:
<code>public void doubleClickTest() throws Exception { iface.go("<LINK_0>"); WebDriverElement dbClickButton = iface.getWebDriverElement(new Hook(Strategy.ID, "buttonId")); dbClickButton.doubleClick(); <START> Assert.assertTrue(iface.isDialogVisible()); <END> }</code><technical_language>Do need clear this alert afterward blocking next test</technical_language>

Target:
public void doubleClickTest() throws Exception { iface.go("<LINK_0>"); WebDriverElement dbClickButton = iface.getWebDriverElement(new Hook(Strategy.ID, "buttonId")); dbClickButton.doubleClick(); Assert.assertTrue(iface.isDialogVisible()); iface.acceptDialog(); }
Source:
<code>public RequestBuilder buildRequest(Api api) { <START> return api.action("query") <END> .param("list", "random") .param("rnnamespace", "0") .param("rnlimit", "10"); }</code><technical_language>Hint: if "generator=random" "prop=pageprops" "ppprop=wikibase_item", get wikidata ID right random titles</technical_language>

Target:
public RequestBuilder buildRequest(Api api) { return api.action("query") .param("prop","pageprops|pageimages") .param("ppprop","wikibase_item") .param("pithumbsize", "144") .param("pilimit", "10") .param("generator", "random") .param("grnnamespace", "0") .param("grnlimit", "10"); }
Source:
<code><START> public Optional<List<SingularityMesosArtifact>> getExtraArtifacts() { <END> return extraArtifacts; }</code><technical_language>Instead of passing Optional lists around, default empty list if constructor arg is null. for other objects this. save a lot of isPresent throw</technical_language>

Target:
public List<SingularityMesosArtifact> getExtraArtifacts() { return extraArtifacts; }
Source:
<code>private void setParentOverflow(Element e, Style.Overflow visible) { if (e != null && <START> e != asWidget().getElement()) { <END> e.getParentElement().getStyle().setOverflow(visible); setParentOverflow(e.getParentElement(), visible); } }</code><technical_language>Is safe do a reference comparison instead of i.e., "equals" IDs</technical_language>

Target:
private void setParentOverflow(Element e, Style.Overflow visible) { if (e != null && !e.equals(asWidget().getElement())) { e.getParentElement().getStyle().setOverflow(visible); setParentOverflow(e.getParentElement(), visible); } }
Source:
<code>protected <START> Control createControl(Composite <END> parent) { toolbar = new FindToolbar(parent); toolbar.setBackground(null); toolbar.addKeyListener(keyListener); toolbar.addListener(SWT.FocusIn, mouseListener); toolbar.addListener(SWT.FocusOut, mouseListener); toolbar.addListener(SWT.MouseDown, mouseListener); toolbar.addListener(SWT.MouseUp, mouseListener); toolbar.addListener(SWT.Modify, (e) -> lastText = toolbar.getText()); toolbar.addSelectionListener(selectionListener); toolbar.addStatusListener(this::showStatus); boolean hasInput = provider != null; if (hasInput) { setInput(provider); } if (lastText != null) { if (lastSearchContext != null && lastSearchContext.equals(searchContext)) { toolbar.setPreselect(lastObjectId); } toolbar.setText(lastText, hasInput); } lastSearchContext = null; lastObjectId = null; if (wasVisible) { return toolbar; } wasVisible = true; toolbar.getDisplay().asyncExec(new Runnable() { @Override public void run() { if (toolbar != null && !toolbar.isDisposed()) { graph.getControl().setFocus(); toolbar.setFocus(); } } }); GridDataFactory.fillDefaults().grab(true, false).applyTo(toolbar); return toolbar; }</code><technical_language>a covariant override here? protected FindToolbar createControl(Composite parent) ? a subclass add listeners if a Control. bring benefits</technical_language>

Target:
protected FindToolbar createControl(Composite parent) { toolbar = new FindToolbar(parent); toolbar.setBackground(null); toolbar.addListener(SWT.Modify, (e) -> lastText = toolbar.getText()); toolbar.addSelectionListener(selectionListener); toolbar.addStatusListener(this::showStatus); boolean hasInput = provider != null; if (hasInput) { setInput(provider); } if (lastText != null) { if (lastSearchContext != null && lastSearchContext.equals(searchContext)) { toolbar.setPreselect(lastObjectId); } toolbar.setText(lastText, hasInput); } lastSearchContext = null; lastObjectId = null; GridDataFactory.fillDefaults().grab(true, false).applyTo(toolbar); return toolbar; }
Source:
<code>public Notification build() { NotificationCompat.Builder notification = new NotificationCompat.Builder(context, NotificationUtils.CHANNEL_ID_PLAYING); if (playable != null) { <START> notification.setContentTitle(Html.fromHtml("<b>" + playable.getFeedTitle() + "</b>")); <END> notification.setContentText(playable.getEpisodeTitle()); addActions(notification, mediaSessionToken, playerStatus, isCasting); if (icon != null) { notification.setLargeIcon(icon); } else { notification.setLargeIcon(getDefaultIcon()); } if (Build.VERSION.SDK_INT < 29) { notification.setSubText(position); } } else { notification.setContentTitle(context.getString(R.string.app_name)); notification.setContentText("Loading. If this does not go away, play any episode and contact us."); } notification.setContentIntent(getPlayerActivityPendingIntent()); notification.setWhen(0); notification.setSmallIcon(R.drawable.ic_antenna); notification.setOngoing(false); notification.setOnlyAlertOnce(true); notification.setShowWhen(false); notification.setPriority(UserPreferences.getNotifyPriority()); notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); notification.setColor(NotificationCompat.COLOR_DEFAULT); return notification.build(); }</code><technical_language>honest, I default here. more consistent rest of system</technical_language>

Target:
public Notification build() { NotificationCompat.Builder notification = new NotificationCompat.Builder(context, NotificationUtils.CHANNEL_ID_PLAYING); if (playable != null) { notification.setContentTitle(playable.getFeedTitle()); notification.setContentText(playable.getEpisodeTitle()); addActions(notification, mediaSessionToken, playerStatus, isCasting); if (icon != null) { notification.setLargeIcon(icon); } else { notification.setLargeIcon(getDefaultIcon()); } if (Build.VERSION.SDK_INT < 29) { notification.setSubText(position); } } else { notification.setContentTitle(context.getString(R.string.app_name)); notification.setContentText("Loading. If this does not go away, play any episode and contact us."); } notification.setContentIntent(getPlayerActivityPendingIntent()); notification.setWhen(0); notification.setSmallIcon(R.drawable.ic_antenna); notification.setOngoing(false); notification.setOnlyAlertOnce(true); notification.setShowWhen(false); notification.setPriority(UserPreferences.getNotifyPriority()); notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); notification.setColor(NotificationCompat.COLOR_DEFAULT); return notification.build(); }
Source:
<code>public static Expression rewrite(Expression expression, Session session, Metadata metadata, SqlParser sqlParser, SymbolAllocator symbolAllocator) { requireNonNull(metadata, "metadata is null"); requireNonNull(sqlParser, "sqlParser is null"); if (expression instanceof SymbolReference) { return expression; } <START> if (expression instanceof LambdaExpression) { <END> LambdaExpression lambdaExpression = (LambdaExpression) expression; return new LambdaExpression(lambdaExpression.getArguments(), rewrite(lambdaExpression.getBody(), session, metadata, sqlParser, symbolAllocator)); } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, sqlParser, symbolAllocator.getTypes(), expression, emptyList(), WarningCollector.NOOP); return rewrite(expression, expressionTypes); }</code><technical_language>@wenleix provide a idea this. In general, need integrate this ExpressionAnalyzer avoid specialization getExpressionTypes</technical_language>

Target:
public static Expression rewrite(Expression expression, Session session, Metadata metadata, SqlParser sqlParser, SymbolAllocator symbolAllocator) { requireNonNull(metadata, "metadata is null"); requireNonNull(sqlParser, "sqlParser is null"); if (expression instanceof SymbolReference) { return expression; } return new AnalyzedExpressionRewriter(session, metadata, sqlParser, symbolAllocator.getTypes()).rewriteWith(Visitor::new, expression); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Basemap.createImageryWithLabels()); mMapView.setMap(map); <START> requestReadPermission(); <END> }</code><technical_language>If this sample is displaying data a URL need read_external_storage permissions</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Type.DARK_GRAY_CANVAS_VECTOR, 51.960403, 10.029217, 5); mMapView.setMap(map); KmlDataset kmlDataset = new KmlDataset(getString(R.string.kml_url)); kmlDataset.addKmlNetworkLinkMessageReceivedListener(kmlNetworkLinkMessageReceivedEvent -> { String message = "KML Network Link Message: " + kmlNetworkLinkMessageReceivedEvent.getMessage(); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); Log.i(TAG, message); }); KmlLayer kmlLayer = new KmlLayer(kmlDataset); mMapView.getMap().getOperationalLayers().clear(); mMapView.getMap().getOperationalLayers().add(kmlLayer); kmlDataset.addDoneLoadingListener(() -> { if (kmlDataset.getLoadStatus() != LoadStatus.LOADED) { String error = "Failed to load kml layer from URL: " + kmlDataset.getLoadError().getMessage(); Toast.makeText(this, error, Toast.LENGTH_LONG).show(); Log.e(TAG, error); } }); }
Source:
<code>public TaskStatus process() { while (true) { if (stopped) { return TaskStatus.finished(); } CompletableFuture<?> future; taskExecutionLock.readLock().lock(); try { future = loadSplits(); } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped); <START> continue; <END> } finally { taskExecutionLock.readLock().unlock(); } invokeNoMoreSplitsIfNecessary(); if (!future.isDone()) { return TaskStatus.continueOn(future); } } }</code><technical_language>return a finished future instead of looping</technical_language>

Target:
public TaskStatus process() { while (true) { if (stopped) { return TaskStatus.finished(); } CompletableFuture<?> future; taskExecutionLock.readLock().lock(); try { future = loadSplits(); } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped); return TaskStatus.finished(); } finally { taskExecutionLock.readLock().unlock(); } invokeNoMoreSplitsIfNecessary(); if (!future.isDone()) { return TaskStatus.continueOn(future); } } }