auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void unloadedUnitsAreTransferredToOnlyOneOfTheNewUnits() { final Unit oldUnit = transport.create(1, player).get(0); final List<Unit> newUnits = transport.create(2, player); final List<Unit> unloadedInfantry = infantry.create(1, player); oldUnit.setUnloaded(unloadedInfantry); final Change changes = UnitUtils.translateAttributesToOtherUnits(oldUnit, newUnits, seaZone); gameData.performChange(changes); assertThat(newUnits.get(0).getUnloaded(), is(unloadedInfantry)); assertThat( "Only the first new unit should get the unloaded infantry", newUnits.get(1).getUnloaded(), is(empty())); }

Target:
void unloadedUnitsAreTransferredToOnlyOneOfTheNewUnits() { final Unit oldTransport = transport.create(1, player).get(0); final Unit newTransport1 = transport.create(1, player).get(0); final Unit newTransport2 = transport.create(1, player).get(0); final List<Unit> unloadedInfantry = infantry.create(2, player); oldTransport.setUnloaded(unloadedInfantry); final Change changes = UnitUtils.translateAttributesToOtherUnits( oldTransport, List.of(newTransport1, newTransport2), seaZone); gameData.performChange(changes); assertThat( "Units can only be unloaded by one unit at a time. So the unloaded unit " + "should be transferred to one of the new units. Since the new units is a list, the " + "first one will be selected and the first one is 'newTransport1'", newTransport1.getUnloaded(), is(unloadedInfantry)); assertThat( "newTransport2 should have no unloaded units because all of the units were assigned to " + "newTransport1", newTransport2.getUnloaded(), is(empty())); }
Source:
public boolean isToExclude(String property) { JsonElement jsonElement = getInstance().getConfigurationProperties().getAsJsonObject().get(property); if (jsonElement != null) { return Boolean.valueOf(jsonElement.getAsString()); } return false; }

Target:
public boolean isToExclude(String property) { if (getConfigurationProperties().has(property)) { return getConfigurationProperties().get(property).getAsBoolean(); } return false; }
Source:
private void writeAttribute(final DlmsConnectionHolder conn, final SetParameter parameter, final String attributeName) throws ProtocolAdapterException { try { final AccessResultCode result = conn.getConnection().set(parameter); if (!result.equals(AccessResultCode.SUCCESS)) { throw new ProtocolAdapterException(String .format("Attribute '%s' of the clock configuration was not set successfully.", attributeName)); } } catch (final IOException e) { throw new ConnectionException(e); } }

Target:
private void writeAttribute(final DlmsConnectionHolder conn, final SetParameter parameter, final String attributeName) throws ProtocolAdapterException { try { final AccessResultCode result = conn.getConnection().set(parameter); if (!result.equals(AccessResultCode.SUCCESS)) { throw new ProtocolAdapterException(String.format( "Attribute '%s' of the clock configuration was not set successfully. ResultCode: %s", attributeName, result.name())); } } catch (final IOException e) { throw new ConnectionException(e); } }
Source:
private RestfulAction getXmlPartial(String groupName, String oldMd5, GoConfigService.XmlPartialSaver xmlPartialSaver) { if (!isTemplate(groupName) && !isCurrentUserAdminOfGroup(groupName)) { return XmlAction.xmlUnAuthorized(errorMessageForGroup(groupName)); } if (isTemplate(groupName) && !isCurrentUserAdmin()) { return XmlAction.xmlUnAuthorized(errorMessageForTemplates()); } String xml = null; try { xml = xmlPartialSaver.asXml(); } catch (Exception e) { return XmlAction.xmlNotFound(e.getMessage()); } String newMd5 = xmlPartialSaver.getMd5(); if (oldMd5 != null && !oldMd5.equals(newMd5)) { return XmlAction.xmlMd5Conflict(ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH, newMd5); } return XmlAction.xmlFound(xml, newMd5); }

Target:
private RestfulAction getXmlPartial(String groupName, String oldMd5, GoConfigService.XmlPartialSaver xmlPartialSaver) { if (!isTemplate(groupName) && !isCurrentUserAdminOfGroup(groupName)) { return XmlAction.xmlUnAuthorized(errorMessageForGroup(groupName)); } if (isTemplate(groupName) && !isCurrentUserAdmin()) { return XmlAction.xmlUnAuthorized(errorMessageForTemplates()); } String xml; try { xml = xmlPartialSaver.asXml(); } catch (Exception e) { return XmlAction.xmlNotFound(e.getMessage()); } String newMd5 = xmlPartialSaver.getMd5(); if (oldMd5 != null && !oldMd5.equals(newMd5)) { return XmlAction.xmlMd5Conflict(ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH, newMd5); } return XmlAction.xmlFound(xml, newMd5); }
Source:
private String webDownloadArtifactToString(BlackboardArtifact artifact) throws TskCoreException { StringBuilder sb = new StringBuilder(1024); Map<BlackboardAttribute.ATTRIBUTE_TYPE, BlackboardAttribute> attributesMap = getAttributesMap(artifact); if (BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_DOWNLOAD.getTypeID() == artifact.getArtifactTypeID() || BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_CACHE.getTypeID() == artifact.getArtifactTypeID()) { appendAttributeString(sb, BlackboardAttribute.ATTRIBUTE_TYPE.TSK_URL, attributesMap, "URL"); appendAttributeString(sb, BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME_CREATED, attributesMap, "On"); } return sb.toString(); }

Target:
private String webDownloadArtifactToString(BlackboardArtifact artifact) throws TskCoreException { StringBuilder sb = new StringBuilder(ARTIFACT_STR_MAX_LEN); Map<BlackboardAttribute.ATTRIBUTE_TYPE, BlackboardAttribute> attributesMap = getAttributesMap(artifact); if (BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_DOWNLOAD.getTypeID() == artifact.getArtifactTypeID() || BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_CACHE.getTypeID() == artifact.getArtifactTypeID()) { appendAttributeString(sb, BlackboardAttribute.ATTRIBUTE_TYPE.TSK_URL, attributesMap, Bundle.ContextViewer_downloadURL()); appendAttributeString(sb, BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME_CREATED, attributesMap, Bundle.ContextViewer_downloadedOn()); } return sb.toString(); }
Source:
public URI uploadPackage() throws UploaderException { if (s3Client.doesObjectExist(bucket, remoteFilePath)) { s3Client.copyObject(bucket, remoteFilePath, bucket, previousVersionFilePath); } try { s3Client.putObject(bucket, remoteFilePath, packageFileHandler); } catch (AmazonClientException e) { throw new UploaderException( String.format("Error writing topology package to %s %s", bucket, remoteFilePath)); } final String resourceUrl = s3Client.getResourceUrl(bucket, remoteFilePath); LOG.log(Level.INFO, "Package URL: {0}", resourceUrl); if (resourceUrl == null) { throw new UploaderException( String.format("Resource not found for bucket %s and path %s", bucket, remoteFilePath)); } try { return new URI(resourceUrl); } catch (URISyntaxException e) { throw new UploaderException(e.getMessage()); } }

