auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean confInvocationPassed(ITestNGMethod method, ITestNGMethod currentTestMethod, IClass testClass, Object instance) { boolean result = true; Class<?> cls = testClass.getRealClass(); if(m_suiteState.isFailed()) { result = false; } else { boolean hasConfigurationFailures = classConfigurationFailed(cls); if (hasConfigurationFailures) { if (! m_continueOnFailedConfiguration) { <START> result = !hasConfigurationFailures; <END> } else { Set<Object> set = getInvocationResults(testClass); result = !set.contains(instance); } return result; } if (m_continueOnFailedConfiguration && hasConfigFailure(currentTestMethod)) { Object key = TestNgMethodUtils.getMethodInvocationToken(currentTestMethod, instance); result = !m_methodInvocationResults.get(currentTestMethod).contains(key); } else if (! m_continueOnFailedConfiguration) { for (Class<?> clazz : m_classInvocationResults.keySet()) { if (clazz.isAssignableFrom(cls)) { result = false; break; } } } } String[] groups = method.getGroups(); for (String group : groups) { if (m_beforegroupsFailures.containsKey(group)) { result = false; break; } } return result; }</code><technical_language>result = false</technical_language>

Target:
private boolean confInvocationPassed(ITestNGMethod method, ITestNGMethod currentTestMethod, IClass testClass, Object instance) { boolean result = true; Class<?> cls = testClass.getRealClass(); if(m_suiteState.isFailed()) { result = false; } else { boolean hasConfigurationFailures = classConfigurationFailed(cls); if (hasConfigurationFailures) { if (! m_continueOnFailedConfiguration) { result = false; } else { Set<Object> set = getInvocationResults(testClass); result = !set.contains(instance); } return result; } if (m_continueOnFailedConfiguration && hasConfigFailure(currentTestMethod)) { Object key = TestNgMethodUtils.getMethodInvocationToken(currentTestMethod, instance); result = !m_methodInvocationResults.get(currentTestMethod).contains(key); } else if (! m_continueOnFailedConfiguration) { for (Class<?> clazz : m_classInvocationResults.keySet()) { if (clazz.isAssignableFrom(cls)) { result = false; break; } } } } String[] groups = method.getGroups(); for (String group : groups) { if (m_beforegroupsFailures.containsKey(group)) { result = false; break; } } return result; }
Source:
<code>public void moduleCreated(IAnalysisModule module) { IPath pathToFiles = XmlUtils.getXmlFilesPath(); <START> File fFolder = pathToFiles.toFile(); if (!(fFolder.isDirectory() && fFolder.exists())) { return; } <END> Map<String, File> files = XmlUtils.listFiles(); for (File xmlFile : files.values()) { if (!XmlUtils.xmlValidate(xmlFile).isOK()) { continue; } try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); if (module instanceof TmfStateSystemAnalysisModule) { for (ViewType viewType : ViewType.values()) { NodeList ssViewNodes = doc.getElementsByTagName(viewType.getXmlElem()); for (int i = 0; i < ssViewNodes.getLength(); i++) { Element node = (Element) ssViewNodes.item(i); List<Element> headNodes = XmlUtils.getChildElements(node, TmfXmlStrings.HEAD); if (headNodes.size() != 1) { continue; } List<Element> analysisNodes = XmlUtils.getChildElements(headNodes.get(0), TmfXmlStrings.ANALYSIS); for (Element analysis : analysisNodes) { String analysisId = analysis.getAttribute(TmfXmlStrings.ID); if (analysisId.equals(module.getId())) { String viewId = viewType.getViewId(); IAnalysisOutput output = new TmfXmlViewOutput(viewId, viewType); output.setOutputProperty(TmfXmlUiStrings.XML_OUTPUT_DATA, node.getAttribute(TmfXmlStrings.ID) + DATA_SEPARATOR + xmlFile.getAbsolutePath(), false); module.registerOutput(output); } } } } } } catch (ParserConfigurationException | SAXException | IOException e) { Activator.logError("Error opening XML file", e); } } }</code><technical_language>verifications moved XmlUtils.listFiles()</technical_language>

Target:
public void moduleCreated(IAnalysisModule module) { Map<String, File> files = XmlUtils.listFiles(); for (File xmlFile : files.values()) { if (!XmlUtils.xmlValidate(xmlFile).isOK()) { continue; } try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); if (module instanceof TmfStateSystemAnalysisModule) { for (ViewType viewType : ViewType.values()) { NodeList ssViewNodes = doc.getElementsByTagName(viewType.getXmlElem()); for (int i = 0; i < ssViewNodes.getLength(); i++) { Element node = (Element) ssViewNodes.item(i); List<Element> headNodes = XmlUtils.getChildElements(node, TmfXmlStrings.HEAD); if (headNodes.size() != 1) { continue; } List<Element> analysisNodes = XmlUtils.getChildElements(headNodes.get(0), TmfXmlStrings.ANALYSIS); for (Element analysis : analysisNodes) { String analysisId = analysis.getAttribute(TmfXmlStrings.ID); if (analysisId.equals(module.getId())) { String viewId = viewType.getViewId(); IAnalysisOutput output = new TmfXmlViewOutput(viewId, viewType); output.setOutputProperty(TmfXmlUiStrings.XML_OUTPUT_DATA, node.getAttribute(TmfXmlStrings.ID) + DATA_SEPARATOR + xmlFile.getAbsolutePath(), false); module.registerOutput(output); } } } } } } catch (ParserConfigurationException | SAXException | IOException e) { Activator.logError("Error opening XML file", e); } } }
Source:
<code>public void getSelectTest() throws Exception { iface.go("<LINK_0>"); WebDriverElement formElement = iface.getWebDriverElement(Strategy.ID, "search"); <START> WebDriverElement actualSelectElement = (WebDriverElement)formElement.getSelect(new Hook(Strategy.TAG, "select")); <END> Assert.assertNotNull(actualSelectElement); }</code><technical_language>want type this WebDriverSelector WebDriverElement</technical_language>

