auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void shouldReturnTheExpectedIdNameForAListContainingTheExpectedId() { applyGetMethodAndCheckResult(ID_NAME_1, 0, ID_NAME_1, ID_NAME_2, ID_NAME_3); applyGetMethodAndCheckResult(ID_NAME_1, 1, ID_NAME_2, ID_NAME_1, ID_NAME_3); applyGetMethodAndCheckResult(ID_NAME_1, 2, ID_NAME_3, ID_NAME_2, ID_NAME_1); }

Target:
Für die Branch Interior Path Coverage überprüft man i.A. 0, 1, 2 Schleifendurchläufe.
Source:
void shouldReturnCorrectStringRepresentationForAGivenIdBasedOnAHardcodedClassname() { final ByIdResultSelector byIdResultSelector = new ByIdResultSelector("ID-Name"); assertThat(byIdResultSelector.toString()).isEqualTo( "io.jenkins.plugins.analysis.core.views.ResultAction with ID ID-Name"); }

Target:
Gute Frage ob man toString testen sollte oder nicht. Aus meiner Sicht würde reichten contains("ID-Name"). (Ist aber nicht falsch so)
Source:
public HealthAwareRecorder(String pluginName) { this.pluginName = "[" + pluginName + "] "; }

Target:
Note that it would be clearer for this to be marked `protected`: the class is `abstract` so this constructor could only be called by subclass constructors.
Source:
public void getReserveScopes() { Set<SystemScope> reserved = SystemScopeService.reservedScopes; assertThat(service.getReserved(), equalTo(reserved)); }

Target:
No need to pull this out as a separate variable, just reference it in the test below
Source:
public String getTestSrc() { return testSrcs.get(0); }

Target:
You require `srcs` to be non-empty, but you don't require `testSrcs` to be non-empty. So this line can throw an exception.
Source:
public static Mode getMode(Run run) { return Optional.ofNullable(run.get(LaunchUtils.Mode.class.getName())) .map(s -> valueOf(s)) .orElse(UNSET); }

Target:
Isn't this more simply: ```java .map(Mode::valueOf) ```
Source:
public static Run setMode(Run run, Mode mode) { run.set(LaunchUtils.Mode.class.getName(), mode.name()); return run; }

Target:
Returning `Run` here seems a bit cheeky for this method as API.
Source:
protected void launchJavaElements(List<IJavaElement> elements, String mode) throws CoreException { launch(elements.iterator().next().getJavaProject().getProject().getFullPath(), mode); }

Target:
Up above you used `elements.get(0).getJava...`. Here it is `elements.iterator().next().getJava...`. Lets make them consistent. Since `elements` is a list, lets use `get(0)` here to match the code above.
Source:
public static IResource getTargetResource(ILaunchConfiguration configuration) throws CoreException { String target = getTargetName(configuration); IResource targetResource = ResourcesPlugin.getWorkspace().getRoot().findMember(target); return targetResource; }

Target:
This null check is still necessary since you do not want to pass null to findMember.
Source:
private String getRemoteBranch() { if (params.branch == null) { return GitCloneTemplateParams.DEFAULT_BRANCH; } if (params.branch.indexOf('/') == -1) { return "origin/" + params.branch; } return params.branch; }

Target:
This is not right. Branches can have `/` in them. Since the local "clone" determines what it calls the remote repo, I suspect jgit is always using origin. So the test needs to be `if (!params.branch.startsWith("origin/")`.
Source:
public void setWireframe(boolean val) { if(chart.isSetWireframe()) chart.getWireframe().setVal(val); else chart.addNewWireframe().setVal(val); }

Target:
all three above methods don't follow the project's formatting style
Source:
boolean dispose() throws IOException { try { _out.close(); } finally { } return true; }

Target:
I don't think exception should be swallowed
Source:
private void updateSheetTable(CTTable ctTable, String title, int index) { CTTableColumns tableColumnList = ctTable.getTableColumns(); CTTableColumn column = null; int columnCount = tableColumnList.getTableColumnList().size()-1; for( int i = columnCount; columnCount < index; i++) { column = tableColumnList.addNewTableColumn(); column.setId(i); ++columnCount; } column = tableColumnList.getTableColumnArray(index); column.setName(title); }

Target:
Could you use this? ``` for (int i = columnCount; i < index; i++) { column = tableColumnList.addNewTableColumn(); column.setId(i); } ```
Source:
public static FormulaShifter createForRowShift(int externSheetIndex, String sheetName, int firstMovedRowIndex, int lastMovedRowIndex, int numberOfRowsToMove, SpreadsheetVersion version) { FormulaShifter instance = new FormulaShifter(externSheetIndex, sheetName, firstMovedRowIndex, lastMovedRowIndex, numberOfRowsToMove, ShiftMode.RowMove, version); return instance; }

Target:
`return new FormulaShifter(`... is fine. No need to store the returned value in `instance`.
Source:
public void shift(int n) { int rownum = getRowNum() + n; String msg = "Row[rownum="+getRowNum()+"] contains cell(s) included in a multi-cell array formula. " + "You cannot change part of an array."; for(Cell c : this){ ((XSSFCell)c).updateCellReferencesForShifting(msg); } setRowNum(rownum); }

Target:
Does `protected` work?
Source:
public boolean matches(URL url) { return url.getProtocol().equals("file") && url.toExternalForm().endsWith(".jar"); }

Target:
Aren't there url's like this too? file://some/path/my.jar!org/foo/bar The ! is often used in java url's to indicate that it's inside zip (not sure if it's used in these kind though). I agree contains has false positives (like tony.jarvis) but endswith might have false negatives (like my.jar!org).
Source:
public boolean disablePearlDamage(boolean allow) { pearlDamage = allow; return allow; }

Target:
No real need for a return type :P
Source:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); Assert.notNull(callbackUri, "callbackUri must be configured."); Assert.notNull(idSiteOrganizationResolver, "idSiteOrganizationResolver must be configured."); Assert.notNull(alreadyLoggedInUri, "alreadyLoggedInUri must be configured."); Assert.isTrue(!(preRegisterHandler != null && preLoginHandler != null), "This IDSite controller must contain only one of preRegisterHandler and preLoginHandler"); }

