auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public JsonWriter(Sink sink) { this(Okio.buffer(sink)); }

Target:
public JsonWriter(Sink sink) { if (sink == null) { throw new NullPointerException("sink == null"); } this.sink = Okio.buffer(sink); }
Source:
private static boolean forcedMove(Path from, Path to) { try { Files.move(from, to); return true; } catch (IOException e) { ControllerLogger.ROOT_LOGGER.cannotRename(e, from, to); return false; } }

Target:
private static boolean forcedMove(Path from, Path to) { try { Files.move(from, to, StandardCopyOption.REPLACE_EXISTING); return true; } catch (IOException e) { ControllerLogger.ROOT_LOGGER.cannotRename(e, from, to); return false; } }
Source:
public void testDecimalBackedByINT32() throws Exception { for (int precision = 1; precision <= MAX_PRECISION_INT32; precision++) { int scale = current().nextInt(precision); MessageType parquetSchema = parseMessageType(format("message hive_decimal { optional INT32 test (DECIMAL(%d, %d)); }", precision, scale)); ContiguousSet<Integer> intValues = intsBetween(1, 1_000); ImmutableList.Builder<SqlDecimal> expectedValues = new ImmutableList.Builder<>(); for (Integer value : intValues) { expectedValues.add(SqlDecimal.of(value, precision, scale)); } tester.testRoundTrip(javaIntObjectInspector, intValues, expectedValues.build(), createDecimalType(precision, scale), Optional.of(parquetSchema)); } }

Target:
public void testDecimalBackedByINT32() throws Exception { for (int precision = 1; precision <= MAX_PRECISION_INT32; precision++) { int scale = ThreadLocalRandom.current().nextInt(precision); MessageType parquetSchema = parseMessageType(format("message hive_decimal { optional INT32 test (DECIMAL(%d, %d)); }", precision, scale)); ContiguousSet<Integer> intValues = intsBetween(1, 1_000); ImmutableList.Builder<SqlDecimal> expectedValues = new ImmutableList.Builder<>(); for (Integer value : intValues) { expectedValues.add(SqlDecimal.of(value, precision, scale)); } tester.testRoundTrip(javaIntObjectInspector, intValues, expectedValues.build(), createDecimalType(precision, scale), Optional.of(parquetSchema)); } }
Source:
public QueryStatistics( Duration cpuTime, Duration wallTime, Duration queuedTime, Optional<Duration> analysisTime, Optional<Duration> distributedPlanningTime, long peakMemoryBytes, long totalBytes, long totalRows, long outputBytes, long outputRows, long writtenBytes, long writtenRows, double cumulativeMemory, int completedSplits, boolean complete, List<StageCpuDistribution> cpuTimeDistribution, List<String> operatorSummaries) { this.cpuTime = requireNonNull(cpuTime, "cpuTime is null"); this.wallTime = requireNonNull(wallTime, "wallTime is null"); this.queuedTime = requireNonNull(queuedTime, "queuedTime is null"); this.analysisTime = requireNonNull(analysisTime, "analysisTime is null"); this.distributedPlanningTime = requireNonNull(distributedPlanningTime, "distributedPlanningTime is null"); this.peakMemoryBytes = requireNonNull(peakMemoryBytes, "peakMemoryBytes is null"); this.totalBytes = requireNonNull(totalBytes, "totalBytes is null"); this.totalRows = requireNonNull(totalRows, "totalRows is null"); this.outputBytes = outputBytes; this.outputRows = outputRows; this.writtenBytes = writtenBytes; this.writtenRows = writtenRows; this.cumulativeMemory = cumulativeMemory; this.completedSplits = requireNonNull(completedSplits, "completedSplits is null"); this.complete = complete; this.cpuTimeDistribution = requireNonNull(cpuTimeDistribution, "cpuTimeDistribution is null"); this.operatorSummaries = requireNonNull(operatorSummaries, "operatorSummaries is null"); }

Target:
public QueryStatistics( Duration cpuTime, Duration wallTime, Duration queuedTime, Optional<Duration> analysisTime, Optional<Duration> distributedPlanningTime, long peakMemoryBytes, long totalBytes, long totalRows, long outputBytes, long outputRows, long writtenBytes, long writtenRows, double cumulativeMemory, int completedSplits, boolean complete, List<StageCpuDistribution> cpuTimeDistribution, List<String> operatorSummaries) { this.cpuTime = requireNonNull(cpuTime, "cpuTime is null"); this.wallTime = requireNonNull(wallTime, "wallTime is null"); this.queuedTime = requireNonNull(queuedTime, "queuedTime is null"); this.analysisTime = requireNonNull(analysisTime, "analysisTime is null"); this.distributedPlanningTime = requireNonNull(distributedPlanningTime, "distributedPlanningTime is null"); this.peakMemoryBytes = peakMemoryBytes; this.totalBytes = totalBytes; this.totalRows = totalRows; this.outputBytes = outputBytes; this.outputRows = outputRows; this.writtenBytes = writtenBytes; this.writtenRows = writtenRows; this.cumulativeMemory = cumulativeMemory; this.completedSplits = completedSplits; this.complete = complete; this.cpuTimeDistribution = requireNonNull(cpuTimeDistribution, "cpuTimeDistribution is null"); this.operatorSummaries = requireNonNull(operatorSummaries, "operatorSummaries is null"); }
Source:
public void onRefresh() { EventBus.getDefault().post(new RefreshListener.RefreshEvent()); }

Target:
public void onRefresh() { EventBus.getDefault().post(new CourseDashboardRefreshEvent()); }
Source:
void putCanBeUsedToReplace() { realCache.put("id", 0); realCache.put("id", 1); assertThat(realCache.get("id"), isPresentAndIs(1)); verify(cacheRemovalListener, never()).accept(any()); }

Target:
void putCanBeUsedToReplace() { realCache.put("id", 0); realCache.put("id", 1); assertThat(realCache.get("id"), isPresentAndIs(1)); verify(cacheRemovalListener, never()).accept(any(), any()); }
Source:
public TaskStats(DateTime createTime, DateTime endTime) { this(createTime, null, null, null, endTime, new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), 0, 0, 0, 0, 0, 0, 0.0, new DataSize(0, BYTE), new DataSize(0, BYTE), new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), false, ImmutableSet.of(), new DataSize(0, BYTE), 0, new DataSize(0, BYTE), 0, new DataSize(0, BYTE), 0, new DataSize(0, BYTE), ImmutableList.of() ); }