Target:
public URI uploadPackage() throws UploaderException { if (s3Client.doesObjectExist(bucket, remoteFilePath)) { s3Client.copyObject(bucket, remoteFilePath, bucket, previousVersionFilePath); } try { s3Client.putObject(bucket, remoteFilePath, packageFileHandler); } catch (SdkClientException e) { throw new UploaderException( String.format("Error writing topology package to %s %s", bucket, remoteFilePath), e); } final URL resourceUrl = s3Client.getUrl(bucket, remoteFilePath); LOG.log(Level.INFO, "Package URL: {0}", resourceUrl); if (resourceUrl == null) { throw new UploaderException( String.format("Resource not found for bucket %s and path %s", bucket, remoteFilePath)); } try { return resourceUrl.toURI(); } catch (URISyntaxException e) { throw new UploaderException( String.format("Could not convert URL %s to URI", resourceUrl, e)); } }
Source:
public int getRefPos() { return 0; }

Target:
public int getRefPos() { return -1; }
Source:
public HttpResponse doChangePassword( @QueryParameter String password, @QueryParameter String newPassword1, @QueryParameter String newPassword2 ) throws Exception { try { parent.connect(dn,password).close(); } catch (javax.naming.AuthenticationException e) { throw new UserError("Wrong current password"); } if (!newPassword1.equals(newPassword2)) throw new UserError("New Password mismatch"); Attributes attrs = new BasicAttributes(); attrs.put("userPassword", PasswordUtil.hashPassword(newPassword1)); LdapContext context = parent.connect(); try { context.modifyAttributes(dn,DirContext.REPLACE_ATTRIBUTE,attrs); } finally { context.close(); } LOGGER.info("User "+userId+" changed the password"); return new HttpRedirect("done"); }

Target:
public HttpResponse doChangePassword( @QueryParameter String password, @QueryParameter String newPassword1, @QueryParameter String newPassword2 ) throws Exception { try { parent.connect(dn,password).close(); } catch (javax.naming.AuthenticationException e) { throw new UserError("Wrong current password"); } if (!newPassword1.equals(newPassword2)) throw new UserError("Password does not match the confirm password"); Attributes attrs = new BasicAttributes(); attrs.put("userPassword", PasswordUtil.hashPassword(newPassword1)); LdapContext context = parent.connect(); try { context.modifyAttributes(dn,DirContext.REPLACE_ATTRIBUTE,attrs); } finally { context.close(); } LOGGER.info("User "+userId+" changed the password"); return new HttpRedirect("done"); }
Source:
public SubPlan createSubPlans(Session session, Metadata metadata, NodePartitioningManager nodePartitioningManager, Plan plan, boolean forceSingleNode) { Fragmenter fragmenter = new Fragmenter(session, metadata, plan.getTypes(), plan.getStats(), plan.getCosts()); FragmentProperties properties = new FragmentProperties(new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), plan.getRoot().getOutputSymbols())); if (forceSingleNode || isForceSingleNodeOutput(session)) { properties = properties.setSingleNodeDistribution(); } PlanNode root = SimplePlanRewriter.rewriteWith(fragmenter, plan.getRoot(), properties); SubPlan subPlan = fragmenter.buildRootFragment(root, properties, plan.getStats(), plan.getCosts()); subPlan = analyzeGroupedExecution(session, metadata, nodePartitioningManager, subPlan); checkState(!isForceSingleNodeOutput(session) || subPlan.getFragment().getPartitioning().isSingleNode(), "Root of PlanFragment is not single node"); sanityCheckFragmentedPlan(subPlan, getQueryMaxStageCount(session)); return subPlan; }

Target:
public SubPlan createSubPlans(Session session, Metadata metadata, NodePartitioningManager nodePartitioningManager, Plan plan, boolean forceSingleNode) { Fragmenter fragmenter = new Fragmenter(session, metadata, plan.getTypes(), plan.getStatsAndCosts()); FragmentProperties properties = new FragmentProperties(new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), plan.getRoot().getOutputSymbols())); if (forceSingleNode || isForceSingleNodeOutput(session)) { properties = properties.setSingleNodeDistribution(); } PlanNode root = SimplePlanRewriter.rewriteWith(fragmenter, plan.getRoot(), properties); SubPlan subPlan = fragmenter.buildRootFragment(root, properties); subPlan = analyzeGroupedExecution(session, metadata, nodePartitioningManager, subPlan); checkState(!isForceSingleNodeOutput(session) || subPlan.getFragment().getPartitioning().isSingleNode(), "Root of PlanFragment is not single node"); sanityCheckFragmentedPlan(subPlan, getQueryMaxStageCount(session)); return subPlan; }
Source:
public static CipherSource blowfish() throws Exception { int ivLength = 8; return new CipherSource() { private Cipher get(KeySource source, int mode, byte[] iv) throws Exception { final Cipher c = Cipher.getInstance("Blowfish/CBC/PKCS5Padding"); final byte[] sourceKey = source.getKey(); final Key key = new SecretKeySpec(sourceKey, "Blowfish"); AlgorithmParameterSpec spec = new IvParameterSpec(iv); c.init(mode, key, spec); return c; } @Override public String encrypt(KeySource source, String data) throws Exception { final byte[] dataBytes = data.getBytes(ENCODING); final byte[] iv = KeySources.random(ivLength).getKey(); final Cipher cipher = get(source, Cipher.ENCRYPT_MODE, iv); final byte[] encryptedData = cipher.doFinal(dataBytes); final byte[] encryptedBytes = new byte[encryptedData.length + ivLength]; System.arraycopy(iv, 0, encryptedBytes, 0, ivLength); System.arraycopy(encryptedData, 0, encryptedBytes, ivLength, encryptedData.length); return BASE64_ENCODER.apply(encryptedBytes); } @Override public String decrypt(KeySource source, String data) throws Exception { final byte[] encryptedBytes = BASE64_DECODER.apply(data.getBytes(ENCODING)); final byte[] iv = new byte[ivLength]; System.arraycopy(encryptedBytes, 0, iv, 0, ivLength); final Cipher cipher = get(source, Cipher.DECRYPT_MODE, iv); return new String(cipher.doFinal(encryptedBytes, ivLength, encryptedBytes.length - ivLength), ENCODING); } }; }

