auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public IndexProxy removeIndexProxy( long indexId ) { IndexProxy removedProxy = indexesById.remove( indexId ); if ( removedProxy == null ) { return null; } SchemaDescriptor schema = removedProxy.getDescriptor().schema(); indexesByDescriptor.remove( schema ); if ( schema.entityType() == EntityType.NODE ) { if ( schema.getEntityTokenIds() == SchemaDescriptor.ANY_ENTITY_TOKEN ) { descriptorsForAllLabels.remove( schema ); } for ( int entityTokenId : schema.getEntityTokenIds() ) { removeFromLookup( entityTokenId, schema, descriptorsByLabel ); } for ( int propertyId : schema.getPropertyIds() ) { removeFromLookup( propertyId, schema, descriptorsByProperty ); } } else if ( schema.entityType() == EntityType.RELATIONSHIP ) { <START> if ( schema.getEntityTokenIds().length == 0 ) <END> { descriptorsForAllReltypes.remove( schema ); } for ( int entityTokenId : schema.getEntityTokenIds() ) { removeFromLookup( entityTokenId, schema, descriptorsByReltype ); } for ( int propertyId : schema.getPropertyIds() ) { removeFromLookup( propertyId, schema, relationshipDescriptorsByProperty ); } } return removedProxy; }</code><technical_language>is this ANY_ENTITY_TOKEN</technical_language>

Target:
public IndexProxy removeIndexProxy( long indexId ) { IndexProxy removedProxy = indexesById.remove( indexId ); if ( removedProxy == null ) { return null; } SchemaDescriptor schema = removedProxy.getDescriptor().schema(); indexesByDescriptor.remove( schema ); if ( schema.entityType() == EntityType.NODE ) { if ( SchemaDescriptor.isAnyEntityTokenSchema( schema ) ) { descriptorsForAllLabels.remove( schema ); } removeFromLookup( schema.getEntityTokenIds(), schema, descriptorsByLabel ); removeFromLookup( schema.getPropertyIds(), schema, nodeDescriptorsByProperty ); } else if ( schema.entityType() == EntityType.RELATIONSHIP ) { if ( SchemaDescriptor.isAnyEntityTokenSchema( schema ) ) { descriptorsForAllReltypes.remove( schema ); } removeFromLookup( schema.getEntityTokenIds(), schema, descriptorsByReltype ); removeFromLookup( schema.getPropertyIds(), schema, relationshipDescriptorsByProperty ); } return removedProxy; }
Source:
<code>public static Chain decode(StructDecoder<?> decoder) { StructArrayDecoder<? extends StructDecoder<?>> elementsDecoder = decoder.structs("elements"); final List<Element> elements = new ArrayList<>(); for (int i = 0; i < elementsDecoder.length(); i++) { StructDecoder<?> elementDecoder = elementsDecoder.next(); Long sequence = elementDecoder.int64("sequence"); ByteBuffer byteBuffer = elementDecoder.byteBuffer("payload"); elementDecoder.end(); if (sequence == null) { <START> elements.add(byteBuffer::duplicate); <END> } else { elements.add(new SequencedElement() { @Override public long getSequenceNumber() { return sequence; } @Override public ByteBuffer getPayload() { return byteBuffer.duplicate(); } }); } } elementsDecoder.end(); return chainFromList(elements); }</code><technical_language>asReadOnlyBuffer</technical_language>

Target:
public static Chain decode(StructDecoder<?> decoder) { StructArrayDecoder<? extends StructDecoder<?>> elementsDecoder = decoder.structs("elements"); final List<Element> elements = new ArrayList<>(); for (int i = 0; i < elementsDecoder.length(); i++) { StructDecoder<?> elementDecoder = elementsDecoder.next(); Long sequence = elementDecoder.int64("sequence"); ByteBuffer byteBuffer = elementDecoder.byteBuffer("payload"); elementDecoder.end(); if (sequence == null) { elements.add(byteBuffer::asReadOnlyBuffer); } else { elements.add(new SequencedElement() { @Override public long getSequenceNumber() { return sequence; } @Override public ByteBuffer getPayload() { return byteBuffer.asReadOnlyBuffer(); } }); } } elementsDecoder.end(); return chainFromList(elements); }
Source:
<code>public void test4_09BringToTop() { SWTBotUtils.openTrace(TRACE_PROJECT_NAME, fTestFile.getAbsolutePath(), CUSTOM_TEXT_LOG.getTraceType()); SWTBotTreeItem traceItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectTracesFolder(fBot, TRACE_PROJECT_NAME), TRACE_NAME); traceItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, TRACE_NAME)); IEditorReference originalEditor = fBot.activeEditor().getReference(); createCopy(traceItem, true); SWTBotTreeItem copiedItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectTracesFolder(fBot, TRACE_PROJECT_NAME), RENAMED_TRACE_NAME); copiedItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, RENAMED_TRACE_NAME)); <START> SWTBotUtils.delay(1000); <END> traceItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, TRACE_NAME)); assertTrue(originalEditor == fBot.activeEditor().getReference()); fBot.closeAllEditors(); SWTBotUtils.clearTracesFolderUI(fBot, TRACE_PROJECT_NAME); }</code><technical_language>set focus Project Explorer view double-clicking</technical_language>

