auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private @Nullable ByteBuffer skipNRBBlockUntilDataPacket(int blockType, SeekableByteChannel fileChannel) throws BadPcapFileException { final String errorMsg = "A pcapng file is invalid"; ByteBuffer pcapNgBlockHeader = null; int blockLength = 0; int typeBlock = 0; <START> pcapNgBlockHeader = ByteBuffer.allocate(PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); <END> pcapNgBlockHeader.clear(); ByteOrder byteOrder = getByteOrder(); pcapNgBlockHeader.order(byteOrder); try { fileChannel.read(pcapNgBlockHeader); } catch (IOException e) { throw new BadPcapFileException(errorMsg, e); } pcapNgBlockHeader.flip(); typeBlock = pcapNgBlockHeader.getInt(); blockLength = pcapNgBlockHeader.getInt(); while (typeBlock != PcapFileValues.PCAPNG_EPB && typeBlock != PcapFileValues.PCAPNG_PB && typeBlock == blockType && typeBlock != PcapFileValues.PCAPNG_SPB) { try { fileChannel.position(fileChannel.position() + blockLength - PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); } catch (IOException e) { throw new BadPcapFileException(errorMsg, e); } pcapNgBlockHeader = ByteBuffer.allocate(PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); pcapNgBlockHeader.clear(); pcapNgBlockHeader.order(getByteOrder()); try { fileChannel.read(pcapNgBlockHeader); } catch (IOException e) { throw new BadPcapFileException(errorMsg, e); } pcapNgBlockHeader.flip(); typeBlock = pcapNgBlockHeader.getInt(); blockLength = pcapNgBlockHeader.getInt(); } setBlockLength(blockLength); setBlocType(typeBlock); return pcapNgBlockHeader; }</code><technical_language>next block is a packet. 28 bytes</technical_language>

Target:
private @Nullable ByteBuffer skipNRBBlockUntilDataPacket(int blockType, SeekableByteChannel fileChannel) throws BadPcapFileException { final String errorMsg = "A pcapng file is invalid"; ByteBuffer pcapNgBlockHeader = null; int blockLength = 0; int typeBlock = 0; try { if (fileChannel.size() - fileChannel.position() < PcapFileValues.PCAPNG_BLOCK_HEADER_SIZE) { return null; } } catch (IOException e1) { e1.printStackTrace(); } pcapNgBlockHeader = ByteBuffer.allocate(PcapFileValues.PCAPNG_BLOCK_HEADER_SIZE); ByteOrder byteOrder = getByteOrder(); pcapNgBlockHeader.order(byteOrder); try { fileChannel.read(pcapNgBlockHeader); } catch (IOException e) { throw new BadPcapFileException(errorMsg, e); } pcapNgBlockHeader.flip(); typeBlock = pcapNgBlockHeader.getInt(); blockLength = pcapNgBlockHeader.getInt(); while (typeBlock != PcapFileValues.PCAPNG_EPB && typeBlock != PcapFileValues.PCAPNG_PB && typeBlock == blockType && typeBlock != PcapFileValues.PCAPNG_SPB) { try { fileChannel.position(fileChannel.position() + blockLength - PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); } catch (IOException e) { throw new BadPcapFileException(errorMsg, e); } pcapNgBlockHeader = ByteBuffer.allocate(PcapFileValues.PCAPNG_BLOCK_HEADER_SIZE); pcapNgBlockHeader.order(getByteOrder()); try { fileChannel.read(pcapNgBlockHeader); } catch (IOException e) { throw new BadPcapFileException(errorMsg, e); } pcapNgBlockHeader.flip(); typeBlock = pcapNgBlockHeader.getInt(); blockLength = pcapNgBlockHeader.getInt(); } setBlockLength(blockLength); setBlocType(typeBlock); return pcapNgBlockHeader; }
Source:
<code>public boolean nodeExists( long id ) { <START> if ( hasTxStateWithChanges() ) <END> { TransactionState txState = txState(); if ( txState.nodeIsDeletedInThisTx( id ) ) { return false; } else if ( txState.nodeIsAddedInThisTx( id ) ) { return true; } } return storeReadLayer.nodeExists( id ); }</code><technical_language>assertOpen() somewhere</technical_language>

Target:
public boolean nodeExists( long id ) { assertOpen.assertOpen(); if ( hasTxStateWithChanges() ) { TransactionState txState = txState(); if ( txState.nodeIsDeletedInThisTx( id ) ) { return false; } else if ( txState.nodeIsAddedInThisTx( id ) ) { return true; } } return storeReadLayer.nodeExists( id ); }
Source:
<code>private static boolean checkEOF(final Version version, final SeekableStream seekableStream) throws IOException { <START> if (version.compatibleWith(CramVersions.CRAM_v3)) { <END> return streamEndsWith(seekableStream, CRAMv3_EOF_MARKER); } if (version.compatibleWith(CramVersions.CRAM_v2_1)) { return streamEndsWith(seekableStream, CRAMv21_EOF_MARKER); } return false; }</code><technical_language>this streamlined version CramVersions return correct EOF_MARKER directly</technical_language>

Target:
private static boolean checkEOF(final Version version, final SeekableStream seekableStream) throws IOException { final byte[] eof = CramVersions.eofForVersion(version); if (eof.length == 0) { return false; } else { return streamEndsWith(seekableStream, eof); } }
Source:
<code><START> public boolean otherNotificationsAreIndirectlyConcerned(Notification <END> notification, Collection<Notification> notifications) { if (NotationPackage.Literals.ROUTING_STYLE__ROUTING == notification.getFeature() || DiagramPackage.Literals.EDGE_STYLE__CENTERED == notification.getFeature()) { for (Notification currentNotification : notifications) { if (currentNotification != notification && !INTERESTING_FEATURES_BIS.contains(currentNotification.getFeature())) { return false; } } return true; } else { return notifications.size() == 1; } }</code><technical_language>change this method static method class method</technical_language>