Target:
public static CipherSource blowfish() throws Exception { int ivLength = 8; return new SymmetricKeyCipherSource(ivLength) { @Override protected Cipher get(KeySource source, int encryptMode, byte[] iv) throws Exception { final Cipher c = Cipher.getInstance("Blowfish/CBC/PKCS5Padding"); final byte[] sourceKey = source.getKey(); final Key key = new SecretKeySpec(sourceKey, "Blowfish"); AlgorithmParameterSpec spec = new IvParameterSpec(iv); c.init(encryptMode, key, spec); return c; } }; }
Source:
public ChartData(IDataChartProvider<?> provider, List<ChartSeries> series) { fProvider = provider; fSeries = checkNotNull(ImmutableList.copyOf(series)); }

Target:
public ChartData(IDataChartProvider<?> provider, List<ChartSeries> series) { fProvider = provider; fSeries = ImmutableList.copyOf(series); }
Source:
private void handleCVSException(CVSException ex) { IStatus status = ex.getStatus(); List toShow = new ArrayList(); IStatus children[] = status.getChildren(); boolean may = true; for (int i = 0; i < children.length; i++) { if (children[i].getCode() == CVSStatus.BINARY_FILES_DIFFER || children[i].getCode() == CVSStatus.PROTOCOL_ERROR || children[i].getCode() == CVSStatus.ERROR_LINE) { toShow.add(children[i]); if (children[i].getCode() == CVSStatus.BINARY_FILES_DIFFER) may = false; } } if (toShow.size() > 0) { String msg = may ? CVSUIMessages.DiffOperation_ThePatchMayNotContainAllTheChanges : CVSUIMessages.DiffOperation_ThePatchDoesNotContainAllTheChanges; if (!patchHasNewFiles && !patchHasContents) { toShow.add(new Status(IStatus.ERROR, CVSProviderPlugin.ID, CVSUIMessages.GenerateCVSDiff_noDiffsFoundMsg)); emptyDiffReported = true; } status = new MultiStatus(CVSProviderPlugin.ID, CVSStatus.SERVER_ERROR, (IStatus[]) toShow.toArray(new IStatus[0]), CVSUIMessages.DiffOperation_ErrorsOccurredWhileCreatingThePatch, null); CVSUIPlugin.openError(getShell(), this.getTaskName(), msg, status, CVSUIPlugin.PERFORM_SYNC_EXEC | CVSUIPlugin.LOG_OTHER_EXCEPTIONS); } }

Target:
private void handleCVSException(CVSException ex) { IStatus status = ex.getStatus(); List toShow = new ArrayList(); IStatus children[] = status.getChildren(); boolean may = true; for (int i = 0; i < children.length; i++) { if (children[i].getCode() == CVSStatus.BINARY_FILES_DIFFER || children[i].getCode() == CVSStatus.PROTOCOL_ERROR || children[i].getCode() == CVSStatus.ERROR_LINE) { toShow.add(children[i]); if (children[i].getCode() == CVSStatus.BINARY_FILES_DIFFER) may = false; } } if (toShow.size() > 0) { String msg = may ? CVSUIMessages.DiffOperation_ThePatchMayNotContainAllTheChanges : CVSUIMessages.DiffOperation_ThePatchDoesNotContainAllTheChanges; status = new MultiStatus(CVSProviderPlugin.ID, CVSStatus.SERVER_ERROR, (IStatus[]) toShow.toArray(new IStatus[0]), CVSUIMessages.DiffOperation_ErrorsOccurredWhileCreatingThePatch, null); CVSUIPlugin.openError(getShell(), this.getTaskName(), msg, status, CVSUIPlugin.PERFORM_SYNC_EXEC | CVSUIPlugin.LOG_OTHER_EXCEPTIONS); errorReported = true; } }
Source:
private void assertCodeMakes(String method, Multimap<String, String> headers, URI uri, int statusCode, String message, String contentType, String content, Class<? extends Exception> expected) { GlanceErrorHandler function = new GlanceErrorHandler(); HttpCommand command = createMock(HttpCommand.class); HttpRequest request = HttpRequest.builder().method(method).headers(headers).endpoint(uri).build(); HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build(); response.getPayload().getContentMetadata().setContentType(contentType); expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); if (expected != null) command.setException(classEq(expected)); replay(command); function.handleError(command, response); verify(command); }

Target:
private void assertCodeMakes(String method, Multimap<String, String> headers, URI uri, int statusCode, String message, String contentType, String content, Class<? extends Exception> expected) { GlanceErrorHandler function = new GlanceErrorHandler(); HttpCommand command = createMock(HttpCommand.class); HttpRequest request = HttpRequest.builder().method(method).headers(headers).endpoint(uri).build(); HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build(); response.getPayload().getContentMetadata().setContentType(contentType); expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); if (expected != null) { command.setException(classEq(expected)); } replay(command); function.handleError(command, response); verify(command); }
Source:
public void testIntermediateWriteFailures() { ChannelHandler encoder = new MessageToMessageEncoder<Object>() { @Override protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) { out.add(new Object()); out.add(msg); } }; final Exception firstWriteException = new Exception(); ChannelHandler writeThrower = new ChannelOutboundHandlerAdapter() { private boolean firstWritten; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (firstWritten) { ctx.write(msg, promise); } else { firstWritten = true; promise.setFailure(firstWriteException); } } }; EmbeddedChannel channel = new EmbeddedChannel(writeThrower, encoder); Object msg = new Object(); ChannelFuture write = channel.writeAndFlush(msg); assertEquals(firstWriteException, write.cause()); assertEquals(msg, channel.readOutbound()); }

