auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void updateNewAttachmentAttribute(TaskAttribute attachmentAttribute) { BugzillaRestConfiguration repositoryConfiguration; try { repositoryConfiguration = connector.getRepositoryConfiguration(this.getTaskRepository()); repositoryConfiguration.updateAttachmentFlags(attachmentAttribute); } catch (CoreException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>log this instead</technical_language>

Target:
public void updateNewAttachmentAttribute(TaskAttribute attachmentAttribute) { BugzillaRestConfiguration repositoryConfiguration; try { repositoryConfiguration = connector.getRepositoryConfiguration(this.getTaskRepository()); repositoryConfiguration.updateAttachmentFlags(attachmentAttribute); } catch (CoreException e) { StatusHandler.log( new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, "Eerror in updateNewAttachmentAttribute", e)); } }
Source:
<code><START> public NewAgileFeatureGroup getFeatureGroup(@PathParam("featureUuid") long featureUuid) { <END> IAgileFeatureGroup feature = atsServer.getAgileService().getAgileFeatureGroups(Arrays.asList(featureUuid)).iterator().next(); NewAgileFeatureGroup created = new NewAgileFeatureGroup(); created.setGuid(feature.getGuid()); created.setName(feature.getName()); created.setUuid(feature.getId()); created.setTeamUuid(feature.getTeamUuid()); created.setActive(feature.isActive()); return created; }</code><technical_language>NewAgileFeatureGroup is a confusing class name - remove New name</technical_language>

Target:
public JaxAgileFeatureGroup getFeatureGroup(@PathParam("featureUuid") long featureUuid) { IAgileFeatureGroup feature = atsServer.getAgileService().getAgileFeatureGroups(Arrays.asList(featureUuid)).iterator().next(); JaxAgileFeatureGroup created = new JaxAgileFeatureGroup(); created.setGuid(feature.getGuid()); created.setName(feature.getName()); created.setUuid(feature.getId()); created.setTeamUuid(feature.getTeamUuid()); created.setActive(feature.isActive()); return created; }
Source:
<code>protected IStatus run(IProgressMonitor monitor) { while (!monitor.isCanceled()) { try { Thread.sleep(INDEXING_THREAD_SLEEP_VALUE); } catch (InterruptedException e) { <START> Thread.currentThread().interrupt(); <END> } } monitor.done(); return Status.OK_STATUS; }</code><technical_language>exit loop. need return</technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { while (!monitor.isCanceled()) { try { Thread.sleep(INDEXING_THREAD_SLEEP_VALUE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return Status.OK_STATUS; } } monitor.done(); return Status.OK_STATUS; }
Source:
<code>public void publishUserTune(UserTuneElement userTuneElement) throws NotLoggedInException, NotALeafNodeException, NoResponseException, NotConnectedException, XMPPErrorException, InterruptedException { if (pubSubManager == null) { pubSubManager = PubSubManager.getInstanceFor(getAuthenticatedConnectionOrThrow(), connection().getUser().asBareJid()); } LeafNode node = pubSubManager.getOrCreateLeafNode(USERTUNE_NODE); userTuneElementStack.push(userTuneElement); <START> Thread.sleep(5000); <END> if (!userTuneElementStack.isEmpty()) { node.publish(new PayloadItem<>(userTuneElementStack.pop())); userTuneElementStack.clear(); } }</code><technical_language>This implement sort of rate limiting. Thread.sleep() in code, ever! possibly require is some sort of synchronized block ensures successive events send in X seconds (where X is configurable)</technical_language>

Target:
public void publishUserTune(UserTuneElement userTuneElement) throws NotLoggedInException, NotALeafNodeException, NoResponseException, NotConnectedException, XMPPErrorException, InterruptedException { pepManager.publish(USERTUNE_NODE, new PayloadItem<>(userTuneElement)); }
Source:
<code>public boolean canHandle(HttpServletRequest request) { String token = CharacterEncoder.getSafeText(request.getParameter("token")); String action = CharacterEncoder.getSafeText(request.getParameter("sendToken")); if (token != null || action != null) { return true; } <START> return false; <END> }</code><technical_language>line 49- 52 simplified "return (token != null || action != null);"</technical_language>

Target:
public boolean canHandle(HttpServletRequest request) { String token = CharacterEncoder.getSafeText(request.getParameter("token")); String action = CharacterEncoder.getSafeText(request.getParameter("sendToken")); return (token != null || action != null); }
Source:
<code><START> private void verifyParentItemsMatch(ParentListItem<Object> expectedParentListItem, boolean expectedExpansion, int actualParentIndex) { <END> assertEquals(expectedParentListItem, mExpandableRecyclerAdapter.getListItem(actualParentIndex)); assertEquals(expectedExpansion, mExpandableRecyclerAdapter.mItemList.get(actualParentIndex).isExpanded()); if (expectedExpansion) { List<Object> expectedChildList = expectedParentListItem.getChildItemList(); int actualChildIndex = actualParentIndex + 1; for (int i = 0; i < expectedChildList.size(); i++) { assertEquals(expectedChildList.get(i), mExpandableRecyclerAdapter.getListItem(actualChildIndex)); actualChildIndex++; } } }</code><technical_language>Good cleanup</technical_language>

Target:
private void verifyParentItemsMatch(ParentListItem<Object> expectedParentListItem, boolean expectedExpansion, int actualParentIndex) { assertEquals(expectedParentListItem, getListItem(actualParentIndex)); assertEquals(expectedExpansion, mExpandableRecyclerAdapter.mItemList.get(actualParentIndex).isExpanded()); if (expectedExpansion) { List<Object> expectedChildList = expectedParentListItem.getChildItemList(); int actualChildIndex = actualParentIndex + 1; for (int i = 0; i < expectedChildList.size(); i++) { assertEquals(expectedChildList.get(i), getListItem(actualChildIndex)); actualChildIndex++; } } }
Source:
<code>private Set<StoreKey> getMissingStoreKeys(ReplicaMetadataResponseInfo replicaMetadataResponseInfo, DataNodeId remoteNode, RemoteReplicaInfo remoteReplicaInfo) throws StoreException { long startTime = SystemTime.getInstance().milliseconds(); List<MessageInfo> messageInfoList = replicaMetadataResponseInfo.getMessageInfoList(); List<StoreKey> storeKeysToCheck = new ArrayList<StoreKey>(messageInfoList.size()); for (MessageInfo messageInfo : messageInfoList) { storeKeysToCheck.add(messageInfo.getStoreKey()); logger.trace("Remote node: Thread name: Remote replica: Key from remote: {}", remoteNode, threadName, remoteReplicaInfo.getReplicaId(), messageInfo.getStoreKey()); } Set<StoreKey> missingStoreKeys = remoteReplicaInfo.getLocalStore().findMissingKeys(storeKeysToCheck); for (StoreKey storeKey : missingStoreKeys) { logger.trace("Remote node: Thread name: Remote replica: Key missing id: {}", remoteNode, threadName, remoteReplicaInfo.getReplicaId(), storeKey); } if (isRemoteColo) { <START> replicationMetrics.interColoCheckMissingKeysTime.get(remoteDatacenterName) <END> .update(SystemTime.getInstance().milliseconds() - startTime); } else { replicationMetrics.intraColoCheckMissingKeysTime.update(SystemTime.getInstance().milliseconds() - startTime); } return missingStoreKeys; }</code><technical_language>a convention established update metrics. For e.g. replicationMetrics.updateMetadataRequestTime(metadataRequestTime, isRemoteColo, isSSLEnabled, remoteDatacenterName); Is follow kind of convention (updating a function)</technical_language>

Target:
private Set<StoreKey> getMissingStoreKeys(ReplicaMetadataResponseInfo replicaMetadataResponseInfo, DataNodeId remoteNode, RemoteReplicaInfo remoteReplicaInfo) throws StoreException { long startTime = SystemTime.getInstance().milliseconds(); List<MessageInfo> messageInfoList = replicaMetadataResponseInfo.getMessageInfoList(); List<StoreKey> storeKeysToCheck = new ArrayList<StoreKey>(messageInfoList.size()); for (MessageInfo messageInfo : messageInfoList) { storeKeysToCheck.add(messageInfo.getStoreKey()); logger.trace("Remote node: Thread name: Remote replica: Key from remote: {}", remoteNode, threadName, remoteReplicaInfo.getReplicaId(), messageInfo.getStoreKey()); } Set<StoreKey> missingStoreKeys = remoteReplicaInfo.getLocalStore().findMissingKeys(storeKeysToCheck); for (StoreKey storeKey : missingStoreKeys) { logger.trace("Remote node: Thread name: Remote replica: Key missing id: {}", remoteNode, threadName, remoteReplicaInfo.getReplicaId(), storeKey); } replicationMetrics .updateCheckMissingKeysTime(SystemTime.getInstance().milliseconds() - startTime, replicatingFromRemoteColo, datacenterName); return missingStoreKeys; }
Source:
<code>public void folderScopedCredentialsTest() { final Folder folder = jenkins.jobs.create(Folder.class, F01); final FreeStyleJob job1 = folder.getJobs().create(FreeStyleJob.class, JOB1); this.checkItemExists(folder, true); this.checkItemExists(job1, true); final WorkflowJob job2 = createWorkflowJob(folder); this.checkItemExists(job2, true); final String console = job2.startBuild().shouldSucceed().getConsole(); assertThat(console, containsRegexp(CRED_INJECTED_MESSAGE)); job1.delete(); elasticSleep(1000); <START> this.checkItemExists(job1, false); <END> job2.delete(); elasticSleep(1000); this.checkItemExists(job2, false); folder.delete(); this.checkItemExists(folder, false); }</code><technical_language>waitFor(job1, Matcher.pageObjectDoesNotExist(), 1000) removing checkItemExists. advantage, pointed out in another PR, checking URL presence other browser break Jenkins authentication</technical_language>

Target:
public void folderScopedCredentialsTest() { final Folder folder = jenkins.jobs.create(Folder.class, F01); final FreeStyleJob job1 = folder.getJobs().create(FreeStyleJob.class, JOB1); this.checkItemExists(folder, true); this.checkItemExists(job1, true); final WorkflowJob job2 = createWorkflowJob(folder); this.checkItemExists(job2, true); final String console = job2.startBuild().shouldSucceed().getConsole(); assertThat(console, containsRegexp(CRED_INJECTED_MESSAGE)); job1.delete(); waitFor(job1, Matchers.pageObjectDoesNotExist(), 1000); job2.delete(); waitFor(job2, Matchers.pageObjectDoesNotExist(), 1000); folder.delete(); waitFor(folder, Matchers.pageObjectDoesNotExist(), 1000); }
Source:
<code>public List<EnrichedHost> getEnrichedHosts(PerunSession sess, Facility facility, List<String> attrNames) throws AttributeNotExistsException, FacilityNotExistsException { Utils.checkPerunSession(sess); getFacilitiesManagerBl().checkFacilityExists(sess, facility); <START> List<Host> hosts = getFacilitiesManagerBl().getHosts(sess, facility); <END> Host host1 = hosts.get(0); List<String> allowedAttributes = new ArrayList<>(); for (String attrName : attrNames) { if (AuthzResolver.isAuthorizedForAttribute(sess, ActionType.READ, getPerunBl().getAttributesManagerBl().getAttributeDefinition(sess, attrName), host1)) { allowedAttributes.add(attrName); } } List<EnrichedHost> enrichedHosts = new ArrayList<>(); for (Host host : hosts) { List<Attribute> hostAttributes = getPerunBl().getAttributesManagerBl().getAttributes(sess, host, allowedAttributes); enrichedHosts.add(new EnrichedHost(host, hostAttributes)); } return enrichedHosts; }</code><technical_language>checking rights get hosts for facility. need check call method api correctly check rights</technical_language>

Target:
public List<EnrichedHost> getEnrichedHosts(PerunSession sess, Facility facility, List<String> attrNames) throws AttributeNotExistsException, FacilityNotExistsException, PrivilegeException { List<Host> hosts = getHosts(sess, facility); List<EnrichedHost> enrichedHosts = new ArrayList<>(); if (hosts.isEmpty()) return enrichedHosts; Host host1 = hosts.get(0); List<String> allowedAttributes = new ArrayList<>(); for (String attrName : attrNames) { if (AuthzResolver.isAuthorizedForAttribute(sess, ActionType.READ, getPerunBl().getAttributesManagerBl().getAttributeDefinition(sess, attrName), host1)) { allowedAttributes.add(attrName); } } for (Host host : hosts) { List<Attribute> hostAttributes = getPerunBl().getAttributesManagerBl().getAttributes(sess, host, allowedAttributes); enrichedHosts.add(new EnrichedHost(host, hostAttributes)); } return enrichedHosts; }
Source:
<code>public Boolean load(EntryKey key) throws NoSuchProjectException, MergeException, IOException { <START> boolean open = key.repo == null; Repository repo = open ? repoManager.openRepository(key.dest.getParentKey()) : key.repo; <END> try { return isMergeable(key, repo); } finally { key.dest = null; key.repo = null; if (open) { repo.close(); } } }</code><technical_language>Havn't agreed, this is needed? This class operate dest, least, caller provide it, provide opened repo</technical_language>

Target:
public Boolean load(EntryKey key) throws NoSuchProjectException, MergeException, IOException { checkArgument(key.dest != null && key.repo != null && key.db != null, "Key cannot be loaded without destination, repo, and db: %s", key); if (key.into.equals(ObjectId.zeroId())) { return true; } try { Map<String, Ref> refs = key.repo.getAllRefs(); RevWalk rw = CodeReviewCommit.newRevWalk(key.repo); try { RevFlag canMerge = rw.newFlag("CAN_MERGE"); CodeReviewCommit rev = parse(rw, key.commit); rev.add(canMerge); CodeReviewCommit tip = parse(rw, key.into); Set<RevCommit> accepted = alreadyAccepted(rw, refs.values()); accepted.add(tip); accepted.addAll(Arrays.asList(rev.getParents())); return submitStrategyFactory.create( key.submitType, key.db, key.repo, rw, null , canMerge, accepted, key.dest).dryRun(tip, rev); } finally { rw.release(); } } finally { key.dest = null; key.repo = null; } }
Source:
<code>public Object[] transform(String sourceData) throws FormatException { if (sourceData == null) { return null; } Tokenizer tokenizer = new Tokenizer(new BufferedReader(new StringReader(sourceData)), m_csvPreference, m_strictquotes, m_escape, DEFAULT_COLUMN_LIMIT_SIZE, 0); CsvListReader csvReader = new CsvListReader(tokenizer, m_csvPreference); List<String> dataList; try { dataList = csvReader.read(); <START> } catch (Exception e) { <END> throw new FormatException(e.getMessage()); } finally { try { if (csvReader != null) csvReader.close(); } catch (Exception e) { throw new FormatException(e.getMessage()); } } String[] data = dataList.toArray(new String[0]); normalize(data); return data; }</code><technical_language>Waht exceptions catching please more specific</technical_language>

Target:
public Object[] transform(String sourceData) throws FormatException { if (sourceData == null) { return null; } Tokenizer tokenizer = new Tokenizer(new StringReader(sourceData), m_csvPreference, m_strictquotes, m_escape, DEFAULT_COLUMN_LIMIT_SIZE, 0); CsvListReader csvReader = new CsvListReader(tokenizer, m_csvPreference); List<String> dataList; try { dataList = csvReader.read(); } catch (IOException | SuperCsvException e) { throw new FormatException("Fail to parse csv data", e); } finally { try { if (csvReader != null) csvReader.close(); } catch (IOException e) { throw new FormatException(e); } } String[] data = dataList.toArray(new String[0]); normalize(data); return data; }
Source:
<code>public void testGetSlaDueDate() { GenericServiceTaskExecutionSet a = new GenericServiceTaskExecutionSet( new GenericServiceTaskInfo(), new SLADueDate(SLA_DUE_DATE_1)); <START> Assert.assertTrue(a.getSlaDueDate().getValue().equals(SLA_DUE_DATE_1)); <END> }</code><technical_language>assertEquals express is expected value</technical_language>

Target:
public void testGetSlaDueDate() { GenericServiceTaskExecutionSet a = new GenericServiceTaskExecutionSet( new GenericServiceTaskInfo(), new SLADueDate(SLA_DUE_DATE_1)); assertEquals(SLA_DUE_DATE_1, a.getSlaDueDate().getValue()); }
Source:
<code>public Class<?>[] getAdapterList() { return <START> new Class<?>[] { ITranslationUnit.class }; <END> }</code><technical_language>moved a constant</technical_language>

Target:
public Class<?>[] getAdapterList() { return ADAPTER_LIST; }
Source:
<code>private ConcurrentNavigableMap<Cell, byte[]> getReadsForTable(TableReference table) { <START> return readsByTable.computeIfAbsent(table, $ -> new ConcurrentSkipListMap<>()); <END> }</code><technical_language>'$' a variable name; disallowed checkstyle unenforced due a checkstyle bug. Rather, prefer 'unused'</technical_language>

Target:
private ConcurrentNavigableMap<Cell, byte[]> getReadsForTable(TableReference table) { return readsByTable.computeIfAbsent(table, unused -> new ConcurrentSkipListMap<>()); }
Source:
<code>public Map<byte[], Iterator<Map.Entry<Cell, byte[]>>> getRowsColumnRangeIterator(TableReference tableRef, Iterable<byte[]> rows, BatchColumnRangeSelection columnRangeSelection) { checkGetPreconditions(tableRef); if (Iterables.isEmpty(rows)) { return ImmutableMap.of(); } hasReads = true; Map<byte[], RowColumnRangeIterator> rawResults = keyValueService.getRowsColumnRange(tableRef, rows, columnRangeSelection, getStartTimestamp()); ImmutableSortedMap.Builder<byte[], Iterator<Map.Entry<Cell, byte[]>>> postFilteredResults = <START> ImmutableSortedMap.orderedBy(UnsignedBytes.lexicographicalComparator()); <END> for (Map.Entry<byte[], RowColumnRangeIterator> e : rawResults.entrySet()) { byte[] row = e.getKey(); RowColumnRangeIterator rawIterator = e.getValue(); Iterator<Map.Entry<Cell, byte[]>> postFilteredIterator = getPostFilteredColumns(tableRef, columnRangeSelection, row, rawIterator); postFilteredResults.put(row, postFilteredIterator); } return postFilteredResults.build(); }</code><technical_language>nit: I in other places PtBytes#BYTES_COMPARATOR shim this method. I noticed</technical_language>

Target:
public Map<byte[], Iterator<Map.Entry<Cell, byte[]>>> getRowsColumnRangeIterator(TableReference tableRef, Iterable<byte[]> rows, BatchColumnRangeSelection columnRangeSelection) { checkGetPreconditions(tableRef); if (Iterables.isEmpty(rows)) { return ImmutableMap.of(); } hasReads = true; Map<byte[], RowColumnRangeIterator> rawResults = keyValueService.getRowsColumnRange(tableRef, rows, columnRangeSelection, getStartTimestamp()); ImmutableSortedMap.Builder<byte[], Iterator<Map.Entry<Cell, byte[]>>> postFilteredResults = ImmutableSortedMap.orderedBy(PtBytes.BYTES_COMPARATOR); for (Map.Entry<byte[], RowColumnRangeIterator> e : rawResults.entrySet()) { byte[] row = e.getKey(); RowColumnRangeIterator rawIterator = e.getValue(); Iterator<Map.Entry<Cell, byte[]>> postFilteredIterator = getPostFilteredColumns(tableRef, columnRangeSelection, row, rawIterator); postFilteredResults.put(row, postFilteredIterator); } return postFilteredResults.build(); }
Source:
<code><START> public synchronized void setFunctionModels(List<FunctionModel> newFunctionModels) { <END> List<FunctionModel> oldFunctionModels = functionModels; this.functionModels = ObservableCollections.observableList(newFunctionModels); pcs.firePropertyChange(PROP_FUNCTION_MODELS, oldFunctionModels, functionModels); }</code><technical_language>is reason for setting FunctionModels VisualizerDataModel? This list of FunctionModels independent SedModels' functions, correct</technical_language>

Target:
private synchronized void setFunctionModels(List<FunctionModel> newFunctionModels) { List<FunctionModel> oldFunctionModels = functionModels; this.functionModels = ObservableCollections.observableList(newFunctionModels); pcs.firePropertyChange(PROP_FUNCTION_MODELS, oldFunctionModels, functionModels); }
Source:
<code>protected void setValueChecked(String fieldName, Object newValue) { Object existingValue = getValueUnchecked(fieldName); ChangeSpec spec = new ChangeSpec(this, fieldName, existingValue, newValue); boolean isNewlyCreated = requestScope.getNewPersistentResources().contains(this); if (!isNewlyCreated) { runTriggers(OnUpdatePreSecurity.class, CLASS_NO_FIELD); runTriggers(OnUpdatePreSecurity.class, fieldName, Optional.of(spec)); <START> checkFieldAwareDeferPermissions(UpdatePermission.class, fieldName, newValue, existingValue); <END> } setValue(fieldName, newValue); }</code><technical_language>This correct is right. remapped create permission in ActivePermissionExectutor</technical_language>

Target:
protected void setValueChecked(String fieldName, Object newValue) { Object existingValue = getValueUnchecked(fieldName); ChangeSpec spec = new ChangeSpec(this, fieldName, existingValue, newValue); boolean isNewlyCreated = requestScope.getNewPersistentResources().contains(this); if (!isNewlyCreated) { runTriggers(OnUpdatePreSecurity.class, CLASS_NO_FIELD); runTriggers(OnUpdatePreSecurity.class, fieldName, Optional.of(spec)); } checkFieldAwareDeferPermissions(UpdatePermission.class, fieldName, newValue, existingValue); setValue(fieldName, newValue); }
Source:
<code>private Notification updateNotifications() { String contentTitle = getString(R.string.download_notification_title); int numDownloads = requester.getNumberOfDownloads(); String downloadsLeft; if (numDownloads > 0) { <START> int downloads = requester.getNumberOfDownloads(); <END> downloadsLeft = getResources() .getQuantityString(R.plurals.downloads_left, downloads, downloads); } else { downloadsLeft = getString(R.string.downloads_processing); } if (notificationCompatBuilder != null) { StringBuilder bigText = new StringBuilder(""); for (int i = 0; i < downloads.size(); i++) { Downloader downloader = downloads.get(i); final DownloadRequest request = downloader .getDownloadRequest(); if (request.getFeedfileType() == Feed.FEEDFILETYPE_FEED) { if (request.getTitle() != null) { if (i > 0) { bigText.append("\n"); } bigText.append("\u2022 " + request.getTitle()); } } else if (request.getFeedfileType() == FeedMedia.FEEDFILETYPE_FEEDMEDIA) { if (request.getTitle() != null) { if (i > 0) { bigText.append("\n"); } bigText.append("\u2022 " + request.getTitle() + " (" + request.getProgressPercent() + "%)"); } } } notificationCompatBuilder.setContentTitle(contentTitle); notificationCompatBuilder.setContentText(downloadsLeft); if (bigText != null) { notificationCompatBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText.toString())); } return notificationCompatBuilder.build(); } return null; }</code><technical_language>re-use numDownloads</technical_language>

