auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void checkIfRepoStarred() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_NO_CONTENT) ).next(new MkAnswer.Simple(HttpURLConnection.HTTP_NOT_FOUND)) .start(); <START> final Stars truestars = new RtStars( <END> new ApacheRequest(container.home()), RtStarsTest.repo("someuser", "starredrepo") ); MatcherAssert.assertThat( truestars.starred(), Matchers.is(true) ); final Stars falsestars = new RtStars( new ApacheRequest(container.home()), RtStarsTest.repo("otheruser", "notstarredrepo") ); MatcherAssert.assertThat( falsestars.starred(), Matchers.is(false) ); }</code><technical_language>call this variable stars starred. avoid compound variable names: <LINK_0></technical_language>

Target:
public void checkIfRepoStarred() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_NO_CONTENT) ).next(new MkAnswer.Simple(HttpURLConnection.HTTP_NOT_FOUND)) .start(); final Stars starred = new RtStars( new ApacheRequest(container.home()), RtStarsTest.repo("someuser", "starredrepo") ); MatcherAssert.assertThat( starred.starred(), Matchers.is(true) ); final Stars unstarred = new RtStars( new ApacheRequest(container.home()), RtStarsTest.repo("otheruser", "notstarredrepo") ); MatcherAssert.assertThat( unstarred.starred(), Matchers.is(false) ); }
Source:
<code>private static Map<String, Long> getExternalResourceAmountMap(Configuration config) { final Set<String> resourceSet = getExternalResourceSet(config); LOG.info("Enabled external resources: {}", resourceSet); if (resourceSet.isEmpty()) { return Collections.emptyMap(); } final Map<String, Long> externalResourceAmountMap = new HashMap<>(); for (String resourceName: resourceSet) { final ConfigOption<Long> amountOption = key(ExternalResourceOptions.keyWithResourceNameAndSuffix(resourceName, ExternalResourceOptions.EXTERNAL_RESOURCE_AMOUNT_SUFFIX)) .longType() .noDefaultValue(); final Long amount = config.getLong(amountOption, 0); <START> if (amount <= 0) { LOG.warn("The amount of the should be configured with a positive value.", resourceName); break; <END> } else { externalResourceAmountMap.put(resourceName, amount); } } return externalResourceAmountMap; }</code><technical_language>here. separate cases of amount illegal amount. Also, log amount is ignored</technical_language>

Target:
public static Map<String, Long> getExternalResourceAmountMap(Configuration config) { final Set<String> resourceSet = getExternalResourceSet(config); LOG.info("Enabled external resources: {}", resourceSet); if (resourceSet.isEmpty()) { return Collections.emptyMap(); } final Map<String, Long> externalResourceAmountMap = new HashMap<>(); for (String resourceName: resourceSet) { final ConfigOption<Long> amountOption = key(ExternalResourceOptions.getAmountConfigOptionForResource(resourceName)) .longType() .noDefaultValue(); final Optional<Long> amountOpt = config.getOptional(amountOption); if (!amountOpt.isPresent()) { LOG.warn("The amount of the should be configured. Will ignore that resource.", resourceName); } else if (amountOpt.get() <= 0) { LOG.warn("The amount of the should be positive while finding {}. Will ignore that resource.", amountOpt.get(), resourceName); } else { externalResourceAmountMap.put(resourceName, amountOpt.get()); } } return externalResourceAmountMap; }
Source:
<code>public DummyXAResource xaResource() { rms.addXAResourceRecovery(xaResourceRecovery()); <START> return new DummyXAResource(); <END> }</code><technical_language>Ah, thanks for pointing out - I missed that. is calls xaResource() method? in spring config boot? need recovery helper is installed boot? Is a reason do in xaResourceRecovery() method immediately below? preference some force DummyXAResourceRecovery set RecoveryManagerService boot? For example call a setter RecoveryManagerService spring wiring passes DummyXAResourceRecovery in pass RecoveryManagerService DummyXAResourceRecovery call add it? This is if possible</technical_language>

Target:
public DummyXAResource xaResource() { return new DummyXAResource(); }
Source:
<code>private void runLibertyMojoDeploy() throws MojoExecutionException { deployParams.addAll(commonParams); deployParams.addAll(commonServerParams); Xpp3Dom config = stripConfigElements(getLibertyPluginConfig(), deployParams); <START> stripConfigElements(config, deployParams); <END> log.info("Running liberty:deploy goal"); runLibertyMojo("deploy", config); }</code><technical_language>This is a duplicate of line</technical_language>

Target:
private void runLibertyMojoDeploy() throws MojoExecutionException { Xpp3Dom pluginConfig = (Xpp3Dom)getLibertyPlugin().getConfiguration(); if (pluginConfig != null && pluginConfig.getChild("looseApplication") != null && "false".equals(pluginConfig.getChild("looseApplication").getValue())) { log.warn("Overriding liberty plugin pararmeter, \"looseApplication\" to \"true\" and deploying application in looseApplication format"); } Xpp3Dom config = stripConfigElements(getLibertyPluginConfig(), deployParams); log.info("Running liberty:deploy goal"); runLibertyMojo("deploy", config); }
Source:
<code>public String getAuthorityKeyID() { if(authorityKeyID == null){ byte[] authorityKey = x509Cert.getExtensionValue(AUTHORITY_KEY_ID); try { if (authorityKey != null) { DERDecoder extValA = new DERDecoder(authorityKey); extValA.skip(AUTHORITY_KEY_POSITION); <START> int length = authorityKey.length - AUTHORITY_KEY_POSITION; <END> authorityKeyID = Hex.encodeHexString(extValA.getBytes(length)); } } catch (WSSecurityException e) { LOG.error("Unable to convert AIK into human readable ", e.getLocalizedMessage(), e); } } return StringUtils.isEmpty(authorityKeyID) ? EMPTY_FIELD : authorityKeyID; }</code><technical_language>move this logic certificatemanagerserviceImpl class</technical_language>

