auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected InputStream createFileInputStream(Path path) throws FileNotFoundException, IOException { final java.nio.file.Path nioPath = createJavaNioPath(path); InputStream stream = null; try { stream = Files.newInputStream(nioPath, java.nio.file.StandardOpenOption.READ); } catch (AccessDeniedException e) { throw new IOException(e.getMessage() + " (Permission denied)", e); } byte[] buf = new byte[1]; int buflen = 0; try { buflen = stream.read(buf, 0, 1); } catch (IOException e) { if (e.getMessage().equals("Is a directory")) { throw new IOException(path.toString() + " (Is a directory)", e); } throw e; } if (buflen == -1 ) { return stream; } return new SequenceInputStream(new ByteArrayInputStream(buf, 0, buflen), stream); }

Target:
protected InputStream createFileInputStream(Path path) throws FileNotFoundException, IOException { return new FileInputStream(createJavaIoFile(path)); }
Source:
public static void main(String[] args) { String endpoint = args[0]; String username = args[1]; String password = args[2]; ContextBuilder contextBuilder = ContextBuilder.newBuilder(DIMENSIONDATA_CLOUDCONTROL_PROVIDER); DimensionDataCloudControlApi api = contextBuilder .endpoint(endpoint) .credentials(username, password) .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule())) .buildApi(DimensionDataCloudControlApi.class); Injector injector = contextBuilder.buildInjector(); final String networkDomainName = "jclouds-example"; String networkDomainId = getNetworkDomainId(api, networkDomainName); final String serverName = "jclouds-server"; final String vlanName = "jclouds-example-vlan"; deleteServer(api, injector, serverName); deleteVlan(api, injector, vlanName, networkDomainId); deleteNetworkDomain(api, injector, networkDomainId); deleteTagKey(api, "jclouds"); }

Target:
public static void main(String[] args) { String endpoint = args[0]; String username = args[1]; String password = args[2]; try (ApiContext<DimensionDataCloudControlApi> ctx = ContextBuilder.newBuilder(DIMENSIONDATA_CLOUDCONTROL_PROVIDER) .endpoint(endpoint) .credentials(username, password) .modules(ImmutableSet.of(new SLF4JLoggingModule())) .build()) { Injector injector = ctx.utils().injector(); DimensionDataCloudControlApi api = ctx.getApi(); final String networkDomainName = "jclouds-example"; String networkDomainId = getNetworkDomainId(api, networkDomainName); final String serverName = "jclouds-server"; final String vlanName = "jclouds-example-vlan"; deleteServer(api, injector, serverName); deleteVlan(api, injector, vlanName, networkDomainId); deleteNetworkDomain(api, injector, networkDomainId); deleteTagKey(api, "jclouds"); } }
Source:
private static List<Object> removeIndirection(List<Object> justificationList) { final List<Object> l = justificationList.stream() .flatMap(item -> { if (item instanceof LogicalTuple) { return removeIndirection((LogicalTuple) item).stream(); } else { return Stream.of(item); } }).collect(Collectors.toList()); return l; }

Target:
private static List<Object> removeIndirection(List<Object> justificationList) { return justificationList.stream() .flatMap(item -> { if (item instanceof DroolsLogicalTuple) { return removeIndirection((DroolsLogicalTuple) item).stream(); } else { return Stream.of(item); } }).collect(Collectors.toList()); }
Source:
private File folderWhiteListBin(File folder) { String[] children = folder.list(); children = (children == null ? new String[0] : children); for( int i = 0; i < children.length; i++ ) { Matcher m = WHITELIST_PATTERN.matcher(children[i]); if( m.matches()) { return new File(folder, children[i]); } } return null; }

Target:
private File folderWhiteListBin(File folder) { String[] children = folder.list(); if( children == null ) return null; for( int i = 0; i < children.length; i++ ) { Matcher m = WHITELIST_PATTERN.matcher(children[i]); if( m.matches()) { return new File(folder, children[i]); } } return null; }
Source:
private void copyUploadDirectoryToAgents() throws IOException { log.info("WORKING DIRECTORY:" + WORKING_DIRECTORY); if (!UPLOAD_DIRECTORY.exists()) { log.debug("Skipping upload, since no upload file in working directory"); return; } log.info("UPLOAD DIRECTORY:" + UPLOAD_HOME); List<File> files = Utils.getFilesFromClassPath(UPLOAD_HOME); for (String ip : agentsClient.getPublicAddresses()){ for (File file : files){ String syncCommand = format("rsync -avv -e \"ssh %s\" %s %s@%s:hazelcast-stabilizer-%s/workers/%s/", props.get("SSH_OPTIONS", ""), file , props.get("USER"), ip, getVersion(), testSuite.id); bash.execute(syncCommand); } log.info(" " + ip + " copied"); } log.info(format("Finished copying '+%s+' to agents", UPLOAD_HOME)); }

Target:
private void copyUploadDirectoryToAgents() throws IOException { if (!UPLOAD_DIRECTORY.exists()) { log.debug("Skipping upload, since no upload file in working directory"); return; } log.info(format("Starting uploading '+%s+' to agents", UPLOAD_DIRECTORY.getAbsolutePath())); List<File> files = Utils.getFilesFromClassPath(UPLOAD_DIRECTORY.getAbsolutePath()); for (String ip : agentsClient.getPublicAddresses()){ log.info(format(" Uploading '+%s+' to agent %s", UPLOAD_DIRECTORY.getAbsolutePath(), ip)); for (File file : files){ String syncCommand = format("rsync -avv -e \"ssh %s\" %s %s@%s:hazelcast-stabilizer-%s/workers/%s/", props.get("SSH_OPTIONS", ""), file , props.get("USER"), ip, getVersion(), testSuite.id); bash.execute(syncCommand); } log.info(" " + ip + " copied"); } log.info(format("Finished uploading '+%s+' to agents", UPLOAD_DIRECTORY.getAbsolutePath())); }
Source:
private Callback setProducerCallback() { return new Callback() { @Override public void onCompletion(RecordMetadata recordMetadata, Exception e) { if(e != null) { if(recordMetadata.topic().equals(config.getMetricTopic())) { metricLost.incrementAndGet(); } else if (recordMetadata.topic().equals(config.getAlertTopic())) { alertLost.incrementAndGet(); } else { invalidLost.incrementAndGet(); } } } }; }

