auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void read(BitBuffer input) { alignRead(input, this.declaration); boolean signed = declaration.isSigned(); int length = declaration.getLength(); long bits = 0; ByteOrder previousByteOrder = input.getByteOrder(); if ((this.declaration.getByteOrder() != null) && (this.declaration.getByteOrder() != input.getByteOrder())) { input.setByteOrder(this.declaration.getByteOrder()); } if (length > 64) { throw new IllegalArgumentException("Cannot read an integer with over 64 bits. Length given: " + length); <START> } else if (length == 64) { <END> try { bits = input.getLong(); } catch (CTFReaderException e) { } } else if (length > 32) { try { bits = input.getLong(length, signed); } catch (CTFReaderException e) { } } else { bits = input.getInt(length, signed); if (!signed) { bits = bits & 0x00000000FFFFFFFFL; } } if (previousByteOrder != input.getByteOrder()) { input.setByteOrder(previousByteOrder); } value = bits; }</code><technical_language>need do a special case for length == 64 next case care of it</technical_language>

Target:
public void read(BitBuffer input) { alignRead(input, this.declaration); boolean signed = declaration.isSigned(); int length = declaration.getLength(); long bits = 0; ByteOrder previousByteOrder = input.getByteOrder(); if ((this.declaration.getByteOrder() != null) && (this.declaration.getByteOrder() != input.getByteOrder())) { input.setByteOrder(this.declaration.getByteOrder()); } if (length > 64) { value = 0; return; } else if (length > 32) { try { bits = input.getLong(length, signed); } catch (CTFReaderException e) { } } else { bits = input.getInt(length, signed); if (!signed) { bits = bits & 0x00000000FFFFFFFFL; } } if (previousByteOrder != input.getByteOrder()) { input.setByteOrder(previousByteOrder); } value = bits; }
Source:
<code>private void checkDeactivatedDirectEdit(SWTBotGefEditPart dEdgeNameEditPartBot, IFigure nameFigure) { Option<IFigure> wrapLabelFigureOption = new FigureQuery(nameFigure).getLabelFigure(); assertTrue("This figure should have a label figure.", wrapLabelFigureOption.some()); assertTrue("The figure of this label should be a SiriusWrapLabel.", wrapLabelFigureOption.get() instanceof SiriusWrapLabel); SiriusWrapLabel viewpointWrapLabel = (SiriusWrapLabel) wrapLabelFigureOption.get(); String wrapText = viewpointWrapLabel.getText(); final long oldTimeout = SWTBotPreferences.TIMEOUT; boolean oldErrorCatchActive = isErrorCatchActive(); setErrorCatchActive(false); SWTBotPreferences.TIMEOUT = 1000; assertLabelMultiLines(nameFigure, 1); <START> boolean noException = editor.directEditType("O\n1\n2", dEdgeNameEditPartBot); if (noException) { SWTBotPreferences.TIMEOUT = oldTimeout; fail("DirectEdit should not be enabled on begin and end edge labels."); } <END> SWTBotUtils.waitAllUiEvents(); assertEquals("DirectEdit should not be enabled on begin and end edge labels.", wrapText, viewpointWrapLabel.getText()); setErrorCatchActive(oldErrorCatchActive); editor.close(); SWTBotUtils.waitAllUiEvents(); }</code><technical_language>setErrorCatchActive TIMEOUT reset original in cases, i.e. a finally block</technical_language>

Target:
private void checkDeactivatedDirectEdit(SWTBotGefEditPart dEdgeNameEditPartBot, IFigure nameFigure) { Option<IFigure> wrapLabelFigureOption = new FigureQuery(nameFigure).getLabelFigure(); assertTrue("This figure should have a label figure.", wrapLabelFigureOption.some()); assertTrue("The figure of this label should be a SiriusWrapLabel.", wrapLabelFigureOption.get() instanceof SiriusWrapLabel); SiriusWrapLabel viewpointWrapLabel = (SiriusWrapLabel) wrapLabelFigureOption.get(); String wrapText = viewpointWrapLabel.getText(); final long oldTimeout = SWTBotPreferences.TIMEOUT; boolean oldErrorCatchActive = isErrorCatchActive(); setErrorCatchActive(false); SWTBotPreferences.TIMEOUT = 1000; try { assertLabelMultiLines(nameFigure, 1); boolean noException = editor.directEditType("O\n1\n2", dEdgeNameEditPartBot); if (noException) { fail("DirectEdit should not be enabled on begin and end edge labels."); } SWTBotUtils.waitAllUiEvents(); assertEquals("DirectEdit should not be enabled on begin and end edge labels.", wrapText, viewpointWrapLabel.getText()); } finally { SWTBotPreferences.TIMEOUT = oldTimeout; setErrorCatchActive(oldErrorCatchActive); editor.close(); SWTBotUtils.waitAllUiEvents(); } }
Source:
<code>public Void call() throws Exception { final long begin = <START> System.currentTimeMillis(); <END> final LongAdder nmodified = new LongAdder(); BigdataSailRepositoryConnection repoConn = null; try { repoConn = getConnection(); new MergingUpdater(repoConn.getTripleStore()) .handleMergingUpdate(namespace, baseURI, getInputStreamFromFileItem(insertStatements), getInputStreamFromFileItem(refSet), getInputStreamFromFileItem(valueSet), uris, nmodified); final long elapsed = System.currentTimeMillis() - begin; reportModifiedCount(nmodified.longValue(), elapsed); return null; } finally { if (repoConn != null) { repoConn.close(); } } }</code><technical_language>nanoTime() for timing, currentTimeMillis() is monotonic</technical_language>

Target:
public Void call() throws Exception { final long begin = System.nanoTime(); final LongAdder nmodified = new LongAdder(); BigdataSailRepositoryConnection repoConn = null; try { repoConn = getConnection(); new MergingUpdater(repoConn.getTripleStore(), outputDumps) .handleMergingUpdate(namespace, baseURI, getInputStreamFromFileItem(insertStatements), getInputStreamFromFileItem(refSet), getInputStreamFromFileItem(valueSet), uris, nmodified); final long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin); reportModifiedCount(nmodified.longValue(), elapsed); return null; } finally { if (repoConn != null) { repoConn.close(); } } }
Source:
<code>protected void onPostExecuteInternal(final Boolean result) { if (activity != null) { final Context nonNullActivity = activity; if (result) { <START> ActivityMixin.showToast(activity, nonNullActivity.getString(R.string.export_fieldnotes_upload_success)); <END> } else { ActivityMixin.showToast(activity, nonNullActivity.getString(R.string.export_failed)); } } }</code><technical_language>reuse existing string R.string.export_fieldnotes_upload_success. simply "Success" in English, translators of other languages refer field notes in there, gave id. If want string in cases, basically introduce a new id "R.string.export_success" similar</technical_language>