Target:
public String getAuthorityKeyID() { return authorityKeyID; }
Source:
<code>public boolean vdsUpEvent(final VDS vds) { HostStoragePoolParametersBase params = new HostStoragePoolParametersBase(vds); boolean isSucceeded = Backend.getInstance().runInternalAction(VdcActionType.InitVdsOnUp, params).getSucceeded(); if (isSucceeded) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { try { List<VmStatic> vmsToMigrate = DbFacade.getInstance().getVmStaticDao().getAllWithFailbackByVds(vds.getId()); if (!vmsToMigrate.isEmpty()) { CommandContext ctx = new CommandContext(new EngineContext()); ctx.getExecutionContext().setMonitored(true); Backend.getInstance().runInternalMultipleActions(VdcActionType.MigrateVmToServer, new ArrayList<>(createMigrateVmToServerParametersList(vmsToMigrate, vds)), ctx); } } catch (RuntimeException e) { <START> log.error("Failed to initialize Vds on up.", e); <END> } } }); } return isSucceeded; }</code><technical_language>intentional error</technical_language>

Target:
public boolean vdsUpEvent(final VDS vds) { HostStoragePoolParametersBase params = new HostStoragePoolParametersBase(vds); boolean isSucceeded = Backend.getInstance().runInternalAction(VdcActionType.InitVdsOnUp, params).getSucceeded(); if (isSucceeded) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { try { List<VmStatic> vmsToMigrate = DbFacade.getInstance().getVmStaticDao().getAllWithFailbackByVds(vds.getId()); if (!vmsToMigrate.isEmpty()) { CommandContext ctx = new CommandContext(new EngineContext()); ctx.getExecutionContext().setMonitored(true); Backend.getInstance().runInternalMultipleActions(VdcActionType.MigrateVmToServer, new ArrayList<>(createMigrateVmToServerParametersList(vmsToMigrate, vds)), ctx); } } catch (RuntimeException e) { log.error("Failed to initialize Vds on up: {}", e.getMessage()); log.debug("Exception", e); } } }); } return isSucceeded; }
Source:
<code>protected int rwAnyNode(IASTNode node, int indirection) { final IASTNode parent = node.getParent(); <START> if (parent instanceof IASTIdExpression) { <END> final IASTNode grandParent = parent.getParent(); if (grandParent instanceof IASTArraySubscriptExpression) { return rwInExpression((IASTArraySubscriptExpression) grandParent, parent, indirection + 1); } else if (grandParent instanceof IASTUnaryExpression) { return rwInExpression((IASTUnaryExpression) grandParent, parent, indirection); } } if (parent instanceof IASTExpression) { return rwInExpression((IASTExpression) parent, node, indirection); } else if (parent instanceof IASTStatement) { return rwInStatement((IASTStatement) parent, node, indirection); } else if (parent instanceof IASTDeclarator) { return rwInDeclarator((IASTDeclarator) parent, indirection); } else if (parent instanceof IASTEqualsInitializer) { return rwInEqualsInitializer((IASTEqualsInitializer) parent, indirection); } else if (parent instanceof IASTArrayModifier) { return READ; } else if (parent instanceof IASTInitializerList) { return rwInInitializerList((IASTInitializerList) parent, indirection); } return READ | WRITE; }</code><technical_language>Move lines 66-73 rwInExpression IASTIdExpression is a subclass of IASTExpression</technical_language>

Target:
protected int rwAnyNode(IASTNode node, int indirection) { final IASTNode parent = node.getParent(); if (parent instanceof IASTExpression) { return rwInExpression((IASTExpression) parent, node, indirection); } else if (parent instanceof IASTStatement) { return rwInStatement((IASTStatement) parent, node, indirection); } else if (parent instanceof IASTDeclarator) { return rwInDeclarator((IASTDeclarator) parent, indirection); } else if (parent instanceof IASTEqualsInitializer) { return rwInEqualsInitializer((IASTEqualsInitializer) parent, indirection); } else if (parent instanceof IASTArrayModifier) { return READ; } else if (parent instanceof IASTInitializerList) { return rwInInitializerList((IASTInitializerList) parent, indirection); } return READ | WRITE; }
Source:
<code>private static Repo repo( final MkStorage storage) throws IOException { <START> final String test = "test"; <END> return new MkGithub(storage, test).repos().create( Json.createObjectBuilder().add("name", test).build() ); }</code><technical_language>strange name for variable, mean</technical_language>

Target:
private static Repo repo( final MkStorage storage) throws IOException { final String login = "test"; return new MkGithub(storage, login).repos().create( Json.createObjectBuilder().add("name", login).build() ); }
Source:
<code>private static HashCode computeValuesHashCode(Set<String> values) { final List<String> sortedValues = new ArrayList<>(values); sortedValues.sort(Comparator.nullsFirst(Ordering.natural())); <START> final Hasher hasher = Hashing.sha256().newHasher(); <END> for (String v : sortedValues) { if (v == null) { hasher.putInt(0); } else { hasher.putString(v, StandardCharsets.UTF_8); } } return hasher.hash(); }</code><technical_language>I this new, worth investigating if faster hashes unique enough for this (not necessary in this PR, thinking out loud)</technical_language>

Target:
public static int computeValuesHashCode(Set<String> values) { final List<String> sortedValues = new ArrayList<>(values); sortedValues.sort(Comparator.nullsFirst(Ordering.natural())); final Hasher hasher = Hashing.sha256().newHasher(); for (String v : sortedValues) { if (v == null) { hasher.putInt(0); } else { hasher.putString(v, StandardCharsets.UTF_8); } } return hasher.hash().asInt(); }
Source:
<code>public void testSaslPrincipalIsSignificant() throws IOException, InterruptedException { UserGroupInformation user1 = UserGroupInformation.createUserForTesting("user1", new String[0]); final KerberosToken token = EasyMock.createMock(KerberosToken.class); SaslConnectionParams saslParams1 = user1 <START> .doAs((PrivilegedExceptionAction<SaslConnectionParams>) () -> createSaslParams(token)); <END> UserGroupInformation user2 = UserGroupInformation.createUserForTesting("user2", new String[0]); SaslConnectionParams saslParams2 = user2 .doAs((PrivilegedExceptionAction<SaslConnectionParams>) () -> createSaslParams(token)); ThriftTransportKey ttk1 = new ThriftTransportKey(HostAndPort.fromParts("localhost", 9997), 1l, null, saslParams1), ttk2 = new ThriftTransportKey(HostAndPort.fromParts("localhost", 9997), 1l, null, saslParams2); assertNotEquals(ttk1, ttk2); assertNotEquals(ttk1.hashCode(), ttk2.hashCode()); }</code><technical_language>Nice clean up</technical_language>