Target:
private Callback setProducerCallback() { return (recordMetadata, e) -> { if (e != null) { log.debug("Event send failed [%s]", e.getMessage()); if (recordMetadata.topic().equals(config.getMetricTopic())) { metricLost.incrementAndGet(); } else if (recordMetadata.topic().equals(config.getAlertTopic())) { alertLost.incrementAndGet(); } else { invalidLost.incrementAndGet(); } } }; }
Source:
public ZkRoutingDataWriter(String namespace, String zkAddress) { if (namespace == null || namespace.isEmpty()) { throw new IllegalArgumentException("namespace cannot be null or empty!"); } _namespace = namespace; if (zkAddress == null || zkAddress.isEmpty()) { throw new IllegalArgumentException("Zk address cannot be null or empty!"); } _zkAddress = zkAddress; _zkClient = DedicatedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer())); try { _zkClient.createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH); } catch (ZkNodeExistsException e) { } ZNRecord myServerInfo = new ZNRecord("dummy hostname"); _leaderElection = new ZkDistributedLeaderElection(_zkClient, MetadataStoreRoutingConstants.LEADER_ELECTION_ZNODE, myServerInfo); }

Target:
public ZkRoutingDataWriter(String namespace, String zkAddress) { if (namespace == null || namespace.isEmpty()) { throw new IllegalArgumentException("namespace cannot be null or empty!"); } _namespace = namespace; if (zkAddress == null || zkAddress.isEmpty()) { throw new IllegalArgumentException("Zk address cannot be null or empty!"); } _zkClient = DedicatedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer())); try { _zkClient.createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, true); } catch (ZkNodeExistsException e) { } ZNRecord myServerInfo = new ZNRecord("dummy hostname"); _leaderElection = new ZkDistributedLeaderElection(_zkClient, MetadataStoreRoutingConstants.LEADER_ELECTION_ZNODE, myServerInfo); }
Source:
public void loadImage(String image, String filepath) throws DockerAccessException { ImageName name = new ImageName(image); String url = urlBuilder.loadImage(); try { delegate.post(url, new File(filepath), new BodyAndStatusResponseHandler(), HTTP_OK); } catch (IOException e) { throw new DockerAccessException(e, "Unable to load %s", filepath); } }

Target:
public void loadImage(String image, String filepath) throws DockerAccessException { String url = urlBuilder.loadImage(); try { delegate.post(url, new File(filepath), new BodyAndStatusResponseHandler(), HTTP_OK); } catch (IOException e) { throw new DockerAccessException(e, "Unable to load %s", filepath); } }
Source:
private boolean isValidCardio2eDateTime (String dateTime) { boolean isValid = false; int dateTimeIntArray = cardio2eDateTimeToInt (dateTime); int year, month, day, hour, minute; Calendar myCalendar; year = dateTimeIntArray [0]; month = dateTimeIntArray [1]; day = dateTimeIntArray [2]; hour = dateTimeIntArray [3]; minute = dateTimeIntArray [4]; if ((year >= CARDIO2E_DATE_MIN_YEAR) && (year <= CARDIO2E_DATE_MAX_YEAR) && (month >=1) && (month <=12) && (day >=1) && (day <=31) && (hour >=0) && (hour <=23) && (minute >=0) && (minute <=59)){ try { myCalendar = new GregorianCalendar (year, (month-1), 1); if (day <= myCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)){ isValid = true; } } catch (Exception e) { e.printStackTrace(); } } return isValid; }

Target:
private boolean isValidCardio2eDateTime(String dateTime) { boolean isValid = false; int dateTimeIntArray[] = cardio2eDateTimeToInt(dateTime); int year, month, day, hour, minute; Calendar myCalendar; year = dateTimeIntArray[0]; month = dateTimeIntArray[1]; day = dateTimeIntArray[2]; hour = dateTimeIntArray[3]; minute = dateTimeIntArray[4]; if ((year >= CARDIO2E_DATE_MIN_YEAR) && (year <= CARDIO2E_DATE_MAX_YEAR) && (month >= 1) && (month <= 12) && (day >= 1) && (day <= 31) && (hour >= 0) && (hour <= 23) && (minute >= 0) && (minute <= 59)) { try { myCalendar = new GregorianCalendar(year, (month - 1), 1); if (day <= myCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)) { isValid = true; } } catch (Exception ex) { isValid = false; } } return isValid; }
Source:
public void setProperty(Object instance, String propertyName, Object value) throws ConversionException { try { DelegatingResourceHandler<? extends T> handler; try { handler = getResourceHandler((T) instance); } catch (Exception e) { handler = this; } Method annotatedSetter = findSetterMethod(handler, propertyName); if (annotatedSetter != null) { Type expectedType = annotatedSetter.getGenericParameterTypes()[1]; value = ConversionUtil.convert(value, expectedType); annotatedSetter.invoke(handler, instance, value); return; } String override = remappedProperties.get(propertyName); if (override != null) propertyName = override; Method setter = PropertyUtils.getPropertyDescriptor(instance, propertyName).getWriteMethod(); Type setterType = setter.getGenericParameterTypes()[0]; if (setterType instanceof TypeVariable<?>) { setterType = ConversionUtil.getTypeVariableClass(instance, (TypeVariable<?>) setterType); } value = ConversionUtil.convert(value, setterType); if (value instanceof Collection) { Collection<?> newCollection = (Collection<?>) value; Object oldValue = PropertyUtils.getProperty(instance, propertyName); if (oldValue instanceof Collection) { Collection collection = (Collection) oldValue; collection.clear(); collection.addAll(newCollection); } else { PropertyUtils.setProperty(instance, propertyName, value); } } else { PropertyUtils.setProperty(instance, propertyName, value); } } catch (Exception ex) { throw new ConversionException(propertyName + " on " + instance.getClass(), ex); } }

