auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private DBNote getNoteFromCursor(long accountId, @NonNull Cursor cursor, boolean pruneContent) { validateAccountId(accountId); Calendar modified = Calendar.getInstance(); modified.setTimeInMillis(cursor.getLong(4) * 1000); return new DBNote( cursor.getLong(0), cursor.getLong(1), modified, cursor.getString(3), pruneContent ? "" : cursor.getString(9), cursor.getInt(5) > 0, <START> getTitleByCategoryId(accountId, cursor.getInt(6)), <END> cursor.getString(7), DBStatus.parse(cursor.getString(2)), accountId, cursor.getString(8) ); }</code><technical_language>This slow app, executing additional SQL query for note. Currently, I 200 notes showing main Activity requires a single SQL query. this change, 201 SQL queries executed. This is a "no go"! alternatives fix this issue: 1. build a "cache" in memory for categories, i.e. load categories of current account a HashMap creation of e.g. NotesDatabase query this cache in getTitleByCategoryId(...) (and related methods). change of categories (insertion, deletion, edit), update this cache. 2. change SQL query in getNotesCustom(...) add a JOIN categories table. Hint: reduce need for changing code if change column names of categories table: If differ column names in notes table, prepend table name (e.g. CATEGORIES.TITLE, TITLE exists in tables CATEGORIES NOTES). I vote for approach. remove method getTitleByCategoryId(...), then</technical_language>

Target:
private DBNote getNoteFromCursor(long accountId, @NonNull Cursor cursor, boolean pruneContent) { validateAccountId(accountId); Calendar modified = Calendar.getInstance(); modified.setTimeInMillis(cursor.getLong(4) * 1000); return new DBNote( cursor.getLong(0), cursor.getLong(1), modified, cursor.getString(3), pruneContent ? "" : cursor.getString(9), cursor.getInt(5) > 0, cursor.getString(6), cursor.getString(7), DBStatus.parse(cursor.getString(2)), accountId, cursor.getString(8) ); }
Source:
<code>public void testYieldProjection() { int rows = 128; int columns = 20; DriverYieldSignal yieldSignal = new DriverYieldSignal(); PageProcessor pageProcessor = new PageProcessor( Optional.empty(), Collections.nCopies(columns, new YieldPageProjection(new InputPageProjection(0, VARCHAR)))); Slice[] slices = new Slice[rows]; Arrays.fill(slices, Slices.allocate(rows)); Page inputPage = new Page(createSlicesBlock(slices)); AggregatedMemoryContext memoryContext = newSimpleAggregatedMemoryContext(); <START> Iterator<Optional<Page>> output = pageProcessor.process(SESSION, yieldSignal, memoryContext, inputPage); <END> for (int i = 0; i < columns - 1; i++) { assertTrue(output.hasNext()); assertNull(output.next().orElse(null)); assertTrue(yieldSignal.isSet()); yieldSignal.reset(); } assertTrue(output.hasNext()); Page actualPage = output.next().orElse(null); assertNotNull(actualPage); assertTrue(yieldSignal.isSet()); yieldSignal.reset(); Block[] blocks = new Block[columns]; Arrays.fill(blocks, createSlicesBlock(Arrays.copyOfRange(slices, 0, rows))); Page expectedPage = new Page(blocks); assertPageEquals(Collections.nCopies(columns, VARCHAR), actualPage, expectedPage); assertFalse(output.hasNext()); }</code><technical_language>add overload processAndAssertRetainedPageSize for of</technical_language>