Target:
public void testSaslPrincipalIsSignificant() throws IOException, InterruptedException { UserGroupInformation user1 = UserGroupInformation.createUserForTesting("user1", new String[0]); final KerberosToken token = EasyMock.createMock(KerberosToken.class); SaslConnectionParams saslParams1 = user1 .doAs((PrivilegedExceptionAction<SaslConnectionParams>) () -> createSaslParams(token)); UserGroupInformation user2 = UserGroupInformation.createUserForTesting("user2", new String[0]); SaslConnectionParams saslParams2 = user2 .doAs((PrivilegedExceptionAction<SaslConnectionParams>) () -> createSaslParams(token)); ThriftTransportKey ttk1 = new ThriftTransportKey(HostAndPort.fromParts("localhost", 9997), 1L, null, saslParams1), ttk2 = new ThriftTransportKey(HostAndPort.fromParts("localhost", 9997), 1L, null, saslParams2); assertNotEquals(ttk1, ttk2); assertNotEquals(ttk1.hashCode(), ttk2.hashCode()); }
Source:
<code>public void testEGetNullEObjectNullFeature() { <START> assertEquals(null, eObjectServices.eGet(null, null)); <END> }</code><technical_language>Remove useless assert</technical_language>

Target:
public void testEGetNullEObjectNullFeature() { eObjectServices.eGet(null, null); }
Source:
<code>public URI createURI(URI location) { URI result = null; <START> switch (oldScheme) { <END> case "http": if (location.getPort() == -1) { result = URI.create(format("%s://%s:80", newScheme, location.getAuthority())); } break; case "https": if (location.getPort() == -1) { result = URI.create(format("%s://%s:443", newScheme, location.getAuthority())); } break; default: } if (result == null) { result = URI.create(format("%s://%s", newScheme, location.getAuthority())); } return result; }</code><technical_language>get scheme location URI caching scheme</technical_language>

Target:
public URI createURI(URI location) { URI result; if (location.getPort() == -1) { int port = getDefaultPortForScheme(location.getScheme()); result = URI.create(format("%s://%s:%d", newScheme, location.getAuthority(), port)); } else { result = URI.create(format("%s://%s", newScheme, location.getAuthority())); } return result; }
Source:
<code>protected static ImmutableList<Ds3Annotation> convertAllAnnotations( final ImmutableList<Ds3Annotation> annotations, final NameMapper nameMapper) { if (annotations == null || annotations.isEmpty()) { return annotations; } <START> ImmutableList.Builder<Ds3Annotation> builder = ImmutableList.builder(); <END> for (final Ds3Annotation annotation : annotations) { final Ds3Annotation convertedAnnotation = new Ds3Annotation( convertName(annotation.getName(), nameMapper), convertAllAnnotationElements(annotation.getDs3AnnotationElements(), nameMapper)); builder.add(convertedAnnotation); } return builder.build(); }</code><technical_language>Missing final</technical_language>

Target:
protected static ImmutableList<Ds3Annotation> convertAllAnnotations( final ImmutableList<Ds3Annotation> annotations, final NameMapper nameMapper) { if (annotations == null || annotations.isEmpty()) { return annotations; } final ImmutableList.Builder<Ds3Annotation> builder = ImmutableList.builder(); for (final Ds3Annotation annotation : annotations) { final Ds3Annotation convertedAnnotation = new Ds3Annotation( convertName(annotation.getName(), nameMapper), convertAllAnnotationElements(annotation.getDs3AnnotationElements(), nameMapper)); builder.add(convertedAnnotation); } return builder.build(); }
Source:
<code>public CUBRIDDialect() { <START> registerColumnType( Types.BOOLEAN, "bit" ); <END> registerColumnType( Types.TINYINT, "smallint" ); registerColumnType(Types.TIMESTAMP, "datetime"); registerColumnType(Types.TIMESTAMP, "datetimetz"); registerColumnType( Types.BINARY, "bit($l)"); registerColumnType( Types.VARBINARY, "bit varying($l)"); getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "true" ); getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); registerKeyword( "TYPE" ); registerKeyword( "YEAR" ); registerKeyword( "MONTH" ); registerKeyword( "ALIAS" ); registerKeyword( "VALUE" ); registerKeyword( "FIRST" ); registerKeyword( "ROLE" ); registerKeyword( "CLASS" ); registerKeyword( "BIT" ); registerKeyword( "TIME" ); registerKeyword( "QUERY" ); registerKeyword( "DATE" ); registerKeyword( "USER" ); registerKeyword( "ACTION" ); registerKeyword( "SYS_USER" ); registerKeyword( "ZONE" ); registerKeyword( "LANGUAGE" ); registerKeyword( "DICTIONARY" ); registerKeyword( "DATA" ); registerKeyword( "TEST" ); registerKeyword( "SUPERCLASS" ); registerKeyword( "SECTION" ); registerKeyword( "LOWER" ); registerKeyword( "LIST" ); registerKeyword( "OID" ); registerKeyword( "DAY" ); registerKeyword( "IF" ); registerKeyword( "ATTRIBUTE" ); registerKeyword( "STRING" ); registerKeyword( "SEARCH" ); }</code><technical_language>is done automatically, yes. of developed Java for more a day ;) But: 1) imo this is kind of change unnecessary conflicts (right?) 2) nice for debug breakpoints 3) is reason them. is performance penalty</technical_language>

