auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<Reference> parseArticleReferences(InputStream xml) throws ParserConfigurationException, IOException, SAXException, XmlContentException { Objects.requireNonNull(xml); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xml); doc.getDocumentElement().normalize(); List<Reference> references = new ArrayList<>(); List<Node> refListNodes = NodeListAdapter.wrap(doc.getElementsByTagName("ref-list")); if (ParseXmlUtil.isNullOrEmpty(refListNodes)) { log.info("No <ref-list> element was found in the xml."); return references; } <START> if (refListNodes.size() > 1) { <END> throw new XmlContentException("More than one <ref-list> element was found in the xml."); } Node refListNode = refListNodes.get(0); if (refListNode.getNodeType() != Node.ELEMENT_NODE) { throw new XmlContentException("<ref-list> is not an element."); } Element refListElement = (Element) refListNode; List<Node> refNodes = NodeListAdapter.wrap(refListElement.getElementsByTagName("ref")); references = refNodes.stream() .map(ref -> { try { return parseReferenceService.buildReferences((Element) ref); } catch (XMLParseException e) { throw new RuntimeException(e); } }) .flatMap(r -> r.stream()).collect(Collectors.toList()); return references; }</code><technical_language>combine this if statement else if improve clarity</technical_language>

Target:
public List<Reference> parseArticleReferences(InputStream xml) throws IOException { Objects.requireNonNull(xml); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc; try { DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(xml); } catch (ParserConfigurationException | SAXException e) { throw new RuntimeException(e); } doc.getDocumentElement().normalize(); List<Reference> references = new ArrayList<>(); List<Node> refListNodes = NodeListAdapter.wrap(doc.getElementsByTagName("ref-list")); if (ParseXmlUtil.isNullOrEmpty(refListNodes)) { log.info("No <ref-list> element was found in the xml."); return references; } if (refListNodes.size() > 1) { throw new XmlContentException("More than one <ref-list> element was found in the xml."); } Node refListNode = refListNodes.get(0); if (refListNode.getNodeType() != Node.ELEMENT_NODE) { throw new XmlContentException("<ref-list> is not an element."); } Element refListElement = (Element) refListNode; List<Node> refNodes = NodeListAdapter.wrap(refListElement.getElementsByTagName("ref")); references = refNodes.stream() .map(ref -> { try { return parseReferenceService.buildReferences((Element) ref); } catch (XMLParseException e) { throw new RuntimeException(e); } }) .flatMap(r -> r.stream()).collect(Collectors.toList()); return references; }
Source:
<code>public Integer resolveLocationId(PL pl) throws HL7Exception { String pointOfCare = pl.getPointOfCare().getValue(); String facility = pl.getFacility().getUniversalID().getValue(); try { Integer locationId = Integer.valueOf(pointOfCare); if (locationId == null) throw new Exception(); return locationId; <START> } <END> }</code><technical_language>extra closing bracket there(line 545)</technical_language>

Target:
public Integer resolveLocationId(PL pl) throws HL7Exception { String pointOfCare = pl.getPointOfCare().getValue(); String facility = pl.getFacility().getUniversalID().getValue(); try { Integer locationId = Integer.valueOf(pointOfCare); if (locationId == null) throw new Exception(); return locationId; } catch (Exception ex) { if (facility == null) { throw new HL7Exception("Error trying to treat PL.pointOfCare '" + pointOfCare + "' as a location.location_id", ex); } } try { Location l = Context.getLocationService().getLocation(facility); if (l == null) { log.debug("Couldn't find a location named '" + facility + "'"); } return l == null ? null : l.getLocationId(); } catch (Exception ex) { log.error("Error trying to treat PL.facility '" + facility + "' as a location.name", ex); return null; } }
Source:
<code>public void testSortMilestone1() { List<TurboIssue> issues = testModel.getIssues(); TurboIssue issue6 = new TurboIssue("testrepo/testrepo", 6, "Issue6"); TurboIssue issue7 = new TurboIssue("testrepo/testrepo", 7, "Issue7"); issue7.setMilestone(testModel.getMilestones().get(3)); issues.add(issue6); issues.add(issue7); Comparator<TurboIssue> comparator = getComparatorForSortQualifier("sort:milestone,id"); Collections.shuffle(issues); Collections.sort(issues, comparator); assertEquals("[#3 Issue3, #2 Issue2, #1 Issue1, #4 Issue4, #7 Issue7, #5 Issue5, #6 Issue6]", <START> issues.toString()); <END> }</code><technical_language>compare ids instead (issues.map(getId) Arrays.asList(1, 2, 3))? rely TurboIssue::toString</technical_language>

Target:
public void testSortMilestone1() { List<TurboIssue> issues = testModel.getIssues(); TurboIssue issue6 = new TurboIssue("testrepo/testrepo", 6, "Issue6"); TurboIssue issue7 = new TurboIssue("testrepo/testrepo", 7, "Issue7"); issue7.setMilestone(testModel.getMilestones().get(3)); issues.add(issue6); issues.add(issue7); Comparator<TurboIssue> comparator = getComparatorForSortQualifier("sort:milestone,id"); Collections.shuffle(issues); Collections.sort(issues, comparator); List<Integer> expected = Arrays.asList(3, 2, 1, 4, 7, 5, 6); List<Integer> actual = issues.stream().map(TurboIssue::getId).collect(Collectors.toList()); assertEquals(expected, actual); }
Source:
<code>public void testMultiBlock_readPastEnd() throws IOException { byte[] uncompressedData = new byte[16 * BLOCK_SIZE]; fillWithCompressibleData(uncompressedData); initializeStreams(uncompressedData); byte[] decompressedData = new byte[17 * BLOCK_SIZE]; int bytesRead = ByteStreams.read(decompressingStream, decompressedData, 0, decompressedData.length); assertEquals(uncompressedData.length, bytesRead); <START> assertArrayEquals(uncompressedData, Arrays.copyOf(decompressedData, bytesRead)); <END> }</code><technical_language>instead of arrayEquals, assertArrayEquals other JUnit asserts, please AssertJ's assertThat methods? Leads perf. assertThat(decompressedData).startsWith(uncompressedData) possible</technical_language>