Target:
public void testIntermediateWriteFailures() { ChannelHandler encoder = new MessageToMessageEncoder<Object>() { @Override protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) { out.add(new Object()); out.add(msg); } }; final Exception firstWriteException = new Exception(); ChannelHandler writeThrower = new ChannelOutboundHandlerAdapter() { private boolean firstWritten; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (firstWritten) { ctx.write(msg, promise); } else { firstWritten = true; promise.setFailure(firstWriteException); } } }; EmbeddedChannel channel = new EmbeddedChannel(writeThrower, encoder); Object msg = new Object(); ChannelFuture write = channel.writeAndFlush(msg); assertSame(firstWriteException, write.cause()); assertSame(msg, channel.readOutbound()); assertFalse(channel.finish()); }
Source:
public StreamingEntropy(String type, String base) { this.x = null; this.cx = 0; this.lastCmp = 0; this.estimator = EntropyEstimator.createEstimator(type, base); if(this.estimator == null) { throw new IllegalArgumentException("input entropy estimator type is not supported. " + "Please refer to StreamingEntropy's javadoc for the supported estimator types"); } }

Target:
public StreamingEntropy(String type, String base) throws ExecException { try { this.estimator = EntropyEstimator.createEstimator(type, base); } catch (IllegalArgumentException ex) { throw new ExecException( String.format("Fail to initialize StreamingEntropy with entropy estimator of type (%s), base: (%s), exception: (%s)", type, base, ex) ); } cleanup(); }
Source:
public boolean isList() { if (isProperty) return prop.isList(); else return false; }

Target:
public boolean isList() { return isProperty && prop.isList(); }
Source:
public void testAddwithExistingTarget() throws DogException { AdderUsageObserver.setUsed( false ); Source source = new Source(); source.setPets( Arrays.asList( new String[]{ "mouse" } ) ); Target target = new Target(); target.setPets( new ArrayList<Long>( Arrays.asList( new Long[]{ 1L } ) ) ); SourceTargetMapper.INSTANCE.toExistingTarget( source, target ); assertThat( target ).isNotNull(); assertThat( target.getPets().size() ).isEqualTo( 2 ); assertThat( target.getPets().get( 0 ) ).isEqualTo( 1L ); assertThat( target.getPets().get( 1 ) ).isEqualTo( 2L ); assertTrue( AdderUsageObserver.isUsed() ); }

Target:
public void testAddwithExistingTarget() throws DogException { AdderUsageObserver.setUsed( false ); Source source = new Source(); source.setPets( Arrays.asList( "mouse" ) ); Target target = new Target(); target.setPets( new ArrayList<Long>( Arrays.asList( 1L ) ) ); SourceTargetMapper.INSTANCE.toExistingTarget( source, target ); assertThat( target ).isNotNull(); assertThat( target.getPets().size() ).isEqualTo( 2 ); assertThat( target.getPets().get( 0 ) ).isEqualTo( 1L ); assertThat( target.getPets().get( 1 ) ).isEqualTo( 2L ); assertTrue( AdderUsageObserver.isUsed() ); }
Source:
UnwrappedMessageContent unwrapContent(byte[] data, Schema schema) { try { Map<Utf8, Utf8> metadata = (Map<Utf8, Utf8>) bytesToRecord(data, schema).get(METADATA_MARKER); long timestamp = getTimestamp(metadata); String messageId = getMessageId(metadata, timestamp); Map<String, String> externalMetadata = extractMetadata(metadata); return new UnwrappedMessageContent(new MessageMetadata(timestamp, messageId, externalMetadata), data); } catch (Exception exception) { throw new UnwrappingException("Could not read avro message", exception); } }

Target:
UnwrappedMessageContent unwrapContent(byte[] data, Schema schema) { try { Map<Utf8, Utf8> metadata = (Map<Utf8, Utf8>) bytesToRecord(data, schema).get(METADATA_MARKER); MessageMetadata messageMetadata = getMetadata(metadata); return new UnwrappedMessageContent(messageMetadata, data); } catch (Exception exception) { throw new UnwrappingException("Could not read avro message", exception); } }
Source:
public Collection<GrantedAuthority> convert(Jwt source) { Collection<GrantedAuthority> result = new ArrayList<>(); for (Converter<Jwt, Collection<GrantedAuthority>> converter: converters) { Collection<GrantedAuthority> authorities = converter.convert(source); if (authorities != null) { result.addAll(authorities); } } return result; }

Target:
public Collection<GrantedAuthority> convert(Jwt source) { Collection<GrantedAuthority> result = new LinkedHashSet<>(); for (Converter<Jwt, Collection<GrantedAuthority>> converter: this.converters) { Collection<GrantedAuthority> authorities = converter.convert(source); if (authorities != null) { result.addAll(authorities); } } return result; }
Source:
private void displayNonLeadSection(int index) { activity.updateProgressBar(true, false, PageActivity.PROGRESS_BAR_MAX_VALUE / model.getPage() .getSections().size() * index); try { final Page page = model.getPage(); JSONObject wrapper = new JSONObject(); wrapper.put("sequence", pageSequenceNum); if (index < page.getSections().size()) { wrapper.put("section", page.getSections().get(index).toJSON()); wrapper.put("index", index); if (sectionTargetFromIntent > 0 && sectionTargetFromIntent < page.getSections().size()) { wrapper.put("fragment", page.getSections().get(sectionTargetFromIntent).getAnchor()); } else if (sectionTargetFromTitle != null) { wrapper.put("fragment", sectionTargetFromTitle); } Log.d(TAG, "Added request for section " + page.getSections().get(index).toJSON().getString("line")); } else { wrapper.put("noMore", true); } wrapper.put("scrollY", (int) (stagedScrollY / activity.getResources().getDisplayMetrics().density)); bridge.sendMessage("displaySection", wrapper); } catch (JSONException e) { ACRA.getErrorReporter().handleException(e); } }

Target:
private void displayNonLeadSection(int index) { activity.updateProgressBar(true, false, PageActivity.PROGRESS_BAR_MAX_VALUE / model.getPage() .getSections().size() * index); try { final Page page = model.getPage(); JSONObject wrapper = new JSONObject(); wrapper.put("sequence", pageSequenceNum); if (index < page.getSections().size()) { JSONObject section = page.getSections().get(index).toJSON(); wrapper.put("section", section); wrapper.put("index", index); if (sectionTargetFromIntent > 0 && sectionTargetFromIntent < page.getSections().size()) { wrapper.put("fragment", page.getSections().get(sectionTargetFromIntent).getAnchor()); } else if (sectionTargetFromTitle != null) { wrapper.put("fragment", sectionTargetFromTitle); } Log.d(TAG, "Added request for section " + section.getString("line")); } else { wrapper.put("noMore", true); } wrapper.put("scrollY", (int) (stagedScrollY / activity.getResources().getDisplayMetrics().density)); bridge.sendMessage("displaySection", wrapper); } catch (JSONException e) { ACRA.getErrorReporter().handleException(e); } }
Source:
public static byte[] hash(byte[] data) throws NoSuchAlgorithmException { MessageDigest crypt; crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(data); return crypt.digest(); }

