auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void configure() throws Exception { final String MANAGEMENT_BUS_IA = "bean:org.opentosca.bus.management.service.IManagementBusService?method=invokeIA"; final String MANAGEMENT_BUS_PLAN = "bean:org.opentosca.bus.management.service.IManagementBusService?method=invokePlan"; this.from("direct:invoke").to("stream:out").process(exchange -> { exchange.getIn().setHeader(MBHeader.APIID_STRING.toString(), Activator.apiID); final String messageID = exchange.getIn().getHeader(MBHeader.PLANCORRELATIONID_STRING.toString(), String.class); if (messageID != null) { exchange.getIn().setMessageId(messageID); exchange.getIn().setHeader(MBHeader.SYNCINVOCATION_BOOLEAN.toString(), false); } else { exchange.getIn().setHeader(MBHeader.SYNCINVOCATION_BOOLEAN.toString(), true); } }).to("stream:out").choice().when(header("OPERATION").isEqualTo(Operations.invokeIA)).to("direct:invokeIA") <START> .when(header("OPERATION").isEqualTo(Operations.invokePlan)).to("direct:invokePlan").end(); <END> this.from("direct:invokeIA").to("stream:out").wireTap(MANAGEMENT_BUS_IA); this.from("direct:invokePlan").to("stream:out").to(MANAGEMENT_BUS_PLAN).end(); this.from("direct-vm:" + Activator.apiID).recipientList(this.simple("direct:response${id}")).end(); }</code><technical_language>if this equality-check is reason for nonstandard naming of enum-members, consider exposing a member enums specifically exposes invoked name following: java public enum Operations { INVOKE_PLAN("invokePlan"), INVOKE_IA("invokeIA"); private final String headerValue; private Operations(String headerValue) { this.headerValue = headerValue; } public String getHeaderValue() { return headerValue; } } // a normal member: //[..] .when(header("OPERATION").isEqualTo(Operations.INVOKE_PLAN.getHeaderValue()).to("direkt:invokePlan").end();</technical_language>

Target:
public void configure() throws Exception { final String MANAGEMENT_BUS_IA = "bean:org.opentosca.bus.management.service.IManagementBusService?method=invokeIA"; final String MANAGEMENT_BUS_PLAN = "bean:org.opentosca.bus.management.service.IManagementBusService?method=invokePlan"; this.from("direct:invoke").to("stream:out").process(exchange -> { exchange.getIn().setHeader(MBHeader.APIID_STRING.toString(), Activator.apiID); final String messageID = exchange.getIn().getHeader(MBHeader.PLANCORRELATIONID_STRING.toString(), String.class); if (messageID != null) { exchange.getIn().setMessageId(messageID); exchange.getIn().setHeader(MBHeader.SYNCINVOCATION_BOOLEAN.toString(), false); } else { exchange.getIn().setHeader(MBHeader.SYNCINVOCATION_BOOLEAN.toString(), true); } }).to("stream:out").choice().when(header("OPERATION").isEqualTo(OsgiEventOperations.INVOKE_IA.getHeaderValue())) .to("direct:invokeIA").when(header("OPERATION").isEqualTo(OsgiEventOperations.INVOKE_PLAN.getHeaderValue())) .to("direct:invokePlan").end(); this.from("direct:invokeIA").to("stream:out").wireTap(MANAGEMENT_BUS_IA); this.from("direct:invokePlan").to("stream:out").to(MANAGEMENT_BUS_PLAN).end(); this.from("direct-vm:" + Activator.apiID).recipientList(this.simple("direct:response${id}")).end(); }
Source:
<code>public <T extends TopLevelItem> T get(Class<T> type, String name) { try { assert getContext() != null; return newInstance(type, getContext(), url("job/%s/", name), name); <START> } catch (AssertionError e) { <END> return newInstance(type, injector, url("job/%s/", name), name); } }</code><technical_language>I do this throw exception place. fix implementations accept external client broken newInstance throw more specific exception implement this fallback</technical_language>

Target:
public <T extends TopLevelItem> T get(Class<T> type, String name) { if (contextAvailable() && typeAcceptsContext(type)) { return newInstance(type, getContext(), url("job/%s/", name), name); } return newInstance(type, injector, url("job/%s/", name), name); }
Source:
<code>private boolean provideJavaClasses(ImportPackageObject pkg, IProgressMonitor monitor) { try { IProject project = fModel.getUnderlyingResource().getProject(); if (!project.hasNature(JavaCore.NATURE_ID)) return false; <START> SubMonitor subMonitor = SubMonitor.convert(monitor, "", 1); END> IJavaProject jProject = JavaCore.create(project); SearchEngine engine = new SearchEngine(); IJavaSearchScope searchScope = PluginJavaSearchUtil.createSeachScope(jProject); Requestor requestor = new Requestor(); String packageName = pkg.getName(); engine.search( SearchPattern.createPattern(packageName, IJavaSearchConstants.PACKAGE, IJavaSearchConstants.REFERENCES, SearchPattern.R_EXACT_MATCH), new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, searchScope, requestor, subMonitor.newChild(1)); if (requestor.foundMatches()) return true; } catch (CoreException e) { } return false; }</code><technical_language>Two-arg constructor</technical_language>

Target:
private boolean provideJavaClasses(ImportPackageObject pkg, IProgressMonitor monitor) { try { IProject project = fModel.getUnderlyingResource().getProject(); if (!project.hasNature(JavaCore.NATURE_ID)) return false; SubMonitor subMonitor = SubMonitor.convert(monitor, 1); IJavaProject jProject = JavaCore.create(project); SearchEngine engine = new SearchEngine(); IJavaSearchScope searchScope = PluginJavaSearchUtil.createSeachScope(jProject); Requestor requestor = new Requestor(); String packageName = pkg.getName(); engine.search( SearchPattern.createPattern(packageName, IJavaSearchConstants.PACKAGE, IJavaSearchConstants.REFERENCES, SearchPattern.R_EXACT_MATCH), new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, searchScope, requestor, subMonitor.newChild(1)); if (requestor.foundMatches()) return true; } catch (CoreException e) { PDEPlugin.logException(e); } return false; }
Source:
<code>public void shouldReturnRandomIntInRange_givenFromLessThanTo() { final Set<Integer> randomInts = new HashSet<>(); final int lowerBound = -Randoms.randomInt(100); final int upperBound = Randoms.randomInt(100); for (int n = 0; n < 100; n++) { final int randomInt = Randoms.randomIntInRange(lowerBound, upperBound); <START> assertTrue(randomInt >= lowerBound && randomInt < upperBound); <END> randomInts.add(randomInt); } assertTrue("100 random samples should not all be same int: " + randomInts.iterator().next(), randomInts.size() > 1); }</code><technical_language>This test fail if lowerBound upperBound 0. I suggest setting follows: java int lowerBound = randomInt(200) - 100; int upperBound = lowerBound + 1 + randomInt(200);</technical_language>