Target:
public boolean otherNotificationsAreIndirectlyConcerned(Notification notification, Collection<Notification> notifications) { if (NotationPackage.Literals.ROUTING_STYLE__ROUTING == notification.getFeature() || DiagramPackage.Literals.EDGE_STYLE__CENTERED == notification.getFeature()) { for (Notification currentNotification : notifications) { if (currentNotification != notification && !INDIRECT_INTERESTING_FEATURES.contains(currentNotification.getFeature())) { return false; } } return true; } else { return notifications.size() == 1; } }
Source:
<code>public void runScenario(PickleEvent pickle) throws Throwable { <START> runtime.runPickle(pickle); <END> }</code><technical_language>a listener in runCucumber Ambiguous Undefined result missed (TestNG detect exceptions step definitions, exceptions for Ambiguous Undefined result thrown internally in runner). provide a Listener class (similar FeatureResultListener) I get bottom of this behaviour</technical_language>

Target:
public void runScenario(PickleEvent pickle) throws Throwable { testCaseResultListener.startPickle(); runtime.getRunner().runPickle(pickle); if (!testCaseResultListener.isPassed()) { throw testCaseResultListener.getError(); } }
Source:
<code>public void call(final SingleSubscriber<? super T> child) { final SingleSubscriber<? super T> parent = new SingleSubscriber<T>() { @Override public void onSuccess(T value) { child.onSuccess(value); } @Override public void onError(Throwable error) { <START> RxJavaPlugins.getInstance().getErrorHandler().handleError(error); <END> try { unsubscribe(); resumeFunctionInCaseOfError.call(error).subscribe(child); } catch (Throwable innerError) { Exceptions.throwOrReport(innerError, child); } } }; child.add(parent); originalSingle.subscribe(parent); }</code><technical_language>I call error handler if error delivered replaced normal path</technical_language>

Target:
public void call(final SingleSubscriber<? super T> child) { final SingleSubscriber<? super T> parent = new SingleSubscriber<T>() { @Override public void onSuccess(T value) { child.onSuccess(value); } @Override public void onError(Throwable error) { try { resumeFunctionInCaseOfError.call(error).subscribe(child); } catch (Throwable innerError) { Exceptions.throwOrReport(innerError, child); } } }; child.add(parent); originalSingle.subscribe(parent); }
Source:
<code>public void waitClose() { <START> webDriverWaitFactory <END> .get() .until( ExpectedConditions.invisibilityOfElementLocated( By.xpath(Locators.RESET_TO_COMMIT_FORM))); }</code><technical_language>ready method SeleniumWebDriverHelper#waitVisibility</technical_language>

Target:
public void waitClose() { seleniumWebDriverHelper.waitInvisibility(By.xpath(Locators.RESET_TO_COMMIT_FORM)); }
Source:
<code>public boolean canCreateChildren() { try { <START> if (canCreateChildrenHandler == null) { <END> return true; } return canCreateChildrenHandler.test(this); } catch (Exception e) { throw handleErrorInCallback(e, "canCreateChildrenHandler"); } }</code><technical_language>I inverting this if check improve readability/flow consistent other methods in this class</technical_language>

Target:
public boolean canCreateChildren() { try { if (canCreateChildrenHandler != null) { return canCreateChildrenHandler.test(this); } return true; } catch (Exception e) { throw handleErrorInCallback(e, "canCreateChildrenHandler"); } }
Source:
<code>protected View newView(LayoutInflater inflater, ViewGroup viewContainer) { <START> View view = inflater.inflate(R.layout.layout_list_item_token_with_menu, viewContainer, false); <END> view.setTag(new ViewHolder(view)); return view; }</code><technical_language>please refactor file name layout_list_item_with_menu</technical_language>

Target:
protected View newView(LayoutInflater inflater, ViewGroup viewContainer) { View view = inflater.inflate(R.layout.layout_list_item_with_menu, viewContainer, false); view.setTag(new ViewHolder(view)); return view; }
Source:
<code>public static void init(int max_traces) throws TmfTraceException { File parentDir = new File(TRACES_ROOT_PATH); File[] traceFiles = parentDir.listFiles(); traces = new CtfTmfTrace[Math.min(max_traces, traceFiles.length)]; fExperiment = new TmfExperimentStub[1]; for (int i = 0; i < traces.length; i++) { traces[i] = new CtfTmfTrace(); <START> <END> } fExperiment[0] = new TmfExperimentStub("MegaExperiment", traces, 100); int j = 0; for (int i = 0; i < traces.length; i++) { String absolutePath = traceFiles[j].getAbsolutePath(); if (traces[i].validate(null, absolutePath).isOK()) { traces[i].initTrace(null, absolutePath, ITmfEvent.class); } else { i--; } j++; } }</code><technical_language>blank line remove</technical_language>

Target:
private void init(int max_traces) throws TmfTraceException { File parentDir = new File(TRACES_ROOT_PATH); File[] traceFiles = parentDir.listFiles(); traces = new CtfTmfTrace[Math.min(max_traces, traceFiles.length)]; fExperiment = new TmfExperimentStub[1]; for (int i = 0; i < traces.length; i++) { traces[i] = new CtfTmfTrace(); } fExperiment[0] = new TmfExperimentStub("MegaExperiment", traces, 100); int j = 0; for (int i = 0; i < (traces.length) && (j < traces.length); i++) { String absolutePath = traceFiles[j].getAbsolutePath(); if (traces[i].validate(null, absolutePath).isOK()) { traces[i].initTrace(null, absolutePath, ITmfEvent.class); } else { i--; } j++; } if (traces[traces.length].getPath() == null) { throw new TmfTraceException("Insufficient valid traces in directory"); } }
Source:
<code>public int compareTo(InetAddressAndPort o) { <START> int retval = ByteBuffer.wrap(address.getAddress()).compareTo(ByteBuffer.wrap(o.address.getAddress())); <END> if (retval != 0) { return retval; } return Integer.compare(port, o.port); }</code><technical_language>Yeah pretty bad. getAddress() allocates address byte array. I store address array I address get it</technical_language>

