auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void putObject(String bucketName, String objectName, ServerSideEncryption sse, String fileName) throws InvalidBucketNameException, NoSuchAlgorithmException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException, InsufficientDataException { if ((sse.getType() == (ServerSideEncryption.Type.SSE_C)) && (!this.baseUrl.isHttps())) { throw new InvalidArgumentException("SSE_C operations must be performed over a secure connection."); <START> } else if ((sse.getType() == (ServerSideEncryption.Type.SSE_KMS)) && (!this.baseUrl.isHttps())) { <END> throw new InvalidArgumentException("SSE_KMS operations must be performed over a secure connection."); } if (fileName == null || "".equals(fileName)) { throw new InvalidArgumentException("empty file name is not allowed"); } Path filePath = Paths.get(fileName); if (!Files.isRegularFile(filePath)) { throw new InvalidArgumentException("'" + fileName + "': not a regular file"); } String contentType = Files.probeContentType(filePath); long size = Files.size(filePath); RandomAccessFile file = new RandomAccessFile(filePath.toFile(), "r"); Map<String, String> headerMap = new HashMap<>(); headerMap.put("Content-Type", contentType); try { putObject(bucketName, objectName, size, file, headerMap, sse); } finally { file.close(); } }</code><technical_language>Remove unnecessary ()</technical_language>

Target:
public void putObject(String bucketName, String objectName, ServerSideEncryption sse, String fileName) throws InvalidBucketNameException, NoSuchAlgorithmException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException, InsufficientDataException { if (sse.getType() == ServerSideEncryption.Type.SSE_C && !this.baseUrl.isHttps()) { throw new InvalidArgumentException("SSE_C operations must be performed over a secure connection."); } else if (sse.getType() == ServerSideEncryption.Type.SSE_KMS && !this.baseUrl.isHttps()) { throw new InvalidArgumentException("SSE_KMS operations must be performed over a secure connection."); } if (fileName == null || "".equals(fileName)) { throw new InvalidArgumentException("empty file name is not allowed"); } Path filePath = Paths.get(fileName); if (!Files.isRegularFile(filePath)) { throw new InvalidArgumentException("'" + fileName + "': not a regular file"); } String contentType = Files.probeContentType(filePath); long size = Files.size(filePath); RandomAccessFile file = new RandomAccessFile(filePath.toFile(), "r"); Map<String, String> headerMap = new HashMap<>(); headerMap.put("Content-Type", contentType); try { putObject(bucketName, objectName, size, file, headerMap, sse); } finally { file.close(); } }
Source:
<code>public void AddNodeDuringInvalidateLayoutTest() { workflow(wf -> { wf.setupDocker(fixture -> { <START> fixture.getCluster().numNodes(3); <END> }); wf.deploy(); try { addNodeDuringInvalidateLayout(wf); } catch (Exception e) { Assertions.fail("Test failed: " + e); } } ); }</code><technical_language>is a 3 node cluster default, need</technical_language>

Target:
public void AddNodeDuringInvalidateLayoutTest() { workflow(wf -> { wf.deploy(); try { addNodeDuringInvalidateLayout(wf); } catch (Exception e) { Assertions.fail("Test failed: " + e); } } ); }
Source:
<code>public String getIdentifier(DashboardData data) { XPathXMLParser parser = getParser(data.getRequestXML()); if (null == parser) { <START> return ""; <END> } String wpsPrefix = parser.getContext().getPrefix(WPS_NAMESPACE_URI); String owsPrefix = parser.getContext().getPrefix(OWS_NAMESPACE_URI); StringBuilder xpath = new StringBuilder(); xpath.append("/").append(wpsPrefix).append(":Execute/").append(owsPrefix).append(":Identifier"); return parser.getString(xpath.toString()); }</code><technical_language>returning ""</technical_language>

Target:
public String getIdentifier(DashboardData data) throws XPathExpressionException { XPathXMLParser parser = new XPathXMLParser(data.getRequestXML()); String wpsPrefix = parser.getContext().getPrefix(WPS_NAMESPACE_URI); String owsPrefix = parser.getContext().getPrefix(OWS_NAMESPACE_URI); StringBuilder xpath = new StringBuilder(); xpath.append("/").append(wpsPrefix).append(":Execute/").append(owsPrefix).append(":Identifier"); return parser.getString(xpath.toString()); }
Source:
<code>public static <T> TupleDomain<T> columnWiseUnion(List<TupleDomain<T>> tupleDomains) { if (tupleDomains.isEmpty()) { throw new IllegalArgumentException("tupleDomains must have at least one element"); } if (tupleDomains.size() == 1) { return tupleDomains.get(0); } <START> Set<T> commonColumns = new LinkedHashSet<>(); <END> boolean found = false; Iterator<TupleDomain<T>> domains = tupleDomains.iterator(); while (domains.hasNext()) { TupleDomain<T> domain = domains.next(); if (!domain.isNone()) { found = true; commonColumns.addAll(domain.getDomains().get().keySet()); break; } } if (!found) { return TupleDomain.none(); } while (domains.hasNext()) { TupleDomain<T> domain = domains.next(); if (!domain.isNone()) { commonColumns.retainAll(domain.getDomains().get().keySet()); } } Map<T, List<Domain>> domainsByColumn = new LinkedHashMap<>(tupleDomains.size()); for (TupleDomain<T> domain : tupleDomains) { if (!domain.isNone()) { for (Map.Entry<T, Domain> entry : domain.getDomains().get().entrySet()) { if (commonColumns.contains(entry.getKey())) { List<Domain> domainForColumn = domainsByColumn.get(entry.getKey()); if (domainForColumn == null) { domainForColumn = new ArrayList<>(); domainsByColumn.put(entry.getKey(), domainForColumn); } domainForColumn.add(entry.getValue()); } } } } Map<T, Domain> result = new LinkedHashMap<>(domainsByColumn.size()); for (Map.Entry<T, List<Domain>> entry : domainsByColumn.entrySet()) { result.put(entry.getKey(), Domain.union(entry.getValue())); } return withColumnDomains(result); }</code><technical_language>Unneeded change</technical_language>

