auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ExtensionId getUIExtensionId() { XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext.isMainWiki()) { return this.distributionManager.getMainUIExtensionId(); } XWikiDocument wikiDocument = xcontext.getWikiServer(); <START> DocumentReference workspaceClassRef = new DocumentReference("xwiki", "WorkspaceManager", "WorkspaceClass"); <END> if (wikiDocument.getXObject(workspaceClassRef) != null) { return this.distributionManager.getWikiUIExtensionId(); } CoreExtension distributionExtension = this.coreExtensionRepository.getEnvironmentExtension(); Model mavenModel = (Model) distributionExtension.getProperty(MavenCoreExtension.PKEY_MAVEN_MODEL); String wikiUIId = mavenModel.getProperties().getProperty("xwiki.extension.distribution.oldwikiui"); return new ExtensionId(wikiUIId, distributionExtension.getId().getVersion()); }</code><technical_language>"xwiki" hard-coded XClass references local (you add object of a type defined in a wiki)</technical_language>

Target:
public ExtensionId getUIExtensionId() { XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext.isMainWiki()) { return this.distributionManager.getMainUIExtensionId(); } XWikiDocument wikiDocument = xcontext.getWikiServer(); DocumentReference workspaceClassRef = new DocumentReference(xcontext.getMainXWiki(), "WorkspaceManager", "WorkspaceClass"); if (wikiDocument.getXObject(workspaceClassRef) != null) { return this.distributionManager.getWikiUIExtensionId(); } CoreExtension distributionExtension = this.coreExtensionRepository.getEnvironmentExtension(); Model mavenModel = (Model) distributionExtension.getProperty(MavenCoreExtension.PKEY_MAVEN_MODEL); String wikiUIId = mavenModel.getProperties().getProperty("xwiki.extension.distribution.oldwikiui"); return new ExtensionId(wikiUIId, distributionExtension.getId().getVersion()); }
Source:
<code>public void bindingChanged(BindingProvider provider, String itemName) { logger.debug("Denon binding changed for item {}", itemName); if (provider instanceof DenonBindingProvider) { DenonBindingConfig config = ((DenonBindingProvider) provider).getConfig(itemName); if (config != null) { <START> connections.get(config.getInstance()).getConnector().updateStateFromCache(config.getProperty()); <END> } } }</code><technical_language>phrase connections.get(config.getInstance()).getConnector() is duplicated a lot worth refactoring a new method</technical_language>

Target:
public void bindingChanged(BindingProvider provider, String itemName) { logger.debug("Denon binding changed for item {}", itemName); if (provider instanceof DenonBindingProvider) { DenonBindingConfig config = ((DenonBindingProvider) provider).getConfig(itemName); if (config != null) { getConnector(config).updateStateFromCache(config.getProperty()); } } }
Source:
<code>public Connection getConnection() throws IOException { Connection connection = this.connection.get(); while (connection == null) { connection = ConnectionFactory.createConnection(this.conf); <START> if (! this.connection.compareAndSet(null, connection)) { try { connection.close(); } catch (IOException exception) { LOG.debug("Ignored failure while closing connection on contended connection creation.", exception); } connection = this.connection.get(); <END> } } return connection; }</code><technical_language>This logic is perfect, for a while I confused connection Connection this.connection AtomicReference. rename connection connectionRef AtomicReference</technical_language>

Target:
public Connection getConnection() throws IOException { Connection connection = this.connectionRef.get(); while (connection == null) { connection = ConnectionFactory.createConnection(this.conf); if (! this.connectionRef.compareAndSet(null, connection)) { try { connection.close(); } catch (IOException exception) { LOG.debug("Ignored failure while closing connection on contended connection creation.", exception); } connection = this.connectionRef.get(); } } return connection; }
Source:
<code>public static void setup() { EntityDictionary dictionary = new EntityDictionary(new HashMap<>()); dictionary.bindEntity(getType(PlayerStatsWithView.class)); dictionary.bindEntity(getType(PlayerStatsView.class)); dictionary.bindEntity(getType(PlayerStats.class)); dictionary.bindEntity(getType(Country.class)); dictionary.bindEntity(getType(SubCountry.class)); dictionary.bindEntity(getType(Player.class)); <START> dictionary.bindEntity(getType(CountryView.class)); <END> dictionary.bindEntity(getType(CountryViewNested.class)); dataStore.populateEntityDictionary(dictionary); }</code><technical_language>getTypes necessary</technical_language>

Target:
public static void setup() { EntityDictionary dictionary = new EntityDictionary(new HashMap<>()); dictionary.bindEntity(PlayerStatsWithView.class); dictionary.bindEntity(PlayerStatsView.class); dictionary.bindEntity(PlayerStats.class); dictionary.bindEntity(Country.class); dictionary.bindEntity(SubCountry.class); dictionary.bindEntity(Player.class); dictionary.bindEntity(CountryView.class); dictionary.bindEntity(CountryViewNested.class); dataStore.populateEntityDictionary(dictionary); }
Source:
<code>public boolean openFileByKey(KeyEvent keyEvent) { if (keyEvent.getCharacter() == null) { return false; } char key = keyEvent.getCharacter().charAt(0); if (!Character.isDigit(key)) { return false; } <START> int num = Integer.parseInt(String.valueOf(key)); <END> if (num > history.getHistory().size()) { return false; } this.openFile(history.getFileAt(Integer.parseInt(keyEvent.getCharacter()) - 1)); return true; }</code><technical_language>I getNumericValue of char <LINK_0></technical_language>

Target:
public boolean openFileByKey(KeyEvent keyEvent) { if (keyEvent.getCharacter() == null) { return false; } char key = keyEvent.getCharacter().charAt(0); int num = Character.getNumericValue(key); if (num <= 0 || num > history.getHistory().size()) { return false; } this.openFile(history.getFileAt(Integer.parseInt(keyEvent.getCharacter()) - 1)); return true; }
Source:
<code><START> public void resumeSnapshotApply() { <END> LogReplicationEntryMetadata metadata = new LogReplicationEntryMetadata(MessageType.SNAPSHOT_END, logReplicationMetadataManager.getTopologyConfigId(), -1L, logReplicationMetadataManager.getLastTransferredSnapshotTimestamp(), new UUID(logReplicationMetadataManager.getCurrentSnapshotSyncCycleId(), Long.MAX_VALUE)); startSnapshotApplyAsync(new LogReplicationEntry(metadata)); }</code><technical_language>Need some log</technical_language>