Target:
public int compareTo(InetAddressAndPort o) { int retval = FastByteOperations.compareUnsigned(addressBytes, 0, addressBytes.length, o.addressBytes, 0, o.addressBytes.length); if (retval != 0) { return retval; } return Integer.compare(port, o.port); }
Source:
<code>private boolean testngXmlExistsInJar(File jarFile, List<String> classes) throws IOException { boolean foundTestngXml = false; try (JarFile jf = new JarFile(jarFile)) { Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); if (matchesXmlPathInJar(je)) { Collection<XmlSuite> parsedSuites = Parser.parse(jf.getInputStream(je), processor); for (XmlSuite suite : parsedSuites) { <START> if (testNames != null) { <END> XmlSuiteUtils.cloneIfContainsTestsWithNamesMatchingAny(suite, testNames); List<String> missMatchedTestname = XmlSuiteUtils.getMissMatchedTestNames(testNames); if (CollectionUtils.hasElements(missMatchedTestname)) { XmlSuiteUtils.resetField(); throw new TestNGException("The test(s) <" + Arrays.toString(missMatchedTestname.toArray())+ "> cannot be found."); } suites.addAll(XmlSuiteUtils.getCloneSuite()); XmlSuiteUtils.resetField(); } else { suites.add(suite); } } return true; } else if (isJavaClass(je)) { classes.add(constructClassName(je)); } } } return foundTestngXml; }</code><technical_language>source code for it. [testng-tests.zip](<LINK_0></technical_language>

Target:
private boolean testngXmlExistsInJar(File jarFile, List<String> classes) throws IOException { boolean foundTestngXml = false; try (JarFile jf = new JarFile(jarFile)) { Enumeration<JarEntry> entries = jf.entries(); File file = java.nio.file.Files.createTempDirectory("testngXmlPathInJar-").toFile(); String suitePath = null; while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); String jeName = je.getName(); if (Parser.canParse(jeName.toLowerCase())){ InputStream inputStream = jf.getInputStream(je); File copyFile = new File(file, jeName); Files.copyFile(inputStream, copyFile); if (matchesXmlPathInJar(je)) { suitePath = copyFile.toString(); } } else if (isJavaClass(je)) { classes.add(constructClassName(je)); } } if (Strings.isNullOrEmpty(suitePath)) { return foundTestngXml; } Collection<XmlSuite> parsedSuites = Parser.parse(suitePath, processor); for (XmlSuite suite : parsedSuites) { if (testNames != null) { TestNamesMatcher testNamesMatcher = new TestNamesMatcher(suite, testNames); List<String> missMatchedTestname = testNamesMatcher.getMissMatchedTestNames(); if (!missMatchedTestname.isEmpty()) { throw new TestNGException("The test(s) <" + missMatchedTestname+ "> cannot be found."); } suites.addAll(testNamesMatcher.getSuitesMatchingTestNames()); } else { suites.add(suite); } return true; } } return foundTestngXml; }
Source:
<code>private void deleteSelectedForms() { if (backgroundTasks.deleteFormsTask == null) { <START> progressDialog = new ProgressDialog(getContext()); <END> progressDialog.setMessage(getResources().getString(R.string.form_delete_message)); progressDialog.setIndeterminate(true); progressDialog.setCancelable(false); progressDialog.show(); backgroundTasks.deleteFormsTask = new DeleteFormsTask(); backgroundTasks.deleteFormsTask .setContentResolver(getActivity().getContentResolver()); backgroundTasks.deleteFormsTask.setDeleteListener(this); backgroundTasks.deleteFormsTask.execute(getCheckedIdObjects()); } else { ToastUtils.showLongToast(R.string.file_delete_in_progress); } }</code><technical_language>ProgressDialog longer [it's deprecated](<LINK_0> Annoyingly warning show in Android Studio for some reason! Ideally a progress indicator block user. I want get redesign for moment a ProgressDialogFragment</technical_language>

Target:
private void deleteSelectedForms() { if (backgroundTasks.deleteFormsTask == null) { Bundle args = new Bundle(); args.putSerializable(ProgressDialogFragment.MESSAGE, getResources().getString(R.string.form_delete_message)); args.putBoolean(ProgressDialogFragment.CANCELABLE, false); DialogUtils.showIfNotShowing(ProgressDialogFragment.class, args, getActivity().getSupportFragmentManager()); backgroundTasks.deleteFormsTask = new DeleteFormsTask(); backgroundTasks.deleteFormsTask .setContentResolver(getActivity().getContentResolver()); backgroundTasks.deleteFormsTask.setDeleteListener(this); backgroundTasks.deleteFormsTask.execute(getCheckedIdObjects()); } else { ToastUtils.showLongToast(R.string.file_delete_in_progress); } }
Source:
<code>public void request(IRestfulClient theClient, IHttpRequest theRequest) { String tenantId = getTenantId(); if (isBlank(tenantId)) { return; } String requestUri = theRequest.getUri(); String serverBase = theClient.getServerBase(); if (serverBase.endsWith("/")) { serverBase = serverBase.substring(0, serverBase.length() - 1); } Validate.isTrue(requestUri.startsWith(serverBase), "Request URI %s does not start with server base %s", requestUri, serverBase); <START> if (requestUri.startsWith(serverBase + "/" + tenantId)) { <END> return; } String newUri = serverBase + "/" + tenantId + requestUri.substring(serverBase.length()); theRequest.setUri(newUri); }</code><technical_language>This risky. if I a tenantId is name a legit path? Is some other in request track tenandId appended? (e.g. in a custom header)</technical_language>

Target:
public void request(IRestfulClient theClient, IHttpRequest theRequest) { String tenantId = getTenantId(); if (isBlank(tenantId)) { return; } String requestUri = theRequest.getUri(); String serverBase = theClient.getServerBase(); if (serverBase.endsWith("/")) { serverBase = serverBase.substring(0, serverBase.length() - 1); } Validate.isTrue(requestUri.startsWith(serverBase), "Request URI %s does not start with server base %s", requestUri, serverBase); if (theRequest.getUrlSource() == UrlSourceEnum.EXPLICIT) { return; } String newUri = serverBase + "/" + tenantId + requestUri.substring(serverBase.length()); theRequest.setUri(newUri); }
Source:
<code>private void createMasterFile(boolean isActive) throws IOException { String fileName = masterName.replaceAll(":", "_"); Path path = null; if (isActive) { path = new Path(activePath, fileName); } else { path = new Path(backupPath, fileName); } StringBuilder sb = new StringBuilder(); InetSocketAddress address = getHostAddress(HAConstants.MASTER_CLIENT_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.RESOURCE_TRACKER_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.CATALOG_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.MASTER_INFO_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()); FSDataOutputStream out = fs.create(path); try { out.writeUTF(sb.toString()); <START> out.hflush(); <END> out.close(); } catch (FileAlreadyExistsException e) { createMasterFile(false); } if (isActive) { isActiveStatus = true; } else { isActiveStatus = false; } startPingChecker(); }</code><technical_language>hflush() is client side buffer flushing. change hsync()</technical_language>

Target:
private void createMasterFile(boolean isActive) throws IOException { String fileName = masterName.replaceAll(":", "_"); Path path = null; if (isActive) { path = new Path(activePath, fileName); } else { path = new Path(backupPath, fileName); } StringBuilder sb = new StringBuilder(); InetSocketAddress address = getHostAddress(HAConstants.MASTER_CLIENT_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.RESOURCE_TRACKER_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.CATALOG_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.MASTER_INFO_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()); FSDataOutputStream out = fs.create(path); try { out.writeUTF(sb.toString()); out.hsync(); out.close(); } catch (FileAlreadyExistsException e) { createMasterFile(false); } if (isActive) { isActiveStatus = true; } else { isActiveStatus = false; } startPingChecker(); }
Source:
<code>protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { <START> Promise<ByteBuf> promise = ctx.channel().attr(Http2BlockingChannel.RESPONSE_PROMISE).get(); <END> if (promise != null) { promise.setSuccess(msg.content().retainedDuplicate()); releaseStreamChannel(ctx); } }</code><technical_language>getAndSet(null) release reference well</technical_language>

Target:
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { Promise<ByteBuf> promise = ctx.channel().attr(Http2BlockingChannel.RESPONSE_PROMISE).getAndSet(null); if (promise != null) { promise.setSuccess(msg.content().retainedDuplicate()); releaseStreamChannel(ctx); } }
Source:
<code>public ImmutableList<InfoInsightCards> getAllGenericInsightCards() { final ImmutableList<Optional<InfoInsightCards>> OptionalInfoInsightCards = this.getAllGenericOptionalInsightCards(); <START> final List<InfoInsightCards> InfoInsightCards = Lists.newArrayList(); <END> for (Optional<InfoInsightCards> optionalInsightCard : OptionalInfoInsightCards) { if (!optionalInsightCard.isPresent()) { continue; } InfoInsightCards.add(optionalInsightCard.get()); } return ImmutableList.copyOf(InfoInsightCards); }</code><technical_language>this is duplicated code. refactor it</technical_language>

Target:
public ImmutableList<InfoInsightCards> getAllGenericInsightCards() { final List<Optional<InfoInsightCards>> optionalInfoInsightCards = this.getAllGenericOptionalInsightCards(); final List<InfoInsightCards> InfoInsightCards = filterAbsentCards(optionalInfoInsightCards); return ImmutableList.copyOf(InfoInsightCards); }
Source:
<code>Simulation createSimulation(Path context, String value) throws Exception; <START> Background createBackground(Path context, String dmnFilePath) throws Exception; <END> Settings createSettings(String value) throws Exception; default <T extends AbstractScesimData, E extends ScesimDataWithIndex<T>> E createScesimDataWithIndex(AbstractScesimModel<T> abstractScesimModel, ScesimModelDescriptor simulationDescriptor, Class<E> toInstantiate) throws Exception { simulationDescriptor.addFactMapping(FactIdentifier.INDEX.getName(), FactIdentifier.INDEX, ExpressionIdentifier.INDEX); simulationDescriptor.addFactMapping(FactIdentifier.DESCRIPTION.getName(), FactIdentifier.DESCRIPTION, ExpressionIdentifier.DESCRIPTION); T scenario = abstractScesimModel.addData(); scenario.setDescription(null); int index = abstractScesimModel.getUnmodifiableData().indexOf(scenario) + 1; return toInstantiate.getConstructor(int.class, scenario.getClass()).newInstance(index, scenario) ; }</code><technical_language>this interface is dmn, rules, I propose change dmnFilePath parameter</technical_language>

Target:
Simulation createSimulation(Path context, String value) throws Exception; Settings createSettings(Path context, String value) throws Exception; default <T extends AbstractScesimData, E extends ScesimDataWithIndex<T>> E createScesimDataWithIndex(AbstractScesimModel<T> abstractScesimModel, ScesimModelDescriptor simulationDescriptor, Class<E> toInstantiate) throws Exception { simulationDescriptor.addFactMapping(FactIdentifier.INDEX.getName(), FactIdentifier.INDEX, ExpressionIdentifier.INDEX); simulationDescriptor.addFactMapping(FactIdentifier.DESCRIPTION.getName(), FactIdentifier.DESCRIPTION, ExpressionIdentifier.DESCRIPTION); T scenario = abstractScesimModel.addData(); scenario.setDescription(null); int index = abstractScesimModel.getUnmodifiableData().indexOf(scenario) + 1; return toInstantiate.getConstructor(int.class, scenario.getClass()).newInstance(index, scenario); }
Source:
<code>public void testInterceptors() throws Exception { Map<Class<?>, SortedSet<MessageHandlingMember<? super A>>> interceptors = inspector.getAllInterceptors(); assertEquals(5, interceptors.size()); assertEquals(1, interceptors.get(pA.class).size()); assertEquals(1, interceptors.get(A.class).size()); assertEquals(2, interceptors.get(B.class).size()); assertEquals(1, interceptors.get(C.class).size()); assertEquals(2, interceptors.get(D.class).size()); MessageHandlerInterceptorMemberChain<A> chain = inspector.chainedInterceptor(B.class); <START> chain.handle(asEventMessage("Hello"), new D(), inspector.getHandlers(pA.class).findFirst().get()); <END> assertThrows(MockException.class, () -> chain.handle(asEventMessage(1), new D(), inspector.getHandlers(pA.class).findFirst().get()) ); }</code><technical_language>I "feel" this call is verifying, I notice assertions. Is fact traverses class hierarchy, in interceptor</technical_language>

Target:
void testInterceptors() throws Exception { D testTarget = new D(); EventMessage<Object> testEvent = asEventMessage("Hello"); EventMessage<Object> testEventTwo = asEventMessage(1); Map<Class<?>, SortedSet<MessageHandlingMember<? super A>>> interceptors = inspector.getAllInterceptors(); assertEquals(5, interceptors.size()); assertEquals(1, interceptors.get(pA.class).size()); assertEquals(1, interceptors.get(A.class).size()); assertEquals(2, interceptors.get(B.class).size()); assertEquals(1, interceptors.get(C.class).size()); assertEquals(2, interceptors.get(D.class).size()); MessageHandlerInterceptorMemberChain<A> chain = inspector.chainedInterceptor(B.class); Optional<MessageHandlingMember<? super A>> optionalHandler = inspector.getHandlers(pA.class).findFirst(); assertTrue(optionalHandler.isPresent()); MessageHandlingMember<? super A> resultHandler = optionalHandler.get(); chain.handle(testEvent, testTarget, resultHandler); assertThrows(MockException.class, () -> chain.handle(testEventTwo, testTarget, resultHandler)); }
Source:
<code>public Response getSamlResponse( @QueryParam(SAML_RESPONSE) String deflatedSamlResponse, @QueryParam(RELAY_STATE) String relayState, @QueryParam(SIG_ALG) String signatureAlgorithm, @QueryParam(SIGNATURE) String signature) { LOGGER.warn("HTTP-Redirect binding should not be used for Single Sign-On responses"); if (validateSignature(deflatedSamlResponse, relayState, signatureAlgorithm, signature)) { try { return (StringUtils.isNotBlank(deflatedSamlResponse) && StringUtils.isNotBlank(relayState) <START> && StringUtils.isNotBlank(signatureAlgorithm)) <END> ? processSamlResponse( RestSecurity.inflateBase64(deflatedSamlResponse), relayState, signature != null) : Response.serverError().entity("SAML is in a bad state.").build(); } catch (IOException e) { String msg = "Unable to decode and inflate AuthN response."; LOGGER.info(msg, e); return Response.serverError().entity(msg).build(); } } else { return Response.serverError().entity("Invalid AuthN response signature.").build(); } }</code><technical_language>need check for deflatedSamlResponse blank here. RelayState null is accounted for chain, signature algorithm anymore (it's above)</technical_language>

Target:
public Response getSamlResponse( @QueryParam(SAML_RESPONSE) String deflatedSamlResponse, @QueryParam(RELAY_STATE) String relayState, @QueryParam(SIG_ALG) String signatureAlgorithm, @QueryParam(SIGNATURE) String signature) { LOGGER.warn("HTTP-Redirect binding should not be used for Single Sign-On responses"); if (StringUtils.isBlank(deflatedSamlResponse)) { return Response.serverError().entity("SAML is in a bad state.").build(); } if (!validateSignature(deflatedSamlResponse, relayState, signatureAlgorithm, signature)) { return Response.serverError().entity("Invalid AuthN response signature.").build(); } try { return processSamlResponse( RestSecurity.inflateBase64(deflatedSamlResponse), relayState, signature != null); } catch (IOException e) { String msg = "Unable to decode and inflate AuthN response."; LOGGER.info(msg, e); return Response.serverError().entity(msg).build(); } }
Source:
<code>public void testValidationWithWhiteSpaceAfterAndBeforeDomainClassName() { TreeIterator<EObject> elements = modelerForDomainClassValidation.eAllContents(); int <START> rand = <END> 0; while (elements.hasNext()) { EObject current = elements.next(); for (EAttribute attribute : current.eClass().getEAllAttributes()) { if ("domainClass".equals(attribute.getName())) { addSpaceInDomainClassValue(current, attribute, rand); if (rand < 2) { rand++; } else { rand = 0; } } } } Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(modelerForDomainClassValidation); assertEquals("The VSM is valid, it should not have popup error message", Diagnostic.OK, diagnostic.getSeverity()); }</code><technical_language>* is random anymore in of this variable, name is wrong. * a small set of cases test, I Java code edit in memory a VSM hard read duplicated logic. Simply craft a VSM 8 combinations test simply call validation it. * test cover cases</technical_language>

Target:
public void testValidationWithWhiteSpaceAfterAndBeforeDomainClassName() { TreeIterator<EObject> elements = modelerForDomainClassValidation.eAllContents(); int i = 0; while (elements.hasNext()) { EObject current = elements.next(); for (EAttribute attribute : current.eClass().getEAllAttributes()) { if ("domainClass".equals(attribute.getName())) { addSpaceInDomainClassValue(current, attribute, i); if (i < 2) { i++; } else { i = 0; } } } } Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(modelerForDomainClassValidation); assertEquals("The VSM is valid, it should not have popup error message", Diagnostic.OK, diagnostic.getSeverity()); }
Source:
<code>private String[] getAllCompatibleFieldNames(DocumentBuilderIndexedEntity<?> documentBuilder) { Collection<DocumentFieldMetadata> allFieldMetadata = documentBuilder.getTypeMetadata().getAllDocumentFieldMetadata(); List<String> fieldNames = new ArrayList<String>( allFieldMetadata.size() ); for ( DocumentFieldMetadata fieldMetadata : allFieldMetadata ) { if ( ( fieldMetadata.getTermVector() != Field.TermVector.NO || fieldMetadata.getStore() != org.hibernate.search.annotations.Store.NO ) <START> && ! ( fieldMetadata.isId() || fieldMetadata.isIdInEmbedded() ) ) { END> fieldNames.add( fieldMetadata.getName() ); } } if ( fieldNames.size() == 0 ) { throw log.noFieldCompatibleForMoreLikeThis( documentBuilder.getBeanClass() ); } return fieldNames.toArray( new String[fieldNames.size()] ); }</code><technical_language>meaningful get wrong results? imagine a case id is a unique manually assigned strings sense</technical_language>

Target:
private String[] getAllCompatibleFieldNames(DocumentBuilderIndexedEntity<?> documentBuilder) { Collection<DocumentFieldMetadata> allFieldMetadata = documentBuilder.getTypeMetadata().getAllDocumentFieldMetadata(); List<String> fieldNames = new ArrayList<String>( allFieldMetadata.size() ); for ( DocumentFieldMetadata fieldMetadata : allFieldMetadata ) { boolean hasTermVector = fieldMetadata.getTermVector() != Field.TermVector.NO; boolean isStored = fieldMetadata.getStore() != Store.NO; boolean isIdOrEmbeddedId = fieldMetadata.isId() || fieldMetadata.isIdInEmbedded(); if ( ( hasTermVector || isStored ) && !isIdOrEmbeddedId ) { fieldNames.add( fieldMetadata.getName() ); } } if ( fieldNames.size() == 0 ) { throw log.noFieldCompatibleForMoreLikeThis( documentBuilder.getBeanClass() ); } return fieldNames.toArray( new String[fieldNames.size()] ); }
Source:
<code>private HTInterval getRelevantInterval(long t, int key) throws TimeRangeException, ClosedChannelException { checkValidTime(t); LinkedList<HTNode> queue = new LinkedList<>(); queue.add(fSht.getRootNode()); HTInterval interval = null; <START> while(interval == null && !queue.isEmpty()){ <END> HTNode currentNode = queue.pop(); if ((currentNode.getNodeType() == HTNode.NodeType.CORE)) { queue.addAll(fSht.selectNextChildren((CoreNode) currentNode, t)); } interval = currentNode.getRelevantInterval(key, t); } return interval; }</code><technical_language>formatting</technical_language>

Target:
private HTInterval getRelevantInterval(long t, int key) throws TimeRangeException, ClosedChannelException { checkValidTime(t); Deque<HTNode> queue = new LinkedList<>(); queue.add(fSht.getRootNode()); HTInterval interval = null; while (interval == null && !queue.isEmpty()) { HTNode currentNode = queue.pop(); if ((currentNode.getNodeType() == HTNode.NodeType.CORE)) { queue.addAll(fSht.selectNextChildren((CoreNode) currentNode, t)); } interval = currentNode.getRelevantInterval(key, t); } return interval; }
Source:
<code>public SolenoidOff(SolenoidSubsystem system) { <START> super("Turning off " + system.getName(), system, SolenoidState.OFF); <END> }</code><technical_language>this(system)</technical_language>

Target:
public SolenoidOff(SolenoidSubsystem system) { this("Turning off " + system.getName(), system); }
Source:
<code>private void processNestedFields(TreeMap<String, Type> fieldsMap, List<ElasticsearchColumn> columns, List<String> arrays) { if (fieldsMap.size() == 0) { return; } Map.Entry<String, Type> first = fieldsMap.firstEntry(); String field = first.getKey(); Type type = first.getValue(); if (field.contains(".")) { String prefix = field.substring(0, field.lastIndexOf('.')); ImmutableList.Builder<RowType.Field> fieldsBuilder = ImmutableList.builder(); int size = field.split("\\.").length; Iterator<String> iterator = fieldsMap.navigableKeySet().iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (name.split("\\.").length == size && name.startsWith(prefix)) { fieldsBuilder.add(new RowType.Field(Optional.of(name.substring(name.lastIndexOf('.') + 1)), fieldsMap.get(name))); iterator.remove(); continue; } break; } fieldsMap.put(prefix, RowType.from(fieldsBuilder.build())); } else { <START> if (!columns.stream().anyMatch(column -> column.getName().equalsIgnoreCase(field))) { <END> columns.add(new ElasticsearchColumn(field, type, field, type.getDisplayName(), arrays.contains(field), -1)); } fieldsMap.remove(field); } processNestedFields(fieldsMap, columns, arrays); }</code><technical_language>ditto anyMatch usage & readability of condition</technical_language>

Target:
private void processNestedFields(TreeMap<String, Type> fieldsMap, List<ElasticsearchColumn> columns, List<String> arrays) { if (fieldsMap.size() == 0) { return; } Entry<String, Type> first = fieldsMap.firstEntry(); String field = first.getKey(); Type type = first.getValue(); if (field.contains(".")) { String prefix = field.substring(0, field.lastIndexOf('.')); ImmutableList.Builder<RowType.Field> fieldsBuilder = ImmutableList.builder(); int size = field.split("\\.").length; Iterator<String> iterator = fieldsMap.navigableKeySet().iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (name.split("\\.").length == size && name.startsWith(prefix)) { fieldsBuilder.add(new RowType.Field(Optional.of(name.substring(name.lastIndexOf('.') + 1)), fieldsMap.get(name))); iterator.remove(); continue; } break; } fieldsMap.put(prefix, RowType.from(fieldsBuilder.build())); } else { boolean newFlattenColumn = columns.stream().noneMatch(column -> column.getName().equalsIgnoreCase(field)); if (newFlattenColumn) { columns.add(new ElasticsearchColumn(field, type, field, type.getDisplayName(), arrays.contains(field), -1)); } fieldsMap.remove(field); } processNestedFields(fieldsMap, columns, arrays); }
Source:
<code>private List<DiseaseOccurrence> getOccurrencesForTable(int diseaseGroupId) { <START> return select(diseaseService.getDiseaseOccurrencesByDiseaseGroupIdAndStatuses( <END> diseaseGroupId, DiseaseOccurrenceStatus.READY, DiseaseOccurrenceStatus.IN_REVIEW, DiseaseOccurrenceStatus.AWAITING_BATCHING), having(on(DiseaseOccurrence.class).getLocation().getPrecision(), not(equalTo(LocationPrecision.COUNTRY)))); }</code><technical_language>filter alias more clear select</technical_language>