Target:
public static byte[] hash(byte[] data) throws NoSuchAlgorithmException { return hash(data, 0, data.length); }
Source:
public void shouldShutdownInternalExecutorService() throws Exception { this.initiator.start(); this.initiator.destroy(); ExecutorService executorService = (ExecutorService) TestUtils.getPropertyValue(this.initiator, "executorService"); assertTrue(executorService.isShutdown()); }

Target:
public void shouldShutdownInternalExecutorService() throws Exception { this.initiator.start(); this.initiator.destroy(); ExecutorService executorService = TestUtils.getPropertyValue(this.initiator, "executorService", ExecutorService.class); assertTrue(executorService.isShutdown()); }
Source:
protected void verify(Step model, Step transform) { assertNotNull(transform); assertEquals(model.getId(), transform.getId()); assertEquals(model.getDescription(), transform.getDescription()); }

Target:
protected void verify(Step model, Step transform) { assertNotNull(transform); assertEquals(model.getId(), transform.getId()); assertEquals(model.getDescription(), transform.getDescription()); assertEquals(model.getJob(), transform.getJob()); if (model.getParentStep() != null) { assertEquals(model.getParentStep(), transform.getParentStep()); } }
Source:
public SpatialIndexBuilderOperator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, HashBuilderOperator.class.getSimpleName()); SpatialIndexBuilderOperator operator = new SpatialIndexBuilderOperator( operatorContext, pagesSpatialIndexFactory, outputChannels, indexChannel, filterFunctionFactory, expectedPositions, pagesIndexFactory); return operator; }

Target:
public SpatialIndexBuilderOperator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, SpatialIndexBuilderOperator.class.getSimpleName()); return new SpatialIndexBuilderOperator( operatorContext, pagesSpatialIndexFactory, outputChannels, indexChannel, spatialRelationshipTest, filterFunctionFactory, expectedPositions, pagesIndexFactory); }
Source:
public void static_member_usages() { ClassSymbolImpl classSymbol = ((ClassSymbolImpl) lastClassSymbol( "class A:", " foo = 42", " def __init__(self): ", " A.foo", " A.bar" )); Map<String, Symbol> members = classSymbol.declaredMembers().stream().collect(Collectors.toMap(Symbol::name, Function.identity())); Symbol foo = members.get("foo"); assertThat(foo.usages()).extracting(Usage::kind).containsExactly(Usage.Kind.ASSIGNMENT_LHS, Usage.Kind.OTHER); assertThat(members.get("bar")).isNull(); classSymbol = ((ClassSymbolImpl) lastClassSymbol( "class A:", " foo1 = 42", " def __init__(self, x): ", " getClass().foo2", " x.foo3", " unknown.foo4" )); assertThat(classSymbol.declaredMembers()) .filteredOn("kind", Symbol.Kind.OTHER) .extracting(Symbol::name).containsOnly("foo1"); }

Target:
public void static_member_usages() { ClassSymbol classSymbol = lastClassSymbol( "class A:", " foo = 42", " def __init__(self): ", " A.foo", " A.foo = 0", " A.bar" ); Symbol foo = classSymbol.resolveMember("foo").get(); assertThat(foo.usages()).extracting(Usage::kind).containsExactly(Usage.Kind.ASSIGNMENT_LHS, Usage.Kind.OTHER, Usage.Kind.ASSIGNMENT_LHS); assertThat(classSymbol.resolveMember("bar")).isEmpty(); }
Source:
public TransactionImple recoverTransaction(Uid actId) throws XAException { if (actId == null) throw new IllegalArgumentException(); TransactionImple recovered = new TransactionImple(actId); if (recovered.baseXid() == null) throw new IllegalArgumentException(); return addImportedTransaction(recovered); }

Target:
public TransactionImple recoverTransaction(Uid actId) throws XAException { if (actId == null) throw new IllegalArgumentException(); TransactionImple recovered = new TransactionImple(actId); if (recovered.baseXid() == null) throw new IllegalArgumentException(); return addImportedTransaction(recovered, recovered.baseXid(), null, 0); }
Source:
private boolean isCreateSnapshotAvailable(List<GlusterVolumeEntity> list) { boolean bricksUpFlag = true; if (list.size() == 1) { List<GlusterBrickEntity> bricks = list.get(0).getBricks(); for (GlusterBrickEntity brick : bricks) { if (brick.getStatus() != GlusterStatus.UP) { bricksUpFlag = false; break; } } return (list.get(0).getStatus() == GlusterStatus.UP && bricksUpFlag); } else { return false; } }

Target:
private boolean isCreateSnapshotAvailable(List<GlusterVolumeEntity> list) { if (list.size() == 1) { List<GlusterBrickEntity> bricks = list.get(0).getBricks(); for (GlusterBrickEntity brick : bricks) { if (brick.getStatus() != GlusterStatus.UP) { return false; } } return (list.get(0).getStatus() == GlusterStatus.UP); } else { return false; } }
Source:
public void VEMediaTests_005_resizeVideoWithHandle() { int numOfVideo = 1; VisualEditorPageObject ve = base.launchVisualEditorWithMainEdit(articleName, wikiURL); VisualEditorAddMediaDialog mediaDialog = (VisualEditorAddMediaDialog) ve.openDialogFromMenu(InsertDialog.MEDIA); mediaDialog = mediaDialog.searchMedia("h"); ve = mediaDialog.addExistingMedia(numOfVideo); ve.verifyVideos(numOfVideo); Dimension source = ve.getVideoDimension(); ve.randomResizeOnMedia(); ve.verifyVideoResized(source); VisualEditorSaveChangesDialog save = ve.clickPublishButton(); ArticlePageObject article = save.savePage(); article.verifyVEPublishComplete(); article.logOut(wikiURL); }

