auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Status update(String table, String key, Map<String, ByteIterator> values) { try { Set<String> fields = values.keySet(); PreparedStatement stmt = updateStmts.get(fields); if (stmt == null) { Update updateStmt = QueryBuilder.update(table); for (String field : fields) { updateStmt.with(QueryBuilder.set(field, QueryBuilder.bindMarker())); } updateStmt.where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker())); stmt = session.prepare(updateStmt); stmt.setConsistencyLevel(writeConsistencyLevel); if (trace) { stmt.enableTracing(); } PreparedStatement prevStmt = updateStmts.putIfAbsent(new HashSet(fields), stmt); if (prevStmt != null) { stmt = prevStmt; } } if (logger.isDebugEnabled()) { logger.debug(stmt.getQueryString()); logger.debug("key = {}", key); for (Map.Entry<String, ByteIterator> entry : values.entrySet()) { logger.debug("{} = {}", entry.getKey(), entry.getValue()); } } ColumnDefinitions vars = stmt.getVariables(); BoundStatement boundStmt = stmt.bind(); for (int i = 0; i < vars.size() - 1; i++) { boundStmt.setString(i, values.get(vars.getName(i)).toString()); } boundStmt.setString(vars.size() - 1, key); session.execute(boundStmt); return Status.OK; } catch (Exception e) { <START> e.printStackTrace(); <END> } return Status.ERROR; }</code><technical_language>this a logger call passes exception a final unbound argument</technical_language>

Target:
public Status update(String table, String key, Map<String, ByteIterator> values) { try { Set<String> fields = values.keySet(); PreparedStatement stmt = updateStmts.get(fields); if (stmt == null) { Update updateStmt = QueryBuilder.update(table); for (String field : fields) { updateStmt.with(QueryBuilder.set(field, QueryBuilder.bindMarker())); } updateStmt.where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker())); stmt = session.prepare(updateStmt); stmt.setConsistencyLevel(writeConsistencyLevel); if (trace) { stmt.enableTracing(); } PreparedStatement prevStmt = updateStmts.putIfAbsent(new HashSet(fields), stmt); if (prevStmt != null) { stmt = prevStmt; } } if (logger.isDebugEnabled()) { logger.debug(stmt.getQueryString()); logger.debug("key = {}", key); for (Map.Entry<String, ByteIterator> entry : values.entrySet()) { logger.debug("{} = {}", entry.getKey(), entry.getValue()); } } ColumnDefinitions vars = stmt.getVariables(); BoundStatement boundStmt = stmt.bind(); for (int i = 0; i < vars.size() - 1; i++) { boundStmt.setString(i, values.get(vars.getName(i)).toString()); } boundStmt.setString(vars.size() - 1, key); session.execute(boundStmt); return Status.OK; } catch (Exception e) { logger.error(MessageFormatter.format("Error updating key: {}", key).getMessage(), e); } return Status.ERROR; }
Source:
<code>public void accept(PubSubMessage pubSubMessage, Context context) { OcrTranslateApiMessage ocrMessage = OcrTranslateApiMessage.fromPubsubData( pubSubMessage.data.getBytes()); String text = ocrMessage.getText(); String filename = ocrMessage.getFilename(); <START> String lang = ocrMessage.getLang(); <END> LOGGER.info("Received request to save file " + filename); String newFileName = String.format("%s_to_%s.txt", filename, lang); END functions_ocr_rename] LOGGER.info(String.format("Saving result to %s in bucket %s", newFileName, RESULT_BUCKET)); BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(RESULT_BUCKET, newFileName)).build(); storage.create(blobInfo, text.getBytes()); LOGGER.info("File saved"); }</code><technical_language>reason inline variables</technical_language>

Target:
public void accept(PubSubMessage pubSubMessage, Context context) { OcrTranslateApiMessage ocrMessage = OcrTranslateApiMessage.fromPubsubData( pubSubMessage.data.getBytes(StandardCharsets.UTF_8)); LOGGER.info("Received request to save file " + ocrMessage.getFilename()); String newFileName = String.format( "%s_to_%s.txt", ocrMessage.getFilename(), ocrMessage.getLang()); END functions_ocr_rename] LOGGER.info(String.format("Saving result to %s in bucket %s", newFileName, RESULT_BUCKET)); BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(RESULT_BUCKET, newFileName)).build(); storage.create(blobInfo, ocrMessage.getText().getBytes(StandardCharsets.UTF_8)); LOGGER.info("File saved"); }
Source:
<code>public void removeGroupUnion(PerunSession sess, Group resultGroup, Group operandGroup) throws InternalErrorException, GroupNotExistsException, PrivilegeException, GroupRelationDoesNotExist, GroupRelationCannotBeRemoved, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, resultGroup); getGroupsManagerBl().checkGroupExists(sess, operandGroup); if (getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, resultGroup)) { throw new ExternallyManagedException("Result group: " + resultGroup + " is externally managed!"); } else if (getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, operandGroup)) { <START> throw new ExternallyManagedException("Operand group: " + operandGroup + " is externally managed!"); <END> } if ( (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, resultGroup) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, resultGroup)) || (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, operandGroup) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, operandGroup)) ) { throw new PrivilegeException(sess, "removeGroupUnion"); } getGroupsManagerBl().removeGroupUnion(sess, resultGroup, operandGroup, false); }</code><technical_language>for creating group union</technical_language>

