auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Collection<Diagram> evaluate(EObject source, IParameterValueList2 parameterValues, IFacetManager facetManager) throws DerivedTypedElementException { List<Diagram> result = new ArrayList<Diagram>(); Collection<Setting> settings = <START> EMFHelper.getUsages(source); <END> if (settings != null) { for (Setting setting : settings) { Diagram diagram = NotationUtils.getDiagramFromRef(setting.getEObject(), source); if (diagram != null) { result.add(diagram); } } } return result; }</code><technical_language>getUsages() is scanning *navigable* inverse references, is useless in this case (and costly), reference diagrams for non-navigable (or ECrossReferenceAdapter in place)</technical_language>

Target:
public Collection<Diagram> evaluate(EObject source, IParameterValueList2 parameterValues, IFacetManager facetManager) throws DerivedTypedElementException { List<Diagram> result = new ArrayList<Diagram>(); Collection<Setting> settings = EMFHelper.getUsages(source); if (settings != null) { for (Setting setting : settings) { Diagram diagram = NotationUtils.getOwnedDiagram(setting.getEObject(), source); if (diagram != null) { result.add(diagram); } } } return result; }
Source:
<code>private static List<License> getLicenses() { LicenseService.Iface licenseClient = new ThriftClients().makeLicenseClient(); try { return licenseClient.getLicenses(); } catch (TException e) { LOGGER.error("Could not get license: " + e.getMessage(), e); <START> return null; <END> } }</code><technical_language>I report generation fail if information is available, instead of (from view of caller) silently succeeding</technical_language>

Target:
private static List<License> getLicenses() throws TException { LicenseService.Iface licenseClient = new ThriftClients().makeLicenseClient(); return licenseClient.getLicenses(); }
Source:
<code>public void testClosingAlreadyClosedJob() { try { TSalesforceInputProperties properties = createTSalesforceInputProperties(false, true); properties.manualQuery.setValue(false); SalesforceBulkQueryInputReader reader = (SalesforceBulkQueryInputReader) this.<IndexedRecord>createBoundedReader(properties); boolean hasRecord = reader.start(); List<IndexedRecord> rows = new ArrayList<>(); while (hasRecord) { IndexedRecord unenforced = reader.getCurrent(); rows.add(unenforced); hasRecord = reader.advance(); <START> } <END> reader.close(); reader.close(); } catch(Throwable t) { Assert.fail("This test shouldn't throw any errors, since we're closing already closed job"); } }</code><technical_language>Do need read lines test this functionality? This a bit more time execute test perform some communication salesforce servers, bad for us(more traffic, some Salesforce limits reached). if start close reader - care is salesforce side. ok, if do it</technical_language>

Target:
public void testClosingAlreadyClosedJob() { try { TSalesforceInputProperties properties = createTSalesforceInputProperties(false, true); properties.manualQuery.setValue(false); SalesforceBulkQueryInputReader reader = (SalesforceBulkQueryInputReader) this.<IndexedRecord>createBoundedReader(properties); reader.start(); reader.close(); reader.close(); } catch(Throwable t) { Assert.fail("This test shouldn't throw any errors, since we're closing already closed job"); } }
Source:
<code>protected void doAfterSelectionChange(final int uiRowIndex, final int uiColumnIndex) { if (getModel().getSelectedCells().stream().map(GridData.SelectedCell::getRowIndex).distinct().count() > 1) { super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); return; } if (getModel().getSelectedHeaderCells().size() > 0) { super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); return; <START> } <END> if (uiRowIndex < model.getRowCount() - 1) { if (expression.isPresent()) { final Context context = expression.get(); fireDomainObjectSelectionEvent(context.getContextEntry().get(uiRowIndex).getVariable()); return; } } super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); }</code><technical_language>Personally, I a long condition line super.doAfterSelectionChange(..) twice: java if (getModel().getSelectedCells().stream().map(GridData.SelectedCell::getRowIndex).distinct().count() > 1 || getModel().getSelectedHeaderCells().size() > 0) { super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); return; } ..or maybe, extract conditions: java if (hasSelectedCells() || hasSelectedHeader()) { super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); return; } But, feel free is ;-)</technical_language>

Target:
protected void doAfterSelectionChange(final int uiRowIndex, final int uiColumnIndex) { if (hasAnyHeaderCellSelected() || hasMultipleRowsSelected()) { super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); return; } if (uiRowIndex < model.getRowCount() - 1) { if (expression.isPresent()) { final Context context = expression.get(); fireDomainObjectSelectionEvent(context.getContextEntry().get(uiRowIndex).getVariable()); return; } } super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); }
Source:
<code>public void testMergeTuplesSorted() throws DbException { TupleBatchBuffer[] randomTuples = new TupleBatchBuffer[3]; randomTuples[0] = generateRandomTuples(123, true); randomTuples[1] = generateRandomTuples(42, true); randomTuples[2] = generateRandomTuples(99, true); TupleSource[] children = new TupleSource[3]; children[0] = new TupleSource(randomTuples[0]); children[1] = new TupleSource(randomTuples[1]); children[2] = new TupleSource(randomTuples[2]); NAryOperator merge = new Merge(children, new int[] { 0 }, new boolean[] { true }); merge.open(null); TupleBatch tb; ArrayList<Long> idCollector = new ArrayList<Long>(); while (!merge.eos()) { tb = merge.nextReady(); if (tb != null) { for (int i = 0; i < tb.numTuples(); i++) { idCollector.add(tb.getLong(0, i)); } } } merge.close(); Long previous = null; for (Long index : idCollector) { if (previous != null) { <START> assertEquals(true, previous <= index); <END> } previous = index; } }</code><technical_language>I assertTrue(x) is a shorthand for assertEquals(true, x)</technical_language>