Target:
public void setProperty(Object instance, String propertyName, Object value) throws ConversionException { try { DelegatingResourceHandler<? extends T> handler; try { handler = getResourceHandler((T) instance); } catch (Exception e) { handler = this; } Method annotatedSetter = findSetterMethod(handler, propertyName); if (annotatedSetter != null) { Type expectedType = annotatedSetter.getGenericParameterTypes()[1]; value = ConversionUtil.convert(value, expectedType); annotatedSetter.invoke(handler, instance, value); return; } String override = remappedProperties.get(propertyName); if (override != null) propertyName = override; Method setter = PropertyUtils.getPropertyDescriptor(instance, propertyName).getWriteMethod(); value = ConversionUtil.convert(value, setter.getGenericParameterTypes()[0], instance); if (value instanceof Collection) { Collection<?> newCollection = (Collection<?>) value; Object oldValue = PropertyUtils.getProperty(instance, propertyName); if (oldValue instanceof Collection) { Collection collection = (Collection) oldValue; collection.clear(); collection.addAll(newCollection); } else { PropertyUtils.setProperty(instance, propertyName, value); } } else { PropertyUtils.setProperty(instance, propertyName, value); } } catch (Exception ex) { throw new ConversionException(propertyName + " on " + instance.getClass(), ex); } }
Source:
private Optional<APIProductIdentifier> getProductIdIfExists(ResultSet rs) throws SQLException { String productProvider = rs.getString("API_TYPE"); if (rs.wasNull() || StringUtils.isEmpty(productProvider)) { return Optional.empty(); } String productName = rs.getString("API_NAME"); String productVersion = rs.getString("API_VERSION"); APIProductIdentifier productIdentifier = new APIProductIdentifier (productProvider, productName, productVersion); return Optional.of(productIdentifier); }

Target:
private Optional<APIProductIdentifier> getProductIdIfExists(ResultSet rs) throws SQLException { String type = rs.getString("API_TYPE"); if (rs.wasNull() || StringUtils.isEmpty(type)) { return Optional.empty(); } String productName = rs.getString("API_NAME"); String productVersion = rs.getString("API_VERSION"); String productProvider = rs.getString("API_PROVIDER"); APIProductIdentifier productIdentifier = new APIProductIdentifier (productProvider, productName, productVersion); return Optional.of(productIdentifier); }
Source:
public void findFirstAsync_emittedOnSubscribe() { realm.beginTransaction(); realm.createObject(AllTypes.class).setColumnLong(42); realm.commitTransaction(); final AllTypes asyncObj = realm.where(AllTypes.class).findFirstAsync(); subscription = asyncObj.<AllTypes>asFlowable().subscribe(rxObject -> { assertTrue(rxObject.isFrozen()); assertFalse(rxObject.isValid()); if (rxObject.isLoaded()) { assertTrue(rxObject.isValid()); assertEquals(42, rxObject.getColumnLong()); } else { assertFalse(rxObject.isValid()); } disposeSuccessfulTest(realm); }); }

Target:
public void findFirstAsync_emittedOnSubscribe() { realm.beginTransaction(); realm.createObject(AllTypes.class).setColumnLong(42); realm.commitTransaction(); final AllTypes asyncObj = realm.where(AllTypes.class).findFirstAsync(); subscription = asyncObj.<AllTypes>asFlowable().subscribe(rxObject -> { assertTrue(rxObject.isFrozen()); if (rxObject.isLoaded()) { assertTrue(rxObject.isValid()); assertEquals(42, rxObject.getColumnLong()); } else { assertFalse(rxObject.isValid()); } disposeSuccessfulTest(realm); }); }
Source:
public void initialize(AdvancedCache<?, ?> cache) { if (searchQuery == null) { QueryEngine<?> queryEngine = getQueryEngine(cache); searchQuery = queryEngine.buildSearchQuery(queryString, namedParameters); } }

Target:
public void initialize(AdvancedCache<?, ?> cache) { if (searchQuery == null) { QueryEngine<?> queryEngine = getQueryEngine(cache); searchQuery = queryEngine.buildSearchQuery(queryString, namedParameters); if (timeout > 0) { searchQuery.failAfter(timeout, TimeUnit.NANOSECONDS); } } }
Source:
public void testGetAttributeAsDoubleList() { final VariantContext context = basicBuilder .attribute("DefaultIntegerList", new int[5]) .attribute("ListWithMissing", new Object[]{1, null, null}) .attribute("IntegerList", new int[]{0, 1, 2, 3}) .attribute("DoubleList", new double[]{1.8, 1.6, 2.1}) .attribute("StringList", new String[]{"1", "2"}) .attribute("NotNumeric", new String[]{"A", "B"}) .make(); Assert.assertEquals(context.getAttributeAsDoubleList("DefaultIntegerList", 5), Arrays.asList(0d, 0d, 0d, 0d, 0d)); Assert.assertEquals(context.getAttributeAsDoubleList("ListWithMissing", 5), Arrays.asList(1d, 5d, 5d)); Assert.assertEquals(context.getAttributeAsDoubleList("IntegerList", 5), Arrays.asList(0d, 1d, 2d, 3d)); Assert.assertEquals(context.getAttributeAsDoubleList("DoubleList", 5), Arrays.asList(1.8, 1.6, 2.1)); Assert.assertEquals(context.getAttributeAsDoubleList("StringList", 5), Arrays.asList(1d, 2d)); try { context.getAttributeAsIntList("NotNumeric", 5); Assert.fail(); } catch (Exception e) { } }

Target:
public void testGetAttributeAsDoubleList() { final VariantContext context = basicBuilder .attribute("Empty", new int[0]) .attribute("DefaultIntegerList", new int[5]) .attribute("ListWithMissing", new Object[]{1, null, null}) .attribute("IntegerList", new int[]{0, 1, 2, 3}) .attribute("DoubleList", new double[]{1.8, 1.6, 2.1}) .attribute("StringList", new String[]{"1", "2"}) .attribute("NotNumeric", new String[]{"A", "B"}) .make(); Assert.assertTrue(context.getAttributeAsDoubleList("Empty", 5).isEmpty()); Assert.assertEquals(context.getAttributeAsDoubleList("DefaultIntegerList", 5), Arrays.asList(0d, 0d, 0d, 0d, 0d)); Assert.assertEquals(context.getAttributeAsDoubleList("ListWithMissing", 5), Arrays.asList(1d, 5d, 5d)); Assert.assertEquals(context.getAttributeAsDoubleList("IntegerList", 5), Arrays.asList(0d, 1d, 2d, 3d)); Assert.assertEquals(context.getAttributeAsDoubleList("DoubleList", 5), Arrays.asList(1.8, 1.6, 2.1)); Assert.assertEquals(context.getAttributeAsDoubleList("StringList", 5), Arrays.asList(1d, 2d)); Assert.assertThrows(() -> context.getAttributeAsDoubleList("NotNumeric", 5)); Assert.assertTrue(context.getAttributeAsDoubleList("MissingList", 5).isEmpty()); }
Source:
public AWSRequestSignerV4(String identity, String credential, Crypto crypto) { this.crypto = crypto; this.identity = identity; this.credential = credential; }

