auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> private void applyContaminationFilter(final M2FiltersArgumentCollection MTFAC, final VariantContext vc, final Collection<String> filters) { <END> if (vc.hasAttribute(VCFConstants.ALLELE_FREQUENCY_KEY)) { final double[] alleleFrequencies = getArrayAttribute(vc, VCFConstants.ALLELE_FREQUENCY_KEY); final double maxFrequency = MathUtils.arrayMax(alleleFrequencies); if (maxFrequency < contamination) { filters.add(CONTAMINATION_FILTER_NAME); } } }</code><technical_language>want extract tumor alt allele _fraction_ genotype field, population allele _frequency_ INFO field, right</technical_language>

Target:
private void applyContaminationFilter(final M2FiltersArgumentCollection MTFAC, final VariantContext vc, final Collection<String> filters) { final Genotype tumorGenotype = vc.getGenotype(tumorSample); final double[] alleleFractions = GATKProtectedVariantContextUtils.getAttributeAsDoubleArray(tumorGenotype, VCFConstants.ALLELE_FREQUENCY_KEY, () -> new double[] {1.0}, 1.0); final double maxFraction = MathUtils.arrayMax(alleleFractions); if (maxFraction < contamination) { filters.add(CONTAMINATION_FILTER_NAME); } }
Source:
<code>public HungryLynx(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{G}"); this.subtype.add(SubType.CAT); this.power = new MageInt(2); this.toughness = new MageInt(2); Effect effect = new GainAbilityAllEffect(new ProtectionAbility(filterProRat), Duration.WhileOnBattlefield, filterCat); effect.setText("Cats you control have protection from Rats. <i>(They can't be blocked, targeted, or dealt damage by Rats.)</i>"); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, effect)); Ability ability = new BeginningOfEndStepTriggeredAbility(Zone.BATTLEFIELD, new CreateTokenTargetEffect(new DeathtouchRatToken()), TargetController.YOU, null, false); Target target = new TargetOpponent(); ability.addTarget(target); this.addAbility(ability); Effect effect2 = new AddCountersAllEffect(CounterType.P1P1.createInstance(), filterCat); <START> effect2.setText(" put a +1/+1 counter on each Cat you control."); <END> this.addAbility(new DiesCreatureTriggeredAbility(effect2, false, filterRat)); }</code><technical_language>blanks start "." end of effect texts. rule text logic handle this automatically</technical_language>

Target:
public HungryLynx(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{G}"); this.subtype.add(SubType.CAT); this.power = new MageInt(2); this.toughness = new MageInt(2); Effect effect = new GainAbilityAllEffect(new ProtectionAbility(filterProRat), Duration.WhileOnBattlefield, filterCat); effect.setText("Cats you control have protection from Rats. <i>(They can't be blocked, targeted, or dealt damage by Rats.)</i>"); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, effect)); Ability ability = new BeginningOfEndStepTriggeredAbility(Zone.BATTLEFIELD, new CreateTokenTargetEffect(new DeathtouchRatToken()), TargetController.YOU, null, false); Target target = new TargetOpponent(); ability.addTarget(target); this.addAbility(ability); Effect effect2 = new AddCountersAllEffect(CounterType.P1P1.createInstance(), filterCat); effect2.setText("put a +1/+1 counter on each Cat you control"); this.addAbility(new DiesCreatureTriggeredAbility(effect2, false, filterRat)); }
Source:
<code>public void testScaleDenominator() throws Exception { LayerGroupInfo info = getCatalog().getLayerGroupByName("cascaded_group"); LayerInfo groupLayer2 = getCatalog().getLayerByName("group_lyr_2"); assertNotNull(info); assertNotNull(groupLayer2); ReferencedEnvelope request1 = new ReferencedEnvelope(groupLayer2.getResource().getNativeBoundingBox()); String lyrBBox = request1.getMinX() + "," + request1.getMinY() + "," + request1.getMaxX() + "," + request1.getMaxY(); WMSLayerInfo groupLayer1WMSResource = (WMSLayerInfo) getCatalog().getLayerByName("group_lyr_1").getResource(); <START> groupLayer1WMSResource.setMinScale(1); <END> groupLayer1WMSResource.setMaxScale(1000); getCatalog().save(groupLayer1WMSResource); String getMapRequest = "wms?service=WMS&version=1.1.0" + "&request=GetMap" + "&layers=" + info.getName() + "&bbox=" + lyrBBox + "&width=768&height=537&srs=EPSG:4326&Format=image/png"; BufferedImage response = getAsImage(getMapRequest, "image/png"); assertNotNull(response); groupLayer1WMSResource.setMinScale(null); groupLayer1WMSResource.setMaxScale(null); getCatalog().save(groupLayer1WMSResource); }</code><technical_language>Set reset put in a try/finally block, a failure in this test spurious failures in other tests</technical_language>

Target:
public void testScaleDenominator() throws Exception { LayerGroupInfo info = getCatalog().getLayerGroupByName("cascaded_group"); LayerInfo groupLayer2 = getCatalog().getLayerByName("group_lyr_2"); assertNotNull(info); assertNotNull(groupLayer2); ReferencedEnvelope request1 = new ReferencedEnvelope(groupLayer2.getResource().getNativeBoundingBox()); String lyrBBox = request1.getMinX() + "," + request1.getMinY() + "," + request1.getMaxX() + "," + request1.getMaxY(); WMSLayerInfo groupLayer1WMSResource = (WMSLayerInfo) getCatalog().getLayerByName("group_lyr_1").getResource(); groupLayer1WMSResource.setMinScale(1d); groupLayer1WMSResource.setMaxScale(1000d); getCatalog().save(groupLayer1WMSResource); String getMapRequest = "wms?service=WMS&version=1.1.0" + "&request=GetMap" + "&layers=" + info.getName() + "&bbox=" + lyrBBox + "&width=768&height=537&srs=EPSG:4326&Format=image/png"; try { BufferedImage response = getAsImage(getMapRequest, "image/png"); assertNotNull(response); } finally { groupLayer1WMSResource.setMinScale(null); groupLayer1WMSResource.setMaxScale(null); getCatalog().save(groupLayer1WMSResource); } }
Source:
<code>public boolean resolve(Game game) { if (ability.getTargets().stillLegal(ability, game) || !canFizzle()) { <START> game.fireEvent(new GameEvent(GameEvent.EventType.RESOLVED_ABILITY, ability.getOriginalId(), ability.getSourceId(), ability.getControllerId())); <END> boolean result = ability.resolve(game); game.getStack().remove(this, game); return result; } if (!game.isSimulation()) { game.informPlayers("Ability has been fizzled: " + getRule()); } counter(null, game); game.getStack().remove(this, game); return false; }</code><technical_language>event fire real resolve, after? named RESOLVED_ABILITY (e.g. for event happened)</technical_language>

Target:
public boolean resolve(Game game) { if (ability.getTargets().stillLegal(ability, game) || !canFizzle()) { boolean result = ability.resolve(game); game.getStack().remove(this, game); return result; } if (!game.isSimulation()) { game.informPlayers("Ability has been fizzled: " + getRule()); } counter(null, game); game.getStack().remove(this, game); return false; }
Source:
<code>private void UpdateSpmPriority(Integer value) { List<EntityModel> items = new ArrayList<EntityModel>(); if (value == null) { value = defaultSpmPriority; } int neverValue = -1; EntityModel neverItem = new EntityModel("Never", neverValue); items.add(neverItem); int lowValue = defaultSpmPriority / 2; <START> items.add(new EntityModel("Low", lowValue)); END> items.add(new EntityModel("Normal", defaultSpmPriority)); int highValue = defaultSpmPriority + (maxSpmPriority - defaultSpmPriority) / 2; items.add(new EntityModel("High", highValue)); EntityModel selectedItem = null; int[] values = new int[] { neverValue, lowValue, defaultSpmPriority, highValue, maxSpmPriority + 1 }; Integer prevValue = null; for (int i = 0; i < values.length; i++) { int currentValue = values[i]; if (value == currentValue) { selectedItem = items.get(i); break; } else if (prevValue != null && value > prevValue && value < currentValue) { EntityModel customItem = new EntityModel("Custom", value); items.add(i, customItem); selectedItem = customItem; break; } prevValue = currentValue; } if (selectedItem != neverItem) { items.remove(neverItem); } getSpmPriority().setItems(items); getSpmPriority().setSelectedItem(selectedItem); }</code><technical_language>"//$NON-NLS-2$" part removed (it suggests hard-coded string in this line localized, in hard-coded string in this line anymore, change)</technical_language>

Target:
private void UpdateSpmPriority(Integer value) { List<EntityModel> items = new ArrayList<EntityModel>(); if (value == null) { value = defaultSpmPriority; } int neverValue = -1; EntityModel neverItem = new EntityModel("Never", neverValue); items.add(neverItem); int lowValue = defaultSpmPriority / 2; items.add(new EntityModel("Low", lowValue)); items.add(new EntityModel("Normal", defaultSpmPriority)); int highValue = defaultSpmPriority + (maxSpmPriority - defaultSpmPriority) / 2; items.add(new EntityModel("High", highValue)); EntityModel selectedItem = null; int[] values = new int[] { neverValue, lowValue, defaultSpmPriority, highValue, maxSpmPriority + 1 }; Integer prevValue = null; for (int i = 0; i < values.length; i++) { int currentValue = values[i]; if (value == currentValue) { selectedItem = items.get(i); break; } else if (prevValue != null && value > prevValue && value < currentValue) { EntityModel customItem = new EntityModel("Custom (" + value + ")", value); items.add(i, customItem); selectedItem = customItem; break; } prevValue = currentValue; } if (selectedItem != neverItem) { items.remove(neverItem); } getSpmPriority().setItems(items); getSpmPriority().setSelectedItem(selectedItem); }
Source:
<code>public CTFCallsite(String en, String func, long ip, String fn, long line) { fEventName = en; fFileName = fn; fFunctionName = func; <START> this.fIp = ip; <END> this.fLineNumber = line; }</code><technical_language>remove 'this.' below</technical_language>

Target:
public CTFCallsite(String en, String func, long ip, String fn, long line) { fEventName = en; fFileName = fn; fFunctionName = func; fIp = ip; fLineNumber = line; }
Source:
<code>public void testLogFrameworkEventType() throws Exception { <START> final AtomicReference<LogEntry> event = new AtomicReference<LogEntry>(); <END> final CountDownLatch countDown = new CountDownLatch(2); final Bundle b = getContext().getBundle(); LogListener listener = new LogListener() { @Override public void logged(LogEntry entry) { if (b.equals(entry.getBundle())) { event.set(entry); countDown.countDown(); } } }; reader.addLogListener(listener); b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, b.adapt(Module.class), new Exception()); countDown.await(10, TimeUnit.MILLISECONDS); assertNotNull("No event.", event.get()); assertEquals("Wrong type.", LogService.LOG_ERROR, event.get().getLevel()); b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.WARNING, b.adapt(Module.class), new Exception()); countDown.await(10, TimeUnit.MILLISECONDS); assertNotNull("No event.", event.get());; assertEquals("Wrong type.", LogService.LOG_WARNING, event.get().getLevel()); }</code><technical_language>capturing more event other singleton AtomicReference. some kind of concurrent list capture events in order</technical_language>

Target:
public void testLogFrameworkEventType() throws Exception { final List<LogEntry> events = new CopyOnWriteArrayList<LogEntry>(); final CountDownLatch countDown = new CountDownLatch(2); final Bundle b = getContext().getBundle(); LogListener listener = new LogListener() { @Override public void logged(LogEntry entry) { if (b.equals(entry.getBundle())) { events.add(entry); countDown.countDown(); } } }; reader.addLogListener(listener); b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, b.adapt(Module.class), new Exception()); b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.WARNING, b.adapt(Module.class), new Exception()); countDown.await(2, TimeUnit.SECONDS); assertEquals("Wrong number of events", 2, events.size()); assertEquals("Wrong type.", LogService.LOG_ERROR, events.get(0).getLevel()); assertEquals("Wrong type.", LogService.LOG_WARNING, events.get(1).getLevel()); }
Source:
<code>public void testCachesResultAfterFirstLookup() throws Exception { <START> ClassLoader ctx_loader = Thread.currentThread().getContextClassLoader(); <END> final AtomicInteger load_count = new AtomicInteger(0); Thread.currentThread().setContextClassLoader(new ClassLoader(ctx_loader) { @Override public InputStream getResourceAsStream(String s) { InputStream in = super.getResourceAsStream(s); load_count.incrementAndGet(); return in; } }); findSqlOnClasspath("caches-result-after-first-lookup"); assertThat(load_count.get()).isEqualTo(1); findSqlOnClasspath("caches-result-after-first-lookup"); assertThat(load_count.get()).isEqualTo(1); Thread.currentThread().setContextClassLoader(ctx_loader); }</code><technical_language>Non-standard naming conventions</technical_language>