Target:
public void getSelectTest() throws Exception { iface.go("<LINK_0>"); WebDriverElement formElement = iface.getWebDriverElement(Strategy.ID, "search"); WebDriverSelector actualSelectElement = (WebDriverSelector) formElement.getSelect(new Hook(Strategy.TAG, "select"), 0); Assert.assertEquals("for sale", actualSelectElement.getFirstSelectedOption()); }
Source:
<code>public ModelResolverManager(Preferences preferenceStore) { <START> super(); <END> this.preferenceStore = preferenceStore; }</code><technical_language>super(); needed</technical_language>

Target:
public ModelResolverManager(Preferences preferenceStore) { this.preferenceStore = preferenceStore; }
Source:
<code>public Set<String> getSubscribedCategories(Installation installation) { String url = IIDURL + "info/" + installation.getDeviceToken() + "?details=true"; String deviceInfo; try { deviceInfo = get(url); } catch (IOException e) { logger.debug("Couldn't get list of subscribed topics from Instance ID service."); return new HashSet<String>(0); } JSONParser parser = new JSONParser(); JSONObject info; try { info = (JSONObject) parser.parse(deviceInfo); } catch (ParseException e) { logger.debug("Couldn't parse list of subscribed topics from Instance ID service."); return new HashSet<String>(0); } JSONObject rel = (JSONObject) info.get("rel"); <START> if (rel == null){ <END> logger.debug("Couldn't parse rel object Instance ID service."); return new HashSet<String>(0); } JSONObject topics = (JSONObject) rel.get("topics"); return topics.keySet(); }</code><technical_language>@matskiv a</technical_language>

Target:
public Set<String> getSubscribedCategories(Installation installation) { String url = IIDURL + "info/" + installation.getDeviceToken() + "?details=true"; String deviceInfo; try { deviceInfo = get(url); } catch (IOException e) { logger.debug("Couldn't get list of subscribed topics from Instance ID service."); return Collections.emptySet(); } JSONParser parser = new JSONParser(); JSONObject info; try { info = (JSONObject) parser.parse(deviceInfo); } catch (ParseException e) { logger.debug("Couldn't parse list of subscribed topics from Instance ID service."); return Collections.emptySet(); } JSONObject rel = (JSONObject) info.get("rel"); if (rel == null){ logger.debug("Couldn't parse rel object Instance ID service."); return Collections.emptySet(); } JSONObject topics = (JSONObject) rel.get("topics"); return topics.keySet(); }
Source:
<code>private void selectItem(int position) { String long_name = MITModuleActivity.navigationTitles.get(position).getLong_name(); <START> currentModule = long_name; <END> mNavItem = MITModuleActivity.navMap.get(long_name); String intentString = mNavItem.getIntent(); String title = navigationTitles.get(position).getLong_name(); mDrawerLayout.closeDrawer(mDrawerList); swapInFragment(intentString, title); }</code><technical_language>camelcase for variable method names long_name getLong_name()</technical_language>

Target:
private void selectItem(int position) { String longName = MITModuleActivity.navigationTitles.get(position).getLongName(); currentModule = longName; mNavItem = MITModuleActivity.navMap.get(longName); String intentString = mNavItem.getIntent(); String title = navigationTitles.get(position).getLongName(); mDrawerLayout.closeDrawer(mDrawerList); swapInFragment(intentString, title); }
Source:
<code>public void testStopConsumingChunksWhenFailed() { final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1); final AtomicInteger chunks = new AtomicInteger(0); ChunkedInput<ByteBuf> nonClosableInput = new ChunkedInput<ByteBuf>() { @Override public boolean isEndOfInput() throws Exception { return chunks.get() >= 5; } @Override public void close() throws Exception { } @Deprecated @Override public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception { return readChunk(ctx.alloc()); } @Override public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception { chunks.incrementAndGet(); return buffer.retainedDuplicate(); } @Override public long length() { return -1; } @Override public long progress() { return 1; } }; ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { promise.tryFailure(new RuntimeException()); } }; <START> <END> EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler()); ch.writeAndFlush(nonClosableInput).awaitUninterruptibly(); ch.close(); buffer.release(); assertEquals(1, chunks.get()); }</code><technical_language>need call ReferenceCountUtil.release(msg) failing promise</technical_language>