Target:
public void testMultiBlock_readPastEnd() throws Exception { byte[] uncompressedData = new byte[16 * BLOCK_SIZE]; fillWithCompressibleData(uncompressedData); initializeStreams(uncompressedData); byte[] decompressedData = new byte[17 * BLOCK_SIZE]; int bytesRead = ByteStreams.read(decompressingStream, decompressedData, 0, decompressedData.length); assertEquals(uncompressedData.length, bytesRead); assertArrayEquals(uncompressedData, Arrays.copyOf(decompressedData, bytesRead)); }
Source:
<code>protected void eventHandle(@NonNull ITmfEvent event) { String name = event.getName(); long inc; if (name.equals(fLayout.eventKmemPageAlloc())) { inc = PAGE_SIZE; } else if (name.equals(fLayout.eventKmemPageFree())) { inc = -PAGE_SIZE; } else { return; } try { ITmfStateSystemBuilder ss = checkNotNull(getStateSystemBuilder()); long ts = event.getTimestamp().getValue(); Integer tidField = KernelTidAspect.INSTANCE.resolve(event); String tid; if (tidField == null) { <START> tid = "other"; END> } else { tid = tidField.toString(); } int tidQuark = ss.getQuarkAbsoluteAndAdd(tid); StateSystemBuilderUtils.incrementAttributeLong(ss, ts, tidQuark, inc); long currentMemoryValue = ss.queryOngoingState(tidQuark).unboxLong(); int lowestMemoryQuark = ss.getQuarkRelativeAndAdd(tidQuark, KernelMemoryAnalysisModule.THREAD_LOWEST_MEMORY_VALUE); ITmfStateValue lowestMemoryValue = ss.queryOngoingState(lowestMemoryQuark); long previousLowest = lowestMemoryValue.isNull() ? 0 : lowestMemoryValue.unboxLong(); if (previousLowest > currentMemoryValue) { ss.modifyAttribute(ts, TmfStateValue.newValueLong(currentMemoryValue), lowestMemoryQuark); } } catch (AttributeNotFoundException e) { Activator.getDefault().logError(e.getMessage(), e); } }</code><technical_language>magic? extract constant</technical_language>

Target:
protected void eventHandle(@NonNull ITmfEvent event) { String name = event.getName(); long inc; if (name.equals(fLayout.eventKmemPageAlloc())) { inc = PAGE_SIZE; } else if (name.equals(fLayout.eventKmemPageFree())) { inc = -PAGE_SIZE; } else { return; } try { ITmfStateSystemBuilder ss = checkNotNull(getStateSystemBuilder()); long ts = event.getTimestamp().getValue(); Integer tidField = KernelTidAspect.INSTANCE.resolve(event); String tid; if (tidField == null) { tid = OTHER_TID; } else { tid = tidField.toString(); } int tidQuark = ss.getQuarkAbsoluteAndAdd(tid); StateSystemBuilderUtils.incrementAttributeLong(ss, ts, tidQuark, inc); long currentMemoryValue = ss.queryOngoingState(tidQuark).unboxLong(); int lowestMemoryQuark = ss.getQuarkRelativeAndAdd(tidQuark, KernelMemoryAnalysisModule.THREAD_LOWEST_MEMORY_VALUE); ITmfStateValue lowestMemoryValue = ss.queryOngoingState(lowestMemoryQuark); long previousLowest = lowestMemoryValue.isNull() ? 0 : lowestMemoryValue.unboxLong(); if (previousLowest > currentMemoryValue) { ss.modifyAttribute(ts, TmfStateValue.newValueLong(currentMemoryValue), lowestMemoryQuark); } } catch (AttributeNotFoundException e) { Activator.getDefault().logError(e.getMessage(), e); } }
Source:
<code>public void setMapType(MapType type) { String webType; <START> if (type == MapType.MAP_TYPE_NORMAL) { <END> webType = "Normal"; } else if (type == MapType.MAP_TYPE_SATELLITE) { webType = "Satellite"; } else if (type == MapType.MAP_TYPE_TERRAIN) { webType = "Terrain"; } else { webType = "Normal"; } webView.loadUrl(String.format(Locale.US, "javascript:setMapTypeId('%1$s');", webType)); }</code><technical_language>get rid of this if fall else a switch</technical_language>

Target:
public void setMapType(MapType type) { String webType = null; switch (type) { case MAP_TYPE_NORMAL: webType = "Normal"; break; case MAP_TYPE_SATELLITE: webType = "Satellite"; break; case MAP_TYPE_TERRAIN: webType = "Terrain"; break; } webView.loadUrl(String.format(Locale.US, "javascript:setMapTypeId('%1$s');", webType)); }
Source:
<code>private RowExpression rewrite(RowExpression expression, ConnectorSession session) { <START> RowExpression optimized = optimizer.optimize(expression, SERIALIZABLE, session); <END> if (optimized instanceof ConstantExpression || !BooleanType.BOOLEAN.equals(optimized.getType())) { return optimized; } return RowExpressionTreeRewriter.rewriteWith(logicalExpressionRewriter, optimized, true); }</code><technical_language>nit: optimizedRowExpression. optimized for boolean variable</technical_language>

Target:
private RowExpression rewrite(RowExpression expression, ConnectorSession session) { RowExpression optimizedRowExpression = optimizer.optimize(expression, SERIALIZABLE, session); if (optimizedRowExpression instanceof ConstantExpression || !BooleanType.BOOLEAN.equals(optimizedRowExpression.getType())) { return optimizedRowExpression; } return RowExpressionTreeRewriter.rewriteWith(logicalExpressionRewriter, optimizedRowExpression, true); }
Source:
<code>public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort, Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> ipRanges, Iterable<String> groupIds, SecurityGroup group) { String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation()); String name = group.getName(); String id = Iterables.get(client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, name), 0).getId(); IpPermission.Builder builder = IpPermission.builder(); builder.ipProtocol(protocol); builder.fromPort(startPort); builder.toPort(endPort); if (Iterables.size(ipRanges) > 0) { for (String cidr : ipRanges) { builder.cidrBlock(cidr); } } if (tenantIdGroupNamePairs.size() > 0) { for (String userId : tenantIdGroupNamePairs.keySet()) { for (String groupName : tenantIdGroupNamePairs.get(userId)) { builder.tenantIdGroupNamePair(userId, groupName); } } } <START> <END> client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, id, builder.build()); return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode()); }</code><technical_language>[trivial] Remove blank line added</technical_language>

