auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Map<String, String> readProperties() { try { Map<String, String> properties = Maps.newHashMap(); File file = new File(AndroidLocation.getFolder(), PATH_FIRST_RUN_PROPERTIES); if (file.isFile()) { try { final List<String> lines = <START> Files.readLines(file, Charsets.UTF_16LE); <END> for (String line : lines) { final Matcher matcher = KEY_VALUE_PATTERN.matcher(line); if (matcher.matches()) { final String key = matcher.group(1); final String value = matcher.group(2); properties.put(key, value); } } } catch (IOException e) { Logger.getInstance(InstallerData.class).error(e); } return properties; } } catch (AndroidLocation.AndroidLocationException e) { Logger.getInstance(InstallerData.class).error(e); } return null; }</code><technical_language>Properties#load(Reader) InputStreamReader proper encoding</technical_language>

Target:
private static Map<String, String> readProperties() { try { Map<String, String> properties = Maps.newHashMap(); File file = new File(AndroidLocation.getFolder(), PATH_FIRST_RUN_PROPERTIES); if (file.isFile()) { try { final List<String> lines = Files.readLines(file, Charsets.UTF_16LE); for (String line : lines) { int keyValueSeparator = line.indexOf('='); final String key = line.substring(0, keyValueSeparator); final String value = line.substring(keyValueSeparator + 1); properties.put(key, value); } } catch (IOException e) { Logger.getInstance(InstallerData.class).error(e); } return properties; } } catch (AndroidLocation.AndroidLocationException e) { Logger.getInstance(InstallerData.class).error(e); } return null; }
Source:
<code>private void getChildrenImpl() { RevWalk rw = new RevWalk(repo); RevFlag localFlag = rw.newFlag("local"); RevFlag remoteFlag = rw.newFlag("remote"); RevFlagSet allFlags = new RevFlagSet(); allFlags.add(localFlag); allFlags.add(remoteFlag); rw.carry(allFlags); List<GitModelCommit> result = new ArrayList<GitModelCommit>(); rw.setRetainBody(true); try { RevCommit srcCommit = rw.parseCommit(srcRev); srcCommit.add(localFlag); rw.markStart(srcCommit); RevCommit dstCommit = rw.parseCommit(dstRev); dstCommit.add(remoteFlag); rw.markStart(dstCommit); for (RevCommit nextCommit : rw) { if (nextCommit.hasAll(allFlags)) break; if (nextCommit.has(localFlag)) <START> result.add(new GitModelCommit(this, nextCommit, LEFT)); <END> else if (nextCommit.has(remoteFlag)) result.add(new GitModelCommit(this, nextCommit, RIGHT)); } } catch (IOException e) { Activator.logError(e.getMessage(), e); } childrens = result.toArray(new GitModelCommit[result.size()]); }</code><technical_language>I get incoming decorator for local change outgoing decorator for remote change</technical_language>

Target:
private void getChildrenImpl() { RevWalk rw = new RevWalk(repo); RevFlag localFlag = rw.newFlag("local"); RevFlag remoteFlag = rw.newFlag("remote"); RevFlagSet allFlags = new RevFlagSet(); allFlags.add(localFlag); allFlags.add(remoteFlag); rw.carry(allFlags); List<GitModelCommit> result = new ArrayList<GitModelCommit>(); rw.setRetainBody(true); try { RevCommit srcCommit = rw.parseCommit(srcRev); srcCommit.add(localFlag); rw.markStart(srcCommit); RevCommit dstCommit = rw.parseCommit(dstRev); dstCommit.add(remoteFlag); rw.markStart(dstCommit); for (RevCommit nextCommit : rw) { if (nextCommit.hasAll(allFlags)) break; if (nextCommit.has(localFlag)) result.add(new GitModelCommit(this, nextCommit, RIGHT)); else if (nextCommit.has(remoteFlag)) result.add(new GitModelCommit(this, nextCommit, LEFT)); } } catch (IOException e) { Activator.logError(e.getMessage(), e); } childrens = result.toArray(new GitModelCommit[result.size()]); }
Source:
<code>public StringColorPickerEditor(Composite parent, int style) { super(parent, style); colorPicker = new Button(this, SWT.PUSH); doSetColor("0"); colorPicker.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { ColorPalettePopup colorPickerPopup = new ColorPalettePopup(getShell(), IDialogConstants.BUTTON_BAR_HEIGHT); colorPickerPopup.setPreviousColor(Integer.valueOf(getValue())); Rectangle r = colorPicker.getBounds(); Point location = colorPicker.getParent().toDisplay(r.x, r.y); colorPickerPopup.open(new Point(location.x, location.y + r.height)); <START> if (colorPickerPopup.getSelectedColor() == null && !colorPickerPopup.useDefaultColor()) { <END> return; } setColor(colorPickerPopup.getSelectedColor()); commit(); } public void widgetDefaultSelected(SelectionEvent e) { } }); }</code><technical_language>do inverse condition fill if-statement body instead of a return-statement break execution</technical_language>

