auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public GlusterVolumeSnapshotCreatePopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants, ApplicationMessages messages, CommonApplicationTemplates templates) { super(eventBus, resources); this.messages = messages; this.constants = constants; this.templates = templates; <START> initEditors(); <END> initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); ViewIdHandler.idHandler.generateAndSetIds(this); localize(); driver.initialize(this); setTitle(constants.newSnapshot()); }</code><technical_language>Please remove initEditors</technical_language>

Target:
public GlusterVolumeSnapshotCreatePopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants, ApplicationMessages messages, CommonApplicationTemplates templates) { super(eventBus, resources); this.messages = messages; this.constants = constants; this.templates = templates; initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); ViewIdHandler.idHandler.generateAndSetIds(this); localize(); driver.initialize(this); setTitle(constants.newSnapshot()); }
Source:
<code>public PipelineConfig getEntityFromRequestBody(Request req) { HashMap<String, Object> options = new HashMap<>(); options.put("goConfig", goConfigService.getCurrentConfig() ); options.put("passwordDeserializer", passwordDeserializer ); JsonReader jsonReader = GsonTransformer.getInstance().jsonReaderFrom(req.body()); return PipelineConfigRepresenter.fromJSON(jsonReader.readJsonObject("pipeline"), options); <START> } <END></code><technical_language>options object, instead of hash? usages of TriggerOptions for example</technical_language>

Target:
public PipelineConfig getEntityFromRequestBody(Request req) { ConfigHelperOptions options = new ConfigHelperOptions(goConfigService.getCurrentConfig(), passwordDeserializer); JsonReader jsonReader = GsonTransformer.getInstance().jsonReaderFrom(req.body()); if ("PUT".equalsIgnoreCase(req.requestMethod())) { return PipelineConfigRepresenter.fromJSON(jsonReader, options); } return PipelineConfigRepresenter.fromJSON(jsonReader.readJsonObject("pipeline"), options); }
Source:
<code>public void initialize(final Resource it) { Account _createAccount = this.createAccount("Lorenzo", "lorenzo@foobar"); <START> final Procedure1<Account> _function = (Account account) -> { <END> EList<EObject> _contents = it.getContents(); _contents.add(account); this.createDefaultFolders(account); }; ObjectExtensions.<Account>operator_doubleArrow(_createAccount, _function); Account _createAccount_1 = this.createAccount("Francesco", "francesco@foobar"); final Procedure1<Account> _function_1 = (Account account) -> { EList<EObject> _contents = it.getContents(); _contents.add(account); this.createDefaultFolders(account); }; ObjectExtensions.<Account>operator_doubleArrow(_createAccount_1, _function_1); Account _createAccount_2 = this.createAccount("Vicenzo", "vincenzo@foobar"); final Procedure1<Account> _function_2 = (Account account) -> { EList<EObject> _contents = it.getContents(); _contents.add(account); this.createDefaultFolders(account); }; ObjectExtensions.<Account>operator_doubleArrow(_createAccount_2, _function_2); }</code><technical_language>running Eclipse Java 8 this DSL compiler compile Xbase lambdas Java 8 lambdas; however, project Java level is Java 8, build fails of that. run Eclipse for developing Parsley Java 7 (at set JRE a Java 7 installation)</technical_language>

Target:
public void initialize(final Resource it) { Account _createAccount = this.createAccount("Lorenzo", "lorenzo@foobar"); final Procedure1<Account> _function = new Procedure1<Account>() { @Override public void apply(final Account account) { EList<EObject> _contents = it.getContents(); _contents.add(account); AccountsviewResourceManager.this.createDefaultFolders(account); } }; ObjectExtensions.<Account>operator_doubleArrow(_createAccount, _function); Account _createAccount_1 = this.createAccount("Francesco", "francesco@foobar"); final Procedure1<Account> _function_1 = new Procedure1<Account>() { @Override public void apply(final Account account) { EList<EObject> _contents = it.getContents(); _contents.add(account); AccountsviewResourceManager.this.createDefaultFolders(account); } }; ObjectExtensions.<Account>operator_doubleArrow(_createAccount_1, _function_1); Account _createAccount_2 = this.createAccount("Vicenzo", "vincenzo@foobar"); final Procedure1<Account> _function_2 = new Procedure1<Account>() { @Override public void apply(final Account account) { EList<EObject> _contents = it.getContents(); _contents.add(account); AccountsviewResourceManager.this.createDefaultFolders(account); } }; ObjectExtensions.<Account>operator_doubleArrow(_createAccount_2, _function_2); }
Source:
<code>void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { if (isPresent != null) { isPresent.flush(); if(!foundNulls) { isPresentOutStream.suppress(); if (rowIndexStream != null) { removeIsPresentPositions(); } } } OrcProto.StripeStatistics.Builder stripeStatsBuilder = OrcProto.StripeStatistics.newBuilder(); writeStripeStatistics(stripeStatsBuilder, this); stripeStatsBuilders.add(stripeStatsBuilder); foundNulls = false; builder.addColumns(getEncoding()); <START> if (streamFactory.hasWriterTimeZone()) { <END> builder.setWriterTimezone(TimeZone.getDefault().getID()); } if (rowIndexStream != null) { if (rowIndex.getEntryCount() != requiredIndexEntries) { throw new IllegalArgumentException("Column has wrong number of " + "index entries found: " + rowIndex.getEntryCount() + " expected: " + requiredIndexEntries); } rowIndex.build().writeTo(rowIndexStream); rowIndexStream.flush(); } rowIndex.clear(); rowIndexEntry.clear(); if (bloomFilterStream != null) { bloomFilterIndex.build().writeTo(bloomFilterStream); bloomFilterStream.flush(); bloomFilterIndex.clear(); bloomFilterEntry.clear(); } }</code><technical_language>This timezone policy of Tajo. check timezone? codes helpful this work. <LINK_0></technical_language>