Target:
private Notification updateNotifications() { String contentTitle = getString(R.string.download_notification_title); int numDownloads = requester.getNumberOfDownloads(); String downloadsLeft; if (numDownloads > 0) { downloadsLeft = getResources() .getQuantityString(R.plurals.downloads_left, numDownloads, numDownloads); } else { downloadsLeft = getString(R.string.downloads_processing); } if (notificationCompatBuilder != null) { StringBuilder bigText = new StringBuilder(""); for (int i = 0; i < downloads.size(); i++) { Downloader downloader = downloads.get(i); final DownloadRequest request = downloader .getDownloadRequest(); if (request.getFeedfileType() == Feed.FEEDFILETYPE_FEED) { if (request.getTitle() != null) { if (i > 0) { bigText.append("\n"); } bigText.append("\u2022 " + request.getTitle()); } } else if (request.getFeedfileType() == FeedMedia.FEEDFILETYPE_FEEDMEDIA) { if (request.getTitle() != null) { if (i > 0) { bigText.append("\n"); } bigText.append("\u2022 " + request.getTitle() + " (" + request.getProgressPercent() + "%)"); } } } notificationCompatBuilder.setContentTitle(contentTitle); notificationCompatBuilder.setContentText(downloadsLeft); if (bigText != null) { notificationCompatBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText.toString())); } return notificationCompatBuilder.build(); } return null; }
Source:
<code>public IAtsUser getTransitionAsUser() throws OseeCoreException { IAtsUser user = helper.getTransitionUser(); if (user == null) { <START> System.err.println("Unexpected: AtsCore.getUserService().getCurrentUser();"); <END> user = AtsCore.getUserService().getCurrentUser(); } return user; }</code><technical_language>this a thrown exception</technical_language>