Target:
public void VEMediaTests_005_resizeVideoWithHandle() { VisualEditorPageObject ve = base.launchVisualEditorWithMainEdit(articleName, wikiURL); VisualEditorAddMediaDialog mediaDialog = (VisualEditorAddMediaDialog) ve.openDialogFromMenu(InsertDialog.MEDIA); mediaDialog = mediaDialog.searchMedia("h"); ve = mediaDialog.addExistingMedia(numOfVideo); ve.verifyVideos(numOfVideo); Dimension source = ve.getVideoDimension(); ve.randomResizeOnMedia(); ve.verifyVideoResized(source); VisualEditorSaveChangesDialog save = ve.clickPublishButton(); ArticlePageObject article = save.savePage(); article.verifyVEPublishComplete(); article.logOut(wikiURL); }
Source:
public void testMaxExecuteWorkerTime() throws Exception { String poolName = TestUtils.randomAlphaString(10); long maxWorkerExecuteTime = NANOSECONDS.convert(3, SECONDS); DeploymentOptions deploymentOptions = new DeploymentOptions() .setWorkerPoolName(poolName) .setMaxWorkerExecuteTime(maxWorkerExecuteTime); vertx.deployVerticle(new AbstractVerticle() { @Override public void start(Future<Void> startFuture) throws Exception { vertx.executeBlocking(fut -> { try { SECONDS.sleep(5); fut.complete(); } catch (InterruptedException e) { fut.fail(e); } }, startFuture); } }, deploymentOptions, onSuccess(did -> { testComplete(); })); await(); String timeLimitMsg = "time limit is " + MILLISECONDS.convert(maxWorkerExecuteTime, NANOSECONDS); assertTrue(Files.lines(Paths.get(System.getProperty("java.io.tmpdir"), "vertx.log")) .anyMatch(line -> { if (line.contains("has been blocked for") && line.contains(timeLimitMsg) && line.contains(poolName)) { return true; } return false; })); }

Target:
public void testMaxExecuteWorkerTime() throws Exception { String poolName = TestUtils.randomAlphaString(10); long maxWorkerExecuteTime = NANOSECONDS.convert(3, SECONDS); DeploymentOptions deploymentOptions = new DeploymentOptions() .setWorkerPoolName(poolName) .setMaxWorkerExecuteTime(maxWorkerExecuteTime); vertx.deployVerticle(new AbstractVerticle() { @Override public void start(Future<Void> startFuture) throws Exception { vertx.executeBlocking(fut -> { try { SECONDS.sleep(5); fut.complete(); } catch (InterruptedException e) { fut.fail(e); } }, startFuture); } }, deploymentOptions, onSuccess(did -> { testComplete(); })); await(); blockedThreadWarning.expectMessage(poolName, maxWorkerExecuteTime); }
Source:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.VmTemplate.name().toLowerCase(), (getVmTemplateName() == null) ? "" : getVmTemplateName()); jobProperties.put("domainname", getStorageDomainName()); } return jobProperties; }

Target:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.VmTemplate.name().toLowerCase(), (getVmTemplateName() == null) ? "" : getVmTemplateName()); jobProperties.put(VdcObjectType.Storage.name().toLowerCase(), getStorageDomainName()); } return jobProperties; }
Source:
public Subscriber<? super T> call(final Subscriber<? super T> child) { return new Subscriber<T>() { private volatile boolean isEmpty = true; @Override public void onCompleted() { if (isEmpty) action.call(); child.onCompleted(); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(T t) { isEmpty = false; try { child.onNext(t); } catch (Exception e) { Exceptions.throwOrReport(e, this, t); } } }; }

Target:
public Subscriber<? super T> call(final Subscriber<? super T> child) { return new Subscriber<T>(child) { private boolean isEmpty = true; private boolean done = false; @Override public void onCompleted() { if (done) { return; } if (isEmpty) { try { onEmpty.call(); } catch (Throwable e) { Exceptions.throwOrReport(e,this); return; } if (!isUnsubscribed()) { child.onCompleted(); } } else { child.onCompleted(); } done = true; } @Override public void onError(Throwable e) { if (done) { return; } child.onError(e); } @Override public void onNext(T t) { if (done) { return; } isEmpty = false; child.onNext(t); } }; }
Source:
public UpdateUserCommand(User user) { this.user = user; setId(user.getId()); if (user.getName() != null) { setFirstName(user.getName().getGivenName()); setLastName(user.getName().getFamilyName()); } Email primaryEmail = getPrimaryEMail(user); if (primaryEmail != null) { setEmail(primaryEmail.getValue()); } }

Target:
public UpdateUserCommand(User user) { this.user = user; setId(user.getId()); if (user.getName() != null) { setFirstName(user.getName().getGivenName()); setLastName(user.getName().getFamilyName()); } Optional<Email> primaryEmail = SCIMHelper.getPrimaryOrFirstEmail(user); if (primaryEmail.isPresent()) { setEmail(primaryEmail.get().getValue()); } }
Source:
protected void onInit() throws Exception { super.onInit(); if (this.expectMessage) { Assert.notNull(this.serializer, "'serializer' has to be provided where 'expectMessage == true'."); } if (this.taskExecutor == null) { String beanName = this.getComponentName(); this.taskExecutor = new SimpleAsyncTaskExecutor((beanName == null ? "" : beanName + "-") + this.getComponentType()); } if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor) && this.getBeanFactory() != null) { MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(this.getBeanFactory())); errorHandler.setDefaultErrorChannel(this.errorChannel); this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, errorHandler); } }

Target:
protected void onInit() throws Exception { super.onInit(); if (!this.extractPayload) { Assert.notNull(this.serializer, "'serializer' has to be provided where 'extractPayload == false'."); } if (this.taskExecutor == null) { String beanName = this.getComponentName(); this.taskExecutor = new SimpleAsyncTaskExecutor((beanName == null ? "" : beanName + "-") + this.getComponentType()); } if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor) && this.getBeanFactory() != null) { MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(this.getBeanFactory())); errorHandler.setDefaultErrorChannel(this.errorChannel); this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, errorHandler); } }
Source:
private void processStopFileRequest(Intent intent) { OCFile file = intent.getExtras().getParcelable(EXTRA_FILE); try { if(file.equals(mFile)) { processStopRequest(true); } } catch (NullPointerException e) { Log_OC.e(TAG, "NullPointerException while stopping on OCFile ", e); } }