Target:
void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { if (isPresent != null) { isPresent.flush(); if(!foundNulls) { isPresentOutStream.suppress(); if (rowIndexStream != null) { removeIsPresentPositions(); } } } OrcProto.StripeStatistics.Builder stripeStatsBuilder = OrcProto.StripeStatistics.newBuilder(); writeStripeStatistics(stripeStatsBuilder, this); stripeStatsBuilders.add(stripeStatsBuilder); foundNulls = false; builder.addColumns(getEncoding()); if (streamFactory.hasWriterTimeZone()) { builder.setWriterTimezone(streamFactory.getTimeZone().getID()); } if (rowIndexStream != null) { if (rowIndex.getEntryCount() != requiredIndexEntries) { throw new IllegalArgumentException("Column has wrong number of " + "index entries found: " + rowIndex.getEntryCount() + " expected: " + requiredIndexEntries); } rowIndex.build().writeTo(rowIndexStream); rowIndexStream.flush(); } rowIndex.clear(); rowIndexEntry.clear(); if (bloomFilterStream != null) { bloomFilterIndex.build().writeTo(bloomFilterStream); bloomFilterStream.flush(); bloomFilterIndex.clear(); bloomFilterEntry.clear(); } }
Source:
<code>private int threadIndex() { final int index = (int) Thread.currentThread().getId(); <START> return STRIDE * (index & (stripes - 1)); <END> }</code><technical_language>Add a private final stripeMask field is initialized stripes - 1. This eliminate arithmetic operation this hot path</technical_language>

Target:
private int threadIndex() { final int index = (int) Thread.currentThread().getId(); return STRIDE * (index & stripeMask); }
Source:
<code>@Test public void performSubmitWithFetchActionWithSuccessCompletionCallback() { String pausedTag = "pausedTag"; dispatcher.pausedTags.add(pausedTag); <START> assertThat(dispatcher.pausedActions).isEmpty(); <END> Callback callback = mockCallback(); FetchAction fetchAction1 = new FetchAction(mockPicasso(), new Request.Builder(URI_1).build(), false, URI_KEY_1, pausedTag, callback); dispatcher.performSubmit(fetchAction1); fetchAction1.complete(bitmap1, MEMORY); verify(callback).onSuccess(); assertThat(dispatcher.pausedActions).hasSize(1); }</code><technical_language>do tests mess tagging? Copy/paste</technical_language>

