auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void onReceive(final Context context, Intent intent) { DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); Query query = new Query(); query.setFilterById(downloadId); Cursor c = dm.query(query); if (c.moveToFirst()) { int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { Uri filenameUri = Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))); final String filename = filenameUri.getPath(); if (StorageManager.shouldEncryptDecrypt(context, filename)) { new Thread() { @Override public void run() { try { CipherUtils.encryptFile(context, filename, true); } catch (Exception e) { <START> e.printStackTrace(); <END> } } }.start(); } } } } }</code><technical_language>e.printStackTrace(); remove instead Log.d(TAG, Log.getStackTraceString(e)). Define error level d,i,w..</technical_language>

Target:
public void onReceive(final Context context, Intent intent) { DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); Query query = new Query(); query.setFilterById(downloadId); Cursor c = dm.query(query); if (c.moveToFirst()) { int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { Uri filenameUri = Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))); final String filename = filenameUri.getPath(); if (StorageManager.shouldEncryptDecrypt(context, filename)) { new Thread() { @Override public void run() { try { CipherUtils.encryptFile(context, filename, true); } catch (Exception e) { Log.d(TAG, Log.getStackTraceString(e)); } } }.start(); } } } } }
Source:
<code>public String toString() { <START> return systemName + "/" + clientId + "/" + super.toString(); <END> }</code><technical_language>a more explicit string (e.g. "systemName={} clientId={}" etc) instead of making users figure out "/" separated parts are. Also, included in super.toString</technical_language>

Target:
public String toString() { return String.format("%s:%s", systemName, clientId); }
Source:
<code>private boolean validateImagesAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; boolean imageAvailable = false; <START> for (Guid storageDomainId : image.getStorageIds()) { <END> DiskImage fromIrs = null; try { fromIrs = (DiskImage) runVdsCommand(VDSCommandType.GetImageInfo, new GetImageInfoVDSCommandParameters(getStoragePool().getId(), storageDomainId, imageGroupId, image.getImageId())).getReturnValue(); } catch (Exception e) { log.debug("Unable to get image info from storage", e); } if (fromIrs == null) { log.warn("Disk image '{}/{}' doesn't exist on storage domain '{}'", imageGroupId, image.getImageId(), storageDomainId); } else { imageAvailable = true; } } if (!imageAvailable) { if (getParameters().isAllowPartialImport()) { log.warn("Disk image '{}/{}' doesn't exist on any of its storage domains. " + "Ignoring since the force flag in on", imageGroupId, image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } else { return failValidation(EngineMessage.TEMPLATE_IMAGE_NOT_EXIST); } } } return true; }</code><technical_language>please refactor loop another method, code more clear</technical_language>

Target:
private boolean validateImagesAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; if (!validateImageAvailability(image, imageGroupId)) { if (getParameters().isAllowPartialImport()) { log.warn("Disk image '{}/{}' doesn't exist on any of its storage domains. " + "Ignoring since the force flag in on", imageGroupId, image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } else { return failValidation(EngineMessage.TEMPLATE_IMAGE_NOT_EXIST); } } } return true; }
Source:
<code>public String toString() { <START> return "BootstrapSession [endpoint=" + endpoint + ", clientIdentity=" + clientIdentity + ", authenticated=" <END> + authenticated + "]"; }</code><technical_language>String format</technical_language>

Target:
public String toString() { return String.format("BootstrapSession [endpoint=%s, clientIdentity=%s, authorized=%s]", endpoint, clientIdentity, authorized); }
Source:
<code>public LocationHandle forExistingTable(SemiTransactionalHiveMetastore metastore, ConnectorSession session, Table table) { HdfsContext context = new HdfsContext(session, table.getDatabaseName(), table.getTableName()); Path targetPath = new Path(table.getStorage().getLocation()); <START> if (table.isTemporary()) { <END> return new LocationHandle(targetPath, targetPath, true, DIRECT_TO_TARGET_EXISTING_DIRECTORY, true); } return createLocationHandle(context, session, targetPath, true); }</code><technical_language>push this createLocationHandle</technical_language>

Target:
public LocationHandle forExistingTable(SemiTransactionalHiveMetastore metastore, ConnectorSession session, Table table) { HdfsContext context = new HdfsContext(session, table.getDatabaseName(), table.getTableName()); Path targetPath = new Path(table.getStorage().getLocation()); return createLocationHandle(context, session, targetPath, EXISTING); }
Source:
<code>public static void setMenuIconSize(View contentView, Rect desiredIconSize) { if (!isLargeSize()) { return; } ViewGroup content = (ViewGroup) contentView; for (int i = 0; i < content.getChildCount(); i++) { View child = content.getChildAt(i); <START> if (child instanceof LinearLayout || child instanceof RelativeLayout || child instanceof ScrollView) { <END> setMenuIconSize(child, desiredIconSize); } else if (child instanceof Button) { Button button = (Button) child; Drawable drawable = button.getCompoundDrawables()[0]; drawable.setBounds(desiredIconSize); button.setCompoundDrawables(drawable, null, null, null); } } }</code><technical_language>check for instanceof ViewGroup here? LinearLayout, RelativeLayout etc. ViewGroups I called recursively? E.g. RecyclerView missing in this check.. ViewGroup worry other container views</technical_language>

Target:
public static void setMenuIconSize(View contentView, Rect desiredIconSize) { if (!isLargeSize()) { return; } ViewGroup content = (ViewGroup) contentView; for (int i = 0; i < content.getChildCount(); i++) { View child = content.getChildAt(i); if (child instanceof ViewGroup) { setMenuIconSize(child, desiredIconSize); } else if (child instanceof Button) { Button button = (Button) child; Drawable drawable = button.getCompoundDrawables()[0]; drawable.setBounds(desiredIconSize); button.setCompoundDrawables(drawable, null, null, null); } } }
Source:
<code>public static boolean isLengthValid(Logger logger, short responseCommand, byte[] thisResponseData, int requiredResponseDataLength) { logger.trace("isLengthValid() called for ({}) with bytes of data.", Command.get(responseCommand).toString(), new CommandNumber(responseCommand).toString(), thisResponseData.length); if (thisResponseData.length != requiredResponseDataLength) { logger.warn( "Gateway response ({}) consists of a malformed packet (effective length is {}, required length is {}).", Command.get(responseCommand).toString(), new CommandNumber(responseCommand).toString(), thisResponseData.length, requiredResponseDataLength); return false; <START> } else { <END> logger.trace("isLengthValid() returns {}.", true); return true; } }</code><technical_language>else is redundant</technical_language>

