auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Set<Account.Id> findAllByNameOrEmail(final String nameOrEmail) throws OrmException { final int lt = nameOrEmail.indexOf('<'); final int gt = nameOrEmail.indexOf('>'); if (lt >= 0 && gt > lt && nameOrEmail.contains("@")) { Set<Account.Id> ids = byEmail.get(nameOrEmail.substring(lt + 1, gt)); if (ids.size() == 1) { return ids; } for (Account.Id id : ids) { Account a = byId.get(id).getAccount(); if (a.getFullName().equals(nameOrEmail.substring(0, lt - 1))) { return Collections.singleton(id); } } return ids; } if (nameOrEmail.contains("@")) { return byEmail.get(nameOrEmail); } final Account.Id id = realm.lookup(nameOrEmail); if (id != null) { return Collections.singleton(id); } List<Account> m = schema.get().accounts().byFullName(nameOrEmail).toList(); if (m.size() == 1) { return Collections.singleton(m.get(0).getId()); } Set<Account.Id> result = new HashSet<Account.Id>(); String a = nameOrEmail; String b = nameOrEmail + "\u9fa5"; for (Account act : schema.get().accounts().suggestByFullName(a, b, 10)) { result.add(act.getId()); } for (AccountExternalId extId : schema .get() .accountExternalIds() .suggestByKey( new AccountExternalId.Key(AccountExternalId.SCHEME_USERNAME, a), new AccountExternalId.Key(AccountExternalId.SCHEME_USERNAME, b), 10)) { result.add(extId.getAccountId()); } for (AccountExternalId extId : schema.get().accountExternalIds() .suggestByEmailAddress(a, b, 10)) { result.add(extId.getAccountId()); } return result; }

Target:
public Set<Account.Id> findAllByNameOrEmail(final String nameOrEmail) throws OrmException { final int lt = nameOrEmail.indexOf('<'); final int gt = nameOrEmail.indexOf('>'); if (lt >= 0 && gt > lt && nameOrEmail.contains("@")) { Set<Account.Id> ids = byEmail.get(nameOrEmail.substring(lt + 1, gt)); if (ids.isEmpty() || ids.size() == 1) { return ids; } String name = nameOrEmail.substring(0, lt - 1); Set<Account.Id> nameMatches = Sets.newHashSet(); for (Account.Id id : ids) { Account a = byId.get(id).getAccount(); if (name.equals(a.getFullName())) { nameMatches.add(id); } } return nameMatches.isEmpty() ? ids : nameMatches; } if (nameOrEmail.contains("@")) { return byEmail.get(nameOrEmail); } final Account.Id id = realm.lookup(nameOrEmail); if (id != null) { return Collections.singleton(id); } List<Account> m = schema.get().accounts().byFullName(nameOrEmail).toList(); if (m.size() == 1) { return Collections.singleton(m.get(0).getId()); } Set<Account.Id> result = new HashSet<Account.Id>(); String a = nameOrEmail; String b = nameOrEmail + "\u9fa5"; for (Account act : schema.get().accounts().suggestByFullName(a, b, 10)) { result.add(act.getId()); } for (AccountExternalId extId : schema .get() .accountExternalIds() .suggestByKey( new AccountExternalId.Key(AccountExternalId.SCHEME_USERNAME, a), new AccountExternalId.Key(AccountExternalId.SCHEME_USERNAME, b), 10)) { result.add(extId.getAccountId()); } for (AccountExternalId extId : schema.get().accountExternalIds() .suggestByEmailAddress(a, b, 10)) { result.add(extId.getAccountId()); } return result; }
Source:
public Visit createVisit(String configName, Visit visit) { validateVisit(visit); Visit createdVisit; Config config = configService.getConfigByName(configName); createdVisit = visitResource.createVisit(config, visit); eventRelay.sendEventMessage(new MotechEvent(EventKeys.CREATED_NEW_VISIT_SUBJECT, EventHelper.visitParameters(createdVisit))); return createdVisit; }

Target:
public Visit createVisit(String configName, Visit visit) { validateVisit(visit); Config config = configService.getConfigByName(configName); Visit createdVisit = visitResource.createVisit(config, visit); eventRelay.sendEventMessage(new MotechEvent(EventKeys.CREATED_NEW_VISIT_SUBJECT, EventHelper.visitParameters(createdVisit))); return createdVisit; }
Source:
public void delete() { final HaxeFile file = (HaxeFile)getContainingFile(); if(file != null) { final PsiClass[] classes = file.getClasses(); if(classes.length == 1 && classes[0] == this) { file.delete(); return; } } super.delete(); }