Target:
public void testMergeTuplesSorted() throws DbException { TupleBatchBuffer[] randomTuples = new TupleBatchBuffer[3]; randomTuples[0] = generateRandomTuples(52300, true); randomTuples[1] = generateRandomTuples(14200, true); randomTuples[2] = generateRandomTuples(29900, true); TupleSource[] children = new TupleSource[3]; children[0] = new TupleSource(randomTuples[0]); children[1] = new TupleSource(randomTuples[1]); children[2] = new TupleSource(randomTuples[2]); NAryOperator merge = new Merge(children, new int[] { 0, 1 }, new boolean[] { true, true }); merge.open(null); TupleBatch tb; final ArrayList<Entry<Long, String>> entries = new ArrayList<Entry<Long, String>>(); while (!merge.eos()) { tb = merge.nextReady(); if (tb != null) { for (int i = 0; i < tb.numTuples(); i++) { entries.add(new SimpleEntry<Long, String>(tb.getLong(0, i), tb.getString(1, i))); } } } merge.close(); assertEquals(52300 + 14200 + 29900, entries.size()); Comparator<Entry<Long, String>> comparator = new EntryComparator(); Entry<Long, String> previous = null; for (Entry<Long, String> entry : entries) { if (previous != null) { assertTrue(comparator.compare(previous, entry) <= 0); } previous = entry; } }
Source:
<code>public void testTransformWithoutIdParam() throws IOException, CatalogTransformerException { Metacard metacard = transformer.transform(new ByteArrayInputStream(sampleBasicMetacard().getBytes())); <START> assertThat("ddf.metacard", is(metacard.getMetacardType().getName())); <END> assertThat("myId", is(metacard.getId())); }</code><technical_language>Please correct order of parameters in usages of assertThat. actual expected second. assertThat(actual, is(expected)), for example. for this specifically: assertThat(metacard.getMetacardType().getName(), is("ddf.metacard"))</technical_language>

Target:
public void testTransformWithoutIdParam() throws IOException, CatalogTransformerException { Metacard metacard = transformer.transform(new ByteArrayInputStream(sampleJsonExtensibleA().getBytes())); assertThat(metacard.getMetacardType().getName(), is("MetacardTypeA")); assertThat(metacard.getId(), is(DEFAULT_ID)); }
Source:
<code>public void theDeviceDebugInformationShouldBeEnabled() throws Throwable { <START> final DlmsDevice device = dlmsDeviceRepository.findByDeviceIdentification(PROPERTIES_MAP.put( <END> Keys.KEY_DEVICE_IDENTIFICATION, ScenarioContext.Current().get(Keys.KEY_DEVICE_IDENTIFICATION) .toString())); assertTrue("Debug mode", device.isInDebugMode()); }</code><technical_language>Is PROPERTIES_MAP.put() needed in this step? get device identification ScenarioContext? split this line increase readability</technical_language>

