auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Sensor processRateSensor(final String threadId, final StreamsMetricsImpl streamsMetrics) { final Sensor sensor = streamsMetrics.threadLevelSensor(threadId, PROCESS, RecordingLevel.INFO); final Map<String, String> tagMap = streamsMetrics.threadLevelTagMap(threadId); final String threadLevelGroup = threadLevelGroup(streamsMetrics); <START> sensor.add( <END> new MetricName( PROCESS + StreamsMetricsImpl.RATE_SUFFIX, threadLevelGroup, PROCESS_RATE_DESCRIPTION, tagMap ), new Rate(TimeUnit.SECONDS, new WindowedSum()) ); sensor.add( new MetricName( PROCESS + StreamsMetricsImpl.TOTAL_SUFFIX, threadLevelGroup, PROCESS_TOTAL_DESCRIPTION, tagMap ), new CumulativeCount() ); return sensor; }</code><technical_language>leverage addInvocationRateToSensor here</technical_language>

Target:
public static Sensor processRateSensor(final String threadId, final StreamsMetricsImpl streamsMetrics) { final Sensor sensor = streamsMetrics.threadLevelSensor(threadId, PROCESS + RATE_SUFFIX, RecordingLevel.INFO); final Map<String, String> tagMap = streamsMetrics.threadLevelTagMap(threadId); final String threadLevelGroup = threadLevelGroup(streamsMetrics); addRateOfSumAndSumMetricsToSensor( sensor, threadLevelGroup, tagMap, PROCESS, PROCESS_RATE_DESCRIPTION, PROCESS_TOTAL_DESCRIPTION ); return sensor; }
Source:
<code>public Double getNormalizedScore() { if (myEmpiRuleCount == 0) { return 0.0; } double retVal = score / myEmpiRuleCount; if (retVal < 0) { retVal = 0.0; <START> } else if (retVal > 1.0) { <END> return 1.0; } return retVal; }</code><technical_language>This impossible now, no? e.g. 5 rules, match, 5/5 == 1.0. I appreciate gate, worried masking potential insidious bugs. A score of >1 error yeah</technical_language>

Target:
public Double getNormalizedScore() { if (myEmpiRuleCount == 0) { return 0.0; } return score / myEmpiRuleCount; }
Source:
<code>public UpdateRequest(String registrationId, Long lifetime, String smsNumber, BindingMode binding, Link[] objectLinks, Map<String, String> additionalAttributes) throws InvalidRequestException { if (registrationId == null || registrationId.isEmpty()) throw new InvalidRequestException("registrationId is mandatory"); this.registrationId = registrationId; this.objectLinks = objectLinks; this.lifeTimeInSec = lifetime; this.bindingMode = binding; this.smsNumber = smsNumber; if (additionalAttributes == null) this.additionalAttributes = Collections.emptyMap(); else <START> this.additionalAttributes = Collections.synchronizedMap(new HashMap<>(additionalAttributes)); <END> }</code><technical_language>UpdateRequest immutable</technical_language>

Target:
public UpdateRequest(String registrationId, Long lifetime, String smsNumber, BindingMode binding, Link[] objectLinks, Map<String, String> additionalAttributes) throws InvalidRequestException { if (registrationId == null || registrationId.isEmpty()) throw new InvalidRequestException("registrationId is mandatory"); this.registrationId = registrationId; this.objectLinks = objectLinks; this.lifeTimeInSec = lifetime; this.bindingMode = binding; this.smsNumber = smsNumber; if (additionalAttributes == null) this.additionalAttributes = Collections.emptyMap(); else this.additionalAttributes = Collections.unmodifiableMap(new HashMap<>(additionalAttributes)); }
Source:
<code>private static SortOrder sortOrder(PrimitiveType primitive) { OriginalType annotation = primitive.getOriginalType(); if (annotation != null) { switch (annotation) { case INT_8: case INT_16: case INT_32: case INT_64: case DATE: case TIME_MICROS: case TIME_MILLIS: case TIMESTAMP_MICROS: case TIMESTAMP_MILLIS: return SortOrder.SIGNED; case UINT_8: case UINT_16: case UINT_32: case UINT_64: <START> case DECIMAL: <END> case ENUM: case UTF8: case BSON: case JSON: return SortOrder.UNSIGNED; case LIST: case MAP: case MAP_KEY_VALUE: case INTERVAL: return SortOrder.UNKNOWN; } } return defaultSortOrder(primitive.getPrimitiveTypeName()); }</code><technical_language>Decimal is unsigned</technical_language>

Target:
private static SortOrder sortOrder(PrimitiveType primitive) { OriginalType annotation = primitive.getOriginalType(); if (annotation != null) { switch (annotation) { case INT_8: case INT_16: case INT_32: case INT_64: case DATE: case TIME_MICROS: case TIME_MILLIS: case TIMESTAMP_MICROS: case TIMESTAMP_MILLIS: return SortOrder.SIGNED; case UINT_8: case UINT_16: case UINT_32: case UINT_64: case ENUM: case UTF8: case BSON: case JSON: return SortOrder.UNSIGNED; case DECIMAL: case LIST: case MAP: case MAP_KEY_VALUE: case INTERVAL: return SortOrder.UNKNOWN; } } return defaultSortOrder(primitive.getPrimitiveTypeName()); }
Source:
<code>public String getArticleName() { String header = getHeader(); <START> return header.substring(header.indexOf('"') + 1, header.length() - 1); <END> }</code><technical_language>is other (more elegant) of article name</technical_language>

Target:
private String getArticleName() { return executeScriptRet(WikiaGlobalVariables.wgPageName); }
Source:
<code>public void onMapReady(final MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; mapboxMap.setStyle(new Style.Builder().fromUri(Style.MAPBOX_STREETS) .withImage(ICON_ID, BitmapUtils.getBitmapFromDrawable( getResources().getDrawable(R.drawable.hurricane_icon))) <START> .withSource(new GeoJsonSource(SOURCE_ID, loadGeoJsonFromAsset("spinning_icon.geojson"))) <END> .withLayer(new SymbolLayer(LAYER_ID, SOURCE_ID) .withProperties(PropertyFactory.iconImage(ICON_ID), iconAllowOverlap(true)) ), new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { startIconSpinningAnimation(); } }); }</code><technical_language>a source constructor, GeoJsonsource(String, URI) pass asset://spinning_icon.geojson instead of loading JSON manually</technical_language>