Target:
public AWSRequestSignerV4(String identity, String credential, Crypto crypto) { this.crypto = checkNotNull(crypto); this.identity = checkNotNull(identity); this.credential = checkNotNull(credential); }
Source:
public void testProtectedEndpointBadCredentials401() { try { RULE.getJerseyTest().target("/protected").request() .header(HttpHeaders.AUTHORIZATION, "Basic c25lYWt5LWJhc3RhcmQ6YXNkZg==") .get(String.class); failBecauseExceptionWasNotThrown(WebApplicationException.class); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatus()).isEqualTo(401); assertThat(e.getResponse().getHeaders().get(HttpHeaders.WWW_AUTHENTICATE)) .containsOnly("Basic realm=\"SUPER SECRET STUFF\""); } }

Target:
public void testProtectedEndpointBadCredentials401() { try { RULE.getJerseyTest().target("/protected").request() .header(HttpHeaders.AUTHORIZATION, "Basic c25lYWt5LWJhc3RhcmQ6YXNkZg==") .get(String.class); failBecauseExceptionWasNotThrown(NotAuthorizedException.class); } catch (NotAuthorizedException e) { assertThat(e.getResponse().getStatus()).isEqualTo(401); assertThat(e.getResponse().getHeaders().get(HttpHeaders.WWW_AUTHENTICATE)) .containsOnly("Basic realm=\"SUPER SECRET STUFF\""); } }
Source:
public static <T extends CoveragePoNNormalizationResult> List<String> retrieveSamplesWithArmLevelEvents(final CoveragePanelOfNormals<T> qcPoN, final JavaSparkContext ctx) { Utils.nonNull(qcPoN, "QC PoN cannot be null."); final List<String> result; logger.info("Tangent normalizing all normals in the PoN..."); final CoveragePoNNormalizationResult qcNormalization = qcPoN.normalizeNormalsInPoN(ctx); final Map<String, Double> contigToMedian = getContigToMedianCRMap(qcNormalization.getProfile()); if (ctx == null) { final List<ReadCountCollection> singleSampleTangentNormalizedReadCounts = createIndividualReadCountCollections(qcNormalization.getProfile()); result = identifySamplesWithSuspiciousContigs(singleSampleTangentNormalizedReadCounts, contigToMedian); } else { final JavaRDD<ReadCountCollection> parallelSingleSampleTangentNormalizedReadCounts = createParallelIndividualReadCountCollections(qcNormalization.getProfile(), ctx); result = identifySamplesWithSuspiciousContigs(parallelSingleSampleTangentNormalizedReadCounts, ctx, contigToMedian); } return result; }

Target:
public static <T extends CoveragePoNNormalizationResult> List<String> retrieveSamplesWithArmLevelEvents(final CoveragePanelOfNormals<T> qcPoN, final JavaSparkContext ctx) { Utils.nonNull(qcPoN, "QC PoN cannot be null."); logger.info("Tangent normalizing all normals in the PoN..."); final CoveragePoNNormalizationResult qcNormalization = qcPoN.normalizeNormalsInPoN(ctx); final Map<String, Double> contigToMedian = getContigToMedianCRMap(qcNormalization.getProfile()); if (ctx == null) { final List<ReadCountCollection> singleSampleTangentNormalizedReadCounts = createIndividualReadCountCollections(qcNormalization.getProfile()); return identifySamplesWithSuspiciousContigs(singleSampleTangentNormalizedReadCounts, contigToMedian); } final JavaRDD<ReadCountCollection> parallelSingleSampleTangentNormalizedReadCounts = createParallelIndividualReadCountCollections(qcNormalization.getProfile(), ctx); return identifySamplesWithSuspiciousContigs(parallelSingleSampleTangentNormalizedReadCounts, ctx, contigToMedian); }
Source:
public static void deleteTempDirectory(File temp) throws IOException { File[] files = temp.listFiles(); if (files != null) { for (File f : files) { if (f.isDirectory()) { deleteTempDirectory(f); } else { if (!(f.delete())) { throw new IOException("Could not delete temp file: " + f.getAbsolutePath()); } } } } if (!(temp.delete())) { throw new IOException( "Could not delete temp file: " + temp.getAbsolutePath()); } }

Target:
public static void deleteTempDirectory(File temp) throws IOException { File[] files = temp.listFiles(); if (files != null) { for (File f : files) { if (f.isDirectory()) { deleteTempDirectory(f); } else { f.delete(); } } } if (!(temp.delete())) { throw new IOException( "Could not delete temp file: " + temp.getAbsolutePath()); } }
Source:
public ValidationResult profileValid(Guid clusterId) { if (nic.getVnicProfileId() != null) { VnicProfile vnicProfile = getDbFacade().getVnicProfileDao().get(nic.getVnicProfileId()); if (vnicProfile == null) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VNIC_PROFILE_NOT_EXISTS); } Network network = getNetworkByVnicProfile(vnicProfile); if (network == null || !isNetworkInCluster(network, clusterId)) { return new ValidationResult(VdcBllMessages.NETWORK_NOT_EXISTS_IN_CURRENT_CLUSTER); } if (!FeatureSupported.networkQoS(version) && getDbFacade().getQosDao().get(vnicProfile.getNetworkQosId()) != null) return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWROK_QOS_IS_NOT_SUPPORTED, clusterVersion()); } return ValidationResult.VALID; }

Target:
public ValidationResult profileValid(Guid clusterId) { if (nic.getVnicProfileId() != null) { VnicProfile vnicProfile = getDbFacade().getVnicProfileDao().get(nic.getVnicProfileId()); if (vnicProfile == null) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VNIC_PROFILE_NOT_EXISTS); } Network network = getNetworkByVnicProfile(vnicProfile); if (network == null || !isNetworkInCluster(network, clusterId)) { return new ValidationResult(VdcBllMessages.NETWORK_NOT_EXISTS_IN_CURRENT_CLUSTER); } if (!FeatureSupported.networkQoS(version) && vnicProfile.getNetworkQosId() != null) return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWROK_QOS_IS_NOT_SUPPORTED, clusterVersion()); } return ValidationResult.VALID; }
Source:
public static OcrTranslateApiMessage fromPubsubData(byte[] data) throws IllegalArgumentException { String jsonStr = new String(Base64.getDecoder().decode(data)); OcrTranslateApiMessage ocrMessage = gson.fromJson(jsonStr, OcrTranslateApiMessage.class); String text = ocrMessage.getText(); String filename = ocrMessage.getFilename(); String targetLang = ocrMessage.getLang(); if (text == null) { throw new IllegalArgumentException("Missing text parameter"); } if (filename == null) { throw new IllegalArgumentException("Missing filename parameter"); } if (targetLang == null) { throw new IllegalArgumentException("Missing lang parameter"); } return ocrMessage; }