Target:
Why can you not have both a pre-login handler and a pre-register handler? You can when not using id site.
Source:
public Phone setAccount(Account account) { if(((AbstractResource)account).isMaterialized()) { setResourceProperty(ACCOUNT,account); } else{ setMaterializableResourceProperty(ACCOUNT,account); } return this; }

Target:
I think the `setMaterializableResourceProperty` should handle the materialized scenario itself. This means that this method can simply invoke `setMaterializableResourceProperty(ACCOUNT,account);` and then, the internal code of `setMaterializableResourceProperty` will check whether the account is materialized or not and then will relay on `setResourceProperty(ACCOUNT,account);` internally.
Source:
public boolean isAccountLinkingEnabled () { return AccountLinkingStatus.ENABLED.equals(getStatus()) ? true : false; }

Target:
Can be simplified to `AccountLinkingStatus.ENABLED.equals(getStatus())`
Source:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); IdSiteController controller = new LogoutIdSiteController(); controller.setServerUriResolver(serverUriResolver); controller.setCallbackUri(idSiteResultUri); controller.setIdSiteOrganizationResolver(idSiteOrganizationResolver); controller.setAlreadyLoggedInUri(nextUri); //this will not really have any affect on logout but we need to set it otherwise controller#init() will throw controller.init(); this.idSiteController = controller; }

Target:
Why are you removing this? `LogoutController#init()` says `//If sub-classess override this method they MUST CALL super.init() at some point insider their custom implementation.` Removing an existing explicit invocation to a method in a parent class could cause uncaught errors if we are not sure about what we are doing. Please add it back in and we can solve any new issue that this could cause.
Source:
public String createCsrfToken(HttpServletRequest request, HttpServletResponse response) { CsrfToken csrfToken = this.csrfTokenRepository.loadToken(request); final boolean missingToken = csrfToken == null; if (missingToken) { csrfToken = this.csrfTokenRepository.generateToken(request); this.csrfTokenRepository.saveToken(csrfToken, request, response); } return csrfToken.getToken(); }

Target:
This line seems unnecessary. Why not: ``` if (csrfToken == null) { ... ```
Source:
public Account removeGroup(String hrefOrName) { GroupMembership groupMembership = null; for (GroupMembership aGroupMembership : getGroupMemberships()) { if (aGroupMembership.getGroup().getName().equalsIgnoreCase(hrefOrName) || aGroupMembership.getGroup().getHref().equalsIgnoreCase(hrefOrName)) { groupMembership = aGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } else { throw new IllegalStateException("This account does not belong to the specified group."); } return this; }

Target:
`href`s are case sensitive. Please do `aGroupMembership.getGroup().getHref().equals(hrefOrName))`
Source:
public ApiAuthenticationResult authenticate(HttpServletRequest httpServletRequest) { Assert.notNull(httpServletRequest, "httpRequest argument cannot be null."); Assert.isInstanceOf(javax.servlet.http.HttpServletRequest.class, httpServletRequest, "The specified httpRequest argument must be an instance of " + HTTP_SERVLET_REQUEST_FQCN); com.stormpath.sdk.impl.http.ServletHttpRequest stmpHttpRequest = new com.stormpath.sdk.impl.http.ServletHttpRequest(httpServletRequest); return (ApiAuthenticationResult) Applications.apiRequestAuthenticator(application).authenticate(stmpHttpRequest); }

Target:
`ApiAuthenticationResult` casting redundant
Source:
public void setWebDialogEnabled(boolean isEnabled) { isWebDialogEnabled = isEnabled; addConfig("webDialogEnabled", isWebDialogEnabled ? "true" : "false"); }

Target:
Please remove this line
Source:
public static void init() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); ITEMS.register(modEventBus); for (SlimeBlock.SlimeType type : SlimeBlock.SlimeType.values()) { System.out.println(type); System.out.println(type.toString()); } }

Target:
Leftover debug?
Source:
public void handleServerSafe(NetHandlerPlayServer netHandler) { if(netHandler.player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem() instanceof ItemSlimeBoots) netHandler.player.fallDistance = 0; }

Target:
Your indentation is way off, we use 2 space indentation. We also always use curly brackets for single if statements
Source:
public List<BakedQuad> getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { if(side == null) return quads; return ImmutableList.of(); }

Target:
Really mezz, no braces? You're better than that ;P
Source:
public void update() { if(isClientWorld()) { return; } // are we fully formed? if(!isActive()) { // check for furnace once per second if(tick == 0) { checkMultiblockStructure(); } } else { // we have a lot less to do than a smeltery since the inside is unreachable and we have no liquids // basically just heating and fuel consumption // we heat items every tick, as otherwise we are quite slow compared to a vanilla furnace if(tick % 4 == 0) { heatItems(); interactWithEntitiesInside(); } if(needsFuel) { consumeFuel(); } // we don't check the inside for obstructions since it should not be possible unless the outside was modified } tick = (tick + 1) % 20; }

Target:
The smeltery only runs this every 20 ticks, or `tick == 0`
Source:
public GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos) { return new GuiTinkerTank((ContainerTinkerTank) createContainer(inventoryplayer, world, pos), this); }