Target:
public StringColorPickerEditor(Composite parent, int style) { super(parent, style); colorPicker = new Button(this, SWT.PUSH); doSetColor("0"); colorPicker.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { ColorPalettePopup colorPickerPopup = new ColorPalettePopup(getShell(), IDialogConstants.BUTTON_BAR_HEIGHT); colorPickerPopup.setPreviousColor(Integer.valueOf(getValue())); Rectangle r = colorPicker.getBounds(); Point location = colorPicker.getParent().toDisplay(r.x, r.y); colorPickerPopup.open(new Point(location.x, location.y + r.height)); if (colorPickerPopup.getSelectedColor() != null || colorPickerPopup.useDefaultColor()) { setColor(colorPickerPopup.getSelectedColor()); commit(); } } public void widgetDefaultSelected(SelectionEvent e) { } }); }
Source:
<code>private Path getRectifiedConfig(String collection, Path collectionPath) { Set<Path> allFiles = SOLR_CONFIG_FILES.stream() .map(configName -> Paths.get(collectionPath.toString(), configName)) .collect(Collectors.toSet()); Set<Path> missingFiles = allFiles.stream().filter(config -> !config.toFile().exists()).collect(Collectors.toSet()); Set<Path> existingFiles = allFiles.stream().filter(missingFiles::contains).collect(Collectors.toSet()); if (missingFiles.isEmpty()) { return collectionPath; } Path tempConfigDir; try { <START> tempConfigDir = Files.createTempDirectory("solr-configsets"); <END> tempConfigDir.toFile().deleteOnExit(); } catch (IOException e) { LOGGER.debug( "Could not create directory to utilize incomplete configset [{}]. Using default configset instead", collection); return defaultPath; } Set<Path> pathsToCopy = ImmutableSet.<Path>builder() .addAll( missingFiles.stream() .map(Path::getFileName) .map(Path::toString) .map(fileName -> Paths.get(defaultPath.toString(), fileName)) .collect(Collectors.toSet())) .addAll(existingFiles) .build(); for (Path filePath : pathsToCopy) { try { Files.copy( filePath, Paths.get(tempConfigDir.toString(), filePath.getFileName().toString()), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { LOGGER.debug("Could not copy config file [{}], reverting to default.", filePath); return defaultPath; } } return tempConfigDir; }</code><technical_language>include collection name in temporary folder clients creating collections do partially overwrite other</technical_language>

Target:
private Path getRectifiedConfig(String collection, Path collectionPath) { Set<Path> allFiles = SOLR_CONFIG_FILES.stream() .map(configName -> Paths.get(collectionPath.toString(), configName)) .collect(Collectors.toSet()); Set<Path> missingFiles = allFiles.stream().filter(config -> !config.toFile().exists()).collect(Collectors.toSet()); Set<Path> existingFiles = allFiles.stream().filter(config -> config.toFile().exists()).collect(Collectors.toSet()); if (missingFiles.isEmpty()) { return collectionPath; } Path tempConfigDir; try { tempConfigDir = Files.createTempDirectory("solr-configsets"); tempConfigDir.toFile().deleteOnExit(); } catch (IOException e) { LOGGER.debug( "Could not create directory to utilize incomplete configset [{}]. Using default configset instead", collection); return defaultPath; } Set<Path> pathsToCopy = ImmutableSet.<Path>builder() .addAll( missingFiles.stream() .map(Path::getFileName) .map(Path::toString) .map(fileName -> Paths.get(defaultPath.toString(), fileName)) .collect(Collectors.toSet())) .addAll(existingFiles) .build(); for (Path filePath : pathsToCopy) { try { Files.copy( filePath, Paths.get(tempConfigDir.toString(), filePath.getFileName().toString()), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { LOGGER.info("Could not copy config file [{}], reverting to default.", filePath); return defaultPath; } } return tempConfigDir; }
Source:
<code>private IProgressMonitor beginWork(IProgressMonitor monitor) { if (monitor == null) <START> return new NullProgressMonitor(); <END> return SubMonitor.convert(monitor, IProgressMonitor.UNKNOWN); }</code><technical_language>Unnecessary branch SubMonitor.convert accepts null</technical_language>

Target:
private IProgressMonitor beginWork(IProgressMonitor monitor) { return SubMonitor.convert(monitor); }
Source:
<code>public void finish() { <START> new PushButton("Finish").click(); <END> }</code><technical_language>add wait condition for shell</technical_language>

Target:
public void finish() { new PushButton("Finish").click(); new WaitWhile(new ShellIsAvailable(this)); }
Source:
<code>public Set<String> loadAllKeys() { Set<String> keys = new HashSet<String>(); LOGGER.debug("Entering loadAllKeys"); <START> File[] files = persistencePath.toFile().listFiles(getFilenameFilter()); <END> if (files == null) { return keys; } for (File file : files) { keys.add(file.getName().replaceFirst(SER_REGEX, "")); } LOGGER.debug("Leaving loadAllKeys"); return keys; }</code><technical_language>consider Files.list(persistentPath).filter(this::serializedFiles) instead</technical_language>

Target:
public Set<String> loadAllKeys() { Set<String> keys = new HashSet<>(); LOGGER.trace("Entering loadAllKeys"); try (Stream<Path> stream = Files.list(persistencePath.toPath())) { keys = stream .filter(getPathMatcher()::matches) .map(Path::getFileName) .map(Path::toString) .map(fileName -> fileName.replaceFirst(EXT_REGEX, "")) .collect(Collectors.toSet()); } catch (IOException e) { LOGGER.warn("Unable to read files at {}", persistencePath); } LOGGER.trace("Leaving loadAllKeys"); return keys; }
Source:
<code>void processServerError(ServerErrorCode errorCode) { switch (errorCode) { case Blob_Deleted: logger.trace("Requested blob was deleted"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobDeleted)); break; case Blob_Expired: logger.trace("Requested blob is expired"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobExpired)); break; case Blob_Not_Found: logger.trace("Requested blob was not found on this server"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobDoesNotExist)); break; default: <START> setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.AmbryUnavailable)); <END> break; } }</code><technical_language>UnexpectedInternalError</technical_language>