Target:
@Test public void performSubmitWithFetchActionWithSuccessCompletionCallback() { String pausedTag = "pausedTag"; Callback callback = mockCallback(); FetchAction fetchAction = new FetchAction(mockPicasso(), new Request.Builder(URI_1).build(), 0, 0, pausedTag, URI_KEY_1, callback); dispatcher.performSubmit(fetchAction); fetchAction.complete(bitmap1, MEMORY); verify(callback).onSuccess(); }
Source:
<code>public void recreateSocketAddresses() { InetAddress address = null; try { <START> address = getReachableAddress(this.hostname, 2000); <END> LOG.info("Resolved hostname: to address: {}", this.hostname, address); this.addr = new InetSocketAddress(address, this.port); if (this.electionPort > 0){ this.electionAddr = new InetSocketAddress(address, this.electionPort); } } catch (UnknownHostException ex) { LOG.warn("Failed to resolve address: {}", this.hostname, ex); if (this.addr != null) { return; } this.addr = InetSocketAddress.createUnresolved(this.hostname, this.port); if (this.electionPort > 0){ this.electionAddr = InetSocketAddress.createUnresolved(this.hostname, this.electionPort); } } }</code><technical_language>Instead of hardcoding 2000 here, a constant variable represent timeout beginning of QuorumPeer.java. [QuorumCnxManager](<LINK_0> is a good example constants</technical_language>

Target:
public void recreateSocketAddresses() { InetAddress address = null; try { int ipReachableTimeout = 0; String ipReachableValue = System.getProperty("zookeeper.ipReachableTimeout"); if (ipReachableValue != null) { try { ipReachableTimeout = Integer.parseInt(ipReachableValue); } catch (NumberFormatException e) { LOG.error("{} is not a valid number", ipReachableValue); } } if (ipReachableTimeout <= 0) { address = InetAddress.getByName(this.hostname); } else { address = getReachableAddress(this.hostname, ipReachableTimeout); } LOG.info("Resolved hostname: to address: {}", this.hostname, address); this.addr = new InetSocketAddress(address, this.port); if (this.electionPort > 0){ this.electionAddr = new InetSocketAddress(address, this.electionPort); } } catch (UnknownHostException ex) { LOG.warn("Failed to resolve address: {}", this.hostname, ex); if (this.addr != null) { return; } this.addr = InetSocketAddress.createUnresolved(this.hostname, this.port); if (this.electionPort > 0){ this.electionAddr = InetSocketAddress.createUnresolved(this.hostname, this.electionPort); } } }
Source:
<code>private SettableFuture<Boolean> logFenceEntryInJournal(Journal journal) { SettableFuture<Boolean> result; synchronized (this) { result = logFenceResult = SettableFuture.create(); } ByteBuf entry = createLedgerFenceEntry(ledgerId); journal.logAddEntry(entry, (rc, ledgerId, entryId, addr, ctx) -> { <START> LOG.debug("Record fenced state for ledger in journal with rc {}", ledgerId, BKException.codeLogger(rc)); <END> if (rc == 0) { fenceEntryPersisted.compareAndSet(false, true); result.set(true); } else { result.set(false); } }, null); return result; }</code><technical_language>wrap this if (LOG.isDebugEnabled()) { LOG.debug ... } codeLogger() creates new objects in 99.9% of cases debug logging is off. This lets bypass extra object creation</technical_language>

Target:
private SettableFuture<Boolean> logFenceEntryInJournal(Journal journal) { SettableFuture<Boolean> result; synchronized (this) { result = logFenceResult = SettableFuture.create(); } ByteBuf entry = createLedgerFenceEntry(ledgerId); journal.logAddEntry(entry, (rc, ledgerId, entryId, addr, ctx) -> { if (LOG.isDebugEnabled()) { LOG.debug("Record fenced state for ledger in journal with rc {}", ledgerId, BKException.codeLogger(rc)); } if (rc == 0) { fenceEntryPersisted.compareAndSet(false, true); result.set(true); } else { result.set(false); } }, null); return result; }
Source:
<code>public void shouldSerializeServerConfigToJSON() { ServerConfig serverConfig = new ServerConfig(); serverConfig.ensureServerIdExists(); serverConfig.setSecureSiteUrl("<LINK_1>"); serverConfig.setSiteUrl("<LINK_0>"); CurrentGoCDVersion goCDVersion = CurrentGoCDVersion.getInstance(); MessageHandlerForServerInfoRequestProcessor2_0 processor = new MessageHandlerForServerInfoRequestProcessor2_0(); <START> assertThat(processor.serverInfoToJSON(serverConfig), <END> is(format("{\"server_id\":\"%s\",\"site_url\":\"%s\",\"secure_site_url\":\"%s\"," + "\"go_version\":\"%s\"," + "\"dist_version\":\"%s\"," + "\"git_revision\":\"%s\"" + "}", serverConfig.getServerId(), serverConfig.getSiteUrl().getUrl(), serverConfig.getSecureSiteUrl().getUrl(), goCDVersion.goVersion(), goCDVersion.distVersion(), goCDVersion.gitRevision() ))); }</code><technical_language>assertThatJson instead of matching JSON strings. guarantee of ordering of keys in JSON. This is flaky tests</technical_language>

Target:
public void shouldSerializeServerConfigToJSON() { ServerConfig serverConfig = new ServerConfig(); serverConfig.ensureServerIdExists(); serverConfig.setSecureSiteUrl("<LINK_1>"); serverConfig.setSiteUrl("<LINK_0>"); CurrentGoCDVersion goCDVersion = CurrentGoCDVersion.getInstance(); MessageHandlerForServerInfoRequestProcessor2_0 processor = new MessageHandlerForServerInfoRequestProcessor2_0(); String expectedJsonStr = format("{\"server_id\":\"%s\"," + "\"site_url\":\"%s\"," + "\"secure_site_url\":\"%s\"," + "\"go_version\":\"%s\"," + "\"dist_version\":\"%s\"," + "\"git_revision\":\"%s\"" + "}", serverConfig.getServerId(), serverConfig.getSiteUrl().getUrl(), serverConfig.getSecureSiteUrl().getUrl(), goCDVersion.goVersion(), goCDVersion.distVersion(), goCDVersion.gitRevision() ); assertThatJson(expectedJsonStr).isEqualTo(processor.serverInfoToJSON(serverConfig)); }
Source:
<code>private byte[] generateZeroRowFile( ConnectorSession session, HdfsContext hdfsContext, Properties properties, String serDe, String outputFormatName, HiveCompressionCodec compressionCodec) { String tmpDirectoryPath = System.getProperty("java.io.tmpdir"); String tmpFileName = format("presto-hive-zero-row-file-creator-%s-%s", session.getQueryId(), randomUUID().toString()); java.nio.file.Path tmpFilePath = Paths.get(tmpDirectoryPath, tmpFileName); try { Path target = new Path(format("file://%s/%s", tmpDirectoryPath, tmpFileName)); JobConf conf = configureCompression(hdfsEnvironment.getConfiguration(hdfsContext, target), compressionCodec); initializeSerializer(conf, properties, serDe); RecordWriter recordWriter = HiveWriteUtils.createRecordWriter( target, conf, properties, outputFormatName, session); recordWriter.close(false); return readAllBytes(tmpFilePath); } catch (IOException e) { throw new UncheckedIOException(e); } finally { <START> if (exists(tmpFilePath)) { <END> try { delete(tmpFilePath); } catch (IOException e) { log.error(e, "Error deleting temporary file: %s", tmpFilePath); } } } }</code><technical_language>This exists check needed try delete file if exists, you</technical_language>

Target:
private byte[] generateZeroRowFile( ConnectorSession session, HdfsContext hdfsContext, Properties properties, String serDe, String outputFormatName, HiveCompressionCodec compressionCodec) { String tmpDirectoryPath = System.getProperty("java.io.tmpdir"); String tmpFileName = format("presto-hive-zero-row-file-creator-%s-%s", session.getQueryId(), randomUUID().toString()); java.nio.file.Path tmpFilePath = Paths.get(tmpDirectoryPath, tmpFileName); try { Path target = new Path(format("file://%s/%s", tmpDirectoryPath, tmpFileName)); JobConf conf = configureCompression(hdfsEnvironment.getConfiguration(hdfsContext, target), compressionCodec); initializeSerializer(conf, properties, serDe); RecordWriter recordWriter = HiveWriteUtils.createRecordWriter( target, conf, properties, outputFormatName, session); recordWriter.close(false); return readAllBytes(tmpFilePath); } catch (IOException e) { throw new UncheckedIOException(e); } finally { try { deleteIfExists(tmpFilePath); } catch (IOException e) { log.error(e, "Error deleting temporary file: %s", tmpFilePath); } } }
Source:
<code>private void checkRequiresCapability() throws RuntimeException { RequiresCapability rc = getClass().getAnnotation(RequiresCapability.class); if (rc != null) { CurrentUser user = currentUser.get(); CapabilityControl ctl = user.getCapabilities(); if (!ctl.canPerform(rc.value()) && !ctl.canAdministrateServer()) { String msg = String.format( "fatal: %s does not have \"%s\" capability.", user.getUserName(), rc.value()); <START> throw new RuntimeException(msg); <END> } } }</code><technical_language>This right return result client HTTP. throw new RequireCapabilityException(msg); private static class RequireCapabilityException extends Exception { }</technical_language>

Target:
private void checkRequiresCapability() throws RequireCapabilityException { RequiresCapability rc = getClass().getAnnotation(RequiresCapability.class); if (rc != null) { CurrentUser user = currentUser.get(); CapabilityControl ctl = user.getCapabilities(); if (!ctl.canPerform(rc.value()) && !ctl.canAdministrateServer()) { String msg = String.format( "fatal: %s does not have \"%s\" capability.", user.getUserName(), rc.value()); throw new RequireCapabilityException(msg); } } }
Source:
<code>public List<ConfigurationMetadataProperty> listProperties(Resource app, boolean exhaustive) { try { if (app != null) { if (isDockerSchema(app.getURI())) { <START> String imageName = app.getURI().getSchemeSpecificPart(); <END> Map<String, String> labels = this.containerImageMetadataResolver.getImageLabels(imageName); if (CollectionUtils.isEmpty(labels)) { return Collections.emptyList(); } String encodedMetadata = labels.get(CONTAINER_IMAGE_CONFIGURATION_METADATA_LABEL_NAME); if (!StringUtils.hasText(encodedMetadata)) { return Collections.emptyList(); } String metadataJson = new String(Base64.getDecoder().decode(encodedMetadata.getBytes())); try { ConfigurationMetadataRepository configurationMetadataRepository = ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(new ByteArrayInputStream(metadataJson.getBytes())).build(); List<ConfigurationMetadataProperty> result = configurationMetadataRepository.getAllProperties().entrySet().stream() .map(e -> e.getValue()) .collect(Collectors.toList()); return result; } catch (Exception e) { throw new AppMetadataResolutionException("Invalid Metadata JSON format: " + metadataJson); } } else { Archive archive = resolveAsArchive(app); return listProperties(archive, exhaustive); } } } catch (Exception e) { throw new AppMetadataResolutionException("Failed to resolve application resource: " + app.getDescription(), e); } return Collections.emptyList(); }</code><technical_language>Move code if (isDockerSchema(app.getURI())) { block a helper method for reading</technical_language>

Target:
public List<ConfigurationMetadataProperty> listProperties(Resource app, boolean exhaustive) { try { if (app != null) { if (isDockerSchema(app.getURI())) { return resolvePropertiesFromContainerImage(app.getURI()); } else { Archive archive = resolveAsArchive(app); return listProperties(archive, exhaustive); } } } catch (Exception e) { throw new AppMetadataResolutionException("Failed to resolve application resource: " + app.getDescription(), e); } return Collections.emptyList(); }
Source:
<code><START> public int length() { <END> switch (vlanIDs.size()) { case 0: return 14 + childLength(); case 1: return 14 + 4 + childLength(); default: return 14 + 8 + childLength(); } }</code><technical_language>Math.max(..., 60) for ethernet padding</technical_language>

Target:
public int length() { int len = MIN_HEADER_LEN + vlanIDs.size() * 4 + childLength(); return pad ? Math.max(len, 60) : len; }
Source:
<code>public static String join(String[] array) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : array) { if (first) { first = false; } else { sb.append('.'); } sb.append(s); } <START> return sb.toString(); <END> }</code><technical_language>is reason for longer version? EDIT: ok, hibernate. String.join Java 8 though</technical_language>