Target:
public void testStopConsumingChunksWhenFailed() { final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1); final AtomicInteger chunks = new AtomicInteger(0); ChunkedInput<ByteBuf> nonClosableInput = new ChunkedInput<ByteBuf>() { @Override public boolean isEndOfInput() throws Exception { return chunks.get() >= 5; } @Override public void close() throws Exception { } @Deprecated @Override public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception { return readChunk(ctx.alloc()); } @Override public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception { chunks.incrementAndGet(); return buffer.retainedDuplicate(); } @Override public long length() { return -1; } @Override public long progress() { return 1; } }; ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ReferenceCountUtil.release(msg); promise.tryFailure(new RuntimeException()); } }; EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler()); ch.writeAndFlush(nonClosableInput).awaitUninterruptibly(); assertFalse(ch.finish()); buffer.release(); assertEquals(1, chunks.get()); }
Source:
<code>public DiskImage getImageAsDiskImage(String id) { DiskImage diskImage = new DiskImage(); Image glanceImage; try { glanceImage = getClient().images().show(id).execute(); } catch (OpenStackResponseException e) { <START> log.error("Exception:", e); <END> throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_ACCESS_IMAGE_REPOSITORY, "Cannot access the image repository. Please make sure it's accessible."); } catch (RuntimeException rte) { log.error("Exception:", rte); throw new RuntimeException("Failed importing image from repository."); } validateContainerFormat(glanceImage); String shortHash = glanceImage.getId().substring(0, 7); if (glanceImage.getName() != null) { diskImage.setDiskDescription(glanceImage.getName() + " (" + shortHash + ")"); } else { diskImage.setDiskDescription("Glance disk: " + shortHash); } setDiskAttributes(diskImage, glanceImage); if (glanceImage.getDiskFormat().equals(GlanceImageFormat.RAW.getValue())) { diskImage.setVolumeFormat(VolumeFormat.RAW); } else if (glanceImage.getDiskFormat().equals(GlanceImageFormat.COW.getValue())) { diskImage.setVolumeFormat(VolumeFormat.COW); } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNSUPPORTED_DISK_FORMAT, "Unknown disk format: " + glanceImage.getDiskFormat()); } return diskImage; }</code><technical_language>wanted avoid printing out entire trace, no? I print in debug mode show http status code exception</technical_language>

Target:
public DiskImage getImageAsDiskImage(String id) { DiskImage diskImage = new DiskImage(); Image glanceImage; try { glanceImage = getClient().images().show(id).execute(); } catch (OpenStackResponseException e) { log.debug("Exception:", e); throw new OpenStackImageException( OpenStackImageException.ErrorType.IMAGE_NOT_FOUND, "Cannot find the specified image."); } catch (RuntimeException rte) { log.error("Exception:", rte); throw new RuntimeException("Failed to import from the repository."); } validateContainerFormat(glanceImage); String shortHash = glanceImage.getId().substring(0, 7); if (glanceImage.getName() != null) { diskImage.setDiskDescription(glanceImage.getName() + " (" + shortHash + ")"); } else { diskImage.setDiskDescription("Glance disk: " + shortHash); } setDiskAttributes(diskImage, glanceImage); if (glanceImage.getDiskFormat().equals(GlanceImageFormat.RAW.getValue())) { diskImage.setVolumeFormat(VolumeFormat.RAW); } else if (glanceImage.getDiskFormat().equals(GlanceImageFormat.COW.getValue())) { diskImage.setVolumeFormat(VolumeFormat.COW); } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNSUPPORTED_DISK_FORMAT, "Unknown disk format: " + glanceImage.getDiskFormat()); } return diskImage; }
Source:
<code>private String[] splitToFileNameAndOvf(String str) { int delimiter = str.indexOf('='); return new String[] { str.substring(0, delimiter), str.substring(delimiter+1) }; <START> } <END></code><technical_language>this done str.split("=", 2)</technical_language>

Target:
private String[] splitToFileNameAndOvf(String str) { return str.split("=", 2); }
Source:
<code>public void refreshVdsStats() { if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vdsManager::refreshVdsStats entered, vds='{}'({})", _vds.getName(), _vds.getId()); } fetchHostInterfaces(); VDSReturnValue statsReturnValue = getResourceManager().runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(_vds)); <START> getResourceManager().getEventListener().updateSchedulingStats(_vds); <END> if (!statsReturnValue.getSucceeded() && statsReturnValue.getExceptionObject() != null) { VDSNetworkException ex = (VDSNetworkException) ((statsReturnValue.getExceptionObject() instanceof VDSNetworkException) ? statsReturnValue.getExceptionObject() : null); if (ex != null) { if (_vdsManager.handleNetworkException(ex, _vds)) { _saveVdsDynamic = true; } log.error("vds::refreshVdsStats Failed getVdsStats, vds='{}'({}): {}", _vds.getName(), _vds.getId(), ex.getMessage()); } else { log.error("vds::refreshVdsStats Failed getVdsStats, vds='{}'({}): {}", _vds.getName(), _vds.getId(), statsReturnValue.getExceptionString()); } throw statsReturnValue.getExceptionObject(); } _saveVdsDynamic = true; _saveVdsStatistics = true; alertIfLowDiskSpaceOnHost(); checkVdsInterfaces(); if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vds::refreshVdsStats\n{0}", this); } }</code><technical_language>please getVdsEventListener().update.</technical_language>

Target:
public void refreshVdsStats() { if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vdsManager::refreshVdsStats entered, vds='{}'({})", _vds.getName(), _vds.getId()); } fetchHostInterfaces(); VDSReturnValue statsReturnValue = getResourceManager().runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(_vds)); getVdsEventListener().updateSchedulingStats(_vds); if (!statsReturnValue.getSucceeded() && statsReturnValue.getExceptionObject() != null) { VDSNetworkException ex = (VDSNetworkException) ((statsReturnValue.getExceptionObject() instanceof VDSNetworkException) ? statsReturnValue.getExceptionObject() : null); if (ex != null) { if (_vdsManager.handleNetworkException(ex, _vds)) { _saveVdsDynamic = true; } log.error("vds::refreshVdsStats Failed getVdsStats, vds='{}'({}): {}", _vds.getName(), _vds.getId(), ex.getMessage()); } else { log.error("vds::refreshVdsStats Failed getVdsStats, vds='{}'({}): {}", _vds.getName(), _vds.getId(), statsReturnValue.getExceptionString()); } throw statsReturnValue.getExceptionObject(); } _saveVdsDynamic = true; _saveVdsStatistics = true; alertIfLowDiskSpaceOnHost(); checkVdsInterfaces(); if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vds::refreshVdsStats\n{0}", this); } }
Source:
<code>public void writeEntityToNBT(NBTTagCompound n) { <START> n.setInteger("frogType", (byte)getType().ordinal()); <END> super.writeEntityToNBT(n); }</code><technical_language>setInteger(byte) :thinking:</technical_language>