Target:
public void resumeSnapshotApply() { snapshotWriter.reset(topologyConfigId, logReplicationMetadataManager.getLastStartedSnapshotTimestamp()); long snapshotTransferTs = logReplicationMetadataManager.getLastTransferredSnapshotTimestamp(); UUID snapshotSyncId = new UUID(logReplicationMetadataManager.getCurrentSnapshotSyncCycleId(), Long.MAX_VALUE); log.info("Resume Snapshot Sync Apply, snapshot_transfer_ts={}, id={}", snapshotTransferTs, snapshotSyncId); LogReplicationEntryMetadata metadata = new LogReplicationEntryMetadata(MessageType.SNAPSHOT_END, logReplicationMetadataManager.getTopologyConfigId(), -1L, snapshotTransferTs, snapshotSyncId); startSnapshotApplyAsync(new LogReplicationEntry(metadata)); }
Source:
<code>private static <K, V> Map.Entry<K, V> entry(K k, V v) { <START> return new AbstractMap.SimpleEntry<>(k, v); <END> }</code><technical_language>SimpleImmutableEntry SimpleEntry</technical_language>

Target:
private static <K, V> Map.Entry<K, V> entry(K k, V v) { return new AbstractMap.SimpleImmutableEntry<>(k, v); }
Source:
<code>public static void removeDuplicateImages(Feed feed) { Set<String> known = new HashSet<String>(); for (FeedItem item : feed.getItems()) { <START> String url = (item.hasItemImage()) ? item.getImage().getDownload_url() : null; <END> if (url != null) { if (known.contains(url)) { item.setImage(null); } else { known.add(url); } } } }</code><technical_language>I find easier read (...)</technical_language>

Target:
public static void removeDuplicateImages(Feed feed) { Set<String> known = new HashSet<String>(); for (FeedItem item : feed.getItems()) { String url = item.hasItemImage() ? item.getImage().getDownload_url() : null; if (url != null) { if (known.contains(url)) { item.setImage(null); } else { known.add(url); } } } }
Source:
<code>public static boolean isHost(final Contentlet contentlet){ <START> final Structure hostStrucuture = CacheLocator.getContentTypeCache().getStructureByVelocityVarName("Host"); <END> return contentlet.getStructureInode().equals(hostStrucuture.getInode()); }</code><technical_language>Host.HOST_VELOCITY_VAR_NAME is a constant for Host</technical_language>

Target:
public static boolean isHost(final Contentlet contentlet){ final Structure hostStrucuture = CacheLocator.getContentTypeCache().getStructureByVelocityVarName(Host.HOST_VELOCITY_VAR_NAME); return contentlet.getStructureInode().equals(hostStrucuture.getInode()); }
Source:
<code><START> public Observable<LoginResponse> status(String siteUrl) throws ExecutionException, InterruptedException { <END> if(!siteUrl.endsWith("/")){ siteUrl = siteUrl + "/"; } siteUrl = new URLHelper().execute(siteUrl).get(); RestService restService = restServiceFactory.createForUrl(siteUrl); return status(restService, siteUrl); }</code><technical_language>catch above</technical_language>

Target:
public Observable<LoginResponse> status(String siteUrl) { String newUrl = null; try { newUrl = new URLHelper().execute(siteUrl).get(); } catch (ExecutionException e) { Log.e("UserRepository", "ExecutionException", e.getCause()); } catch (InterruptedException e) { Log.e("UserRepository", "InterruptedException", e.getCause()); } if (newUrl == null) newUrl = siteUrl; if(!siteUrl.endsWith("/")){ newUrl = newUrl + "/"; } RestService restService = restServiceFactory.createForUrl(newUrl); return status(restService, newUrl); }
Source:
<code>private void addNode(String parentPath, String nodeName, String diffValue) throws DiffException, RepositoryException { Item item = session.getItem(parentPath); if (!item.isNode()) { throw new ItemNotFoundException(parentPath); } Node parent = (Node) item; try { <START> importer.start(); <END> NodeHandler hndlr = new NodeHandler(parent, nodeName); new JsonParser(hndlr).parse(diffValue); importer.end(); } catch (IOException e) { if (e instanceof DiffException) { throw (DiffException) e; } else { throw new DiffException(e.getMessage(), e); } } }</code><technical_language>if importer constructor used</technical_language>

Target:
private void addNode(String parentPath, String nodeName, String diffValue) throws DiffException, RepositoryException { Item item = session.getItem(parentPath); if (!item.isNode()) { throw new ItemNotFoundException(parentPath); } Node parent = (Node) item; contentHandler = parent.getSession().getImportContentHandler(parentPath, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW); try { NodeHandler hndlr = new NodeHandler(parent, nodeName); new JsonParser(hndlr).parse(diffValue); } catch (IOException e) { if (e instanceof DiffException) { throw (DiffException) e; } else { throw new DiffException(e.getMessage(), e); } } }
Source:
<code>public void register(String id, SocketChannel socketChannel) throws IOException { ensureNotRegistered(id); registerChannel(id, socketChannel, SelectionKey.OP_READ); this.sensors.connectionCreated.record(); <START> this.channel(id).channelMetadataRegistry().registerClientInformation(ClientInformation.EMPTY); <END> }</code><technical_language>I good check registry registered do this (since overwriting is)</technical_language>

Target:
public void register(String id, SocketChannel socketChannel) throws IOException { ensureNotRegistered(id); registerChannel(id, socketChannel, SelectionKey.OP_READ); this.sensors.connectionCreated.record(); ChannelMetadataRegistry metadataRegistry = this.channel(id).channelMetadataRegistry(); if (metadataRegistry.clientInformation() == null) metadataRegistry.registerClientInformation(ClientInformation.EMPTY); }
Source:
<code>public Account createAccount(CreateAccountRequest request) { Assert.notNull(request, "Request cannot be null."); final Account account = request.getAccount(); String href = getAccounts().getHref(); char querySeparator = '?'; if (request.isRegistrationWorkflowOptionSpecified()) { <START> href += "?registrationWorkflowEnabled=" + request.isRegistrationWorkflowEnabled(); <END> } if (request.isPasswordFormatSpecified()) { href += querySeparator + "passwordFormat=" + request.getPasswordFormat(); } if (request.isAccountOptionsSpecified()) { return getDataStore().create(href, account, request.getAccountOptions()); } return getDataStore().create(href, account); }</code><technical_language>querySeparator</technical_language>