Target:
public static String join(String[] array) { return join(Arrays.asList(array)); }
Source:
<code>public void shouldRejectNoAlternateVariants() throws Exception { <START> Variant input = new Variant("1", 1000, 1001, "A", "."); <END> Variant output = processor.process(input); assertEquals(Variant.VariantType.NO_ALTERNATE, input.getType()); assertNull(output); }</code><technical_language>forgot this one, I guess 1000 1000</technical_language>

Target:
public void shouldRejectNoAlternateVariants() throws Exception { Variant input = new Variant("1", 1000, 1000, "A", "."); Variant output = processor.process(input); assertEquals(Variant.VariantType.NO_ALTERNATE, input.getType()); assertNull(output); }
Source:
<code>public void created( BoltConnection connection ) { <START> activeConnections.put( connection.id(), connection ); <END> }</code><technical_language>assert #put() returns null</technical_language>

Target:
public void created( BoltConnection connection ) { BoltConnection previous = activeConnections.put( connection.id(), connection ); assert previous == null; }
Source:
<code>public void run() { try { int i = start; OpenTsdbClient client = null; while (i < end && !Thread.interrupted()) { if (client == null) { client = clientPool.get(); } try { String message = convert(metrics[i]); client.put(message); ++i; } catch (IOException ex) { log.error("Failed to write metric:", ex); clientPool.kill(client); client = null; } } service.incrementTotalProcessed(end - start); if (client != null) { try { client.flush(); String response = client.read(); if (response != null) { log.warn("Error detected writing metrics: {}", response); service.incrementTotalError(1); } } catch (SocketTimeoutException ex) { } catch (IOException ex) { log.error("Failed flushing or reading opentsdb response:", ex); clientPool.kill(client); client = null; } } <START> if (client != null) clientPool.put(client); <END> } catch (InterruptedException ignored) { } }</code><technical_language>feel if this is in a finally block</technical_language>

Target:
public void run() { try { OpenTsdbClient client = null; int i = 0; long size = metrics.size(); try { while (i < size && !Thread.interrupted()) { if (client == null) { client = clientPool.get(); } try { Metric metric = metrics.get(i); String message = convert(metric); client.put(message); ++i; } catch (IOException ex) { log.error("Failed to write metric:", ex); clientPool.kill(client); client = null; } } incrementProcessed(size, i); if (client != null) { try { client.flush(); String response = client.read(); if (response != null) { log.warn("Error detected writing metrics: {}", response); incrementError(); } } catch (SocketTimeoutException ex) { } catch (IOException ex) { log.error("Failed flushing or reading opentsdb response:", ex); clientPool.kill(client); client = null; } } } finally { if (client != null) { clientPool.put(client); client = null; } } } catch (InterruptedException ignored) { } }
Source:
<code>public void run() { try { LOG.info("Running Chaos Agent on : " + agentName); while (!this.isConnected()) { Thread.sleep(100); } this.getTasks(); while (!stopChaosAgent.get()) { Thread.sleep(500); } } catch (InterruptedException e) { <START> LOG.error("Error while running Chaos Agent"); <END> } }</code><technical_language>please provide e argument for stacktrace</technical_language>