Target:
protected void onPostExecuteInternal(final Boolean result) { if (activity != null) { final Context nonNullActivity = activity; if (result) { ActivityMixin.showToast(activity, nonNullActivity.getString(R.string.export_persnotes_upload_success, persNotesCount)); } else { ActivityMixin.showToast(activity, nonNullActivity.getString(R.string.export_failed)); } } }
Source:
<code>public HSQuery createHSQuery(Query luceneQuery, Class<?>... entityTypes) { <START> IndexedTypeIdentifier[] newtypes = Arrays.asList( entityTypes ) <END> .stream() .map( PojoIndexedTypeIdentifier::new ) .toArray( IndexedTypeIdentifier[]::new ); QueryDescriptor descriptor = createQueryDescriptor( luceneQuery, newtypes ); return descriptor.createHSQuery( this ).targetedEntities( IndexedTypesSets.fromClasses( entityTypes ) ); }</code><technical_language>a version accepting a vararg of IndexedTypeIdentifier, IndexedTypesSet, this version deprecated? Similarly getIndexBinding? work in 6 easier... I suspect a long, long PR removing of deprecated methods :)</technical_language>

Target:
public HSQuery createHSQuery(Query luceneQuery, Class<?>... entityTypes) { IndexedTypeSet newtypes = IndexedTypesSets.fromClasses( entityTypes ); QueryDescriptor descriptor = createQueryDescriptor( luceneQuery, newtypes ); return descriptor.createHSQuery( this ).targetedEntities( newtypes ); }
Source:
<code>public void generateDailyReport(MotechEvent event) { <START> LocalDate startDate = (LocalDate) event.getParameters().get(EbodacConstants.DAILY_REPORT_EVENT_START_DATE); <END> reportService.generateDailyReports(); LOGGER.info("Daily Reports generation completed"); }</code><technical_language>this changed</technical_language>

Target:
public void generateDailyReport(MotechEvent event) { DateTime startDate = (DateTime) event.getParameters().get(EbodacConstants.DAILY_REPORT_EVENT_START_DATE); reportService.generateDailyReports(); LOGGER.info("Daily Reports generation completed"); }
Source:
<code>static void adjust(Node<Span> node, @Nullable ClockSkew skewFromParent) { if (skewFromParent != null) { node.value(adjustTimestamps(node.value(), skewFromParent)); } ClockSkew skew = getClockSkew(node.value()); if (skew != null) { node.value(adjustTimestamps(node.value(), skew)); } else { if (skewFromParent != null) { for (int i = 0, length = node.value().binaryAnnotations.size(); i < length; i++) { BinaryAnnotation b = node.value().binaryAnnotations.get(i); if (b.endpoint == null) continue; <START> if (b.key.equals(Constants.LOCAL_COMPONENT) && ipsMatch(skewFromParent.endpoint, b.endpoint)) { <END> skew = skewFromParent; break; } } } } for (Node<Span> child : node.children()) { adjust(child, skew); } }</code><technical_language>fyi, this result in maintenance local spans required tag "lc". local component tag is primarily a tool other annotation binary annotations (as allows some endpoint attached search with. So, while this work for single-host spans, for of them. change heuristic note in a TODO this work for single-host spans "lc"</technical_language>

Target:
static void adjust(Node<Span> node, @Nullable ClockSkew skewFromParent) { if (skewFromParent != null) { node.value(adjustTimestamps(node.value(), skewFromParent)); } ClockSkew skew = getClockSkew(node.value()); if (skew != null) { node.value(adjustTimestamps(node.value(), skew)); } else { if (skewFromParent != null && isLocalSpan(node.value())) { skew = skewFromParent; } } for (Node<Span> child : node.children()) { adjust(child, skew); } }
Source:
<code>public GerritEventType getEventType() { <START> return GerritEventType.PRIVATE_STATE_CHANGED; <END> }</code><technical_language>@darfink this line GerritEventType.WIP_STATE_CHANGED</technical_language>

Target:
public GerritEventType getEventType() { return GerritEventType.WIP_STATE_CHANGED; }
Source:
<code>protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCompositeLit(@NotNull GoCompositeLit o) { super.visitCompositeLit(o); if (PsiTreeUtil.getParentOfType(o, GoReturnStatement.class, GoShortVarDeclaration.class, GoAssignmentStatement.class) == null) return; GoType type = o.getType(); GoType typeFromTypeRef = GoPsiImplUtil.findTypeFromTypeRef(o.getTypeReferenceExpression()); <START> if (!(type instanceof GoStructType || <END> (typeFromTypeRef instanceof GoSpecType && ((GoSpecType) typeFromTypeRef).getType() instanceof GoStructType) )) { return; } for (GoElement element : o.getLiteralValue().getElementList()) { if (element.getKey() == null) { holder.registerProblem(element, "Unnamed field initialization", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } } }; }</code><technical_language>replacing && || is enough</technical_language>

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCompositeLit(@NotNull GoCompositeLit o) { super.visitCompositeLit(o); if (PsiTreeUtil.getParentOfType(o, GoReturnStatement.class, GoShortVarDeclaration.class, GoAssignmentStatement.class) == null) { return; } if (!(o.getContainingFile() instanceof GoFile)) return; String myPackage = ((GoFile)o.getContainingFile()).getPackageName(); List<GoFieldDeclaration> fields; GoType type = o.getType(); if (type instanceof GoStructType) { if (!canProcess(myPackage, (GoStructType)type)) return; fields = ((GoStructType)type).getFieldDeclarationList(); if (hasAnonymousStructField(fields)) return; processLiteralValue(holder, fields, o.getLiteralValue()); return; } GoTypeReferenceExpression ref = o.getTypeReferenceExpression(); if (ref == null || ref.resolveType() == null) return; GoType refType = ref.resolveType().getUnderlyingType(); if (refType instanceof GoStructType) { if (!canProcess(myPackage, (GoStructType)refType)) return; fields = ((GoStructType)refType).getFieldDeclarationList(); if (hasAnonymousStructField(fields)) return; processLiteralValue(holder, fields, o.getLiteralValue()); } else if (refType instanceof GoArrayOrSliceType) { type = ((GoArrayOrSliceType)refType).getType(); if (type == null || !(type.getUnderlyingType() instanceof GoStructType)) return; if (!canProcess(myPackage, (GoStructType)type.getUnderlyingType())) return; fields = ((GoStructType)type.getUnderlyingType()).getFieldDeclarationList(); if (hasAnonymousStructField(fields)) return; for (GoElement element : o.getLiteralValue().getElementList()) { GoValue value = element.getValue(); if (value == null || value.getExpression() != null || value.getLiteralValue() == null) continue; processLiteralValue(holder, fields, value.getLiteralValue()); } } } }; }
Source:
<code>public boolean test(List<WebElement> elements) { if (elements.size() != expectedTexts.size()) { return false; } for (String expectedText : expectedTexts) { boolean found = false; for (WebElement element : elements) { <START> if (Html.text.equalsCaseSensitive(element.getText(), expectedText)) { <END> found = true; } } if (!found) { return false; } } return true; }</code><technical_language>This double-iteration ineffective. call WebDriver.getText() is slow. For performance, collect texts a List<String>, iterate this list</technical_language>