Target:
public void testCachesResultAfterFirstLookup() throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final AtomicInteger loadCount = new AtomicInteger(0); Thread.currentThread().setContextClassLoader(new ClassLoader(classLoader) { @Override public InputStream getResourceAsStream(String s) { InputStream in = super.getResourceAsStream(s); loadCount.incrementAndGet(); return in; } }); findSqlOnClasspath("caches-result-after-first-lookup"); assertThat(loadCount.get()).isEqualTo(1); findSqlOnClasspath("caches-result-after-first-lookup"); assertThat(loadCount.get()).isEqualTo(1); Thread.currentThread().setContextClassLoader(classLoader); }
Source:
<code>private Object deserializePayload(byte[] bytes, MimeType contentType) { <START> if (TEXT_PLAIN.equals(contentType) || APPLICATION_JSON.equals(contentType)) { <END> try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new SerializationFailedException("unable to deserialize [java.lang.String]. Encoding not supported.", e); } } else { String className = JavaClassMimeTypeConversion.classNameFromMimeType(contentType); try { Class<?> targetType = this.payloadTypeCache.get(className); if (targetType == null) { targetType = ClassUtils.forName(className, null); this.payloadTypeCache.put(className, targetType); } return this.codec.decode(bytes, targetType); } catch (ClassNotFoundException e) { throw new SerializationFailedException("unable to deserialize [" + className + "]. Class not found.", e); } catch (IOException e) { throw new SerializationFailedException("unable to deserialize [" + className + "]", e); } } }</code><technical_language>This is necessary of <LINK_0>, necessary itself. I rely text/plain</technical_language>