Target:
public static OcrTranslateApiMessage fromPubsubData(byte[] data) { String jsonStr = new String(Base64.getDecoder().decode(data), StandardCharsets.UTF_8); Map<String, String> jsonMap = gson.fromJson(jsonStr, Map.class); return new OcrTranslateApiMessage( jsonMap.get("text"), jsonMap.get("filename"), jsonMap.get("lang")); }
Source:
public static void setTool(Tool tool) { if (K.tool != null) { assert false : "Can only call setTool once"; } K.tool = tool; }

Target:
public static void setTool(Tool tool) { assert K.tool == null : "Can only call setTool once"; K.tool = tool; }
Source:
private void evaluateMaintenanceHostCommandProgress(List<Guid> childCmdIds, CommandBase<?> rootCommand) { UpgradeHostParameters parameters = (UpgradeHostParameters) rootCommand.getParameters(); VdsDynamic host = vdsDynamicDao.get(parameters.getVdsId()); switch (host.getStatus()) { case PreparingForMaintenance: break; case Maintenance: switch (getMaintenanceCmdStatus(childCmdIds)) { case FAILED: case ENDED_WITH_FAILURE: log.info("Host '{}' is on maintenance mode. But not invoking Upgrade process because moving to " + "maintenance completed with failure, please see logs for details.", getHostName(parameters.getVdsId())); handleActionFailed(rootCommand, parameters); break; case SUCCEEDED: case ENDED_SUCCESSFULLY: log.info("Host '{}' is on maintenance mode. Proceeding with Upgrade process.", getHostName(parameters.getVdsId())); invokeHostUpgrade(rootCommand, parameters); break; case UNKNOWN: if (childCmdIds.isEmpty()) { log.info("Host '{}' is on maintenance mode. Proceeding with Upgrade process.", getHostName(parameters.getVdsId())); invokeHostUpgrade(rootCommand, parameters); } break; default: break; } break; default: if (isMaintenanceCommandExecuted(childCmdIds) || hasMaintenanceCmdFailed(childCmdIds)) { handleActionFailed(rootCommand, parameters); } break; } }

Target:
private void evaluateMaintenanceHostCommandProgress(List<Guid> childCmdIds, CommandBase<?> rootCommand) { UpgradeHostParameters parameters = (UpgradeHostParameters) rootCommand.getParameters(); VdsDynamic host = vdsDynamicDao.get(parameters.getVdsId()); switch (host.getStatus()) { case PreparingForMaintenance: break; case Maintenance: if (childCmdIds.isEmpty()) { logAndinvokeHostUpgrade(rootCommand, parameters); break; } switch (getMaintenanceCmdStatus(childCmdIds)) { case FAILED: case ENDED_WITH_FAILURE: log.info("Host '{}' is on maintenance mode. But not invoking Upgrade process because moving to " + "maintenance completed with failure, please see logs for details.", getHostName(parameters.getVdsId())); handleActionFailed(rootCommand, parameters); break; case SUCCEEDED: case ENDED_SUCCESSFULLY: logAndinvokeHostUpgrade(rootCommand, parameters); break; case UNKNOWN: log.info("Host '{}' is on maintenance mode. But not invoking Upgrade process because moving to " + "maintenance command is in UNKNOWN status.", getHostName(parameters.getVdsId())); break; default: log.info("Host '{}' is on maintenance mode. But not invoking Upgrade process because moving to " + "maintenance command is in unhandled status '{}'.", getHostName(parameters.getVdsId()), host.getStatus()); break; } break; default: if (isMaintenanceCommandExecuted(childCmdIds) || hasMaintenanceCmdFailed(childCmdIds)) { handleActionFailed(rootCommand, parameters); } break; } }
Source:
public Clue investigate() { if (getResponse() == null || getResponse().getCrn() == null || getResponse().getStackV4Response() == null) { return null; } AuditEventV4Responses auditEvents = AuditUtil.getAuditEvents( getTestContext().getMicroserviceClient(CloudbreakClient.class), CloudbreakEventService.DATAHUB_RESOURCE_TYPE, null, getResponse().getCrn()); boolean hasSpotTermination = getResponse().getStackV4Response().getInstanceGroups().stream() .flatMap(ig -> ig.getMetadata().stream()) .anyMatch(metadata -> InstanceStatus.DELETED_BY_PROVIDER == metadata.getInstanceStatus()); return new Clue("SDX", auditEvents, getResponse(), hasSpotTermination); }

Target:
public Clue investigate() { if (getResponse() == null || getResponse().getCrn() == null) { return null; } AuditEventV4Responses auditEvents = AuditUtil.getAuditEvents( getTestContext().getMicroserviceClient(CloudbreakClient.class), CloudbreakEventService.DATAHUB_RESOURCE_TYPE, null, getResponse().getCrn()); boolean hasSpotTermination = (getResponse().getStackV4Response() == null) ? false : getResponse().getStackV4Response().getInstanceGroups().stream() .flatMap(ig -> ig.getMetadata().stream()) .anyMatch(metadata -> InstanceStatus.DELETED_BY_PROVIDER == metadata.getInstanceStatus()); return new Clue("SDX", auditEvents, getResponse(), hasSpotTermination); }
Source:
private String initMatchOwnerEntityNode(EntityKeyMetadata ownerEntityKeyMetadata) { StringBuilder queryBuilder = new StringBuilder( "MATCH " ); appendEntityNode( "owner", ownerEntityKeyMetadata, queryBuilder ); return queryBuilder.toString(); }

Target:
private static String initMatchOwnerEntityNode(EntityKeyMetadata ownerEntityKeyMetadata) { StringBuilder queryBuilder = new StringBuilder(); appendMatchOwnerEntityNode( queryBuilder, ownerEntityKeyMetadata ); return queryBuilder.toString(); }
Source:
public String toString() { return MoreObjects.toStringHelper(this) .add("configurationBinding", configurationBinding) .toString(); }