Target:
public Account createAccount(CreateAccountRequest request) { Assert.notNull(request, "Request cannot be null."); final Account account = request.getAccount(); String href = getAccounts().getHref(); char querySeparator = '?'; if (request.isRegistrationWorkflowOptionSpecified()) { href += querySeparator + "registrationWorkflowEnabled=" + request.isRegistrationWorkflowEnabled(); } if (request.isPasswordFormatSpecified()) { href += querySeparator + "passwordFormat=" + request.getPasswordFormat(); } if (request.isAccountOptionsSpecified()) { return getDataStore().create(href, account, request.getAccountOptions()); } return getDataStore().create(href, account); }
Source:
<code>public void testOnlyPreScriptContainsAPIBinding() throws InvalidScriptException { Script s = scriptWithApiBindingUser(); Script s2 = scriptWithoutApiBinding(); FlowScript fs = flowScriptWithoutApiBinding(); Mockito.when(it.getPreScript()).thenReturn(s); Mockito.when(it.getPostScript()).thenReturn(s2); Mockito.when(sec.getScript()).thenReturn(s2); Mockito.when(fe.getEnvScript()).thenReturn(s2); Mockito.when(it.getFlowScript()).thenReturn(fs); Boolean result = new CheckEligibleTaskDescriptorScript().isTaskContainsAPIBinding(etd); <START> assertEquals(true, result); <END> }</code><technical_language>assertEquals is relevant</technical_language>

Target:
public void testOnlyPreScriptContainsAPIBinding() throws InvalidScriptException { Script s = scriptWithApiBindingUser(); Script s2 = scriptWithoutApiBinding(); FlowScript fs = flowScriptWithoutApiBinding(); Mockito.when(it.getPreScript()).thenReturn(s); Mockito.when(it.getPostScript()).thenReturn(s2); Mockito.when(sec.getScript()).thenReturn(s2); Mockito.when(fe.getEnvScript()).thenReturn(s2); Mockito.when(it.getFlowScript()).thenReturn(fs); assertTrue(new CheckEligibleTaskDescriptorScript().isTaskContainsAPIBinding(etd)); }
Source:
<code>public static PlayerBreakBlockEvent createPlayerBreakBlock(Game game, Cause cause, Player player, Direction direction, Location block, BlockSnapshot replacementBlock, int exp) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", player); values.put("user", player); <START> values.put("replacementBlock", replacementBlock); <END> values.put("blockFaceDirection", direction); values.put("exp", exp); return createEvent(PlayerBreakBlockEvent.class, values); }</code><technical_language>moving this line</technical_language>

Target:
public static PlayerBreakBlockEvent createPlayerBreakBlock(Game game, Cause cause, Player player, Direction direction, Location block, BlockSnapshot replacementBlock, int exp) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", player); values.put("replacementBlock", replacementBlock); values.put("user", player); values.put("blockFaceDirection", direction); values.put("exp", exp); return createEvent(PlayerBreakBlockEvent.class, values); }
Source:
<code>private Integer unZipFromStream(ZipInputStream zis, String destinationPath) { File destination = new File(destinationPath); int count = 0; ZipEntry entry = null; try { while ((entry = zis.getNextEntry()) != null) { publishProgress(Localization.get("mult.install.progress", new String[]{String.valueOf(count)})); count++; if (entry.isDirectory()) { FileUtil.createFolder(new File(destination, entry.getName()).toString()); continue; } File outputFile = new File(destination, entry.getName()); if (!outputFile.getParentFile().exists()) { FileUtil.createFolder(outputFile.getParentFile().toString()); } if (outputFile.exists()) { if (!outputFile.delete()) { <START> continue; <END> } } if (!copyZipEntryToOutputFile(outputFile, zis)) { return -1; } } } catch (IOException e) { publishProgress(Localization.get("mult.install.progress.badentry", new String[]{entry.getName()})); return -1; } finally { StreamsUtil.closeStream(zis); } Logger.log(TAG, "Successfully unzipped files"); return count; }</code><technical_language>is this OK? this potentially result in entry zip file copied (and lost zip is deleted) silently</technical_language>

Target:
private Integer unZipFromStream(ZipInputStream zis, String destinationPath) { File destination = new File(destinationPath); int count = 0; ZipEntry entry = null; try { while ((entry = zis.getNextEntry()) != null) { publishProgress(Localization.get("mult.install.progress", new String[]{String.valueOf(count)})); count++; Logger.log(TAG, "Unzipped entry " + entry.getName()); if (entry.isDirectory()) { FileUtil.createFolder(new File(destination, entry.getName()).toString()); continue; } File outputFile = new File(destination, entry.getName()); if (!outputFile.getParentFile().exists()) { FileUtil.createFolder(outputFile.getParentFile().toString()); } if (outputFile.exists()) { if (!outputFile.delete()) { continue; } } if (!copyZipEntryToOutputFile(outputFile, zis)) { return -1; } } } catch (IOException e) { publishProgress(Localization.get("mult.install.progress.badentry", new String[]{entry.getName()})); return -1; } finally { StreamsUtil.closeStream(zis); } Logger.log(TAG, "Successfully unzipped files"); return count; }
Source:
<code>private static void setInitialPhaseForNodeA(NodeController nodeA, final int currentTopology) { nodeA.interceptor.addAction(new Action() { @Override public boolean isApplicable(InvocationContext context, VisitableCommand command) { return context.isOriginLocal() && command instanceof PrepareCommand; } @Override public void before(InvocationContext context, VisitableCommand command, Cache cache) { try { CompletableFuture<Void> topologyFuture = cache.getAdvancedCache().getComponentRegistry().getStateTransferLock().topologyFuture(currentTopology + 1); <START> if (topologyFuture != null) topologyFuture.get(10, TimeUnit.SECONDS); <END> } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { throw new CacheException(e); } } @Override public void after(InvocationContext context, VisitableCommand command, Cache cache) { } }); nodeA.topologyManager.startBlocking(BlockingLocalTopologyManager.LatchType.CONSISTENT_HASH_UPDATE); }</code><technical_language>revert this change</technical_language>