Target:
public void run() { try { LOG.info("Running Chaos Agent on : " + agentName); while (!this.isConnected()) { Thread.sleep(100); } this.getTasks(); while (!stopChaosAgent.get()) { Thread.sleep(500); } } catch (InterruptedException e) { LOG.error("Error while running Chaos Agent", e); } }
Source:
<code>public void initStore(final Store<?, ?> resource) { StoreConfig storeConfig = createdStores.get(resource); if (storeConfig == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } final ClusteredStore clusteredStore = (ClusteredStore) resource; try { clusteredStore.storeProxy = clusteringService.getServerStoreProxy(storeConfig.getCacheIdentifier(), storeConfig.getStoreConfig(), storeConfig.getConsistency()); clusteredStore.storeProxy.addInvalidationListener(new ServerStoreProxy.InvalidationListener() { @Override public void onInvalidateHash(long hash) { if (clusteredStore.invalidationValve != null) { try { LOGGER.debug("CLIENT: calling invalidation valve for hash {}", hash); clusteredStore.invalidationValve.invalidateAllWithHash(hash); } catch (StoreAccessException sae) { LOGGER.error("Error invalidating hash {}", hash, sae); } } } @Override public void onInvalidateAll() { if (clusteredStore.invalidationValve != null) { try { LOGGER.debug("CLIENT: calling invalidation valve for all"); clusteredStore.invalidationValve.invalidateAll(); } catch (StoreAccessException sae) { LOGGER.error("Error invalidating all", sae); } } } }); } catch (CachePersistenceException e) { <START> throw new RuntimeException("Unable to create server store proxy - " + storeConfig.getCacheIdentifier(), e); <END> } }</code><technical_language>this try catch need this scope</technical_language>