Target:
public void shouldReturnRandomIntInRange_givenFromLessThanTo() { final Set<Integer> randomInts = new HashSet<>(); final int lowerBound = Randoms.randomInt(200) - 100; final int upperBound = lowerBound + 50 + Randoms.randomInt(200); for (int n = 0; n < 100; n++) { final int randomInt = Randoms.randomIntInRange(lowerBound, upperBound); assertTrue(randomInt >= lowerBound && randomInt < upperBound); randomInts.add(randomInt); } assertTrue("100 random samples should not all be same int: " + randomInts.iterator().next(), randomInts.size() > 1); }
Source:
<code>public String toString() { <START> return String.format("Topology[%s] :: Active Cluster=%s :: Standby Clusters=%s", topologyConfigId, activeClusters, standbyClusters); <END> }</code><technical_language>add invalid well</technical_language>

Target:
public String toString() { return String.format("Topology[%s] :: Active Cluster=%s :: Standby Clusters=%s :: Invalid Clusters=%s", topologyConfigId, activeClusters, standbyClusters, invalidClusters); }
Source:
<code>public int read(byte[] buffer, int offset, int length) throws IOException { int bytesRead; if (mSequentialReadCount >= SEQUENTIAL_READ_LIMIT) { ((FSDataInputStream) in).seek(mPos); mSequentialReadCount = 0; } if (mPos == ((FSDataInputStream) in).getPos()) { bytesRead = in.read(buffer, offset, length); } else { bytesRead = ((FSDataInputStream) in).read(mPos, buffer, offset, length); } if (bytesRead > 0) { mPos += bytesRead; } <START> mSequentialReadCount++; <END> return bytesRead; }</code><technical_language>this incremented if bytesRead > 0</technical_language>

Target:
public int read(byte[] buffer, int offset, int length) throws IOException { int bytesRead; if (isSequentialReadMode() && mPos != ((Seekable) in).getPos()) { ((Seekable) in).seek(mPos); } if (mPos == ((Seekable) in).getPos()) { bytesRead = in.read(buffer, offset, length); } else { bytesRead = ((PositionedReadable) in).read(mPos, buffer, offset, length); } if (bytesRead > 0) { mPos += bytesRead; mSequentialReadCount++; } return bytesRead; }
Source:
<code>private RepositoryTreeNode getNodeForPath(Repository repository, String repoRelativePath) { for (ViewerFilter filter : getCommonViewer().getFilters()) { if (NodeFilterFactory.isWorkTreeFilter(filter)) { ITreeContentProvider cp = (ITreeContentProvider) getCommonViewer() .getContentProvider(); RepositoryTreeNode repoNode = findRepositoryNode(cp, cp.getElements(getCommonViewer().getInput()), repository); return repoNode; } } RepositoryTreeNode currentNode = getRepositoryChildNode(repository, RepositoryTreeNodeType.WORKINGDIR); <START> if (currentNode == null) { return null; } <END> ITreeContentProvider cp = (ITreeContentProvider) getCommonViewer() .getContentProvider(); IPath relPath = new Path(repoRelativePath); for (String segment : relPath.segments()) { for (Object child : cp.getChildren(currentNode)) { @SuppressWarnings("unchecked") RepositoryTreeNode<File> childNode = (RepositoryTreeNode<File>) child; if (childNode.getObject().getName().equals(segment)) { currentNode = childNode; break; } } } return currentNode; }</code><technical_language>instead of loop CommonViewer viewer = getCommonViewer(); if (currentNode == null) { return null; } else if (Arrays.stream(viewer.getFilters()) .anyMatch(filter -> !filter .select(viewer, currentNode.getParent(), currentNode))) { return currentNode.getParent(); } changes in other classes needed</technical_language>

Target:
private RepositoryTreeNode getNodeForPath(Repository repository, String repoRelativePath) { RepositoryTreeNode currentNode = getRepositoryChildNode(repository, RepositoryTreeNodeType.WORKINGDIR); CommonViewer viewer = getCommonViewer(); if (currentNode == null) { return null; } else { final RepositoryTreeNode workingDir = currentNode; if (Arrays.stream(viewer.getFilters()).anyMatch(filter -> !filter .select(viewer, workingDir.getParent(), workingDir))) { return currentNode.getParent(); } } ITreeContentProvider cp = (ITreeContentProvider) viewer .getContentProvider(); IPath relPath = new Path(repoRelativePath); for (String segment : relPath.segments()) { for (Object child : cp.getChildren(currentNode)) { @SuppressWarnings("unchecked") RepositoryTreeNode<File> childNode = (RepositoryTreeNode<File>) child; if (childNode.getObject().getName().equals(segment)) { currentNode = childNode; break; } } } return currentNode; }
Source:
<code>public static Driver createDriver(DriverContext driverContext, Operator firstOperator, Operator... otherOperators) { <START> return createDriver(requireNonNull(driverContext, "driverContext is null"), <END> ImmutableList.<Operator>builder() .add(requireNonNull(firstOperator, "firstOperator is null")) .add(requireNonNull(otherOperators, "otherOperators is null")) .build()); }</code><technical_language>here. Move requiredNonNull a separate line</technical_language>

Target:
public static Driver createDriver(DriverContext driverContext, Operator firstOperator, Operator... otherOperators) { requireNonNull(driverContext, "driverContext is null"); requireNonNull(firstOperator, "firstOperator is null"); requireNonNull(otherOperators, "otherOperators is null"); ImmutableList<Operator> operators = ImmutableList.<Operator>builder() .add(firstOperator) .add(otherOperators) .build(); return createDriver(driverContext, operators); }
Source:
<code><START> public boolean isExtended() { <END> return (NB.decodeUInt16(info, infoOffset + P_FLAGS) & EXTENDED) == EXTENDED; }</code><technical_language>expose this a public member yet. I doubt callers need it, lets start package private</technical_language>

