id
stringlengths 23
26
| content
stringlengths 182
2.49k
|
|---|---|
codereview_java_data_10
|
return false;
}
- public boolean supportsFunction(RexCall call) {
return true;
}
Is the change to RexCall absolutely necessary? I don't want SqlDialect to depend on Rex or RelNode.
return false;
}
+ public boolean supportsFunction(SqlOperator operator, RelDataType type,
+ List<RelDataType> paramsList) {
return true;
}
|
codereview_java_data_13
|
List<String> folderServerIds = search.getFolderServerIds();
singleFolderMode = singleAccountMode && folderServerIds.size() == 1;
if (drawer == null) {
return;
} else if (singleFolderMode) {
This skips the last line of the method that seems unrelated to the drawer. My suggestion is to extract the drawer-related code to a separate method and do the `null` check there.
List<String> folderServerIds = search.getFolderServerIds();
singleFolderMode = singleAccountMode && folderServerIds.size() == 1;
+
+ // now we know if we are in single account mode and need a subtitle
+ actionBarSubTitle.setVisibility((!singleFolderMode) ? View.GONE : View.VISIBLE);
+
if (drawer == null) {
return;
} else if (singleFolderMode) {
|
codereview_java_data_15
|
public GlucoseStatus round() {
this.glucose = Round.roundTo(this.glucose, 0.1);
- this.noise = Round.roundTo(this.noise, 0.1);
this.delta = Round.roundTo(this.delta, 0.01);
this.avgdelta = Round.roundTo(this.avgdelta, 0.01);
this.short_avgdelta = Round.roundTo(this.short_avgdelta, 0.01);
The noise calculation coming in oref0 0.7.1 needs two decimal places.
public GlucoseStatus round() {
this.glucose = Round.roundTo(this.glucose, 0.1);
+ this.noise = Round.roundTo(this.noise, 0.01);
this.delta = Round.roundTo(this.delta, 0.01);
this.avgdelta = Round.roundTo(this.avgdelta, 0.01);
this.short_avgdelta = Round.roundTo(this.short_avgdelta, 0.01);
|
codereview_java_data_24
|
TableMetadata updated = table.ops().current();
Integer updatedVersion = TestTables.metadataVersion("test");
Assert.assertEquals(current, updated);
- Assert.assertEquals(++currentVersion, updatedVersion.intValue());
// no-op commit due to no-op rename
table.updateSpec()
We don't use the return value of the `++` operator because it is not obvious which value is returned. Could you move these to separate lines?
TableMetadata updated = table.ops().current();
Integer updatedVersion = TestTables.metadataVersion("test");
Assert.assertEquals(current, updated);
+ currentVersion += 1;
+ Assert.assertEquals(currentVersion, updatedVersion.intValue());
// no-op commit due to no-op rename
table.updateSpec()
|
codereview_java_data_27
|
private final Context context;
public static final String PREF_KEY_COUNTRY_CODE = "country_code";
public static final String PREFS = "CountryRegionPrefs";
-
public ItunesTopListLoader(Context context) {
this.context = context;
}
What do you think about only falling back to `US` when no country was selected yet? Other countries could display something like "Sorry, we do not have suggestions for your region".
private final Context context;
public static final String PREF_KEY_COUNTRY_CODE = "country_code";
public static final String PREFS = "CountryRegionPrefs";
+ public static final String DISCOVER_HIDE_FAKE_COUNTRY_CODE = "00";
public ItunesTopListLoader(Context context) {
this.context = context;
}
|
codereview_java_data_28
|
TSERV_WAL_SORT_FILE_PREFIX("tserver.wal.sort.file.", null, PropertyType.PREFIX,
"The rfile properties to use when sorting logs during recovery. Most of the properties"
+ " that begin with 'table.file' can be used here. For example, to set the compression"
- + " of the sorted recovery files to snappy use 'tserver.sort.file.compress.type=snappy'",
"2.1.0"),
TSERV_WORKQ_THREADS("tserver.workq.threads", "2", PropertyType.COUNT,
"The number of threads for the distributed work queue. These threads are"
Do you know of 'table.file' props that can't be used here?
TSERV_WAL_SORT_FILE_PREFIX("tserver.wal.sort.file.", null, PropertyType.PREFIX,
"The rfile properties to use when sorting logs during recovery. Most of the properties"
+ " that begin with 'table.file' can be used here. For example, to set the compression"
+ + " of the sorted recovery files to snappy use 'tserver.wal.sort.file.compress.type=snappy'",
"2.1.0"),
TSERV_WORKQ_THREADS("tserver.workq.threads", "2", PropertyType.COUNT,
"The number of threads for the distributed work queue. These threads are"
|
codereview_java_data_31
|
Iconify.with(new FontAwesomeModule());
SPAUtil.sendSPAppsQueryFeedsIntent(this);
-
- throw new NullPointerException();
}
}
pretty sure you didn't want to keep this in here...
Iconify.with(new FontAwesomeModule());
SPAUtil.sendSPAppsQueryFeedsIntent(this);
}
}
|
codereview_java_data_35
|
}
/**
- * Sets the used properties. Can be null if no properties should be used.
- * <p>
- * Properties are used to resolve ${variable} occurrences in the XML file.
*
- * @param properties the new properties
* @return the XmlJetConfigBuilder
*/
public XmlJetConfigBuilder setProperties(@Nullable Properties properties) {
Sentence `Can be null if no properties should be used.` is not correct. It uses `System.getProperties()` if null is used.
}
/**
+ * Sets properties to be used in variable resolution.
+ *
+ * If null properties supplied, System.properties will be used.
*
+ * @param properties the properties to be used to resolve ${variable}
+ * occurrences in the XML file
* @return the XmlJetConfigBuilder
*/
public XmlJetConfigBuilder setProperties(@Nullable Properties properties) {
|
codereview_java_data_45
|
Map<VariableNameDeclaration, List<NameOccurrence>> vars = node.getScope()
.getDeclarations(VariableNameDeclaration.class);
for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : vars.entrySet()) {
- AccessNode accessNodeParent = entry.getKey().getAccessNodeParent();
if (entry.getValue().isEmpty() || accessNodeParent.isTransient() || accessNodeParent.isStatic()) {
continue;
}
- String varName = trimIfPrefix(entry.getKey().getImage());
varName = varName.substring(0, 1).toUpperCase() + varName.substring(1, varName.length());
boolean hasGetMethod = Arrays.binarySearch(methNameArray, "get" + varName) >= 0
|| Arrays.binarySearch(methNameArray, "is" + varName) >= 0;
I'd add a `VariableNameDeclaration decl = entry.getKey();` here for readability
Map<VariableNameDeclaration, List<NameOccurrence>> vars = node.getScope()
.getDeclarations(VariableNameDeclaration.class);
for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : vars.entrySet()) {
+ VariableNameDeclaration decl = entry.getKey();
+ AccessNode accessNodeParent = decl.getAccessNodeParent();
if (entry.getValue().isEmpty() || accessNodeParent.isTransient() || accessNodeParent.isStatic()) {
continue;
}
+ String varName = trimIfPrefix(decl.getImage());
varName = varName.substring(0, 1).toUpperCase() + varName.substring(1, varName.length());
boolean hasGetMethod = Arrays.binarySearch(methNameArray, "get" + varName) >= 0
|| Arrays.binarySearch(methNameArray, "is" + varName) >= 0;
|
codereview_java_data_48
|
import java.util.OptionalInt;
import java.util.concurrent.CompletableFuture;
import io.vertx.core.Vertx;
import io.vertx.core.datagram.DatagramPacket;
import io.vertx.core.datagram.DatagramSocket;
Per style guild lambdas should be 1-3 lines.
import java.util.OptionalInt;
import java.util.concurrent.CompletableFuture;
+import io.vertx.core.AsyncResult;
import io.vertx.core.Vertx;
import io.vertx.core.datagram.DatagramPacket;
import io.vertx.core.datagram.DatagramSocket;
|
codereview_java_data_53
|
SwipeRefreshLayout swipeRefreshLayout = root.findViewById(R.id.swipeRefresh);
swipeRefreshLayout.setOnRefreshListener(() -> {
AutoUpdateManager.runImmediate(requireContext());
- new Handler().postDelayed(() -> swipeRefreshLayout.setRefreshing(false), 1000);
});
progLoading = root.findViewById(R.id.progLoading);
1 second feels a bit too much to me. This is sometimes more than what it takes to actually refresh. What about 500ms?
SwipeRefreshLayout swipeRefreshLayout = root.findViewById(R.id.swipeRefresh);
swipeRefreshLayout.setOnRefreshListener(() -> {
AutoUpdateManager.runImmediate(requireContext());
+ new Handler().postDelayed(() -> swipeRefreshLayout.setRefreshing(false), SubscriptionFragment.SWIPE_TO_REFRESH_DURATION);
});
progLoading = root.findViewById(R.id.progLoading);
|
codereview_java_data_55
|
+ "scan is switched to that local file. We can not switch to the minor compacted file because it may have been modified by iterators. The file "
+ "dumped to the local dir is an exact copy of what was in memory."),
TSERV_BULK_PROCESS_THREADS("tserver.bulk.process.threads", "1", PropertyType.COUNT,
- "The master will task a tablet server with pre-processing a bulk import file prior to assigning it to the appropriate tablet servers. This configuration"
+ " value controls the number of threads used to process the files."),
TSERV_BULK_ASSIGNMENT_THREADS("tserver.bulk.assign.threads", "1", PropertyType.COUNT,
- "The master delegates bulk import file processing and assignment to tablet servers. After file has been processed, the tablet server will assign"
+ " the file to the appropriate tablets on all servers. This property controls the number of threads used to communicate to the other servers."),
TSERV_BULK_RETRY("tserver.bulk.retry.max", "5", PropertyType.COUNT,
"The number of times the tablet server will attempt to assign a RFile to a tablet as it migrates and splits."),
Do we want to specify "bulk import RFile" here (and possibly in other places), since RFile is the file type for bulk-imported files, or is "bulk import file" sufficient?
+ "scan is switched to that local file. We can not switch to the minor compacted file because it may have been modified by iterators. The file "
+ "dumped to the local dir is an exact copy of what was in memory."),
TSERV_BULK_PROCESS_THREADS("tserver.bulk.process.threads", "1", PropertyType.COUNT,
+ "The master will task a tablet server with pre-processing a bulk import RFile prior to assigning it to the appropriate tablet servers. This configuration"
+ " value controls the number of threads used to process the files."),
TSERV_BULK_ASSIGNMENT_THREADS("tserver.bulk.assign.threads", "1", PropertyType.COUNT,
+ "The master delegates bulk import RFile processing and assignment to tablet servers. After file has been processed, the tablet server will assign"
+ " the file to the appropriate tablets on all servers. This property controls the number of threads used to communicate to the other servers."),
TSERV_BULK_RETRY("tserver.bulk.retry.max", "5", PropertyType.COUNT,
"The number of times the tablet server will attempt to assign a RFile to a tablet as it migrates and splits."),
|
codereview_java_data_57
|
private String composedTaskRunnerName = "composed-task-runner";
@NotBlank
- private String schedulerTaskLauncher = "scheduler-task-launcher";
public String getComposedTaskRunnerName() {
return composedTaskRunnerName;
The name `schedulerTaskLauncher` implies the launcher itself instead of being the `name` of the launcher. Can we rename this to be something similar to `schedulerTaskLauncherName`?
private String composedTaskRunnerName = "composed-task-runner";
@NotBlank
+ private String schedulerTaskLauncherName = "scheduler-task-launcher";
public String getComposedTaskRunnerName() {
return composedTaskRunnerName;
|
codereview_java_data_76
|
public static final int WHITE = 8;
public static final int JELLIE = 9;
public static final int ALL_BLACK = 10;
}
These really need a private constructor to prevent instantiation.
public static final int WHITE = 8;
public static final int JELLIE = 9;
public static final int ALL_BLACK = 10;
+
+ private CatTypes() {
+ }
}
|
codereview_java_data_80
|
protected void fetchColumns(final CommandLine cl, final ScannerBase scanner,
final ScanInterpreter formatter) throws UnsupportedEncodingException {
- if ((cl.hasOption(scanOptCfOptions.getOpt()) || cl.hasOption(scanOptColQualifier.getOpt()))
&& cl.hasOption(scanOptColumns.getOpt())) {
String formattedString =
- String.format("Options - %s AND (- %s" + "OR - %s are mutually exclusive ",
- scanOptColumns.getOpt(), scanOptCfOptions.getOpt(), scanOptColQualifier.getOpt());
throw new IllegalArgumentException(formattedString);
}
The spacing is a little off here. This is how it looks in the shell: `Options - c AND (- cfOR - cq are mutually exclusive`
protected void fetchColumns(final CommandLine cl, final ScannerBase scanner,
final ScanInterpreter formatter) throws UnsupportedEncodingException {
+ if ((cl.hasOption(scanOptCf.getOpt()) || cl.hasOption(scanOptCq.getOpt()))
&& cl.hasOption(scanOptColumns.getOpt())) {
String formattedString =
+ String.format("Options - %s AND (- %s" + " OR - %s are mutually exclusive )",
+ scanOptColumns.getOpt(), scanOptCf.getOpt(), scanOptCq.getOpt());
throw new IllegalArgumentException(formattedString);
}
|
codereview_java_data_85
|
if (posDeletes.stream().mapToLong(DeleteFile::recordCount).sum() < setFilterThreshold) {
return Deletes.filter(
records, this::pos,
- Deletes.toPositionSet(
- dataFile.path(),
- CloseableIterable.concat(deletes, ThreadPools.getWorkerPool(), ThreadPools.getPoolParallelism())
- )
);
}
I think that parallelizing this requires adding an option. There are many cases where we wouldn't want to parallelize and cases where we want to use a thread pool besides the shared worker pool. It would be better to pass a pool in and parallelize if it is non-null.
if (posDeletes.stream().mapToLong(DeleteFile::recordCount).sum() < setFilterThreshold) {
return Deletes.filter(
records, this::pos,
+ Deletes.toPositionSet(dataFile.path(), CloseableIterable.combine(deletes, readService, readParallelism))
);
}
|
codereview_java_data_89
|
return scheduleTimeZone;
}
- @Schema(nullable = true, description = "A count limit of tasks to run for on-demand requests")
public Optional<Integer> getInstances() {
return instances;
}
this should be an addition, not a replacement. It functions as both, depending on the context of the request type. eg. `A count of tasks to run for long-running requests or the limit on the number of concurrent tasks for on-demand requests`
return scheduleTimeZone;
}
+ @Schema(nullable = true, description = "A count of tasks to run for long-running requests or the limit on the number of concurrent tasks for on-demand requests")
public Optional<Integer> getInstances() {
return instances;
}
|
codereview_java_data_93
|
int blockSize = (int) aconf.getAsBytes(Property.TABLE_FILE_BLOCK_SIZE);
try (
Writer small = new RFile.Writer(
- new BCFile.Writer(new RateLimitedOutputStream(fs.create(new Path(smallName)), null),
- "gz", conf, false, aconf),
blockSize);
Writer large = new RFile.Writer(
- new BCFile.Writer(new RateLimitedOutputStream(fs.create(new Path(largeName)), null),
- "gz", conf, false, aconf),
blockSize)) {
small.startDefaultLocalityGroup();
large.startDefaultLocalityGroup();
Do we always call this constructor with a RateLimitedOutputStream? If so, can we push that into the constructor implementation?
int blockSize = (int) aconf.getAsBytes(Property.TABLE_FILE_BLOCK_SIZE);
try (
Writer small = new RFile.Writer(
+ new BCFile.Writer(fs.create(new Path(smallName)), null, "gz", conf, aconf),
blockSize);
Writer large = new RFile.Writer(
+ new BCFile.Writer(fs.create(new Path(largeName)), null, "gz", conf, aconf),
blockSize)) {
small.startDefaultLocalityGroup();
large.startDefaultLocalityGroup();
|
codereview_java_data_102
|
public static final CalciteSystemProperty<Boolean> TEST_SLOW =
booleanProperty("calcite.test.slow", false);
- /**
- * Whether to do validation within VolcanoPlanner after each rule firing.
- * Note that doing so would significantly slow down the planning. Should only
- * enable for unit test.
- */
- public static final CalciteSystemProperty<Boolean> TEST_VALIDATE_VOLCANO_PLANNER =
- booleanProperty("calcite.test.validate.volcano.planner", false);
-
/**
* Whether to run MongoDB tests.
*/
I think the flag is not limited to test, so we can remove `test` from the flag name. TEST_VALIDATE_VOLCANO_PLANNER -> VALIDATE_VOLCANO_PLANNER
public static final CalciteSystemProperty<Boolean> TEST_SLOW =
booleanProperty("calcite.test.slow", false);
/**
* Whether to run MongoDB tests.
*/
|
codereview_java_data_114
|
@DatabaseField
public boolean isSMB = false;
public Treatment() {
}
I'd prefer to keep it. It's not done yet but it's prepared for supporting multiple insulin types with MDI or pump+MDI
@DatabaseField
public boolean isSMB = false;
+ @DatabaseField
+ public int insulinInterfaceID = InsulinInterface.FASTACTINGINSULIN; // currently unused, will be used in the future
+ @DatabaseField
+ public double dia = Constants.defaultDIA; // currently unused, will be used in the future
+
public Treatment() {
}
|
codereview_java_data_120
|
}
recordSchema = Schema.createRecord(recordName, null, null, false, fields);
- if (struct.isUnionSchema()) {
recordSchema.addProp(AvroSchemaUtil.UNION_SCHEMA_TO_RECORD, true);
}
results.put(struct, recordSchema);
Is there some reason why this needs to be a round-trip conversion? I think it should be fine to convert back to a record instead of a union schema. That's what we should be writing into a table with a schema converted from an Avro union schema anyway.
}
recordSchema = Schema.createRecord(recordName, null, null, false, fields);
+ if (struct.isConvertedFromUnionSchema()) {
recordSchema.addProp(AvroSchemaUtil.UNION_SCHEMA_TO_RECORD, true);
}
results.put(struct, recordSchema);
|
codereview_java_data_144
|
public abstract Address[] getRecipients(RecipientType type) throws MessagingException;
- public abstract Address[] getListPost();
-
public abstract void setRecipients(RecipientType type, Address[] addresses)
throws MessagingException;
Please don't add more utility methods to `Message`. Instead you could create a method `ListHeaders.getListPostAddress(Message)` that gets the appropriate header from the message.
public abstract Address[] getRecipients(RecipientType type) throws MessagingException;
public abstract void setRecipients(RecipientType type, Address[] addresses)
throws MessagingException;
|
codereview_java_data_151
|
@javax.inject.Inject
public ApplicationConfig(
Instance<org.kie.kogito.KogitoConfig> configs) {
- super($Addons$, configs.stream().toArray(org.kie.kogito.KogitoConfig[]::new));
}
}
\ No newline at end of file
same note about using an overloaded constructor for `StaticApplication` with Iterable applies here to `StaticConfig` ``` public StaticConfig( Addons addons, Iterable<KogitoConfig> configs) { ```
@javax.inject.Inject
public ApplicationConfig(
Instance<org.kie.kogito.KogitoConfig> configs) {
+ super($Addons$, configs);
}
}
\ No newline at end of file
|
codereview_java_data_154
|
return new UncommittedIterator<>(this, from, to, false, forEntries);
case REPEATABLE_READ:
case SERIALIZABLE:
- return transaction.hasChanges() ?
- new RepeatableIterator<K, X>(this, from, to, forEntries) :
- new CommittedIterator<K, X>(this, from, to, forEntries);
case READ_COMMITTED:
default:
return new CommittedIterator<>(this, from, to, forEntries);
It could be shortened even more, if you wish: ```Java if (transaction.hasChanges()) { return new Repeatable } //$FALL-THROUGH$ ```
return new UncommittedIterator<>(this, from, to, false, forEntries);
case REPEATABLE_READ:
case SERIALIZABLE:
+ if (transaction.hasChanges()) {
+ new RepeatableIterator<K, X>(this, from, to, forEntries);
+ }
+ //$FALL-THROUGH$
case READ_COMMITTED:
default:
return new CommittedIterator<>(this, from, to, forEntries);
|
codereview_java_data_165
|
return new UidFetchCommand.Builder()
.maximumAutoDownloadMessageSize(maximumAutoDownloadMessageSize)
.idSet(Collections.singletonList(uid))
- .messageParams(fetchProfile, new HashMap<>(Collections.singletonMap(String.valueOf(uid),
- (Message) createImapMessage(String.valueOf(uid)))))
.build();
}
a builder shouldn't take mutable data structures. if this parameter actually needs a mutable hashmap, rather than an immutable Map type, something is wrong
return new UidFetchCommand.Builder()
.maximumAutoDownloadMessageSize(maximumAutoDownloadMessageSize)
.idSet(Collections.singletonList(uid))
+ .messageParams(fetchProfile, Collections.singletonMap(String.valueOf(uid),
+ (Message) createImapMessage(String.valueOf(uid))))
.build();
}
|
codereview_java_data_167
|
public String getLogFileParentDir() {
ArrayList<String> elements = new ArrayList<String>();
- if(mPrefix.length() > 0) {
elements.add(mPrefix);
}
- if(mTopic.length() > 0) {
elements.add(mTopic);
}
return StringUtils.join(elements, "/");
If you want to be safe, you can do: if (mPrefix != null && mPrefix.length()) > 0 ) { On the coding style side, there should be a space after 'if'
public String getLogFileParentDir() {
ArrayList<String> elements = new ArrayList<String>();
+ if (mPrefix != null && mPrefix.length() > 0) {
elements.add(mPrefix);
}
+ if (mTopic != null && mTopic.length() > 0) {
elements.add(mTopic);
}
return StringUtils.join(elements, "/");
|
codereview_java_data_175
|
public List<RoleInfo> getRoles(String username) {
List<RoleInfo> roleInfoList = roleInfoMap.get(username);
- if (!authConfigs.isCachingEnabled() || roleInfoList == null) {
Page<RoleInfo> roleInfoPage = getRolesFromDatabase(username, DEFAULT_PAGE_NO, Integer.MAX_VALUE);
if (roleInfoPage != null) {
roleInfoList = roleInfoPage.getPageItems();
Why add this?there is not null judgement in 163.
public List<RoleInfo> getRoles(String username) {
List<RoleInfo> roleInfoList = roleInfoMap.get(username);
+ if (!authConfigs.isCachingEnabled()) {
Page<RoleInfo> roleInfoPage = getRolesFromDatabase(username, DEFAULT_PAGE_NO, Integer.MAX_VALUE);
if (roleInfoPage != null) {
roleInfoList = roleInfoPage.getPageItems();
|
codereview_java_data_180
|
*/
package org.flowable.scripting.secure.impl;
import org.flowable.variable.api.delegate.VariableScope;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
-import java.util.Map;
-
/**
* @author Joram Barrez
*/
Project standards are to place `java` imports before `org` imports. The same change needs to be made in the next file too.
*/
package org.flowable.scripting.secure.impl;
+import java.util.Map;
+
import org.flowable.variable.api.delegate.VariableScope;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
* @author Joram Barrez
*/
|
codereview_java_data_193
|
} else if (getSupportFragmentManager().findFragmentByTag(nearbyFragmentTag) != null && !isContributionsFragmentVisible) {
// Means that nearby fragment is visible (not contributions fragment)
NearbyParentFragment nearbyFragment = (NearbyParentFragment) contributionsActivityPagerAdapter.getItem(1);
- nearbyFragment.nearbyParentFragmentPresenter.backButtonClicked();
} else {
super.onBackPressed();
}
Again, the back press should be passed to the fragment and not the presenter directly
} else if (getSupportFragmentManager().findFragmentByTag(nearbyFragmentTag) != null && !isContributionsFragmentVisible) {
// Means that nearby fragment is visible (not contributions fragment)
NearbyParentFragment nearbyFragment = (NearbyParentFragment) contributionsActivityPagerAdapter.getItem(1);
+ NearbyParentFragmentPresenter.getInstance().backButtonClicked();
} else {
super.onBackPressed();
}
|
codereview_java_data_197
|
protected Catalog createCatalog(String name, Map<String, String> properties, Configuration hadoopConf) {
CatalogLoader catalogLoader = createCatalogLoader(name, properties, hadoopConf);
String defaultDatabase = properties.getOrDefault(DEFAULT_DATABASE, "default");
- boolean cacheEnabled = Boolean.parseBoolean(properties.getOrDefault(CACHE_ENABLED, "true"));
Namespace baseNamespace = Namespace.empty();
if (properties.containsKey(BASE_NAMESPACE)) {
baseNamespace = Namespace.of(properties.get(BASE_NAMESPACE).split("\\."));
}
return new FlinkCatalog(name, defaultDatabase, baseNamespace, catalogLoader, cacheEnabled);
}
Why move this below `cacheEnabled`? That seems like it would cause unnecessary git conflicts.
protected Catalog createCatalog(String name, Map<String, String> properties, Configuration hadoopConf) {
CatalogLoader catalogLoader = createCatalogLoader(name, properties, hadoopConf);
String defaultDatabase = properties.getOrDefault(DEFAULT_DATABASE, "default");
Namespace baseNamespace = Namespace.empty();
if (properties.containsKey(BASE_NAMESPACE)) {
baseNamespace = Namespace.of(properties.get(BASE_NAMESPACE).split("\\."));
}
+ boolean cacheEnabled = Boolean.parseBoolean(properties.getOrDefault(CACHE_ENABLED, "true"));
return new FlinkCatalog(name, defaultDatabase, baseNamespace, catalogLoader, cacheEnabled);
}
|
codereview_java_data_208
|
}
return objectMapper.readValue(response.getResponseBodyAsStream(), MESOS_FILE_OBJECTS);
- } catch (ExecutionException | ConnectException ce) {
throw new SlaveNotFoundException(ce);
} catch (Exception e) {
- throw Throwables.propagate(e);
}
}
the issue it that `ConnectException` is the inner exception of `ExecutionException` -- i'd suggest checking the `getCause()` value for `ConnectException`, and throwing SNFE if so and `Throwables.propagate()` if not
}
return objectMapper.readValue(response.getResponseBodyAsStream(), MESOS_FILE_OBJECTS);
+ } catch (ConnectException ce) {
throw new SlaveNotFoundException(ce);
} catch (Exception e) {
+ if (e.getCause().getClass() == ConnectException.class) {
+ throw new SlaveNotFoundException(e);
+ } else {
+ throw Throwables.propagate(e);
+ }
}
}
|
codereview_java_data_235
|
Types.NestedField.optional(icebergID, name, type);
}
- private static class OrcToIcebergVisitor extends OrcSchemaWithTypeVisitor<Optional<Types.NestedField>> {
private final Map<Integer, OrcField> icebergToOrcMapping;
Would it make sense to define an `OrcSchemaVisitor` visitor, similar to `org.apache.iceberg.avro.AvroSchemaVisitor`. Here we are not making use of the Iceberg type parameter at all and that could be a little confusing.
Types.NestedField.optional(icebergID, name, type);
}
+ private static class OrcToIcebergVisitor extends OrcSchemaVisitor<Optional<Types.NestedField>> {
private final Map<Integer, OrcField> icebergToOrcMapping;
|
codereview_java_data_237
|
import static org.assertj.core.api.Assertions.assertThat;
import tech.pegasys.pantheon.consensus.ibft.ibftmessage.CommitMessage;
import tech.pegasys.pantheon.consensus.ibft.ibftmessage.NewRoundMessage;
import tech.pegasys.pantheon.consensus.ibft.ibftmessage.PrepareMessage;
import tech.pegasys.pantheon.consensus.ibft.ibftmessage.ProposalMessage;
instead of using else if here we could use a switch here and use the message type for case. should make it bit easier to read. something like ``` switch (expectedPayload.getMessageType()) { case IbftV2.PROPOSAL: return ProposalMessage.fromMessage(actual).decode().equals(expected); case IbftV2.PREPARE: return PrepareMessage.fromMessage(actual).decode().equals(expected); ... ```
import static org.assertj.core.api.Assertions.assertThat;
+import java.util.Arrays;
import tech.pegasys.pantheon.consensus.ibft.ibftmessage.CommitMessage;
+import tech.pegasys.pantheon.consensus.ibft.ibftmessage.IbftV2;
import tech.pegasys.pantheon.consensus.ibft.ibftmessage.NewRoundMessage;
import tech.pegasys.pantheon.consensus.ibft.ibftmessage.PrepareMessage;
import tech.pegasys.pantheon.consensus.ibft.ibftmessage.ProposalMessage;
|
codereview_java_data_238
|
Column column = table.getColumn(columnName);
columnsToRemove.add(column);
} while (readIf(","));
- readIf(")"); // For Oracle compatibility - close bracket
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setColumnsToRemove(columnsToRemove);
you need a boolean if you read the first bracket, and then this line should be read(")") not readIf, otherwise we could accept some dodgy syntax :-)
Column column = table.getColumn(columnName);
columnsToRemove.add(column);
} while (readIf(","));
+ if (openingBracketDetected) {
+ read(")"); // For Oracle compatibility - close bracket
+ }
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setColumnsToRemove(columnsToRemove);
|
codereview_java_data_240
|
<h1>Error 503 Backend is unhealthy</h1>
<p>Backend is unhealthy</p>
<h3>Guru Mediation:</h3>
- <p>Details: cache-sea4456-SEA 1645539068 1201284252</p>
<hr>
<p>Varnish cache server</p>
</body>
I don't quite like that the responsibility for executing the actual call on the `ImapConnection` lies in this object. I'd rather this be part of an `ImapConnection.execute` method. As a suggestion: ``` abstract class <R extends FolderSelectedResponse> FolderStateSelectedCommand<R> { abstract R parseResponse(List<ImapResponse> unparsedResponses); } public class ImapConnection { public <R extends FolderSelectedResponse> R execute(FolderSelectedStateCommand<R> command) { // roughly what executeInternal does // obtains the list of commands from command.getCommands // parses the response from command.parseResponse to get the result } } ``` That way, the command classes only provide the commands as strings, and a way to parse the responses into specialized objects. Thoughts?
<h1>Error 503 Backend is unhealthy</h1>
<p>Backend is unhealthy</p>
<h3>Guru Mediation:</h3>
+ <p>Details: cache-sea4442-SEA 1645539068 1130943798</p>
<hr>
<p>Varnish cache server</p>
</body>
|
codereview_java_data_242
|
@RunWith(HazelcastSerialClassRunner.class)
public class JetInstanceTest extends JetTestSupport {
- private static final String UNABLE_CONNECTION_MESSAGE = "Unable to connect";
@Rule
public ExpectedException expectedException = ExpectedException.none();
should be `UNABLE_TO_CONNECT_MESSAGE`
@RunWith(HazelcastSerialClassRunner.class)
public class JetInstanceTest extends JetTestSupport {
+ private static final String UNABLE_TO_CONNECT_MESSAGE = "Unable to connect";
@Rule
public ExpectedException expectedException = ExpectedException.none();
|
codereview_java_data_247
|
* @param callback the callback {@link Consumer}
* @return the callback to enable fluent programming
*/
- public Consumer<Value<T>> onSetNextValue(Consumer<Value<T>> callback);
/**
* Removes an onSetNextValue callback.
There should be a corresponding add method
* @param callback the callback {@link Consumer}
* @return the callback to enable fluent programming
*/
+ // TODO rename to 'addOnSetNextValueCallback()'; apply same naming also for
+ // other callbacks
+ public void onSetNextValue(Consumer<Value<T>> callback);
/**
* Removes an onSetNextValue callback.
|
codereview_java_data_249
|
* Multiplies one mapping by another.
*
* <p>{@code multiply(A, B)} returns a mapping C such that A . B (the mapping
- * B followed by the mapping A) is equivalent to C.
*
* @param mapping1 First mapping
* @param mapping2 Second mapping
It should be "the mapping A followed by the mapping B"?
* Multiplies one mapping by another.
*
* <p>{@code multiply(A, B)} returns a mapping C such that A . B (the mapping
+ * A followed by the mapping B) is equivalent to C.
*
* @param mapping1 First mapping
* @param mapping2 Second mapping
|
codereview_java_data_255
|
* the pipeline aborted.
*
* <p>In most cases a Pipe is used through one of two narrower interfaces it supports {@link
- * InputPipe} and {@link OutputPipe}. These are designed to expose only the operations relevant to
* objects either reading from or publishing to the pipe respectively.
*
* @param <T> the type of item that flows through the pipe.
*/
-public class Pipe<T> implements InputPipe<T>, OutputPipe<T> {
private static final Logger LOG = LogManager.getLogger();
private final BlockingQueue<T> queue;
private final int capacity;
If the pipe is not open, should this return 0 ??
* the pipeline aborted.
*
* <p>In most cases a Pipe is used through one of two narrower interfaces it supports {@link
+ * ReadPipe} and {@link WritePipe}. These are designed to expose only the operations relevant to
* objects either reading from or publishing to the pipe respectively.
*
* @param <T> the type of item that flows through the pipe.
*/
+public class Pipe<T> implements ReadPipe<T>, WritePipe<T> {
private static final Logger LOG = LogManager.getLogger();
private final BlockingQueue<T> queue;
private final int capacity;
|
codereview_java_data_256
|
this.serialized = serialized;
}
- MaterialColor(int color500, int color900, int color700, String serialized) {
- this(color500, color500, color700, color700, color700, color900, serialized);
}
public int toConversationColor(@NonNull Context context) {
not down with the renaming, the class shouldn't be exposing these kinds of internals
this.serialized = serialized;
}
+ MaterialColor(int lightColor, int darkColor, int semiDarkColor, String serialized) {
+ this(lightColor, lightColor, semiDarkColor, semiDarkColor, semiDarkColor, darkColor, serialized);
}
public int toConversationColor(@NonNull Context context) {
|
codereview_java_data_281
|
return offers;
}
@Override
public void returnOffer(OfferID offerId) {
synchronized (offerCache) {
Saw a sentry come through for this the other day. This exception will bubble all the way back up to the LeaderOnlyPoller and cause us to abort. Should we maybe catch this and just skip the offer in the case that something else has it checked out?
return offers;
}
+ @Override
+ public List<Offer> peakOffers() {
+ List<Offer> offers = new ArrayList<>((int) offerCache.size());
+ for (CachedOffer cachedOffer : offerCache.asMap().values()) {
+ offers.add(cachedOffer.offer);
+ }
+ return offers;
+ }
+
@Override
public void returnOffer(OfferID offerId) {
synchronized (offerCache) {
|
codereview_java_data_282
|
}
public static final String MESSAGE_PARTS_MARKER = "_|_";
- public static Pattern MESSAGE_PARTS_MARKER_REGEX = Pattern.compile("_\\|_");
@Override
public void setMessage(String[] messageParts) {
I guess this should be final too?
}
public static final String MESSAGE_PARTS_MARKER = "_|_";
+ public static final Pattern MESSAGE_PARTS_MARKER_REGEX = Pattern.compile("_\\|_");
@Override
public void setMessage(String[] messageParts) {
|
codereview_java_data_283
|
private boolean isPortInUse(int port) {
try {
- new Socket("127.0.0.1", port).close();
- return true;
} catch(IOException e) {
// Could not connect.
}
- return false;
}
private SingularityTaskExecutorData readExecutorData(ObjectMapper objectMapper, Protos.TaskInfo taskInfo) {
You should create a ServerSocket on `0.0.0.0` to attempt to bind the port, rather than attempting to connect to it. There are a lot of reasons the connection to the port could fail, and it could even block for a bit trying to connect which would cause this function to hang. Additionally, there's no real guarantee in singularity that the app will bind to 127.0.0.1, it could just bind to the main IP of the host and you'd miss it, so binding 0.0.0.0 would ensure it's not listening to the port on any address.
private boolean isPortInUse(int port) {
try {
+ new ServerSocket(port, 1).close();
+ return false;
} catch(IOException e) {
// Could not connect.
}
+ return true;
}
private SingularityTaskExecutorData readExecutorData(ObjectMapper objectMapper, Protos.TaskInfo taskInfo) {
|
codereview_java_data_284
|
this.store = new Iterable<TabletLocationState>() {
@Override
public Iterator<TabletLocationState> iterator() {
- return Iterators.concat(new RootTabletStateStore(context).iterator(),
- new MetaDataStateStore(context).iterator());
}
};
}
Could call `liveServers.scanServers()` here making it more functionally equivalent to the old code. The old code used to call `liveServers.startListeningForTabletServerChanges()` which internally called `scanServers()` and registered a timer to call `scanServers()`. I don't think registering the timer is needed.
this.store = new Iterable<TabletLocationState>() {
@Override
public Iterator<TabletLocationState> iterator() {
+ try {
+ return Iterators.concat(new ZooTabletStateStore().iterator(),
+ new RootTabletStateStore(context).iterator(),
+ new MetaDataStateStore(context).iterator());
+ } catch (DistributedStoreException e) {
+ throw new RuntimeException(e);
+ }
}
};
}
|
codereview_java_data_301
|
this.threadChecker = threadChecker;
this.threadChecker.start(this);
- this.requestManager = requestManager;
- this.deployManager = deployManager;
- this.taskManager = taskManager;
-
this.tasks = Maps.newConcurrentMap();
this.processBuildingTasks = Maps.newConcurrentMap();
this.processRunningTasks = Maps.newConcurrentMap();
SingularityData stuff would be a very heavy dep to add into every executor. I do not think we want to add these here. - `requestManager` data your fetching here isn't actually being used - `HealthcheckOptions` we should feed in through the `SingularityTaskExecutorData` like you are doing with the path - There is no valuable information in saving health check results for the task since all we are doing is checking a file. There will essentially be a single pass/fail health check result, and we can even leave that as encoded in the task status update to keep things simpler if we want. The basics would be that the status update of running serves as our healthcheck success, or a status update of killing/failed/etc serves as our failure.
this.threadChecker = threadChecker;
this.threadChecker.start(this);
this.tasks = Maps.newConcurrentMap();
this.processBuildingTasks = Maps.newConcurrentMap();
this.processRunningTasks = Maps.newConcurrentMap();
|
codereview_java_data_302
|
* Instantiates an action to remove all the files reachable from given metadata location.
*/
default RemoveReachableFiles removeReachableFiles(String metadataLocation) {
- throw new UnsupportedOperationException(this.getClass().getName() + " does not implement" +
- " removeReachableFiles");
}
}
Can this be on one line?
* Instantiates an action to remove all the files reachable from given metadata location.
*/
default RemoveReachableFiles removeReachableFiles(String metadataLocation) {
+ throw new UnsupportedOperationException(this.getClass().getName() + " does not implement removeReachableFiles");
}
}
|
codereview_java_data_304
|
*
* @param forUpdateRows the rows to lock
*/
- public void lockRows(Iterator<Row> forUpdateRows) {
table.lockRows(session, forUpdateRows);
}
From my point of view It's better to preserve `ArrayList<Row>` here and change singature of `Table.lockRows()` to the `(Session, ArrayList<Row>)`. In this case C2 can optimize this code better. Also it's not common to pass iterators directly, `Iterable<Row>` can be used if `ArrayList` will not be used in all cases and it this case C2 also have better possibilities for optimizations.
*
* @param forUpdateRows the rows to lock
*/
+ public void lockRows(Iterable<Row> forUpdateRows) {
table.lockRows(session, forUpdateRows);
}
|
codereview_java_data_311
|
.url(urlBuilder.toString())
.build();
Response response = okHttpClient.newCall(request).execute();
- if (response.body() != null && response.isSuccessful()) {
String json = response.body().string();
return gson.fromJson(json, FeedbackResponse.class);
}
return null;
The issue seems to be caused by a SocketTimeoutException here. Now that the method is Nullable, should we catch that exception and return null as well?
.url(urlBuilder.toString())
.build();
Response response = okHttpClient.newCall(request).execute();
+ if (response != null && response.body() != null && response.isSuccessful()) {
String json = response.body().string();
+ if (json == null) {
+ return null;
+ }
return gson.fromJson(json, FeedbackResponse.class);
}
return null;
|
codereview_java_data_312
|
templates.add(templateName);
}
TemplateMetaData templateMeta = new TemplateMetaData();
templateMeta.setCurrentVersion(templateMetaData.getLatestVersion());
templateMetalist.add(templateMeta);
domainStruct.setTemplateMeta(templateMetalist);
this implementation doesn't look correct to me. we're setting a templateMetaList object which contains only a single templateMeta which only has a version number. where are the rest of the templates or where are the template names we're storing?
templates.add(templateName);
}
TemplateMetaData templateMeta = new TemplateMetaData();
+ templateMeta.setTemplateName(templateName);
+ templateMeta.setKeywordsToReplace(templateMetaData.getKeywordsToReplace());
+ templateMeta.setAutoUpdate(templateMetaData.getAutoUpdate());
+ templateMeta.setDescription(templateMetaData.getDescription());
+ templateMeta.setTimestamp(templateMetaData.getTimestamp());
templateMeta.setCurrentVersion(templateMetaData.getLatestVersion());
templateMetalist.add(templateMeta);
domainStruct.setTemplateMeta(templateMetalist);
|
codereview_java_data_313
|
private final Address recipient;
private final VoteType voteType;
public static final ImmutableBiMap<VoteType, Byte> voteToValue =
ImmutableBiMap.of(
- VoteType.ADD, (byte) 0xFF,
- VoteType.DROP, (byte) 0x0);
public Vote(final Address recipient, final VoteType voteType) {
this.recipient = recipient;
This probably should be private with just `ADD_NONCE` and `DROP_NONCE` as public constants.
private final Address recipient;
private final VoteType voteType;
+ public static final byte ADD_NONCE = (byte) 0xFF;
+ public static final byte DROP_NONCE = (byte) 0x0L;
+
public static final ImmutableBiMap<VoteType, Byte> voteToValue =
ImmutableBiMap.of(
+ VoteType.ADD, ADD_NONCE,
+ VoteType.DROP, DROP_NONCE);
public Vote(final Address recipient, final VoteType voteType) {
this.recipient = recipient;
|
codereview_java_data_321
|
@NeedAuth
@GetMapping("/datum")
- public String get(@RequestParam(name = "keys") String keysString,HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setHeader("Content-Type", "application/json; charset=" + getAcceptEncoding(request));
response.setHeader("Cache-Control", "no-cache");
Need code format.
@NeedAuth
@GetMapping("/datum")
+ public String get(@RequestParam(name = "keys") String keysString, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setHeader("Content-Type", "application/json; charset=" + getAcceptEncoding(request));
response.setHeader("Cache-Control", "no-cache");
|
codereview_java_data_329
|
* @deprecated since 2.0.0, replaced by {@link Accumulo#newClient()}
*/
@Deprecated
-public class ClientConfiguration extends CompositeConfiguration {
private static final Logger log = LoggerFactory.getLogger(ClientConfiguration.class);
public static final String USER_ACCUMULO_DIR_NAME = ".accumulo";
This went through a deprecation cycle in 1.9. It should not be re-added. We intentionally removed this to avoid non-public API leakage of commons-configuration stuff.
* @deprecated since 2.0.0, replaced by {@link Accumulo#newClient()}
*/
@Deprecated
+public class ClientConfiguration {
private static final Logger log = LoggerFactory.getLogger(ClientConfiguration.class);
public static final String USER_ACCUMULO_DIR_NAME = ".accumulo";
|
codereview_java_data_336
|
public long getTimestamp() {
return timestamp;
}
-
- public String toJson() {
- try {
- return new ObjectMapper().writeValueAsString(this);
- } catch (JsonProcessingException e) {
- throw new RuntimeException(e);
- }
- }
}
To be removed? I don't see where it is used and it makes the bean depends on jackson
public long getTimestamp() {
return timestamp;
}
}
|
codereview_java_data_338
|
/**
* Before moving next check if the required feilds are empty
- * */
-
public boolean areRequiredFieldsEmpty() {
if (mImageUrl == null || mImageUrl.equals("")) {
- Toast.makeText(OFFApplication.getInstance(), R.string.add_at_least_one_picture, Toast.LENGTH_SHORT).show();
- scrollView.fullScroll(View.FOCUS_UP);
return true;
} else {
return false;
```suggestion * Before moving next check if the required fields are empty ```
/**
* Before moving next check if the required feilds are empty
+ */
public boolean areRequiredFieldsEmpty() {
if (mImageUrl == null || mImageUrl.equals("")) {
+ Toast.makeText(getContext(), R.string.add_at_least_one_picture, Toast.LENGTH_SHORT).show();
+ binding.scrollView.fullScroll(View.FOCUS_UP);
return true;
} else {
return false;
|
codereview_java_data_339
|
}
public InclusiveMetricsEvaluator(Schema schema, Expression unbound, boolean caseSensitive) {
- final StructType struct = schema.asStruct();
this.expr = Binder.bind(struct, rewriteNot(unbound), caseSensitive);
}
Can you remove the unnecessary `final`?
}
public InclusiveMetricsEvaluator(Schema schema, Expression unbound, boolean caseSensitive) {
+ StructType struct = schema.asStruct();
this.expr = Binder.bind(struct, rewriteNot(unbound), caseSensitive);
}
|
codereview_java_data_342
|
}
}
- private boolean isCacheUpToDate(final RuleContext context) {
- return configuration.getAnalysisCache().isUpToDate(context.getSourceCodeFile());
- }
-
- private Iterable<RuleViolation> getCachedViolationsForFile(final File sourceCodeFile) {
- return configuration.getAnalysisCache().getCachedViolations(sourceCodeFile);
- }
-
private Node parse(RuleContext ctx, Reader sourceCode, Parser parser) {
long start = System.nanoTime();
Node rootNode = parser.parse(ctx.getSourceCodeFilename(), sourceCode);
these 2 methods have no reason to be in `SourceCodeProcessor` and add little value; I'd revert this
}
}
private Node parse(RuleContext ctx, Reader sourceCode, Parser parser) {
long start = System.nanoTime();
Node rootNode = parser.parse(ctx.getSourceCodeFilename(), sourceCode);
|
codereview_java_data_354
|
public static void outputShellVariables(Map<String,String> config, PrintStream out) {
for (String section : SECTIONS) {
if (config.containsKey(section)) {
- out.printf((PROPERTY_FORMAT) + "%n", section.toUpperCase() + "_HOSTS", config.get(section));
} else {
if (section.equals("manager") || section.equals("tserver")) {
throw new RuntimeException("Required configuration section is missing: " + section);
```suggestion out.printf(PROPERTY_FORMAT + "%n", section.toUpperCase() + "_HOSTS", config.get(section)); ```
public static void outputShellVariables(Map<String,String> config, PrintStream out) {
for (String section : SECTIONS) {
if (config.containsKey(section)) {
+ out.printf(PROPERTY_FORMAT, section.toUpperCase() + "_HOSTS", config.get(section));
} else {
if (section.equals("manager") || section.equals("tserver")) {
throw new RuntimeException("Required configuration section is missing: " + section);
|
codereview_java_data_358
|
}
private void reset() {
existingManifests.clear();
processedManifests.clear();
newManifests.clear();
By clearing `newManifests`, this loses track of any any manifests that were written by a previous call to `performRewrite`. Those should be deleted instead. Could you run `cleanAll` at the start of this method?
}
private void reset() {
+ cleanAll();
existingManifests.clear();
processedManifests.clear();
newManifests.clear();
|
codereview_java_data_376
|
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- ApplicationlessInjection
- - .getInstance(getActivity().getApplicationContext())
- - .getCommonsApplicationComponent()
- - .inject(this);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
What are these "-" means? Can you make sure your code is compiled with no issue, before pushing it? Currently it doesn't.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ ApplicationlessInjection
+ .getInstance(getActivity().getApplicationContext())
+ .getCommonsApplicationComponent()
+ .inject(this);
+
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
|
codereview_java_data_380
|
@Test
public void shouldLimitNumberOfResponsesToNodeDataRequests() throws Exception {
- new EthServer(
- blockchain,
- worldStateArchive,
- ethMessages,
- EthServer.DEFAULT_REQUEST_LIMIT,
- EthServer.DEFAULT_REQUEST_LIMIT,
- EthServer.DEFAULT_REQUEST_LIMIT,
- EthServer.DEFAULT_REQUEST_LIMIT);
when(worldStateArchive.getNodeData(HASH1)).thenReturn(Optional.of(VALUE1));
when(worldStateArchive.getNodeData(HASH2)).thenReturn(Optional.of(VALUE2));
ethMessages.dispatch(
Not sure how this is testing is passing with the default limit at 200. The intention of this test is to check that the server caps the amount of data returned.
@Test
public void shouldLimitNumberOfResponsesToNodeDataRequests() throws Exception {
+ new EthServer(blockchain, worldStateArchive, ethMessages);
when(worldStateArchive.getNodeData(HASH1)).thenReturn(Optional.of(VALUE1));
when(worldStateArchive.getNodeData(HASH2)).thenReturn(Optional.of(VALUE2));
ethMessages.dispatch(
|
codereview_java_data_382
|
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
intent.setType("image/png");
- startActivity(Intent.createChooser(intent, getString(R.string.achiev_activity_share_screen)));
} catch (IOException e) {
e.printStackTrace();
}
This could be made generic, share_image_via
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
intent.setType("image/png");
+ startActivity(Intent.createChooser(intent, getString(R.string.share_image_via)));
} catch (IOException e) {
e.printStackTrace();
}
|
codereview_java_data_390
|
break;
case KeyEvent.KEYCODE_B:
case KeyEvent.KEYCODE_T:
- OnKeyListenerForFragments myFragment =
- (OnKeyListenerForFragments) getSupportFragmentManager()
- .findFragmentById(R.id.main_view);
- if (myFragment != null) {
- myFragment.onKeyUp(keyCode);
- }
return true;
}
This looks like it will crash when pressing the keys for any fragment that is not the feed item list. Instead, I would take the event and send it using `EventBus.getDefault().post(event)`. You can then `@Subscribe` to it in the fragment directly (see other methods with that annotation in the fragment). This also reduces coupling between fragments and main activity.
break;
case KeyEvent.KEYCODE_B:
case KeyEvent.KEYCODE_T:
+ EventBus.getDefault().post(event);
return true;
}
|
codereview_java_data_395
|
.withCommand("-t4 -c128 -d100s http://frontend:8081 --latency");
startContainer(wrk);
- LOGGER.info("Benchmark started.");
if (zipkin != null) {
printContainerMapping(zipkin);
}
is the logger helping us? seems to add a bunch of redundant formatting :)
.withCommand("-t4 -c128 -d100s http://frontend:8081 --latency");
startContainer(wrk);
+ System.out.println("Benchmark started.");
if (zipkin != null) {
printContainerMapping(zipkin);
}
|
codereview_java_data_396
|
*/
@Override
public int compare(SearchResult o1, SearchResult o2) {
- if(o1.getComponent() instanceof FeedItem && o2.getComponent() instanceof FeedItem){
return ((FeedItem) o2.getComponent()).getPubDate().compareTo(((FeedItem) o1.getComponent()).getPubDate());
}
return 0;
Plesse add a space between `if` and `(`, as well as `)` and `{`
*/
@Override
public int compare(SearchResult o1, SearchResult o2) {
+ if (o1.getComponent() instanceof FeedItem && o2.getComponent() instanceof FeedItem) {
return ((FeedItem) o2.getComponent()).getPubDate().compareTo(((FeedItem) o1.getComponent()).getPubDate());
}
return 0;
|
codereview_java_data_404
|
-/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
-/* Generated By:JJTree: Do not edit this line. ASTDeclaration.java */
package net.sourceforge.pmd.lang.jsp.ast;
public class ASTDeclaration extends AbstractJspNode {
private String name;
`setName()` can be package-private as well
+/*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
+import net.sourceforge.pmd.annotation.InternalApi;
+
public class ASTDeclaration extends AbstractJspNode {
private String name;
|
codereview_java_data_407
|
private final String canonical;
protected AbstractId(final String canonical) {
- if (canonical == null || canonical.trim().isEmpty())
- throw new IllegalArgumentException("Id string provided can't be empty or null.");
- this.canonical = canonical;
}
/**
Since the parameter name is "canonical", it'd be good to use that word when referencing the parameter. ```suggestion throw new IllegalArgumentException("canonical id provided can't be empty or null."); ```
private final String canonical;
protected AbstractId(final String canonical) {
+ this.canonical = Objects.requireNonNull(canonical, "canonical cannot be null");
}
/**
|
codereview_java_data_411
|
/**
* Return the current schema version for the host.
* <p/>
- * Schema versions in Cassandra are used to insure all the nodes agree on the current
* Cassandra schema when it is modified. For more information see {@link ExecutionInfo#isSchemaInAgreement()}
*
* @return the node's current schema version value.
Small nit: `insure` should be `ensure`
/**
* Return the current schema version for the host.
* <p/>
+ * Schema versions in Cassandra are used to ensure all the nodes agree on the current
* Cassandra schema when it is modified. For more information see {@link ExecutionInfo#isSchemaInAgreement()}
*
* @return the node's current schema version value.
|
codereview_java_data_419
|
int theme = getTheme();
if (theme == R.style.Theme_AntennaPod_Dark) {
return R.style.Theme_AntennaPod_Dark_NoTitle;
- }else if (theme == R.style.Theme_AntennaPod_TrueBlack){
return R.style.Theme_AntennaPod_TrueBlack_NoTitle;
} else {
return R.style.Theme_AntennaPod_Light_NoTitle;
There are spaces missing ;) Just have a look at the code style of the `if` statement above
int theme = getTheme();
if (theme == R.style.Theme_AntennaPod_Dark) {
return R.style.Theme_AntennaPod_Dark_NoTitle;
+ } else if (theme == R.style.Theme_AntennaPod_TrueBlack) {
return R.style.Theme_AntennaPod_TrueBlack_NoTitle;
} else {
return R.style.Theme_AntennaPod_Light_NoTitle;
|
codereview_java_data_420
|
package software.amazon.awssdk.regions;
/**
* Metadata about a partition such as aws or aws-cn.
*
* <p>This is useful for building meta-functionality around AWS services. Partition metadata helps to provide
* data about regions which may not yet be in the endpoints.json file but have a specific prefix.</p>
*/
public interface PartitionMetadata {
/**
checktyle might fail because of missing sdk annotation
package software.amazon.awssdk.regions;
+import software.amazon.awssdk.annotations.SdkPublicApi;
+
/**
* Metadata about a partition such as aws or aws-cn.
*
* <p>This is useful for building meta-functionality around AWS services. Partition metadata helps to provide
* data about regions which may not yet be in the endpoints.json file but have a specific prefix.</p>
*/
+@SdkPublicApi
public interface PartitionMetadata {
/**
|
codereview_java_data_429
|
case "Long":
return currentNode.asLong();
case "Short":
- return (short) currentNode.asDouble();
case "Integer":
return currentNode.asInt();
case "String":
Query :Why asDouble and not .asInt(); ?
case "Long":
return currentNode.asLong();
case "Short":
+ return (short) currentNode.asInt();
case "Integer":
return currentNode.asInt();
case "String":
|
codereview_java_data_431
|
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.batchmanager.BatchOverrideConfiguration;
import software.amazon.awssdk.services.sqs.SqsAsyncClient;
-import software.amazon.awssdk.services.sqs.internal.batchmanager.DefaultSqsAsyncBatchManager;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityResponse;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
Should we throw UnsupportedOperation? That's what we do for the APIs in the low level client interface
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.batchmanager.BatchOverrideConfiguration;
import software.amazon.awssdk.services.sqs.SqsAsyncClient;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityResponse;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
|
codereview_java_data_444
|
try {
negativeTtl = Integer.parseInt(Security.getProperty("networkaddress.cache.negative.ttl"));
} catch (NumberFormatException exception) {
- log.warn("Failed to get JVM negative DNS responses cache TTL due to format problem "
+ "(e.g. this JVM might not have the property). "
+ "Falling back to default based on Oracle JVM 1.4+ (10s)", exception);
} catch (SecurityException exception) {
Maybe response? ``` suggest log.warn("Failed to get JVM negative DNS response cache TTL due to format problem " ```
try {
negativeTtl = Integer.parseInt(Security.getProperty("networkaddress.cache.negative.ttl"));
} catch (NumberFormatException exception) {
+ log.warn("Failed to get JVM negative DNS response cache TTL due to format problem "
+ "(e.g. this JVM might not have the property). "
+ "Falling back to default based on Oracle JVM 1.4+ (10s)", exception);
} catch (SecurityException exception) {
|
codereview_java_data_454
|
LocalRepository localRepo = new LocalRepository(localRepoPath);
session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
session.setOffline(this.offline);
- if (this.mavenProperties != null && this.mavenProperties.getConnectTimeout() > 0) {
- session.setConfigProperty("aether.connector.connectTimeout", this.mavenProperties.getConnectTimeout());
}
- if (this.mavenProperties != null && this.mavenProperties.getRequestTimeout() > 0) {
- session.setConfigProperty("aether.connector.requestTimeout", this.mavenProperties.getRequestTimeout());
}
if (isProxyEnabled()) {
DefaultProxySelector proxySelector = new DefaultProxySelector();
should use the constants in Aether's `ConfigurationProperties` instead of the String keys
LocalRepository localRepo = new LocalRepository(localRepoPath);
session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
session.setOffline(this.offline);
+ if (this.mavenProperties != null && this.mavenProperties.getConnectTimeout() != null) {
+ session.setConfigProperty(ConfigurationProperties.CONNECT_TIMEOUT, this.mavenProperties.getConnectTimeout());
}
+ if (this.mavenProperties != null && this.mavenProperties.getRequestTimeout() != null) {
+ session.setConfigProperty(ConfigurationProperties.REQUEST_TIMEOUT, this.mavenProperties.getRequestTimeout());
}
if (isProxyEnabled()) {
DefaultProxySelector proxySelector = new DefaultProxySelector();
|
codereview_java_data_460
|
@BindView(R.id.contributionSequenceNumber) TextView seqNumView;
@BindView(R.id.contributionProgress) ProgressBar progressView;
@BindView(R.id.failed_image_options) LinearLayout failedImageOptions;
- @BindView(R.id.failed_image_options_retry) LinearLayout failedImageOptionsretry;
private DisplayableContribution contribution;
Ideally this PR should only edit .xml file. Since buttons are already defined and works fine. Please solve this issue by just editing .xml file, ie. adding a space between them
@BindView(R.id.contributionSequenceNumber) TextView seqNumView;
@BindView(R.id.contributionProgress) ProgressBar progressView;
@BindView(R.id.failed_image_options) LinearLayout failedImageOptions;
private DisplayableContribution contribution;
|
codereview_java_data_462
|
// variable
private volatile boolean enable = SystemConfig.getInstance().getEnableStatistic() == 1;
- private volatile int statisticTableSize = SystemConfig.getInstance().getStatisticTableSize();
private int statisticQueueSize = SystemConfig.getInstance().getStatisticQueueSize();
private StatisticManager() {
disruptor = new StatisticDisruptor(statisticQueueSize, (StatisticDataHandler[]) statisticDataHandlers.values().toArray()); ?
// variable
private volatile boolean enable = SystemConfig.getInstance().getEnableStatistic() == 1;
+ private volatile int associateTablesByEntryByUserTableSize = SystemConfig.getInstance().getAssociateTablesByEntryByUserTableSize();
+ private volatile int frontendByBackendByEntryByUserTableSize = SystemConfig.getInstance().getFrontendByBackendByEntryByUserTableSize();
+ private volatile int tableByUserByEntryTableSize = SystemConfig.getInstance().getTableByUserByEntryTableSize();
private int statisticQueueSize = SystemConfig.getInstance().getStatisticQueueSize();
private StatisticManager() {
|
codereview_java_data_467
|
* This class was copied from Guava release 23.0 to replace the older Guava 14 version that had been used in Accumulo.
* It was annotated as Beta by Google, therefore unstable to use in a core Accumulo library. We learned this the hard
* way when Guava version 20 deprecated the getHostText method and then removed the method all together in version 22.
*
* Unused methods and annotations were removed to reduce maintenance costs.
*
could reference the issue number
* This class was copied from Guava release 23.0 to replace the older Guava 14 version that had been used in Accumulo.
* It was annotated as Beta by Google, therefore unstable to use in a core Accumulo library. We learned this the hard
* way when Guava version 20 deprecated the getHostText method and then removed the method all together in version 22.
+ * See ACCUMULO-4702
*
* Unused methods and annotations were removed to reduce maintenance costs.
*
|
codereview_java_data_469
|
media.generateThumbnail(inputFile, getFormat(), getType(), seekPosition, isResume(), renderer);
if (!isResume() && media.getThumb() != null && configurationSpecificToRenderer.getUseCache() && inputFile.getFile() != null) {
- Connection connection = null;
- try {
- connection = MediaDatabase.getConnectionIfAvailable();
- if (connection != null) {
- MediaTableThumbnails.setThumbnail(connection, media.getThumb(), inputFile.getFile().getAbsolutePath(), -1);
- }
- } finally {
- MediaDatabase.close(connection);
- }
}
}
}
I wonder if we can have the best of both worlds by _allowing_ an incoming connection, but if one doesn't exist, the method itself (in this case `MediaTableThumbnails.setThumbnail`) makes a new one? That way if we have a chain of db operations to do, we can use the same connection, but in cases like this one we don't have to create one in the caller for just one operation. Is that too messy logically? I'm interested in your opinion
media.generateThumbnail(inputFile, getFormat(), getType(), seekPosition, isResume(), renderer);
if (!isResume() && media.getThumb() != null && configurationSpecificToRenderer.getUseCache() && inputFile.getFile() != null) {
+ MediaTableThumbnails.setThumbnail(media.getThumb(), inputFile.getFile().getAbsolutePath(), -1);
}
}
}
|
codereview_java_data_475
|
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.junit.After;
import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.collect.Iterables;
public class AccumuloClientIT extends AccumuloClusterHarness {
- Logger log = LoggerFactory.getLogger(AccumuloClientIT.class);
-
@After
public void deleteUsers() throws Exception {
try (AccumuloClient client = Accumulo.newClient().from(getClientProps()).build()) {
This seems to be a new logger, but I don't see any new log messages in this PR. Is this unused?
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.junit.After;
import org.junit.Test;
import com.google.common.collect.Iterables;
public class AccumuloClientIT extends AccumuloClusterHarness {
@After
public void deleteUsers() throws Exception {
try (AccumuloClient client = Accumulo.newClient().from(getClientProps()).build()) {
|
codereview_java_data_477
|
+ qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1);
try {
myType = pmdClassLoader.loadClass(qualifiedNameInner);
- } catch (Exception ignored) {
// ignored, we'll try again with a different package name/fqcn
} catch (LinkageError e) {
// we found the class, but there is a problem with it (see https://github.com/pmd/pmd/issues/1131)
We should probable catch here just "ClassNotFoundException", too - at least, to make it consistent...
+ qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1);
try {
myType = pmdClassLoader.loadClass(qualifiedNameInner);
+ } catch (ClassNotFoundException ignored) {
// ignored, we'll try again with a different package name/fqcn
} catch (LinkageError e) {
// we found the class, but there is a problem with it (see https://github.com/pmd/pmd/issues/1131)
|
codereview_java_data_483
|
* @see SummarizerConfiguration#getOptions()
*/
public Builder addOptions(Map<String,String> options) {
- options.forEach((key, value) -> addOption(key, value));
return this;
}
You can even go a step further with this one: ```suggestion options.forEach(this::addOption); ```
* @see SummarizerConfiguration#getOptions()
*/
public Builder addOptions(Map<String,String> options) {
+ options.forEach(this::addOption);
return this;
}
|
codereview_java_data_489
|
taskId.getId()
);
purgeFromZk(taskId);
}
- LOG.error("Task ID {} too long to pesist to DB, skipping", taskId.getId());
} else {
if (moveToHistoryOrCheckForPurge(taskId, forRequest)) {
LOG.debug("Transferred task {}", taskId);
nit, can put that log line in an else so we don't get the double log line when it's actually deleted and not skipped
taskId.getId()
);
purgeFromZk(taskId);
+ } else {
+ LOG.error(
+ "Task ID {} too long to persist to DB, skipping",
+ taskId.getId()
+ );
}
} else {
if (moveToHistoryOrCheckForPurge(taskId, forRequest)) {
LOG.debug("Transferred task {}", taskId);
|
codereview_java_data_495
|
}
public BaseVectorizedParquetValuesReader(int bitWidth, int maxDefLevel, boolean setValidityVector) {
- this.fixedWidth = true;
- this.readLength = bitWidth != 0;
- this.maxDefLevel = maxDefLevel;
- this.setArrowValidityVector = setValidityVector;
- init(bitWidth);
}
public BaseVectorizedParquetValuesReader(int bitWidth, int maxDefLevel, boolean readLength,
It seems a little strange to me that we have this constructor which we only use when readLength is false. Perhaps we should swap the original constructor's code to call this constructor? ```java public BaseVectorizedParquetValuesReader(int bitWidth, int maxDefLevel, boolean setValidityVector) { this(bitWidth, maxDefLevel, bitWidth != 0, setValidityVector) } ```
}
public BaseVectorizedParquetValuesReader(int bitWidth, int maxDefLevel, boolean setValidityVector) {
+ this(bitWidth, maxDefLevel, bitWidth != 0, setValidityVector);
}
public BaseVectorizedParquetValuesReader(int bitWidth, int maxDefLevel, boolean readLength,
|
codereview_java_data_500
|
private @Nullable Recipients conversationRecipients;
private @NonNull Stub<ThumbnailView> mediaThumbnailStub;
private @NonNull Stub<AudioView> audioViewStub;
private @NonNull ExpirationTimerView expirationTimer;
private int defaultBubbleColor;
- private int sentTextPrimColor;
private final PassthroughClickListener passthroughClickListener = new PassthroughClickListener();
private final AttachmentDownloadClickListener downloadClickListener = new AttachmentDownloadClickListener();
no abbreviations please
private @Nullable Recipients conversationRecipients;
private @NonNull Stub<ThumbnailView> mediaThumbnailStub;
private @NonNull Stub<AudioView> audioViewStub;
+ private @NonNull Stub<DocumentView> documentViewStub;
private @NonNull ExpirationTimerView expirationTimer;
private int defaultBubbleColor;
+ private int sentTextPrimaryColor;
private final PassthroughClickListener passthroughClickListener = new PassthroughClickListener();
private final AttachmentDownloadClickListener downloadClickListener = new AttachmentDownloadClickListener();
|
codereview_java_data_508
|
System.exit(1);
}
- String name ="sampleQuery" ; //args[0];
AthenaClient athenaClient = AthenaClient.builder()
.region(Region.US_WEST_2)
.build();
Did you intend to ignore the command line arg?
System.exit(1);
}
+ String name = args[0];
AthenaClient athenaClient = AthenaClient.builder()
.region(Region.US_WEST_2)
.build();
|
codereview_java_data_509
|
manifest -> Objects.equal(manifest.snapshotId(), snapshotId));
try (CloseableIterable<ManifestEntry> entries = new ManifestGroup(ops, changedManifests)
.ignoreExisting()
- .select("file_path", "file_format", "partition", "record_count", "file_size_in_bytes")
.entries()) {
for (ManifestEntry entry : entries) {
switch (entry.status()) {
nit: might we worthwhile to use `ManifestReader#CHANGE_COLUNNS` here.
manifest -> Objects.equal(manifest.snapshotId(), snapshotId));
try (CloseableIterable<ManifestEntry> entries = new ManifestGroup(ops, changedManifests)
.ignoreExisting()
+ .select(ManifestReader.CHANGE_COLUNNS)
.entries()) {
for (ManifestEntry entry : entries) {
switch (entry.status()) {
|
codereview_java_data_510
|
}
}
private void askDexterToHandleExternalStoragePermission() {
Timber.d(TAG, "External storage permission is being requested");
if (null == dexterStoragePermissionBuilder) {
Please don't split this line, it does not improve readability. :)
}
}
+ /**
+ * This method initialised the Dexter's permission builder (if not already initialised). Also makes sure that the builder is initialised
+ * only once, otherwise we would'nt know on which instance of it, the user is working on. And after the builder is initialised, it checks for the required
+ * permission and then handles the permission status, thanks to Dexter's appropriate callbacks.
+ */
private void askDexterToHandleExternalStoragePermission() {
Timber.d(TAG, "External storage permission is being requested");
if (null == dexterStoragePermissionBuilder) {
|
codereview_java_data_515
|
@CliOption(mandatory = true, key = {
"expression" }, help = "the cron expression of the schedule") String expression,
@CliOption(key = {
- PROPERTIES_OPTION }, help = "a task properties (coma separated string eg.: --properties 'prop.first=prop,prop.sec=prop2'") String properties,
@CliOption(key = {
PROPERTIES_FILE_OPTION }, help = "the properties for this deployment (as a File)") File propertiesFile,
@CliOption(key = {
Just noticed that comma is misspelled.
@CliOption(mandatory = true, key = {
"expression" }, help = "the cron expression of the schedule") String expression,
@CliOption(key = {
+ PROPERTIES_OPTION }, help = "a task properties (comma separated string eg.: --properties 'prop.first=prop,prop.sec=prop2'") String properties,
@CliOption(key = {
PROPERTIES_FILE_OPTION }, help = "the properties for this deployment (as a File)") File propertiesFile,
@CliOption(key = {
|
codereview_java_data_522
|
holder.placeTypeLayout.setBackgroundColor(label.isSelected() ? ContextCompat.getColor(context, R.color.divider_grey) : Color.WHITE);
NearbyParentFragmentPresenter.getInstance().filterByMarkerType(selectedLabels);
});
-
- //TODO: recover current location marker if selection is empty
}
@Override
Does this still need to be done?
holder.placeTypeLayout.setBackgroundColor(label.isSelected() ? ContextCompat.getColor(context, R.color.divider_grey) : Color.WHITE);
NearbyParentFragmentPresenter.getInstance().filterByMarkerType(selectedLabels);
});
}
@Override
|
codereview_java_data_527
|
}
private AuthenticationException onError(JwtException e) {
- if (logger.isDebugEnabled()) {
- logger.debug("Authentication error for Jwt Token: " + e.getMessage());
- }
if (e instanceof BadJwtException) {
return new InvalidBearerTokenException(e.getMessage(), e);
} else {
I'm not seeing the added benefit of this one since `AuthenticationWebFilter` displays the same information. Is it necessary?
}
private AuthenticationException onError(JwtException e) {
if (e instanceof BadJwtException) {
return new InvalidBearerTokenException(e.getMessage(), e);
} else {
|
codereview_java_data_528
|
if (isSupported(dmnType)) {
Optional<AbstractDmnType> type = supportedDmnTypes.stream().filter(x -> x.getDmnType().equalsIgnoreCase(dmnType)).findFirst();
if (type.isPresent()) {
- return Optional.of(type.get().getGrafanaFunction());
}
}
return Optional.empty();
Can `getGrafanaFunction()` return `null`? If so it is safer to use ```suggestion return Optional.ofNullable(type.get().getGrafanaFunction()); ```
if (isSupported(dmnType)) {
Optional<AbstractDmnType> type = supportedDmnTypes.stream().filter(x -> x.getDmnType().equalsIgnoreCase(dmnType)).findFirst();
if (type.isPresent()) {
+ return Optional.ofNullable(type.get().getGrafanaFunction());
}
}
return Optional.empty();
|
codereview_java_data_542
|
if ((method != LoadBalancerMethod.CHECK_STATE && method != LoadBalancerMethod.PRE_ENQUEUE) &&
result.state == BaragonRequestState.FAILED
- && result.message.orElse("").contains("is already enqueued with different parameters")) {
LOG.info("Baragon request {} already in the queue, will fetch current state instead", loadBalancerRequestId.getId());
return sendRequestWrapper(loadBalancerRequestId, LoadBalancerMethod.CHECK_STATE, request, onFailure);
}
Bit of a nit, but is there any cleaner way to check for this state other than matching the against the message string? Or if we do have to do a string match, can we put the string into a constant somewhere?
if ((method != LoadBalancerMethod.CHECK_STATE && method != LoadBalancerMethod.PRE_ENQUEUE) &&
result.state == BaragonRequestState.FAILED
+ && result.message.orElse("").contains(ALREADY_ENQUEUED_ERROR)) {
LOG.info("Baragon request {} already in the queue, will fetch current state instead", loadBalancerRequestId.getId());
return sendRequestWrapper(loadBalancerRequestId, LoadBalancerMethod.CHECK_STATE, request, onFailure);
}
|
codereview_java_data_543
|
@Test
public void shouldCollectDefinedValueUsingPartialFunction() {
- final PartialFunction<Integer, String> pf = new PartialFunction<Integer, String>() {
- @Override
- public String apply(Integer i) {
- return String.valueOf(i);
- }
- @Override
- public boolean isDefinedAt(Integer i) {
- return i % 2 == 1;
- }
- };
final Future<String> future = Future.of(zZz(3)).collect(pf);
waitUntil(future::isCompleted);
assertThat(future.getValue().get()).isEqualTo(Try.success("3"));
Please reduce the duplicate code in all tests ```diff + final PartialFunction<Integer, String> pf = new PartialFunction<Integer, String>() { + @Override + public String apply(Integer i) { + return String.valueOf(i); + } + @Override + public boolean isDefinedAt(Integer i) { + return i % 2 == 1; + } + }; ``` with this more concise variant: ```java final PartialFunction<Integer, String> pf = Function1.<Integer, String> of(String::valueOf).partial(i -> i % 2 == 1); ``` (or `Function1.of(String::valueOf).partial(i -> i % 2 == 1);` ???)
@Test
public void shouldCollectDefinedValueUsingPartialFunction() {
+ final PartialFunction<Integer, String> pf = Function1.<Integer, String> of(String::valueOf).partial(i -> i % 2 == 1);
final Future<String> future = Future.of(zZz(3)).collect(pf);
waitUntil(future::isCompleted);
assertThat(future.getValue().get()).isEqualTo(Try.success("3"));
|
codereview_java_data_556
|
if (!compress) {
return encode();
}
-
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DeflaterOutputStream outputStream = new DeflaterOutputStream(byteArrayOutputStream, new Deflater(Deflater.BEST_COMPRESSION));
DataVersion dataVersion = topicConfigSerializeWrapper.getDataVersion();
I think `Deflater.BEST_COMPRESSION` may be even slower than GZIP. Do we care about compression speed?
if (!compress) {
return encode();
}
+ long start = System.currentTimeMillis();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DeflaterOutputStream outputStream = new DeflaterOutputStream(byteArrayOutputStream, new Deflater(Deflater.BEST_COMPRESSION));
DataVersion dataVersion = topicConfigSerializeWrapper.getDataVersion();
|
codereview_java_data_559
|
private static final String NAMESPACE = "default";
- // Error message
- private static final String OUTPUT_DIFFERENT_ERROR_MSG =
- "Output data different between iceberg and non-iceberg table";
-
@Parameterized.Parameters(name = "Catalog Name {0} - Options {2}")
public static Object[][] parameters() {
return new Object[][] {
nit: I think it is alright to use the error message in place. To stay on one line, we can simplify the message like `Output must match` or anything appropriate.
private static final String NAMESPACE = "default";
@Parameterized.Parameters(name = "Catalog Name {0} - Options {2}")
public static Object[][] parameters() {
return new Object[][] {
|
codereview_java_data_568
|
this.configuration = configuration;
this.exceptionNotifier = exceptionNotifier;
- this.checkFileOpenLock = new ReentrantLock();
}
protected abstract void uploadSingle(int sequence, Path file) throws Exception;
Just checking, is this class always a singleton? Want to make sure we aren't just creating multiple locks. I had thought the singleton was the uploader driver, not the uploader
this.configuration = configuration;
this.exceptionNotifier = exceptionNotifier;
+ this.checkFileOpenLock = checkFileOpenLock;
}
protected abstract void uploadSingle(int sequence, Path file) throws Exception;
|
codereview_java_data_570
|
// check rogue syntax in spec module
Set<Sentence> toCheck = mutable(specModule.sentences().$minus$minus(mainDefModule.sentences()));
for (Sentence s : toCheck)
- if (s instanceof Production || s instanceof SyntaxSort || s instanceof SyntaxLexical ||
- s instanceof SyntaxPriority || s instanceof SyntaxAssociativity)
kem.registerCompilerWarning(ExceptionType.FUTURE_ERROR, errors,
"Found syntax declaration in proof module. This will not be visible from the main module.", s);
There isn't some `Syntax` super-class you can use instead of listing all these out? @dwightguth should probably check that this check is being done in the correct place, output looks OK to me.
// check rogue syntax in spec module
Set<Sentence> toCheck = mutable(specModule.sentences().$minus$minus(mainDefModule.sentences()));
for (Sentence s : toCheck)
+ if (s.isSyntax())
kem.registerCompilerWarning(ExceptionType.FUTURE_ERROR, errors,
"Found syntax declaration in proof module. This will not be visible from the main module.", s);
|
codereview_java_data_571
|
staticFromMap.addStatement(new AssignExpr(nameField, new NameExpr("name"), AssignExpr.Operator.ASSIGN));
for (Entry<String, String> entry : humanTaskNode.getInMappings().entrySet()) {
- Variable variable = variableScope.findVariable(entry.getValue());
if (variable == null) {
- variable = processVariableScope.findVariable(entry.getValue());
- if (variable == null) {
- throw new IllegalStateException("Task " + humanTaskNode.getName() +" (input) " + entry.getKey() + " reference not existing variable " + entry.getValue());
- }
}
FieldDeclaration fd = new FieldDeclaration().addVariable(
what about using Variable variable = Optional.ofNullable(variableScope.findVariable(entry.getValue())) .orElse(processVariableScope.findVariable(entry.getValue()));
staticFromMap.addStatement(new AssignExpr(nameField, new NameExpr("name"), AssignExpr.Operator.ASSIGN));
for (Entry<String, String> entry : humanTaskNode.getInMappings().entrySet()) {
+
+ Variable variable = Optional.ofNullable(variableScope.findVariable(entry.getValue()))
+ .orElse(processVariableScope.findVariable(entry.getValue()));
if (variable == null) {
+ throw new IllegalStateException("Task " + humanTaskNode.getName() +" (input) " + entry.getKey() + " reference not existing variable " + entry.getValue());
}
FieldDeclaration fd = new FieldDeclaration().addVariable(
|
codereview_java_data_575
|
public static final String COMMIT_TOTAL_RETRY_TIME_MS = "commit.retry.total-timeout-ms";
public static final int COMMIT_TOTAL_RETRY_TIME_MS_DEFAULT = 1800000; // 30 minutes
- public static final String COMMIT_NUM_STATUS_CHECKS = "commit.num-status-checks";
public static final int COMMIT_NUM_STATUS_CHECKS_DEFAULT = 3;
public static final String COMMIT_STATUS_CHECKS_MIN_WAIT_MS = "commit.status-check.min-wait-ms";
@coolderli, @aokolnychyi, has `commit.num-status-checks` been released yet? If not, then we should rename it to mirror the `commit.retry.*` settings: `commit.status-check.num-retries`
public static final String COMMIT_TOTAL_RETRY_TIME_MS = "commit.retry.total-timeout-ms";
public static final int COMMIT_TOTAL_RETRY_TIME_MS_DEFAULT = 1800000; // 30 minutes
+ public static final String COMMIT_NUM_STATUS_CHECKS = "commit.status-checks.num-retries";
public static final int COMMIT_NUM_STATUS_CHECKS_DEFAULT = 3;
public static final String COMMIT_STATUS_CHECKS_MIN_WAIT_MS = "commit.status-check.min-wait-ms";
|
codereview_java_data_581
|
if(currentProfile == null)
return;
if(currentProfile.getUnits().equals(Constants.MMOL))
- tt = prefTT > 0 ? Profile.toMgdl(prefTT, Constants.MGDL) : 80d;
else
tt = prefTT > 0 ? prefTT : 80d;
final double finalTT = tt;
This must be `tt = prefTT > 0 ? Profile.toMgdl(prefTT, Constants.MMOL) : 80d;` as we are in the MMOL branch. It should be possible to reduce the whole if-else construct by something like `tt = prefTT > 0 ? Profile.toMgdl(prefTT, currentProfile.getUnits()) : 80d;`
if(currentProfile == null)
return;
if(currentProfile.getUnits().equals(Constants.MMOL))
+ tt = prefTT > 0 ? Profile.toMgdl(prefTT, Constants.MMOL) : 80d;
else
tt = prefTT > 0 ? prefTT : 80d;
final double finalTT = tt;
|
codereview_java_data_583
|
return typeDeclaration;
}
- @Override
- protected boolean useApplication() {
- return false;
- }
-
private void populateStaticKieRuntimeFactoryFunctionInit(ClassOrInterfaceDeclaration typeDeclaration) {
final InitializerDeclaration staticDeclaration = typeDeclaration.getMembers()
.stream()
To be removed? This override has been removed from DecisionContainerGenerator so I expect it can be removed here too
return typeDeclaration;
}
private void populateStaticKieRuntimeFactoryFunctionInit(ClassOrInterfaceDeclaration typeDeclaration) {
final InitializerDeclaration staticDeclaration = typeDeclaration.getMembers()
.stream()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.