Target:
public IAtsUser getTransitionAsUser() throws OseeCoreException { IAtsUser user = helper.getTransitionUser(); if (user == null) { user = AtsCore.getUserService().getCurrentUser(); } return user; }
Source:
<code>public @ResponseBody String ping( @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) final String accessToken, @RequestHeader(value = "User-Agent", defaultValue = "unknown") String userAgent, HttpServletRequest request) { <START> String ipAddress = request.getHeader(com.google.common.net.HttpHeaders.X_FORWARDED_FOR); <END> if (ipAddress == null) { ipAddress = request.getRemoteAddr(); } log.info("Requesting download of sentinel object id with access token (MD5) from and client version {}", identifier(accessToken), ipAddress, userAgent); return downloadService.getSentinelObject(); }</code><technical_language>Static import</technical_language>

Target:
public @ResponseBody String ping( @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) final String accessToken, @RequestHeader(value = "User-Agent", defaultValue = "unknown") String userAgent, HttpServletRequest request) { val ipAddress = RequestHeaderUtils.getIpAddress(request); log.info("Requesting download of sentinel object id with access token (MD5) from and client version {}", identifier(accessToken), ipAddress, userAgent); return downloadService.getSentinelObject(); }
Source:
<code>public void testGetNonExistingImage() throws Exception { MockWebServer server = mockWebServer(); <START> server.enqueue(new MockResponse().setResponseCode(500).setBody(payloadFromResource("/image/image-not-found.xml"))); <END> ProfitBricksApi pbApi = api(server.getUrl(rootUrl)); ImageApi api = pbApi.imageApi(); String id = "random-non-existing-id"; try { Image image = api.getImage(id); assertRequestHasCommonProperties(server.takeRequest()); assertNull(image); } finally { pbApi.close(); server.shutdown(); } }</code><technical_language>Hmmm this test depends ResponseStatusFromPayloadHttpCommandExecutorService fixing response code. if _real_ provider returns a 500, configure a 404 response API works, coupling class. ResponseStatusFromPayloadHttpCommandExecutorService tests care status is properly fixed enough</technical_language>