Target:
void processServerError(ServerErrorCode errorCode) { switch (errorCode) { case Blob_Deleted: logger.trace("Requested blob was deleted"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobDeleted)); break; case Blob_Expired: logger.trace("Requested blob is expired"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobExpired)); break; case Blob_Not_Found: logger.trace("Requested blob was not found on this server"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobDoesNotExist)); break; default: setOperationException( new RouterException("Server returned: " + errorCode, RouterErrorCode.UnexpectedInternalError)); break; } }
Source:
<code>protected Iterator<E> flatMap(final Traverser.Admin<S> traverser) { final S s = traverser.get(); if (s instanceof Iterator) return (Iterator) s; else if (s instanceof Iterable) return ((Iterable) s).iterator(); else if (s instanceof Map) return ((Map) s).entrySet().iterator(); else if (s.getClass().isArray()) <START> return new ArrayIterator((Object[])s); <END> else return IteratorUtils.of((E) s); }</code><technical_language>This cast fail if incoming array is array of primitives. I do this is short point creates intermediate, albeit short-lived list. return (Iterator<E>)Arrays.asList(s).iterator(); I able reproduce issue I nested a primitive array of a list. Calling unfold a silly do this if dealing nested collections. gremlin> __.inject([0, 1, 2, [3, 4] int[]]).unfold().unfold() ==>0 ==>1 ==>2 [I cast [Ljava.lang.Object; Type ':help' ':h' for help. Display stack trace? [yN]n gremlin> __.inject([0, 1, 2, [3, 4]]).unfold().unfold() ==>0 ==>1 ==>2 ==>3 ==>4</technical_language>

Target:
protected Iterator<E> flatMap(final Traverser.Admin<S> traverser) { final S s = traverser.get(); if (s instanceof Iterator) return (Iterator) s; else if (s instanceof Iterable) return ((Iterable) s).iterator(); else if (s instanceof Map) return ((Map) s).entrySet().iterator(); else if (s.getClass().isArray()) return handleArrays(s); else return IteratorUtils.of((E) s); }
Source:
<code>public void testSerializePlayMessage() throws IOException { <START> File file = new File("./assets/Jesse_normal_trimmed.wav"); <END> FileInputStream fis = new FileInputStream(file); byte[] bytes = new byte[fis.available()]; fis.read(bytes); TransferSongMessage oldMessage = new TransferSongMessage(132452L, file.getName(), bytes); TransferSongMessage newMessage = super.testSerializeMessage(oldMessage); assertEquals(oldMessage.getSongId(), newMessage.getSongId()); assertEquals(oldMessage.getSongFileName(), newMessage.getSongFileName()); assertTrue(Arrays.equals(oldMessage.getSongData(), newMessage.getSongData())); }</code><technical_language>this test work device, @theJenix</technical_language>

Target:
public void testSerializePlayMessage() throws IOException { File file = new File("./assets/Jesse_normal_trimmed.wav"); FileInputStream fis = new FileInputStream(file); byte[] bytes = new byte[fis.available()]; fis.read(bytes); long songId = 132452L; TransferSongMessage oldMessage = new TransferSongMessage(songId, file.getName(), bytes); TransferSongMessage newMessage = super.testSerializeMessage(oldMessage); assertEquals(oldMessage.getSongId(), newMessage.getSongId()); assertEquals(oldMessage.getSongFileName(), newMessage.getSongFileName()); assertTrue(Arrays.equals(oldMessage.getSongData(), newMessage.getSongData())); }
Source:
<code>protected void closeSplitInputStreams() throws IOException { <START> for (StreamsHolder<InputStream> holder : splitInputHolders.values()) { <END> if (holder.getStream() != null) { holder.getStream().close(); } if (holder.getWrappedStream() != null) { holder.getWrappedStream().close(); } } splitInputHolders.clear(); }</code><technical_language>this is looping multiple streams, more defer propagation of exception close operations attempted</technical_language>

Target:
protected void closeSplitInputStreams() throws IOException { IOException last = null; for (StreamsHolder<InputStream> holder : splitInputHolders.values()) { try { holder.close(); } catch (IOException e) { last = e; } } splitInputHolders.clear(); if (last != null) { throw last; } }
Source:
<code>public String toString() { <START> return MoreObjects.toStringHelper(this).omitNullValues().add("code", code).add("message", message).toString(); <END> }</code><technical_language>[minor] new implementations remove omitNullValues. Intentionally left here? @AutoValue do</technical_language>

Target:
public String toString() { return toStringHelper(this).add("code", code).add("message", message).toString(); }
Source:
<code>public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); composite.setFont(parent.getFont()); Label label = new Label(composite, SWT.NONE); label.setLayoutData(new GridData()); label.setText(Messages.rename_label); this.nameText = new Text(composite, SWT.BORDER); <START> this.nameText.setText(""); END> this.nameText.setFont(composite.getFont()); this.nameText.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); this.nameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (!CharMatcher.whitespace().matchesAnyOf(RenameInputWizardPage.this.nameText.getText())) { setPageComplete(true); } } }); this.nameText.selectAll(); this.setPageComplete(false); this.setControl(composite); }</code><technical_language>Showing empty field is a bad practice helpful for user. Showing "newName" "name" a bit more helpful. Also, important this point, nameText focus content is selected user click widget select remove content, type</technical_language>

Target:
public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); composite.setFont(parent.getFont()); Label label = new Label(composite, SWT.NONE); label.setLayoutData(new GridData()); label.setText(Messages.rename_label); this.nameText = new Text(composite, SWT.BORDER); this.nameText.setText("newName"); this.nameText.setFont(composite.getFont()); this.nameText.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); this.nameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (!CharMatcher.whitespace().matchesAnyOf(RenameInputWizardPage.this.nameText.getText())) { setPageComplete(true); } } }); this.nameText.selectAll(); this.setPageComplete(true); this.setControl(composite); }
Source:
<code>public void init() { dictionaryConnection = _dictionary.openConnection(_configuration); <START> dictionary = new ArrayList<>(); <END> final Iterator<String> allValues = dictionaryConnection.getAllValues(); while (allValues.hasNext()) { dictionary.add(allValues.next()); } }</code><technical_language>Naming wise I sense call this "dictionaryValues" so. sorted longest is on</technical_language>

