auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void doSave(final AsyncCallback<Account> onSave) { String newName = canEditFullName() ? nameTxt.getText() : null; <START> if ("".equals(newName.trim())) { <END> newName = null; } final String newEmail; if (emailPick.isEnabled() && emailPick.getSelectedIndex() >= 0) { final String v = emailPick.getValue(emailPick.getSelectedIndex()); if (Util.C.buttonOpenRegisterNewEmail().equals(v)) { newEmail = currentEmail; } else { newEmail = v; } } else { newEmail = currentEmail; } final ContactInformation info = toContactInformation(); save.setEnabled(false); registerNewEmail.setEnabled(false); Util.ACCOUNT_SEC.updateContact(newName, newEmail, info, new GerritCallback<Account>() { public void onSuccess(final Account result) { registerNewEmail.setEnabled(true); onSaveSuccess(result); if (onSave != null) { onSave.onSuccess(result); } } @Override public void onFailure(final Throwable caught) { save.setEnabled(true); registerNewEmail.setEnabled(true); super.onFailure(caught); } }); }</code><technical_language>newName null</technical_language>

Target:
void doSave(final AsyncCallback<Account> onSave) { String newName = canEditFullName() ? nameTxt.getText() : null; if (newName != null && newName.trim().isEmpty()) { newName = null; } final String newEmail; if (emailPick.isEnabled() && emailPick.getSelectedIndex() >= 0) { final String v = emailPick.getValue(emailPick.getSelectedIndex()); if (Util.C.buttonOpenRegisterNewEmail().equals(v)) { newEmail = currentEmail; } else { newEmail = v; } } else { newEmail = currentEmail; } final ContactInformation info = toContactInformation(); save.setEnabled(false); registerNewEmail.setEnabled(false); Util.ACCOUNT_SEC.updateContact(newName, newEmail, info, new GerritCallback<Account>() { public void onSuccess(final Account result) { registerNewEmail.setEnabled(true); onSaveSuccess(result); if (onSave != null) { onSave.onSuccess(result); } } @Override public void onFailure(final Throwable caught) { save.setEnabled(true); registerNewEmail.setEnabled(true); super.onFailure(caught); } }); }
Source:
<code>public void testConvertProfileGenericDataResponseVo() { ProfileGenericDataResponseDto responseDto = this.makeResponseDto(); ProfileGenericDataResponse responseVo = this.mapper.map(responseDto, ProfileGenericDataResponse.class); <START> assertTrue(responseVo != null); <END> assertTrue(responseVo.getProfileEntries().get(0).getProfileEntryValues().size() == EXPECTED_CLASS.length); int i = 0; for (ProfileEntryValue profileEntryValueVo : responseVo.getProfileEntries().get(0).getProfileEntryValues()) { Class<?> clazz = profileEntryValueVo.getValue().getClass(); assertTrue(EXPECTED_CLASS[i++].equals(clazz)); } }</code><technical_language>I assertNotNull</technical_language>

Target:
public void testConvertProfileGenericDataResponseVo() { ProfileGenericDataResponseDto responseDto = this.makeResponseDto(); ProfileGenericDataResponse responseVo = this.mapper.map(responseDto, ProfileGenericDataResponse.class); assertNotNull("response object should not be null", responseVo); assertEquals("response object should return same number of profilentries", responseVo.getProfileEntries() .get(0).getProfileEntryValues().size(), EXPECTED_CLASS.length); int i = 0; for (ProfileEntryValue profileEntryValueVo : responseVo.getProfileEntries().get(0).getProfileEntryValues()) { Class<?> clazz = profileEntryValueVo.getValue().getClass(); assertEquals("the return class should be of the same type", EXPECTED_CLASS[i++], clazz); } }
Source:
<code>BlobOutputStream(final BlockBlobAsyncClient parentBlob, final BlobAccessConditions accessCondition) throws StorageException { this(parentBlob, accessCondition, null, UUID.randomUUID().toString() + "-", new TreeMap<>(), 0, <START> BlobType.BLOCK_BLOB, BlockBlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE); <END> }</code><technical_language>argument is BlockBlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE, argument name is internalWriteThreshold. I this is there, is weird naming? // @alzimmermsft</technical_language>

Target:
BlobOutputStream(final BlockBlobAsyncClient parentBlob, final BlobAccessConditions accessCondition) throws StorageException { this((BlobAsyncClient) parentBlob); this.accessCondition = accessCondition; this.blockList = new TreeMap<>(); this.blockIdPrefix = UUID.randomUUID().toString() + "-"; this.streamType = BlobType.BLOCK_BLOB; this.internalWriteThreshold = (int) BlockBlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE; }
Source:
<code>public void run() { try { startDiscovery(); while (shouldRun) { try { DiscoveryServiceEvent event = eventQueue.take(); processEvent(event); } catch (Exception e) { log.error("Caught an exception. Stop discovery service.", e); shouldRun = false; stopLogReplication(); if (e instanceof InterruptedException) { Thread.interrupted(); } } } } catch (Exception e) { <START> log.error("Unhandled exception caught during log replication service discovery. Retry,", e); <END> } finally { runtime.cleanup(CorfuRuntime::shutdown); } }</code><technical_language>curious, is this 'Retry' in log error a leftover? retry..</technical_language>

Target:
public void run() { try { startDiscovery(); while (shouldRun) { try { DiscoveryServiceEvent event = eventQueue.take(); processEvent(event); } catch (Exception e) { log.error("Caught an exception. Stop discovery service.", e); shouldRun = false; stopLogReplication(); if (e instanceof InterruptedException) { Thread.interrupted(); } } } } catch (Exception e) { log.error("Unhandled exception caught during log replication service discovery.", e); } finally { runtime.cleanup(CorfuRuntime::shutdown); interClusterReplicationService.close(); } }
Source:
<code>static float getProgressForMedia(MediaModel media) { if (!sProgressByMediaId.containsKey(media.getId())) { return 1; } <START> float uploadProgress = sProgressByMediaId.get(media.getId()); <END> if (media.isVideo() && WPMediaUtils.isVideoOptimizationEnabled()) { if (sOptimizationProgressByMediaId.containsKey(media.getId())) { float optimizationProgress = sOptimizationProgressByMediaId.get(media.getId()); return optimizationProgress * 0.5F; } return 0.5F + (uploadProgress * 0.5F); } return uploadProgress; }</code><technical_language>a distinction optimisation progress upload progress, rename this var sProgressByMediaId sUploadProgressByMediaId match naming structure of sOptimizationProgressByMediaId</technical_language>