Target:
public void initStore(final Store<?, ?> resource) { StoreConfig storeConfig = createdStores.get(resource); if (storeConfig == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } final ClusteredStore clusteredStore = (ClusteredStore) resource; try { clusteredStore.storeProxy = clusteringService.getServerStoreProxy(storeConfig.getCacheIdentifier(), storeConfig.getStoreConfig(), storeConfig.getConsistency()); } catch (CachePersistenceException e) { throw new RuntimeException("Unable to create server store proxy - " + storeConfig.getCacheIdentifier(), e); } clusteredStore.storeProxy.addInvalidationListener(new ServerStoreProxy.InvalidationListener() { @Override public void onInvalidateHash(long hash) { if (clusteredStore.invalidationValve != null) { try { LOGGER.debug("CLIENT: calling invalidation valve for hash {}", hash); clusteredStore.invalidationValve.invalidateAllWithHash(hash); } catch (StoreAccessException sae) { LOGGER.error("Error invalidating hash {}", hash, sae); } } } @Override public void onInvalidateAll() { if (clusteredStore.invalidationValve != null) { try { LOGGER.debug("CLIENT: calling invalidation valve for all"); clusteredStore.invalidationValve.invalidateAll(); } catch (StoreAccessException sae) { LOGGER.error("Error invalidating all", sae); } } } }); }
Source:
<code>public void activate() { logger.info("active"); <START> setProperlyConfigured(true); <END> }</code><technical_language>this Bindings needs configuration openhab.cfg setProperlyConfigured called configuration read applied properly (see method updated()</technical_language>

Target:
public void activate() { logger.info("active"); }
Source:
<code>public ImmutableDruidDataSource toImmutableDruidDataSource() { <START> return new ImmutableDruidDataSource(name, properties, partitionNames, Collections.unmodifiableSet(segmentsHolder)); <END> }</code><technical_language>This immutable- unmodifiableSet reflect changes in parent set</technical_language>

Target:
public ImmutableDruidDataSource toImmutableDruidDataSource() { return new ImmutableDruidDataSource( name, ImmutableMap.copyOf(properties), ImmutableMap.copyOf(partitionNames), ImmutableSet.copyOf(segmentsHolder) ); }
Source:
<code>public void shouldAllowRequestWithValidToken() throws IOException, ServletException { <START> when(request.getHeader(eq("Authentication"))).thenReturn("Talend myToken"); <END> filter.doFilter(request, response, filterChain); assertNotNull(capturedContext.get()); final Authentication authentication = capturedContext.get().getAuthentication(); assertNotNull(authentication); assertTrue(authentication.getAuthorities().stream().allMatch(g -> { final String authority = g.getAuthority(); return "ROLE_ACTUATOR".equals(authority) || "ROLE_VERSION".equals(authority); })); }</code><technical_language>suggestion when(request.getHeader(eq("Authorization"))).thenReturn("Talend myToken"); well</technical_language>

Target:
public void shouldAllowRequestWithValidToken() throws IOException, ServletException { when(request.getServletPath()).thenReturn("/actuator/prometheus"); when(request.getHeader(eq("Authorization"))).thenReturn("Talend myToken"); filter.doFilter(request, response, filterChain); assertNotNull(capturedAuthentication.get()); final Authentication authentication = capturedAuthentication.get(); assertTrue(authentication.getAuthorities().stream().allMatch(g -> { final String authority = g.getAuthority(); return "ROLE_ACTUATOR".equals(authority); })); }
Source:
<code>public NextAction repeat(StateExecution execution) { System.out.println("Counter: " + execution.getVariable(VAR_COUNTER)); execution.setVariable(VAR_COUNTER, execution.getVariable(VAR_COUNTER, Integer.class) + 1); <START> return NextAction.moveToStateAfter(State.repeat, DateTime.now().plusSeconds(10), "Next iteration"); <END> }</code><technical_language>static import for moveToStateAfter</technical_language>

Target:
public NextAction repeat(StateExecution execution) { System.out.println("Counter: " + execution.getVariable(VAR_COUNTER)); execution.setVariable(VAR_COUNTER, execution.getVariable(VAR_COUNTER, Integer.class) + 1); return moveToStateAfter(State.repeat, now().plusSeconds(10), "Next iteration"); }
Source:
<code>private void cleanupStack() { if (!stack.empty()) { RowType stackTop = stack.peek().getType(); switch (stackTop) { case SINGLE: break; case MULTI_START: stack.peek().setRowType(RowType.SINGLE); break; case MULTI_MID: stack.peek().setRowType(RowType.MULTI_END); break; case MULTI_END: break; case FIRST_ROW: <START> break; <END> } stack.clear(); } }</code><technical_language>default:</technical_language>

Target:
private void cleanupStack() { if (!stack.empty()) { RowType stackTop = stack.peek().getType(); switch (stackTop) { case SINGLE: break; case MULTI_START: stack.peek().setRowType(RowType.SINGLE); break; case MULTI_MID: stack.peek().setRowType(RowType.MULTI_END); break; case MULTI_END: break; case FIRST_ROW: break; default: throw new OseeStateException("Unhandled enumeration", stackTop); } stack.clear(); } }
Source:
<code>public Long create(Sample sample) throws IOException { loadChildEntities(sample); authorizationManager.throwIfNotWritable(sample); setChangeDetails(sample, true); if (sample.getSampleAdditionalInfo() != null) { if (sample.getSampleAdditionalInfo().getSampleClass() == null || sample.getSampleAdditionalInfo().getSampleClass().getSampleCategory() == null) { throw new IllegalArgumentException("Sample class or category missing"); } if (!Identity.CATEGORY_NAME.equals(sample.getSampleAdditionalInfo().getSampleClass().getSampleCategory())) { sample.getSampleAdditionalInfo().setParent(findOrCreateParent(sample)); validateHierarchy(sample); if (sample.getSampleAdditionalInfo().getGroupId() == null) { sample.getSampleAdditionalInfo().setGroupId(sample.getSampleAdditionalInfo().getParent().getSampleAdditionalInfo().getGroupId()); } if (sample.getSampleAdditionalInfo().getGroupDescription() == null) { sample.getSampleAdditionalInfo() .setGroupDescription(sample.getSampleAdditionalInfo().getParent().getSampleAdditionalInfo().getGroupDescription()); <START> } <END> } } sample.setName(generateTemporaryName()); if (isStringEmptyOrNull(sample.getAlias()) && sampleNamingScheme.hasGeneratorFor("alias")) { sample.setAlias(generateTemporaryName()); } else { validateAliasUniqueness(sample.getAlias()); } if (sample.getSampleAdditionalInfo() != null && sample.getParent() != null) { int siblingNumber = sampleDao.getNextSiblingNumber(sample.getParent(), sample.getSampleAdditionalInfo().getSampleClass()); sample.getSampleAdditionalInfo().setSiblingNumber(siblingNumber); } normalizeSample(sample); return save(sample).getId(); }</code><technical_language>I this behaviour is correct. understanding, is fine for a sample group ID if parent one. I "inherited changeable" idea is parent's group ID default in UI creating a sample, clearing is valid</technical_language>

Target:
public Long create(Sample sample) throws IOException { loadChildEntities(sample); authorizationManager.throwIfNotWritable(sample); setChangeDetails(sample, true); if (sample.getSampleAdditionalInfo() != null) { if (sample.getSampleAdditionalInfo().getSampleClass() == null || sample.getSampleAdditionalInfo().getSampleClass().getSampleCategory() == null) { throw new IllegalArgumentException("Sample class or category missing"); } if (!Identity.CATEGORY_NAME.equals(sample.getSampleAdditionalInfo().getSampleClass().getSampleCategory())) { sample.getSampleAdditionalInfo().setParent(findOrCreateParent(sample)); validateHierarchy(sample); } } sample.setName(generateTemporaryName()); if (isStringEmptyOrNull(sample.getAlias()) && sampleNamingScheme.hasGeneratorFor("alias")) { sample.setAlias(generateTemporaryName()); } else { validateAliasUniqueness(sample.getAlias()); } if (sample.getSampleAdditionalInfo() != null && sample.getParent() != null) { int siblingNumber = sampleDao.getNextSiblingNumber(sample.getParent(), sample.getSampleAdditionalInfo().getSampleClass()); sample.getSampleAdditionalInfo().setSiblingNumber(siblingNumber); } normalizeSample(sample); return save(sample).getId(); }
Source:
<code>public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_SUBSCRIPTION_KEY")) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT")) .buildClient(); String text = "Satya Nadella is the CEO of Microsoft"; client.recognizeEntities(text).getNamedEntities().forEach( entity -> System.out.printf( <START> "Recognized NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s", <END> entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), entity.getLength(), entity.getScore())); }</code><technical_language>add %n</technical_language>