Target:
public static <T> TupleDomain<T> columnWiseUnion(List<TupleDomain<T>> tupleDomains) { if (tupleDomains.isEmpty()) { throw new IllegalArgumentException("tupleDomains must have at least one element"); } if (tupleDomains.size() == 1) { return tupleDomains.get(0); } Set<T> commonColumns = new HashSet<>(); boolean found = false; Iterator<TupleDomain<T>> domains = tupleDomains.iterator(); while (domains.hasNext()) { TupleDomain<T> domain = domains.next(); if (!domain.isNone()) { found = true; commonColumns.addAll(domain.getDomains().get().keySet()); break; } } if (!found) { return TupleDomain.none(); } while (domains.hasNext()) { TupleDomain<T> domain = domains.next(); if (!domain.isNone()) { commonColumns.retainAll(domain.getDomains().get().keySet()); } } Map<T, List<Domain>> domainsByColumn = new LinkedHashMap<>(tupleDomains.size()); for (TupleDomain<T> domain : tupleDomains) { if (!domain.isNone()) { for (Map.Entry<T, Domain> entry : domain.getDomains().get().entrySet()) { if (commonColumns.contains(entry.getKey())) { List<Domain> domainForColumn = domainsByColumn.get(entry.getKey()); if (domainForColumn == null) { domainForColumn = new ArrayList<>(); domainsByColumn.put(entry.getKey(), domainForColumn); } domainForColumn.add(entry.getValue()); } } } } Map<T, Domain> result = new LinkedHashMap<>(domainsByColumn.size()); for (Map.Entry<T, List<Domain>> entry : domainsByColumn.entrySet()) { result.put(entry.getKey(), Domain.union(entry.getValue())); } return withColumnDomains(result); }
Source:
<code>public Set<File> findConfigurableLocations(File root, IProgressMonitor monitor) { LocalProjectScanner scanner = new LocalProjectScanner( ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile(), root.getAbsolutePath(), false, MavenPlugin.getMavenModelManager()); try { scanner.run(monitor); } catch (Exception ex) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex)); return null; } List<MavenProjectInfo> projects = new ArrayList<MavenProjectInfo>(); projects.addAll(scanner.getProjects()); <START> HashSet<File> res <END> = new HashSet<File>(); int i = 0; while (i < projects.size()) { MavenProjectInfo projectInfo = projects.get(i); res.add(projectInfo.getPomFile().getParentFile()); projects.addAll(projectInfo.getProjects()); i++; } return res; }</code><technical_language>declare a Set<File></technical_language>

Target:
public Set<File> findConfigurableLocations(File root, IProgressMonitor monitor) { LocalProjectScanner scanner = new LocalProjectScanner( ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile(), root.getAbsolutePath(), false, MavenPlugin.getMavenModelManager()); try { scanner.run(monitor); } catch (Exception ex) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex)); return null; } Queue<MavenProjectInfo> projects = new LinkedList<MavenProjectInfo>(); projects.addAll(scanner.getProjects()); HashSet<File> res = new HashSet<File>(); while (!projects.isEmpty()) { MavenProjectInfo projectInfo = projects.poll(); res.add(projectInfo.getPomFile().getParentFile()); projects.addAll(projectInfo.getProjects()); } return res; }
Source:
<code>public AsyncRunLoop(Map<TaskName, TaskInstance> taskInstances, ExecutorService threadPool, SystemConsumers consumerMultiplexer, int maxConcurrency, long windowMs, long commitMs, long callbackTimeoutMs, long maxThrottlingDelayMs, SamzaContainerMetrics containerMetrics, HighResolutionClock clock, boolean isAsyncCommitEnabled) { this.threadPool = threadPool; this.consumerMultiplexer = consumerMultiplexer; this.containerMetrics = containerMetrics; <START> this.containerMetricsCompletedCounter = containerMetrics.newCounter("async-callback-complete-calls"); <END> this.containerMetricsFailureCounter = containerMetrics.newCounter("async-callback-failure-calls"); this.windowMs = windowMs; this.commitMs = commitMs; this.maxConcurrency = maxConcurrency; this.callbackTimeoutMs = callbackTimeoutMs; this.callbackTimer = (callbackTimeoutMs > 0) ? Executors.newSingleThreadScheduledExecutor() : null; this.callbackExecutor = new ThrottlingScheduler(maxThrottlingDelayMs); this.coordinatorRequests = new CoordinatorRequests(taskInstances.keySet()); this.latch = new Object(); this.workerTimer = Executors.newSingleThreadScheduledExecutor(); this.clock = clock; Map<TaskName, AsyncTaskWorker> workers = new HashMap<>(); for (TaskInstance task : taskInstances.values()) { workers.put(task.taskName(), new AsyncTaskWorker(task)); } this.sspToTaskWorkerMapping = Collections.unmodifiableMap(getSspToAsyncTaskWorkerMap(taskInstances, workers)); this.taskWorkers = Collections.unmodifiableList(new ArrayList<>(workers.values())); this.isAsyncCommitEnabled = isAsyncCommitEnabled; }</code><technical_language>Please follow pattern declare/add metric in SamzaContainerMetrics (i.e. instantiate metric SamzaContainerMetrics class refer containerMetrics.callbackCompletes.inc()</technical_language>

Target:
public AsyncRunLoop(Map<TaskName, TaskInstance> taskInstances, ExecutorService threadPool, SystemConsumers consumerMultiplexer, int maxConcurrency, long windowMs, long commitMs, long callbackTimeoutMs, long maxThrottlingDelayMs, SamzaContainerMetrics containerMetrics, HighResolutionClock clock, boolean isAsyncCommitEnabled) { this.threadPool = threadPool; this.consumerMultiplexer = consumerMultiplexer; this.containerMetrics = containerMetrics; this.windowMs = windowMs; this.commitMs = commitMs; this.maxConcurrency = maxConcurrency; this.callbackTimeoutMs = callbackTimeoutMs; this.callbackTimer = (callbackTimeoutMs > 0) ? Executors.newSingleThreadScheduledExecutor() : null; this.callbackExecutor = new ThrottlingScheduler(maxThrottlingDelayMs); this.coordinatorRequests = new CoordinatorRequests(taskInstances.keySet()); this.latch = new Object(); this.workerTimer = Executors.newSingleThreadScheduledExecutor(); this.clock = clock; Map<TaskName, AsyncTaskWorker> workers = new HashMap<>(); for (TaskInstance task : taskInstances.values()) { workers.put(task.taskName(), new AsyncTaskWorker(task)); } this.sspToTaskWorkerMapping = Collections.unmodifiableMap(getSspToAsyncTaskWorkerMap(taskInstances, workers)); this.taskWorkers = Collections.unmodifiableList(new ArrayList<>(workers.values())); this.isAsyncCommitEnabled = isAsyncCommitEnabled; }
Source:
<code>private synchronized void handleNiInEs(GpsNiNotification notif) { if (DEBUG) Log.d(TAG, "entering handleNiInEs(GpsNiNotification notif)"); boolean isUEInEmergencyMode = getEmergencyStatus() || <START> Boolean.parseBoolean(SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE)); <END> if (DEBUG) Log.d(TAG, "isUEInEmergencyMode is" + isUEInEmergencyMode + "getEmergencyStatus() is" + getEmergencyStatus() + "Boolean.parseBoolean(SystemProperties.get(TelephonyProperties" + ".PROPERTY_INECM_MODE)) is" + Boolean.parseBoolean(SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE))); if ((notif.niType == GPS_NI_TYPE_EMERGENCY_SUPL) != isUEInEmergencyMode) { if (DEBUG) Log.d(TAG, "(notif.niType == GPS_NI_TYPE_EMERGENCY_SUPL)" + " != isUEInEmergencyMode"); try { if (DEBUG) Log.d(TAG, "ignoring the NI"); mNetInitiatedListener.sendNiResponse(notif.notificationId, GPS_NI_RESPONSE_IGNORE); } catch (RemoteException e) { Slog.e(TAG, "RemoteException in sendNiResponse"); } } else { if (DEBUG) Log.d(TAG, "(notif.niType == GPS_NI_TYPE_EMERGENCY_SUPL)" + " == isUEInEmergencyMode;"+ "calling handleSuplNi(notif)"); handleNi(notif); } if (DEBUG) Log.d(TAG, "leaving handleNiInEs(GpsNiNotification notif)"); }</code><technical_language>this throw? if so, handle it</technical_language>