Target:
public void onMapReady(final MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; mapboxMap.setStyle(new Style.Builder().fromUri(Style.MAPBOX_STREETS) .withImage(ICON_ID, BitmapUtils.getBitmapFromDrawable( getResources().getDrawable(R.drawable.hurricane_icon))), new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { try { style.addSource(new GeoJsonSource(SOURCE_ID, new URI("asset://spinning_icon.geojson"))); style.addLayer(new SymbolLayer(LAYER_ID, SOURCE_ID) .withProperties(PropertyFactory.iconImage(ICON_ID), iconAllowOverlap(true), iconPitchAlignment(ICON_PITCH_ALIGNMENT_MAP))); startIconSpinningAnimation(); } catch (URISyntaxException exception) { Timber.d(exception); } } }); }
Source:
<code>private void initializeEphemeralCount() { this.ephemeralCount = new HashMap<Long, Integer>(); <START> if (this.zks.getZKDatabase() != null) { <END> for (Map.Entry<Long, Set<String>> entry : this.zks.getZKDatabase().getEphemerals().entrySet()) { this.ephemeralCount.put(entry.getKey(), entry.getValue().size()); } } }</code><technical_language>this.ephemeralCount = new HashMap<>();</technical_language>

Target:
private void initializeEphemeralCount() { this.ephemeralCount = new ConcurrentHashMap<>(); for (Map.Entry<Long, Set<String>> entry : this.zks.getZKDatabase().getEphemerals().entrySet()) { this.ephemeralCount.put(entry.getKey(), entry.getValue().size()); } }
Source:
<code>private static Map<String, RemoteRefUpdate> asUpdateMap( List<RemoteCommand> cmds) { Map<String, RemoteRefUpdate> m = new LinkedHashMap<>(); for (RemoteCommand <START> c : <END> cmds) { m.put(c.getRemoteName(), c); } return m; }</code><technical_language>s/c/cmd/</technical_language>

Target:
private static Map<String, RemoteRefUpdate> asUpdateMap( List<RemoteCommand> cmds) { Map<String, RemoteRefUpdate> m = new LinkedHashMap<>(); for (RemoteCommand cmd : cmds) { m.put(cmd.getRemoteName(), cmd); } return m; }
Source:
<code>public ExternalIdBundle withExternalId(ExternalId externalId) { ArgChecker.notNull(externalId, "externalId"); Set<ExternalId> ids = new HashSet<>(externalIds); <START> if (ids.add(externalId) == false) { <END> return this; } return create(ids); }</code><technical_language>contains() read more naturally here, is performance gain sufficient justify it</technical_language>

Target:
public ExternalIdBundle withExternalId(ExternalId externalId) { ArgChecker.notNull(externalId, "externalId"); return withExternalIds(ImmutableSortedSet.of(externalId)); }
Source:
<code>protected void recvCommands() throws IOException { for (;;) { String line; try { line = pckIn.readStringRaw(); } catch (EOFException eof) { if (commands.isEmpty()) return; throw eof; } if (line == PacketLineIn.END) break; if (line.length() >= 48 && line.startsWith("shallow ")) { clientShallowCommits.add(ObjectId.fromString(line.substring(8, 48))); continue; } if (commands.isEmpty()) { final FirstLine firstLine = new FirstLine(line); enabledCapabilities = firstLine.getCapabilities(); line = firstLine.getLine(); <START> if (line.startsWith(GitProtocolConstants.OPTION_PUSH_CERT)) <END> recvCommandsWithPushCertificate(); } if (line.length() < 83) { final String m = JGitText.get().errorInvalidProtocolWantedOldNewRef; sendError(m); throw new PackProtocolException(m); } final ObjectId oldId = ObjectId.fromString(line.substring(0, 40)); final ObjectId newId = ObjectId.fromString(line.substring(41, 81)); final String name = line.substring(82); final ReceiveCommand cmd = new ReceiveCommand(oldId, newId, name); if (name.equals(Constants.HEAD)) { cmd.setResult(Result.REJECTED_CURRENT_BRANCH); } else { cmd.setRef(refs.get(cmd.getRefName())); } commands.add(cmd); } }</code><technical_language>equals? capability splitting left "push-cert"</technical_language>

Target:
protected void recvCommands() throws IOException { for (;;) { String line; try { line = pckIn.readStringRaw(); } catch (EOFException eof) { if (commands.isEmpty()) return; throw eof; } if (line == PacketLineIn.END) break; if (line.length() >= 48 && line.startsWith("shallow ")) { clientShallowCommits.add(ObjectId.fromString(line.substring(8, 48))); continue; } if (commands.isEmpty()) { final FirstLine firstLine = new FirstLine(line); enabledCapabilities = firstLine.getCapabilities(); line = firstLine.getLine(); if (line.equals(GitProtocolConstants.OPTION_PUSH_CERT)) pushCertificateParser.receiveHeader(); } if (line.equals("-----BEGIN PGP SIGNATURE-----\n")) pushCertificateParser.receiveSignature(); if (line.length() < 83) { final String m = JGitText.get().errorInvalidProtocolWantedOldNewRef; sendError(m); throw new PackProtocolException(m); } final ObjectId oldId = ObjectId.fromString(line.substring(0, 40)); final ObjectId newId = ObjectId.fromString(line.substring(41, 81)); final String name = line.substring(82); final ReceiveCommand cmd = new ReceiveCommand(oldId, newId, name); if (name.equals(Constants.HEAD)) { cmd.setResult(Result.REJECTED_CURRENT_BRANCH); } else { cmd.setRef(refs.get(cmd.getRefName())); } commands.add(cmd); } }
Source:
<code>public static void injectSessionExpiration(ZooKeeper zooKeeper) { try { WatchedEvent event = new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null); ClientCnxn clientCnxn = (ClientCnxn)cnxnField.get(zooKeeper); Object eventThread = eventThreadField.get(clientCnxn); queueEventMethod.invoke(eventThread, event); <START> queueEventOfDeathMethod.invoke(eventThread); <END> Object sendThread = sendThreadField.get(clientCnxn); Object clientCnxnSocket = getClientCnxnSocketMethod.invoke(sendThread); wakeupCnxnMethod.invoke(clientCnxnSocket); } catch ( ReflectiveOperationException e ) { throw new RuntimeException("Could not inject session expiration using reflection", e); } }</code><technical_language>is important queue event of death immediately? done for soon this flow: ConnectionState.process -> handleExpiredSession -> ... -> ClientCnxn.disconnect ->... queued this WatchedEvent. for wakeupCnxnMethod.invoke</technical_language>

