auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public void testHexNoHashSign() { END assertThat(faker.color().hex(true), matchesRegularExpression("^[0-9A-F]{6}$")); } technically you should have a test that tests passing in a false... so `testHexWithHashSign()`

Target:
public void testHexNoHashSign() { assertThat(faker.color().hex(false), matchesRegularExpression("^[0-9A-F]{6}$")); }
Source:
START public final String toString() { END return this.joinpoint.toString(); } @shelan so no need to declare every method as final

Target:
public String toString() { return this.joinpoint.toString(); }
Source:
private Callable<Throwable> callable(final ProceedingJoinPoint point, final CountDownLatch start) { return new Callable<Throwable>() { @Override public Throwable call() { try { start.await(); point.proceed(); // @checkstyle IllegalCatchCheck (1 line) } catch (Throwable ex) { START return ex; END } return null; } }; } I don't like this multiple returning in one method. Better declare `Throwable result` and assign it twice, and return once.

Target:
private Callable<Throwable> callable(final ProceedingJoinPoint point, final CountDownLatch start) { return new Callable<Throwable>() { @Override public Throwable call() { Throwable result = null; try { start.await(); point.proceed(); // @checkstyle IllegalCatchCheck (1 line) } catch (Throwable ex) { result = ex; } return result; } }; }
Source:
protected void removeAllAnnotations() { // clear normal markers for (int i = 0; i < timarkers.size(); i++) { TiMarker timarker = timarkers.get(i); if (timarker.getMarker() != null) { timarker.getMarker().remove(); START timarker.release(); END } } timarkers.clear(); // clear cluster markers if (mClusterManager != null) { mClusterManager.clearItems(); mClusterManager.cluster(); } } ```Java if (timarker.getMarker() != null) { timarker.getMarker().remove(); } timarker.release(); ```

Target:
protected void removeAllAnnotations() { // clear normal markers for (int i = 0; i < timarkers.size(); i++) { TiMarker timarker = timarkers.get(i); if (timarker.getMarker() != null) { timarker.getMarker().remove(); } timarker.release(); } timarkers.clear(); // clear cluster markers if (mClusterManager != null) { mClusterManager.clearItems(); mClusterManager.cluster(); } }
Source:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { try { testExecutor.configure() .init(defaultArguments()); } catch (WebDriverException ex) { // should happen } JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions.build(), (JavascriptStateValidator) (driver, output, events) -> { START assertThat(jsDriver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); END }); } Hopefully, it is understandable and I don't just confuse you more. I like our JS tests, but lots of people are struggling with them. It is almost done though, just some nitpicks to fix

Target:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { testExecutor.configure().init(defaultArguments()); JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> { assertThat(driver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); }
Source:
public JavascriptTestExecutor login() { START return login((JSObjectBuilder)null, null); END } ```suggestion return login((String)null, null); ```

Target:
public JavascriptTestExecutor login() { return login((String)null, null); }
Source:
public JavascriptTestExecutor login(JavascriptStateValidator validator) { START return login((JSObjectBuilder)null, validator); END } ```suggestion return login((String)null, validator); ```

Target:
public JavascriptTestExecutor login(JavascriptStateValidator validator) { return login((String)null, validator); }
Source:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { START try { END testExecutor.configure() .init(defaultArguments()); } catch (WebDriverException ex) { // should happen } JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> { assertThat(driver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); } This `try-catch` block is not necessary. It is necessary only when you are using `onLoad: login-required`.

Target:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { testExecutor.configure().init(defaultArguments()); JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> { assertThat(driver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); }
Source:
public boolean correspondsTo(AttributeType attribute) { START return Objects.equals(this.uri, attribute.getName()) || Objects.equals(this.friendlyName, attribute.getFriendlyName()); END } ensure that attribute is not null to prevent NPE

Target:
public boolean correspondsTo(AttributeType attribute) { return attribute != null ? Objects.equals(this.uri, attribute.getName()) || Objects.equals(this.friendlyName, attribute.getFriendlyName()) : false; }
Source:
private SAMLAttributeParser() { super(SAMLAssertionQNames.ATTRIBUTE); START END Set<String> localAttributeNames = new HashSet<>(); for (SAMLAssertionQNames name : Arrays.asList(SAMLAssertionQNames.ATTR_NAME, SAMLAssertionQNames.ATTR_FRIENDLY_NAME, SAMLAssertionQNames.ATTR_NAME_FORMAT)) { localAttributeNames.add(name.getQName().getLocalPart()); } DEFAULT_KNOWN_LOCAL_ATTRIBUTE_NAMES = localAttributeNames; } Remove this whole block (l49-54) since this has moved to static initialization above.

Target:
private SAMLAttributeParser() { super(SAMLAssertionQNames.ATTRIBUTE); }
Source:
public void setAttribute(String name, List<String> values) { // Remove all existing removeAttribute(name); START List<String> nonNullValues = values.stream().filter(Objects::nonNull).collect(Collectors.toList()); END // Put all new nonNull values for (String value : nonNullValues) { persistAttributeValue(name, value); } } No need to realize this list into memory via `.collect`. you can either obtain a stream `iterator()` or use `Stream.forEach()`.

Target:
public void setAttribute(String name, List<String> values) { // Remove all existing removeAttribute(name); for (Iterator<String> it = values.stream().filter(Objects::nonNull).iterator(); it.hasNext();) { persistAttributeValue(name, it.next()); } }
Source:
public void init(Config.Scope config) { Integer maxDetail = config.getInt("max-detail-length", 0); START maxDetailLength = (maxDetail == null) ? 0 : maxDetail; END } maxDetail won't be null, so you can just do: `maxDetailLength = config.getInt("max-detail-length", 0);`

Target:
public void init(Config.Scope config) { maxDetailLength = config.getInt("max-detail-length", 0); }
Source:
private String trimToMaxLength(String detail) { if (detail != null && detail.length() > maxDetailLength) { START String result = detail.substring(0, maxDetailLength).concat("..."); END logger.warn("Detail was truncated to " + result); return result; } else { return detail; } } It should take `...` into account in the max-length, so the string with `...` should be max maxDetailLength long

Target:
private String trimToMaxLength(String detail) { if (detail != null && detail.length() > maxDetailLength) { // (maxDetailLength - 3) takes "..." into account String result = detail.substring(0, maxDetailLength - 3).concat("..."); logger.warn("Detail was truncated to " + result); return result; } else { return detail; } }
Source:
START public static ProviderConfigurationBuilder configurationBuilder() { END return ProviderConfigurationBuilder.create() .property(Attributes.PRIORITY_PROPERTY) .property(Attributes.ENABLED_PROPERTY) .property(Attributes.ACTIVE_PROPERTY); } If "final" is removed it would make it possible to override from subclass, so this change should be reverted

Target:
public final static ProviderConfigurationBuilder configurationBuilder() { return ProviderConfigurationBuilder.create() .property(Attributes.PRIORITY_PROPERTY) .property(Attributes.ENABLED_PROPERTY) .property(Attributes.ACTIVE_PROPERTY); }
Source:
START public static OAuth2Code deserializeCode(Map<String, String> data) { END return new OAuth2Code(data); } See above. Final prevents overriding.

Target:
public static final OAuth2Code deserializeCode(Map<String, String> data) { return new OAuth2Code(data); }
Source:
public boolean supportsCredentialType(String credentialType) { START return credentialType == null || credentialType.equals(CredentialModel.PASSWORD); END } I'm not a reviewer but FYI ` CredentialModel.PASSWORD.equals(credentialType)` in that order can't throw a null pointer exception, usually always the constants first because equals accept "null" but null don't have equals function.

Target:
public boolean supportsCredentialType(String credentialType) { return credentialType.equals(getType()); }
Source:
public List<ClientModel> getClients() { START return cacheSession.getClients(this, 0, cacheSession.getClientsCount(this).intValue()); END } Realm should have an overloaded method getClients(this), that just calls getClients(this, null, null). This approach will result in extra query to get the client counts first, to then list all clients.

Target:
public List<ClientModel> getClients() { return cacheSession.getClients(this); }
Source:
public VaultRawSecret getRawSecret(final String value) { String entryId = this.getVaultEntryKey(value); if (entryId != null) { if (this.provider == null) { throw new IllegalStateException("Required VaultProvider not found - check vault configuration"); } // we have a valid ${vault.<KEY>} string, use the provider to retrieve the entry. return this.provider.obtainSecret(entryId); } else { // this should be avoided by calling isVaultEntry with the value before attempting to use this method. ByteBuffer buffer = value != null ? ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)) : null; return DefaultVaultRawSecret.forBuffer(Optional.ofNullable(buffer)); } START } END Not here. If the value is not found, `VaultProvider` should write it to the log.

Target:
public VaultRawSecret getRawSecret(final String value) { String entryId = this.getVaultEntryKey(value); if (entryId != null) { // we have a valid ${vault.<KEY>} string, use the provider to retrieve the entry. return this.provider.obtainSecret(entryId); } else { // not a vault expression - encode the value itself as a byte buffer. ByteBuffer buffer = value != null ? ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)) : null; return DefaultVaultRawSecret.forBuffer(Optional.ofNullable(buffer)); } }
Source:
public PlainTextVaultProvider(@Nonnull Path path, @Nonnull String realmName) { vaultPath = path; secretMappingFunction = (vaultDirectory, secretId) -> vaultDirectory.resolve(realmName + "__" + secretId); START logger.debugf("PlainTextVaultProvider will operate in %s directory", vaultPath.toAbsolutePath().toString()); END } `vaultPath.toAbsolutePath().toString()` would be evaluated always which is redundant if debug is not enabled. ` if (logger.isDebugEnabled()) {` ```suggestion logger.debugf("PlainTextVaultProvider will operate in %s directory", vaultPath.toAbsolutePath()); ``` }

Target:
public PlainTextVaultProvider(@Nonnull Path path, @Nonnull String realmName) { this.vaultPath = path; this.realmName = realmName; logger.debugf("PlainTextVaultProvider will operate in %s directory", vaultPath.toAbsolutePath()); }
Source:
START public List<GroupModel> getGroups() { END List<GroupModel> ldapGroupMappings = getLDAPGroupMappingsConverted(); if (config.getMode() == LDAPGroupMapperMode.LDAP_ONLY) { // Use just group mappings from LDAP return ldapGroupMappings; } else { // Merge mappings from both DB and LDAP List<GroupModel> modelGroupMappings = super.getGroups(); ldapGroupMappings.addAll(modelGroupMappings); return ldapGroupMappings; } } Revert to a `Set`, `List` would negatively impact performance

Target:
public Set<GroupModel> getGroups() { Set<GroupModel> ldapGroupMappings = getLDAPGroupMappingsConverted(); if (config.getMode() == LDAPGroupMapperMode.LDAP_ONLY) { // Use just group mappings from LDAP return ldapGroupMappings; } else { // Merge mappings from both DB and LDAP Set<GroupModel> modelGroupMappings = super.getGroups(); ldapGroupMappings.addAll(modelGroupMappings); return ldapGroupMappings; } }
Source:
protected List<GroupModel> getLDAPGroupMappingsConverted() { if (cachedLDAPGroupMappings != null) { return new ArrayList<>(cachedLDAPGroupMappings); } List<LDAPObject> ldapGroups = getLDAPGroupMappings(ldapUser); START List<GroupModel> result = new ArrayList<>(); END for (LDAPObject ldapGroup : ldapGroups) { GroupModel kcGroup = findKcGroupOrSyncFromLDAP(realm, ldapGroup, this); if (kcGroup != null) { result.add(kcGroup); } } cachedLDAPGroupMappings = new HashSet<>(result); return result; } Use `LinkedHashSet` instead of `ArrayList`.

Target:
protected Set<GroupModel> getLDAPGroupMappingsConverted() { if (cachedLDAPGroupMappings != null) { return new HashSet<>(cachedLDAPGroupMappings); } List<LDAPObject> ldapGroups = getLDAPGroupMappings(ldapUser); Set<GroupModel> result = new HashSet<>(); for (LDAPObject ldapGroup : ldapGroups) { GroupModel kcGroup = findKcGroupOrSyncFromLDAP(realm, ldapGroup, this); if (kcGroup != null) { result.add(kcGroup); } } cachedLDAPGroupMappings = new HashSet<>(result); return result; }
Source:
SignatureSignerContext signer() throws SignatureException; SignatureVerifierContext verifier(String kid) throws VerificationException; // KEYCLOAK-8460 client signed signature verification START SignatureVerifierContext verifier(ClientModel client, JWSInput input) throws VerificationException; END @Override default void close() { } Verifying signatures for clients should not be added to the SignatureProvider. Instead a new ClientSignatureVerifierProvider should be introduced. This will also enable listing supported algorithms properly rather than hard-coding the lists.

Target:
SignatureSignerContext signer() throws SignatureException; SignatureVerifierContext verifier(String kid) throws VerificationException; @Override default void close() { }
Source:
public void isActiveReturnFalseWhenBeforeTimeInFuture() { int currentTime = Time.currentTime(); int futureTime = currentTime + 1; JsonWebToken jsonWebToken = new JsonWebToken(); jsonWebToken.notBefore(futureTime); START assertFalse(jsonWebToken.isActive()); END } If I understand correctly, when the line 70 with "jsonWebToken.isActive()" is executed, the system time may be already increased during the time when lines 66-70 were executed and "Time.currentTime()" called from "jsonWebToken.isActive()" will return 1 second ahead of value of "currentTime" variable. If this happen, the test would fail IMO. Could it be changed to be less fragile? Instead of using 1 second interval, use 10 seconds intervals or something?

Target:
public void isActiveReturnFalseWhenBeforeTimeInFuture() { int currentTime = Time.currentTime(); int futureTime = currentTime + 10; JsonWebToken jsonWebToken = new JsonWebToken(); jsonWebToken.notBefore(futureTime); assertFalse(jsonWebToken.isActive()); }
Source:
protected void commenceLoginRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException { if (request.getSession(false) == null && KeycloakCookieBasedRedirect.getRedirectUrlFromCookie(request) == null) { // If no session exists yet at this point, then apparently the redirect URL is not // stored in a session. We'll store it in a cookie instead. START response.addCookie(KeycloakCookieBasedRedirect.createCookieFromRedirectUrl(request.getRequestURI())); END } String contextAwareLoginUri = request.getContextPath() + loginUri; log.debug("Redirecting to login URI {}", contextAwareLoginUri); response.sendRedirect(contextAwareLoginUri); } This does not preserve query parameters of the original request. Is this intentional? Is there any (e.g. security related) reason to not include the query?

Target:
protected void commenceLoginRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException { String contextAwareLoginUri = request.getContextPath() + loginUri; log.debug("Redirecting to login URI {}", contextAwareLoginUri); response.sendRedirect(contextAwareLoginUri); }
Source:
public Response update(final ClientRepresentation rep) { auth.requireManage(); try { RepresentationToModel.updateClient(rep, client); START adminEvent.realm(realm).operation(OperationType.UPDATE).resourcePath(client).representation(rep).success(); END return Response.noContent().build(); } catch (ModelDuplicateException e) { return ErrorResponse.exists("Client " + rep.getClientId() + " already exists"); } } Set realm in RealmAdminResource, then you don't have to do it everywhere

Target:
public Response update(final ClientRepresentation rep) { auth.requireManage(); try { RepresentationToModel.updateClient(rep, client); adminEvent.operation(OperationType.UPDATE).resourcePath(client).representation(rep).success(); return Response.noContent().build(); } catch (ModelDuplicateException e) { return ErrorResponse.exists("Client " + rep.getClientId() + " already exists"); } }
Source:
START public String getSrcRecord() { END return srcRecord; } Thou hast a typo :)

Target:
public String getSrcRecord() { return srcRecord.toString(); }
Source:
public AbstractSequence<NucleotideCompound> getSequence() throws CompoundNotFoundException { try { DNASequenceCreator creator = new DNASequenceCreator(ABITracerCompoundSet.getABITracerCompoundSet()); return creator.getSequence(sequence, 0); START } catch (Exception e) { END // this should be impossible! throw new CompoundNotFoundException(e.toString()); } } No need to catch, just let the `CompoundNotFoundException` go through. Catching a general `Exception` here could cause undesired side effects in the error handling. If you think the `CompoundNotFoundException` can't happen (other than because of a bug), then it's valid to catch it (but only that exception), log a warning and not throw it.

Target:
public AbstractSequence<NucleotideCompound> getSequence() throws CompoundNotFoundException { DNASequenceCreator creator = new DNASequenceCreator(ABITracerCompoundSet.getABITracerCompoundSet()); return creator.getSequence(sequence, 0); }
Source:
START public void testCryst1Parsing() throws Exception { END String cryst1Line = "CRYST1 11.111 11.111 111.111 70.00 80.00 60.00 P 1"; Structure s; PDBFileParser pdbPars = new PDBFileParser(); try(InputStream is = new ByteArrayInputStream(cryst1Line.getBytes()) ) { s = pdbPars.parsePDBFile(is); } assertEquals("P 1", s.getPDBHeader().getCrystallographicInfo().getSpaceGroup().getShortSymbol()); } This can be specified to "throws IOException" only.

Target:
public void testCryst1Parsing() throws IOException { String cryst1Line = "CRYST1 11.111 11.111 111.111 70.00 80.00 60.00 P 1"; Structure s; PDBFileParser pdbPars = new PDBFileParser(); try(InputStream is = new ByteArrayInputStream(cryst1Line.getBytes()) ) { s = pdbPars.parsePDBFile(is); } assertEquals("P 1", s.getPDBHeader().getCrystallographicInfo().getSpaceGroup().getShortSymbol()); }
Source:
public static final void translate(Group group, Vector3d v) { for (Atom atom : group.getAtoms()) { translate(atom, v); } for (Group altG : group.getAltLocs()) { START for (Atom atom : altG.getAtoms()) { END translate(atom, v); } } } Why not using `translate(g, v)`? It would be a recursive call to this function, nicer solution.

Target:
public static final void translate(Group group, Vector3d v) { for (Atom atom : group.getAtoms()) { translate(atom, v); } for (Group altG : group.getAltLocs()) { translate(altG, v); } }
Source:
START public static String complement(String sequence, boolean RNA) { END String result = ""; for (int i = sequence.length() - 1; i >= 0; i--) { result += complementBase(sequence.charAt(i), RNA); } return result; } Isn't this already present elsewhere in biojava?

Target:
private static String complement(String sequence, boolean RNA) { String result = ""; for (int i = sequence.length() - 1; i >= 0; i--) { result += complementBase(sequence.charAt(i), RNA); } return result; }
Source:
public void setUp(){ Dataset ds = new Dataset(); String f = Dataset.ACETYLATION; File localFile = getLocalFileName(f); try { if (!localFile.exists()) { ds.downloadFile(new URL(f), localFile); } } catch (IOException e) { START e.printStackTrace(); END } } It'd be better to throw the exception here. If there's a problem with the download, a stack trace will be printed but junit won't know anything about it. The failure would come later when the file is not found. With the exception thrown, the junit report will be a lot clearer and a naive user that knows nothing about this test will understand better what went wrong.

Target:
public void setUp() throws IOException{ Dataset ds = new Dataset(); String f = Dataset.ACETYLATION; File localFile = getLocalFileName(f); if (!localFile.exists()) { ds.downloadFile(new URL(f), localFile); } }
Source:
public void testAcetylation() { try { File localFile = getLocalFileName(Dataset.ACETYLATION); List<Site> sites = Site.parseSites(localFile); assertTrue(sites.size() > 0); for (Site s : sites) { assertTrue(s.getResidue() != null); } } catch (Exception e) { e.printStackTrace(); START fail(e.getMessage()); END } } It would be better to throw the exception here. Like this an exception will be reported as a test failure by junit. Junit reports either errors or failures, and both are different: failures indicate that an assertion did not work, errors indicate that some unexpected exception occurred (see http://stackoverflow.com/questions/3425995/whats-the-difference-between-failure-and-error-in-junit)

Target:
public void testAcetylation() throws IOException { File localFile = getLocalFileName(Dataset.ACETYLATION); List<Site> sites = Site.parseSites(localFile); assertTrue(sites.size() > 0); for (Site s : sites) { assertTrue(s.getResidue() != null); } }
Source:
START public static List<Range> getCDSExonRanges(GeneChromosomePosition chromPos){ END if ( chromPos.getOrientation() == '+') return getCDSExonRangesForward(chromPos,CDS); return getCDSExonRangesReverse(chromPos,CDS); } Range should be parameterised, the compiler gives warnings for it. Same for all other occurrences below

Target:
public static List<Range<Integer>> getCDSExonRanges(GeneChromosomePosition chromPos){ if ( chromPos.getOrientation() == '+') return getCDSExonRangesForward(chromPos,CDS); return getCDSExonRangesReverse(chromPos,CDS); }
Source:
private List<Step> getAlignmentsSteps(String gappedSequenceString){ START List<Step> returnList = new ArrayList(); END for (char c: gappedSequenceString.toCharArray()){ if (c=='-') returnList.add(Step.GAP); else returnList.add(Step.COMPOUND); } return returnList; } You are missing the type in ArrayList

Target:
private List<Step> getAlignmentsSteps(String gappedSequenceString){ List<Step> returnList = new ArrayList<Step>(); for (char c: gappedSequenceString.toCharArray()){ if (c=='-') returnList.add(Step.GAP); else returnList.add(Step.COMPOUND); } return returnList; }
Source:
public List<String> getFileExtensions(){ START ArrayList<String> extensions = new ArrayList(1); END extensions.add("blastxml"); return extensions; } Missing type

Target:
public List<String> getFileExtensions(){ ArrayList<String> extensions = new ArrayList<String>(1); extensions.add("blastxml"); return extensions; }
Source:
public UniprotProxySequenceReader(String accession, CompoundSet<C> compoundSet) throws CompoundNotFoundException, IOException { if (!UP_AC_PATTERN.matcher(accession.toUpperCase()).matches()) { throw new CompoundNotFoundException("Accession provided " + accession + " doesn't comply with the uniprot acession pattern."); } START setCompoundSet(compoundSet); END uniprotDoc = this.getUniprotXML(accession); String seq = this.getSequence(uniprotDoc); setContents(seq); } CompoundNotFoundException was intended for cases when a particular symbol in a sequence (nucleotide or aminoacid) is not recognised. Should we have a different exception for this case? what do people think?

Target:
public UniprotProxySequenceReader(String accession, CompoundSet<C> compoundSet) throws CompoundNotFoundException, IOException { if (!UP_AC_PATTERN.matcher(accession.toUpperCase()).matches()) { throw new IllegalArgumentException("Accession provided " + accession + " doesn't comply with the uniprot acession pattern."); } setCompoundSet(compoundSet); uniprotDoc = this.getUniprotXML(accession); String seq = this.getSequence(uniprotDoc); setContents(seq); }
Source:
START public void setCommodity(@NonNull String currencyCode){ END mCommodity = Commodity.getInstance(currencyCode); } Was just going through the pr and this caught my eye. `Money` objects are meant to be immutable, just like Java Strings. Could you change this back to private and use `Money.withCurrency()` at the relevant places instead?

Target:
private void setCommodity(@NonNull String currencyCode){ mCommodity = Commodity.getInstance(currencyCode); }
Source:
START private void checkNumColumns(String location, int[] baseColumnMap, Dataset<Row> table) throws StandardException { END if( baseColumnMap.length > table.schema().fields().length) { throw StandardException.newException(SQLState.INCONSISTENT_NUMBER_OF_ATTRIBUTE, baseColumnMap.length, table.schema().fields().length, location, ExternalTableUtils.getSuggestedSchema(table.schema())); } } nice! 👍 could be made `static` I guess?

Target:
private static void checkNumColumns(String location, int[] baseColumnMap, Dataset<Row> table) throws StandardException { if( baseColumnMap.length > table.schema().fields().length) { throw StandardException.newException(SQLState.INCONSISTENT_NUMBER_OF_ATTRIBUTE, baseColumnMap.length, table.schema().fields().length, location, ExternalTableUtils.getSuggestedSchema(table.schema())); } }
Source:
public static byte[] getRowKey(long txnId) { long beginTS = txnId & SIConstants.TRANSANCTION_ID_MASK; byte[] rowKey = new byte[9]; rowKey[0] = (byte)((beginTS / SIConstants.TRASANCTION_INCREMENT) & (TRANSACTION_TABLE_BUCKET_COUNT-1)); START rowKey[0] = (byte)(2); END Bytes.longToBytes(beginTS, rowKey, 1); return rowKey; } Remove

Target:
public static byte[] getRowKey(long txnId) { long beginTS = txnId & SIConstants.TRANSANCTION_ID_MASK; byte[] rowKey = new byte[9]; rowKey[0] = (byte)((beginTS / SIConstants.TRASANCTION_INCREMENT) & (TRANSACTION_TABLE_BUCKET_COUNT-1)); Bytes.longToBytes(beginTS, rowKey, 1); return rowKey; }
Source:
private String getClassName(String niceIndexName) throws StandardException { String cName = ""; if(niceIndexName!=null){ START cName = "IndexScan["+niceIndexName+"]"; END }else{ cName = "TableScan["+getPrettyTableName(); if(pastTxId >= 0){ cName += " timeTravelTx(" + pastTxId + ")"; } cName += "]"; } if(isMultiProbing()) cName = "MultiProbe"+cName; if (isDistinctScan()) cName = "Distinct" + cName; if (specialMaxScan) cName = "LastKey" + cName; return cName; } We need to remove the closing bracket "]" for IndexScan here also

Target:
private String getClassName(String niceIndexName) throws StandardException { String cName = ""; if(niceIndexName!=null){ cName = "IndexScan["+niceIndexName; }else{ cName = "TableScan["+getPrettyTableName(); if(pastTxId >= 0){ cName += " timeTravelTx(" + pastTxId + ")"; } cName += "]"; } if(isMultiProbing()) cName = "MultiProbe"+cName; if (isDistinctScan()) cName = "Distinct" + cName; if (specialMaxScan) cName = "LastKey" + cName; return cName; }
Source:
public void stopSpooling() { doSpool = false; START this.out.flush(); this.out = new LocalizedOutput(System.out); END } We should close the FileOutputStream, relying on finalizers is very finicky

Target:
public void stopSpooling() { doSpool = false; this.out.flush(); this.out.close(); this.out = new LocalizedOutput(System.out); }
Source:
public void setReplicationRoleLocal(String role) { SIDriver.driver().lifecycleManager().setReplicationRole(role); Collection<Context> allContexts= ContextService.getFactory().getAllContexts(LanguageConnectionContext.CONTEXT_ID); START for(Context context : allContexts){ END ((LanguageConnectionContext)context).setReplicationRole(role); } SpliceLogUtils.info(LOG, "Set replication role to %s", role); } I think it is a good idea to throw an exception is `role` doesn't match (or at least add an assert)

Target:
private void setReplicationRoleLocal(String role) { SIDriver.driver().lifecycleManager().setReplicationRole(role); Collection<Context> allContexts= ContextService.getFactory().getAllContexts(LanguageConnectionContext.CONTEXT_ID); for(Context context : allContexts){ ((LanguageConnectionContext)context).setReplicationRole(role); } SpliceLogUtils.info(LOG, "Set replication role to %s", role); }
Source:
public RunningOperation(SpliceOperation operation, Thread thread, Date submittedTime, DataSetProcessor.Type engine, UUID uuid, String rdbIntTkn) { this.operation = operation; this.thread =thread; START this.submittedTime = (Date)submittedTime.clone(); END this.engine = engine; this.uuid = uuid; this.rdbIntTkn = rdbIntTkn; } I would rather remove this clone, it shouldn't be too costly but for OLTP queries it could add up since it's in the hot path.

Target:
public RunningOperation(SpliceOperation operation, Thread thread, Date submittedTime, DataSetProcessor.Type engine, UUID uuid, String rdbIntTkn) { this.operation = operation; this.thread =thread; // EI_EXPOSE_REP2: May expose internal representation by incorporating // reference to mutable object // todo(martinrupp) replace java.util.Date with java.time.Instance, see // https://stackoverflow.com/questions/36639154/convert-java-util-date-to-what-java-time-type this.submittedTime = submittedTime; this.engine = engine; this.uuid = uuid; this.rdbIntTkn = rdbIntTkn; }
Source:
public void testCurrentServer() throws Exception { String sqlText = "values current server"; String sqlTextAlt = "values current_server"; String expected = "1 |\n" + "----------\n" + "splicedb |"; START ResultSet rs = methodWatcher.executeQuery(sqlText); END assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); rs.close(); rs = methodWatcher.executeQuery(sqlTextAlt); assertEquals("\n" + sqlTextAlt + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } You can use "try-with-resources" to ensure resultsets get closed: try(ResultSet rs = methodWatcher.executeQuery(sqlText)) { assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); }

Target:
public void testCurrentServer() throws Exception { String sqlText = "values current server"; String sqlTextAlt = "values current_server"; String expected = "1 |\n" + "----------\n" + "splicedb |"; try (ResultSet rs = methodWatcher.executeQuery(sqlText)) { assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } try (ResultSet rs = methodWatcher.executeQuery(sqlTextAlt)) { assertEquals("\n" + sqlTextAlt + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } }
Source:
public DirectPipelineWriter(long destConglomerate, TxnView txn, byte[] token, OperationContext opCtx, boolean skipIndex, String tableVersion){ START this.destConglomerate=destConglomerate; END this.txn=txn; this.token=token; this.opCtx=opCtx; this.skipIndex=skipIndex; } `this.tableVersion = tableVersion` is probably missing

Target:
public DirectPipelineWriter(long destConglomerate, TxnView txn, byte[] token, OperationContext opCtx, boolean skipIndex, String tableVersion){ this.destConglomerate=destConglomerate; this.txn=txn; this.token=token; this.opCtx=opCtx; this.skipIndex=skipIndex; this.tableVersion = tableVersion; }
Source:
protected SocketConfig buildSocketConfig() { START return SocketConfig.custom() END .setSoTimeout(readTimeout == -1 ? 0 : readTimeout) .build(); } I think this can return null if there is no timeout. From what I see, a null SocketConfig is supported and what occurs normally (if you have no customizations).

Target:
protected SocketConfig buildSocketConfig() { if (readTimeout < 1) { return null; } return SocketConfig.custom() .setSoTimeout(readTimeout) .build(); }
Source:
START public static String getDefaultBeanName(String className){ END int lastDotPosition = className.lastIndexOf("."); //$NON-NLS-1$ if(lastDotPosition >= 0 && className.length() > lastDotPosition){ className = className.substring(+1); } if(className.length() > 0) { className = className.substring(0, 1).toLowerCase() + className.substring(1); } return className; } Please add JavaDoc to this util method.

Target:
public static String getDefaultBeanName(String className){ int lastDotPosition = className.lastIndexOf("."); //$NON-NLS-1$ if(lastDotPosition >= 0 && className.length() > lastDotPosition){ className = className.substring(lastDotPosition+1); } if(className.length() > 0) { className = className.substring(0, 1).toLowerCase() + className.substring(1); } return className; }
Source:
private static void initializeUserHomeRuntimes(IProgressMonitor monitor) { String userHome = System.getProperty(USER_HOME); if (userHome != null) { File directory = new File(userHome, JBOSS_RUNTIMES); START RuntimeInitializerUtil.initializeRuntimesFromFolder(directory, monitor); END if (directory != null && directory.isDirectory()) { RuntimePath path = new RuntimePath(directory.getAbsolutePath()); path.setScanOnEveryStartup(true); RuntimeUIActivator.getDefault().getModel().addRuntimePath(path); } } } Why would you call RuntimeInitializerUtil.initializeRuntimesFromFolder if directory is null or not a directory? i.e. why not put that down in the if block below?

Target:
private static void initializeUserHomeRuntimes(IProgressMonitor monitor) { String userHome = System.getProperty(USER_HOME); if (userHome != null) { File directory = new File(userHome, JBOSS_RUNTIMES); if (directory != null && directory.isDirectory()) { RuntimeInitializerUtil.initializeRuntimesFromFolder(directory, monitor); RuntimePath path = new RuntimePath(directory.getAbsolutePath()); path.setScanOnEveryStartup(true); RuntimeUIActivator.getDefault().getModel().addRuntimePath(path); } } }
Source:
public void start(BundleContext bundleContext) throws Exception { StacksCoreActivator.context = bundleContext; DEFAULT = this; START new StacksManager().getStacks(new NullProgressMonitor()); END } This has nothing to do here. You're invoking blocking code during plugin activation and wasting this instance

Target:
public void start(BundleContext bundleContext) throws Exception { StacksCoreActivator.context = bundleContext; DEFAULT = this; }
Source:
START private DelayDays(String value) { END this.value = value; } Can you update the generator to remove the modifier so that the constructor stays at the package-private level?

Target:
DelayDays(String value) { this.value = value; }
Source:
START public SubscriptionScheduleCollection list(Map<String, Object> params) throws StripeException { END return list(params, (RequestOptions) null); } @ob-stripe totally random but do we really need those duplicate collection classes? (nothing to do with autogen, just realizing I haven't asked in a while)

Target:
public static SubscriptionScheduleCollection list(Map<String, Object> params) throws StripeException { return list(params, (RequestOptions) null); }
Source:
public void setOnBehalfOf(String onBehalfOfID) { START this.onBehalfOf = APIResource.setExpandableFieldID(onBehalfOfID, this.destination); END } I don't understand why `this.destination` is used here, can you clarify?

Target:
public void setOnBehalfOf(String onBehalfOfID) { this.onBehalfOf = APIResource.setExpandableFieldID(onBehalfOfID, this.onBehalfOf); }
Source:
public static IssuerFraudRecord retrieve(String id) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { String url = instanceURL(IssuerFraudRecord.class, id); return request(RequestMethod.GET, url, null, IssuerFraudRecord.class, null); START } END Could you add a variant for `retrieve` that takes a `RequestOptions` like you have for `list` below? Thanks!

Target:
public static IssuerFraudRecord retrieve(String id) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return retrieve(id, null); }
Source:
protected static String subresourceURL(Class<?> clazz, String id, Class<?> subClazz, String apiBase) throws InvalidRequestException { try { return String.format("%s/%s/%ss", classURL(clazz, apiBase), urlEncode(id), className(subClazz)); } catch (UnsupportedEncodingException e) { throw new InvalidRequestException("Unable to encode parameters to " + CHARSET + ". Please contact support@stripe.com for assistance.", null, null, null, 0, e); } START } END Hm, I'm not too crazy about adding a couple new global helpers like this and then using them in just the one place. It feels like we should either just re-use the template found elsewhere (see transfer reversals for example), or convert everything over to use these. What do you think @ob-stripe?

Target:
private static String subresourceURL(Class<?> clazz, String id, Class<?> subClazz, String apiBase) throws InvalidRequestException { try { return String.format("%s/%s/%ss", classURL(clazz, apiBase), urlEncode(id), className(subClazz)); } catch (UnsupportedEncodingException e) { throw new InvalidRequestException("Unable to encode parameters to " + CHARSET + ". Please contact support@stripe.com for assistance.", null, null, null, 0, e); } }
Source:
public static Topup retrieve(String id, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { START return request(RequestMethod.GET, instanceURL(Topup.class, id), null, Topup.class, options); END } Can this one be implemented using the below method: <pre> public static Topup retrieve(String id, Map<String, Object> params, RequestOptions options); </pre> ?

Target:
public static Topup retrieve(String id, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return retrieve(id, null, options); }
Source:
public void testCreate() throws StripeException { Map<String, Object> params = new HashMap<String, Object>(); params.put("plan", "plan_123"); params.put("subscription", "cus_123"); params.put("quantity", 99); START SubscriptionItem subscriptionItem = SubscriptionItem.create(params); END assertNotNull(subscriptionItem); verifyRequest( APIResource.RequestMethod.POST, "/v1/subscription_items", params ); } should be called `resource`

Target:
public void testCreate() throws StripeException { final Map<String, Object> params = new HashMap<String, Object>(); params.put("plan", "plan_123"); params.put("subscription", "cus_123"); params.put("quantity", 99); final SubscriptionItem subscriptionItem = SubscriptionItem.create(params); assertNotNull(subscriptionItem); verifyRequest( APIResource.RequestMethod.POST, "/v1/subscription_items", params ); }
Source:
public String get(String name) { List<String> valuesList = values(name); START String requestId = null; END if (valuesList != null && valuesList.size() > 0) { requestId = valuesList.get(0); } return requestId; } Sorry to be such a bother, but mind giving a generic name to this variable too?

Target:
public String get(String name) { List<String> valuesList = values(name); String value = null; if (valuesList != null && valuesList.size() > 0) { value = valuesList.get(0); } return value; }
Source:
public DeletedAccount delete(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { START return request(RequestMethod.DELETE, instanceURL(Account.class, this.id), null, DeletedAccount.class, options); END } IMO they should both call the other methods. They shouldn't make the request themselves so that there's only one path to a call to `request`

Target:
public DeletedAccount delete(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return delete(null, (RequestOptions) null); }
Source:
START public static String getClassURL() { END return String.format("%s/v1/%s", Stripe.getApiBase(), "apple_pay/domains"); } I notice that most of the other models with this method don't use `static`. Would you mind making it an instance method for consistency? Also, can you see if you can change it to private visibility? I don't think there's any reason to leak this interface out of the package.

Target:
private static String getClassURL() { return String.format("%s/v1/%s", Stripe.getApiBase(), "apple_pay/domains"); }
Source:
public void testDisputeList() throws StripeException, InterruptedException { createDisputedCharge(100).getDispute(); createDisputedCharge(150).getDispute(); START createDisputedCharge(300).getDispute(); END Map<String, Object> listParams = new HashMap<String, Object>(); listParams.put("count", 3); List<Dispute> disputes = Dispute.all(listParams).getData(); assertEquals(3, disputes.size()); } I think it's safe to remove these

Target:
public void testDisputeList() throws StripeException, InterruptedException { Map<String, Object> listParams = new HashMap<String, Object>(); listParams.put("count", 3); List<Dispute> disputes = Dispute.all(listParams).getData(); assertEquals(3, disputes.size()); }
Source:
public static RequestOptions getDefault() { START return new RequestOptions(Stripe.apiKey, Stripe.apiVersion, Stripe.getApiBase()); END } Per IRL, I meant to say `uploadApiBase`. This is fine too, but unrelated.

Target:
public static RequestOptions getDefault() { return new RequestOptions(Stripe.apiKey, Stripe.apiVersion); }
Source:
START public String getInstanceURL() { END if (this.getCustomer() != null) { return String.format("%s/%s/cards/%s", classURL(Customer.class), this.getCustomer(), this.getId()); } else { return String.format("%s/%s/cards/%s", classURL(Recipient.class), this.getRecipient(), this.getId()); } } I realize that it wasn't smart enough to do this before, but ideally this method would return `null` when both `getCustomer()` and `getRecipient()` return `null`.

Target:
public String getInstanceURL() { if (this.getCustomer() != null) { return String.format("%s/%s/cards/%s", classURL(Customer.class), this.getCustomer(), this.getId()); } else if (this.getRecipient() != null) { return String.format("%s/%s/cards/%s", classURL(Recipient.class), this.getRecipient(), this.getId()); } else { return null; } }
Source:
START ListKeysOperation(Builder builder) END { super(RiakMessageCodes.MSG_TsListKeysReq, RiakMessageCodes.MSG_TsListKeysResp, builder.reqBuilder, RiakTsPB.TsListKeysResp.PARSER); this.builder = builder; } Suspicious package visibility, do we need it?

Target:
private ListKeysOperation(Builder builder) { super(RiakMessageCodes.MSG_TsListKeysReq, RiakMessageCodes.MSG_TsListKeysResp, builder.reqBuilder, RiakTsPB.TsListKeysResp.PARSER); this.builder = builder; }
Source:
START private List<Row> getKeyHeads() END { List<Row> keyHeads = new ArrayList<Row>(rows.size()); for (Row row : rows) { final List<Cell> cells = row.getCellsCopy(); // Hack: replace timestamp cell with sint64 cell. keyHeads.add(new Row(cells.get(0), cells.get(1), new Cell(cells.get(2).getTimestamp()))); } return keyHeads; } Better to make it static

Target:
private static List<Row> getKeyHeads() { List<Row> keyHeads = new ArrayList<Row>(rows.size()); for (Row row : rows) { final List<Cell> cells = row.getCellsCopy(); keyHeads.add(new Row(cells.get(0), cells.get(1), cells.get(2))); } return keyHeads; }
Source:
START public static ArrayList<RiakKvPB.TsCell> convertCellsToPb(Collection<Cell> cells) END { final ArrayList<RiakKvPB.TsCell> pbCells = new ArrayList<RiakKvPB.TsCell>(cells.size()); for (Cell cell : cells) { pbCells.add(convertCellToPb(cell)); } return pbCells; } it is better to return more generic List rather than return a concrete ArrayList

Target:
public static List<RiakKvPB.TsCell> convertCellsToPb(Collection<Cell> cells) { final ArrayList<RiakKvPB.TsCell> pbCells = new ArrayList<RiakKvPB.TsCell>(cells.size()); for (Cell cell : cells) { pbCells.add(convertCellToPb(cell)); } return pbCells; }
Source:
public SetOp add(ByteArrayWrapper element) { START this.adds.add(element); END this.removes.remove(element); return this; } This is something I struggled with. The semantics of observed-remove make it not-so-obvious what the user _means_ by an add shipped in the same operation as a remove. In the Erlang client, we decided that sending _all_ recorded operations was the least surprising solution, with the caveat that removes are applied before adds.

Target:
public SetOp add(ByteArrayWrapper element) { this.adds.add(element); return this; }
Source:
public boolean isClientHealthy(RawClient client) { try { //-- First check to see if client is up client.ping(); //-- Check to see if client has joined ring by check to see if it has any buckets START return !client.listBuckets().isEmpty(); END } catch (IOException ioe) { return false; } } The listBuckets() operation will kill the cluster in production as it needs to go trough all the keys. Maybe there is a better way to check for health?

Target:
public boolean isClientHealthy(RawClient client) { try { client.ping(); return true; } catch (IOException ioe) { return false; } }
Source:
START public NodeStats stats() END { NodeStats nodeStats = null; for(RawClient rc : cluster) { if (nodeStats == null) nodeStats = rc.stats(); else nodeStats.add(rc.stats()); } return nodeStats; } Style points as before. In this case the class has existing code in a certain style.

Target:
public NodeStats stats() throws IOException { NodeStats nodeStats = null; for(RawClient rc : cluster) { if (nodeStats == null) nodeStats = rc.stats(); else nodeStats.add(rc.stats()); } return nodeStats; }
Source:
Integer safeGet(String key) { if (containsKey(key)) { return get(key); } else { START System.out.println(key + " unknown"); END return get("UNK"); } } Is that a leftover from debugging or on purpose?

Target:
Integer safeGet(String key) { if (containsKey(key)) { return get(key); } else { return get("UNK"); } }
Source:
void activate() { try { Central.bndCall(() -> { process(); START list = memoize(this::list0); END return null; }); } catch (Exception e) { logger.error("Could not activate {}", getName(), e); } } This does not do what you want. It just creates the memoize object. You need to wrap the supplier. So move the bndCall invocation into list0.

Target:
void activate() { process(); }
Source:
public void partClosed(IWorkbenchPart part) { IDragAndDropService dndService = part.getSite() .getService(IDragAndDropService.class); IAdaptable adapter = part; START Control control = adapter.getAdapter(Control.class); END if (control != null && dndService != null) { dndService.removeMergedDropTarget(control); } } BndEditor would need to add `getAdapter` support for Control.class for this to properly unmerge the dropTarget.

Target:
public void partClosed(IWorkbenchPart part) { IDragAndDropService dndService = part.getSite() .getService(IDragAndDropService.class); Control control = part.getAdapter(Control.class); if (control != null && dndService != null) { dndService.removeMergedDropTarget(control); } }
Source:
public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) { try { if (!init()) { return Collections.emptyMap(); } } catch (RuntimeException re) { START throw re; END } catch (Exception e) { throw Exceptions.duck(e); } return repoImpl.findProviders(requirements); } if you use duck, no need to do this extra Runtime check

Target:
public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) { if (!init()) { return Collections.emptyMap(); } return repoImpl.findProviders(requirements); }