Target:
public void writeEntityToNBT(NBTTagCompound n) { n.setInteger("frogType", getType().ordinal()); super.writeEntityToNBT(n); }
Source:
<code>public @Nullable URL getResource(final String inputPath, final String inputPath2) { final String path = resourceLocationTracker.getMapPrefix() + inputPath; final String path2 = resourceLocationTracker.getMapPrefix() + inputPath2; return getMatchingResources(path).stream() .findFirst() .orElse( getMatchingResources(path2).stream() .findFirst() .orElse( getMatchingResources(inputPath).stream() .findFirst() .orElse( <START> getMatchingResources(inputPath2).stream().findFirst().orElse(null)))); <END> }</code><technical_language>approach a refactor removing potentially unused parameter. usage of this method like: return Optional.ofNullable(resourceLoader.getResource(FILE_NAME_BASE + id.getName() + "/" + baseImageName + ".png")) .or(() -> resourceLoader.getResource(FILE_NAME_BASE + baseImageName + ".png") For method itself, repeated part is: return getMatchingResources(path).stream() .findFirst() fix that, add a helper method, eg: private Optional<URL> findResource(final String searchPath) { return getMatchingResources(searchPath) .stream() .findFirst() } helper method, this method becomes: public @Nullable URL getResource(final String inputPath) { return findResource(resourceLocationTracker.getMapPrefix() + inputPath) .or(() -> findResource(inputPath)) .orElse(null);</technical_language>

Target:
public @Nullable URL getResource(final String inputPath, final String inputPath2) { final String path = resourceLocationTracker.getMapPrefix() + inputPath; final String path2 = resourceLocationTracker.getMapPrefix() + inputPath2; return findResource(path) .or(() -> findResource(path2)) .or(() -> findResource(inputPath)) .or(() -> findResource(inputPath2)) .orElse(null); }
Source:
<code>protected void updateData(double[] x, @NonNull AnalysisBaseQueryFilter filters, IProgressMonitor monitor) { if (fXYDataProvider == null) { return; } ICommonXAxisResponse response = null; ICommonXAxisModel model = null; boolean isComplete = false; long currentEnd = 0; while (!isComplete && currentEnd < filters.getQueryInterval().getEndTime().toNanos()) { response = fXYDataProvider.fetch(x, filters, monitor); model = response.getModel(); if (model != null) { updateDisplay(model); } isComplete = response.getStatus() == ICommonXAxisResponse.Status.COMPLETED; if(isComplete) { return; } try { finishedLatch.await(BUILD_UPDATE_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> return; } } }</code><technical_language>log exception printing stack trace. search for tracecompasslog log</technical_language>

Target:
protected void updateData(double[] x, @NonNull AnalysisBaseQueryFilter filters, IProgressMonitor monitor) { if (fXYDataProvider == null) { return; } ICommonXAxisResponse response = null; ICommonXAxisModel model = null; ICommonXAxisResponse.Status status; long currentEnd = 0; while (currentEnd < filters.getQueryInterval().getEndTime().toNanos()) { response = fXYDataProvider.fetch(x, filters, monitor); model = response.getModel(); if (model != null) { updateDisplay(model); } status = response.getStatus(); if (status == ICommonXAxisResponse.Status.COMPLETED) { return; } else if(status == ICommonXAxisResponse.Status.FAILED || status == ICommonXAxisResponse.Status.CANCELLED) { LOGGER.log(Level.WARNING, response.getStatusMessage()); return; } else { try { finishedLatch.await(BUILD_UPDATE_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOGGER.log(Level.INFO, e.getMessage()); return; } } } }
Source:
<code>public RsWithHeader(final Response res, final CharSequence header) { super( <START> new RsOf( <END> () -> RsWithHeader.extend(res.head(), header.toString()), res::body ) ); }</code><technical_language>@fanifieiev above</technical_language>

Target:
public RsWithHeader(final Response res, final CharSequence header) { super( new ResponseOf( () -> RsWithHeader.extend(res.head(), header.toString()), res::body ) ); }
Source:
<code>public Response act(final Request req) throws IOException { final Request file = new RqMultipart.Smart( new RqMultipart.Base(req) ).single("file"); <START> final String name = name(file); <END> final File temp = File.createTempFile("netbout", "bin"); IOUtils.copy(file.body(), new FileOutputStream(temp)); final Bout bout = new RqBout(this.base, req).bout(); final StringBuilder msg = new StringBuilder(Tv.HUNDRED); if (new Attachments.Search(bout.attachments()).exists(name)) { msg.append(String.format("attachment \"%s\" overwritten", name)); } else { try { bout.attachments().create(name); } catch (final Attachments.InvalidNameException ex) { throw new RsFailure(ex); } msg.append(String.format("attachment \"%s\" uploaded", name)); } final String ctype = TkAttach.ctype(temp); msg.append(" (").append(temp.length()) .append(" bytes, ").append(ctype).append(')'); try { bout.attachments().get(name).write( new FileInputStream(temp), ctype, Long.toString(System.currentTimeMillis()) ); } catch (final Attachment.TooBigException | Attachment.BrokenContentException ex) { throw new RsFailure(ex); } FileUtils.forceDelete(temp); bout.messages().post(msg.toString()); throw new RsForward(new RsFlash(msg.toString())); }</code><technical_language>@bdragan this.name(file)</technical_language>

Target:
public Response act(final Request req) throws IOException { final Request file = new RqMultipart.Smart( new RqMultipart.Base(req) ).single("file"); final String name = this.name(file); final File temp = File.createTempFile("netbout", "bin"); IOUtils.copy(file.body(), new FileOutputStream(temp)); final Bout bout = new RqBout(this.base, req).bout(); final StringBuilder msg = new StringBuilder(Tv.HUNDRED); if (new Attachments.Search(bout.attachments()).exists(name)) { msg.append(String.format("attachment \"%s\" overwritten", name)); } else { try { bout.attachments().create(name); } catch (final Attachments.InvalidNameException ex) { throw new RsFailure(ex); } msg.append(String.format("attachment \"%s\" uploaded", name)); } final String ctype = TkAttach.ctype(temp); msg.append(" (").append(temp.length()) .append(" bytes, ").append(ctype).append(')'); try { bout.attachments().get(name).write( new FileInputStream(temp), ctype, Long.toString(System.currentTimeMillis()) ); } catch (final Attachment.TooBigException | Attachment.BrokenContentException ex) { throw new RsFailure(ex); } FileUtils.forceDelete(temp); bout.messages().post(msg.toString()); throw new RsForward(new RsFlash(msg.toString())); }
Source:
<code>public List<LogEntry> getCurrentPage() { long t0 = System.currentTimeMillis(); Bson filter = buildAuditFilter(); List<SortInfo> sortInfos = getSortInfos(); List<Bson> sorts = new ArrayList<>(sortInfos.size()); for (SortInfo sortInfo : sortInfos) { String sortColumn = sortInfo.getSortColumn(); if ("id".equals(sortColumn)) { sortColumn = MongoDBSerializationHelper.MONGODB_ID; } if (sortInfo.getSortAscending()) { sorts.add(Sorts.ascending(sortColumn)); } else { sorts.add(Sorts.descending(sortColumn)); } } MongoCollection<Document> auditCollection = getMongoDBBackend().getAuditCollection(); FindIterable<Document> response = auditCollection.find(filter) .sort(Sorts.orderBy(sorts)) .skip((int) (getCurrentPageIndex() * pageSize)) .limit((int) getMinMaxPageSize()); List<LogEntry> entries = new ArrayList<>(); MongoDatabase database = Framework.getService(MongoDBConnectionService.class).getDatabase(AUDIT_DATABASE_ID); <START> setResultsCount(countDocuments(database, auditCollection, filter)); <END> for (Document document : response) { entries.add(MongoDBAuditEntryReader.read(document)); } preprocessCommentsIfNeeded(entries); CoreSession session = getCoreSession(); if (session != null) { fireSearchEvent(session.getPrincipal(), filter.toString(), entries, System.currentTimeMillis() - t0); } return entries; }</code><technical_language>origin of static helper based idea rely collection's db name discriminate databases. in context avoid making long calls Framework call service get database. this is relevant anymore (since say, need get this anyway) update MongoDBConnectionService then, need port this for people migrate 10.10 11.1 in future</technical_language>

Target:
public List<LogEntry> getCurrentPage() { long t0 = System.currentTimeMillis(); Bson filter = buildAuditFilter(); List<SortInfo> sortInfos = getSortInfos(); List<Bson> sorts = new ArrayList<>(sortInfos.size()); for (SortInfo sortInfo : sortInfos) { String sortColumn = sortInfo.getSortColumn(); if ("id".equals(sortColumn)) { sortColumn = MongoDBSerializationHelper.MONGODB_ID; } if (sortInfo.getSortAscending()) { sorts.add(Sorts.ascending(sortColumn)); } else { sorts.add(Sorts.descending(sortColumn)); } } MongoCollection<Document> auditCollection = getMongoDBBackend().getAuditCollection(); FindIterable<Document> response = auditCollection.find(filter) .sort(Sorts.orderBy(sorts)) .skip((int) (getCurrentPageIndex() * pageSize)) .limit((int) getMinMaxPageSize()); List<LogEntry> entries = new ArrayList<>(); setResultsCount(countDocuments(AUDIT_DATABASE_ID, auditCollection, filter)); for (Document document : response) { entries.add(MongoDBAuditEntryReader.read(document)); } preprocessCommentsIfNeeded(entries); CoreSession session = getCoreSession(); if (session != null) { fireSearchEvent(session.getPrincipal(), filter.toString(), entries, System.currentTimeMillis() - t0); } return entries; }
Source:
<code>public void testGetHTMLNullInput() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); dtc.getHTML(null, DoorsColumnType.OBJECT_TEXT); <START> Assert.fail(); <END> }</code><technical_language>fail is unecesary if exception happen test fail</technical_language>

Target:
public void testGetHTMLNullInput() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); dtc.getHTML(null, DoorsColumnType.OBJECT_TEXT); }
Source:
<code>Entries(Object[] pairs) { Objects.requireNonNull(pairs, "pairs is null"); <START> if ((pairs.length & 1) != 0) { <END> throw new IllegalArgumentException("Odd length of key-value pairs"); } this.pairs = pairs; }</code><technical_language>this extracted a method, java static boolean hasEvenSize(Object[] pairs) { return (pairs.length & 1) == 0; }</technical_language>