Target:
private static void setInitialPhaseForNodeA(NodeController nodeA, final int currentTopology) { nodeA.interceptor.addAction(new Action() { @Override public boolean isApplicable(InvocationContext context, VisitableCommand command) { return context.isOriginLocal() && command instanceof PrepareCommand; } @Override public void before(InvocationContext context, VisitableCommand command, Cache cache) { try { cache.getAdvancedCache().getComponentRegistry().getStateTransferLock().waitForTopology(currentTopology + 1, 10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (TimeoutException e) { throw LogFactory.getLog(getClass()).failedWaitingForTopology(currentTopology + 1); } } @Override public void after(InvocationContext context, VisitableCommand command, Cache cache) { } }); nodeA.topologyManager.startBlocking(BlockingLocalTopologyManager.LatchType.CONSISTENT_HASH_UPDATE); }
Source:
<code>public int enableSegments(final String dataSource, final Collection<String> segmentIds) { VersionedIntervalTimeline<String, DataSegment> versionedIntervalTimeline = getVersionedIntervalTimeline(dataSource, segmentIds); versionedIntervalTimeline.getAllTimelineEntries().keySet().stream().reduce( (acc, val) -> acc.withStartMillis(Math.min(acc.getStartMillis(), val.getStartMillis())).withEndMillis(Math.max(acc.getEndMillis(), val.getEndMillis())) ).ifPresent(interval -> VersionedIntervalTimeline.addSegments( versionedIntervalTimeline, <START> dataSources.get(dataSource).getSegments().stream().filter(segment -> interval.contains(segment.getInterval())).iterator() <END> )); return enableSegments( segmentIdsForInterval(versionedIntervalTimeline, Intervals.ETERNITY) .filter(segmentId -> segmentIds.contains(segmentId.toString())) .collect(Collectors.toSet()), versionedIntervalTimeline ); }</code><technical_language>part adds segments datasource interval.overlaps deal partial overshadowing</technical_language>

Target:
public int enableSegments(final String dataSource, final Collection<String> segmentIds) { Pair<List<DataSegment>, VersionedIntervalTimeline<String, DataSegment>> data = connector.inReadOnlyTransaction( (handle, status) -> { List<DataSegment> segments = getDataSegments(dataSource, segmentIds, handle) .stream() .filter(pair -> !pair.rhs) .map(pair -> pair.lhs) .collect(Collectors.toList()); VersionedIntervalTimeline<String, DataSegment> versionedIntervalTimeline = buildVersionedIntervalTimeline( dataSource, JodaUtils.condenseIntervals(segments.stream().map(segment -> segment.getInterval()).collect(Collectors.toList())), handle ); VersionedIntervalTimeline.addSegments(versionedIntervalTimeline, segments.iterator()); return new Pair<>( segments, versionedIntervalTimeline ); } ); return enableSegments( data.lhs, data.rhs ); }
Source:
<code>public Iterable<MachineTypeInZone> listHardwareProfiles() { return FluentIterable.from(zones.get().values()) .transformAndConcat(new Function<Location, ImmutableSet<MachineType>>() { @Override public ImmutableSet<MachineType> apply(Location input) { return api.getMachineTypeApiForProject(userProject.get()).listInZone(input.getId()).concat().toSet(); } }).transform(new Function<MachineType, MachineTypeInZone>() { @Override public MachineTypeInZone apply(MachineType arg0) { return new MachineTypeInZone(arg0, arg0.getZone()); } <START> }).toSet(); <END> }</code><technical_language>+1 for imperative version a chance</technical_language>

Target:
public Iterable<MachineTypeInZone> listHardwareProfiles() { ImmutableSet.Builder<MachineTypeInZone> builder = ImmutableSet.builder(); for (final Location zone : zones.get().values()) { builder.addAll(api.getMachineTypeApiForProject(userProject.get()) .listInZone(zone.getId()) .concat() .transform(new Function<MachineType, MachineTypeInZone>() { @Override public MachineTypeInZone apply(MachineType arg0) { return new MachineTypeInZone(arg0, arg0.getZone()); } })); } return builder.build(); }
Source:
<code>private Map<String, Integer> fetchCapacityUsage(String partitionName, ResourceConfig resourceConfig) { Map<String, Map<String, Integer>> capacityMap; try { capacityMap = resourceConfig.getPartitionCapacityMap(); } catch (IOException ex) { throw new IllegalArgumentException("Invalid partition capacity configuration.", ex); } Map<String, Integer> partitionCapacity = capacityMap.get(partitionName); if (partitionCapacity == null) { <START> partitionCapacity.get(ResourceConfig.DEFAULT_PARTITION_KEY); <END> } if (partitionCapacity == null) { throw new IllegalArgumentException(String.format( "The capacity usage of the specified partition %s is not configured in the Resource Config. No default partition capacity is configured neither.", partitionName)); } return partitionCapacity; }</code><technical_language>Typo? this do? If partitionCapacity is null, this throw a NullPointerException</technical_language>

Target:
private Map<String, Integer> fetchCapacityUsage(String partitionName, ResourceConfig resourceConfig) { Map<String, Map<String, Integer>> capacityMap; try { capacityMap = resourceConfig.getPartitionCapacityMap(); } catch (IOException ex) { throw new IllegalArgumentException( "Invalid partition capacity configuration of resource: " + resourceConfig .getResourceName(), ex); } Map<String, Integer> partitionCapacity = capacityMap.get(partitionName); if (partitionCapacity == null) { partitionCapacity = capacityMap.get(ResourceConfig.DEFAULT_PARTITION_KEY); } if (partitionCapacity == null) { throw new IllegalArgumentException(String.format( "The capacity usage of the specified partition %s is not configured in the Resource Config %s. No default partition capacity is configured neither.", partitionName, resourceConfig.getResourceName())); } return partitionCapacity; }
Source:
<code>public static NodeSelection from(IStructuredSelection selection) { <START> if (selection instanceof NodeSelection) { <END> return (NodeSelection) selection; } return selection.isEmpty() ? empty() : new NodeSelection(selection.toList()); }</code><technical_language>If argument selection is a NodeSelection method brakes contract create a new instance. remove if statement</technical_language>

Target:
public static NodeSelection from(IStructuredSelection selection) { return selection.isEmpty() ? empty() : new NodeSelection(selection.toList()); }
Source:
<code>public void testUnion() throws DatabaseEngineException { test5Columns(); engine.persist("TEST", entry().set("COL1", 1).set("COL5", "a") .build()); engine.persist("TEST", entry().set("COL1", 2).set("COL5", "b") .build()); engine.persist("TEST", entry().set("COL1", 3).set("COL5", "c") .build()); engine.persist("TEST", entry().set("COL1", 4).set("COL5", "d") .build()); engine.persist("TEST", entry().set("COL1", 5).set("COL5", "d") .build()); final String[] letters = new String[] {"a", "b", "c", "d", "d"}; final Collection<Expression> queries = Arrays.stream(letters) .map(literal -> select(column("COL5")) .from(table("TEST")) .where(eq(column("COL5"), k(literal)))) .collect(Collectors.toList()); final Expression query = union(queries); final List<Map<String, ResultColumn>> result = engine.query(query); <START> System.out.println(result.size()); <END> assertEquals("Must return 4 results due to distinct property", 4, result.size()); System.out.println(result.get(0).get("COL5").toString()); System.out.println(result.get(1).get("COL5").toString()); System.out.println(result.get(2).get("COL5").toString()); System.out.println(result.get(3).get("COL5").toString()); final List<String> resultSorted = result.stream() .map(row -> row.get("COL5").toString()) .sorted() .collect(Collectors.toList()); assertEquals("COL5 must be a", "a", resultSorted.get(0)); assertEquals("COL5 must be b", "b", resultSorted.get(1)); assertEquals("COL5 must be c", "c", resultSorted.get(2)); assertEquals("COL5 must be d", "d", resultSorted.get(3)); }</code><technical_language>Remove System.outs</technical_language>

Target:
public void testUnion() throws DatabaseEngineException { test5Columns(); engine.persist("TEST", entry().set("COL1", 1).set("COL5", "a") .build()); engine.persist("TEST", entry().set("COL1", 2).set("COL5", "b") .build()); engine.persist("TEST", entry().set("COL1", 3).set("COL5", "c") .build()); engine.persist("TEST", entry().set("COL1", 4).set("COL5", "d") .build()); engine.persist("TEST", entry().set("COL1", 5).set("COL5", "d") .build()); final String[] letters = new String[] {"a", "b", "c", "d", "d"}; final Collection<Expression> queries = Arrays.stream(letters) .map(literal -> select(column("COL5")) .from(table("TEST")) .where(eq(column("COL5"), k(literal)))) .collect(Collectors.toList()); final Expression query = union(queries); final List<Map<String, ResultColumn>> result = engine.query(query); assertEquals("Must return 4 results due to distinct property", 4, result.size()); final List<String> resultSorted = result.stream() .map(row -> row.get("COL5").toString()) .sorted() .collect(Collectors.toList()); assertEquals("COL5 must be a", "a", resultSorted.get(0)); assertEquals("COL5 must be b", "b", resultSorted.get(1)); assertEquals("COL5 must be c", "c", resultSorted.get(2)); assertEquals("COL5 must be d", "d", resultSorted.get(3)); }
Source:
<code>public String getText(Object element) { if (element instanceof String) { return (String) element; } if (element instanceof FileAndName) { <START> return ((FileAndName) element).getFile().getName(); <END> } return null; }</code><technical_language>Is a chance of a NPE? getFile() null</technical_language>

Target:
public String getText(Object element) { if (element instanceof String) { return (String) element; } if (element instanceof FileAndName) { final File file = ((FileAndName) element).getFile(); if (file != null) { return file.getName(); } } return null; }
Source:
<code>private void buildTryStatement(TryStatementTree tryStatementTree) { currentBlock = createBlock(currentBlock); BlockTree finallyBlockTree = tryStatementTree.finallyBlock(); if (finallyBlockTree != null) { currentBlock.isFinallyBlock = true; Block finallyBlock = currentBlock; build(finallyBlockTree); finallyBlock.addExitSuccessor(exitBlock()); exitBlocks.push(currentBlock); } Block finallyOrEndBlock = currentBlock; Block beforeFinally = createBlock(currentBlock); Map<Type, Block> catches = new HashMap<>(); TryStatement tryStatement = new TryStatement(); tryStatement.successorBlock = finallyOrEndBlock; enclosingTry.push(tryStatement); enclosedByCatch.push(false); for (CatchTree catchTree : tryStatementTree.catches()) { currentBlock = createBlock(finallyOrEndBlock); currentBlock.isCatchBlock = true; enclosedByCatch.push(true); build(catchTree.block()); enclosedByCatch.pop(); <START> catches.put(catchTree.parameter().type().symbolType(), currentBlock); <END> } catches.forEach(tryStatement::addCatch); currentBlock = beforeFinally; build(tryStatementTree.block()); build((List<? extends Tree>) tryStatementTree.resources()); enclosingTry.pop(); enclosedByCatch.pop(); currentBlock = createBlock(currentBlock); currentBlock.elements.add(tryStatementTree); if (finallyBlockTree != null) { exitBlocks.pop(); } }</code><technical_language>catches map removed in profit of calling tryStatement.addCatch(Type, block)</technical_language>

Target:
private void buildTryStatement(TryStatementTree tryStatementTree) { currentBlock = createBlock(currentBlock); BlockTree finallyBlockTree = tryStatementTree.finallyBlock(); if (finallyBlockTree != null) { currentBlock.isFinallyBlock = true; Block finallyBlock = currentBlock; build(finallyBlockTree); finallyBlock.addExitSuccessor(exitBlock()); exitBlocks.push(currentBlock); } Block finallyOrEndBlock = currentBlock; Block beforeFinally = createBlock(currentBlock); TryStatement tryStatement = new TryStatement(); tryStatement.successorBlock = finallyOrEndBlock; enclosingTry.push(tryStatement); enclosedByCatch.push(false); for (CatchTree catchTree : tryStatementTree.catches()) { currentBlock = createBlock(finallyOrEndBlock); currentBlock.isCatchBlock = true; enclosedByCatch.push(true); build(catchTree.block()); enclosedByCatch.pop(); tryStatement.addCatch(catchTree.parameter().type().symbolType(), currentBlock); } currentBlock = beforeFinally; build(tryStatementTree.block()); build((List<? extends Tree>) tryStatementTree.resources()); enclosingTry.pop(); enclosedByCatch.pop(); currentBlock = createBlock(currentBlock); currentBlock.elements.add(tryStatementTree); if (finallyBlockTree != null) { exitBlocks.pop(); } }
Source:
<code>private String readConfigurations(String groupId, String artifactId, String id, String attribute) { Plugin plugin = project.getPlugin(groupId + ":" + artifactId); if (plugin == null) { plugin = plugin(groupId(groupId), artifactId(artifactId), version("RELEASE")); } Xpp3Dom config = null; List<Plugin> buildPlugins = project.getBuildPlugins(); for (Plugin p : buildPlugins) { if (p.equals(plugin)) { config = (Xpp3Dom) p.getConfiguration(); <START> log.info("config: " + config.toString()); <END> PluginExecution pe; Map<String, PluginExecution> peMap = p.getExecutionsAsMap(); if ((pe = peMap.get(id)) != null ){ Xpp3Dom executionConfig = (Xpp3Dom) pe.getConfiguration(); config = Xpp3Dom.mergeXpp3Dom(executionConfig, config); log.info("install-apps config: " + config); for (Xpp3Dom elem : config.getChildren()){ log.info("elem: " + elem.getName()); if (elem.getName().equals(attribute)) { return elem.getValue(); } } String value = config.getAttribute(attribute); } break; } } return null; }</code><technical_language>debug instead of info logging this method</technical_language>

Target:
private String readConfigurations(String groupId, String artifactId, String id, String attribute) { Plugin plugin = project.getPlugin(groupId + ":" + artifactId); if (plugin == null) { plugin = plugin(groupId(groupId), artifactId(artifactId), version("RELEASE")); } Xpp3Dom config = null; List<Plugin> buildPlugins = project.getBuildPlugins(); for (Plugin p : buildPlugins) { if (p.equals(plugin)) { config = (Xpp3Dom) p.getConfiguration(); PluginExecution pe; Map<String, PluginExecution> peMap = p.getExecutionsAsMap(); if ((pe = peMap.get(id)) != null ){ Xpp3Dom executionConfig = (Xpp3Dom) pe.getConfiguration(); config = Xpp3Dom.mergeXpp3Dom(executionConfig, config); for (Xpp3Dom elem : config.getChildren()){ if (elem.getName().equals(attribute)) { return elem.getValue(); } } String value = config.getAttribute(attribute); } break; } } log.debug(attribute + " could not be found in the configuration file."); return null; }
Source:
<code>public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { if (inEventLoop()) { throw new IllegalStateException("cannot await termination of the current thread"); } <START> threadLock.await(timeout, ObjectUtil.checkNotNull(unit, "unit")); <END> return isTerminated(); }</code><technical_language>move check in method change behaviour if null is passed unit in EventLoop thread</technical_language>

Target:
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { ObjectUtil.checkNotNull(unit, "unit"); if (inEventLoop()) { throw new IllegalStateException("cannot await termination of the current thread"); } threadLock.await(timeout, unit); return isTerminated(); }
Source:
<code>public byte[] getCacheKey() { <START> if (pattern == null) { <END> return ByteBuffer.allocate(1) .put(CACHE_TYPE_ID).array(); } byte[] patternBytes = StringUtils.toUtf8(pattern); return ByteBuffer.allocate(1 + patternBytes.length) .put(CACHE_TYPE_ID) .put(patternBytes) .array(); }</code><technical_language>pattern null</technical_language>

Target:
public byte[] getCacheKey() { byte[] patternBytes = StringUtils.toUtf8(pattern); return ByteBuffer.allocate(1 + patternBytes.length) .put(CACHE_TYPE_ID) .put(patternBytes) .array(); }
Source:
<code>private boolean updatePostObject(boolean isAutosave) { if (!mEditPostRepository.hasPost() || mEditorFragment == null) { AppLog.e(AppLog.T.POSTS, "Attempted to save an invalid Post."); <START> return true; <END> } return mEditPostRepository.updateInTransaction(postModel -> { try { boolean postTitleOrContentChanged = updatePostContentNewEditor(postModel, isAutosave, (String) mEditorFragment.getTitle(), (String) mEditorFragment.getContent(postModel.getContent())); if (postTitleOrContentChanged) { mEditPostRepository.updatePublishDateIfShouldBePublishedImmediately(postModel); postModel .setDateLocallyChanged( DateTimeUtils.iso8601FromTimestamp(System.currentTimeMillis() / 1000)); } } catch (EditorFragmentNotAddedException e) { AppLog.e(T.EDITOR, "Impossible to save the post, we weren't able to update it."); return false; } return true; }); }</code><technical_language>please double check this : Do want return true here</technical_language>

Target:
private boolean updatePostObject(boolean isAutosave) { if (!mEditPostRepository.hasPost() || mEditorFragment == null) { AppLog.e(AppLog.T.POSTS, "Attempted to save an invalid Post."); return false; } return mEditPostRepository.updateInTransaction(postModel -> { try { boolean postTitleOrContentChanged = updatePostContentNewEditor(postModel, isAutosave, (String) mEditorFragment.getTitle(), (String) mEditorFragment.getContent(postModel.getContent())); if (postTitleOrContentChanged) { mEditPostRepository.updatePublishDateIfShouldBePublishedImmediately(postModel); postModel .setDateLocallyChanged( DateTimeUtils.iso8601FromTimestamp(System.currentTimeMillis() / 1000)); } } catch (EditorFragmentNotAddedException e) { AppLog.e(T.EDITOR, "Impossible to save the post, we weren't able to update it."); return false; } return true; }); }
Source:
<code>public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!children.get(0).evaluate(tuple, ptr)) { <START> if (logger.isDebugEnabled()) { <END> logger.debug("-> left value is null"); } return false; } PhoenixJson source = (PhoenixJson)PJson.INSTANCE.toObject(ptr, children.get(0).getSortOrder()); if (!children.get(1).evaluate(tuple, ptr)) { if (logger.isDebugEnabled()) { logger.debug("-> right value is null"); } return false; } String key = (String) PVarchar.INSTANCE.toObject(ptr, children.get(1).getSortOrder()); PhoenixJson jsonValue=source.getValue(key); if(jsonValue!=null) { defaultType=jsonValue.getValueAsPDataType(); ptr.set(jsonValue.valueWrapToBytes()); return true; } return false; }</code><technical_language>remove logger.debug() for null arguments</technical_language>

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!children.get(0).evaluate(tuple, ptr)) { return false; } PhoenixJson source = (PhoenixJson)PJson.INSTANCE.toObject(ptr); if (!children.get(1).evaluate(tuple, ptr)) { return false; } String key = (String) PVarchar.INSTANCE.toObject(ptr); PhoenixJson jsonValue=source.getValue(key); if(jsonValue!=null) { ptr.set(jsonValue.valueWrapToBytes()); return true; } return false; }
Source:
<code>public static CRSTable find( int tableId ) { <START> for ( CRSTable table : CRSTable.values() ) <END> { if ( tableId == table.tableId ) { return table; } } throw new IllegalArgumentException( "No known Coordinate Reference System table: " + tableId ); }</code><technical_language>lookup pattern</technical_language>