Target:
public CUBRIDDialect() { super(); registerColumnType( Types.BOOLEAN, "bit" ); registerColumnType( Types.TINYINT, "smallint" ); registerColumnType(Types.TIMESTAMP, "datetime"); registerColumnType(Types.TIMESTAMP, "datetimetz"); registerColumnType( Types.BINARY, "bit($l)"); registerColumnType( Types.VARBINARY, "bit varying($l)"); getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "true" ); getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); registerKeyword( "TYPE" ); registerKeyword( "YEAR" ); registerKeyword( "MONTH" ); registerKeyword( "ALIAS" ); registerKeyword( "VALUE" ); registerKeyword( "FIRST" ); registerKeyword( "ROLE" ); registerKeyword( "CLASS" ); registerKeyword( "BIT" ); registerKeyword( "TIME" ); registerKeyword( "QUERY" ); registerKeyword( "DATE" ); registerKeyword( "USER" ); registerKeyword( "ACTION" ); registerKeyword( "SYS_USER" ); registerKeyword( "ZONE" ); registerKeyword( "LANGUAGE" ); registerKeyword( "DICTIONARY" ); registerKeyword( "DATA" ); registerKeyword( "TEST" ); registerKeyword( "SUPERCLASS" ); registerKeyword( "SECTION" ); registerKeyword( "LOWER" ); registerKeyword( "LIST" ); registerKeyword( "OID" ); registerKeyword( "DAY" ); registerKeyword( "IF" ); registerKeyword( "ATTRIBUTE" ); registerKeyword( "STRING" ); registerKeyword( "SEARCH" ); }
Source:
<code>public void stop(Throwable cause) throws Exception { LOGGER.log(Level.FINE, "Stopping container step."); <START> closeQuietly(client); <END> }</code><technical_language>This is called interruption. proc in this case? Is handled Jenkins, do cleanup ourselves</technical_language>

Target:
public void stop(Throwable cause) throws Exception { LOGGER.log(Level.FINE, "Stopping container step."); closeQuietly(client, decorator); }
Source:
<code>protected void executeQueryCommand() { GlusterGeoRepDao geoRepDao = getGeoRepDao(); List<GlusterGeoRepSession> geoRepSessions = geoRepDao.getGeoRepSessions(getParameters().getId()); if (geoRepSessions != null) { for (GlusterGeoRepSession currentSession : geoRepSessions) { List<GlusterGeoRepSessionDetails> geoRepSessionDetails = geoRepDao.getGeoRepSessionDetails(currentSession.getId()); if(geoRepSessionDetails == null) { continue; } ArrayList<GlusterGeoRepSessionDetails> currentSessionDetails = (ArrayList<GlusterGeoRepSessionDetails>) geoRepSessionDetails; <START> currentSession.setSessionDetails(currentSessionDetails); <END> if (currentSession.getSessionDetails() != null) { for (GlusterGeoRepSessionDetails currentDetail : currentSession.getSessionDetails()) { GlusterBrickEntity currentBrick = getGlusterBrickDao().getById(currentDetail.getMasterBrickId()); if (currentBrick != null) { currentDetail.setMasterBrickNode(currentBrick.getServerName()); } } } } } getQueryReturnValue().setReturnValue(geoRepSessions); }</code><technical_language>set if null check next? Check for null of currentSessionDetails if null call currentSession.setSessionDetails continue further</technical_language>

Target:
protected void executeQueryCommand() { GlusterGeoRepDao geoRepDao = getGeoRepDao(); List<GlusterGeoRepSession> geoRepSessions = geoRepDao.getGeoRepSessions(getParameters().getId()); if (geoRepSessions != null) { for (GlusterGeoRepSession currentSession : geoRepSessions) { List<GlusterGeoRepSessionDetails> geoRepSessionDetails = geoRepDao.getGeoRepSessionDetails(currentSession.getId()); if(geoRepSessionDetails == null) { continue; } for (GlusterGeoRepSessionDetails currentDetail : geoRepSessionDetails) { if(currentDetail == null) { continue; } Guid currentMasterBrickId = currentDetail.getMasterBrickId(); if(currentMasterBrickId == null) { continue; } GlusterBrickEntity currentBrick = getGlusterBrickDao().getById(currentMasterBrickId); if (currentBrick != null) { currentDetail.setMasterBrickNode(currentBrick.getServerName()); } } currentSession.setSessionDetails((ArrayList<GlusterGeoRepSessionDetails>) geoRepSessionDetails); } } getQueryReturnValue().setReturnValue(geoRepSessions); }
Source:
<code>public T execute() throws E { WikiReference currWiki = getContext().getWikiRef(); try { <START> if (wiki != null) { <END> getContext().setWikiRef(wiki); } return call(); } finally { getContext().setWikiRef(currWiki); } }</code><technical_language>I checkState(wiki != null) is more force a proper usage</technical_language>

Target:
public T execute() throws E { checkState(wiki != null, "No wiki set for ContextExecutor"); WikiReference currWiki = getContext().getWikiRef(); try { getContext().setWikiRef(wiki); return call(); } finally { getContext().setWikiRef(currWiki); } }
Source:
<code>public static String abbreviateName(Class<?> cls, int pkgNameDepth) { if (pkgNameDepth < 1) return cls.getSimpleName(); if (pkgNameDepth >= MAX_ABBREVIATE_NAME_LVL) return cls.getName(); String[] pkgNameParts = cls.getName().split("\\."); if (pkgNameParts.length == 1) return pkgNameParts[0]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < pkgNameParts.length - 1; ++i) { if( pkgNameParts[i].length() == 3 ) sb.append(pkgNameParts[i]); else { sb.append(pkgNameParts[i].charAt(0)); if (pkgNameParts[i].length() > 3) sb.append(pkgNameParts[i].charAt(pkgNameParts[i].length() / 2)); if (pkgNameParts[i].length() > 1) sb.append(pkgNameParts[i].charAt(pkgNameParts[i].length() - 1)); } <START> sb.append("."); <END> } sb.append(pkgNameParts[pkgNameParts.length - 1]); return sb.toString(); }</code><technical_language>sb.append('.')</technical_language>