Target:
public static void injectSessionExpiration(ZooKeeper zooKeeper) { try { WatchedEvent event = new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null); ClientCnxn clientCnxn = (ClientCnxn)cnxnField.get(zooKeeper); Object eventThread = eventThreadField.get(clientCnxn); queueEventMethod.invoke(eventThread, event); } catch ( ReflectiveOperationException e ) { throw new RuntimeException("Could not inject session expiration using reflection", e); } }
Source:
<code>protected LocalizerTesterRobot() { super(); ArrayList<GpsMeasurement> waypoints = null; try { waypoints = WayPointUtil.createWayPointsFromWaypointList(RobobuggyConfigFile.getWaypointSourceLogFile()); } catch (FileNotFoundException e) { e.printStackTrace(); } nodeList.add(new LocalizerTester("localizer tester", waypoints, 1)); <START> nodeList.add(new RobobuggyKFLocalizer(10, "localizer", new LocTuple(40.441670, -79.9416362))); <END> RobobuggyJFrame mainWindow = new RobobuggyJFrame("MainWindow", 1.0, 1.0); Gui.getInstance().addWindow(mainWindow); RobobuggyGUITabs tabs = new RobobuggyGUITabs(); mainWindow.addComponent(tabs, 0.0, 0.0, 1.0, 1.0); tabs.addTab(new MainGuiWindow(), "Home"); tabs.add(new PathPanel(), "Path Visualizer"); tabs.addTab(new ConfigurationPanel(), "Configuration"); }</code><technical_language>More magic numbers; variables for longitude/latitude</technical_language>

Target:
protected LocalizerTesterRobot() { super(); ArrayList<GpsMeasurement> waypoints = null; try { waypoints = WayPointUtil.createWayPointsFromWaypointList(RobobuggyConfigFile.getWaypointSourceLogFile()); } catch (FileNotFoundException e) { e.printStackTrace(); } nodeList.add(new LocalizerTester("localizer tester", waypoints)); nodeList.add(new RobobuggyKFLocalizer(10, "localizer", new LocTuple(40.441670, -79.9416362))); RobobuggyJFrame mainWindow = new RobobuggyJFrame("MainWindow", 1.0, 1.0); Gui.getInstance().addWindow(mainWindow); RobobuggyGUITabs tabs = new RobobuggyGUITabs(); mainWindow.addComponent(tabs, 0.0, 0.0, 1.0, 1.0); tabs.addTab(new MainGuiWindow(), "Home"); tabs.add(new PathPanel(), "Path Visualizer"); tabs.addTab(new ConfigurationPanel(), "Configuration"); }
Source:
<code>public static void main(final String[] args) { try { final Arguments arguments = new Arguments(args); configureLogging(arguments.getConsoleLogLevel(), arguments.getFileLogLevel()); LOG.info("Version: {}", arguments.getVersion()); LOG.info("Command line args: {}", Joiner.on(", ").join(args)); LOG.info("Console log level: {}", arguments.getConsoleLogLevel().toString()); LOG.info("Log file log level: {}", arguments.getFileLogLevel().toString()); LOG.info(CliCommand.getPlatformInformation()); LOG.info(arguments.getArgumentLog()); if (arguments.isHelp()) { final Ds3Cli runner = new Ds3Cli(null, arguments, null); final CommandResponse response = runner.getCommandHelp(); System.out.println(response.getMessage()); System.exit(response.getReturnCode()); } final Ds3Client client = createClient(arguments); if (!Utils.isVersionSupported(client)) { System.out.println(String.format("ERROR: Minimum Black Pearl supported is %s", Utils.MINIMUM_VERSION_SUPPORTED)); System.exit(2); } final Ds3Provider provider = new Ds3ProviderImpl(client, Ds3ClientHelpers.wrap(client)); final FileUtils fileUtils = new FileUtilsImpl(); final Ds3Cli runner = new Ds3Cli(provider, arguments, fileUtils); final CommandResponse response = runner.call(); System.out.println(response.getMessage()); System.exit(response.getReturnCode()); } catch (final RuntimeException e) { System.out.println(e.getMessage()); System.exit(2); } catch (final Exception e) { <START> EXCEPTION.handleException(Main.class.getSimpleName(), e, false); <END> System.exit(2); } }</code><technical_language>This handle exceptionsl ike RuntimeException block above. distinction here</technical_language>