Target:
public void test4_09BringToTop() { SWTBotUtils.openTrace(TRACE_PROJECT_NAME, fTestFile.getAbsolutePath(), CUSTOM_TEXT_LOG.getTraceType()); SWTBotTreeItem traceItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectTracesFolder(fBot, TRACE_PROJECT_NAME), TRACE_NAME); fBot.viewByTitle(PROJECT_EXPLORER_VIEW_NAME).setFocus(); traceItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, TRACE_NAME)); IEditorReference originalEditor = fBot.activeEditor().getReference(); createCopy(traceItem, true); SWTBotTreeItem copiedItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectTracesFolder(fBot, TRACE_PROJECT_NAME), RENAMED_TRACE_NAME); fBot.viewByTitle(PROJECT_EXPLORER_VIEW_NAME).setFocus(); copiedItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, RENAMED_TRACE_NAME)); SWTBotUtils.delay(1000); fBot.viewByTitle(PROJECT_EXPLORER_VIEW_NAME).setFocus(); traceItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, TRACE_NAME)); assertTrue(originalEditor == fBot.activeEditor().getReference()); fBot.closeAllEditors(); SWTBotUtils.clearTracesFolderUI(fBot, TRACE_PROJECT_NAME); }
Source:
<code>public void ensureValid(String name, Object value) { if (value == null) { return; } if (!(value instanceof List)) { throw new ConfigException("Invalid value type (list expected)."); } List items = (List) value; if (items.isEmpty()) { return; } for (Object item: items) { if (!(item instanceof String)) { throw new ConfigException("Invalid type for admin listener (expected String)."); } <START> if (((String) item).length() == 0) { <END> throw new ConfigException("Empty listener found when parsing list."); } } }</code><technical_language>prevent whitespace-only strings: suggestion if (((String) item).trim().isEmpty()) {</technical_language>

Target:
public void ensureValid(String name, Object value) { if (value == null) { return; } if (!(value instanceof List)) { throw new ConfigException("Invalid value type (list expected)."); } List items = (List) value; if (items.isEmpty()) { return; } for (Object item: items) { if (!(item instanceof String)) { throw new ConfigException("Invalid type for admin listener (expected String)."); } if (((String) item).trim().isEmpty()) { throw new ConfigException("Empty listener found when parsing list."); } } }
Source:
<code>private List<SqlStageExecution> getStagesReadyForExecution() { return stream(forTree(StreamingPlanSection::getChildren).depthFirstPreOrder(sectionedPlan)) .filter(this::isReadyForExecution) .flatMap(section -> stream(forTree(SubPlan::getChildren).depthFirstPreOrder(section.getPlan()))) .map(SubPlan::getFragment) .map(PlanFragment::getId) .map(this::getFragmentExecution) <START> .collect(toImmutableList()); <END> }</code><technical_language>hmm.. need double check if works expected if child stage get CANCELLED / ABORTED / FAILED .. :) Update: ABORTED / FAILED a problem, query fail: <LINK_0></technical_language>