Target:
public static CRSTable find( int tableId ) { if ( tableId < TYPES.length ) { return TYPES[tableId]; } else { throw new IllegalArgumentException( "No known Coordinate Reference System table: " + tableId ); } }
Source:
<code>private static byte[] print(final RsJSON.Source src) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); <START> final JsonWriter writer = Json.createWriter(baos); <END> writer.write(src.toJSON()); writer.close(); return baos.toByteArray(); }</code><technical_language>@dmzaytsev replace this a try-with-resources - JsonWriter is Closeable, I work. If not, close in a finally block</technical_language>

Target:
private static byte[] print(final RsJSON.Source src) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final JsonWriter writer = Json.createWriter(baos); try { writer.write(src.toJSON()); } finally { writer.close(); } return baos.toByteArray(); }
Source:
<code>void subscribe(Observable<? extends T> source) { if (wip.getAndIncrement() == 0) { do { if (child.isUnsubscribed()) { break; } if (!active) { <START> if (secondary) { <END> AlternateSubscriber<T> as = new AlternateSubscriber<T>(child, arbiter); serial.set(as); active = true; alternate.unsafeSubscribe(as); } else { secondary = true; active = true; source.unsafeSubscribe(this); } } } while (wip.decrementAndGet() != 0); } }</code><technical_language>Is this variable needed? source == null accomplish thing</technical_language>