Target:
private void handleNiInEs(GpsNiNotification notif) { if (DEBUG) Log.d(TAG, "in handleNiInEs () :" + " niType: " + notif.niType + " notificationId: " + notif.notificationId); boolean isUEInEmergencyMode = mIsInEmergency || Boolean.parseBoolean(SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE)); boolean isNiTypeES = notif.niType == GPS_NI_TYPE_EMERGENCY_SUPL ? true : false; if (isNiTypeES != isUEInEmergencyMode) { try { mNetInitiatedListener.sendNiResponse(notif.notificationId, GPS_NI_RESPONSE_IGNORE); } catch (RemoteException e) { Log.e(TAG, "RemoteException in sendNiResponse"); } } else { handleNi(notif); } }
Source:
<code>public GlowEnderPearl(Location location, float speed) { super(location); setDrag(0.99, false); setDrag(0.99, true); setHorizontalAirDrag(1); <START> setGravityAccel(new Vector(0, -0.03, 0)); <END> setVelocity(location.getDirection().multiply(speed)); setBoundingBox(0.25, 0.25); }</code><technical_language>put Y acceleration (-0.03) in a named constant in class? e.g. VERTICAL_GRAVITY_ACCEL</technical_language>

Target:
public GlowEnderPearl(Location location, float speed) { super(location); setDrag(0.99, false); setDrag(0.99, true); setHorizontalAirDrag(1); setGravityAccel(new Vector(0, VERTICAL_GRAVITY_ACCEL, 0)); setVelocity(location.getDirection().multiply(speed)); setBoundingBox(0.25, 0.25); }
Source:
<code>protected void initializeSuppliedImage() { super.initSuppliedImage(transferImageCommand); DiskImage diskImage = new DiskImage(); <START> diskImage.setId(transferImageCommand.getParameters().getImageId()); <END> diskImage.setStorageIds(new ArrayList<>(Collections.singletonList(Guid.newGuid()))); doReturn(diskImage).when(diskImageDao).get(any()); doReturn(diskValidator).when(getCommand()).getDiskValidator(any()); doReturn(diskImagesValidator).when(getCommand()).getDiskImagesValidator(any()); doReturn(storageDomainValidator).when(getCommand()).getStorageDomainValidator(any()); }</code><technical_language>setImageId</technical_language>

Target:
protected void initializeSuppliedImage() { super.initSuppliedImage(transferImageCommand); DiskImage diskImage = new DiskImage(); diskImage.setImageId(transferImageCommand.getParameters().getImageId()); diskImage.setStorageIds(new ArrayList<>(Collections.singletonList(Guid.newGuid()))); doReturn(diskImage).when(diskImageDao).get(any()); doReturn(diskValidator).when(getCommand()).getDiskValidator(any()); doReturn(diskImagesValidator).when(getCommand()).getDiskImagesValidator(any()); doReturn(storageDomainValidator).when(getCommand()).getStorageDomainValidator(any()); }
Source:
<code><START> public double logEmissionProbability(final AllelicCount data, final Double minorFraction) { <END> return logEmissionProbability(data, minorFraction, parameters, allelicPoN); }</code><technical_language>validate MAF</technical_language>

Target:
public double logEmissionProbability(final AllelicCount data, final Double minorFraction) { ParamUtils.inRange(minorFraction, 0.0, 0.5, "Minor fraction must be in [0, 1/2]."); return logEmissionProbability(data, minorFraction, parameters, allelicPoN); }
Source:
<code>public boolean isOperationPermitted(Object id, Action action) { if (action == Action.CREATE || action == Action.UPDATE) { <START> throw new UnexpectedEnumException(action); <END> } return checkEntityTypePermission(id, action); }</code><technical_language>Tricky. enum is perfectly valid I think, expect get here. IllegalStateException</technical_language>