Target:
public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort, Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> ipRanges, Iterable<String> groupIds, SecurityGroup group) { String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation()); String name = group.getName(); String id = groupNameToId.apply(new RegionAndName(region, name).slashEncode()); IpPermission.Builder builder = IpPermission.builder(); builder.ipProtocol(protocol); builder.fromPort(startPort); builder.toPort(endPort); if (Iterables.size(ipRanges) > 0) { for (String cidr : ipRanges) { builder.cidrBlock(cidr); } } if (tenantIdGroupNamePairs.size() > 0) { for (String userId : tenantIdGroupNamePairs.keySet()) { for (String groupName : tenantIdGroupNamePairs.get(userId)) { builder.tenantIdGroupNamePair(userId, groupName); } } } client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, id, builder.build()); return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode()); }
Source:
<code>public Context currentContext() { <START> return context; <END> }</code><technical_language>standard convention is prefix this for instance members - return this.context</technical_language>

Target:
public Context currentContext() { return this.context; }
Source:
<code>public int getPort() { checkNotNull(server); <START> return server.getListenAddress().getPort(); <END> }</code><technical_language>reason this return port</technical_language>

Target:
public int getPort() { verifyServerState(); return server.getListenAddress().getPort(); }
Source:
<code>public List<Suggestion> enhanceResults(List<Suggestion> results, String query) { <START> LinkedList<Suggestion> enhanced = new LinkedList<>(results); <END> LiteralSuggestion literal = getMgrsSuggestion(query); if (literal != null && literal.hasGeo()) { enhanced.addFirst(literal); } return enhanced; }</code><technical_language>list left side; a linked list</technical_language>

Target:
public void enhanceResults(List<Suggestion> results, String query) { final LiteralSuggestion literal = getMgrsSuggestion(query); if (literal != null && literal.hasGeo()) { LOGGER.trace("Adding the MGRS suggestion to results [{}]", literal); results.add(0, literal); } }
Source:
<code>private void copyComment(TaggedValuePointable tvp, NodeTreePointable ntp, IMutableValueStorage mvs) throws IOException { <START> CommentNodeBuilder cnb = new CommentNodeBuilder(); <END> VoidPointable vp = ppool.takeOne(VoidPointable.class); TextOrCommentNodePointable tcnp = ppool.takeOne(TextOrCommentNodePointable.class); tvp.getValue(tcnp); tcnp.getValue(ntp, vp); cnb.reset(mvs); cnb.setValue(vp); ppool.giveBack(vp); ppool.giveBack(tcnp); }</code><technical_language>builder a class level variable</technical_language>

Target:
private void copyComment(TaggedValuePointable tvp, NodeTreePointable ntp, IMutableValueStorage mvs) throws IOException { VoidPointable vp = ppool.takeOne(VoidPointable.class); TextOrCommentNodePointable tcnp = ppool.takeOne(TextOrCommentNodePointable.class); tvp.getValue(tcnp); tcnp.getValue(ntp, vp); cnb.reset(mvs); cnb.setValue(vp); ppool.giveBack(vp); ppool.giveBack(tcnp); }
Source:
<code>private int evictExpiredInternal(int maxIterationCount, long now) { initExpirationIterator(); int processedCount = 0; LinkedList<Map.Entry<Data, R>> records = new LinkedList<Map.Entry<Data, R>>(); <START> while (expirationIterator.hasNext()) { <END> Map.Entry<Data, R> record = expirationIterator.next(); records.add(record); processedCount++; if (processedCount >= maxIterationCount) { break; } } int evictedCount = 0; while (!records.isEmpty()) { Map.Entry<Data, R> record = records.poll(); Data key = record.getKey(); R value = record.getValue(); boolean expired = evictIfExpired(key, value, now); if (expired) { accumulateOrSendExpiredKeysToBackup(key, value); evictedCount++; } } return evictedCount; }</code><technical_language>while (expirationIterator.hasNext() && processedCount < maxIterationCount) get rid of extra if break condition</technical_language>

Target:
private int evictExpiredInternal(int maxIterationCount, long now) { initExpirationIterator(); int processedCount = 0; LinkedList<Map.Entry<Data, R>> records = new LinkedList<Map.Entry<Data, R>>(); while (expirationIterator.hasNext() && processedCount < maxIterationCount) { Map.Entry<Data, R> record = expirationIterator.next(); records.add(record); processedCount++; } int evictedCount = 0; while (!records.isEmpty()) { Map.Entry<Data, R> record = records.poll(); Data key = record.getKey(); R value = record.getValue(); boolean expired = evictIfExpired(key, value, now); if (expired) { accumulateOrSendExpiredKeysToBackup(key, value); evictedCount++; } } return evictedCount; }
Source:
<code>public void testSimple() throws Exception { BulkCommand command = createCommand(); bulkService.submit(command); assertTrue("Bulk action didn't finish", bulkService.await(command.getId(), Duration.ofSeconds(60))); BulkStatus status = bulkService.getStatus(command.getId()); assertEquals(COMPLETED, status.getState()); assertEquals(10, status.getProcessed()); assertEquals(10, status.getTotal()); String url = Framework.getService(DownloadService.class).getDownloadUrl(command.getId()); assertEquals(url, status.getResult().get("url")); Blob blob = getBlob(command.getId()); assertNotNull(blob); try (InputStream is = new FileInputStream(blob.getFile())) { assertTrue(ZipUtils.isValid(is)); } File file = getUnzipFile(command, blob); List<String> lines = Files.lines(file.toPath()).collect(Collectors.toList()); assertEquals(11, lines.size()); assertArrayEquals(SYSTEM_PROPERTIES_HEADER_FIELDS, lines.get(0).split(",")); <START> long count = lines.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting())).get(lines.get(0)); <END> assertEquals(1, count); List<String> content = lines.subList(1, lines.size()); List<String> sortedContent = new ArrayList<>(content); Collections.sort(sortedContent); assertEquals(content, sortedContent); }</code><technical_language>do following, do more readable ? suggestion long count = lines.stream().filter(Predicate.isEqual(lines.get(0))).count();</technical_language>