Target:
Entries(Object[] pairs) { Objects.requireNonNull(pairs, "pairs is null"); if (!hasEvenSize(pairs)) { throw new IllegalArgumentException("Odd length of key-value pairs"); } this.pairs = pairs; }
Source:
<code>private static Date getUsableDate(Order order) { <START> return order.getDateStopped() != null ? order.getDateStopped() : order.getAutoExpireDate(); <END> }</code><technical_language>a final fallback if dateStopped getAutoExpireDate null... (not if happen, fields allowed null in db *possible* happen). I fall dateCreated (since is date is guaranteed null)</technical_language>

Target:
private static Date getUsableDate(Order order) { return order.getDateStopped() != null ? order.getDateStopped() : (order.getAutoExpireDate() != null ? order.getAutoExpireDate() : order.getDateCreated()); }
Source:
<code>private BuildCommand isRepoUrlChanged(String workDir) { return test("-neq", <START> material.getUrlArgument().rawUrl(), <END> exec("git", "config", "remote.origin.url").setWorkingDirectory(workDir)); }</code><technical_language>This changed forCommandline()</technical_language>

Target:
private BuildCommand isRepoUrlChanged(String workDir) { return test("-neq", material.getUrlArgument().forCommandLine(), exec("git", "config", "remote.origin.url").setWorkingDirectory(workDir)); }
Source:
<code>public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent .getServerTransaction(); <START> LOG.info("\n\nRequest " + request.getMethod() <END> + " received at " + ProtocolObjects.sipStack.getStackName() + " with server transaction id " + serverTransactionId); SipProvider provider = (SipProvider) requestReceivedEvent.getSource(); if (request.getMethod().equals(Request.BYE)) processBye(provider, request, serverTransactionId); }</code><technical_language>I agree conventions set var names, JAINSIP stack is guy, lots of style problem everywhere. I perefer modify files possible, commit targetted log4j upgrade. If concerned code convention, open a new issue, cover code convention problems log4j more ( plenty of them). point Log4jAPI I ok modify 170 files for log4j2 upgrade, if introduce enhacement in terms of logging usage, changing Logger var name is reason enough change 170 files IMO</technical_language>