Target:
public void init() { _dictionaryConnection = _dictionary.openConnection(_configuration); dictionaryValues = new ArrayList<>(); final Iterator<String> allValues = _dictionaryConnection.getLengthSortedValues(); while (allValues.hasNext()) { dictionaryValues.add(allValues.next()); } }
Source:
<code>public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length != 1) { return false; } if (args[0].equalsIgnoreCase("all") || args[0].equalsIgnoreCase("everyone")) { playerMsg("Correct usage: /opall"); return true; } OfflinePlayer player = null; for (Player onlinePlayer : server.getOnlinePlayers()) { if (args[0].equalsIgnoreCase(onlinePlayer.getName())) { player = onlinePlayer; } } if (player == null) { if (TFM_AdminList.isSuperAdmin(sender) || senderIsConsole) { player = TFM_DepreciationAggregator.getOfflinePlayer(server, args[0]); } else { playerMsg("That player is not online."); playerMsg("You don't have permissions to OP offline players.", ChatColor.YELLOW); return true; } } if (!player.isOp()) { TFM_Util.adminAction(sender.getName(), "Opping " + player.getName(), false); <START> player.setOp(true); <END> } else { playerMsg("That player is not online."); } return true; }</code><technical_language>Formatting is out here, I dont looking, line 56 57 be</technical_language>

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length != 1) { return false; } if (args[0].equalsIgnoreCase("all") || args[0].equalsIgnoreCase("everyone")) { playerMsg("Correct usage: /opall"); return true; } OfflinePlayer player = null; for (Player onlinePlayer : server.getOnlinePlayers()) { if (args[0].equalsIgnoreCase(onlinePlayer.getName())) { player = onlinePlayer; } } if (player == null) { if (TFM_AdminList.isSuperAdmin(sender) || senderIsConsole) { player = TFM_DepreciationAggregator.getOfflinePlayer(server, args[0]); } else { playerMsg("That player is not online."); playerMsg("You don't have permissions to OP offline players.", ChatColor.YELLOW); return true; } } if (!player.isOp()) { TFM_Util.adminAction(sender.getName(), "Opping " + player.getName(), false); player.setOp(true); } else { playerMsg("That player is already an Op."); } return true; }
Source:
<code>void assignExclusiveSegments() throws IOException { checkState(bufferManager.unsynchronizedGetAvailableExclusiveBuffers() == 0, "Bug in input channel setup logic: exclusive buffers have already been set for this input channel."); <START> checkState(initialCredit > 0, "Number of exclusive buffers must be larger than 0."); <END> bufferManager.requestExclusiveBuffers(initialCredit); }</code><technical_language>nit: if want check this argument, done in initialization of constructor. I remove passed networkBuffersPerChannel in constructor checked in previous component</technical_language>

Target:
void assignExclusiveSegments() throws IOException { checkState(bufferManager.unsynchronizedGetAvailableExclusiveBuffers() == 0, "Bug in input channel setup logic: exclusive buffers have already been set for this input channel."); bufferManager.requestExclusiveBuffers(initialCredit); }
Source:
<code><START> public List getClients() { <END> return clientDao.getClients(); }</code><technical_language>List<ClientEntity></technical_language>

Target:
public List<ClientEntity> getClients() { return clientDao.getClients(); }
Source:
<code>protected Message beforeForward(final Message message, final SimpleString forwardingAddress) { if (useDuplicateDetection) { byte[] bytes = getDuplicateBytes(nodeUUID, message.getMessageID()); message.putExtraBytesProperty(Message.HDR_BRIDGE_DUPLICATE_ID, bytes); } if (forwardingAddress != null) { message.setAddress(forwardingAddress); } if (transformer != null) { final Message transformedMessage = transformer.transform(message); if (transformedMessage != message) { if (logger.isDebugEnabled()) { logger.debug("The transformer " + transformer + " made a copy of the message " + message + " as transformedMessage"); } } <START> transformedMessage.reencode(); <END> return EmbedMessageUtil.embedAsCoreMessage(transformedMessage); } else { return EmbedMessageUtil.embedAsCoreMessage(message); } }</code><technical_language>This is responsibility of transformer code</technical_language>

Target:
protected Message beforeForward(final Message message, final SimpleString forwardingAddress) { if (useDuplicateDetection) { byte[] bytes = getDuplicateBytes(nodeUUID, message.getMessageID()); message.putExtraBytesProperty(Message.HDR_BRIDGE_DUPLICATE_ID, bytes); } if (forwardingAddress != null) { message.setAddress(forwardingAddress); } switch (routingType) { case ANYCAST: message.setRoutingType(RoutingType.ANYCAST); break; case MULTICAST: message.setRoutingType(RoutingType.MULTICAST); break; case STRIP: message.setRoutingType(null); break; case PASS: break; } if (transformer != null) { final Message transformedMessage = transformer.transform(message); if (transformedMessage != message) { if (logger.isDebugEnabled()) { logger.debug("The transformer " + transformer + " made a copy of the message " + message + " as transformedMessage"); } } return EmbedMessageUtil.embedAsCoreMessage(transformedMessage); } else { return EmbedMessageUtil.embedAsCoreMessage(message); } }
Source:
<code><START> public static ReaderPost getPost(boolean isFeed, long blogOrFeedId, long postOrItemId, boolean excludeTextColumn) { <END> String columns = (excludeTextColumn ? COLUMN_NAMES_NO_TEXT : "*"); String sql = "SELECT " + columns + " FROM tbl_posts WHERE " + (isFeed ? "feed_id" : "blog_id") + "=? AND " + (isFeed ? "feed_item_id" : "post_id") + "=? LIMIT 1"; String[] args = new String[] {Long.toString(blogOrFeedId), Long.toString(postOrItemId)}; Cursor c = ReaderDatabase.getReadableDb().rawQuery(sql, args); try { if (!c.moveToFirst()) { return null; } return getPostFromCursor(c); } finally { SqlUtils.closeCursor(c); } }</code><technical_language>I prefer this separate functions, getBlogPost() getFeedPost(). this function as-is, mark private new functions rely it</technical_language>