Target:
private List<DiseaseOccurrence> getOccurrencesForTable(int diseaseGroupId) { List<DiseaseOccurrence> occurrences = diseaseService.getDiseaseOccurrencesByDiseaseGroupIdAndStatuses( diseaseGroupId, DiseaseOccurrenceStatus.READY, DiseaseOccurrenceStatus.IN_REVIEW, DiseaseOccurrenceStatus.AWAITING_BATCHING ); return filter( having(on(DiseaseOccurrence.class).getLocation().getPrecision(), not(equalTo(LocationPrecision.COUNTRY))), occurrences ); }
Source:
<code>public void doInitializeRepository(CoreSession session) { <START> if (Framework.getService(ConfigurationService.class).getBoolean("nuxeo.picture.migration.enabled", true)) { <END> if (log.isInfoEnabled()) { log.info( "Starting picture migration handler (this may take some time depending on the number of documents)"); } boolean txStarted = false; if (!TransactionHelper.isTransactionActive()) { txStarted = true; } try { doMigration(session); } finally { if (txStarted) { TransactionHelper.commitOrRollbackTransaction(); } } } }</code><technical_language>Default false</technical_language>

Target:
public void doInitializeRepository(CoreSession session) { if (Framework.getService(ConfigurationService.class).isBooleanTrue("nuxeo.picture.migration.enabled")) { if (log.isInfoEnabled()) { log.info( "Starting picture migration handler (this may take some time depending on the number of documents)"); } boolean txStarted = false; if (!TransactionHelper.isTransactionActive()) { txStarted = true; } try { doMigration(session); } finally { if (txStarted) { TransactionHelper.commitOrRollbackTransaction(); } } } }
Source:
<code>private String getCreateTableQuery() { StringBuilder sb = new StringBuilder(); sb.append(this.getConfig().SQL_CREATE_TABLE_PREFIX); sb.append(this.getConfig().SQL_CREATE_TABLE); <START> sb.append(" "); <END> if(createIfNotExists){ sb.append(this.getConfig().SQL_CREATE_TABLE_IF_NOT_EXISTS); sb.append(" "); } sb.append(escape(table)); sb.append(" "); sb.append(this.getConfig().SQL_CREATE_TABLE_FIELD_ENCLOSURE_START); sb.append(buildColumns()); sb.append(this.getConfig().SQL_CREATE_TABLE_FIELD_ENCLOSURE_END); sb.append(this.getConfig().SQL_CREATE_TABLE_SUFFIX); return sb.toString(); }</code><technical_language>spaces, good add constant. Optional change</technical_language>