Target:
public static boolean isLengthValid(Logger logger, short responseCommand, byte[] thisResponseData, int requiredResponseDataLength) { logger.trace("isLengthValid() called for ({}) with bytes of data.", Command.get(responseCommand).toString(), new CommandNumber(responseCommand).toString(), thisResponseData.length); if (thisResponseData.length != requiredResponseDataLength) { logger.warn( "Gateway response ({}) consists of a malformed packet (effective length is {}, required length is {}).", Command.get(responseCommand).toString(), new CommandNumber(responseCommand).toString(), thisResponseData.length, requiredResponseDataLength); return false; } logger.trace("isLengthValid() returns {}.", true); return true; }
Source:
<code>private void parsedReadWriteQueryPct(String readWriteQueryPct) { String[] readWriteQueryPctList = readWriteQueryPct.split(","); if (readWriteQueryPctList.length == 3) { try { if (Integer.valueOf(readWriteQueryPctList[0]) + Integer.valueOf(readWriteQueryPctList[1]) + Integer.valueOf(readWriteQueryPctList[2]) == 100) { readPct = Integer.valueOf(readWriteQueryPctList[0]); writePct = Integer.valueOf(readWriteQueryPctList[1]); queryPct = Integer.valueOf(readWriteQueryPctList[2]); } else { logger.warn(PERCENT_PARSING_ERROR, readPct, writePct, queryPct); } } catch (NumberFormatException ex) { logger.warn(PERCENT_PARSING_ERROR, readPct, writePct, queryPct); } } else { logger.warn(PERCENT_PARSING_ERROR, readPct, writePct, queryPct); <START> } <END> }</code><technical_language>if input config is valid, log error terminate? invalid config unnoticed. I throwing exception invalid config</technical_language>

Target:
private void parsedReadWriteQueryPct(String readWriteQueryPct) { String[] readWriteQueryPctList = readWriteQueryPct.split(","); if (readWriteQueryPctList.length == 3) { try { if (Integer.valueOf(readWriteQueryPctList[0]) + Integer.valueOf(readWriteQueryPctList[1]) + Integer.valueOf(readWriteQueryPctList[2]) == 100) { readPct = Integer.valueOf(readWriteQueryPctList[0]); writePct = Integer.valueOf(readWriteQueryPctList[1]); queryPct = Integer.valueOf(readWriteQueryPctList[2]); } else { throw new IllegalArgumentException(PERCENT_PARSING_ERROR + readWriteQueryPct); } } catch (NumberFormatException ex) { throw new IllegalArgumentException(PERCENT_PARSING_ERROR + readWriteQueryPct); } } else { throw new IllegalArgumentException(PERCENT_PARSING_ERROR + readWriteQueryPct); } }
Source:
<code>public List<OntClass> listRelated(OntClass cls) { List<OntClass> range = new ArrayList<>(); cls.listDeclaredProperties().toList().stream() <START> .filter(OntProperty::isObjectProperty) <END> .forEach(prop -> { prop.listRange().toList().forEach(ontRes -> { range.add(ontology.getOntClass(ontRes.getURI())); }); }); return range; }</code><technical_language>filter OntProperty yield results</technical_language>

Target:
public Set<Pair<ObjectProperty, OntClass>> listRelated(OntClass cls) { Set<Pair<ObjectProperty, OntClass>> range = new HashSet<>(); listObjectProperties(cls).stream().forEach(prop -> range.addAll(getRange(prop).stream() .map(rcls -> Pair.of(prop, rcls)) .collect(Collectors.toSet()))); return range; }
Source:
<code><START> private static byte[] convertFileToByte(String xmlFilePath) <END> { FileInputStream fileInputStream=null; File file = new File(xmlFilePath); byte[] bFile = new byte[(int) file.length()]; try { fileInputStream = new FileInputStream(file); fileInputStream.read(bFile); fileInputStream.close(); }catch(Exception e){ e.printStackTrace(); } return bFile; }</code><technical_language>replace this method by... > ByteArrayOutputStream os = new ByteArrayOutputStream(); > Utils.copyStream ( new File(xmlFilePath), os ); > return os.toByteArray();</technical_language>

Target:
private byte[] convertFileToByte(String xmlFilePath) { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { Utils.copyStream ( new File(xmlFilePath), os ); } catch (IOException e) { this.logger.severe( e.getMessage() ); } return os.toByteArray(); }
Source:
<code>public final void authenticateURN() { final AuthKeys authKeys = new AuthKeys(); final String user = "urn:git:rultor"; final String password = "test"; MatcherAssert.assertThat( <START> authKeys.authenticate(user, password) <END> .name(), Matchers.equalTo(Identity.ANONYMOUS.name()) ); }</code><technical_language>happened indentation? Matchers.equalTo() is indented 8 chars instead of 4</technical_language>

Target:
public final void authenticateURN() throws Exception { final AuthKeys authKeys = new AuthKeys(); MatcherAssert.assertThat( authKeys.authenticate("urn:git:rultor", "test").name(), Matchers.equalTo(Identity.ANONYMOUS.name()) ); }
Source:
<code>public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) { if (!isValidIp(ipAddress)) { return false; } if (!isValidCIDR(cidr)) { return false; } final SubnetUtils subnetUtils = new SubnetUtils(cidr); subnetUtils.setInclusiveHostCount(true); final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress); <START> return !isInRange; <END> }</code><technical_language>reverse this return @kansal ? I missed in itteration</technical_language>