Target:
static float getProgressForMedia(MediaModel media) { Float progress = sUploadProgressByMediaId.get(media.getId()); float uploadProgress = progress == null ? 0 : progress; if (media.isVideo() && WPMediaUtils.isVideoOptimizationEnabled()) { if (sOptimizationProgressByMediaId.containsKey(media.getId())) { float optimizationProgress = sOptimizationProgressByMediaId.get(media.getId()); return optimizationProgress * 0.5F; } return 0.5F + (uploadProgress * 0.5F); } return uploadProgress; }
Source:
<code>public void editBufferSizeInvalid() throws Exception { final int value = -1; <START> ModelNodeResult originalModelNodeResult = operations.readAttribute(BUFFER_POOL_ADDRESS, BUFFER_SIZE); <END> originalModelNodeResult.assertSuccess(); try { new ConfigChecker.Builder(client, BUFFER_POOL_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.TEXT, BUFFER_SIZE, String.valueOf(value)) .verifyFormNotSaved(); } finally { operations.writeAttribute(BUFFER_POOL_ADDRESS, BUFFER_SIZE, originalModelNodeResult.value()); } }</code><technical_language>Please rename originalBufferSizeResult originalResult</technical_language>

Target:
public void editBufferSizeInvalid() throws Exception { final int value = -1; final ModelNodeResult originalModelNodeResult = operations.readAttribute(BUFFER_POOL_ADDRESS, BUFFER_SIZE); originalModelNodeResult.assertSuccess(); try { new ConfigChecker.Builder(client, BUFFER_POOL_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.TEXT, BUFFER_SIZE, String.valueOf(value)) .verifyFormNotSaved(); } finally { operations.writeAttribute(BUFFER_POOL_ADDRESS, BUFFER_SIZE, originalModelNodeResult.value()); } }
Source:
<code>public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException { LOG.debug("CXFSAMLCallbackHandler.handle begin-Minh version 111111"); for (final Callback callback : callbacks) { if (callback instanceof SAMLCallback) { try { final Message message = getCurrentMessage(); final Object obj = message.get("assertion"); AssertionType custAssertion = null; if (obj != null) { custAssertion = (AssertionType) obj; } final SAMLCallback oSAMLCallback = (SAMLCallback) callback; oSAMLCallback.setIssuerKeyName("gateway"); oSAMLCallback.setIssuerKeyPassword("changeit"); oSAMLCallback.setSignAssertion(true); oSAMLCallback.setSendKeyValue(true); issuerCrypto = CryptoFactory.getInstance("signature.properties"); oSAMLCallback.setIssuerCrypto(issuerCrypto); oSAMLCallback.setSamlVersion(Version.SAML_20); oSAMLCallback.setSignatureAlgorithm(SPConstants.SHA1); oSAMLCallback.setSignatureDigestAlgorithm(SPConstants.SHA1); final SamlTokenCreator creator = new SamlTokenCreator(); final CallbackProperties properties = new CallbackMapProperties(addMessageProperties( creator.createRequestContext(custAssertion, getResource(message), null), message)); oSAMLCallback.setAssertionElement(builder.build(properties)); } catch (final Exception e) { LOG.error("Failed to create saml: {}", e.getLocalizedMessage(), e); } } } <START> LOG.debug("CXFSAMLCallbackHandler.handle end"); <END> }</code><technical_language>above. Change this trace</technical_language>

Target:
public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException { LOG.trace("CXFSAMLCallbackHandler.handle begin"); for (final Callback callback : callbacks) { if (callback instanceof SAMLCallback) { try { final Message message = getCurrentMessage(); final Object obj = message.get("assertion"); AssertionType custAssertion = null; if (obj != null) { custAssertion = (AssertionType) obj; } final SAMLCallback oSAMLCallback = (SAMLCallback) callback; oSAMLCallback.setIssuerKeyName("gateway"); oSAMLCallback.setIssuerKeyPassword("changeit"); oSAMLCallback.setSignAssertion(true); oSAMLCallback.setSendKeyValue(true); issuerCrypto = CryptoFactory.getInstance("signature.properties"); oSAMLCallback.setIssuerCrypto(issuerCrypto); oSAMLCallback.setSamlVersion(Version.SAML_20); oSAMLCallback.setSignatureAlgorithm(SPConstants.SHA1); oSAMLCallback.setSignatureDigestAlgorithm(SPConstants.SHA1); final SamlTokenCreator creator = new SamlTokenCreator(); final CallbackProperties properties = new CallbackMapProperties(addMessageProperties( creator.createRequestContext(custAssertion, getResource(message), null), message)); oSAMLCallback.setAssertionElement(builder.build(properties)); } catch (final Exception e) { LOG.error("Failed to create saml: {}", e.getLocalizedMessage(), e); } } } LOG.trace("CXFSAMLCallbackHandler.handle end"); }
Source:
<code>public Object execute() { String key = getKey(); Optional<byte[]> value = blobStore.get(key, THRESHOLDING_KV_CONTEXT); if (value.isPresent()) { System.out.println(fst.asObject(value.get()).toString()); } else { <START> System.out.println(String.format("Could not find a state for key '%s'", key)); <END> } return null; }</code><technical_language>suggestion System.out.printf("Could find a state for key '%s'\n", key);</technical_language>

