auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void drawEventRectangle(Canvas canvas, int day) { mBoundaries.setRectangle(mFormat.getDaySpan(day), mFormat.getEventLines()); mEventSquarePaint.setStyle(getRectanglePaintStyle()); mEventSquarePaint.setColor(getRectangleColor()); <START> if(!mEvent.allDay){ <END> r.left+=EVENT_RECT_MARGIN_LEFT; r.right+=EVENT_RECT_MARGIN_LEFT; r.top+=EVENT_RECT_MARGIN_TOP; canvas.drawRoundRect(new RectF(r), EVENT_RECT_ROUNDING, EVENT_RECT_ROUNDING, mEventSquarePaint); }else{ r.left+=EVENT_RECT_MARGIN_LEFT; r.right-=EVENT_RECT_MARGIN_RIGHT; r.top+=EVENT_RECT_MARGIN_TOP; r.bottom-=EVENT_RECT_MARGIN_BOTTOM; canvas.drawRoundRect(new RectF(r), EVENT_RECT_ALLDAY_ROUNDING, EVENT_RECT_ALLDAY_ROUNDING, mEventSquarePaint); } }</code><technical_language>invert logic (remove !)</technical_language>

Target:
protected void drawEventRectangle(Canvas canvas, int day) { mBoundaries.setRectangle(mFormat.getDaySpan(day), mFormat.getEventLines()); mEventSquarePaint.setStyle(getRectanglePaintStyle()); mEventSquarePaint.setColor(getRectangleColor()); if(mEvent.allDay){ r.left += EVENT_RECT_MARGIN_LEFT; r.right -= EVENT_RECT_MARGIN_RIGHT; r.top += EVENT_RECT_MARGIN_TOP; r.bottom -= EVENT_RECT_MARGIN_BOTTOM; canvas.drawRoundRect(new RectF(r), EVENT_RECT_ALLDAY_ROUNDING, EVENT_RECT_ALLDAY_ROUNDING, mEventSquarePaint); } else { r.left += EVENT_RECT_MARGIN_LEFT; r.right += EVENT_RECT_MARGIN_RIGHT; r.top += EVENT_RECT_MARGIN_TOP; r.bottom += EVENT_RECT_MARGIN_BOTTOM; canvas.drawRoundRect(new RectF(r), EVENT_RECT_ROUNDING, EVENT_RECT_ROUNDING, mEventSquarePaint); } }
Source:
<code>protected boolean importDefinition() { <START> if (!getFromField().getText().isEmpty()) { <END> showWarningDialog(Constant.messages.getString("graphql.importfromdialog.message")); return false; } else Introspection.sendIntrospectionQuery(getEndpointUri()); return true; }</code><technical_language>require file, if user wants import URL other dialogue</technical_language>

Target:
protected boolean importDefinition() { showWarningDialog(Constant.messages.getString("graphql.importfromdialog.message")); return false; }
Source:
<code>public void testNegativeStartCoordinateInConstructor() throws IllegalArgumentException { exception.expect(IllegalArgumentException.class); <START> exception.expectMessage(CoreMatchers.equalTo("Variant start coordinate cannot be negative")); <END> new Variant("1", -1, 1, "C", "T"); }</code><technical_language>messages extracted in constants in AbstractVariant class call here. if message eventually changes tests changed</technical_language>

Target:
public void testNegativeStartCoordinateInConstructor() throws IllegalArgumentException { exception.expect(IllegalArgumentException.class); exception.expectMessage(CoreMatchers.equalTo(AbstractVariant.VARIANT_START_COORDINATE_CANNOT_BE_NEGATIVE)); new Variant("1", -1, 1, "C", "T"); }
Source:
<code>public void stoppedApplicationsAreNotStartedWhenDomainIsRedeployed() throws Exception { <START> DeploymentListener mockDeploymentListener = spy(new DeploymentStatusTracker()); <END> deploymentService.addDeploymentListener(mockDeploymentListener); addExplodedDomainFromBuilder(emptyDomain100FileBuilder, emptyDomain100FileBuilder.getId()); addExplodedAppFromBuilder(appDependingOnDomain100FileBuilder); startDeployment(); assertApplicationDeploymentSuccess(applicationDeploymentListener, appDependingOnDomain100FileBuilder.getId()); assertApplicationStatus(appDependingOnDomain100FileBuilder.getId(), STARTED); deploymentService.findApplication(appDependingOnDomain100FileBuilder.getId()).stop(); assertApplicationStatus(appDependingOnDomain100FileBuilder.getId(), STOPPED); deploymentService.redeployDomain(emptyDomain100FileBuilder.getId()); verify(mockDeploymentListener, times(1)).onRedeploymentSuccess(appDependingOnDomain100FileBuilder.getId()); assertApplicationStatus(appDependingOnDomain100FileBuilder.getId(), CREATED); deploymentService.redeployDomain(emptyDomain100FileBuilder.getId()); verify(mockDeploymentListener, times(2)).onRedeploymentSuccess(appDependingOnDomain100FileBuilder.getId()); assertApplicationStatus(appDependingOnDomain100FileBuilder.getId(), CREATED); }</code><technical_language>I tests duplicate code. refactored account this</technical_language>

Target:
public void stoppedApplicationsAreNotStartedWhenDomainIsRedeployed() throws Exception { DeploymentListener mockDeploymentListener = spy(new DeploymentStatusTracker()); deploymentService.addDeploymentListener(mockDeploymentListener); deployDomainAndApplication(emptyDomain100FileBuilder, appDependingOnDomain100FileBuilder); assertApplicationStatus(appDependingOnDomain100FileBuilder.getId(), STARTED); deploymentService.findApplication(appDependingOnDomain100FileBuilder.getId()).stop(); assertApplicationStatus(appDependingOnDomain100FileBuilder.getId(), STOPPED); deploymentService.redeployDomain(emptyDomain100FileBuilder.getId()); verify(mockDeploymentListener, times(1)).onRedeploymentSuccess(appDependingOnDomain100FileBuilder.getId()); assertApplicationStatus(appDependingOnDomain100FileBuilder.getId(), CREATED); deploymentService.redeployDomain(emptyDomain100FileBuilder.getId()); verify(mockDeploymentListener, times(2)).onRedeploymentSuccess(appDependingOnDomain100FileBuilder.getId()); assertApplicationStatus(appDependingOnDomain100FileBuilder.getId(), CREATED); }
Source:
<code>public Long read(ByteBuffer binary) throws IOException, ClassNotFoundException { long l = binary.getLong(); <START> LOG.info("deserialized {}", l); <END> return l; }</code><technical_language>need log here: return binary.getLong();</technical_language>