Target:
public void testYieldProjection() { int rows = 128; int columns = 20; DriverYieldSignal yieldSignal = new DriverYieldSignal(); PageProcessor pageProcessor = new PageProcessor( Optional.empty(), Collections.nCopies(columns, new YieldPageProjection(new InputPageProjection(0, VARCHAR))), OptionalInt.of(MAX_BATCH_SIZE)); Slice[] slices = new Slice[rows]; Arrays.fill(slices, Slices.allocate(rows)); Page inputPage = new Page(createSlicesBlock(slices)); Iterator<Optional<Page>> output = processAndAssertRetainedPageSize(pageProcessor, yieldSignal, inputPage); for (int i = 0; i < columns - 1; i++) { assertTrue(output.hasNext()); assertNull(output.next().orElse(null)); assertTrue(yieldSignal.isSet()); yieldSignal.reset(); } assertTrue(output.hasNext()); Page actualPage = output.next().orElse(null); assertNotNull(actualPage); assertTrue(yieldSignal.isSet()); yieldSignal.reset(); Block[] blocks = new Block[columns]; Arrays.fill(blocks, createSlicesBlock(Arrays.copyOfRange(slices, 0, rows))); Page expectedPage = new Page(blocks); assertPageEquals(Collections.nCopies(columns, VARCHAR), actualPage, expectedPage); assertFalse(output.hasNext()); }
Source:
<code>public void updatePartitionStatistics(String databaseName, String tableName, String partitionName, Function<PartitionStatistics, PartitionStatistics> update) { PartitionStatistics currentStatistics = requireNonNull(getPartitionStatistics(databaseName, tableName, ImmutableSet.of(partitionName)).get(partitionName), "currentStatistics is null"); PartitionStatistics updatedStatistics = update.apply(currentStatistics); <START> verify(updatedStatistics.getColumnStatistics().isEmpty(), "glue metastore does not support column level statistics"); <END> List<String> partitionValues = toPartitionValues(partitionName); Partition partition = getPartition(databaseName, tableName, partitionValues) .orElseThrow(() -> new PartitionNotFoundException(new SchemaTableName(databaseName, tableName), partitionValues)); try { PartitionInput partitionInput = GlueInputConverter.convertPartition(partition); partitionInput.setParameters(updateStatisticParameters(partition.getParameters(), updatedStatistics.getBasicStatistics())); glueClient.updatePartition(new UpdatePartitionRequest() .withDatabaseName(databaseName) .withTableName(tableName) .withPartitionValueList(partition.getValues()) .withPartitionInput(partitionInput)); } catch (EntityNotFoundException e) { throw new PartitionNotFoundException(new SchemaTableName(databaseName, tableName), partition.getValues()); } catch (AmazonServiceException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }</code><technical_language>Throw NOT_SUPPORTED</technical_language>

Target:
public void updatePartitionStatistics(String databaseName, String tableName, String partitionName, Function<PartitionStatistics, PartitionStatistics> update) { PartitionStatistics currentStatistics = requireNonNull( getPartitionStatistics(databaseName, tableName, ImmutableSet.of(partitionName)).get(partitionName), "getPartitionStatistics() returned null"); PartitionStatistics updatedStatistics = update.apply(currentStatistics); if (!updatedStatistics.getColumnStatistics().isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "glue metastore does not support column level statistics"); } List<String> partitionValues = toPartitionValues(partitionName); Partition partition = getPartition(databaseName, tableName, partitionValues) .orElseThrow(() -> new PartitionNotFoundException(new SchemaTableName(databaseName, tableName), partitionValues)); try { PartitionInput partitionInput = GlueInputConverter.convertPartition(partition); partitionInput.setParameters(updateStatisticParameters(partition.getParameters(), updatedStatistics.getBasicStatistics())); glueClient.updatePartition(new UpdatePartitionRequest() .withDatabaseName(databaseName) .withTableName(tableName) .withPartitionValueList(partition.getValues()) .withPartitionInput(partitionInput)); } catch (EntityNotFoundException e) { throw new PartitionNotFoundException(new SchemaTableName(databaseName, tableName), partitionValues); } catch (AmazonServiceException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }
Source:
<code>public boolean executeAttack(ServerSideAttack serverSideAttack) { this.serverSideAttack = serverSideAttack; try { return this.executeCustomPrivateKeySignedJWTTokenAttack() || this.executeAlgoKeyConfusionAttack() || this.executeNullByteAttack(); } catch (JWTException e) { <START> LOGGER.error("error occurred while getting signed manipulated tokens", e); <END> } return false; }</code><technical_language>suggestion LOGGER.error("An error occurred while signed manipulated tokens", e);</technical_language>

Target:
public boolean executeAttack(ServerSideAttack serverSideAttack) { this.serverSideAttack = serverSideAttack; try { return this.executeCustomPrivateKeySignedJWTTokenAttack() || this.executeAlgoKeyConfusionAttack() || this.executeNullByteAttack(); } catch (JWTException e) { LOGGER.error("An error occurred while getting signed manipulated tokens", e); } return false; }
Source:
<code>protected int doStartTagInternal() throws Exception { pageContext.getOut().append(String.format( "<br/><h1>%2$s</h1><table id='ajaxlist%1$d' class='display no-border ui-widget-content'></table><script type='text/javascript'>jQuery(document).ready(function () { ListUtils.createTable('ajaxlist%1$d', ListTarget.%3$s, null, %4$s);});</script>", <START> uniqueId++, name, target, config)); <END> return SKIP_BODY; }</code><technical_language>thing, in more lines. ID in JSP instead? <miso:list-section-ajax id="statusAjaxlist" name="Order Status" target="completion" config="{ poolId: ${pool.id} }"/></technical_language>

Target:
protected int doStartTagInternal() throws Exception { pageContext.getOut().append(String.format( "<br/><h1>%2$s</h1><table id='%1$s' class='display no-border ui-widget-content'></table><script type='text/javascript'>jQuery(document).ready(function () { ListUtils.createTable('%1$s', ListTarget.%3$s, null, %4$s);});</script>", getId(), name, target, config)); return SKIP_BODY; }
Source:
<code>public static Map<String, Object> getEnvironmentAttributesWithApplicationHostname() { Map<String, Object> attributes = new HashMap<>(); try { if (!TestProperties.TEAMMATES_URL.contains("localhost")) { attributes.put("com.google.appengine.runtime.default_version_hostname", <START> new URL(TestProperties.TEAMMATES_URL).getAuthority().substring(10)); <END> return attributes; } attributes.put("com.google.appengine.runtime.default_version_hostname", new URL(TestProperties.TEAMMATES_URL).getAuthority()); } catch (MalformedURLException e) { throw new RuntimeException(e); } return attributes; }</code><technical_language>10</technical_language>

Target:
public static Map<String, Object> getEnvironmentAttributesWithApplicationHostname() { Map<String, Object> attributes = new HashMap<>(); try { attributes.put("com.google.appengine.runtime.default_version_hostname", new URL(TestProperties.TEAMMATES_URL).getAuthority()); } catch (MalformedURLException e) { throw new RuntimeException(e); } return attributes; }
Source:
<code>public void remove(Session session) { this.removeSuper(session); try { store.remove(session.getId()); } catch (IOException e) { <START> log.error("An error occurred while removing session" + e.getMessage()); <END> } }</code><technical_language>output session id in message aid debugging. Also, I this form log.error("An error occurred while removing session", e);</technical_language>

Target:
public void remove(Session session) { this.removeSuper(session); try { store.remove(session.getId()); } catch (IOException e) { log.error("An error occurred while removing session with id: " + session.getId(), e); } }
Source:
<code>public void testMetricSystemRestart() { MetricsSystemImpl ms = new MetricsSystemImpl("msRestartTestSystem"); TestSink ts = new TestSink(); String sinkName = "restartTestSink"; try { ms.start(); ms.register(sinkName, "", ts); <START> assertNotNull("an adapter should exist for each sink", ms.getSinkAdapter(sinkName)); <END> ms.stop(); ms.start(); assertNotNull("an adapter should exist for each sink", ms.getSinkAdapter(sinkName)); } finally { ms.stop(); } }</code><technical_language>generally 80 chars wide, afraid...put actual probe a new line. nice some text for assertion tnough -appreciated</technical_language>

Target:
public void testMetricSystemRestart() { MetricsSystemImpl ms = new MetricsSystemImpl("msRestartTestSystem"); TestSink ts = new TestSink(); String sinkName = "restartTestSink"; try { ms.start(); ms.register(sinkName, "", ts); assertNotNull("no adapter exists for " + sinkName, ms.getSinkAdapter(sinkName)); ms.stop(); ms.start(); assertNotNull("no adapter exists for " + sinkName, ms.getSinkAdapter(sinkName)); } finally { ms.stop(); } }
Source:
<code>public synchronized boolean waitForState(Processor processor, int state) { processor.addControllerListener(this); setFailed(false); if (state == Processor.Configured) processor.configure(); else if (state == Processor.Realized) processor.realize(); boolean interrupted = false; Object stateLock = getStateLock(); synchronized (stateLock) { while ((processor.getState() < state) && !failed) { try { stateLock.wait(10000); if (processor.getState() < state) { <START> setFailed(true); <END> } } catch (InterruptedException ie) { logger.warn( "Interrupted while waiting on Processor " + processor + " for state " + state, ie); interrupted = true; } } } if (interrupted) Thread.currentThread().interrupt(); processor.removeControllerListener(this); return !failed; }</code><technical_language>If Processor passes intermediary state 10s elapse, trigger a failure here. I execute this if waited for a period (e.g. 10s)</technical_language>

Target:
public synchronized boolean waitForState(Processor processor, int state) { processor.addControllerListener(this); setFailed(false); if (state == Processor.Configured) processor.configure(); else if (state == Processor.Realized) processor.realize(); boolean interrupted = false; Object stateLock = getStateLock(); synchronized (stateLock) { while ((processor.getState() < state) && !failed) { try { Instant startTime = Instant.now(); stateLock.wait(WAIT_TIMEOUT*1000); if (Duration.between(startTime, Instant.now()) .getSeconds() >= WAIT_TIMEOUT) { setFailed(true); } } catch (InterruptedException ie) { logger.warn( "Interrupted while waiting on Processor " + processor + " for state " + state, ie); interrupted = true; } } } if (interrupted) Thread.currentThread().interrupt(); processor.removeControllerListener(this); return !failed; }
Source:
<code>public void testPartialPerTypeStatsCancel() throws TmfAnalysisException { StubSegmentStatisticsAnalysis fixture = getValidSegmentStats(); NullProgressMonitor monitor = new NullProgressMonitor(); monitor.setCanceled(true); Map<@NonNull String, @NonNull SegmentStoreStatistics> perTypeStats = <START> fixture.getPerSegmentTypeStatsForRange(100, 1100, monitor); <END> assertNull(perTypeStats); }</code><technical_language>test succeed if replace this fixture.getPerSegmentTypeStatsForRange(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); fails actually. I think, failure avoid testing monitor testing range in AbstractSegmentStatisticsAnalysis.getPerSegmentTypeStatsForRange() AbstractSegmentStatisticsAnalysis.getTotalStatsForRange()</technical_language>

Target:
public void testPartialPerTypeStatsCancel() throws TmfAnalysisException { StubSegmentStatisticsAnalysis fixture = getValidSegmentStats(); NullProgressMonitor monitor = new NullProgressMonitor(); monitor.setCanceled(true); Map<@NonNull String, @NonNull SegmentStoreStatistics> perTypeStats = fixture.getPerSegmentTypeStatsForRange(100, 1100, monitor); assertNull(perTypeStats); perTypeStats = fixture.getPerSegmentTypeStatsForRange(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); assertNotNull(perTypeStats); }
Source:
<code>public WALPrettyPrinter() { outputValues = false; outputJSON = false; sequence = -1; <START> tableList = new HashSet<>(); <END> region = null; row = null; outputOnlyRowKey = false; persistentOutput = false; firstTxn = true; out = System.out; }</code><technical_language>Is HashSet needed here? this a simple ArrayList</technical_language>

Target:
public WALPrettyPrinter() { outputValues = false; outputJSON = false; sequence = -1; tableSet = new HashSet<>(); region = null; row = null; outputOnlyRowKey = false; persistentOutput = false; firstTxn = true; out = System.out; }
Source:
<code>private boolean canReadFrom(Job<?, ?> job, Run<?, ?> build) { if ((job instanceof AbstractProject) && (build instanceof AbstractBuild) && CopyArtifactPermissionProperty.canCopyArtifact( ((AbstractBuild)build).getProject().getRootProject(), <START> ((AbstractProject<?,?>)job).getRootProject() <END> )) { return true; } Authentication a = Jenkins.getAuthentication(); if (!ACL.SYSTEM.equals(a)) { boolean b = job.getACL().hasPermission(Item.READ); if (!b) LOGGER.fine(String.format("Refusing to copy artifact from %s to %s because %s lacks Item.READ access",job,build, a)); return b; } boolean b = job.getACL().hasPermission( new UsernamePasswordAuthenticationToken("authenticated", "", new GrantedAuthority[]{ SecurityRealm.AUTHENTICATED_AUTHORITY }), Item.READ); if (!b) LOGGER.fine(String.format("Refusing to copy artifact from %s to %s because 'authenticated' lacks Item.READ access",job,build)); return b; }</code><technical_language>want do canCopyArtifact check non-AbstractBuilds, do need call getRootProject</technical_language>

Target:
private boolean canReadFrom(Job<?, ?> job, Run<?, ?> build) { Job<?, ?> fromJob = job; Job<?, ?> toJob = build.getParent(); if (CopyArtifactPermissionProperty.canCopyArtifact(getRootProject(toJob), getRootProject(fromJob))) { return true; } Authentication a = Jenkins.getAuthentication(); if (!ACL.SYSTEM.equals(a)) { boolean b = job.getACL().hasPermission(Item.READ); if (!b) LOGGER.fine(String.format("Refusing to copy artifact from %s to %s because %s lacks Item.READ access",job,build, a)); return b; } boolean b = job.getACL().hasPermission( new UsernamePasswordAuthenticationToken("authenticated", "", new GrantedAuthority[]{ SecurityRealm.AUTHENTICATED_AUTHORITY }), Item.READ); if (!b) LOGGER.fine(String.format("Refusing to copy artifact from %s to %s because 'authenticated' lacks Item.READ access",job,build)); return b; }
Source:
<code>protected LoadCreator(PerfConfig perfConfig, PerfNioServerMetrics perfNioServerMetrics, RestRequestHandler restRequestHandler) { this.perfConfig = perfConfig; this.perfNioServerMetrics = perfNioServerMetrics; this.restRequestHandler = restRequestHandler; chunk = new byte[perfConfig.perfNioServerChunkSize]; <START> byte[] um = new byte[perfConfig.perfUserMetadataSize]; <END> Random random = new Random(); random.nextBytes(chunk); random.nextBytes(um); usermetadata = new String(um); slots = new LinkedBlockingQueue<Boolean>(perfConfig.perfNioServerConcurrency); logger.trace("Instantiated LoadCreator"); }</code><technical_language>um umBytes userMetadataBytes</technical_language>

Target:
protected LoadCreator(PerfConfig perfConfig, PerfNioServerMetrics perfNioServerMetrics, RestRequestHandler restRequestHandler) { this.perfConfig = perfConfig; this.perfNioServerMetrics = perfNioServerMetrics; this.restRequestHandler = restRequestHandler; chunk = new byte[perfConfig.perfNioServerChunkSize]; byte[] umBytes = new byte[perfConfig.perfUserMetadataSize]; Random random = new Random(); random.nextBytes(chunk); random.nextBytes(umBytes); usermetadata = new String(umBytes); slots = new LinkedBlockingQueue<Boolean>(perfConfig.perfNioServerConcurrency); logger.trace("Instantiated LoadCreator"); }
Source:
<code>void testCommand() { Category category = TestUtilities.getCategory(plugin, "rechargeable"); final SlimefunItemStack RECHARGEABLE_ITEM = new SlimefunItemStack("RECHARGEABLE_ITEM", Material.REDSTONE_BLOCK, "Rechargeable Item", "This isn't real", LoreBuilder.powerCharged(0, 100)); new RechargeableMock(category, RECHARGEABLE_ITEM, RecipeType.NULL, new ItemStack[9]).register(plugin); Player player = server.addPlayer(); player.setOp(true); player.getInventory().setItemInMainHand(RECHARGEABLE_ITEM.clone()); server.execute("slimefun", player, "charge"); ItemStack chargedItemStack = player.getInventory().getItemInMainHand(); Rechargeable chargedItem = (Rechargeable) SlimefunItem.getByItem(chargedItemStack); <START> Assertions.assertEquals(chargedItem.getItemCharge(chargedItemStack), chargedItem.getMaxItemCharge(chargedItemStack)); <END> }</code><technical_language>assert ground condition, charge 0 executing command. This this update</technical_language>

Target:
void testCommand() { Category category = TestUtilities.getCategory(plugin, "rechargeable"); SlimefunItemStack RECHARGEABLE_ITEM = new SlimefunItemStack("SF_CHARGE_TEST_ITEM", Material.REDSTONE_BLOCK, "Rechargeable Item", "This isn't real", LoreBuilder.powerCharged(0, 100)); new RechargeableMock(category, RECHARGEABLE_ITEM, RecipeType.NULL, new ItemStack[9]).register(plugin); Player player = server.addPlayer(); player.setOp(true); player.getInventory().setItemInMainHand(RECHARGEABLE_ITEM.clone()); ItemStack chargedItemStack = player.getInventory().getItemInMainHand(); Rechargeable chargedItem = (Rechargeable) SlimefunItem.getByItem(chargedItemStack); Assertions.assertEquals(chargedItem.getItemCharge(chargedItemStack), 0); server.execute("slimefun", player, "charge"); chargedItemStack = player.getInventory().getItemInMainHand(); chargedItem = (Rechargeable) SlimefunItem.getByItem(chargedItemStack); Assertions.assertEquals(chargedItem.getItemCharge(chargedItemStack), chargedItem.getMaxItemCharge(chargedItemStack)); }
Source:
<code>private Criterion getCriterionForLongName(String name, boolean includeVoided) { MatchMode matchMode = getMatchMode(); if (includeVoided) { return Restrictions.disjunction().add(Restrictions.like("name.givenName", name, matchMode)).add( Restrictions.like("name.middleName", name, matchMode)).add( Restrictions.like("name.familyName", name, matchMode)).add( Restrictions.like("name.familyName2", name, matchMode)); } else { return Restrictions.conjunction().add(Restrictions.eq("name.voided", false)).add( <START> Restrictions.disjunction().add(Restrictions.like("name.givenName", name, matchMode)).add( <END> Restrictions.like("name.middleName", name, matchMode)).add( Restrictions.like("name.familyName", name, matchMode)).add( Restrictions.like("name.familyName2", name, matchMode))); } }</code><technical_language>Repeats above. Eliminate duplication</technical_language>

Target:
private Criterion getCriterionForLongName(String name, boolean includeVoided) { MatchMode matchMode = getMatchMode(); Criterion criterion = Restrictions.disjunction().add(Restrictions.like("name.givenName", name, matchMode)).add( Restrictions.like("name.middleName", name, matchMode)) .add(Restrictions.like("name.familyName", name, matchMode)).add( Restrictions.like("name.familyName2", name, matchMode)); if (!includeVoided) { return Restrictions.conjunction().add(Restrictions.eq("name.voided", false)).add(criterion); } return criterion; }
Source:
<code>private void printPrincipalRecord(ExtMap extMap) { logger.info("============================== Principal ==============================="); if (extMap != null) { <START> logger.info( <END> String.format( "PrincipalRecord: ID '%s', name: '%s', principal: '%s', namespace: '%s', display name: '%s', email: '%s', first name: '%s', last name: '%s', department: '%s', title: '%s'", extMap.get(Authz.PrincipalRecord.ID, ""), extMap.get(Authz.PrincipalRecord.NAME, ""), extMap.get(Authz.PrincipalRecord.PRINCIPAL, ""), extMap.get(Authz.PrincipalRecord.NAMESPACE, ""), extMap.get(Authz.PrincipalRecord.DISPLAY_NAME, ""), extMap.get(Authz.PrincipalRecord.EMAIL, ""), extMap.get(Authz.PrincipalRecord.FIRST_NAME, ""), extMap.get(Authz.PrincipalRecord.LAST_NAME, ""), extMap.get(Authz.PrincipalRecord.DEPARTMENT, ""), extMap.get(Authz.PrincipalRecord.TITLE, "") ) ); if(getFlags() != 0) { logger.info("Groups of PrincipalRecord"); for (ExtMap group : extMap.get(Authz.PrincipalRecord.GROUPS, Collections.<ExtMap>emptyList())) { printGroupRecord(group); } logger.info("End of groups of PrincipalRecord"); } } logger.info("========================================================================"); }</code><technical_language>please {}</technical_language>

Target:
private void printPrincipalRecord(ExtMap extMap) { if (extMap != null) { log.info("============================== Principal ==============================="); log.info( "PrincipalRecord: ID '{}', name: '{}', principal: '{}', namespace: '{}', display name: '{}', email: '{}', first name: '{}', last name: '{}', department: '{}', title: '{}'", extMap.get(Authz.PrincipalRecord.ID, ""), extMap.get(Authz.PrincipalRecord.NAME, ""), extMap.get(Authz.PrincipalRecord.PRINCIPAL, ""), extMap.get(Authz.PrincipalRecord.NAMESPACE, ""), extMap.get(Authz.PrincipalRecord.DISPLAY_NAME, ""), extMap.get(Authz.PrincipalRecord.EMAIL, ""), extMap.get(Authz.PrincipalRecord.FIRST_NAME, ""), extMap.get(Authz.PrincipalRecord.LAST_NAME, ""), extMap.get(Authz.PrincipalRecord.DEPARTMENT, ""), extMap.get(Authz.PrincipalRecord.TITLE, "") ); log.info("Groups of PrincipalRecord"); flatGroups(extMap); log.info("End of groups of PrincipalRecord"); log.info("========================================================================"); } }
Source:
<code>public List<Container> getContainers() throws UnrecoverableKeyException, CertificateEncodingException, NoSuchAlgorithmException, KeyStoreException, IOException { if(!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) { LOGGER.log(Level.FINE, " Computer {0} getContainers, lack of admin permission, returning empty list", this); <START> return new ArrayList<>(); <END> } KubernetesSlave slave = getNode(); if(slave == null) { return new ArrayList<>(); } KubernetesCloud cloud = slave.getKubernetesCloud(); KubernetesClient client = cloud.connect(); String namespace = StringUtils.defaultIfBlank(slave.getNamespace(), client.getNamespace()); Pod pod = client.pods().inNamespace(namespace).withName(getName()).get(); return pod.getSpec().getContainers(); }</code><technical_language>Collections.emptyList() avoid new objects</technical_language>

Target:
public List<Container> getContainers() throws UnrecoverableKeyException, CertificateEncodingException, NoSuchAlgorithmException, KeyStoreException, IOException { if(!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) { LOGGER.log(Level.FINE, " Computer {0} getContainers, lack of admin permission, returning empty list", this); return Collections.emptyList(); } KubernetesSlave slave = getNode(); if(slave == null) { return Collections.emptyList(); } KubernetesCloud cloud = slave.getKubernetesCloud(); KubernetesClient client = cloud.connect(); String namespace = StringUtils.defaultIfBlank(slave.getNamespace(), client.getNamespace()); Pod pod = client.pods().inNamespace(namespace).withName(getName()).get(); return pod.getSpec().getContainers(); }
Source:
<code>public String createTaskInStory(@PathParam("projectName") String projectName, @PathParam("storyId") long storyId, @QueryParam("username") String username, @QueryParam("password") String password, String taskJson) { InformationDecoder decoder = new InformationDecoder(); <START> String newtaskId = ""; <END> try { decoder.decode(username, password); decoder.decodeProjectName(projectName); mTaskWebService = new TaskWebService(decoder.getDecodeUserName(), decoder.getDecodePwd(), decoder.getDecodeProjectName()); newtaskId = mTaskWebService.createTaskInStory(storyId, taskJson); } catch (IOException e) { System.out .println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "api:InformationDecoder, " + "exception: " + e.toString()); e.printStackTrace(); } catch (LogonException e) { System.out.println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "exception: " + e.toString()); e.printStackTrace(); } catch (JSONException e) { System.out.println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "exception: " + e.toString()); e.printStackTrace(); } return newtaskId; }</code><technical_language>newTaskId is OK</technical_language>