Target:
public void testSimple() throws Exception { BulkCommand command = createCommand(); testCsvExport(command); }
Source:
<code>private boolean shouldBeDeleted(@Nonnull TopLevelItem item, FilePath dir, @Nonnull Node n) throws IOException, InterruptedException { if(!dir.exists()) { LOGGER.log(Level.FINE, "Directory {0} does not exist", dir); return false; } long now = new Date().getTime(); if(dir.lastModified() + retainForDays * DAY > now) { LOGGER.log(Level.FINE, "Directory {0} is only {1} old, so not deleting", new Object[] {dir, Util.getTimeSpanString(now-dir.lastModified())}); return false; } if (item instanceof AbstractProject<?,?>) { AbstractProject<?,?> p = (AbstractProject<?,?>) item; Node lb = p.getLastBuiltOn(); LOGGER.log(Level.FINER, "Directory {0} is last built on {1}", new Object[] {dir, lb}); if(lb!=null && lb.equals(n)) { LOGGER.log(Level.FINE, "Directory {0} is the last workspace for {1}", new Object[] {dir, p}); return false; } if(!p.getScm().processWorkspaceBeforeDeletion((Job<?, ?>) p,dir,n)) { LOGGER.log(Level.FINE, "Directory deletion of {0} is vetoed by SCM", dir); return false; } } if (item instanceof Job<?,?>) { Job<?,?> j = (Job<?,?>) item; if (j.isBuilding()) { <START> return false; <END> } } LOGGER.log(Level.FINER, "Going to delete directory {0}", dir); return true; }</code><technical_language>Fine logging message useful</technical_language>

Target:
private boolean shouldBeDeleted(@Nonnull TopLevelItem item, FilePath dir, @Nonnull Node n) throws IOException, InterruptedException { if(!dir.exists()) { LOGGER.log(Level.FINE, "Directory {0} does not exist", dir); return false; } long now = new Date().getTime(); if(dir.lastModified() + retainForDays * DAY > now) { LOGGER.log(Level.FINE, "Directory {0} is only {1} old, so not deleting", new Object[] {dir, Util.getTimeSpanString(now-dir.lastModified())}); return false; } if (item instanceof AbstractProject<?,?>) { AbstractProject<?,?> p = (AbstractProject<?,?>) item; Node lb = p.getLastBuiltOn(); LOGGER.log(Level.FINER, "Directory {0} is last built on {1}", new Object[] {dir, lb}); if(lb!=null && lb.equals(n)) { LOGGER.log(Level.FINE, "Directory {0} is the last workspace for {1}", new Object[] {dir, p}); return false; } if(!p.getScm().processWorkspaceBeforeDeletion((Job<?, ?>) p,dir,n)) { LOGGER.log(Level.FINE, "Directory deletion of {0} is vetoed by SCM", dir); return false; } } if (item instanceof Job<?,?>) { Job<?,?> j = (Job<?,?>) item; if (j.isBuilding()) { LOGGER.log(Level.FINE, "Job {0} is building, so not deleting", item.getFullDisplayName()); return false; } } LOGGER.log(Level.FINER, "Going to delete directory {0}", dir); return true; }
Source:
<code>public void scrollToSelectedNote(String id) { if (mNoteListFragment != null && mNoteListFragment.getListAdapter() != null) { ListAdapter listAdapter = mNoteListFragment.getListAdapter(); ListView listView = mNoteListFragment.getListView(); for (int i = 0; i < listAdapter.getCount(); i++) { if (((Note) listAdapter.getItem(i + listView.getHeaderViewsCount())).getSimperiumKey().equals(id)) { <START> listView.smoothScrollToPosition(i); <END> } } } }</code><technical_language>worth adding a break; this line, is more note a matching id</technical_language>

Target:
public void scrollToSelectedNote(String id) { if (mNoteListFragment != null && mNoteListFragment.getListAdapter() != null) { ListAdapter listAdapter = mNoteListFragment.getListAdapter(); ListView listView = mNoteListFragment.getListView(); for (int i = 0; i < listAdapter.getCount(); i++) { if (((Note) listAdapter.getItem(i + listView.getHeaderViewsCount())).getSimperiumKey().equals(id)) { listView.smoothScrollToPosition(i); break; } } } }
Source:
<code>private void initViews(){ setOrientation(LinearLayout.HORIZONTAL); setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, <START> getPixels(35))); <END> setGravity(Gravity.CENTER_VERTICAL); mImageView = new ImageView(getContext()); mImageView.setLayoutParams(new ViewGroup.LayoutParams(getPixels(25), getPixels(25))); addView(mImageView); mTextView = new TextView(getContext()); mTextView.setPadding(getPixels(20), 0, 0, 0); mTextView.setTextColor(0xFF666666); addView(mTextView); }</code><technical_language>this OK screen sizes? put 35 in dimens.xml</technical_language>

Target:
private void initViews(){ setOrientation(LinearLayout.HORIZONTAL); setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int)getContext().getResources().getDimension(R.dimen.my_priorities_item_height))); setGravity(Gravity.CENTER_VERTICAL); mImageView = new ImageView(getContext()); mImageView.setLayoutParams(new ViewGroup.LayoutParams(getPixels(25), getPixels(25))); addView(mImageView); mTextView = new TextView(getContext()); mTextView.setPadding(getPixels(20), 0, 0, 0); mTextView.setTextColor(0xFF666666); addView(mTextView); }
Source:
<code>public void stop() { try { client.close(); } catch (Exception e) { <START> e.printStackTrace(); <END> } }</code><technical_language>log, a warning</technical_language>