Target:
public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) { if (!isValidIp(ipAddress)) { return false; } if (!isValidCIDR(cidr)) { return false; } final SubnetUtils subnetUtils = new SubnetUtils(cidr); subnetUtils.setInclusiveHostCount(true); final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress); return isInRange; }
Source:
<code>protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); String nextUrl = getRequestParamValue(Const.ParamsNames.NEXT_URL); Assumption.assertNotNull(courseId); Assumption.assertNotNull(feedbackSessionName); nextUrl = nextUrl == null ? Const.ActionURIs.INSTRUCTOR_FEEDBACKS_PAGE : nextUrl; new GateKeeper().verifyAccessible( logic.getInstructorForGoogleId(courseId, account.googleId), logic.getFeedbackSession(feedbackSessionName, courseId), false, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); logic.deleteFeedbackSession(feedbackSessionName, courseId); statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_SESSION_DELETED, StatusMessageColor.SUCCESS)); statusToAdmin = "Feedback Session <span class=\"bold\">[" + feedbackSessionName + "]</span> " + "from Course: <span class=\"bold\">[" + courseId + " deleted."; <START> nextUrl = nextUrl == null ? Const.ActionURIs.INSTRUCTOR_FEEDBACKS_PAGE : nextUrl; <END> return createRedirectResult(nextUrl); }</code><technical_language>This repeated above, line 22</technical_language>

Target:
protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); String nextUrl = getRequestParamValue(Const.ParamsNames.NEXT_URL); Assumption.assertNotNull(courseId); Assumption.assertNotNull(feedbackSessionName); nextUrl = nextUrl == null ? Const.ActionURIs.INSTRUCTOR_FEEDBACKS_PAGE : nextUrl; new GateKeeper().verifyAccessible( logic.getInstructorForGoogleId(courseId, account.googleId), logic.getFeedbackSession(feedbackSessionName, courseId), false, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); logic.deleteFeedbackSession(feedbackSessionName, courseId); statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_SESSION_DELETED, StatusMessageColor.SUCCESS)); statusToAdmin = "Feedback Session <span class=\"bold\">[" + feedbackSessionName + "]</span> " + "from Course: <span class=\"bold\">[" + courseId + " deleted."; return createRedirectResult(nextUrl); }
Source:
<code>private int getLocalAdminPort(IPod pod) { <START> return PortForwardingUtils.getForwardablePorts(pod).stream().filter(p -> p.getRemotePort() == 9999) <END> .mapToInt(p -> p.getLocalPort()).findAny().orElse(9999); }</code><technical_language>pelase extract this a constant (in OpenShiftDebugUtils?) (re)use in - - OpenShiftLaunchController - OpenShiftDebugUtils</technical_language>

Target:
private int getLocalAdminPort(IPod pod) { return PortForwardingUtils.getForwardablePorts(pod).stream().filter(p -> p.getRemotePort() == OpenShiftDebugUtils.NATIVE_MANAGMENT_PORT) .mapToInt(p -> p.getLocalPort()).findAny().orElse(OpenShiftDebugUtils.NATIVE_MANAGMENT_PORT); }
Source:
<code>public Builder(CircuitBreakerConfig baseConfig) { this.waitDurationInOpenState = baseConfig.waitDurationInOpenState; this.permittedNumberOfCallsInHalfOpenState = baseConfig.permittedNumberOfCallsInHalfOpenState; this.slidingWindowSize = baseConfig.slidingWindowSize; this.slidingWindowType = baseConfig.slidingWindowType; this.minimumNumberOfCalls = baseConfig.minimumNumberOfCalls; this.failureRateThreshold = baseConfig.failureRateThreshold; this.ignoreExceptions = baseConfig.ignoreExceptions; this.recordExceptions = baseConfig.recordExceptions; this.recordExceptionPredicate = baseConfig.recordExceptionPredicate; this.ignoreExceptionPredicate = baseConfig.ignoreExceptionPredicate; this.automaticTransitionFromOpenToHalfOpenEnabled = baseConfig.automaticTransitionFromOpenToHalfOpenEnabled; this.slowCallRateThreshold = baseConfig.slowCallRateThreshold; this.slowCallDurationThreshold = baseConfig.slowCallDurationThreshold; <START> this.disableStackTraces = baseConfig.disableStackTraces; <END> }</code><technical_language>rename writableStackTraceEnabled set true default in order compatible</technical_language>

Target:
public Builder(CircuitBreakerConfig baseConfig) { this.waitDurationInOpenState = baseConfig.waitDurationInOpenState; this.permittedNumberOfCallsInHalfOpenState = baseConfig.permittedNumberOfCallsInHalfOpenState; this.slidingWindowSize = baseConfig.slidingWindowSize; this.slidingWindowType = baseConfig.slidingWindowType; this.minimumNumberOfCalls = baseConfig.minimumNumberOfCalls; this.failureRateThreshold = baseConfig.failureRateThreshold; this.ignoreExceptions = baseConfig.ignoreExceptions; this.recordExceptions = baseConfig.recordExceptions; this.recordExceptionPredicate = baseConfig.recordExceptionPredicate; this.ignoreExceptionPredicate = baseConfig.ignoreExceptionPredicate; this.automaticTransitionFromOpenToHalfOpenEnabled = baseConfig.automaticTransitionFromOpenToHalfOpenEnabled; this.slowCallRateThreshold = baseConfig.slowCallRateThreshold; this.slowCallDurationThreshold = baseConfig.slowCallDurationThreshold; this.writableStackTraceEnabled = baseConfig.writableStackTraceEnabled; }
Source:
<code>public String toString() { <START> return "Pool[id: " + getId() + ", owner: " + ((owner == null) ? "null" : owner.getId()) + <END> ", product: " + productId + ", quantity: " + getQuantity() + ", expires: " + getEndDate() + "]"; }</code><technical_language>I owner a solid toString, more useful do more this: java return "Pool[id: " + getId() + ", owner: " + owner + need "owner: ", owner.toString returns java return "Owner [id: " + getId() + ", key: " + getKey() + "]"; null alone. (that happen else is wrong, safe allowing it)</technical_language>