Target:
private Object deserializePayload(byte[] bytes, MimeType contentType) { if (TEXT_PLAIN.equals(contentType)) { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new SerializationFailedException("unable to deserialize [java.lang.String]. Encoding not supported.", e); } } else { String className = JavaClassMimeTypeConversion.classNameFromMimeType(contentType); try { Class<?> targetType = this.payloadTypeCache.get(className); if (targetType == null) { targetType = ClassUtils.forName(className, null); this.payloadTypeCache.put(className, targetType); } return this.codec.decode(bytes, targetType); } catch (ClassNotFoundException e) { throw new SerializationFailedException("unable to deserialize [" + className + "]. Class not found.", e); } catch (IOException e) { throw new SerializationFailedException("unable to deserialize [" + className + "]", e); } } }
Source:
<code>protected List<String> run(Map<String, Object> params) throws LiteCoreException { List<String> docIDs = new ArrayList<>(); C4QueryOptions opts = new C4QueryOptions(); AllocSlice encodedParams = encodeParameters(params); C4QueryEnumerator e = query.run(opts, encodedParams); assertNotNull(e); while (e.next()) { docIDs.add(e.getColumns().getValueAt(0).asString()); } <START> if (e != null) e.free(); <END> if (encodedParams != null) encodedParams.free(); return docIDs; }</code><technical_language>assertNotNill(e) doing, is _e != null_ necessary</technical_language>

Target:
protected List<String> run(Map<String, Object> params) throws LiteCoreException { List<String> docIDs = new ArrayList<>(); C4QueryOptions opts = new C4QueryOptions(); AllocSlice encodedParams = encodeParameters(params); C4QueryEnumerator e = query.run(opts, encodedParams); try { assertNotNull(e); while (e.next()) { docIDs.add(e.getColumns().getValueAt(0).asString()); } return docIDs; } finally { if (e != null) e.free(); if (encodedParams != null) encodedParams.free(); } }
Source:
<code>public KeyValue<String, String> next() { String pair = pairIter.next(); Iterator<String> keyValIter = Splitter.on(keyValDelimiter).trimResults().split(pair).iterator(); String key = keyValIter.next(); if (!keyValIter.hasNext()) { <START> throw new IllegalArgumentException(String.format("Invalid syntax for key-value pair in list: %s. " + <END> "%s is expected to to be a string separated " + "by one and only one %s", pair, pair, keyValDelimiter)); } String val = keyValIter.next(); if (keyValIter.hasNext()) { throw new IllegalArgumentException(String.format("Invalid syntax for key-value pair in list: %s. " + "%s is expected to to be a string separated " + "by one and only one %s", pair, pair, keyValDelimiter)); } return new KeyValue<>(key, val); }</code><technical_language>need put pair in message twice, right other. Invalid syntax for key-value pair: %s. is expected be..</technical_language>