Target:
public void stop() { try { client.close(); } catch (Exception e) { log.cannotCloseClient(e); } }
Source:
<code>public void applyMigration() { try { if (curatorFramework.checkExists().forPath(ACTIVE_TASKS_ROOT) != null) { List<String> currentActive = curatorFramework.getChildren().forPath(ACTIVE_STATUSES_ROOT); for (String taskIdString : currentActive) { SingularityTaskId taskId = SingularityTaskId.valueOf(taskIdString); <START> String oldPath = ZKPaths.makePath(ACTIVE_STATUSES_ROOT, taskIdString); <END> byte[] oldData = curatorFramework.getData().forPath(oldPath); String newPath = ZKPaths.makePath(ACTIVE_STATUSES_ROOT, taskId.getRequestId(), taskIdString); if (curatorFramework.checkExists().forPath(newPath) != null) { curatorFramework.setData().forPath(newPath, oldData); } else { curatorFramework.create().creatingParentsIfNeeded().forPath(newPath, oldData); } curatorFramework.delete().forPath(oldPath); } curatorFramework.delete().deletingChildrenIfNeeded().forPath(ACTIVE_TASKS_ROOT); } } catch (Throwable t) { throw new RuntimeException(t); } }</code><technical_language>running this code based ACTIVE_TASKS_ROOT exists in ZK, reading path this migration. double-checking, is intended</technical_language>

Target:
public void applyMigration() { try { if (curatorFramework.checkExists().forPath(ACTIVE_TASKS_ROOT) != null) { List<String> currentActive = curatorFramework.getChildren().forPath(ACTIVE_STATUSES_ROOT); for (String taskIdString : currentActive) { try { SingularityTaskId taskId = SingularityTaskId.valueOf(taskIdString); String oldPath = ZKPaths.makePath(ACTIVE_STATUSES_ROOT, taskIdString); byte[] oldData = curatorFramework.getData().forPath(oldPath); String newPath = ZKPaths.makePath(ACTIVE_STATUSES_ROOT, taskId.getRequestId(), taskIdString); if (curatorFramework.checkExists().forPath(newPath) != null) { curatorFramework.setData().forPath(newPath, oldData); } else { curatorFramework.create().creatingParentsIfNeeded().forPath(newPath, oldData); } curatorFramework.delete().forPath(oldPath); } catch (InvalidSingularityTaskIdException e) { LOG.warn("Found invalid task id {}. This is likely because the migration did not finish successfully on a previous run. Will continue to migrate additional nodes", taskIdString); } } curatorFramework.delete().deletingChildrenIfNeeded().forPath(ACTIVE_TASKS_ROOT); } } catch (Throwable t) { throw new RuntimeException(t); } }
Source:
<code>protected boolean proceedVdsStats() { boolean returnValue = true; try { runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(getVds())); List<Guid> problematicDomainsIds = IrsBrokerCommand.checkIfDomainsReportedAsProblematic(getVds().getStoragePoolId(), getVds().getDomains()); for (Guid domainId : problematicDomainsIds) { StorageDomainStatic domainInfo = getStorageDomainStaticDAO().get(domainId); log.errorFormat("Storage Domain {0} of pool {1} is in problem in host {1}", domainInfo != null ? domainInfo.getStorageName() : domainId, getVds().getName(), getStoragePool() <START> .getName()); <END> if (domainInfo == null || domainInfo.getStorageDomainType().isDataDomain()) { returnValue = false; } } } catch (VdcBLLException e) { log.errorFormat("Could not get Host statistics for Host {0}, Error is {1}", getVds().getName(), e); returnValue = false; } return returnValue; }</code><technical_language>Please, revise this log message again, mismatch - pool host marked {1} host parameter is 1 while pool 2</technical_language>

Target:
protected boolean proceedVdsStats() { boolean returnValue = true; try { runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(getVds())); List<Guid> problematicDomainsIds = IrsBrokerCommand.fetchDomainsReportedAsProblematic(getVds().getStoragePoolId(), getVds().getDomains()); for (Guid domainId : problematicDomainsIds) { StorageDomainStatic domainInfo = getStorageDomainStaticDAO().get(domainId); log.errorFormat("Storage Domain {0} of pool {1} is in problem in host {1}", domainInfo != null ? domainInfo.getStorageName() : domainId, getStoragePool().getName(), getVds().getName()); if (domainInfo == null || domainInfo.getStorageDomainType().isDataDomain()) { returnValue = false; } } } catch (VdcBLLException e) { log.errorFormat("Could not get Host statistics for Host {0}, Error is {1}", getVds().getName(), e); returnValue = false; } return returnValue; }
Source:
<code>private static GoType findTypeInConstSpec(@NotNull GoConstDefinition o) { PsiElement parent = PsiTreeUtil.getStubOrPsiParent(o); if (!(parent instanceof GoConstSpec)) return null; GoConstSpec spec = (GoConstSpec)parent; GoType commonType = spec.getType(); if (commonType != null) return commonType; List<GoConstDefinition> varList = spec.getConstDefinitionList(); int i = Math.max(varList.indexOf(o), 0); <START> List<GoExpression> es = spec.getExpressionList(); <END> if (es.size() <= i) return null; return es.get(i).getGoType(null); }</code><technical_language>Mmm? Why</technical_language>

Target:
private static Pair<GoType, Boolean> findTypeInConstSpec(@NotNull GoConstDefinition o) { PsiElement parent = PsiTreeUtil.getStubOrPsiParent(o); if (!(parent instanceof GoConstSpec)) return Pair.create(null, false); GoConstSpec spec = (GoConstSpec)parent; GoType commonType = spec.getType(); if (commonType != null) return Pair.create(commonType, true); List<GoConstDefinition> varList = spec.getConstDefinitionList(); int i = Math.max(varList.indexOf(o), 0); GoConstSpecStub specStub = spec.getStub(); List<GoExpression> es = specStub != null ? specStub.getExpressionList() : spec.getExpressionList(); if (es.size() <= i) return Pair.create(null, false); return Pair.create(es.get(i).getGoType(null), true); }
Source:
<code>private void endTransaction(BinlogEventV4 e) { <START> LOG.info("Ending transaction " + _scn); <END> DatastreamProducerRecordBuilder builder = new DatastreamProducerRecordBuilder(); builder.setPartition(1); String checkpoint = MysqlCheckpoint.createCheckpointString(_sourceId, _scn, _currFileName, _mostRecentSeenEventPosition); builder.setSourceCheckpoint(checkpoint); for (String event : _eventsInTransaction) { DatastreamEvent datastreamEvent = new DatastreamEvent(); datastreamEvent.payload = ByteBuffer.wrap(event.getBytes()); datastreamEvent.key = null; builder.addEvent(datastreamEvent); } _producer.send(builder.build(), (metadata, exception) -> { if (exception == null) { LOG.debug(String.format("Sending event succeeded, metadata:{%s}", metadata)); } else { LOG.error(String.format("Sending event failed, metadata:{%s}", metadata), exception); } }); resetTransactionData(); }</code><technical_language>this debug level</technical_language>