Target:
public void removeGroupUnion(PerunSession sess, Group resultGroup, Group operandGroup) throws InternalErrorException, GroupNotExistsException, PrivilegeException, GroupRelationDoesNotExist, GroupRelationCannotBeRemoved, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, resultGroup); getGroupsManagerBl().checkGroupExists(sess, operandGroup); if (getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, resultGroup)) { throw new ExternallyManagedException("Result group: " + resultGroup + " is externally managed!"); } if ( (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, resultGroup) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, resultGroup)) || (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, operandGroup) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, operandGroup)) ) { throw new PrivilegeException(sess, "removeGroupUnion"); } getGroupsManagerBl().removeGroupUnion(sess, resultGroup, operandGroup, false); }
Source:
<code>public CompiledSchemaRepository<Schema> provide() { <START> CompiledSchemaRepository repository = new DirectCompiledSchemaRepository<>(rawSchemaClient, <END> SchemaCompilersFactory.avroSchemaCompiler()); if (configFactory.getBooleanProperty(SCHEMA_CACHE_ENABLED)) { return new CachedCompiledSchemaRepository<>(repository, configFactory.getIntProperty(SCHEMA_CACHE_COMPILED_MAXIMUM_SIZE), configFactory.getIntProperty(Configs.SCHEMA_CACHE_COMPILED_EXPIRE_AFTER_ACCESS_MINUTES)); } else { return repository; } }</code><technical_language>I CompiledSchemaRepository<Schema></technical_language>

Target:
public CompiledSchemaRepository<Schema> provide() { CompiledSchemaRepository<Schema> repository = new DirectCompiledSchemaRepository<>(rawSchemaClient, SchemaCompilersFactory.avroSchemaCompiler()); if (configFactory.getBooleanProperty(SCHEMA_CACHE_ENABLED)) { return new CachedCompiledSchemaRepository<>(repository, configFactory.getIntProperty(SCHEMA_CACHE_COMPILED_MAXIMUM_SIZE), configFactory.getIntProperty(Configs.SCHEMA_CACHE_COMPILED_EXPIRE_AFTER_ACCESS_MINUTES)); } else { return repository; } }
Source:
<code>public void render(Context context, VDS host, SafeHtmlBuilder sb, String id) { if (host == null || !host.isUpdateAvailable()) { return; } ImageResource statusImage = resources.updateAvailableImage(); SafeHtml statusImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(statusImage).getHTML()); <START> sb.append(statusImageHtml); <END> templates.hostAdditionalStatusIcon(id, statusImageHtml); }</code><technical_language>Line 31 is redundant. Line 33 do anything. returned SafeHtml appended sb. Instead of 31-33 just- sb.append(templates.hostAdditionalStatusIcon(id, statusImageHtml););</technical_language>

Target:
public void render(Context context, VDS host, SafeHtmlBuilder sb, String id) { if (host == null || !host.isUpdateAvailable()) { return; } ImageResource statusImage = resources.updateAvailableImage(); SafeHtml statusImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(statusImage).getHTML()); sb.append(templates.hostAdditionalStatusIcon(id, statusImageHtml)); }
Source:
<code>protected void rename() { if ( isDirty() ) { view.showYesNoCancelPopup( CommonConstants.INSTANCE.Information(), Constants.INSTANCE.modelEditor_confirm_save_before_rename(), new Command() { @Override public void execute() { rename( true ); } }, new Command() { @Override public void execute() { rename( false ); } }, <START> new Command() { <END> @Override public void execute() { } } ); } else { rename( false ); } }</code><technical_language>a parameter then! I guess easier copy paste code before, delegate View interface</technical_language>

Target:
protected void rename() { if ( isDirty() ) { view.showYesNoCancelPopup( CommonConstants.INSTANCE.Information(), Constants.INSTANCE.modelEditor_confirm_save_before_rename(), new Command() { @Override public void execute() { rename( true ); } }, new Command() { @Override public void execute() { rename( false ); } } ); } else { rename( false ); } }
Source:
<code>public void testRepeatedRolledBack() throws Exception { Xid xid = new CustomXid(654321); xaRes.start(xid, XAResource.TMNOFLAGS); xaRes.end(xid, XAResource.TMSUCCESS); xaRes.prepare(xid); xaRes.recover(XAResource.TMSTARTRSCAN); xaRes.rollback(xid); try { <START> xaRes.rollback(xid); <END> } catch (XAException xae) { assertEquals("Checking the errorCode is XAER_NOTA indicating the " + "xid does not exist.", XAException.XAER_NOTA, xae.errorCode ); } }</code><technical_language>jeremy, need a fail("Rollback successful")</technical_language>

Target:
public void testRepeatedRolledBack() throws Exception { Xid xid = new CustomXid(654321); xaRes.start(xid, XAResource.TMNOFLAGS); xaRes.end(xid, XAResource.TMSUCCESS); xaRes.prepare(xid); xaRes.recover(XAResource.TMSTARTRSCAN); xaRes.rollback(xid); try { xaRes.rollback(xid); fail("Rollback was successful"); } catch (XAException xae) { assertEquals("Checking the errorCode is XAER_NOTA indicating the " + "xid does not exist.", XAException.XAER_NOTA, xae.errorCode ); } }
Source:
<code>public static Set<URL> getResourceURLs(ResourceURLFilter filter) { try(URLClassLoader ucl = new URLClassLoader(new URL[] {(ClassLoader.getSystemClassLoader()).getResource("L10N")}, Resources.class.getClassLoader())) { Set<URL> collectedURLs = new HashSet<>(); for (URL url : ucl.getURLs()) { try { iterateEntry(new File(url.toURI()), filter, collectedURLs); } catch (URISyntaxException e) { LOGGER.debug(e.getMessage(), e); } } return collectedURLs; } catch (IOException e) { LOGGER.debug(e.getMessage(), e); } <START> return null; <END> }</code><technical_language>please return empty set instead of null here</technical_language>