Target:
public Object execute() { String key = getKey(); Optional<byte[]> value = blobStore.get(key, THRESHOLDING_KV_CONTEXT); if (value.isPresent()) { System.out.println(fst.asObject(value.get()).toString()); } else { System.out.printf("Could not find a state for key '%s'\n", key); } return null; }
Source:
<code>public static String configToConnectionString(QuorumVerifier data) throws Exception { StringBuilder sb = new StringBuilder(); for ( QuorumPeer.QuorumServer server : data.getAllMembers().values() ) { if ( server.clientAddr == null ) { <START> continue; <END> } if ( sb.length() != 0 ) { sb.append(","); } InetAddress wildcardAddress = new InetSocketAddress(0).getAddress(); String hostAddress; if ( wildcardAddress.equals(server.clientAddr.getAddress()) ) { hostAddress = server.addr.getAddress().getHostAddress(); } else { hostAddress = server.clientAddr.getAddress().getHostAddress(); } sb.append(hostAddress).append(":").append(server.clientAddr.getPort()); } return sb.toString(); }</code><technical_language>spec of server address is server.<positive id> = <address1>:<port1>:<port2>[:role];[<client port address>:]<client port>, if server.clientAddr is null means client port address is present. client port address is optional, address is a valid address</technical_language>

Target:
public static String configToConnectionString(QuorumVerifier data) throws Exception { StringBuilder sb = new StringBuilder(); for ( QuorumPeer.QuorumServer server : data.getAllMembers().values() ) { if ( server.clientAddr == null ) { continue; } if ( sb.length() != 0 ) { sb.append(","); } String hostAddress; if ( server.clientAddr.getAddress().isAnyLocalAddress() ) { hostAddress = server.addr.getAddress().getHostAddress(); } else { hostAddress = server.clientAddr.getAddress().getHostAddress(); } sb.append(hostAddress).append(":").append(server.clientAddr.getPort()); } return sb.toString(); }
Source:
<code>protected void updateDetailsAvailability() { if (getSelectedItem() != null) { Disk disk = getSelectedItem(); <START> vmListModel.setIsAvailable(disk.getVmEntityType() == null || !disk.getVmEntityType().isTemplateType()); <END> templateListModel.setIsAvailable(isTemplateDisk(disk)); storageListModel.setIsAvailable(disk.getDiskStorageType() == DiskStorageType.IMAGE || disk.getDiskStorageType() == DiskStorageType.CINDER); } }</code><technical_language>I this section is exactly: "!isTemplateDisk(disk)"</technical_language>

Target:
protected void updateDetailsAvailability() { if (getSelectedItem() != null) { Disk disk = getSelectedItem(); vmListModel.setIsAvailable(!isTemplateDisk(disk)); templateListModel.setIsAvailable(isTemplateDisk(disk)); storageListModel.setIsAvailable(disk.getDiskStorageType() == DiskStorageType.IMAGE || disk.getDiskStorageType() == DiskStorageType.CINDER); } }
Source:
<code>static void addCommitStep(final OperationContext context, final ConfigurationPersistence configurationPersistence) { context.addStep(new CommitOperationStepHandler(configurationPersistence), Stage.RUNTIME); final Collection<OperationStepHandler> afterCommitSteps = context.getAttachment(AFTER_COMMIT_STEPS); if (afterCommitSteps != null && !afterCommitSteps.isEmpty()) { for (OperationStepHandler step : afterCommitSteps) { context.addStep(step, Stage.RUNTIME); <START> } <END> context.addStep(new CommitOperationStepHandler(configurationPersistence), Stage.RUNTIME); } }</code><technical_language>this get called more in op, after-commit steps get added multiple times? of addCommitStep happen</technical_language>

Target:
static void addCommitStep(final OperationContext context, final ConfigurationPersistence configurationPersistence) { context.addStep(new CommitOperationStepHandler(configurationPersistence), Stage.RUNTIME); final Collection<OperationStepHandler> afterCommitSteps = context.detach(AFTER_COMMIT_STEPS); if (afterCommitSteps != null && !afterCommitSteps.isEmpty()) { for (OperationStepHandler step : afterCommitSteps) { context.addStep(step, Stage.RUNTIME); } context.addStep(new CommitOperationStepHandler(configurationPersistence), Stage.RUNTIME); } }
Source:
<code>protected Type getNewMethodType(ASTRewrite rewrite, ImportRewriteContext context) throws CoreException { AST ast= rewrite.getAST(); return <START> ast.newSimpleType(ast.newSimpleName(fReturnType)); <END> }</code><technical_language>This creates uncompilable code if return type is visible simple name. getImportRewrite().addImport(..). Question is: overload suites needs here, passing in simple name fReturnType is insufficient</technical_language>

Target:
protected Type getNewMethodType(ASTRewrite rewrite, ImportRewriteContext context) throws CoreException { AST ast= rewrite.getAST(); getImportRewrite().addImport(fReturnType.getFullyQualifiedName()); return ast.newSimpleType(ast.newSimpleName(fReturnType.getElementName())); }
Source:
<code>protected GetFeatureRequest createGetFeature(Query query, ResultType resultType) throws IOException { GetFeatureRequest request = client.createGetFeatureRequest(); final WFSDataStore dataStore = getDataStore(); final QName remoteTypeName = dataStore.getRemoteTypeName(getEntry().getName()); final SimpleFeatureType remoteSimpleFeatureType; remoteSimpleFeatureType = dataStore.getRemoteSimpleFeatureType(remoteTypeName); request.setTypeName(remoteTypeName); request.setFullType(remoteSimpleFeatureType); <START> removeFastBBOXFilterIfNeeded(query); <END> invertAxisInFilterIfNeeded(query, remoteSimpleFeatureType); request.setFilter(query.getFilter()); request.setResultType(resultType); request.setHints(query.getHints()); int maxFeatures = query.getMaxFeatures(); if (Integer.MAX_VALUE > maxFeatures) { request.setMaxFeatures(maxFeatures); } request.setPropertyNames(query.getPropertyNames()); request.setSortBy(query.getSortBy()); String srsName = getSupportedSrsName(request, query); request.setSrsName(srsName); return request; }</code><technical_language>A hacky alternative (untested): if (query.getFilter() != null) { DuplicatingFilterVisitor duplicator = new DuplicatingFilterVisitor(); Filter copy = (Filter) query.getFilter().accept(duplicator, null); query.setFilter(copy); } Tests passing this method instead of double inversion</technical_language>