Target:
public static String abbreviateName(Class<?> cls, int pkgNameDepth) { if (pkgNameDepth < 1) return cls.getSimpleName(); if (pkgNameDepth >= MAX_ABBREVIATE_NAME_LVL) return cls.getName(); String[] pkgNameParts = cls.getName().split("\\."); if (pkgNameParts.length == 1) return pkgNameParts[0]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < pkgNameParts.length - 1; ++i) { if( pkgNameParts[i].length() == 3 ) sb.append(pkgNameParts[i]); else { sb.append(pkgNameParts[i].charAt(0)); if (pkgNameParts[i].length() > 3) sb.append(pkgNameParts[i].charAt(pkgNameParts[i].length() / 2)); if (pkgNameParts[i].length() > 1) sb.append(pkgNameParts[i].charAt(pkgNameParts[i].length() - 1)); } sb.append('.'); } sb.append(pkgNameParts[pkgNameParts.length - 1]); return sb.toString(); }
Source:
<code>public void testSplitter() throws Exception { LineSplitter splitter = new LineSplitter(); Stream<StringHandle> contentStream = splitter.split(new FileInputStream(jsonlFile)); assertNotNull(contentStream); StringHandle[] result = contentStream.toArray(size -> new StringHandle[size]); assertNotNull(result); <START> assertEquals(result.length, Files.lines(Paths.get(jsonlFile)).count()); <END> String[] originalResult = Files.lines(Paths.get(jsonlFile)) .toArray(size -> new String[size]); for (int i = 0; i < result.length && i < originalResult.length; i++) { assertNotNull(result[i].get()); assertEquals(result[i].get(), originalResult[i]); } }</code><technical_language>test run slightly faster if, instead of reading file twice, test moved originalResult line 37 initialization originalResult.length for this assertion. a thought. Also, if asserted result.length is equal originalResult.length, need test in loop below. a thought</technical_language>

Target:
public void testSplitter() throws Exception { LineSplitter splitter = new LineSplitter(); Stream<StringHandle> contentStream = splitter.split(new FileInputStream(jsonlFile)); assertNotNull(contentStream); String[] originalResult = Files.lines(Paths.get(jsonlFile)) .toArray(size -> new String[size]); checkContent(contentStream, splitter.getFormat(), originalResult); }
Source:
<code><START> public static KeyVaultKey fromKeyId(String keyId, JsonWebKey jsonWebKey) { <END> KeyProperties properties = new KeyProperties(); properties.unpackId(keyId); return new KeyVaultKey(properties, jsonWebKey); }</code><technical_language>Good null checks helper methods</technical_language>

Target:
public static KeyVaultKey fromKeyId(String keyId, JsonWebKey jsonWebKey) { Objects.requireNonNull(jsonWebKey, "The Json web key cannot be null"); KeyProperties properties = new KeyProperties(); properties.unpackId(keyId); return new KeyVaultKey(properties, jsonWebKey); }
Source:
<code>public void shouldDropIndexOnRecovery() throws IOException { CommittedTransactionRepresentation dropTransaction = prepareDropTransaction(); File storeDir = directory.graphDbDir(); GraphDatabaseService db = new TestGraphDatabaseFactory().newEmbeddedDatabase( storeDir ); createIndex( db ); db.shutdown(); appendDropTransactionToTransactionLog( storeDir, dropTransaction ); Monitors monitors = new Monitors(); AssertRecoveryIsPerformed recoveryMonitor = new AssertRecoveryIsPerformed(); monitors.addMonitorListener( recoveryMonitor ); db = new TestGraphDatabaseFactory().setMonitors( monitors ).newEmbeddedDatabase( storeDir ); assertTrue( recoveryMonitor.recoveryWasPerformed ); try ( Transaction tx = db.beginTx() ) { assertEquals( 0, count( db.schema().getIndexes() ) ); tx.success(); } <START> db.shutdown(); <END> }</code><technical_language>This guy belongs in a finally clause</technical_language>

Target:
public void shouldDropIndexOnRecovery() throws IOException { CommittedTransactionRepresentation dropTransaction = prepareDropTransaction(); File storeDir = directory.graphDbDir(); GraphDatabaseService db = new TestGraphDatabaseFactory().newEmbeddedDatabase( storeDir ); createIndex( db ); db.shutdown(); appendDropTransactionToTransactionLog( storeDir, dropTransaction ); Monitors monitors = new Monitors(); AssertRecoveryIsPerformed recoveryMonitor = new AssertRecoveryIsPerformed(); monitors.addMonitorListener( recoveryMonitor ); db = new TestGraphDatabaseFactory().setMonitors( monitors ).newEmbeddedDatabase( storeDir ); try { assertTrue( recoveryMonitor.recoveryWasPerformed ); try ( Transaction tx = db.beginTx() ) { assertEquals( 0, count( db.schema().getIndexes() ) ); tx.success(); } } finally { db.shutdown(); } }
Source:
<code>public void testCollector() { final CollectorAsserterMonitor[] mon = new CollectorAsserterMonitor[1]; final int[] numLoops = new int[] { 10000 }; <START> TestThread t <END> = new TestThread("Test Accumulating Monitor") { @Override public void run() { mon[0] = new CollectorAsserterMonitor(); IProgressMonitorWithBlocking wrapper = ProgressMonitorUtil.createAccumulatingProgressMonitor(mon[0], Display.getDefault()); wrapper.beginTask("Some Task", 100); for (int i = 0; i < numLoops[0]; i++) { wrapper.setTaskName("Task Name " + i); } wrapper.done(); } }; t.start(); runEventLoop(4000, t); assertNotNull(mon[0]); ArrayList<String> tasks = mon[0].getTaskNames(); int size = tasks.size(); assertFalse("No events were fired in the UI thread. No events reached our intended monitor.", size == 0); assertTrue("Events received should be less than 20% of events fired: expected=" + (numLoops[0] / 5) + ", actual=" + size, size < (numLoops[0] / 5)); assertFalse(t.isCanceled()); }</code><technical_language>need for a thread in this test. simpler verify flow control properties of monitor if post a bunch of events progress monitor right UI thread, run event loop empty (rather for 4s), assert number of events posted Collector 1. run 1000x faster potential for flakiness if task scheduler strange. test is sufficient for verifying monitor works correctly in presence of multithreading</technical_language>

Target:
public void testCollector() { final CollectorAsserterMonitor mon = new CollectorAsserterMonitor(); final int[] numLoops = new int[] { 10000 }; IProgressMonitorWithBlocking wrapper = ProgressMonitorUtil.createAccumulatingProgressMonitor(mon, Display.getDefault()); wrapper.beginTask("Some Task", 100); for (int i = 0; i < numLoops[0]; i++) { wrapper.setTaskName("Task Name " + i); } wrapper.done(); ArrayList<String> tasks = mon.getTaskNames(); int size = tasks.size(); assertEquals(0, size); runEventLoopUntilEmpty(); tasks = mon.getTaskNames(); size = tasks.size(); assertEquals(1, size); }
Source:
<code>public void getReport(XResultData rd) { <START> rd.logWithFormat("AtsConfigCache\n", AtsConfigCache.instance); <END> rd.logWithFormat("TagToConfigObject size %d\n", tagToConfigObject.keySet().size()); rd.logWithFormat("ConfigObjects size %d\n", configObjects.size()); }</code><technical_language>need pass in instance formatting characters in string</technical_language>