Target:
public TaskStats(DateTime createTime, DateTime endTime) { this(createTime, null, null, null, endTime, new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), 0, 0, 0, 0, 0, 0, 0, 0.0, new DataSize(0, BYTE), new DataSize(0, BYTE), new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), new Duration(0, MILLISECONDS), false, ImmutableSet.of(), new DataSize(0, BYTE), 0, new DataSize(0, BYTE), 0, new DataSize(0, BYTE), 0, new DataSize(0, BYTE), ImmutableList.of()); }
Source:
public void onResume() { super.onResume(); this.setTitle("Switch Instance"); Criteria crit = new Criteria(); crit.setAccuracy(Criteria.ACCURACY_COARSE); userLocation = getBestLocation(crit); RequestGenerator rg = new RequestGenerator(); loadingInstances = ProgressDialog.show(this, "Please Wait", "Loading Instances..."); rg.getInstancesNearLocation(userLocation.getLatitude(), userLocation.getLongitude(), new InstanceListHandler()); updateAccountElements(); findViewById(R.id.login_button).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent(InstanceSwitcherActivity.this, LoginActivity.class)); } }); findViewById(R.id.logout_button).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { App.getLoginManager().logOut(InstanceSwitcherActivity.this); startActivity(new Intent(InstanceSwitcherActivity.this, LoginActivity.class)); } }); }

Target:
public void onResume() { super.onResume(); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); userLocation = getBestLocation(criteria); RequestGenerator rg = new RequestGenerator(); loadingInstances = ProgressDialog.show(this, "Please Wait", "Loading Instances..."); rg.getInstancesNearLocation(userLocation.getLatitude(), userLocation.getLongitude(), new InstanceListHandler()); updateAccountElements(); findViewById(R.id.login_button).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent(InstanceSwitcherActivity.this, LoginActivity.class)); } }); findViewById(R.id.logout_button).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { App.getLoginManager().logOut(InstanceSwitcherActivity.this); startActivity(new Intent(InstanceSwitcherActivity.this, LoginActivity.class)); } }); }
Source:
public void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerAsyncClient(httpClient, serviceVersion); receiptPngSourceUrlRunnerTextDetails((sourceUrl, includeTextDetails) -> { SyncPoller<OperationResult, List<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl( new RecognizeOptions(sourceUrl).setIncludeTextContent(includeTextDetails)).getSyncPoller(); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), includeTextDetails); }); }

Target:
public void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerAsyncClient(httpClient, serviceVersion); receiptPngSourceUrlRunnerTextDetails((sourceUrl, includeTextContent) -> { SyncPoller<OperationResult, List<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl( new RecognizeOptions(sourceUrl).setIncludeTextContent(includeTextContent) .setPollInterval(durationTestMode)) .getSyncPoller(); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), includeTextContent); }); }
Source:
public int hashCode(){ int hashCode; final int from = this.getFrom(); final int to = this.getTo(); hashCode = new Integer(((from+to+1)*(from+to))/2).intValue()+to; return hashCode; }

Target:
public int hashCode(){ int hashCode; final int from = this.getFrom(); final int to = this.getTo(); hashCode = ((from+to+1)*(from+to))/2+to; return hashCode; }
Source:
public static Object[][] cartesianProduct(Object[][] ... dataProviders){ final List[] lists = Arrays.stream(dataProviders) .map(TestNGUtils::nestedArraysToNestedLists) .toArray(List[]::new); @SuppressWarnings("unchecked") final List<List<List<Object>>> product = Lists.cartesianProduct(lists); final List<List<Object>> mergeProduct = product.stream() .map((List<List<Object>> list) -> { List<Object> result = new ArrayList<>(); list.forEach(result::addAll); return result; }).collect(Collectors.toList()); return nestedListsToNestedArrays(mergeProduct); }

Target:
public static Object[][] cartesianProduct(Object[][]... dataProviders) { List<List<List<Object>>> lists = Arrays.stream(dataProviders) .map(TestNGUtils::nestedArraysToNestedLists) .collect(Collectors.toList()); final List<List<List<Object>>> product = Lists.cartesianProduct(lists); final List<List<Object>> mergeProduct = product.stream() .map( l -> l.stream() .flatMap(Collection::stream) .collect(Collectors.toList())) .collect(Collectors.toList()); return nestedListsToNestedArrays(mergeProduct); }
Source:
protected void onPostExecute(Boolean hasUnsyncedNotes) { PreferencesFragment fragment = fragmentWeakReference.get(); if (fragment == null) { return; } if (hasUnsyncedNotes) { AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getContext()); builder.setTitle(R.string.unsynced_notes); builder.setMessage(R.string.unsynced_notes_message); builder.setPositiveButton(R.string.delete_notes, fragment.signOutClickListener); builder.setNeutralButton(R.string.visit_web_app, fragment.loadWebAppClickListener); builder.setNegativeButton(R.string.cancel, null); builder.show(); } else { fragment.signOut(); } }

Target:
protected void onPostExecute(Boolean hasUnsyncedNotes) { PreferencesFragment fragment = fragmentWeakReference.get(); if (fragment == null) { return; } if (hasUnsyncedNotes) { new AlertDialog.Builder(fragment.getContext()) .setTitle(R.string.unsynced_notes) .setMessage(R.string.unsynced_notes_message) .setPositiveButton(R.string.delete_notes, fragment.signOutClickListener) .setNeutralButton(R.string.visit_web_app, fragment.loadWebAppClickListener) .setNegativeButton(R.string.cancel, null) .show(); } else { fragment.signOut(); } }
Source:
private String generateExtNameAssignment(String[] value, boolean hasInvocation) { String getNameCode = defaultExtName == null ? null : String.format("\"%s\"", defaultExtName); for (int i = value.length - 1; i >= 0; --i) { if ("protocol".equals(value[i])) { getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode); } else if (hasInvocation) { getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\", (String) %s)", value[i], getNameCode); } } return String.format(CODE_EXT_NAME_ASSIGNMENT, getNameCode); }

