id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_584
} private int getRetentionDays() { - String val = env.getProperty("retention.days"); if (null == val) { return retentionDays; } It's better to use property in application.properties. And the property name should be with prefix 'nacos.config'. } private int getRetentionDays() { + String val = env.getProperty("nacos.config.retention.days"); if (null == val) { return retentionDays; }
codereview_java_data_586
// ResolvedCatalogTable class into the iceberg-flink-runtime jar for compatibility purpose. private static final DynMethods.UnboundMethod GET_CATALOG_TABLE = DynMethods.builder("getCatalogTable") .impl(Context.class, "getCatalogTable") .build(); private final FlinkCatalog catalog; Won't this fail if there is no `getCatalogTable` method? And if the method exists then it wouldn't need to be called dynamically. You may need a `orNoop()` call here. // ResolvedCatalogTable class into the iceberg-flink-runtime jar for compatibility purpose. private static final DynMethods.UnboundMethod GET_CATALOG_TABLE = DynMethods.builder("getCatalogTable") .impl(Context.class, "getCatalogTable") + .orNoop() .build(); private final FlinkCatalog catalog;
codereview_java_data_587
return MPEGPS; } - if (supportSpec.match(MPEGTS, MPEG2, AC3) || supportSpec.match(MPEGTS, MPEG2, AAC)) { return MPEGTS; } Wouldn't it be (MPEGTS, H264, AAC)? return MPEGPS; } + if (supportSpec.match(MPEGTS, MPEG2, AC3) || supportSpec.match(MPEGTS, H264, AAC)) { return MPEGTS; }
codereview_java_data_593
contributionsFragment.backButtonClicked(); } else if (nearbyParentFragment != null && activeFragment == ActiveFragment.NEARBY) { // Means that nearby fragment is visible - // function nearbyParentFragment.backButtonClick() return false mean bottomsheet is not expand then if backbutton pressed then come to Contributions tab if(!nearbyParentFragment.backButtonClicked()){ getSupportFragmentManager().beginTransaction().remove(nearbyParentFragment).commit(); setSelectedItemId(NavTab.CONTRIBUTIONS.code()); Minor change: Could you please rephrase to: `If function nearbyParentFragment.backButtonClick() returns false, it means that the bottomsheet is not expanded. So if the back button is pressed, then go back to the Contributions tab`. Thanks! contributionsFragment.backButtonClicked(); } else if (nearbyParentFragment != null && activeFragment == ActiveFragment.NEARBY) { // Means that nearby fragment is visible + // function nearbyParentFragment.backButtonClick() return false mean bottomsheet + // is not expand then if backbutton pressed then come to Contributions tab if(!nearbyParentFragment.backButtonClicked()){ getSupportFragmentManager().beginTransaction().remove(nearbyParentFragment).commit(); setSelectedItemId(NavTab.CONTRIBUTIONS.code());
codereview_java_data_601
{ adapterResult.addFragment( new NutritionProductFragment(), menuTitles[2] ); adapterResult.addFragment( new NutritionInfoProductFragment(), menuTitles[3] ); - adapterResult.addFragment( new EnvironmentProductFragment(), "Environment" ); if( PreferenceManager.getDefaultSharedPreferences( this ).getBoolean( "photoMode", false ) ) { adapterResult.addFragment( new ProductPhotosFragment(), "Product Photos" ); You need to add this to `menuTitles` string array and then reference it here. Do the same for other entries that may have missed this logic. { adapterResult.addFragment( new NutritionProductFragment(), menuTitles[2] ); adapterResult.addFragment( new NutritionInfoProductFragment(), menuTitles[3] ); + if( mState.getProduct().getNutriments().contains(Nutriments.CARBON_FOOTPRINT) ) + { + adapterResult.addFragment( new EnvironmentProductFragment(), "Environment" ); + } if( PreferenceManager.getDefaultSharedPreferences( this ).getBoolean( "photoMode", false ) ) { adapterResult.addFragment( new ProductPhotosFragment(), "Product Photos" );
codereview_java_data_604
public synchronized void shutdown() { if (this.producerNum.decrementAndGet() == 0) { - this.getScheduledExecutorService().shutdown(); } } set the scheduledExecutorService to null? public synchronized void shutdown() { if (this.producerNum.decrementAndGet() == 0) { + this.scheduledExecutorService = null; } }
codereview_java_data_606
command.setOldColumnName(columnName); command.setNewColumnName(newColumnName); return command; - } else if (readIf("CONVERT")) { readIf("TO"); readIf("CHARACTER"); readIf(SET); this needs a && database.getMode().getEnum() == ModeEnum.MySQL so it doesn't accidentally start "working" for other database testing command.setOldColumnName(columnName); command.setNewColumnName(newColumnName); return command; + } else if (readIf("CONVERT") && database.getMode().getEnum() == ModeEnum.MySQL) { readIf("TO"); readIf("CHARACTER"); readIf(SET);
codereview_java_data_610
} private boolean isEligibleForShuffle(SingularityTaskId task) { return ( - isLongRunning(task) && !configuration.getDoNotShuffleRequests().contains(task.getRequestId()) - && (TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - task.getStartedAt()) > configuration.getMinutesBeforeNewTaskEligibleForShuffle()) ); } I wonder if we should go by the task running timestamp instead? Take out any delay that may have been caused by mesos/singularity that way } private boolean isEligibleForShuffle(SingularityTaskId task) { + Optional<SingularityTaskHistoryUpdate> taskRunning = taskManager.getTaskHistoryUpdate(task, ExtendedTaskState.TASK_RUNNING); return ( + taskRunning.isPresent() && !configuration.getDoNotShuffleRequests().contains(task.getRequestId()) + && isLongRunning(task) + && (TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - taskRunning.get().getTimestamp()) > configuration.getMinutesBeforeNewTaskEligibleForShuffle()) ); }
codereview_java_data_611
* @return <code>true</code> if there were any configuration errors, * <code>false</code> otherwise * - * @deprecated Use {@link #getConfigErrors()}.isEmpty() */ @Deprecated public boolean hasConfigErrors() { - return !getConfigErrors().isEmpty(); } /** ... `Use {@link #getViolations()}.isEmpty() instead.` * @return <code>true</code> if there were any configuration errors, * <code>false</code> otherwise * + * @deprecated Use {@link #getConfigurationErrors()}.isEmpty() */ @Deprecated public boolean hasConfigErrors() { + return !getConfigurationErrors().isEmpty(); } /**
codereview_java_data_619
@Override public void onClick(View view) { if (eventListener != null && batchSelected.isEmpty() && messageRecord.isMms() && !((MmsMessageRecord) messageRecord).getSharedContacts().isEmpty()) { - eventListener.onSharedContactDetailsClicked(((SharedContactView) view).getContact(), ((SharedContactView) view).getAvatarView()); } else { passthroughClickListener.onClick(view); } Why did this need to change? @Override public void onClick(View view) { if (eventListener != null && batchSelected.isEmpty() && messageRecord.isMms() && !((MmsMessageRecord) messageRecord).getSharedContacts().isEmpty()) { + eventListener.onSharedContactDetailsClicked(((MmsMessageRecord) messageRecord).getSharedContacts().get(0), sharedContactStub.get().getAvatarView()); } else { passthroughClickListener.onClick(view); }
codereview_java_data_622
@Parameter(names="--bison-file", description="C file containing functions to link into bison parser.") public String bisonFile; - @Parameter(names="--bison-stack-max-depth", description="Maximum size of bison parsing stack.") public long bisonStackMaxDepth = 10000; @Parameter(names="--transition", listConverter=StringListConverter.class, description="<string> is a whitespace-separated list of tags designating rules to become transitions.") ```suggestion @Parameter(names="--bison-stack-max-depth", description="Maximum size of bison parsing stack (default: 10000).") public long bisonStackMaxDepth = 10000; ``` @Parameter(names="--bison-file", description="C file containing functions to link into bison parser.") public String bisonFile; + @Parameter(names="--bison-stack-max-depth", description="Maximum size of bison parsing stack (default: 10000).") public long bisonStackMaxDepth = 10000; @Parameter(names="--transition", listConverter=StringListConverter.class, description="<string> is a whitespace-separated list of tags designating rules to become transitions.")
codereview_java_data_635
// Key is accountUuid:folderName:messageUid , value is unimportant private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>(); - private static final Flag[] SYNCFLAGS = new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED }; private String createMessageKey(Account account, String folder, Message message) { return createMessageKey(account, folder, message.getUid()); These are two words -- they should be separated by an underscore (i.e. SYNC_FLAGS). // Key is accountUuid:folderName:messageUid , value is unimportant private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>(); + private static final Flag[] SYNC_FLAGS = new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED }; private String createMessageKey(Account account, String folder, Message message) { return createMessageKey(account, folder, message.getUid());
codereview_java_data_639
@Override public String toString() { - if (dateUploaded != null) { return "UploadResult{" + "errorCode='" + errorCode + '\'' + ", resultStatus='" + resultStatus + '\'' + Do not add the check here. Add the check just for `dateuploaded`. @Override public String toString() { + if (dateUploaded == null) { + return "Server is in read only mode"; + } return "UploadResult{" + "errorCode='" + errorCode + '\'' + ", resultStatus='" + resultStatus + '\'' +
codereview_java_data_641
package org.apache.calcite.rel.metadata.janino; /** - * An key used in caching with descriptive to string. Note the key uses * reference equality for performance. */ public final class DescriptiveCacheKey { typo. `An` -> `A` package org.apache.calcite.rel.metadata.janino; /** + * A key used in caching with descriptive to string. Note the key uses * reference equality for performance. */ public final class DescriptiveCacheKey {
codereview_java_data_645
upperBounds.containsKey(fieldId) ? fromByteBuffer(type, upperBounds.get(fieldId)) : null); } - private File writeRecords(Schema schema, Record... records) throws IOException { - return TestParquet.writeRecords(temp, schema, Collections.emptyMap(), null, records); - } } Tests shouldn't use methods in other tests because they are hard to keep track of. If you want to use the same method, then let's move it to a test utility class, or a base class. upperBounds.containsKey(fieldId) ? fromByteBuffer(type, upperBounds.get(fieldId)) : null); } }
codereview_java_data_647
return this; } - public RunnerBuilder advertisedHost(final String advertisedHost) { - this.advertisedHost = advertisedHost; return this; } - public RunnerBuilder listenPort(final int listenPort) { - this.listenPort = listenPort; return this; } `listenPort` feels too generic here. I wonder if these should be p2pAdvertisedHost and p2pListenPort? A bigger refactoring would be to make an actual `P2pConfiguration` object to match `JsonRpcConfiguration` and friends but that's probably scope creep on what you were working on. :) return this; } + public RunnerBuilder p2pAdvertisedHost(final String p2pAdvertisedHost) { + this.p2pAdvertisedHost = p2pAdvertisedHost; return this; } + public RunnerBuilder p2pListenPort(final int p2pListenPort) { + this.p2pListenPort = p2pListenPort; return this; }
codereview_java_data_649
public static class ScanBuilder { private final Table table; private TableScan tableScan; - private final Expression defaultWhere = Expressions.alwaysTrue(); - private final List<String> defaultColumns = ImmutableList.of("*"); private boolean reuseContainers = false; - private final boolean defaultCaseSensitive = true; public ScanBuilder(Table table) { this.table = table; - this.tableScan = table.newScan() - .select(this.defaultColumns) - .caseSensitive(this.defaultCaseSensitive); } public ScanBuilder reuseContainers() { Instead of having defaults here as well as in the table scan, this should just create a new scan and rely on its defaults. public static class ScanBuilder { private final Table table; private TableScan tableScan; private boolean reuseContainers = false; public ScanBuilder(Table table) { this.table = table; + this.tableScan = table.newScan(); } public ScanBuilder reuseContainers() {
codereview_java_data_671
* * @return a new {@link RewriteManifests} */ - RewriteManifests newRewriteManifests(); /** * Create a new {@link OverwriteFiles overwrite API} to overwrite files by a filter expression. Can we change this to just `rewriteManifests` and use the verb? I know this matches `newRewrite`, but that rewrite is applying rewrite changes, not actually doing the rewrite. * * @return a new {@link RewriteManifests} */ + RewriteManifests rewriteManifests(); /** * Create a new {@link OverwriteFiles overwrite API} to overwrite files by a filter expression.
codereview_java_data_676
anyBoolean(), fileArgumentCaptor.capture()); - assertThat(fileArgumentCaptor.getValue().compareTo(file)).isZero(); assertThat(commandOutput.toString()).isEmpty(); assertThat(commandErrorOutput.toString()).isEmpty(); This is a particularly unusual form of assertion and won't provide very useful feedback. Is `assertThat(fileArgumentCaptor.getValue()).isEqualTo(file)` not sufficient? If not maybe you could just compare the absolute file paths? anyBoolean(), fileArgumentCaptor.capture()); + assertThat(fileArgumentCaptor.getValue()).isEqualTo(file); assertThat(commandOutput.toString()).isEmpty(); assertThat(commandErrorOutput.toString()).isEmpty();
codereview_java_data_690
long cachedUidValidity = localFolder.getUidValidity(); long currentUidValidity = imapFolder.getUidValidity(); - if (localFolder.isCachedUidValidityValid() && cachedUidValidity != currentUidValidity) { Timber.v("SYNC: Deleting all local messages in folder %s due to UIDVALIDITY change", localFolder); Set<String> localUids = localFolder.getAllMessagesAndEffectiveDates().keySet(); maybe just `hasCachedUidValidity`? long cachedUidValidity = localFolder.getUidValidity(); long currentUidValidity = imapFolder.getUidValidity(); + if (localFolder.hasCachedUidValidity() && cachedUidValidity != currentUidValidity) { Timber.v("SYNC: Deleting all local messages in folder %s due to UIDVALIDITY change", localFolder); Set<String> localUids = localFolder.getAllMessagesAndEffectiveDates().keySet();
codereview_java_data_692
private static String getCause(Exception e) { StringBuilder sb = new StringBuilder(); if (e.getMessage() != null) { - sb.append(" : ").append(e.getMessage()); } if (e.getCause() != null && e.getCause().getMessage() != null) { - sb.append(" : ").append(e.getCause().getMessage()); } return sb.toString(); } There shouldn't be a space before a `:` private static String getCause(Exception e) { StringBuilder sb = new StringBuilder(); if (e.getMessage() != null) { + sb.append(": ").append(e.getMessage()); } if (e.getCause() != null && e.getCause().getMessage() != null) { + sb.append(": ").append(e.getCause().getMessage()); } return sb.toString(); }
codereview_java_data_694
private long batchCount = 0; private long readaheadThreshold; - private Set<ScannerIterator> activeIters; private static ThreadPoolExecutor readaheadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 3L, TimeUnit.SECONDS, new SynchronousQueue<>(), I see you are using a SynchronizedSet in ScannerImpl but this constructor only takes a set. Isn't it possible to pass in a non synchronized set? private long batchCount = 0; private long readaheadThreshold; + private ScannerImpl.Reporter reporter; private static ThreadPoolExecutor readaheadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 3L, TimeUnit.SECONDS, new SynchronousQueue<>(),
codereview_java_data_701
Integer productionPower = 0; for (String chargerId : this.config.charger_ids()) { EssDcCharger charger; - try { - charger = this.componentManager.getComponent(chargerId); - } catch (OpenemsNamedException e) { - this.logError(this.log, e.getMessage()); - continue; - } productionPower += charger.getActualPower().value().orElse(0); } calculatedPower = productionPower - calculatedPower; If you catch the error here, you will never find out about it. You'd rather throw it, so that the Controller "RunFailed" StateChannel gets set. Integer productionPower = 0; for (String chargerId : this.config.charger_ids()) { EssDcCharger charger; + charger = this.componentManager.getComponent(chargerId); productionPower += charger.getActualPower().value().orElse(0); } calculatedPower = productionPower - calculatedPower;
codereview_java_data_727
} // Add a junk file, should be ignored - FSDataOutputStream out = fs.create(new Path(dir + "/junk")); out.writeChars("ABCDEFG\n"); out.close(); ~I think that the `Paths.get(dir, "junk")` syntax might be a bit cleaner than the concatenation. Not a bug, but probably better, in that it's less platform dependent on the OS path separator char, and therefore a good habit to get into.~ Never mind. I was thinking this was java `Path`, not Hadoop `Path`. } // Add a junk file, should be ignored + FSDataOutputStream out = fs.create(new Path(dir, "junk")); out.writeChars("ABCDEFG\n"); out.close();
codereview_java_data_731
return statusAssembler.toResource(status); } - @RequestMapping("/logs/{streamName}") public String getLog(@PathVariable String streamName) { return this.streamDeployer.getLog(streamName); } - @RequestMapping("/logs/{streamName}/{appName}") public String getLog(@PathVariable String streamName, @PathVariable String appName) { return this.streamDeployer.getLog(streamName, appName); } We need to figure out a different path as `http://localhost:9393/runtime/apps/logs/ticktock` would not work as we already use `http://localhost:9393/runtime/apps/ticktock.time-v1`. Either something in `/runtime/logs/` and/or `/runtime/apps/ticktock.time-v1/logs`. return statusAssembler.toResource(status); } + @RequestMapping("{streamName}/logs") public String getLog(@PathVariable String streamName) { return this.streamDeployer.getLog(streamName); } + @RequestMapping("{streamName}/{appName}/logs") public String getLog(@PathVariable String streamName, @PathVariable String appName) { return this.streamDeployer.getLog(streamName, appName); }
codereview_java_data_751
return null; } - protected SqlNode emulateNullDirectionForLowNulls( - SqlNode node, boolean nullsFirst, boolean desc) { - // No emulation required for the following 2 cases - if (/*order by id nulls first*/ (nullsFirst && !desc) - || /*order by id desc nulls last*/ (!nullsFirst && desc)) { return null; } How about considering the `nullCollation` already present in `SqlDialect`? Rename this method to `emulateNullDirectionWithIsNull` and skip the null emulation based on the `nullCollation` and the given `nullsFirst` and `desc` settings. It's not relevant for your purposes but is a nice and small generalization that we could use later for other DBMS. return null; } + protected SqlNode emulateNullDirectionWithIsNull(SqlNode node, boolean nullsFirst, boolean desc) { + boolean nullsAreInNaturalOrder = nullCollation.naturalOrder(nullsFirst, desc); + // No need for emulation if the nulls will anyways come out the way we want them based on + // "nullsFirst" and "desc" + if (nullsAreInNaturalOrder) { return null; }
codereview_java_data_765
private String pendingQueueKey(SingularityPendingRequest pendingRequest) { SingularityDeployKey deployKey = new SingularityDeployKey(pendingRequest.getRequestId(), pendingRequest.getDeployId()); - return String.format("%s%s", deployKey.toString(), pendingRequest.getTimestamp()); } private String getCleanupPath(String requestId, RequestCleanupType type) { Only immediate thing I see here is that we'd need to handle any pending requests that are currently in the queue when singularity starts. Otherwise we will not delete them correctly since we will calculate the wrong path, but we will continually process them since it's just a getChildren call. Should be able to write a simple zk migration for this that reads them all writes to the correct path and deletes the old path on startup private String pendingQueueKey(SingularityPendingRequest pendingRequest) { SingularityDeployKey deployKey = new SingularityDeployKey(pendingRequest.getRequestId(), pendingRequest.getDeployId()); + if (pendingRequest.getPendingType() == PendingType.ONEOFF + || pendingRequest.getPendingType() == PendingType.IMMEDIATE) { + return String.format("%s%s", deployKey.toString(), pendingRequest.getTimestamp()); + } else { + return deployKey.toString(); + } } private String getCleanupPath(String requestId, RequestCleanupType type) {
codereview_java_data_768
import org.apache.iceberg.io.CloseableIterable; public class FindFiles { private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); public static Builder in(Table table) { I assume `snapshotLog()` is in ascending order. Should we then `break` after the condition is not true anymore? import org.apache.iceberg.io.CloseableIterable; public class FindFiles { + private FindFiles() { + } + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); public static Builder in(Table table) {
codereview_java_data_775
private final BlockTimer blockTimer; private final IbftMessageTransmitter transmitter; private final MessageFactory messageFactory; - private final Map<Integer, RoundState> futureRoundStateBuffer; private final NewRoundMessageValidator newRoundMessageValidator; private final Clock clock; private final Function<ConsensusRoundIdentifier, RoundState> roundStateCreator; is this related to the incoming event queue size? private final BlockTimer blockTimer; private final IbftMessageTransmitter transmitter; private final MessageFactory messageFactory; + private final Map<Integer, RoundState> futureRoundStateBuffer = Maps.newHashMap(); private final NewRoundMessageValidator newRoundMessageValidator; private final Clock clock; private final Function<ConsensusRoundIdentifier, RoundState> roundStateCreator;
codereview_java_data_781
return Sets.union(scopesConfiguration.getRead(), scopesConfiguration.getWrite()); case WRITE: return scopesConfiguration.getWrite(); - case DEPLOY: - return scopesConfiguration.getDeploy().isEmpty() - ? scopesConfiguration.getWrite() - : scopesConfiguration.getDeploy(); - case EXEC: - return scopesConfiguration.getExec(); case ADMIN: default: return scopesConfiguration.getAdmin(); If it makes it simpler in the overall implementation, I'm fine with having the DEPLOY scope behave similar to the new ones (i.e. falls under WRITE unless otherwise overriden by a request). I had originally separated out DEPLOY for future use with our internal automation, but it isn't turned on or enforced by default return Sets.union(scopesConfiguration.getRead(), scopesConfiguration.getWrite()); case WRITE: return scopesConfiguration.getWrite(); case ADMIN: default: return scopesConfiguration.getAdmin();
codereview_java_data_786
"Usage:\n" + " <functionName> \n\n" + "Where:\n" + - " functionName - the name of the function to delete. \n"; if (args.length != 1) { System.out.println(USAGE); "function to delete" again. "Usage:\n" + " <functionName> \n\n" + "Where:\n" + + " functionName - the name of the function to describe. \n"; if (args.length != 1) { System.out.println(USAGE);
codereview_java_data_788
final MutableAccount account = updater.createAccount(ADDRESS); account.setBalance(Wei.of(100000)); account.setCode(BytesValue.of(1, 2, 3)); account.setCode(BytesValue.of(3, 2, 1)); updater.commit(); assertEquals(BytesValue.of(3, 2, 1), worldState.get(ADDRESS).getCode()); assertEquals( Hash.fromHexString("0xc14f5e30581de9155ea092affa665fad83bcd9f98e45c4a42885b9b36d939702"), worldState.rootHash()); (Discussion) The version is not set in the test, should we set explicitly the version and check it ? final MutableAccount account = updater.createAccount(ADDRESS); account.setBalance(Wei.of(100000)); account.setCode(BytesValue.of(1, 2, 3)); + account.setVersion(Account.DEFAULT_VERSION); account.setCode(BytesValue.of(3, 2, 1)); updater.commit(); assertEquals(BytesValue.of(3, 2, 1), worldState.get(ADDRESS).getCode()); + assertEquals(Account.DEFAULT_VERSION, worldState.get(ADDRESS).getVersion()); assertEquals( Hash.fromHexString("0xc14f5e30581de9155ea092affa665fad83bcd9f98e45c4a42885b9b36d939702"), worldState.rootHash());
codereview_java_data_790
} } - static public void bulkImport(Connector c, FileSystem fs, String table, String dir) - throws Exception { - // Ensure server can read/modify files - c.tableOperations().addFilesTo(table).from(dir).load(); - } - static public void checkSplits(Connector c, String table, int min, int max) throws Exception { Collection<Text> splits = c.tableOperations().listSplits(table); if (splits.size() < min || splits.size() > max) { maybe this method can be inlined now. } } static public void checkSplits(Connector c, String table, int min, int max) throws Exception { Collection<Text> splits = c.tableOperations().listSplits(table); if (splits.size() < min || splits.size() > max) {
codereview_java_data_797
Column c = cols[j]; DataType dataType = c.getDataType(); String precision = Integer.toString(c.getPrecisionAsInt()); - boolean isDateTime; - switch (dataType.type) { - case Value.TIME: - case Value.DATE: - case Value.TIMESTAMP: - case Value.TIMESTAMP_TZ: - isDateTime = true; - break; - default: - isDateTime = false; - } Sequence sequence = c.getSequence(); add(rows, // TABLE_CATALOG probably this should be a util method next to DataType.isStringType Column c = cols[j]; DataType dataType = c.getDataType(); String precision = Integer.toString(c.getPrecisionAsInt()); Sequence sequence = c.getSequence(); add(rows, // TABLE_CATALOG
codereview_java_data_798
// Start playback immediately if continuous playback is enabled // Repeat episode implementation - if (UserPreferences.repeatEpisode() && !wasSkipped) { nextMedia = currentMedia; nextMedia.setPosition(0); } else { I think this should be done outside LocalPSMP, but in `getNextInQueue`. The reason is that I want to reduce the dependence of the media players on the preferences and database. Also, it will then probably work on Chromecast. // Start playback immediately if continuous playback is enabled // Repeat episode implementation + if (UserPreferences.getShouldRepeatEpisode() && !wasSkipped) { nextMedia = currentMedia; nextMedia.setPosition(0); } else {
codereview_java_data_812
private boolean isUsesMultifile; private boolean isUsesTyperesolution; public RuleBuilder(String name, ResourceLoader resourceLoader, String clazz, String language) { this.name = name; this.resourceLoader = resourceLoader; In order to keep backwards compatible, we need to provide an overloaded constructor. The one without a resource loader should initialize the resource loader as `new ResourceLoader()`, which uses the same classpath as before. We could mark this constructor already as deprecated, since it might load the rule implementation class from a wrong class loader. private boolean isUsesMultifile; private boolean isUsesTyperesolution; + @Deprecated + public RuleBuilder(String name, String clazz, String language) { + this.name = name; + this.resourceLoader = new ResourceLoader(); + language(language); + className(clazz); + } + public RuleBuilder(String name, ResourceLoader resourceLoader, String clazz, String language) { this.name = name; this.resourceLoader = resourceLoader;
codereview_java_data_815
conf.setStrings(enumToConfKey(implementingClass, ScanOpts.RANGES), rangeStrings.toArray(new String[0])); } catch (IOException ex) { - throw new UncheckedIOException("Unable to encode ranges to Base64", ex); } } The user-facing exception should be IAE. conf.setStrings(enumToConfKey(implementingClass, ScanOpts.RANGES), rangeStrings.toArray(new String[0])); } catch (IOException ex) { + throw new IllegalArgumentException("Unable to encode ranges to Base64", ex); } }
codereview_java_data_823
} private static void apply(UpdateSchema pendingUpdate, TableChange.AddColumn add) { Type type = SparkSchemaUtil.convert(add.dataType()); - if (add.isNullable()) { - pendingUpdate.addColumn(parentName(add.fieldNames()), leafName(add.fieldNames()), type, add.comment()); - } else { - pendingUpdate.allowIncompatibleChanges() - .addRequiredColumn(parentName(add.fieldNames()), leafName(add.fieldNames()), type, add.comment()); - } if (add.position() instanceof TableChange.After) { TableChange.After after = (TableChange.After) add.position(); String referenceField = peerName(add.fieldNames(), after.column()); I'm not sure that this should call `allowIncompatibleChanges()` because adding a required column when there are no existing values will break reading the new column in any table with data in it. The only time it is safe to add a required column is if there is no data in the table. What about throwing an exception here instead? I agree that the column should not be optional if NOT NULL was specified. Another alternative is to check whether the table has data and allow the incompatible change if it doesn't have any rows. } private static void apply(UpdateSchema pendingUpdate, TableChange.AddColumn add) { + Preconditions.checkArgument(add.isNullable(), + "Incompatible change: cannot add required column: %s", leafName(add.fieldNames())); Type type = SparkSchemaUtil.convert(add.dataType()); + pendingUpdate.addColumn(parentName(add.fieldNames()), leafName(add.fieldNames()), type, add.comment()); + if (add.position() instanceof TableChange.After) { TableChange.After after = (TableChange.After) add.position(); String referenceField = peerName(add.fieldNames(), after.column());
codereview_java_data_826
txtvPosition = findViewById(R.id.txtvPosition); SharedPreferences prefs = getSharedPreferences(PREFS, MODE_PRIVATE); - showTimeLeft = UserPreferences.getShowRemainTimeSetting(); Log.d("timeleft", showTimeLeft ? "true" : "false"); txtvLength = findViewById(R.id.txtvLength); if (txtvLength != null) { The word "setting" sounds a bit redundant here. How about `isShowRemainingTime` or `shouldShowRemainingTime`? txtvPosition = findViewById(R.id.txtvPosition); SharedPreferences prefs = getSharedPreferences(PREFS, MODE_PRIVATE); + showTimeLeft = UserPreferences.shouldShowRemainingTime(); Log.d("timeleft", showTimeLeft ? "true" : "false"); txtvLength = findViewById(R.id.txtvLength); if (txtvLength != null) {
codereview_java_data_829
inner.next(); return result; } catch (IOException ex) { - throw new UncheckedIOException(ex); } } The NSEE makes a little more sense here, since it matches the Iterator interface's behavior when calling next without any more elements. inner.next(); return result; } catch (IOException ex) { + throw new NoSuchElementException(); } }
codereview_java_data_835
@Override public void onBackPressed() { - if (getSupportFragmentManager().getBackStackEntryCount()==1){ // back to search so show search toolbar and hide navigation toolbar toolbar.setVisibility(View.VISIBLE); setNavigationBaseToolbarVisibility(false); spaces around `==` @Override public void onBackPressed() { + if (getSupportFragmentManager().getBackStackEntryCount() == 1){ // back to search so show search toolbar and hide navigation toolbar toolbar.setVisibility(View.VISIBLE); setNavigationBaseToolbarVisibility(false);
codereview_java_data_836
@Test public void parseModuleDeclaration() { - JavaParser.getStaticConfiguration().setLanguageLevel(JAVA_9); JavaParser.parseModuleDeclaration("module X {}"); } Is it good to change the static configuration in a test? @Test public void parseModuleDeclaration() { JavaParser.parseModuleDeclaration("module X {}"); }
codereview_java_data_840
super.onStart(); EventBus.getDefault().register(this); - autoDownload = prefs.getString(PREF_AUTO_DOWNLOAD,STRING_NO_FILTER); - keepUpdated = prefs.getString(PREF_KEEP_UPDATED,STRING_NO_FILTER); - autoDelete = prefs.getString(PREF_AUTO_DELETE,STRING_NO_FILTER); loadSubscriptions(); } I think those can be loaded when actually filtering the items. That way, the Fragment does not need to keep preferences as member variables and watch out that they are always updated. super.onStart(); EventBus.getDefault().register(this); + // autoDownload = SubscriptionFilterDialog.AutoDownload.valueOf(prefs.getString(PREF_AUTO_DOWNLOAD,STRING_NO_FILTER)); +// keepUpdated = SubscriptionFilterDialog.KeepUpdated.valueOf(prefs.getString(PREF_KEEP_UPDATED,STRING_NO_FILTER)); + // autoDelete =SubscriptionFilterDialog.AutoDelete.valueOf(prefs.getString(PREF_AUTO_DELETE,STRING_NO_FILTER)); loadSubscriptions(); }
codereview_java_data_842
loadModule(OfflineMessageStrategy.class.getName()); loadModule(OfflineMessageStore.class.getName()); loadModule(VCardManager.class.getName()); - loadModule(SoftwareVersionManager.class.getName()); // Load standard modules loadModule(IQBindHandler.class.getName()); loadModule(IQSessionEstablishmentHandler.class.getName()); This new module is not a 'core' module. Please move it to the bottom of the list of the 'standard' modules. loadModule(OfflineMessageStrategy.class.getName()); loadModule(OfflineMessageStore.class.getName()); loadModule(VCardManager.class.getName()); // Load standard modules loadModule(IQBindHandler.class.getName()); loadModule(IQSessionEstablishmentHandler.class.getName());
codereview_java_data_843
CommonsApplication application = CommonsApplication.getInstance(); compositeDisposable.add( - RxJava2Tasks.getUploadCount(application.getCurrentAccount().name) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( This would be a good candidate to pull behind the `MediaWikiApi` interface rather than living out on its own. Eventually all the other methods on that interface will return Single / Observable. CommonsApplication application = CommonsApplication.getInstance(); compositeDisposable.add( + CommonsApplication.getInstance().getMWApi() + .getUploadCount(application.getCurrentAccount().name) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(
codereview_java_data_844
} public Builder contractAccountVersion(final int contractAccountVersion) { this.contractAccountVersion = contractAccountVersion; return this; } Probably worth asserting the value is `>= 0`. } public Builder contractAccountVersion(final int contractAccountVersion) { + checkArgument(contractAccountVersion >= 0, "Contract account version cannot be negative"); this.contractAccountVersion = contractAccountVersion; return this; }
codereview_java_data_851
String jsonFilePath = String.format("META-INF/resources/%s", jsonFile); storeFile(GeneratedFileType.RESOURCE, jsonFilePath, jsonContent); } catch (Exception e) { - System.out.println("Failed to write OAS schema"); } } if (model instanceof HasNestedModels) { Please use logger String jsonFilePath = String.format("META-INF/resources/%s", jsonFile); storeFile(GeneratedFileType.RESOURCE, jsonFilePath, jsonContent); } catch (Exception e) { + LOGGER.warn("Failed to write OAS schema"); } } if (model instanceof HasNestedModels) {
codereview_java_data_874
} @Test public void syncModeOptionMustBeUsed() { parseCommand("--sync-mode", "FAST"); Also 2 new tests similar to `syncModeOptionMustBeUsed` to check the two new options values are well passed from the CLI to the SynchronizerConfiguration would help make sure we don't have an issue with a valid integer passed but not matching the entered value on the command line. } @Test + @Ignore public void syncModeOptionMustBeUsed() { parseCommand("--sync-mode", "FAST");
codereview_java_data_880
} default Tuple2<Seq<K>, Seq<V>> unzip() { - return this.unzip(Function.identity()); } default <T1, T2> Tuple2<Seq<T1>, Seq<T2>> unzip(BiFunction<? super K, ? super V, Tuple2<? extends T1, ? extends T2>> unzipper) { we can remove `this.` } default Tuple2<Seq<K>, Seq<V>> unzip() { + return unzip(Function.identity()); } default <T1, T2> Tuple2<Seq<T1>, Seq<T2>> unzip(BiFunction<? super K, ? super V, Tuple2<? extends T1, ? extends T2>> unzipper) {
codereview_java_data_889
@Deprecated public void setSourceCodeFilename(String filename) { // ignored, does nothing. } /** we could nag (log an error) about the usage of a deprecated API @Deprecated public void setSourceCodeFilename(String filename) { // ignored, does nothing. + LOG.warning("The method RuleContext::setSourceCodeFilename(String) has been deprecated and will be removed." + + "Setting the filename here has no effect. Use RuleContext::setSourceCodeFile(File) instead."); } /**
codereview_java_data_891
nonSynchronizedAction = () -> mc.writeJobExecutionRecord(false); } else if (failure != null && !wasCancelled && mc.jobConfig().isSuspendOnFailure()) { mc.setJobStatus(SUSPENDED); - mc.jobExecutionRecord().setSuspended("Due to failure:\n" + ExceptionUtil.stackTraceToString(failure)); nonSynchronizedAction = () -> mc.writeJobExecutionRecord(false); } else { mc.setJobStatus(isSuccess(failure) ? COMPLETED : FAILED); ```suggestion mc.jobExecutionRecord().setSuspended("Execution failure:\n" + ExceptionUtil.stackTraceToString(failure)); ``` nonSynchronizedAction = () -> mc.writeJobExecutionRecord(false); } else if (failure != null && !wasCancelled && mc.jobConfig().isSuspendOnFailure()) { mc.setJobStatus(SUSPENDED); + mc.jobExecutionRecord().setSuspended("Execution failure:\n" + + ExceptionUtil.stackTraceToString(failure)); nonSynchronizedAction = () -> mc.writeJobExecutionRecord(false); } else { mc.setJobStatus(isSuccess(failure) ? COMPLETED : FAILED);
codereview_java_data_893
throw new NoSuchTableException("No such table: " + identifier); } TableMetadata metadata; if (ops.current() != null) { String baseLocation = location != null ? location : ops.current().location(); - Map<String, String> tableProperties = properties != null ? properties : Maps.newHashMap(); metadata = ops.current().buildReplacement(schema, spec, baseLocation, tableProperties); } else { String baseLocation = location != null ? location : defaultWarehouseLocation(identifier); - Map<String, String> tableProperties = properties != null ? properties : Maps.newHashMap(); metadata = TableMetadata.newTableMetadata(schema, spec, baseLocation, tableProperties); } You can probably take this out of the `if...else` since it's repeated and has to be done on either case. throw new NoSuchTableException("No such table: " + identifier); } + Map<String, String> tableProperties = properties != null ? properties : Maps.newHashMap(); + TableMetadata metadata; if (ops.current() != null) { String baseLocation = location != null ? location : ops.current().location(); metadata = ops.current().buildReplacement(schema, spec, baseLocation, tableProperties); } else { String baseLocation = location != null ? location : defaultWarehouseLocation(identifier); metadata = TableMetadata.newTableMetadata(schema, spec, baseLocation, tableProperties); }
codereview_java_data_896
methodUsage = ((TypeVariableResolutionCapability) methodDeclaration) .resolveTypeVariables(this, argumentsTypes); } else { - return Optional.empty(); } return Optional.of(methodUsage); mmm, why a method declaration should not have the TypeVariableResolutionCapability? Is this ok? methodUsage = ((TypeVariableResolutionCapability) methodDeclaration) .resolveTypeVariables(this, argumentsTypes); } else { + throw new UnsupportedOperationException(); } return Optional.of(methodUsage);
codereview_java_data_901
try { return getDaoCareportalEvents().queryForId(timestamp); } catch (SQLException e) { - e.printStackTrace(); } return null; } could you please change that to a log statement like `log.error("Unhandled exception", e);`? (and while you are editing, please do the same for `update(BgReading bgReading)`) ` try { return getDaoCareportalEvents().queryForId(timestamp); } catch (SQLException e) { + log.error("Unhandled exception", e); } return null; }
codereview_java_data_902
startActivity(new Intent(getActivity(), PreferenceActivity.class))); getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) .registerOnSharedPreferenceChangeListener(this); - - progressBar = root.findViewById(R.id.progressBar); - progressBar.bringToFront(); return root; } Instead of calling this, please move the progress bar further down in the layout xml file. startActivity(new Intent(getActivity(), PreferenceActivity.class))); getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) .registerOnSharedPreferenceChangeListener(this); return root; }
codereview_java_data_913
import java.util.UUID; @RunWith(RobolectricTestRunner.class) -@Config(manifest = Config.NONE, sdk = 27) public class KinesisRecorderTest { private static final String WORKING_DIRECTORY = "KinesisRecorderTest"; You can make a single `src/test/resources/robolectric.properties` that includes these values and then you don't have to put them on every test. import java.util.UUID; @RunWith(RobolectricTestRunner.class) +@Config(manifest = Config.NONE) public class KinesisRecorderTest { private static final String WORKING_DIRECTORY = "KinesisRecorderTest";
codereview_java_data_923
stateCache.getActiveTaskIds().remove(taskId); } - if (task.isPresent() && task.get().getTaskRequest().getRequest().isLoadBalanced()) { taskManager.createLBCleanupTask(taskId); } Is this an optimization? Is it 100% safe? What if the task isn't present but it's being load balanced due to a data corruption issue in Singularity? stateCache.getActiveTaskIds().remove(taskId); } + if (task.isPresent() && task.get().getTaskRequest().getRequest().isLoadBalanced() || !task.isPresent()) { taskManager.createLBCleanupTask(taskId); }
codereview_java_data_936
private void checkImports(JavaNode node, Object data) { String name = node.getImage(); - matches.clear(); // Find all "matching" import declarations for (ASTImportDeclaration importDeclaration : imports) { I've seen, that matches is actually only used in this method, so I would remove the field and add it as a local variable here. private void checkImports(JavaNode node, Object data) { String name = node.getImage(); + List<ASTImportDeclaration> matches = new ArrayList<>(); // Find all "matching" import declarations for (ASTImportDeclaration importDeclaration : imports) {
codereview_java_data_943
switch (item.getItemId()) { case R.id.archived: if (item.getTitle().equals(getString(R.string.menu_option_archived))) { refresh(true); isarchivedvisible = true; }else if (item.getTitle().equals(getString(R.string.menu_option_unread))) { call ``` NotificationActivity.startYourself(this, "read"); ``` This is how the Wikipedia app does it. It opens a new activity. switch (item.getItemId()) { case R.id.archived: if (item.getTitle().equals(getString(R.string.menu_option_archived))) { + NotificationActivity.startYourself(NotificationActivity.this, "read"); refresh(true); isarchivedvisible = true; }else if (item.getTitle().equals(getString(R.string.menu_option_unread))) {
codereview_java_data_951
private final Set<Integer> selected; PruneColumns(Set<Integer> selected) { - Preconditions.checkNotNull(selected, "Selected cannot be null"); this.selected = selected; } Rather than just using the name of the variable, I think this should give more context to users when it happens. "Field id set" or "Selected field ids" would be better. private final Set<Integer> selected; PruneColumns(Set<Integer> selected) { + Preconditions.checkNotNull(selected, "Selected field ids cannot be null"); this.selected = selected; }
codereview_java_data_955
ConsumeQueue logicQueue = this.findConsumeQueue(topic, queueId); if (logicQueue != null) { SelectMappedBufferResult result = logicQueue.getIndexBuffer(consumeQueueOffset); - long storeTime = getStoreTime(result); } return -1; Convert Long to long ? may lead to NPE? ConsumeQueue logicQueue = this.findConsumeQueue(topic, queueId); if (logicQueue != null) { SelectMappedBufferResult result = logicQueue.getIndexBuffer(consumeQueueOffset); + return getStoreTime(result); } return -1;
codereview_java_data_963
protected abstract void doDeployStream(String name, Map<String, String> deploymentProperties); - @Override - public void undeployStream(String streamName) { - doUndeployStream(streamName); - } - - protected abstract void doUndeployStream(String streamName); - protected StreamDefinition createStreamDefinitionForDeploy(String name) { StreamDefinition streamDefinition = this.streamDefinitionRepository.findOne(name); There is not point in a separate doUndeployStream method anymore as its calling method (undeployStream) is empty. We can get rid of the doUndeployStream and have the child classes override the undepoyStream instead. protected abstract void doDeployStream(String name, Map<String, String> deploymentProperties); protected StreamDefinition createStreamDefinitionForDeploy(String name) { StreamDefinition streamDefinition = this.streamDefinitionRepository.findOne(name);
codereview_java_data_973
} @Test - public void testVerifiedIllegalNumBucket() { AssertHelpers.assertThrows("Should fail if numBucket is less than or equal to zero", IllegalArgumentException.class, - "The number of bucket must larger than zero", () -> Bucket.get(Types.IntegerType.get(), 0)); } bucket -> buckets , but here it matters less since it's just a test message } @Test + public void testVerifiedIllegalNumBuckets() { AssertHelpers.assertThrows("Should fail if numBucket is less than or equal to zero", IllegalArgumentException.class, + "The number of bucket(s) must be larger than zero", () -> Bucket.get(Types.IntegerType.get(), 0)); }
codereview_java_data_975
closeStream(null); } if (xmppSession != null) { - xmppSession.getStreamManager().formalClose(); - if (!xmppSession.getStreamManager().getResume()) { Log.debug( "Closing session {}", xmppSession ); xmppSession.close(); This does not seem right. Effectively, we've allowed resumption to be negotiated, but when the session is closed, we disregard that completely, and instead simply close the session. It would be a lot better to prevent resumption from being negotiated for these kind of sessions in the first place. I think that can be done by modifying `org.jivesoftware.openfire.streammanagement.StreamManager#allowResume` closeStream(null); } if (xmppSession != null) { if (!xmppSession.getStreamManager().getResume()) { Log.debug( "Closing session {}", xmppSession ); xmppSession.close();
codereview_java_data_980
/** * The settings of open indexes. */ - private static final Map<String, FullTextSettings> SETTINGS = Collections.synchronizedMap(New.<String, FullTextSettings>hashMap()); /** * Whether this instance has been initialized. why do all these need to be synch collections? In general I do not think synch collections ever make much sense. Because you can't synch properly when doing iteration over them, and people never remember to synch across read/write pairs, etc, so you might just as well declare some other object as the lock and synch on that object. Sorry if this doesn't make too much sense, rather late here :-) /** * The settings of open indexes. */ + private static final Map<String, FullTextSettings> SETTINGS = New.hashMap(); /** * Whether this instance has been initialized.
codereview_java_data_991
*/ public static Address recoverProposerAddress( final BlockHeader header, final CliqueExtraData cliqueExtraData) { - if (header.getNumber() == 0) { - return ADDRESS_ZERO; } if (!cliqueExtraData.getProposerSeal().isPresent()) { throw new IllegalArgumentException( ```suggestion if (header.getNumber() == BlockHeader.GENESIS_BLOCK_NUMBER) { ``` Please don't ever hard code 0 as the genesis block number. One day we're going to have to support variable genesis block numbers. */ public static Address recoverProposerAddress( final BlockHeader header, final CliqueExtraData cliqueExtraData) { + if (header.getNumber() == BlockHeader.GENESIS_BLOCK_NUMBER) { + return Address.ZERO; } if (!cliqueExtraData.getProposerSeal().isPresent()) { throw new IllegalArgumentException(
codereview_java_data_996
if (pendingConfiguration.port != null) { pendingRequest.configuration.port = pendingConfiguration.port; } - if (pendingConfiguration.remoteHost != null) { - pendingRequest.configuration.remoteHost = pendingConfiguration.remoteHost; - } // make sure we have a valid host pendingRequest.configuration.fixUpHost(); This is not really needed, the line added in `GridNodeConfiguration.java` is what really fixes the `remoteHost` regression. if (pendingConfiguration.port != null) { pendingRequest.configuration.port = pendingConfiguration.port; } // make sure we have a valid host pendingRequest.configuration.fixUpHost();
codereview_java_data_1006
case FLOAT: case DOUBLE: Expression condition = operand; - if(operand instanceof MethodCallExpression) { condition = ((MethodCallExpression) operand).targetExpression; } operand = Expressions.call(BuiltInMethod.STRING_VALUEOF.method, operand); We assume notnull by default, so there's no need for explicit notnull case FLOAT: case DOUBLE: Expression condition = operand; + if (operand instanceof MethodCallExpression) { condition = ((MethodCallExpression) operand).targetExpression; } operand = Expressions.call(BuiltInMethod.STRING_VALUEOF.method, operand);
codereview_java_data_1017
.replace(R.id.fragment_container, frag) .commit(); currentScreen = HomeScreenState.GALLERY; - keycode = 0; } else { AlertDialog.Builder alertbox = new AlertDialog.Builder(ctx); alertbox.setMessage(getString(R.string.exit_message)); As stated in issue we don't need this. .replace(R.id.fragment_container, frag) .commit(); currentScreen = HomeScreenState.GALLERY; } else { AlertDialog.Builder alertbox = new AlertDialog.Builder(ctx); alertbox.setMessage(getString(R.string.exit_message));
codereview_java_data_1035
queryRequest.setIncludeTaskLocalVariables(Boolean.valueOf(allRequestParams.get("includeTaskLocalVariables"))); } - if (requestParams.containsKey("includeProcessVariables")) { - request.setIncludeProcessVariables(Boolean.valueOf(requestParams.get("includeProcessVariables"))); } if (allRequestParams.get("tenantId") != null) { Shouldn't `requestParams` be `allRequestParams` instead? queryRequest.setIncludeTaskLocalVariables(Boolean.valueOf(allRequestParams.get("includeTaskLocalVariables"))); } + if (allRequestParams.containsKey("includeProcessVariables")) { + queryRequest.setIncludeProcessVariables(Boolean.valueOf(allRequestParams.get("includeProcessVariables"))); } if (allRequestParams.get("tenantId") != null) {
codereview_java_data_1041
mProfile.put("exercise_mode", SMBDefaults.exercise_mode); mProfile.put("half_basal_exercise_target", SMBDefaults.half_basal_exercise_target); mProfile.put("maxCOB", SMBDefaults.maxCOB); - if (!manufacturer.name().equals("Medtronic")) { - mProfile.put("skip_neutral_temps",SMBDefaults.skip_neutral_temps); - } else { - mProfile.put("skip_neutral_temps", sp.getBoolean(R.string.key_skip_neutral_temps, SMBDefaults.skip_neutral_temps_medtronic)); - } // min_5m_carbimpact is not used within SMB determinebasal //if (mealData.usedMinCarbsImpact > 0) { // mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); Imho this adapter should be pump-manufacturer agnostic. I'd add a new function `shouldStopTbrAtFullHourIfSave()` (might be better names) into pump interface with a default to false. Then this logic could be part of the Medtronic plugin. mProfile.put("exercise_mode", SMBDefaults.exercise_mode); mProfile.put("half_basal_exercise_target", SMBDefaults.half_basal_exercise_target); mProfile.put("maxCOB", SMBDefaults.maxCOB); + mProfile.put("skip_neutral_temps", !pump.setNeutralTempAtFullHour()); // min_5m_carbimpact is not used within SMB determinebasal //if (mealData.usedMinCarbsImpact > 0) { // mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact);
codereview_java_data_1046
@Override public ObjectNode queryService(String namespaceId, String serviceName) throws NacosException { Service service = getServiceFromGroupedServiceName(namespaceId, serviceName, true); - boolean serviceExist = ServiceManager.getInstance().containSingleton(service); - if (!serviceExist) { throw new NacosException(NacosException.INVALID_PARAM, "service not found, namespace: " + namespaceId + ", serviceName: " + serviceName); } merge `serviceExist`, because `serviceExist` will not be used after this logic. @Override public ObjectNode queryService(String namespaceId, String serviceName) throws NacosException { Service service = getServiceFromGroupedServiceName(namespaceId, serviceName, true); + if (!ServiceManager.getInstance().containSingleton(service)) { throw new NacosException(NacosException.INVALID_PARAM, "service not found, namespace: " + namespaceId + ", serviceName: " + serviceName); }
codereview_java_data_1053
public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); - if (orientation != newConfig.orientation) { - orientation = newConfig.orientation; - } - configureForOrientation(orientation, newConfig); } public float convertDpToPixel(float dp) { Can this be within the `if` statement above? public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); + configureForOrientation(newConfig); } public float convertDpToPixel(float dp) {
codereview_java_data_1062
return current; } abstract Pair<Schema, Iterator<T>> getJoinedSchemaAndIteratorWithIdentityPartition( DataFile file, FileScanTask task, Schema requiredSchema, Set<Integer> idColumns, PartitionSpec spec); Since this is part of the Base Readers api, would be good to add a docstring on what this is supposed to do and where it's being used. return current; } + /** + * Return a {@link Pair} of {@link Schema} and {@link Iterator} over records of type T that include the identity + * partition columns being projected. + */ abstract Pair<Schema, Iterator<T>> getJoinedSchemaAndIteratorWithIdentityPartition( DataFile file, FileScanTask task, Schema requiredSchema, Set<Integer> idColumns, PartitionSpec spec);
codereview_java_data_1065
* Stores all nearby places found and related users response for * each place while uploading media */ - public static HashMap<Place,Boolean> existingPlaces; @SuppressLint("CheckResult") @Override I think we need a more explicit name for this. How about `nearbyPopupAnswers`? Or any other idea? * Stores all nearby places found and related users response for * each place while uploading media */ + public static HashMap<Place,Boolean> nearbyPopupAnswers; @SuppressLint("CheckResult") @Override
codereview_java_data_1066
category = Category.ONE_OFF, link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks", linkType = LinkType.CUSTOM, - severity = SeverityLevel.WARNING, summary = "log statement in catch block does not log the caught exception.") public final class CatchBlockLogException extends BugChecker implements BugChecker.CatchTreeMatcher { IMHO if there's no false positives it should be an ERROR since you always should be logging the exception? category = Category.ONE_OFF, link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks", linkType = LinkType.CUSTOM, + severity = SeverityLevel.ERROR, summary = "log statement in catch block does not log the caught exception.") public final class CatchBlockLogException extends BugChecker implements BugChecker.CatchTreeMatcher {
codereview_java_data_1074
return new ExpectEthAccountsException(transactions.accounts(), expectedMessage); } - public Condition getTransactionReceipt(final Hash transactionHash) { return new ExpectEthGetTransactionReceiptIsPresent( transactions.getTransactionReceipt(transactionHash.toString())); } - public Condition getTransactionReceiptNotAvailable(final String transactionHash) { return new ExpectEthGetTransactionReceiptIsAbsent( transactions.getTransactionReceipt(transactionHash)); } Both these method should share consistent names with the objects they return and their function i.e. `getTransactionReceipt` does not get the transaction receipt (it checks there is one present). return new ExpectEthAccountsException(transactions.accounts(), expectedMessage); } + public Condition expectTransactionReceipt(final Hash transactionHash) { return new ExpectEthGetTransactionReceiptIsPresent( transactions.getTransactionReceipt(transactionHash.toString())); } + public Condition expectNoTransactionReceipt(final String transactionHash) { return new ExpectEthGetTransactionReceiptIsAbsent( transactions.getTransactionReceipt(transactionHash)); }
codereview_java_data_1088
*/ package org.apache.accumulo.test.functional; -import static org.apache.accumulo.core.conf.Property.TABLE_CRYPTO_PREFIX; import org.apache.accumulo.core.cli.BatchWriterOpts; import org.apache.accumulo.core.cli.ScannerOpts; It looks like `keyManager` property is just set to `uri`. Does it not need to be set? */ package org.apache.accumulo.test.functional; +import static org.apache.accumulo.core.conf.Property.INSTANCE_CRYPTO_PREFIX; import org.apache.accumulo.core.cli.BatchWriterOpts; import org.apache.accumulo.core.cli.ScannerOpts;
codereview_java_data_1091
return homeDirectory; } - @Override - public boolean jsonRpcEnabled() { - return isJsonRpcEnabled(); - } - JsonRpcConfiguration jsonRpcConfiguration() { return jsonRpcConfiguration; } (nit) `getHomeDirectory` ? return homeDirectory; } JsonRpcConfiguration jsonRpcConfiguration() { return jsonRpcConfiguration; }
codereview_java_data_1092
}; /** - * Operand type-checking strategy type must be a positive numeric non-NULL * literal in the range 0 - 1. */ - public static final SqlSingleOperandTypeChecker POSITIVE_NUMERIC_LITERAL = new FamilyOperandTypeChecker(ImmutableList.of(SqlTypeFamily.NUMERIC), i -> false) { @Override public boolean checkSingleOperandType( Let's find a better name than 'positive'. Positive means 'greater than zero'. So your use of it here is misleading. You seem to need something in the range 0 to 1, including both end points. That's a fairly common notion, so there must be a word for it. }; /** + * Operand type-checking strategy type must be a numeric non-NULL * literal in the range 0 - 1. */ + public static final SqlSingleOperandTypeChecker UNIT_INTERVAL_NUMERIC_LITERAL = new FamilyOperandTypeChecker(ImmutableList.of(SqlTypeFamily.NUMERIC), i -> false) { @Override public boolean checkSingleOperandType(
codereview_java_data_1093
ExtMetadata metadata = imageInfo.getMetadata(); if (metadata == null) { Media media = new Media(null, imageInfo.getOriginalUrl(), - page.title(), "", 0, null, null, null, null); if (!StringUtils.isBlank(imageInfo.getThumbUrl())) { media.setThumbUrl(imageInfo.getThumbUrl()); } ImageInfo doesn't have a user if metaData is null? ExtMetadata metadata = imageInfo.getMetadata(); if (metadata == null) { Media media = new Media(null, imageInfo.getOriginalUrl(), + page.title(), "", 0, null, null, null, imageInfo.getUser()); if (!StringUtils.isBlank(imageInfo.getThumbUrl())) { media.setThumbUrl(imageInfo.getThumbUrl()); }
codereview_java_data_1095
* * @return {@code true} if there are more tokens to process */ - protected boolean more() { return position < tokenStream.size(); } maybe change to `hasNext()`? (or at least `hasMore()` but the latter is more consistent with an Iterator) * * @return {@code true} if there are more tokens to process */ + protected boolean hasNext() { return position < tokenStream.size(); }
codereview_java_data_1099
package org.springframework.cloud.dataflow.core.dsl; /** - * After parsing a composed task definition from a DSL string, the validation visitor may optionally run. * Even though it parses successfully there may be issues with how the definition is constructed. The * {@link TaskValidatorVisitor} will find those problems and report them as instances of * {@link TaskValidationProblem}. does this only apply to composed task definitions? package org.springframework.cloud.dataflow.core.dsl; /** + * After parsing a task definition from a DSL string, the validation visitor may optionally run. * Even though it parses successfully there may be issues with how the definition is constructed. The * {@link TaskValidatorVisitor} will find those problems and report them as instances of * {@link TaskValidationProblem}.
codereview_java_data_1100
String brokerAddr = findBrokerResult.getBrokerAddr(); if (PullSysFlag.hasClassFilterFlag(sysFlagInner)) { - brokerAddr = computePullFromWhichFilterServer(mq.getTopic(), brokerAddr); } PullResult pullResult = this.mQClientFactory.getMQClientAPIImpl().pullMessage( Could you do more further to polish the name of the computePullFromWhichFilterServer? it is not good enough. String brokerAddr = findBrokerResult.getBrokerAddr(); if (PullSysFlag.hasClassFilterFlag(sysFlagInner)) { + brokerAddr = acquireFilterServerRandomly(mq.getTopic(), brokerAddr); } PullResult pullResult = this.mQClientFactory.getMQClientAPIImpl().pullMessage(
codereview_java_data_1123
return result; } - @Nullable static InetAddress InetAddressOrNull(@Nullable String string, @Nullable byte[] bytes) { try { return bytes == null ? null : InetAddress.getByAddress(bytes); } catch (UnknownHostException e) { Lowercase since method return result; } + @Nullable static InetAddress inetAddressOrNull(@Nullable String string, @Nullable byte[] bytes) { try { return bytes == null ? null : InetAddress.getByAddress(bytes); } catch (UnknownHostException e) {
codereview_java_data_1128
response.setOpaque(request.getOpaque()); - if (log.isDebugEnabled()) { - log.debug("receive PullMessage request command, {}", request); - } if (!PermName.isReadable(this.brokerController.getBrokerConfig().getBrokerPermission())) { response.setCode(ResponseCode.NO_PERMISSION); `log.isDebugEnabled()` is not necessary, and do not consistent with other codes log-style. response.setOpaque(request.getOpaque()); + log.debug("receive PullMessage request command, {}", request); if (!PermName.isReadable(this.brokerController.getBrokerConfig().getBrokerPermission())) { response.setCode(ResponseCode.NO_PERMISSION);
codereview_java_data_1145
@NotNull @JsonProperty - private String metricsFilePath = "/var/run/singularity/s3uploader-metrics.out"; public SingularityS3UploaderConfiguration() { super(Optional.of("singularity-s3uploader.log")); random thought, if we don't want everyone to have to have this enabled, maybe this could be an optional and we only start the poller if it's set? (Or another boolean for enabled?) @NotNull @JsonProperty + private Optional<String> metricsFilePath = Optional.absent(); public SingularityS3UploaderConfiguration() { super(Optional.of("singularity-s3uploader.log"));
codereview_java_data_1149
return Optional.empty(); } - public static BlockHeaderBuilder insertVoteToHeaderBuilder( final BlockHeaderBuilder builder, final Optional<ValidatorVote> vote) { final BlockHeaderBuilder voteHeaderBuilder = BlockHeaderBuilder.fromBuilder(builder); if (vote.isPresent()) { I know this was a bad function - but maybe "insert" doesn't make sense given we're not changing the passed in Builder - is it simply createBuilderFrom(x, y)? return Optional.empty(); } + public static BlockHeaderBuilder createHeaderBuilderWithVoteHeaders( final BlockHeaderBuilder builder, final Optional<ValidatorVote> vote) { final BlockHeaderBuilder voteHeaderBuilder = BlockHeaderBuilder.fromBuilder(builder); if (vote.isPresent()) {
codereview_java_data_1154
List<Presence> presences = applyAffiliationChange(getRole(), groupMember, null); if (presences.size() == 0 && isMembersOnly()) { - sendAffiliationChangeNotification(groupMember, affiliation); } else { // member is in MUC, send presence stanzas for (Presence presence : presences) { I don't think it's correct to add the `role` attribute like this. This does not take into account whatever role the user had - it will always inform others that this user now has no role. List<Presence> presences = applyAffiliationChange(getRole(), groupMember, null); if (presences.size() == 0 && isMembersOnly()) { + sendOutOfRoomAffiliationChangeNotification(groupMember, affiliation); } else { // member is in MUC, send presence stanzas for (Presence presence : presences) {
codereview_java_data_1157
mediaAdapter.notifyItemChanged(toggleSelectPhoto(m)); editMode = true; } - else { - selectAllPhotosUpTo(getImagePosition(m.getPath()),mediaAdapter); - } } else if (fav_photos && !all_photos) { if (!editMode) { mediaAdapter.notifyItemChanged(toggleSelectPhoto(m)); @angmas1 make this if else block similar to the block in lines 277-280. There is no need for the braces as there is a single statement in the else block. mediaAdapter.notifyItemChanged(toggleSelectPhoto(m)); editMode = true; } + else selectAllPhotosUpTo(getImagePosition(m.getPath()),mediaAdapter); } else if (fav_photos && !all_photos) { if (!editMode) { mediaAdapter.notifyItemChanged(toggleSelectPhoto(m));
codereview_java_data_1159
@JavascriptEnabled @Ignore({IE, PHANTOMJS, SAFARI, MARIONETTE}) public void testShouldRetainImplicitlyWaitFromTheReturnedWebDriverOfFrameSwitchTo() { - driver.manage().timeouts().implicitlyWait(3, SECONDS); driver.get(pages.xhtmlTestPage); driver.findElement(By.name("windowOne")).click(); String handle = (String)driver.getWindowHandles().toArray()[1]; would rather do a smaller timeout, 1 second should be sufficient @JavascriptEnabled @Ignore({IE, PHANTOMJS, SAFARI, MARIONETTE}) public void testShouldRetainImplicitlyWaitFromTheReturnedWebDriverOfFrameSwitchTo() { + driver.manage().timeouts().implicitlyWait(1, SECONDS); driver.get(pages.xhtmlTestPage); driver.findElement(By.name("windowOne")).click(); String handle = (String)driver.getWindowHandles().toArray()[1];
codereview_java_data_1160
public final static String generateHash(String data) throws Exception { String hashedData = data; try { - byte[] bytes = data.getBytes(StandardCharsets.US_ASCII); MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(bytes, 0, bytes.length); byte[] digestBytes = digest.digest(); Unfortunately, we cannot use this API as it was introduced in API level 19. Our SDK supports platforms that are lower than 19. Can you revert this back to "US-ASCII" string? We are reviewing the Base64 encoding change, public final static String generateHash(String data) throws Exception { String hashedData = data; try { + byte[] bytes = data.getBytes("US-ASCII"); MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(bytes, 0, bytes.length); byte[] digestBytes = digest.digest();
codereview_java_data_1169
} @Override - public void setRebalanceKeyForInput(int ordinal, FunctionEx<?, ?> keyFn) { - upstreamPartitionKeyFns[ordinal] = keyFn; } @Override - public boolean shouldRebalanceInput(int ordinal) { - return upstreamRebalancingFlags[ordinal]; } @Override Rename to `setPartitionKeyFnForInput` to match `public FunctionEx<?, ?> partitionKeyFnForInput(int ordinal)` } @Override + public boolean shouldRebalanceInput(int ordinal) { + return upstreamRebalancingFlags[ordinal]; } @Override + public void setPartitionKeyFnForInput(int ordinal, FunctionEx<?, ?> keyFn) { + upstreamPartitionKeyFns[ordinal] = keyFn; } @Override
codereview_java_data_1172
return collector.getReferenced(); } - final ExecutorService executorService = Executors.newCachedThreadPool(); - final class ChunkIdsCollector { - private final Set<Integer> referencedChunks = ConcurrentHashMap.newKeySet(); private final ChunkIdsCollector parent; private int mapId; `executorService.shotdown()` should be invoked somewhere. If `submit(...)` was used, resources (threads) are not released without proper shutdown. return collector.getReferenced(); } final class ChunkIdsCollector { + private final Set<Integer> referencedChunks = ConcurrentHashMap.<Integer>newKeySet(); private final ChunkIdsCollector parent; private int mapId;
codereview_java_data_1174
private void killPantheonProcess(final String name, final Process process) { LOG.info("Killing " + name + " process"); - Awaitility.waitAtMost(60, TimeUnit.SECONDS) .until( () -> { if (process.isAlive()) { Did you mean to keep this duration change? private void killPantheonProcess(final String name, final Process process) { LOG.info("Killing " + name + " process"); + Awaitility.waitAtMost(30, TimeUnit.SECONDS) .until( () -> { if (process.isAlive()) {
codereview_java_data_1194
substanceProduct.append(" "); String allergen; - for (int i = 0; i <= allergens.size() - 1; i++) { allergen = allergens.get(i); substanceProduct.append(Utils.getClickableText(allergen, allergen, SearchType.ALLERGEN, getActivity(), customTabsIntent)); substanceProduct.append(", "); This should actually read as the following `for (int i = 0; i < allergens.size(); i++)` substanceProduct.append(" "); String allergen; + for (int i = 0; i < allergens.size(); i++) { allergen = allergens.get(i); substanceProduct.append(Utils.getClickableText(allergen, allergen, SearchType.ALLERGEN, getActivity(), customTabsIntent)); substanceProduct.append(", ");
codereview_java_data_1200
enforceConnectionLimits(); } - private boolean doTheFractionOfRemoteConnectionsAllowsNewOne() { final int remotelyInitiatedConnectionsCount = Math.toIntExact( connectionsById.values().stream() I think this should be against the max allowed connection count, not a ratio against the current set of connection. @mbaxter, what's your opinion? enforceConnectionLimits(); } + private boolean remoteConnectionExceedsLimit() { final int remotelyInitiatedConnectionsCount = Math.toIntExact( connectionsById.values().stream()
codereview_java_data_1210
appUrlConfig = Config.getString("server.url"); appAllowNavigationConfig = Config.getArray("server.allowNavigation"); - String authority = "app"; - localUrl = "capacitor://" + authority + "/"; boolean isLocal = true; Should we ditch authority completely and move to a fixed, configurable hostname? The possibility of clash seems rare considering it's local to the app, no? appUrlConfig = Config.getString("server.url"); appAllowNavigationConfig = Config.getArray("server.allowNavigation"); + String authority = Config.getString("server.hostName", "app"); + localUrl = CAPACITOR_SCHEME_NAME + "://" + authority + "/"; boolean isLocal = true;
codereview_java_data_1212
} @Override - public void undo(long tid, Master env) throws Exception { // Clean up split files if create table operation fails - Path p = tableInfo.getSplitPath().getParent(); - FileSystem fs = p.getFileSystem(env.getContext().getHadoopConf()); - fs.delete(p, true); Utils.unreserveNamespace(env, tableInfo.getNamespaceId(), tid, false); } returns boolean, should we log when delete fails? } @Override + public void undo(long tid, Master env) throws IOException { // Clean up split files if create table operation fails + if(tableInfo.getInitialSplitSize() > 0) { + Path p = tableInfo.getSplitPath().getParent(); + FileSystem fs = p.getFileSystem(env.getContext().getHadoopConf()); + fs.delete(p, true); + } Utils.unreserveNamespace(env, tableInfo.getNamespaceId(), tid, false); }
codereview_java_data_1224
public class ByteBuffers { - public static byte[] copy(ByteBuffer buffer) { if (buffer.hasArray()) { byte[] array = buffer.array(); if (buffer.arrayOffset() == 0 && buffer.position() == 0 This method doesn't actually provide a defensive copy in all cases, so it shouldn't be a helper that claims to make a copy. A better name is `toByteArray` because it will use the underlying byte array if it exists and has an appropriate offset and length. I think ByteBuffers should provide both `copy` and `toByteArray` and `SerializableByteBufferMap` should continue to use `toByteArray`. public class ByteBuffers { + public static byte[] toByteArray(ByteBuffer buffer) { if (buffer.hasArray()) { byte[] array = buffer.array(); if (buffer.arrayOffset() == 0 && buffer.position() == 0