Target:
private String getCreateTableQuery() { StringBuilder sb = new StringBuilder(); sb.append(this.getConfig().SQL_CREATE_TABLE_PREFIX); sb.append(this.getConfig().SQL_CREATE_TABLE); sb.append(" "); if(createIfNotExists){ sb.append(this.getConfig().SQL_CREATE_TABLE_IF_NOT_EXISTS); sb.append(" "); } sb.append(buildFullTableName(fullTableName, this.getConfig().SQL_FULL_NAME_SEGMENT_SEP, true)); sb.append(" "); sb.append(this.getConfig().SQL_CREATE_TABLE_FIELD_ENCLOSURE_START); sb.append(buildColumns()); sb.append(this.getConfig().SQL_CREATE_TABLE_FIELD_ENCLOSURE_END); sb.append(this.getConfig().SQL_CREATE_TABLE_SUFFIX); return sb.toString(); }
Source:
<code>public FormValidation doCheckEnvironment(@QueryParameter(value = "credential") @RelativePath(value = "..") String credential, @QueryParameter(value = "credential") String credential2, @QueryParameter final String value, @AncestorInPath AbstractProject<?,?> project) { <START> Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); <END> if (isNullOrEmpty(value) || "Environments/".equals(value)) return ok("Fill in the target environment ID, eg Environments/MyEnv"); String creds = !isNullOrEmpty(credential) ? credential : credential2; Credential overridingCredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(creds, overridingCredential, project); DeployitNotifier.DeployitDescriptor deployitDescriptor = getDeployitDescriptor(); String resolvedValue = deployitDescriptor.expandValue(value, project); final String environment = DeployitServerFactory.getNameFromId(resolvedValue).trim(); List<String> candidates = deployitServer.search(DeployitDescriptorRegistry.UDM_ENVIRONMENT, environment); if(candidates.isEmpty()) { return warning("Environment '%s' does not exist, please ensure it exists during deployment", environment); } return ok(); }</code><technical_language>I convinced this is correct permission, AbstractProject @AncestorInPath</technical_language>