Target:
public static void main(final String[] args) { try { final Arguments arguments = new Arguments(args); configureLogging(arguments.getConsoleLogLevel(), arguments.getFileLogLevel()); LOG.info("Version: {}", arguments.getVersion()); LOG.info("Command line args: {}", Joiner.on(", ").join(args)); LOG.info("Console log level: {}", arguments.getConsoleLogLevel().toString()); LOG.info("Log file log level: {}", arguments.getFileLogLevel().toString()); LOG.info(CliCommand.getPlatformInformation()); LOG.info(arguments.getArgumentLog()); if (arguments.isHelp()) { final Ds3Cli runner = new Ds3Cli(null, arguments, null); final CommandResponse response = runner.getCommandHelp(); System.out.println(response.getMessage()); System.exit(response.getReturnCode()); } final Ds3Client client = createClient(arguments); if (!Utils.isVersionSupported(client)) { System.out.println(String.format("ERROR: Minimum Black Pearl supported is %s", Utils.MINIMUM_VERSION_SUPPORTED)); System.exit(2); } final Ds3Provider provider = new Ds3ProviderImpl(client, Ds3ClientHelpers.wrap(client)); final FileUtils fileUtils = new FileUtilsImpl(); final Ds3Cli runner = new Ds3Cli(provider, arguments, fileUtils); final CommandResponse response = runner.call(); System.out.println(response.getMessage()); System.exit(response.getReturnCode()); } catch (final Exception e) { EXCEPTION.handleException(e); System.exit(2); } }
Source:
<code>public void start() { DynamicTasks.queue("install", new Runnable() { public void run() { waitForConfigKey(BrooklynConfigKeys.INSTALL_LATCH); install(); }}); DynamicTasks.queue("customize", new Runnable() { public void run() { waitForConfigKey(BrooklynConfigKeys.CUSTOMIZE_LATCH); customize(); }}); <START> if (!Strings.isNullOrEmpty(entity.getConfig(BrooklynConfigKeys.PRE_LAUNCH_COMMAND))) { <END> DynamicTasks.queue("pre-launch command", new Runnable() { public void run() { runPreLaunchCommand(entity.getConfig(BrooklynConfigKeys.PRE_LAUNCH_COMMAND)); }}); }; DynamicTasks.queue("launch", new Runnable() { public void run() { waitForConfigKey(BrooklynConfigKeys.LAUNCH_LATCH); launch(); }}); if (!Strings.isNullOrEmpty(entity.getConfig(BrooklynConfigKeys.POST_LAUNCH_COMMAND))) { DynamicTasks.queue("post-launch command", new Runnable() { public void run() { runPostLaunchCommand(entity.getConfig(BrooklynConfigKeys.POST_LAUNCH_COMMAND)); }}); }; DynamicTasks.queue("post-launch", new Runnable() { public void run() { postLaunch(); }}); }</code><technical_language>Minor preference: if (Strings.isNonBlank(...)) is easier read if (!Strings.isNullOrEmpty(...)) (but in brooklyn.util.text.Strings, annoyingly class name guava's!)</technical_language>

Target:
public void start() { DynamicTasks.queue("install", new Runnable() { public void run() { waitForConfigKey(BrooklynConfigKeys.INSTALL_LATCH); install(); }}); DynamicTasks.queue("customize", new Runnable() { public void run() { waitForConfigKey(BrooklynConfigKeys.CUSTOMIZE_LATCH); customize(); }}); if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.PRE_LAUNCH_COMMAND))) { DynamicTasks.queue("pre-launch command", new Runnable() { public void run() { runPreLaunchCommand(entity.getConfig(BrooklynConfigKeys.PRE_LAUNCH_COMMAND)); }}); }; DynamicTasks.queue("launch", new Runnable() { public void run() { waitForConfigKey(BrooklynConfigKeys.LAUNCH_LATCH); launch(); }}); if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.POST_LAUNCH_COMMAND))) { DynamicTasks.queue("post-launch command", new Runnable() { public void run() { runPostLaunchCommand(entity.getConfig(BrooklynConfigKeys.POST_LAUNCH_COMMAND)); }}); }; DynamicTasks.queue("post-launch", new Runnable() { public void run() { postLaunch(); }}); }
Source:
<code>private void findAllFragmentsWithViews( android.app.FragmentManager fragmentManager, ArrayMap<View, android.app.Fragment> result) { <START> String key = "i"; <END> int index = 0; while (true) { tempBundle.putInt(FRAGMENT_INDEX_KEY, index++); android.app.Fragment fragment = null; try { fragment = fragmentManager.getFragment(tempBundle, key); } catch (Exception e) { } if (fragment == null) { break; } if (fragment.getView() != null) { result.put(fragment.getView(), fragment); if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) { findAllFragmentsWithViews(fragment.getChildFragmentManager(), result); } } } }</code><technical_language>want FRAGMENT_INDEX_KEY instead of key local</technical_language>

Target:
private void findAllFragmentsWithViews( android.app.FragmentManager fragmentManager, ArrayMap<View, android.app.Fragment> result) { int index = 0; while (true) { tempBundle.putInt(FRAGMENT_INDEX_KEY, index++); android.app.Fragment fragment = null; try { fragment = fragmentManager.getFragment(tempBundle, FRAGMENT_MANAGER_GET_FRAGMENT_KEY); } catch (Exception e) { } if (fragment == null) { break; } if (fragment.getView() != null) { result.put(fragment.getView(), fragment); if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) { findAllFragmentsWithViews(fragment.getChildFragmentManager(), result); } } } }
Source:
<code>protected AbstractTreeIterator[] mergeBases() throws IOException { final int numsourceTrees = sourceTrees.length; int commitIdx = 0; RevTree tempTrees[] = new RevTree[MAX_BASES]; AbstractTreeIterator tempIterators[] = new AbstractTreeIterator[MAX_BASES]; if (baseTrees == null) { baseTrees = new RevTree[MAX_BASES]; baseTreeIterators = new AbstractTreeIterator[MAX_BASES]; } for (int aIdx = 0; aIdx < numsourceTrees; aIdx++) { for (int bIdx = aIdx + 1; bIdx < numsourceTrees; bIdx++) { List<RevCommit> baseCommits = getBaseCommits(aIdx, bIdx); for (RevCommit baseCommit : baseCommits) { if (commitIdx < MAX_BASES) { tempTrees[commitIdx] = baseCommit.getTree(); tempIterators[commitIdx] = openTree(baseCommit .getTree()); commitIdx++; } else { <START> throw new IOException(String.format( <END> tooManyMergeBasesFor, "TOO_MANY_BASES", sourceCommits[aIdx].name(), sourceCommits[bIdx].name(), Integer.valueOf(commitIdx), baseCommit.name())); } } } } if (commitIdx == 0) { baseTreeIterators[commitIdx] = new EmptyTreeIterator(); commitIdx++; } else { baseTrees = Arrays.copyOf(tempTrees, commitIdx); baseTreeIterators = Arrays.copyOf(tempIterators, commitIdx); } return Arrays.copyOf(baseTreeIterators, baseTreeIterators.length); }</code><technical_language>is this IOException</technical_language>

Target:
protected AbstractTreeIterator[] mergeBases() throws IOException { final int numsourceTrees = sourceTrees.length; int commitIdx = 0; RevTree tempTrees[] = new RevTree[MAX_BASES]; AbstractTreeIterator tempIterators[] = new AbstractTreeIterator[MAX_BASES]; if (baseTrees == null) { baseTrees = new RevTree[MAX_BASES]; baseTreeIterators = new AbstractTreeIterator[MAX_BASES]; } for (int aIdx = 0; aIdx < numsourceTrees; aIdx++) { for (int bIdx = aIdx + 1; bIdx < numsourceTrees; bIdx++) { List<RevCommit> baseCommits = getBaseCommits(aIdx, bIdx); for (RevCommit baseCommit : baseCommits) { if (commitIdx < MAX_BASES) { tempTrees[commitIdx] = baseCommit.getTree(); tempIterators[commitIdx] = openTree(baseCommit .getTree()); commitIdx++; } else { throw new IOException(String.format( tooManyMergeBasesFor, "TOO_MANY_BASES", sourceCommits[aIdx].name(), sourceCommits[bIdx].name(), Integer.valueOf(commitIdx), baseCommit.name())); } } } } if (commitIdx == 0) { baseTreeIterators[commitIdx] = new EmptyTreeIterator(); commitIdx++; } else { baseTrees = copyOf(tempTrees, commitIdx); baseTreeIterators = copyOf(tempIterators, commitIdx); } return copyOf(baseTreeIterators, baseTreeIterators.length); }
Source:
<code>public void tearDown() throws Exception { <START> deleteIfWorkspaceExist(expectedJavaItem.getWorkspaceName()); <END> deleteIfWorkspaceExist(expectedBlankItem.getWorkspaceName()); deleteIfWorkspaceExist(expectedNewestWorkspaceItem.getWorkspaceName()); }</code><technical_language>need do if test workspace is injected</technical_language>