Target:
void subscribe(Observable<? extends T> source) { if (wip.getAndIncrement() == 0) { do { if (child.isUnsubscribed()) { break; } if (!active) { if (source == null) { AlternateSubscriber<T> as = new AlternateSubscriber<T>(child, arbiter); serial.set(as); active = true; alternate.unsafeSubscribe(as); } else { active = true; source.unsafeSubscribe(this); source = null; } } } while (wip.decrementAndGet() != 0); } }
Source:
<code><START> public GHCreateTeamBuilder createTeam(String name) { <END> return new GHCreateTeamBuilder(root, "/orgs/" + login + "/teams", name); }</code><technical_language>I other createTeam methods marked @Deprecated. Do agree</technical_language>

Target:
public GHTeamBuilder createTeam(String name) { return new GHTeamBuilder(root, login, name); }
Source:
<code>public boolean onTouchEvent(@NonNull MotionEvent event) { if (mSeekBar == null) { return super.onTouchEvent(event); } else { <START> View containingView = (View) mSeekBar.getParent(); <END> final float offsetX = -(containingView.getLeft() + mSeekBar.getLeft()); final float offsetY = -(containingView.getTop() + mSeekBar.getTop()); event.offsetLocation(offsetX, offsetY); mSeekBar.onTouchEvent(event); event.offsetLocation(-offsetX, -offsetY); return true; } }</code><technical_language>Oh, I forgot parent-view of SeekBar SeekBarPanel. ViewUtils.getLocationInAncestor() in case layout changes</technical_language>