Target:
public KeyValue<String, String> next() { String pair = pairIter.next(); Iterator<String> keyValIter = Splitter.on(keyValDelimiter).trimResults().split(pair).iterator(); String key = keyValIter.next(); if (!keyValIter.hasNext()) { throw new IllegalArgumentException(String.format("Invalid syntax for key-value pair in list: %s. " + "It is expected to be a string separated " + "by exactly one %s", pair, keyValDelimiter)); } String val = keyValIter.next(); if (keyValIter.hasNext()) { throw new IllegalArgumentException(String.format("Invalid syntax for key-value pair in list: %s. " + "It is expected to be a string separated " + "by exactly one %s", pair, keyValDelimiter)); } return new KeyValue<>(key, val); }
Source:
<code>public void testToString() { <START> assertEquals( <END> ENTITY_DIMENSION.toString(), "EntityDimension[name='country', longName='country', description='country', dimensionType=ENTITY, dataType=Country, cardinality=SMALL, friendlyName='name']" ); assertEquals( DEGENERATE_DIMENSION.toString(), "DegenerateDimension[columnType=FIELD, name='overallRating', longName='overallRating', description='overallRating', dimensionType=DEGENERATE, dataType=String, cardinality=SMALL, friendlyName='overallRating']" ); assertEquals( TIME_DIMENSION.toString(), "TimeDimension[timeZone=Pacific Standard Time, timeGrain=DAY, columnType=TEMPORAL, name='recordedTime', longName='recordedTime', description='recordedTime', dimensionType=DEGENERATE, dataType=class java.lang.Long, cardinality=LARGE, friendlyName='recordedTime']" ); }</code><technical_language>Do need swap expected actual (and for next well)</technical_language>

Target:
public void testToString() { assertEquals( "EntityDimension[name='country', longName='country', description='country', dimensionType=ENTITY, dataType=Country, cardinality=SMALL, friendlyName='name']", ENTITY_DIMENSION.toString() ); assertEquals( "DegenerateDimension[columnType=FIELD, name='overallRating', longName='overallRating', description='overallRating', dimensionType=DEGENERATE, dataType=String, cardinality=SMALL, friendlyName='overallRating']", DEGENERATE_DIMENSION.toString() ); assertEquals( "TimeDimension[timeZone=Pacific Standard Time, timeGrain=DAY, columnType=TEMPORAL, name='recordedTime', longName='recordedTime', description='recordedTime', dimensionType=DEGENERATE, dataType=class java.lang.Long, cardinality=LARGE, friendlyName='recordedTime']", TIME_DIMENSION.toString() ); }
Source:
<code>public void testRpad() { String rpad = StringUtils.rpad("abc", 7, "de"); Assert.assertEquals("abcdede", rpad); rpad = StringUtils.rpad("abc", 6, "de"); Assert.assertEquals("abcded", rpad); rpad = StringUtils.rpad("abc", 2, "de"); Assert.assertEquals("ab", rpad); rpad = StringUtils.rpad("abc", 0, "de"); Assert.assertEquals("", rpad); rpad = StringUtils.rpad("abc", -1, "de"); Assert.assertNull(rpad); <START> rpad = StringUtils.lpad("abc", 10, ""); <END> Assert.assertNull(rpad); rpad = StringUtils.lpad("abc", 1, ""); Assert.assertNull(rpad); }</code><technical_language>this call rpad()? (same below)</technical_language>

Target:
public void testRpad() { String rpad = StringUtils.rpad("abc", 7, "de"); Assert.assertEquals("abcdede", rpad); rpad = StringUtils.rpad("abc", 6, "de"); Assert.assertEquals("abcded", rpad); rpad = StringUtils.rpad("abc", 2, "de"); Assert.assertEquals("ab", rpad); rpad = StringUtils.rpad("abc", 0, "de"); Assert.assertEquals("", rpad); rpad = StringUtils.rpad("abc", -1, "de"); Assert.assertEquals("", rpad); rpad = StringUtils.rpad("abc", 10, ""); Assert.assertEquals("abc", rpad); rpad = StringUtils.rpad("abc", 1, ""); Assert.assertEquals("a", rpad); }
Source:
<code>static File copyTestFile(String file) throws IOException { File newFile = File.createTempFile(file, "test"); InputStream in = QueueTestUtils.class.getResourceAsStream(file); BufferedSink sink = Okio.buffer(Okio.sink(newFile)); sink.writeAll(Okio.source(in)); <START> sink.flush(); <END> sink.close(); assertTrue(newFile.exists()); return newFile; }</code><technical_language>Close flush. better, try-with-resources</technical_language>

Target:
static File copyTestFile(String file) throws IOException { File newFile = File.createTempFile(file, "test"); InputStream in = QueueTestUtils.class.getResourceAsStream(file); try (BufferedSink sink = Okio.buffer(Okio.sink(newFile))) { sink.writeAll(Okio.source(in)); } assertTrue(newFile.exists()); return newFile; }
Source:
<code>public void testStreamInputPacketIndexInvalidAppend() { fFixture = new StreamInputPacketIndex(); assertTrue(fFixture.append(new PacketStub(0, 0, 1))); assertFalse("Same offset", fFixture.append(new PacketStub(0, 1, 2))); assertFalse("Before", fFixture.append(new PacketStub(1, -1, 0))); assertFalse("Empty", fFixture.append(new PacketStub(1, <START> -1, 0) <END> { @Override public long getContentSizeBits() { return 0; } @Override public long getPayloadStartBits() { return 0; } })); }</code><technical_language>if fails empty of start time</technical_language>

Target:
public void testStreamInputPacketIndexInvalidAppend() { fFixture = new StreamInputPacketIndex(); assertTrue(fFixture.append(new PacketStub(0, 0, 1))); assertFalse("Same offset", fFixture.append(new PacketStub(0, 1, 2))); assertFalse("Before", fFixture.append(new PacketStub(1, -1, 0))); assertFalse("Empty", fFixture.append(new PacketStub(2, 3, 4) { @Override public long getContentSizeBits() { return 0; } @Override public long getPayloadStartBits() { return 0; } })); }
Source:
<code>public String toString() { <START> return "SimpleMethodInvocation [method=" + method + "]"; <END> }</code><technical_language>slight character: java return "SimpleMethodInvocation [method=" + method + ']';</technical_language>

Target:
public String toString() { return "SimpleMethodInvocation [method=" + method + ']'; }
Source:
<code>private void recycleTransactionalProducer(FlinkKafkaInternalProducer<byte[], byte[]> producer) { availableTransactionalIds.add(producer.getTransactionalId()); producer.close(Duration.ofSeconds(0)); <START> } <END></code><technical_language>flush producer here? matter this point this method is invoked committing aborting transactions, I want safe in case this method is called in other places in future</technical_language>