Target:
public static Set<URL> getResourceURLs(ResourceURLFilter filter) { Set<URL> collectedURLs = new HashSet<>(); try(URLClassLoader ucl = new URLClassLoader(new URL[] {(ClassLoader.getSystemClassLoader()).getResource("L10N")}, Resources.class.getClassLoader())) { for (URL url : ucl.getURLs()) { try { iterateEntry(new File(url.toURI()), filter, collectedURLs); } catch (URISyntaxException e) { LOGGER.debug(e.getMessage(), e); } } return collectedURLs; } catch (IOException e) { LOGGER.debug(e.getMessage(), e); } return collectedURLs; }
Source:
<code>public <START> void ipSecListenSocket(Integer <END> socketFd) { FileDescriptor fd = new FileDescriptor(); fd.setInt$(socketFd.intValue()); try { Os.listen(fd, 10); } catch (ErrnoException e) { Log.e("IpSec: Failed to listen on socket " + e.toString()); } }</code><technical_language>this needs return a boolean success/failure</technical_language>

Target:
public Boolean ipSecListenSocket(Integer socketFd) { FileDescriptor fd = new FileDescriptor(); fd.setInt$(socketFd.intValue()); try { Os.listen(fd, 10); return true; } catch (ErrnoException e) { Log.e("IpSec: Failed to listen on socket " + e.toString()); } return false; }
Source:
<code>protected LightblueResponse callService(HttpRequestBase httpOperation) { String jsonOut; LOGGER.debug("Calling " + httpOperation); try { try (CloseableHttpClient httpClient = getLightblueHttpClient()) { httpOperation.setHeader("Content-Type", "application/json"); if (LOGGER.isDebugEnabled()) { try { LOGGER.debug("Request body: " + (EntityUtils.toString(((HttpEntityEnclosingRequestBase) httpOperation).getEntity()))); } catch (ClassCastException e) { LOGGER.debug("Request body: None"); } } try (CloseableHttpResponse httpResponse = httpClient.execute(httpOperation)) { HttpEntity entity = httpResponse.getEntity(); jsonOut = EntityUtils.toString(entity); LOGGER.debug("Response received from service" + jsonOut); return new LightblueResponse(jsonOut); <START> } <END> } } catch (IOException e) { LOGGER.error("There was a problem calling the lightblue service", e); return new LightblueResponse("{\"error\":\"There was a problem calling the lightblue service\"}"); } }</code><technical_language>if a consumer of LightblueHttpClient wants set a custom ObjectMapper, LightblueResponse it</technical_language>

Target:
protected LightblueResponse callService(HttpRequestBase httpOperation) { String jsonOut; LOGGER.debug("Calling " + httpOperation); try { try (CloseableHttpClient httpClient = getLightblueHttpClient()) { httpOperation.setHeader("Content-Type", "application/json"); if (LOGGER.isDebugEnabled()) { try { LOGGER.debug("Request body: " + (EntityUtils.toString(((HttpEntityEnclosingRequestBase) httpOperation).getEntity()))); } catch (ClassCastException e) { LOGGER.debug("Request body: None"); } } long t1 = new Date().getTime(); try (CloseableHttpResponse httpResponse = httpClient.execute(httpOperation)) { HttpEntity entity = httpResponse.getEntity(); jsonOut = EntityUtils.toString(entity); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response received from service: " + jsonOut); long t2 = new Date().getTime(); LOGGER.debug("Call took "+(t2-t1)+"ms"); } return new LightblueResponse(jsonOut, mapper); } } } catch (IOException e) { LOGGER.error("There was a problem calling the lightblue service", e); return new LightblueResponse("{\"error\":\"There was a problem calling the lightblue service\"}", mapper); } }
Source:
<code>private void unregisterServices(Thing thing) { ThingUID thingUID = thing.getUID(); Set<ServiceRegistration<?>> serviceRegs = this.thingHandlerServices.remove(thingUID); if (serviceRegs != null) { for (ServiceRegistration<?> serviceReg : serviceRegs) { <START> serviceReg.unregister(); <END> } } }</code><technical_language>deactivate is present THS interface called here</technical_language>

Target:
private void unregisterServices(Thing thing) { ThingUID thingUID = thing.getUID(); Set<ServiceRegistration<?>> serviceRegs = this.thingHandlerServices.remove(thingUID); if (serviceRegs != null) { for (ServiceRegistration<?> serviceReg : serviceRegs) { ThingHandlerService service = (ThingHandlerService) getBundleContext() .getService(serviceReg.getReference()); serviceReg.unregister(); if (service != null) { service.deactivate(); } } } }
Source:
<code>public void setIDSupplier(ToLongFunction<E> supplier) { this.idSupplier = supplier; <START> nodeMap = new LongObjectHashMap<>(this.size); <END> Iterator iterator = (Iterator)iterator(); try { while (iterator.hasNext()) { E value = iterator.next(); Node<E> position = iterator.last; putID(value, position); } } finally { iterator.close(); } }</code><technical_language>happen previously set idSupplier/nodeMap? throw new IllegalStateException("cannot set ID supplier twice") save happen</technical_language>

Target:
public void setIDSupplier(ToLongFunction<E> supplier) { this.idSupplier = supplier; nodeMap = newLongHashMap(); try (Iterator iterator = (Iterator) iterator()) { while (iterator.hasNext()) { E value = iterator.next(); Node<E> position = iterator.last; putID(value, position); } } }
Source:
<code>public int hashCode() { <START> return Objects.hash(getBucket(), getPath()); <END> }</code><technical_language>matter much, do bucket path match equals</technical_language>

Target:
public int hashCode() { return Objects.hash(bucket, path); }
Source:
<code>private Optional<String> formatPlanNodeStatsAndCost(PlanNode node) { PlanNodeStatsEstimate stats = estimatedStatsAndCosts.getStats().getOrDefault(node.getId(), PlanNodeStatsEstimate.unknown()); PlanNodeCostEstimate cost = estimatedStatsAndCosts.getCosts().getOrDefault(node.getId(), UNKNOWN_COST); <START> if (stats.isOutputRowCountUnknown() || cost.equals(UNKNOWN_COST)) { <END> return Optional.empty(); } return Optional.of(String.format("{rows: %s (%s), cpu: %s, memory: %s, network: %s}", formatAsLong(stats.getOutputRowCount()), formatEstimateAsDataSize(stats.getOutputSizeInBytes(node.getOutputSymbols(), types)), formatDouble(cost.getCpuCost()), formatDouble(cost.getMemoryCost()), formatDouble(cost.getNetworkCost()))); }</code><technical_language>Semantics change, part of Add PlanNodeStatsEstimate#unknown() method refactor</technical_language>

Target:
private Optional<String> formatPlanNodeStatsAndCost(PlanNode node) { PlanNodeStatsEstimate stats = estimatedStatsAndCosts.getStats().getOrDefault(node.getId(), PlanNodeStatsEstimate.unknown()); PlanNodeCostEstimate cost = estimatedStatsAndCosts.getCosts().getOrDefault(node.getId(), PlanNodeCostEstimate.unknown()); if (stats.isOutputRowCountUnknown() || cost.equals(PlanNodeCostEstimate.unknown())) { return Optional.empty(); } return Optional.of(String.format("{rows: %s (%s), cpu: %s, memory: %s, network: %s}", formatAsLong(stats.getOutputRowCount()), formatEstimateAsDataSize(stats.getOutputSizeInBytes(node.getOutputSymbols(), types)), formatDouble(cost.getCpuCost()), formatDouble(cost.getMemoryCost()), formatDouble(cost.getNetworkCost()))); }
Source:
<code>private static void ensureSameTenant(Iterable<Event> events) { checkNotNull(events); <START> final Set<TenantId> tenants = FluentIterable.from(events) <END> .transform(new Function<Event, TenantId>() { @Override public TenantId apply( @Nullable Event event) { checkNotNull(event); return getTenantId(event); } }) .toSet(); checkArgument(tenants.size() == 1, DIFFERENT_TENANT_ERROR_TEMPLATE, tenants); }</code><technical_language>Please move FluentIterable. ... next line reformat accordingly</technical_language>

Target:
private static void ensureSameTenant(Iterable<Event> events) { checkNotNull(events); final Set<TenantId> tenants = FluentIterable.from(events) .transform(new Function<Event, TenantId>() { @Override public TenantId apply( @Nullable Event event) { checkNotNull(event); return getTenantId(event); } }) .toSet(); checkArgument(tenants.size() == 1, TENANT_MISMATCH_ERROR_MSG, tenants); }
Source:
<code>private void startMetricsService() { if (state != State.STARTING) { return; } LOG.info("Initializing metrics service"); connectionAttempts++; try { session = createSession(); } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); LOG.warn("Could not connect to Cassandra cluster - assuming its not up yet", rootCause); long delay = 1 + ((connectionAttempts - 1) % 4); LOG.warn("[{}] Retrying connecting to Cassandra cluster in [{}]s...", connectionAttempts, delay); lifecycleExecutor.schedule(this::startMetricsService, delay, SECONDS); return; } <START> SchemaManager schemaManager = new SchemaManager(session); <END> try { if (Boolean.parseBoolean(resetDb)) { schemaManager.dropKeyspace(keyspace); } schemaManager.createSchema(keyspace); session.execute("USE " + keyspace); LOG.info("Using a key space of '{}'", keyspace); metricsService.startUp(session); LOG.info("Metrics service started"); state = State.STARTED; } catch (Throwable t) { LOG.error("An error occurred trying to connect to the Cassandra cluster", t); state = State.FAILED; } }</code><technical_language>I mentioned previously, I schema initialization done in MetricsServiceImpl. is implementation detail of service. Right CQL statements for task service in cql file, separated out some point task service schema is independent of rest of metrics schema</technical_language>