Target:
public boolean isOperationPermitted(Object id, Action action) { if (action == Action.CREATE || action == Action.UPDATE) { throw new IllegalStateException( "CREATE and UPDATE permission checks should use 'isOperationPermitted(EntityType entityType, Action action)'"); } return checkEntityTypePermission(id, action); }
Source:
<code>private void setShuffleKeysFromPartitionedTableStore(StoreTableNode node, DataChannel channel) { Preconditions.checkState(node.hasTargetTable(), "A target table must be a partitioned table."); PartitionMethodDesc partitionMethod = node.getPartitionMethod(); if (node.getType() == NodeType.INSERT) { InsertNode insertNode = (InsertNode) node; channel.setSchema(((InsertNode) node).getProjectedSchema()); Column[] shuffleKeys = new Column[partitionMethod.getExpressionSchema().size()]; int i = 0; for (Column column : partitionMethod.getExpressionSchema().getColumns()) { int id = insertNode.getTableSchema().getColumnId(column.getQualifiedName()); shuffleKeys[i++] = insertNode.getProjectedSchema().getColumn(id); } channel.setShuffleKeys(shuffleKeys); channel.setShuffleType(SCATTERED_HASH_SHUFFLE); <START> } else if (node.getType() == NodeType.CREATE_TABLE) { <END> channel.setSchema(node.getInSchema()); Column[] shuffleKeys = new Column[partitionMethod.getExpressionSchema().size()]; int i = 0; for (int j = 0; j < partitionMethod.getExpressionSchema().getColumns().size(); j++) { int id = node.getOutSchema().getColumns().size() + j; shuffleKeys[i++] = node.getInSchema().getColumn(id); } channel.setShuffleKeys(shuffleKeys); channel.setShuffleType(SCATTERED_HASH_SHUFFLE); } else { channel.setShuffleKeys(partitionMethod.getExpressionSchema().toArray()); channel.setShuffleType(HASH_SHUFFLE); } channel.setShuffleOutputNum(32); }</code><technical_language>newly added code is of INSERT. nice if some code get ProjectSchema InSchema distinguished</technical_language>

Target:
private void setShuffleKeysFromPartitionedTableStore(StoreTableNode node, DataChannel channel) { Preconditions.checkState(node.hasTargetTable(), "A target table must be a partitioned table."); PartitionMethodDesc partitionMethod = node.getPartitionMethod(); if (node.getType() == NodeType.INSERT || node.getType() == NodeType.CREATE_TABLE) { Schema tableSchema = null, projectedSchema = null; if (node.getType() == NodeType.INSERT) { tableSchema = ((InsertNode) node).getTableSchema(); projectedSchema = ((InsertNode) node).getProjectedSchema(); } else { tableSchema = node.getOutSchema(); projectedSchema = node.getInSchema(); } channel.setSchema(projectedSchema); Column[] shuffleKeys = new Column[partitionMethod.getExpressionSchema().size()]; int i = 0, id = 0; for (Column column : partitionMethod.getExpressionSchema().getColumns()) { if (node.getType() == NodeType.INSERT) { id = tableSchema.getColumnId(column.getQualifiedName()); } else { id = tableSchema.getColumns().size() + i; } shuffleKeys[i++] = projectedSchema.getColumn(id); } channel.setShuffleKeys(shuffleKeys); channel.setShuffleType(SCATTERED_HASH_SHUFFLE); } else { channel.setShuffleKeys(partitionMethod.getExpressionSchema().toArray()); channel.setShuffleType(HASH_SHUFFLE); } channel.setShuffleOutputNum(32); }
Source:
<code>private void finishedTestClassRun(Class<?> testClazz) throws IOException { File directory = new File(FileUtils.getTempDirectoryPath() .concat(File.separator) .concat(XML_SNAPSHOT_DIRECTORY) .concat(File.separator) .concat(testClazz.getCanonicalName())); if (!directory.exists()) { if (!directory.mkdirs()) { throw new IOException("Unable to create path '" + directory.toString() + "'."); } } File copyTo = File.createTempFile(PropUtils.get("snapshots.target.file.prefix"), <START> PropUtils.get("snapshots.target.file.suffix"), directory); <END> File copyFrom = getSourceFile(); FileUtils.copyFile(copyFrom, copyTo); log.debug("Created snapshot of server configuration in '{}'.", copyTo); }</code><technical_language>putting time name clear snapshot created, a suggestion</technical_language>

Target:
private void finishedTestClassRun(Class<?> testClazz) throws IOException { LocalTime time = LocalTime.now(); String timeStamp = String.format("%02d:%02d:%02d_", time.getHour(), time.getMinute(), time.getSecond()); File directory = new File(FileUtils.getTempDirectoryPath() .concat(File.separator) .concat(XML_SNAPSHOT_DIRECTORY) .concat(File.separator) .concat(timeStamp) .concat(testClazz.getCanonicalName())); if (!directory.exists()) { if (!directory.mkdirs()) { throw new IOException("Unable to create path '" + directory.toString() + "'."); } } File copyTo = File.createTempFile(PropUtils.get("snapshots.target.file.prefix"), PropUtils.get("snapshots.target.file.suffix"), directory); File copyFrom = getSourceFile(); FileUtils.copyFile(copyFrom, copyTo); log.debug("Created snapshot of server configuration in '{}'.", copyTo); }
Source:
<code>public void testEnforceValidityErrorsOnly() throws Exception { Dictionary<String, Object> markerPluginProps = configureValidationMarkerPlugin( Collections.singletonList(SAMPLE_VALIDATOR), true, false, getAdminConfig()); String warningId = ingestXmlFromResourceAndWait(WARNING_METACARD); String cleanId = ingestXmlFromResourceAndWait(CLEAN_METACARD); ingestXmlFromResourceWaitForFailure(ERROR_METACARD); query(cleanId, TRANSFORMER_XML, HttpStatus.SC_OK); query(warningId, TRANSFORMER_XML, HttpStatus.SC_OK); String warningData = getFileContent(WARNING_METACARD); String errorData = getFileContent(ERROR_METACARD); update(cleanId, warningData, MediaType.APPLICATION_XML, HttpStatus.SC_OK); update(cleanId, errorData, MediaType.APPLICATION_XML, HttpStatus.SC_BAD_REQUEST); <START> configureValidationMarkerPlugin(markerPluginProps, getAdminConfig()); <END> }</code><technical_language>is reset if test failed before</technical_language>