Target:
public boolean test(List<WebElement> elements) { if (elements.size() != expectedTexts.size()) { return false; } List<String> elementsTexts = elements.stream().map(WebElement::getText).collect(Collectors.toList()); for (String expectedText : expectedTexts) { boolean found = false; for (String elementText : elementsTexts) { if (Html.text.equalsCaseSensitive(elementText, expectedText)) { found = true; } } if (!found) { return false; } } return true; }
Source:
<code>private void parseUpdate(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); if (ctl.canUpdate()) { if (isHead(cmd) && !isCommit(cmd)) { return; } validateNewCommits(ctl, cmd); } else { if (GitRepositoryManager.REF_CONFIG.equals(ctl.getRefName())) { rp.sendMessage("You are not allowed to perform this operation.\n" + "Configuration changes can only be pushed by project owners\n" <START> + "who also have 'Push' rights"); <END> } else { rp.sendMessage("You are not allowed to perform this operation.\n" + "To push into this reference you need 'Push' rights." + MESSAGE_FOOTER); } reject(cmd, "Current user '" + ctl.getCurrentUser().getUserName() + "' can not update the reference as a fast forward"); } }</code><technical_language>worth expanding this include say: + "who 'Push' rights " + GitRepositoryManager.REF_CONFIG</technical_language>

Target:
private void parseUpdate(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); if (ctl.canUpdate()) { if (isHead(cmd) && !isCommit(cmd)) { return; } validateNewCommits(ctl, cmd); } else { if (GitRepositoryManager.REF_CONFIG.equals(ctl.getRefName())) { errors.put(Error.CONFIG_UPDATE, Collections.<String> emptyList()); } else { addError(Error.UPDATE, ctl.getRefName()); } reject(cmd, String.format("%s cannot update the reference as a fast forward", displayName(ctl))); } }
Source:
<code>public void testPhoneStateChangeAsExpected() throws Exception { if (!mShouldTestTelecom) { return; } setupConnectionService(null, FLAG_REGISTER | FLAG_ENABLE); Uri testNumber = createTestNumber(); addAndVerifyNewIncomingCall(testNumber, null); TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); CountDownLatch count = new CountDownLatch(1); Executor executor = <START> (Runnable command)->count.countDown(); <END> PhoneStateListener listener = new PhoneStateListener(executor); telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); count.await(TIMEOUT, TimeUnit.MILLISECONDS); Thread.sleep(TIMEOUT); assertEquals(TelephonyManager.CALL_STATE_RINGING, telephonyManager.getCallState()); }</code><technical_language>huh this is creative, thought executor this</technical_language>

Target:
public void testPhoneStateChangeAsExpected() throws Exception { if (!mShouldTestTelecom) { return; } setupConnectionService(null, FLAG_REGISTER | FLAG_ENABLE); Uri testNumber = createTestNumber(); addAndVerifyNewIncomingCall(testNumber, null); TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); CountDownLatch count = new CountDownLatch(1); Executor executor = (Runnable command)->count.countDown(); PhoneStateListener listener = new PhoneStateListener(executor); telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); count.await(TestUtils.WAIT_FOR_PHONE_STATE_LISTENER_REGISTERED_TIMEOUT_S, TimeUnit.SECONDS); Thread.sleep(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS); assertEquals(TelephonyManager.CALL_STATE_RINGING, telephonyManager.getCallState()); }
Source:
<code>public void onDraw(Canvas canvas) { for (int i = viewPort.x; i < (viewPort.x + NUM_SQUARES_IN_ROW); i++) { for (int j = viewPort.y; j < (viewPort.y + NUM_SQUARES_IN_COLUMN); j++) { <START> Sector sector = sectors[i][j]; <END> if (globalGameData.getHumanPlayer().isVisible(sector)) { paint.setColor(Color.BLACK); } else { paint.setColor(THE_UNDISCOVERED_COUNTRY); } int x = (sector.getX() - viewPort.x) * SQUARE_SIZE; int y = (sector.getY() - viewPort.y) * SQUARE_SIZE; r.left = x; r.top = y; r.right = x + (SQUARE_SIZE); r.bottom = y + (SQUARE_SIZE); canvas.drawRect(r, paint); drawWormhole(sector, canvas); drawSystem(sector, canvas); drawShip(canvas, sector); } } drawGrid(canvas); for (Object s : globalGameData.getHumanPlayer().getDiscoveredSectors()) { drawSystem((Sector) s, canvas); drawSystemLabel(canvas, (Sector) s); } drawTopLeftInformation(canvas); }</code><technical_language>This line ArrayOutOfBoundsException: length 10, index -5</technical_language>