Target:
private void processStopFileRequest(Intent intent) { OCFile file = intent.getExtras().getParcelable(EXTRA_FILE); if(file != null && file.equals(mFile)) { processStopRequest(true); } }
Source:
public void shouldReturnAllTransactionsForAGivenGatewayAccount() { Long chargeId1 = 10001L; String externalChargeId1 = "10001"; Long chargeId2 = 10002L; String externalChargeId2 = "10002"; int amount1 = 100; int amount2 = 500; String gatewayTransactionId1 = "transaction-id-1"; app.getDatabaseTestHelper().addCharge(chargeId1, externalChargeId1, accountId, amount1, AUTHORISATION_SUCCESS, returnUrl, gatewayTransactionId1); app.getDatabaseTestHelper().addCharge(chargeId2, externalChargeId2, accountId, amount2, AUTHORISATION_REJECTED, returnUrl, null); String anotherAccountId = "5454545"; Long chargeId3 = 5001L; app.getDatabaseTestHelper().addGatewayAccount(anotherAccountId, "worldpay"); app.getDatabaseTestHelper().addCharge(chargeId3, "charge5001", anotherAccountId, 200, AUTHORISATION_READY, returnUrl, "transaction-id-2"); List<ChargeStatus> statuses = asList(CREATED, ENTERING_CARD_DETAILS, AUTHORISATION_READY, AUTHORISATION_SUCCESS); setupLifeCycleEventsFor(app, chargeId1, statuses); setupLifeCycleEventsFor(app, chargeId2, statuses); setupLifeCycleEventsFor(app, chargeId3, statuses); ValidatableResponse response = connectorRestApi.withHeader(HttpHeaders.ACCEPT, APPLICATION_JSON).getCharges(); response.statusCode(OK.getStatusCode()) .contentType(JSON) .body("results", hasSize(2)); assertTransactionEntry(response, 0, externalChargeId2, null, amount2, ExternalChargeState.EXTERNAL_FAILED_REJECTED.getStatus()); assertTransactionEntry(response, 1, externalChargeId1, gatewayTransactionId1, amount1, ExternalChargeState.EXTERNAL_SUBMITTED.getStatus()); }

Target:
public void shouldReturnAllTransactionsForAGivenGatewayAccount() { Long chargeId1 = 10001L; String externalChargeId1 = "10001"; Long chargeId2 = 10002L; String externalChargeId2 = "10002"; int amount1 = 100; int amount2 = 500; String gatewayTransactionId1 = "transaction-id-1"; app.getDatabaseTestHelper().addCharge(chargeId1, externalChargeId1, accountId, amount1, AUTHORISATION_SUCCESS, returnUrl, gatewayTransactionId1); app.getDatabaseTestHelper().addCharge(chargeId2, externalChargeId2, accountId, amount2, AUTHORISATION_REJECTED, returnUrl, null); String anotherAccountId = "5454545"; Long chargeId3 = 5001L; app.getDatabaseTestHelper().addGatewayAccount(anotherAccountId, "worldpay"); app.getDatabaseTestHelper().addCharge(chargeId3, "charge5001", anotherAccountId, 200, AUTHORISATION_READY, returnUrl, "transaction-id-2"); List<ChargeStatus> statuses = asList(CREATED, ENTERING_CARD_DETAILS, AUTHORISATION_READY, AUTHORISATION_SUCCESS); setupLifeCycleEventsFor(app, chargeId1, statuses); setupLifeCycleEventsFor(app, chargeId2, statuses); setupLifeCycleEventsFor(app, chargeId3, statuses); ValidatableResponse response = connectorRestApi.withHeader(HttpHeaders.ACCEPT, APPLICATION_JSON).getTransactions(); response.statusCode(OK.getStatusCode()) .contentType(JSON) .body("results", hasSize(2)); assertTransactionEntry(response, 0, externalChargeId2, null, amount2, ExternalChargeState.EXTERNAL_FAILED_REJECTED.getStatus()); assertTransactionEntry(response, 1, externalChargeId1, gatewayTransactionId1, amount1, ExternalChargeState.EXTERNAL_SUBMITTED.getStatus()); }
Source:
private static CustomJCommander parseArguments(CommandRepository commandRepository, RemoteMainCommand mainCommand, String[] args) { CustomJCommander jCommander = new CustomJCommander(CONFIG_TOOL, commandRepository, mainCommand); try { jCommander.parse(args); } catch (ParameterException e) { jCommander.printUsage(); throw e; } return jCommander; }

Target:
private static CustomJCommander parseArguments(CommandRepository commandRepository, RemoteMainCommand mainCommand, String[] args) { CustomJCommander jCommander = new CustomJCommander("config-tool", commandRepository, mainCommand) { @Override public void appendDefinitions(StringBuilder out, String indent) { out.append(indent).append(lineSeparator()).append("Definitions:").append(lineSeparator()); out.append(indent).append(" ").append("namespace").append(lineSeparator()); Map<String, String> nameSpaces = new LinkedHashMap<>(); nameSpaces.put("stripe.<stripeId>.node.<nodeId>", "to apply a change only on a specific node"); nameSpaces.put("stripe.<stripeId>", "to apply a change only on a specific stripe"); nameSpaces.put("'' (empty namespace)", "to apply a change only on all nodes of the cluster"); int maxNamespaceLength = Integer.MIN_VALUE; for (String nameSpace : nameSpaces.keySet()) { if (nameSpace.length() > maxNamespaceLength) { maxNamespaceLength = nameSpace.length(); } } for (Map.Entry<String, String> entry : nameSpaces.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); out.append(indent).append(" ").append(key); for (int i = 0; i < maxNamespaceLength - key.length() + 4; i++) { out.append(" "); } out.append(value).append(lineSeparator()); } } }; try { jCommander.parse(args); } catch (ParameterException e) { jCommander.printUsage(); throw e; } return jCommander; }
Source:
public void invalidLowMTU() { Set<ConstraintViolation<MtuContainer>> validate = validate(new MtuContainer(30)); Assert.assertFalse(validate.isEmpty()); }

Target:
public void invalidLowMTU() { Set<ConstraintViolation<MtuContainer>> validate = validate(new MtuContainer(30)); assertFalse(validate.isEmpty()); }
Source:
public void expireOnOneServer_shouldResultInKeyRemovalFromOtherServer() { String key = "key"; jedis1.set(key, "value"); jedis1.expire(key, 2); assertThat(jedis2.ttl(key)).isGreaterThan(0); GeodeAwaitility.await().until(() -> jedis2.ttl(key) == TTLExecutor.NOT_EXISTS); }