Target:
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey("subscription-key") .endpoint("<LINK_0>") .buildClient(); String text = "Satya Nadella is the CEO of Microsoft"; for (NamedEntity entity : client.recognizeEntities(text).getNamedEntities()) { System.out.printf( "Recognized NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), entity.getLength(), entity.getScore()); } }
Source:
<code>URLConnection openURLConnection(URI object) throws IOException { URLConnection urlConnection = object.toURL().openConnection(); <START> if (!"".equals(httpAuthenticationUsername) && !"".equals(httpAuthenticationPasswordProvider.getPassword())) { <END> String userPass = httpAuthenticationUsername + ":" + httpAuthenticationPasswordProvider.getPassword(); String basicAuthString = "Basic " + Base64.getEncoder().encodeToString(StringUtils.toUtf8(userPass)); urlConnection.setRequestProperty("Authorization", basicAuthString); } return urlConnection; }</code><technical_language>httpAuthenticationUsername null. Strings.isNullOrEmpty()</technical_language>

Target:
URLConnection openURLConnection(URI object) throws IOException { URLConnection urlConnection = object.toURL().openConnection(); if (!Strings.isNullOrEmpty(httpAuthenticationUsername) && httpAuthenticationPasswordProvider != null) { String userPass = httpAuthenticationUsername + ":" + httpAuthenticationPasswordProvider.getPassword(); String basicAuthString = "Basic " + Base64.getEncoder().encodeToString(StringUtils.toUtf8(userPass)); urlConnection.setRequestProperty("Authorization", basicAuthString); } return urlConnection; }
Source:
<code>public RolledUpUsageModelDao(final UUID id, final DateTime createdDate, final DateTime updatedDate, final UUID subscriptionId, final String unitType, final LocalDate recordDate, final Long amount, final String trackingId) { super(id, createdDate, updatedDate); this.subscriptionId = subscriptionId; this.unitType = unitType; this.recordDate = recordDate; this.amount = amount; if(Strings.isNullOrEmpty(trackingId)){ <START> this.trackingId = UUID.randomUUID().toString(); <END> } else { this.trackingId = trackingId; } }</code><technical_language>warning: UUIDs instead (from org.killbill.billing.util). Kill Bill generates ids, a special, optimized, implementation</technical_language>

Target:
public RolledUpUsageModelDao(final UUID id, final DateTime createdDate, final DateTime updatedDate, final UUID subscriptionId, final String unitType, final LocalDate recordDate, final Long amount, final String trackingId) { super(id, createdDate, updatedDate); this.subscriptionId = subscriptionId; this.unitType = unitType; this.recordDate = recordDate; this.amount = amount; if(Strings.isNullOrEmpty(trackingId)){ this.trackingId = UUIDs.randomUUID().toString(); } else { this.trackingId = trackingId; } }
Source:
<code>private String getXForwardHeader(HttpServletRequest httpRequest) { Enumeration<String> names = httpRequest.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Enumeration<String> values = httpRequest.getHeaders(name); String value = ""; if (values != null) { while (values.hasMoreElements()) { <START> value = values.nextElement(); <END> } } if (StringUtils.trimToNull(name) != null && StringUtils.trimToNull(value) != null) { if (name.equalsIgnoreCase(TRUSTED_PROXY_KNOX_HEADER)) { return value; } } } return ""; }</code><technical_language>If header exists getHeader used. If more headers name of values checked one</technical_language>

Target:
private String getXForwardHeader(HttpServletRequest httpRequest) { Enumeration<String> names = httpRequest.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Enumeration<String> values = httpRequest.getHeaders(name); String value = ""; if (values != null) { while (values.hasMoreElements()) { value = values.nextElement(); if (StringUtils.isNotBlank(value)) { break; } } } if (StringUtils.trimToNull(name) != null && StringUtils.trimToNull(value) != null) { if (name.equalsIgnoreCase(TRUSTED_PROXY_KNOX_HEADER)) { return value; } } } return ""; }
Source:
<code>public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId != null) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); <START> if (id == EventDeclaration.UNSET_EVENT_ID) { <END> if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = event; } else { List<IEventDeclaration> eventsList = new ArrayList<>(); eventsList.addAll(fEvents); if (eventsList.size() > id && eventsList.get(id) != UNASSIGNED) { throw new ParseException("Event id already exists"); } while (eventsList.size() <= id) { eventsList.add(UNASSIGNED); } if (eventsList.get(id) == UNASSIGNED) { eventsList.set(id, event); } else { eventsList.add(event); } fEvents = ImmutableList.copyOf(eventsList); } }</code><technical_language>setting list SingletonList in this case, if try add else (set unset id) catch UnsupportedOperationException rethrow a ParseException</technical_language>

Target:
public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); if (id == EventDeclaration.UNSET_EVENT_ID) { if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = true; fEvents = ImmutableList.<IEventDeclaration>of(event); } else { List<IEventDeclaration> eventsList = new ArrayList<>(); eventsList.addAll(fEvents); if (eventsList.size() > id && eventsList.get(id) != UNASSIGNED) { throw new ParseException("Event id already exists"); } while (eventsList.size() <= id) { eventsList.add(UNASSIGNED); } if (eventsList.get(id) == UNASSIGNED) { eventsList.set(id, event); } else { eventsList.add(event); } fEvents = ImmutableList.copyOf(eventsList); } }
Source:
<code>public void setUp() { final InMemoryStorageFactory storageFactory = InMemoryStorageFactory.getInstance(); commandStore = spy(new CommandStore(storageFactory.createCommandStorage())); scheduler = spy(new ExecutorCommandScheduler()); log = spy(new ProblemLog()); commandBus = new CommandBus(commandStore, scheduler, log); <START> eventBus = Given.Event.newEventBus(storageFactory); <END> commandFactory = TestCommandFactory.newInstance(CommandBusShould.class); createProjectHandler = new CreateProjectHandler(newUuid()); responseObserver = new TestResponseObserver(); }</code><technical_language>avoid new prefix then, reads good: Given.eventBus()</technical_language>