Target:
public void onDraw(Canvas canvas) { for (int i = viewPort.x; i < globalGameData.galaxySizeX; i++) { for (int j = viewPort.y; j < globalGameData.galaxySizeY; j++) { try { Sector sector = sectors[i][j]; if (globalGameData.getHumanPlayer().isVisible(sector)) { paint.setColor(Color.BLACK); } else { paint.setColor(THE_UNDISCOVERED_COUNTRY); } int x = (sector.getX() - viewPort.x) * SQUARE_SIZE; int y = (sector.getY() - viewPort.y) * SQUARE_SIZE; r.left = x; r.top = y; r.right = x + (SQUARE_SIZE); r.bottom = y + (SQUARE_SIZE); canvas.drawRect(r, paint); drawWormhole(sector, canvas); drawSystem(sector, canvas); drawShip(canvas, sector); } catch (ArrayIndexOutOfBoundsException e) { } } } drawGrid(canvas); for (Object s : globalGameData.getHumanPlayer().getDiscoveredSectors()) { drawSystem((Sector) s, canvas); drawSystemLabel(canvas, (Sector) s); } drawTopLeftInformation(canvas); }
Source:
<code>public String evaluate(AbstractBuild<?, ?> build, TaskListener listener, String macroName) throws MacroEvaluationException, IOException, InterruptedException { if (StringUtils.isEmpty(format)) { format = showPaths ? FORMAT_DEFAULT_VALUE_WITH_PATHS : FORMAT_DEFAULT_VALUE; } DateFormat dateFormatter; if (StringUtils.isEmpty(dateFormat)) { dateFormatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT); } else { dateFormatter = new SimpleDateFormat(dateFormat); } StringBuffer buf = new StringBuffer(); if (!build.getChangeSet().isEmptySet()) { for (ChangeLogSet.Entry entry : build.getChangeSet()) { Util.printf(buf, format, new ChangesSincePrintfSpec(entry, pathFormat, dateFormatter)); } } else { buf.append(def); } if (showDependencies) { Run<?,?> previousRun = ExtendedEmailPublisher.getPreviousRun(build, listener); <START> if (previousRun != null && previousRun instanceof AbstractBuild) { <END> for (Entry<AbstractProject, DependencyChange> e : build.getDependencyChanges((AbstractBuild)previousRun).entrySet()) { buf.append("\n=======================\n"); buf.append("\nChanges in ").append(e.getKey().getName()) .append(":\n"); for (AbstractBuild<?, ?> b : e.getValue().getBuilds()) { if (!b.getChangeSet().isEmptySet()) { for (ChangeLogSet.Entry entry : b.getChangeSet()) { Util.printf(buf, format, new ChangesSincePrintfSpec(entry, pathFormat, dateFormatter)); } } else { buf.append(def); } } } } } return buf.toString(); }</code><technical_language>BTW instanceof subsumes a null check</technical_language>

Target:
public String evaluate(AbstractBuild<?, ?> build, TaskListener listener, String macroName) throws MacroEvaluationException, IOException, InterruptedException { if (StringUtils.isEmpty(format)) { format = showPaths ? FORMAT_DEFAULT_VALUE_WITH_PATHS : FORMAT_DEFAULT_VALUE; } DateFormat dateFormatter; if (StringUtils.isEmpty(dateFormat)) { dateFormatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT); } else { dateFormatter = new SimpleDateFormat(dateFormat); } StringBuffer buf = new StringBuffer(); if (!build.getChangeSet().isEmptySet()) { for (ChangeLogSet.Entry entry : build.getChangeSet()) { Util.printf(buf, format, new ChangesSincePrintfSpec(entry, pathFormat, dateFormatter)); } } else { buf.append(def); } if (showDependencies) { Run<?,?> previousRun = ExtendedEmailPublisher.getPreviousRun(build, listener); if (previousRun instanceof AbstractBuild) { for (Entry<AbstractProject, DependencyChange> e : build.getDependencyChanges((AbstractBuild)previousRun).entrySet()) { buf.append("\n=======================\n"); buf.append("\nChanges in ").append(e.getKey().getName()) .append(":\n"); for (AbstractBuild<?, ?> b : e.getValue().getBuilds()) { if (!b.getChangeSet().isEmptySet()) { for (ChangeLogSet.Entry entry : b.getChangeSet()) { Util.printf(buf, format, new ChangesSincePrintfSpec(entry, pathFormat, dateFormatter)); } } else { buf.append(def); } } } } } return buf.toString(); }
Source:
<code>public void verifySwiping (PerformTouchAction touchAction, String direction, int attempts) { String currentImageSrc = getCurrentImagePath(); String nextImageSrc; boolean imageChanged = false; int startX = 70; int endX = 20; int duration = 300; int waitAfter = 5000; if (direction == "right") { int temp = startX; startX = endX; endX = temp; } else { direction = "left"; } for (int i = 0; i < attempts; ++i) { <START> touchAction.swipeFromPointToPoint(startX, 50, endX, 50, duration, waitAfter); <END> nextImageSrc = getCurrentImagePath(); if (!nextImageSrc.contains(currentImageSrc)) { imageChanged = true; break; } } if (imageChanged) { PageObjectLogging.log("verifySwiping", "Swiping to " + direction + " works", true); } else { PageObjectLogging.log("verifySwiping", "Swiping to " + direction + " doesn't work", false); } }</code><technical_language>Suggest moving "50" top a variable/constant instead</technical_language>