Target:
public boolean onTouchEvent(@NonNull MotionEvent event) { if (mSeekBar == null) { return super.onTouchEvent(event); } else { int[] location = new int[2]; ViewUtils.getLocationInAncestor(mSeekBar, location, this); final float offsetX = -location[0]; final float offsetY = -location[1]; event.offsetLocation(offsetX, offsetY); mSeekBar.onTouchEvent(event); event.offsetLocation(-offsetX, -offsetY); return true; } }
Source:
<code>public String getMessage() { <START> String msg = super.getMessage().replaceAll("\\.$", ""); <END> return ((getStatusCode() > 0) ? getStatusCode() + " " : "") + msg + ((url != null) ? " at " + url : "") + "." + ((error != null) ? " Error: " + getError() + ".": "") + ((reason != null) ? " Reason: " + getReason() + ".": ""); }</code><technical_language>this is tidy, I if a bit inefficient a regex. In simplistic testing using: msg = (super.getMessage().endsWith(".")) ? super.getMessage().substring(0, msg.length() - 1) : super.getMessage(); is 13 times faster replacement needs made, more 20 times faster in case doesn't. writing exception messages worth considering</technical_language>

Target:
public String getMessage() { String msg = super.getMessage(); msg = (msg.endsWith(".")) ? msg.substring(0, msg.length() - 1) : msg; return ((getStatusCode() > 0) ? getStatusCode() + " " : "") + msg + ((url != null) ? " at " + url : "") + "." + ((error != null) ? " Error: " + getError() + ".": "") + ((reason != null) ? " Reason: " + getReason() + ".": ""); }
Source:
<code>public void execute(DatastoreService ds, String[] args) throws Exception { if (args.length != 0) { System.err.println("Usage: " + RemoteAPI.class.getName() + "EnsureHouseholdPrivacy <appid> <username> <password>"); System.exit(1); } <START> Query surveyQuery = new Query("SurveyGroup"); <END> for (Entity survey : ds.prepare(surveyQuery).asIterable()) { Object projectType = survey.getProperty("projectType"); if ("PROJECT".equals(projectType)) { long id = survey.getKey().getId(); Filter filter = new FilterPredicate("surveyGroupId", FilterOperator.EQUAL, id); Query formQuery = new Query("Survey").setFilter(filter); boolean containsHouseholdData = false; for (Entity form : ds.prepare(formQuery).asIterable()) { Object pointType = form.getProperty("pointType"); if ("Household".equals(pointType)) { containsHouseholdData = true; } } Object privacyLevel = survey.getProperty("privacyLevel"); if (containsHouseholdData && !"PRIVATE".equals(privacyLevel)) { survey.setProperty("privacyType", "PRIVATE"); ds.put(survey); System.out.println(String.format("Survey #%s (%s) privacyLevel changed to PRIVATE", id, survey.getProperty("name"))); } } } }</code><technical_language>This query include a filter for SurveyGroup projectType = 'PROJECT'</technical_language>