Target:
public String toString() { return "Pool[id: " + getId() + ", owner: " + owner + ", product: " + productId + ", quantity: " + getQuantity() + ", expires: " + getEndDate() + "]"; }
Source:
<code>public boolean validate(String definition) { boolean isValid = false; try { SchemaParser schemaParser = new SchemaParser(); TypeDefinitionRegistry typeRegistry = schemaParser.parse(definition); GraphQLSchema graphQLSchema = UnExecutableSchemaGenerator.makeUnExecutableSchema(typeRegistry); SchemaValidator schemaValidation = new SchemaValidator(); Set<SchemaValidationError> validationErrors = schemaValidation.validateSchema(graphQLSchema); isValid = (validationErrors.toArray().length == 0); } catch (SchemaProblem e) { <START> log.error("Unable to parse the GraphQL definition", e); <END> } return isValid; }</code><technical_language>exception thrown in here</technical_language>

Target:
public boolean validate(String definition) throws DefinitionValidationException { boolean isValid; try { SchemaParser schemaParser = new SchemaParser(); TypeDefinitionRegistry typeRegistry = schemaParser.parse(definition); GraphQLSchema graphQLSchema = UnExecutableSchemaGenerator.makeUnExecutableSchema(typeRegistry); SchemaValidator schemaValidation = new SchemaValidator(); Set<SchemaValidationError> validationErrors = schemaValidation.validateSchema(graphQLSchema); isValid = (validationErrors.toArray().length == 0); } catch (SchemaProblem e) { throw new DefinitionValidationException("Unable to parse the GraphQL definition", e); } return isValid; }
Source:
<code>private void cleanUp() throws IOException { if (!packageUpdater.nodeModulesFolder.exists()) { return; } File modulesYaml = new File(packageUpdater.nodeModulesFolder, MODULES_YAML); boolean hasModulesYaml = modulesYaml.exists() && modulesYaml.isFile(); if (!enablePnpm && hasModulesYaml) { FileUtils.forceDelete(packageUpdater.nodeModulesFolder); } else if (enablePnpm && !hasModulesYaml) { File staging = new File(".staging"); if (!staging.isDirectory() || staging.listFiles( <START> (dir, name) -> name.startsWith("pnpm-")).length == 0) { <END> FileUtils.forceDelete(packageUpdater.nodeModulesFolder); } } }</code><technical_language>![INFO](<LINK_1> 'Severity: INFO') null pointer dereference in com.vaadin.flow.server.frontend.TaskRunNpmInstall.cleanUp() due return of called method [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private void cleanUp() throws IOException { if (!packageUpdater.nodeModulesFolder.exists()) { return; } File modulesYaml = new File(packageUpdater.nodeModulesFolder, MODULES_YAML); boolean hasModulesYaml = modulesYaml.exists() && modulesYaml.isFile(); if (!enablePnpm && hasModulesYaml) { FileUtils.forceDelete(packageUpdater.nodeModulesFolder); } else if (enablePnpm && !hasModulesYaml) { File staging = new File(packageUpdater.nodeModulesFolder, ".staging"); if (!staging.isDirectory() || staging.listFiles( (dir, name) -> name.startsWith("pnpm-")).length == 0) { FileUtils.forceDelete(packageUpdater.nodeModulesFolder); } } }
Source:
<code><START> protected TreeSet<CClassType> getTypes() { <END> TreeSet<CClassType> t = new TreeSet<>(Comparator.comparing(CClassType::getFQCN)); for(FullyQualifiedClassName type : types) { try { t.add(CClassType.get(type)); } catch (ClassNotFoundException ex) { throw new Error(ex); } } return t; }</code><technical_language>[Dependency Inversion](<LINK_0> is preferred approach here, want return Set, Set lhs of assignment</technical_language>

Target:
protected Set<CClassType> getTypes() { Set<CClassType> t = new TreeSet<>(Comparator.comparing(CClassType::getFQCN)); for(FullyQualifiedClassName type : types) { try { t.add(CClassType.get(type)); } catch (ClassNotFoundException ex) { throw new Error(ex); } } return t; }
Source:
<code>public void start() { try { coreContainer = (CoreContainer) getHelped().getContext() .getAttributes().get("CoreContainer"); if (coreContainer == null) { String directory = getHelped().getContext().getParameters() .getFirstValue("directory"); String configFile = getHelped().getContext().getParameters() .getFirstValue("configFile"); if (directory != null && configFile != null) { File config = new File(configFile); if (!config.exists()) { config = new File(new URI(configFile)); } <START> coreContainer = CoreContainer.createAndLoad(Paths.get(directory), config.toPath()); <END> } } if (coreContainer == null) { throw new RuntimeException( "Could not initialize core container"); } } catch (Exception e) { throw new RuntimeException("Could not initialize core container", e); } }</code><technical_language>pretty get a path a URI a File. Is config elsewhere</technical_language>

Target:
public void start() { try { coreContainer = (CoreContainer) getHelped().getContext() .getAttributes().get("CoreContainer"); if (coreContainer == null) { String directory = getHelped().getContext().getParameters() .getFirstValue("directory"); String configFile = getHelped().getContext().getParameters() .getFirstValue("configFile"); if (directory != null && configFile != null) { Path configPath = Paths.get(configFile); if (configPath.toFile().exists()) { coreContainer = CoreContainer.createAndLoad(Paths.get(directory), configPath); } else { coreContainer = CoreContainer.createAndLoad(Paths.get(directory), Paths.get(new URI(configFile))); } } } if (coreContainer == null) { throw new RuntimeException( "Could not initialize core container"); } } catch (Exception e) { throw new RuntimeException("Could not initialize core container", e); } }
Source:
<code>public RecoveryTestClusterManager getClusterMap() throws IOException { if (recoveryTestClusterManagerRef.get() == null) { StaticClusterManager staticClusterManager = staticClusterAgentsFactory.getClusterMap(); HelixClusterManager helixClusterManager = null; try { helixClusterManager = helixClusterAgentsFactory.getClusterMap(); <START> } catch (Exception e) { <END> logger.error("Helix cluster manager instantiation failed with exception", e); } recoveryTestClusterManagerRef.compareAndSet(null, new RecoveryTestClusterManager(staticClusterManager, helixClusterManager)); } return recoveryTestClusterManagerRef.get(); }</code><technical_language>If is exception helix cluster manager, terminate startup</technical_language>

Target:
public RecoveryTestClusterManager getClusterMap() throws IOException { if (recoveryTestClusterManagerRef.get() == null) { StaticClusterManager staticClusterManager = staticClusterAgentsFactory.getClusterMap(); HelixClusterManager helixClusterManager = null; try { helixClusterManager = helixClusterAgentsFactory.getClusterMap(); } catch (Exception e) { logger.error("Helix cluster manager instantiation failed with exception", e); throw new IOException( String.format("Helix cluster manager instantiation failed with exception %s", e.getMessage())); } recoveryTestClusterManagerRef.compareAndSet(null, new RecoveryTestClusterManager(staticClusterManager, helixClusterManager)); } return recoveryTestClusterManagerRef.get(); }
Source:
<code>private void consumeDurability(ItemStack stack, World world, BlockState state, BlockPos pos, LivingEntity living) { <START> if((double)state.getBlockHardness(world, pos)!=0.0D) <END> { int dmg = ForgeHooks.isToolEffective(world, pos, stack)||isEffective(stack, state.getMaterial())?1: 3; ItemStack sawblade = getSawblade(stack); if(!sawblade.isEmpty()) { if(!getUpgrades(stack).getBoolean("oiled")||Utils.RAND.nextInt(4)==0) sawblade.damageItem(dmg, living, (entity) -> entity.sendBreakAnimation(Hand.MAIN_HAND)); this.setSawblade(stack, sawblade); IFluidHandler handler = FluidUtil.getFluidHandler(stack).orElseThrow(RuntimeException::new); handler.drain(1, FluidAction.EXECUTE); Triple<ItemStack, ShaderRegistryEntry, ShaderCase> shader = ShaderRegistry.getStoredShaderAndCase(stack); if(shader!=null) shader.getMiddle().getEffectFunction().execute(world, shader.getLeft(), stack, shader.getRight().getShaderType().toString(), new Vec3d(pos.getX()+.5, pos.getY()+.5, pos.getZ()+.5), null, .375f); } } }</code><technical_language>cast double strange</technical_language>

Target:
private void consumeDurability(ItemStack stack, World world, BlockState state, BlockPos pos, LivingEntity living) { if(state.getBlockHardness(world, pos)!=0.0f) { int dmg = ForgeHooks.isToolEffective(world, pos, stack)||isEffective(stack, state.getMaterial())?1: 3; ItemStack sawblade = getSawblade(stack); if(!sawblade.isEmpty()) { if(!getUpgrades(stack).getBoolean("oiled")||Utils.RAND.nextInt(4)==0) sawblade.damageItem(dmg, living, (entity) -> entity.sendBreakAnimation(Hand.MAIN_HAND)); this.setSawblade(stack, sawblade); IFluidHandler handler = FluidUtil.getFluidHandler(stack).orElseThrow(RuntimeException::new); handler.drain(1, FluidAction.EXECUTE); Triple<ItemStack, ShaderRegistryEntry, ShaderCase> shader = ShaderRegistry.getStoredShaderAndCase(stack); if(shader!=null) shader.getMiddle().getEffectFunction().execute(world, shader.getLeft(), stack, shader.getRight().getShaderType().toString(), new Vec3d(pos.getX()+.5, pos.getY()+.5, pos.getZ()+.5), null, .375f); } } }
Source:
<code><START> private void runDistcp(Path from, Path to) throws Exception { <END> info("source: " + from); info("destination: " + to); EmbeddedGobblin embeddedGobblin = new EmbeddedGobblinDistcp(from, to).mrMode(); embeddedGobblin.distributeJar("lib/*"); for (Map.Entry<String, String> entry : this.props.entrySet()) { if (entry.getKey() != null && (entry.getKey()).startsWith("distcpConf.")) { String key = (entry.getKey()).substring("distcpConf.".length()); embeddedGobblin.setConfiguration(key, entry.getValue()); } } JobExecutionResult result = embeddedGobblin.run(); if (!result.isSuccessful()) { throw new RuntimeException("Distcp job failed!", result.getErrorCause()); } }</code><technical_language>add log message before/after distcp? logs useful measure running time of distcp for colo, print running time of distcp well</technical_language>

Target:
private void runDistcp(Path from, Path to) throws Exception { info("sourcePath: " + from + ", destinationPath: " + to); EmbeddedGobblin embeddedGobblin = new EmbeddedGobblinDistcp(from, to).mrMode(); embeddedGobblin.distributeJar("lib/*"); for (Map.Entry<String, String> entry : this.props.entrySet()) { if (entry.getKey() != null && (entry.getKey()).startsWith(ATTR_PREFIX)) { String key = (entry.getKey()).substring(ATTR_PREFIX.length()); embeddedGobblin.setConfiguration(key, entry.getValue()); } } JobExecutionResult result = embeddedGobblin.run(); if (!result.isSuccessful()) { throw new RuntimeException("Distcp job failed!", result.getErrorCause()); } }
Source:
<code>public void testGeneratedClassName() { PageFunctionCompiler functionCompiler = new PageFunctionCompiler(createTestMetadataManager(), 0); String dateTimePattern = "YYYYMMdd_HHmmss_SSS"; String planNodeId = "7"; String stageId = "20170707_223500_67496_zguwn.2"; String classSuffix = stageId + "_" + planNodeId; Supplier<PageProjection> projectionSupplier = functionCompiler.compileProjection(ADD_10_EXPRESSION, Optional.of(classSuffix)); PageProjection projection = projectionSupplier.get(); Work<Block> work = projection.project(SESSION, new DriverYieldSignal(), createLongBlockPage(0), SelectedPositions.positionsRange(0, 1)); String className = work.getClass().getSimpleName(); assertTrue(className.startsWith("PageProjectionWork_" + stageId.replace('.', '_') + "_" + planNodeId)); <START> DateTimeFormat.forPattern(dateTimePattern).parseDateTime(className.substring(className.length() - dateTimePattern.length())); <END> }</code><technical_language>this check? parse succeed throwing exception? do parse date time assert <= current timestmap? @haozhun</technical_language>

Target:
public void testGeneratedClassName() { PageFunctionCompiler functionCompiler = new PageFunctionCompiler(createTestMetadataManager(), 0); String planNodeId = "7"; String stageId = "20170707_223500_67496_zguwn.2"; String classSuffix = stageId + "_" + planNodeId; Supplier<PageProjection> projectionSupplier = functionCompiler.compileProjection(ADD_10_EXPRESSION, Optional.of(classSuffix)); PageProjection projection = projectionSupplier.get(); Work<Block> work = projection.project(SESSION, new DriverYieldSignal(), createLongBlockPage(0), SelectedPositions.positionsRange(0, 1)); assertTrue(work.getClass().getSimpleName().startsWith("PageProjectionWork_" + stageId.replace('.', '_') + "_" + planNodeId)); }
Source:
<code>private Object getEntityFieldAsObject(JsonNode parentNode, String fieldName) { JsonNode valueNode = parentNode.get(fieldName); <START> if (!TablesConstants.METADATA_KEYS.contains(fieldName) <END> && !fieldName.endsWith(TablesConstants.ODATA_TYPE_KEY_SUFFIX)) { JsonNode typeNode = parentNode.get(fieldName + TablesConstants.ODATA_TYPE_KEY_SUFFIX); if (typeNode != null) { String typeString = typeNode.asText(); EntityDataModelType type = EntityDataModelType.parse(typeString); if (type != null) { try { return type.deserialize(valueNode.asText()); } catch (Exception e) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "'%s' value is not a valid %s.", fieldName, type.getEdmType()), e)); } } else { logger.warning(String.format("'%s' value has unknown OData type %s", fieldName, typeString)); } } } return valueNode.asText(); }</code><technical_language>multi nested if loops is hard reason about.. is flatten return early? java if (TablesConstants.METADATA_KEYS.contains(fieldName) .... ) { return valueNode.asText(); }</technical_language>