Target:
public void getReport(XResultData rd) { rd.logWithFormat("TagToConfigObject size %d\n", tagToConfigObject.keySet().size()); rd.logWithFormat("ConfigObjects size %d\n", configObjects.size()); }
Source:
<code>public void testXmlConfig() throws IOException { EmbeddedCacheManager cm = new DefaultCacheManager("jpa-config.xml"); Cache<String, KeyValueEntity> specificCache = cm.getCache("specificCache"); validateConfig(specificCache); KeyValueEntity entity = new KeyValueEntity("k", "v"); specificCache.put(entity.getK(), entity); <START> cm.stop(); <END> }</code><technical_language>stop() in a finally block, TestingUtil.withCacheManager()</technical_language>

Target:
public void testXmlConfig() throws IOException { EmbeddedCacheManager cm = null; try { cm = new DefaultCacheManager("jpa-config.xml"); Cache<String, KeyValueEntity> specificCache = cm.getCache("specificCache"); validateConfig(specificCache); KeyValueEntity entity = new KeyValueEntity("k", "v"); specificCache.put(entity.getK(), entity); } finally { if (cm != null) cm.stop(); } }
Source:
<code>private static void writeTargetWeightsFile(final File ponFile, final File outputFile) { Utils.regularReadableUserFile(ponFile); try (final HDF5File file = new HDF5File(ponFile, HDF5File.OpenMode.READ_ONLY)) { final HDF5PCACoveragePoN pon = new HDF5PCACoveragePoN(file); <START> final double[] targetWeights = DoubleStream.of(pon.getTargetVariances()).boxed().mapToDouble(v -> 1/v).toArray(); <END> ParamUtils.writeValuesToFile(targetWeights, outputFile); } }</code><technical_language>boxed().mapToDouble() equivalent .map()</technical_language>

Target:
private static void writeTargetWeightsFile(final File ponFile, final File outputFile) { Utils.regularReadableUserFile(ponFile); try (final HDF5File file = new HDF5File(ponFile, HDF5File.OpenMode.READ_ONLY)) { final HDF5PCACoveragePoN pon = new HDF5PCACoveragePoN(file); final double[] targetWeights = DoubleStream.of(pon.getTargetVariances()).map(v -> 1 / v).toArray(); ParamUtils.writeValuesToFile(targetWeights, outputFile); } }
Source:
<code><START> private static Object wrapHash(String key, Multihash h) { <END> Map<String, Object> json = new TreeMap<>(); json.put(key, h.toString()); return json; }</code><technical_language>Mind changing type of this Map<String, Object></technical_language>

Target:
private static Map<String, Object> wrapHash(String key, Multihash h) { Map<String, Object> json = new TreeMap<>(); json.put(key, h.toString()); return json; }
Source:
<code>public Setter(final String fieldLocation, String into, final String fieldName, final String methodName, final String desc, final boolean methodStatic, final String fieldDesc) { this.fieldLocation = ASMUtils.getClass(fieldLocation); into = (into == null) ? fieldLocation : into; this.into = ASMUtils.getClass(into); this.field = ASMUtils.getField(this.fieldLocation, fieldName, fieldDesc); this.name = methodName; <START> this.desc = (desc == null) && this.field != null ? this.field.desc : desc; <END> this.methodStatic = methodStatic; }</code><technical_language>this change do</technical_language>

Target:
public Setter(final String fieldLocation, String into, final String fieldName, final String methodName, final String desc, final boolean methodStatic, final String fieldDesc) { this.fieldLocation = ASMUtils.getClass(fieldLocation); into = (into == null) ? fieldLocation : into; this.into = ASMUtils.getClass(into); this.field = ASMUtils.getField(this.fieldLocation, fieldName, fieldDesc); this.name = methodName; this.desc = (desc == null && this.field != null) ? this.field.desc : desc; this.methodStatic = methodStatic; }
Source:
<code>private boolean hasValidSignature(SignableSAMLObject samlObject, Saml2AuthenticationToken token) { if (!samlObject.isSigned()) { if (logger.isDebugEnabled()) { logger.debug("SAML object is not signed, no signatures found"); } return false; } <START> final List<X509Certificate> verificationKeys = getVerificationCertificates(token); <END> if (verificationKeys.isEmpty()) { return false; } for (X509Certificate certificate : verificationKeys) { final Credential credential = getVerificationCredential(certificate); try { SignatureValidator.validate(samlObject.getSignature(), credential); if (logger.isDebugEnabled()) { logger.debug("Valid signature found in SAML object:"+samlObject.getClass().getName()); } return true; } catch (SignatureException ignored) { if (logger.isTraceEnabled()) { logger.trace("Signature validation failed with cert:"+certificate.toString(), ignored); } else if (logger.isDebugEnabled()) { logger.debug("Signature validation failed with cert:"+certificate.toString()); } } } return false; }</code><technical_language>align rest of codebase, please leave final keyword of local variables</technical_language>

Target:
private boolean hasValidSignature(SignableSAMLObject samlObject, Saml2AuthenticationToken token) { if (!samlObject.isSigned()) { if (logger.isDebugEnabled()) { logger.debug("SAML object is not signed, no signatures found"); } return false; } List<X509Certificate> verificationKeys = getVerificationCertificates(token); if (verificationKeys.isEmpty()) { return false; } for (X509Certificate certificate : verificationKeys) { Credential credential = getVerificationCredential(certificate); try { SignatureValidator.validate(samlObject.getSignature(), credential); if (logger.isDebugEnabled()) { logger.debug("Valid signature found in SAML object:"+samlObject.getClass().getName()); } return true; } catch (SignatureException ignored) { if (logger.isTraceEnabled()) { logger.trace("Signature validation failed with cert:"+certificate.toString(), ignored); } else if (logger.isDebugEnabled()) { logger.debug("Signature validation failed with cert:"+certificate.toString()); } } } return false; }
Source:
<code>public GeneralEnvelope getOriginalEnvelope() { <START> return GeneralEnvelope.toGeneralEnvelope(JTS.toEnvelope(roiGeom)); <END> }</code><technical_language>intersect original envelope first? Some unit tests for this class (and feature equivalent) hurt</technical_language>