Target:
public void execute(DatastoreService ds, String[] args) throws Exception { if (args.length != 0) { System.err.println("Usage: " + RemoteAPI.class.getName() + "EnsureHouseholdPrivacy <appid> <username> <password>"); System.exit(1); } Filter projectFilter = new FilterPredicate("projectType", FilterOperator.EQUAL, "PROJECT"); Filter publicFilter = new FilterPredicate("privacyLevel", FilterOperator.EQUAL, "PUBLIC"); Query surveyQuery = new Query("SurveyGroup") .setFilter(CompositeFilterOperator.and(projectFilter, publicFilter)); for (Entity survey : ds.prepare(surveyQuery).asIterable()) { long id = survey.getKey().getId(); Filter surveyIdFilter = new FilterPredicate("surveyGroupId", FilterOperator.EQUAL, id); Filter householdFilter = new FilterPredicate("pointType", FilterOperator.EQUAL, "Household"); Query formQuery = new Query("Survey") .setFilter(CompositeFilterOperator.and(surveyIdFilter, householdFilter)); boolean containsHouseholdData = !ds.prepare(formQuery) .asList(FetchOptions.Builder.withLimit(1)).isEmpty(); if (containsHouseholdData) { survey.setProperty("privacyLevel", "PRIVATE"); ds.put(survey); System.out.println(String.format( "Survey #%s (%s) privacyLevel changed to PRIVATE", id, survey.getProperty("name"))); } } }
Source:
<code>private byte[] getPageKey(long fileId, long pageIndex) { <START> return ("" + fileId + "" + pageIndex).getBytes(); <END> }</code><technical_language>string concat inefficient. consider sth: ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(x);</technical_language>

Target:
private byte[] getPageKey(long fileId, long pageIndex) { ByteBuffer buf = ByteBuffer.allocate(16); buf.putLong(fileId); buf.putLong(pageIndex); return buf.array(); }
Source:
<code>public static void checkDates () { dateChecker(); <START> if (isNewYears == true) { <END> Constants.LOG.info("Happy New Year"); } if (isAprilFirst == true) { Constants.LOG.info("Happy April Fools Day"); } if (isHalloween == true) { Constants.LOG.info("Happy Halloween"); } if (isChristmas == true) { Constants.LOG.info("Merry Christmas"); } }</code><technical_language>Remove == true change if/else, holidays</technical_language>

Target:
public static void checkDates () { dateChecker(); if (isNewYears = true) { Constants.LOG.info("Happy New Year"); } else if (isAprilFirst = true) { Constants.LOG.info("Happy April Fools Day"); } else if (isHalloween = true) { Constants.LOG.info("Happy Halloween"); } else if (isChristmas = true) { Constants.LOG.info("Merry Christmas"); } else { Constants.LOG.info(":( Today is not a Holiday"); } }
Source:
<code>private static void loadInterceptors() { OMElement interceptorsConfig = MiscellaneousUtil.loadXMLConfig(RelayConstants.STREAM_INTERCEPTOR_FILE); if (interceptorsConfig != null) { if (!ROOT_Q.equals(interceptorsConfig.getQName())) { handleException("Invalid interceptor configuration file"); } Iterator iterator = interceptorsConfig.getChildrenWithName(INTERCEPTOR_Q); while (iterator.hasNext()) { OMElement interceptorElem = (OMElement) iterator.next(); String name = null; if (interceptorElem.getAttribute(NAME_ATT) != null) { name = interceptorElem.getAttributeValue(NAME_ATT); } else { handleException("Name not defined in one or more interceptor"); } if (interceptorElem.getAttribute(CLASS_Q) != null) { String className = interceptorElem.getAttributeValue(CLASS_Q); if (!"".equals(className)) { StreamInterceptor interceptor = createInterceptor(className); interceptors.add(interceptor); <START> interceptor.setName(name); <END> populateParameters(interceptorElem, interceptor); } else { handleException("Class name is null for interceptor name : " + name); } } else { handleException("Class name not defined for interceptor named : " + name); } } } }</code><technical_language>me, if name change in runtime interceptor is created. remove setter add parameter constructor itself</technical_language>

Target:
private static void loadInterceptors() { OMElement interceptorsConfig = MiscellaneousUtil.loadXMLConfig(RelayConstants.STREAM_INTERCEPTOR_FILE); if (interceptorsConfig != null) { if (!ROOT_Q.equals(interceptorsConfig.getQName())) { handleException("Invalid interceptor configuration file"); } Iterator iterator = interceptorsConfig.getChildrenWithName(INTERCEPTOR_Q); while (iterator.hasNext()) { OMElement interceptorElem = (OMElement) iterator.next(); if (interceptorElem.getAttribute(CLASS_Q) != null) { String className = interceptorElem.getAttributeValue(CLASS_Q); if (!"".equals(className)) { StreamInterceptor interceptor = createInterceptor(className); interceptors.add(interceptor); populateParameters(interceptorElem, interceptor); } else { handleException("Class name is one or more interceptor"); } } else { handleException("Class name is one or more interceptor"); } } } }