Target:
public String toString() { return toStringHelper(this) .add("configurationBinding", configurationBinding) .toString(); }
Source:
private boolean generateDefaultDomainName (final Configuration configuration, final DaoManager storage) { try{ final String defaultOrganization = "ORafbe225ad37541eba518a74248f0ac4c"; final String hostname = configuration.getString("hostname"); Organization organization = storage.getOrganizationsDao().getOrganization(new Sid(defaultOrganization)); if(organization != null){ if(hostname != null && !hostname.trim().equals("")){ if(logger.isInfoEnabled()) logger.info("Generate Default Domain Name based on RC hostname: "+hostname); organization = organization.setDomainName(hostname); storage.getOrganizationsDao().updateOrganization(organization); }else{ logger.error("Unable to generateDefaultDomainName hostname property is null in restcomm.xml"); return false; } }else{ logger.error("Unable to generateDefaultDomainName default org not found"); return false; } }catch(Exception e){ logger.error("Unable to generateDefaultDomainName {}", e); return false; } return true; }

Target:
private boolean generateDefaultDomainName (final Configuration configuration, final DaoManager storage) { try{ final Sid defaultOrganization = new Sid("ORafbe225ad37541eba518a74248f0ac4c"); final String hostname = configuration.getString("hostname"); if(hostname != null && !hostname.trim().equals("")){ if(logger.isInfoEnabled()) logger.info("Generate Default Domain Name based on RC hostname: "+hostname); }else{ logger.error("Unable to generateDefaultDomainName hostname property is null in restcomm.xml"); return false; } Organization organization = storage.getOrganizationsDao().getOrganization(defaultOrganization); if(organization == null){ storage.getOrganizationsDao().addOrganization(new Organization(defaultOrganization, hostname, DateTime.now(), DateTime.now())); }else{ organization = organization.setDomainName(hostname); storage.getOrganizationsDao().updateOrganization(organization); } }catch(Exception e){ logger.error("Unable to generateDefaultDomainName {}", e); return false; } return true; }
Source:
public JSONObject sendHarbormasterMessage(String phid, boolean pass, UnitResults unitResults, Map<String, String> coverage) throws ConduitAPIException, IOException { JSONObject params = new JSONObject(); params.element("type", pass ? "pass" : "fail") .element("buildTargetPHID", phid); List<JSONObject> unit = new ArrayList<JSONObject>(); if (unitResults != null) { unit.addAll(unitResults.toHarbormaster()); } if (coverage != null) { JSONObject coverageUnit = new JSONObject() .element("result", "pass") .element("name", "Coverage Data") .element("coverage", coverage); unit.add(coverageUnit); } if (!unit.isEmpty()) { params.element("unit", unit); } return this.callConduit("harbormaster.sendmessage", params); }

Target:
public JSONObject sendHarbormasterMessage(String phid, boolean pass, UnitResults unitResults, Map<String, String> coverage) throws ConduitAPIException, IOException { List<JSONObject> unit = new ArrayList<JSONObject>(); if (unitResults != null) { unit.addAll(unitResults.toHarbormaster()); } if (coverage != null) { JSONObject coverageUnit = new JSONObject() .element("result", "pass") .element("name", "Coverage Data") .element("coverage", coverage); unit.add(coverageUnit); } JSONObject params = new JSONObject(); params.element("type", pass ? "pass" : "fail") .element("buildTargetPHID", phid); if (!unit.isEmpty()) { params.element("unit", unit); } return this.callConduit("harbormaster.sendmessage", params); }
Source:
private Optional<X509Certificate> getClientCertFromXfccHeaderEnvoyFormatted( List<String> xfccHeaderValues) { if (xfccHeaderValues.size() == 0) { return Optional.empty(); } else if (xfccHeaderValues.size() > 1) { logger.warn("Keywhiz only supports one certificate set in the header", XFCC_HEADER_NAME); return Optional.empty(); } String[] keyValuePairs = xfccHeaderValues.get(0).split(";"); for (String pair : keyValuePairs) { String[] keyValue = pair.split("="); if (keyValue.length != 2) { logger.warn("Got entry in header that wasn't a key/value pair: {}", XFCC_HEADER_NAME, pair); continue; } if (!CERT_KEY.equals(keyValue[0])) { continue; } return parseCertFromCertField(keyValue[1]); } logger.warn("Unable to find in header; no client ID parsed from header", CERT_KEY, XFCC_HEADER_NAME); return Optional.empty(); }

Target:
private Optional<X509Certificate> getClientCertFromXfccHeaderEnvoyFormatted( List<String> xfccHeaderValues) { if (xfccHeaderValues.size() == 0) { return Optional.empty(); } else if (xfccHeaderValues.size() > 1) { logger.warn( "Keywhiz only supports one header, but were provided", XFCC_HEADER_NAME, xfccHeaderValues.size()); return Optional.empty(); } XfccHeader xfccHeader; try { xfccHeader = XfccHeader.parse(xfccHeaderValues.get(0)); } catch (XfccHeader.ParseException e) { logger.warn(format("Unable to parse input %s header", XFCC_HEADER_NAME), e); return Optional.empty(); } if (xfccHeader.elements.length == 0) { logger.warn("No data provided in header", XFCC_HEADER_NAME); return Optional.empty(); } else if (xfccHeader.elements.length > 1) { logger.warn( "Keywhiz only supports one certificate set in the header, but were provided", XFCC_HEADER_NAME, xfccHeader.elements.length); return Optional.empty(); } List<String> certValues = Arrays.stream(xfccHeader.elements[0].pairs) .filter((pair) -> CERT_KEY.equalsIgnoreCase(pair.key)) .map((pair) -> pair.value) .collect(Collectors.toUnmodifiableList()); if (certValues.size() == 0) { logger.warn("Unable to find in header; no client ID parsed from header", CERT_KEY, XFCC_HEADER_NAME); return Optional.empty(); } else if (certValues.size() > 1) { logger.warn( "Keywhiz only supports one key in the header, but were provided", CERT_KEY, XFCC_HEADER_NAME, certValues.size()); return Optional.empty(); } return parseUrlEncodedPem(certValues.get(0)); }
Source:
public Potion getPotion() { return toRemove; }

Target:
public Potion getPotion() { return this.potion; }
Source:
public T moveTo(int x, int y) { return moveTo(useAbsolute(x, y)); }

Target:
public T moveTo(int x, int y) { return moveTo(point(x, y)); }
Source:
public void fetchKeysAndValuesInvokesGetValuesForKeys() throws Exception { PartitionedRegion spyPartitionedRegion = spy(partitionedRegion); VersionedObjectList values = mock(VersionedObjectList.class); ServerConnection serverConnection = mock(ServerConnection.class); Set<Integer> failures = mock(Set.class); InternalDistributedMember member = mock(InternalDistributedMember.class); Set<Integer> buckets = new HashSet<>(); buckets.add(1); FetchKeysMessage.FetchKeysResponse fetchKeysResponse = mock(FetchKeysMessage.FetchKeysResponse.class); doReturn(fetchKeysResponse).when(spyPartitionedRegion).getFetchKeysResponse(member, 1); Set keys = mock(Set.class); when(fetchKeysResponse.waitForKeys()).thenReturn(keys); doNothing().when(spyPartitionedRegion).getValuesForKeys(values, serverConnection, keys); spyPartitionedRegion.fetchKeysAndValues(values, serverConnection, failures, member, null, buckets); verify(failures, never()).add(1); verify(spyPartitionedRegion).getValuesForKeys(values, serverConnection, keys); }