Target:
public void verifySwiping (PerformTouchAction touchAction, String direction, int attempts) { String currentImageSrc = getCurrentImagePath(); String nextImageSrc; boolean imageChanged = false; int startX = 70; int endX = 20; int duration = 300; int waitAfter = 5000; int centerY = 50; if ("right".equals(direction)) { int temp = startX; startX = endX; endX = temp; } else { direction = "left"; } for (int i = 0; i < attempts; ++i) { touchAction.swipeFromPointToPoint(startX, centerY, endX, centerY, duration, waitAfter); nextImageSrc = getCurrentImagePath(); if (!nextImageSrc.contains(currentImageSrc)) { imageChanged = true; break; } } if (imageChanged) { PageObjectLogging.log("verifySwiping", "Swiping to " + direction + " works", true); } else { PageObjectLogging.log("verifySwiping", "Swiping to " + direction + " doesn't work", false); } }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); searchEditText = (EditText) findViewById(R.id.searchEditText); searchEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) @Override public void onTextChanged(CharSequence s, int start, int before, int count) { <START> if(count>2 ) <END> showResults(s.toString()); } @Override public void afterTextChanged(Editable s) }); messageView = (TextView) findViewById(R.id.search_area); warningView = (TextView) findViewById(R.id.search_warning); buttonGetTranslations = (Button) findViewById(R.id.btnGetTranslations); buttonGetTranslations.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent; if (downloadArabicSearchDb) { downloadArabicSearchDb(); return; } else { intent = new Intent(getApplicationContext(), TranslationManagerActivity.class); } startActivity(intent); finish(); } }); handleIntent(getIntent()); }</code><technical_language>if (count > 2) {</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); searchEditText = (EditText) findViewById(R.id.searchEditText); searchEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (count > 2) { showResults(s.toString()); } } @Override public void afterTextChanged(Editable s) { } }); messageView = (TextView) findViewById(R.id.search_area); warningView = (TextView) findViewById(R.id.search_warning); buttonGetTranslations = (Button) findViewById(R.id.btnGetTranslations); buttonGetTranslations.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent; if (downloadArabicSearchDb) { downloadArabicSearchDb(); return; } else { intent = new Intent(getApplicationContext(), TranslationManagerActivity.class); } startActivity(intent); finish(); } }); handleIntent(getIntent()); }
Source:
<code>public static byte[] encode(Message msg) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { GZIPOutputStream zip = new GZIPOutputStream(bytes); <START> ObjectOutputStream output = new ObjectOutputStream(zip); <END> output.writeObject(msg); output.flush(); zip.finish(); } catch (IOException e) { throw bomb(e); } return bytes.toByteArray(); }</code><technical_language>Need close streams, fine</technical_language>

Target:
public static byte[] encode(Message msg) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { GZIPOutputStream zip = new GZIPOutputStream(bytes); ObjectOutputStream output = new ObjectOutputStream(zip); try { output.writeObject(msg); } finally { output.close(); } } catch (IOException e) { throw bomb(e); } return bytes.toByteArray(); }
Source:
<code>public MatchResult detailMatches(PlanNode node, StatsProvider stats, Session session, Metadata metadata, SymbolAliases symbolAliases) { checkState(shapeMatches(node), "Plan testing framework error: shapeMatches returned false in detailMatches in %s", this.getClass().getName()); ExchangeNode exchangeNode = (ExchangeNode) node; if (!orderBy.isEmpty()) { if (!exchangeNode.getOrderingScheme().isPresent()) { return NO_MATCH; } for (int i = 0; i < orderBy.size(); ++i) { Ordering ordering = orderBy.get(i); Symbol symbol = Symbol.from(symbolAliases.get(ordering.getField())); <START> OrderingScheme orderingScheme = exchangeNode.getOrderingScheme().get(); <END> if (!symbol.equals(orderingScheme.getOrderBy().get(i))) { return NO_MATCH; } if (!ordering.getSortOrder().equals(orderingScheme.getOrdering(symbol))) { return NO_MATCH; } } } return MatchResult.match(); }</code><technical_language>put out of loop</technical_language>

Target:
public MatchResult detailMatches(PlanNode node, StatsProvider stats, Session session, Metadata metadata, SymbolAliases symbolAliases) { checkState(shapeMatches(node), "Plan testing framework error: shapeMatches returned false in detailMatches in %s", this.getClass().getName()); ExchangeNode exchangeNode = (ExchangeNode) node; if (!orderBy.isEmpty()) { if (!exchangeNode.getOrderingScheme().isPresent()) { return NO_MATCH; } if (!orderingSchemeMatches(orderBy, exchangeNode.getOrderingScheme().get(), symbolAliases)) { return NO_MATCH; } } return MatchResult.match(); }
Source:
<code>public boolean processMessage(Object msg) { if (msg instanceof DatagramPacket) { DatagramPacket packet = (DatagramPacket) msg; ByteBuf buffer = packet.content(); <START> if (!buffer.isDirect()) { <END> ByteBuf ioBuffer = UnixChannelUtil.ioBuffer(allocator, buffer.readableBytes()); ioBuffer.writeBytes(buffer, buffer.readerIndex(), buffer.readableBytes()); if (add(ioBuffer, packet.recipient())) { buffers[idx++] = ioBuffer; return true; } else { ioBuffer.release(); return false; } } else { return add(buffer, packet.recipient()); } } return false; }</code><technical_language>I pack non-direct buffer case in a separate method, TBH processMessage short is</technical_language>

Target:
public boolean processMessage(Object msg) { if (msg instanceof DatagramPacket) { DatagramPacket packet = (DatagramPacket) msg; ByteBuf buffer = packet.content(); if (!buffer.isDirect()) { return processNonDirectPacket(buffer, packet.recipient()); } return add(buffer, packet.recipient()); } return false; }
Source:
<code>public void shouldRecordChannelConnect() throws Exception { try (Recording recording = new Recording()) { <START> recording.setSettings(Map.of("io.netty.channel.Connect#threshold", "0ms")); <END> recording.start(); EmbeddedChannel channel = new EmbeddedChannel(new JfrChannelHandler()); channel.connect(new InetSocketAddress(80)).await(); recording.stop(); final Path tempFile = Files.createTempFile(JFrChannelHandlerTest.class.getSimpleName(), ".jfr"); recording.dump(tempFile); final List<RecordedEvent> recordedEvents = RecordingFile.readAllEvents(tempFile); boolean hasConnectEvent = false; for (RecordedEvent event : recordedEvents) { if ("io.netty.channel.Connect".equals(event.getEventType().getName())) { hasConnectEvent = true; break; } } assertTrue("Expected a connect event", hasConnectEvent); } }</code><technical_language>do: recording.enable("io.netty.channel.Connect").withoutThreshold();</technical_language>

Target:
public void shouldRecordChannelConnect() throws Exception { try (Recording recording = new Recording()) { recording.enable("io.netty.channel.Connect").withoutThreshold(); recording.start(); EmbeddedChannel channel = new EmbeddedChannel(new JfrChannelHandler()); channel.connect(new InetSocketAddress(80)).await(); recording.stop(); final Path tempFile = Files.createTempFile(JFrChannelHandlerTest.class.getSimpleName(), ".jfr"); recording.dump(tempFile); final List<RecordedEvent> recordedEvents = RecordingFile.readAllEvents(tempFile); boolean hasConnectEvent = false; for (RecordedEvent event : recordedEvents) { if ("io.netty.channel.Connect".equals(event.getEventType().getName())) { hasConnectEvent = true; break; } } assertTrue("Expected a connect event", hasConnectEvent); } }
Source:
<code>public void close() { Channel rawChannel = rawChannel(); if ( rawChannel.isOpen() ) { messageLogger.serverEvent( "CLOSE" ); try { rawChannel.close().sync(); } catch ( InterruptedException e ) { <START> Thread.currentThread().interrupt(); <END> } } }</code><technical_language>I is useful log exception propagating exception above</technical_language>