Target:
protected GetFeatureRequest createGetFeature(Query query, ResultType resultType) throws IOException { GetFeatureRequest request = client.createGetFeatureRequest(); final WFSDataStore dataStore = getDataStore(); final QName remoteTypeName = dataStore.getRemoteTypeName(getEntry().getName()); final SimpleFeatureType remoteSimpleFeatureType; remoteSimpleFeatureType = dataStore.getRemoteSimpleFeatureType(remoteTypeName); request.setTypeName(remoteTypeName); request.setFullType(remoteSimpleFeatureType); invertAxisInFilterIfNeeded(query, remoteSimpleFeatureType); request.setFilter(query.getFilter()); request.setResultType(resultType); request.setHints(query.getHints()); int maxFeatures = query.getMaxFeatures(); if (Integer.MAX_VALUE > maxFeatures) { request.setMaxFeatures(maxFeatures); } request.setPropertyNames(query.getPropertyNames()); request.setSortBy(query.getSortBy()); String srsName = getSupportedSrsName(request, query); request.setSrsName(srsName); return request; }
Source:
<code>private V computeInternal(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, boolean computeIfPresent, Metadata metadata, long flags) { <START> return computeInternal(key, remappingFunction, computeIfPresent, metadata, flags, this::singleKeyContextWithImplicitTransaction); <END> }</code><technical_language>Please cache method reference - this is a capturing method handle => allocation</technical_language>

Target:
private V computeInternal(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, boolean computeIfPresent, Metadata metadata, long flags) { return computeInternal(key, remappingFunction, computeIfPresent, metadata, flags, contextBuilder); }
Source:
<code>public Computation execute(String program) { <START> return new Computation(this.transport, program, new HashMap<String, String>(), false); <END> }</code><technical_language>Nit: Collections.emptyMap(); avoids allocation</technical_language>

Target:
public Computation execute(String program) { return new Computation(this.transport, program, Collections.<String, String> emptyMap(), false); }
Source:
<code>public void changeSharingScope() throws Exception { TestUtils.mockPlay().withJsonBody("{\"scope\":\"all_qualified_researchers\"}").mock(); Result result = controller.changeSharingScope(); assertEquals(200, result.status()); UserSession retrievedSession = TestUtils.getResponsePayload(result, UserSession.class); assertEquals(ORIGINAL_SESSION_TOKEN, retrievedSession.getSessionToken()); verify(accountDao).editAccount(eq(TestConstants.TEST_STUDY), eq(HEALTH_CODE), any()); <START> verify(sessionUpdateService).updateSharingScope(session, SharingScope.ALL_QUALIFIED_RESEARCHERS); <END> }</code><technical_language>mock editAccount() call passed in function pointer verify account.setSharingScope() is called</technical_language>

Target:
public void changeSharingScope() throws Exception { TestUtils.mockPlay().withJsonBody("{\"scope\":\"all_qualified_researchers\"}").mock(); Result result = controller.changeSharingScope(); assertEquals(200, result.status()); UserSession retrievedSession = TestUtils.getResponsePayload(result, UserSession.class); assertEquals(ORIGINAL_SESSION_TOKEN, retrievedSession.getSessionToken()); verify(accountDao).editAccount(eq(TestConstants.TEST_STUDY), eq(HEALTH_CODE), accountConsumerCaptor.capture()); verify(sessionUpdateService).updateSharingScope(session, SharingScope.ALL_QUALIFIED_RESEARCHERS); Consumer<Account> accountConsumer = accountConsumerCaptor.getValue(); Account account = Mockito.mock(Account.class); accountConsumer.accept(account); verify(account).setSharingScope(SharingScope.ALL_QUALIFIED_RESEARCHERS); }
Source:
<code>public Void visit(GenContext state, Case ast) { <START> return null; <END> }</code><technical_language>Need Case's ast</technical_language>

Target:
public Void visit(GenContext state, Case ast) { ast.getAST().acceptVisitor(this, state); return null; }
Source:
<code><START> private void printSession(RestSession session) <END> { ln("session id: %d", session.getId()); ln("attempt id: %s", session.getLastAttempt().transform(a -> String.valueOf(a.getId())).or("")); ln("uuid: %s", session.getSessionUuid()); ln("project: %s", session.getProject().getName()); ln("workflow: %s", session.getWorkflow().getName()); ln("session time: %s", TimeUtil.formatTime(session.getSessionTime())); ln("retry attempt name: %s", session.getLastAttempt().transform(a -> a.getRetryAttemptName().or("")).or("")); ln("params: %s", session.getLastAttempt().transform(a -> a.getParams().toString()).or("")); ln("created at: %s", session.getLastAttempt().transform(a -> TimeUtil.formatTime(a.getCreatedAt())).or("")); ln("kill requested: %s", session.getLastAttempt().transform(a -> a.getCancelRequested()).or(false)); ln("status: %s", status(session)); ln(""); }</code><technical_language>I people expect --format json option shows session in json format. rejected a message --format "json" is allowed show session. improve this in future</technical_language>