Target:
private void endTransaction(BinlogEventV4 e) { LOG.info("Ending transaction " + _scn); if (_eventsInTransaction.size() > 0) { DatastreamProducerRecordBuilder builder = new DatastreamProducerRecordBuilder(); builder.setPartition(0); String checkpoint = MysqlCheckpoint.createCheckpointString(_sourceId, _scn, _currFileName, _mostRecentSeenEventPosition); builder.setSourceCheckpoint(checkpoint); _eventsInTransaction.forEach(builder::addEvent); _producer.send(builder.build(), (metadata, exception) -> { if (exception == null) { LOG.debug(String.format("Sending event succeeded, metadata:{%s}", metadata)); } else { LOG.error(String.format("Sending event failed, metadata:{%s}", metadata), exception); } }); } resetTransactionData(); }
Source:
<code>private WebDriver getWebDriverImpl( int requester, String providedBrowserId, String proxyAddress, int proxyPort) { ProvidedBrowser providedBrowser = getProvidedBrowser(providedBrowserId); if (providedBrowser == null) { throw new IllegalArgumentException("Unknown browser: " + providedBrowserId); } if (proxyAddress == null) { return webDriverProviders.get(providedBrowser.getProviderId()).getWebDriver(requester); } WebDriver wd = webDriverProviders .get(providedBrowser.getProviderId()) .getWebDriver(requester, proxyAddress, proxyPort); ExtensionScript extScript = Control.getSingleton().getExtensionLoader().getExtension(ExtensionScript.class); if (extScript != null) { List<ScriptWrapper> scripts = extScript.getScripts(SCRIPT_TYPE_SELENIUM); for (ScriptWrapper script : scripts) { try { if (script.isEnabled()) { SeleniumScript s = extScript.getInterface(script, SeleniumScript.class); if (s != null) { new Thread("ZAP-selenium-script") { @Override public void run() { <START> s.browserLaunched( <END> wd, requester, providedBrowserId, proxyAddress, proxyPort); } }.start(); } else { extScript.handleFailedScriptInterface( script, Constant.messages.getString( "selenium.scripts.interface.error", script.getName())); } } } catch (Exception e) { extScript.handleScriptException(script, e); } } } return wd; }</code><technical_language>handle/catch Exception here</technical_language>

Target:
private WebDriver getWebDriverImpl( int requester, String providedBrowserId, String proxyAddress, int proxyPort) { ProvidedBrowser providedBrowser = getProvidedBrowser(providedBrowserId); if (providedBrowser == null) { throw new IllegalArgumentException("Unknown browser: " + providedBrowserId); } WebDriver wd; if (proxyAddress == null) { wd = webDriverProviders.get(providedBrowser.getProviderId()).getWebDriver(requester); } else { wd = webDriverProviders .get(providedBrowser.getProviderId()) .getWebDriver(requester, proxyAddress, proxyPort); } if (getExtScript() != null) { List<ScriptWrapper> scripts = extScript.getScripts(SCRIPT_TYPE_SELENIUM); for (ScriptWrapper script : scripts) { try { if (script.isEnabled()) { SeleniumScript s = extScript.getInterface(script, SeleniumScript.class); if (s != null) { new Thread("ZAP-selenium-script") { @Override public void run() { try { s.browserLaunched( new SeleniumScriptUtils( wd, requester, providedBrowserId, proxyAddress, proxyPort)); } catch (Exception e) { extScript.handleScriptException(script, e); } } }.start(); } else { extScript.handleFailedScriptInterface( script, Constant.messages.getString( "selenium.scripts.interface.error", script.getName())); } } } catch (Exception e) { extScript.handleScriptException(script, e); } } } return wd; }
Source:
<code>private boolean findNextToken() { int totalLen = bytes.length; for (pos = end; pos < totalLen && bytes[pos] == '/'; pos++) { } <START> if (pos == totalLen) { <END> return hasCurrent = false; } for (end = pos + 1; end < totalLen && bytes[end] != '/'; end++) { } return hasCurrent = true; }</code><technical_language>style-nit: avoid braces for simple constructs</technical_language>

Target:
private boolean findNextToken() { int totalLen = path.length; for (pathOffset = pathEnd; pathOffset < totalLen && path[pathOffset] == '/'; pathOffset++) { } if (pathOffset == totalLen) return hasCurrent = false; for (pathEnd = pathOffset + 1; pathEnd < totalLen && path[pathEnd] != '/'; pathEnd++) { } return hasCurrent = true; }
Source:
<code>public boolean hasEntity() { Object actualEntity = getActualEntity(); if (actualEntity == null) { return false; } else if (actualEntity instanceof InputStream) { final InputStream is = (InputStream) actualEntity; try { if (is.markSupported()) { is.mark(1); int i = is.read(); is.reset(); return i != -1; } else { try { if (is.available() > 0) { return true; } } catch (IOException ioe) { <START> } <END> int b = is.read(); if (b == -1) { return false; } PushbackInputStream pbis; if (is instanceof PushbackInputStream) { pbis = (PushbackInputStream) is; } else { pbis = new PushbackInputStream(is, 1); if (lastEntity != null) { lastEntity = pbis; } else { entity = pbis; } } pbis.unread(b); return true; } } catch (IOException ex) { throw new ProcessingException(ex); } } else { return true; } }</code><technical_language>This modify state of stream, correct? simpler check/construct PushbackInputStream do read / unread</technical_language>