Target:
private void recycleTransactionalProducer(FlinkKafkaInternalProducer<byte[], byte[]> producer) { availableTransactionalIds.add(producer.getTransactionalId()); producer.flush(); producer.close(Duration.ofSeconds(0)); }
Source:
<code>public final String toString() { <START> StackTraceElement element = new StackTraceElement(getClassName(), <END> getMethodName(), getFileName().orElse(null), getLineNumber()); return element.toString(); }</code><technical_language>guarantee non-null, simply construct this. IMO, reasonable do: StackTraceElement element = new StackTraceElement( getClassName().orElse("UnknownClass"), getMethodName().orElse("unknownMethod"), getFileName.orElse(null), getLineNumer.orElse(0));</technical_language>

Target:
public final String toString() { StackTraceElement element = new StackTraceElement( getClassName().orElse("UnknownClass"), getMethodName().orElse("UnknownMethod"), getFileName().orElse(null), getLineNumber().orElse(0)); return element.toString(); }
Source:
<code>public void getProblemFacts() { TestdataAbstractSolutionBasedSolution solution = new TestdataAbstractSolutionBasedSolution(); TestdataValue singleValue = new TestdataValue("sv1"); solution.setSingleValue(singleValue); TestdataValue v1 = new TestdataValue("v1"); TestdataValue v2 = new TestdataValue("v2"); TestdataValue v3 = new TestdataValue("v3"); List<TestdataValue> valueList = Arrays.asList(v1, v2, v3); solution.setValueList(valueList); List<TestdataEntity> entityList = Arrays.asList( new TestdataEntity("e1"), new TestdataEntity("e2"), new TestdataEntity("e3")); solution.setEntityList(entityList); TestdataEntity singleEntity = new TestdataEntity("se1"); solution.setSingleEntity(singleEntity); SimpleScore score = SimpleScore.of(-10); solution.setScore(score); <START> assertThat((Collection<Object>) solution.getProblemFactList()).containsExactly(singleValue, v1, v2, v3); <END> }</code><technical_language>Redundant cast</technical_language>

Target:
public void getProblemFacts() { TestdataAbstractSolutionBasedSolution solution = new TestdataAbstractSolutionBasedSolution(); TestdataValue singleValue = new TestdataValue("sv1"); solution.setSingleValue(singleValue); TestdataValue v1 = new TestdataValue("v1"); TestdataValue v2 = new TestdataValue("v2"); TestdataValue v3 = new TestdataValue("v3"); List<TestdataValue> valueList = Arrays.asList(v1, v2, v3); solution.setValueList(valueList); List<TestdataEntity> entityList = Arrays.asList( new TestdataEntity("e1"), new TestdataEntity("e2"), new TestdataEntity("e3")); solution.setEntityList(entityList); TestdataEntity singleEntity = new TestdataEntity("se1"); solution.setSingleEntity(singleEntity); SimpleScore score = SimpleScore.of(-10); solution.setScore(score); assertThat(solution.getProblemFactList()).containsExactly(singleValue, v1, v2, v3); }
Source:
<code>private void validateNewAssignment(Map<String, List<DatastreamTask>> newAssignmentsByInstance) { if (_config.getMaxDatastreamTasksPerInstance() > 0) { <START> Map<String, Integer> instancesWithTaskCountAboveThreshold = newAssignmentsByInstance.entrySet().stream() <END> .filter(e -> !e.getKey().equals(PAUSED_INSTANCE) && (e.getValue().size() > _config.getMaxDatastreamTasksPerInstance())) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().size())); if (instancesWithTaskCountAboveThreshold.size() > 0) { throw new DatastreamRuntimeException(String.format("Too many tasks assigned to some instances, max tasks per " + "instance: %d, instances above the threshold: %s", _config.getMaxDatastreamTasksPerInstance(), instancesWithTaskCountAboveThreshold)); } } }</code><technical_language>consider assignments if a "quorum" number of instances participating in membership? I find a bi t odd connector max task limit somehow. some connector tasks more memory others</technical_language>

Target:
void validateNewAssignment(Map<String, List<DatastreamTask>> newAssignmentsByInstance) { if (_config.getMaxDatastreamTasksPerInstance() > 0) { Map<String, Integer> instancesWithTaskCountAboveThreshold = newAssignmentsByInstance.entrySet().stream() .filter(e -> !e.getKey().equals(PAUSED_INSTANCE) && (e.getValue().size() > _config.getMaxDatastreamTasksPerInstance())) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().size())); if (instancesWithTaskCountAboveThreshold.size() > 0) { throw new DatastreamRuntimeException(String.format("Too many tasks assigned to some instances, max tasks per " + "instance: %d, instances above the threshold: %s", _config.getMaxDatastreamTasksPerInstance(), instancesWithTaskCountAboveThreshold)); } } }
Source:
<code>public CappedHaplotypeProbabilities(final HaplotypeProbabilities haplotypeProbabilities, double cap) { super(haplotypeProbabilities.getHaplotype()); this.cap = cap; final double[] logLikelihoods = haplotypeProbabilities.getLogLikelihoods(); final double max = MathUtil.max(logLikelihoods); <START> final double[] cappedLogLikelihoods = MathUtil.sum(logLikelihoods,-max); <END> this.setLogLikelihoods(MathUtil.max(cappedLogLikelihoods,cap)); }</code><technical_language>whitespace, suggestion final double[] cappedLogLikelihoods = MathUtil.sum(logLikelihoods, -max);</technical_language>

Target:
public CappedHaplotypeProbabilities(final HaplotypeProbabilities haplotypeProbabilities, double cap) { super(haplotypeProbabilities.getHaplotype()); this.cap = cap; final double[] logLikelihoods = haplotypeProbabilities.getLogLikelihoods(); final double[] cappedLogLikelihoods = MathUtil.subtractMax(logLikelihoods); this.setLogLikelihoods(MathUtil.capFromBelow(cappedLogLikelihoods, cap)); }
Source:
<code>@Test public void successWithHeaders() { Object body = new Object(); <START> Response<Object> response = Response.success(body, Headers.of("foo", "bar")); <END> assertThat(response.raw()).isNotNull(); assertThat(response.code()).isEqualTo(200); assertThat(response.message()).isEqualTo("OK"); assertThat(response.headers().size()).isEqualTo(1); assertThat(response.headers().get("foo")).isEqualTo("bar"); assertThat(response.isSuccess()).isTrue(); assertThat(response.body()).isSameAs(body); assertThat(response.errorBody()).isNull(); }</code><technical_language>prefer if put Headers in a local isSameAs is done body</technical_language>