Target:
private String generateExtNameAssignment(String[] value, boolean hasInvocation) { String getNameCode = defaultExtName == null ? null : String.format("\"%s\"", defaultExtName); for (int i = value.length - 1; i >= 0; --i) { if (Constants.PROTOCOL_KEY.equals(value[i])) { getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode); } else if (hasInvocation) { getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\", (String) %s)", value[i], getNameCode); } } return String.format(CODE_EXT_NAME_ASSIGNMENT, getNameCode); }
Source:
protected String toString(NSDictionary args) { StringBuilder builder = new StringBuilder(); builder.append(pages.size() + " pages.\n\t"); for (WebkitPage p : pages) { builder.append("[" + p.getPageId() + "],title:" + p.getTitle() + ",url:" + p.getURL() + "\t\tConnection:" + p.getConnection() + "\n\t"); } return builder.toString(); }

Target:
protected String toString(NSDictionary args) { StringBuilder builder = new StringBuilder(); builder.append(pages.size() + " pages.\n\t"); for (WebkitPage p : pages) { builder.append("[").append(p.getPageId()).append("], title: ").append(p.getTitle()).append(", url: ") .append(p.getURL()).append(" \t\tConnection:").append(p.getConnection()).append("\n\t"); } return builder.toString(); }
Source:
private void setValue(Type type, BlockBuilder blockBuilder, String value) { if (value == null) { blockBuilder.appendNull(); return; } boolean handled = true; if (type instanceof FixedWidthType) { completedBytes += ((FixedWidthType) type).getFixedSize(); if (type instanceof BigintType) { type.writeLong(blockBuilder, parseDouble(value).longValue()); } else if (type instanceof IntegerType) { blockBuilder.writeInt(parseDouble(value).intValue()); } else if (type instanceof TinyintType) { blockBuilder.writeByte(parseDouble(value).byteValue()); } else if (type instanceof SmallintType) { blockBuilder.writeShort(parseDouble(value).shortValue()); } else if (type instanceof BooleanType) { type.writeBoolean(blockBuilder, Boolean.valueOf(value)); } else if (type instanceof DecimalType || type instanceof DoubleType) { type.writeDouble(blockBuilder, parseDouble(value).doubleValue()); } else if (type instanceof TimestampType) { type.writeLong(blockBuilder, Long.valueOf(value)); } else { handled = false; } } else if (type instanceof VarcharType) { Slice slice = Slices.utf8Slice(value); blockBuilder.writeBytes(slice, 0, slice.length()).closeEntry(); completedBytes += slice.length(); } else { handled = false; } if (!handled) { throw new PinotException(PinotErrorCode.PINOT_UNSUPPORTED_COLUMN_TYPE, Optional.empty(), "type '" + type + "' not supported"); } }

Target:
private void setValue(Type type, BlockBuilder blockBuilder, String value) { if (value == null) { blockBuilder.appendNull(); return; } if (!(type instanceof FixedWidthType) && !(type instanceof VarcharType)) { throw new PinotException(PINOT_UNSUPPORTED_COLUMN_TYPE, Optional.empty(), "type '" + type + "' not supported"); } if (type instanceof FixedWidthType) { completedBytes += ((FixedWidthType) type).getFixedSize(); if (type instanceof BigintType) { type.writeLong(blockBuilder, parseDouble(value).longValue()); } else if (type instanceof IntegerType) { blockBuilder.writeInt(parseDouble(value).intValue()); } else if (type instanceof TinyintType) { blockBuilder.writeByte(parseDouble(value).byteValue()); } else if (type instanceof SmallintType) { blockBuilder.writeShort(parseDouble(value).shortValue()); } else if (type instanceof BooleanType) { type.writeBoolean(blockBuilder, parseBoolean(value)); } else if (type instanceof DecimalType || type instanceof DoubleType) { type.writeDouble(blockBuilder, parseDouble(value)); } else if (type instanceof TimestampType) { type.writeLong(blockBuilder, parseLong(value)); } else { throw new PinotException(PINOT_UNSUPPORTED_COLUMN_TYPE, Optional.empty(), "type '" + type + "' not supported"); } } else { Slice slice = Slices.utf8Slice(value); blockBuilder.writeBytes(slice, 0, slice.length()).closeEntry(); completedBytes += slice.length(); } }
Source:
private static void storeInSession(final HttpServletRequest request, final AuthenticationContext authenticationContext) { final HttpSession session = request.getSession(); session.setAttribute(LOGGED_USER_ATTRIBUTE, authenticationContext.getUser()); session.setAttribute(LOGGED_USER_AUTHENTICATION_CONTEXT_ATTRIBUTE, authenticationContext.export()); }

Target:
private static void storeInSession(final HttpServletRequest request, final AuthenticationContext authenticationContext) { final HttpSession session = request.getSession(); session.setAttribute(LOGGED_USER_ATTRIBUTE, authenticationContext.getUser()); session.setAttribute(LOGGED_USER_AUTHENTICATION_CONTEXT_ATTRIBUTE, authenticationContext); }
Source:
private static void checkNotIndeterminate(Boolean equalsResult) { if (equalsResult == null) { throw new PrestoException(NOT_SUPPORTED, "contains does not support indeterminate comparison results"); } }

Target:
private static void checkNotIndeterminate(Boolean equalsResult) { if (equalsResult == null) { throw new PrestoException(NOT_SUPPORTED, "contains does not support arrays with elements that are null or contain null"); } }
Source:
public ArrayList<Person> getTechs(boolean noZeroMinute, UUID firstTechId, boolean sorted, boolean eliteFirst) { ArrayList<Person> techs = new ArrayList<>(); Person firstTech = getPerson(firstTechId); if ((firstTech != null) && firstTech.isTech() && firstTech.isActive() && (!noZeroMinute || firstTech.getMinutesLeft() > 0)) { techs.add(firstTech); } for (Person p : getPersonnel()) { if (p.isTech() && p.isActive() && (!p.equals(firstTech)) && (!noZeroMinute || (p.getMinutesLeft() > 0))) { techs.add(p); } } for (Unit u : getUnits()) { if (u.isSelfCrewed() && !(u.getEntity() instanceof Infantry) && null != u.getEngineer()) { techs.add(u.getEngineer()); } } if (sorted) { techs.sort((person1, person2) -> { int retVal = 0; boolean p1Secondary = !person1.isTechPrimary() && person1.isTechSecondary(); boolean p2Secondary = !person2.isTechPrimary() && person2.isTechSecondary(); if (person1.getExperienceLevel(p1Secondary) > person2.getExperienceLevel(p2Secondary)) { retVal = -1; } else if (person1.getExperienceLevel(p1Secondary) < person2.getExperienceLevel(p2Secondary)) { retVal = 1; } return eliteFirst ? retVal *= -1 : retVal; }); } return techs; }