Target:
boolean isExtended() { return (info[infoOffset + P_FLAGS] & EXTENDED) != 0; }
Source:
<code>public void setTableQuota(final TableName table, final SetQuotaRequest req) throws IOException, InterruptedException { setQuota(req, new SetQuotaOperations() { @Override public GlobalQuotaSettingsImpl fetch() throws IOException { return new GlobalQuotaSettingsImpl(null, table, null, null, QuotaUtil.getTableQuota(masterServices.getConnection(), table)); } @Override public void update(GlobalQuotaSettingsImpl quotaPojo) throws IOException { QuotaUtil.addTableQuota(masterServices.getConnection(), table, quotaPojo.toQuotas()); } @Override public void delete() throws IOException { SpaceQuotaSnapshot currSnapshotOfTable = QuotaTableUtil.getCurrentSnapshotFromQuotaTable(masterServices.getConnection(), table); QuotaUtil.deleteTableQuota(masterServices.getConnection(), table); <START> QuotaObserverChore quotaChore = ((HMaster)masterServices).getQuotaObserverChore(); <END> quotaChore.removeTableQuotasnapshot(table); if (currSnapshotOfTable != null) { SpaceQuotaStatus quotaStatus = currSnapshotOfTable.getQuotaStatus(); if (SpaceViolationPolicy.DISABLE == quotaStatus.getPolicy().orElse(null) && quotaStatus.isInViolation()) { QuotaUtil.enableTableIfNotEnabled(masterServices.getConnection(), table); } } } @Override public void preApply(GlobalQuotaSettingsImpl quotaPojo) throws IOException { masterServices.getMasterCoprocessorHost().preSetTableQuota(table, quotaPojo); } @Override public void postApply(GlobalQuotaSettingsImpl quotaPojo) throws IOException { masterServices.getMasterCoprocessorHost().postSetTableQuota(table, quotaPojo); } }); }</code><technical_language>need Chores MasterServices interface</technical_language>

Target:
public void setTableQuota(final TableName table, final SetQuotaRequest req) throws IOException, InterruptedException { setQuota(req, new SetQuotaOperations() { @Override public GlobalQuotaSettingsImpl fetch() throws IOException { return new GlobalQuotaSettingsImpl(null, table, null, null, QuotaUtil.getTableQuota(masterServices.getConnection(), table)); } @Override public void update(GlobalQuotaSettingsImpl quotaPojo) throws IOException { QuotaUtil.addTableQuota(masterServices.getConnection(), table, quotaPojo.toQuotas()); } @Override public void delete() throws IOException { SpaceQuotaSnapshot currSnapshotOfTable = QuotaTableUtil.getCurrentSnapshotFromQuotaTable(masterServices.getConnection(), table); QuotaUtil.deleteTableQuota(masterServices.getConnection(), table); QuotaObserverChore quotaChore = masterServices.getQuotaObserverChore(); quotaChore.removeTableQuotasnapshot(table); if (currSnapshotOfTable != null) { SpaceQuotaStatus quotaStatus = currSnapshotOfTable.getQuotaStatus(); if (SpaceViolationPolicy.DISABLE == quotaStatus.getPolicy().orElse(null) && quotaStatus.isInViolation()) { QuotaUtil.enableTableIfNotEnabled(masterServices.getConnection(), table); } } } @Override public void preApply(GlobalQuotaSettingsImpl quotaPojo) throws IOException { masterServices.getMasterCoprocessorHost().preSetTableQuota(table, quotaPojo); } @Override public void postApply(GlobalQuotaSettingsImpl quotaPojo) throws IOException { masterServices.getMasterCoprocessorHost().postSetTableQuota(table, quotaPojo); } }); }
Source:
<code>public void setUseGlobalState(boolean enableGlobalState) { <START> useGlobalState = enableGlobalState; <END> if (useGlobalState) { checkState(); } else { client.setState(new HttpState()); clientViaProxy.setState(new HttpState()); setProxyAuth(clientViaProxy); setClientsCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } }</code><technical_language>Tweak this.useGlobalState = enableGlobalState for clarity</technical_language>

Target:
public void setUseGlobalState(boolean enableGlobalState) { this.useGlobalState = enableGlobalState; checkState(); }
Source:
<code>private void processNextPeriodicMeterReadsForMonthly(final List<PeriodicMeterReads> periodicMeterReads, final List<DataObject> bufferedObjects, final DateTime bufferedDateTime) { final DataObject positiveActiveEnergyTariff1 = bufferedObjects.get(BUFFER_INDEX_A_POS_RATE_1 - 1); LOGGER.debug("positiveActiveEnergyTariff1: {}", this.dlmsHelperService.getDebugInfo(positiveActiveEnergyTariff1)); final DataObject positiveActiveEnergyTariff2 = bufferedObjects.get(BUFFER_INDEX_A_POS_RATE_2 - 1); LOGGER.debug("positiveActiveEnergyTariff2: {}", this.dlmsHelperService.getDebugInfo(positiveActiveEnergyTariff2)); final DataObject negativeActiveEnergyTariff1 = bufferedObjects.get(BUFFER_INDEX_A_NEG_RATE_1 - 1); LOGGER.debug("negativeActiveEnergyTariff1: {}", this.dlmsHelperService.getDebugInfo(negativeActiveEnergyTariff1)); final DataObject negativeActiveEnergyTariff2 = bufferedObjects.get(BUFFER_INDEX_A_NEG_RATE_2 - 1); LOGGER.debug("negativeActiveEnergyTariff2: {}", this.dlmsHelperService.getDebugInfo(negativeActiveEnergyTariff2)); final PeriodicMeterReads nextMeterReads = new PeriodicMeterReads(bufferedDateTime.toDate(), (long) positiveActiveEnergyTariff1.value(), (long) positiveActiveEnergyTariff2.value(), <START> (long) negativeActiveEnergyTariff1.value(), (long) negativeActiveEnergyTariff2.value()); <END> periodicMeterReads.add(nextMeterReads); }</code><technical_language>I adding some kind of conversion method get a long a DataObject a bit cleaner, for example offer some extra logging DataObject contains some unexpected value. DlmsHelperService#readLong similar, this method takes a GetResult (and could/should of method conversion of DataObect if this added)</technical_language>