Target:
private static ReaderPost getPost(boolean isFeed, long blogOrFeedId, long postOrItemId, boolean excludeTextColumn) { String columns = (excludeTextColumn ? COLUMN_NAMES_NO_TEXT : "*"); String sql = "SELECT " + columns + " FROM tbl_posts WHERE " + (isFeed ? "feed_id" : "blog_id") + "=? AND " + (isFeed ? "feed_item_id" : "post_id") + "=? LIMIT 1"; String[] args = new String[] {Long.toString(blogOrFeedId), Long.toString(postOrItemId)}; Cursor c = ReaderDatabase.getReadableDb().rawQuery(sql, args); try { if (!c.moveToFirst()) { return null; } return getPostFromCursor(c); } finally { SqlUtils.closeCursor(c); } }
Source:
<code>public Object[][] testHeaderVersionScenarios() { return new Object[][]{ {"1.0", true}, {"1.3", true}, {"1.4", true}, <START> {"1.5", true} <END> }; }</code><technical_language>want add {"1.6", false} list fail version 1.6</technical_language>

Target:
public Object[][] testHeaderVersionScenarios() { return new Object[][]{ {"1.0", true}, {"1.3", true}, {"1.4", true}, {"1.5", true}, {"1.6", false}, }; }
Source:
<code>private List<RelDataTypeField> getRelFields(List<Schema.Field> fields) { List<RelDataTypeField> relFields = new ArrayList<>(); <START> relFields.add(new RelDataTypeFieldImpl(AvroRelConverter.KEY_NAME, 0, <END> createTypeWithNullability(createSqlType(SqlTypeName.VARCHAR), true))); for (Schema.Field field : fields) { String fieldName = field.name(); int fieldPos = field.pos() + 1; RelDataType dataType = getRelDataType(field.schema()); relFields.add(new RelDataTypeFieldImpl(fieldName, fieldPos, dataType)); } return relFields; }</code><technical_language>Definitely, enforcing existence of KEY_NAME field VARCHAR in relational schema here. I recommend explicit enforce/assume in relational schema enforce/assume in avro schema explain exact conversion rules other obvious 1:1 mapping fields</technical_language>

Target:
private List<RelDataTypeField> getRelFields(List<Schema.Field> fields) { List<RelDataTypeField> relFields = new ArrayList<>(); for (Schema.Field field : fields) { String fieldName = field.name(); int fieldPos = field.pos() + 1; RelDataType dataType = getRelDataType(field.schema()); relFields.add(new RelDataTypeFieldImpl(fieldName, fieldPos, dataType)); } return relFields; }
Source:
<code>public void processAction(RequiredActionContext context) { if (context.getHttpRequest().getDecodedFormParameters().containsKey("cancel")) { context.getUser().removeAttribute(USER_ATTRIBUTE); context.failure(); return; } SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); <START> context.getUser().setAttribute(USER_ATTRIBUTE, Arrays.asList(dateTimeFormat.format(new Date()))); <END> context.success(); }</code><technical_language>store time seconds 1970 else, UserModel.getCreatedTimestamp changed consistent (use org.keycloak.common.util.Time.currentTime)</technical_language>

Target:
public void processAction(RequiredActionContext context) { if (context.getHttpRequest().getDecodedFormParameters().containsKey("cancel")) { context.getUser().removeAttribute(USER_ATTRIBUTE); context.failure(); return; } context.getUser().setAttribute(USER_ATTRIBUTE, Arrays.asList(Integer.toString(Time.currentTime()))); context.success(); }
Source:
<code><START> public void waitHttp() { <END> String server = String.format("http://localhost:%s", serverPort); httpServer.setPort(serverPort); start(httpServer); parallel().actions( sequential().actions( waitFor() .http() .url(server) ), sequential().actions( http(http -> http.server(httpServer).receive().head()), http(http -> http.server(httpServer).respond(HttpStatus.NOT_FOUND)), http(http -> http.server(httpServer).receive().head()), http(http -> http.server(httpServer).respond(HttpStatus.OK)) ) ); doFinally().actions(stop(httpServer)); }</code><technical_language>code duplication</technical_language>

Target:
public void waitHttp() { String server = startHttpServerAndGetUrl(); parallel().actions( sequential().actions( waitFor() .http() .url(server) ), sequential().actions( http(http -> http.server(httpServer).receive().head()), http(http -> http.server(httpServer).respond(HttpStatus.NOT_FOUND)), http(http -> http.server(httpServer).receive().head()), http(http -> http.server(httpServer).respond(HttpStatus.OK)) ) ); doFinally().actions(stop(httpServer)); }
Source:
<code>private void setDataProfilesAsNeeded() { if (DBG) log("setDataProfilesAsNeeded"); ArrayList<DataProfile> dataProfileList = new ArrayList<>(); if <START> (mAllApnSettings != <END> null) { for (ApnSetting apn : mAllApnSettings) { DataProfile dp = createDataProfile(apn); if (!dataProfileList.contains(dp)) { dataProfileList.add(dp); } } } if (dataProfileList.size() != mLastDataProfileList.size() || !mLastDataProfileList.containsAll(dataProfileList)) { mDataServiceManager.setDataProfile(dataProfileList, mPhone.getServiceState().getDataRoamingFromRegistration(), null); mLastDataProfileList = dataProfileList; } }</code><technical_language>If APN settings for a carrier null, do communicate that</technical_language>