Target:
public GeneralEnvelope getOriginalEnvelope() { GeneralEnvelope originalEnvelope = super.getOriginalEnvelope(); try { Geometry envIntersection = roiGeom.intersection(JTS.toGeometry(originalEnvelope.toRectangle2D())); envIntersection.setSRID( CRS.lookupEpsgCode(originalEnvelope.getCoordinateReferenceSystem(), false)); return GeneralEnvelope.toGeneralEnvelope(JTS.toEnvelope(envIntersection)); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } return originalEnvelope; }
Source:
<code>public BooleanWrapper configure(Object... policyParameters) { super.configure(policyParameters); if (policyParameters[2] == null) { throw new IllegalArgumentException("Scheduler url must be specified"); } schedulerUrl = policyParameters[2].toString(); if (policyParameters[3] == null) { throw new IllegalArgumentException("Credentials must be specified"); } credentials = (byte[]) policyParameters[3]; if (policyParameters[4] == null) { <START> nodeSourceRecoveryTimeout = PAResourceManagerProperties.RM_NODESOURCE_RECOVERY_TIMEOUT.getValueAsInt(); <END> } if (policyParameters[5] == null) { nodeSourceRecoveryTrialsNumber = PAResourceManagerProperties.RM_NODESOURCE_RECOVERY_TRIAL_NUMBER.getValueAsInt(); } return new BooleanWrapper(true); }</code><technical_language>getValueAsLong()</technical_language>

Target:
public BooleanWrapper configure(Object... policyParameters) { super.configure(policyParameters); if (policyParameters[2] == null) { throw new IllegalArgumentException("Scheduler url must be specified"); } schedulerUrl = policyParameters[2].toString(); if (policyParameters[3] == null) { throw new IllegalArgumentException("Credentials must be specified"); } credentials = (byte[]) policyParameters[3]; if (policyParameters[4] == null) { schedulerAwarePolicyNodeSourceRecoveryDelay = PAResourceManagerProperties.RM_SCHEDULER_AWARE_POLICY_NODESOURCE_RECOVERY_TIMEOUT.getValueAsLong(); } if (policyParameters[5] == null) { schedulerAwarePolicyNodeSourceRecoveryTrialsNumber = PAResourceManagerProperties.RM_SCHEDULER_AWARE_POLICY_NODESOURCE_RECOVERY_TRIAL_NUMBER.getValueAsInt(); } return new BooleanWrapper(true); }
Source:
<code>public static MetricSet of(Cache cache, String name, String... names) { GuavaCacheMetric metrics = new GuavaCacheMetric(); metrics.putMetrics("averageLoadPenalty", () -> cache.stats().averageLoadPenalty(), name, names); metrics.putMetrics("evictionCount", () -> cache.stats().evictionCount(), name, names); metrics.putMetrics("hitCount", () -> cache.stats().hitCount(), name, names); metrics.putMetrics("hitRate", () -> cache.stats().hitRate(), name, names); metrics.putMetrics("loadCount", () -> cache.stats().loadCount(), name, names); metrics.putMetrics("loadExceptionCount", () -> cache.stats().loadExceptionCount(), name, names); metrics.putMetrics("loadExceptionRate", () -> cache.stats().loadExceptionRate(), name, names); metrics.putMetrics("loadSuccessCount", () -> cache.stats().loadSuccessCount(), name, names); metrics.putMetrics("missCount", () -> cache.stats().missCount(), name, names); metrics.putMetrics("missRate", () -> cache.stats().missRate(), name, names); metrics.putMetrics("requestCount", () -> cache.stats().requestCount(), name, names); metrics.putMetrics("totalLoadTime", () -> cache.stats().totalLoadTime(), name, names); <START> return metrics; <END> }</code><technical_language>is choose a dot notation for metrics easier create aggregation rules collector: hitCount -> hit.count hitRate -> hit.rate averageLoadPenalty -> load.penalty.mean load.count, load.exception.count ..</technical_language>

Target:
public static MetricSet of(Cache cache, String name, String... names) { String basicName = MetricRegistry.name(name, names); GuavaCacheMetric metrics = new GuavaCacheMetric(); metrics.putMetrics(() -> cache.stats().averageLoadPenalty(), basicName, "average", "load", "penalty"); metrics.putMetrics(() -> cache.stats().evictionCount(), basicName, "eviction", "count"); metrics.putMetrics(() -> cache.stats().hitCount(), basicName, "hit", "count"); metrics.putMetrics(() -> cache.stats().hitRate(), basicName, "hit", "rate"); metrics.putMetrics(() -> cache.stats().loadCount(), basicName, "load", "count"); metrics.putMetrics(() -> cache.stats().loadExceptionCount(), basicName, "load", "exception", "count"); metrics.putMetrics(() -> cache.stats().loadExceptionRate(), basicName, "load", "exception", "rate"); metrics.putMetrics(() -> cache.stats().loadSuccessCount(), basicName, "load", "success", "count"); metrics.putMetrics(() -> cache.stats().missCount(), basicName, "miss", "count"); metrics.putMetrics(() -> cache.stats().missRate(), basicName, "miss", "rate"); metrics.putMetrics(() -> cache.stats().requestCount(), basicName, "request", "count"); metrics.putMetrics(() -> cache.stats().totalLoadTime(), basicName, "total", "load", "time"); return metrics; }
Source:
<code>private static ITmfStateValue getCpuStatus(ITmfStateSystemBuilder ssb, int cpuQuark) throws AttributeNotFoundException { int irqQuarks = ssb.getQuarkRelativeAndAdd(cpuQuark, Attributes.IRQS); List<Integer> irqs = ssb.getSubAttributes(irqQuarks, false); for (Integer quark : irqs) { final ITmfStateValue irqState = ssb.queryOngoingState(quark.intValue()); if (irqState.equals(StateValues.CPU_STATUS_IRQ_VALUE)) { return irqState; } } int softIrqQuarks = ssb.getQuarkRelativeAndAdd(cpuQuark, Attributes.SOFT_IRQS); List<Integer> softIrqs = ssb.getSubAttributes(softIrqQuarks, false); for (Integer quark : softIrqs) { final ITmfStateValue softIrqState = ssb.queryOngoingState(quark.intValue()); <START> if (softIrqState.equals(StateValues.CPU_STATUS_SOFTIRQ_VALUE)) { <END> return softIrqState; } } int currentThreadQuark = ssb.getQuarkRelativeAndAdd(cpuQuark, Attributes.CURRENT_THREAD); ITmfStateValue currentThreadState = ssb.queryOngoingState(currentThreadQuark); if (currentThreadState.isNull()) { return TmfStateValue.nullValue(); } int tid = currentThreadState.unboxInt(); if (tid == 0) { return StateValues.CPU_STATUS_IDLE_VALUE; } int threadSystemCallQuark = ssb.getQuarkAbsoluteAndAdd(Attributes.THREADS, Integer.toString(tid), Attributes.SYSTEM_CALL); return (ssb.queryOngoingState(threadSystemCallQuark).isNull() ? StateValues.CPU_STATUS_RUN_USERMODE_VALUE : StateValues.CPU_STATUS_RUN_SYSCALL_VALUE); }</code><technical_language>I SOFTIRQ RAISED_RUNNING, in cases want return SOFTIRQ</technical_language>