Target:
public void expireOnOneServer_shouldResultInKeyRemovalFromOtherServer() { String key = "key"; jedis1.set(key, "value"); jedis1.expire(key, 2); GeodeAwaitility.await().until(() -> jedis2.ttl(key) == TTLExecutor.NOT_EXISTS); }
Source:
private static Set<List<JavaFileScannerContext.Location>> flowsForMethodArguments(ExplodedGraph.Node node, MethodInvocationTree mit, int parameterCausingExceptionIndex) { ProgramState programState = node.programState; List<ProgramState.SymbolicValueSymbol> arguments = Lists.reverse(programState.peekValuesAndSymbols(mit.arguments().size())); SymbolicValue parameterCausingExceptionSV = arguments.get(parameterCausingExceptionIndex).symbolicValue(); Set<SymbolicValue> argSymbolicValues = new LinkedHashSet<>(); Set<Symbol> argSymbols = new LinkedHashSet<>(); for (ProgramState.SymbolicValueSymbol svs : arguments) { Symbol symbol = svs.symbol(); SymbolicValue sv = svs.symbolicValue(); if (parameterCausingExceptionSV == sv) { argSymbolicValues.add(sv); } else { PMap<Class<? extends Constraint>, Constraint> constraints = programState.getConstraints(sv); if (constraints == null || (domainsFromConstraints(constraints).size() == 1 && constraints.get(ObjectConstraint.class) == ObjectConstraint.NOT_NULL)) { continue; } argSymbolicValues.add(sv); } if (symbol != null) { argSymbols.add(symbol); } } List<Class<? extends Constraint>> domains = domainsFromArguments(programState, argSymbolicValues); return FlowComputation.flow(node, argSymbolicValues, c -> true, c -> false, domains, argSymbols); }

Target:
private static Set<List<JavaFileScannerContext.Location>> flowsForMethodArguments(ExplodedGraph.Node node, MethodInvocationTree mit, int parameterCausingExceptionIndex) { ProgramState programState = node.programState; List<ProgramState.SymbolicValueSymbol> arguments = Lists.reverse(programState.peekValuesAndSymbols(mit.arguments().size())); SymbolicValue parameterCausingExceptionSV = arguments.get(parameterCausingExceptionIndex).symbolicValue(); Set<SymbolicValue> argSymbolicValues = new LinkedHashSet<>(); Set<Symbol> argSymbols = new LinkedHashSet<>(); arguments.stream() .filter(svs -> parameterCausingExceptionSV == svs.symbolicValue() || hasConstraintOtherThanNonNull(svs, programState)) .forEach(svs -> { argSymbolicValues.add(svs.symbolicValue()); Symbol symbol = svs.symbol(); if (symbol != null) { argSymbols.add(symbol); } }); List<Class<? extends Constraint>> domains = domainsFromArguments(programState, argSymbolicValues); return FlowComputation.flow(node, argSymbolicValues, c -> true, c -> false, domains, argSymbols); }
Source:
public int getAudioStreamType() { if (!mProto.hasAudioTrackIndex() && mProto.getAudioTrackIndex() == -1) { return INVALID_STREAMTYPE; } return mProto.getAudioStreamTypes(mProto.getAudioTrackIndex()).getNumber(); }

Target:
public int getAudioStreamType() { if (mProto.getAudioTrackIndex() == -1) { return INVALID_STREAMTYPE; } return mProto.getAudioStreamTypes(mProto.getAudioTrackIndex()).getNumber(); }
Source:
public String getWelcomeSections(final Locale locale) { Map<String, String> messageMap = getMessageMap(WELCOME, locale); List<BrandingTheme> brandingThemes = getBrandingThemes(); StringBuilder templateBuilder = new StringBuilder(); for (BrandingTheme theme: brandingThemes) { String template = theme.getWelcomePageSectionTemplate(); String replacedTemplate = template; Matcher keyMatcher = TEMPLATE_PATTERN.matcher(template); while (keyMatcher.find()) { String key = keyMatcher.group(1); replacedTemplate = replacedTemplate.replaceAll("\\{" + key + "\\}", messageMap.get(key)); } replacedTemplate = replacedTemplate.replaceAll("\\{0\\}", locale.toString()); templateBuilder.append(replacedTemplate); } return templateBuilder.toString(); }

Target:
public String getWelcomeSections(final Locale locale) { Map<String, String> messageMap = getMessageMap(WELCOME, locale); List<BrandingTheme> brandingThemes = getBrandingThemes(); StringBuilder templateBuilder = new StringBuilder(); for (BrandingTheme theme: brandingThemes) { String template = theme.getWelcomePageSectionTemplate(); String replacedTemplate = template; Matcher keyMatcher = TEMPLATE_PATTERN.matcher(template); while (keyMatcher.find()) { String key = keyMatcher.group(1); if (!USER_LOCALE_HOLDER.substring(2, USER_LOCALE_HOLDER.length() - 2).equals(key)) { replacedTemplate = replacedTemplate.replaceAll("\\{" + key + "\\}", messageMap.get(key)); } } replacedTemplate = replacedTemplate.replaceAll(USER_LOCALE_HOLDER, locale.toString()); templateBuilder.append(replacedTemplate); } return templateBuilder.toString(); }
Source:
public void forEachMetric(BiConsumer<MetricName, Metric> consumer) { first.getMetrics().forEach(consumer); second.getMetrics().forEach(consumer); }

Target:
public void forEachMetric(BiConsumer<MetricName, Metric> consumer) { first.forEachMetric(consumer); second.forEachMetric(consumer); }
Source:
private static Optional<TimeRangeFilter> extractTimeRangeFilter(Collection<Filter> filters){ return filters.stream() .filter(f -> f instanceof TimeRangeFilter) .map(f -> (TimeRangeFilter)f) .findFirst(); }

Target:
private static TimeRangeFilter extractTimeRangeFilter(Collection<Filter> filters){ return filters.stream() .filter(f -> f instanceof TimeRangeFilter) .map(f -> (TimeRangeFilter)f) .findFirst().orElse(null); }
Source:
public static String asValidHref(String urlString) { try { return new URL(urlString).toExternalForm(); } catch (MalformedURLException e) { return ""; } }

Target:
public static String asValidHref(String urlString) { try { return new URL(urlString).toExternalForm(); } catch (MalformedURLException e) { LOG.debug("Malformed url - {}, empty string will be returned", urlString); return ""; } }