Target:
public void theDeviceDebugInformationShouldBeEnabled() throws Throwable { final DlmsDevice device = dlmsDeviceRepository.findByDeviceIdentification(ScenarioContext.Current() .get(Keys.KEY_DEVICE_IDENTIFICATION).toString()); assertTrue("Debug mode", device.isInDebugMode()); }
Source:
<code>public PortfolioItemSummary summarize() { StringBuilder buf = new StringBuilder(96); IborCapFloorLeg mainLeg = product.getCapFloorLeg(); buf.append(SummarizerUtils.datePeriod(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); buf.append(' '); buf.append(SummarizerUtils.amount(mainLeg.getCurrency(), mainLeg.getNotional().getInitialValue())); buf.append(' '); if (mainLeg.getPayReceive().isReceive()) { buf.append("Rec "); summarizeMainLeg(mainLeg, buf); buf.append(getPremium().isPresent() ? " / Pay Premium" : (product.getPayLeg().isPresent() ? " / Pay Periodic" : "")); } else { buf.append("Rec "); <START> buf.append(getPremium().isPresent() ? "Premium" : (product.getPayLeg().isPresent() ? "Periodic" : "")); <END> buf.append(" / Pay "); summarizeMainLeg(mainLeg, buf); } buf.append(" : "); buf.append(SummarizerUtils.dateRange(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); return SummarizerUtils.summary(this, ProductType.IBOR_CAP_FLOOR, buf.toString(), mainLeg.getCurrency()); }</code><technical_language>"Rec" populated if premium is present, similar pay premium? "Rec / Pay 5Y ...." right</technical_language>

Target:
public PortfolioItemSummary summarize() { StringBuilder buf = new StringBuilder(96); IborCapFloorLeg mainLeg = product.getCapFloorLeg(); buf.append(SummarizerUtils.datePeriod(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); buf.append(' '); buf.append(SummarizerUtils.amount(mainLeg.getCurrency(), mainLeg.getNotional().getInitialValue())); buf.append(' '); if (mainLeg.getPayReceive().isReceive()) { buf.append("Rec "); summarizeMainLeg(mainLeg, buf); buf.append(getPremium().isPresent() ? " / Pay Premium" : (product.getPayLeg().isPresent() ? " / Pay Periodic" : "")); } else { buf.append( getPremium().isPresent() ? "Rec Premium / Pay " : (product.getPayLeg().isPresent() ? "Rec Periodic / Pay " : "")); summarizeMainLeg(mainLeg, buf); } buf.append(" : "); buf.append(SummarizerUtils.dateRange(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); return SummarizerUtils.summary(this, ProductType.IBOR_CAP_FLOOR, buf.toString(), mainLeg.getCurrency()); }
Source:
<code>private List<String> getCommandLines(File file) { try { return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); } catch (IOException e1) { <START> return Collections.emptyList(); <END> } }</code><technical_language>This is behavior change</technical_language>

Target:
private List<String> getCommandLines(File file) { try { return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalStateException("Failed to process file " + file.getAbsolutePath(), e); } }
Source:
<code>public CompletableFuture<Map<K, V>> getAllAsync(List<K> keys) { Preconditions.checkNotNull(keys); if (keys.isEmpty()) { return CompletableFuture.completedFuture(Collections.EMPTY_MAP); } readMetrics.numGetAlls.inc(); return asyncHelper.execute(keys, readFn::getAllAsync, readMetrics.getAllNs) .handle((result, e) -> { if (e != null) { throw new SamzaException("Failed to get the records for " + keys, e); } else { <START> if (result != null && result.size() != keys.size()) { <END> throw new SamzaException("Received insufficient records for " + keys); } } return result; }); }</code><technical_language>In theory this happen. do throw here</technical_language>

Target:
public CompletableFuture<Map<K, V>> getAllAsync(List<K> keys) { Preconditions.checkNotNull(keys); if (keys.isEmpty()) { return CompletableFuture.completedFuture(Collections.EMPTY_MAP); } readMetrics.numGetAlls.inc(); return execute(readRateLimiter, keys, readFn::getAllAsync, readMetrics.getAllNs) .handle((result, e) -> { if (e != null) { throw new SamzaException("Failed to get the records for " + keys, e); } return result; }); }
Source:
<code>public static Collection<Object[]> comparisonParameters() { return Arrays.asList(new Object[][] { { null, null, 0 }, { null, "", -1 }, { "", "", 0 }, { "", "123", -1 }, { "123", "abc", -1 }, { "123", "123", 0 }, { "012", "12", -1 }, { "2", "10", -1 }, { "abc", "abc", 0 }, { "abc", "def", -1 }, { "abc012", "abc012", 0 }, { "abc2", "abc10", -1 }, { "abc012def", "abc012def", 0 }, { "abc012def", "abc012ghi", -1 }, <START> { "abc2def", "abc10def", -1 } <END> }); }</code><technical_language>mind adding: 012abc 012ab</technical_language>

Target:
public static Collection<Object[]> comparisonParameters() { return Arrays.asList(new Object[][] { { null, null, 0 }, { null, "", -1 }, { "", "", 0 }, { "", "123", -1 }, { "123", "123", 0 }, { "123", "456", -1 }, { "12", "123", -1 }, { "012", "12", -1 }, { "2", "10", -1 }, { "123abc", "123abc", 0 }, { "123abc", "456abc", -1 }, { "12abc", "123abc", -1 }, { "012abc", "12abc", -1 }, { "2abc", "10abc", -1 }, { "123", "abc", -1 }, { "abc", "abc", 0 }, { "abc", "def", -1 }, { "ab", "abc", -1 }, { "123abc", "123def", -1 }, { "123ab", "123abc", -1 }, { "abc123", "abc123", 0 }, { "abc123", "def123", -1 }, { "ab123", "abc123", -1 }, { "abc123", "abc456", -1 }, { "abc12", "abc123", -1 }, { "abc012", "abc12", -1 }, { "abc2", "abc10", -1 }, { "abc123def", "abc123def", 0 }, { "abc123def", "abc123ghi", -1 }, { "abc123de", "abc123def", -1 } }); }
Source:
<code>private void updateDictionaryLocked(boolean mutable) { if (data == null) { root = null; internalDict = mutable ? new MutableDictionary() : new Dictionary(); return; } final Database db = getDatabase(); if (db == null) { throw new IllegalStateException(""); } <START> final MRoot newRoot = new MRoot(new DocContext(db, c4Document), data.toFLValue(), isMutable()); <END> root = newRoot; synchronized (db.getLock()) { internalDict = (Dictionary) newRoot.asNative(); } }</code><technical_language>mutable passed argument instead</technical_language>

Target:
private void updateDictionaryLocked(boolean mutable) { if (data == null) { root = null; internalDict = mutable ? new MutableDictionary() : new Dictionary(); return; } final Database db = getDatabase(); if (db == null) { throw new IllegalStateException(""); } final MRoot newRoot = new MRoot(new DocContext(db, c4Document), data.toFLValue(), mutable); root = newRoot; synchronized (db.getLock()) { internalDict = (Dictionary) newRoot.asNative(); } }
Source:
<code>public void testConfigurationBindingListener() { List<ConfigurationBinding<?>> seenBindings = new ArrayList<>(); Module module = binder -> { ConfigBinder configBinder = configBinder(binder); configBinder.bindConfig(AnotherConfig.class); <START> configBinder.bindConfigurationBindingListener((configurationBinding, configBinder1) -> { <END> seenBindings.add(configurationBinding); configBinder1.bindConfig(Config1.class); configBinder1.bindConfig(Config1.class, MyAnnotation.class); }); }; Injector injector = createInjector(properties, module); verifyConfig(injector.getInstance(Config1.class)); verifyConfig(injector.getInstance(Key.get(Config1.class, MyAnnotation.class))); assertEquals(seenBindings.size(), 3); assertEquals( ImmutableSet.copyOf(seenBindings), ImmutableSet.of( new ConfigurationBinding<>(Key.get(Config1.class), Config1.class, Optional.empty()), new ConfigurationBinding<>(Key.get(Config1.class, MyAnnotation.class), Config1.class, Optional.empty()), new ConfigurationBinding<>(Key.get(AnotherConfig.class), AnotherConfig.class, Optional.empty()))); }</code><technical_language>configBinder1 -> listenerBinder</technical_language>

Target:
public void testConfigurationBindingListener() { List<ConfigurationBinding<?>> seenBindings = new ArrayList<>(); Module module = binder -> { ConfigBinder configBinder = configBinder(binder); configBinder.bindConfig(AnotherConfig.class); configBinder.bindConfigurationBindingListener((configurationBinding, callbackConfigBinder) -> { seenBindings.add(configurationBinding); callbackConfigBinder.bindConfig(Config1.class); callbackConfigBinder.bindConfig(Config1.class, MyAnnotation.class); }); }; Injector injector = createInjector(properties, module); verifyConfig(injector.getInstance(Config1.class)); verifyConfig(injector.getInstance(Key.get(Config1.class, MyAnnotation.class))); assertEquals(seenBindings.size(), 3); assertEquals( ImmutableSet.copyOf(seenBindings), ImmutableSet.of( new ConfigurationBinding<>(Key.get(Config1.class), Config1.class, Optional.empty()), new ConfigurationBinding<>(Key.get(Config1.class, MyAnnotation.class), Config1.class, Optional.empty()), new ConfigurationBinding<>(Key.get(AnotherConfig.class), AnotherConfig.class, Optional.empty()))); }
Source:
<code>public void testReadUnencoded() { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.memory().storageType(StorageType.OFF_HEAP); withCacheManager(new CacheManagerCallable( createCacheManager(TestDataSCI.INSTANCE, cfg)) { @Override public void call() { cm.getClassWhiteList().addClasses(Person.class); Cache<String, Person> cache = cm.getCache(); DataConversion conversion = cache.getAdvancedCache().getValueDataConversion(); <START> Function<Object, byte[]> asStored = s -> (byte[]) conversion.convert(s, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM); <END> Person value = new Person(); cache.put("1", value); assertEquals(cache.get("1"), value); Cache<?, ?> unencodedCache = cache.getAdvancedCache().withStorageMediaType(); assertEquals(unencodedCache.get(asStored.apply("1")), asStored.apply(value)); } }); }</code><technical_language>A method clearer IMO</technical_language>

Target:
public void testReadUnencoded() { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.memory().storageType(StorageType.OFF_HEAP); withCacheManager(new CacheManagerCallable( createCacheManager(TestDataSCI.INSTANCE, cfg)) { private final DataConversion conversion = cm.getCache().getAdvancedCache().getValueDataConversion(); public Object asStored(Object object) { return conversion.convert(object, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM); } @Override public void call() { cm.getClassWhiteList().addClasses(Person.class); Cache<String, Person> cache = cm.getCache(); Person value = new Person(); cache.put("1", value); assertEquals(cache.get("1"), value); Cache<?, ?> unencodedCache = cache.getAdvancedCache().withStorageMediaType(); assertEquals(unencodedCache.get(asStored("1")), asStored(value)); } }); }
Source:
<code>public DocumentModel createEntryWithoutReferences(Map<String, Object> fieldMap) throws DirectoryException { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>interesting put this code a default method in interface</technical_language>

Target:
public DocumentModel createEntryWithoutReferences(Map<String, Object> fieldMap) throws DirectoryException { Object rawId = fieldMap.get(getIdField()); if (rawId == null) { throw new DirectoryException("Missing id"); } String id = String.valueOf(rawId); Map<String, Object> map = data.get(id); if (map != null) { throw new DirectoryException(String.format("Entry with id %s already exists", id)); } map = new HashMap<>(); data.put(id, map); for (Entry<String, Object> e : fieldMap.entrySet()) { String fieldName = e.getKey(); if (!getDirectory().schemaSet.contains(fieldName)) { continue; } map.put(fieldName, e.getValue()); } return getEntry(id); }
Source:
<code>private void setDiskImageActiveBySnapshotType(Map<Guid, DiskImage> diskImageMap, Snapshot snapshot) { DiskImage diskImage = diskImageMap.get(snapshot.getId()); if (diskImage == null) { return; } <START> if (snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW) { <END> diskImage.setActive(true); } else { diskImage.setActive(false); } }</code><technical_language>this shorter: diskImage.setActive(snapshot.getType == ... || ...);</technical_language>

Target:
private void setDiskImageActiveBySnapshotType(Map<Guid, DiskImage> diskImageMap, Snapshot snapshot) { DiskImage diskImage = diskImageMap.get(snapshot.getId()); if (diskImage == null) { return; } diskImage.setActive(snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW); }
Source:
<code>public static Map<String, String> createStructFromLibvirtSecret(LibvirtSecret libvirtSecret) { HashMap<String, String> con = new HashMap<>(); con.put("uuid", libvirtSecret.getId().toString()); con.put("password", libvirtSecret.getValue()); con.put("description", libvirtSecret.getDescription()); con.put("usageType", libvirtSecret.getUsageType().name()); <START> con.put("usageID", String.format("ovirt/%s/%s", libvirtSecret.getProviderId(), libvirtSecret.getId())); <END> return con; }</code><technical_language>worth ovirt a constant variable</technical_language>

Target:
public static Map<String, String> createStructFromLibvirtSecret(LibvirtSecret libvirtSecret) { HashMap<String, String> con = new HashMap<>(); con.put("uuid", libvirtSecret.getId().toString()); con.put("password", libvirtSecret.getValue()); con.put("description", libvirtSecret.getDescription()); con.put("usageType", libvirtSecret.getUsageType().name().toLowerCase()); con.put("usageID", String.format("ovirt/%s/%s", libvirtSecret.getProviderId(), libvirtSecret.getId())); return con; }
Source:
<code>public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { delegate.applyState(sender, topologyId, pushTransfer, stateChunks); <START> return null; <END> }</code><technical_language>This return previous line well</technical_language>

Target:
public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { return delegate.applyState(sender, topologyId, pushTransfer, stateChunks); }
Source:
<code>private MessageContent getMessageContent(MessageValidationWrapper wrapper, Topic topic) { CompiledSchema<Schema> schema = null; byte[] bytes = null; switch (topic.getContentType()) { case JSON: bytes = wrapper.getMessage().getBytes(); break; case AVRO: try { if (Optional.ofNullable(wrapper.getSchemaVersion()).isPresent()) { schema = schemaRepository.getAvroSchema(topic, SchemaVersion.valueOf(wrapper.getSchemaVersion())); } else { <START> <END> schema = schemaRepository.getLatestAvroSchema(topic); } bytes = jsonAvroConverter.convertToAvro(wrapper.getMessage().getBytes(), schema.getSchema()); } catch (AvroConversionException e) { throw new FilteringConversionException("Could not convert to avro message. Please check schema version"); } break; } return new MessageContent.Builder() .withData(bytes) .withContentType(topic.getContentType()) .withSchema(Optional.ofNullable(schema)) .build(); }</code><technical_language>whitespace</technical_language>

Target:
private MessageContent getMessageContent(MessageValidationWrapper wrapper, Topic topic) { CompiledSchema<Schema> schema = null; byte[] bytes = null; switch (topic.getContentType()) { case JSON: bytes = wrapper.getMessage().getBytes(); break; case AVRO: try { if (Optional.ofNullable(wrapper.getSchemaVersion()).isPresent()) { schema = schemaRepository.getAvroSchema(topic, SchemaVersion.valueOf(wrapper.getSchemaVersion())); } else { schema = schemaRepository.getLatestAvroSchema(topic); } bytes = jsonAvroConverter.convertToAvro(wrapper.getMessage().getBytes(), schema.getSchema()); } catch (AvroConversionException e) { throw new FilterValidationException("Could not convert to avro message. Cause: " + e.getMessage()); } break; } return new MessageContent.Builder() .withContent(bytes) .withContentType(topic.getContentType()) .withSchema(Optional.ofNullable(schema)) .build(); }
Source:
<code>public void inStoreLocale() { <START> StoreFixtures.withStore(client(), store -> { <END> final CartDraft cartDraft = CartDraft.of(EUR).withLocale(Locale.GERMAN).withStore(store.toResourceIdentifier()); final Cart cart = client().executeBlocking(CartCreateCommand.of(cartDraft)); final PagedQueryResult<Cart> result = client().executeBlocking(CartInStoreQuery.of(store.getKey()) .plusPredicates(m -> m.is(cart)) .plusPredicates(m -> m.locale().is(Locale.GERMAN))); assertThat(result.getResults()).hasSize(1); assertThat(result.head().get().getId()).isEqualTo(cart.getId()); client().executeBlocking(CartDeleteCommand.of(cart)); }); }</code><technical_language>nice a static import - more consistent other code</technical_language>

Target:
public void inStoreLocale() { withStore(client(), store -> { final CartDraft cartDraft = CartDraft.of(EUR).withLocale(Locale.GERMAN).withStore(store.toResourceIdentifier()); final Cart cart = client().executeBlocking(CartCreateCommand.of(cartDraft)); final PagedQueryResult<Cart> result = client().executeBlocking(CartInStoreQuery.of(store.getKey()) .plusPredicates(m -> m.is(cart)) .plusPredicates(m -> m.locale().is(Locale.GERMAN))); assertThat(result.getResults()).hasSize(1); assertThat(result.head().get().getId()).isEqualTo(cart.getId()); client().executeBlocking(CartDeleteCommand.of(cart)); }); }
Source:
<code>public void start() { URI restApiUri = restApiUri( ); webServer.addFilter( new CollectUserAgentFilter( clientNames() ), "/*", Collections.emptyMap() ); webServer.addFilter( new CorsFilter( logProvider ), "/*", Collections.singletonMap( <START> "access_control_allow_origin", config.get( access_control_allow_origin ) ) ); <END> webServer.addJAXRSClasses( getClassNames(), restApiUri.toString(), null ); loadPlugins(); }</code><technical_language>is reason for piping this untyped config map thing, passing access_control_allow_origin setting constructor of CorsFilter</technical_language>

Target:
public void start() { URI restApiUri = restApiUri( ); webServer.addFilter( new CollectUserAgentFilter( clientNames() ), "/*" ); webServer.addFilter( new CorsFilter( logProvider, config.get( http_access_control_allow_origin ) ), "/*" ); webServer.addJAXRSClasses( getClassNames(), restApiUri.toString(), null ); loadPlugins(); }
Source:
<code>public String getDefaultQuotaName(storage_pool storagePool) { List<Quota> quotaList = getQuotaDAO().getQuotaByStoragePoolGuid(storagePool.getId()); String quotaDefaultName = "Quota_Def_" + storagePool.getname(); String regexToolPattern = quotaDefaultName + "_[0-9]{1,}$"; Integer suffixQuotaName = 0; for (Quota quota : quotaList) { String quotaName = quota.getQuotaName(); if (quotaName.contains(quotaDefaultName) && (quotaName.length() == quotaDefaultName.length() && suffixQuotaName == 0)) { suffixQuotaName = 1; } else if (quotaName.matches(regexToolPattern)) { String defaultQuotaString = quotaName.substring(quotaName.lastIndexOf("_") + 1); Integer defaultQuotaNumber = new Integer(defaultQuotaString); if (suffixQuotaName < defaultQuotaNumber.intValue()) { suffixQuotaName = defaultQuotaNumber.intValue() + 1; } } } <START> return (suffixQuotaName > 0) ? quotaDefaultName + "_" + suffixQuotaName.toString() : quotaDefaultName; <END> }</code><technical_language>String.format("%1$s_%2$s",quotaDefaultName,suffixQuotaName) instead of adding strings</technical_language>

Target:
public String getDefaultQuotaName(storage_pool storagePool) { List<Quota> quotaList = getQuotaDAO().getQuotaByStoragePoolGuid(storagePool.getId()); String quotaDefaultName = "Quota_Def_" + storagePool.getname(); String regexToolPattern = quotaDefaultName + "_[0-9]{1,}$"; Integer suffixQuotaName = 0; for (Quota quota : quotaList) { String quotaName = quota.getQuotaName(); if (quotaName.contains(quotaDefaultName) && (quotaName.length() == quotaDefaultName.length() && suffixQuotaName == 0)) { suffixQuotaName = 1; } else if (quotaName.matches(regexToolPattern)) { String defaultQuotaString = quotaName.substring(quotaName.lastIndexOf("_") + 1); Integer defaultQuotaNumber = new Integer(defaultQuotaString); if (suffixQuotaName < defaultQuotaNumber.intValue()) { suffixQuotaName = defaultQuotaNumber.intValue() + 1; } } } return (suffixQuotaName > 0) ? String.format("%1$s_%2$s", quotaDefaultName, suffixQuotaName.toString()) : quotaDefaultName; }
Source:
<code>public Map<String, CacheInfo> apply(ConfigResource rsrc) { Map<String, CacheInfo> cacheInfos = new TreeMap<>(); for (Map.Entry<String, Cache<?,?>> entry : getCaches().entrySet()) { cacheInfos.put(entry.getKey(), <START> new CacheInfo(entry.getValue())); <END> } return cacheInfos; }</code><technical_language>inline this for loop walks caches in getCaches(), fold getCaches this method. a lot left remove a completely unnecessary intermediate O(n log n) TreeMap insertion step</technical_language>

Target:
public Map<String, CacheInfo> apply(ConfigResource rsrc) { Map<String, CacheInfo> cacheInfos = new TreeMap<>(); for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) { cacheInfos.put(cacheNameOf(e.getPluginName(), e.getExportName()), new CacheInfo(e.getProvider().get())); } return cacheInfos; }
Source:
<code>public void testHighLevelApi() throws Exception { Random random = new Random(); int count = 10; List<PageView> pageviews = new ArrayList<>(count); Map<Integer, List<PageView>> expectedOutput = new HashMap<>(); for (int i = 0; i < count; i++) { String pagekey = PAGEKEYS[random.nextInt(PAGEKEYS.length - 1)]; int memberId = i; PageView pv = new PageView(pagekey, memberId); pageviews.add(pv); expectedOutput.put(i, new ArrayList<PageView>()); expectedOutput.get(i).add(pv); } CollectionStream<PageView> input = CollectionStream.of("test", "PageView", pageviews); CollectionStream output = CollectionStream.empty("test", "Output", 10); TestRunner .of(pageViewParition) .addInputStream(input) .addOutputStream(output) .addOverrideConfig("job.default.system", "test") .run(Duration.ofMillis(1500)); <START> Assert.assertEquals(TestRunner.consumeStream(output, Duration.ofMillis(1000)).get(random.nextInt(count)).size(), 1); <END> }</code><technical_language>double checking: intentional 10K ms 1K ms</technical_language>

Target:
public void testHighLevelApi() throws Exception { Random random = new Random(); int count = 10; List<PageView> pageviews = new ArrayList<>(count); Map<Integer, List<PageView>> expectedOutput = new HashMap<>(); for (int i = 0; i < count; i++) { String pagekey = PAGEKEYS[random.nextInt(PAGEKEYS.length - 1)]; int memberId = i; PageView pv = new PageView(pagekey, memberId); pageviews.add(pv); } CollectionStream<PageView> input = CollectionStream.of("test", "PageView", pageviews); CollectionStream output = CollectionStream.empty("test", "Output", 10); TestRunner .of(pageViewParition) .addInputStream(input) .addOutputStream(output) .addOverrideConfig("job.default.system", "test") .run(Duration.ofMillis(1500)); Assert.assertEquals(TestRunner.consumeStream(output, Duration.ofMillis(1000)).get(random.nextInt(count)).size(), 1); }
Source:
<code>public static void resetConnectionAfterTransaction( Connection con, @Nullable Integer previousIsolationLevel, boolean resetReadOnly) { Assert.notNull(con, "No Connection specified"); <START> final boolean debugEnabled = logger.isDebugEnabled(); <END> try { if (previousIsolationLevel != null) { if (debugEnabled) { logger.debug("Resetting isolation level of JDBC Connection [" + con + "] to " + previousIsolationLevel); } con.setTransactionIsolation(previousIsolationLevel); } if (resetReadOnly) { if (debugEnabled) { logger.debug("Resetting read-only flag of JDBC Connection [" + con + "]"); } con.setReadOnly(false); } } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } }</code><technical_language>suggestion boolean debugEnabled = logger.isDebugEnabled();</technical_language>

Target:
public static void resetConnectionAfterTransaction( Connection con, @Nullable Integer previousIsolationLevel, boolean resetReadOnly) { Assert.notNull(con, "No Connection specified"); boolean debugEnabled = logger.isDebugEnabled(); try { if (previousIsolationLevel != null) { if (debugEnabled) { logger.debug("Resetting isolation level of JDBC Connection [" + con + "] to " + previousIsolationLevel); } con.setTransactionIsolation(previousIsolationLevel); } if (resetReadOnly) { if (debugEnabled) { logger.debug("Resetting read-only flag of JDBC Connection [" + con + "]"); } con.setReadOnly(false); } } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } }
Source:
<code>public void trackVideoSeek(String videoId, Double oldTime, Double newTime, String courseId, String unitUrl, Boolean skipSeek) { final FirebaseEvent event = new FirebaseEvent(Events.SEEK_VIDEO, videoId, Values.VIDEO_SEEKED); event.setCourseContext(courseId, unitUrl, Values.VIDEOPLAYER); oldTime = JavaUtil.formatDoubleValue(oldTime, 3); newTime = JavaUtil.formatDoubleValue(newTime, 3); Double skipInterval = newTime - oldTime; skipInterval = JavaUtil.formatDoubleValue(skipInterval, 3); event.putDouble(Keys.OLD_TIME, oldTime); event.putDouble(Keys.NEW_TIME, newTime); <START> if (skipSeek) { <END> event.putString(Keys.SEEK_TYPE, Values.SKIP); } else { event.putString(Keys.SEEK_TYPE, Values.SLIDE); } event.putDouble(Keys.REQUESTED_SKIP_INTERVAL, skipInterval); tracker.logEvent(event.getName(), event.getBundle()); ; }</code><technical_language>I this logic belong in here. I thinking level Segment Firebase DRY free, if sense put this in AnalyticsRegistery</technical_language>

Target:
public void trackVideoSeek(String videoId, Double oldTime, Double newTime, String courseId, String unitUrl, Boolean skipSeek) { final FirebaseEvent event = new FirebaseEvent(Events.SEEK_VIDEO, videoId, Values.VIDEO_SEEKED); event.setCourseContext(courseId, unitUrl, Values.VIDEOPLAYER); oldTime = JavaUtil.formatDoubleValue(oldTime, 3); newTime = JavaUtil.formatDoubleValue(newTime, 3); Double skipInterval = newTime - oldTime; skipInterval = JavaUtil.formatDoubleValue(skipInterval, 3); event.putDouble(Keys.OLD_TIME, oldTime); event.putDouble(Keys.NEW_TIME, newTime); if (skipSeek) { event.putString(Keys.SEEK_TYPE, Values.SKIP); } else { event.putString(Keys.SEEK_TYPE, Values.SLIDE); } event.putDouble(Keys.REQUESTED_SKIP_INTERVAL, skipInterval); tracker.logEvent(event.getName(), event.getBundle()); }
Source:
<code>private SurfaceMetadata updateSurfaceMetadata(SurfaceMetadata surfaceMetadata, Set<DoublesPair> pairs) { List<SurfaceParameterMetadata> sortedMetaList = new ArrayList<SurfaceParameterMetadata>(); if (surfaceMetadata.getParameterMetadata().isPresent()) { List<SurfaceParameterMetadata> metaList = new ArrayList<SurfaceParameterMetadata>(surfaceMetadata.getParameterMetadata().get()); for (DoublesPair pair : pairs) { metadataLoop: for (SurfaceParameterMetadata parameterMetadata : metaList) { ArgChecker.isTrue(parameterMetadata instanceof SwaptionSurfaceExpiryTenorNodeMetadata, "Surface parameter metadata must be instance of SwaptionVolatilitySurfaceExpiryTenorNodeMetadata"); SwaptionSurfaceExpiryTenorNodeMetadata casted = (SwaptionSurfaceExpiryTenorNodeMetadata) parameterMetadata; if (pair.getFirst() == casted.getYearFraction() && pair.getSecond() == casted.getTenor()) { sortedMetaList.add(casted); metaList.remove(parameterMetadata); break metadataLoop; } } } ArgChecker.isTrue(metaList.size() == 0, "Mismatch between surface parameter metadata list and doubles pair list"); } else { <START> for (DoublesPair pair : pairs) { <END> SwaptionSurfaceExpiryTenorNodeMetadata parameterMetadata = SwaptionSurfaceExpiryTenorNodeMetadata.of(pair.getFirst(), pair.getSecond()); sortedMetaList.add(parameterMetadata); } } return surfaceMetadata.withParameterMetadata(sortedMetaList); }</code><technical_language>sortedMetaList = pairs.stream() .map(pair -> SwaptionSurfaceExpiryTenorNodeMetadata.of(pair.getFirst(), pair.getSecond())) .collect(toList());</technical_language>

Target:
private SurfaceMetadata updateSurfaceMetadata(SurfaceMetadata surfaceMetadata, Set<DoublesPair> pairs) { List<SurfaceParameterMetadata> orderedMetaList = new ArrayList<SurfaceParameterMetadata>(); if (surfaceMetadata.getParameterMetadata().isPresent()) { List<SurfaceParameterMetadata> metaList = new ArrayList<SurfaceParameterMetadata>(surfaceMetadata.getParameterMetadata().get()); for (DoublesPair pair : pairs) { metadataLoop: for (SurfaceParameterMetadata parameterMetadata : metaList) { ArgChecker.isTrue(parameterMetadata instanceof SwaptionSurfaceExpiryTenorNodeMetadata, "Surface parameter metadata must be instance of SwaptionVolatilitySurfaceExpiryTenorNodeMetadata"); SwaptionSurfaceExpiryTenorNodeMetadata casted = (SwaptionSurfaceExpiryTenorNodeMetadata) parameterMetadata; if (pair.getFirst() == casted.getYearFraction() && pair.getSecond() == casted.getTenor()) { orderedMetaList.add(casted); metaList.remove(parameterMetadata); break metadataLoop; } } } ArgChecker.isTrue(metaList.size() == 0, "Mismatch between surface parameter metadata list and doubles pair list"); } else { orderedMetaList = pairs.stream() .map(pair -> SwaptionSurfaceExpiryTenorNodeMetadata.of(pair.getFirst(), pair.getSecond())) .collect(toImmutableList()); } return surfaceMetadata.withParameterMetadata(orderedMetaList); }
Source:
<code><START> public String getEscapedReplacement() { <END> return escapedReplacement; }</code><technical_language>package visibility, this is implementation detail</technical_language>

Target:
String getEscapedReplacement() { return escapedReplacement; }
Source:
<code>private void checkValid(String input, String errorMessage) throws InternalInfrastructureException { if (!namePattern.matcher(input).matches()) { <START> throw new InternalInfrastructureException(format(errorMessage, input)); <END> } }</code><technical_language>I is InternalInfrastructureException. Please consider ValidationException here</technical_language>

Target:
private void checkValid(String input, String errorMessage) throws ValidationException { if (!namePattern.matcher(input).matches()) { throw new ValidationException(format(errorMessage, input)); } }
Source:
<code><START> private boolean checkFilterParams() throws BadArgumentException { <END> if (Guard.isMapNullOrEmpty(this.filterParams)) { return true; } final ImmutableList<String> legalParams = ImmutableList.of(CONTAINS, OWNER, NEWERTHAN, OLDERTHAN, LARGERTHAN, SMALLERTHAN); for (final String paramName : this.filterParams.keySet()) { if (!legalParams.contains(paramName)) { throw new BadArgumentException("Unknown filter parameter: " + paramName); } } return true; }</code><technical_language>This method returns true throws exception fails. return void throw exception, return true/false</technical_language>

Target:
private void checkFilterParams() throws BadArgumentException { if (Guard.isMapNullOrEmpty(this.filterParams)) { return; } final ImmutableList<String> legalParams = ImmutableList.of(CONTAINS, OWNER, NEWERTHAN, OLDERTHAN, LARGERTHAN, SMALLERTHAN); for (final String paramName : this.filterParams.keySet()) { if (!legalParams.contains(paramName)) { throw new BadArgumentException("Unknown filter parameter: " + paramName); } } }
Source:
<code>public void restartMachine(final org.eclipse.che.api.core.model.machine.Machine machineState) { eventBus.addHandler(MachineStateEvent.TYPE, new MachineStateEvent.Handler() { @Override public void onMachineCreating(MachineStateEvent event) { } @Override public void onMachineRunning(MachineStateEvent event) { } @Override public void onMachineDestroyed(MachineStateEvent event) { if (isMachineRestarting) { final MachineSource machineSource = machineState.getConfig().getSource(); final String displayName = machineState.getConfig().getName(); final boolean isDev = machineState.getConfig().isDev(); <START> startMachine(asDto(machineSource), displayName, isDev, RESTART, "dockerfile", "docker"); <END> isMachineRestarting = false; } } }); destroyMachine(machineState).then(new Operation<Void>() { @Override public void apply(Void arg) throws OperationException { isMachineRestarting = true; } }); }</code><technical_language>please check "dockerfile" is correct of argument in cases</technical_language>

Target:
public void restartMachine(final org.eclipse.che.api.core.model.machine.Machine machineState) { eventBus.addHandler(MachineStateEvent.TYPE, new MachineStateEvent.Handler() { @Override public void onMachineCreating(MachineStateEvent event) { } @Override public void onMachineRunning(MachineStateEvent event) { } @Override public void onMachineDestroyed(MachineStateEvent event) { if (isMachineRestarting) { final MachineSource machineSource = machineState.getConfig().getSource(); final String displayName = machineState.getConfig().getName(); final boolean isDev = machineState.getConfig().isDev(); startMachine(asDto(machineSource), displayName, isDev, RESTART, "docker"); isMachineRestarting = false; } } }); destroyMachine(machineState).then(new Operation<Void>() { @Override public void apply(Void arg) throws OperationException { isMachineRestarting = true; } }); }
Source:
<code>public ElasticsearchTableDescription( @JsonProperty("tableName") String tableName, @JsonProperty("schemaName") String schemaName, @JsonProperty("hostAddress") String hostAddress, @JsonProperty("port") int port, @JsonProperty("clusterName") String clusterName, @JsonProperty("index") String index, @JsonProperty("indexExactMatch") boolean indexExactMatch, @JsonProperty("type") String type, @JsonProperty("columns") List<ElasticsearchColumn> columns) { checkArgument(!isNullOrEmpty(tableName), "tableName is null or is empty"); checkArgument(!isNullOrEmpty(hostAddress), "hostAddress is null or is empty"); <START> checkArgument(!isNullOrEmpty(String.valueOf(port)), "port is null or is empty"); <END> checkArgument(!isNullOrEmpty(clusterName), "clusterName is null or is empty"); checkArgument(!isNullOrEmpty(type), "type is null or is empty"); this.tableName = tableName; this.schemaName = schemaName; this.hostAddress = hostAddress; this.port = port; this.clusterName = clusterName; this.index = index; this.indexExactMatch = indexExactMatch; this.type = type; if (columns == null) { this.columns = null; } else { this.columns = ImmutableList.copyOf(columns); } }</code><technical_language>this check for port variable necessary (String.valueOf(port) return null empty)</technical_language>

Target:
public ElasticsearchTableDescription( @JsonProperty("tableName") String tableName, @JsonProperty("schemaName") String schemaName, @JsonProperty("hostAddress") String hostAddress, @JsonProperty("port") int port, @JsonProperty("clusterName") String clusterName, @JsonProperty("index") String index, @JsonProperty("indexExactMatch") boolean indexExactMatch, @JsonProperty("type") String type, @JsonProperty("columns") List<ElasticsearchColumn> columns) { checkArgument(!isNullOrEmpty(tableName), "tableName is null or is empty"); checkArgument(!isNullOrEmpty(hostAddress), "hostAddress is null or is empty"); checkArgument(!isNullOrEmpty(clusterName), "clusterName is null or is empty"); checkArgument(!isNullOrEmpty(type), "type is null or is empty"); this.tableName = tableName; this.schemaName = schemaName; this.hostAddress = hostAddress; this.port = port; this.clusterName = clusterName; this.index = index; this.indexExactMatch = indexExactMatch; this.type = type; if (columns == null) { this.columns = ImmutableList.of(); } else { this.columns = ImmutableList.copyOf(columns); } }
Source:
<code>public boolean matches(byte[] array) { long state = 0; for (int i = 0; i < array.length; ++i) { <START> byte symbol = array[i]; <END> long highMask = high[symbol >>> 4]; long lowMask = low[symbol & 0xF]; state = ((state << 1) | 1) & highMask & lowMask; if ((state & termination) == termination) { return true; } } return false; }</code><technical_language>minor: this a foreach method above, of i is access element</technical_language>

Target:
public boolean matches(byte[] array) { long state = 0; for (byte symbol : array) { long highMask = high[symbol >>> 4]; long lowMask = low[symbol & 0xF]; state = ((state << 1) | 1) & highMask & lowMask; if ((state & termination) == termination) { return true; } } return false; }
Source:
<code>public WorldBorder.Builder from(WorldBorder border) { this.diameter = border.getDiameter(); this.centre = border.getCenter(); this.warningTime = border.getWarningTime(); this.warningDistance = border.getWarningDistance(); this.damageThreshold = border.getDamageThreshold(); this.damageAmount = border.getDamageAmount(); <START> return this; <END> }</code><technical_language>~~Missing licence header.~~</technical_language>

Target:
public WorldBorder.Builder from(WorldBorder border) { this.diameter = border.getDiameter(); this.center = border.getCenter(); this.warningTime = border.getWarningTime(); this.warningDistance = border.getWarningDistance(); this.damageThreshold = border.getDamageThreshold(); this.damageAmount = border.getDamageAmount(); return this; }
Source:
<code>private static void checkThreadPool(final OperationContext context, final ModelNode operation, final String type) throws OperationFailedException { <START> PathAddress threadPoolPath = PathAddress.pathAddress(operation.require(OP_ADDR)); <END> PathAddress workManagerPath = threadPoolPath.getParent(); Set<Resource.ResourceEntry> entrySet = context.readResourceFromRoot(workManagerPath).getChildren(type); if (entrySet.size() > 0 && !entrySet.iterator().next().getName().equals(threadPoolPath.getLastElement().getValue())) { throw ConnectorLogger.ROOT_LOGGER.oneThreadPoolWorkManager(threadPoolPath.getLastElement().getValue(), type, workManagerPath.getLastElement().getValue()); } }</code><technical_language>context.getCurrentAddress()</technical_language>

Target:
private static void checkThreadPool(final OperationContext context, final ModelNode operation, final String type) throws OperationFailedException { PathAddress threadPoolPath = context.getCurrentAddress(); PathAddress workManagerPath = threadPoolPath.getParent(); Set<Resource.ResourceEntry> entrySet = context.readResourceFromRoot(workManagerPath).getChildren(type); if (entrySet.size() > 0 && !entrySet.iterator().next().getName().equals(threadPoolPath.getLastElement().getValue())) { throw ConnectorLogger.ROOT_LOGGER.oneThreadPoolWorkManager(threadPoolPath.getLastElement().getValue(), type, workManagerPath.getLastElement().getValue()); } }