Target:
public void testEnforceValidityErrorsOnly() throws Exception { Dictionary<String, Object> markerPluginProps = configureValidationMarkerPlugin( Collections.singletonList(SAMPLE_VALIDATOR), true, false, getAdminConfig()); try { String warningId = ingestXmlFromResourceAndWait(WARNING_METACARD); String cleanId = ingestXmlFromResourceAndWait(CLEAN_METACARD); ingestXmlFromResourceWaitForFailure(ERROR_METACARD); query(cleanId, TRANSFORMER_XML, HttpStatus.SC_OK); query(warningId, TRANSFORMER_XML, HttpStatus.SC_OK); String warningData = getFileContent(WARNING_METACARD); String errorData = getFileContent(ERROR_METACARD); update(cleanId, warningData, MediaType.APPLICATION_XML, HttpStatus.SC_OK); update(cleanId, errorData, MediaType.APPLICATION_XML, HttpStatus.SC_BAD_REQUEST); } finally { configureValidationMarkerPlugin(markerPluginProps, getAdminConfig()); } }
Source:
<code>public SnapshotStatus[] getSnapshotListing(String snapshotRoot) throws IOException { checkOpen(); <START> try (TraceScope ignored = tracer.newScope("getSnapshottableDirListing")) { <END> return namenode.getSnapshotListing(snapshotRoot); } catch (RemoteException re) { throw re.unwrapRemoteException(); } }</code><technical_language>Copy-paste error, Change try (TraceScope = tracer.newScope("getSnapshotListing")) {</technical_language>

Target:
public SnapshotStatus[] getSnapshotListing(String snapshotRoot) throws IOException { checkOpen(); try (TraceScope ignored = tracer.newScope("getSnapshotListing")) { return namenode.getSnapshotListing(snapshotRoot); } catch (RemoteException re) { throw re.unwrapRemoteException(); } }
Source:
<code>private static void error( HttpResponse response, String body, Map<String, Object> payload) throws APIError { <START> if (payload.containsKey("errors")) { <END> Map<String, Object> entity = (Map<String, Object>) ((ArrayList) payload.get("errors")).get(0); String category_code = (String) entity.get("category_code"); if (InsufficientFunds.CODES.contains(category_code)) throw new InsufficientFunds(response, body, entity); else if (Declined.CODES.contains(category_code)) throw new Declined(response, body, entity); else if (DuplicateAccountEmailAddress.CODES.contains(category_code)) throw new DuplicateAccountEmailAddress(response, body, entity); else if (BankAccountVerificationFailure.CODES.contains(category_code)) throw new BankAccountVerificationFailure(response, body, entity); throw new APIError(response, body, entity); } else { throw new APIError(response, body, payload); } }</code><technical_language>simpler if write code this java if (!payload.containsKey("errors")) { throw new APIError(response, body, payload); } ... notice do code if statement easier read</technical_language>

Target:
private static void error( HttpResponse response, String body, Map<String, Object> payload) throws APIError { if (!payload.containsKey("errors")) { throw new APIError(response, body, payload); } else { Map<String, Object> entity = (Map<String, Object>) ((ArrayList) payload.get("errors")).get(0); String category_code = (String) entity.get("category_code"); if (InsufficientFunds.CODES.contains(category_code)) throw new InsufficientFunds(response, body, entity); else if (Declined.CODES.contains(category_code)) throw new Declined(response, body, entity); else if (DuplicateAccountEmailAddress.CODES.contains(category_code)) throw new DuplicateAccountEmailAddress(response, body, entity); else if (BankAccountVerificationFailure.CODES.contains(category_code)) throw new BankAccountVerificationFailure(response, body, entity); throw new APIError(response, body, entity); } }
Source:
<code>public void setUp() throws Exception { DataSourceFactory factory = new DataSourceFactory(); factory.setDriverClass(org.h2.Driver.class.getName()); factory.setUrl("jdbc:h2:mem:DbTest-" + System.currentTimeMillis()); factory.setUser("DbTest"); dataSource = (ManagedPooledDataSource) factory.build(new MetricRegistry(), "DbTest"); DatabaseConnection conn = new JdbcConnection(dataSource.getConnection()); Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn); <START> liquibase = new CloseableLiquibaseWithClassPathMigrationsFile(dataSource, database, "migrations.xml"); <END> }</code><technical_language>I instantiate Database H2Database, connection, precisely type of database connect to</technical_language>

Target:
public void setUp() throws Exception { DataSourceFactory factory = new DataSourceFactory(); factory.setDriverClass(org.h2.Driver.class.getName()); factory.setUrl("jdbc:h2:mem:DbTest-" + System.currentTimeMillis()); factory.setUser("DbTest"); dataSource = (ManagedPooledDataSource) factory.build(new MetricRegistry(), "DbTest"); liquibase = new CloseableLiquibaseWithClassPathMigrationsFile(dataSource, "migrations.xml"); }
Source:
<code>public void testDrawSumOfQScores(final File metricsFile, final int altDepth, final double tolerance) throws Exception { final MetricsFile<TheoreticalSensitivityMetrics, Integer> Metrics = new MetricsFile<>(); <START> Metrics.read(new FileReader(metricsFile)); <END> final List<Histogram<Integer>> histograms = Metrics.getAllHistograms(); final Histogram<Integer> qualityHistogram = histograms.get(1); final TheoreticalSensitivity.RouletteWheel qualityRW = new TheoreticalSensitivity.RouletteWheel(TheoreticalSensitivity.trimDistribution(TheoreticalSensitivity.normalizeHistogram(qualityHistogram))); final Random randomNumberGenerator = new Random(TheoreticalSensitivity.RANDOM_SEED); final double averageQuality = qualityHistogram.getMean(); final double standardDeviationQuality = qualityHistogram.getStandardDeviation(); for(int k = 0;k < 1;k++) { int sumOfQualitiesFull = IntStream.range(0, altDepth).map(n -> qualityRW.draw()).sum(); int sumOfQualities = TheoreticalSensitivity.drawSumOfQScores(altDepth, averageQuality, standardDeviationQuality, randomNumberGenerator.nextGaussian()); Assert.assertEquals(sumOfQualitiesFull, sumOfQualities, sumOfQualitiesFull*tolerance); } }</code><technical_language>FileReaders opened try-with-resources closed for sure</technical_language>