Target:
public void testGetNonExistingImage() throws Exception { MockWebServer server = mockWebServer(); server.enqueue(new MockResponse().setResponseCode(404)); ProfitBricksApi pbApi = api(server.getUrl(rootUrl)); ImageApi api = pbApi.imageApi(); String id = "random-non-existing-id"; try { Image image = api.getImage(id); assertRequestHasCommonProperties(server.takeRequest()); assertNull(image); } finally { pbApi.close(); server.shutdown(); } }
Source:
<code><START> public ConfigBuilder withSchema(Schema readerSchema) { <END> conf.set(KITE_READER_SCHEMA, readerSchema.toString()); return this; }</code><technical_language>this, add validation class set a view. Also, methods views call appropriate. possibly add select(String...)</technical_language>

Target:
public ConfigBuilder withSchema(Schema readerSchema) { Class<?> type = conf.getClass(KITE_TYPE, null); Preconditions.checkArgument(type == null, "Can't configure a reader schema when a type is already set: {}", type); conf.set(KITE_READER_SCHEMA, readerSchema.toString()); return this; }
Source:
<code>public void testRandomDigit() { for (int i = 0; i < 1000; ++i) { int value = faker.number().randomDigit(); <START> assertTrue(value <= 9 && value >= 0); <END> } }</code><technical_language>hamcrest matchers for consistency in tests for assertions? Thanks</technical_language>