Target:
@Test public void successWithHeaders() { Object body = new Object(); Headers headers = Headers.of("foo", "bar"); Response<Object> response = Response.success(body, headers); assertThat(response.raw()).isNotNull(); assertThat(response.code()).isEqualTo(200); assertThat(response.message()).isEqualTo("OK"); assertThat(response.headers().size()).isEqualTo(1); assertThat(response.headers().get("foo")).isSameAs("bar"); assertThat(response.isSuccess()).isTrue(); assertThat(response.body()).isSameAs(body); assertThat(response.errorBody()).isNull(); }
Source:
<code>ClientConnectionManager newClientConnectionManager(HttpParams params, X509HostnameVerifier verifier, SSLContext context, Closer closer) throws NoSuchAlgorithmException, KeyManagementException { SchemeRegistry schemeRegistry = new SchemeRegistry(); <START> Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); <END> SSLSocketFactory sf = new SSLSocketFactory(context); sf.setHostnameVerifier(verifier); Scheme https = new Scheme("https", sf, 443); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", sf, 443)); final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); closer.addToClose(new Closeable() { @Override public void close() throws IOException { cm.shutdown(); } }); return cm; }</code><technical_language>@demobox This line removed http is registered inline line 135</technical_language>

Target:
ClientConnectionManager newClientConnectionManager(HttpParams params, X509HostnameVerifier verifier, SSLContext context, Closer closer) throws NoSuchAlgorithmException, KeyManagementException { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sf = new SSLSocketFactory(context); sf.setHostnameVerifier(verifier); schemeRegistry.register(new Scheme("https", sf, 443)); final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); closer.addToClose(new Closeable() { @Override public void close() throws IOException { cm.shutdown(); } }); return cm; }
Source:
<code>boolean removeKeysById(int grpId, Set<Integer> ids) { <START> return removeKeysById(grpKeys.get(grpId), ids); <END> }</code><technical_language>removeKeysById(List<GroupKey> keys, Set<Integer> ids) is redundant, replaced removeIf(key -> ids.contains(key.unsignedId())); for example: grpKeys.get(grpId).removeIf(key -> ids.contains(key.unsignedId())); Also, do need check grpKeys.get(grpId) for null</technical_language>

Target:
boolean removeKeysById(int grpId, Set<Integer> ids) { List<GroupKey> keys = grpKeys.get(grpId); if (F.isEmpty(keys)) return false; return keys.subList(1, keys.size()).removeIf(key -> ids.contains(key.unsignedId())); }
Source:
<code>public long getTimeTillUpdate(long currMediaTime) { long next = super.getTimeTillUpdate(currMediaTime); if (monitorThread == null) return next; <START> if (next == sage.Sage.MILLIS_PER_WEEK) <END> { inDemand = currMediaTime; synchronized (srtLock) { if (inDemand != -1) { loadSubtitlesFromFiles(); } next = super.getTimeTillUpdate(currMediaTime); } if (next == sage.Sage.MILLIS_PER_WEEK) { next = 1000; subEntryPos = -1; } } return next; }</code><technical_language>suggest changing this another constant NO_MORE_SUBS_LONG_WAIT changing other places in subtitle classes match that, interdependence more clear</technical_language>

Target:
public long getTimeTillUpdate(long currMediaTime) { long next = super.getTimeTillUpdate(currMediaTime); if (monitorThread == null) return next; if (next == NO_MORE_SUBS_LONG_WAIT) { inDemand = currMediaTime; synchronized (srtLock) { if (inDemand != -1) { loadSubtitlesFromFiles(); } next = super.getTimeTillUpdate(currMediaTime); } if (next == NO_MORE_SUBS_LONG_WAIT) { next = 1000; subEntryPos = -1; } } return next; }
Source:
<code>public Response execute(Command command) throws WebDriverException { if (DriverCommand.NEW_SESSION.equals(command.getName())) { serviceOptional.ifPresent(driverService -> { try { driverService.start(); } catch (IOException e) { throw new WebDriverException(e.getMessage(), e); } }); } Response response; try { for (IDriverCommandListener listener : listeners) { listener.beforeEvent(command); } <START> if (command.getName().equals("newSession")) { <END> LOGGER.info("New session request. Parameters: ".concat(command.getParameters().toString())); } response = super.execute(command); for (IDriverCommandListener listener : listeners) { listener.afterEvent(command); } } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); if (rootCause instanceof ConnectException && rootCause.getMessage().contains("Connection refused")) { throw serviceOptional.map(service -> { if (service.isRunning()) { return new WebDriverException("The session is closed!", rootCause); } return new WebDriverException("The appium server has accidentally died!", rootCause); }).orElseGet((Supplier<WebDriverException>) () -> new WebDriverException(rootCause.getMessage(), rootCause)); } throw new WebDriverException(t); } finally { if (DriverCommand.QUIT.equals(command.getName())) { serviceOptional.ifPresent(DriverService::stop); } } if (DriverCommand.NEW_SESSION.equals(command.getName()) && getCommandCodec() instanceof W3CHttpCommandCodec) { setCommandCodec(new AppiumW3CHttpCommandCodec()); getAdditionalCommands().forEach(this::defineCommand); } return response; }</code><technical_language>do need it? hide debug level</technical_language>