Target:
public void testDrawSumOfQScores(final File metricsFile, final int altDepth, final double tolerance) throws Exception { final MetricsFile<TheoreticalSensitivityMetrics, Integer> metrics = new MetricsFile<>(); try (final FileReader metricsFileReader = new FileReader(metricsFile)) { metrics.read(metricsFileReader); } final List<Histogram<Integer>> histograms = metrics.getAllHistograms(); final Histogram<Integer> qualityHistogram = histograms.get(1); final TheoreticalSensitivity.RouletteWheel qualityRW = new TheoreticalSensitivity.RouletteWheel(TheoreticalSensitivity.trimDistribution(TheoreticalSensitivity.normalizeHistogram(qualityHistogram))); final Random randomNumberGenerator = new Random(51); final double averageQuality = qualityHistogram.getMean(); final double standardDeviationQuality = qualityHistogram.getStandardDeviation(); for(int k = 0;k < 1;k++) { int sumOfQualitiesFull = IntStream.range(0, altDepth).map(n -> qualityRW.draw()).sum(); int sumOfQualities = TheoreticalSensitivity.drawSumOfQScores(altDepth, averageQuality, standardDeviationQuality, randomNumberGenerator.nextGaussian()); Assert.assertEquals(sumOfQualitiesFull, sumOfQualities, sumOfQualitiesFull*tolerance); } }
Source:
<code>private void beforeSlotChangedCraftingGrid(final InventoryCraftResult output, final int index, final ItemStack itemstack) { if (!this.impl$captureInventory) { output.setInventorySlotContents(index, itemstack); return; } final ItemStackSnapshot orig = ItemStackUtil.snapshotOf(output.getStackInSlot(index)); output.setInventorySlotContents(index, itemstack); final ItemStackSnapshot repl = ItemStackUtil.snapshotOf(output.getStackInSlot(index)); final SlotAdapter slot = this.impl$getAdapters().get(index); if (this.impl$capturedCraftPreviewTransaction == null) { this.impl$capturedCraftPreviewTransaction = new SlotTransaction(slot, orig, repl); } else if (this.impl$capturedCraftPreviewTransaction.getSlot().equals(slot) && this.impl$capturedCraftPreviewTransaction.getFinal().equals(orig)) { this.impl$capturedCraftPreviewTransaction = new SlotTransaction(slot, this.impl$capturedCraftPreviewTransaction.getOriginal(), repl); } else { SlotTransaction replace = new SlotTransaction(slot, orig, repl); <START> SpongeImpl.getLogger().warn("Could not merge craft preview transactions - some events may break (original {}, replace {})", <END> this.impl$capturedCraftPreviewTransaction, replace); this.impl$capturedCraftPreviewTransaction = replace; } }</code><technical_language>this configurable</technical_language>

Target:
private void beforeSlotChangedCraftingGrid(final InventoryCraftResult output, final int index, final ItemStack itemstack) { if (!this.impl$captureInventory) { output.setInventorySlotContents(index, itemstack); return; } final ItemStackSnapshot orig = ItemStackUtil.snapshotOf(output.getStackInSlot(index)); output.setInventorySlotContents(index, itemstack); final ItemStackSnapshot repl = ItemStackUtil.snapshotOf(output.getStackInSlot(index)); final SlotAdapter slot = this.impl$getAdapters().get(index); if (this.impl$capturedCraftPreviewTransaction == null) { this.impl$capturedCraftPreviewTransaction = new SlotTransaction(slot, orig, repl); } else if (this.impl$capturedCraftPreviewTransaction.getSlot().equals(slot) && this.impl$capturedCraftPreviewTransaction.getFinal().equals(orig)) { this.impl$capturedCraftPreviewTransaction = new SlotTransaction(slot, this.impl$capturedCraftPreviewTransaction.getOriginal(), repl); } else { final SlotTransaction replace = new SlotTransaction(slot, orig, repl); ContainerMixin.impl$numTransactionErrorsLogged++; final int maxLogs = SpongeImpl.getGlobalConfigAdapter().getConfig().getLogging().logTransactionMergeFailure(); if (maxLogs <= 0 || ContainerMixin.impl$numTransactionErrorsLogged <= maxLogs) { SpongeImpl.getLogger().warn("Could not merge craft preview transactions - some events may break (original {}, replace {})", this.impl$capturedCraftPreviewTransaction, replace); if (ContainerMixin.impl$numTransactionErrorsLogged == maxLogs) { SpongeImpl.getLogger().warn("Further warnings about this will be suppressed. Change transaction-merge-fail in global.conf to " + "show more."); } } this.impl$capturedCraftPreviewTransaction = replace; } }
Source:
<code>public ForgedMethod(String name, Type sourceType, Type targetType, MapperConfiguration mapperConfiguration, ExecutableElement positionHintElement) { <START> String sourceParamName = Strings.decapitalize( sourceType.getName() ); <END> String sourceParamSafeName = Strings.getSaveVariableName( sourceParamName ); this.parameters = Arrays.asList( new Parameter( sourceParamSafeName, sourceType ) ); this.returnType = targetType; this.thrownTypes = new ArrayList<Type>(); this.name = Strings.sanatizeIdentifierName( name ); this.mapperConfiguration = mapperConfiguration; this.positionHintElement = positionHintElement; }</code><technical_language>hmm .. this superflous</technical_language>

Target:
public ForgedMethod(String name, Type sourceType, Type targetType, MapperConfiguration mapperConfiguration, ExecutableElement positionHintElement) { String sourceParamName = Strings.decapitalize( sourceType.getName() ); String sourceParamSafeName = Strings.getSaveVariableName( sourceParamName ); this.parameters = Arrays.asList( new Parameter( sourceParamSafeName, sourceType ) ); this.returnType = targetType; this.thrownTypes = new ArrayList<Type>(); this.name = Strings.sanitizeIdentifierName( name ); this.mapperConfiguration = mapperConfiguration; this.positionHintElement = positionHintElement; }
Source:
<code>public static Connection getConnection(SnowflakeConnectionProperties properties) throws IOException { try { Driver driver = (Driver) Class.forName(SnowflakeConstants.SNOWFLAKE_DRIVER).newInstance(); DriverManager.registerDriver(driver); return DriverManager .getConnection(properties.getConnectionUrl(), AuthenticationType.OAUTH == properties.authenticationType.getValue() <START> ? properties.getJdbcProperties(DriverManagerUtils::getAccessToken) <END> : properties.getJdbcProperties()); } catch (Exception e) { if (e.getMessage().contains("HTTP status=403")) { throw new IllegalArgumentException(e.getMessage()); } else { throw new IOException(e); } } }</code><technical_language>DriverManagerUtils::getAccessToken changed getAccessToken(properties)</technical_language>