Target:
public ArrayList<Person> getTechs(boolean noZeroMinute, UUID firstTechId, boolean sorted, boolean eliteFirst) { ArrayList<Person> techs = new ArrayList<>(); Person firstTech = getPerson(firstTechId); if ((firstTech != null) && firstTech.isTech() && firstTech.isActive() && (!noZeroMinute || firstTech.getMinutesLeft() > 0)) { techs.add(firstTech); } for (Person p : getPersonnel()) { if (p.isTech() && p.isActive() && (!p.equals(firstTech)) && (!noZeroMinute || (p.getMinutesLeft() > 0))) { techs.add(p); } } for (Unit u : getUnits()) { if (u.isSelfCrewed() && !(u.getEntity() instanceof Infantry) && null != u.getEngineer()) { techs.add(u.getEngineer()); } } if (sorted) { techs.sort((person1, person2) -> { int retVal = 0; boolean p1Secondary = !person1.isTechPrimary() && person1.isTechSecondary(); boolean p2Secondary = !person2.isTechPrimary() && person2.isTechSecondary(); if (person1.getExperienceLevel(p1Secondary) > person2.getExperienceLevel(p2Secondary)) { retVal = -1; } else if (person1.getExperienceLevel(p1Secondary) < person2.getExperienceLevel(p2Secondary)) { retVal = 1; } return eliteFirst ? -retVal : retVal; }); } return techs; }
Source:
public Openstack(@Nonnull String endPointUrl, @Nonnull String identity, @Nonnull Secret credential, @CheckForNull String region) { String[] id = identity.split(":", 2); String tenant = id.length > 0 ? id[0] : ""; String username = id.length > 1 ? id[1] : ""; if (Jenkins.getInstance() != null && Jenkins.getInstance().proxy != null){ ProxyConfiguration proxy = Jenkins.getInstance().proxy; LOGGER.info("So we have a proxy defined with the following details:"); LOGGER.info("proxy.name= " +proxy.name); LOGGER.info("proxy.port= " +proxy.port); client = OSFactory.builder().endpoint(endPointUrl).credentials(username, credential.getPlainText()) .tenantName(tenant) .withConfig(Config.newConfig().withSSLVerificationDisabled().withProxy(ProxyHost.of(HTTP_PREFIX +proxy.name,proxy.port,proxy.getUserName(), proxy.getPassword()))) .authenticate() .useRegion(region); } else { client = OSFactory.builder().endpoint(endPointUrl) .credentials(username, credential.getPlainText()) .tenantName(tenant) .authenticate() .useRegion(region); } debug("Openstack client created for " + endPointUrl); }

Target:
public Openstack(@Nonnull String endPointUrl, @Nonnull String identity, @Nonnull Secret credential, @CheckForNull String region) { String[] id = identity.split(":", 2); String tenant = id.length > 0 ? id[0] : ""; String username = id.length > 1 ? id[1] : ""; Config config = Config.newConfig(); if (Jenkins.getInstance() != null && Jenkins.getInstance().proxy != null) { ProxyConfiguration proxy = Jenkins.getInstance().proxy; debug("Jenkins has a proxy defined with the following details: proxy.name= " +proxy.name +"proxy.port= " +proxy.port); config = Config.newConfig().withProxy(ProxyHost.of(HTTP_PREFIX + proxy.name, proxy.port, proxy.getUserName(), proxy.getPassword())); } client = OSFactory.builder().endpoint(endPointUrl).credentials(username, credential.getPlainText()) .tenantName(tenant) .withConfig(config) .authenticate() .useRegion(region); debug("Openstack client created for " + endPointUrl); }
Source:
public FlightMultiAbility(Player player) { super(player); if (bPlayer.isOnCooldown(this)) { return; } FlightMultiAbility f = getAbility(player, FlightMultiAbility.class); if (f != null) { if (player.isSneaking()) { player.eject(); return; } switch (player.getInventory().getHeldItemSlot()) { case 0: f.manageSoarSpeed(); break; case 3: f.remove(); break; } return; } if (player.isInsideVehicle()) { return; } if (isWater(player.getEyeLocation().getBlock())) { return; } if (player.isOnGround()) { return; } CoreAbility abil = null; if (hasAbility(player, AirSpout.class)) { abil = getAbility(player, AirSpout.class); } else if (hasAbility(player, WaterSpout.class)) { abil = getAbility(player, WaterSpout.class); } else if (hasAbility(player, FireJet.class)) { abil = getAbility(player, FireJet.class); } else if (hasAbility(player, AirScooter.class)) { abil = getAbility(player, AirScooter.class); } if (abil != null) { abil.remove(); } MultiAbilityManager.bindMultiAbility(player, "Flight"); flight = ProjectKorra.flightHandler.createInstance(player, "FlightMultiAbility"); hadGlide = player.isGliding(); flying.add(player.getUniqueId()); prevDir = player.getEyeLocation().getDirection().clone(); duration = getConfig().getLong("Abilities.Air.Flight.Duration"); baseSpeed = getConfig().getDouble("Abilities.Air.Flight.BaseSpeed"); slowSpeed = baseSpeed/2; fastSpeed = baseSpeed*2; multiplier = baseSpeed; start(); }

Target:
public FlightMultiAbility(Player player) { super(player); if (bPlayer.isOnCooldown(this)) { return; } FlightMultiAbility f = getAbility(player, FlightMultiAbility.class); if (f != null) { if (player.isSneaking()) { player.eject(); return; } switch (player.getInventory().getHeldItemSlot()) { case 0: f.manageSoarSpeed(); break; case 3: f.remove(); break; } return; } if (player.isInsideVehicle()) { return; } if (isWater(player.getEyeLocation().getBlock())) { return; } if (player.isOnGround()) { return; } CoreAbility abil = null; if (hasAbility(player, AirSpout.class)) { abil = getAbility(player, AirSpout.class); } else if (hasAbility(player, WaterSpout.class)) { abil = getAbility(player, WaterSpout.class); } else if (hasAbility(player, FireJet.class)) { abil = getAbility(player, FireJet.class); } else if (hasAbility(player, AirScooter.class)) { abil = getAbility(player, AirScooter.class); } if (abil != null) { abil.remove(); } MultiAbilityManager.bindMultiAbility(player, "Flight"); ProjectKorra.flightHandler.createInstance(player, ID); hadGlide = player.isGliding(); flying.add(player.getUniqueId()); prevDir = player.getEyeLocation().getDirection().clone(); duration = getConfig().getLong("Abilities.Air.Flight.Duration"); baseSpeed = getConfig().getDouble("Abilities.Air.Flight.BaseSpeed"); slowSpeed = baseSpeed/2; fastSpeed = baseSpeed*2; multiplier = baseSpeed; start(); }
Source:
private Object getAdapter(Object adaptable, Class c) { if (c.isInstance(adaptable)) { return adaptable; } if (adaptable instanceof IAdaptable) { IAdaptable a = (IAdaptable) adaptable; Object adapter = a.getAdapter(c); if (c.isInstance(adapter)) { return adapter; } } return null; }