Target:
private Object getEntityFieldAsObject(JsonNode parentNode, String fieldName) throws IOException { JsonNode valueNode = parentNode.get(fieldName); if (TablesConstants.METADATA_KEYS.contains(fieldName) || fieldName.endsWith(TablesConstants.ODATA_TYPE_KEY_SUFFIX)) { return serializer().treeToValue(valueNode, Object.class); } JsonNode typeNode = parentNode.get(fieldName + TablesConstants.ODATA_TYPE_KEY_SUFFIX); if (typeNode == null) { return serializer().treeToValue(valueNode, Object.class); } String typeString = typeNode.asText(); EntityDataModelType type = EntityDataModelType.fromString(typeString); if (type == null) { logger.warning(String.format("'%s' value has unknown OData type %s", fieldName, typeString)); return serializer().treeToValue(valueNode, Object.class); } try { return type.deserialize(valueNode.asText()); } catch (Exception e) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "'%s' value is not a valid %s.", fieldName, type.getEdmType()), e)); } }
Source:
<code>public void unparse(SqlWriter writer, int leftPrec, int rightPrec) { writer.getDialect().unparseDataType(writer, this, leftPrec, rightPrec); <START> } <END></code><technical_language>modify this method ? match CAST expression in SqlDialect#unparseCall method, unparse SqlDataTypeSpec specifically(have a default implementation invoke method unparseDataType defined.) want SqlNode kinds of SqlDialect</technical_language>