Target:
public void close() { Channel rawChannel = rawChannel(); if ( rawChannel.isOpen() ) { messageLogger.serverEvent( "CLOSE" ); rawChannel.close().syncUninterruptibly(); } }
Source:
<code>public static CtfTmfEventType get(CtfTmfTrace trace, String eventName) { <START> String path = CONTEXT_ID; <END> if (trace != null) { path = trace.getPath(); } return (CtfTmfEventType) TmfEventTypeManager.getInstance().getType(CONTEXT_ID + "/" + path, eventName); }</code><technical_language>path = CONTEXT_ID ? naming of variable generalized a bit. secondaryId</technical_language>

Target:
public static CtfTmfEventType get(CtfTmfTrace trace, String eventName) { return (CtfTmfEventType) TmfEventTypeManager.getInstance().getType(computeContextName(trace), eventName); }
Source:
<code>public static final boolean isKQueueAvailable() { try { <START> return Env.isMacOs() && KQueue.isAvailable(); <END> } catch (java.lang.NoClassDefFoundError e) { logger.debug(e.getMessage(), e); ActiveMQClientLogger.LOGGER.unableToCheckKQueueAvailability(e); return false; } }</code><technical_language>is Env.isMacOs() needed? pointed out me. raised throw a NCDFE. add Env.isLinux epoll also. I agree i totally wrong earlier. i Env.IsMacOs is needed originally said</technical_language>

Target:
public static final boolean isKQueueAvailable() { try { return Env.isMacOs() && KQueue.isAvailable(); } catch (Throwable e) { ActiveMQClientLogger.LOGGER.unableToCheckKQueueAvailability(e); return false; } }
Source:
<code>public void testUnsetDataDirAtClusterLevelBeforeActivate() { assertThat( invokeConfigTool("unset", "-s", "localhost:" + getNodePort(), "-c", "data-dirs.main"), is(successful())); activateCluster(); <START> } <END></code><technical_language>Assertions needs failing in validation phase _before_ nomad transactions triggered</technical_language>

Target:
public void testUnsetDataDirAtClusterLevelBeforeActivate() throws IOException, SanskritException { invokeConfigTool("unset", "-s", "localhost:" + getNodePort(), "-c", "data-dirs.main"); activateCluster(); assertChanges(3); }
Source:
<code>private static boolean isJavaFxAvailable() { if (System.getProperty(ZAP_JAVAFX_INIT_FAILED_SYSTEM_PROPERTY) != null) { return false; } try { @SuppressWarnings("unused") javafx.embed.swing.JFXPanel unused = new javafx.embed.swing.JFXPanel(); return true; } catch (Throwable e) { LOGGER.warn("Unable to use JavaFX: " + e.getMessage()); System.setProperty(ZAP_JAVAFX_INIT_FAILED_SYSTEM_PROPERTY, "true"); if (LOGGER.isDebugEnabled()) { <START> LOGGER.warn(e); <END> } } return false; }</code><technical_language>debug? odd check debug warn. - done immediately warn</technical_language>

Target:
private static boolean isJavaFxAvailable() { if (System.getProperty(ZAP_JAVAFX_INIT_FAILED_SYSTEM_PROPERTY) != null) { return false; } try { @SuppressWarnings("unused") javafx.embed.swing.JFXPanel unused = new javafx.embed.swing.JFXPanel(); return true; } catch (Throwable e) { LOGGER.warn("Unable to use JavaFX: " + e.getMessage()); LOGGER.debug(e); System.setProperty(ZAP_JAVAFX_INIT_FAILED_SYSTEM_PROPERTY, "true"); } return false; }
Source:
<code>ImageSupplier(Function<Collection<B>, Collection<B>> outdatedBoxesFilter, VagrantBoxApiFacade.Factory<B> cliFactory, Function<B, Image> boxToImage) { this.outdatedBoxesFilter = checkNotNull(outdatedBoxesFilter, "outdatedBoxesFilter"); this.cliFactory = checkNotNull(cliFactory, "cliFactory"); <START> this.boxToImage = checkNotNull(boxToImage, "boxToImage"); <END> }</code><technical_language>Remove redundant null checks</technical_language>

Target:
ImageSupplier(Function<Collection<B>, Collection<B>> outdatedBoxesFilter, VagrantBoxApiFacade.Factory<B> cliFactory, Function<B, Image> boxToImage) { this.outdatedBoxesFilter = outdatedBoxesFilter; this.cliFactory = cliFactory; this.boxToImage = boxToImage; }
Source:
<code><START> public void testThreadLeakWhenClientCanNotStartDueToAuthenticationError() { <END> try { Hazelcast.newHazelcastInstance(); ClientConfig config = new ClientConfig(); config.getGroupConfig().setName("invalid cluster"); HazelcastClient.newHazelcastClient(config); Assert.fail(); } finally { Hazelcast.shutdownAll(); } }</code><technical_language>AbstractThreadLeakTest extends HazelcastTestSupport; if create HZ HazelcastTestSupport, instance is automatically terminated end of test part of 'after' handling</technical_language>