Target:
public void tearDown() throws Exception { testWorkspaceServiceClient.delete( expectedNewestWorkspaceItem.getWorkspaceName(), defaultTestUser.getName()); }
Source:
<code>private void writeAlias(VmDevice device) { writer.writeStartElement("alias"); writer.writeAttributeString("name", String.format("ua-%s", <START> device.getId().getDeviceId().toString())); <END> writer.writeEndElement(); }</code><technical_language>toString() is needed here, AFAIK</technical_language>

Target:
private void writeAlias(VmDevice device) { writer.writeStartElement("alias"); writer.writeAttributeString("name", String.format("ua-%s", device.getId().getDeviceId())); writer.writeEndElement(); }
Source:
<code>protected void delete(Context context, Integer id) throws AuthorizeException { String copyVirtual = requestService.getCurrentRequest().getServletRequest().getParameter("copyVirtualMetadata"); if (copyVirtual == null) { copyVirtual = "none"; } Relationship relationship = null; try { relationship = relationshipService.find(context, id); if (relationship != null) { try { switch (copyVirtual) { case "all": relationshipService.delete(context, relationship, true, true); break; case "left": relationshipService.delete(context, relationship, true, false); break; case "right": relationshipService.delete(context, relationship, false, true); break; <START> case "configured": <END> relationshipService.delete(context, relationship); break; default: relationshipService.delete(context, relationship, false, false); break; } } catch (AuthorizeException e) { throw new AccessDeniedException("You do not have write rights on this relationship's items"); } } } catch (SQLException e) { log.error("Error deleting Relationship specified by ID:" + id, e); } }</code><technical_language>of case statements reference constants in ItemRestRepository? good set this in ItemRestRepository more easily options pass this endpoint</technical_language>

Target:
protected void delete(Context context, Integer id) throws AuthorizeException { String copyVirtual = requestService.getCurrentRequest().getServletRequest().getParameter("copyVirtualMetadata"); if (copyVirtual == null) { copyVirtual = "none"; } Relationship relationship = null; try { relationship = relationshipService.find(context, id); if (relationship != null) { try { switch (copyVirtual) { case ALL: relationshipService.delete(context, relationship, true, true); break; case LEFT: relationshipService.delete(context, relationship, true, false); break; case RIGHT: relationshipService.delete(context, relationship, false, true); break; case CONFIGURED: relationshipService.delete(context, relationship); break; default: relationshipService.delete(context, relationship, false, false); break; } } catch (AuthorizeException e) { throw new AccessDeniedException("You do not have write rights on this relationship's items"); } } } catch (SQLException e) { log.error("Error deleting Relationship specified by ID:" + id, e); } }
Source:
<code>public IConnection createOpenshiftConnection(IServer server, ServiceManagerEnvironment adb, ConnectionsRegistry registry) { Properties dotcdkProps = new CDKServerUtility().getDotCDK(server); String authScheme = dotcdkProps.containsKey(DOTCDK_AUTH_SCHEME) ? dotcdkProps.getProperty(DOTCDK_AUTH_SCHEME) : "Basic"; String username = dotcdkProps.containsKey(DOTCDK_AUTH_USERNAME) ? dotcdkProps.getProperty(DOTCDK_AUTH_USERNAME) : "openshift-dev"; String password = null; if( dotcdkProps.containsKey(DOTCDK_AUTH_PASS) ) { password = dotcdkProps.getProperty(DOTCDK_AUTH_PASS); } else { if( "openshift-dev".equals(username)) { password = "devel"; } } String soughtHost = adb.openshiftHost + ":" + adb.openshiftPort; ConnectionsFactoryTracker connectionsFactory = new ConnectionsFactoryTracker(); connectionsFactory.open(); IConnectionFactory factory = connectionsFactory.getById(IConnectionsFactory.CONNECTIONFACTORY_OPENSHIFT_ID); IConnection con = factory.create(soughtHost); ((Connection)con).setAuthScheme(authScheme); ((Connection)con).setUsername(username); ((Connection)con).setRememberPassword(true); <START> String defaultImageRegistry = "<LINK_0> "; <END> ((Connection)con).setExtendedProperty(ICommonAttributes.IMAGE_REGISTRY_URL_KEY, defaultImageRegistry); if( password != null ) { ((Connection)con).setPassword(password); } if( registry != null ) registry.add(con); return con; }</code><technical_language>nitpicking: move constant more easily identified hard-coded</technical_language>

Target:
public IConnection createOpenshiftConnection(IServer server, ServiceManagerEnvironment adb, ConnectionsRegistry registry) { Properties dotcdkProps = new CDKServerUtility().getDotCDK(server); String authScheme = dotcdkProps.containsKey(DOTCDK_AUTH_SCHEME) ? dotcdkProps.getProperty(DOTCDK_AUTH_SCHEME) : "Basic"; String username = dotcdkProps.containsKey(DOTCDK_AUTH_USERNAME) ? dotcdkProps.getProperty(DOTCDK_AUTH_USERNAME) : "openshift-dev"; String password = null; if( dotcdkProps.containsKey(DOTCDK_AUTH_PASS) ) { password = dotcdkProps.getProperty(DOTCDK_AUTH_PASS); } else { if( "openshift-dev".equals(username)) { password = "devel"; } } String soughtHost = adb.openshiftHost + ":" + adb.openshiftPort; ConnectionsFactoryTracker connectionsFactory = new ConnectionsFactoryTracker(); connectionsFactory.open(); IConnectionFactory factory = connectionsFactory.getById(IConnectionsFactory.CONNECTIONFACTORY_OPENSHIFT_ID); IConnection con = factory.create(soughtHost); ((Connection)con).setAuthScheme(authScheme); ((Connection)con).setUsername(username); ((Connection)con).setRememberPassword(true); ((Connection)con).setExtendedProperty(ICommonAttributes.IMAGE_REGISTRY_URL_KEY, DEFAULT_IMAGE_REGISTRY_URL); if( password != null ) { ((Connection)con).setPassword(password); } if( registry != null ) registry.add(con); return con; }
Source:
<code>public static int mapDPIToZoom (int dpi) { <START> int zoom; zoom = dpi * 100 / DPI_ZOOM_100; zoom = (int) (Math.round (zoom / MIN_ZOOM_INTERVAL) * MIN_ZOOM_INTERVAL); return zoom; <END> }</code><technical_language>Tested 199 dpi, mapped 175% zoom.. reason zoom is 'int' looses precision in calculation, instead float</technical_language>