Target:
public void testRandomDigit() { for (int i = 0; i < 1000; ++i) { int value = faker.number().randomDigit(); assertThat(value, is(lessThanOrEqualTo(9))); assertThat(value, is(greaterThanOrEqualTo(0))); } }
Source:
<code>public void testWithValidIgw() { DescribeRouteTablesResult describeRouteTablesResult = new DescribeRouteTablesResult(); <START> RouteTable routeTable = new RouteTable().withVpcId(VPC_ID).withVpcId(VPC_ID); <END> Route route = new Route(); route.setGatewayId(GATEWAY_ID); route.setDestinationCidrBlock(OPEN_CIDR_BLOCK); routeTable.setRoutes(List.of(route)); RouteTableAssociation routeTableAssociation = new RouteTableAssociation(); routeTableAssociation.setSubnetId(SUBNET_ID); routeTable.setAssociations(List.of(routeTableAssociation)); describeRouteTablesResult.setRouteTables(List.of(routeTable)); boolean hasInternetGateway = awsSubnetIgwExplorer.hasInternetGatewayOfSubnet(describeRouteTablesResult, SUBNET_ID, VPC_ID); assertTrue(hasInternetGateway); }</code><technical_language>duplicated</technical_language>

Target:
public void testWithValidIgw() { DescribeRouteTablesResult describeRouteTablesResult = new DescribeRouteTablesResult(); RouteTable routeTable = new RouteTable().withVpcId(VPC_ID); Route route = new Route(); route.setGatewayId(GATEWAY_ID); route.setDestinationCidrBlock(OPEN_CIDR_BLOCK); routeTable.setRoutes(List.of(route)); RouteTableAssociation routeTableAssociation = new RouteTableAssociation(); routeTableAssociation.setSubnetId(SUBNET_ID); routeTable.setAssociations(List.of(routeTableAssociation)); describeRouteTablesResult.setRouteTables(List.of(routeTable)); boolean hasInternetGateway = awsSubnetIgwExplorer.hasInternetGatewayOfSubnet(describeRouteTablesResult, SUBNET_ID, VPC_ID); assertTrue(hasInternetGateway); }
Source:
<code>public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); if (baseClass.equals(Device.class)) { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); } Context.getPermissionsManager().checkPermission(baseClass, getUserId(), id); BaseObjectManager<T> manager = Context.getManager(baseClass); manager.removeItem(id); if (manager instanceof SimpleObjectManager) { ((SimpleObjectManager<T>) manager).refreshUserItems(); } <START> if (manager instanceof ExtendedObjectManager) { <END> ((ExtendedObjectManager<T>) manager).refreshExtendedPermissions(); } if (baseClass.equals(Group.class) || baseClass.equals(Device.class) || baseClass.equals(User.class)) { Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); if (baseClass.equals(User.class)) { Context.getPermissionsManager().refreshAllUsersPermissions(); } else { Context.getPermissionsManager().refreshAllExtendedPermissions(); } } if (baseClass.equals(Device.class)) { Context.getAliasesManager().removeDevice(id); } return Response.noContent().build(); }</code><technical_language>else</technical_language>