Target:
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) { typeNameSpec.unparse(writer, leftPrec, rightPrec); }
Source:
<code>private Set<String> itemIds( Iterable<com.metabroadcast.atlas.glycerin.model.Broadcast> nitroBroadcasts) { return ImmutableSet.copyOf(Iterables.transform( nitroBroadcasts, new Function<com.metabroadcast.atlas.glycerin.model.Broadcast, String>() { @Override <START> public String apply(com.metabroadcast.atlas.glycerin.model.Broadcast input) { <END> return NitroUtil.programmePid(input).getPid(); } } )); }</code><technical_language>I write .map(ModelAndPayload::getModel) .map(Item::getContainer) .filter(Objects::nonNull) .map(Container::getUri) save (slightly confusing) extra method) (Obviously put extra filter(Objects::nonNull) in required)</technical_language>

Target:
private Set<String> itemIds( Iterable<com.metabroadcast.atlas.glycerin.model.Broadcast> nitroBroadcasts) { return ImmutableSet.copyOf(Iterables.transform( nitroBroadcasts, input -> NitroUtil.programmePid(input).getPid() )); }
Source:
<code>public void tapOnWebElement(By locator, int index, int duration, int waitAfter) { JavascriptExecutor js = (JavascriptExecutor) driver; WebElement element; if (index > 0) { List<WebElement> elements = driver.findElements(locator); element = elements.get(index); } else { element = driver.findElement(locator); } int elementStartPointX = element.getLocation().getX(); int elementHeight = element.getSize().getHeight(); int elementWidth = element.getSize().getHeight(); int offSetY = loadedPageHeight - element.getLocation().getY() - appWebviewHeight; if (offSetY < 0) { offSetY = -offSetY; } else { offSetY = 0; } js.executeScript("window.scrollTo(0, "+element.getLocation().getY()+")"); int pointX = (elementStartPointX + (elementWidth / 2)) * ratio; int pointY = (taskbarWebviewHeight + (elementHeight / 2) + offSetY) * ratio; <START> if (mobileDriver.getContext() != "NATIVE_APP") { <END> mobileDriver.context("NATIVE_APP"); } try { mobileDriver.tap(1, pointX, pointY, duration); } catch (Exception e) try { Thread.sleep(waitAfter); } catch (Exception e) if (mobileDriver.getContext() != "NATIVE_APP") { mobileDriver.context("NATIVE_APP"); } }</code><technical_language>if a String comparison, needs .equals() Right now, this comparison hold true trigger next statement</technical_language>