Target:
Unneeded cast
Source:
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { // use the glowball for the pickblock, as it is more useful than the technical block if(gadgetsLoaded) { return new ItemStack(TinkerGadgets.throwball, 1, ItemThrowball.ThrowballType.GLOW.ordinal()); } // if unavailable, just return nothing, Minecraft will just not do anything on pick block return null; }

Target:
I'd reduce this to a simple `if(TinkerGadgets.throwball != null)`. That way there is no hard dependency on the pulse.
Source:
public void setUp() throws Exception { TestPersistentBinaryDeque.setupTestDir(); m_pbd = PersistentBinaryDeque.builder(TestPersistentBinaryDeque.TEST_NONCE, TestPersistentBinaryDeque.TEST_DIR, s_logger) .compression(true) .initialExtraHeader(null, TestPersistentBinaryDeque.SERIALIZER).build(); m_pbd.setRetentionPolicy(BinaryDeque.RetentionPolicyType.TIME_MS, new Long(s_retainMillis)); m_pbd.startRetentionPolicyEnforcement(); }

Target:
Minor: Usually better to use `Long.valueOf` instead of `new Long`
Source:
public static Object extractPartitioningValue(RelDistribution dist) { RexNode partitioningNode = dist.getPartitionEqualValue(); if (partitioningNode instanceof RexLiteral) { RexLiteral literal = (RexLiteral) partitioningNode; Comparable value = literal.getValue(); if (value instanceof Number) { return ((Number) value).longValue(); } else { try { RexLiteral.stringValue(literal); } catch(Exception ex) { } } } return null; }

Target:
missing return?
Source:
public synchronized void resume() { m_isPaused = false; }

Target:
This doesn't need to be synchronized, right?
Source:
public boolean isOrderDeterministic(boolean orderIsDeterministic) { CompiledPlan plan = getBestCostPlan(); // If the plan is null, there is an error in the query, // so we can return anything. if (plan != null) { return orderIsDeterministic && plan.isOrderDeterministic(); } else { return orderIsDeterministic; } }

Target:
BTW this style is considered an unnecessary else and is actually a possible compiler error/warning in eclipse and I think other java compilers
Source:
protected ClientConfig createClientConfig() { ClientConfig cc = new ClientConfig(m_username, m_password); cc.setProcedureCallTimeout(10 * 60 * 1000); // 10 min return cc; }

Target:
I think it would be cleaner to add a `createClientConfig(Stirng username, String password)` method and then just have this current one call that one with empty strings.
Source:
public void newSegmentAdded() { if (!m_pbd.isCursorOpen(CURSOR_NAME)) { // not started yet return; } if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Processing newSegmentAdded for PBD " + m_pbd.getNonce()); } scheduleTaskFor(m_pbd.getNonce(), ()->deleteOldSegments(), MIN_DELAY); }

Target:
You can do `this::deleteOldSegments` for the callable
Source:
public ValidationError(String msg) { super("ValidationError: " + msg); }

Target:
It might be better to override toString rather than append ValidationError because now you will get `org.voltdb.exception.ValidationError: ValidationError: MESSAGE` when toString is called or the stack trace is printed
Source:
public void put(TraceEventType eventType, TraceEventWrapper beginWrapper, long beginTime, String eventId) { if (TraceEventType.DURATION_BEGIN.equals(eventType)) { m_durationEvents.addLast(new Pair<TraceEventWrapper, Long>(beginWrapper, beginTime)); return; } if (TraceEventType.ASYNC_BEGIN.equals(eventType)) { m_asyncEvents.put(eventId, new Pair<TraceEventWrapper, Long>(beginWrapper, beginTime)); return; } return; }

Target:
Use `Pair.of(beginWrapper, beginTime)`
Source:
private void fillNextCycle(int numUpdates, boolean expect) { for (int ii = 0; ii < numUpdates; ii++) { Random m_random = new Random(); int maxStreamSuffix = m_expectedValues.lastKey() + 1; int targetSuffix; do { targetSuffix = m_random.nextInt(maxStreamSuffix); } while (!m_expectedValues.containsKey(targetSuffix)); changeCursor(targetSuffix, getRandomPartitionId(), Math.abs(m_random.nextLong()), expect); } }

Target:
Why is this creating a new random instance for each iteration in the loop? Also shouldn't be using the `m_` prefix
Source:
public static RelBuilderFactory proto(final Context context) { return new RelBuilderFactory() { public RelBuilder create(RelOptCluster cluster, RelOptSchema schema) { return new VoltPRelBuilder(context, cluster, schema); } }; }

Target:
As suggested by IntelliJ: ```suggestion public static RelBuilderFactory proto(final Context context) { return (cluster, schema) -> new VoltPRelBuilder(context, cluster, schema); } ```
Source:
public AggregateExpression(ExpressionType type) { super(type); m_userAggregateId = "-1"; m_name = "notUDAF"; }

Target:
empty string is better, if that works.
Source:
public boolean isUserDefined() { if (m_userAggregateId != null) { return FunctionForVoltDB.isUserDefinedFunctionId(Integer.parseInt(m_userAggregateId)); } else { return false; } }

Target:
Is this correct? It's never set to null.
Source:
public synchronized void startPolling(CatalogContext catalogContext) { m_startPolling = true; CatalogMap<Connector> connectors = CatalogUtil.getConnectors(catalogContext); if(!CatalogUtil.hasEnabledConnectors(connectors)) { exportLog.info("System is not using any export functionality or connectors configured are disabled."); return; } ExportDataProcessor processor = m_processor.get(); Preconditions.checkState(processor != null, "guest processor is not set"); processor.startPolling(); // Notify export datasources to check the *generation* of export buffers, // delete buffers older than current generation number or generation number // from snapshot. cleanupStaleBuffers(); }

Target:
BUG? Should'nt this be done BEFORE startting the processor polling?
Source:
private static RelNode toIndexJoin(VoltPhysicalJoin join, RelNode outerScan, RelNode innerChild, String indexName) { return new VoltPhysicalNestLoopIndexJoin( join.getCluster(), join.getTraitSet(), outerScan, innerChild, join.getCondition(), join.getVariablesSet(), join.getJoinType(), join.isSemiJoinDone(), ImmutableList.copyOf(join.getSystemFieldList()), join.getSplitCount(), indexName); }

Target:
Join type check should be consolidated probably in the logical phase
Source:
private int containsFunctionByIds(Set<Integer> functionIds) { if (this instanceof AbstractValueExpression) { return -1; } List<AbstractExpression> functionsList = findAllFunctionSubexpressions(); for (AbstractExpression funcExpr : functionsList) { assert (funcExpr instanceof FunctionExpression); if (functionIds.contains(((FunctionExpression) funcExpr).getFunctionId())) { return ((FunctionExpression) funcExpr).getFunctionId(); } } return -1; }

Target:
Do you need this here? When? Or should it belong to `findAllFunctionsSubexpressions()`?
Source:
public void updateCatalog(Table table, long genId) { m_es.execute(new Runnable() { public void run() { if (genId != m_previousGenId) { assert (genId > m_previousGenId); // This serializer is used to write stream schema to pbd StreamTableSchemaSerializer ds = new StreamTableSchemaSerializer(table, table.getTypeName(), genId); try { m_committedBuffers.updateSchema(ds); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to write PBD export header.", true, e); } m_previousGenId = genId; } } }); }

Target:
I would check the equality first and add a runable if needed to avoid unneeded runs.
Source:
static void resetDir() throws IOException { File f = new File("/tmp/" + System.getProperty("user.name")); VoltFile.recursivelyDelete(f); f.mkdirs(); }

Target:
This directory should probably be defined in a common place so if we want to move it to another location it is a single update
Source:
void reset() { m_syncedSinceLastEdit = false; if (m_segmentHeaderBuf != null) { m_segmentHeaderBuf.discard(); m_segmentHeaderBuf = null; } if (m_entryHeaderBuf != null) { m_entryHeaderBuf.discard(); m_entryHeaderBuf = null; } m_crc.reset(); m_crc.reset(); }

Target:
Duplicated line (probably global replace)
Source:
public static void writeEntryHeader(CRC32 crc, ByteBuffer headerBuf, ByteBuffer destBuf, int size, int flag) { crc.update(size); crc.update(flag); crc.update(destBuf); headerBuf.clear(); headerBuf.order(ByteOrder.LITTLE_ENDIAN); headerBuf.putLong(crc.getValue()); headerBuf.putInt(size); headerBuf.putInt(flag); headerBuf.order(ByteOrder.BIG_ENDIAN); }

Target:
Not sure if it matters but the value returned by getValue is really an unsigned int so you could store an int here and save 4bytes if that matters at all
Source:
public static void setFinal(File file, boolean isFinal) { try { UserDefinedFileAttributeView view = getFileAttributeView(file); view.write(IS_FINAL_ATTRIBUTE, Charset.defaultCharset().encode(new Boolean(isFinal).toString())); } catch (Exception e) { // No-op } }

Target:
I would prefer if not all exceptions were swallowed but instead maybe just IOExceptions and it still might be nice to log those at debug in case somebody ever wonders why this isn't working.
Source:
@Override void addHostData(VoltTableRow row) throws IOException { assert(row.getString("TABLE").equals(getTableName())); checkSiteConsistency(row); // throws if inconsistent // this cast should be safe; site_ids are ints but get // promoted to long in the VoltTable.row.getLong return m_hostsWithThisTable.add((int) row.getLong("CURRENT_HOST_ID")); }

Target:
Why are you putting the annotation on the same line as the method name. Normally all annotations are on their own line
Source:
VoltPSetOpsRule(RelOptRuleOperand operand, MatchType matchType) { super(operand, "VoltPSetOpsRule_" + matchType.name()); m_matchType = matchType; }

Target:
The constructor can be private.
Source:
public NonDdlBatch setInferPartitioning(boolean value) { value = m_batchToDecorate.getTaskCount() == 1 && value; if (m_inferPartitioning ^ value) { m_inferPartitioning = value; updateStatementPartitioning(); } return this; }

Target:
let's just use `m_inferPartitioning != value`.
Source:
JoinType(int val) { assert (this.ordinal() == val) : "Enum element " + this.name() + " in position " + this.ordinal() + " instead of position " + val; m_val = val; }

Target:
if m_val has to equal ordinal why bother storing it you could just use ordinal everywhere.
Source:
public VoltDBLLimit( RelOptCluster cluster, RelTraitSet traitSet, RelNode input, RexNode offset, RexNode limit) { super(cluster, traitSet, input); assert VoltDBLRel.VOLTDB_LOGICAL.equals(getConvention()); m_offset = offset; m_limit = limit; }

Target:
Should we be consistent with the assert assert VoltDBLRel.VOLTDB_LOGICAL.equals(getConvention()); vs assert traitSet.contains(VoltDBLRel.VOLTDB_LOGICAL);
Source:
protected CompiledPlan compileAdHocCalcitePlan(String sql, boolean inferPartitioning, boolean forcedSP, DeterminismMode detMode) { CompiledPlan cp = null; try { cp = m_aide.compileAdHocPlan(PlannerType.CALCITE, sql, inferPartitioning, forcedSP, detMode); assertNotNull(cp); } catch (Exception ex) { fail(ex.getMessage()); } return cp; }

Target:
Why not just let the exception bubble up and fail the test by having the test throw an exception. That way the entire stack trace is captured by junit.
Source:
protected RelNode visitChild(RelNode parent, int i, RelNode child) { child.accept(this); parent.getCluster().setMetadataProvider(metadataProvider); return parent; }

Target:
And also here: refer to L55 of calcite/core/src/main/java/org/apache/calcite/rel/RelShuttleImpl.java. The `accept` method does not change anything on `this` instance; it returns a modified copy of `child`, which you then discarded.
Source:
public CatalogMap(Catalog catalog, CatalogType parent, String name, Class<T> cls, int depth) { m_catalog = catalog; m_parent = parent; m_name = name; m_cls = cls; m_depth = depth; if (depth <= 3) { m_cachedPath = getPath(); } }

Target:
Revert this
Source:
protected void writeTestFileName(String name, boolean append) throws FileNotFoundException { File outFileName = new File(m_testNamesFile); if ( ! outFileName.exists() ) { append = false; } PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFileName, append))); ps.print(name); ps.close(); }

Target:
[Java-8 try-with-resource](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html): try(PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFileName, append)))) { ps.print(name); }
Source:
public Object getValue(Session session) { if (opType != OpTypes.STARTS_WITH) { return super.getValue(session); } Object leftValue = nodes[LEFT].getValue(session); Object rightValue = nodes[RIGHT].getValue(session); if (startsWithObject.isVariable) { synchronized (startsWithObject) { startsWithObject.setPattern(session, rightValue); return startsWithObject.compare(session, leftValue); } } return startsWithObject.compare(session, leftValue); }

Target:
Is this necessary? When would multiple threads with same `ExpressionStartsWith` object instance be?
Source:
public Object getValue(Session session) { if (opType != OpTypes.STARTS_WITH) { return super.getValue(session); } Object leftValue = nodes[LEFT].getValue(session); Object rightValue = nodes[RIGHT].getValue(session); if (startsWithObject.isVariable) { startsWithObject.setPattern(session, rightValue); return startsWithObject.compare(session, leftValue); } return startsWithObject.compare(session, leftValue); }

Target:
This return statement can be deleted, right?
Source:
String getPathOfBatchDir(String prefix) { assert(m_batched); String hostId = ""; if(m_uniquenames) { hostId = "-("+VoltDB.instance().getHostMessenger().getHostId()+")"; } return m_outDir.getPath() + File.separator + prefix + m_nonce + "-" + m_dateformat.get().format(start) + hostId; }

Target:
This is changing the batch directory name. This shouldn't be changed. Only the filenames need to be changed.
Source:
void resolveColumnIndexesUsingSchema(NodeSchema inputSchema) { // get all the TVEs in the output columns int difftor = 0; for (SchemaColumn col : m_outputSchema) { col.setDifferentiator(difftor); ++difftor; Collection<TupleValueExpression> allTves = ExpressionUtil.getTupleValueExpressions(col.getExpression()); // and update their indexes against the table schema for (TupleValueExpression tve : allTves) { tve.setColumnIndexUsingSchema(inputSchema); assert (tve.getColumnIndex() >= 0 || tve.getColumnIndex() < inputSchema.size()); } } // DON'T RE-SORT HERE }

Target:
Is is possible for the column index to be negative? How can that be? Should this be an && and not a ||?
Source:
public VoltNIOWriteStream writeStream() { assert(m_writeStream != null && m_writeStream instanceof VoltNIOWriteStream); return (VoltNIOWriteStream) m_writeStream; }

Target:
If m_writeStream is defined as VoltNIOWriteStream, then the assertion and cast here is not needed.
Source:
private synchronized void buildListener(AdvertisedDataSource ads) { //Dont construct if we are shutdown if (m_shutdown) return; final ExportDecoderBase edb = m_client.constructExportDecoder(ads); detectDecoder(m_client, edb); Pair<ExportDecoderBase, AdvertisedDataSource> pair = Pair.of(edb, ads); m_decoders.add(pair); final ListenableFuture<BBContainer> fut = m_source.poll(); addBlockListener(m_source, fut, edb); }

Target:
It doesn't have to be `synchronized`, ExportRunner already grabs `GuestProcessor.this` lock before it calls `buildListener()`
Source:
public void notifyOfCatalogUpdate() { try { clearSessions(); if (httpClientInterface != null) { httpClientInterface.notifyOfCatalogUpdate(); } } catch (Exception ex) { m_log.error("Failed to update HTTP interface after catalog update", ex); } }

Target:
Is this error handling enough? What are the risks of getting here?
Source:
public ListenableFuture<?> sync(final boolean nofsync) { return m_es.submit(new Runnable() { @Override public void run() { new SyncRunnable(nofsync).run(); } }); }

Target:
Can be simplified to `return m_es.submit(new SyncRunnable(nofsync));`
Source:
private synchronized void ackImpl(long uso, Exception ackCallStack) { if (uso == Long.MIN_VALUE && m_onDrain != null) { //If we are not continueing generation set drained flag. if (!m_isInContinueingGeneration) m_drained = true; m_drainTraceForDebug = new Exception("Acking USO " + uso, ackCallStack); m_onDrain.run(); return; } //Process the ack if any and add blocks to the delete list or move the released USO pointer if (uso > 0) { try { releaseExportBytes(uso); } catch (IOException e) { VoltDB.crashLocalVoltDB("Error attempting to release export bytes", true, e); return; } } }

Target:
Is it necessary to synchronize this?
Source:
private static void addStatementDependence(Function function, Statement catalogStmt) { String stmtDeps = catalogStmt.getFunctiondependees(); if ("".equals(stmtDeps)) { // We will add this function. So make sure it has an // initial comma. stmtDeps = ","; } String functionName = function.getTypeName(); if ( ! stmtDeps.contains("," + functionName + ",")) { stmtDeps += functionName + ","; catalogStmt.setFunctiondependees(stmtDeps); } }

Target:
I would prefer `stmtDeps.isEmpty()`
Source:
private static void addFunctionDependence(Function function, Procedure procedure, Statement catalogStmt) { String funcDeps = function.getStmtdependers(); if ("".equals(funcDeps)) { // We will add this procedure:statement pair. So make sure we have // an initial comma. funcDeps = ","; } String statementName = procedure.getTypeName() + ":" + catalogStmt.getTypeName(); if ( ! funcDeps.contains("," + statementName + ",")) { funcDeps = funcDeps + statementName + ","; function.setStmtdependers(funcDeps); } }

Target:
I would prefer `funcDeps.isEmpty()`
Source:
public static void saveDefinedFunctions() { for (String name : FunctionDescriptor.defined_functions) { FunctionDescriptor fd = FunctionDescriptor.by_LC_name.get(name); FunctionDescriptor.by_LC_name.remove(name); m_savedFunctionDfns.put(name, fd); } FunctionDescriptor.defined_functions.clear(); }

Target:
This method seems equivalent to `deleteOldFunctions`?
Source:
public synchronized void onClusterStateChange(VersionedOperationMode mode) { m_clusterMode = mode.getMode(); switch (m_clusterMode) { case PAUSED: importLog.info("Cluster is paused shutting down all importers."); close(); importLog.info("Cluster is paused all importers shutdown."); break; case RUNNING: importLog.info("Cluster is resumed STARTING all importers."); resume(); importLog.info("Cluster is resumed STARTED all importers."); break; default: break; } }

Target:
You dont need to keep this keeping copy of cluster mode somewhere inside is not good.
Source:
public CompleteTransactionMessage(long initiatorHSId, long coordinatorHSId, long txnId, boolean isReadOnly, int hash, boolean isRollback, boolean requiresAck, boolean isRestart, boolean isForReplay) { super(initiatorHSId, coordinatorHSId, txnId, 0, isReadOnly, isForReplay); m_hash = hash; setBit(ISROLLBACK, isRollback); setBit(REQUIRESACK, requiresAck); setBit(ISRESTART, isRestart); m_isForReplica = true; m_ackRequestedFromSender = false; }

Target:
Why change the default value?
Source:
private CompleteTransactionMessage makeCompleteTxnMsg(boolean readOnly, boolean isRollback, boolean isRestart) { CompleteTransactionMessage msg = new CompleteTransactionMessage(0l, 0l, m_mpiTxnEgo.getTxnId(), readOnly, 0, isRollback, false, isRestart, false); msg.setForReplica(false); return msg; }

Target:
If by default it's false, then you can remove it.
Source:
public void close() throws InterruptedException, NoConnectionsException { while (m_processedCount.get() != m_totalRowCount.get()) { m_client.drain(); Thread.yield(); } m_reinsertExecutor.shutdown(); m_reinsertExecutor.awaitTermination(365, TimeUnit.DAYS); // Don't close the client because it may be shared with other loaders }

Target:
only shutdown if its present.
Source:
public void testIndividualProcTimeout() throws IOException, ProcCallException, InterruptedException { // If the authentication information is // incorrect, shutdown will not succeed. // So, we need to set this in any case. // Feel free to reset it later on. m_username="adminUser"; m_password="password"; if (isValgrind() || isDebug()) { // Disable the memcheck/debug for this test, it takes too long return; } Client client; m_username = "adminUser"; m_password = "password"; client = getClient(); checkIndividualProcTimeout(client, true); m_username = "userWithAllProc"; m_password = "password"; client = getClient(); checkIndividualProcTimeout(client, false); }

Target:
In this case, these member variables seem to be set to the same values immediately below... delete lines 440-441?
Source:
protected void addCorrelationParameterValueExpression(AbstractExpression expr, List<AbstractExpression> pves) { int paramIdx = AbstractParsedStmt.NEXT_PARAMETER_ID.getAndIncrement(); m_parameterIdxList.add(paramIdx); ParameterValueExpression pve = new ParameterValueExpression(paramIdx, expr); pves.add(pve); }

Target:
Hmm... parameter IDs should all be adjacent for the same statement, right? If there were concurrent planners that might not be the case and havoc could result. I think `NEXT_PARAMETER_ID` should be a normal (non-static) member of some object that is not shared by more than one thread. `QueryPlanner` seems to fit this description?
Source:
private void doInitiation(RejoinMessage message) { m_coordinatorHsId = message.m_sourceHSId; registerSnapshotMonitor(message.getSnapshotNonce()); long sinkHSId = m_dataSink.initialize(message.getSnapshotSourceCount(), message.getSnapshotBufferPool()); // respond to the coordinator with the sink HSID RejoinMessage msg = new RejoinMessage(m_mailbox.getHSId(), -1, sinkHSId); m_mailbox.send(m_coordinatorHsId, msg); m_taskQueue.offer(this); m_taskQueue.setQueueDepthTracker(new QueueDepthTracker(m_partitionId)); JOINLOG.info("P" + m_partitionId + " received initiation"); }

Target:
Do we have to do this for RejoinProducer too?
Source:
private void doInitiation(RejoinMessage message) { m_coordinatorHsId = message.m_sourceHSId; registerSnapshotMonitor(message.getSnapshotNonce()); long sinkHSId = m_dataSink.initialize(message.getSnapshotSourceCount(), message.getSnapshotBufferPool()); // respond to the coordinator with the sink HSID RejoinMessage msg = new RejoinMessage(m_mailbox.getHSId(), -1, sinkHSId); m_mailbox.send(m_coordinatorHsId, msg); m_taskQueue.setQueueDepthTracker(new QueueDepthTracker(m_partitionId)); m_taskQueue.offer(this); JOINLOG.info("P" + m_partitionId + " received initiation"); }

Target:
The `m_taskQueue` should already been initialized with a tracker by `BaseInitiator` at this point. If you are adding this because of some unit test failures, that might be because the unit tests construct `ElasticJoinProducer` without a real `BaseInitiator`. In that case, the proper place to set the tracker is in the unit tests. Maybe you can follow the starvation tracker initialization pattern because it is also used in the `SiteTaskerQueue`.
Source:
public String getVoltDBRootPath(PathsType.Voltdbroot path) { if (isRunningWithOldVerbs()) { return path.getPath(); } try { return m_nodeSettings.getVoltDBRoot().getCanonicalPath(); } catch (IOException e) { throw new SettingsException("failed to canonicalize voltdbroot"); } }

Target:
Can include the path for which it failed to canonicalize. Something like ```Java File root = m_nodeSettings.getVoltDBRoot(); String path = voltdbRoot.getPath(); try { return root.getCanonicalPath(); } catch (IOException e) { throw new SettingsException("failed to canonicalize voltdbroot " + path + ". Reason: " + e.getMessage()); } ``` Similar recommendation for all other paths below - command log, snapshot, dr/export overflow and so forth.
Source:
static public Test suite() throws IOException { // the suite made here will all be using the tests from this class MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestEmptySchema.class); // build up a project builder for the workload VoltProjectBuilder project = getBuilderForTest(); boolean success; LocalCluster config = new LocalCluster(true, "decimal-default.jar", 2, 3, 0, BackendTarget.NATIVE_EE_JNI); success = config.compile(project); assertTrue(success); // add this config to the set of tests to run builder.addServerConfig(config); return builder; }

Target:
@zeemanhe @vittvolt Great suggestion!
Source:
public boolean equals(Object o) { if (!(o instanceof ImportConfiguration)) { return false; } ImportConfiguration other = (ImportConfiguration) o; return m_moduleProps.equals(other.m_moduleProps) && m_formatterBuilder.equals(other.m_formatterBuilder); }

Target:
add if (o == this) return true;
Source:
public void shutdown(ShutdownInput shutDownInput) { if (isDebugEnabled()) { debug(null, "shard ID: " + (m_shardId.trim().isEmpty()? "unknown" : m_shardId) + ", shutdown reason: " + shutDownInput.getShutdownReason().name()); } if (ShutdownReason.TERMINATE.equals(shutDownInput.getShutdownReason())) { //The shard may be split or merged. checkpoint one last time commitCheckPoint(shutDownInput.getCheckpointer()); } }

Target:
Not blocker: please put a space before the ?
Source:
void close() { try { m_reader.close(); } catch (IOException e) { } }

Target:
Why not throw IOException and let caller handle and log etc.
Source:
public static int get(String token) { int type = reservedKeys.get(token, -1); if (type == -1) { return commandSet.get(token, -1); } return type; }

Target:
This looks like it can go back to having package visibility now.
Source:
public int getCount() throws InterruptedException, KeeperException { ZKUtil.FutureWatcher fw = new ZKUtil.FutureWatcher(); return ByteBuffer.wrap(m_zk.getData(m_path, fw, null)).getInt(); }

Target:
Is this FutureWatcher needed here? I don't know what's the purpose of this watcher. The method await() above calls get() on it after getting ZK data.
Source:
VoltTableSpliterator(VoltTable table, int origin, int fence) { System.out.printf("New VTS %d -> %d in Table with %d rows\n", origin, fence, table.getRowCount()); System.out.flush(); if (origin == fence) { m_row = null; return; } assert(origin < fence); m_row = table.fetchRow(origin); m_fence = fence; }

Target:
Cleanup?
Source:
public void reInitSysProc(CatalogContext catalogContext, CatalogSpecificPlanner csp) { assert(m_procedure != null); if (! m_isSysProc) { return; } assert(m_procedure instanceof VoltSystemProcedure); ((VoltSystemProcedure) m_procedure).initSysProc(m_site, catalogContext.cluster, catalogContext.getClusterSettings(), catalogContext.getNodeSettings()); m_csp = csp; }

Target:
This assert is not needed since it will hit line 228 if the procedure is not a VoltSystemProcedure.
Source:
public static Client createClient(ClientConfig config) { Client client = null; synchronized (ClientFactory.class) { if (!m_preserveResources && ++m_activeClientCount == 1) { VoltLogger.startAsynchronousLogging(); EstTimeUpdater.start(); ReverseDNSCache.start(); } } config.enableSSL(); client = new ClientImpl(config, config.getSslContext()); return client; }

Target:
What's up here? Does this always create SSL clients?
Source:
public void markHostMissing(boolean isMissing) { if (isMissing) { this.isMissing = true; } }

Target:
Do you need the IF case here? Or does it has use case to set isMissing to be false?
Source:
public void testMultiPartitionCURRENT_TIMESTAMP() throws IOException, ProcCallException { if (!isHSQL()) { Client client = getClient(); client.callProcedure(CurrentTimestampProcedure.class.getSimpleName()); } }

Target:
A positive test would be clearer here: if (isHSQL()) { return; }
Source:
public void stopping(Connection c) { m_isUp = false; if (!m_closing) { if (isPrimary()) { if (!m_hostMessenger.isShuttingDown()) { VoltDB.dropStackTrace("Received remote hangup from foreign host " + hostnameAndIPAndPort()); hostLog.warn("Received remote hangup from foreign host " + hostnameAndIPAndPort()); } m_hostMessenger.reportForeignHostFailed(m_hostId); } } }

Target:
Remove one wrap of IF by: if (!m_closing && isPrimary())
Source:
public String getHostnameForHostID(int hostId) { if (hostId == m_localHostId) { return CoreUtils.getHostnameOrAddress(); } Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator(); if (it.hasNext()) { ForeignHost fh = it.next(); return fh.hostname(); } else { return "UNKNOWN"; } }

Target:
@luyangco You can remove the ELSE and return "UNKNOWN".
Source:
public void testFiveNodeK1TwoRacks() throws JSONException { TestDescription td = getBoringDescription(5, 6, 1, 2, 1); subTestDescription(td, false); }

Target:
If leafCount is still 1, how could it be two rack groups?
Source:
private TablePopulationRequirements getMVInfoMessage(Table table, MaterializedViewInfo mv) { TablePopulationRequirements retval; if (! mv.getIssafewithnonemptysources()) { String viewName = mv.getTypeName(); String sourceName = mv.getParent().getTypeName(); String errorMessage = createViewDisallowedMessage(viewName, sourceName); retval = new TablePopulationRequirements(viewName); retval.setErrorMessage(errorMessage); if ( ! m_newTables.contains(sourceName)) { retval.addTableName(sourceName); } return retval; } return null; }

Target:
Merge declaration into block-scoped initialization statement (first use).
Source:
public synchronized void close() throws IOException { if (m_closed) { return; } m_readCursors.clear(); for (PBDSegment segment : m_segments.values()) { segment.close(); } m_segments.clear(); m_closed = true; }

Target:
Is this correct? It doesn't look right to forget about all segments on segment close, which just closes the FDs. What happens to the segment files on disk? Are they just leaked?
Source:
public void enqueue(final DeferredSerialization ds) { synchronized (this) { if (m_isShutdown) { ds.cancel(); return; } updateLastPendingWriteTimeAndQueueBackpressure(); if (m_isSSLConfigured) { Iterator<DeferredSerialization> dsIter = new SSLDeferredSerializationIterator(m_sslEngine, ds); while (dsIter.hasNext()) { m_queuedWrites.offer(dsIter.next()); } } else { m_queuedWrites.offer(ds); } m_port.setInterests( SelectionKey.OP_WRITE, 0); } }

Target:
shouldn't this be more implemented using [drainTo](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#drainTo%28java.util.Collection%29) strategy?
Source:
public MockPort() throws UnknownHostException { super(null, null, new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 21212), pool, null); }

Target:
These tests should have SSL. They dont depend on server.
Source:
private DeferredSerialization dsOf(final ByteBuffer buf) { return new DeferredSerialization() { @Override public ByteBuffer serialize(final ByteBuffer outbuf) throws IOException { outbuf.put(buf); return null; } @Override public void cancel() @Override public int getSerializedSize() { return buf.remaining(); } }; }

Target:
I thought for non ssl we return the same bytebuffer.
Source:
public SSLBufferDecrypter(SSLEngine sslEngine) { this.m_sslEngine = sslEngine; this.m_srcBuffer = ByteBuffer.allocateDirect(Constants.SSL_CHUNK_SIZE + 128); this.m_dstBuffer = ByteBuffer.allocateDirect(Constants.SSL_CHUNK_SIZE + 128); this.m_partialLength = ByteBuffer.allocate(4); }

Target:
where are the corresponding cleaners for these direct byte buffer allocations?
Source:
public final void convertToHeapBuffer() { if (m_buffer.isDirect()) { // Either this was allocated by the stored procedure as a direct buffer cached // from the EE. If the second, we need to make a copy so the EE can reuse the // buffer fir the next stored procedure. ByteBuffer heapBuffer = ByteBuffer.allocate(m_buffer.limit()); m_buffer.position(0); heapBuffer.put(m_buffer); heapBuffer.position(heapBuffer.limit()); } }

Target:
This is a nit, but should this be "can reuse the buffer FOR the next stored procedure"?
Source:
private boolean hasTrivialCoordinator(AbstractPlanNode planNode) { PlanNodeType planNodeType = planNode.getPlanNodeType(); if (PlanNodeType.RECEIVE == planNodeType || PlanNodeType.MERGERECEIVE == planNodeType) { return true; } else if (PlanNodeType.PROJECTION == planNodeType) { assert(planNode.getChildCount() == 1); return hasTrivialCoordinator(planNode.getChild(0)); } return false; }

Target:
no "else" required after return
Source:
private void updatePartitioning(VoltTable vt) { List<Integer> ketSet = new ArrayList<Integer>(); while (vt.advanceRow()) { //check for mock unit test if (vt.getColumnCount() == 2) { Integer key = (int)(vt.getLong("PARTITION_KEY")); ketSet.add(key); } } m_partitionKeys.set(ImmutableSet.copyOf(ketSet)); }

Target:
is ketSet a typo? keySet? Or am I missing what ket is?
Source:
public void clientCallback(ClientResponse clientResponse) throws Exception { if (clientResponse.getStatus() == ClientResponse.SUCCESS) { synchronized (Distributer.this) { VoltTable results[] = clientResponse.getResults(); if (results != null && results.length > 0) { updatePartitioning(results[0]); } } } m_partitionUpdateStatus.set(clientResponse); if (m_latch != null) { m_latch.countDown(); } }

Target:
Does this have to be synchronized? What isn't thread-safe?
Source:
default File resolve(File path) { return path.isAbsolute() ? path : new VoltFile(getVoltDBRoot(), path.getPath()); }

Target:
You dont have to use VoltFile as this is for new cli only right?
Source:
public String getServerSpecificRoot(String hostId) { if (!m_hostRoots.containsKey(hostId)) { throw new RuntimeException("getServerSpecificRoot possibly called before cluster has started."); } return m_hostRoots.get(hostId) + "/voltdbroot"; }

Target:
IllegalArgumentException
Source:
void doCommonSPICompleteActions() { // Mark the transaction state as DONE m_txnState.setDone(); // Set the truncation handle here instead of when processing the // messages in the SpScheduler to avoid any races of transaction // completing on the Site and receiving the messages in the Scheduler // for MPs. // // We have to use the spHandle from the first fragment, not from the // current message because it may be out of order if we do so. If we use // the spHandle from the current completion message, it may be advancing // the truncation handle before previous SPs are finished. if (m_txnDoneNotification != null) { m_txnDoneNotification.transactionDone(m_txnState.m_spHandle); } // Flush us out of the head of the TransactionTaskQueue. Null check so we're reusable // for live rejoin replay if (m_queue != null) { m_queue.flush(getTxnId()); } }

Target:
@nshi Does " m_txnState.setDone();" also means that the SPI receives the duplicate counter DONE? How does it make sure the SPI knows?
Source:
public void increaseBackpressure(int messageSize) { assert(m_expectedThreadId == Thread.currentThread().getId()); if (messageSize < 1) { throw new IllegalArgumentException("Message size must be > 0 but was " + messageSize); } m_pendingTxnBytes += messageSize; m_pendingTxnCount++; checkAndLogInvariants(); if (m_pendingTxnBytes > MAX_DESIRED_PENDING_BYTES || m_pendingTxnCount > MAX_DESIRED_PENDING_TXNS) { if (!m_hadBackPressure) { hostLog.info("TXN back pressure began"); m_hadBackPressure = true; for (ACGMember m : m_members) { m.onBackpressure(); } } } }

Target:
Unintended changes for debugging?
Source:
private void offerInternal(Mailbox mailbox, Item item, long handle) { if (item.getSpHandle() <= handle) { mailbox.send(item.getResponseHSId(), item.getMessage()); } else { m_bufferedReads.add(item); releaseBufferedReads(mailbox, handle); } }

Target:
Don't you want to call `releaseBufferedReads()` regardless of whether the current item can be released or not?
Source:
public boolean hasAllFinishedReading() throws IOException { if (m_closed) throw new IOException("Segment closed"); if (m_readCursors.size() == 0) return false; for (String cid : m_readCursors.keySet()) { SegmentReader reader = m_readCursors.get(cid); if (reader.m_objectReadIndex < m_numOfEntries) { return false; } } return true; }

Target:
Use `values()` instead of `keySet()` can save a map lookup for you.
Source:
private PBDSegment peekFirstSegment() { Map.Entry<Long, PBDSegment> entry = m_segments.firstEntry(); return (entry!=null) ? entry.getValue() : null; }

Target:
Those functions are confusing because they may return `null` but under our assumption pdb should always has at least one segment. Maybe `assert(entry != null)` is more readable.
Source:
public SegmentReader(String cursorId) { m_cursorId = cursorId; }

Target:
precondition checks for null and assert for tests please.
Source:
public boolean isClosed() { return m_closed == true; }

Target:
just return m_closed.
Source:
public synchronized void close() throws IOException { if (m_closed) { return; } m_closed = true; for (ReadCursor cursor : m_readCursors.values()) { cursor.close(); } m_readCursors.clear(); for (PBDSegment segment : m_segments.values()) { segment.close(); } m_cursorsWriter.close(); m_closed = true; }

Target:
Shouldnt you close all cursors before setting m_closed=true