Target:
public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); if (baseClass.equals(Device.class)) { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); } Context.getPermissionsManager().checkPermission(baseClass, getUserId(), id); BaseObjectManager<T> manager = Context.getManager(baseClass); manager.removeItem(id); if (manager instanceof SimpleObjectManager) { ((SimpleObjectManager<T>) manager).refreshUserItems(); if (manager instanceof ExtendedObjectManager) { ((ExtendedObjectManager<T>) manager).refreshExtendedPermissions(); } } if (baseClass.equals(Group.class) || baseClass.equals(Device.class) || baseClass.equals(User.class)) { Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); if (baseClass.equals(User.class)) { Context.getPermissionsManager().refreshAllUsersPermissions(); } else { Context.getPermissionsManager().refreshAllExtendedPermissions(); } } if (baseClass.equals(Device.class)) { Context.getAliasesManager().removeDevice(id); } return Response.noContent().build(); }
Source:
<code>private List<EmailLogEntry> filterLogsForEmailLogPage(List<AppLogLine> appLogLines, AdminEmailLogPageData data) { List<EmailLogEntry> emailLogs = new LinkedList<EmailLogEntry>(); for (AppLogLine appLog : appLogLines) { String logMsg = appLog.getLogMessage(); boolean isNotEmailLog = !logMsg.contains("TEAMMATESEMAILLOG"); if (isNotEmailLog) { continue; } EmailLogEntry emailLogEntry = new EmailLogEntry(appLog); <START> if (emailLogEntry.isTestData() && !data.isShouldShowAll()) { <END> continue; } if (data.shouldShowLog(emailLogEntry)) { emailLogs.add(emailLogEntry); } } return emailLogs; }</code><technical_language>possibly moved shouldShowLog of PageData class checks for a emailLogEntry included is located in place</technical_language>

Target:
private List<EmailLogEntry> filterLogsForEmailLogPage(List<AppLogLine> appLogLines, AdminEmailLogPageData data) { List<EmailLogEntry> emailLogs = new LinkedList<EmailLogEntry>(); for (AppLogLine appLog : appLogLines) { String logMsg = appLog.getLogMessage(); boolean isNotEmailLog = !logMsg.contains("TEAMMATESEMAILLOG"); if (isNotEmailLog) { continue; } EmailLogEntry emailLogEntry = new EmailLogEntry(appLog); if (data.shouldShowLog(emailLogEntry)) { emailLogs.add(emailLogEntry); } } return emailLogs; }
Source:
<code>private boolean isJandexSetFlagsAvailable() { try { <START> Method setFlags = GetDeclaredMethodAction.of(ClassFileInfo.class, "setFlags").run(); <END> return setFlags != null; } catch (Exception e) { return false; } }</code><technical_language>I accurate, like: Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(ClassFileInfo.class, "setFlags", new Class<?>[]{ short.class }));</technical_language>

Target:
private boolean isJandexSetFlagsAvailable() { try { Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(ClassFileInfo.class, "setFlags", short.class)); return setFlags != null; } catch (Exception e) { return false; } }
Source:
<code>public int compareTo(final Scale scale) { if (!scale.unit.equals(scale.unit)) { throw new RuntimeException("Unable to compare scales in different units"); } <START> return new Double(this.resolution).compareTo(new Double(scale.resolution)); <END> }</code><technical_language>please static Double.compare</technical_language>

Target:
public int compareTo(final Scale scale) { if (!this.unit.equals(scale.unit)) { throw new RuntimeException("Unable to compare scales in different units"); } return Double.compare(this.resolution, scale.resolution); }
Source:
<code>public void configure(final MapperFactory mapperFactory) { mapperFactory.getConverterFactory().registerConverter(new CosemDateTimeConverter(this)); mapperFactory.getConverterFactory().registerConverter(new AdministrativeStatusResponseConverter()); mapperFactory.getConverterFactory().registerConverter(new FirmwareVersionConverter()); mapperFactory.getConverterFactory().registerConverter(new GetAttributeValuesResponseConverter()); <START> mapperFactory.getConverterFactory().registerConverter(new GetConfigurationObjectResponseConverter()); <END> }</code><technical_language>Some time a substantial effort remove unnecessary Orika converters code. is, lots of mapping works out of box if follow a couple of reasonable conventions. In this case, mapping work OK if * this line registering GetConfigurationObjectResponseConverter is removed; * GetConfigurationObjectResponseConverter is removed; * GetConfigurationResponseDto in Shared is modified, removing "Dto" end of name of field constructor argument configurationObjectDto end of name of getter method for this field</technical_language>

Target:
public void configure(final MapperFactory mapperFactory) { mapperFactory.getConverterFactory().registerConverter(new CosemDateTimeConverter(this)); mapperFactory.getConverterFactory().registerConverter(new AdministrativeStatusResponseConverter()); mapperFactory.getConverterFactory().registerConverter(new FirmwareVersionConverter()); mapperFactory.getConverterFactory().registerConverter(new GetAttributeValuesResponseConverter()); }
Source:
<code>public boolean sendMessage(ChatMessage message) { <START> return ChatManager.getInstance(context).enqueueOutGoingMessageQueue(message.convertMessageToJson()) && this.pushMessage(message); <END> }</code><technical_language>break long line</technical_language>

Target:
public boolean sendMessage(ChatMessage message) { return ChatManager .getInstance() .enqueueOutGoingMessageQueue(message.convertMessageToJson()) && this.pushMessage(message); }
Source:
<code>protected static boolean isFieldValueNotSet(final Object field) { <START> return field == null || ObjectHelper.isEmpty(field); <END> }</code><technical_language>ObjectHelper#isEmpty contains null check. suggestion return ObjectHelper.isEmpty(field);</technical_language>

Target:
protected static boolean isFieldValueNotSet(final Object field) { return ObjectHelper.isEmpty(field); }
Source:
<code>public String getJdbcUrl() { if (getUriInfo().getUriString().startsWith(JDBC_PREFIX)) { return getUriInfo().getUriString(); } <START> return String.format("jdbc:%s://%s:%d/%s", <END> jdbcUrlDatabaseType, getHost(), getPort(), getPath()); }</code><technical_language>created JDBC URL include username password credentials. this needed for authenticated database connections</technical_language>

Target:
public String getJdbcUrl() { if (getUriInfo().getUriString().startsWith(JDBC_PREFIX)) { return getUriInfo().getUriString(); } return String.format("jdbc:%s://%s:%d/%s:user=%s;password=%s;", jdbcUrlDatabaseType, getHost(), getPort(), getPath(), getUserName(), getPassword()); }
Source:
<code>public void deleteNodeTestEntityNotFound_chef() throws EntityNotFoundException, ClientProtocolException, IOException, NodeExecutionException { HttpResponse httpResponse= mock(HttpResponse.class); StatusLine statusLine= mock(StatusLine.class); when(httpResponse.getStatusLine()).thenReturn(statusLine); when(httpResponse.getStatusLine().getStatusCode()).thenReturn(200); when(client.execute((HttpUriRequest) anyObject())).thenReturn(httpResponse); when(propertiesProvider.getProperty(anyString())).thenReturn("URL"); List<ProductInstance> productInstances = new ArrayList<ProductInstance>(); productInstances.add(new ProductInstance()); when(productInstanceDao.findByHostname(anyString())).thenThrow(EntityNotFoundException.class); nodeManager.nodeDelete("test", "testError"); <START> <END> }</code><technical_language>please add verify assert</technical_language>

Target:
public void deleteNodeTestEntityNotFound_chef() throws EntityNotFoundException, ClientProtocolException, IOException, NodeExecutionException { HttpResponse httpResponse= mock(HttpResponse.class); StatusLine statusLine= mock(StatusLine.class); when(httpResponse.getStatusLine()).thenReturn(statusLine); when(httpResponse.getStatusLine().getStatusCode()).thenReturn(200); when(client.execute((HttpUriRequest) anyObject())).thenReturn(httpResponse); when(propertiesProvider.getProperty(anyString())).thenReturn("URL"); List<ProductInstance> productInstances = new ArrayList<ProductInstance>(); productInstances.add(new ProductInstance()); when(productInstanceDao.findByHostname(anyString())).thenThrow(EntityNotFoundException.class); nodeManager.nodeDelete("test", "testError"); verify(httpResponse,times(2)).getStatusLine(); verify(client, times(1)).execute((HttpUriRequest) anyObject()); }
Source:
<code>CircuitBreaker(long timeout, int failureThreshold, long retryTimePeriod) { this.state = State.CLOSED; this.failureThreshold = failureThreshold; this.timeout = timeout; this.retryTimePeriod = retryTimePeriod; <START> this.lastFailureTime = System.nanoTime() + 1000 * 1000 * 1000 * 1000; <END> this.failureCount = 0; }</code><technical_language>constant? a bit cryptic</technical_language>

Target:
CircuitBreaker(long timeout, int failureThreshold, long retryTimePeriod) { this.state = State.CLOSED; this.failureThreshold = failureThreshold; this.timeout = timeout; this.retryTimePeriod = retryTimePeriod; this.lastFailureTime = System.nanoTime() + futureTime; this.failureCount = 0; }
Source:
<code>private void validateTypeValue(Map<String, Object> rootObject) throws CatalogTransformerException { Object typeValue = rootObject.get(CompositeGeometry.TYPE_KEY); <START> if (typeValue == null || !typeValue.equals("Feature")) { <END> throw new CatalogTransformerException( new UnsupportedOperationException( "Only supported type is Feature, not [" + typeValue + "]")); } }</code><technical_language>Reversing check more optimal: if (!"Feature".equals(typeValue))</technical_language>

Target:
private void validateTypeValue(Map<String, Object> rootObject) throws CatalogTransformerException { Object typeValue = rootObject.get(CompositeGeometry.TYPE_KEY); if (!"Feature".equals(typeValue)) { throw new CatalogTransformerException( new UnsupportedOperationException( "Only supported type is Feature, not [" + typeValue + "]")); } }
Source:
<code>protected void innerMap( InputRow inputRow, Object value, Context context ) throws IOException, InterruptedException { final Optional<Bucket> bucket = getConfig().getBucket(inputRow); if (!bucket.isPresent()) { throw new ISE("WTF?! No bucket found for row: %s", inputRow); } final long truncatedTimestamp = granularitySpec.getQueryGranularity().truncate(inputRow.getTimestampFromEpoch()); final byte[] hashedDimensions = hashFunction.hashBytes( HadoopDruidIndexerConfig.jsonMapper.writeValueAsBytes( Rows.toGroupKey( truncatedTimestamp, inputRow ) ) ).asBytes(); context.write( new SortableBytes( bucket.get().toGroupKey(), ByteBuffer.allocate(Longs.BYTES + hashedDimensions.length) .putLong(truncatedTimestamp) .put(hashedDimensions) .array() ).toBytesWritable(), <START> new BytesWritable(InputRowHelper.toBytes(inputRow, config.getSchema().getDataSchema().getAggregators())) <END> ); }</code><technical_language>aggregators change. Get reuse that..</technical_language>