Target:
public void tapOnWebElement(By locator, int index, int duration, int waitAfter) { String methodName = "tapOnWebElement"; JavascriptExecutor js = (JavascriptExecutor) driver; WebElement element; if (index > 0) { List<WebElement> elements = driver.findElements(locator); element = elements.get(index); } else { element = driver.findElement(locator); } int elementStartPointX = element.getLocation().getX(); int elementHeight = element.getSize().getHeight(); int elementWidth = element.getSize().getHeight(); int offSetY = loadedPageHeight - element.getLocation().getY() - appWebviewHeight; if (offSetY < 0) { offSetY = -offSetY; } else { offSetY = 0; } js.executeScript("window.scrollTo(0, "+element.getLocation().getY()+")"); int pointX = (elementStartPointX + (elementWidth / 2)) * ratio; int pointY = (taskbarWebviewHeight + (elementHeight / 2) + offSetY) * ratio; switchToContext(CONTEXT_NATIVE_APP, methodName); mobileDriver.tap(1, pointX, pointY, duration); waitForFinish(waitAfter, methodName); switchToContext(CONTEXT_WEBVIEW_1, methodName); }
Source:
<code>public List<ResolutionMethod> getValidResolutions() { List<ResolutionMethod> toReturn = new ArrayList<ResolutionMethod>(); List<String> attributes = artifact.getAttributeValues(CoreAttributeTypes.GeneralStringData); String resolutionsJson = "[]"; for (String attribute : attributes) { if (attribute.startsWith("RESOLUTION_METHODS")) { resolutionsJson = attribute.replaceFirst("RESOLUTION_METHODS=", ""); break; } } try { JSONArray jArray = DispoUtil.asJSONArray(resolutionsJson); for (int i = 0; i < jArray.length(); i++) { JSONObject resolutionMethodJObject = jArray.getJSONObject(i); ResolutionMethod method = DispoUtil.jsonObjToResolutionMethod(resolutionMethodJObject); toReturn.add(method); } return toReturn; <START> } catch (JSONException ex) { <END> throw new OseeCoreException("Could not parse Resolution Methods", ex); } }</code><technical_language>Nit: parsing here. consider improving error message</technical_language>

Target:
public List<ResolutionMethod> getValidResolutions() { List<ResolutionMethod> toReturn = new ArrayList<ResolutionMethod>(); List<String> attributes = artifact.getAttributeValues(CoreAttributeTypes.GeneralStringData); String resolutionsJson = "[]"; for (String attribute : attributes) { if (attribute.startsWith("RESOLUTION_METHODS")) { resolutionsJson = attribute.replaceFirst("RESOLUTION_METHODS=", ""); break; } } try { JSONArray jArray = DispoUtil.asJSONArray(resolutionsJson); for (int i = 0; i < jArray.length(); i++) { JSONObject resolutionMethodJObject = jArray.getJSONObject(i); ResolutionMethod method = DispoUtil.jsonObjToResolutionMethod(resolutionMethodJObject); toReturn.add(method); } return toReturn; } catch (JSONException ex) { throw new OseeCoreException("Invalid Resolutions JSON in Dispo Config", ex); } }
Source:
<code>protected void setDockWidget(final PlaceRequest placeRequest, <START> final IsWidget widget) { <END> if (getDockPresenter(placeRequest).isPresent()) { getDockPresenter(placeRequest).get().setView(widget); } }</code><technical_language>formatting</technical_language>

Target:
protected void setDockWidget(final PlaceRequest placeRequest, final IsWidget widget) { final Optional<DockPlaceHolderBase> dockPlaceHolder = getDockPlaceHolder(placeRequest); if (dockPlaceHolder.isPresent()) { dockPlaceHolder.get().setView(widget); } }
Source:
<code>protected ClientHttpResponse run() throws Exception { final RequestContext context = RequestContext.getCurrentContext(); <START> if (context.getRequest() != null) { <END> String contentLengthHeader = context.getRequest().getHeader("Content-Length"); if (StringUtils.hasText(contentLengthHeader)) { this.context.setContentLength(new Long(contentLengthHeader)); } } RQ request = createRequest(); RS response = this.client.executeWithLoadBalancer(request); context.set("ribbonResponse", response); if (this.isResponseTimedOut()) { if (response != null) { response.close(); } } return new RibbonHttpResponse(response); }</code><technical_language>This concerns me. is this for</technical_language>

Target:
protected ClientHttpResponse run() throws Exception { final RequestContext context = RequestContext.getCurrentContext(); RQ request = createRequest(); RS response = this.client.executeWithLoadBalancer(request); context.set("ribbonResponse", response); if (this.isResponseTimedOut()) { if (response != null) { response.close(); } } return new RibbonHttpResponse(response); }
Source:
<code>public List<ProgramEnrollment> getProgramEnrollmentByPatientMotechId(String configName, String patientMotechId) { Config config = configService.getConfigByName(configName); <START> Patient patient = patientResource.queryForPatient(config, patientMotechId).getResults().get(0); <END> return programEnrollmentResource.getProgramEnrollmentByPatientUuid(config, patient.getUuid()); }</code><technical_language>request get patient for motechId</technical_language>

Target:
public List<ProgramEnrollment> getProgramEnrollmentByPatientMotechId(String configName, String patientMotechId) { Patient patient = patientService.getPatientByMotechId(configName, patientMotechId); return Objects.nonNull(patient) ? getProgramEnrollmentByPatientUuid(configName, patient.getUuid()) : new ArrayList<>(); }
Source:
<code>public void onApiChange(SyncthingService.State currentState) { if (currentState != SyncthingService.State.ACTIVE || getApi() == null) return; List<Folder> folders = getApi().getFolders(); int folderIndex = 0; <START> String savedFolderId = getSharedPreferences(SHARED_PREFS_SAVED_DIRECTORIES, MODE_PRIVATE) <END> .getString(PREF_PREVIOUSLY_SELECTED_SYNCTHING_FOLDER, ""); for (Folder folder: folders) { if (folder.id.equals(savedFolderId)) { folderIndex = folders.indexOf(folder); break; } } ArrayAdapter<Folder> adapter = new ArrayAdapter<>( this, android.R.layout.simple_spinner_item, folders); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner sItems = (Spinner) findViewById(R.id.folders); sItems.setAdapter(adapter); sItems.setSelection(folderIndex); }</code><technical_language>Yeah easier complicated</technical_language>