Target:
private void setDataProfilesAsNeeded() { if (DBG) log("setDataProfilesAsNeeded"); ArrayList<DataProfile> dataProfileList = new ArrayList<>(); if (mAllApnSettings != null) { for (ApnSetting apn : mAllApnSettings) { DataProfile dp = createDataProfile(apn); if (!dataProfileList.contains(dp)) { dataProfileList.add(dp); } } } if (mLastDataProfileList == null || dataProfileList.size() != mLastDataProfileList.size() || !mLastDataProfileList.containsAll(dataProfileList)) { mDataServiceManager.setDataProfile(dataProfileList, mPhone.getServiceState().getDataRoamingFromRegistration(), null); mLastDataProfileList = dataProfileList; } }
Source:
<code>private static boolean areColumnTypesSupported(List<Column> columns) { if (columns == null || columns.isEmpty()) { return false; } for (Column column : columns) { String type = column.getType().getHiveTypeName().toString(); <START> if (type.startsWith(StandardTypes.DECIMAL)) { <END> type = StandardTypes.DECIMAL; } if (!SUPPORTED_COLUMN_TYPES.contains(type.toLowerCase(Locale.ENGLISH))) { return false; } } return true; }</code><technical_language>comparing a string prefix, do this java if (column.getType().getTypeInfo() instanceof DecimalTypeInfo)</technical_language>

Target:
private static boolean areColumnTypesSupported(List<Column> columns) { if (columns == null || columns.isEmpty()) { return false; } for (Column column : columns) { String type = column.getType().getHiveTypeName().toString(); if (column.getType().getTypeInfo() instanceof DecimalTypeInfo) { type = DECIMAL_TYPE_NAME; } if (!SUPPORTED_COLUMN_TYPES.contains(type)) { return false; } } return true; }
Source:
<code>public int writeAsBinary(ByteBuf buffer, @Nonnull Object value) { MonthDaySecondInterval MOnthDaySecondInterval = (MonthDaySecondInterval) value; buffer.writeInt(TYPE_LEN); <START> buffer.writeDouble(MOnthDaySecondInterval.getSeconds()); <END> buffer.writeInt(MOnthDaySecondInterval.getDays()); buffer.writeInt(MOnthDaySecondInterval.getMonths()); return TYPE_LEN; }</code><technical_language>this writeLong ? for compat latest PostgreSQL version</technical_language>

Target:
public int writeAsBinary(ByteBuf buffer, @Nonnull Object value) { Interval MOnthDaySecondInterval = (Interval) value; buffer.writeInt(TYPE_LEN); buffer.writeLong(Double.valueOf(MOnthDaySecondInterval.getSeconds()).longValue()); buffer.writeInt(MOnthDaySecondInterval.getDays()); buffer.writeInt(MOnthDaySecondInterval.getMonths()); return TYPE_LEN; }
Source:
<code>public void done(IJobChangeEvent event) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { <START> Map<Repository, Object> res = new HashMap<Repository, Object>( <END> PullOperationUI.this.results); Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); handlePullResults(res, shell); } }); }</code><technical_language>This a LinkedHashMap, order in uncommitted changes dialogs is predictable</technical_language>

Target:
public void done(IJobChangeEvent event) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { Map<Repository, Object> res = new LinkedHashMap<Repository, Object>( PullOperationUI.this.results); Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); handlePullResults(res, shell); } }); }
Source:
<code>protected void initLibraryTargetFolder(ISCTFileSystemAccess access, GeneratorEntry entry) { FeatureParameterValue libraryTargetFolderValue = helper.getLibraryTargetFolderValue(entry); if (libraryTargetFolderValue != null) { String folderName = libraryTargetFolderValue.getStringValue(); <START> access.setOutputPath(LIBRARY_TARGET_FOLDER_OUTPUT, libraryTargetFolderValue.getStringValue()); <END> OutputConfiguration output = access.getOutputConfigurations().get(LIBRARY_TARGET_FOLDER_OUTPUT); checkWriteAccess(access, LIBRARY_TARGET_FOLDER_OUTPUT, folderName); output.setCreateOutputDirectory(true); output.setCanClearOutputDirectory(false); output.setOverrideExistingResources(false); } }</code><technical_language>reuse folderName</technical_language>

Target:
protected void initLibraryTargetFolder(ISCTFileSystemAccess access, GeneratorEntry entry) { FeatureParameterValue libraryTargetFolderValue = helper.getLibraryTargetFolderValue(entry); if (libraryTargetFolderValue != null) { String folderName = libraryTargetFolderValue.getStringValue(); access.setOutputPath(LIBRARY_TARGET_FOLDER_OUTPUT, folderName); OutputConfiguration output = access.getOutputConfigurations().get(LIBRARY_TARGET_FOLDER_OUTPUT); checkWriteAccess(access, LIBRARY_TARGET_FOLDER_OUTPUT, folderName); output.setCreateOutputDirectory(true); output.setCanClearOutputDirectory(false); output.setOverrideExistingResources(false); } }
Source:
<code>private Map<String, Object> getDetails(String depositUUID) { Map<String, String> status = depositStatusFactory.get(depositUUID); Map<String, Object> result = new HashMap<>(); for (Entry<String, String> field : status.entrySet()) { result.put(field.getKey(), field.getValue()); } Map<String, Map<String, String>> jobStatuses = jobStatusFactory.getAllJobs(depositUUID); result.put("jobs", jobStatuses); String state = status.get(DepositField.state.name()); if (DepositState.running.name().equals(state)) { String jobUUID = jobStatusFactory.getWorkingJob(depositUUID); result.put("currentJobUUID", jobUUID); } result.put("jobsURI", "/api/status/deposit/" + depositUUID + "/jobs"); result.put("eventsURI", "/api/status/deposit/" + depositUUID + "/eventsXML"); AccessGroupSet groups = getAgentPrincipals().getPrincipals(); <START> result.put("isAdmin", groups.contains("unc:app:lib:cdr:admin")); <END> return result; }</code><technical_language>avoid hardcoding this. access GlobalPermissionEvaluator in this controller, hasGlobalPermission getGlobalUserRoles, of for this purpose. latter, I check result if contains Admin role, globalPermissionEvaluator.hasGlobalPermission(principals, Permission.createAdminUnit) below. is fine</technical_language>