Target:
public static int mapDPIToZoom (int dpi) { double zoom = dpi * 100 / DPI_ZOOM_100; int roundedZoom = (int) (Math.round (zoom / MIN_ZOOM_INTERVAL) * MIN_ZOOM_INTERVAL); return roundedZoom; }
Source:
<code>static protected Tuple combine(DataBag values) throws ExecException { Tuple output = mTupleFactory.newTuple(2); boolean sawNonNull = false; double sumOfCxLogCx = 0; long sumOfCx = 0; for (Iterator<Tuple> it = values.iterator(); it.hasNext();) { Tuple t = it.next(); Double scxlogcx = (Double)t.get(0); Long scx = (Long)t.get(1); <START> sumOfCxLogCx += (scxlogcx == null ? 0 : scxlogcx.doubleValue()); <END> sumOfCx += (scx == null ? 0 : scx.longValue()); if(scxlogcx != null && scx != null) { sawNonNull = true; } } if(sawNonNull) { output.set(0, sumOfCxLogCx); output.set(1, sumOfCx); } else { output.set(0, null); output.set(1, null); } return output; }</code><technical_language>instead throw exception null</technical_language>

Target:
static protected Tuple combine(DataBag values) throws ExecException { Tuple output = mTupleFactory.newTuple(2); boolean sawNonNull = false; double sumOfCxLogCx = 0; long sumOfCx = 0; for (Iterator<Tuple> it = values.iterator(); it.hasNext();) { Tuple t = it.next(); Double scxlogcx = (Double)t.get(0); Long scx = (Long)t.get(1); if(scxlogcx != null && scx != null) { sumOfCxLogCx += scxlogcx.doubleValue(); sumOfCx += scx.longValue(); sawNonNull = true; } } if (sawNonNull) { output.set(0, sumOfCxLogCx); output.set(1, sumOfCx); } else { output.set(0, null); output.set(1, null); } return output; }
Source:
<code>public void formLoginSecurityContextRepository() { ServerSecurityContextRepository defaultSecContextRepository = mock(ServerSecurityContextRepository.class); ServerSecurityContextRepository formLoginSecContextRepository = mock(ServerSecurityContextRepository.class); TestingAuthenticationToken token = new TestingAuthenticationToken("rob", "rob", "ROLE_USER"); given(defaultSecContextRepository.save(any(), any())).willReturn(Mono.empty()); given(defaultSecContextRepository.load(any())).willReturn(authentication(token)); given(formLoginSecContextRepository.save(any(), any())).willReturn(Mono.empty()); given(formLoginSecContextRepository.load(any())).willReturn(authentication(token)); SecurityWebFilterChain securityWebFilter = this.http .authorizeExchange() .anyExchange().authenticated() .and() .securityContextRepository(defaultSecContextRepository) .formLogin() .securityContextRepository(formLoginSecContextRepository) .and() .build(); WebTestClient webTestClient = WebTestClientBuilder .bindToWebFilters(securityWebFilter) .build(); WebDriver driver = WebTestClientHtmlUnitDriverBuilder .webTestClientSetup(webTestClient) .build(); DefaultLoginPage loginPage = DefaultLoginPage.to(driver) .assertAt(); HomePage homePage = loginPage.loginForm() .username("user") .password("password") .submit(HomePage.class); homePage.assertAt(); <START> verify(defaultSecContextRepository, times(3)).load(any()); <END> verify(formLoginSecContextRepository).save(any(), any()); }</code><technical_language>I times(3) criteria this brittle. For this test, I simply confirm application configured repository</technical_language>

Target:
public void formLoginSecurityContextRepository() { ServerSecurityContextRepository defaultSecContextRepository = mock(ServerSecurityContextRepository.class); ServerSecurityContextRepository formLoginSecContextRepository = mock(ServerSecurityContextRepository.class); TestingAuthenticationToken token = new TestingAuthenticationToken("rob", "rob", "ROLE_USER"); given(defaultSecContextRepository.save(any(), any())).willReturn(Mono.empty()); given(defaultSecContextRepository.load(any())).willReturn(authentication(token)); given(formLoginSecContextRepository.save(any(), any())).willReturn(Mono.empty()); given(formLoginSecContextRepository.load(any())).willReturn(authentication(token)); SecurityWebFilterChain securityWebFilter = this.http .authorizeExchange() .anyExchange().authenticated() .and() .securityContextRepository(defaultSecContextRepository) .formLogin() .securityContextRepository(formLoginSecContextRepository) .and() .build(); WebTestClient webTestClient = WebTestClientBuilder .bindToWebFilters(securityWebFilter) .build(); WebDriver driver = WebTestClientHtmlUnitDriverBuilder .webTestClientSetup(webTestClient) .build(); DefaultLoginPage loginPage = DefaultLoginPage.to(driver) .assertAt(); HomePage homePage = loginPage.loginForm() .username("user") .password("password") .submit(HomePage.class); homePage.assertAt(); verify(defaultSecContextRepository, atLeastOnce()).load(any()); verify(formLoginSecContextRepository).save(any(), any()); }
Source:
<code>public String toString() { <START> return MoreObjects.toStringHelper("") <END> .add("ClientType", getStringFromOptional(mClientType)) .add("ServerAddress", mServerAddress) .add("ChannelId", mChannelId) .add("KeepAliveTime", getStringFromOptional(mKeepAliveTime)) .add("KeepAliveTimeout", getStringFromOptional(mKeepAliveTimeout)) .add("FlowControlWindow", getStringFromOptional(mFlowControlWindow)) .add("MaxInboundMessageSize", getStringFromOptional(mMaxInboundMessageSize)) .add("ChannelType", getStringFromOptional(mChannelType)) .omitNullValues() .toString(); }</code><technical_language>I confused this is supposed "" this</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("ClientType", getStringFromOptional(mClientType)) .add("ServerAddress", mServerAddress) .add("ChannelId", mChannelId) .add("KeepAliveTime", getStringFromOptional(mKeepAliveTime)) .add("KeepAliveTimeout", getStringFromOptional(mKeepAliveTimeout)) .add("FlowControlWindow", getStringFromOptional(mFlowControlWindow)) .add("MaxInboundMessageSize", getStringFromOptional(mMaxInboundMessageSize)) .add("ChannelType", getStringFromOptional(mChannelType)) .omitNullValues() .toString(); }
Source:
<code>public void testPrimaryKeyOrderIsNotAffectedIfReInsertedWithDifferentSecondaryKey() { final DualKeyLinkedMap<Integer, Integer, String> map = new DualKeyLinkedMap<>(2); final String value = "foobar"; map.put(1, 1, value); map.put(2, 2, value); <START> map.put(1, 3, value); <END> assertThat(map.keySetA().iterator().next(), is(1)); }</code><technical_language>do want check cleanup of key B 3 if in map</technical_language>