Target:
public void delete() { final HaxeFile file = (HaxeFile)getContainingFile(); super.delete(); if(file != null && file.getClasses().length == 0) { file.delete(); } }
Source:
void relyingPartyRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { this.contextRunner.withPropertyValues(getPropertyValues()).run((context) -> { RelyingPartyRegistrationRepository repository = context.getBean(RelyingPartyRegistrationRepository.class); RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); assertThat(registration.getProviderDetails().getWebSsoUrl()) .isEqualTo("<LINK_0>"); assertThat(registration.getProviderDetails().getEntityId()) .isEqualTo("<LINK_1>"); assertThat(registration.getAssertionConsumerServiceUrlTemplate()) .isEqualTo("{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI); assertThat(registration.getProviderDetails().getBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(registration.getProviderDetails().isSignAuthNRequest()).isEqualTo(false); assertThat(registration.getSigningCredentials()).isNotNull(); assertThat(registration.getVerificationCredentials()).isNotNull(); assertThat(registration.getLocalEntityIdTemplate()).isEqualTo("{baseUrl}/saml2/local-entity-id"); }); }

Target:
void relyingPartyRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { this.contextRunner.withPropertyValues(getPropertyValues()).run((context) -> { RelyingPartyRegistrationRepository repository = context.getBean(RelyingPartyRegistrationRepository.class); RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); assertThat(registration.getProviderDetails().getWebSsoUrl()) .isEqualTo("<LINK_0>"); assertThat(registration.getProviderDetails().getEntityId()) .isEqualTo("<LINK_1>"); assertThat(registration.getAssertionConsumerServiceUrlTemplate()) .isEqualTo("{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI); assertThat(registration.getProviderDetails().getBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(registration.getProviderDetails().isSignAuthNRequest()).isEqualTo(false); assertThat(registration.getSigningCredentials()).isNotNull(); assertThat(registration.getVerificationCredentials()).isNotNull(); assertThat(registration.getEntityId()).isEqualTo("{baseUrl}/saml2/foo-entity-id"); }); }
Source:
public SchemaPlus get() { SchemaPlus rootSchema = CalciteSchema.createRootSchema(false, false).plus(); calciteSchemas.forEach(schema -> rootSchema.add(schema.getSchemaName(), schema.getSchema())); return rootSchema; }

Target:
public SchemaPlus get() { SchemaPlus rootSchema = CalciteSchema.createRootSchema(false, false).plus(); List<String> schemaNames = namedSchemas.stream() .map(NamedSchema::getSchemaName) .collect(Collectors.toList()); Set<String> uniqueSchemaNames = new HashSet<>(schemaNames); if (uniqueSchemaNames.size() < schemaNames.size()) { throw new ISE("Found multiple schemas registered to the same name. " + "The list of registered schemas are %s", schemaNames); } namedSchemas.forEach(schema -> rootSchema.add(schema.getSchemaName(), schema.getSchema())); return rootSchema; }
Source:
public void testUMDPatternConversion() { setFilename("test"); testModules( "var foobar = {foo: 'bar'};" + "if (typeof module === 'object' && module.exports) {" + "module.exports = foobar;" + "} else if (typeof define === 'function' && define.amd) {" + "define([], function() {return foobar;});" + "} else {this.foobar = foobar;}", "goog.provide('module$test');" + "var module$test={};" + "var foobar$$module$test={foo:'bar'};" + "module$test=foobar$$module$test;"); testModules( "var foobar = {foo: 'bar'};" + "if (typeof define === 'function' && define.amd) {" + "define([], function() {return foobar;});" + "} else if (typeof module === 'object' && module.exports) {" + "module.exports = foobar;" + "} else {this.foobar = foobar;}", "goog.provide('module$test');" + "var module$test={};" + "var foobar$$module$test={foo:'bar'};" + "module$test=foobar$$module$test;"); testModules( "var foobar = {foo: 'bar'};" + "if (typeof module === 'object' && module.exports) {" + "module.exports = foobar;}" + "if (typeof define === 'function' && define.amd) {" + "define([], function () {return foobar;});}", "goog.provide('module$test');" + "var module$test={};" + "var foobar$$module$test={foo:'bar'};" + "module$test=foobar$$module$test;"); }

Target:
public void testUMDPatternConversion() { setFilename("test"); testModules( "var foobar = {foo: 'bar'};" + "if (typeof module === 'object' && module.exports) {" + " module.exports = foobar;" + "} else if (typeof define === 'function' && define.amd) {" + " define([], function() {return foobar;});" + "} else {" + " this.foobar = foobar;}", "goog.provide('module$test');" + "var foobar$$module$test = {foo: 'bar'};" + "module$test = foobar$$module$test;"); testModules( "var foobar = {foo: 'bar'};" + "if (typeof define === 'function' && define.amd) {" + " define([], function() {return foobar;});" + "} else if (typeof module === 'object' && module.exports) {" + " module.exports = foobar;" + "} else {" + " this.foobar = foobar;}", "goog.provide('module$test');" + "var foobar$$module$test = {foo: 'bar'};" + "module$test = foobar$$module$test;"); testModules( "var foobar = {foo: 'bar'};" + "if (typeof module === 'object' && module.exports) {" + " module.exports = foobar;}" + "if (typeof define === 'function' && define.amd) {" + " define([], function () {return foobar;});}", "goog.provide('module$test');" + "var foobar$$module$test = {foo: 'bar'};" + "module$test = foobar$$module$test;"); }
Source:
private void updateExportedFeedInstance(WorkflowExecutionContext context) throws FalconException { LOG.info("Adding export feed instance: {}", context.getNominalTimeAsISO8601()); instanceGraphBuilder.addExportedInstance(context); }

Target:
private void updateExportedFeedInstance(WorkflowExecutionContext context) throws FalconException { LOG.info("Updating export feed instance: {}", context.getNominalTimeAsISO8601()); instanceGraphBuilder.addExportedInstance(context); }
Source:
private void interpolateBridgesAndOrTunnels() { if (!ghStorage.getEncodingManager().supports("generic")) { logger.warn("Elevation interpolation of bridges or tunnels is turned on, but generic flag encoder is not enabled. " + "Either enable generic flag encoder using graph.flag_encoders=generic,... " + "or turn off bridge and tunnel interpolation using graph.elevation.interpolate.bridges=false and graph.elevation.interpolate.tunnels=false."); } else { final FlagEncoder genericFlagEncoder = ghStorage.getEncodingManager().getEncoder("generic"); if (!(genericFlagEncoder instanceof DataFlagEncoder)) { throw new IllegalStateException("Generic flag encoder equired for elevation interpolation of bridges and tunnels is enabled but does not habe the expected type " + DataFlagEncoder.class.getName() + "."); } else { final DataFlagEncoder dataFlagEncoder = (DataFlagEncoder) genericFlagEncoder; if (interpolateTunnels) { interpolateTunnels(dataFlagEncoder); } if (interpolateBridges) { interpolateBridges(dataFlagEncoder); } } } }

Target:
private void interpolateBridgesAndOrTunnels() { if (!ghStorage.getEncodingManager().supports("generic")) { logger.warn("Elevation interpolation of bridges or tunnels is turned on, but generic flag encoder is not enabled. " + "Please enable generic flag encoder using graph.flag_encoders=generic,... ."); } else { final FlagEncoder genericFlagEncoder = ghStorage.getEncodingManager() .getEncoder("generic"); if (!(genericFlagEncoder instanceof DataFlagEncoder)) { throw new IllegalStateException( "Generic flag encoder equired for elevation interpolation of bridges and tunnels is enabled but does not habe the expected type " + DataFlagEncoder.class.getName() + "."); } final DataFlagEncoder dataFlagEncoder = (DataFlagEncoder) genericFlagEncoder; interpolateTunnels(dataFlagEncoder); interpolateBridges(dataFlagEncoder); } }
Source:
public RequestRepresentation claim( UserAuthenticationToken user, @PathVariable String id, @RequestBody RequestRepresentation request) { log.info("PUT /requests/" + id + "/claim"); HistoricProcessInstance instance = requestService.getProcessInstance(id); requestService.claimCurrentPalgaTask(id, user.getUser()); Map<String, Object> variables = instance.getProcessVariables(); if (variables != null) { variables.put("assigned_date", new Date()); } runtimeService.setVariables(instance.getId(), variables); requestFormService.invalidateCacheEntry(id); instance = requestService.getProcessInstance(id); RequestRepresentation updatedRequest = new RequestRepresentation(); requestFormService.transferData(instance, updatedRequest, user.getUser()); if (updatedRequest.getAssigneeName() != null) { requestFormService.updateLastAssignee(instance.getId(), updatedRequest.getAssigneeName()); } return updatedRequest; }

Target:
public RequestRepresentation claim( UserAuthenticationToken user, @PathVariable String id, @RequestBody RequestRepresentation request) { log.info("PUT /requests/" + id + "/claim"); HistoricProcessInstance instance = requestService.getProcessInstance(id); requestService.claimCurrentPalgaTask(id, user.getUser()); Map<String, Object> variables = instance.getProcessVariables(); if (variables != null) { variables.put("assigned_date", new Date()); } runtimeService.setVariables(instance.getId(), variables); requestFormService.invalidateCacheEntry(id); instance = requestService.getProcessInstance(id); RequestRepresentation updatedRequest = new RequestRepresentation(); requestFormService.transferData(instance, updatedRequest, user.getUser()); if (updatedRequest.getAssignee() != null) { requestFormService.updateLastAssignee(instance.getId(), updatedRequest.getAssignee()); } return updatedRequest; }
Source:
public void initClusterConnection(Executor asyncWorker) { this.asyncWorker = asyncWorker; try { connect(); } catch (ConnectionException ex) { LOGGER.error("Initial connection failed due to", ex); throw new RuntimeException(ex); } }

Target:
public void initClusterConnection(Executor asyncWorker) { this.asyncWorker = requireNonNull(asyncWorker); try { connect(); } catch (ConnectionException ex) { LOGGER.error("Initial connection failed due to", ex); throw new RuntimeException(ex); } }
Source:
public void setAttributeMap(List<String> attributeMappings) { if (CollectionUtils.isEmpty(attributeMappings) || (attributeMappings.size() == 1 && attributeMappings.get(0).isEmpty())) { attributeMap = new HashMap<>(); return; } for (String attributeMapping : attributeMappings) { String[] keyValue = attributeMapping.split("="); attributeMap.put( keyValue[0].trim(), Arrays.asList(keyValue[1].split(",")) .stream() .map(String::trim) .collect(Collectors.toList())); } }

Target:
public void setAttributeMap(List<String> attributeMappings) { if (CollectionUtils.isEmpty(attributeMappings) || (attributeMappings.size() == 1 && attributeMappings.get(0).isEmpty())) { attributeMap = new HashMap<>(); return; } for (String attributeMapping : attributeMappings) { String[] keyValue = attributeMapping.split("="); attributeMap.put( keyValue[0].trim(), Arrays.stream(keyValue[1].split(",")).map(String::trim).collect(Collectors.toList())); } }
Source:
public void setScript(@Nonnull Location l, @Nonnull String script) { BlockStorage.addBlockInfo(l, "script", script); }

Target:
public void setScript(@Nonnull Location l, @Nonnull String script) { Validate.notNull(l, "Location for android not specified"); Validate.notNull(script, "No script given"); BlockStorage.addBlockInfo(l, "script", script); }
Source:
private void getProcessDMContexts(Object[] elements, final DataRequestMonitor<IProcessDMContext[]> rm) { GdbLaunch launch = null; final Set<IProcessDMContext> procDmcs = new HashSet<IProcessDMContext>(); for (Object obj : elements) { if (obj instanceof GdbLaunch) { launch = (GdbLaunch)obj; break; } if (obj instanceof IDMVMContext) { IProcessDMContext procDmc = DMContexts.getAncestorOfType(((IDMVMContext)obj).getDMContext(), IProcessDMContext.class); if (procDmc != null) { procDmcs.add(procDmc); } } } if (launch == null) { rm.setData(procDmcs.toArray(new IProcessDMContext[procDmcs.size()])); rm.done(); } else { try { fExecutor.execute(new DsfRunnable() { @Override public void run() { ICommandControlService commandControl = fTracker.getService(ICommandControlService.class); final IProcesses procService = fTracker.getService(IProcesses.class); if (commandControl != null && procService != null) { procService.getProcessesBeingDebugged( commandControl.getContext(), new ImmediateDataRequestMonitor<IDMContext[]>() { @Override protected void handleCompleted() { if (!isSuccess()) { rm.setStatus(getStatus()); } else { for (IDMContext ctx : getData()) { IProcessDMContext procDmc = DMContexts.getAncestorOfType(ctx, IProcessDMContext.class); if (procDmc != null) { procDmcs.add(procDmc); } } rm.setData(procDmcs.toArray(new IProcessDMContext[procDmcs.size()])); } rm.done(); }; }); } else { rm.setStatus(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Service is not available.")); rm.done(); } } }); } catch (RejectedExecutionException e) { rm.setStatus(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, e.getLocalizedMessage())); rm.done(); } } }

Target:
private void getProcessDMContexts(Object[] elements, final DataRequestMonitor<IProcessDMContext[]> rm) { final Set<IProcessDMContext> procDmcs = new HashSet<IProcessDMContext>(); for (Object obj : elements) { if (obj instanceof IDMVMContext) { IProcessDMContext procDmc = DMContexts.getAncestorOfType(((IDMVMContext)obj).getDMContext(), IProcessDMContext.class); if (procDmc != null) { procDmcs.add(procDmc); } } } try { fExecutor.execute(new DsfRunnable() { @Override public void run() { ICommandControlService commandControl = fTracker.getService(ICommandControlService.class); final IProcesses procService = fTracker.getService(IProcesses.class); if (commandControl != null && procService != null) { procService.getProcessesBeingDebugged( commandControl.getContext(), new ImmediateDataRequestMonitor<IDMContext[]>() { @Override protected void handleCompleted() { if (!isSuccess()) { rm.setStatus(getStatus()); } else { for (IDMContext ctx : getData()) { IProcessDMContext procDmc = DMContexts.getAncestorOfType(ctx, IProcessDMContext.class); if (procDmc != null) { procDmcs.add(procDmc); } } rm.setData(procDmcs.toArray(new IProcessDMContext[procDmcs.size()])); } rm.done(); }; }); } else { rm.setStatus(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Service is not available.")); rm.done(); } } }); } catch (RejectedExecutionException e) { rm.setStatus(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, e.getLocalizedMessage())); rm.done(); } }
Source:
protected static Collection<RequirementMatcher> getRestrictionMatcherCDI11() { return Arrays.asList(new RequirementMatcher(JBossServer.class, FAMILY, ServerMatcher.WildFly()), new RequirementMatcher(JBossServer.class, VERSION, "18"), new RequirementMatcher(JRE.class, VERSION, "1.8")); }

Target:
protected static Collection<RequirementMatcher> getRestrictionMatcherCDI11() { return Arrays.asList(new RequirementMatcher(JBossServer.class, FAMILY, ServerMatcher.WildFly()), new RequirementMatcher(JBossServer.class, VERSION, "13"), new RequirementMatcher(JRE.class, VERSION, "1.8")); }
Source:
public Set<String> getPendingDocIDs() throws LiteCoreException { synchronized (lock) { if (handle == 0) { return null; } FLSliceResult result = new FLSliceResult(getPendingDocIds(handle)); return null; } }

Target:
public Set<String> getPendingDocIDs() throws LiteCoreException { synchronized (lock) { if (handle == 0) { return null; } final FLSliceResult result = new FLSliceResult(getPendingDocIds(handle)); try { final FLValue slice = FLValue.fromData(result); return (slice == null) ? Collections.emptySet() : new HashSet<>(slice.asTypedArray()); } finally { result.free(); } } }
Source:
public Features(ClassLoader classLoader) { features = new Properties(); try { Enumeration<URL> featureFiles = classLoader.getResources(FEATURES_FILE); while (featureFiles.hasMoreElements()) { URL url = featureFiles.nextElement(); try (InputStream is = url.openStream()) { features.load(is); } catch (IOException e) { } } } catch (IOException e) { } }

Target:
public Features(ClassLoader classLoader) { features = new Properties(); try { Enumeration<URL> featureFiles = classLoader.getResources(FEATURES_FILE); while (featureFiles.hasMoreElements()) { URL url = featureFiles.nextElement(); try (InputStream is = url.openStream()) { features.load(is); } } if (log.isDebugEnabled()) { features.entrySet().forEach(e -> log.debugf("Feature %s=%s", e.getKey(), e.getValue())); } } catch (IOException e) { log.debugf(e, "Error while attempting to obtain `%s` resources from the classpath", FEATURES_FILE); throw new CacheConfigurationException(e); } }
Source:
public void addAttributesToTooltip(GetItemTooltip event, EntityRef entity, OreonAttributeComponent oreonAttributeComponent) { event.getTooltipLines().add(new TooltipLine("Level : " + oreonAttributeComponent.currentLevel)); event.getTooltipLines().add(new TooltipLine("Health : " + oreonAttributeComponent.health + " / " + oreonAttributeComponent.maxStrength )); event.getTooltipLines().add(new TooltipLine("Hunger : " + oreonAttributeComponent.hunger)); event.getTooltipLines().add(new TooltipLine("Strength : " + oreonAttributeComponent.strength + " / " + oreonAttributeComponent.maxStrength )); event.getTooltipLines().add(new TooltipLine("Intelligence : " + oreonAttributeComponent.intelligence + " / " + oreonAttributeComponent.maxIntelligence )); }

Target:
public void addAttributesToTooltip(GetItemTooltip event, EntityRef entity, OreonAttributeComponent oreonAttributeComponent) { event.getTooltipLines().add(new TooltipLine("Level : " + oreonAttributeComponent.currentLevel)); event.getTooltipLines().add(new TooltipLine("Health : " + oreonAttributeComponent.health + " / " + oreonAttributeComponent.maxHealth)); event.getTooltipLines().add(new TooltipLine("Hunger : " + oreonAttributeComponent.hunger)); event.getTooltipLines().add(new TooltipLine("Strength : " + oreonAttributeComponent.strength + " / " + oreonAttributeComponent.maxStrength )); event.getTooltipLines().add(new TooltipLine("Intelligence : " + oreonAttributeComponent.intelligence + " / " + oreonAttributeComponent.maxIntelligence )); }
Source:
public void shouldSendApplePayRequestWhenApplePayDetailsArePresent() throws Exception { try { worldpayApplePayAuthorisationHandler.authorise(getApplePayAuthorisationRequest()); } catch (GatewayErrorException e) { gatewayOrderArgumentCaptor = ArgumentCaptor.forClass(GatewayOrder.class); headers = ArgumentCaptor.forClass(Map.class); verify(mockGatewayClient).postRequestFor(eq(WORLDPAY_URL), eq(gatewayAccountEntity), gatewayOrderArgumentCaptor.capture(), headers.capture()); assertXMLEqual(TestTemplateResourceLoader.load(WORLDPAY_VALID_AUTHORISE_WORLDPAY_APPLE_PAY_REQUEST), gatewayOrderArgumentCaptor.getValue().getPayload()); assertThat(headers.getValue().size(), is(1)); assertThat(headers.getValue(), is(AuthUtil.getGatewayAccountCredentialsAsAuthHeader(gatewayAccountEntity))); } }

Target:
public void shouldSendApplePayRequestWhenApplePayDetailsArePresent() throws Exception { try { worldpayApplePayAuthorisationHandler.authorise(getApplePayAuthorisationRequest()); } catch (GatewayErrorException e) { verify(mockGatewayClient).postRequestFor(eq(WORLDPAY_URL), eq(gatewayAccountEntity), gatewayOrderArgumentCaptor.capture(), headers.capture()); assertXMLEqual(TestTemplateResourceLoader.load(WORLDPAY_VALID_AUTHORISE_WORLDPAY_APPLE_PAY_REQUEST), gatewayOrderArgumentCaptor.getValue().getPayload()); assertThat(headers.getValue().size(), is(1)); assertThat(headers.getValue(), is(AuthUtil.getGatewayAccountCredentialsAsAuthHeader(gatewayAccountEntity))); } }
Source:
private MessageContent getMessageContent(Message message) { return new MessageContent.Builder() .withContentType(message.getContentType()) .withSchema(message.getSchema()) .withData(message.getData()) .build(); }

Target:
private MessageContent getMessageContent(Message message) { return new MessageContent.Builder() .withContentType(message.getContentType()) .withSchema(message.getSchema()) .withContent(message.getData()) .build(); }
Source:
private void updateActionAvailability() { getNewCommand().setIsExecutionAllowed(true); boolean hasSelectedItems = getSelectedItems() != null && getSelectedItems().size() > 0; getEditCommand().setIsExecutionAllowed(hasSelectedItems && getSelectedItems().size() == 1); getRemoveCommand().setIsExecutionAllowed(hasSelectedItems); }

Target:
private void updateActionAvailability() { boolean hasSelectedItems = getSelectedItems() != null && getSelectedItems().size() > 0; getEditCommand().setIsExecutionAllowed(hasSelectedItems && getSelectedItems().size() == 1); getRemoveCommand().setIsExecutionAllowed(hasSelectedItems); }
Source:
public QuestionableActivityListingDTO checkNonCuresAuditCriteriaAndAddedIcsOnEdit(CertifiedProductSearchDetails origListing, CertifiedProductSearchDetails newListing) { QuestionableActivityListingDTO activity = null; if (ff4j.check(FeatureList.EFFECTIVE_RULE_DATE)) { if (!origListing.getIcs().getInherits() && newListing.getIcs().getInherits()) { List<String> matchingNewCriteriaNumbers = new ArrayList<String>(); List<String> matchingOldCriteriaNumbers = new ArrayList<String>(); if (isCriteriaAttestedTo(d2Criterion, newListing)) { matchingNewCriteriaNumbers.add(d2Criterion.getNumber()); } if (isCriteriaAttestedTo(d3Criterion, newListing)) { matchingNewCriteriaNumbers.add(d3Criterion.getNumber()); } if (isCriteriaAttestedTo(d10Criterion, newListing)) { matchingNewCriteriaNumbers.add(d10Criterion.getNumber()); } if (matchingNewCriteriaNumbers.size() > 0) { if (isCriteriaAttestedTo(d2Criterion, origListing)) { matchingOldCriteriaNumbers.add(d2Criterion.getNumber()); } if (isCriteriaAttestedTo(d3Criterion, origListing)) { matchingOldCriteriaNumbers.add(d3Criterion.getNumber()); } if (isCriteriaAttestedTo(d10Criterion, origListing)) { matchingOldCriteriaNumbers.add(d10Criterion.getNumber()); } String newCriteriaNumbers = matchingNewCriteriaNumbers.stream() .collect(Collectors.joining(", ")); String oldCriteriaNumbers = matchingOldCriteriaNumbers.stream() .collect(Collectors.joining(", ")); activity = new QuestionableActivityListingDTO(); activity.setBefore("ICS = 0, Criteria Numbers: " + oldCriteriaNumbers); activity.setAfter("ICS = 1, Criteria Numbers: " + newCriteriaNumbers); } } } return activity; }

Target:
public QuestionableActivityListingDTO checkNonCuresAuditCriteriaAndAddedIcsOnEdit(CertifiedProductSearchDetails origListing, CertifiedProductSearchDetails newListing) { QuestionableActivityListingDTO activity = null; if (ff4j.check(FeatureList.EFFECTIVE_RULE_DATE)) { if (!hasICS(origListing) && hasICS(newListing)) { List<String> matchingNewCriteriaNumbers = new ArrayList<String>(); List<String> matchingOldCriteriaNumbers = new ArrayList<String>(); if (isCriteriaAttestedTo(d2Criterion, newListing)) { matchingNewCriteriaNumbers.add(d2Criterion.getNumber()); } if (isCriteriaAttestedTo(d3Criterion, newListing)) { matchingNewCriteriaNumbers.add(d3Criterion.getNumber()); } if (isCriteriaAttestedTo(d10Criterion, newListing)) { matchingNewCriteriaNumbers.add(d10Criterion.getNumber()); } if (matchingNewCriteriaNumbers.size() > 0) { String newCriteriaNumbers = matchingNewCriteriaNumbers.stream() .collect(Collectors.joining(", ")); activity = new QuestionableActivityListingDTO(); activity.setAfter(newCriteriaNumbers); } } } return activity; }
Source:
private String toJson(Map<String, Object> arguments) { final ObjectMapper mapper = new ObjectMapper(); ObjectNode jsonObject = mapper.createObjectNode(); arguments.forEach((s, o) -> jsonObject.set(s, mapper.convertValue(o, JsonNode.class))); return jsonObject.toString(); }

Target:
private String toJson(Map<String, Object> arguments) { try { return new ObjectMapper().writeValueAsString(arguments); } catch (JsonProcessingException e) { throw new RuntimeException("Failed to convert arguments into json: " + e.getMessage(), e); } }
Source:
public void read_all_messages_with_field_mask() { final int count = 5; final List<I> ids = new LinkedList<>(); final String projectDescriptor = Project.getDescriptor() .getFullName(); @SuppressWarnings("DuplicateStringLiteralInspection") final FieldMask fieldMask = FieldMask.newBuilder() .addPaths(projectDescriptor + ".id") .addPaths(projectDescriptor + ".name") .build(); for (int i = 0; i < count; i++) { final I id = newId(); final ProjectId stateId = ProjectId.newBuilder() .setId(id.toString()) .build(); final Project state = Project.newBuilder() .setId(stateId) .setName(String.format("project_%s", i)) .setStatus(Project.Status.CREATED) .build(); final Any packedState = AnyPacker.pack(state); final EntityStorageRecord record = EntityStorageRecord.newBuilder() .setState(packedState) .setWhenModified(Timestamps.getCurrentTime()) .setVersion(1) .build(); storage.write(id, record); ids.add(id); } final Map<I, EntityStorageRecord> read = storage.readAll(fieldMask); assertSize(ids.size(), read); for (Map.Entry<I, EntityStorageRecord> record : read.entrySet()) { assertContains(record.getKey(), ids); final Any packedState = record.getValue() .getState(); final Project state = AnyPacker.unpack(packedState); assertMatchesMask(state, fieldMask); } }

Target:
public void read_all_messages_with_field_mask() { final List<I> ids = fillStorage(5); final String projectDescriptor = Project.getDescriptor() .getFullName(); @SuppressWarnings("DuplicateStringLiteralInspection") final FieldMask fieldMask = maskForPaths(projectDescriptor + ".id", projectDescriptor + ".name"); final Map<I, EntityStorageRecord> read = storage.readAll(fieldMask); assertSize(ids.size(), read); for (Map.Entry<I, EntityStorageRecord> record : read.entrySet()) { assertContains(record.getKey(), ids); final Any packedState = record.getValue() .getState(); final Project state = AnyPacker.unpack(packedState); assertMatchesMask(state, fieldMask); } }
Source:
public void scroll (int destX, int destY, int x, int y, int width, int height, boolean all) { checkWidget(); if (width <= 0 || height <= 0 || GTK.GTK4) return; Point destination = DPIUtil.autoScaleUp (new Point (destX, destY)); Rectangle srcRect = DPIUtil.autoScaleUp (new Rectangle (x, y, width, height)); scrollInPixels(destination.x, destination.y, srcRect.x, srcRect.y, srcRect.width, srcRect.height, all); }

Target:
public void scroll (int destX, int destY, int x, int y, int width, int height, boolean all) { checkWidget(); if (width <= 0 || height <= 0) return; if (GTK.GTK4) return; Point destination = DPIUtil.autoScaleUp (new Point (destX, destY)); Rectangle srcRect = DPIUtil.autoScaleUp (new Rectangle (x, y, width, height)); scrollInPixels(destination.x, destination.y, srcRect.x, srcRect.y, srcRect.width, srcRect.height, all); }
Source:
public void Case4() { NumberExpression<Float> numExpression = cat.bodyWeight.floatValue().divide(otherCat.bodyWeight.floatValue()).multiply(100); NumberExpression<Float> numExpression2 = cat.id.when(0).then(0.0F).otherwise(numExpression); query().from(cat, otherCat).list(numExpression2); }

Target:
public void Case4() { NumberExpression<Float> numExpression = cat.bodyWeight.floatValue().divide(otherCat.bodyWeight.floatValue()).multiply(100); NumberExpression<Float> numExpression2 = cat.id.when(0).then(0.0F).otherwise(numExpression); assertEquals(ImmutableList.of(200, 150, 133, 125, 120), query().from(cat, otherCat) .where(cat.id.eq(otherCat.id.add(1))) .orderBy(cat.id.asc(), otherCat.id.asc()) .list(numExpression2.intValue())); }
Source:
DirectCodecFactory(Configuration config, ByteBufferAllocator allocator, int pageSize) { super(config, pageSize); this.allocator = Objects.requireNonNull(allocator, "allocator"); Preconditions.checkState(allocator.isDirect(), "A %s requires a direct buffer allocator be provided.", getClass().getSimpleName()); }

Target:
DirectCodecFactory(Configuration config, ByteBufferAllocator allocator, int pageSize) { super(config, pageSize); this.allocator = Objects.requireNonNull(allocator, "allocator cannot be null"); Preconditions.checkState(allocator.isDirect(), "A %s requires a direct buffer allocator be provided.", getClass().getSimpleName()); }
Source:
public void convertWithConfluentAvroBytesConverter() { Schema schema = SimpleRecord.getClassSchema(); KafkaSerDe.AvroSkipBytesConverter conv = new KafkaSerDe.AvroSkipBytesConverter(schema, 5); AvroGenericRecordWritable simpleRecord1Writable = conv.getWritable(simpleRecord1AsBytes); Assert.assertNotNull(simpleRecord1Writable); Assert.assertEquals(SimpleRecord.class, simpleRecord1Writable.getRecord().getClass()); SimpleRecord simpleRecord1Deserialized = (SimpleRecord) simpleRecord1Writable.getRecord(); Assert.assertNotNull(simpleRecord1Deserialized); Assert.assertEquals(simpleRecord1, simpleRecord1Deserialized); }

Target:
public void convertWithConfluentAvroBytesConverter() throws SerDeException { Integer offset = 5; Properties tbl = new Properties(); tbl.setProperty(AvroSerdeUtils.AvroTableProperties.AVRO_SERDE_TYPE.getPropName(), "SKIP"); tbl.setProperty(AvroSerdeUtils.AvroTableProperties.AVRO_SERDE_SKIP_BYTES.getPropName(), offset.toString()); runConversionTest(tbl, simpleRecordConfluentBytes); }
Source:
protected void setMuteButton(final ImageButton muteButton, final boolean isMuted) { if (isMuted) { muteButton.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.white)); } else { muteButton.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.gray)); } }

Target:
protected void setMuteButton(final ImageButton muteButton, final boolean isMuted) { muteButton.setColorFilter(ContextCompat.getColor(getApplicationContext(), isMuted ? R.color.white : R.color.gray)); }
Source:
public synchronized void setOkHttpClient(OkHttpClient okHttpClient) { if (OK_CLIENTS == null) { OK_CLIENTS = new HashMap<>(); } final String uniqueId = this.oAuthRefreshInterceptor.clientInfo.buildUniqueId(); OkHttpClient curOkHttpClient = null; if (uniqueId != null) { curOkHttpClient = OK_CLIENTS.get(uniqueId); if (curOkHttpClient == null) { if (okHttpClient == null) { curOkHttpClient = getOkHttpClientBuilder().build(); OK_CLIENTS.put(uniqueId, curOkHttpClient); } else { OK_CLIENTS.put(uniqueId, okHttpClient); } } else if (okHttpClient != null) { OK_CLIENTS.put(uniqueId, okHttpClient); } } this.okHttpClient = OK_CLIENTS.get(uniqueId); }

Target:
public synchronized void setOkHttpClient(OkHttpClient okHttpClient) { if (OK_CLIENTS == null) { OK_CLIENTS = new HashMap<>(); } final String uniqueId = this.oAuthRefreshInterceptor.clientInfo.buildUniqueId(); if (uniqueId == null) { return; } if (okHttpClient != null) { OK_CLIENTS.put(uniqueId, okHttpClient); } else if (!OK_CLIENTS.containsKey(uniqueId)) { OK_CLIENTS.put(uniqueId, getOkHttpClientBuilder().build()); } this.okHttpClient = OK_CLIENTS.get(uniqueId); }
Source:
public Iterable<Object> loadObjects(Class<?> entityClass, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination, RequestScope scope) { Map<String, Object> data = dataStore.get(entityClass); synchronized (data) { if (filterExpression.isPresent()) { Predicate predicate = filterExpression.get().accept(new InMemoryFilterVisitor(scope)); return data.values().stream() .filter(predicate::test) .collect(Collectors.toList()); } List<Object> results = new ArrayList<>(); data.values().forEach(results::add); return results; } }

Target:
public Iterable<Object> loadObjects(Class<?> entityClass, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination, RequestScope scope) { synchronized (dataStore) { Map<String, Object> data = dataStore.get(entityClass); if (filterExpression.isPresent()) { Predicate predicate = filterExpression.get().accept(new InMemoryFilterVisitor(scope)); return data.values().stream() .filter(predicate::test) .collect(Collectors.toList()); } List<Object> results = new ArrayList<>(); data.values().forEach(results::add); return results; } }
Source:
private Component newComponent(final ByteBuf buf, final int offset) { final int srcIndex = buf.readerIndex(); final int len = buf.writerIndex() - buf.readerIndex(); ByteBuf unwrapped = buf; int unwrappedIndex = srcIndex; while (unwrapped instanceof WrappedByteBuf || unwrapped instanceof SwappedByteBuf) { unwrapped = unwrapped.unwrap(); } if (unwrapped instanceof AbstractUnpooledSlicedByteBuf) { unwrappedIndex += ((AbstractUnpooledSlicedByteBuf) unwrapped).idx(0); unwrapped = unwrapped.unwrap(); } else if (unwrapped instanceof PooledSlicedByteBuf) { unwrappedIndex += ((PooledSlicedByteBuf) unwrapped).adjustment; unwrapped = unwrapped.unwrap(); } else if (unwrapped instanceof DuplicatedByteBuf || unwrapped instanceof PooledDuplicatedByteBuf) { unwrapped = unwrapped.unwrap(); } final ByteBuf slice = buf.capacity() == len ? buf : null; return new Component(buf.order(ByteOrder.BIG_ENDIAN), srcIndex, unwrapped.order(ByteOrder.BIG_ENDIAN), unwrappedIndex, offset, len, slice); }

Target:
private Component newComponent(final ByteBuf buf, final int offset) { final int srcIndex = buf.readerIndex(); final int len = buf.readableBytes(); ByteBuf unwrapped = buf; int unwrappedIndex = srcIndex; while (unwrapped instanceof WrappedByteBuf || unwrapped instanceof SwappedByteBuf) { unwrapped = unwrapped.unwrap(); } if (unwrapped instanceof AbstractUnpooledSlicedByteBuf) { unwrappedIndex += ((AbstractUnpooledSlicedByteBuf) unwrapped).idx(0); unwrapped = unwrapped.unwrap(); } else if (unwrapped instanceof PooledSlicedByteBuf) { unwrappedIndex += ((PooledSlicedByteBuf) unwrapped).adjustment; unwrapped = unwrapped.unwrap(); } else if (unwrapped instanceof DuplicatedByteBuf || unwrapped instanceof PooledDuplicatedByteBuf) { unwrapped = unwrapped.unwrap(); } final ByteBuf slice = buf.capacity() == len ? buf : null; return new Component(buf.order(ByteOrder.BIG_ENDIAN), srcIndex, unwrapped.order(ByteOrder.BIG_ENDIAN), unwrappedIndex, offset, len, slice); }
Source:
public static InitCommand init() { return new InitCommand(); }

Target:
static public InitCommand init() { return new InitCommand(); }
Source:
private NamespaceIdentifier getNamespaceIdentifierInstance() { if (namespaceIdentifierInstance == null) { ArrayList<String> name = new ArrayList<String>(1); name.add("whdl"); namespaceIdentifierInstance = new NamespaceIdentifier(name); } return namespaceIdentifierInstance; }

Target:
private NamespaceIdentifier getNamespaceIdentifierInstance() { ArrayList<String> name = new ArrayList<String>(1); name.add("whdl"); return new NamespaceIdentifier(name); }
Source:
public CompositeDriverExecutionProfile refresh() { try { primaryProfile = primaryConfig.getProfile(profileName); } catch (IllegalArgumentException e) { primaryProfile = null; } try { fallbackProfile = fallbackConfig.getProfile(profileName); } catch (IllegalArgumentException e) { fallbackProfile = null; } Preconditions.checkArgument( primaryProfile != null || fallbackProfile != null, "Unknown profile '%s'. Check your configuration.", profileName); return this; }

Target:
public CompositeDriverExecutionProfile refresh() { return refreshInternal(); }
Source:
public void onNext(ReadRowsResponse response) { List<CellChunk> cellChunks = response.getChunksList(); if (cellChunks.isEmpty()) { log.warn("Got empty cell chunk list"); return; } log.trace("Got cell chunks", response.getChunksList().size()); cellChunkHandler.set(cellChunkHandler.get().consumeChunks(cellChunks)); lastQualifierRef.set(cellChunks.get(cellChunks.size() - 1).getQualifier().getValue()); }

Target:
public void onNext(ReadRowsResponse response) { List<CellChunk> cellChunks = response.getChunksList(); if (cellChunks.isEmpty()) { log.warn("Got empty cell chunk list"); return; } log.trace("Got cell chunks", response.getChunksList().size()); cellChunkHandler = cellChunkHandler.consumeChunks(cellChunks); lastQualifierRef = cellChunks.get(cellChunks.size() - 1).getQualifier().getValue(); }
Source:
boolean isDefaultExceptionMapperDisabled() { Object prop = getConfiguration().getProperty(CONFIG_KEY_DISABLE_MAPPER); if (prop instanceof Boolean) { return (Boolean)prop; } else { Config config = ConfigProvider.getConfig(); Optional<Boolean> optionalValue = config.getOptionalValue(CONFIG_KEY_DISABLE_MAPPER, Boolean.class); if (optionalValue.isPresent()) { return optionalValue.get(); } } return false; }

Target:
boolean isDefaultExceptionMapperDisabled() { Object prop = getConfiguration().getProperty(CONFIG_KEY_DISABLE_MAPPER); if (prop instanceof Boolean) { return (Boolean)prop; } return ConfigFacade.getOptionalValue(CONFIG_KEY_DISABLE_MAPPER, Boolean.class).orElse(false); }
Source:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { IdleStateEvent e = null; if (evt instanceof IdleStateEvent) { e = (IdleStateEvent) evt; if (e.state() == IdleState.WRITER_IDLE) { if (isProcessing(ctx)) { logger.trace("keep alive"); ChannelFuture f = ctx.writeAndFlush(new Ack(Protocol.VERSION_2, 0)); if (logger.isTraceEnabled()) { f.addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { logger.trace("Keep alive Success"); } else { logger.trace("Not success"); } }); } } else { logger.warn("not processing so no keep alive"); } } else if (e.state() == IdleState.ALL_IDLE) { logger.debug("idle state, all idle, timeout reaching could if this happen it could mean logstash is under backpressure."); ctx.close(); } } }

Target:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { IdleStateEvent e = null; if (evt instanceof IdleStateEvent) { e = (IdleStateEvent) evt; if (e.state() == IdleState.WRITER_IDLE) { if (isProcessing(ctx)) { ChannelFuture f = ctx.writeAndFlush(new Ack(Protocol.VERSION_2, 0)); if (logger.isTraceEnabled()) { logger.trace("sending keep alive ack to libbeat"); f.addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { logger.trace("acking was successful"); } else { logger.trace("acking failed"); } }); } } } else if (e.state() == IdleState.ALL_IDLE) { logger.debug("reader and writer are idle, closing remote connection"); ctx.flush(); ChannelFuture f = ctx.close(); f.addListener((future) ->{ if (future.isSuccess()){ logger.warn("success"); } else { logger.warn("could not close the ctx"); } }); } } }
Source:
public static RenderScript create(Context ctx, ContextType ct, int flags) { int v = ctx.getApplicationInfo().targetSdkVersion; if (v < 23) { return internalCreate(ctx, v, ct, flags); } for (RenderScript prs : mProcessContextList) { if ((prs.mContextType == ct) && (prs.mContextFlags == flags) && (prs.mContextSdkVersion == v)) { return prs; } } RenderScript prs = internalCreate(ctx, v, ct, flags); prs.mIsProcessContext = true; mProcessContextList.add(prs); return prs; }

Target:
public static RenderScript create(Context ctx, ContextType ct, int flags) { int v = ctx.getApplicationInfo().targetSdkVersion; if (v < 23) { return internalCreate(ctx, v, ct, flags); } synchronized (mProcessContextList) { for (RenderScript prs : mProcessContextList) { if ((prs.mContextType == ct) && (prs.mContextFlags == flags) && (prs.mContextSdkVersion == v)) { return prs; } } } RenderScript prs = internalCreate(ctx, v, ct, flags); synchronized (mProcessContextList) { prs.mIsProcessContext = true; mProcessContextList.add(prs); } return prs; }
Source:
public void testPartitionManagedLockReleaseOnInterruptException() throws InterruptedException { Datastream datastream = KafkaMirrorMakerConnectorTestUtils.createDatastream("pizzaStream", _broker, "\\w+Pizza"); DatastreamTaskImpl task = new DatastreamTaskImpl(Collections.singletonList(datastream)); DatastreamEventProducer mockDatastreamEventProducer = mock(DatastreamEventProducer.class); doThrow(InterruptException.class).when(mockDatastreamEventProducer).flush(); doNothing().when(mockDatastreamEventProducer).send(any(DatastreamProducerRecord.class), any(SendCallback.class)); task.setEventProducer(mockDatastreamEventProducer); KafkaBasedConnectorConfig connectorConfig = new KafkaBasedConnectorConfigBuilder() .setConsumerFactory(new LiKafkaConsumerFactory()) .setCommitIntervalMillis(10000) .setEnablePartitionManaged(true) .build(); ZkAdapter zkAdatper = new ZkAdapter(_kafkaCluster.getZkConnection(), "testCluster", null, ZkClient.DEFAULT_SESSION_TIMEOUT, ZkClient.DEFAULT_CONNECTION_TIMEOUT, null); task.setZkAdapter(zkAdatper); zkAdatper.connect(); KafkaMirrorMakerConnectorTaskTest connectorTask = new KafkaMirrorMakerConnectorTaskTest(connectorConfig, task, "", false, new KafkaMirrorMakerGroupIdConstructor(false, "testCluster")); Thread connectorThread = new Thread(connectorTask, "connector thread"); connectorThread.setDaemon(true); AtomicReference<Throwable> uncaughtException = new AtomicReference<>(); connectorThread.setUncaughtExceptionHandler((t, e) -> uncaughtException.set(e)); connectorThread.start(); if (!connectorTask.awaitStart(60, TimeUnit.SECONDS)) { Assert.fail("connector did not start within timeout"); } connectorThread.join(); Assert.assertFalse(connectorTask.isPostShutdownHookExceptionCaught()); }

Target:
public void testPartitionManagedLockReleaseOnInterruptException() throws InterruptedException { Datastream datastream = KafkaMirrorMakerConnectorTestUtils.createDatastream("pizzaStream", _broker, "\\w+Pizza"); DatastreamTaskImpl task = new DatastreamTaskImpl(Collections.singletonList(datastream)); DatastreamEventProducer mockDatastreamEventProducer = mock(DatastreamEventProducer.class); doThrow(InterruptException.class).when(mockDatastreamEventProducer).flush(); task.setEventProducer(mockDatastreamEventProducer); KafkaBasedConnectorConfig connectorConfig = new KafkaBasedConnectorConfigBuilder() .setConsumerFactory(new LiKafkaConsumerFactory()) .setCommitIntervalMillis(10000) .setEnablePartitionManaged(true) .build(); ZkAdapter zkAdatper = new ZkAdapter(_kafkaCluster.getZkConnection(), "testCluster", null, ZkClient.DEFAULT_SESSION_TIMEOUT, ZkClient.DEFAULT_CONNECTION_TIMEOUT, null); task.setZkAdapter(zkAdatper); zkAdatper.connect(); KafkaMirrorMakerConnectorTaskTest connectorTask = new KafkaMirrorMakerConnectorTaskTest(connectorConfig, task, "", false, new KafkaMirrorMakerGroupIdConstructor(false, "testCluster")); Thread connectorThread = KafkaMirrorMakerConnectorTestUtils.runKafkaMirrorMakerConnectorTask(connectorTask); connectorThread.join(); Assert.assertFalse(connectorTask.isPostShutdownHookExceptionCaught()); }
Source:
private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix, int reqWidth, int reqHeight) { int matrixWidth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); int outputWidth = Math.max(reqWidth, matrixWidth); int outputHeight = Math.max(reqHeight, matrixHeight); int multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight); int leftPadding = (outputWidth - (matrixWidth * multiple)) / 2 ; int topPadding = (outputHeight - (matrixHeight * multiple)) / 2 ; BitMatrix output; if (reqHeight < matrixHeight || reqWidth < matrixWidth) { leftPadding = topPadding = 0 ; output = new BitMatrix(matrixWidth, matrixHeight); } else { output = new BitMatrix(reqWidth, reqHeight); } output.clear(); for (int inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) { for (int inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) { if (matrix.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; }

Target:
private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix, int reqWidth, int reqHeight) { int matrixWidth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); int outputWidth = Math.max(reqWidth, matrixWidth); int outputHeight = Math.max(reqHeight, matrixHeight); int multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight); int leftPadding = (outputWidth - (matrixWidth * multiple)) / 2 ; int topPadding = (outputHeight - (matrixHeight * multiple)) / 2 ; BitMatrix output; if (reqHeight < matrixHeight || reqWidth < matrixWidth) { leftPadding = 0; topPadding = 0; output = new BitMatrix(matrixWidth, matrixHeight); } else { output = new BitMatrix(reqWidth, reqHeight); } output.clear(); for (int inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) { for (int inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) { if (matrix.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; }