Target:
private void processNextPeriodicMeterReadsForMonthly(final List<PeriodicMeterReads> periodicMeterReads, final List<DataObject> bufferedObjects, final DateTime bufferedDateTime) throws ProtocolAdapterException { final Long positiveActiveEnergyTariff1 = this.dlmsHelperService.readLongNotNull( bufferedObjects.get(BUFFER_INDEX_A_POS_RATE_1 - 1), "positiveActiveEnergyTariff1"); final Long positiveActiveEnergyTariff2 = this.dlmsHelperService.readLongNotNull( bufferedObjects.get(BUFFER_INDEX_A_POS_RATE_2 - 1), "positiveActiveEnergyTariff2"); final Long negativeActiveEnergyTariff1 = this.dlmsHelperService.readLongNotNull( bufferedObjects.get(BUFFER_INDEX_A_NEG_RATE_1 - 1), "negativeActiveEnergyTariff1"); final Long negativeActiveEnergyTariff2 = this.dlmsHelperService.readLongNotNull( bufferedObjects.get(BUFFER_INDEX_A_NEG_RATE_2 - 1), "negativeActiveEnergyTariff2"); final PeriodicMeterReads nextMeterReads = new PeriodicMeterReads(bufferedDateTime.toDate(), positiveActiveEnergyTariff1, positiveActiveEnergyTariff2, negativeActiveEnergyTariff1, negativeActiveEnergyTariff2); periodicMeterReads.add(nextMeterReads); }
Source:
<code>public int dequeueSample(DecoderInputBuffer sample) { DecoderInputBuffer sampleFromQueue = mQueue.poll(); if (sampleFromQueue == null) { return C.RESULT_NOTHING_READ; } int size = sampleFromQueue.data.position(); sample.ensureSpaceForWrite(size); sample.setFlags((sampleFromQueue.isKeyFrame() ? C.BUFFER_FLAG_KEY_FRAME : 0) | (sampleFromQueue.isDecodeOnly() ? C.BUFFER_FLAG_DECODE_ONLY : 0) | (sampleFromQueue.isEncrypted() ? C.BUFFER_FLAG_ENCRYPTED : 0)); sample.timeUs = sampleFromQueue.timeUs; sample.data.clear(); <START> sampleFromQueue.data.position(0).limit(size); <END> sample.data.put(sampleFromQueue.data); mSamplePool.releaseSample(sampleFromQueue); return C.RESULT_BUFFER_READ; }</code><technical_language>sampleFromQueue.ensureSpaceForWrite</technical_language>

Target:
public int dequeueSample(DecoderInputBuffer sample) { DecoderInputBuffer sampleFromQueue = mQueue.poll(); if (sampleFromQueue == null) { return C.RESULT_NOTHING_READ; } int size = sampleFromQueue.data.position(); sample.ensureSpaceForWrite(size); sample.setFlags((sampleFromQueue.isKeyFrame() ? C.BUFFER_FLAG_KEY_FRAME : 0) | (sampleFromQueue.isDecodeOnly() ? C.BUFFER_FLAG_DECODE_ONLY : 0) | (sampleFromQueue.isEncrypted() ? C.BUFFER_FLAG_ENCRYPTED : 0)); sample.timeUs = sampleFromQueue.timeUs; sample.data.clear(); sampleFromQueue.flip(); sample.data.put(sampleFromQueue.data); mSamplePool.releaseSample(sampleFromQueue); return C.RESULT_BUFFER_READ; }
Source:
<code>public static Iterable<Object[]> parameters() { List<Fixture> fixtures = new ArrayList<>(); <START> int[] iterations = new int[]{100}; <END> LockManager[] lockManagers = LockManager.values(); LockWaitStrategies[] lockWaitStrategies = LockWaitStrategies.values(); LockType[] lockTypes = LockType.values(); for ( LockManager lockManager : lockManagers ) { for ( LockWaitStrategies waitStrategy : lockWaitStrategies ) { for ( LockType lockTypeAX : lockTypes ) { for ( LockType lockTypeAY : lockTypes ) { for ( LockType lockTypeBX : lockTypes ) { for ( LockType lockTypeBY : lockTypes ) { for ( int iteration : iterations ) { fixtures.add( new Fixture( iteration, lockManager, waitStrategy, lockTypeAX, lockTypeAY, lockTypeBX, lockTypeBY ) ); } } } } } } } return fixtures.stream().map( f -> new Object[]{f} ).collect( Collectors.toList() ); }</code><technical_language>this singleton array is confusing - if used, inlining value</technical_language>