Target:
public boolean hasEntity() { Object actualEntity = getActualEntity(); if (actualEntity == null) { return false; } else if (actualEntity instanceof InputStream) { final InputStream is = (InputStream) actualEntity; try { if (is.markSupported()) { is.mark(1); int i = is.read(); is.reset(); return i != -1; } else { try { if (is.available() > 0) { return true; } } catch (IOException ioe) { } int b = is.read(); if (b == -1) { return false; } PushbackInputStream pbis; if (is instanceof PushbackInputStream) { pbis = (PushbackInputStream) is; } else { pbis = new PushbackInputStream(is, 1); if (lastEntity != null) { lastEntity = pbis; } else { entity = pbis; } } pbis.unread(b); return true; } } catch (IOException ex) { throw new ProcessingException(ex); } } return true; }
Source:
<code>public void processElement(ProcessContext c) throws Exception { final String shardId = c.element().getKey(); final BoundedSource<Result> source = c.element().getValue(); LOG.info("Starting new shard"); final String finalFilePath = basePath + "/" + shardId; final SequenceFile.Writer.Option[] writerOptions = new SequenceFile.Writer.Option[]{ SequenceFile.Writer.file(new Path(finalFilePath)), SequenceFile.Writer.keyClass(ImmutableBytesWritable.class), SequenceFile.Writer.valueClass(Result.class), SequenceFile.Writer.compression(CompressionType.BLOCK) }; final long start = System.nanoTime(); long localStart = System.nanoTime(); long reportedTotalDuration = 0; try (BoundedSource.BoundedReader<Result> reader = source.createReader(c.getPipelineOptions())) { boolean hasMore = reader.start(); <START> readDuration.addValue(System.nanoTime() - localStart); <END> if (hasMore) { try (SequenceFile.Writer writer = SequenceFile.createWriter(hadoopConfig, writerOptions)) { final ImmutableBytesWritable key = new ImmutableBytesWritable(); Result value; while (hasMore) { localStart = System.nanoTime(); value = reader.getCurrent(); key.set(value.getRow()); writer.append(key, value); writeDuration.addValue(System.nanoTime() - localStart); localStart = System.nanoTime(); hasMore = reader.advance(); readDuration.addValue(System.nanoTime() - localStart); itemCounter.addValue(1L); final long newTotalDuration = System.nanoTime() - start; totalDuration.addValue(newTotalDuration - reportedTotalDuration); reportedTotalDuration = newTotalDuration; } bytesWritten.addValue(writer.getLength()); } } } final long newTotalDuration = System.nanoTime() - start; totalDuration.addValue(newTotalDuration - reportedTotalDuration); }</code><technical_language>System.nanoTime() - localStart is repeated often. sense encapsulate that</technical_language>

Target:
public void processElement(ProcessContext c) throws Exception { final ExportShard<Result> shard = c.element().getValue(); LOG.info("Starting new shard"); final String projectId = c.getPipelineOptions().as(DataflowPipelineOptions.class).getProject(); final String finalFilePath = basePath + "/" + shard.filename; try (BoundedSource.BoundedReader<Result> reader = shard.source.createReader(c.getPipelineOptions())) { if (!reader.start()) { return; } try (SequenceFile.Writer writer = createWriter(projectId, finalFilePath)) { final ImmutableBytesWritable key = new ImmutableBytesWritable(); Result value; long bytesReported = 0; boolean hasMore = true; while (hasMore) { value = reader.getCurrent(); key.set(value.getRow()); writer.append(key, value); hasMore = reader.advance(); itemCounter.addValue(1L); long newBytes = writer.getLength() - bytesReported; bytesWritten.addValue(newBytes); bytesReported += newBytes; } long newBytes = writer.getLength() - bytesReported; bytesWritten.addValue(newBytes); bytesReported += newBytes; } } }
Source:
<code>public void placeEntity(World world, Entity entity, float yaw) { entity.setPosition(targetPos.getX() + 0.5, targetPos.getY(), targetPos.getZ() + 0.5); AxisAlignedBB aabb = entity.getEntityBoundingBox(); BlockPos min = new BlockPos(MathHelper.floor(aabb.minX), MathHelper.floor(aabb.minY), MathHelper.floor(aabb.minZ)); BlockPos max = new BlockPos(MathHelper.ceil(aabb.maxX), MathHelper.ceil(aabb.maxY), MathHelper.ceil(aabb.maxZ)); for (BlockPos pos : BlockPos.getAllInBoxMutable(min, max)) { <START> world.setBlockToAir(pos); <END> } }</code><technical_language>This destroy important blocks, in someone's base. vanilla teleport do</technical_language>

Target:
public void placeEntity(World world, Entity entity, float yaw) { entity.moveToBlockPosAndAngles(targetPos, yaw, entity.rotationPitch); }
Source:
<code>private void internalFreeMac(String mac) { if (allocatedMacs.containsKey(mac)) { removeMacFromMap(allocatedMacs, mac); <START> availableMacs.add(mac); <END> } else if (allocatedCustomMacs.containsKey(mac)) { removeMacFromMap(allocatedCustomMacs, mac); } }</code><technical_language>troubled this line: AllowDuplicateMacAddress configuration variable is reloadable, this code serve in case moved permissive restrictive mode: returning a MAC address mac address pool done if longer in allocatedMacs</technical_language>

Target:
private void internalFreeMac(String mac) { if (allocatedMacs.containsKey(mac)) { removeMacFromMap(allocatedMacs, mac); if (!allocatedMacs.containsKey(mac)) { availableMacs.add(mac); } } else if (allocatedCustomMacs.containsKey(mac)) { removeMacFromMap(allocatedCustomMacs, mac); } }
Source:
<code>public void handle() { super.handle(); PrototypeFactory prototypeFactory = new LivePrototypeFactory(); try { <START> CommCareConfigEngine engine = configureApp(args[0], prototypeFactory); <END> ApplicationHost host = new ApplicationHost(engine, prototypeFactory); if (cmd.hasOption("r")) { host.setRestoreToLocalFile(cmd.getOptionValue("r")); } else { username = username.trim().toLowerCase(); host.setRestoreToRemoteUser(username, password); } host.run(); System.exit(-1); } catch (RuntimeException re) { System.out.print("Unhandled Fatal Error executing CommCare app"); re.printStackTrace(); throw re; } finally { System.exit(0); } }</code><technical_language>args[0] -> resourcePath</technical_language>