Target:
private Map<String, Object> getDetails(String depositUUID) { Map<String, String> status = depositStatusFactory.get(depositUUID); Map<String, Object> result = new HashMap<>(); for (Entry<String, String> field : status.entrySet()) { result.put(field.getKey(), field.getValue()); } Map<String, Map<String, String>> jobStatuses = jobStatusFactory.getAllJobs(depositUUID); result.put("jobs", jobStatuses); String state = status.get(DepositField.state.name()); if (DepositState.running.name().equals(state)) { String jobUUID = jobStatusFactory.getWorkingJob(depositUUID); result.put("currentJobUUID", jobUUID); } result.put("jobsURI", "/api/status/deposit/" + depositUUID + "/jobs"); result.put("eventsURI", "/api/status/deposit/" + depositUUID + "/eventsXML"); AccessGroupSet principals = getAgentPrincipals().getPrincipals(); result.put("isAdmin", globalPermissionEvaluator.hasGlobalPermission(principals, Permission.createAdminUnit)); return result; }
Source:
<code>public static FilterPredicate rewrite(FilterPredicate pred) { <START> Preconditions.checkNotNull(pred, "pred"); <END> return pred.accept(INSTANCE); }</code><technical_language>I personally a static import checkNotNull line shorter. if feel adding those. a requirement</technical_language>

Target:
public static FilterPredicate rewrite(FilterPredicate pred) { checkNotNull(pred, "pred"); return pred.accept(INSTANCE); }
Source:
<code>private ParentDimensions getTargetDimensions(Container target) { <START> int targetWidth = target.getSize().width; <END> Container container = target; while (container.getSize().width == 0 && container.getParent() != null) { container = container.getParent(); } targetWidth = container.getSize().width; if (targetWidth == 0) { targetWidth = Integer.MAX_VALUE; } int hgap = getHgap(); Insets insets = target.getInsets(); int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); int maxWidth = targetWidth - horizontalInsetsAndGap; return new ParentDimensions(targetWidth, maxWidth, insets); }</code><technical_language>Assigned used</technical_language>

Target:
private ParentDimensions getTargetDimensions(Container target) { Container container = target; while (container.getSize().width == 0 && container.getParent() != null) { container = container.getParent(); } int targetWidth = container.getSize().width; if (targetWidth == 0) { targetWidth = Integer.MAX_VALUE; } Insets insets = container.getInsets(); int horizontalInsetsAndGap = insets.left + insets.right + (getHorizontalGap() * 2); int maxWidth = targetWidth - horizontalInsetsAndGap; return new ParentDimensions(targetWidth, maxWidth, insets); }
Source:
<code>public void prepareTextLookup(ILookupCall<LOOKUP_KEY> call, String text) { String textPattern = text; if (textPattern == null) { textPattern = ""; } textPattern = textPattern.toLowerCase(); IDesktop desktop = ClientSessionProvider.currentSession().getDesktop(); if (desktop != null && desktop.isAutoPrefixWildcardForTextSearch()) { textPattern = getWildcard() + textPattern; } if (!textPattern.endsWith(getWildcard())) { textPattern = textPattern + getWildcard(); } if (isBrowseHierarchy() && <START> getLookupCall() != <END> null && getLookupCall() instanceof LocalLookupCall) { ((LocalLookupCall) getLookupCall()).setHierarchicLookup(true); } call.setKey(null); call.setText(textPattern); call.setAll(null); call.setRec(null); call.setActive(isActiveFilterEnabled() ? getActiveFilter() : TriState.TRUE); if (getMasterValue() != null || getLookupCall() == null || getLookupCall().getMaster() == null) { call.setMaster(getMasterValue()); } interceptPrepareLookup(call); interceptPrepareTextLookup(call, text); }</code><technical_language>necessary</technical_language>

Target:
public void prepareTextLookup(ILookupCall<LOOKUP_KEY> call, String text) { String textPattern = text; if (textPattern == null) { textPattern = ""; } textPattern = textPattern.toLowerCase(); IDesktop desktop = ClientSessionProvider.currentSession().getDesktop(); if (desktop != null && desktop.isAutoPrefixWildcardForTextSearch()) { textPattern = getWildcard() + textPattern; } if (!textPattern.endsWith(getWildcard())) { textPattern = textPattern + getWildcard(); } if (isBrowseHierarchy() && getLookupCall() instanceof LocalLookupCall) { ((LocalLookupCall) getLookupCall()).setHierarchicLookup(true); } call.setKey(null); call.setText(textPattern); call.setAll(null); call.setRec(null); call.setActive(isActiveFilterEnabled() ? getActiveFilter() : TriState.TRUE); if (getMasterValue() != null || getLookupCall() == null || getLookupCall().getMaster() == null) { call.setMaster(getMasterValue()); } interceptPrepareLookup(call); interceptPrepareTextLookup(call, text); }
Source:
<code>public void testLeavesBehindTurdlingsWhenToldTo() throws Exception { curator.start(); Announcer announcer = new Announcer(curator, exec); final byte[] billy = "billy".getBytes(); final String testPath = "/somewhere/test2"; final String parent = ZKPaths.getPathAndNode(testPath).getPath(); announcer.start(); try { Assert.assertNull(curator.checkExists().forPath(parent)); <START> announcer.announce(testPath, billy, false); <END> Assert.assertNotNull(curator.checkExists().forPath(parent)); } finally { announcer.stop(); } Assert.assertNotNull(curator.checkExists().forPath(parent)); }</code><technical_language>this is synchronous. some means of retrying curator is caught up</technical_language>