Target:
private void startMetricsService() { if (state != State.STARTING) { return; } LOG.info("Initializing metrics service"); connectionAttempts++; try { session = createSession(); } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); LOG.warn("Could not connect to Cassandra cluster - assuming its not up yet", rootCause); long delay = 1 + ((connectionAttempts - 1) % 4); LOG.warn("[{}] Retrying connecting to Cassandra cluster in [{}]s...", connectionAttempts, delay); lifecycleExecutor.schedule(this::startMetricsService, delay, SECONDS); return; } try { metricsService.startUp(session, keyspace, Boolean.parseBoolean(resetDb)); LOG.info("Metrics service started"); state = State.STARTED; } catch (Throwable t) { LOG.error("An error occurred trying to connect to the Cassandra cluster", t); state = State.FAILED; } finally { if (state != State.STARTED) { try { metricsService.shutdown(); } catch (Throwable ignore) { } } } }
Source:
<code>private Pod newPod() { return new PodBuilder() .withNewMetadata() <START> .withName("che-plugin-broker") <END> .endMetadata() .withNewSpec() .withRestartPolicy("Never") .endSpec() .build(); }</code><technical_language>Consider moving this constant</technical_language>

Target:
private Pod newPod() { return new PodBuilder() .withNewMetadata() .withName(BROKERS_POD_NAME) .endMetadata() .withNewSpec() .withRestartPolicy("Never") .endSpec() .build(); }
Source:
<code>public Builder withRequest(ReadRowsRequest request) { <START> this.request = request; <END> return this; }</code><technical_language>this.scan set null mimic behavior of withScan()</technical_language>

Target:
public Builder withRequest(ReadRowsRequest request) { this.request = request; this.scan = null; return this; }
Source:
<code>public void onRebindLocationFailed(Location location, Exception e) { Exceptions.propagateIfFatal(e); <START> String errmsg = "problem rebinding location "+(location == null ? null : location.getId()+" ("+location+")"); <END> rebindLocationFailures.put(location, new IllegalStateException(errmsg, e)); onErrorImpl(errmsg, e); }</code><technical_language>Is a null location possible</technical_language>