Target:
public void testPrimaryKeyOrderIsNotAffectedIfReInsertedWithDifferentSecondaryKey() { final DualKeyLinkedMap<Integer, Integer, String> map = new DualKeyLinkedMap<>(2); final String value1 = "1"; map.put(1, 1, value1); final String value2 = "2"; map.put(2, 2, value2); final String value3 = "3"; map.put(1, 3, value3); assertThat(map.keySetA().iterator().next(), is(1)); assertThat(map.values().iterator().next(), is(value3)); }
Source:
<code>private Image getEnhancedImage(final Image image, final Viewpoint viewpoint) { if <START> (ViewpointRegistry.getInstance().isFromPlugin(viewpoint) <END> && image != null) { return SiriusEditPlugin.getPlugin().getImage(getOverlayedDescriptor(image, "icons/full/decorator/folder_close.gif")); } return image; }</code><technical_language>do want decorate Viewpoint plugins workspace</technical_language>

Target:
private Image getEnhancedImage(final Image image, final Viewpoint viewpoint) { if (!ViewpointRegistry.getInstance().isFromPlugin(viewpoint) && image != null) { return SiriusEditPlugin.getPlugin().getImage(getOverlayedDescriptor(image, "icons/full/decorator/folder_close.gif")); } return image; }
Source:
<code>private static Long parseMaxMemory( String maxMemoryString ) { if ( maxMemoryString != null ) { maxMemoryString = maxMemoryString.trim(); if ( maxMemoryString.endsWith( "%" ) ) { int percent = Integer.parseInt( maxMemoryString.substring( 0, maxMemoryString.length() - 1 ) ); long result = calculateMaxMemoryFromPercent( percent ); if ( !canDetectFreeMemory() ) { System.err.println( "WARNING: amount of free memory couldn't be detected so defaults to " + bytes( result ) + ". For optimal performance instead explicitly specify amount of " + "memory that importer is allowed to use using " + Options.MAX_MEMORY.argument() ); <START> } <END> } return Settings.parseLongWithUnit( maxMemoryString ); } return null; }</code><technical_language>return result here, right</technical_language>

Target:
private static Long parseMaxMemory( String maxMemoryString ) { if ( maxMemoryString != null ) { maxMemoryString = maxMemoryString.trim(); if ( maxMemoryString.endsWith( "%" ) ) { int percent = Integer.parseInt( maxMemoryString.substring( 0, maxMemoryString.length() - 1 ) ); long result = calculateMaxMemoryFromPercent( percent ); if ( !canDetectFreeMemory() ) { System.err.println( "WARNING: amount of free memory couldn't be detected so defaults to " + bytes( result ) + ". For optimal performance instead explicitly specify amount of " + "memory that importer is allowed to use using " + Options.MAX_MEMORY.argument() ); } return result; } return Settings.parseLongWithUnit( maxMemoryString ); } return null; }
Source:
<code>private static void zipFiles(List<File> files, String basepath, OutputStream os) throws IOException { Closer closer = Closer.create(); try { ZipOutputStream zos = new ZipOutputStream(os); closer.register(zos); for (File file : files) { if (file.isFile()) { FileInputStream inputStream = new FileInputStream(file); closer.register(inputStream); <START> writeZipEntry(zipEntry(basepath, file), inputStream, zos); <END> } } } catch (IOException ioe) { throw closer.rethrow(ioe); } finally { closer.close(); } }</code><technical_language>strange write a zip entry pathname refers a directory. supposed be, automatically done children files added, empty directories ? I guess skipped</technical_language>

Target:
private static void zipFiles(List<File> files, String basepath, OutputStream os) throws IOException { Closer closer = Closer.create(); try { ZipOutputStream zos = new ZipOutputStream(os); closer.register(zos); for (File file : files) { if (file.isFile()) { FileInputStream inputStream = new FileInputStream(file); closer.register(inputStream); writeZipEntry(zipEntry(basepath, file), inputStream, zos); } else { ZipEntry ze = zipEntry(basepath, file); logger.trace("Adding directory zip entry: " + ze.toString()); zos.putNextEntry(ze); } } } catch (IOException ioe) { throw closer.rethrow(ioe); } finally { closer.close(); } }
Source:
<code>private Method findMethod(Class<?> clazz, String methodName) { return ReflectionUtils.findMethod(clazz, methodName) .orElseGet(() -> ReflectionUtils.findMethod(clazz, methodName, ExtensionContext.class) .orElseThrow(() -> new JUnitException( format("Could not find method [%s] in class [%s]", methodName, clazz.getName())))); <START> } <END></code><technical_language>reuse this logic MethodArgumentsProvider somehow</technical_language>

Target:
private Method findMethod(Class<?> clazz, String methodName) { return ReflectionUtils.findMethod(clazz, methodName) .orElseGet(() -> ReflectionUtils.getRequiredMethod(clazz, methodName, ExtensionContext.class)); }
Source:
<code>public void testNonExistentUrl() { WebRequestHandler request = new WebRequestHandler(); try { request.sendGet( getUrl("<LINK_0>"), null); <START> } catch (final IOException e) { <END> assertTrue(e instanceof UnknownHostException); assertTrue(e.getMessage().toLowerCase(Locale.US).contains("unable to resolve host")); } }</code><technical_language>assertfail (if exception thrown)</technical_language>