Target:
public static Iterable<Object[]> parameters() { List<Fixture> fixtures = new ArrayList<>(); int iteration = 100; LockManager[] lockManagers = LockManager.values(); LockWaitStrategies[] lockWaitStrategies = LockWaitStrategies.values(); LockType[] lockTypes = LockType.values(); for ( LockManager lockManager : lockManagers ) { for ( LockWaitStrategies waitStrategy : lockWaitStrategies ) { for ( LockType lockTypeAX : lockTypes ) { for ( LockType lockTypeAY : lockTypes ) { for ( LockType lockTypeBX : lockTypes ) { for ( LockType lockTypeBY : lockTypes ) { fixtures.add( new Fixture( iteration, lockManager, waitStrategy, lockTypeAX, lockTypeAY, lockTypeBX, lockTypeBY ) ); } } } } } } return fixtures.stream().map( f -> new Object[]{f} ).collect( Collectors.toList() ); }
Source:
<code>public EventHeaderDef createDefinition(IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException { alignRead(input); ByteOrder bo = input.getByteOrder(); input.setByteOrder(fByteOrder); int first = (int) input.get(COMPACT_ID, false); int second = (int) input.get(COMPACT_TS, false); <START> if (first != 65535) { <END> input.setByteOrder(bo); return new EventHeaderDef(this, first, second, COMPACT_TS); } long timestampLong = input.get(FULL_TS, false); input.setByteOrder(bo); return new EventHeaderDef(this, second, timestampLong, FULL_TS); }</code><technical_language>a define</technical_language>

Target:
public EventHeaderDef createDefinition(IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException { alignRead(input); ByteOrder bo = input.getByteOrder(); input.setByteOrder(fByteOrder); int first = (int) input.get(COMPACT_ID, false); int second = (int) input.get(COMPACT_TS, false); if (first != EXTENDED_VALUE) { input.setByteOrder(bo); return new EventHeaderDef(this, first, second, COMPACT_TS); } long timestampLong = input.get(FULL_TS, false); input.setByteOrder(bo); return new EventHeaderDef(this, second, timestampLong, FULL_TS); }
Source:
<code>public static BeanMapping fromPrism( BeanMappingPrism beanMapping, ExecutableElement method, Messager messager ) { if ( beanMapping == null ) { return null; } boolean resultTypeIsDefined = !TypeKind.VOID.equals( beanMapping.resultType().getKind() ); if ( !resultTypeIsDefined && beanMapping.qualifiedBy().isEmpty() ) { messager.printMessage( Diagnostic.Kind.ERROR, <START> "'resultType' and 'qualifiedBy' are are are undefined in @BeanMapping, " <END> + "define at least one of them.", method ); } return new BeanMapping( beanMapping.qualifiedBy(), resultTypeIsDefined ? beanMapping.resultType() : null ); }</code><technical_language>Some "are" :)</technical_language>

Target:
public static BeanMapping fromPrism( BeanMappingPrism beanMapping, ExecutableElement method, Messager messager ) { if ( beanMapping == null ) { return null; } boolean resultTypeIsDefined = !TypeKind.VOID.equals( beanMapping.resultType().getKind() ); if ( !resultTypeIsDefined && beanMapping.qualifiedBy().isEmpty() ) { messager.printMessage( Diagnostic.Kind.ERROR, "'resultType' and 'qualifiedBy' are undefined in @BeanMapping, " + "define at least one of them.", method ); } return new BeanMapping( beanMapping.qualifiedBy(), resultTypeIsDefined ? beanMapping.resultType() : null ); }
Source:
<code>private TestClient testClient() { final TestClient client = Mockito.mock(TestClient.class); final TestResponse response = Mockito.mock(TestResponse.class); Mockito.when(client.header(Mockito.anyString(), Mockito.anyObject())) .thenReturn(client); Mockito.when(client.post(Mockito.anyString(), Mockito.anyObject())) .thenReturn(response); Mockito.when(response.assertStatus(Mockito.anyInt())) .thenReturn(response); <START> Mockito.when(response.xpath(Mockito.anyString())).thenReturn(null); <END> return client; }</code><technical_language>this smells... NULL, :)</technical_language>

Target:
private TestClient testClient() { final TestClient client = Mockito.mock(TestClient.class); final TestResponse response = Mockito.mock(TestResponse.class); Mockito.when(client.header(Mockito.anyString(), Mockito.anyObject())) .thenReturn(client); Mockito.when(client.post(Mockito.anyString(), Mockito.anyObject())) .thenReturn(response); Mockito.when(response.assertStatus(Mockito.anyInt())) .thenReturn(response); Mockito.when(response.xpath(Mockito.anyString())) .thenReturn(Collections.<String>emptyList()); return client; }
Source:
<code>protected void map( Object key, Object value, Context context ) throws IOException, InterruptedException { try { final InputRow inputRow; try { inputRow = parseInputRow(value, parser); } catch (ParseException e) { if (reportParseExceptions) { throw e; } <START> if (log.isDebugEnabled()) { <END> log.debug(e, "Ignoring invalid row [%s] due to parsing error", value.toString()); } context.getCounter(HadoopDruidIndexerConfig.IndexJobCounters.INVALID_ROW_COUNTER).increment(1); return; } if (inputRow == null) { if (log.isDebugEnabled()) { log.debug("Throwing away row [%s]", value.toString()); } return; } if (!granularitySpec.bucketIntervals().isPresent() || granularitySpec.bucketInterval(DateTimes.utc(inputRow.getTimestampFromEpoch())) .isPresent()) { innerMap(inputRow, value, context, reportParseExceptions); } } catch (RuntimeException e) { throw new RE(e, "Failure on row[%s]", value); } }</code><technical_language>log.isDebugEnabled() check is built-in log.debug(..) this is necessary. wanted avoid eager value.toString() computation done replacing</technical_language>