Target:
public void testThreadLeakWhenClientCanNotStartDueToAuthenticationError() { Hazelcast.newHazelcastInstance(); ClientConfig config = new ClientConfig(); config.getGroupConfig().setName("invalid cluster"); Set<Thread> testStartThreads = getThreads(); try { HazelcastClient.newHazelcastClient(config); } finally { Hazelcast.shutdownAll(); assertHazelcastThreadShutdown(testStartThreads); } }
Source:
<code>private void runMigrations() { <START> for (Map.Entry<String, Configuration.DatastoreConfig> entry : _configuration.getDatastores().entrySet()) { <END> final String dbName = entry.getKey(); final Configuration.DatastoreConfig config = entry.getValue(); final String directory = config.getDirectory(); if (!Strings.isNullOrEmpty(directory)) { final URL resource = _environment.resource(directory); if (resource != null) { LOGGER.info("Running migrations for Cassandra database " + dbName); try { final scala.collection.immutable.Map<String, Object> replication = JavaConverters.mapAsScalaMapConverter( config.getReplication()).asScala().toMap(Predef.conforms()); final File file = new File(resource.toURI()); final Registry registry = Registry.fromDirectory(file); final Migrator migrator = new CassandraMigrator(registry); final Session session = _injector.getInstance(Key.get(Session.class, Names.named(dbName))); session.init(); migrator.initialize(session, config.getKeyspace(), new ReplicationOptions(replication)); session.execute("USE " + config.getKeyspace()); migrator.migrate(session, Option.<Date>none().asScala()); } catch (final URISyntaxException e) { LOGGER.error("Unable to run migrations at " + resource, e); } } else { LOGGER.info("Found no migrations in directory " + directory + " for Cassandra database " + dbName); } } } }</code><technical_language>final entry</technical_language>

Target:
private void runMigrations() { for (final Map.Entry<String, Configuration.DatastoreConfig> entry : _configuration.getDatastores().entrySet()) { final String dbName = entry.getKey(); final Configuration.DatastoreConfig config = entry.getValue(); final Path directory = config.getDirectory(); @Nullable final URL resource = _environment.resource(directory.toString()); if (resource != null) { LOGGER.info() .setMessage("Running migrations for Cassandra database") .addData("database", dbName) .log(); try { final scala.collection.immutable.Map<String, Object> replication = JavaConverters.<String, Object>mapAsScalaMapConverter( MAPPER.convertValue(config.getReplication(), MAP_TYPE_REFERENCE)) .asScala() .toMap(Predef.conforms()); final File file = new File(resource.toURI()); final Registry registry = Registry.fromDirectory(file); final Migrator migrator = new CassandraMigrator(registry); final Session session = _injector.getInstance(Key.get(Session.class, Names.named(dbName))); session.init(); migrator.initialize(session, config.getKeyspace(), new ReplicationOptions(replication)); session.execute("USE " + config.getKeyspace()); migrator.migrate(session, Option.<Date>none().asScala()); } catch (final URISyntaxException e) { LOGGER.error() .setMessage("Unable to run migrations") .addData("resource", resource) .setThrowable(e) .log(); } } else { LOGGER.info() .setMessage("Could not find migrations directory") .addData("directory", directory) .addData("database" , dbName) .log(); } } }
Source:
<code>private void refreshSnapshotsInCluster(VDSGroup cluster) { if (!supportsGlusterSnapshotFeature(cluster)) { return; } final VDS upServer = getClusterUtils().getRandomUpServer(cluster.getId()); if (upServer == null) { return; } <START> VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeSnapshotInfo, <END> new GlusterVolumeSnapshotVDSParameters(upServer.getId(), null, cluster.getId())); try { addOrUpdateSnapshots(cluster.getId(), (ArrayList<GlusterVolumeSnapshotEntity>) returnValue.getReturnValue()); } catch (VdcBLLException e) { throw e; } }</code><technical_language>If storing return runVdsCommand, cast assignment</technical_language>

Target:
private void refreshSnapshotsInCluster(VDSGroup cluster) { if (!supportsGlusterSnapshotFeature(cluster)) { return; } final VDS upServer = getClusterUtils().getRandomUpServer(cluster.getId()); if (upServer == null) { return; } try { List<GlusterVolumeSnapshotEntity> snapshotsList = (ArrayList<GlusterVolumeSnapshotEntity>) runVdsCommand(VDSCommandType.GetGlusterVolumeSnapshotInfo, new GlusterVolumeSnapshotVDSParameters(upServer.getId(), null, cluster.getId())).getReturnValue(); addOrUpdateSnapshots(cluster.getId(), snapshotsList); } catch (VdcBLLException e) { throw e; } }
Source:
<code>public static CassandraKeyValueService createForTesting(CassandraKeyValueServiceConfig config) { try { <START> MetricsManager metricsManager = MetricsManagers.createForTests(); <END> Optional<CqlClientManager> cqlClientManager = config.cqlClientManager(); CassandraClientPool clientPool = CassandraClientPoolImpl.createImplForTest(metricsManager, config, CassandraClientPoolImpl.StartupChecks.RUN, new Blacklist(config)); Optional<CqlClient> cqlClient = config.servers() .visit((thriftServers, maybeCqlServers) -> maybeCqlServers .map(servers -> cqlClientManager .map(manager -> manager.createCqlClient(config, servers)) .orElseGet(() -> CqlClientImpl.create(config, servers)))); return createOrShutdownClientPool(metricsManager, config, CassandraKeyValueServiceRuntimeConfig::getDefault, clientPool, cqlClient, CassandraMutationTimestampProviders.legacyModeForTestsOnly(), LoggerFactory.getLogger(CassandraKeyValueService.class), AtlasDbConstants.DEFAULT_INITIALIZE_ASYNC); } catch (Exception e) { throw Throwables.unwrapAndThrowAtlasDbDependencyException(e); } }</code><technical_language>I want similar createOrShutdownClientPool takes in a client pool optional CqlClient. duplicated code create createForTesting, a small amount either</technical_language>

Target:
public static CassandraKeyValueService createForTesting(CassandraKeyValueServiceConfig config) { MetricsManager metricsManager = MetricsManagers.createForTests(); CassandraClientPool clientPool = CassandraClientPoolImpl.createImplForTest(metricsManager, config, CassandraClientPoolImpl.StartupChecks.RUN, new Blacklist(config)); return createOrShutdownClientPool(metricsManager, config, CassandraKeyValueServiceRuntimeConfig::getDefault, clientPool, CassandraMutationTimestampProviders.legacyModeForTestsOnly(), LoggerFactory.getLogger(CassandraKeyValueService.class), AtlasDbConstants.DEFAULT_INITIALIZE_ASYNC); }
Source:
<code>public void actionUpdateAttributeTypes(AttributeType typeNew) { if (model.getInputConfig() != null && model.getInputConfig().getInput() != null) { DataHandle handle = model.getInputConfig().getInput().getHandle(); if (handle != null) { for (int i = 0; i < handle.getNumColumns(); i++) { String attribute = handle.getAttributeName(i); AttributeType type = model.getInputDefinition().getAttributeType(attribute); if (type != typeNew) { <START> if (attribute.equals(model.getSelectedAttribute())) { <END> for (int k = 0; k < COMBO1_TYPES.length; k++) { if (typeNew == COMBO1_TYPES[k]) { cmbType.select(k); break; } } } actionAttributeTypeChanged(attribute, typeNew); } } } } }</code><technical_language>more intuitive test for equality "this.attribute"? AFAICT "this.attribute" "model.getSelectedAttribute()" equal, however, testing more intuitive manipulating view represented current object..</technical_language>