Target:
public void fetchKeysAndValuesInvokesGetValuesForKeys() throws Exception { PartitionedRegion spyPartitionedRegion = spy(partitionedRegion); VersionedObjectList values = mock(VersionedObjectList.class); ServerConnection serverConnection = mock(ServerConnection.class); Set<Integer> failures = new HashSet<>(); InternalDistributedMember member = mock(InternalDistributedMember.class); Set<Integer> buckets = new HashSet<>(); buckets.add(1); FetchKeysMessage.FetchKeysResponse fetchKeysResponse = mock(FetchKeysMessage.FetchKeysResponse.class); doReturn(fetchKeysResponse).when(spyPartitionedRegion).getFetchKeysResponse(member, 1); Set keys = new HashSet(); when(fetchKeysResponse.waitForKeys()).thenReturn(keys); doNothing().when(spyPartitionedRegion).getValuesForKeys(values, serverConnection, keys); spyPartitionedRegion.fetchKeysAndValues(values, serverConnection, failures, member, null, buckets); verify(spyPartitionedRegion).getValuesForKeys(values, serverConnection, keys); assertThat(failures.contains(1)).isFalse(); }
Source:
public SchedulerAccount readAccount(final String username) { return executeReadOnlyTransaction(session -> { Query tasksQuery = session.getNamedQuery("readAccountTasks").setParameter("username", username); int taskCount; long taskDuration; Object[] taskResult = (Object[]) tasksQuery.uniqueResult(); taskCount = ((Number) taskResult[0]).intValue(); if (taskResult[1] != null) { taskDuration = ((Number) taskResult[1]).longValue(); } else { taskDuration = 0; } int jobCount; long jobDuration; Query jobQuery = session.getNamedQuery("readAccountJobs").setParameter("username", username); Object[] jobResult = (Object[]) jobQuery.uniqueResult(); jobCount = ((Number) jobResult[0]).intValue(); if (jobResult[1] != null) { jobDuration = ((Number) jobResult[1]).longValue(); } else { jobDuration = 0; } return new SchedulerAccount(username, taskCount, taskDuration, jobCount, jobDuration); }); }

Target:
public SchedulerAccount readAccount(final String username) { return executeReadOnlyTransaction(session -> { Query tasksQuery = session.getNamedQuery("readAccountTasks").setParameter("username", username); int taskCount; long taskDuration; Object[] taskResult = (Object[]) tasksQuery.uniqueResult(); taskCount = ((Number) taskResult[0]).intValue(); if (taskResult[1] != null) { taskDuration = ((Number) taskResult[1]).longValue(); } else { taskDuration = 0L; } int jobCount; long jobDuration; Query jobQuery = session.getNamedQuery("readAccountJobs").setParameter("username", username); Object[] jobResult = (Object[]) jobQuery.uniqueResult(); jobCount = ((Number) jobResult[0]).intValue(); if (jobResult[1] != null) { jobDuration = ((Number) jobResult[1]).longValue(); } else { jobDuration = 0L; } return new SchedulerAccount(username, taskCount, taskDuration, jobCount, jobDuration); }); }
Source:
public static double stSphericalDistance(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice left, @SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice right) { OGCGeometry leftGeometry = deserialize(left); OGCGeometry rightGeometry = deserialize(right); if (leftGeometry.isEmpty()) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Left-hand-side input value is empty"); } if (rightGeometry.isEmpty()) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Right-hand-side input value is empty"); } validateSphericalType("ST_Distance", leftGeometry, EnumSet.of(POINT)); validateSphericalType("ST_Distance", rightGeometry, EnumSet.of(POINT)); Point leftPoint = (Point) leftGeometry.getEsriGeometry(); Point rightPoint = (Point) rightGeometry.getEsriGeometry(); return greatCircleDistance(leftPoint.getY(), leftPoint.getX(), rightPoint.getY(), rightPoint.getX()) * 1000; }

Target:
public static Double stSphericalDistance(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice left, @SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice right) { OGCGeometry leftGeometry = deserialize(left); OGCGeometry rightGeometry = deserialize(right); if (leftGeometry.isEmpty() || rightGeometry.isEmpty()) { return null; } validateSphericalType("ST_Distance", leftGeometry, EnumSet.of(POINT)); validateSphericalType("ST_Distance", rightGeometry, EnumSet.of(POINT)); Point leftPoint = (Point) leftGeometry.getEsriGeometry(); Point rightPoint = (Point) rightGeometry.getEsriGeometry(); return greatCircleDistance(leftPoint.getY(), leftPoint.getX(), rightPoint.getY(), rightPoint.getX()) * 1000; }
Source:
public boolean isRead(Tip tip) { return fReadList.contains(new Integer(tip.hashCode())); }

Target:
public boolean isRead(Tip tip) { return fReadList.contains(Integer.valueOf(tip.hashCode())); }
Source:
public Set<KList> runRule(Set<KList> input) { Set<KList> result; if (this.label == null) { result = input; } else { result = new HashSet<>(); for (KList kl : input) { result.add(new KList(Arrays.<Term>asList(new KApp(label, kl)))); } } if (this instanceof ExitState) { return new HashSet<KList>(Arrays.asList(new KList(Arrays.asList((Term)new Ambiguity("K", new ArrayList<Term>(result)))))); } else { return result; } }

Target:
public Set<KList> runRule(Set<KList> input) { Set<KList> result; if (this.label == null) { result = input; } else { result = new HashSet<>(); for (KList kl : input) { result.add(new KList(Arrays.<Term>asList(new KApp(label, kl)))); } } if (this instanceof ExitState) { return new HashSet<KList>(Arrays.asList(new KList(Arrays.asList((Term)new Ambiguity(KSorts.K, new ArrayList<Term>(result)))))); } else { return result; } }
Source:
public void configure(MetricRegistry metricRegistry, String name) { hijackJDKLogging(); final Logger root = configureLevels(); for (AppenderFactory output : appenders) { root.addAppender(output.build(root.getLoggerContext(), name, null)); } printIfErrorsOccured(root.getLoggerContext()); final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { final ObjectName objectName = new ObjectName("io.dropwizard:type=Logging"); if (!server.isRegistered(objectName)) { server.registerMBean(new JMXConfigurator(root.getLoggerContext(), server, objectName), objectName); } } catch (MalformedObjectNameException | InstanceAlreadyExistsException | NotCompliantMBeanException | MBeanRegistrationException e) { throw new RuntimeException(e); } configureInstrumentation(root, metricRegistry); }