Target:
public Long read(ByteBuffer binary) throws IOException, ClassNotFoundException { return binary.getLong(); }
Source:
<code>synchronized public void decrementFileOpCount(String appUser) { if (!appUserToLocalUser.containsKey(appUser)) { String errMsg = "decrementFileOpCount: No local user allocation for appUser " + appUser; LOG.warn(errMsg); return; } LocalUserInfo localUserInfo = appUserToLocalUser.get(appUser); localUserInfo.fileOpCount--; LOG.info("Decremented fileOpCount for appUser " + appUser + " to " + localUserInfo.fileOpCount); <START> <END> checkAndDeallocateAppUser(appUser, localUserInfo); }</code><technical_language>whitespace:end of line</technical_language>

Target:
synchronized public void decrementFileOpCount(String appUser) { if (!appUserToLocalUser.containsKey(appUser)) { String errMsg = "decrementFileOpCount: No local user allocation for appUser " + appUser; LOG.error(errMsg); return; } LocalUserInfo localUserInfo = appUserToLocalUser.get(appUser); localUserInfo.fileOpCount--; LOG.info("Decremented fileOpCount for appUser " + appUser + " to " + localUserInfo.fileOpCount); checkAndDeallocateAppUser(appUser, localUserInfo); }
Source:
<code>protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); AppLog.i(T.MAIN, "main activity > new intent"); <START> if (FluxCUtils.isSignedInWPComOrHasWPOrgSite(mAccountStore, mSiteStore)) { if (intent.hasExtra(ARG_NOTIFICATION_TYPE)) { NotificationType notificationType = (NotificationType) intent.getSerializableExtra(ARG_NOTIFICATION_TYPE); if (notificationType != null) { mSystemNotificationsTracker.trackTappedNotification(notificationType); } } } <END> if (intent.hasExtra(NotificationsListFragment.NOTE_ID_EXTRA)) { launchWithNoteId(); } if (intent.hasExtra(ARG_OPEN_PAGE)) { handleOpenPageIntent(intent); } }</code><technical_language>this safe enough...TBH find path trigger this code ...happy learn in case want share, thanks</technical_language>

Target:
protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); AppLog.i(T.MAIN, "main activity > new intent"); if (intent.hasExtra(NotificationsListFragment.NOTE_ID_EXTRA)) { launchWithNoteId(); } if (intent.hasExtra(ARG_OPEN_PAGE)) { handleOpenPageIntent(intent); } }
Source:
<code>public String asString() throws IOException { <START> return new TextOf(this.bytes.value()).asString(); <END> }</code><technical_language>@fabriciofx above, new TextOf(InputStream) constructor</technical_language>

Target:
public String asString() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); this.print(baos); return new TextOf(baos.toByteArray()).asString(); }
Source:
<code><START> public <T> T serializeAndDeserialize(T obj) throws IOException, ClassNotFoundException { <END> ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream output = null; ObjectInputStream input = null; try { output = new ObjectOutputStream(bytes); output.writeObject(obj); input = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())); return (T) input.readObject(); } finally { if (output != null) { output.close(); } if (input != null) { input.close(); } } }</code><technical_language>This appears duplicated new code. Is consolidate</technical_language>

Target:
public <T> T serializeAndDeserialize(T obj) throws IOException, ClassNotFoundException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (ObjectOutputStream output = new ObjectOutputStream(bytes)) { output.writeObject(obj); } try (ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { return (T) input.readObject(); } }
Source:
<code>public static String u(String value) { if (value == null || value.isEmpty()) { return ""; } try { return UriUtils.encodeQueryParam(value, "UTF-8"); } catch (UnsupportedEncodingException ignored) { <START> logger.warn("UnsupportedEncodingException",ignored); <END> return value; } }</code><technical_language>[x] UnsupportedEncodingException <- Please write exception occurs</technical_language>

Target:
public static String u(String value) { if (value == null || value.isEmpty()) { return ""; } try { return UriUtils.encodeQueryParam(value, "UTF-8"); } catch (UnsupportedEncodingException ignored) { logger.warn("the given encoding parameter is not supported", ignored); return value; } }
Source:
<code>public void replaceNodeShouldNotRemoveIdenticalOldNode() throws Exception { Node oldNode = r.createSlave("foo", "", null); Node newNode = r.createSlave("foo", "", null); r.jenkins.addNode(oldNode); r.jenkins.getNodesObject().replaceNode(oldNode, newNode); r.jenkins.getNodesObject().load(); <START> assertNotNull(r.jenkins.getNode(oldNode.getNodeName())); <END> }</code><technical_language>suggestion assertNotNull(r.jenkins.getNode("foo"));</technical_language>

Target:
public void replaceNodeShouldNotRemoveIdenticalOldNode() throws Exception { Node oldNode = r.createSlave("foo", "", null); Node newNode = r.createSlave("foo", "", null); r.jenkins.addNode(oldNode); r.jenkins.getNodesObject().replaceNode(oldNode, newNode); r.jenkins.getNodesObject().load(); assertNotNull(r.jenkins.getNode("foo")); }
Source:
<code>public String getFullPath(Object element) { <START> return stripPath(new Path(((ZipEntry) element).getName()).toString()); <END> }</code><technical_language>callers this (confusing) stripPath(*) wrapped in a Path entry, simply reimplement stripPath Path</technical_language>

Target:
public String getFullPath(Object element) { IPath path = new Path(((ZipEntry) element).getName()); if (path.segmentCount() >= stripLevel) path = path.removeFirstSegments(stripLevel); return path.toString(); }
Source:
<code>private void refactorReferencesInOtherClasses(File[] files, String oldFieldType, String newFieldType) throws IOException { final String fieldTypeFQN = DO_PACKAGE + oldFieldType; for (File file : files) { if (isCandidateForRefactoring(oldFieldType, newFieldType, file)) { String fileContent = FileUtils.readFileToString(file, Charset.defaultCharset()); if (needsRefactoring(fieldTypeFQN, fileContent)) { fileContent = refactorFields(oldFieldType, newFieldType, fileContent); FileUtils.write(file, fileContent, Charset.defaultCharset()); } <START> } <END> } }</code><technical_language>mutate external references, we? If fileContent is final, force create a new local variable for mutation operations, making code easier understand</technical_language>