Target:
private void printSession(RestSession session) throws IOException { EntityPrinter<RestSession> printer = new EntityPrinter<>(); printer.field("session id", s -> Long.toString(s.getId())); printer.field("attempt id", s -> s.getLastAttempt().transform(a -> Long.toString(a.getId())).or("")); printer.field("uuid", s -> s.getSessionUuid().toString()); printer.field("project", s -> s.getProject().getName()); printer.field("workflow", s -> s.getWorkflow().getName()); printer.field("session time", s -> TimeUtil.formatTime(s.getSessionTime())); printer.field("retry attempt name", s -> s.getLastAttempt().transform(a -> a.getRetryAttemptName().or("")).or("")); printer.field("params", s -> s.getLastAttempt().transform(a -> a.getParams().toString()).or("")); printer.field("created at", s -> s.getLastAttempt().transform(a -> TimeUtil.formatTime(a.getCreatedAt())).or("")); printer.field("kill requested", s -> Boolean.toString(s.getLastAttempt().transform(a -> a.getCancelRequested()).or(false))); printer.field("status", this::status); printer.print(format, session, out); }
Source:
<code>public static JsonSchema generateJsonSchema(JsonSchemaExternalType jsonTypeDefinition) throws IOException, ProcessingException { <START> String includedResourceURI = null; <END> TypeDeclarationNode typeDeclarationNode = jsonTypeDefinition.getTypeDeclarationNode(); List<ExternalSchemaTypeExpressionNode> schemas = typeDeclarationNode.findDescendantsWith(ExternalSchemaTypeExpressionNode.class); if (schemas.size() > 0) { includedResourceURI = schemas.get(0).getStartPosition().getIncludedResourceURI(); } else { List<NamedTypeExpressionNode> refNode = typeDeclarationNode.findDescendantsWith(NamedTypeExpressionNode.class); if (refNode.size() > 0) { typeDeclarationNode = refNode.get(0).resolveReference(); if (typeDeclarationNode != null) { schemas = typeDeclarationNode.findDescendantsWith(ExternalSchemaTypeExpressionNode.class); if (schemas.size() > 0) { includedResourceURI = schemas.get(0).getStartPosition().getIncludedResourceURI(); } } } } JsonNode jsonSchema = JsonLoader.fromString(jsonTypeDefinition.getSchemaValue()); JsonSchemaFactory factory = JsonSchemaFactory.newBuilder().freeze(); if (jsonTypeDefinition.getInternalFragment() != null) { return factory.getJsonSchema(jsonSchema, "/definitions/" + jsonTypeDefinition.getInternalFragment()); } else { if (includedResourceURI != null) { return factory.getJsonSchema(includedResourceURI); } else { return factory.getJsonSchema(jsonSchema); } } }</code><technical_language>move this logic a separate method, resolveResourceURI</technical_language>

Target:
public static JsonSchema generateJsonSchema(JsonSchemaExternalType jsonTypeDefinition) throws IOException, ProcessingException { String includedResourceUri = resolveResourceUriIfIncluded(jsonTypeDefinition); JsonNode jsonSchema = JsonLoader.fromString(jsonTypeDefinition.getSchemaValue()); JsonSchemaFactory factory = JsonSchemaFactory.newBuilder().freeze(); if (jsonTypeDefinition.getInternalFragment() != null) { return factory.getJsonSchema(jsonSchema, "/definitions/" + jsonTypeDefinition.getInternalFragment()); } else { if (includedResourceUri != null) { return factory.getJsonSchema(includedResourceUri); } else { return factory.getJsonSchema(jsonSchema); } } }
Source:
<code>XlsxWriter(Path target, Workbook workbook, TimeZone timeZone) { this.target = requireNonNull(target); this.workbook = requireNonNull(workbook); this.timeZone = requireNonNull(timeZone); <START> this.simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd"); <END> simpleDateFormat.setTimeZone(timeZone); this.simpleDateTimeFormat = new SimpleDateFormat("YYYY-MM-dd'T'hh:mm:ssZ"); simpleDateTimeFormat.setTimeZone(timeZone); }</code><technical_language>SonarLint reports in IntelliJ: Bug Major squid:S3986 Week Year ("YYYY") for date formatting</technical_language>

Target:
XlsxWriter(Path target, Workbook workbook, TimeZone timeZone) { this.target = requireNonNull(target); this.workbook = requireNonNull(workbook); this.timeZone = requireNonNull(timeZone); this.simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); simpleDateFormat.setTimeZone(timeZone); this.simpleDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); simpleDateTimeFormat.setTimeZone(timeZone); }
Source:
<code>@Ignore @Test public void annotatedArrayType() { TypeName type = ArrayTypeName.of(ClassName.get(Object.class)).annotated(TYPE_USE_ANNOTATION); <START> assertThat(type.toString()).isEqualTo("java.lang.Object @" + TUA + " []"); <END> }</code><technical_language>this counterintuitive me. annotation is outermost type, printed here? (not incorrect, wow, this feature is weird)</technical_language>

Target:
@Test public void annotatedArrayType() { TypeName type = ArrayTypeName.of(ClassName.get(Object.class)).annotated(TYPE_USE_ANNOTATION); assertThat(type.toString()).isEqualTo("java.lang.Object @" + TUA + " []"); }
Source:
<code>public void writePage(BytesInput bytes, int valueCount, Statistics statistics, Encoding rlEncoding, Encoding dlEncoding, Encoding valuesEncoding) throws IOException { long uncompressedSize = bytes.size(); if (uncompressedSize > Integer.MAX_VALUE) { throw new ParquetEncodingException( "Cannot write page larger than Integer.MAX_VALUE bytes: " + uncompressedSize); } BytesInput compressedBytes = compressor.compress(bytes); long compressedSize = compressedBytes.size(); if (compressedSize > Integer.MAX_VALUE) { throw new ParquetEncodingException( "Cannot write compressed page larger than Integer.MAX_VALUE bytes: " + compressedSize); } tempOutputStream.reset(); final PageHeader pageHeader = parquetMetadataConverter.writeDataPageHeader( (int)uncompressedSize, (int)compressedSize, valueCount, statistics, rlEncoding, dlEncoding, valuesEncoding, tempOutputStream); this.uncompressedLength += uncompressedSize; this.compressedLength += compressedSize; this.totalValueCount += valueCount; this.pageCount += 1; this.totalStatistics.mergeStatistics(statistics); buf.collect(BytesInput.concat(BytesInput.from(tempOutputStream), compressedBytes)); encodings.add(rlEncoding); encodings.add(dlEncoding); encodings.add(valuesEncoding); <START> pageHeaderWithOffsets.add(new PageHeaderWithOffset(pageHeader, -1, tempOutputStream.size())); <END> }</code><technical_language>store relative datapage instead of -1 here</technical_language>