Target:
public String createTaskInStory(@PathParam("projectName") String projectName, @PathParam("storyId") long storyId, @QueryParam("username") String username, @QueryParam("password") String password, String taskJson) { InformationDecoder decoder = new InformationDecoder(); String newTaskId = ""; try { decoder.decode(username, password); decoder.decodeProjectName(projectName); mTaskWebService = new TaskWebService(decoder.getDecodeUsername(), decoder.getDecodePwd(), decoder.getDecodeProjectName()); newTaskId = mTaskWebService.createTaskInStory(storyId, taskJson); } catch (IOException e) { System.out .println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "api:InformationDecoder, " + "exception: " + e.toString()); e.printStackTrace(); } catch (LogonException e) { System.out.println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "exception: " + e.toString()); e.printStackTrace(); } catch (JSONException e) { System.out.println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "exception: " + e.toString()); e.printStackTrace(); } return newTaskId; }
Source:
<code>public void placeNewOrder(Market currentMarket, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { if (price > cashInHand) { throw new StockMarketExpection( "Stock price is larger than cash in hand."); } <START> if (orderType == OrderType.BUY) { if (OrderUtility.isAlreadyPresent(ordersPlaced, new BuyOrder( symbol, volume, price, this))) throw new StockMarketExpection( "Trader is trying to place two orders for the same stock."); } else { if (OrderUtility.isAlreadyPresent(ordersPlaced, new SellOrder( symbol, volume, price, this))) throw new StockMarketExpection( "Trader is trying to place two orders for the same stock."); } if (orderType == OrderType.SELL) { boolean ownsStock = false; for (int i = 0; i < position.size(); i++) { if (position.get(i).getSymbol().equals(symbol)) ownsStock = true; } if (!ownsStock) throw new StockMarketExpection( "Trader is trying to sell a stock that he doesn't own."); } <END> if (orderType == OrderType.BUY) { Order newOrder = new BuyOrder(symbol, volume, price, this); position.add(new Stock("", newOrder.getStockSymbol(), price)); ordersPlaced.add(newOrder); currentMarket.addOrder(newOrder); } else { Order newOrder = new SellOrder(symbol, volume, price, this); position.add(new Stock("", newOrder.getStockSymbol(), price)); ordersPlaced.add(newOrder); currentMarket.addOrder(newOrder); } }</code><technical_language>done in if-else loop</technical_language>

Target:
public void placeNewOrder(Market currentMarket, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { if (price > cashInHand) { throw new StockMarketExpection( "Stock price is larger than cash in hand."); } if (orderType == OrderType.BUY) { if (OrderUtility.isAlreadyPresent(ordersPlaced, new BuyOrder( symbol, volume, price, this))) throw new StockMarketExpection( "Trader is trying to place two orders for the same stock."); Order newOrder = new BuyOrder(symbol, volume, price, this); position.add(new Stock("", newOrder.getStockSymbol(), price)); ordersPlaced.add(newOrder); currentMarket.addOrder(newOrder); } else { if (OrderUtility.isAlreadyPresent(ordersPlaced, new SellOrder( symbol, volume, price, this))) throw new StockMarketExpection( "Trader is trying to place two orders for the same stock."); boolean ownsStock = false; for (int i = 0; i < position.size(); i++) { if (position.get(i).getSymbol().equals(symbol)) ownsStock = true; } if (!ownsStock) throw new StockMarketExpection( "Trader is trying to sell a stock that he doesn't own."); } }
Source:
<code>protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { <START> Matcher matcher = GET_JOB_EXECUTION_INFO_PATTERN.matcher(req.getRequestURI()); if(matcher.matches()) { <END> String executionId = matcher.group(1); String jobDefinitionId = matcher.group(3); logger.info("Getting execution details of job in execution {}.", jobDefinitionId, executionId); Optional<JobExecution> jobExecution; try { jobExecution = executorService.getJobExecution(executionId, jobDefinitionId, session.getUser().getUserId()); } catch (CloudFlowException e) { sendErrorResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DEFAULT_500_ERROR_MESSAGE); return; } if(jobExecution.isPresent()) { sendResponse(resp, HttpServletResponse.SC_OK, toJsonMap(jobExecution.get())); } else { sendErrorResponse(resp, HttpServletResponse.SC_NOT_FOUND, String.format("Execution %s not found or doesn't have job with id %s.", executionId, jobDefinitionId)); } return; } }</code><technical_language>a strictly defined regex limited in ability specific part of request path failed validation. Recommend method UriTemplate::match() give template variables a path define a explicit regex</technical_language>

Target:
protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { Map<String, String> templateVariableToValue = new HashMap<>(); if (GET_JOB_EXECUTION_INFO_URI.match(req.getRequestURI(), templateVariableToValue)) { final String executionId = templateVariableToValue.get("executionId"); final String jobDefinitionId = templateVariableToValue.get("jobDefinitionId"); try { Integer.parseInt(executionId); Integer.parseInt(jobDefinitionId); } catch (NumberFormatException e) { sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid execution id" + " or job definition id."); return; } logger.info("Getting execution details of job in execution {}.", jobDefinitionId, executionId); JobExecution jobExecution; try { jobExecution = executorService.getJobExecution(executionId, templateVariableToValue.get( "jobPath"), session.getUser().getUserId()); } catch (CloudFlowNotFoundException e) { sendErrorResponse(resp, HttpServletResponse.SC_NOT_FOUND, e.getMessage()); return; } catch (CloudFlowException e) { sendErrorResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DEFAULT_500_ERROR_MESSAGE); return; } sendResponse(resp, HttpServletResponse.SC_OK, toJsonMap(jobExecution)); return; } }
Source:
<code>public boolean processMessage(Message msg) { if (super.processMessage(msg) == HANDLED) { return HANDLED; } switch (msg.what) { case CONNECT_WIRED_HEADSET: sendInternalMessage(SWITCH_HEADSET); return HANDLED; case CONNECT_BLUETOOTH: if (!mHasUserExplicitlyLeftBluetooth) { sendInternalMessage(SWITCH_BLUETOOTH); } else { Log.i(this, "Not switching to BT route from speaker because user has " + "explicitly disconnected."); updateSystemAudioState(); } return HANDLED; case DISCONNECT_BLUETOOTH: updateSystemAudioState(); return HANDLED; case DISCONNECT_WIRED_HEADSET: updateSystemAudioState(); return HANDLED; case BT_AUDIO_DISCONNECT: return HANDLED; case CONNECT_DOCK: return HANDLED; case DISCONNECT_DOCK: <START> if (!mCallsManager.hasVideoCall()) { <END> sendInternalMessage(SWITCH_BASELINE_ROUTE); } return HANDLED; default: return NOT_HANDLED; } }</code><technical_language>this check in calculateBaselineRouteMessage, speakerphone route is baseline for video calls. Also, synchronize mLock calling hasVideoCall() -- CallAudioRouteStateMachine operates a separate thread, unsynchronized access CallsManager a ConcurrentModificationException thrown if list of calls is modified while this method is looping it</technical_language>

Target:
public boolean processMessage(Message msg) { if (super.processMessage(msg) == HANDLED) { return HANDLED; } switch (msg.what) { case CONNECT_WIRED_HEADSET: sendInternalMessage(SWITCH_HEADSET); return HANDLED; case CONNECT_BLUETOOTH: if (!mHasUserExplicitlyLeftBluetooth) { sendInternalMessage(SWITCH_BLUETOOTH); } else { Log.i(this, "Not switching to BT route from speaker because user has " + "explicitly disconnected."); updateSystemAudioState(); } return HANDLED; case DISCONNECT_BLUETOOTH: updateSystemAudioState(); return HANDLED; case DISCONNECT_WIRED_HEADSET: updateSystemAudioState(); return HANDLED; case BT_AUDIO_DISCONNECT: return HANDLED; case CONNECT_DOCK: return HANDLED; case DISCONNECT_DOCK: sendInternalMessage(SWITCH_BASELINE_ROUTE); return HANDLED; default: return NOT_HANDLED; } }
Source:
<code>private List<ModuleConfig> deserializeModules(JsonObject configJson) { <START> List<ModuleConfig> modules = new ArrayList<>(); <END> JsonArray modulesFromJson = configJson.get("modules") == null ? null : configJson.get("modules").getAsJsonArray(); if (modulesFromJson != null) { for (JsonElement jsonElement : modulesFromJson) { modules.add(deserializeModule(jsonElement)); } } return modules; }</code><technical_language>In this case define modules variable JsonArray modulesFromJson this able create modules list instance defined size new ArrayList<>(modulesFromJson.size);</technical_language>

Target:
private List<ModuleConfig> deserializeModules(JsonObject configJson) { JsonArray modulesFromJson = configJson.get("modules") == null ? null : configJson.get("modules").getAsJsonArray(); if (modulesFromJson == null) { return Collections.emptyList(); } List<ModuleConfig> modules = new ArrayList<>(modulesFromJson.size()); for (JsonElement jsonElement : modulesFromJson) { modules.add(deserializeModule(jsonElement)); } return modules; }
Source:
<code>public synchronized void notifyBarrierReceived(CheckpointBarrier barrier, InputChannelInfo channelInfo) throws IOException { long barrierId = barrier.getId(); <START> int channelIndex = handler.getFlattenedChannelIndex(channelInfo); <END> LOG.error("{}: Received barrier from channel ({}) @ {}.", handler.taskName, channelIndex, storeNewBuffers[channelIndex], barrierId); if (currentReceivedCheckpointId < barrierId) { handleNewCheckpoint(barrier); handler.executeInTaskThread(() -> handler.notifyCheckpoint(barrier), "notifyCheckpoint"); } if (barrierId == currentReceivedCheckpointId && storeNewBuffers[channelIndex]) { storeNewBuffers[channelIndex] = false; if (++numBarriersReceived == numOpenChannels) { allBarriersReceivedFuture.complete(null); } } }</code><technical_language>irrelevant changes cleanup</technical_language>

Target:
public synchronized void notifyBarrierReceived(CheckpointBarrier barrier, InputChannelInfo channelInfo) throws IOException { long barrierId = barrier.getId(); if (currentReceivedCheckpointId < barrierId) { handleNewCheckpoint(barrier); handler.executeInTaskThread(() -> handler.notifyCheckpoint(barrier), "notifyCheckpoint"); } int channelIndex = handler.getFlattenedChannelIndex(channelInfo); if (barrierId == currentReceivedCheckpointId && storeNewBuffers[channelIndex]) { if (LOG.isDebugEnabled()) { LOG.debug("{}: Received barrier from channel @ {}.", handler.taskName, channelIndex, barrierId); } storeNewBuffers[channelIndex] = false; if (++numBarriersReceived == numOpenChannels) { allBarriersReceivedFuture.complete(null); } } }
Source:
<code>protected QueryKeys<FeedbackResponseComment> getEntityQueryKeys(FeedbackResponseCommentAttributes attributes) { Long id = attributes.getId(); if (id != null) { return getEntityQueryKeys(id); } return load() .filter("courseId =", attributes.courseId) <START> .filter("feedbackResponseId =", attributes.feedbackResponseId) <END> .filter("createdAt =", TimeHelper.convertInstantToDate(attributes.createdAt)) .filter("giverEmail =", attributes.commentGiver) .keys(); }</code><technical_language>change is for</technical_language>

Target:
protected QueryKeys<FeedbackResponseComment> getEntityQueryKeys(FeedbackResponseCommentAttributes attributes) { Long id = attributes.getId(); if (id != null) { return getEntityQueryKeys(id); } return load() .filter("feedbackResponseId =", attributes.feedbackResponseId) .filter("createdAt =", TimeHelper.convertInstantToDate(attributes.createdAt)) .filter("giverEmail =", attributes.commentGiver) .keys(); }
Source:
<code><START> public void goToweb (View view) { String url = "<LINK_0>"; link(url); <END> }</code><technical_language>"@OnClick" butterknife instead (look for other existing fragments activities for reference ClientDetailsFragment). Change this for other function</technical_language>

Target:
public void goToweb (View view) { link("<LINK_0>"); }
Source:
<code>public InputStreamWithHints openNextWithHints() throws IOException { if (!iterator.hasNext()) { return null; } <START> String key = iterator.next(); <END> final GetObjectRequest request = new GetObjectRequest(bucket, key); S3Object object = new DefaultRetryable<S3Object>(format("Getting object '%s'", request.getKey())) { @Override public S3Object call() { return client.getObject(request); } }.executeWithCheckedException(retryExec, IOException.class); long objectSize = object.getObjectMetadata().getContentLength(); InputStream inputStream = new ResumableInputStream(object.getObjectContent(), new S3InputStreamReopener(client, request, objectSize, retryExec)); return new InputStreamWithHints(inputStream, String.format("s3://%s/%s", bucket, key)); }</code><technical_language>reason remove final</technical_language>

Target:
public InputStreamWithHints openNextWithHints() throws IOException { if (!iterator.hasNext()) { return null; } final String key = iterator.next(); final GetObjectRequest request = new GetObjectRequest(bucket, key); S3Object object = new DefaultRetryable<S3Object>(format("Getting object '%s'", request.getKey())) { @Override public S3Object call() { return client.getObject(request); } }.executeWithCheckedException(retryExec, IOException.class); long objectSize = object.getObjectMetadata().getContentLength(); InputStream inputStream = new ResumableInputStream(object.getObjectContent(), new S3InputStreamReopener(client, request, objectSize, retryExec)); return new InputStreamWithHints(inputStream, String.format("s3://%s/%s", bucket, key)); }
Source:
<code>public HuobiDepthResult( @JsonProperty("status") String status, @JsonProperty("ts") Date ts, @JsonProperty("tick") HuobiDepth tick, @JsonProperty("ch") String ch, @JsonProperty("err-code") String errCode, @JsonProperty("err-msg") String errMsg) { super(status, errCode, errMsg, tick); this.ts = ts; this.ch = ch; <START> getResult().setTs(ts); <END> }</code><technical_language>this is odd, DTO object represent exchanges response do premature mapping data coping logic</technical_language>

Target:
public HuobiDepthResult( @JsonProperty("status") String status, @JsonProperty("ts") Date ts, @JsonProperty("tick") HuobiDepth tick, @JsonProperty("ch") String ch, @JsonProperty("err-code") String errCode, @JsonProperty("err-msg") String errMsg) { super(status, errCode, errMsg, tick); }
Source:
<code>public PropertyManager reload() { try { <START> putProperty(PROPMGR_DEVICE_ID, SCHEME_IMEI, deviceDetailsProvider.getDeviceId()); <END> putProperty(PROPMGR_PHONE_NUMBER, SCHEME_TEL, deviceDetailsProvider.getLine1Number()); } catch (SecurityException e) { Timber.e(e); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); initUserDefined(prefs, KEY_METADATA_USERNAME, PROPMGR_USERNAME, SCHEME_USERNAME); initUserDefined(prefs, KEY_METADATA_PHONENUMBER, PROPMGR_PHONE_NUMBER, SCHEME_TEL); initUserDefined(prefs, KEY_METADATA_EMAIL, PROPMGR_EMAIL, SCHEME_MAILTO); if (getSingularProperty(PROPMGR_USERNAME) == null || getSingularProperty(PROPMGR_USERNAME).isEmpty()) { putProperty(PROPMGR_USERNAME, SCHEME_USERNAME, (String) GeneralSharedPreferences.getInstance().get(KEY_USERNAME)); } return this; }</code><technical_language>effect SCHEME_IMEI have? collect, maybe</technical_language>

Target:
public PropertyManager reload() { try { putProperty(PROPMGR_DEVICE_ID, "", deviceDetailsProvider.getDeviceId()); putProperty(PROPMGR_PHONE_NUMBER, SCHEME_TEL, deviceDetailsProvider.getLine1Number()); } catch (SecurityException e) { Timber.e(e); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); initUserDefined(prefs, KEY_METADATA_USERNAME, PROPMGR_USERNAME, SCHEME_USERNAME); initUserDefined(prefs, KEY_METADATA_PHONENUMBER, PROPMGR_PHONE_NUMBER, SCHEME_TEL); initUserDefined(prefs, KEY_METADATA_EMAIL, PROPMGR_EMAIL, SCHEME_MAILTO); if (getSingularProperty(PROPMGR_USERNAME) == null || getSingularProperty(PROPMGR_USERNAME).isEmpty()) { putProperty(PROPMGR_USERNAME, SCHEME_USERNAME, (String) GeneralSharedPreferences.getInstance().get(KEY_USERNAME)); } return this; }
Source:
<code>public InputStream getInputStream() { <START> if (logToFile || logToStderr) { <END> inputStream = new FilterInputStream(provider.getInputStream()) { @Override public int read(byte[] b, int off, int len) throws IOException { int bytes = super.read(b, off, len); byte[] payload = new byte[bytes]; System.arraycopy(b, off, payload, 0, bytes); if (logToStderr) { System.err.println(id + " to LSP4E:" + new String(payload)); } if (logToFile) { log("\n" + id + " to LSP4E:" + new String(payload)); } return bytes; } }; } else { inputStream = provider.getInputStream(); } return inputStream; }</code><technical_language>"shouldLog" is checked instantiation in LanguageServerWrapper, I clearer if remove assume instance of this class automatically create proxy streams</technical_language>

Target:
public InputStream getInputStream() { inputStream = provider.getInputStream(); if (inputStream != null) { inputStream = new FilterInputStream(inputStream) { @Override public int read(byte[] b, int off, int len) throws IOException { int bytes = super.read(b, off, len); byte[] payload = new byte[bytes]; System.arraycopy(b, off, payload, 0, bytes); if (logToStderr) { System.err.println(id + " to LSP4E:" + new String(payload)); } if (logToFile) { log("\n" + id + " to LSP4E:" + new String(payload)); } return bytes; } }; } return inputStream; }
Source:
<code>public Exercise call() throws Exception { logger.info("Checking adaptive exercises availability"); Exercise exercise = tmcServerCommunicationTaskFactory.getAdaptiveExercise().call(); if (exercise == null) { return null; } try { exercise.setCourseName(TmcSettingsHolder.get().getCurrentCourse().get().getName()); } catch (Exception e) { exercise.setCourseName("None"); <START> } <END> exercise.setReturnable(true); exercise.setAdaptive(true); byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call(); Progress progress = new Progress(1); extractProject(zipb, exercise, progress); return exercise; }</code><technical_language>log this</technical_language>

Target:
public Exercise call() throws Exception { logger.info("Checking adaptive exercises availability"); Exercise exercise = tmcServerCommunicationTaskFactory.getAdaptiveExercise().call(); if (exercise == null) { return null; } try { exercise.setCourseName(TmcSettingsHolder.get().getCurrentCourse().get().getName()); } catch (Exception e) { logger.warn("Setting course name failed, setting it to 'None'.", e); exercise.setCourseName("None"); } exercise.setReturnable(true); exercise.setAdaptive(true); byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call(); Progress progress = new Progress(1); extractProject(zipb, exercise, progress); return exercise; }
Source:
<code>public JSONObject generatePayload(String fileUrl, String password, String fileLocation) { JSONObject payload = new JSONObject(); try { <START> payload.put("fileURL", fileUrl); <END> payload.put("ftpPassword", password); payload.put("fileLocation", fileLocation); } catch (JSONException e) { Log.e(TAG, "JSON Exception in preparing payload. " + e.getLocalizedMessage()); } return payload; }</code><technical_language>is constants for payload JSON keys</technical_language>

Target:
public JSONObject generatePayload(String fileUrl, String password, String fileLocation) { JSONObject payload = new JSONObject(); try { payload.put(org.wso2.iot.agent.utils.Constants.FileTransfer.FILE_URL, fileUrl); payload.put(org.wso2.iot.agent.utils.Constants.FileTransfer.FTP_PASSWORD, password); payload.put(org.wso2.iot.agent.utils.Constants.FileTransfer.FILE_LOCATION, fileLocation); } catch (JSONException e) { Log.e(TAG, "JSON Exception in preparing payload. " + e.getLocalizedMessage()); } return payload; }
Source:
<code><START> static boolean isValid(byte code) { <END> return code >= 0 && code <= 7; }</code><technical_language>this more robust hardcoding maximum code value. (Same applies other enums) This add new enum items worry updating hardcoded constants. this: public enum Type { BANDWIDTH((byte)0), ... UPTIME_7D((byte)7); .. private static final int MAX_CODE = Type.values().length; // <- computed class loading time .. static boolean isValid(byte code) { return code >= 0 && code < MAX_CODE; // <-- strictly <, <= } ... }</technical_language>

Target:
static boolean isValid(byte code) { return code >= 0 && code < MAX_CODE; }