Target:
public void handle() { super.handle(); PrototypeFactory prototypeFactory = new LivePrototypeFactory(); try { CommCareConfigEngine engine = configureApp(resourcePath, prototypeFactory); ApplicationHost host = new ApplicationHost(engine, prototypeFactory); if (cmd.hasOption("r")) { host.setRestoreToLocalFile(cmd.getOptionValue("r")); } else { username = username.trim().toLowerCase(); host.setRestoreToRemoteUser(username, password); } host.run(); System.exit(-1); } catch (RuntimeException re) { System.out.print("Unhandled Fatal Error executing CommCare app"); re.printStackTrace(); throw re; } finally { System.exit(0); } }
Source:
<code>public boolean setFontSizeMultiplier(int multiplier) { if (multiplier < <START> getResources().getInteger(R.integer.minTextSizeMultiplier)) { <END> multiplier = getResources().getInteger(R.integer.minTextSizeMultiplier); } else if (multiplier > getResources().getInteger(R.integer.maxTextSizeMultiplier)) { multiplier = getResources().getInteger(R.integer.maxTextSizeMultiplier); } if (multiplier != getTextSizeMultiplier()) { Prefs.setTextSizeMultiplier(multiplier); bus.post(new ChangeTextSizeEvent()); return true; } return false; }</code><technical_language>minor: improve readability slightly get min max text size multipliers in beginning hold local variables</technical_language>

Target:
public boolean setFontSizeMultiplier(int multiplier) { int minMultiplier = getResources().getInteger(R.integer.minTextSizeMultiplier); int maxMultiplier = getResources().getInteger(R.integer.maxTextSizeMultiplier); if (multiplier < minMultiplier) { multiplier = minMultiplier; } else if (multiplier > maxMultiplier) { multiplier = maxMultiplier; } if (multiplier != getTextSizeMultiplier()) { Prefs.setTextSizeMultiplier(multiplier); bus.post(new ChangeTextSizeEvent()); return true; } return false; }
Source:
<code>public static Image map(RepoImage entity, Image template) { Image model = template != null ? template : new Image(); model.setId(entity.getRepoImageId()); model.setName(entity.getRepoImageName()); if <START> (entity.isSetSize()) { <END> model.setSize(entity.getSize().intValue()); } if (entity.isSetFileType()) { model.setFileType(map(entity.getFileType(), null)); } return model; }</code><technical_language>apologies confusion previous patch. I misread converting a model entity a backend one. model entities auto generated isSetXyz() for non-primitive getXyz() method, I use, this method in fact **the opposite**, this a good idea. In fact, I if model entity changed a java.lang.Integer member instead of a primitive int, size in backend null, want misrepresent 0</technical_language>

Target:
public static Image map(RepoImage entity, Image template) { Image model = template != null ? template : new Image(); model.setId(entity.getRepoImageId()); model.setName(entity.getRepoImageName()); if (entity.getSize() != null) { model.setSize(entity.getSize()); } model.setFileType(map(entity.getFileType(), null)); return model; }
Source:
<code>public void findSections() throws Exception { getClient().perform(get("/api/config/submissiondefinitions/traditional/sections")) <START> .andExpect(status().isForbidden()); <END> String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/config/submissiondefinitions/traditional/sections")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$._embedded.submissionsections", hasSize(5))) .andExpect(jsonPath("$._embedded.submissionsections", Matchers.hasItem( allOf( hasJsonPath("$.id", is("traditionalpageone")), hasJsonPath("$.sectionType", is("submission-form")), hasJsonPath("$.type", is("submissionsection")), hasJsonPath("$._links.config.href", is(REST_SERVER_URL + "config/submissionforms/traditionalpageone")), hasJsonPath("$._links.self.href", is(REST_SERVER_URL + "config/submissionsections/traditionalpageone")) )))) ; }</code><technical_language>isUnauthorized 403</technical_language>

Target:
public void findSections() throws Exception { getClient().perform(get("/api/config/submissiondefinitions/traditional/sections")) .andExpect(status().isUnauthorized()); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/config/submissiondefinitions/traditional/sections")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$._embedded.submissionsections", hasSize(5))) .andExpect(jsonPath("$._embedded.submissionsections", Matchers.hasItem( allOf( hasJsonPath("$.id", is("traditionalpageone")), hasJsonPath("$.sectionType", is("submission-form")), hasJsonPath("$.type", is("submissionsection")), hasJsonPath("$._links.config.href", is(REST_SERVER_URL + "config/submissionforms/traditionalpageone")), hasJsonPath("$._links.self.href", is(REST_SERVER_URL + "config/submissionsections/traditionalpageone")) )))) ; }
Source:
<code>public int hashCode() { if(getName().equalsIgnoreCase("INBOX")){ String inbox = new String("INBOX") ; <START> return inbox.hashCode(); <END> } return getName().hashCode(); }</code><technical_language>do return "INBOX".hashCode(); Nice approach good push tidied that</technical_language>

Target:
public int hashCode() { if (getName().equalsIgnoreCase("INBOX")) { return "INBOX".hashCode(); } return getName().hashCode(); }
Source:
<code>public void doMain(String[] args) throws IOException { ParserProperties properties = ParserProperties.defaults().withUsageWidth(80); CmdLineParser parser = new CmdLineParser(this, properties); try { parser.parseArgument(args); } catch (CmdLineException e) { e.printStackTrace(); return; } if( arguments.isEmpty() ) <START> System.out.println("No args given. Example useage: java SampleMain" + parser.printExample(OptionHandlerFilter.ALL)); <END> System.out.println(out); if( recursive ) System.out.println("-r flag is set"); if( data ) System.out.println("-custom flag is set"); System.out.println("-str was "+str); if( num>=0 ) System.out.println("-n was "+num); System.out.println("other arguments are:"); for( String s : arguments ) System.out.println(s); }</code><technical_language>This System.err, e.printStackTrace()</technical_language>

Target:
public void doMain(String[] args) throws IOException { ParserProperties properties = ParserProperties.defaults().withUsageWidth(80); CmdLineParser parser = new CmdLineParser(this, properties); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()+"\n"); System.err.println("java SampleMain [options...] arguments..."); parser.printUsage(System.err); System.err.println(); return; } if( arguments.isEmpty() ) System.err.println("No args given. Example useage: java SampleMain" + parser.printExample(OptionHandlerFilter.ALL)); System.out.println(out); if( recursive ) System.out.println("-r flag is set"); if( data ) System.out.println("-custom flag is set"); System.out.println("-str was "+str); if( num>=0 ) System.out.println("-n was "+num); System.out.println("other arguments are:"); for( String s : arguments ) System.out.println(s); }