Target:
public static Connection getConnection(SnowflakeConnectionProperties properties) throws IOException { try { Driver driver = (Driver) Class.forName(SnowflakeConstants.SNOWFLAKE_DRIVER).newInstance(); DriverManager.registerDriver(driver); return DriverManager .getConnection(properties.getConnectionUrl(), AuthenticationType.OAUTH == properties.authenticationType.getValue() ? properties.getJdbcProperties(OauthTokenUtils.getToken(properties.getOauthProperties())) : properties.getJdbcProperties()); } catch (Exception e) { if (e instanceof IllegalArgumentException) { throw IllegalArgumentException.class.cast(e); } else if(e.getMessage().contains("HTTP status=403")) { throw new IllegalArgumentException(e.getMessage(), e); } else { throw new IOException(e); } } }
Source:
<code><START> public void testHelp() throws Exception { <END> assertArrayEquals(new String[] { "", "jgit ls-files [-- path ...] [--help (-h)]", "", " --help (-h) : display this help text (default: true)", "", "", "" }, execute("git ls-files -h")); }</code><technical_language>This feels a change detector test. in is aiming defend against? E.g. if check output starts "jgit ls-files", sufficient</technical_language>

Target:
public void testHelp() throws Exception { String[] result = execute("git ls-files -h"); assertTrue(result[1].startsWith("jgit ls-files")); }
Source:
<code>private void initArticleHeaderView() { pageHeaderView.addOnLayoutChangeListener((View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) -> setWebViewPaddingTop()); pageHeaderView.setCallback(new PageHeaderView.Callback() { @Override public void onImageClicked() { if (getPage() != null && isLeadImageEnabled()) { String imageName = getPage().getPageProperties().getLeadImageName(); String imageUrl = getPage().getPageProperties().getLeadImageUrl(); if (imageName != null && imageUrl != null) { String filename = "File:" + imageName; WikiSite wiki = getTitle().getWikiSite(); getActivity().startActivityForResult(GalleryActivity.newIntent(getActivity(), parentFragment.getTitleOriginal(), filename, UriUtil.resolveProtocolRelativeUrl(imageUrl), wiki, GalleryFunnel.SOURCE_LEAD_IMAGE), Constants.ACTIVITY_REQUEST_GALLERY); } } } @Override public void onArticleCTAClicked() { <START> getActivity().startActivityForResult(DescriptionEditActivity.newIntent(getActivity(), isTranslation ? captionTargetPageTitle : captionSourcePageTitle, null, sourceSummary, targetSummary, isTranslation ? SUGGESTED_EDITS_TRANSLATE_CAPTION : SUGGESTED_EDITS_ADD_CAPTION), <END> ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT); } }); }</code><technical_language>sourceSummary.getPageTitle() targetSummary.getPageTitle() for PageTitle</technical_language>

Target:
private void initArticleHeaderView() { pageHeaderView.addOnLayoutChangeListener((View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) -> setWebViewPaddingTop()); pageHeaderView.setCallback(new PageHeaderView.Callback() { @Override public void onImageClicked() { if (getPage() != null && isLeadImageEnabled()) { String imageName = getPage().getPageProperties().getLeadImageName(); String imageUrl = getPage().getPageProperties().getLeadImageUrl(); if (imageName != null && imageUrl != null) { String filename = "File:" + imageName; WikiSite wiki = getTitle().getWikiSite(); getActivity().startActivityForResult(GalleryActivity.newIntent(getActivity(), parentFragment.getTitleOriginal(), filename, UriUtil.resolveProtocolRelativeUrl(imageUrl), wiki, GalleryFunnel.SOURCE_LEAD_IMAGE), Constants.ACTIVITY_REQUEST_GALLERY); } } } @Override public void onCallToActionClicked() { if (isTranslation ? (targetSummary != null && sourceSummary != null) : sourceSummary != null) { getActivity().startActivityForResult(DescriptionEditActivity.newIntent(getActivity(), isTranslation ? targetSummary.getPageTitle() : sourceSummary.getPageTitle(), null, sourceSummary, targetSummary, isTranslation ? SUGGESTED_EDITS_TRANSLATE_CAPTION : SUGGESTED_EDITS_ADD_CAPTION), ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT); } } }); }
Source:
<code>public void storeSettings() { int i = 0; <START> while (i < formatterListProperty.getValue().size()) { <END> if (formatterListProperty.getValue().get(i).getName().isEmpty()) { formatterListProperty.getValue().remove(i); } else { i++; } } List<String> names = new ArrayList<>(formatterListProperty.size()); List<String> formats = new ArrayList<>(formatterListProperty.size()); for (NameFormatterItemModel formatter : formatterListProperty) { names.add(formatter.getName()); formats.add(formatter.getFormat()); } preferences.putStringList(JabRefPreferences.NAME_FORMATER_KEY, names); preferences.putStringList(JabRefPreferences.NAME_FORMATTER_VALUE, formats); }</code><technical_language>Iterator remove entries in for loop (your code work indicies reshuffeled if remove entry. <LINK_0></technical_language>

Target:
public void storeSettings() { formatterListProperty.removeIf(formatter -> formatter.getName().isEmpty()); List<String> names = new ArrayList<>(formatterListProperty.size()); List<String> formats = new ArrayList<>(formatterListProperty.size()); for (NameFormatterItemModel formatterListItem : formatterListProperty) { names.add(formatterListItem.getName()); formats.add(formatterListItem.getFormat()); } preferences.putStringList(JabRefPreferences.NAME_FORMATER_KEY, names); preferences.putStringList(JabRefPreferences.NAME_FORMATTER_VALUE, formats); }
Source:
<code>public String getFromGetter() { if(!fromGetter.startsWith(PREFIX)) { return PREFIX + fromGetter; } return fromGetter; <START> } <END></code><technical_language>I this more straightforward test if getFromGetter() method read a differently named private field: java public final String fromGetter = "ACCESSED FIELD"; private String actuallyFromGetter; public Bean(..., String fromGetter) { ... this.actuallyFromGetter = fromGetter; } public String getFromGetter() { return actuallyFromGetter; } This expect stored in database, instead of munging it</technical_language>

Target:
public String getFromGetter() { return actuallyFromGetter; }
Source:
<code>public static SimpleModule getModule(final ObjectMapper mapper) { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { <START> if (BeanDeserializer.class.isAssignableFrom(deserializer.getClass())) { <END> return new FlatteningDeserializer(beanDesc.getBeanClass(), deserializer, mapper); } else { return deserializer; } } }); return module; }</code><technical_language>I if opening is good bad this point. is a bug in track1 kind of *caused* open-up (not really, previous class "@JsonFlatten" affected, will, bug) <LINK_1> this <LINK_0> risky if is unfixed unknown bug</technical_language>