Target:
public void onApiChange(SyncthingService.State currentState) { if (currentState != SyncthingService.State.ACTIVE || getApi() == null) return; List<Folder> folders = getApi().getFolders(); int folderIndex = 0; String savedFolderId = PreferenceManager.getDefaultSharedPreferences(this) .getString(PREF_PREVIOUSLY_SELECTED_SYNCTHING_FOLDER, ""); for (Folder folder : folders) { if (folder.id.equals(savedFolderId)) { folderIndex = folders.indexOf(folder); break; } } ArrayAdapter<Folder> adapter = new ArrayAdapter<>( this, android.R.layout.simple_spinner_item, folders); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner sItems = findViewById(R.id.folders); sItems.setAdapter(adapter); sItems.setSelection(folderIndex); }
Source:
<code>public void testLexicographicalBinaryComparator() { testObjectComparator(LEXICOGRAPHICAL_BINARY_COMPARATOR, Binary.fromConstantByteArray(new byte[0]), Binary.fromConstantByteArray(new byte[]{127, 127, 0, 127}, 2, 1), Binary.fromCharSequence("aaa"), Binary.fromString("aaaa"), Binary.fromReusedByteArray("aaab".getBytes()), Binary.fromReusedByteArray("azzza".getBytes(), 1, 3), Binary.fromReusedByteBuffer(ByteBuffer.wrap("zzzzzz".getBytes())), Binary.fromReusedByteBuffer(ByteBuffer.wrap("aazzzzzzaa".getBytes(), 2, 7)), <START> Binary.fromConstantByteBuffer(ByteBuffer.wrap(new byte[]{-128, -128, -128})), <END> Binary.fromConstantByteBuffer(ByteBuffer.wrap(new byte[]{-128, -128, -1}, 1, 2)) ); }</code><technical_language>(nit) other around, in this case hexadecimal literals values more human-readable</technical_language>

Target:
public void testLexicographicalBinaryComparator() { testObjectComparator(UNSIGNED_LEXICOGRAPHICAL_BINARY_COMPARATOR, null, Binary.fromConstantByteArray(new byte[0]), Binary.fromConstantByteArray(new byte[] { 127, 127, 0, 127 }, 2, 1), Binary.fromCharSequence("aaa"), Binary.fromString("aaaa"), Binary.fromReusedByteArray("aaab".getBytes()), Binary.fromReusedByteArray("azzza".getBytes(), 1, 3), Binary.fromReusedByteBuffer(ByteBuffer.wrap("zzzzzz".getBytes())), Binary.fromReusedByteBuffer(ByteBuffer.wrap("aazzzzzzaa".getBytes(), 2, 7)), Binary.fromConstantByteBuffer(ByteBuffer.wrap(new byte[] { -128, -128, -128 })), Binary.fromConstantByteBuffer(ByteBuffer.wrap(new byte[] { -128, -128, -1 }, 1, 2)) ); }
Source:
<code>private void validateRecords(final List<SAMRecord> expectedRecords, ByteArrayInputStream is, ReferenceSource referenceSource) { try (CRAMFileReader cReader = new CRAMFileReader(null, is, referenceSource)) { SAMRecordIterator iterator2 = cReader.getIterator(); int index = 0; while (iterator2.hasNext()) { SAMRecord actualRecord = iterator2.next(); SAMRecord expectedRecord = expectedRecords.get(index++); Assert.assertEquals(actualRecord.getReadName(), expectedRecord.getReadName()); Assert.assertEquals(actualRecord.getFlags(), expectedRecord.getFlags()); Assert.assertEquals(actualRecord.getAlignmentStart(), expectedRecord.getAlignmentStart()); Assert.assertEquals(actualRecord.getAlignmentEnd(), expectedRecord.getAlignmentEnd()); Assert.assertEquals(actualRecord.getReferenceName(), expectedRecord.getReferenceName()); Assert.assertEquals(actualRecord.getMateAlignmentStart(), expectedRecord.getMateAlignmentStart()); Assert.assertEquals(actualRecord.getMateReferenceName(), expectedRecord.getMateReferenceName()); Assert.assertEquals(actualRecord.getReadBases(), expectedRecord.getReadBases()); Assert.assertEquals(actualRecord.getBaseQualities(), expectedRecord.getBaseQualities()); Assert.assertEquals(actualRecord.getAttributes().stream().map(s -> s.tag).collect(Collectors.toSet()), <START> actualRecord.getAttributes().stream().map(s -> s.tag).collect(Collectors.toSet()), expectedRecord.getReadName()); <END> actualRecord.getAttributes().forEach(tv -> { Assert.assertEquals(tv.value, expectedRecord.getAttribute(tv.tag)); }); } } }</code><technical_language>this comparing actual actual? I a typo</technical_language>

Target:
private void validateRecords(final List<SAMRecord> expectedRecords, ByteArrayInputStream is, ReferenceSource referenceSource) { try (CRAMFileReader cReader = new CRAMFileReader(null, is, referenceSource)) { SAMRecordIterator iterator2 = cReader.getIterator(); int index = 0; while (iterator2.hasNext()) { SAMRecord actualRecord = iterator2.next(); SAMRecord expectedRecord = expectedRecords.get(index++); Assert.assertEquals(actualRecord.getReadName(), expectedRecord.getReadName()); Assert.assertEquals(actualRecord.getFlags(), expectedRecord.getFlags()); Assert.assertEquals(actualRecord.getAlignmentStart(), expectedRecord.getAlignmentStart()); Assert.assertEquals(actualRecord.getAlignmentEnd(), expectedRecord.getAlignmentEnd()); Assert.assertEquals(actualRecord.getReferenceName(), expectedRecord.getReferenceName()); Assert.assertEquals(actualRecord.getMateAlignmentStart(), expectedRecord.getMateAlignmentStart()); Assert.assertEquals(actualRecord.getMateReferenceName(), expectedRecord.getMateReferenceName()); Assert.assertEquals(actualRecord.getReadBases(), expectedRecord.getReadBases()); Assert.assertEquals(actualRecord.getBaseQualities(), expectedRecord.getBaseQualities()); Assert.assertEquals( actualRecord.getAttributes().stream().map(s -> s.tag).collect(Collectors.toSet()), expectedRecord.getAttributes().stream().map(s -> s.tag).collect(Collectors.toSet()), expectedRecord.getReadName()); actualRecord.getAttributes().forEach(tv -> { Assert.assertEquals(tv.value, expectedRecord.getAttribute(tv.tag)); }); } } }