Target:
public void writePage(BytesInput bytes, int valueCount, Statistics statistics, Encoding rlEncoding, Encoding dlEncoding, Encoding valuesEncoding) throws IOException { bufferedPages.add(new PageV1Holder(pageCount, bytes, valueCount, statistics, rlEncoding, dlEncoding, valuesEncoding)); }
Source:
<code>public void testArcUserAssigned() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration(); String token1 = "token1"; String endpoint = "http://localhost"; TokenRequestContext request = new TokenRequestContext().addScopes("<LINK_0>"); OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); configuration.put("IDENTITY_ENDPOINT", endpoint); configuration.put("IMDS_ENDPOINT", endpoint); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) <START> .expectError(CredentialUnavailableException.class); <END> }</code><technical_language>this expecting ClientAuthenticationException exception</technical_language>

Target:
public void testArcUserAssigned() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration().clone(); String token1 = "token1"; String endpoint = "http://localhost"; TokenRequestContext request = new TokenRequestContext().addScopes("<LINK_0>"); configuration.put("IDENTITY_ENDPOINT", endpoint); configuration.put("IMDS_ENDPOINT", endpoint); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(t -> t instanceof ClientAuthenticationException) .verify(); }
Source:
<code>public JSONObject listAllBoxesTable(HttpSession session, JSONObject json) { try { JSONObject j = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (Box box : requestManager.listAllBoxes()) { int filledSpaces = box.getSize().getRows() * box.getSize().getColumns() - box.getFree(); int availableSpaces = box.getSize().getRows() * box.getSize().getColumns(); JSONArray inner = new JSONArray(); inner.add(TableHelper.hyperLinkify("/miso/box/" + box.getId(), box.getName())); inner.add(TableHelper.hyperLinkify("/miso/box/" + box.getId(), box.getAlias())); inner.add(box.getLocationBarcode()); inner.add(filledSpaces + "/" + availableSpaces); inner.add(box.getSize().getRows() + "x" + box.getSize().getColumns()); inner.add(box.getUse().getAlias()); inner.add(isStringEmptyOrNull(box.getIdentificationBarcode()) ? "" : box.getIdentificationBarcode()); <START> <END> jsonArray.add(inner); } j.put("array", jsonArray); return j; } catch (IOException e) { log.debug("Failed", e); return JSONUtils.SimpleJSONError("Failed: " + e.getMessage()); } }</code><technical_language>I get error List Boxes page: > DataTables warning (table id = 'listingBoxesTable'): Requested unknown parameter '7' data source for row 0 BoxUse alias Box's IdentificationBarcode in wrong order,</technical_language>

Target:
public JSONObject listAllBoxesTable(HttpSession session, JSONObject json) { try { JSONObject j = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (Box box : requestManager.listAllBoxes()) { int filledSpaces = box.getSize().getRows() * box.getSize().getColumns() - box.getFree(); int availableSpaces = box.getSize().getRows() * box.getSize().getColumns(); JSONArray inner = new JSONArray(); inner.add(TableHelper.hyperLinkify("/miso/box/" + box.getId(), box.getName())); inner.add(TableHelper.hyperLinkify("/miso/box/" + box.getId(), box.getAlias())); inner.add(box.getLocationBarcode()); inner.add(filledSpaces + "/" + availableSpaces); inner.add(box.getSize().getRows() + "x" + box.getSize().getColumns()); inner.add(isStringEmptyOrNull(box.getLocationBarcode()) ? "" : box.getLocationBarcode()); inner.add(box.getUse().getAlias()); inner.add(isStringEmptyOrNull(box.getIdentificationBarcode()) ? "" : box.getIdentificationBarcode()); jsonArray.add(inner); } j.put("array", jsonArray); return j; } catch (IOException e) { log.debug("Failed", e); return JSONUtils.SimpleJSONError("Failed: " + e.getMessage()); } }
Source:
<code>public CompiledExpression compile(String expression, CompilerContext ctx) { FEEL_1_1Parser parser = FEELParser.parse(getEventsManager(ctx.getListeners()), expression, ctx.getInputVariableTypes(), ctx.getInputVariables(), ctx.getFEELFunctions(), profiles); ParseTree tree = parser.compilation_unit(); <START> if (!doCompile) { <END> ASTBuilderVisitor v = new ASTBuilderVisitor(ctx.getInputVariableTypes()); BaseNode expr = v.visit(tree); CompiledExpression ce = new CompiledExpressionImpl(expr); return ce; } else { DirectCompilerVisitor v = new DirectCompilerVisitor(ctx.getInputVariableTypes()); DirectCompilerResult directResult = v.visit(tree); Expression expr = directResult.getExpression(); CompiledFEELExpression cu = new CompilerBytecodeLoader().makeFromJPExpression(expression, expr, directResult.getFieldDeclarations()); return cu; } }</code><technical_language>a recommendation: is more clear positive logic in ifs. do if (doCompile) branch first. boolean variable need negated => 1 ultrananosupermillisecond faster :)</technical_language>