Target:
public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent .getServerTransaction(); logger.info("\n\nRequest " + request.getMethod() + " received at " + ProtocolObjects.sipStack.getStackName() + " with server transaction id " + serverTransactionId); SipProvider provider = (SipProvider) requestReceivedEvent.getSource(); if (request.getMethod().equals(Request.BYE)) processBye(provider, request, serverTransactionId); }
Source:
<code>public void testEntitiesOnSameNodeBecomeSameServerEntities() { <START> String templateUrl = "classpath://templates END> EntitySpec<? extends Application> spec = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(spec); Application app = this.mgmt.getEntityManager().createEntity(spec); assertEquals(app.getChildren().size(), 1); Entity appChild = Iterables.getOnlyElement(app.getChildren()); assertTrue(appChild instanceof SameServerEntity, "Expected " + SameServerEntity.class.getName() + ", got " + appChild); assertEquals(appChild.getChildren().size(), 2); assertEquals(Iterables.size(Entities.descendants(appChild, MySqlNode.class)), 1, "expected " + MySqlNode.class.getName() + " in " + appChild.getChildren()); assertEquals(Iterables.size(Entities.descendants(appChild, TomcatServer.class)), 1, "expected " + TomcatServer.class.getName() + " in " + appChild.getChildren()); }</code><technical_language>additional /</technical_language>

Target:
public void testEntitiesOnSameNodeBecomeSameServerEntities() { String templateUrl = "classpath://templates/tomcat-mysql-on-one-compute.yaml"; EntitySpec<? extends Application> spec = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(spec); Application app = this.mgmt.getEntityManager().createEntity(spec); assertEquals(app.getChildren().size(), 1); Entity appChild = Iterables.getOnlyElement(app.getChildren()); assertTrue(appChild instanceof SameServerEntity, "Expected " + SameServerEntity.class.getName() + ", got " + appChild); assertEquals(appChild.getChildren().size(), 2); assertEquals(Iterables.size(Entities.descendants(appChild, MySqlNode.class)), 1, "expected " + MySqlNode.class.getName() + " in " + appChild.getChildren()); assertEquals(Iterables.size(Entities.descendants(appChild, TomcatServer.class)), 1, "expected " + TomcatServer.class.getName() + " in " + appChild.getChildren()); }
Source:
<code>void afterChannelIsSet() { <START> this.messages = new ArrayBlockingQueue<>(1000); <END> this.getChannel().subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { messages.offer(message); } }); }</code><technical_language>I LinkedTransferQueue better</technical_language>

Target:
void afterChannelIsSet() { this.messages = new LinkedTransferQueue<>(); this.getChannel().subscribe(message -> messages.offer(message)); }
Source:
<code>private DbUser getUserByUserId(Guid userId) throws SQLException { Connection connection = null; Statement ps = null; ResultSet rs = null; DbUser dbUser = null; try { connection = ds.getConnection(); ps = connection.createStatement(); rs = ps.executeQuery(String.format("SELECT email FROM users WHERE user_id = '%s'", userId.toString())); if (rs.next()) { dbUser = new DbUser(); dbUser.setuser_id(userId); dbUser.setemail(rs.getString("email")); } } finally { <START> DbUtils.closeQuietly(rs,connection); <END> } return dbUser; }</code><technical_language>ps is closed. DbUtils.closeQuietly(rs, ps, connection);</technical_language>