Target:
public void actionUpdateAttributeTypes(AttributeType typeNew) { if (model.getInputConfig() != null && model.getInputConfig().getInput() != null) { DataHandle handle = model.getInputConfig().getInput().getHandle(); if (handle != null) { for (int i = 0; i < handle.getNumColumns(); i++) { String attribute = handle.getAttributeName(i); AttributeType type = model.getInputDefinition().getAttributeType(attribute); if (type != typeNew) { if (attribute.equals(this.attribute)) { for (int k = 0; k < COMBO1_TYPES.length; k++) { if (typeNew == COMBO1_TYPES[k]) { cmbType.select(k); break; } } } actionAttributeTypeChanged(attribute, typeNew); } } } } }
Source:
<code>public ProcessResult processFiles(Content dataSource, Path moduleOutputPath, AbstractFile iLeappFile) { try { List<String> iLeappTsvOutputFiles = findTsvFiles(moduleOutputPath); <START> if (!iLeappTsvOutputFiles.isEmpty()) { <END> processiLeappFiles(iLeappTsvOutputFiles, iLeappFile); } } catch (IOException | IngestModuleException ex) { logger.log(Level.SEVERE, String.format("Error trying to process iLeapp output files in directory %s. ", moduleOutputPath.toString()), ex); return ProcessResult.ERROR; } return ProcessResult.OK; }</code><technical_language>This check is necessary</technical_language>

Target:
public ProcessResult processFiles(Content dataSource, Path moduleOutputPath, AbstractFile iLeappFile) { try { List<String> iLeappTsvOutputFiles = findTsvFiles(moduleOutputPath); processiLeappFiles(iLeappTsvOutputFiles, iLeappFile); } catch (IOException | IngestModuleException ex) { logger.log(Level.SEVERE, String.format("Error trying to process iLeapp output files in directory %s. ", moduleOutputPath.toString()), ex); return ProcessResult.ERROR; } return ProcessResult.OK; }
Source:
<code>public static ConsoleNote readFrom(DataInputStream in) throws IOException, ClassNotFoundException { try { byte[] preamble = new byte[PREAMBLE.length]; in.readFully(preamble); if (!Arrays.equals(preamble,PREAMBLE)) return null; DataInputStream decoded = new DataInputStream(new UnbufferedBase64InputStream(in)); int macSz = - decoded.readInt(); byte[] mac; int sz; if (macSz > 0) { mac = new byte[macSz]; decoded.readFully(mac); sz = decoded.readInt(); if (sz < 0) { throw new IOException("Corrupt stream"); } } else { mac = null; sz = - macSz; } byte[] buf = new byte[sz]; decoded.readFully(buf); byte[] postamble = new byte[POSTAMBLE.length]; in.readFully(postamble); if (!Arrays.equals(postamble,POSTAMBLE)) return null; if (!INSECURE) { if (mac == null) { throw new IOException("Refusing to deserialize unsigned note from an old log."); } else if (!MAC.checkMac(buf, mac)) { throw new IOException("MAC mismatch"); } } Jenkins jenkins = Jenkins.get(); try (ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream(new ByteArrayInputStream(buf)), <START> jenkins.pluginManager.uberClassLoader, <END> ClassFilter.DEFAULT)) { return (ConsoleNote) ois.readObject(); } } catch (Error e) { throw new IOException(e); } }</code><technical_language>Nit: get rid of local var in this case</technical_language>

Target:
public static ConsoleNote readFrom(DataInputStream in) throws IOException, ClassNotFoundException { try { byte[] preamble = new byte[PREAMBLE.length]; in.readFully(preamble); if (!Arrays.equals(preamble,PREAMBLE)) return null; DataInputStream decoded = new DataInputStream(new UnbufferedBase64InputStream(in)); int macSz = - decoded.readInt(); byte[] mac; int sz; if (macSz > 0) { mac = new byte[macSz]; decoded.readFully(mac); sz = decoded.readInt(); if (sz < 0) { throw new IOException("Corrupt stream"); } } else { mac = null; sz = - macSz; } byte[] buf = new byte[sz]; decoded.readFully(buf); byte[] postamble = new byte[POSTAMBLE.length]; in.readFully(postamble); if (!Arrays.equals(postamble,POSTAMBLE)) return null; if (!INSECURE) { if (mac == null) { throw new IOException("Refusing to deserialize unsigned note from an old log."); } else if (!MAC.checkMac(buf, mac)) { throw new IOException("MAC mismatch"); } } Jenkins jenkins = Jenkins.getInstanceOrNull(); try (ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream(new ByteArrayInputStream(buf)), jenkins != null ? jenkins.pluginManager.uberClassLoader : ConsoleNote.class.getClassLoader(), ClassFilter.DEFAULT)) { return (ConsoleNote) ois.readObject(); } } catch (Error e) { throw new IOException(e); } }
Source:
<code>public static URL url(String protocol, String host, int port, String path) throws IllegalArgumentException { <START> if ((80 == port && "http".equals(protocol)) || (443 == port && "https".equals(protocol))) { <END> port = -1; } try { return new URL(protocol, host, port, path); } catch (MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } }</code><technical_language>Of url http://localhost/api in comparison http://localhost:80/api? Anyway, concern is magic constants :) If refine if clause: int httpsDefaultPort = new URL("https://"+host).getDefaultPort(); int httpDefaultPort = new URL("http://"+host").getDefaultPort(); if ((httpDefaultPort == port && "http".equals(protocol)) || (httpsDefaultPort == port && "https".equals(protocol))) { ... }</technical_language>

Target:
public static URL url(String protocol, String host, int port, String path) throws IllegalArgumentException { if ((DEFAULT_HTTP_PORT == port && "http".equals(protocol)) || (DEFAULT_HTTPS_PORT == port && "https".equals(protocol))) { port = -1; } try { return new URL(protocol, host, port, path); } catch (MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } }