auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private PostModel handleRemoteAutoSave(boolean isError, PostModel post) { if (!isError && isUploadingPostForPreview()) { <START> mViewModel.hideSavingDialog(); <END> updateOnSuccessfulUpload(); ActivityLauncher.previewPostOrPageForResult( EditPostActivity.this, mSite, post, mPostLoadingState == PostLoadingState.UPLOADING_FOR_PREVIEW ? RemotePreviewLogicHelper.RemotePreviewType.REMOTE_PREVIEW : RemotePreviewLogicHelper.RemotePreviewType.REMOTE_PREVIEW_WITH_REMOTE_AUTO_SAVE ); updatePostLoadingAndDialogState(PostLoadingState.PREVIEWING, post); } else if (isError || isRemoteAutoSaveError()) { updatePostLoadingAndDialogState(PostLoadingState.NONE); mUploadUtilsWrapper.showSnackbarError(findViewById(R.id.editor_activity), getString(R.string.remote_preview_operation_error)); } return post; }</code><technical_language>wondering - need hide dialog remote-autosave fails? is handled in a code path</technical_language>

Target:
private PostModel handleRemoteAutoSave(boolean isError, PostModel post) { mViewModel.hideSavingDialog(); if (!isError && isUploadingPostForPreview()) { updateOnSuccessfulUpload(); ActivityLauncher.previewPostOrPageForResult( EditPostActivity.this, mSite, post, mPostLoadingState == PostLoadingState.UPLOADING_FOR_PREVIEW ? RemotePreviewLogicHelper.RemotePreviewType.REMOTE_PREVIEW : RemotePreviewLogicHelper.RemotePreviewType.REMOTE_PREVIEW_WITH_REMOTE_AUTO_SAVE ); updatePostLoadingAndDialogState(PostLoadingState.PREVIEWING, post); } else if (isError || isRemoteAutoSaveError()) { updatePostLoadingAndDialogState(PostLoadingState.NONE); mUploadUtilsWrapper.showSnackbarError(findViewById(R.id.editor_activity), getString(R.string.remote_preview_operation_error)); } return post; }
Source:
<code>public synchronized void addEncoding( long primarySSRC, long rtxSSRC, long fecSSRC, int order) { RTPEncoding encoding = new RTPEncoding(this, primarySSRC, rtxSSRC, fecSSRC); if (encoding.getPrimarySSRC() != -1) { encodingsBySSRC.put(encoding.getPrimarySSRC(), encoding); } if (encoding.getRTXSSRC() != -1) { encodingsBySSRC.put(encoding.getRTXSSRC(), encoding); } if (encoding.getFECSSRC() != -1) { encodingsBySSRC.put(encoding.getFECSSRC(), encoding); <START> } <END> encodingsByOrder.put(order, encoding); }</code><technical_language>I 3 ifs. I a simple function captures common source code easier understand</technical_language>

Target:
public synchronized void addEncoding( long primarySSRC, long rtxSSRC, long fecSSRC, int order) { RTPEncoding encoding = new RTPEncoding(this, primarySSRC, rtxSSRC, fecSSRC); encodingsBySSRC.put(encoding.getPrimarySSRC(), encoding); encodingsBySSRC.put(encoding.getRTXSSRC(), encoding); encodingsBySSRC.put(encoding.getFECSSRC(), encoding); encodingsByOrder.put(order, encoding); }
Source:
<code>private void displayMessage(String message, boolean bad, boolean suppressToast) { if(!suppressToast) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } if(isUsingNewUI()) { <START> adapter.setNotificationTextForButton(R.layout.home_sync_button, false, message); <END> } else { TextView syncMessage = (TextView)findViewById(R.id.home_sync_message); syncMessage.setText(message); int[] padding = {syncMessage.getPaddingLeft(), syncMessage.getPaddingTop(), syncMessage.getPaddingRight(),syncMessage.getPaddingBottom() }; if(bad){ syncMessage.setTextColor(getResources().getColor(R.color.red)); syncMessage.setTypeface(null, Typeface.BOLD); syncMessage.setBackgroundDrawable(getResources().getDrawable(R.drawable.bubble_danger)); } else{ syncMessage.setTextColor(getResources().getColor(R.color.black)); syncMessage.setTypeface(null, Typeface.NORMAL); syncMessage.setBackgroundDrawable(getResources().getDrawable(R.drawable.bubble)); } syncMessage.setPadding(padding[0],padding[1], padding[2], padding[3]); } }</code><technical_language>if messages stuff adapter anyway, move padding layout/typeface stuff button itself? button/message class moving styling command</technical_language>

Target:
private void displayMessage(String message, boolean bad, boolean suppressToast) { if (!suppressToast) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } adapter.setNotificationTextForButton(R.layout.home_sync_button, false, message); }
Source:
<code>protected void migrateComments(CoreSession session, RelationManager relationManager, CommentServiceConfig config, Statement statement) { Map<String, Object> ctxMap = Collections.singletonMap(ResourceAdapter.CORE_SESSION_CONTEXT_KEY, session); QNameResourceImpl object = (QNameResourceImpl) statement.getObject(); DocumentModel parent = (DocumentModel) relationManager.getResourceRepresentation(config.documentNamespace, object, ctxMap); QNameResourceImpl subject = (QNameResourceImpl) statement.getSubject(); DocumentModel comment = (DocumentModel) relationManager.getResourceRepresentation(config.commentNamespace, subject, ctxMap); if (parent != null && comment != null) { comment.setPropertyValue(COMMENT_PARENT_ID, parent.getId()); session.saveDocument(comment); } Graph graph = relationManager.getGraph(config.graphName, session); graph.remove(statement); <START> } <END></code><technical_language>add a else a log.debug of statement some trace</technical_language>

Target:
protected void migrateComments(CoreSession session, RelationManager relationManager, CommentServiceConfig config, Statement statement) { Map<String, Object> ctxMap = Collections.singletonMap(ResourceAdapter.CORE_SESSION_CONTEXT_KEY, session); QNameResourceImpl object = (QNameResourceImpl) statement.getObject(); DocumentModel parent = (DocumentModel) relationManager.getResourceRepresentation(config.documentNamespace, object, ctxMap); QNameResourceImpl subject = (QNameResourceImpl) statement.getSubject(); DocumentModel comment = (DocumentModel) relationManager.getResourceRepresentation(config.commentNamespace, subject, ctxMap); if (parent != null && comment != null) { comment.setPropertyValue(COMMENT_PARENT_ID, parent.getId()); session.saveDocument(comment); } else if (parent == null && comment == null) { log.debug("Documents and do not exist, they can not be migrated", object.getLocalName(), subject.getLocalName()); } else { log.debug("Document does not exist, it can not be migrated", parent == null ? object.getLocalName() : subject.getLocalName()); } Graph graph = relationManager.getGraph(config.graphName, session); graph.remove(statement); }
Source:
<code>public void testRangeQueried() { List<Token> tokens = updateTokens(Arrays.asList(100, 200, 300, 400)); Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF_STANDARD1); cfs.clearUnsafe(); int rows = 100; for (int i = 0; i < rows; ++i) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 10, String.valueOf(i)); builder.clustering("c"); builder.add("val", String.valueOf(i)); builder.build().applyUnsafe(); } cfs.forceBlockingFlush(); PartitionRangeReadCommand command = (PartitionRangeReadCommand) Util.cmd(cfs).build(); StorageProxy.RangeIterator rangeIterator = new StorageProxy.RangeIterator(command, keyspace, ConsistencyLevel.ONE); StorageProxy.RangeCommandIterator data = new StorageProxy.RangeCommandIterator(rangeIterator, command, 1, 1000, keyspace, ConsistencyLevel.ONE, System.nanoTime()); int num = Util.size(data); assertEquals(rows, num); <START> assertEquals(tokens.size() + 1, data.rangesQueried()); <END> }</code><technical_language>helpful remind future reader a +1 ;)</technical_language>

Target:
public void testRangeQueried() { List<Token> tokens = setTokens(Arrays.asList(100, 200, 300, 400)); int vnodeCount = tokens.size() + 1; Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF_STANDARD1); cfs.clearUnsafe(); int rows = 100; for (int i = 0; i < rows; ++i) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 10, String.valueOf(i)); builder.clustering("c"); builder.add("val", String.valueOf(i)); builder.build().applyUnsafe(); } cfs.forceBlockingFlush(); PartitionRangeReadCommand command = (PartitionRangeReadCommand) Util.cmd(cfs).build(); Iterator<ReplicaPlan.ForRangeRead> ranges = rangeIterator(command, keyspace, false); StorageProxy.RangeCommandIterator data = new StorageProxy.RangeCommandIterator(ranges, command, 1, 1000, vnodeCount, System.nanoTime()); verifyRangeCommandIterator(data, rows, 2, vnodeCount); ranges = rangeIterator(command, keyspace, false); data = new StorageProxy.RangeCommandIterator(ranges, command, vnodeCount, 1000, vnodeCount, System.nanoTime()); verifyRangeCommandIterator(data, rows, 1, vnodeCount); ranges = rangeIterator(command, keyspace, false); data = new StorageProxy.RangeCommandIterator(ranges, command, 1, 1, vnodeCount, System.nanoTime()); verifyRangeCommandIterator(data, rows, vnodeCount, vnodeCount); ranges = rangeIterator(command, keyspace, true); data = new StorageProxy.RangeCommandIterator(ranges, command, 1, 1000, vnodeCount, System.nanoTime()); verifyRangeCommandIterator(data, rows, 1, vnodeCount); ranges = rangeIterator(command, keyspace, true); data = new StorageProxy.RangeCommandIterator(ranges, command, 1, 1, vnodeCount, System.nanoTime()); verifyRangeCommandIterator(data, rows, 1, vnodeCount); }
Source:
<code>private List<InstituteStats> convertToList( HashMap<String, HashMap<Integer, HashSet<String>>> institutes) { List<InstituteStats> list = new ArrayList<>(); <START> institutes.forEach((insStatName, inStatStudents) -> { <END> InstituteStats insStat = new InstituteStats(); insStat.name = insStatName; insStat.studentTotal = inStatStudents.get(STUDENT_INDEX).size(); insStat.instructorTotal = inStatStudents.get(INSTRUCTOR_INDEX).size(); list.add(insStat); }); return list; }</code><technical_language>object concerned is InstituteStats, map is institutes more apt name insName insStudents</technical_language>

Target:
private List<InstituteStats> convertToList( HashMap<String, HashMap<Integer, HashSet<String>>> institutes) { List<InstituteStats> list = new ArrayList<>(); institutes.forEach((insName, insStudents) -> { InstituteStats insStat = new InstituteStats(); insStat.name = insName; insStat.studentTotal = insStudents.get(STUDENT_INDEX).size(); insStat.instructorTotal = insStudents.get(INSTRUCTOR_INDEX).size(); list.add(insStat); }); return list; }
Source:
<code>@Override public V putIfAbsent(int key, V val) { lock.writeLock().lock(); try { int idx = find(key); if (idx < 0) { <START> put(key, val); <END> return null; } else return entries[idx].val; } finally { lock.writeLock().unlock(); } }</code><technical_language>"put(key, val)" extra lock need</technical_language>

Target:
@Override public V putIfAbsent(int key, V val) { int idx = find(key); if (idx < 0) { put(key, val); return null; } else return entries[idx].val; }
Source:
<code>static void modifyPersonaAccount(long id, Persona.Confidence confidence, String justification) throws CentralRepoException { CentralRepository cr = CentralRepository.getInstance(); if (cr == null) { throw new CentralRepoException("Failed to modify persona account, Central Repo is not enabled"); } <START> String updateClause = "UPDATE persona_accounts SET confidence_id = " + confidence.getLevelId() + ", justification = '" + justification + "' WHERE id = " + id; <END> cr.executeUpdateSQL(updateClause); }</code><technical_language>justification a single quote in it. I need check escape those</technical_language>

Target:
static void modifyPersonaAccount(long id, Persona.Confidence confidence, String justification) throws CentralRepoException { String updateClause = "UPDATE persona_accounts SET confidence_id = " + confidence.getLevelId() + ", justification = '" + justification + "' WHERE id = " + id; getCRInstance().executeUpdateSQL(updateClause); }
Source:
<code>public void flushAndReleaseResources() { Address lockHolder = getLockHolder(getIndexName()); if (lockHolder != null) { InfinispanDirectoryProvider directoryProvider = (InfinispanDirectoryProvider) getDirectoryProvider(); int activeDeleteTasks = directoryProvider.getActiveDeleteTasks(); while (activeDeleteTasks > 0) { try { Thread.sleep(POLL_WAIT); logDebug("Waiting for pending delete tasks, remaining: %s", activeDeleteTasks); activeDeleteTasks = directoryProvider.getActiveDeleteTasks(); } catch (InterruptedException e) { <START> Thread.currentThread().interrupt(); <END> } } logDebug("Flushing directory provider"); super.flushAndReleaseResources(); } }</code><technical_language>This get in infinite loop if :-1: If want ignore interrupt need set a boolean reset interrupt flag of while loop</technical_language>

Target:
public void flushAndReleaseResources() { Address lockHolder = getLockHolder(getIndexName()); if (lockHolder != null) { InfinispanDirectoryProvider directoryProvider = (InfinispanDirectoryProvider) getDirectoryProvider(); int activeDeleteTasks = directoryProvider.getActiveDeleteTasks(); boolean wasInterrupted = false; while (activeDeleteTasks > 0) { try { Thread.sleep(POLL_WAIT); logDebug("Waiting for pending delete tasks, remaining: %s", activeDeleteTasks); activeDeleteTasks = directoryProvider.getActiveDeleteTasks(); } catch (InterruptedException e) { wasInterrupted = true; } } if (wasInterrupted) { Thread.currentThread().interrupt(); } logDebug("Flushing directory provider"); super.flushAndReleaseResources(); } }
Source:
<code>public void clickRemoveAvatar() { showAvatarControls(); avatarRemoveButton.click(); Alert alert = driver.switchTo().alert(); alert.accept(); hideAvatarControls(); <START> waitForElementByElement(avatarWrapper); <END> }</code><technical_language>add PageObjectLogging.log() in this method :)</technical_language>

Target:
public void clickRemoveAvatar() { showAvatarControls(); avatarRemoveButton.click(); Alert alert = driver.switchTo().alert(); alert.accept(); hideAvatarControls(); waitForElementByElement(avatarWrapper); PageObjectLogging.log("clickRemoveAvatar", "avatar remove button clicked", true); }
Source:
<code>private Thread getStuckThread (Thread mainThread) { if (fThreadGroup == null) return null; final int count = fThreadGroup.activeCount(); int enumSize = Math.max (count * 2, 100); int enumCount; Thread[] threads; ThreadMXBean mxBean = ManagementFactory.getThreadMXBean(); int loopCount = 0; while (true) { threads = new Thread[enumSize]; enumCount = fThreadGroup.enumerate (threads); if (enumCount < enumSize) break; enumSize += 100; if (++loopCount >= 5) return null; } Thread firstRunnable = null; Thread mostCpu = null; long maxCpuTime = 0; int runnableCount = 0; for (int i = 0; i < enumCount; i++) { if (threads[i].getState() == Thread.State.RUNNABLE) { runnableCount++; <START> if (firstRunnable == null) firstRunnable = threads[i]; <END> if (mxBean.isThreadCpuTimeSupported()) { try { long cpuTime = mxBean.getThreadCpuTime(threads[i].getId()); if (mostCpu == null || cpuTime > maxCpuTime) { mostCpu = threads[i]; maxCpuTime = cpuTime; } } catch (UnsupportedOperationException e) { } } } } Thread stuckThread = (runnableCount == 1) ? firstRunnable : ((mostCpu != null) ? mostCpu : firstRunnable); return (stuckThread == mainThread) ? null : stuckThread; }</code><technical_language>I code simplified a bit pulling out a cpuTime(Thread) method this class, returns actual cpu time estimate if supported, 0 otherwise, runnable thread participate in max-finding code</technical_language>

Target:
private Thread getStuckThread (Thread mainThread) { if (fThreadGroup == null) return null; Thread[] threadsInGroup = getThreadArray(fThreadGroup); if (threadsInGroup == null) return null; Thread stuckThread = null; long maxCpuTime = 0; for (Thread thread : threadsInGroup) { if (thread.getState() == Thread.State.RUNNABLE) { long threadCpuTime = cpuTime(thread); if (stuckThread == null || threadCpuTime > maxCpuTime) { stuckThread = thread; maxCpuTime = threadCpuTime; } } } return (stuckThread == mainThread) ? null : stuckThread; }
Source:
<code>public PackageMaterialPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { RepositoryConfiguration repositoryConfiguration = extension.getRepositoryConfiguration(descriptor.id()); com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration = extension.getPackageConfiguration(descriptor.id()); if (repositoryConfiguration == null) { throw new RuntimeException(format("Plugin[%s] returned null repository configuration", descriptor.id())); } if (packageConfiguration == null) { throw new RuntimeException(format("Plugin[%s] returned null package configuration", descriptor.id())); } <START> PluggableInstanceSettings pluginSettingsAndView = getPluginSettingsAndView(descriptor, extension); <END> return new PackageMaterialPluginInfo(descriptor, new PluggableInstanceSettings(configurations(repositoryConfiguration)), new PluggableInstanceSettings(configurations(packageConfiguration)), pluginSettingsAndView); }</code><technical_language>Do need tests for changes in this plugin info builder others</technical_language>

Target:
public PackageMaterialPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { RepositoryConfiguration repositoryConfiguration = extension.getRepositoryConfiguration(descriptor.id()); com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration = extension.getPackageConfiguration(descriptor.id()); if (repositoryConfiguration == null) { throw new RuntimeException(format("Plugin[%s] returned null repository configuration", descriptor.id())); } if (packageConfiguration == null) { throw new RuntimeException(format("Plugin[%s] returned null package configuration", descriptor.id())); } PluggableInstanceSettings pluginSettingsAndView = getPluginSettingsAndView(descriptor, extension); return new PackageMaterialPluginInfo(descriptor, new PluggableInstanceSettings(packageRepoConfigurations(repositoryConfiguration)), new PluggableInstanceSettings(packageRepoConfigurations(packageConfiguration)), pluginSettingsAndView); }
Source:
<code>public void save(OutputStream out) { try { PropertiesConfiguration pconf = newPropertiesConfiguration(); pconf.append(internalConfig); <START> new FileHandler(pconf).save(out); <END> } catch (ConfigurationException e) { throw new FluoException(e); } }</code><technical_language>FileHandler here. instead PropertiesConfigurationLayout: java StringWriter writer = new StringWriter(); pconf.getLayout().save(pconf, writer);</technical_language>

Target:
public void save(OutputStream out) { try { PropertiesConfiguration pconf = new PropertiesConfiguration(); pconf.append(internalConfig); pconf.getLayout().save(pconf, new OutputStreamWriter(out, UTF_8)); } catch (ConfigurationException e) { throw new FluoException(e); } }
Source:
<code>public Map<String, List<BuddyController.BuddyResource>> getEmbeddedResources() { if(getContent().getPrivateData() != null) { Optional<Set<BuddyDTO>> buddies = getContent().getPrivateData().getBuddies(); if(buddies.isPresent()) { return Collections.singletonMap(UserDTO.BUDDIES_REL_NAME, new BuddyController.BuddyResourceAssembler(getContent().getID()).toResources(buddies.get())); } } return Collections.emptyMap(); <START> } <END></code><technical_language>Remove nesting moving return of empty collection if statement</technical_language>

Target:
public Map<String, List<BuddyController.BuddyResource>> getEmbeddedResources() { if(getContent().getPrivateData() == null) { return Collections.emptyMap(); } Set<BuddyDTO> buddies = getContent().getPrivateData().getBuddies(); return Collections.singletonMap(UserDTO.BUDDIES_REL_NAME, new BuddyController.BuddyResourceAssembler(getContent().getID()).toResources(buddies)); }
Source:
<code>void checkRowNumber() { Preconditions.checkArgument(dedicatedRowNumber() >= 0 && dedicatedRowNumber() < MAX_DEDICATED_ROWS, "Dedicated row number must be between 0 and %s inclusive, but it is %s.", <START> MAX_DEDICATED_ROWS, dedicatedRowNumber()); <END> }</code><technical_language>MAX_DEDICATED_ROWS - 1 (or line exclusive for upper bound)</technical_language>

Target:
void checkRowNumber() { Preconditions.checkArgument(dedicatedRowNumber() >= 0 && dedicatedRowNumber() < MAX_DEDICATED_ROWS, "Dedicated row number must be at least 0 and less than %s, but it is %s.", MAX_DEDICATED_ROWS, dedicatedRowNumber()); }
Source:
<code>public BufferedMultipleNodeCallField toBuffered() { Stream<BufferableHandle> bufferableHandleStream = paramValues.map(handle ->{ if(!(handle instanceof BufferableHandle)) throw new IllegalArgumentException("Default parameter must implement BufferableHandle."); <START> return new BytesHandle((BufferableHandle) handle); <END> }); return new BufferedMultipleNodeCallField(super.getParamName(), bufferableHandleStream); }</code><technical_language>Instead of constructing a BytesHandle here, return cast BufferableHandle conversion performed concurrently executing immediately call</technical_language>

Target:
public BufferedMultipleNodeCallField toBuffered() { Stream<BufferableHandle> bufferableHandleStream = paramValues.map(handle ->{ if(!(handle instanceof BufferableHandle)) throw new IllegalArgumentException("Default parameter must implement BufferableHandle."); return ((BufferableHandle) handle); }); return new BufferedMultipleNodeCallField(super.getParamName(), bufferableHandleStream); }
Source:
<code>public String toString() { <START> StringBuffer sbuf = new StringBuffer(); <END> for (long position = 0; position < this.size;) { if ((position + WORD_SIZE) < this.size) { int arrayPos = (int) (position >> LG_WORD_SIZE); sbuf.append(toString(this.array[arrayPos])); position += WORD_SIZE; } else { sbuf.append(getBit(position) ? "1" : "0"); position++; } } return sbuf.toString(); }</code><technical_language>Good a StringBuffer instead of a String. a StringBuilder instead</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); for (long position = 0; position < this.size;) { if ((position + WORD_SIZE) < this.size) { int arrayPos = (int) (position >> LG_WORD_SIZE); sb.append(wordToString(this.arrayOfBits[arrayPos])); position += WORD_SIZE; } else { sb.append(getBit(position) ? "1" : "0"); position++; } } return sb.toString(); }
Source:
<code>private void setUpAdapterFactoryRegistry(final IExtensionRegistry registry) { <START> adapterFactoryRegistry = Multimaps.synchronizedListMultimap(ArrayListMultimap <END> .<Collection<?>, RankedAdapterFactoryDescriptor> create()); adapterFactoryRegistryListener = new AdapterFactoryDescriptorRegistryListener( EMFCompareEditPlugin.PLUGIN_ID, FACTORY_PPID, getLog(), adapterFactoryRegistry); registry.addListener(adapterFactoryRegistryListener, PLUGIN_ID + "." + FACTORY_PPID); adapterFactoryRegistryListener.readRegistry(registry); }</code><technical_language>this is registry, this is backing data structure. Please rename 'adapterFactoryRegsitryBackingMultimap' (also rename 2nd parameter of constructor of RankedAdapterFactoryImpl parameter of listener)</technical_language>

Target:
private void setUpAdapterFactoryRegistry(final IExtensionRegistry registry) { adapterFactoryRegistryBackingMultimap = Multimaps.synchronizedListMultimap(ArrayListMultimap .<Collection<?>, RankedAdapterFactoryDescriptor> create()); adapterFactoryRegistryListener = new AdapterFactoryDescriptorRegistryListener( EMFCompareEditPlugin.PLUGIN_ID, FACTORY_PPID, getLog(), adapterFactoryRegistryBackingMultimap); registry.addListener(adapterFactoryRegistryListener, PLUGIN_ID + "." + FACTORY_PPID); adapterFactoryRegistryListener.readRegistry(registry); rankedAdapterFactoryRegistry = new RankedAdapterFactoryDescriptorRegistryImpl( ComposedAdapterFactory.Descriptor.Registry.INSTANCE, Multimaps .unmodifiableMultimap(adapterFactoryRegistryBackingMultimap)); }
Source:
<code>public String toString() { <START> return "Problem: " + message; <END> }</code><technical_language>is interesting show other attributes too</technical_language>

Target:
public String toString() { return "Problem: '" + message + "' at " + sourceLineNumber + ":" + sourceStart + "-" + sourceEnd; }
Source:
<code>public boolean include(TreeWalk walker) throws MissingObjectException, IncorrectObjectTypeException, IOException { pointer = null; if (walker.isSubtree()) { return walker.isRecursive(); } ObjectId objectId = walker.getObjectId(0); ObjectLoader object = walker.getObjectReader().open(objectId); if (object.isLarge()) { return false; } <START> ObjectStream stream = object.openStream(); byte[] buffer = new byte[VERSION_LINE.length]; int read = stream.read(buffer); if (read == VERSION_LINE.length && RawParseUtils.match(buffer, 0, VERSION_LINE) < 0) { return false; } <END> int line = 2; int foundKeys = 0; byte[][] values = new byte[REQUIRED_KEYS.length][]; buffer = object.getCachedBytes(); IntList lineMap = RawParseUtils.lineMap(buffer, 0, buffer.length); int lineMapSize = lineMap.size() - 1; for (int r = 0; r < REQUIRED_KEYS.length; r++) { byte[] key = REQUIRED_KEYS[r]; for (; line < lineMapSize; line++) { int lineStart = lineMap.get(line); int match = RawParseUtils.match(buffer, lineStart, key); if (match > 0) { foundKeys++; int len = lineMap.get(line + 1) - match - 1; values[r] = new byte[len]; System.arraycopy(buffer, match, values[r], 0, len); break; } } } if (foundKeys == REQUIRED_KEYS.length) { LongObjectId oid = LongObjectId.fromString(values[OID_INDEX], 0); int size = RawParseUtils.parseBase10(values[SIZE_INDEX], 0, new MutableInteger()); pointer = new LargeObjectPointer(oid, size); return true; } return false; }</code><technical_language>this needs rewritten handle 2 types of version headers</technical_language>

Target:
public boolean include(TreeWalk walker) throws MissingObjectException, IncorrectObjectTypeException, IOException { pointer = null; if (walker.isSubtree()) { return walker.isRecursive(); } ObjectId objectId = walker.getObjectId(0); ObjectLoader object = walker.getObjectReader().open(objectId); if (object.isLarge()) { return false; } ObjectStream stream = object.openStream(); byte[] buffer = new byte[VERSION_LINE_LEGACY.length]; int read = stream.read(buffer); if (!validVersionLine(read, buffer)) { return false; } int line = 2; int foundKeys = 0; byte[][] values = new byte[REQUIRED_KEYS.length][]; buffer = object.getCachedBytes(); IntList lineMap = RawParseUtils.lineMap(buffer, 0, buffer.length); int lineMapSize = lineMap.size() - 1; for (int r = 0; r < REQUIRED_KEYS.length; r++) { byte[] key = REQUIRED_KEYS[r]; for (; line < lineMapSize; line++) { int lineStart = lineMap.get(line); int match = RawParseUtils.match(buffer, lineStart, key); if (match > 0) { foundKeys++; int len = lineMap.get(line + 1) - match - 1; values[r] = new byte[len]; System.arraycopy(buffer, match, values[r], 0, len); break; } } } if (foundKeys == REQUIRED_KEYS.length) { LongObjectId oid = LongObjectId.fromString(values[OID_INDEX], 0); int size = RawParseUtils.parseBase10(values[SIZE_INDEX], 0, new MutableInteger()); pointer = new LargeObjectPointer(oid, size); return true; } return false; }
Source:
<code>private void informAppAboutAssignment(TaskRequest request, Container container) { Object task = request.getTask(); if (blacklistedNodes.contains(container.getNodeId()) <START> || task instanceof TaskAttempt && ((TaskAttempt) task).getUnhealthyNodesHistory().contains(container.getNodeId())) { <END> LOG.info("Container allocated for task on blacklisted node {}", container.getId(), container.getNodeId(), task); deallocateContainer(container.getId()); allocateTask(task, request.getCapability(), (request.getNodes() == null ? null : request.getNodes().toArray(new String[request.getNodes().size()])), (request.getRacks() == null ? null : request.getRacks().toArray(new String[request.getRacks().size()])), request.getPriority(), request.getContainerSignature(), request.getCookie()); } else { getContext().taskAllocated(request.getTask(), request.getCookie(), container); } }</code><technical_language>I informAppAboutAssignment avoid scheduling speculative attempt nodes running tasks, is good. However, consequence of deallocating free containers nodes running attempts speculated. If knew node slow, treat node unhealthy. choosing a tasks for speculation is a reasonable guess false positives. Instead work if check in tryAssignReuseContainer, tryAssignNewContainer, tryAssignTaskToIdleContainer? check early, prevent deallocating containers. In future, I passing node avoid AMRMClient requesting new containers prevent requesting a node avoid for a speculative task attempt. do now, I checked</technical_language>

Target:
private void informAppAboutAssignment(TaskRequest request, Container container) { if (blacklistedNodes.contains(container.getNodeId())) { Object task = request.getTask(); LOG.info("Container allocated for task on blacklisted node {}", container.getId(), container.getNodeId(), task); deallocateContainer(container.getId()); allocateTask(task, request.getCapability(), (request.getNodes() == null ? null : request.getNodes().toArray(new String[request.getNodes().size()])), (request.getRacks() == null ? null : request.getRacks().toArray(new String[request.getRacks().size()])), request.getPriority(), request.getContainerSignature(), request.getCookie()); } else { getContext().taskAllocated(request.getTask(), request.getCookie(), container); } }
Source:
<code>public static String getPartAtPosition(Iterable<String> parts, int pos) { String part = Iterables.get(parts, pos); if (StringUtils.isNotEmpty(part)) { return part; } <START> return null; <END> }</code><technical_language>return Strings.emptyToNull(part)</technical_language>

Target:
public static String getPartAtPosition(Iterable<String> parts, int pos) { String part = Iterables.get(parts, pos); return Strings.emptyToNull(part); }
Source:
<code>public void run() { try { <START> doProcess(); <END> } finally { super.run(); } }</code><technical_language>Again, processible renamed runnable, process run, doProcess remains is. I easily avoidable inconsistency</technical_language>

Target:
public void run() { try { doRun(); } finally { super.run(); } }
Source:
<code>private void validate() { <START> assertThat(localCommandBus, <END> Objects::nonNull, () -> new AxonConfigurationException( "The localCommandBus is a hard requirement and should be provided")); assertThat(restOperations, Objects::nonNull, () -> new AxonConfigurationException( "The RestOperations is a hard requirement and should be provided")); assertThat(serializer, Objects::nonNull, () -> new AxonConfigurationException( "The Serializer is a hard requirement and should be provided")); }</code><technical_language>Extraction a separate method</technical_language>

Target:
protected void validate() { assertNonNull(localCommandBus, "The local CommandBus is a hard requirement and should be provided"); assertNonNull(restOperations, "The RestOperations is a hard requirement and should be provided"); assertNonNull(serializer, "The Serializer is a hard requirement and should be provided"); }
Source:
<code>private static Map<JdbcQuery, List<Map<String, Object>>> getSqlQueryResults( Set<JdbcQuery> jdbcQueries, BatchLoaderEnvironment context ) { Map<JdbcQuery, List<Map<String, Object>>> allResults = new HashMap<>(); Map<Object, Object> keyContexts = context.getKeyContexts(); <START> for (JdbcQuery jdbcQuery : jdbcQueries) { <END> Connection connection = null; try { DataSource dataSource = ((DataSource) keyContexts.get(jdbcQuery)); connection = dataSource.getConnection(); allResults.put( jdbcQuery, getSqlQueryResult( jdbcQuery, connection ) ); } catch (SQLException e) { throw new RuntimeException(e); } finally { DbUtils.closeQuietly(connection); } } return allResults; }</code><technical_language>is goal of batching SQL queries in this way? run sequentially separate connections</technical_language>

Target:
private static Map<JdbcQuery, List<Map<String, Object>>> getSqlQueryResults( Set<JdbcQuery> jdbcQueries, BatchLoaderEnvironment context ) { Map<JdbcQuery, List<Map<String, Object>>> allResults = new HashMap<>(); Map<Object, Object> keyContexts = context.getKeyContexts(); List<CombinedQuery> combinedQueries = new ArrayList<>(); for (JdbcQuery jdbcQuery : jdbcQueries) { DataSource dataSource = ((DataSource) keyContexts.get(jdbcQuery)); if (combinedQueries.isEmpty()) { combinedQueries.add(new CombinedQuery(jdbcQuery, dataSource)); continue; } boolean foundOtherQueryToCombineWith = false; for (CombinedQuery combinedQuery : combinedQueries) { if (combinedQuery.combineWith(jdbcQuery)) { foundOtherQueryToCombineWith = true; break; } } if (!foundOtherQueryToCombineWith) { combinedQueries.add(new CombinedQuery(jdbcQuery, dataSource)); } } for (CombinedQuery combinedQuery : combinedQueries) { combinedQuery.executeAndAddToResults(allResults); } return allResults; }
Source:
<code>public boolean match(final ChangeData object) throws OrmException { <START> final Change c = object.change(dbProvider); <END> final ProjectState project = projectCache.get(c.getDest().getParentKey()); if (project == null) { return false; } final LabelType labelType = type(project.getLabelTypes(), type); final Set<Account.Id> allApprovers = new HashSet<Account.Id>(); final Set<Account.Id> approversThatVotedInCategory = new HashSet<Account.Id>(); for (PatchSetApproval p : object.currentApprovals(dbProvider)) { allApprovers.add(p.getAccountId()); if (p.getCategoryId().get().equals(labelType.getId())) { approversThatVotedInCategory.add(p.getAccountId()); if (match(c, p.getValue(), p.getAccountId(), labelType)) { return true; } } } final Set<Account.Id> approversThatDidNotVoteInCategory = new HashSet<Account.Id>(allApprovers); approversThatDidNotVoteInCategory.removeAll(approversThatVotedInCategory); for (Account.Id a : approversThatDidNotVoteInCategory) { if (match(c, 0, a, labelType)) { return true; } } return false; }</code><technical_language>This null if database modified change deleted</technical_language>

Target:
public boolean match(final ChangeData object) throws OrmException { final Change c = object.change(dbProvider); if (c == null) { return false; } final ProjectState project = projectCache.get(c.getDest().getParentKey()); if (project == null) { return false; } final LabelType labelType = type(project.getLabelTypes(), type); final Set<Account.Id> allApprovers = new HashSet<Account.Id>(); final Set<Account.Id> approversThatVotedInCategory = new HashSet<Account.Id>(); for (PatchSetApproval p : object.currentApprovals(dbProvider)) { allApprovers.add(p.getAccountId()); if (p.getCategoryId().get().equals(labelType.getId())) { approversThatVotedInCategory.add(p.getAccountId()); if (match(c, p.getValue(), p.getAccountId(), labelType)) { return true; } } } final Set<Account.Id> approversThatDidNotVoteInCategory = new HashSet<Account.Id>(allApprovers); approversThatDidNotVoteInCategory.removeAll(approversThatVotedInCategory); for (Account.Id a : approversThatDidNotVoteInCategory) { if (match(c, 0, a, labelType)) { return true; } } return false; }
Source:
<code>private String getOvnCentral() { Guid providerId = getParameters().getNetworkProviderId(); if (providerId != null) { Provider provider = providerDao.get(providerId); if (provider.getType() == ProviderType.EXTERNAL_NETWORK) { return <START> NetworkUtils.getIpAddress(provider.getUrl()); <END> } } return null; }</code><technical_language>if this method fails some reason return null, is correct behavior ? If decide ignore configure OVN host, please add event log warning. If decided fail process - fine well. user expect a successful installation requirement configured host, including OVN</technical_language>

Target:
private String getOvnCentral() { Guid providerId = getParameters().getNetworkProviderId(); if (providerId != null) { Provider provider = providerDao.get(providerId); if (provider.getType() == ProviderType.EXTERNAL_NETWORK) { String ovnCentral = NetworkUtils.getIpAddress(provider.getUrl()); if (ovnCentral == null) { throw new VdsInstallException( VDSStatus.InstallFailed, String.format( "Failed to extract OVN central IP from %1$s", provider.getUrl() ) ); } return ovnCentral; } } return null; }
Source:
<code>public ITestNGMethod getMethodDependingOn(String methodName, ITestNGMethod fromMethod) { List<ITestNGMethod> l = m_dependencies.get(methodName); if (l.isEmpty()) { l = m_dependencies.get(constructMethodNameUsingTestClass(methodName, fromMethod)); } if (l.isEmpty() && fromMethod.ignoreMissingDependencies()){ return fromMethod; } for (ITestNGMethod m : l) { Object fromMethodInstance = fromMethod.getInstance(); Object mInstance = m.getInstance(); if (mInstance != null && fromMethodInstance != null && fromMethodInstance.getClass().isAssignableFrom(mInstance.getClass())) { return m; } else { <START> return m; <END> } } throw new TestNGException("Method \"" + fromMethod + "\" depends on nonexistent method \"" + methodName + "\""); }</code><technical_language>indentation is 2 spaces in this file</technical_language>

Target:
public ITestNGMethod getMethodDependingOn(String methodName, ITestNGMethod fromMethod) { List<ITestNGMethod> l = m_dependencies.get(methodName); if (l.isEmpty()) { l = m_dependencies.get(constructMethodNameUsingTestClass(methodName, fromMethod)); } if (l.isEmpty() && fromMethod.ignoreMissingDependencies()){ return fromMethod; } for (ITestNGMethod m : l) { if (isSameInstance(fromMethod, m) || belongToDifferentClassHierarchy(fromMethod, m) || hasInstance(fromMethod, m)) { return m; } } throw new TestNGException("Method \"" + fromMethod + "\" depends on nonexistent method \"" + methodName + "\""); }
Source:
<code>private DatabaseRow getNextRow() throws SQLException { _numRowsInResult++; try { ResultSetMetaData rsmd = _queryResultSet.getMetaData(); int colCount = rsmd.getColumnCount(); DatabaseRow payloadRecord = new DatabaseRow(); for (int i = 1; i <= colCount; i++) { String colName = rsmd.getColumnName(i); <START> Object column = _queryResultSet.getObject(i); <END> payloadRecord.addField(colName, column, rsmd.getColumnType(i)); if (_chunkingKeys.containsKey(colName)) { if (column == null) { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, colName + " field is not expected to be null"); } _chunkingKeys.put(colName, column); } } return payloadRecord; } catch (SQLException e) { _metrics.updateErrorRate(); if (_skipBadMessagesEnabled) { LOG.warn("Skipping row due to SQL exception", e); _metrics.updateSkipBadMessagesRate(); } else { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, "Failed to interpret row and skipBadMessage not enabled", e); } return null; } }</code><technical_language>nitpick: a variable this is for this column in row, "colValue" (to consistent other variable "colName")</technical_language>

Target:
private DatabaseRow getNextRow() throws SQLException { _numRowsInResult++; try { ResultSetMetaData rsmd = _queryResultSet.getMetaData(); int colCount = rsmd.getColumnCount(); DatabaseRow payloadRecord = new DatabaseRow(); for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object columnValue = _queryResultSet.getObject(i); payloadRecord.addField(columnName, columnValue, rsmd.getColumnType(i)); if (_chunkingKeys.containsKey(columnName)) { if (columnValue == null) { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, columnName + " field is not expected to be null"); } _chunkingKeys.put(columnName, columnValue); } } return payloadRecord; } catch (SQLException e) { _metrics.updateErrorRate(); if (_skipBadMessagesEnabled) { LOG.warn("Skipping row due to SQL exception", e); _metrics.updateSkipBadMessagesRate(); } else { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, "Failed to interpret row and skipBadMessage not enabled", e); } return null; } }
Source:
<code>protected synchronized void onFirstPeerRegistered() { <START> mDocument.createDomProviderIfNoneExists(); <END> }</code><technical_language>Letting DOMProvider leak option, scratch (it memory)... lifecycle management, assertion domain modules a peer manager is reasonable, I fully accept this argument CSS DOM codependent code, designed here, assumes erroneously DOM is "real" owner supports in code protocol is laid out. I reference counting is right compromise here</technical_language>

Target:
protected synchronized void onFirstPeerRegistered() { mDocument.addRef(); mDocument.addUpdateListener(mListener); }
Source:
<code>protected void addVmToDb() { super.addVmToDb(); if (getVm().getOrigin() == OriginType.KVM) { ImportUtils.updateGraphicsDevices(getVm().getStaticData(), getStoragePool().getCompatibilityVersion()); <START> VmDeviceDao dao = DbFacade.getInstance().getVmDeviceDao(); <END> dao.saveAll(getVm().getStaticData().getManagedDeviceMap().values()); } }</code><technical_language>simply call getVmDeviceDao instead</technical_language>

Target:
protected void addVmToDb() { super.addVmToDb(); if (getVm().getOrigin() == OriginType.KVM) { ImportUtils.updateGraphicsDevices(getVm().getStaticData(), getStoragePool().getCompatibilityVersion()); getVmDeviceDao().saveAll(getVm().getStaticData().getManagedDeviceMap().values()); } }
Source:
<code>protected boolean validate() { if (!super.validate()) { return false; } StorageDomain dom = getStorageDomain(); if (dom == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } VDS vds = getVds(); StorageDomainToPoolRelationValidator domainPoolValidator = createDomainToPoolValidator(dom); <START> if (VDSStatus.Maintenance == vds.getStatus()) { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_HOST_IN_MAINTENANCE, String.format("$%1$s %2$s", "hostName", vds.getName())); } <END> if (!checkStorageDomain()) { return false; } boolean localFs = isLocalFs(dom); if (!localFs && !validate(domainPoolValidator.isStorageDomainNotInAnyPool())) { return false; } if (localFs && isDomainAttached(dom) && !canDetachDomain(getParameters().getDestroyingPool(), false)) { return false; } if (getParameters().getDoFormat() && !localFs && isStorageDomainAttached(dom)) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FORMAT_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } if (vds == null) { if (localFs) { if (!initializeVds()) { return false; } } else { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_INVALID_HOST_ID); } } if (dom.getStorageType().isOpenStackDomain()) { return failValidation(EngineMessage.ERROR_CANNOT_MANAGE_STORAGE_DOMAIN); } return true; }</code><technical_language>fail status - report status in error message too</technical_language>

Target:
protected boolean validate() { if (!super.validate()) { return false; } StorageDomain dom = getStorageDomain(); if (dom == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } VDS vds = getVds(); StorageDomainToPoolRelationValidator domainPoolValidator = createDomainToPoolValidator(dom); if (vds.getStatus() != VDSStatus.Up) { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_HOST_NOT_UP, String.format("$%1$s %2$s", "hostName", vds.getName())); } if (!checkStorageDomain()) { return false; } boolean localFs = isLocalFs(dom); if (!localFs && !validate(domainPoolValidator.isStorageDomainNotInAnyPool())) { return false; } if (localFs && isDomainAttached(dom) && !canDetachDomain(getParameters().getDestroyingPool(), false)) { return false; } if (getParameters().getDoFormat() && !localFs && isStorageDomainAttached(dom)) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FORMAT_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } if (vds == null) { if (localFs) { if (!initializeVds()) { return false; } } else { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_INVALID_HOST_ID); } } if (dom.getStorageType().isOpenStackDomain()) { return failValidation(EngineMessage.ERROR_CANNOT_MANAGE_STORAGE_DOMAIN); } return true; }
Source:
<code>public boolean isValidUser(String pluginId, String username, SecurityAuthConfig authConfig) { <START> String cacheKey = cacheKeyFor(IS_VALID_USER_CACHE_KEY, pluginId, username, authConfig); <END> Boolean fromCache = isValidUserCache.getIfPresent(cacheKey); if (fromCache == null) { fromCache = authorizationExtension.isValidUser(pluginId, username, authConfig); isValidUserCache.put(cacheKey, fromCache); } return fromCache; }</code><technical_language>This possibly simplified doing: java return cache.get(key, () -> { return expensiveComputation(); }) even: java cache = CacheBuilder.build((key) -> { return expensiveComputation(); }); ... return cache.get(thing);</technical_language>

Target:
public boolean isValidUser(String pluginId, String username, SecurityAuthConfig authConfig) { String cacheKey = cacheKeyFor(pluginId, username, authConfig); Boolean fromCache = isValidUserCache.getIfPresent(cacheKey); if (fromCache == null) { fromCache = authorizationExtension.isValidUser(pluginId, username, authConfig); isValidUserCache.put(cacheKey, fromCache); } return fromCache; }
Source:
<code>private Eh107CacheManager createCacheManager(URI uri, ClassLoader classLoader, CacheManagerBuilder<org.ehcache.CacheManager> builder) { Eh107CacheLoaderWriterProvider cacheLoaderWriterFactory = new Eh107CacheLoaderWriterProvider(); <START> Object[] serviceCreationConfigurations = builder.getServices().toArray(); <END> Jsr107Service jsr107Service = new DefaultJsr107Service(ServiceUtils.findSingletonAmongst(Jsr107Configuration.class, serviceCreationConfigurations)); Collection<Service> services = new ArrayList<>(4); services.add(cacheLoaderWriterFactory); services.add(jsr107Service); if (ServiceUtils.findSingletonAmongst(DefaultSerializationProviderConfiguration.class, serviceCreationConfigurations) == null) { services.add(new DefaultJsr107SerializationProvider()); } InternalCacheManager ehcacheManager = (InternalCacheManager) builder.build(true); return new Eh107CacheManager(this, ehcacheManager, new Properties(), classLoader, uri, new ConfigurationMerger(null, jsr107Service, cacheLoaderWriterFactory)); }</code><technical_language>Type safety messed here. code is for a ServiceCreationConfigurations builder return services. fix "extra services" logic catch services instances creation configs result in service instances. good common paths well</technical_language>

Target:
private Eh107CacheManager createCacheManager(URI uri, ClassLoader classLoader, CacheManagerBuilder<org.ehcache.CacheManager> builder) { Collection<Service> services = builder.getServices(); Collection<ServiceCreationConfiguration<?>> serviceCreationConfigurations = builder.getServiceConfigurations(); Jsr107Configuration jsr107Configuration = ServiceUtils.findSingletonAmongst(Jsr107Configuration.class, serviceCreationConfigurations); Jsr107Service jsr107Service = findOrCreateService(services, Jsr107Service.class, () -> new DefaultJsr107Service(jsr107Configuration)); builder = builder.using(jsr107Service); Eh107CacheLoaderWriterProvider cacheLoaderWriterFactory = findOrCreateService(services, Eh107CacheLoaderWriterProvider.class, Eh107CacheLoaderWriterProvider::new); builder = builder.using(cacheLoaderWriterFactory); SerializationProvider serializationProvider = findOrCreateService(services, SerializationProvider.class, () -> new DefaultSerializationProvider(null)); builder = builder.using(serializationProvider); org.ehcache.CacheManager cacheManager = builder.build(true); return new Eh107CacheManager(this, cacheManager, jsr107Service, new Properties(), classLoader, uri, new ConfigurationMerger(null, jsr107Service, cacheLoaderWriterFactory)); }