Target:
public static SimpleModule getModule(final ObjectMapper mapper) { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { if (beanDesc.getBeanClass().getAnnotation(JsonFlatten.class) != null) { return new FlatteningDeserializer(beanDesc.getBeanClass(), deserializer, mapper); } else { return deserializer; } } }); return module; }
Source:
<code>private Object <START> setPropertyViewLabelProvider(SWTBotView <END> propertiesView) { Object oldLabelProvider; IPage currentPage = ((org.eclipse.ui.views.properties.PropertySheet) propertiesView.getReference().getView(false)).getCurrentPage(); Option<Object> valueOption = ReflectionHelper.getFieldValueWithoutException(currentPage, "registry"); assertTrue(valueOption.get() instanceof TabbedPropertyRegistry); TabbedPropertyRegistry tabbedPropertyRegistry = (TabbedPropertyRegistry) valueOption.get(); String contributorId = (String) ReflectionHelper.getFieldValueWithoutException(tabbedPropertyRegistry, "contributorId").get(); oldLabelProvider = ReflectionHelper.getFieldValueWithoutException(tabbedPropertyRegistry, "labelProvider").get(); Object newLabelProvider = null; if (DiagramUIPlugin.ID.equals(contributorId)) { newLabelProvider = new SiriusSheetLabelProvider(); } else if ("org.eclipse.sirius.table.ui.EditorID".equals(contributorId) || DTreeEditor.ID.equals(contributorId)) { newLabelProvider = new DTableLabelProvider(); } if (newLabelProvider != null) { ReflectionHelper.setFieldValueWithoutException(tabbedPropertyRegistry, "labelProvider", newLabelProvider); } return oldLabelProvider; }</code><technical_language>method currently set e new label provider checking if eef runtime is present. change provider if EEF runtime is present (see patch set 1). If present check explictly expected label provider for dialect. current patch force label provider: do test default behavior able detect a change this</technical_language>

Target:
private Object setPropertyViewLabelProvider(SWTBotView propertiesView) { Object oldLabelProvider = null; if (Platform.getBundle("org.eclipse.emf.eef.runtime") != null) { IPage currentPage = ((org.eclipse.ui.views.properties.PropertySheet) propertiesView.getReference().getView(false)).getCurrentPage(); Option<Object> valueOption = ReflectionHelper.getFieldValueWithoutException(currentPage, "registry"); assertTrue(valueOption.get() instanceof TabbedPropertyRegistry); TabbedPropertyRegistry tabbedPropertyRegistry = (TabbedPropertyRegistry) valueOption.get(); String contributorId = (String) ReflectionHelper.getFieldValueWithoutException(tabbedPropertyRegistry, "contributorId").get(); oldLabelProvider = ReflectionHelper.getFieldValueWithoutException(tabbedPropertyRegistry, "labelProvider").get(); Object newLabelProvider = null; if (DiagramUIPlugin.ID.equals(contributorId)) { newLabelProvider = new SiriusSheetLabelProvider(); } else if ("org.eclipse.sirius.table.ui.EditorID".equals(contributorId) || DTreeEditor.ID.equals(contributorId)) { newLabelProvider = new DTableLabelProvider(); } if (newLabelProvider != null) { ReflectionHelper.setFieldValueWithoutException(tabbedPropertyRegistry, "labelProvider", newLabelProvider); } } return oldLabelProvider; }
Source:
<code>public void testOnCheckAllAndOnClickCheckbox() { this.solo.clickOnCheckBox(0); this.solo.clickOnCheckBox(1); this.inst.waitForIdleSync(); CheckBox selectAll = (CheckBox) this.solo.getCurrentActivity().findViewById(R.id.select_all); <START> Assert.assertFalse(selectAll.isChecked()); <END> }</code><technical_language>I understand current functionality. If of cards(say card1) is checked, if 'select all' button is clicked, previously selected card1 unchecked? 'select all' select cards irrespective of previous selections</technical_language>

Target:
public void testOnCheckAllAndOnClickCheckbox() { this.solo.clickOnCheckBox(SELECT_ALL); this.solo.clickOnCheckBox(1); this.inst.waitForIdleSync(); CheckBox selectAll = (CheckBox) this.solo.getCurrentActivity().findViewById(R.id.select_all); Assert.assertFalse(selectAll.isChecked()); }
Source:
<code>public void passesValid() throws IOException { MatcherAssert.assertThat( new String( new CcStrict(new CcPlain()).encode( new Identity.Simple("urn:test:1") ) ), Matchers.equalTo("urn%3Atest%3A1") ); MatcherAssert.assertThat( new String( new CcStrict(new CcPlain()).encode( <START> new Identity.Simple("urn:test:1:1") <END> ) ), Matchers.equalTo("urn%3Atest%3A1%3A1") ); }</code><technical_language>@dmzaytsev test urn provided in original ticker: urn:test-domain-org:valid:1</technical_language>

Target:
public void passesValid() throws IOException { MatcherAssert.assertThat( new String( new CcStrict(new CcPlain()).encode( new Identity.Simple("urn:test:1") ) ), Matchers.equalTo("urn%3Atest%3A1") ); MatcherAssert.assertThat( new String( new CcStrict(new CcPlain()).encode( new Identity.Simple("urn:test-domain-org:valid:1") ) ), Matchers.equalTo("urn%3Atest-domain-org%3Avalid%3A1") ); }
Source:
<code>private boolean hasSelectedSingleNoteId() { <START> if (checkedCardCount() == 0) { <END> return true; } if (checkedCardCount() > 50) { return false; } Integer[] checkedPositions = mCheckedCardPositions.toArray(new Integer[0]); String firstId = mCards.get(checkedPositions[0]).get(NOTE); for (Integer position : checkedPositions) { String noteId = mCards.get(position).get(NOTE); if (noteId != firstId) { return false; } } return true; }</code><technical_language>This calls checkedCardCount() Also: previous code returned false</technical_language>

Target:
private boolean hasSelectedSingleNoteId() { int count = checkedCardCount(); if (count == 0 || count > 50) { return false; } Integer[] checkedPositions = mCheckedCardPositions.toArray(new Integer[0]); String firstId = mCards.get(checkedPositions[0]).get(NOTE); try { for (Integer position : checkedPositions) { String noteId = mCards.get(position).get(NOTE); if (noteId != firstId) { return false; } } } catch (IndexOutOfBoundsException e) { Timber.w(e, "concurrent modification of mCards array - assume more than one note selected"); return false; } return true; }