Target:
private static ITmfStateValue getCpuStatus(ITmfStateSystemBuilder ssb, int cpuQuark) throws AttributeNotFoundException { int irqQuarks = ssb.getQuarkRelativeAndAdd(cpuQuark, Attributes.IRQS); List<Integer> irqs = ssb.getSubAttributes(irqQuarks, false); for (Integer quark : irqs) { final ITmfStateValue irqState = ssb.queryOngoingState(quark.intValue()); if (irqState.equals(StateValues.CPU_STATUS_IRQ_VALUE)) { return irqState; } } int softIrqQuarks = ssb.getQuarkRelativeAndAdd(cpuQuark, Attributes.SOFT_IRQS); List<Integer> softIrqs = ssb.getSubAttributes(softIrqQuarks, false); for (Integer quark : softIrqs) { final ITmfStateValue softIrqState = ssb.queryOngoingState(quark.intValue()); if ( 0 != (softIrqState.unboxInt()&StateValues.CPU_STATUS_SOFTIRQ)) { return softIrqState; } } int currentThreadQuark = ssb.getQuarkRelativeAndAdd(cpuQuark, Attributes.CURRENT_THREAD); ITmfStateValue currentThreadState = ssb.queryOngoingState(currentThreadQuark); if (currentThreadState.isNull()) { return TmfStateValue.nullValue(); } int tid = currentThreadState.unboxInt(); if (tid == 0) { return StateValues.CPU_STATUS_IDLE_VALUE; } int threadSystemCallQuark = ssb.getQuarkAbsoluteAndAdd(Attributes.THREADS, Integer.toString(tid), Attributes.SYSTEM_CALL); return (ssb.queryOngoingState(threadSystemCallQuark).isNull() ? StateValues.CPU_STATUS_RUN_USERMODE_VALUE : StateValues.CPU_STATUS_RUN_SYSCALL_VALUE); }
Source:
<code>private final static double[] parseDeprecatedGLString(String GLString) { if ( !GLString.equals(VCFConstants.MISSING_VALUE_v4) ) { String[] strings = GLString.split(","); double[] likelihoodsAsVector = new double[strings.length]; for ( int i = 0; i < strings.length; i++ ) { if ( strings[i].equals(VCFConstants.MISSING_VALUE_v4) ) { <START> return null; END> } else { likelihoodsAsVector[i] = Double.parseDouble(strings[i]); } } return likelihoodsAsVector; } return null; }</code><technical_language>hmmm. 1,.,2 return a null value? I guess primitive doubles have, to...though NaNs for that. support 4.3...</technical_language>

Target:
private final static double[] parseDeprecatedGLString(String GLString) { if ( !GLString.equals(VCFConstants.MISSING_VALUE_v4) ) { String[] strings = GLString.split(","); double[] likelihoodsAsVector = new double[strings.length]; int missing = 0; for ( int i = 0; i < strings.length; i++ ) { if (strings[i].equals(VCFConstants.MISSING_VALUE_v4)) { missing++; } else { likelihoodsAsVector[i] = Double.parseDouble(strings[i]); } } if (missing == 0) { return likelihoodsAsVector; } else if (likelihoodsAsVector.length == missing) { return null; } else { throw new TribbleException("partial missing values for GL field"); } } return null; }
Source:
<code>public Repository openRepository(Project.NameKey name) throws RepositoryNotFoundException { if (isUnreasonableName(name)) { throw new RepositoryNotFoundException("Invalid name: " + name); } final FileKey loc = FileKey.lenient(gitDirOf(name), FS.DETECTED); if (!getProjectName(loc.getFile()).equals(name)) { System.out.println("getProjectName(loc.getFile()): " + getProjectName(loc.getFile())); System.out.println("loc.getFile() : " + loc.getFile()); <START> System.out.println("name : " + name); <END> throw new RepositoryNotFoundException(gitDirOf(name)); } try { return RepositoryCache.open(loc); } catch (IOException e1) { final RepositoryNotFoundException e2; e2 = new RepositoryNotFoundException("Cannot open repository " + name); e2.initCause(e1); throw e2; } }</code><technical_language>this accidentally included this change</technical_language>

Target:
public Repository openRepository(Project.NameKey name) throws RepositoryNotFoundException { if (isUnreasonableName(name)) { throw new RepositoryNotFoundException("Invalid name: " + name); } final FileKey loc = FileKey.lenient(gitDirOf(name), FS.DETECTED); if (!getProjectName(loc.getFile()).equals(name)) { throw new RepositoryNotFoundException(gitDirOf(name)); } try { return RepositoryCache.open(loc); } catch (IOException e1) { final RepositoryNotFoundException e2; e2 = new RepositoryNotFoundException("Cannot open repository " + name); e2.initCause(e1); throw e2; } }