Target:
public FormValidation doCheckEnvironment(@QueryParameter(value = "credential") @RelativePath(value = "..") String credential, @QueryParameter(value = "credential") String credential2, @QueryParameter final String value, @AncestorInPath AbstractProject<?,?> project) { project.checkPermission(Jenkins.ADMINISTER); if (isNullOrEmpty(value) || "Environments/".equals(value)) return ok("Fill in the target environment ID, eg Environments/MyEnv"); String creds = !isNullOrEmpty(credential) ? credential : credential2; Credential overridingCredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(creds, overridingCredential, project); DeployitNotifier.DeployitDescriptor deployitDescriptor = getDeployitDescriptor(); String resolvedValue = deployitDescriptor.expandValue(value, project); final String environment = DeployitServerFactory.getNameFromId(resolvedValue).trim(); List<String> candidates = deployitServer.search(DeployitDescriptorRegistry.UDM_ENVIRONMENT, environment); if(candidates.isEmpty()) { return warning("Environment '%s' does not exist, please ensure it exists during deployment", environment); } return ok(); }
Source:
<code>public T getItem(int index) { int activeDataEnd = activeStart + activeKeyOrder.size() - 1; if (index < activeStart || index > activeDataEnd) { <START> int dataSize = getItemCount(); <END> if (dataSize == 0) { throw new IndexOutOfBoundsException(String .format("Requested index %d on empty data.", index)); } if (index < 0 || index >= dataSize) { throw new IndexOutOfBoundsException(String.format( "Given index %d is outside of the accepted range '0 - %d'", index, dataSize - 1)); } return (T) getDataProvider().fetch(buildQuery(index, 1)).findFirst() .orElse(null); } else { return getKeyMapper().get(activeKeyOrder.get(index - activeStart)); } }</code><technical_language>For unknown size, getItemCount() returns 0 (initially) current estimate. is intentionally working if I ask for item is current estimate + 1? is intentionally working if I ask for item data communicator fetched items? problem if backend handle query for range, I return null this returns null. I presume 1) if exact size is I request current size, I get exception this 2) if unknown size is used, query is done if is of current estimate - this method returns depend active range estimate moment data provider loaded items yet, flush occurs roundtrip</technical_language>