Target:
public void onRebindLocationFailed(Location location, Exception e) { Exceptions.propagateIfFatal(e); String errmsg = "problem rebinding location "+location.getId()+" ("+location+")"; exceptions.add(new IllegalStateException(errmsg, e)); onErrorImpl(errmsg, e); }
Source:
<code>public default LocalDate selectDateOrSame(LocalDate inputDate, SequenceDate sequenceDate) { <START> DateSequence seq = sequenceDate.isFullSequence() ? this : baseSequence(); return sequenceDate.selectDate(inputDate, seq, true); <END> }</code><technical_language>line is repeated in SequenceDate change</technical_language>

Target:
public default LocalDate selectDateOrSame(LocalDate inputDate, SequenceDate sequenceDate) { return sequenceDate.selectDate(inputDate, this, true); }
Source:
<code>public void authenticateAndOpen(SeleniumWebDriver driver) throws Exception { String dashboardUrlPath = dashboardUrl.get().toString(); driver.get(dashboardUrlPath); entrance.login(owner); <START> waitUntilTextPresentInUrl(driver, dashboardUrlPath + "#/"); <END> driver.get(factoryUrl); }</code><technical_language>"#/" a kind of rudiment</technical_language>

Target:
public void authenticateAndOpen(SeleniumWebDriver driver) throws Exception { driver.get(dashboardUrl.get().toString()); entrance.login(owner); driver.get(factoryUrl); }
Source:
<code>private void flushData(final Partition.PartitionKey pk, final SortedMap<Long, String> data, final Optional<String> metadata) { try { <START> final String evt = EventStream.createStreamEvent( <END> pk.partition, String.valueOf(offsets.get(pk).getSentOffset()), new ArrayList<>(data.values()), metadata); getOut().streamData(evt.getBytes(EventStream.UTF8)); } catch (final IOException e) { getLog().error("Failed to write data to output.", e); shutdownGracefully("Failed to write data to output"); } }</code><technical_language>please merge master, now</technical_language>

Target:
private void flushData(final Partition.PartitionKey pk, final SortedMap<Long, String> data, final Optional<String> metadata) { try { final String offset = String.valueOf(offsets.get(pk).getSentOffset()); final String batch = serializeBatch(pk, offset, new ArrayList<>(data.values()), metadata); getOut().streamData(batch.getBytes(EventStream.UTF8)); } catch (final IOException e) { getLog().error("Failed to write data to output.", e); shutdownGracefully("Failed to write data to output"); } }
Source:
<code>private void <START> lockTemplateInDb() <END> { TransactionSupport.executeInNewTransaction(() -> { getCompensationContext().snapshotEntityStatus(getVmTemplate()); vmTemplateDao.updateStatus(getVmTemplate().getId(), VmTemplateStatus.Locked); getDiskImages().forEach(diskImage -> { getCompensationContext().snapshotEntityStatus(diskImage.getImage()); diskImage.setImageStatus(ImageStatus.LOCKED); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.LOCKED); }); getCompensationContext().stateChanged(); return null; }); }</code><technical_language>this is a bit confusing template images locked here. VmTemplateHandler#lockVmTemplateInTransaction for template lock images here</technical_language>

Target:
private void lockTemplateInDb() { VmTemplateHandler.lockVmTemplateInTransaction(getVmTemplateId(), getCompensationContext()); }
Source:
<code>public void elasticsearchOssImage() throws IOException { try (ElasticsearchContainer container = new ElasticsearchContainer( DockerImageName .parse("docker.elastic.co/elasticsearch/elasticsearch-oss") .withTag(ELASTICSEARCH_VERSION) <START> .asCompatibleSubstituteFor("docker.elastic.co/elasticsearch/elasticsearch") <END> ) ) { container.start(); Response response = getClient(container).performRequest(new Request("GET", "/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThrows("We should not have /_xpack endpoint with an OSS License", ResponseException.class, () -> getClient(container).performRequest(new Request("GET", "/_xpack/"))); } }</code><technical_language>this is interesting edge case. Ideally, images treated compatible automatically. WDYT</technical_language>

Target:
public void elasticsearchOssImage() throws IOException { try (ElasticsearchContainer container = new ElasticsearchContainer( DockerImageName .parse("docker.elastic.co/elasticsearch/elasticsearch-oss") .withTag(ELASTICSEARCH_VERSION) ) ) { container.start(); Response response = getClient(container).performRequest(new Request("GET", "/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThrows("We should not have /_xpack endpoint with an OSS License", ResponseException.class, () -> getClient(container).performRequest(new Request("GET", "/_xpack/"))); } }
Source:
<code>private void readOffset() throws ConnectException { String path = FileUtils.topicDirectory(url, topicsDir, tp.topic()); CommittedFileFilter filter = new TopicPartitionCommittedFileFilter(tp); FileStatus fileStatusWithMaxOffset = FileUtils.fileStatusWithMaxOffset( storage, new Path(path), filter ); if (fileStatusWithMaxOffset != null) { offset = FileUtils.extractOffset(fileStatusWithMaxOffset.getPath().getName()) + 1; <START> committedOffset = offset; <END> } }</code><technical_language>nit: committedOffset is offset - 1. offset is next read from</technical_language>

Target:
private void readOffset() throws ConnectException { String path = FileUtils.topicDirectory(url, topicsDir, tp.topic()); CommittedFileFilter filter = new TopicPartitionCommittedFileFilter(tp); FileStatus fileStatusWithMaxOffset = FileUtils.fileStatusWithMaxOffset( storage, new Path(path), filter ); if (fileStatusWithMaxOffset != null) { committedOffset = FileUtils.extractOffset(fileStatusWithMaxOffset.getPath().getName()); offset = committedOffset + 1; } }
Source:
<code>public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { if (!currentUser.getCapabilities().canCreateProject()) { String msg = String.format( "fatal: %s does not have \"Create Project\" capability.", currentUser.getUserName()); throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } parseCommandLine(); if (projectName == null) { <START> throw new UnloggedFailure(1, "Error: Project name is required."); <END> } try { final CreateProjectArgs args = new CreateProjectArgs(); args.setProjectName(projectName); args.ownerIds = ownerIds; args.newParent = newParent; args.permissionsOnly = permissionsOnly; args.projectDescription = projectDescription; args.submitType = submitType; args.contributorAgreements = contributorAgreements; args.signedOffBy = signedOffBy; args.contentMerge = contentMerge; args.changeIdRequired = requireChangeID; args.branch = branch; args.createEmptyCommit = createEmptyCommit; final CreateProject createProject = CreateProjectFactory.create(args); createProject.createProject(); } catch (ProjectCreationFailedException err) { throw new UnloggedFailure(1, "fatal: " + err.getMessage(), err); } } }); }</code><technical_language>consistent other error output, I replcae 'Error:' 'fatal:'. missed this before</technical_language>

Target:
public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { if (!currentUser.getCapabilities().canCreateProject()) { String msg = String.format( "fatal: %s does not have \"Create Project\" capability.", currentUser.getUserName()); throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } parseCommandLine(); if (projectName == null) { throw new UnloggedFailure(1, "fatal: Project name is required."); } try { final CreateProjectArgs args = new CreateProjectArgs(); args.setProjectName(projectName); args.ownerIds = ownerIds; args.newParent = newParent; args.permissionsOnly = permissionsOnly; args.projectDescription = projectDescription; args.submitType = submitType; args.contributorAgreements = contributorAgreements; args.signedOffBy = signedOffBy; args.contentMerge = contentMerge; args.changeIdRequired = requireChangeID; args.branch = branch; args.createEmptyCommit = createEmptyCommit; final CreateProject createProject = CreateProjectFactory.create(args); createProject.createProject(); } catch (ProjectCreationFailedException err) { throw new UnloggedFailure(1, "fatal: " + err.getMessage(), err); } } }); }
Source:
<code>public String version() { <START> return "0.1.4.3"; <END> }</code><technical_language>suggestion return "0.1.4.6";</technical_language>

Target:
public String version() { return "0.1.4.6"; }
Source:
<code>private Socket enableTlsOnSocket(Socket socket) { if (socket != null && (socket instanceof SSLSocket)) { <START> ((SSLSocket) socket).setEnabledProtocols(new String[]{"MonkeyBalls"}); <END> } return socket; }</code><technical_language>protocol selected supported socket.getSupportedProtocols there, choose compatible TLS 1.2. This ensure Java version compatibility</technical_language>

Target:
private Socket enableTlsOnSocket(Socket socket) { if (socket != null && (socket instanceof SSLSocket)) { ((SSLSocket) socket).setEnabledProtocols(PROTOCOLS_TLS_1_2_ONLY); } return socket; }
Source:
<code>public void addPostShouldSetModificationDateToPostCreationDate() throws InterruptedException { Topic topic = createTopic(); DateTime prevDate = topic.getModificationDate(); <START> Thread.sleep(25); <END> Post post = new Post(); post.setCreationDate(new DateTime()); topic.addPost(post); assertEquals(topic.getModificationDate(), post.getCreationDate()); assertFalse(prevDate.equals(topic.getModificationDate())); }</code><technical_language>I think, Thread.sleep() a choise in this case. set date manually methods date.plusDays() change it</technical_language>

Target:
public void addPostShouldSetModificationDateToPostCreationDate() throws InterruptedException { Topic topic = createTopic(); DateTime prevDate = topic.getModificationDate(); Post post = new Post(); post.setCreationDate(new DateTime().plusDays(1)); topic.addPost(post); assertEquals(topic.getModificationDate(), post.getCreationDate()); assertFalse(prevDate.equals(topic.getModificationDate())); }
Source:
<code>public static void createServer() throws Exception { server = SshServer.setUpDefaultServer(); server.setPasswordAuthenticator((username, password, session) -> true); server.setPort(0); server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser"))); server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory())); server.setFileSystemFactory( <START> new VirtualFileSystemFactory(Paths.get(remoteTemporaryFolder.getRoot().getAbsolutePath()))); <END> server.start(); port = server.getPort(); }</code><technical_language>remoteTemporaryFolder.getRoot().toPath() work for you</technical_language>

Target:
public static void createServer() throws Exception { server = SshServer.setUpDefaultServer(); server.setPasswordAuthenticator((username, password, session) -> true); server.setPort(0); server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser"))); server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory())); server.setFileSystemFactory(new VirtualFileSystemFactory(remoteTemporaryFolder.getRoot().toPath())); server.start(); port = server.getPort(); }
Source:
<code>switch(4) { case 4 : break; <START> default: <END> switch(5) { case 5 : break; case 6 : default: break; } break; }</code><technical_language>please extra case for: next line in good column position relative previos line: case 4 : // violation</technical_language>

Target:
switch(4) { case 4 : break; default: switch(5) { case 5 : break; case 6 : break; case 7 : break; default: break; } break; }
Source:
<code>private long insertBootstrapStartRow(Connection connection, String db, String table, String whereClause, Long totalRows) throws SQLException { LOGGER.info("inserting bootstrap start row"); String sql = null; <START> if ( whereClause != null ) { <END> sql = "insert into `bootstrap` (database_name, table_name, where_clause, total_rows) values(?, ?, ?, ?)"; } else { sql = "insert into `bootstrap` (database_name, table_name, total_rows) values(?, ?, ?)"; } PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, db); preparedStatement.setString(2, table); if ( whereClause != null ) { preparedStatement.setString(3, whereClause); preparedStatement.setLong(4, totalRows); } else { preparedStatement.setLong(3, totalRows); } preparedStatement.execute(); ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); generatedKeys.next(); return generatedKeys.getLong(1); }</code><technical_language>I SQL unconditionally include column, pass null column line 179 no</technical_language>

Target:
private long insertBootstrapStartRow(Connection connection, String db, String table, String whereClause, Long totalRows) throws SQLException { LOGGER.info("inserting bootstrap start row"); String sql = null; sql = "insert into `bootstrap` (database_name, table_name, where_clause, total_rows) values(?, ?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, db); preparedStatement.setString(2, table); preparedStatement.setString(3, whereClause); preparedStatement.setLong(4, totalRows); preparedStatement.execute(); ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); generatedKeys.next(); return generatedKeys.getLong(1); }
Source:
<code>public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.doGet(request, response); String target = request.getPathInfo(); String uri = request.getRequestURI(); try { if (uri != null && uri.endsWith("help.htm")) { target = HELP_HTM; } else if (uri != null && "/".equals(uri)){ target = INDEX_HTM; } URL url = VoltDB.class.getResource("dbmonitor" + target); if (url == null) { String msg = "404: Resource not found.\n"; response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); return; } InputStream is = VoltDB.class.getResourceAsStream("dbmonitor" + target); if (target.endsWith(INDEX_HTM) || target.endsWith(HELP_HTM)) { response.setContentType(HTML_CONTENT_TYPE); response.setStatus(HttpServletResponse.SC_OK); OutputStream os = response.getOutputStream(); BufferedInputStream bis = new BufferedInputStream(is); int c = -1; while ((c = bis.read()) != -1) { os.write(c); } } else { String msg = "404: Resource not found.\n"; response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); } } catch (Exception ex) { <START> m_log.info("Not servicing url: " + target + " Details: " + ex.getMessage()); <END> } }</code><technical_language>Is this enough? respond a 404 something</technical_language>