Target:
public void testLeavesBehindTurdlingsWhenToldTo() throws Exception { curator.start(); Announcer announcer = new Announcer(curator, exec); final byte[] billy = "billy".getBytes(); final String testPath = "/somewhere/test2"; final String parent = ZKPaths.getPathAndNode(testPath).getPath(); announcer.start(); try { Assert.assertNull(curator.checkExists().forPath(parent)); awaitAnnounce(announcer, testPath, billy, false); Assert.assertNotNull(curator.checkExists().forPath(parent)); } finally { announcer.stop(); } Assert.assertNotNull(curator.checkExists().forPath(parent)); }
Source:
<code><START> public SquidCursor<?> swapCursor(SquidCursor<? extends M> newCursor) { <END> if (cursor == newCursor) { return null; } SquidCursor<?> oldCursor = cursor; cursor = newCursor; notifyDataSetChanged(); return oldCursor; }</code><technical_language>Return type SquidCursor<? extends M> for consistency's sake</technical_language>

Target:
public SquidCursor<? extends M> swapCursor(SquidCursor<? extends M> newCursor) { if (cursor == newCursor) { return null; } SquidCursor<? extends M> oldCursor = cursor; cursor = newCursor; notifyDataSetChanged(); return oldCursor; }
Source:
<code>char sendIMKeyEvent (int type, long event, char chars) { int index = 0, count = 0, state = 0; long ptr = 0; if (event == 0) { ptr = GTK.gtk_get_current_event (); if (ptr != 0) { int eventType = GDK.gdk_event_get_event_type(ptr); eventType = Control.fixGdkEventTypeValues(eventType); switch (eventType) { case GDK.GDK_KEY_PRESS: case GDK.GDK_KEY_RELEASE: int eventState = new int[1]; GDK.gdk_event_get_state(ptr, eventState); state = eventState[0]; break; default: event = 0; break; } } } if (event == 0) { int buffer = new int [1]; GTK.gtk_get_current_event_state (buffer); state = buffer [0]; } while (index < chars.length) { Event javaEvent = new Event (); if ((event != 0 || ptr != 0) && chars.length <= 1) { <START> setKeyState (javaEvent, ptr); <END> } else { setInputState (javaEvent, state); } javaEvent.character = chars [index]; sendEvent (type, javaEvent); if (isDisposed ()) { if (ptr != 0) gdk_event_free (ptr); return null; } if (javaEvent.doit) chars [count++] = chars [index]; index++; } if (ptr != 0) gdk_event_free (ptr); if (count == 0) return null; if (index != count) { char result = new char [count]; System.arraycopy (chars, 0, result, 0, count); return result; } return chars; }</code><technical_language>familiar this code, appears if event != 0 caller, call setKeyState() ptr = 0 here? Is this OK</technical_language>

Target:
char sendIMKeyEvent (int type, long event, char chars) { int index = 0, count = 0, state = 0; long ptr = 0; if (event == 0) { ptr = GTK.gtk_get_current_event (); if (ptr != 0) { int eventType = GDK.gdk_event_get_event_type(ptr); eventType = Control.fixGdkEventTypeValues(eventType); switch (eventType) { case GDK.GDK_KEY_PRESS: case GDK.GDK_KEY_RELEASE: int eventState = new int[1]; GDK.gdk_event_get_state(ptr, eventState); state = eventState[0]; break; default: event = 0; break; } } else { int buffer = new int [1]; GTK.gtk_get_current_event_state (buffer); state = buffer [0]; } } else { ptr = event; } while (index < chars.length) { Event javaEvent = new Event (); if (ptr != 0 && chars.length <= 1) { setKeyState (javaEvent, ptr); } else { setInputState (javaEvent, state); } javaEvent.character = chars [index]; sendEvent (type, javaEvent); if (isDisposed ()) { if (ptr != 0) gdk_event_free (ptr); return null; } if (javaEvent.doit) chars [count++] = chars [index]; index++; } if (ptr != 0) gdk_event_free (ptr); if (count == 0) return null; if (index != count) { char result = new char [count]; System.arraycopy (chars, 0, result, 0, count); return result; } return chars; }
Source:
<code>private Iterator<DiscoveryDruidNode> getDruidServers(DruidNodeDiscoveryProvider druidNodeDiscoveryProvider) { final Collection<DiscoveryDruidNode> discoveryDruidNodes = new ArrayList<>(); discoveryDruidNodes.addAll(getServerTypeNodes(druidNodeDiscoveryProvider, NodeType.COORDINATOR)); discoveryDruidNodes.addAll(getServerTypeNodes(druidNodeDiscoveryProvider, NodeType.OVERLORD)); discoveryDruidNodes.addAll(getServerTypeNodes(druidNodeDiscoveryProvider, NodeType.BROKER)); discoveryDruidNodes.addAll(getServerTypeNodes(druidNodeDiscoveryProvider, NodeType.ROUTER)); discoveryDruidNodes.addAll(getServerTypeNodes(druidNodeDiscoveryProvider, NodeType.HISTORICAL)); discoveryDruidNodes.addAll(getServerTypeNodes(druidNodeDiscoveryProvider, NodeType.MIDDLE_MANAGER)); discoveryDruidNodes.addAll(getServerTypeNodes(druidNodeDiscoveryProvider, NodeType.PEON)); <START> return discoveryDruidNodes.iterator(); <END> }</code><technical_language>change instead of listing node type explicitly. suggestion return Arrays.stream(NodeType.values()) .flatMap(t -> getServerTypeNodes(druidNodeDiscoveryProvider, t).stream()) .collect(Collectors.toList()) .iterator();</technical_language>

Target:
private Iterator<DiscoveryDruidNode> getDruidServers(DruidNodeDiscoveryProvider druidNodeDiscoveryProvider) { return Arrays.stream(NodeType.values()) .flatMap(nodeType -> druidNodeDiscoveryProvider.getForNodeType(nodeType).getAllNodes().stream()) .collect(Collectors.toList()) .iterator(); }
Source:
<code><START> public CellAddress getAddress() { <END> throw new UnsupportedOperationException("Not implememted yet."); }</code><technical_language>return new CellAddress(getRow().getRowIndex(), cellNumber);</technical_language>

Target:
public CellAddress getAddress() { return new CellAddress(getRow().getRowNum(), columnIndex); }