Target:
public void testNonExistentUrl() { WebRequestHandler request = new WebRequestHandler(); try { request.sendGet( getUrl("<LINK_0>"), null); fail("Unreachable host, should throw IOException"); } catch (final IOException e) { assertTrue(e instanceof UnknownHostException); assertTrue(e.getMessage().toLowerCase(Locale.US).contains("unable to resolve host")); } }
Source:
<code>public ColumnWriterV1(ColumnDescriptor path, PageWriter pageWriter, BloomFilterWriter bloomFilterWriter, ParquetProperties props) { this(path, pageWriter, props); <START> if (path.getPath().length == 1) { <END> this.bloomFilterWriter = bloomFilterWriter; HashMap<String, Long> bloomFilterInfo = props.getBloomFilterInfo(); String column = path.getPath()[0]; if (bloomFilterInfo.keySet().contains(column)) { this.bloomFilter = new BloomFilter(bloomFilterInfo.get(column).intValue()); } } }</code><technical_language>nit: remove a level of indentation if (path.getPath().length != 1) return;</technical_language>

Target:
public ColumnWriterV1(ColumnDescriptor path, PageWriter pageWriter, BloomFilterWriter bloomFilterWriter, ParquetProperties props) { super(path, pageWriter, bloomFilterWriter, props); }
Source:
<code>public void testAcceptWhenIsExpectedClass() { when(rule.getId()).thenReturn(definition.getClass().getName()); <START> boolean actual = check.accepts(rule, context); <END> assertTrue(actual); }</code><technical_language>for consistency, please final boolean actual</technical_language>

Target:
public void testAcceptWhenIsExpectedClass() { when(rule.getId()).thenReturn(definition.getClass().getName()); final boolean actual = check.accepts(rule, context); assertTrue(actual); }
Source:
<code>public void support_short_form_subscriber_methods() { <START> final ShortFormSubscriber subscriber = new ShortFormSubscriber(); <END> checkFailure(subscriber); }</code><technical_language>Please rename this subscriber</technical_language>

Target:
public void support_short_form_subscriber_methods() { final FailureMessageSubscriber subscriber = new FailureMessageSubscriber(); checkFailure(subscriber); }
Source:
<code><START> private List<Guid> performVmCheckpointsOperation(VDSCommandType vdsCommandType, VdsAndVmIDVDSParametersBase params) { <END> VDSReturnValue vdsRetVal; try { vdsRetVal = runVdsCommand(vdsCommandType, params); if (!vdsRetVal.getSucceeded()) { EngineException engineException = new EngineException(); engineException.setVdsError(vdsRetVal.getVdsError()); throw engineException; } } catch (EngineException e) { log.error("Failed to execute '{}': {}", vdsCommandType, e); throw e; } return (List<Guid>) vdsRetVal.getReturnValue(); }</code><technical_language>line exceeded, please split</technical_language>

Target:
private VDSReturnValue performVmCheckpointsOperation(VDSCommandType vdsCommandType, VdsAndVmIDVDSParametersBase params) { VDSReturnValue vdsRetVal; try { vdsRetVal = runVdsCommand(vdsCommandType, params); if (!vdsRetVal.getSucceeded()) { EngineException engineException = new EngineException(); engineException.setVdsError(vdsRetVal.getVdsError()); engineException.setVdsReturnValue(vdsRetVal); throw engineException; } } catch (EngineException e) { log.error("Failed to execute '{}': {}", vdsCommandType, e); throw e; } return vdsRetVal; }
Source:
<code>public void setCallback(ReportProblemFragmentCallback callback) { <START> this.mCallback = callback; <END> }</code><technical_language>able remove this. here</technical_language>

Target:
public void setCallback(ReportProblemFragmentCallback callback) { mCallback = callback; }
Source:
<code>public void setup() { Request request1 = preparePost() .setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build()) .setBodyGenerator(createStaticBodyGenerator(LONG_LASTING_QUERY, UTF_8)) .setHeader(PRESTO_USER, "user1") .build(); queryResults = client.execute(request1, createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC)); client.execute(prepareGet().setUri(queryResults.getNextUri()).build(), createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC)); Request request2 = preparePost() .setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build()) .setBodyGenerator(createStaticBodyGenerator(LONG_LASTING_QUERY, UTF_8)) .setHeader(PRESTO_USER, "user2") .build(); QueryResults queryResults2 = client.execute(request2, createJsonResponseHandler(jsonCodec(QueryResults.class))); client.execute(prepareGet().setUri(queryResults2.getNextUri()).build(), createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC)); <START> int queryCount = 0; <END> boolean queued = true; while (queued && queryCount != 2) { queued = false; List<BasicQueryInfo> queryInfos = client.execute( prepareGet().setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/query").build()).build(), createJsonResponseHandler(listJsonCodec(BasicQueryInfo.class))); queryCount = queryInfos.size(); for (BasicQueryInfo queryInfo : queryInfos) { queued = queued || queryInfo.getState() == QUEUED; } } }</code><technical_language>I simplify this java while (true) { List<BasicQueryInfo> queryInfos = ...; if ((queryInfos.size() == 2) && queryInfos.stream().allMatch(info -> info.getState() == QUEUED)) { break; } }</technical_language>

Target:
public void setup() { Request request1 = preparePost() .setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build()) .setBodyGenerator(createStaticBodyGenerator(LONG_LASTING_QUERY, UTF_8)) .setHeader(PRESTO_USER, "user1") .build(); queryResults = client.execute(request1, createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC)); client.execute(prepareGet().setUri(queryResults.getNextUri()).build(), createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC)); Request request2 = preparePost() .setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build()) .setBodyGenerator(createStaticBodyGenerator(LONG_LASTING_QUERY, UTF_8)) .setHeader(PRESTO_USER, "user2") .build(); QueryResults queryResults2 = client.execute(request2, createJsonResponseHandler(jsonCodec(QueryResults.class))); client.execute(prepareGet().setUri(queryResults2.getNextUri()).build(), createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC)); while (true) { List<BasicQueryInfo> queryInfos = client.execute( prepareGet().setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/query").build()).build(), createJsonResponseHandler(listJsonCodec(BasicQueryInfo.class))); if ((queryInfos.size() == 2) && queryInfos.stream().noneMatch(info -> info.getState() == QUEUED)) { break; } } }