Target:
private DbUser getUserByUserId(Guid userId) throws SQLException { Connection connection = null; Statement ps = null; ResultSet rs = null; DbUser dbUser = null; try { connection = ds.getConnection(); ps = connection.createStatement(); rs = ps.executeQuery(String.format("SELECT email FROM users WHERE user_id = '%s'", userId.toString())); if (rs.next()) { dbUser = new DbUser(); dbUser.setuser_id(userId); dbUser.setemail(rs.getString("email")); } } finally { DbUtils.closeQuietly(rs,ps,connection); } return dbUser; }
Source:
<code>private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { boolean success = true; if (isEventQuestionOrListGroup()) { HashMap<FormIndex, IAnswerData> answers = uiController.questionsView.getAnswers(); List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, FormIndex::compareTo); try { for (FormIndex index : indexKeys) { if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { uiController.showConstraintWarning(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } catch (XPathException e) { UserfacingErrorHandling.createErrorDialog(this, e.getLocalizedMessage(), true); <START> } catch (Exception e) { <END> Log.d(TAG, e.getLocalizedMessage()); e.printStackTrace(); } } return success; }</code><technical_language>wanna catch XpathException application crash in other failures. remove Exception catch other places in PR added it</technical_language>

Target:
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { boolean success = true; if (isEventQuestionOrListGroup()) { HashMap<FormIndex, IAnswerData> answers = uiController.questionsView.getAnswers(); List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, FormIndex::compareTo); try { for (FormIndex index : indexKeys) { if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { uiController.showConstraintWarning(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } catch (XPathException e) { UserfacingErrorHandling.createErrorDialog(this, e.getLocalizedMessage(), true); } } return success; }
Source:
<code>public void testAssetReportGetSuccess() throws Exception { List<String> accessTokens = Arrays.asList(getItemCreateResponse().getAccessToken()); Response<AssetReportCreateResponse> createResponse = AssetReportCreateTest.createAssetReport(client(), accessTokens); String assetReportToken = createResponse.body().getAssetReportToken(); Response<AssetReportGetResponse> response = waitTillReady(client(), assetReportToken); AssetReportGetResponse respBody = response.body(); <START> assertSuccessResponse(response); <END> assertNotNull(respBody.getReport()); assertNotNull(respBody.getReport().getUser()); assertFalse(respBody.getReport().getItems().isEmpty()); assertNotNull(respBody.getReport().getAssetReportId()); assertEquals(new Integer(365), respBody.getReport().getDaysRequested()); assertEquals("Alberta", respBody.getReport().getUser().getFirstName()); assertEquals("Charleson", respBody.getReport().getUser().getLastName()); assertEquals(1, respBody.getReport().getItems().size()); AssetReportGetResponse.Item assetItem = respBody.getReport().getItems().get(0); assertEquals(4, assetItem.getAccounts().size()); assertEquals("ins_109511", assetItem.getInstitutionId()); assertEquals("Tartan Bank", assetItem.getInstitutionName()); }</code><technical_language>tests great! I worry is hard constraints in cases below. If update sandbox data include, say, 5 accounts instead of 4, tests fail. remove test cases dependent user-provided data? For example, fine assert user-provided data is in response in request. a good idea assume number of accounts same</technical_language>

Target:
public void testAssetReportGetSuccess() throws Exception { List<String> accessTokens = Arrays.asList(getItemCreateResponse().getAccessToken()); Response<AssetReportCreateResponse> createResponse = AssetReportCreateTest.createAssetReport(client(), accessTokens); String assetReportToken = createResponse.body().getAssetReportToken(); Response<AssetReportGetResponse> response = waitTillReady(client(), assetReportToken); AssetReportGetResponse respBody = response.body(); assertSuccessResponse(response); assertNotNull(respBody.getReport()); assertNotNull(respBody.getReport().getUser()); assertFalse(respBody.getReport().getItems().isEmpty()); assertNotNull(respBody.getReport().getAssetReportId()); }
Source:
<code>public byte[] getBody() { byte[] body = null; <START> switch(amqpAnnotatedMessage.getBody().getBodyType()) { <END> case DATA: List<BinaryData> binaryData = ((AmqpDataBody)amqpAnnotatedMessage.getBody()).getData().stream() .collect(Collectors.toList()); if (binaryData != null && binaryData.size() > 0) { byte[] firstData = binaryData.get(0).getData(); body = Arrays.copyOf(firstData, firstData.length); } break; case SEQUENCE: case VALUE: throw logger.logThrowableAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + amqpAnnotatedMessage.getBody().getBodyType())); default: throw logger.logThrowableAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + amqpAnnotatedMessage.getBody().getBodyType())); } return body; }</code><technical_language>need format this</technical_language>