Target:
public CompiledExpression compile(String expression, CompilerContext ctx) { if (doCompile) { Set<FEELEventListener> listeners = new HashSet<>(ctx.getListeners()); CompilerErrorListener errorListener = new CompilerErrorListener(); listeners.add(errorListener); FEEL_1_1Parser parser = FEELParser.parse(getEventsManager(listeners), expression, ctx.getInputVariableTypes(), ctx.getInputVariables(), ctx.getFEELFunctions(), profiles); ParseTree tree = parser.compilation_unit(); if (errorListener.evt != null) { return compiledError(expression, errorListener.evt.getMessage()); } try { DirectCompilerVisitor v = new DirectCompilerVisitor(ctx.getInputVariableTypes()); DirectCompilerResult directResult = v.visit(tree); Expression expr = directResult.getExpression(); return new CompilerBytecodeLoader().makeFromJPExpression(expression, expr, directResult.getFieldDeclarations()); } catch (FEELCompilationError e) { return compiledError(expression, e.getMessage()); } } else { FEEL_1_1Parser parser = FEELParser.parse(getEventsManager(ctx.getListeners()), expression, ctx.getInputVariableTypes(), ctx.getInputVariables(), ctx.getFEELFunctions(), profiles); ParseTree tree = parser.compilation_unit(); ASTBuilderVisitor v = new ASTBuilderVisitor(ctx.getInputVariableTypes()); BaseNode expr = v.visit(tree); CompiledExpression ce = new CompiledExpressionImpl(expr); return ce; } }
Source:
<code>public D create(Map<String,String> parameters) { <START> D result = ClassLoaderHelper.untypedInstanceFromClass( targetClass, "Analyzer definition" ); <END> Map<String, JsonElement> parameterMap = new LinkedHashMap<>(); for ( Entry<String, String> parameter : parameters.entrySet() ) { String name = parameter.getKey(); String value = parameter.getValue(); switch ( name ) { case "type": result.setType( parseJsonString( name, value ) ); break; default: parameterMap.put( name, parseJson( name, value ) ); break; } } if ( !parameterMap.isEmpty() ) { result.setParameters( parameterMap ); } return result; }</code><technical_language>"Analyzer definition" => "analysis definition". This encompasses tokenizer definitions, token filter definitions, char filter definitions analyzer definitions</technical_language>

Target:
public D create(Map<String,String> parameters) { D result = ClassLoaderHelper.untypedInstanceFromClass( targetClass, "analysis definition" ); Map<String, JsonElement> parameterMap = new LinkedHashMap<>(); for ( Entry<String, String> parameter : parameters.entrySet() ) { String name = parameter.getKey(); String value = parameter.getValue(); switch ( name ) { case "type": result.setType( parseJsonString( name, value ) ); break; default: parameterMap.put( name, parseJson( name, value ) ); break; } } if ( !parameterMap.isEmpty() ) { result.setParameters( parameterMap ); } return result; }
Source:
<code>public String toString() { long columnCount = getColumnCount(); <START> StringBuilder stringBuilder = new StringBuilder("This TableView "); <END> stringBuilder.append("contains "); stringBuilder.append(columnCount); stringBuilder.append(" columns: "); for (int i = 0; i < columnCount; i++) { if (i != 0) { stringBuilder.append(", "); } stringBuilder.append(getColumnName(i)); } stringBuilder.append("."); stringBuilder.append(" And "); stringBuilder.append(size()); stringBuilder.append(" rows."); return stringBuilder.toString(); }</code><technical_language>"This" -> "The"</technical_language>

Target:
public String toString() { long columnCount = getColumnCount(); StringBuilder stringBuilder = new StringBuilder("The TableView "); stringBuilder.append("contains "); stringBuilder.append(columnCount); stringBuilder.append(" columns: "); for (int i = 0; i < columnCount; i++) { if (i != 0) { stringBuilder.append(", "); } stringBuilder.append(getColumnName(i)); } stringBuilder.append("."); stringBuilder.append(" And "); stringBuilder.append(size()); stringBuilder.append(" rows."); return stringBuilder.toString(); }
Source:
<code>private void setupToolbar() { setTitle(getResources().getText(R.string.jetpack_security_setting_title)); <START> Toolbar toolbar = findViewById(org.wordpress.mobile.ReactNativeGutenbergBridge.R.id.toolbar); <END> if (toolbar != null) { setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_close_24px); actionBar.setSubtitle(""); } } }</code><technical_language>Do need full package name for String</technical_language>

Target:
private void setupToolbar() { setTitle(getResources().getText(R.string.jetpack_security_setting_title)); Toolbar toolbar = findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_close_24px); actionBar.setSubtitle(""); } } }
Source:
<code>public CdaTemplate(String templateName, Byte[] templateData, Map<String, String> properties) { this.templateName = templateName; if (templateData != null) { <START> byte[] bytes = new byte[templateData.length]; <END> int i = 0; for (Byte b : templateData) { bytes[i++] = b.byteValue(); } String templateString = new String(bytes); Pattern regex = Pattern.compile("(?s)<!--.*?-->", Pattern.DOTALL); Matcher regexMatcher = regex.matcher(templateString); templateString = regexMatcher.replaceAll(""); templateString.replaceAll("(?s)<!--.*?-->", ""); bytes = templateString.getBytes(); Byte[] byteObjects = new Byte[bytes.length]; i = 0; for (byte b : bytes) { byteObjects[i++] = new Byte(b); } this.templateData = byteObjects.clone(); } else { this.templateData = ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY; } this.properties = properties; }</code><technical_language>this works expected ? I CdaTemplate object is added MDS, sure, new empty instance is created values set separately, this constructor used. Generally adding this kind of parsing in constructors idea</technical_language>