Target:
private Object getAdapter(Object adaptable, Class c) { if (c.isInstance(adaptable)) return adaptable; if (adaptable instanceof IAdaptable) { IAdaptable a = (IAdaptable) adaptable; Object adapter = a.getAdapter(c); if (c.isInstance(adapter)) return adapter; } return null; }
Source:
public static Map<String, List<String>> getQueryParams(final URL url) { if (url == null) { throw new IllegalArgumentException("Cannot get query params from the null url"); } Map<String, List<String>> returnValue = new HashMap<>(); if (url.getQuery() == null) { return returnValue; } String[] pairs = url.getQuery().split("&"); for (String pair : pairs) { if (pair.isEmpty()) { continue; } int idx = pair.indexOf('='); String key = pair.substring(0, idx); String value = pair.substring(idx + 1); try { key = URLDecoder.decode(key, StandardCharsets.UTF_8.toString()); value = URLDecoder.decode(value, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Could not find UTF-8 encoding", e); } List<String> paramValues = returnValue.computeIfAbsent(key, k -> new LinkedList<>()); paramValues.add(value); } return returnValue; }

Target:
public static Map<String, List<String>> getQueryParams(final URL url) { if (url == null) { throw new IllegalArgumentException("Cannot get query params from the null url"); } Map<String, List<String>> returnValue = new HashMap<>(); if (url.getQuery() == null) { return returnValue; } String[] pairs = url.getQuery().split("&"); for (String pair : pairs) { if (pair.isEmpty()) { continue; } int idx = pair.indexOf('='); if (idx == -1) { returnValue.computeIfAbsent(pair, k -> new LinkedList<>()); continue; } String key = pair.substring(0, idx); String value = pair.substring(idx + 1); try { key = URLDecoder.decode(key, StandardCharsets.UTF_8.toString()); value = URLDecoder.decode(value, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Could not find UTF-8 encoding", e); } List<String> paramValues = returnValue.computeIfAbsent(key, k -> new LinkedList<>()); paramValues.add(value); } return returnValue; }
Source:
public boolean execute(String jobName, Date jobRunDate) throws InterruptedException { List<String> listOfSaeFileNames = getConcurStandardAccountingExtractService().buildListOfFileNamesToBeProcessed(); for (String saeFileName : listOfSaeFileNames) { LOG.debug("execute, processing: " + saeFileName); try { processCurrentFileAndExtractPdpFeedFromSAEFile(saeFileName); } catch (Exception e) { LOG.error("execute, there was an unexpected error processing a file: ", e); } finally { getFileStorageService().removeDoneFiles(Collections.singletonList(saeFileName)); } } return true; }

Target:
public boolean execute(String jobName, Date jobRunDate) throws InterruptedException { List<String> listOfSaeFullyQualifiedFileNames = getConcurStandardAccountingExtractService().buildListOfFullyQualifiedFileNamesToBeProcessed(); for (String saeFileName : listOfSaeFullyQualifiedFileNames) { LOG.debug("execute, processing: " + saeFileName); try { processCurrentFileAndExtractPdpFeedFromSAEFile(saeFileName); } catch (Exception e) { LOG.error("execute, there was an unexpected error processing a file: ", e); } finally { getFileStorageService().removeDoneFiles(Collections.singletonList(saeFileName)); } } return true; }
Source:
private void onMaintenance() { ArrayList<ActionParametersBase> list = new ArrayList<>(); for (StorageDomain item : getSelectedItems()) { DeactivateStorageDomainWithOvfUpdateParameters parameters = new DeactivateStorageDomainWithOvfUpdateParameters(); parameters.setStorageDomainId(getEntity().getId()); parameters.setForceMaintenance(false); if (item.getStoragePoolId() != null) { parameters.setStoragePoolId(item.getStoragePoolId()); } list.add(parameters); } final ConfirmationModel confirmationModel = (ConfirmationModel) getWindow(); confirmationModel.startProgress(); Frontend.getInstance().runMultipleAction(ActionType.DeactivateStorageDomainWithOvfUpdate, list, result -> { confirmationModel.stopProgress(); setWindow(null); }, null); }

Target:
private void onMaintenance() { ArrayList<ActionParametersBase> list = new ArrayList<>(); for (StorageDomain item : getSelectedItems()) { DeactivateStorageDomainWithOvfUpdateParameters parameters = new DeactivateStorageDomainWithOvfUpdateParameters(); parameters.setStorageDomainId(getEntity().getId()); if (item.getStoragePoolId() != null) { parameters.setStoragePoolId(item.getStoragePoolId()); } list.add(parameters); } final ConfirmationModel confirmationModel = (ConfirmationModel) getWindow(); confirmationModel.startProgress(); Frontend.getInstance().runMultipleAction(ActionType.DeactivateStorageDomainWithOvfUpdate, list, result -> { confirmationModel.stopProgress(); setWindow(null); }, null); }
Source:
public static List<VMImage> getImages(String containerName, String group, String storageAccountName, String key, String offer, String location) { final AzureBlobClient azureBlob = ContextBuilder.newBuilder("azureblob") .credentials(storageAccountName, key) .buildApi(AzureBlobClient.class); List<VMImage> list = new ArrayList<VMImage>(); try { BoundedSet<ContainerProperties> containerList = azureBlob.listContainers(); for (ContainerProperties props : containerList) { if (props.getName().equals("system")) { ListBlobsResponse blobList = azureBlob.listBlobs("system"); String osDisk = ""; String dataDisk = ""; for (BlobProperties blob : blobList) { System.out.println(blob.getName()); String name = blob.getName(); if (dataDisk.length() == 0) dataDisk = name.substring(1 + name.lastIndexOf('/')); else if (osDisk.length() == 0) osDisk = name.substring(1 + name.lastIndexOf('/')); } final VMImage ref = VMImage.create(group, storageAccountName, osDisk, dataDisk, "test-create-image", "custom", location); list.add(ref); } } } catch (Exception e) { e.printStackTrace(); } try { azureBlob.close(); } catch (IOException e) { e.printStackTrace(); } return list; }

Target:
public static List<VMImage> getImages(String containerName, String group, String storageAccountName, String key, String offer, String location) { final AzureBlobClient azureBlob = ContextBuilder.newBuilder("azureblob") .credentials(storageAccountName, key) .buildApi(AzureBlobClient.class); List<VMImage> list = new ArrayList<VMImage>(); try { BoundedSet<ContainerProperties> containerList = azureBlob.listContainers(); for (ContainerProperties props : containerList) { if (props.getName().equals("system")) { ListBlobsResponse blobList = azureBlob.listBlobs("system"); String osDisk = ""; String dataDisk = ""; for (BlobProperties blob : blobList) { String name = blob.getName(); if (dataDisk.length() == 0) dataDisk = name.substring(1 + name.lastIndexOf('/')); else if (osDisk.length() == 0) osDisk = name.substring(1 + name.lastIndexOf('/')); } final VMImage ref = VMImage.create(group, storageAccountName, osDisk, dataDisk, "test-create-image", "custom", location); list.add(ref); } } } finally { Closeables2.closeQuietly(azureBlob); } return list; }
Source:
protected void onHandleIntent(Intent intent) { PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NotificationsIntent"); try { wl.acquire(); Log.d("Notifications", "Running Notifications Intent Service"); Context context =getApplicationContext(); ReadPerfs(context); notificationSetter(context); ArmTimer(context); context.startService(new Intent(context, MissedReadingService.class)); } finally { if (wl.isHeld()) wl.release(); } }

Target:
protected void onHandleIntent(Intent intent) { PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NotificationsIntent"); wl.acquire(); try { Log.d("Notifications", "Running Notifications Intent Service"); Context context =getApplicationContext(); ReadPerfs(context); notificationSetter(context); ArmTimer(context); context.startService(new Intent(context, MissedReadingService.class)); } finally { if (wl.isHeld()) wl.release(); } }
Source:
public static JobStatus findPriority(String name) { if (name.equalsIgnoreCase(PENDING.toString())) { return PENDING; } if (name.equalsIgnoreCase(RUNNING.toString())) { return RUNNING; } if (name.equalsIgnoreCase(STALLED.toString())) { return STALLED; } if (name.equalsIgnoreCase(FINISHED.toString())) { return FINISHED; } if (name.equalsIgnoreCase(PAUSED.toString())) { return PAUSED; } if (name.equalsIgnoreCase(CANCELED.toString())) { return CANCELED; } if (name.equalsIgnoreCase(FAILED.toString())) { return FAILED; } return KILLED; }

Target:
public static JobStatus findPriority(String name) { for (JobStatus jobStatus : JobStatus.values()) { if (name.equalsIgnoreCase(jobStatus.toString())) return jobStatus; } return KILLED; }
Source:
public void execute(List<Tuple> tuples, OutputCollector collector) { System.out.println("---- store "+tuples.size() ); if ( !initialized ) { if( !config.isCounterBolt() ) { dao.init(); dao.setConfig(config); dao.analyzeTuple( tuples.get(0) ); dao.createDataStructures(); } else { ctn.setConfig( config ); ctn.connect( config.getIP() ); ctn.createDataStructures(); keyFields = new Fields(config.getPrimaryKeys().getPrimaryKeyFields()); } initialized = true; } try{ if( !config.isCounterBolt() ) { for( Tuple t : tuples ){ System.out.println("debug: store "+t); } dao.store( tuples ); } else { for( Tuple t : tuples ){ List<Object> keyValues = t.select( keyFields ); List<Object> val = t.select(config.getTupleFields()); System.out.println("debug: store "+t); ctn.update( keyValues, (int)val.get(0) ); } } } catch (Exception e ){ System.err.print("ERROR: "+e); e.printStackTrace(); } for( Tuple p : tuples ){ collector.emit(p.getValues()); } }

Target:
public void execute(List<Tuple> tuples, OutputCollector collector) { System.out.println("debug: store "+tuples.size() ); if ( !initialized ) { if( !config.isCounterBolt() ) { dao.init(); dao.setConfig(config); dao.analyzeTuple( tuples.get(0) ); dao.createDataStructures(); } else { ctn.connect( config.getIP() ); ctn.createDataStructures(); keyFields = new Fields(config.getPrimaryKeys().getPrimaryKeyFields()); } initialized = true; } try{ if( !config.isCounterBolt() ) { for( Tuple t : tuples ){ System.out.println("debug: store "+t); } dao.store( tuples ); } else { for( Tuple t : tuples ){ List<Object> keyValues = t.select( keyFields ); List<Object> val = t.select(config.getTupleFields()); System.out.println("debug: store "+t); ctn.update( keyValues, (int)val.get(0) ); } } } catch (Exception e ){ System.err.print("ERROR: "+e); e.printStackTrace(); } for( Tuple p : tuples ){ collector.emit(p.getValues()); } }
Source:
public void testCapture404() throws Exception { server.enqueue(response404()); final VirtualMachineApi vmAPI = api.getVirtualMachineApi("groupname"); URI uri = vmAPI.capture("vm", "prefix", "container"); assertNull(uri); assertSent(server, "POST", "/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute" + "/virtualMachines/vm/capture?api-version=2015-06-15"); }

Target:
public void testCapture404() throws Exception { server.enqueue(response404()); final VirtualMachineApi vmAPI = api.getVirtualMachineApi("groupname"); URI uri = vmAPI.capture("vm", "prefix", "container"); assertNull(uri); assertSent(server, "POST", "/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute" + "/virtualMachines/vm/capture?api-version=2015-06-15", "{\"vhdPrefix\":\"prefix\",\"destinationContainerName\":\"container\"}"); }
Source:
public static boolean checkAclRight(List<OzoneAclInfo> acls, RequestContext context) throws OMException { String[] userGroups = context.getClientUgi().getGroupNames(); for (OzoneAclInfo a : acls) { BitSet rights = BitSet.valueOf(a.getRights().toByteArray()); switch (a.getType()) { case USER: if (a.getName().equals(context.getClientUgi().getUserName())) { return ((rights.get(context.getAclRights().ordinal()) || rights.get(ALL.ordinal())) && !rights.get(NONE.ordinal())); } break; case GROUP: for (String grp : userGroups) { if (a.getName().equals(grp)) { return ((rights.get(context.getAclRights().ordinal()) || rights.get(ALL.ordinal())) && !rights.get(NONE.ordinal())); } } break; default: throw new OMException("Unexpected type:" + a.getType(), INTERNAL_ERROR); } } return false; }

Target:
public static boolean checkAclRight(List<OzoneAclInfo> acls, RequestContext context) throws OMException { String[] userGroups = context.getClientUgi().getGroupNames(); String userName = context.getClientUgi().getUserName(); ACLType aclToCheck = context.getAclRights(); for (OzoneAclInfo a : acls) { if(checkAccessInAcl(a, userGroups, userName, aclToCheck)) { return true; } } return false; }
Source:
public void waitForCopyEmailPopoverVisible() { String selector = "#copy-email-button + div.popover"; waitForElementPresence(By.cssSelector(selector)); }

Target:
public void waitForCopyEmailPopoverVisible() { String cssSelector = "#copy-email-button + div.popover"; WebElement copyEmailPopover = browser.driver.findElement(By.cssSelector(cssSelector)); waitForElementVisibility(copyEmailPopover); }
Source:
public Object aggregateArguments(ArgumentsAccessor accessor, ParameterContext context) { Map<String, Object> m = new HashMap<>(); IntStream.range(0, accessor.size()).forEach(i -> m.put(Integer.toString(i), accessor.get(i))); return m; }

Target:
public Object aggregateArguments(ArgumentsAccessor accessor, ParameterContext context) { return IntStream .range(0, accessor.size()) .boxed() .collect( toMap( i -> Integer.toString(i), i -> accessor.get(i) ) ); }
Source:
public Set<CoLocationGroupDesc> getCoLocationGroupDescriptors() { final Set<CoLocationGroup> coLocationGroups = new HashSet<>(); for (JobVertex vertex : getVertices()) { CoLocationGroup coLocationGroup = vertex.getCoLocationGroup(); if (coLocationGroup != null) { coLocationGroups.add(coLocationGroup); } } final Set<CoLocationGroupDesc> coLocationGroupDescs = coLocationGroups .stream() .map(CoLocationGroupDesc::from) .collect(Collectors.toSet()); return Collections.unmodifiableSet(coLocationGroupDescs); }

Target:
public Set<CoLocationGroupDesc> getCoLocationGroupDescriptors() { final Set<CoLocationGroupDesc> coLocationGroups = IterableUtils .toStream(getVertices()) .map(JobVertex::getCoLocationGroup) .filter(Objects::nonNull) .distinct() .map(CoLocationGroupDesc::from) .collect(Collectors.toSet()); return Collections.unmodifiableSet(coLocationGroups); }
Source:
private void createVehicleList() { List<Vehicle> vehicleList = new ArrayList<>(vehicleListSize); long id = 0; for (int i = 0; i < vehicleListSize; i++) { Vehicle vehicle = new Vehicle(); vehicle.setId(id); id++; vehicle.setCapacity(capacity); if(depotList.size() == vehicleListSize){ vehicle.setDepot(depotList.get(i)); } else { vehicle.setDepot(depotList.get(0)); } vehicle.setDepot(depotList.get(0)); vehicleList.add(vehicle); } solution.setVehicleList(vehicleList); }

Target:
private void createVehicleList() { List<Vehicle> vehicleList = new ArrayList<>(vehicleListSize); long id = 0; for (int i = 0; i < vehicleListSize; i++) { Vehicle vehicle = new Vehicle(); vehicle.setId(id); id++; vehicle.setCapacity(capacity); depotList.get(i % depotList.size()); vehicle.setDepot(depotList.get(0)); vehicleList.add(vehicle); } solution.setVehicleList(vehicleList); }
Source:
public static IPath getXmlFilesPath() { IPath path = Activator.getDefault().getStateLocation(); path = path.addTrailingSeparator().append(XML_DIRECTORY); File dir = path.toFile(); if (!dir.exists()) { dir.mkdirs(); } return path; }

Target:
public static IPath getXmlFilesPath() { IPath path = Activator.getDefault().getStateLocation(); path = path.addTrailingSeparator().append(XML_DIRECTORY); File dir = path.toFile(); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } return path; }
Source:
public void testTaskRestoreStateIsNulledAfterDeployment() throws Exception { final JobVertex jobVertex = createNoOpJobVertex(); final JobVertexID jobVertexId = jobVertex.getID(); final SingleSlotTestingSlotOwner slotOwner = new SingleSlotTestingSlotOwner(); final ProgrammedSlotProvider slotProvider = createProgrammedSlotProvider( 1, Collections.singleton(jobVertexId), slotOwner); final SchedulerBase scheduler = SchedulerTestingUtils .newSchedulerBuilderWithDefaultSlotAllocator(new JobGraph(jobVertex), slotProvider) .build(); scheduler.start(ComponentMainThreadExecutorServiceAdapter.forMainThread()); ExecutionJobVertex executionJobVertex = scheduler.getExecutionJobVertex(jobVertexId); ExecutionVertex executionVertex = executionJobVertex.getTaskVertices()[0]; final Execution execution = executionVertex.getCurrentExecutionAttempt(); final JobManagerTaskRestore taskRestoreState = new JobManagerTaskRestore(1L, new TaskStateSnapshot()); execution.setInitialState(taskRestoreState); assertThat(execution.getTaskRestore(), is(notNullValue())); scheduler.startScheduling(); assertThat(execution.getTaskRestore(), is(nullValue())); }

Target:
public void testTaskRestoreStateIsNulledAfterDeployment() throws Exception { final JobVertex jobVertex = createNoOpJobVertex(); final JobVertexID jobVertexId = jobVertex.getID(); final SingleSlotTestingSlotOwner slotOwner = new SingleSlotTestingSlotOwner(); final ProgrammedSlotProvider slotProvider = createProgrammedSlotProvider( 1, Collections.singleton(jobVertexId), slotOwner); final SchedulerBase scheduler = SchedulerTestingUtils .newSchedulerBuilderWithDefaultSlotAllocator(new JobGraph(jobVertex), slotProvider) .build(); scheduler.initialize(ComponentMainThreadExecutorServiceAdapter.forMainThread()); ExecutionJobVertex executionJobVertex = scheduler.getExecutionJobVertex(jobVertexId); ExecutionVertex executionVertex = executionJobVertex.getTaskVertices()[0]; final Execution execution = executionVertex.getCurrentExecutionAttempt(); final JobManagerTaskRestore taskRestoreState = new JobManagerTaskRestore(1L, new TaskStateSnapshot()); execution.setInitialState(taskRestoreState); assertThat(execution.getTaskRestore(), is(notNullValue())); scheduler.startScheduling(); assertThat(execution.getTaskRestore(), is(nullValue())); }
Source:
public void firstBatchHasNoValidation() { Runnable validationStep = mock(Runnable.class); Set<Cell> puts = putColumns(BATCH_SIZE + 5); int limit = BATCH_SIZE - 1; Iterator<Map.Entry<Cell, byte[]>> iteratorUnderTest = createIteratorUnderTest(validationStep); List<Map.Entry<Cell, byte[]>> firstBatchBarOne = ImmutableList.copyOf(Iterators.limit(iteratorUnderTest, limit)); verifyNoInteractions(validationStep); Map.Entry<Cell, byte[]> lastInFirstBatch = Iterators.getNext(iteratorUnderTest, null); assertThat(lastInFirstBatch).isNotNull(); verifyNoInteractions(validationStep); Map.Entry<Cell, byte[]> firstInSecondBatch = Iterators.getNext(iteratorUnderTest, null); assertThat(firstInSecondBatch).isNotNull(); verify(validationStep, times(1)).run(); ImmutableList<Map.Entry<Cell, byte[]>> restOfSecondBatch = ImmutableList.copyOf(iteratorUnderTest); verifyNoMoreInteractions(validationStep); Map<Cell, byte[]> returnedEntries = ImmutableMap.<Cell, byte[]>builder() .putAll(firstBatchBarOne) .put(lastInFirstBatch) .put(firstInSecondBatch) .putAll(restOfSecondBatch) .build(); assertThat(returnedEntries.keySet()) .as("we can read all that we wrote") .isEqualTo(puts); }

Target:
public void firstBatchHasNoValidation() { Runnable validationStep = mock(Runnable.class); Set<Cell> puts = putColumns(BATCH_SIZE + 5); int limit = BATCH_SIZE - 1; Iterator<Map.Entry<Cell, byte[]>> iteratorUnderTest = createIteratorUnderTest(validationStep); List<Map.Entry<Cell, byte[]>> firstBatchBarOne = ImmutableList.copyOf(Iterators.limit(iteratorUnderTest, limit)); verifyNoInteractions(validationStep); Map.Entry<Cell, byte[]> lastInFirstBatch = Iterators.getNext(iteratorUnderTest, null); assertThat(lastInFirstBatch).isNotNull(); verifyNoInteractions(validationStep); Map.Entry<Cell, byte[]> firstInSecondBatch = Iterators.getNext(iteratorUnderTest, null); assertThat(firstInSecondBatch).isNotNull(); verify(validationStep, times(1)).run(); ImmutableList<Map.Entry<Cell, byte[]>> restOfSecondBatch = ImmutableList.copyOf(iteratorUnderTest); verifyNoMoreInteractions(validationStep); List<Cell> cellsReadInOrder = Streams.stream(Iterables.concat( firstBatchBarOne, ImmutableList.of(lastInFirstBatch, firstInSecondBatch), restOfSecondBatch)) .map(Map.Entry::getKey) .collect(Collectors.toList()); assertThat(cellsReadInOrder) .as("we can read all that we wrote") .hasSameElementsAs(puts) .as("iterator returns cells back in sorted order") .isSorted(); }
Source:
public Collection<IAnyResource> findCandidates(String theResourceType, IAnyResource theResource) { Map<Long, IAnyResource> matchedPidsToResources = new HashMap<>(); List<EmpiFilterSearchParamJson> filterSearchParams = myEmpiConfig.getEmpiRules().getCandidateFilterSearchParams(); List<String> filterCriteria = buildFilterQuery(filterSearchParams, theResourceType); List<EmpiResourceSearchParamJson> candidateSearchParams = myEmpiConfig.getEmpiRules().getCandidateSearchParams(); if (candidateSearchParams == null || candidateSearchParams.isEmpty()) { searchForIdsAndAddToMap(theResourceType, theResource, matchedPidsToResources, filterCriteria, null); } else { for (EmpiResourceSearchParamJson resourceSearchParam : candidateSearchParams) { if (!isSearchParamForResource(theResourceType, resourceSearchParam)) { continue; } searchForIdsAndAddToMap(theResourceType, theResource, matchedPidsToResources, filterCriteria, resourceSearchParam); } } if (theResource.getIdElement().getIdPart() != null) { matchedPidsToResources.remove(myIdHelperService.getPidOrNull(theResource)); } return matchedPidsToResources.values(); }

Target:
public Collection<IAnyResource> findCandidates(String theResourceType, IAnyResource theResource) { Map<Long, IAnyResource> matchedPidsToResources = new HashMap<>(); List<EmpiFilterSearchParamJson> filterSearchParams = myEmpiConfig.getEmpiRules().getCandidateFilterSearchParams(); List<String> filterCriteria = buildFilterQuery(filterSearchParams, theResourceType); List<EmpiResourceSearchParamJson> candidateSearchParams = myEmpiConfig.getEmpiRules().getCandidateSearchParams(); if (candidateSearchParams.isEmpty()) { searchForIdsAndAddToMap(theResourceType, theResource, matchedPidsToResources, filterCriteria, null); } else { for (EmpiResourceSearchParamJson resourceSearchParam : candidateSearchParams) { if (!isSearchParamForResource(theResourceType, resourceSearchParam)) { continue; } searchForIdsAndAddToMap(theResourceType, theResource, matchedPidsToResources, filterCriteria, resourceSearchParam); } } if (theResource.getIdElement().getIdPart() != null) { matchedPidsToResources.remove(myIdHelperService.getPidOrNull(theResource)); } return matchedPidsToResources.values(); }