Target:
protected void innerMap( InputRow inputRow, Object value, Context context ) throws IOException, InterruptedException { final Optional<Bucket> bucket = getConfig().getBucket(inputRow); if (!bucket.isPresent()) { throw new ISE("WTF?! No bucket found for row: %s", inputRow); } final long truncatedTimestamp = granularitySpec.getQueryGranularity().truncate(inputRow.getTimestampFromEpoch()); final byte[] hashedDimensions = hashFunction.hashBytes( HadoopDruidIndexerConfig.jsonMapper.writeValueAsBytes( Rows.toGroupKey( truncatedTimestamp, inputRow ) ) ).asBytes(); context.write( new SortableBytes( bucket.get().toGroupKey(), ByteBuffer.allocate(Longs.BYTES + hashedDimensions.length) .putLong(truncatedTimestamp) .put(hashedDimensions) .array() ).toBytesWritable(), new BytesWritable(InputRowSerde.toBytes(inputRow, aggregators)) ); }
Source:
<code>public void write(NullWritable key, Text value) throws IOException, InterruptedException { PutRecordRequest putRecordRequest = new PutRecordRequest(); <START> putRecordRequest.setStreamName(context.getConfiguration().get(Properties.KinesisRealtimeSink.NAME)); <END> String dist = distribute ? String.valueOf(Math.random()) : String.valueOf(distribute); putRecordRequest.setPartitionKey(dist); ByteBuffer buffer = ByteBuffer.wrap(value.toString().getBytes()); sendKinesisRecord(buffer, putRecordRequest); }</code><technical_language>put stream name in a class field, wont change call. (no need get property time)</technical_language>

Target:
public void write(NullWritable key, Text value) throws IOException, InterruptedException { PutRecordRequest putRecordRequest = new PutRecordRequest(); putRecordRequest.setStreamName(streamName); String dist = distribute ? String.valueOf(Math.random()) : String.valueOf(distribute); putRecordRequest.setPartitionKey(dist); ByteBuffer buffer = ByteBuffer.wrap(value.toString().getBytes()); sendKinesisRecord(buffer, putRecordRequest); }
Source:
<code>private void updateAttributes(final String typeDamage) { mSelectedArcGISFeature.loadAsync(); mSelectedArcGISFeature.addDoneLoadingListener(new Runnable() { @Override public void run() { if (mSelectedArcGISFeature.getLoadStatus() == LoadStatus.FAILED_TO_LOAD) { Log.d(getResources().getString(R.string.app_name), "Error while loading feature"); } mSelectedArcGISFeature.getAttributes().put("typdamage", typeDamage); try { ListenableFuture<Boolean> mapViewResult = mServiceFeatureTable.updateFeatureAsync(mSelectedArcGISFeature); <START> if (mapViewResult.get().booleanValue()) { <END> final ListenableFuture<List<FeatureEditResult>> serverResult = mServiceFeatureTable.applyEditsAsync(); serverResult.addDoneListener(new Runnable() { @Override public void run() { try { List<FeatureEditResult> edits = serverResult.get(); if (edits.size() > 0) { if (!edits.get(0).hasCompletedWithErrors()) { Log.e(getResources().getString(R.string.app_name), "Feature successfully updated"); } } else { Log.e(getResources().getString(R.string.app_name), "The attribute type was not changed"); } showCallout((String) mSelectedArcGISFeature.getAttributes().get("typdamage")); } catch (Exception e) { Log.e(getResources().getString(R.string.app_name), "applying changes to the server failed: " + e.getMessage()); } } }); } } catch (Exception e) { Log.e(getResources().getString(R.string.app_name), "updating feature in the feature table failed: " + e.getMessage()); } } }); }</code><technical_language>remove unnecessary unboxing call Boolean constructor: java if (mapViewResult.get()) {</technical_language>

Target:
private boolean updateAttributes(final String typeDamage) { mSelectedArcGISFeature.loadAsync(); mSelectedArcGISFeature.addDoneLoadingListener(new Runnable() { @Override public void run() { if (mSelectedArcGISFeature.getLoadStatus() == LoadStatus.FAILED_TO_LOAD) { Log.d(getResources().getString(R.string.app_name), "Error while loading feature"); } mSelectedArcGISFeature.getAttributes().put("typdamage", typeDamage); try { ListenableFuture<Boolean> mapViewResult = mServiceFeatureTable.updateFeatureAsync(mSelectedArcGISFeature); if (mapViewResult.get()) { final ListenableFuture<List<FeatureEditResult>> serverResult = mServiceFeatureTable.applyEditsAsync(); serverResult.addDoneListener(new Runnable() { @Override public void run() { try { List<FeatureEditResult> edits = serverResult.get(); if (edits.size() > 0) { if (!edits.get(0).hasCompletedWithErrors()) { Log.e(getResources().getString(R.string.app_name), "Feature successfully updated"); mFeatureUpdated = true; } } else { Log.e(getResources().getString(R.string.app_name), "The attribute type was not changed"); mFeatureUpdated = false; } showCallout((String) mSelectedArcGISFeature.getAttributes().get("typdamage")); } catch (Exception e) { Log.e(getResources().getString(R.string.app_name), "applying changes to the server failed: " + e.getMessage()); } } }); } } catch (Exception e) { Log.e(getResources().getString(R.string.app_name), "updating feature in the feature table failed: " + e.getMessage()); } } }); return mFeatureUpdated; }
Source:
<code><START> public DefaultCommandMatcher(Class<? extends ReplicableCommand> commandClass) { <END> this(commandClass, null, null, null, MATCH_ANY_COUNT); }</code><technical_language>I this. I is nice constraints based command type :)</technical_language>

Target:
public DefaultCommandMatcher(Class<? extends ReplicableCommand> commandClass) { this(commandClass, null, null, null); }
Source:
<code>public void startUp() { for (Pipe pipe : pipeList) { <START> pipe.startUp(); <END> } }</code><technical_language>call protected method. interact methods defined in Service interface. Please fix other places</technical_language>

Target:
public void startUp() { serviceManager.startAsync().awaitHealthy(); }