Target:
protected void map( Object key, Object value, Context context ) throws IOException, InterruptedException { try { final InputRow inputRow; try { inputRow = parseInputRow(value, parser); } catch (ParseException e) { if (reportParseExceptions) { throw e; } log.debug(e, "Ignoring invalid row [%s] due to parsing error", value); context.getCounter(HadoopDruidIndexerConfig.IndexJobCounters.INVALID_ROW_COUNTER).increment(1); return; } if (inputRow == null) { log.debug("Throwing away row [%s]", value); return; } if (!granularitySpec.bucketIntervals().isPresent() || granularitySpec.bucketInterval(DateTimes.utc(inputRow.getTimestampFromEpoch())) .isPresent()) { innerMap(inputRow, value, context, reportParseExceptions); } } catch (RuntimeException e) { throw new RE(e, "Failure on row[%s]", value); } }
Source:
<code>private void setLatestExecutionStatus(final SchedulingServiceAsync service, final JobIdentifier job, final TenantIdentifier tenant) { service.getLatestExecution(tenant, job, new DCAsyncCallback<ExecutionLog>() { @Override public void onSuccess(final ExecutionLog result) { if (result != null) { final ExecutionStatus executionStatus = result.getExecutionStatus(); <START> final DateTimeFormat formatDate = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss"); <END> final String formattedDate = formatDate.format(result.getJobBeginDate()); latestExecutionLabel.setText("- Latest execution:" + formattedDate + ", " + executionStatus.name()); } } }); }</code><technical_language>refactor a constant class</technical_language>

Target:
private void setLatestExecutionStatus(final SchedulingServiceAsync service, final JobIdentifier job, final TenantIdentifier tenant) { service.getLatestExecution(tenant, job, new DCAsyncCallback<ExecutionLog>() { @Override public void onSuccess(final ExecutionLog result) { if (result != null) { final String executionStatus = result.getExecutionStatus().toString().toLowerCase(); final String formattedDate = FORMAT_DATE.format(result.getJobBeginDate()); latestExecutionLabel.setText("- Latest execution: " + formattedDate + ", " + executionStatus .substring(0, 1).toUpperCase() + executionStatus.substring(1)); } } }); }
Source:
<code>private List<MavenProject> probableFractionProjects() { if (PROBABLE_FRACTIONS == null) { final ProjectBuildingRequest request = new DefaultProjectBuildingRequest(); request.setProcessPlugins(false); request.setSystemProperties(System.getProperties()); request.setRemoteRepositories(this.project.getRemoteArtifactRepositories()); request.setRepositorySession(this.repositorySystemSession); request.setResolveDependencies(true); try { PROBABLE_FRACTIONS = this.projectBuilder .build(Collections.singletonList(findRoot(this.project).getFile()), true, request) .stream() .filter(this::isNotArquillianArtifact) .map(ProjectBuildingResult::getProject) .collect(Collectors.toList()); } catch (ProjectBuildingException e) { <START> getLog().error(e); <END> } } return PROBABLE_FRACTIONS; }</code><technical_language>I this exception propagated</technical_language>

Target:
private List<MavenProject> probableFractionProjects() throws MojoExecutionException { if (PROBABLE_FRACTIONS == null) { final ProjectBuildingRequest request = new DefaultProjectBuildingRequest(); request.setProcessPlugins(false); request.setSystemProperties(System.getProperties()); request.setRemoteRepositories(this.project.getRemoteArtifactRepositories()); request.setRepositorySession(this.repositorySystemSession); request.setResolveDependencies(true); try { PROBABLE_FRACTIONS = this.projectBuilder .build(Collections.singletonList(findRoot(this.project).getFile()), true, request) .stream() .filter(this::isNotArquillianArtifact) .map(ProjectBuildingResult::getProject) .collect(Collectors.toList()); } catch (ProjectBuildingException e) { throw new MojoExecutionException("Error generating list of PROBABLE_FRACTIONS", e); } } return PROBABLE_FRACTIONS; }
Source:
<code>public DocumentModel defaultCreateFolder(CoreSession documentManager, String fullname, String path, String containerTypeName, boolean checkAllowedSubTypes, boolean overwrite) { String title = FileManagerUtils.fetchFileName(fullname); <START> DocumentModel docModel = null; <END> if (overwrite) { docModel = FileManagerUtils.getExistingDocByTitle(documentManager, path, title); if (docModel != null) { return docModel; } } PathRef containerRef = new PathRef(path); if (!documentManager.hasPermission(containerRef, SecurityConstants.READ_PROPERTIES) || !documentManager.hasPermission(containerRef, SecurityConstants.ADD_CHILDREN)) { throw new DocumentSecurityException("Not enough rights to create folder"); } DocumentModel container = documentManager.getDocument(containerRef); if (checkAllowedSubTypes && !getTypeService().isAllowedSubType(containerTypeName, container.getType(), container)) { return null; } PathSegmentService pss = Framework.getService(PathSegmentService.class); docModel = documentManager.createDocumentModel(containerTypeName); docModel.setProperty("dublincore", "title", title); docModel.setPathInfo(path, pss.generatePathSegment(docModel)); docModel = documentManager.createDocument(docModel); documentManager.save(); log.debug("Created container: " + docModel.getName() + " with type " + containerTypeName); return docModel; }</code><technical_language>move docModel declaration if</technical_language>

Target:
public DocumentModel defaultCreateFolder(CoreSession documentManager, String fullname, String path, String containerTypeName, boolean checkAllowedSubTypes, boolean overwrite) { String title = FileManagerUtils.fetchFileName(fullname); if (overwrite) { DocumentModel docModel = FileManagerUtils.getExistingDocByTitle(documentManager, path, title); if (docModel != null) { return docModel; } } PathRef containerRef = new PathRef(path); if (!documentManager.hasPermission(containerRef, SecurityConstants.READ_PROPERTIES) || !documentManager.hasPermission(containerRef, SecurityConstants.ADD_CHILDREN)) { throw new DocumentSecurityException("Not enough rights to create folder"); } DocumentModel container = documentManager.getDocument(containerRef); if (checkAllowedSubTypes && !getTypeService().isAllowedSubType(containerTypeName, container.getType(), container)) { return null; } PathSegmentService pss = Framework.getService(PathSegmentService.class); DocumentModel docModel = documentManager.createDocumentModel(containerTypeName); docModel.setProperty("dublincore", "title", title); docModel.setPathInfo(path, pss.generatePathSegment(docModel)); docModel = documentManager.createDocument(docModel); documentManager.save(); log.debug("Created container: " + docModel.getName() + " with type " + containerTypeName); return docModel; }
Source:
<code>protected <T> PagedAsyncCompletionHandler<List<T>> handleIncrementalList(final Class<T> clazz, final String name) { return new PagedAsyncListCompletionHandler<T>(clazz, name) { public void setPagedProperties(JsonNode responseNode, Class<?> clazz) { JsonNode node = responseNode.get(NEXT_PAGE); if (node == null) { throw new NullPointerException(NEXT_PAGE + " property not found, pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } JsonNode endTimeNode = responseNode.get(END_TIME); if (endTimeNode == null || endTimeNode.asLong() == 0) { throw new NullPointerException(END_TIME + " property not found, incremental export pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } <START> if (endTimeNode.asLong() * 1000 > System.currentTimeMillis() - FIVE_MINUTES_IN_MS) { <END> nextPage = null; } else { nextPage = node.asText(); } } }; }</code><technical_language>TimeUnit.SECONDS.toMillis(endTimeNode.asLong()) expressive * 1000</technical_language>

Target:
protected <T> PagedAsyncCompletionHandler<List<T>> handleIncrementalList(final Class<T> clazz, final String name) { return new PagedAsyncListCompletionHandler<T>(clazz, name) { @Override public void setPagedProperties(JsonNode responseNode, Class<?> clazz) { JsonNode node = responseNode.get(NEXT_PAGE); if (node == null) { throw new NullPointerException(NEXT_PAGE + " property not found, pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } JsonNode endTimeNode = responseNode.get(END_TIME); if (endTimeNode == null || endTimeNode.asLong() == 0) { throw new NullPointerException(END_TIME + " property not found, incremental export pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } if (TimeUnit.SECONDS.toMillis(endTimeNode.asLong()) > System.currentTimeMillis() - FIVE_MINUTES_IN_MS) { setNextPage(null); } else { setNextPage(node.asText()); } } }; }
Source:
<code>public void testManualToolStayManual() { String gitUrl = "git@github.com:DockstoreTestUser2/dockstore-whalesay-imports.git"; ContainersApi toolsApi = setupWebService(); DockstoreTool tool = getQuayContainer(gitUrl); DockstoreTool toolTest = toolsApi.registerManual(tool); toolsApi.refresh(toolTest.getId()); final CommonTestUtilities.TestingPostgres testingPostgres = getTestingPostgres(); final long count = testingPostgres .runSelectStatement("select count(*) from tool where mode = '" + DockstoreTool.ModeEnum.MANUAL_IMAGE_PATH + "' and giturl = '" + gitUrl + "' and name = 'my-md5sum' and namespace = 'dockstoretestuser2' and toolname = 'altname'", new ScalarHandler<>()); <START> assertTrue("The tool should be manual, there are " + count, count == 1); <END> }</code><technical_language>assertEquals</technical_language>

Target:
public void testManualToolStayManual() { String gitUrl = "git@github.com:DockstoreTestUser2/dockstore-whalesay-imports.git"; ContainersApi toolsApi = setupWebService(); DockstoreTool tool = getQuayContainer(gitUrl); DockstoreTool toolTest = toolsApi.registerManual(tool); toolsApi.refresh(toolTest.getId()); final CommonTestUtilities.TestingPostgres testingPostgres = getTestingPostgres(); final long count = testingPostgres .runSelectStatement("select count(*) from tool where mode = '" + DockstoreTool.ModeEnum.MANUAL_IMAGE_PATH + "' and giturl = '" + gitUrl + "' and name = 'my-md5sum' and namespace = 'dockstoretestuser2' and toolname = 'altname'", new ScalarHandler<>()); assertEquals("The tool should be manual, there are " + count, 1, count); }
Source:
<code>public void testTemplateScheduledPushPayloadSerializer() throws Exception { TemplateSelector mergeData = TemplateSelector.newBuilder() .setTemplateId("id123") .addSubstitution("FIRST_NAME", "Prince") .addSubstitution("LAST_NAME", "") .build(); <START> Schedule schedule = Schedule.newBuilder().setScheduledTimestamp(DateTime.now()).build(); <END> TemplateScheduledPushPayload payload = TemplateScheduledPushPayload.newBuilder() .setAudience(Selectors.all()) .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID)) .setMergeData(mergeData) .build(); String templateScheduledPushPayloadSerialized = MAPPER.writeValueAsString(payload); String templateScheduledPushPayloadString = "{" + "\"audience\":\"ALL\"," + "\"device_types\":[\"ios\",\"android\"]," + "\"merge_data\":{" + "\"template_id\":\"id123\"," + "\"substitutions\":{" + "\"FIRST_NAME\":\"Prince\"," + "\"LAST_NAME\":\"\"" + "}" + "}," +"\"schedule\":null"+ "}"; JsonNode jsonFromObject = MAPPER.readTree(templateScheduledPushPayloadSerialized); JsonNode jsonFromString = MAPPER.readTree(templateScheduledPushPayloadString); assertEquals(jsonFromObject, jsonFromString); }</code><technical_language>This is created used</technical_language>

Target:
public void testTemplateScheduledPushPayloadSerializer() throws Exception { TemplateSelector mergeData = TemplateSelector.newBuilder() .setTemplateId("id123") .addSubstitution("FIRST_NAME", "Prince") .addSubstitution("LAST_NAME", "") .build(); Schedule schedule = Schedule.newBuilder().setScheduledTimestamp(DateTime.parse("2019-05-30T07:53:13Z")).build(); TemplateScheduledPushPayload payload = TemplateScheduledPushPayload.newBuilder() .setAudience(Selectors.all()) .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID)) .setMergeData(mergeData) .setSchedule(schedule) .setName("Prince") .build(); String templateScheduledPushPayloadSerialized = MAPPER.writeValueAsString(payload); String templateScheduledPushPayloadString = "{" + "\"audience\":\"ALL\"," + "\"name\":\"Prince\"," + "\"device_types\":[\"ios\",\"android\"]," + "\"merge_data\":{" + "\"template_id\":\"id123\"," + "\"substitutions\":{" + "\"FIRST_NAME\":\"Prince\"," + "\"LAST_NAME\":\"\"" + "}" + "}," +"\"schedule\":{\"scheduled_time\":\"2019-05-30T07:53:13\"}"+ "}"; JsonNode jsonFromObject = MAPPER.readTree(templateScheduledPushPayloadSerialized); JsonNode jsonFromString = MAPPER.readTree(templateScheduledPushPayloadString); assertEquals(jsonFromObject, jsonFromString); }
Source:
<code>void postConstruct() { metrics.registerAll(namespace("bufpool", new BufferPoolMetricSet(mbs))); <START> metrics.register(base + ".fd", new FileDescriptorMetricSet()); <END> metrics.registerAll(namespace("gc", new GarbageCollectorMetricSet())); metrics.registerAll(namespace("mem", new MemoryUsageGaugeSet())); metrics.registerAll(namespace("class", new ClassLoadingGaugeSet())); metrics.registerAll(namespace("thread", new ThreadStatesGaugeSet())); metrics.register(base + ".cpu.load", new CpuLoadGauge()); nmtMetrics.register(); }</code><technical_language>call namespace("fd", new ...) instead, right</technical_language>

Target:
void postConstruct() { metrics.registerAll(namespace("bufpool", new BufferPoolMetricSet(mbs))); metrics.registerAll(namespace("fd", new FileDescriptorMetricSet())); metrics.registerAll(namespace("gc", new GarbageCollectorMetricSet())); metrics.registerAll(namespace("mem", new MemoryUsageGaugeSet())); metrics.registerAll(namespace("class", new ClassLoadingGaugeSet())); metrics.registerAll(namespace("thread", new ThreadStatesGaugeSet())); metrics.register(BASE + ".cpu.load", new CpuLoadGauge()); nmtMetrics.register(); }
Source:
<code>public synchronized void authenticate() throws PortalSecurityException { this.isauth = false; if (this.myPrincipal.UID != null && this.myOpaqueCredentials.credentialstring != null) { StringBuilder msg = new StringBuilder(); msg.append("An attempt to log into the local login has occurred. "); msg.append("user=" + this.myPrincipal.UID); if (log.isWarnEnabled()) log.warn(msg.toString()); <START> <END> try { ILocalAccountDao accountStore = LocalAccountDaoLocator.getLocalAccountDao(); IPortalPasswordService passwordService = PortalPasswordServiceLocator.getPortalPasswordService(); ILocalAccountPerson account = accountStore.getPerson(this.myPrincipal.UID); if (account != null) { String loginPassword = new String(this.myOpaqueCredentials.credentialstring, UTF_8); if (passwordService.validatePassword(loginPassword, account.getPassword())) { String fullName = (String) account.getAttributeValue("displayName"); this.myPrincipal.FullName = fullName; if (log.isInfoEnabled()) log.info("User " + this.myPrincipal.UID + " is authenticated"); this.isauth = true; } else { log.info("Password Invalid"); } } else { if (log.isInfoEnabled()) log.info("No such user: " + this.myPrincipal.UID); } } catch (Exception e) { log.error("Error authenticating user", e); throw new RuntimeException("Error authenticating user", e); } } else { log.info("Principal or OpaqueCredentials not initialized prior to authenticate"); } super.authenticate(); return; }</code><technical_language>I wrap StringBuilder in if statement</technical_language>

Target:
public synchronized void authenticate() throws PortalSecurityException { this.isauth = false; if (this.myPrincipal.UID != null && this.myOpaqueCredentials.credentialstring != null) { if (log.isWarnEnabled()) log.warn( "An attempt to log into the local login has occurred. user=" + this.myPrincipal.UID); try { ILocalAccountDao accountStore = LocalAccountDaoLocator.getLocalAccountDao(); IPortalPasswordService passwordService = PortalPasswordServiceLocator.getPortalPasswordService(); ILocalAccountPerson account = accountStore.getPerson(this.myPrincipal.UID); if (account != null) { String loginPassword = new String(this.myOpaqueCredentials.credentialstring, UTF_8); if (passwordService.validatePassword(loginPassword, account.getPassword())) { String fullName = (String) account.getAttributeValue("displayName"); this.myPrincipal.FullName = fullName; if (log.isInfoEnabled()) log.info("User " + this.myPrincipal.UID + " is authenticated"); this.isauth = true; } else { log.info("Password Invalid"); } } else { if (log.isInfoEnabled()) log.info("No such user: " + this.myPrincipal.UID); } } catch (Exception e) { log.error("Error authenticating user", e); throw new RuntimeException("Error authenticating user", e); } } else { log.info("Principal or OpaqueCredentials not initialized prior to authenticate"); } super.authenticate(); return; }
Source:
<code>public boolean matchPod(String podName) { try { return machines <START> .getMachines(identity) <END> .values() .stream() .filter(m -> m.getPodName() != null) .anyMatch(m -> m.getPodName().equals(podName)); } catch (InfrastructureException e) { LOG.error( "Failed to get the machines when checking whether LogHandler do care about pod [{}]. Not much to do here.", podName, e); return false; } }</code><technical_language>This is hitting database in case of JpaKubernetesMachineCache. match name some list of strings supplied constructor instead</technical_language>

Target:
public boolean matchPod(String podName) { return podNames.contains(podName); }
Source:
<code>public boolean isFinished() { if (!finishing) { return false; } <START> if (joinPagesNotNeeded.isPresent() && !joinPagesNotNeeded.get().isDone()) { <END> return false; } return true; }</code><technical_language>return joinPagesNotNeeded.map(Future::isDone).orElse(true)</technical_language>

Target:
public boolean isFinished() { return probeDoneWithPages.map(Future::isDone).orElse(false); }
Source:
<code>public PatientProgram savePatientProgram(PatientProgram patientProgram) throws APIException { if (patientProgram.getPatient() == null || patientProgram.getProgram() == null) { throw new APIException("PatientProgram.requires", (Object[]) null); } for (PatientState state : patientProgram.getStates()) { if (state.getState() == null) { throw new APIException("PatientState.requires", (Object[]) null); } if (state.getPatientProgram() == null) { state.setPatientProgram(patientProgram); } else if (!state.getPatientProgram().equals(patientProgram)) { throw new APIException("PatientProgram.already.assigned", new Object[] { state.getPatientProgram() }); } if (patientProgram.getVoided() || state.getVoided()) { state.setVoided(true); if (state.getVoidReason() == null && patientProgram.getVoidReason() != null) { state.setVoidReason(patientProgram.getVoidReason()); } } } <START> for (PatientState state : patientProgram.getMostRecentStateInEachWorkflow()) { <END> state.setEndDate(patientProgram.getDateCompleted()); } return dao.savePatientProgram(patientProgram); }</code><technical_language>I thought this happening completing a program, condition ensures that</technical_language>

Target:
public PatientProgram savePatientProgram(PatientProgram patientProgram) throws APIException { if (patientProgram.getPatient() == null || patientProgram.getProgram() == null) { throw new APIException("PatientProgram.requires", (Object[]) null); } for (PatientState state : patientProgram.getStates()) { if (state.getState() == null) { throw new APIException("PatientState.requires", (Object[]) null); } if (state.getPatientProgram() == null) { state.setPatientProgram(patientProgram); } else if (!state.getPatientProgram().equals(patientProgram)) { throw new APIException("PatientProgram.already.assigned", new Object[] { state.getPatientProgram() }); } if (patientProgram.getVoided() || state.getVoided()) { state.setVoided(true); if (state.getVoidReason() == null && patientProgram.getVoidReason() != null) { state.setVoidReason(patientProgram.getVoidReason()); } } } if (patientProgram.getDateCompleted() != null) { for (PatientState state : patientProgram.getMostRecentStateInEachWorkflow()) { if (state.getEndDate() == null) { state.setEndDate(patientProgram.getDateCompleted()); } } } return dao.savePatientProgram(patientProgram); }