Target:
public T getItem(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index must be non-negative"); } int activeDataEnd = activeStart + activeKeyOrder.size() - 1; if (index >= activeStart && index <= activeDataEnd) { return getKeyMapper().get(activeKeyOrder.get(index - activeStart)); } else { final int itemCount = getItemCount(); if (isDefinedSize()) { if (itemCount == 0) { throw new IndexOutOfBoundsException(String .format("Requested index %d on empty data.", index)); } else if (index >= itemCount) { throw new IndexOutOfBoundsException(String.format( "Given index %d is outside of the accepted range '0 - %d'", index, itemCount - 1)); } } return (T) getDataProvider().fetch(buildQuery(index, 1)).findFirst() .orElse(null); } }
Source:
<code>private String guessRealIconPath(String path) { File file = new File(path); if (!file.exists()) { try { File productFolder = defaults.getLocation().getParentFile(); String productPath = productFolder.getCanonicalPath(); String iconPath = file.getCanonicalPath(); if (iconPath.startsWith(productPath)) { String rawPath = iconPath.substring(productPath.length()); if (rawPath.startsWith("/") || rawPath.startsWith(File.separator)) { rawPath = rawPath.substring(1); } File parentDirectory = productFolder.getParentFile(); if (parentDirectory != null) { File guessedFile = new File(parentDirectory, rawPath); String absolutePath = guessedFile.getAbsolutePath(); logger.debug("raw path is " + rawPath + ", guessed path is " + absolutePath); if (guessedFile.exists()) { return absolutePath; } } } logger.warn("Icon path " + path + " does not exits and can't be determined by tycho, make sure that either the icon path is relative to the product file, or <START> denoted a <END> folder in the parent path of the product! (current product path is " + productPath + ")"); } catch (IOException e) { logger.warn("can't guess icon path because of I/O problem", e); } } return path; }</code><technical_language>denotes</technical_language>

Target:
private String guessRealIconPath(String path) { File file = new File(path); if (!file.exists()) { try { File productFolder = defaults.getLocation().getParentFile(); String productPath = productFolder.getCanonicalPath(); String iconPath = file.getCanonicalPath(); if (iconPath.startsWith(productPath)) { String rawPath = iconPath.substring(productPath.length()); if (rawPath.startsWith("/") || rawPath.startsWith(File.separator)) { rawPath = rawPath.substring(1); } File parentDirectory = productFolder.getParentFile(); if (parentDirectory != null) { File guessedFile = new File(parentDirectory, rawPath); String absolutePath = guessedFile.getAbsolutePath(); logger.debug("raw path is " + rawPath + ", guessed path is " + absolutePath); if (guessedFile.exists()) { return absolutePath; } } } logger.warn("Icon path " + path + " does not exist and can't be determined by tycho, make sure that either the icon path is relative to the product file, or denotes a folder in the parent path of the product! (current product path is " + productPath + ")"); } catch (IOException e) { logger.warn("can't guess icon path because of I/O problem", e); } } return path; }
Source:
<code>private void appendClientIpToCallerContext() { final CallerContext ctx = CallerContext.getCurrent(); String origContext = ctx == null ? null : ctx.getContext(); byte[] origSignature = ctx == null ? null : ctx.getSignature(); CallerContext.setCurrent( <START> new CallerContext.Builder(origContext, clientConfiguration) <END> .append(CLIENT_IP_STR, Server.getRemoteAddress()) .setSignature(origSignature).build()); }</code><technical_language>pass string separator instead of configuration avoid unnecessary Configuration.get() for RPC</technical_language>

Target:
private void appendClientIpToCallerContext() { final CallerContext ctx = CallerContext.getCurrent(); String origContext = ctx == null ? null : ctx.getContext(); byte[] origSignature = ctx == null ? null : ctx.getSignature(); CallerContext.setCurrent( new CallerContext.Builder(origContext, contextFieldSeparator) .append(CLIENT_IP_STR, Server.getRemoteAddress()) .setSignature(origSignature).build()); }
Source:
<code><START> public void setGeoLocation(String geoLocationString) { <END> String[] geoParts = geoLocationString.split("\\|"); if (geoParts == null || geoParts.length < 2 || geoParts[0] == null || geoParts[1] == null) return; this.latitude = Double.parseDouble(geoParts[0]); this.longitude = Double.parseDouble(geoParts[1]); }</code><technical_language>in case: is geoLocationString is null</technical_language>

Target:
public void setGeoLocation(String geoLocationString) { if (geoLocationString == null) { return; } String[] geoParts = geoLocationString.split("\\|"); if (geoParts == null || geoParts.length < 2 || geoParts[0] == null || geoParts[1] == null) { return; } this.latitude = Double.parseDouble(geoParts[0]); this.longitude = Double.parseDouble(geoParts[1]); }
Source:
<code><START> public void setIpAddress(String ip) { <END> this.ip = ip; }</code><technical_language>validate IP address in setter? this need validated time used, getFQDN() is called,</technical_language>

Target:
public void setIpAddress(String ip) { if (ip == null) { this.ip = null; } else { try { InetAddress inet = InetAddress.getByName(ip); this.ip = (inet != null ? inet.getHostAddress() : null); } catch (IOException e) { log.error("Error getting InetAddress from given ip " + ip, e); throw new IllegalArgumentException("Error getting InetAddress from given ip " + ip, e); } } }