Target:
public void configure(MetricRegistry metricRegistry, String name) { hijackJDKLogging(); final Logger root = configureLevels(); for (AppenderFactory output : appenders) { root.addAppender(output.build(loggerContext, name, null)); } StatusPrinter.setPrintStream(configurationErrorsStream); try { StatusPrinter.printIfErrorsOccured(loggerContext); }finally { StatusPrinter.setPrintStream(System.out); } final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { final ObjectName objectName = new ObjectName("io.dropwizard:type=Logging"); if (!server.isRegistered(objectName)) { server.registerMBean(new JMXConfigurator(loggerContext, server, objectName), objectName); } } catch (MalformedObjectNameException | InstanceAlreadyExistsException | NotCompliantMBeanException | MBeanRegistrationException e) { throw new RuntimeException(e); } configureInstrumentation(root, metricRegistry); }
Source:
public int compare(Task firstTask, Task secondTask) { if (Objects.isNull(firstTask) || Objects.isNull(secondTask)) { return 1; } if (Objects.isNull(firstTask.getTitle()) ? !Objects.isNull(secondTask.getTitle()) : !firstTask.getTitle().equals(secondTask.getTitle())) { return 1; } if (Objects.isNull(firstTask.getOrdering()) ? !Objects.isNull(secondTask.getOrdering()) : !firstTask.getOrdering().equals(secondTask.getOrdering())) { return 1; } if (!firstTask.isTypeAutomatic() == secondTask.isTypeAutomatic()) { return 1; } if (!firstTask.isTypeMetadata() == secondTask.isTypeMetadata()) { return 1; } if (!firstTask.isTypeImagesRead() == secondTask.isTypeImagesRead()) { return 1; } if (!firstTask.isTypeImagesWrite() == secondTask.isTypeImagesWrite()) { return 1; } if (!firstTask.isTypeExportDMS() == secondTask.isTypeExportDMS()) { return 1; } if (!firstTask.isTypeAcceptClose() == secondTask.isTypeAcceptClose()) { return 1; } if (!firstTask.isTypeCloseVerify() == secondTask.isTypeCloseVerify()) { return 1; } if (Objects.isNull(firstTask.getScriptPath()) ? !Objects.isNull(secondTask.getScriptPath()) : !firstTask.getScriptPath().equals(secondTask.getScriptPath())) { return 1; } if (!firstTask.isBatchStep() == secondTask.isBatchStep()) { return 1; } return 0; }

Target:
public int compare(Task firstTask, Task secondTask) { if (Objects.isNull(firstTask) || Objects.isNull(secondTask)) { return 1; } if (Objects.isNull(firstTask.getTitle()) ? Objects.nonNull(secondTask.getTitle()) : !firstTask.getTitle().equals(secondTask.getTitle())) { return 1; } if (Objects.isNull(firstTask.getOrdering()) ? Objects.nonNull(secondTask.getOrdering()) : !firstTask.getOrdering().equals(secondTask.getOrdering())) { return 1; } if (firstTask.isTypeAutomatic() != secondTask.isTypeAutomatic()) { return 1; } if (firstTask.isTypeMetadata() != secondTask.isTypeMetadata()) { return 1; } if (firstTask.isTypeImagesRead() != secondTask.isTypeImagesRead()) { return 1; } if (firstTask.isTypeImagesWrite() != secondTask.isTypeImagesWrite()) { return 1; } if (firstTask.isTypeExportDMS() != secondTask.isTypeExportDMS()) { return 1; } if (firstTask.isTypeAcceptClose() != secondTask.isTypeAcceptClose()) { return 1; } if (firstTask.isTypeCloseVerify() != secondTask.isTypeCloseVerify()) { return 1; } if (Objects.isNull(firstTask.getScriptPath()) ? Objects.nonNull(secondTask.getScriptPath()) : !firstTask.getScriptPath().equals(secondTask.getScriptPath())) { return 1; } if (firstTask.isBatchStep() != secondTask.isBatchStep()) { return 1; } return 0; }
Source:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int lastVisibleItem = firstVisibleItem + visibleItemCount; if (lastVisibleItem > 0 && getCards().size() > lastVisibleItem) { String firstAns = getCards().get(firstVisibleItem).get("answer"); String lastAns = getCards().get(lastVisibleItem - 1).get("answer"); if (firstAns != null && firstAns.equals("") || lastAns != null && lastAns.equals("")) { showProgressBar(); long currentTime = SystemClock.elapsedRealtime (); if ((currentTime - mLastRenderStart > 300 || lastVisibleItem >= totalItemCount)) { mLastRenderStart = currentTime; DeckTask.cancelTask(DeckTask.TASK_TYPE_RENDER_BROWSER_QA); DeckTask.launchDeckTask(DeckTask.TASK_TYPE_RENDER_BROWSER_QA, mRenderQAHandler, new DeckTask.TaskData(new Object[]{getCards(), firstVisibleItem, visibleItemCount})); } } } }

Target:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int lastVisibleItem = firstVisibleItem + visibleItemCount; int size = getCards().size(); if (size > 0 && firstVisibleItem < size && lastVisibleItem - 1 < size) { String firstAns = getCards().get(firstVisibleItem).get("answer"); String lastAns = getCards().get(lastVisibleItem - 1).get("answer"); if (firstAns != null && firstAns.equals("") || lastAns != null && lastAns.equals("")) { showProgressBar(); long currentTime = SystemClock.elapsedRealtime (); if ((currentTime - mLastRenderStart > 300 || lastVisibleItem >= totalItemCount)) { mLastRenderStart = currentTime; DeckTask.cancelTask(DeckTask.TASK_TYPE_RENDER_BROWSER_QA); DeckTask.launchDeckTask(DeckTask.TASK_TYPE_RENDER_BROWSER_QA, mRenderQAHandler, new DeckTask.TaskData(new Object[]{getCards(), firstVisibleItem, visibleItemCount})); } } } }