Target:
public Response execute(Command command) throws WebDriverException { if (DriverCommand.NEW_SESSION.equals(command.getName())) { serviceOptional.ifPresent(driverService -> { try { driverService.start(); } catch (IOException e) { throw new WebDriverException(e.getMessage(), e); } }); } Response response; try { for (IDriverCommandListener listener : listeners) { listener.beforeEvent(command); } response = super.execute(command); for (IDriverCommandListener listener : listeners) { listener.afterEvent(command); } } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); if (rootCause instanceof ConnectException && rootCause.getMessage().contains("Connection refused")) { throw serviceOptional.map(service -> { if (service.isRunning()) { return new WebDriverException("The session is closed!", rootCause); } return new WebDriverException("The appium server has accidentally died!", rootCause); }).orElseGet((Supplier<WebDriverException>) () -> new WebDriverException(rootCause.getMessage(), rootCause)); } throw new WebDriverException(t); } finally { if (DriverCommand.QUIT.equals(command.getName())) { serviceOptional.ifPresent(DriverService::stop); } } if (DriverCommand.NEW_SESSION.equals(command.getName()) && getCommandCodec() instanceof W3CHttpCommandCodec) { setCommandCodec(new AppiumW3CHttpCommandCodec()); getAdditionalCommands().forEach(this::defineCommand); } return response; }
Source:
<code>public void setReportTitle(String reportTitle) { this.reportTitle = reportTitle; <START> this.directoryQualifier = reportTitle.replaceAll("[^A-Za-z0-9@+-_.,~]", "_"); <END> }</code><technical_language>Risky, read <LINK_0></technical_language>

Target:
public void setReportTitle(String reportTitle) { this.reportTitle = StringUtils.isEmpty(reportTitle) ? "" : reportTitle.trim(); }
Source:
<code>private void releaseCurrentSortBuffer() { if (currentSortBuffer != null) { currentSortBuffer.release(); <START> currentSortBuffer = null; <END> } }</code><technical_language>I guess this call is necessary. current sort buffer in followup small data flushing large record file directly</technical_language>

Target:
private void releaseCurrentSortBuffer() { if (currentSortBuffer != null) { currentSortBuffer.release(); } }
Source:
<code>public void testInstanceIdIsSet() throws Exception { final CountDownLatch latch = new CountDownLatch(1); ThreadSpyAuditWrapper wrapper = new ThreadSpyAuditWrapper( latch ); String expected = UUID.randomUUID().toString(); PentahoAsyncReportExecution execution = new PentahoAsyncReportExecution( url, component, handler, session, expected, wrapper ); PentahoAsyncExecutor executor = new PentahoAsyncExecutor( 2 ); executor.addTask( execution, session ); <START> latch.await( 10, TimeUnit.DAYS ); <END> assertEquals( expected, wrapper.capturedId ); }</code><technical_language>Do want wait 10 days</technical_language>

Target:
public void testInstanceIdIsSet() throws Exception { final CountDownLatch latch = new CountDownLatch(1); ThreadSpyAuditWrapper wrapper = new ThreadSpyAuditWrapper( latch ); String expected = UUID.randomUUID().toString(); PentahoAsyncReportExecution execution = new PentahoAsyncReportExecution( url, component, handler, session, expected, wrapper ); PentahoAsyncExecutor executor = new PentahoAsyncExecutor( 2 ); executor.addTask( execution, session ); latch.await( 10, TimeUnit.SECONDS ); assertEquals( expected, wrapper.capturedId ); }
Source:
<code><START> public void downloadPackageWithScope(@RepositoryMapping Repository repository, <END> @PathVariable(name = "packageScope") String packageScope, @PathVariable(name = "packageName") String packageName, @PathVariable(name = "packageNameWithVersion") String packageNameWithVersion, @PathVariable(name = "packageExtension") String packageExtension, @RequestHeader HttpHeaders httpHeaders, HttpServletRequest request, HttpServletResponse response) throws Exception { final String storageId = repository.getStorage().getId(); final String repositoryId = repository.getId(); String pattern = packageName + "-"; final String packageVersion = packageNameWithVersion.replaceAll(pattern, ""); NpmArtifactCoordinates coordinates; try { coordinates = NpmArtifactCoordinates.of(String.format("%s/%s", packageScope, packageName), packageVersion); } catch (IllegalArgumentException e) { response.setStatus(HttpStatus.BAD_REQUEST.value()); response.getWriter().write(e.getMessage()); return; } RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath()); provideArtifactDownloadResponse(request, response, httpHeaders, path); }</code><technical_language>@pyashwanthkumar please fix downloadPackage well</technical_language>

Target:
public void downloadPackageWithScope(@RepositoryMapping Repository repository, @PathVariable(name = "packageScope") String packageScope, @PathVariable(name = "packageName") String packageName, @PathVariable(name = "packageNameWithVersion") String packageNameWithVersion, @PathVariable(name = "packageExtension") String packageExtension, @RequestHeader HttpHeaders httpHeaders, HttpServletRequest request, HttpServletResponse response) throws Exception { final String storageId = repository.getStorage().getId(); final String repositoryId = repository.getId(); if (!packageNameWithVersion.startsWith(packageName + "-")) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } final String packageVersion = getPackageVersion(packageNameWithVersion, packageName); NpmArtifactCoordinates coordinates; try { coordinates = NpmArtifactCoordinates.of(String.format("%s/%s", packageScope, packageName), packageVersion); } catch (IllegalArgumentException e) { response.setStatus(HttpStatus.BAD_REQUEST.value()); response.getWriter().write(e.getMessage()); return; } RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath()); provideArtifactDownloadResponse(request, response, httpHeaders, path); }
Source:
<code>public int compareTo(QC t) { <START> if (getId() != 0L && t.getId() != 0L) { <END> if (getId() < t.getId()) return -1; if (getId() > t.getId()) return 1; } else if (getQcType() != null && t.getQcType() != null && getQcDate() != null && t.getQcDate() != null) { int type = getQcType().compareTo(t.getQcType()); if (type != 0) return type; int creator = getQcDate().compareTo(t.getQcDate()); if (creator != 0) return creator; } return 0; }</code><technical_language>AbstractQC.UNSAVED_ID instead of hard-coding 0L. in impl class versions</technical_language>