Target:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.doGet(request, response); String target = request.getPathInfo(); final String uri = request.getRequestURI(); final String msg = "404: Resource not found.\n"; try { if (uri != null && uri.endsWith("help.htm")) { target = HELP_HTM; } else if (uri != null && "/".equals(uri)){ target = INDEX_HTM; } URL url = VoltDB.class.getResource("dbmonitor" + target); if (url == null) { response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); return; } InputStream is = VoltDB.class.getResourceAsStream("dbmonitor" + target); if (target.endsWith(INDEX_HTM) || target.endsWith(HELP_HTM)) { response.setContentType(HTML_CONTENT_TYPE); response.setStatus(HttpServletResponse.SC_OK); OutputStream os = response.getOutputStream(); BufferedInputStream bis = new BufferedInputStream(is); int c = -1; while ((c = bis.read()) != -1) { os.write(c); } } else { response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); } } catch (Exception ex) { rateLimitedLogWarn("Not servicing url: %s Details: ", target, ex.getMessage()); response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); } }
Source:
<code>public Resource loadResource(IStorage storage, Map<?, ?> options) { InputStream stream = null; Resource resource = null; try { URI uri = createURIFor(storage); resource = createResource(uri); <START> if (!(storage instanceof File)) { <END> stream = storage.getContents(); resource.load(stream, options); } else { resource.load(options); } } catch (IOException e) { } catch (CoreException e) { } catch (WrappedException e) { } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } return resource; }</code><technical_language>Do restricted "File", API IFile instead. Furthermore, File's "getContent()" stream working, number of special chars in path. If not, eclipse platform a bugs. If fail, means IFile's handle created in a this file returns false storage.exists. bug is higher in call stack, create this handle</technical_language>

Target:
public Resource loadResource(IStorage storage, Map<?, ?> options) { InputStream stream = null; Resource resource = null; try { resource = createResource(createURIFor(storage)); stream = storage.getContents(); resource.load(stream, options); } catch (IOException e) { } catch (CoreException e) { } catch (WrappedException e) { } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } return resource; }
Source:
<code>private void receivePublish(SubscribedRepository repo) throws IOException { final String remote = repo.getRemote(); <START> ReceivePack rp = new ReceivePack(repo.getRepository()) { <END> @Override protected void validateCommands() { for (ReceiveCommand c : getAllCommands()) c.setName(SubscribedRepository.getPubSubRefFromLocal( remote, c.getRefName())); super.validateCommands(); } }; rp.setExpectDataAfterPackFooter(true); rp.setBiDirectionalPipe(false); rp.setAdvertisedRefs(repo.getPubSubRefs(), null); try { rp.receive(in, out, null); } finally { rp.unlockPack(); } }</code><technical_language>BaseReceivePack avoid status reporting stuff exists in ReceivePack</technical_language>

Target:
private void receivePublish(SubscribedRepository repo) throws IOException { ReceivePublishedPack rp = new ReceivePublishedPack( repo.getRepository(), repo.getRemote()); rp.setExpectDataAfterPackFooter(true); rp.setAdvertisedRefs(repo.getPubSubRefs(), null); rp.receive(in); }
Source:
<code>private IncrementalBuildResults addResource( final Path resource, final InputStream inputStream ) { synchronized ( kieFileSystem ) { checkNotNull( "resource", resource ); if ( !Files.isRegularFile( resource ) ) { return new IncrementalBuildResults( projectGAV ); } checkAFullBuildHasBeenPerformed(); final IncrementalBuildResults results = new IncrementalBuildResults( projectGAV ); final BuildValidationHelper validator = getBuildValidationHelper( resource ); if ( validator != null ) { final List<ValidationMessage> addedValidationMessages = validator.validate( Paths.convert( resource ) ); results.addAllAddedMessages( convertValidationMessages( addedValidationMessages ) ); results.addAllRemovedMessages( convertValidationMessages( nonKieResourceValidationHelperMessages.remove( resource ) ) ); nonKieResourceValidationHelpers.put( resource, validator ); nonKieResourceValidationHelperMessages.put( resource, addedValidationMessages ); } final String destinationPath = destinationPath( resource ); final Resource inputStreamResource = KieServices.Factory.get().getResources().newInputStreamResource( new BufferedInputStream( inputStream ) ); kieFileSystem.write( destinationPath, inputStreamResource ); addJavaClass( resource ); handles.put( getBaseFileName( destinationPath ), Paths.convert( resource ) ); <START> <END> buildIncrementally( results, destinationPath( resource ) ); return results; } }</code><technical_language>back-ticks start (and end) blocks of code. in more detail: <LINK_0> private void addNewResource( final Path resource, final InputStream inputStream ) { final String destinationPath = destinationPath( resource ); final Resource inputStreamResource = KieServices.Factory.get().getResources() .newInputStreamResource( new BufferedInputStream( inputStream ) ); kieFileSystem.write( destinationPath, inputStreamResource ); addJavaClass( resource ); handles.put( getBaseFileName( destinationPath ), Paths.convert( resource ) ); }</technical_language>