Target:
public byte[] getBody() { final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return Arrays.copyOf(binaryData, binaryData.length); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
Source:
<code>private static Object castIntegerToObect(int value, Type type) { if (type == INTEGER || type == TINYINT || type == BIGINT) { return (long) value; } if (type == VARCHAR) { <START> return value + ""; <END> } if (type == DOUBLE) { return (double) value; } throw new UnsupportedOperationException(); }</code><technical_language>String.valueOf()</technical_language>

Target:
private static Object castIntegerToObect(int value, Type type) { if (type == INTEGER || type == TINYINT || type == BIGINT) { return (long) value; } if (type == VARCHAR) { return String.valueOf(value); } if (type == DOUBLE) { return (double) value; } throw new UnsupportedOperationException(); }
Source:
<code>private IndexEntry(final long compressedOffset, final long uncompressedOffset) { <START> if (Long.signum(compressedOffset) == -1) { <END> throw new IllegalArgumentException("negative compressed offset: " + compressedOffset); } if (Long.signum(uncompressedOffset) == -1) { throw new IllegalArgumentException("negative uncompressed offset: " + uncompressedOffset); } this.compressedOffset = compressedOffset; this.uncompressedOffset = uncompressedOffset; }</code><technical_language>this clearer checks for compressedOffset < 0</technical_language>

Target:
private IndexEntry(final long compressedOffset, final long uncompressedOffset) { if (compressedOffset < 0) { throw new IllegalArgumentException("negative compressed offset: " + compressedOffset); } if (uncompressedOffset < 0) { throw new IllegalArgumentException("negative uncompressed offset: " + uncompressedOffset); } this.compressedOffset = compressedOffset; this.uncompressedOffset = uncompressedOffset; }
Source:
<code>public void testPut(BaseThreadState state) { long key = state.randomInt(keyCount); try { map.put(key, 0L); } catch (QuorumException qe) { <START> qe.printStackTrace(); <END> } }</code><technical_language>This is provide a lot of value. If fails, get a stacktrace, test fail</technical_language>

Target:
public void testPut(BaseThreadState state) { final long key = state.randomInt(keyCount); LastClusterSizeChange lastChange = lastClusterSizeChange; if (lastChange.timestamp + gracePeriodMillis > System.currentTimeMillis()) { doProtectedOperation(key, 0L); return; } try { map.put(key, 0L); checkGracePeriod(lastChange, true); } catch (QuorumException qe) { checkGracePeriod(lastChange, false); } }
Source:
<code>public EEFTextLifecycleManager(EEFTextDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { <START> super(description, variableManager, <END> interpreter, editingDomain); this.description = description; }</code><technical_language>done</technical_language>

Target:
public EEFTextLifecycleManager(EEFTextDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(variableManager, interpreter, editingDomain); this.description = description; }
Source:
<code>public ViewPreferencesPanel(boolean immediateUpdates) { initComponents(); this.immediateUpdates = immediateUpdates; TextTranslationService tts = TextTranslationService.getInstance(); if(!tts.hasProvider()) { translatedNamesButton.setVisible(false); fileDisplayLabel.setVisible(false); <START> } <END> }</code><technical_language>I thinking enabling/disabling UI components hiding/showing them. thinking this primarily problems in layout components go, especially here, future additions likely. Also, disabled visible components lets user exists possibility of adding a translation service. motivated provide a service in open source world</technical_language>

Target:
public ViewPreferencesPanel(boolean immediateUpdates) { initComponents(); this.immediateUpdates = immediateUpdates; this.timeZoneList.setListData(TimeZoneUtils.createTimeZoneList().stream().toArray(String[]::new)); }
Source:
<code>protected void writeBlobProperty(JsonGenerator jg, Property prop, PropertyConsumer fieldNameWriter) throws PropertyException, JsonGenerationException, IOException { Blob blob = (Blob) prop.getValue(); if (blob == null) { if (writeNull) { fieldNameWriter.accept(jg, prop); jg.writeNull(); } } else { fieldNameWriter.accept(jg, prop); jg.writeStartObject(); String v = blob.getFilename(); if (v == null) { if (writeNull) { jg.writeNullField("name"); } } else { <START> if (writeNull) { <END> jg.writeStringField("name", v); } } v = blob.getMimeType(); if (v == null) { if (writeNull) { jg.writeNullField("mime-type"); } } else { jg.writeStringField("mime-type", v); } v = blob.getEncoding(); if (v == null) { if (writeNull) { jg.writeNullField("encoding"); } } else { jg.writeStringField("encoding", v); } v = blob.getDigest(); if (v == null) { if (writeNull) { jg.writeNullField("digest"); } } else { jg.writeStringField("digest", v); } jg.writeNumberField("length", blob.getLength()); if (filesBaseUrl != null) { jg.writeStringField("data", getBlobUrl(prop, filesBaseUrl)); } jg.writeEndObject(); } }</code><technical_language>Do need this if (writeNull) here? follow pattern of others below</technical_language>

Target:
protected void writeBlobProperty(JsonGenerator jg, Property prop, PropertyConsumer fieldNameWriter) throws PropertyException, JsonGenerationException, IOException { Blob blob = (Blob) prop.getValue(); if (blob == null) { if (writeNull) { fieldNameWriter.accept(jg, prop); jg.writeNull(); } } else { fieldNameWriter.accept(jg, prop); jg.writeStartObject(); String v = blob.getFilename(); if (v == null) { if (writeNull) { jg.writeNullField("name"); } } else { jg.writeStringField("name", v); } v = blob.getMimeType(); if (v == null) { if (writeNull) { jg.writeNullField("mime-type"); } } else { jg.writeStringField("mime-type", v); } v = blob.getEncoding(); if (v == null) { if (writeNull) { jg.writeNullField("encoding"); } } else { jg.writeStringField("encoding", v); } v = blob.getDigest(); if (v == null) { if (writeNull) { jg.writeNullField("digest"); } } else { jg.writeStringField("digest", v); } jg.writeNumberField("length", blob.getLength()); if (filesBaseUrl != null) { jg.writeStringField("data", getBlobUrl(prop, filesBaseUrl)); } jg.writeEndObject(); } }
Source:
<code>public Set<String> getAllNodesUrls() { HashSet<String> nodesUrls = new HashSet<>(size() + (extraNodes != null ? extraNodes.size() : 0)); <START> for (Node node : this) { <END> nodesUrls.add(node.getNodeInformation().getURL()); } if (extraNodes != null) { for (Node node : extraNodes) { nodesUrls.add(node.getNodeInformation().getURL()); } } return nodesUrls; }</code><technical_language>Duplicated _for_ loop extract a private method factorize code</technical_language>

Target:
public Set<String> getAllNodesUrls() { HashSet<String> nodesUrls = new HashSet<>(size() + (extraNodes != null ? extraNodes.size() : 0)); addNodesToUrlsSet(nodesUrls, this); if (extraNodes != null) { addNodesToUrlsSet(nodesUrls, extraNodes); } return nodesUrls; }
Source:
<code>private Ports() { <START> super(); <END> }</code><technical_language>@danff do need call super() here</technical_language>

Target:
private Ports() { }