Target:
public int compareTo(QC t) { if (getId() != AbstractQC.UNSAVED_ID && t.getId() != AbstractQC.UNSAVED_ID) { if (getId() < t.getId()) return -1; if (getId() > t.getId()) return 1; } else if (getQcType() != null && t.getQcType() != null && getQcDate() != null && t.getQcDate() != null) { int type = getQcType().compareTo(t.getQcType()); if (type != 0) return type; int creator = getQcDate().compareTo(t.getQcDate()); if (creator != 0) return creator; } return 0; }
Source:
<code>Set<Broadcast> mergeBroadcastContinuations( Collection<Broadcast> broadcasts ) { return broadcasts.stream() .sorted(Comparator.comparing(Broadcast::getTransmissionEndTime)) .collect( Collector.<Broadcast, ListMultimap<Id, Broadcast>, Set<Broadcast>>of( ArrayListMultimap::create, this::accumulateBroadcastContinuations, this::combineBroadcastContinuations, <START> m -> ImmutableSet.copyOf(m.values()))); <END> }</code><technical_language>naming: expand 'm', I idea means</technical_language>

Target:
Set<Broadcast> mergeBroadcastContinuations(Collection<Broadcast> broadcasts) { return broadcasts.stream() .sorted(Comparator.comparing(Broadcast::getTransmissionEndTime)) .collect( Collector.<Broadcast, ListMultimap<Id, Broadcast>, Set<Broadcast>>of( ArrayListMultimap::create, this::accumulateBroadcastContinuations, this::combineBroadcastContinuations, channelId2broadcasts -> ImmutableSet.copyOf(channelId2broadcasts.values()))); }
Source:
<code>public InlineAnnotatedMethods() { JAnnotationMethod removeAfter = (JAnnotationMethod) forceInlineAnnotationType.getMethod(REMOVE_AFTER_ANNOTATION, JPrimitiveTypeEnum.BOOLEAN.getType(), new ArrayList<JType>(0)); JBooleanLiteral defaultValue = (JBooleanLiteral) removeAfter.getDefaultValue(); removeAfterDefault = <START> defaultValue.getValue(); <END> }</code><technical_language>Missing assert FindBugs happy assert defaultValue != null thinking this, this null DefaultValueAnnotationAdder removes default literal values (actually moves a separate annotation) schedulable in plan. IMO solutions: 1) Add a constraint 'need = { ..., AnnotationMethodDefaultValue.class}' run DefaultValueAnnotationAdder move schedulable in plan DefaultValueAnnotationAdder. 2) If default is annotation method (null), find special annotation added DefaultValueAnnotationAdder (if exists). API use. I prefer option 2) 1) faster do</technical_language>

Target:
public InlineAnnotatedMethods() { JAnnotationMethod removeAfter = (JAnnotationMethod) forceInlineAnnotationType.getMethod(REMOVE_AFTER_ANNOTATION, JPrimitiveTypeEnum.BOOLEAN.getType(), new ArrayList<JType>(0)); assert removeAfter != null; JBooleanLiteral defaultValue = (JBooleanLiteral) removeAfter.getDefaultValue(); assert defaultValue != null; removeAfterDefault = defaultValue.getValue(); }
Source:
<code>public void shouldNotifyListenerWhenNewLogIsCreated() throws Exception { final CountDownLatch allowRotationComplete = new CountDownLatch( 1 ); final CountDownLatch rotationComplete = new CountDownLatch( 1 ); String outputFileCreatedMessage = "Output file created"; String rotationCompleteMessage = "Rotation complete"; RotationListener rotationListener = spy( new RotationListener() { @Override public void outputFileCreated( OutputStream out ) { try { allowRotationComplete.await( 1L, TimeUnit.SECONDS ); out.write( outputFileCreatedMessage.getBytes() ); } catch ( InterruptedException | IOException e ) { throw new RuntimeException( e ); } } @Override public void rotationCompleted( OutputStream out ) { rotationComplete.countDown(); try { out.write( rotationCompleteMessage.getBytes() ); } catch ( IOException e ) { throw new RuntimeException( e ); } } } ); <START> ExecutorService rotationExecutor = Executors.newSingleThreadExecutor(); <END> RotatingFileOutputStreamSupplier supplier = new RotatingFileOutputStreamSupplier( fileSystem, logFile, 10, 0, 10, rotationExecutor, rotationListener ); write( supplier, "A string longer than 10 bytes" ); write( supplier, "A string longer than 10 bytes" ); allowRotationComplete.countDown(); rotationComplete.await( 1L, TimeUnit.SECONDS ); verify( rotationListener ).outputFileCreated( any( OutputStream.class ) ); verify( rotationListener ).rotationCompleted( any( OutputStream.class ) ); shutDownExecutor( rotationExecutor ); }</code><technical_language>this more correct wrapping try...finally block</technical_language>

Target:
public void shouldNotifyListenerWhenNewLogIsCreated() throws Exception { final CountDownLatch allowRotationComplete = new CountDownLatch( 1 ); final CountDownLatch rotationComplete = new CountDownLatch( 1 ); String outputFileCreatedMessage = "Output file created"; String rotationCompleteMessage = "Rotation complete"; RotationListener rotationListener = spy( new RotationListener() { @Override public void outputFileCreated( OutputStream out ) { try { allowRotationComplete.await( 1L, TimeUnit.SECONDS ); out.write( outputFileCreatedMessage.getBytes() ); } catch ( InterruptedException | IOException e ) { throw new RuntimeException( e ); } } @Override public void rotationCompleted( OutputStream out ) { rotationComplete.countDown(); try { out.write( rotationCompleteMessage.getBytes() ); } catch ( IOException e ) { throw new RuntimeException( e ); } } } ); ExecutorService rotationExecutor = Executors.newSingleThreadExecutor(); try { RotatingFileOutputStreamSupplier supplier = new RotatingFileOutputStreamSupplier( fileSystem, logFile, 10, 0, 10, rotationExecutor, rotationListener ); write( supplier, "A string longer than 10 bytes" ); write( supplier, "A string longer than 10 bytes" ); allowRotationComplete.countDown(); rotationComplete.await( 1L, TimeUnit.SECONDS ); verify( rotationListener ).outputFileCreated( any( OutputStream.class ) ); verify( rotationListener ).rotationCompleted( any( OutputStream.class ) ); } finally { shutDownExecutor( rotationExecutor ); } }