Target:
private void refactorReferencesInOtherClasses(File[] files, String oldFieldType, String newFieldType) throws IOException { final String fieldTypeFQN = DO_PACKAGE + oldFieldType; for (File file : files) { if (!isCandidateForRefactoring(oldFieldType, newFieldType, file)) { continue; } String fileContent = FileUtils.readFileToString(file, Charset.defaultCharset()); if (needsRefactoring(fieldTypeFQN, fileContent)) { fileContent = refactorFields(oldFieldType, newFieldType, fileContent); FileUtils.write(file, fileContent, Charset.defaultCharset()); } } }
Source:
<code>public static ObjectId computeChangeId(final ObjectId firstParentId, final ObjectId treeId, final PersonIdent author, final PersonIdent committer, final String message) throws IOException { StringBuilder b = new StringBuilder(); b.append("tree "); b.append(ObjectId.toString(treeId)); b.append("\n"); if (firstParentId != null) { b.append("parent "); b.append(ObjectId.toString(firstParentId)); b.append("\n"); } b.append("author "); b.append(author.toExternalString()); b.append("\n"); b.append("committer "); b.append(committer.toExternalString()); b.append("\n\n"); b.append(clean(message)); <START> File f = File.createTempFile("test", ".git"); <END> f.delete(); f.deleteOnExit(); ObjectWriter w = new ObjectWriter(null); ByteArrayInputStream is = new ByteArrayInputStream(b.toString() .getBytes(Constants.CHARSET)); ObjectId sha1 = w.computeObjectSha1(Constants.OBJ_COMMIT, b.length(), is); return sha1; }</code><technical_language>This temporary file is necessary</technical_language>

Target:
public static ObjectId computeChangeId(final ObjectId firstParentId, final ObjectId treeId, final PersonIdent author, final PersonIdent committer, final String message) throws IOException { StringBuilder b = new StringBuilder(); b.append("tree "); b.append(ObjectId.toString(treeId)); b.append("\n"); if (firstParentId != null) { b.append("parent "); b.append(ObjectId.toString(firstParentId)); b.append("\n"); } b.append("author "); b.append(author.toExternalString()); b.append("\n"); b.append("committer "); b.append(committer.toExternalString()); b.append("\n\n"); b.append(clean(message)); ObjectWriter w = new ObjectWriter(null); byte[] bytes = b.toString().getBytes(Constants.CHARACTER_ENCODING); ByteArrayInputStream is = new ByteArrayInputStream(bytes); ObjectId sha1 = w.computeObjectSha1(Constants.OBJ_COMMIT, bytes.length, is); return sha1; }
Source:
<code>public static void clearTestFolder() { try { if (Files.exists(Paths.get(RepoStore.TEST_DIRECTORY))) { Files.walk(Paths.get(RepoStore.TEST_DIRECTORY), 1) .filter(Files::isRegularFile) .filter(p -> getFileExtension(String.valueOf(p.getFileName())).equalsIgnoreCase("json") || getFileExtension(String.valueOf(p.getFileName())).equalsIgnoreCase("json-err") ) .forEach(p -> new File(p.toAbsolutePath().toString()).delete()); <START> } <END> } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>a guard clause reduce nesting</technical_language>

Target:
public static void clearTestFolder() { Path testDirectory = Paths.get(RepoStore.TEST_DIRECTORY); try { if (!Files.exists(testDirectory)) { throw new FileNotFoundException(testDirectory.toString()); } Files.walk(Paths.get(RepoStore.TEST_DIRECTORY), 1) .filter(Files::isRegularFile) .filter(p -> getFileExtension(String.valueOf(p.getFileName())).equalsIgnoreCase("json") || getFileExtension(String.valueOf(p.getFileName())).equalsIgnoreCase("json-err") ) .forEach(p -> new File(p.toAbsolutePath().toString()).delete()); } catch (IOException e) { e.printStackTrace(); } }
Source:
<code><START> public boolean equals(Object obj) { <END> if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AbstractPermission other = (AbstractPermission) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } return true; }</code><technical_language>hashcode override</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AbstractPermission other = (AbstractPermission) obj; if (context == null) { if (other.context != null) { return false; } } else if (!context.equals(other.context)) { return false; } if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } return true; }
Source:
<code>public void onNeutral(String callerTag) { ComponentsGetter cg = (ComponentsGetter)getSherlockActivity(); cg.getFileOperationsHelper() .removeFile(mTargetFile, true); FileDataStorageManager storageManager = cg.getStorageManager(); boolean containsKeepInSync = false; if (mTargetFile.isFolder()) { Vector<OCFile> files = storageManager.getFolderContent(mTargetFile); for(OCFile file: files) { containsKeepInSync = file.keepInSync() || containsKeepInSync; if (containsKeepInSync) break; } } if (mTargetFile.keepInSync() || containsKeepInSync) { OCFile folder = null; if (mTargetFile.isFolder()) { folder = mTargetFile; } else { folder = storageManager.getFileById(mTargetFile.getParentId()); } folder.setEtag(""); storageManager.saveFile(folder); <START> Log_OC.d("RemoveFileDialogFragment", "Parent etag= |" + folder.getEtag() + "|"); <END> } }</code><technical_language>Remove this log also, please</technical_language>

Target:
public void onNeutral(String callerTag) { ComponentsGetter cg = (ComponentsGetter)getSherlockActivity(); cg.getFileOperationsHelper() .removeFile(mTargetFile, true); FileDataStorageManager storageManager = cg.getStorageManager(); boolean containsKeepInSync = false; if (mTargetFile.isFolder()) { Vector<OCFile> files = storageManager.getFolderContent(mTargetFile); for(OCFile file: files) { containsKeepInSync = file.keepInSync() || containsKeepInSync; if (containsKeepInSync) break; } } if (mTargetFile.keepInSync() || containsKeepInSync) { OCFile folder = null; if (mTargetFile.isFolder()) { folder = mTargetFile; } else { folder = storageManager.getFileById(mTargetFile.getParentId()); } folder.setEtag(""); storageManager.saveFile(folder); } }
Source:
<code>private ExprAnalysis analyzeExprs(List<Expr> exprs, Expr.ObjectBinding bindings) { Set<ExprType> presentTypes = EnumSet.noneOf(ExprType.class); List<ExprEval<?>> exprEvals = new ArrayList<>(); for (Expr expr : exprs) { ExprEval<?> exprEval = expr.eval(bindings); ExprType exprType = exprEval.type(); if (isValidType(exprType)) { presentTypes.add(exprType); } <START> if (exprEval.asString() == null) { <END> return null; } exprEvals.add(exprEval); } ExprType comparisonType = getComparisionType(presentTypes); return new ExprAnalysis(comparisonType, exprEvals); }</code><technical_language>I exprEval.value() == null is equivalent avoid computing stringValue in some cases</technical_language>