Target:
private List<SqlStageExecution> getStagesReadyForExecution() { return stream(forTree(StreamingPlanSection::getChildren).depthFirstPreOrder(sectionedPlan)) .filter(this::isReadyForExecution) .flatMap(section -> stream(forTree(StreamingSubPlan::getChildren).depthFirstPreOrder(section.getPlan()))) .map(StreamingSubPlan::getFragment) .map(PlanFragment::getId) .map(this::getStageExecution) .collect(toImmutableList()); }
Source:
<code>public static void main(String[] args) { if (args.length < 2) { System.out.println("Please specify your access key and a voice call flow ID"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Deleting a Voice Call Flow"); <START> VoiceCallFlow voiceCallFlow = messageBirdClient <END> .deleteVoiceCallFlow(args[1]); System.out.println("Voice call flow deleted "); } catch (GeneralException | UnauthorizedException exception) { exception.printStackTrace(); } }</code><technical_language>import VoiceCallFlow in here, delete unused NotFoundException import</technical_language>

Target:
public static void main(String[] args) { if (args.length < 2) { System.out.println("Please specify your access key and a voice call flow ID"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Deleting a Voice Call Flow"); messageBirdClient.deleteVoiceCallFlow(args[1]); System.out.println("Voice call flow deleted "); } catch (GeneralException | NotFoundException | UnauthorizedException exception) { exception.printStackTrace(); } }
Source:
<code>public void addPropertyListener(IPropertyListener listener) { for (AbstractJavaBreakpointEditor <START> fEditor : <END> fEditors) { fEditor.addPropertyListener(listener); } }</code><technical_language>rename editor locations</technical_language>

Target:
public void addPropertyListener(IPropertyListener listener) { for (AbstractJavaBreakpointEditor editor : fEditors) { editor.addPropertyListener(listener); } }
Source:
<code>private static boolean isOverrideExchange(ExchangeType exchange) { return null != exchange.getOrganizationList() && CollectionUtils.isNotEmpty(exchange.getOrganizationList().getOrganization()) <START> && StringUtils.isNotEmpty(exchange.getType()) && StringUtils.equalsIgnoreCase( <END> EXCHANGE_TYPE.OVERRIDES.toString(), exchange.getType()); }</code><technical_language>Optional: need do StringUtils.isNotEmpty(exchange.getType()) StringUtils.equalsIgnoreCase handle null if exchange.getType()=null</technical_language>

Target:
private static boolean isOverrideExchange(ExchangeType exchange) { return null != exchange.getOrganizationList() && CollectionUtils.isNotEmpty(exchange.getOrganizationList().getOrganization()) && StringUtils.equalsIgnoreCase(EXCHANGE_TYPE.OVERRIDES.toString(), exchange.getType()); }
Source:
<code>public void process(GeneratingRegion region) { <START> Border3D border = region.getBorderForFacet(BaseFacet.class).extendBy(0, 8, 4); <END> BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }</code><technical_language>do need extension? I removed tested abnormally large bases work</technical_language>

Target:
public void process(GeneratingRegion region) { Border3D border = region.getBorderForFacet(BaseFacet.class); BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }
Source:
<code>private boolean doVisitDelta(IResourceDelta delta) throws Exception { if (delta.getResource() instanceof IProject) { IProject project = (IProject) delta.getResource(); IPath fromPath = delta.getMovedFromPath(); IPath toPath = delta.getMovedToPath(); if (delta.getKind() == IResourceDelta.REMOVED) { if (fromPath == null && toPath == null) { CorePlugin.listenerRegistry().dispatch(new ProjectDeletedEvent(project)); } } else if (delta.getKind() == IResourceDelta.ADDED) { if (fromPath == null && toPath == null) { CorePlugin.listenerRegistry().dispatch(new ProjectCreatedEvent(project)); } else if (fromPath != null) { CorePlugin.listenerRegistry().dispatch(new ProjectMovedEvent(project, fromPath.lastSegment())); } } else if (delta.getFlags() == IResourceDelta.OPEN) { if (project.isOpen()) { CorePlugin.listenerRegistry().dispatch(new ProjectOpenedEvent(project)); <START> } else if (!project.isOpen()) { <END> CorePlugin.listenerRegistry().dispatch(new ProjectClosedEvent(project)); } } return false; } else { return delta.getResource() instanceof IWorkspaceRoot; } }</code><technical_language>a simple else</technical_language>

Target:
private boolean doVisitDelta(IResourceDelta delta) throws Exception { if (delta.getResource() instanceof IProject) { IProject project = (IProject) delta.getResource(); IPath fromPath = delta.getMovedFromPath(); IPath toPath = delta.getMovedToPath(); if (delta.getKind() == IResourceDelta.REMOVED) { if (fromPath == null && toPath == null) { CorePlugin.listenerRegistry().dispatch(new ProjectDeletedEvent(project)); } } else if (delta.getKind() == IResourceDelta.ADDED) { if (fromPath == null && toPath == null) { CorePlugin.listenerRegistry().dispatch(new ProjectCreatedEvent(project)); } else if (fromPath != null) { CorePlugin.listenerRegistry().dispatch(new ProjectMovedEvent(project, fromPath.lastSegment())); } } else if (delta.getFlags() == IResourceDelta.OPEN) { if (project.isOpen()) { CorePlugin.listenerRegistry().dispatch(new ProjectOpenedEvent(project)); } else { CorePlugin.listenerRegistry().dispatch(new ProjectClosedEvent(project)); } } return false; } else { return delta.getResource() instanceof IWorkspaceRoot; } }
Source:
<code><START> public static ExpectedCondition<WebElement> visibilityOfNestedElementsLocatedBy(final By locator, <END> final By sub_locator) { return new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver webDriver) { Boolean displayed = false; Boolean exists = false; try { exists = webDriver.findElement(locator).findElements(sub_locator).size() > 0; displayed = webDriver.findElement(locator).findElement(sub_locator).isDisplayed(); } catch (Exception e) { } return (exists && displayed) ? webDriver.findElement(locator).findElement(sub_locator) : null; } @Override public String toString() { return "visibility of element located by " + locator + sub_locator; } }; }</code><technical_language>for Nested methods change method signature this instead: (final locator, final ... sub_locators) method more like: WebElement element = webDriver.findElement(locator); for (By sub_locator in sub_locators) { element = element.findElement(sub_locator); } this put a private method (similar findElement(By, WebDriver))</technical_language>

Target:
public static ExpectedCondition<List<WebElement>> visibilityOfNestedElementsLocatedBy( final By locator, final By sub_locator) { return new ExpectedCondition<List<WebElement>>() { @Override public List<WebElement> apply(WebDriver webDriver) { Boolean displayed = false; Boolean exists = false; try { exists = webDriver.findElement(locator).findElements(sub_locator).size() > 0; displayed = webDriver.findElement(locator).findElement(sub_locator).isDisplayed(); } catch (Exception e) { int i = 0; } return (exists && displayed) ? webDriver.findElement(locator).findElements(sub_locator) : null; } @Override public String toString() { return "visibility of elements located by " + locator + sub_locator; } }; }
Source:
<code>private void removeFormNameFromLabel(Map<String, FormElement> formElementMap) { for (String key : formElementMap.keySet()) { FormElement element = formElementMap.get(key); String label = element.getLabel(); <START> element.setLabel(label.substring(label.substring(1).indexOf('/') + 1)); <END> } }</code><technical_language>reviewing find I conclussion this substring parsing belongs in some sort of FormUtils (or lines) class</technical_language>

Target:
private void removeFormNameFromLabel(Map<String, FormElement> formElementMap) { for (String key : formElementMap.keySet()) { FormElement element = formElementMap.get(key); String label = FormUtils.removeFormNameFromLabel(element.getLabel()); element.setLabel(label); } }
Source:
<code>protected Value<Boolean> constructValue(Boolean actualValue) { <START> return new SpongeValue<>(Keys.ENTITY_HAS_GRAVITY, actualValue); <END> }</code><technical_language>this.key (or this.usedKey, of fields - name escapes :P)</technical_language>

Target:
protected Value<Boolean> constructValue(Boolean actualValue) { return new SpongeValue<>(this.key, DataConstants.DEFAULT_HAS_GRAVITY, actualValue); }
Source:
<code>public void afterCheckProject(@NonNull Context context) { if (mLocation != null && !mIgnore) { <START> String message = "Potentially insecure random numbers on some versions of " <END> + "Android. Read " + BLOG_URL + " for more info."; context.report(ISSUE, mLocation, message, null); } }</code><technical_language>This more precise: Android 4.3 older</technical_language>

Target:
public void afterCheckProject(@NonNull Context context) { if (mLocation != null && !mIgnore) { String message = "Potentially insecure random numbers on Android 4.3 and older. " + "Read " + BLOG_URL + " for more info."; context.report(ISSUE, mLocation, message, null); } }
Source:
<code>public void cancelTask() { if (currentTask != null) { currentTask.cancel(false); <START> if (currentTask instanceof DataPullTask) { <END> ((DataPullTask)currentTask).abortRequest(); } } }</code><technical_language>refactored commcare task</technical_language>

Target:
public void cancelTask() { if (currentTask != null) { currentTask.cancel(false); currentTask.tryAbort(); } }
Source:
<code>public CloseableHttpResponse getResponse(HttpUriRequest target) throws IOException { CloseableHttpClient client = createClient(); boolean returningResponse = false; CloseableHttpResponse response = null; try { try { response = client.execute(target); } catch (HttpHostConnectException e) { throw new ServiceConnectionException(e); } StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (isErrorStatus(statusCode)) { URI targetUri = target.getURI(); String address = targetUri.getPath(); if (!Strings.isNullOrEmpty(targetUri.getQuery())) { address += "?" + targetUri.getQuery(); } if (statusCode == HttpStatus.NOT_FOUND.value()) { <START> throw new NotFoundException(address); <END> } else { String responseBody = IOUtils.toString(response.getEntity().getContent()); String message = String.format("Request to \"%s\" failed (%d): %s.", address, statusCode, statusLine.getReasonPhrase()); throw new ServiceRequestException(statusCode, message, responseBody); } } returningResponse = true; return response; } finally { if (!returningResponse && response != null) { response.close(); } } }</code><technical_language>more catch EntityNotFoundException wrap in NotFoundException up. This method is a low-level utility. called in places a not-found result is expected a result of user behavior, means want throw EntityNotFoundException in order halt error status. instead add a catch (EntityNotFoundException) block controller method(s) apply error reported in ticket</technical_language>

Target:
public CloseableHttpResponse getResponse(HttpUriRequest target) throws IOException { CloseableHttpClient client = createClient(); boolean returningResponse = false; CloseableHttpResponse response = null; try { try { response = client.execute(target); } catch (HttpHostConnectException e) { throw new ServiceConnectionException(e); } StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (isErrorStatus(statusCode)) { URI targetUri = target.getURI(); String address = targetUri.getPath(); if (!Strings.isNullOrEmpty(targetUri.getQuery())) { address += "?" + targetUri.getQuery(); } if (statusCode == HttpStatus.NOT_FOUND.value()) { throw new EntityNotFoundException(address); } else { String responseBody = IOUtils.toString(response.getEntity().getContent()); String message = String.format("Request to \"%s\" failed (%d): %s.", address, statusCode, statusLine.getReasonPhrase()); throw new ServiceRequestException(statusCode, message, responseBody); } } returningResponse = true; return response; } finally { if (!returningResponse && response != null) { response.close(); } } }
Source:
<code>public Schema generateSchema() { final Schema inputSchema = getChild().getSchema(); final List<String> outputColumnNames = new ArrayList<>(inputSchema.getColumnNames()); final String splitColumnName = outputColumnNames.get(splitColumnIndex); <START> final String splitResultsColumnName = splitColumnName + "_splits"; <END> outputColumnNames.set(splitColumnIndex, splitResultsColumnName); return Schema.of(inputSchema.getColumnTypes(), outputColumnNames); }</code><technical_language>name choice LGTM</technical_language>

Target:
public Schema generateSchema() { final Schema inputSchema = getChild().getSchema(); final String splitColumnName = inputSchema.getColumnNames().get(splitColumnIndex); final String splitResultsColumnName = splitColumnName + "_splits"; return Schema.appendColumn(inputSchema, Type.STRING_TYPE, splitResultsColumnName); }
Source:
<code>public ConvertIIFEArgsToVars(AbstractCompiler compiler) { this.compiler = compiler; <START> validIifes = new ArrayList(); <END> }</code><technical_language>validIifes is unused</technical_language>

Target:
public ConvertIIFEArgsToVars(AbstractCompiler compiler) { this.compiler = compiler; }
Source:
<code>List<ResourceRequest> getStarvedResourceRequests() { List<ResourceRequest> ret = new ArrayList<>(); Map<Priority, List<Resource>> visitedRRs= new HashMap<>(); Resource pending = getStarvation(); for (ResourceRequest rr : appSchedulingInfo.getAllResourceRequests()) { <START> if (Resources.isNone(pending)) { <END> break; } if (checkAndMarkRRVisited(visitedRRs, rr)) { continue; } int ratio = (int) Math.floor( Resources.ratio(scheduler.getResourceCalculator(), pending, rr.getCapability())); if (ratio == 0) { continue; } if (ratio < rr.getNumContainers()) { rr = ResourceRequest.newInstance( rr.getPriority(), rr.getResourceName(), rr.getCapability(), ratio); } ret.add(rr); Resources.subtractFromNonNegative(pending, Resources.multiply(rr.getCapability(), ratio)); } return ret; }</code><technical_language>is this check loop</technical_language>

Target:
List<ResourceRequest> getStarvedResourceRequests() { List<ResourceRequest> ret = new ArrayList<>(); VisitedResourceRequestTracker visitedRRs = new VisitedResourceRequestTracker(scheduler.getNodeTracker()); Resource pending = getStarvation(); for (ResourceRequest rr : appSchedulingInfo.getAllResourceRequests()) { if (Resources.isNone(pending)) { break; } if (!visitedRRs.visit(rr)) { continue; } int numContainersThatFit = (int) Math.floor( Resources.ratio(scheduler.getResourceCalculator(), pending, rr.getCapability())); if (numContainersThatFit == 0) { continue; } if (numContainersThatFit < rr.getNumContainers()) { rr = ResourceRequest.newInstance(rr.getPriority(), rr.getResourceName(), rr.getCapability(), numContainersThatFit); } ret.add(rr); Resources.subtractFromNonNegative(pending, Resources.multiply(rr.getCapability(), rr.getNumContainers())); } return ret; }
Source:
<code>private void fetch() throws IOException { if (output != null) { return; } outpuTupletList = scanner.getNextTupleRows(count); StringBuilder sb = new StringBuilder(); if (startOffset == 0) { Schema schema = this.scanner.getLogicalSchema(); List<Column> columns = schema.getAllColumns(); boolean first = true; for (Column column : columns) { <START> if (first == false) { <END> sb.append(","); } sb.append(StringEscapeUtils.escapeCsv(column.getSimpleName())); first = false; } sb.append("\r\n"); } for (Tuple tuple : outpuTupletList) { Datum[] datums = tuple.getValues(); int size = datums.length; for (int i = 0; i < size; i++) { if (i != 0) { sb.append(","); } Datum datum = datums[i]; sb.append(StringEscapeUtils.escapeCsv(datum.toString())); } sb.append("\r\n"); } output = sb.toString(); }</code><technical_language>This condition simplified !first</technical_language>

Target:
private void fetch() throws IOException { if (output != null) { return; } List<Tuple> outputTupletList = scanner.getNextTupleRows(count); size = outputTupletList.size(); StringBuilder sb = new StringBuilder(); if (startOffset == 0) { Schema schema = this.scanner.getLogicalSchema(); List<Column> columns = schema.getAllColumns(); boolean first = true; for (Column column : columns) { if (!first) { sb.append(","); } sb.append(StringEscapeUtils.escapeCsv(column.getSimpleName())); first = false; } sb.append("\r\n"); } for (Tuple tuple : outputTupletList) { Datum[] datums = tuple.getValues(); int size = datums.length; for (int i = 0; i < size; i++) { if (i != 0) { sb.append(","); } Datum datum = datums[i]; sb.append(StringEscapeUtils.escapeCsv(datum.toString())); } sb.append("\r\n"); } output = sb.toString(); }
Source:
<code><START> private void assertRewritten(String from, String to) <END> { assertEquals(rewrite(PlanBuilder.expression(from)), PlanBuilder.expression(to)); }</code><technical_language>put utility methods bottom</technical_language>

Target:
private static void assertRewritten(String from, String to) { assertEquals(CanonicalizeExpressionRewriter.rewrite(PlanBuilder.expression(from)), PlanBuilder.expression(to)); }
Source:
<code>public static AuthUI getInstance(@NonNull FirebaseApp app) { String releaseUrl = "<LINK_0>"; String devWarning = "Beginning with FirebaseUI 6.2.0 you no longer need to include %s to " + "sign in with %s. Go to %s for more information"; if (ProviderAvailability.IS_TWITTER_AVAILABLE) { Log.w(TAG, String.format(devWarning, "the TwitterKit SDK", "Twitter", releaseUrl)); } if (ProviderAvailability.IS_GITHUB_AVAILABLE) { <START> Log.w(TAG, String.format(devWarning, "auth-github", "GitHub", releaseUrl)); <END> } AuthUI authUi; synchronized (INSTANCES) { authUi = INSTANCES.get(app); if (authUi == null) { authUi = new AuthUI(app); INSTANCES.put(app, authUi); } } return authUi; }</code><technical_language>instead of "auth-github" "com.firebaseui:firebase-ui-auth-github"</technical_language>

Target:
public static AuthUI getInstance(@NonNull FirebaseApp app) { String releaseUrl = "<LINK_0>"; String devWarning = "Beginning with FirebaseUI 6.2.0 you no longer need to include %s to " + "sign in with %s. Go to %s for more information"; if (ProviderAvailability.IS_TWITTER_AVAILABLE) { Log.w(TAG, String.format(devWarning, "the TwitterKit SDK", "Twitter", releaseUrl)); } if (ProviderAvailability.IS_GITHUB_AVAILABLE) { Log.w(TAG, String.format(devWarning, "com.firebaseui:firebase-ui-auth-github", "GitHub", releaseUrl)); } AuthUI authUi; synchronized (INSTANCES) { authUi = INSTANCES.get(app); if (authUi == null) { authUi = new AuthUI(app); INSTANCES.put(app, authUi); } } return authUi; }
Source:
<code>public static void getExcel(OutputStream outputStream, long userId, Collection<Long> deviceIds, Collection<Long> groupIds, Date from, Date to) throws SQLException, IOException { Collection<SummaryReport> summaries = getObjects(userId, deviceIds, groupIds, from, to); String templatePath = Context.getConfig().getString("report.templatesPath", "templates/export/"); try (InputStream inputStream = new FileInputStream(templatePath + "/summary.xlsx")) { org.jxls.common.Context jxlsContext = PoiTransformer.createInitialContext(); jxlsContext.putVar("summaries", summaries); jxlsContext.putVar("from", from); jxlsContext.putVar("to", to); jxlsContext.putVar("distanceUnit", ReportUtils.getDistanceUnit(userId)); jxlsContext.putVar("speedUnit", ReportUtils.getSpeedUnit(userId)); jxlsContext.putVar("webUrl", Context.getVelocityEngine().getProperty("web.url")); jxlsContext.putVar("dateTool", new DateTool()); jxlsContext.putVar("timezone", ReportUtils.getTimezone(userId)); <START> jxlsContext.putVar("locale", Locale.getDefault()); <END> JxlsHelper.getInstance().setUseFastFormulaProcessor(false) .processTemplate(inputStream, outputStream, jxlsContext); } }</code><technical_language>Is share context initialization code? growing, nice remove some code duplication</technical_language>

Target:
public static void getExcel(OutputStream outputStream, long userId, Collection<Long> deviceIds, Collection<Long> groupIds, Date from, Date to) throws SQLException, IOException { Collection<SummaryReport> summaries = getObjects(userId, deviceIds, groupIds, from, to); String templatePath = Context.getConfig().getString("report.templatesPath", "templates/export/"); try (InputStream inputStream = new FileInputStream(templatePath + "/summary.xlsx")) { org.jxls.common.Context jxlsContext = ReportUtils.initializeContext(userId); jxlsContext.putVar("summaries", summaries); jxlsContext.putVar("from", from); jxlsContext.putVar("to", to); JxlsHelper.getInstance().setUseFastFormulaProcessor(false) .processTemplate(inputStream, outputStream, jxlsContext); } }
Source:
<code>public String toData() { if (url != null) { return url; } try { JSONObject jsonObject = new JSONObject(); if (groupId > 0) { jsonObject.put("groupId", groupId); } <START> if (!uuid.equals(EMPTY_STRING)) { <END> jsonObject.put("uuid", uuid); } if (!title.equals(EMPTY_STRING)) { jsonObject.put("title", title); } if (!version.equals(EMPTY_STRING)) { jsonObject.put("version", version); } return jsonObject.toString(); } catch (JSONException ex) { return null; } }</code><technical_language>If source formatter I invert condition</technical_language>

Target:
public String toData() { if (url != null) { return url; } try { JSONObject jsonObject = new JSONObject(); if (groupId > 0) { jsonObject.put("groupId", groupId); } if (!EMPTY_STRING.equals(uuid)) { jsonObject.put("uuid", uuid); } if (!EMPTY_STRING.equals(title)) { jsonObject.put("title", title); } if (!EMPTY_STRING.equals(version)) { jsonObject.put("version", version); } return jsonObject.toString(); } catch (JSONException ex) { return null; } }
Source:
<code>void adaptTypedFilterTo( FilterContext context, ColumnRangeFilter filter, OutputStream outputStream) throws IOException { byte lowerBoundMarker = (byte) (filter.getMinColumnInclusive() ? '[' : '('); byte upperBoundMarker = (byte) (filter.getMaxColumnInclusive() ? ']' : ')'); try (ReaderExpressionScope scope = new ReaderExpressionScope(outputStream, "(col(", "))")) { outputStream.write(lowerBoundMarker); <START> outputStream.write(getSingleFamily(context.getScan())); <END> outputStream.write(BigtableConstants.BIGTABLE_COLUMN_SEPARATOR_BYTE); helper.writeQuotedExpression(filter.getMinColumn(), outputStream); outputStream.write((byte) ','); outputStream.write(getSingleFamily(context.getScan())); outputStream.write(BigtableConstants.BIGTABLE_COLUMN_SEPARATOR_BYTE); helper.writeQuotedExpression(filter.getMaxColumn(), outputStream); outputStream.write(upperBoundMarker); outputStream.write((byte)','); outputStream.write(ReaderExpressionHelper.ALL_VERSIONS_BYTES); } }</code><technical_language>Is worth keeping single family instead of a time</technical_language>

Target:
void adaptTypedFilterTo( FilterContext context, ColumnRangeFilter filter, OutputStream outputStream) throws IOException { byte lowerBoundMarker = (byte) (filter.getMinColumnInclusive() ? '[' : '('); byte upperBoundMarker = (byte) (filter.getMaxColumnInclusive() ? ']' : ')'); byte[] family = getSingleFamily(context.getScan()); try (ReaderExpressionScope scope = new ReaderExpressionScope(outputStream, "(col(", "))")) { outputStream.write(lowerBoundMarker); outputStream.write(family); outputStream.write(BigtableConstants.BIGTABLE_COLUMN_SEPARATOR_BYTE); helper.writeQuotedExpression(filter.getMinColumn(), outputStream); outputStream.write((byte) ','); outputStream.write(family); outputStream.write(BigtableConstants.BIGTABLE_COLUMN_SEPARATOR_BYTE); helper.writeQuotedExpression(filter.getMaxColumn(), outputStream); outputStream.write(upperBoundMarker); outputStream.write((byte)','); outputStream.write(ReaderExpressionHelper.ALL_VERSIONS_BYTES); } }
Source:
<code><START> public String getVersion() { <END> return version; }</code><technical_language>public modifier version field represents reference's implementation details. I doubt consumers interested in it. I leave private (or remove it) is a real usecase requires access value. Making private hard (due API breakage), public problems</technical_language>

Target:
String getVersion() { return version; }
Source:
<code><START> public void createUnivocityParser() <END> { List<FixedWidthSchema.Field> fields = schema.getFields(); FixedWidthFields fieldWidth = new FixedWidthFields(); for (int i = 0; i < fields.size(); i++) { FixedWidthSchema.Field currentField = fields.get(i); int fieldLength = currentField.getFieldLength(); FieldAlignment currentFieldAlignment; if (currentField.getAlignment().equalsIgnoreCase("centre")) { currentFieldAlignment = FieldAlignment.CENTER; } else if (currentField.getAlignment().equalsIgnoreCase("left")) { currentFieldAlignment = FieldAlignment.LEFT; } else { currentFieldAlignment = FieldAlignment.RIGHT; } fieldWidth.addField(currentField.getName(), fieldLength, currentFieldAlignment, currentField.getPadding()); } FixedWidthParserSettings settings = new FixedWidthParserSettings(fieldWidth); univocityParser = new com.univocity.parsers.fixed.FixedWidthParser(settings); }</code><technical_language>Access of this method private</technical_language>

Target:
private void createUnivocityParser() { List<FixedWidthSchema.Field> fields = schema.getFields(); FixedWidthFields fieldWidthFields = new FixedWidthFields(); for (int i = 0; i < fields.size(); i++) { FixedWidthSchema.Field currentField = fields.get(i); int fieldLength = currentField.getFieldLength(); FieldAlignment currentFieldAlignment; if (currentField.getAlignment().equalsIgnoreCase("centre")) { currentFieldAlignment = FieldAlignment.CENTER; } else if (currentField.getAlignment().equalsIgnoreCase("left")) { currentFieldAlignment = FieldAlignment.LEFT; } else { currentFieldAlignment = FieldAlignment.RIGHT; } fieldWidthFields.addField(currentField.getName(), fieldLength, currentFieldAlignment, currentField.getPadding()); } FixedWidthParserSettings settings = new FixedWidthParserSettings(fieldWidthFields); univocityParser = new com.univocity.parsers.fixed.FixedWidthParser(settings); }
Source:
<code>public KeyStoreCredentialProvider(final KeyStore keyStore, final String keyStoreAlias, String keyStoreType, final Resource keyStoreResource, final String keyStorePath, final String storePasswd, final String privateKeyPasswd) { CommonHelper.assertTrue(keyStore != null || keyStoreResource != null || CommonHelper.isNotBlank(keyStorePath), "Either keyStore, keyStoreResource or keyStorePath must be provided"); final KeyStore keyStoreToUse; if (keyStore != null) { keyStoreToUse = keyStore; } else { final InputStream inputStream; if (keyStoreResource != null) { try { <START> inputStream = keyStoreResource.getInputStream(); <END> } catch (IOException e) { throw new TechnicalException(e); } } else { inputStream = CommonHelper.getInputStreamFromName(keyStorePath); } keyStoreToUse = loadKeyStore(inputStream, storePasswd, keyStoreType); } this.privateKey = getPrivateKeyAlias(keyStoreToUse, keyStoreAlias); final Map<String, String> passwords = new HashMap<String, String>(); passwords.put(this.privateKey, privateKeyPasswd); this.credentialResolver = new KeyStoreCredentialResolver(keyStoreToUse, passwords); }</code><technical_language>I this stream is closed..</technical_language>

Target:
public KeyStoreCredentialProvider(final KeyStore keyStore, final String keyStoreAlias, String keyStoreType, final Resource keyStoreResource, final String keyStorePath, final String storePasswd, final String privateKeyPasswd) { CommonHelper.assertTrue(keyStore != null || keyStoreResource != null || CommonHelper.isNotBlank(keyStorePath), "Either keyStore, keyStoreResource or keyStorePath must be provided"); final KeyStore keyStoreToUse; if (keyStore != null) { keyStoreToUse = keyStore; } else { InputStream inputStream = null; try { if (keyStoreResource != null) { inputStream = keyStoreResource.getInputStream(); } else { inputStream = CommonHelper.getInputStreamFromName(keyStorePath); } keyStoreToUse = loadKeyStore(inputStream, storePasswd, keyStoreType); } catch (IOException e) { throw new SAMLException("Error loading keystore", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (final IOException e) { this.logger.debug("Error closing input stream of keystore", e); } } } } this.privateKey = getPrivateKeyAlias(keyStoreToUse, keyStoreAlias); final Map<String, String> passwords = new HashMap<String, String>(); passwords.put(this.privateKey, privateKeyPasswd); this.credentialResolver = new KeyStoreCredentialResolver(keyStoreToUse, passwords); }
Source:
<code>protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); Assumption.assertNotNull(feedbackSessionName); List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(account.googleId); Assumption.assertNotNull(instructors); InstructorFeedbackEditCopyPageData data = new InstructorFeedbackEditCopyPageData(account, new ArrayList<CourseAttributes>(), courseId, feedbackSessionName); List<CourseAttributes> courses = logic.getCoursesForInstructor(account.googleId); for (CourseAttributes course : courses) { InstructorAttributes instructor = logic.getInstructorForGoogleId(course.id, account.googleId); boolean isAllowedToMakeSession = instructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); boolean isArchived = Logic.isCourseArchived(course.id, account.googleId); if (!isArchived && isAllowedToMakeSession) { data.getCourses().add(course); } } <START> CourseAttributes.sortByCreatedDate(data.getCourses()); <END> return createShowPageResult(Const.ViewURIs.INSTRUCTOR_FEEDBACK_COPY_MODAL, data); }</code><technical_language>do processing courses needs in this method passing constructor for InstructorFeedbackEditCopyPageData</technical_language>

Target:
protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); Assumption.assertNotNull(feedbackSessionName); List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(account.googleId); Assumption.assertNotNull(instructors); List<CourseAttributes> allCourses = logic.getCoursesForInstructor(account.googleId); List<CourseAttributes> coursesToAddToData = new ArrayList<CourseAttributes>(); for (CourseAttributes course : allCourses) { InstructorAttributes instructor = logic.getInstructorForGoogleId(course.id, account.googleId); boolean isAllowedToMakeSession = instructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); boolean isArchived = Logic.isCourseArchived(course.id, account.googleId); if (!isArchived && isAllowedToMakeSession) { coursesToAddToData.add(course); } } CourseAttributes.sortByCreatedDate(coursesToAddToData); InstructorFeedbackEditCopyPageData data = new InstructorFeedbackEditCopyPageData(account, coursesToAddToData, courseId, feedbackSessionName); return createShowPageResult(Const.ViewURIs.INSTRUCTOR_FEEDBACK_COPY_MODAL, data); }
Source:
<code>private boolean processEvent(UpdatableProcessInstance instance, String stepId, State state) throws WorkflowException { UpdatableHistoryStep step = (UpdatableHistoryStep) instance.getHistoryStep(stepId); instance.updateHistoryStep(step); if (event.getDataRecord() != null) { instance.saveActionRecord(step, event.getDataRecord()); } <START> state = (state != null) ? state : new StateImpl(""); <END> instance.addWorkingUser(step.getUser(), state, step.getUserRoleName()); instance.unLock(); step.setActionStatus(3); return false; }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Introduce a new variable instead of reusing parameter "state". [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private boolean processEvent(UpdatableProcessInstance instance, String stepId, State state) throws WorkflowException { UpdatableHistoryStep step = (UpdatableHistoryStep) instance.getHistoryStep(stepId); instance.updateHistoryStep(step); if (event.getDataRecord() != null) { instance.saveActionRecord(step, event.getDataRecord()); } instance.addWorkingUser(step.getUser(), state, step.getUserRoleName()); instance.unLock(); step.setActionStatus(UpdatableHistoryStep.ACTION_STATUS_SAVED); return false; }
Source:
<code>private boolean decideWhetherToLogAllPriorities() { <START> ZonedDateTime now = ZonedDateTime.now(); <END> boolean shouldLog = Duration.between(lastLogTime, now).compareTo(Duration.of(10, ChronoUnit.MINUTES)) > 0; if (shouldLog) { lastLogTime = now; } return shouldLog; }</code><technical_language>a rate-limiter 1 permit/(10 minutes) 0.1 permit/minute</technical_language>

Target:
private boolean decideWhetherToLogAllPriorities() { return loggingRateLimiter.tryAcquire(); }
Source:
<code>public Node<View<Import>, ?> nodeFromDMN(org.kie.dmn.model.v1_1.Import source) { String name = source.getAdditionalAttributes().get(droolsName); String identifier = name != null ? name : source.getNamespace() + source.getLocationURI(); Node<View<Import>, ?> node = new NodeImpl<>(identifier); node.setContent(new ViewImpl<>(null, null)); LocationURI locationURI = new LocationURI(source.getLocationURI()); node.getContent().setDefinition(new Import(source.getNamespace(), locationURI, source.getImportType())); Map<QName, String> additionalAttributes = new HashMap<>(); for (Map.Entry<javax.xml.namespace.QName, String> entry : source.getAdditionalAttributes().entrySet()) { additionalAttributes.put(QNamePropertyConverter.wbFromDMN(entry.getKey()), entry.getValue()); } <START> node.getContent().getDefinition().setAdditionalAttributes(additionalAttributes); <END> return node; }</code><technical_language>/cc @manstis kindly advise, this PR discussion, UI/authoring functionality if DMN Import element needs converted _its node_, is sufficient for Definitions' "main" node graph, please</technical_language>

Target:
public static Import nodeFromDMN(org.kie.dmn.model.v1_1.Import source) { LocationURI locationURI = new LocationURI(source.getLocationURI()); Import result = new Import(source.getNamespace(), locationURI, source.getImportType()); Map<QName, String> additionalAttributes = new HashMap<>(); for (Map.Entry<javax.xml.namespace.QName, String> entry : source.getAdditionalAttributes().entrySet()) { additionalAttributes.put(QNamePropertyConverter.wbFromDMN(entry.getKey()), entry.getValue()); } result.setAdditionalAttributes(additionalAttributes); return result; }
Source:
<code>private void processMemberListQuery(IQ packet) { MUCRole roleToUseHere = server.getChatRoom(packet.getTo().getNode()).getRole(); try { roleToUseHere.getChatRoom().getIQAdminHandler().handleIQ(packet, roleToUseHere); } catch ( ForbiddenException e ) { Log.debug("Unable to process IQ stanza: sender don't have authorization to perform the request.", e); sendErrorPacket(packet, PacketError.Condition.forbidden, "You don't have authorization to perform this request."); } catch ( ConflictException e ) { Log.debug("Unable to process IQ stanza: processing this request would leave the room in an invalid state (eg: without owners).", e); <START> sendErrorPacket(packet, PacketError.Condition.conflict, "Processing this request would leave the room in an invalid state (eg: without owners)."); <END> } catch ( NotAllowedException e ) { Log.debug("Unable to process IQ stanza: an owner or administrator cannot be banned from the room.", e); sendErrorPacket(packet, PacketError.Condition.not_allowed, "An owner or administrator cannot be banned from the room."); } catch ( CannotBeInvitedException e ) { Log.debug("Unable to process IQ stanza: user being invited as a result of being added to a members-only room still does not have permission.", e); sendErrorPacket(packet, PacketError.Condition.not_acceptable, "User being invited as a result of being added to a members-only room still does not have permission."); } catch ( Exception e ) { Log.error("An unexpected exception occurred while processing IQ stanza: {}", packet.toXML(), e); sendErrorPacket(packet, PacketError.Condition.internal_server_error, "An unexpected exception occurred while processing your request."); } }</code><technical_language>This error message sense in context of processing a request for a member list</technical_language>

Target:
private void processMemberListQuery(IQ packet) { MUCRole roleToUseHere = server.getChatRoom(packet.getTo().getNode()).getRole(); try { roleToUseHere.getChatRoom().getIQAdminHandler().handleIQ(packet, roleToUseHere); } catch ( ForbiddenException e ) { Log.debug("Unable to process IQ stanza: sender don't have authorization to perform the request.", e); sendErrorPacket(packet, PacketError.Condition.forbidden, "You don't have authorization to perform this request."); } catch ( ConflictException e ) { Log.debug("Unable to process IQ stanza: There was a conflict while handle the memberlist request.", e); sendErrorPacket(packet, PacketError.Condition.conflict, "There was a conflict while handle the memberlist request."); } catch ( NotAllowedException e ) { Log.debug("Unable to process IQ stanza: The user is not allowed to retrieve memberlist.", e); sendErrorPacket(packet, PacketError.Condition.not_allowed, "The user is not allowed to retrieve memberlist."); } catch ( Exception e ) { Log.error("An unexpected exception occurred while processing IQ stanza: {}", packet.toXML(), e); sendErrorPacket(packet, PacketError.Condition.internal_server_error, "An unexpected exception occurred while processing your request."); } }
Source:
<code>protected void openConnection() { if (this.thing.getStatus().equals(ThingStatus.OFFLINE)) { try { if (senderNode.getAddress() == null) { if (senderNode.getPort() == 0) { socket = new DatagramSocket(); senderNode.setInetAddress(socket.getLocalAddress()); senderNode.setPort(socket.getLocalPort()); } else { socket = new DatagramSocket(senderNode.getPort()); senderNode.setInetAddress(socket.getLocalAddress()); } } else { socket = new DatagramSocket(senderNode.getPort(), senderNode.getAddress()); } updateStatus(ThingStatus.ONLINE); logger.debug("opened socket in bridge {}", senderNode, this.thing.getUID()); } catch (SocketException e) { <START> logger.warn("could not open socket in bridge {}", senderNode, this.thing.getUID()); <END> updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR); } } }</code><technical_language>reduce debug</technical_language>

Target:
protected void openConnection() { if (!this.thing.getStatus().equals(ThingStatus.ONLINE)) { try { if (senderNode.getAddress() == null) { if (senderNode.getPort() == 0) { socket = new DatagramSocket(); senderNode.setInetAddress(socket.getLocalAddress()); senderNode.setPort(socket.getLocalPort()); } else { socket = new DatagramSocket(senderNode.getPort()); senderNode.setInetAddress(socket.getLocalAddress()); } } else { socket = new DatagramSocket(senderNode.getPort(), senderNode.getAddress()); } updateStatus(ThingStatus.ONLINE); logger.debug("opened socket in bridge {}", senderNode, this.thing.getUID()); } catch (SocketException e) { logger.debug("could not open socket in bridge {}", senderNode, this.thing.getUID()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "opening UDP socket failed"); } } }