Target:
private IncrementalBuildResults addResource( final Path resource, final InputStream inputStream ) { synchronized ( kieFileSystem ) { checkNotNull( "resource", resource ); if ( !Files.isRegularFile( resource ) ) { return new IncrementalBuildResults( projectGAV ); } checkAFullBuildHasBeenPerformed(); final IncrementalBuildResults results = new IncrementalBuildResults( projectGAV ); final BuildValidationHelper validator = getBuildValidationHelper( resource ); if ( validator != null ) { final List<ValidationMessage> addedValidationMessages = validator.validate( Paths.convert( resource ) ); results.addAllAddedMessages( convertValidationMessages( addedValidationMessages ) ); results.addAllRemovedMessages( convertValidationMessages( nonKieResourceValidationHelperMessages.remove( resource ) ) ); nonKieResourceValidationHelpers.put( resource, validator ); nonKieResourceValidationHelperMessages.put( resource, addedValidationMessages ); } addNewResource( resource, inputStream ); buildIncrementally( results, destinationPath( resource ) ); return results; } }
Source:
<code>private void refreshGeoRepDataInCluster(VDSGroup cluster) { if (!supportsGlusterGeoRepFeature(cluster)) { return; } List<GlusterGeoRepSession> sessions = getSessionsForCluster(cluster); if (sessions == null) { <START> log.debugFormat("No sessions returned for cluster {0} from CLI, nothing to do", cluster.getName()); <END> return; } for (GlusterGeoRepSession session: sessions) { session.setMasterVolumeId(getVolumeId(cluster, session.getMasterVolumeName())); updateGeoRepStatus(session); if (getGeoRepDao().getById(session.getId()) == null) { getGeoRepDao().save(session); } else { getGeoRepDao().updateSession(session); } getGeoRepDao().saveOrUpdateDetailsInBatch(session.getSessionDetails()); } }</code><technical_language>if session created ui deleted cli</technical_language>

Target:
private void refreshGeoRepDataInCluster(VDSGroup cluster) { if (!supportsGlusterGeoRepFeature(cluster)) { return; } Map<Guid, GlusterGeoRepSession> sessionsMap = getSessionsForCluster(cluster); if (sessionsMap == null) { log.debugFormat("Error in retrieving sessions for cluster {0} from CLI, nothing to do", cluster.getName()); return; } removeDeletedSessions(cluster.getId(), sessionsMap); for (GlusterGeoRepSession session : sessionsMap.values()) { GlusterVolumeEntity masterVolume = getVolume(cluster, session.getMasterVolumeName()); if (masterVolume == null) { log.infoFormat("Could not find corresponding volume for geo-rep session {0} and volume {1}", session.getSessionKey(), session.getMasterVolumeName()); } else { session.setMasterVolumeId(masterVolume.getId()); } updateGeoRepStatus(masterVolume, session); if (getGeoRepDao().getById(session.getId()) == null) { log.debugFormat("detected new geo-rep session {0} for volume {1}", session.getSessionKey(), session.getMasterVolumeName()); getGeoRepDao().save(session); logGeoRepMessage(AuditLogType.GLUSTER_GEOREP_SESSION_DETECTED_FROM_CLI, cluster.getId(), session); } else { getGeoRepDao().updateSession(session); } getGeoRepDao().saveOrUpdateDetailsInBatch(session.getSessionDetails()); } }
Source:
<code>private ResponseCallback release(int streamId, ChannelHandlerContext ctx) { LOG.trace("[{}] Releasing stream id {}", logPrefix, streamId); ResponseCallback responseCallback; if (!abortingAllRequests) { responseCallback = MoreObjects.firstNonNull(inFlight.remove(streamId), orphaned.remove(streamId)); } else { responseCallback = orphaned.remove(streamId); } <START> orphanedSize = orphaned.size(); <END> streamIds.release(streamId); if (closingGracefully && inFlight.isEmpty()) { LOG.debug("[{}] Done handling the last pending query, closing channel", logPrefix); ctx.channel().close(); } return responseCallback; }</code><technical_language>This right handle this, problem I initial fix inflight.remove invoked while abort inflight executed exceptionCaught(InFlightHandler.java:293) path</technical_language>

Target:
private void release(int streamId, ChannelHandlerContext ctx) { LOG.trace("[{}] Releasing stream id {}", logPrefix, streamId); if (inFlight.remove(streamId) != null) { if (closingGracefully && inFlight.isEmpty()) { LOG.debug("[{}] Done handling the last pending query, closing channel", logPrefix); ctx.channel().close(); } } else if (orphaned.remove(streamId) != null) { orphanedSize = orphaned.size(); } streamIds.release(streamId); }
Source:
<code>public ScriptHelper uniqueSshConnection() { <START> setFlag("unique", Identifiers.makeRandomBase64Id(32)); <END> return this; }</code><technical_language>UNIQUE_ID constant</technical_language>

Target:
public ScriptHelper uniqueSshConnection() { setFlag(SshMachineLocation.UNIQUE_ID, Identifiers.makeRandomBase64Id(32)); return this; }