Target:
private ExprAnalysis analyzeExprs(List<Expr> exprs, Expr.ObjectBinding bindings) { Set<ExprType> presentTypes = EnumSet.noneOf(ExprType.class); List<ExprEval<?>> exprEvals = new ArrayList<>(); for (Expr expr : exprs) { ExprEval<?> exprEval = expr.eval(bindings); ExprType exprType = exprEval.type(); if (isValidType(exprType)) { presentTypes.add(exprType); } if (exprEval.value() != null) { exprEvals.add(exprEval); } } ExprType comparisonType = getComparisionType(presentTypes); return new ExprAnalysis(comparisonType, exprEvals); }
Source:
<code>@Override public void lock() { <START> if (hasLocked.get()) <END> return; threadCount.incrementAndGet(); lock.lock(); if (!onGlobalLock) { globalSync.acquire(); onGlobalLock = true; nextFinish = MAX_TIME + System.nanoTime(); } hasLocked.set(true); }</code><technical_language>u support reentrancy for local threads</technical_language>

Target:
@Override public void lock() { if (reentrantCnt.get() > 0) { reentrantCnt.increment(); return; } threadCnt.incrementAndGet(); lock.lock(); if (closed) { reentrantCnt.decrement(); lock.unlock(); throw new IllegalStateException("Can't acquire a lock after a close operation."); } if (!isGloballyLocked) { globalSync.acquire(); isGloballyLocked = true; nextFinish = MAX_TIME + System.nanoTime(); } reentrantCnt.increment(); }
Source:
<code>private void validateDirsAndRegex() { <START> if (topicDirGroupsMaxIndex > 0 && topixRegexCaptureGroup == null) { <END> throw new ConfigException( TOPICS_DIR_CONFIG + " cannot contain ${} without a valid " + TOPIC_REGEX_CAPTURE_GROUP_CONFIG + " being configured." ); } if (logDirGroupsMaxIndex > 0 && topixRegexCaptureGroup == null) { throw new ConfigException( LOGS_DIR_CONFIG + " cannot contain ${} without a valid " + TOPIC_REGEX_CAPTURE_GROUP_CONFIG + " being configured." ); } validateReplacements(TOPICS_DIR_CONFIG); validateReplacements(LOGS_DIR_CONFIG); }</code><technical_language>this check correctly catch if specifies ${0} in topic dir, higher index? maximums null if substitutions specified, differentiate substitutions a ${0} substitution</technical_language>

Target:
private void validateDirsAndRegex() { if (topicDirGroupsMaxIndex >= 0 && topicRegexCaptureGroup == null) { throw new ConfigException( TOPICS_DIR_CONFIG + " cannot contain ${} without a valid " + TOPIC_CAPTURE_GROUPS_REGEX_CONFIG + " being configured." ); } if (logDirGroupsMaxIndex >= 0 && topicRegexCaptureGroup == null) { throw new ConfigException( LOGS_DIR_CONFIG + " cannot contain ${} without a valid " + TOPIC_CAPTURE_GROUPS_REGEX_CONFIG + " being configured." ); } validateReplacements(TOPICS_DIR_CONFIG); validateReplacements(LOGS_DIR_CONFIG); }
Source:
<code>public TaskExecution createTaskExecution() { initialize(); TaskExecution taskExecution = <START> taskExecutionDao.createTaskExecution(null, null, new ArrayList<String>(0), null); <END> logger.debug("Creating: " + taskExecution.toString()); return taskExecution; }</code><technical_language>Collections.emptyList</technical_language>

Target:
public TaskExecution createTaskExecution() { initialize(); TaskExecution taskExecution = taskExecutionDao.createTaskExecution(null, null, Collections.<String>emptyList(), null); logger.debug("Creating: " + taskExecution.toString()); return taskExecution; }
Source:
<code><START> protected boolean doBind(CommandMetaData meta) { if (CommandMetaData.Mode.MASTER_OR_SLAVE == meta.runsAt()) { return true; } boolean runswithMasterOnly = meta.runsAt() == CommandMetaData.Mode.MASTER ? true : false; if (slaveMode ^ runswithMasterOnly) { return false; } return true; } <END></code><technical_language>Move this logic CommandMetaData.Mode enum, e. g. public isSupported(boolean slaveMode) { [...] }</technical_language>