Target:
public CdaTemplate(String templateName, Byte[] templateData, Map<String, String> properties) { this.templateName = templateName; if (templateData != null) { this.templateData = removeCommentsFromTemplate(templateData).clone(); } else { this.templateData = ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY; } this.properties = properties; }
Source:
<code>public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) { InternalCacheRegistry icr = cr.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class); if (!icr.isInternalCache(cacheName) || icr.internalCacheHasFlag(cacheName, Flag.QUERYABLE)) { <START> boolean isIndexed = cfg.indexing().index().isEnabled(); <END> AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache(); ClassLoader aggregatedClassLoader = makeAggregatedClassLoader(cr.getGlobalComponentRegistry().getGlobalConfiguration().classLoader()); SearchIntegrator searchFactory = null; if (isIndexed) { log.registeringQueryInterceptor(cacheName); cr.registerComponent(new ShardAllocationManagerImpl(), ShardAllocatorManager.class); searchFactory = createSearchIntegrator(cfg.indexing(), cr, aggregatedClassLoader); createQueryInterceptorIfNeeded(cr, cfg, searchFactory); addCacheDependencyIfNeeded(cacheName, cache.getCacheManager(), cfg.indexing()); CommandInitializer initializer = cr.getComponent(CommandInitializer.class); initializer.setCacheManager(cache.getCacheManager()); cr.registerComponent(new QueryBox(), QueryBox.class); } registerMatcher(cr, searchFactory, aggregatedClassLoader); EmbeddedQueryEngine queryEngine = new EmbeddedQueryEngine(cache, isIndexed); cr.registerComponent(queryEngine, EmbeddedQueryEngine.class); } }</code><technical_language>makeAggregatedClassLoader() implementation, I stop adding TCCL (we TCCL default configuration classloader) system classloader (all others delegate anyway)</technical_language>

Target:
public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) { InternalCacheRegistry icr = cr.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class); if (!icr.isInternalCache(cacheName) || icr.internalCacheHasFlag(cacheName, Flag.QUERYABLE)) { AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache(); ClassLoader aggregatedClassLoader = makeAggregatedClassLoader(cr.getGlobalComponentRegistry().getGlobalConfiguration().classLoader()); SearchIntegrator searchFactory = null; boolean isIndexed = cfg.indexing().index().isEnabled(); if (isIndexed) { cr.registerComponent(new ShardAllocationManagerImpl(), ShardAllocatorManager.class); searchFactory = createSearchIntegrator(cfg.indexing(), cr, aggregatedClassLoader); createQueryInterceptorIfNeeded(cr, cfg, cache, searchFactory); addCacheDependencyIfNeeded(cacheName, cache.getCacheManager(), cfg.indexing()); CommandInitializer initializer = cr.getComponent(CommandInitializer.class); initializer.setCacheManager(cache.getCacheManager()); cr.registerComponent(new QueryBox(), QueryBox.class); } registerMatcher(cr, searchFactory, aggregatedClassLoader); EmbeddedQueryEngine queryEngine = new EmbeddedQueryEngine(cache, isIndexed); cr.registerComponent(queryEngine, EmbeddedQueryEngine.class); } }
Source:
<code>public Preferences() { gameTileSortingOrder = new SimpleObjectProperty<>(TilesSortingOrder.PLAYER_DES); chat = new ChatPrefs(); login = new LoginPrefs(); localization = new LocalizationPrefs(); mainWindow = new WindowPrefs(); forgedAlliance = new ForgedAlliancePrefs(); themeName = new SimpleStringProperty(DEFAULT_THEME_NAME); lastGameType = new SimpleStringProperty(KnownFeaturedMod.DEFAULT.getTechnicalName()); ignoredNotifications = new SimpleListProperty<>(observableArrayList()); notification = new NotificationsPrefs(); rememberLastTab = new SimpleBooleanProperty(true); lastGameTitle = new SimpleStringProperty(); lastMap = new SimpleStringProperty(); lastGameMinRating = new SimpleIntegerProperty(800); lastGameMaxRating = new SimpleIntegerProperty(1300); ladder1v1 = new Ladder1v1Prefs(); gamesViewMode = new SimpleStringProperty(); news = new NewsPrefs(); developer = new DeveloperPrefs(); gameListSorting = new SimpleListProperty<>(observableArrayList()); vaultPrefs = new VaultPrefs(); unitDataBaseType = new SimpleObjectProperty<>(UnitDataBaseType.RACKOVER); storedCookies = new SimpleMapProperty<>(FXCollections.observableHashMap()); showPasswordProtectedGames = new SimpleBooleanProperty(true); showModdedGames = new SimpleBooleanProperty(true); lastGameOnlyFriends = new SimpleBooleanProperty(); <START> disallowJoinsViaDiscord = new SimpleBooleanProperty(false); <END> }</code><technical_language>false is default should, therefore, skipped</technical_language>

Target:
public Preferences() { gameTileSortingOrder = new SimpleObjectProperty<>(TilesSortingOrder.PLAYER_DES); chat = new ChatPrefs(); login = new LoginPrefs(); localization = new LocalizationPrefs(); mainWindow = new WindowPrefs(); forgedAlliance = new ForgedAlliancePrefs(); themeName = new SimpleStringProperty(DEFAULT_THEME_NAME); lastGameType = new SimpleStringProperty(KnownFeaturedMod.DEFAULT.getTechnicalName()); ignoredNotifications = new SimpleListProperty<>(observableArrayList()); notification = new NotificationsPrefs(); rememberLastTab = new SimpleBooleanProperty(true); lastGameTitle = new SimpleStringProperty(); lastMap = new SimpleStringProperty(); lastGameMinRating = new SimpleIntegerProperty(800); lastGameMaxRating = new SimpleIntegerProperty(1300); ladder1v1 = new Ladder1v1Prefs(); gamesViewMode = new SimpleStringProperty(); news = new NewsPrefs(); developer = new DeveloperPrefs(); gameListSorting = new SimpleListProperty<>(observableArrayList()); vaultPrefs = new VaultPrefs(); unitDataBaseType = new SimpleObjectProperty<>(UnitDataBaseType.RACKOVER); storedCookies = new SimpleMapProperty<>(FXCollections.observableHashMap()); showPasswordProtectedGames = new SimpleBooleanProperty(true); showModdedGames = new SimpleBooleanProperty(true); lastGameOnlyFriends = new SimpleBooleanProperty(); disallowJoinsViaDiscord = new SimpleBooleanProperty(); }