Target:
public void setUp() { final InMemoryStorageFactory storageFactory = InMemoryStorageFactory.getInstance(); commandStore = spy(new CommandStore(storageFactory.createCommandStorage())); scheduler = spy(new ExecutorCommandScheduler()); log = spy(new ProblemLog()); commandBus = new CommandBus(commandStore, scheduler, log); eventBus = EventBusFactory.create(storageFactory); commandFactory = TestCommandFactory.newInstance(CommandBusShould.class); createProjectHandler = new CreateProjectHandler(newUuid()); responseObserver = new TestResponseObserver(); }
Source:
<code>public void saveScreenshot() { <START> FBO sceneFinalFbo = displayResolutionDependentFBOs.get(new ResourceUrn("engine:sceneFinal")); <END> final ByteBuffer buffer = sceneFinalFbo.getColorBufferRawData(); if (buffer == null) { logger.error("No screenshot data available. No screenshot will be saved."); return; } int width = sceneFinalFbo.width(); int height = sceneFinalFbo.height(); Runnable task = () -> { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); final String format = renderingConfig.getScreenshotFormat(); final String fileName = "Terasology-" + sdf.format(new Date()) + "-" + width + "x" + height + "." + format; Path path = PathManager.getInstance().getScreenshotPath().resolve(fileName); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int i = (x + width * y) * 4; int r = buffer.get(i) & 0xFF; int g = buffer.get(i + 1) & 0xFF; int b = buffer.get(i + 2) & 0xFF; image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b); } } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path))) { ImageIO.write(image, format, out); logger.info("Screenshot '" + fileName + "' saved! "); } catch (IOException e) { logger.warn("Failed to save screenshot!", e); } }; threadManager.submitTask("Write screenshot", task); isTakingScreenshot = false; }</code><technical_language>get() method is ok, move ResourceUrn a static final field</technical_language>

Target:
public void saveScreenshot() { if (displayResolutionDependentFBOs == null) displayResolutionDependentFBOs = CoreRegistry.get(DisplayResolutionDependentFBOs.class); FBO sceneFinalFbo = displayResolutionDependentFBOs.get(FINAL_BUFFER); final ByteBuffer buffer = sceneFinalFbo.getColorBufferRawData(); if (buffer == null) { logger.error("No screenshot data available. No screenshot will be saved."); return; } int width = sceneFinalFbo.width(); int height = sceneFinalFbo.height(); Runnable task = () -> { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); final String format = renderingConfig.getScreenshotFormat(); final String fileName = "Terasology-" + sdf.format(new Date()) + "-" + width + "x" + height + "." + format; Path path = PathManager.getInstance().getScreenshotPath().resolve(fileName); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int i = (x + width * y) * 4; int r = buffer.get(i) & 0xFF; int g = buffer.get(i + 1) & 0xFF; int b = buffer.get(i + 2) & 0xFF; image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b); } } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path))) { ImageIO.write(image, format, out); logger.info("Screenshot '" + fileName + "' saved! "); } catch (IOException e) { logger.warn("Failed to save screenshot!", e); } }; threadManager.submitTask("Write screenshot", task); isTakingScreenshot = false; }
Source:
<code><START> public VelocityNavigateEditMode( <END> final HttpServletRequest request, final HttpServletResponse response, final IHTMLPage htmlPage, final Host host) { super(request, response, htmlPage, host); uri = CMSUrlUtil.getCurrentURI(request); this.setMode(this.getMode()); this.user = WebAPILocator.getUserWebAPI().getUser(request); }</code><technical_language>constructor signature changed</technical_language>

Target:
protected VelocityNavigateEditMode( final HttpServletRequest request, final HttpServletResponse response, final IHTMLPage htmlPage, final Host host) { super(request, response, htmlPage, host); uri = CMSUrlUtil.getCurrentURI(request); this.setMode(this.getMode()); this.user = WebAPILocator.getUserWebAPI().getUser(request); }
Source:
<code>public void cleanupEvents(long time) { final String tableName = EventRecordContract.TABLE; final SQLiteDatabase db = getWritableDatabase(); try { int result = db.delete(EventRecordContract.TABLE, EventRecordContract.Col.POSTED_TIMESTAMP.getName() + " IS NOT NULL OR " + EventRecordContract.Col.RECORDED_TIMESTAMP.getName() + " < " + Long.toString(time) + " OR " + EventRecordContract.Col.POST_ATTEMPTS.getName() + " > 3", null); L.d("cleaned " + Integer.toString(result) + " event records"); } catch <START> (final SQLiteException <END> e) { L.e("Could not clean sent EventLogging records from " + tableName + ". Re-initializing database.", e); deleteDB(); } finally { db.close(); } }</code><technical_language>final</technical_language>

Target:
public void cleanupEvents(long time) { final String tableName = EventRecordContract.TABLE; final SQLiteDatabase db = getWritableDatabase(); try { int result = db.delete(EventRecordContract.TABLE, EventRecordContract.Col.POSTED_TIMESTAMP.getName() + " IS NOT NULL OR " + EventRecordContract.Col.RECORDED_TIMESTAMP.getName() + " < " + Long.toString(time) + " OR " + EventRecordContract.Col.POST_ATTEMPTS.getName() + " > 3", null); L.d("cleaned " + Integer.toString(result) + " event records"); } catch (SQLiteException e) { L.e("Could not clean sent EventLogging records from " + tableName + ". Re-initializing database.", e); deleteDB(); } finally { db.close(); } }
Source:
<code>public SensorPersistenceMode getPersistenceMode() { <START> return persistence; <END> }</code><technical_language>is worth adding if null return REQUIRED, prevent persisted items returning null here? explicit @Nullable</technical_language>

Target:
public SensorPersistenceMode getPersistenceMode() { return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; }
Source:
<code>public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); <START> } <END></code><technical_language>@Override public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); super.restart(launchMode); }</technical_language>

Target:
public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); super.restart(launchMode); }
Source:
<code>public void cleanup() { <START> for (final Map.Entry<Reporter.Channel, Reporter> e : reporters.entrySet()) { <END> final AbstractReporterImpl reporter = (AbstractReporterImpl) e.getValue(); reporter.cleanup(); } tempFileSpace.cleanup(); }</code><technical_language>Tests failing CI here</technical_language>

Target:
public void cleanup() { for (final Reporter.Channel channel : Reporter.Channel.values()) { final AbstractReporterImpl reporter = (AbstractReporterImpl) reporters.get(channel); try { reporter.cleanup(); } catch (Exception ex) { } } tempFileSpace.cleanup(); }