Target:
protected boolean doBind(CommandMetaData meta) { if (CommandMetaData.Mode.MASTER_OR_SLAVE == meta.runsAt()) { return true; } boolean runsWithMasterOnly = meta.runsAt() == CommandMetaData.Mode.MASTER ? true : false; if (slaveMode ^ runsWithMasterOnly) { return true; } return false; }
Source:
<code>private int integerLiteral() { int i = 0; char c = fValue[i++]; if (c == '0' && i < fValue.length) { c = fValue[i]; switch ((c | 0x20)) { case 'x': return probablyHex(i); case 'b': return probablyBinary(i); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': while (isOctal(c) && i < fValue.length) { c = fValue[++i]; } break; case '.': return afterDecimalPoint(i); } if (c == '8' || c == '9') { c = fValue[i]; while (Character.isDigit(c) && i < fValue.length) { c = fValue[++i]; } return i; } if (c == '.') { return afterDecimalPoint(i); <START> } <END> } else if (Character.isDigit(c)) { c = fValue[i]; while (Character.isDigit(c) && i < fValue.length) { c = fValue[++i]; } if (c == '.') { return afterDecimalPoint(i); } else if ((c | 0x20) == 'e') { return exponentPart(i); } } else { assert false; } return i; }</code><technical_language>I of is if handle "09.1" (without testing it, I previous if statement flag a malformed octal sequence.)</technical_language>

Target:
private int integerLiteral() { int i = 0; char c = fValue[i++]; if (c == '0' && i < fValue.length) { c = fValue[i]; switch ((c | 0x20)) { case 'x': return probablyHex(i); case 'b': return probablyBinary(i); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': while (isOctal(c) && i < fValue.length) { c = fValue[++i]; } break; case '.': return afterDecimalPoint(i); } if (c == '8' || c == '9') { c = fValue[i]; while (Character.isDigit(c) && i < fValue.length) { c = fValue[++i]; } } return handleDecimalOrExponent(c, i); } else if (Character.isDigit(c)) { c = fValue[i]; while (Character.isDigit(c) && i < fValue.length) { c = fValue[++i]; } return handleDecimalOrExponent(c, i); } else { assert false; } return i; }
Source:
<code>private ObjectId storeCommentsInNotes() throws OrmException, IOException { ChangeNotes notes = ctl.getNotes(); <START> notes.load(); <END> NoteMap noteMap = notes.getNoteMap(); if (noteMap == null) { noteMap = NoteMap.newEmptyMap(); } if (commentsForPs.isEmpty() && commentsForBase.isEmpty()) { return null; } Multimap<PatchSet.Id, PatchLineComment> allCommentsOnBases = notes.getBaseComments(); Multimap<PatchSet.Id, PatchLineComment> allCommentsOnPs = notes.getPatchSetComments(); if (!commentsForBase.isEmpty()) { List<PatchLineComment> baseCommentsForThisPs = new ArrayList<>(allCommentsOnBases.get(psId)); baseCommentsForThisPs.addAll(commentsForBase); commentsUtil.writeCommentsToNoteMap(noteMap, baseCommentsForThisPs, inserter); } if (!commentsForPs.isEmpty()) { List<PatchLineComment> commentsForThisPs = new ArrayList<>(allCommentsOnPs.get(psId)); commentsForThisPs.addAll(commentsForPs); commentsUtil.writeCommentsToNoteMap(noteMap, commentsForThisPs, inserter); } return noteMap.writeTree(inserter); }</code><technical_language>add .load() previous line</technical_language>

Target:
private ObjectId storeCommentsInNotes() throws OrmException, IOException { ChangeNotes notes = ctl.getNotes().load(); NoteMap noteMap = notes.getNoteMap(); if (noteMap == null) { noteMap = NoteMap.newEmptyMap(); } if (commentsForPs.isEmpty() && commentsForBase.isEmpty()) { return null; } Multimap<PatchSet.Id, PatchLineComment> allCommentsOnBases = notes.getBaseComments(); Multimap<PatchSet.Id, PatchLineComment> allCommentsOnPs = notes.getPatchSetComments(); if (!commentsForBase.isEmpty()) { List<PatchLineComment> baseCommentsForThisPs = new ArrayList<>(allCommentsOnBases.get(psId)); baseCommentsForThisPs.addAll(commentsForBase); commentsUtil.writeCommentsToNoteMap(noteMap, baseCommentsForThisPs, inserter); } if (!commentsForPs.isEmpty()) { List<PatchLineComment> commentsForThisPs = new ArrayList<>(allCommentsOnPs.get(psId)); commentsForThisPs.addAll(commentsForPs); commentsUtil.writeCommentsToNoteMap(noteMap, commentsForThisPs, inserter); } return noteMap.writeTree(inserter); }
Source:
<code>public NetRC(File netrc) { <START> this.netrc = netrc; <END> }</code><technical_language>call parse()</technical_language>

Target:
public NetRC(File netrc) { this.netrc = netrc; parse(); }
Source:
<code>public void testCall() { String change_id = null; String commit_id = null; try { GitAccess gAccess = new GitAccess(); Git git = gAccess.getGitProject(); gAccess.addFile("EGerritTestReviewFile.java", "Hello reviewers community !\n This is the second line \n"); gAccess.pushFile(); change_id = gAccess.getChangeId(); commit_id = gAccess.getCommitId(); } catch (Exception e1) { e1.printStackTrace(); } CreateDraftCommand command = fGerrit.createDraftComments(change_id, commit_id); CommentInfo commentInfo = new CommentInfo(); commentInfo.setLine(2); commentInfo.setMessage("This is a test comment"); commentInfo.setPath("EGerritTestReviewFile.java"); command.setCommentInfo(commentInfo); <START> command.requiresAuthentication(true); <END> CommentInfo result = null; try { result = command.call(); } catch (EGerritException e) { fail(e.getMessage()); } SetReviewCommand command2 = fGerrit.setReview(change_id, commit_id); ReviewInput reviewInput = new ReviewInput(); reviewInput.setMessage("This review is NOW ready to go ..."); Map obj = new HashMap(); obj.put("Code-Review", "+2"); reviewInput.setLabels(obj); command2.setReviewInput(reviewInput); command2.requiresAuthentication(true); ReviewInfo result2 = null; try { result2 = command2.call(); } catch (EGerritException e) { fail(e.getMessage()); } PublishDraftRevisionCommand command3 = fGerrit.publishDraftRevision(change_id, commit_id); command3.requiresAuthentication(true); String result3 = null; try { result3 = command3.call(); } catch (EGerritException e) { fail(e.getMessage()); } System.out.println(result3); assertTrue(true); }</code><technical_language>do set true for requiresAuthentication is set create class</technical_language>

Target:
public void testCall() { String change_id = null; String commit_id = null; try { GitAccess gAccess = new GitAccess(); Git git = gAccess.getGitProject(); gAccess.addFile("EGerritTestReviewFile.java", "Hello reviewers community !\n This is the second line \n"); gAccess.pushFile(); change_id = gAccess.getChangeId(); commit_id = gAccess.getCommitId(); } catch (Exception e1) { fail(e1.getMessage()); } CreateDraftCommand command = fGerrit.createDraftComments(change_id, commit_id); CommentInfo commentInfo = new CommentInfo(); commentInfo.setLine(2); commentInfo.setMessage("This is a test comment"); commentInfo.setPath("EGerritTestReviewFile.java"); command.setCommentInfo(commentInfo); CommentInfo result = null; try { result = command.call(); } catch (EGerritException e) { fail(e.getMessage()); } SetReviewCommand command2 = fGerrit.setReview(change_id, commit_id); ReviewInput reviewInput = new ReviewInput(); reviewInput.setMessage("This review is NOW ready to go ..."); Map obj = new HashMap(); obj.put("Code-Review", "+2"); reviewInput.setLabels(obj); command2.setReviewInput(reviewInput); ReviewInfo result2 = null; try { result2 = command2.call(); } catch (EGerritException e) { fail(e.getMessage()); } PublishDraftRevisionCommand command3 = fGerrit.publishDraftRevision(change_id, commit_id); String result3 = null; try { result3 = command3.call(); } catch (EGerritException e) { fail(e.getMessage()); } System.out.println(result3); assertTrue(true); }
Source:
<code>public void editingLocalCss_008_MonobookUserWithAdminRightsOpensSpecialCss() { <START> WikiBasePageObject wiki = new WikiBasePageObject(driver, Global.DOMAIN); <END> wiki.openWikiPage(); CommonFunctions.logInMonobook(Properties.userNameMonobook, Properties.passwordMonobook, driver); WikiArticleUserMonoBookPageObject monobookArticle = new WikiArticleUserMonoBookPageObject(driver); monobookArticle.openArticle(this.specialCSS); monobookArticle.verifyOasisOnly(); }</code><technical_language>I initialize SpecialUserLoginMonobookPageObject in instead of wikiBasePageObject run login methond initialized object</technical_language>

Target:
public void editingLocalCss_008_MonobookUserWithAdminRightsOpensSpecialCss() { SpecialUserLoginMonobookPageObject loginMonobook = new SpecialUserLoginMonobookPageObject(driver); loginMonobook.open(); loginMonobook.fillLoginForm(Properties.userNameMonobook, Properties.passwordMonobook, ""); loginMonobook.submitForm(); loginMonobook.verifyLogin(); WikiArticleMonoBookPageObject monobookArticle = new WikiArticleMonoBookPageObject(driver); monobookArticle.openArticle(URLsContent.specialCSS); monobookArticle.verifyOasisOnly(); }
Source:
<code>public void deleteByQProfileAndUser(DbSession dbSession, QProfileDto profile, UserDto user) { <START> mapper(dbSession).delete(profile.getKee(), user.getLogin()); <END> }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove this of "now"; is deprecated. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public void deleteByQProfileAndUser(DbSession dbSession, QProfileDto profile, UserDto user) { mapper(dbSession).delete(profile.getKee(), user.getId()); }
Source:
<code>private PositionInfo findMovePositionInfo(MUIElement element) { if (element != null) { for (String tag : element.getTags()) { if (tag.startsWith(MOVE_TAG)) { <START> return PositionInfo.parse(tag.substring(5)); <END> } } } return null; }</code><technical_language>substring(#) calculated MOVE_TAG</technical_language>

Target:
private PositionInfo findMovePositionInfo(MUIElement element) { if (element != null) { for (String tag : element.getTags()) { if (tag.startsWith(MOVE_TAG)) { return PositionInfo.parse(tag.substring(MOVE_TAG.length())); } } } return null; }
Source:
<code>private void validateRequest() { if (this.dataClass != null && this.dataClass == HtsgetClass.header && ( this.interval != null || !this.fields.isEmpty() || !this.tags.isEmpty() || !this.notags.isEmpty())) { throw new IllegalArgumentException("Invalid request: no query parameters except `format` may be specified when class=header"); } if (this.format != null) { final String path = this.endpoint.getPath(); <START> if ((path.endsWith(FileExtensions.BAM) || path.endsWith(FileExtensions.SAM) && ( <END> this.format != HtsgetFormat.BAM && this.format != HtsgetFormat.CRAM)) || FileExtensions.VCF_LIST.stream().anyMatch(path::endsWith) && ( this.format != HtsgetFormat.VCF && this.format != HtsgetFormat.BCF)) { throw new IllegalArgumentException("Specified format: " + this.format + " is incompatible with id's file extension"); } } final String intersections = this.tags.stream() .filter(getNoTags()::contains) .collect(Collectors.joining(", ")); if (!intersections.isEmpty()) { throw new IllegalArgumentException("Invalid request: tags and notags overlap in the following fields: " + intersections); } }</code><technical_language>this include CRAM too</technical_language>

Target:
private void validateRequest() { if (this.dataClass != null && this.dataClass == HtsgetClass.header && ( this.interval != null || !this.fields.isEmpty() || !this.tags.isEmpty() || !this.notags.isEmpty())) { throw new IllegalArgumentException("Invalid request: no query parameters except `format` may be specified when class=header"); } if (this.format != null) { final String path = this.endpoint.getPath(); if ((path.endsWith(FileExtensions.BAM) || path.endsWith(FileExtensions.CRAM)) && ( this.format != HtsgetFormat.BAM && this.format != HtsgetFormat.CRAM)) { throw new IllegalArgumentException("Specified reads format: " + this.format + " is incompatible with id's file extension " + path); } if (FileExtensions.VCF_LIST.stream().anyMatch(path::endsWith) && ( this.format != HtsgetFormat.VCF && this.format != HtsgetFormat.BCF)) { throw new IllegalArgumentException("Specified variant format: " + this.format + " is incompatible with id's file extension " + path); } } final String intersections = this.tags.stream() .filter(getNoTags()::contains) .collect(Collectors.joining(", ")); if (!intersections.isEmpty()) { throw new IllegalArgumentException("Invalid request: tags and notags overlap in the following fields: " + intersections); } }
Source:
<code>public AppEngineCredentials(Collection<String> scopes, AppIdentityService appIdentityService) { <START> this.scopes = scopes; <END> this.appIdentityService = appIdentityService != null ? appIdentityService : AppIdentityServiceFactory.getAppIdentityService(); scopesRequired = (scopes == null || scopes.isEmpty()); }</code><technical_language>Do need a defensive copy</technical_language>

Target:
public AppEngineCredentials(Collection<String> scopes, AppIdentityService appIdentityService) { this.scopes = ImmutableList.copyOf(scopes); this.appIdentityService = appIdentityService != null ? appIdentityService : AppIdentityServiceFactory.getAppIdentityService(); scopesRequired = (scopes == null || scopes.isEmpty()); }
Source:
<code>public static <T> T bytes2obj(Marshaller marshaller, byte[] bytes) { if (bytes == null) return null; try { Object ret = marshaller.objectFromByteBuffer(bytes); if (ret instanceof byte[]) { <START> try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream((byte[]) ret))) { <END> return (T) ois.readObject(); } catch (Exception ee) { if (log.isDebugEnabled()) log.debugf("Standard deserialization not in use for %s", Util.printArray(bytes)); } } return (T) ret; } catch (Exception e) { throw log.unableToUnmarshallBytes(Util.toHexString(bytes), e); } }</code><technical_language>a quick check for "magic" beginning attempting read OIS</technical_language>

Target:
public static <T> T bytes2obj(Marshaller marshaller, byte[] bytes) { if (bytes == null) return null; try { Object ret = marshaller.objectFromByteBuffer(bytes); if (ret instanceof byte[] && isJavaSerialized((byte[]) ret)) { try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream((byte[]) ret))) { return (T) ois.readObject(); } catch (Exception ee) { if (log.isDebugEnabled()) log.debugf("Standard deserialization not in use for %s", Util.printArray(bytes)); } } return (T) ret; } catch (Exception e) { throw log.unableToUnmarshallBytes(Util.toHexString(bytes), e); } }
Source:
<code>public void removeAll(Collection<IClass> toRemove) { <START> toRemove.stream().map(IClass::getName) <END> .peek(loadedClasses::remove) .forEach(sourceMap::remove); }</code><technical_language>Retain null check argument</technical_language>

Target:
public void removeAll(Collection<IClass> toRemove) { if (toRemove == null) { throw new IllegalArgumentException("toRemove is null"); } toRemove.stream().map(IClass::getName) .peek(loadedClasses::remove) .forEach(sourceMap::remove); }
Source:
<code>private String getSaveAsADraftButtonText() { if (!userCanPublishPosts()) { return getString(R.string.submit_for_review); } <START> switch (PostStatus.fromPost(mPost)) { <END> case DRAFT: return getString(R.string.menu_publish_now); case PUBLISHED: case UNKNOWN: default: if (!isNewPost()) { return getString(R.string.menu_publish_now); } else { return getString(R.string.menu_save_as_draft); } } }</code><technical_language>This a more of a personal preference - feel free ignore it. I prefer include cases in switch statements. If adds a new enum value, explicitly decide do in switch. If post in state Draft, Published, Unknown consider throwing exception for other cases follow Fail ASAP principle</technical_language>

Target:
private String getSaveAsADraftButtonText() { if (!userCanPublishPosts()) { return getString(R.string.submit_for_review); } switch (PostStatus.fromPost(mPost)) { case DRAFT: return getString(R.string.menu_publish_now); case PUBLISHED: case UNKNOWN: if (mPost.isLocalDraft()) { return getString(R.string.menu_publish_now); } else { return getString(R.string.update_verb); } case PRIVATE: case PENDING: case TRASHED: case SCHEDULED: default: if (!isNewPost()) { return getString(R.string.menu_publish_now); } else { return getString(R.string.menu_save_as_draft); } } }
Source:
<code>public void setCreatedAt(final Timestamp value) { <START> this._createdAt = value; <END> }</code><technical_language>"this." necessary; please apply all</technical_language>

Target:
public void setCreatedAt(final Timestamp value) { _createdAt = value; }
Source:
<code>public void inventoryMode() throws Exception { testOrderAspect(builder -> { builder.inventoryMode(null); }, order -> assertThat(order.getInventoryMode()).isEqualTo(InventoryMode.NONE)); testOrderAspect(builder -> { builder.inventoryMode(InventoryMode.NONE); }, <START> order -> assertThat(order.getInventoryMode()).isEqualTo(InventoryMode.NONE)); <END> }</code><technical_language>This true if forgot send inventory mode builder. e.g InventoryMode.RESERVE_ON_ORDER a assertion ;)</technical_language>

Target:
public void inventoryMode() throws Exception { testOrderAspect(builder -> { builder.inventoryMode(null); }, order -> assertThat(order.getInventoryMode()).isEqualTo(InventoryMode.NONE)); withProductOfStock(client(), 5, product -> { final int variantId = 1; final String sku = product.getMasterData().getStaged().getMasterVariant().getSku(); final String productId = product.getId(); final LocalizedString name = en("a name"); final long quantity = 1; final Price price = Price.of(EURO_10); final OrderState orderState = OrderState.COMPLETE; final MonetaryAmount amount = EURO_10; final ProductVariantImportDraft variant = ProductVariantImportDraftBuilder.of(productId, variantId, sku).build(); final LineItemImportDraft lineItemImportDraft = LineItemImportDraftBuilder.of(variant, quantity, price, name).build(); final OrderImportDraft orderImportDraft = OrderImportDraftBuilder.ofLineItems(amount, orderState, asList(lineItemImportDraft)) .inventoryMode(InventoryMode.TRACK_ONLY).build(); final OrderImportCommand cmd = OrderImportCommand.of(orderImportDraft); final Order order = client().executeBlocking(cmd); assertThat(order.getInventoryMode()).isEqualTo(InventoryMode.TRACK_ONLY); client().executeBlocking(OrderDeleteCommand.of(order)); }); }
Source:
<code>public void testCurrencySelection() { ArrayList<String> currenciestoUpdate = new ArrayList<String>(); currenciestoUpdate.add("KES"); currenciestoUpdate.add("BND"); currenciestoUpdate.add("LBP"); currenciestoUpdate.add("GHC"); currenciestoUpdate.add("USD"); ArrayList currenciesOutput = CurrenciesHelper.updateSelectedCurrencies(this.requestSpec, this.responseSpec, currenciestoUpdate); Assert.assertNotNull(currenciesOutput); Assert.assertEquals("Verifying Do Outputed Currencies Match after Updation", currenciestoUpdate, currenciesOutput); ArrayList<CurrencyDomain> currenciesBeforeUpdate = new ArrayList<CurrencyDomain>(); <START> for (String e : currenciestoUpdate) <END> currenciesBeforeUpdate.add(CurrenciesHelper.getCurrencybyCode(requestSpec, responseSpec, e)); Collections.sort(currenciesBeforeUpdate); ArrayList<CurrencyDomain> currenciesAfterUpdate = CurrenciesHelper.getSelectedCurrencies(requestSpec, responseSpec); Assert.assertNotNull(currenciesAfterUpdate); Assert.assertEquals("Verifying Do Selected Currencies Match after Updation", currenciesBeforeUpdate, currenciesAfterUpdate); }</code><technical_language>Please braces</technical_language>

Target:
public void testCurrencySelection() { ArrayList<String> currenciestoUpdate = new ArrayList<String>(); currenciestoUpdate.add("KES"); currenciestoUpdate.add("BND"); currenciestoUpdate.add("LBP"); currenciestoUpdate.add("GHC"); currenciestoUpdate.add("USD"); ArrayList<String> currenciesOutput = CurrenciesHelper.updateSelectedCurrencies(this.requestSpec, this.responseSpec, currenciestoUpdate); Assert.assertNotNull(currenciesOutput); Assert.assertEquals("Verifying Do Outputed Currencies Match after Updation", currenciestoUpdate, currenciesOutput); ArrayList<CurrencyDomain> currenciesBeforeUpdate = new ArrayList<CurrencyDomain>(); for (String e : currenciestoUpdate) { currenciesBeforeUpdate.add(CurrenciesHelper.getCurrencybyCode(requestSpec, responseSpec, e)); } Collections.sort(currenciesBeforeUpdate); ArrayList<CurrencyDomain> currenciesAfterUpdate = CurrenciesHelper.getSelectedCurrencies(requestSpec, responseSpec); Assert.assertNotNull(currenciesAfterUpdate); Assert.assertEquals("Verifying Do Selected Currencies Match after Updation", currenciesBeforeUpdate, currenciesAfterUpdate); }
Source:
<code>final void afterDeserialization(Boolean readOnlyBeforeAttachedToSession, String sessionFactoryUuid, boolean allowLoadOutsideTransaction) { if ( isReadOnlySettingAvailable() ) { throw new IllegalStateException( "Cannot call afterDeserialization when isReadOnlySettingAvailable == true [" + entityName + "#" + id + "]" ); } this.readOnlyBeforeAttachedToSession = readOnlyBeforeAttachedToSession; this.allowLoadOutsideTransaction = allowLoadOutsideTransaction; <START> if ( allowLoadOutsideTransaction ) { <END> this.sessionFactoryUuid = sessionFactoryUuid; } }</code><technical_language>worth a test here. I set uuid (it null)</technical_language>

Target:
final void afterDeserialization(Boolean readOnlyBeforeAttachedToSession, String sessionFactoryUuid, boolean allowLoadOutsideTransaction) { if ( isReadOnlySettingAvailable() ) { throw new IllegalStateException( "Cannot call afterDeserialization when isReadOnlySettingAvailable == true [" + entityName + "#" + id + "]" ); } this.readOnlyBeforeAttachedToSession = readOnlyBeforeAttachedToSession; this.sessionFactoryUuid = sessionFactoryUuid; this.allowLoadOutsideTransaction = allowLoadOutsideTransaction; }
Source:
<code>boolean StopDetector(float distance_d, int stop_type, float speed) { float lastToSecDistance = lastCoords.distanceTo(secondToLastCoords); Log.d(TAG, "Detecting stop. distance_d=" + distance_d + ". stop_type=" + stop_type + " speed=" + speed); if (stop_type == 1) { if ((distance_d > 50) && (distance_d < 100) && (distance_d != -1) && !m100_a) { m100_a = true; Log.d(TAG, "Case 1: false"); return false; } if ((distance_d > 20) && (distance_d < 50) && (distance_d != -1) && !m50_a) { m50_a = true; Log.d(TAG, "Case 2: false"); return false; } if ((distance_d < 20) && (distance_d != -1) && !m20_a) { m20_a = true; <START> if ((speed > 15) && (lastToSecDistance < 100)) { <END> Log.d(TAG, "Case 3: true"); return true; } Log.d(TAG, "Case 3: false"); return false; } if ((distance_d < 20) && (distance_d != -1) && m20_a && !m20_d) { m20_d = true; if (speed < 10) { Log.d(TAG, "Case 4: false"); return false; } else if (speed > 15) { Log.d(TAG, "Case 4: true"); return true; } } if ((distance_d > 20) && (distance_d < 50) && (distance_d != -1) && !m50_d && (m20_d || m20_a)) { m50_d = true; Log.d(TAG, "Case 5: true"); return true; } } return false; }</code><technical_language>remove extra ( here: if (speed > 15 && lastToSecDistance < 100) {</technical_language>

Target:
boolean StopDetector(float distance_d, int stop_type, float speed) { float lastToSecDistance = lastCoords.distanceTo(secondToLastCoords); Log.d(TAG, "Detecting stop. distance_d=" + distance_d + ". stop_type=" + stop_type + " speed=" + speed); if (stop_type == 1) { if ((distance_d > 50) && (distance_d < 100) && (distance_d != -1) && !m100_a) { m100_a = true; Log.d(TAG, "Case 1: false"); return false; } if ((distance_d > 20) && (distance_d < 50) && (distance_d != -1) && !m50_a) { m50_a = true; Log.d(TAG, "Case 2: false"); return false; } if ((distance_d < 20) && (distance_d != -1) && !m20_a) { m20_a = true; if (speed > 15 && lastToSecDistance < 100) { Log.d(TAG, "Case 3: true"); return true; } Log.d(TAG, "Case 3: false"); return false; } if ((distance_d < 20) && (distance_d != -1) && m20_a && !m20_d) { m20_d = true; if (speed < 10) { Log.d(TAG, "Case 4: false"); return false; } else if (speed > 15) { Log.d(TAG, "Case 4: true"); return true; } } if ((distance_d > 20) && (distance_d < 50) && (distance_d != -1) && !m50_d && (m20_d || m20_a)) { m50_d = true; Log.d(TAG, "Case 5: true"); return true; } } return false; }
Source:
<code>public void takeLeadership(CuratorFramework curatorFramework) throws Exception { try { if (currentLeader != null) { String[] address = currentLeader.getId().split(":"); String host = address[0]; int port = Integer.parseInt(address[1]); OracleService.Client client = getOracleClient(host, port); if (client != null) { try { while (client.isLeader()) { Thread.sleep(500); } } catch (Exception e) { log.debug("Exception thrown in takeLeadership()", e); } } } synchronized (this) { <START> isLeader = true; <END> while (!curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { Thread.sleep(100); } byte[] d = curatorFramework.getData().forPath(maxTsPath); currentTs = maxTs = LongUtil.fromByteArray(d); } gcTsTracker = new GcTimestampTracker(); gcTsTracker.start(); while (started) { Thread.sleep(100); } } finally { isLeader = false; if (started) { Halt.halt("Oracle has lost leadership unexpectedly and is now halting."); } } }</code><technical_language>this moved avoid race condition updateAdvertisedGcTimestamp() and/or isLeader()</technical_language>

Target:
public void takeLeadership(CuratorFramework curatorFramework) throws Exception { try { if (currentLeader != null) { String[] address = currentLeader.getId().split(":"); String host = address[0]; int port = Integer.parseInt(address[1]); OracleService.Client client = getOracleClient(host, port); if (client != null) { try { while (client.isLeader()) { Thread.sleep(500); } } catch (Exception e) { log.debug("Exception thrown in takeLeadership()", e); } } } synchronized (this) { isLeader = true; byte[] d = curatorFramework.getData().forPath(maxTsPath); currentTs = maxTs = LongUtil.fromByteArray(d); } gcTsTracker = new GcTimestampTracker(); gcTsTracker.start(); while (started) { Thread.sleep(100); } } finally { isLeader = false; if (started) { Halt.halt("Oracle has lost leadership unexpectedly and is now halting."); } } }