auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected AbstractObjectConfigurationProvider(ObjectMapper mapper) { this.mapper = mapper; <START> this.logger = LoggerFactory.getLogger(getClass()); <END> }</code><technical_language>logger a private static final</technical_language>

Target:
protected AbstractObjectConfigurationProvider(ObjectMapper mapper) { if (mapper == null) { this.mapper = new ObjectMapper(); } else { this.mapper = mapper; } this.logger = LoggerFactory.getLogger(getClass()); }
Source:
<code>public void testListScalingPoliciesFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_policy_list_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); PolicyApi api = autoscaleApi.getPolicyApiForZoneAndGroup("DFW", "groupId1"); FluentIterable<ScalingPolicyResponse> scalingPolicyResponse = api.list(); assertAuthentication(server); assertRequest(server.takeRequest(), "GET", "/v1.0/888888/groups/groupId1/policies"); <START> assertEquals(scalingPolicyResponse.size(), 0); <END> } finally { server.shutdown(); } }</code><technical_language>assertTrue(scalingPolicyResponse.isEmpty(), "Expected empty response was: " + scalingPolicyResponse), that</technical_language>

Target:
public void testListScalingPoliciesFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_policy_list_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); PolicyApi api = autoscaleApi.getPolicyApiForZoneAndGroup("DFW", "groupId1"); FluentIterable<ScalingPolicyResponse> scalingPolicyResponse = api.list(); assertAuthentication(server); assertRequest(server.takeRequest(), "GET", "/v1.0/888888/groups/groupId1/policies"); assertTrue(scalingPolicyResponse.isEmpty(), "Expected no policy response, but was: " + scalingPolicyResponse); } finally { server.shutdown(); } }
Source:
<code>public FormEntryPage clickOnForm(String formName) { <START> onView(withText(formName)).perform(click()); <END> return new FormEntryPage(formName, rule); }</code><technical_language>This require scrolling, I think, depending form list like. If sounds right, address now</technical_language>

Target:
public FormEntryPage clickOnForm(String formName) { clickOnFormButton(formName); return new FormEntryPage(formName, rule); }
Source:
<code>public void run() { <START> Object selection = getStructuredSelection().getFirstElement(); <END> if (selection instanceof IBuildPlan) { final IBuildPlan plan = (IBuildPlan) selection; askParametersAndAbortBuild(plan); } }</code><technical_language>... need iterate selected builds cancel them</technical_language>

Target:
public void run() { Object selection = getStructuredSelection().getFirstElement(); if (selection instanceof IBuildPlan) { final IBuildPlan plan = (IBuildPlan) selection; abortBuild(plan); } }
Source:
<code>public void testValidContainerIdWhenContainerIdIsValidInTheThirdAttempt() { final ServerTemplate template = mock(ServerTemplate.class); final ContainerSpec containerSpec = mock(ContainerSpec.class); when(template.getContainerSpec("org.jbpm:Evaluation:1.0")).thenReturn(containerSpec); when(template.getContainerSpec("org.jbpm:Evaluation:1.0-2")).thenReturn(containerSpec); when(template.getContainerSpec("org.jbpm:Evaluation:1.0-3")).thenReturn(null); doReturn(template).when(specManagementService).getServerTemplate(TEMPLATE_ID); final String containerId = specManagementServiceCDI.validContainerId(TEMPLATE_ID, "org.jbpm:Evaluation:1.0"); <START> assertEquals(containerId, "org.jbpm:Evaluation:1.0-3"); <END> }</code><technical_language>"org.jbpm:Evaluation:1.0-3" is repeated, in variable</technical_language>

Target:
public void testValidContainerIdWhenContainerIdIsValidInTheThirdAttempt() { final ServerTemplate template = mock(ServerTemplate.class); final ContainerSpec containerSpec = mock(ContainerSpec.class); when(template.getContainerSpec(EVALUATION_GAV_1_0)).thenReturn(containerSpec); when(template.getContainerSpec(EVALUATION_GAV_1_0_2)).thenReturn(containerSpec); when(template.getContainerSpec(EVALUATION_GAV_1_0_3)).thenReturn(null); doReturn(template).when(specManagementService).getServerTemplate(TEMPLATE_ID); final String containerId = specManagementServiceCDI.validContainerId(TEMPLATE_ID, EVALUATION_GAV_1_0); assertEquals(containerId, EVALUATION_GAV_1_0_3); }
Source:
<code><START> public void writeTo(final Object data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { <END> try { String xslName = "/" + type.getSimpleName() + "AsPdf.xsl"; templateStream = type.getResourceAsStream(xslName); if (templateStream != null) { StreamSource transformSource = new StreamSource(templateStream); Method factoryMethod = null; for (Method currentMethod : objectFactory.getClass().getDeclaredMethods()) { Class<?>[] parameterTypes = currentMethod.getParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0] == type) { factoryMethod = currentMethod; break; } } JAXBElement<?> element = (JAXBElement<?>) factoryMethod.invoke(objectFactory, data); if (data != null) { Source source = new JAXBSource(jaxbContext, element); Transformer xslfoTransformer = transfact.newTransformer(transformSource); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, entityStream); Result res = new SAXResult(fop.getDefaultHandler()); xslfoTransformer.transform(source, res); } else { log.error("No profile data is available for the selected volume"); } } else { log.error("Error while generating PDF.Null InputStream"); } } catch (Exception e) { log.error("Error while generating PDF.", e); } finally { if (templateStream != null) { templateStream.close(); } } }</code><technical_language>Declare templateStream hear, a local variable</technical_language>

Target:
public void writeTo(final Object data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { String xslName = "/" + type.getSimpleName() + "AsPdf.xsl"; InputStream templateStream = type.getResourceAsStream(xslName); if (templateStream != null) { StreamSource transformSource = new StreamSource(templateStream); Method factoryMethod = null; for (Method currentMethod : objectFactory.getClass().getDeclaredMethods()) { Class<?>[] parameterTypes = currentMethod.getParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0] == type) { factoryMethod = currentMethod; break; } } if (data != null && factoryMethod != null) { JAXBElement<?> element = (JAXBElement<?>) factoryMethod.invoke(objectFactory, data); Source source = new JAXBSource(jaxbContext, element); Transformer xslfoTransformer = transfact.newTransformer(transformSource); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, entityStream); Result res = new SAXResult(fop.getDefaultHandler()); xslfoTransformer.transform(source, res); } else { log.error("No profile data is available for the selected volume"); } } else { log.error("Error while generating PDF.Null InputStream"); } } catch (Exception e) { log.error("Error while generating PDF.", e); } finally { if (templateStream != null) { templateStream.close(); } } }
Source:
<code>@Override public void onMatch(RelOptRuleCall call) { final Project project = call.rel(0); final RelMetadataQuery mq = call.getMetadataQuery(); final RelOptPredicateList predicates = mq.getPulledUpPredicates(project.getInput()); final List<RexNode> expList = Lists.newArrayList(project.getProjects()); if (reduceExpressions(project, expList, predicates, false, matchNullability)) { <START> assert !project.getProjects().equals(expList); <END> call.transformTo( call.builder() .push(project.getInput()) .project(expList, project.getRowType().getFieldNames()) .build()); call.getPlanner().setImportance(project, 0.0); } }</code><technical_language>please add a message, failure human-readable</technical_language>

Target:
@Override public void onMatch(RelOptRuleCall call) { final Project project = call.rel(0); final RelMetadataQuery mq = call.getMetadataQuery(); final RelOptPredicateList predicates = mq.getPulledUpPredicates(project.getInput()); final List<RexNode> expList = Lists.newArrayList(project.getProjects()); if (reduceExpressions(project, expList, predicates, false, matchNullability)) { assert !project.getProjects().equals(expList) : "Reduced expressions should be different from original expressions"; call.transformTo( call.builder() .push(project.getInput()) .project(expList, project.getRowType().getFieldNames()) .build()); call.getPlanner().setImportance(project, 0.0); } }
Source:
<code>public void testTimeout() throws DatabaseFactoryException, ClassNotFoundException, InterruptedException, RecoveryException, RetryLimitExceededException, SQLException { final int socketTimeout = 60; final int loginTimeout = 30; final Properties properties = new Properties() { { setProperty(JDBC, config.jdbc); setProperty(USERNAME, config.username); setProperty(PASSWORD, config.password); setProperty(ENGINE, config.engine); setProperty(SCHEMA_POLICY, "create"); setProperty(SOCKET_TIMEOUT, Integer.toString(socketTimeout)); setProperty(LOGIN_TIMEOUT, Integer.toString(loginTimeout)); } }; final DatabaseEngine de = DatabaseFactory.getConnection(properties); final int connectionTimeoutInMs = de.getConnection().getNetworkTimeout(); <START> assertEquals("timeout in db connection ok?", 0, connectionTimeoutInMs); <END> }</code><technical_language>Error message more specific: "Is timeout of DB connection disabled expected?"</technical_language>

Target:
public void testTimeout() throws DatabaseFactoryException, ClassNotFoundException, InterruptedException, RecoveryException, RetryLimitExceededException, SQLException { final int socketTimeout = 60; final int loginTimeout = 30; final Properties properties = new Properties() { { setProperty(JDBC, config.jdbc); setProperty(USERNAME, config.username); setProperty(PASSWORD, config.password); setProperty(ENGINE, config.engine); setProperty(SCHEMA_POLICY, "create"); setProperty(SOCKET_TIMEOUT, Integer.toString(socketTimeout)); setProperty(LOGIN_TIMEOUT, Integer.toString(loginTimeout)); } }; final DatabaseEngine de = DatabaseFactory.getConnection(properties); final int connectionTimeoutInMs = de.getConnection().getNetworkTimeout(); assertEquals("Is the timeout of the DB connection disabled as expected?", 0, connectionTimeoutInMs); }
Source:
<code>public Fragment getItem(int position) { switch (position) { case 0: return new HomeFragment(); case 1: return new MinervaFragment(); case 4: <START> return new ComingSoonFragment(); <END> default: return new ActivitiesFragment(); } }</code><technical_language>set ComingSoonFragment default case. switch shipping fragments :)</technical_language>

Target:
public Fragment getItem(int position) { switch (position) { case 0: return new HomeFragment(); case 1: return new MinervaFragment(); case 3: return new ActivitiesFragment(); default: return new ComingSoonFragment(); } }
Source:
<code>public void testBinarySpatialTypeDWithin() throws Exception { JAXBElement filter = builder .beginBinarySpatialType("DWITHIN") .setProperty("name") .setValue("value") .setDistance(10.5) .endTerminalType() .getResult(); <START> assertTrue(filter.getDeclaredType().equals(FilterType.class)); <END> forNode(filter) .verifyTerminalNode("/Filter/DWithin", "name", "value") .verifyTerminalNode("/Filter/DWithin", 10.5); }</code><technical_language>assertThat(filter.getDeclaredType(), is(FilterType.class))</technical_language>

Target:
public void testBinarySpatialTypeDWithin() throws Exception { JAXBElement filter = builder .beginBinarySpatialType("DWITHIN") .setProperty("name") .setValue("value") .setDistance(10.5) .endTerminalType() .getResult(); assertThat(filter.getDeclaredType(), is(FilterType.class)); forNode(filter) .verifyTerminalNode("/Filter/DWithin", "name", "value") .verifyTerminalNode("/Filter/DWithin", 10.5); }
Source:
<code><START> public void go() throws IOException, InterruptedException { <END> boolean alive = true; while (isRunning() && alive) { CircularElement<E> element = this.dispatcher.take(SortStage.SORT); if (element != EOF_MARKER && element != SPILLING_MARKER) { if (element.getBuffer().size() == 0) { element.getBuffer().reset(); this.dispatcher.send(SortStage.READ, element); continue; } LOG.debug("Sorting buffer {}.", element.getId()); this.sorter.sort(element.getBuffer()); LOG.debug("Sorted buffer {}.", element.getId()); } else if (element == EOF_MARKER) { LOG.debug("Sorting thread done."); alive = false; } this.dispatcher.send(SortStage.SPILL, element); } }</code><technical_language>remove IOException now</technical_language>

Target:
public void go() throws InterruptedException { boolean alive = true; while (isRunning() && alive) { final CircularElement<E> element = this.dispatcher.take(SortStage.SORT); if (element != EOF_MARKER && element != SPILLING_MARKER) { if (element.getBuffer().size() == 0) { element.getBuffer().reset(); this.dispatcher.send(SortStage.READ, element); continue; } LOG.debug("Sorting buffer {}.", element.getId()); this.sorter.sort(element.getBuffer()); LOG.debug("Sorted buffer {}.", element.getId()); } else if (element == EOF_MARKER) { LOG.debug("Sorting thread done."); alive = false; } this.dispatcher.send(SortStage.SPILL, element); } }
Source:
<code>protected Checker createChecker(Configuration checkConfig, boolean printSeverity) throws Exception { final DefaultConfiguration dc = createCheckerConfig(checkConfig); <START> final Checker c = new Checker(); <END> final Locale locale = Locale.ENGLISH; c.setLocaleCountry(locale.getCountry()); c.setLocaleLanguage(locale.getLanguage()); c.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); c.configure(dc); c.addListener(new BriefLogger(stream, printSeverity)); return c; }</code><technical_language>TC says: Variable named c type 'char' 'java.lang.Character' rename checker</technical_language>

Target:
protected Checker createChecker(Configuration checkConfig, boolean printSeverity) throws Exception { final DefaultConfiguration dc = createCheckerConfig(checkConfig); final Checker checker = new Checker(); final Locale locale = Locale.ENGLISH; checker.setLocaleCountry(locale.getCountry()); checker.setLocaleLanguage(locale.getLanguage()); checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.configure(dc); checker.addListener(new BriefLogger(stream, printSeverity)); return checker; }
Source:
<code>public void configure() throws Exception { onException(Exception.class) <START> .redeliveryDelay("{{error.retryDelay}}") <END> .maximumRedeliveries("{{error.maxRedeliveries}}") .backOffMultiplier(2) .retryAttemptedLogLevel(LoggingLevel.WARN); from("direct-vm:replication") .routeId("CdrReplicationRoute") .log(LoggingLevel.INFO, "Calling replication route for ${headers[org.fcrepo.jms.identifier]}") .to("direct:file.replication"); from("direct:file.replication") .bean(replicationProcessor); }</code><technical_language>Indent other routers</technical_language>

Target:
public void configure() throws Exception { onException(Exception.class) .redeliveryDelay("{{error.retryDelay}}") .maximumRedeliveries("{{error.maxRedeliveries}}") .backOffMultiplier(2) .retryAttemptedLogLevel(LoggingLevel.WARN); from("direct-vm:replication") .routeId("CdrReplicationRoute") .log(LoggingLevel.INFO, "Calling replication route for ${headers[org.fcrepo.jms.identifier]}") .log(LoggingLevel.INFO, "Replication completed for ${headers[org.fcrepo.jms.identifier]}") .to("direct:file.replication"); from("direct:file.replication") .bean(replicationProcessor); }
Source:
<code>private void setupHostNetworkQosDao(){ when(getDbFacadeMockInstance().getHostNetworkQosDao()).thenReturn(hostNetworkQosDao); <START> when(hostNetworkQosDao.get(networkMocked.getQosId())).thenReturn(hostNetworkQos); <END> }</code><technical_language>If mock QoS entity, please mock properly - generate ID for return DAO ID is used</technical_language>

Target:
private void setupHostNetworkQosDao() { when(getDbFacadeMockInstance().getHostNetworkQosDao()).thenReturn(hostNetworkQosDao); when(networkMocked.getQosId()).thenReturn(qosId); when(hostNetworkQosDao.get(networkMocked.getQosId())).thenReturn(hostNetworkQos); }
Source:
<code>public void zeroMissingIndexes() { List<Map<String, Object>> <START> result = <END> jdbcTemplate.queryForList(missingIndexesQuery); assertThat(result.size()).isZero(); }</code><technical_language>dumping missing indices a file ? purpose creating upgrade script - ease process for developer</technical_language>

Target:
public void zeroMissingIndexes() { List<Map<String, Object>> result = jdbcTemplate.queryForList(missingIndexesQuery); String statements = result.stream() .flatMap(m -> m.entrySet() .stream() .filter(e -> e.getKey().equals("ddl")) .map(e -> e.getValue().toString())) .collect(Collectors.joining(";\n")); assertThat(result.size()) .withFailMessage("Found missing indexes. Crete them using these statements:\n\n%s", statements) .isZero(); }
Source:
<code>public void testEventExpirationValue() throws Exception { String drl1 = "package org.drools.pkg1\n" + "import org.drools.compiler.StockTick\n" + "declare StockTick\n" + " @role(event)\n" + "end\n" + "rule X\n" + "when\n" + " StockTick()\n" + "then\n" + "end\n"; String drl2 = "package org.drools.pkg2\n" + "import org.drools.compiler.StockTick\n" + "declare StockTick\n" + " @role(event)\n" + "end\n" + "rule X\n" + "when\n" + " StockTick()\n" + "then\n" + "end\n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(drl1.getBytes()), ResourceType.DRL); kbuilder.add(ResourceFactory.newByteArrayResource(drl2.getBytes()), ResourceType.DRL); assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors()); KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kconf.setOption( EventProcessingOption.STREAM ); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase( kconf ); kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() ); List<ObjectTypeNode> otns = ( (KnowledgeBaseImpl) kbase ).getRete().getObjectTypeNodes(); ObjectType stot = new ClassObjectType( StockTick.class ); for (ObjectTypeNode otn : otns) { if (otn.getObjectType().isAssignableFrom( stot )) { <START> assertEquals( Long.MAX_VALUE, <END> otn.getExpirationOffset() ); } } }</code><technical_language>I wondering if expiration offset convention -1 signified "infinite", hard-coded check for -1 expiration is considered for actual facts? possibly check offset needed >= 0</technical_language>

Target:
public void testEventExpirationValue() throws Exception { String drl1 = "package org.drools.pkg1\n" + "import org.drools.compiler.StockTick\n" + "declare StockTick\n" + " @role(event)\n" + "end\n" + "rule X\n" + "when\n" + " StockTick()\n" + "then\n" + "end\n"; String drl2 = "package org.drools.pkg2\n" + "import org.drools.compiler.StockTick\n" + "declare StockTick\n" + " @role(event)\n" + "end\n" + "rule X\n" + "when\n" + " StockTick()\n" + "then\n" + "end\n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(drl1.getBytes()), ResourceType.DRL); kbuilder.add(ResourceFactory.newByteArrayResource(drl2.getBytes()), ResourceType.DRL); assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors()); KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kconf.setOption( EventProcessingOption.STREAM ); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase( kconf ); kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() ); List<ObjectTypeNode> otns = ( (KnowledgeBaseImpl) kbase ).getRete().getObjectTypeNodes(); ObjectType stot = new ClassObjectType( StockTick.class ); for (ObjectTypeNode otn : otns) { if (otn.getObjectType().isAssignableFrom( stot )) { assertEquals( NEVER_EXPIRES, otn.getExpirationOffset() ); } } }
Source:
<code>protected boolean isRequiredField() { <START> return requiredOption.getValue() || strict; <END> }</code><technical_language>Please result variable here</technical_language>

Target:
protected boolean isRequiredField() { final boolean result = requiredOption.getValue() || strict; return result; }
Source:
<code>public VmBackupInfo(Map<String, Object> innerMap) { super(innerMap); disks = (Map<String, Object>) innerMap.get(VdsProperties.vm_disks); Object tempObj = innerMap.get(VdsProperties.CHECKPOINT); if (tempObj != null) { checkpoint = (String) <START> innerMap.get(VdsProperties.CHECKPOINT); <END> } }</code><technical_language>Why? case tempObj</technical_language>

Target:
public VmBackupInfo(Map<String, Object> innerMap) { super(innerMap); disks = (Map<String, Object>) innerMap.get(VdsProperties.vm_disks); Object tempObj = innerMap.get(VdsProperties.CHECKPOINT); if (tempObj != null) { checkpoint = (String) tempObj; } }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) <END> return true; if (o == null || getClass() != o.getClass()) return false; org.drools.constraint.parser.JavaToken javaToken = (org.drools.constraint.parser.JavaToken) o; if (kind != javaToken.kind) return false; if (!text.equals(javaToken.text)) return false; return true; }</code><technical_language>I this is a generated code, please include curly braces for ifs. them, code misinterpreted more easily</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } org.drools.constraint.parser.JavaToken javaToken = (org.drools.constraint.parser.JavaToken) o; if (kind != javaToken.kind) { return false; } if (!text.equals(javaToken.text)) { return false; } return true; }
Source:
<code>protected ImageDescriptor decorateImage(ImageDescriptor input, Object element) { ImageDescriptor res = super.decorateImage(input, element); IResource resource = <START> Adapters.adapt(element, <END> IResource.class); if (resource != null && res != null && (resource.getType() != IResource.PROJECT || ((IProject) resource).isOpen())) { ImageDescriptor overlay = null; switch (getHighestProblemSeverity(resource)) { case IMarker.SEVERITY_ERROR: overlay = PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_ERROR); break; case IMarker.SEVERITY_WARNING: overlay = PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_WARNING); break; } if (overlay != null) { Image baseImage = res.createImage(); res = new DecorationOverlayIcon(baseImage, overlay, IDecoration.BOTTOM_LEFT); } } return res; }</code><technical_language>I check other preconditions delay resolving adapter needed, is for free</technical_language>

Target:
protected ImageDescriptor decorateImage(ImageDescriptor input, Object element) { ImageDescriptor res = super.decorateImage(input, element); if (res == null) { return null; } IResource resource = Adapters.adapt(element, IResource.class); if (resource != null && (resource.getType() != IResource.PROJECT || ((IProject) resource).isOpen())) { ImageDescriptor overlay = null; switch (getHighestProblemSeverity(resource)) { case IMarker.SEVERITY_ERROR: overlay = PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_ERROR); break; case IMarker.SEVERITY_WARNING: overlay = PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_WARNING); break; } if (overlay != null) { res = new DecorationOverlayIcon(res, overlay, IDecoration.BOTTOM_LEFT); } } return res; }
Source:
<code>public void handleDataChange(String dataPath, Object data) { LOG.info("got notification about barrier " + barrierStatePath + "; done=" + data); <START> if (notAValidEven()) <END> return; zkUtils.unsubscribeDataChanges(barrierStatePath, this); barrierListenerOptional.ifPresent( zkBarrierListener -> zkBarrierListener.onBarrierStateChanged(barrierVersion, (State) data)); }</code><technical_language>* s/notAValidEven/notAValidEvent. * Please log debug level skipping this event</technical_language>

Target:
public void handleDataChange(String dataPath, Object data) { LOG.info("got notification about barrier " + barrierStatePath + "; done=" + data); if (notAValidEvent()) return; zkUtils.unsubscribeDataChanges(barrierStatePath, this); barrierListenerOptional.ifPresent( zkBarrierListener -> zkBarrierListener.onBarrierStateChanged(barrierVersion, (State) data)); }
Source:
<code>protected JComponent getDialogContent() { final DCPanel formPanel = new DCPanel(); WidgetUtils.addToGridBag(DCLabel.bright("Datastore name:"), formPanel, 0, 0); WidgetUtils.addToGridBag(_datastoreNameField, formPanel, 1, 0); final DCPanel checkBoxPanel = new DCPanel().setTitledBorder("Contained datastores"); checkBoxPanel.setLayout(new VerticalLayout(4)); for (JCheckBox checkBox : _checkBoxes) { checkBoxPanel.add(checkBox); } <START> JScrollPane checkBoxScrollPane = WidgetUtils.scrolleable(checkBoxPanel); <END> checkBoxScrollPane.setPreferredSize(new Dimension(checkBoxPanel.getWidth(), 300)); checkBoxScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); checkBoxScrollPane.setBackground(_outerPanel.getBackground()); WidgetUtils.addToGridBag(checkBoxScrollPane, formPanel, 0, 1, 2, 1); DCPanel buttonPanel = getButtonPanel(); DCPanel centerPanel = new DCPanel(); centerPanel.setLayout(new VerticalLayout(4)); centerPanel.add(formPanel); centerPanel.add(buttonPanel); JXStatusBar statusBar = WidgetFactory.createStatusBar(_statusLabel); _outerPanel.setLayout(new BorderLayout()); _outerPanel.add(centerPanel, BorderLayout.CENTER); _outerPanel.add(statusBar, BorderLayout.SOUTH); return _outerPanel; }</code><technical_language>final</technical_language>

Target:
protected JComponent getDialogContent() { final DCPanel formPanel = new DCPanel(); WidgetUtils.addToGridBag(DCLabel.bright("Datastore name:"), formPanel, 0, 0); WidgetUtils.addToGridBag(_datastoreNameField, formPanel, 1, 0); final DCPanel checkBoxPanel = new DCPanel().setTitledBorder("Contained datastores"); checkBoxPanel.setLayout(new VerticalLayout(4)); for (JCheckBox checkBox : _checkBoxes) { checkBoxPanel.add(checkBox); } final JScrollPane checkBoxScrollPane = WidgetUtils.scrolleable(checkBoxPanel); checkBoxScrollPane.setPreferredSize(new Dimension(checkBoxPanel.getWidth(), 300)); checkBoxScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); checkBoxScrollPane.setBackground(_outerPanel.getBackground()); WidgetUtils.addToGridBag(checkBoxScrollPane, formPanel, 0, 1, 2, 1); final DCPanel buttonPanel = getButtonPanel(); final DCPanel centerPanel = new DCPanel(); centerPanel.setLayout(new VerticalLayout(4)); centerPanel.add(formPanel); centerPanel.add(buttonPanel); final JXStatusBar statusBar = WidgetFactory.createStatusBar(_statusLabel); _outerPanel.setLayout(new BorderLayout()); _outerPanel.add(centerPanel, BorderLayout.CENTER); _outerPanel.add(statusBar, BorderLayout.SOUTH); return _outerPanel; }
Source:
<code>public ImageInputStream createInputStreamInstance(Object input, boolean useCache, File cacheDir) throws IOException { if (input instanceof CogUri) { if (((CogUri)input).isUseCache()) { return new CachingCogImageInputStream((CogUri) input); } else { return new DefaultCogImageInputStream((CogUri) input); } } if (input instanceof String || input instanceof URL || input instanceof URI) { <START> if (((CogUri)input).isUseCache()) { <END> return new CachingCogImageInputStream(new CogUri(input.toString())); } else { return new DefaultCogImageInputStream(new CogUri(input.toString())); } } throw new IOException("Invalid input."); }</code><technical_language>This guarantee ClassCastException, input a string, url uri this point. in this if some sort of default configuration based system properties, choose caching caching path</technical_language>

Target:
public ImageInputStream createInputStreamInstance(Object input, boolean useCache, File cacheDir) throws IOException { if (input instanceof CogUri) { return ((CogUri) input).isUseCache() ? new CachingCogImageInputStream((CogUri) input) : new DefaultCogImageInputStream((CogUri) input); } if (input instanceof String || input instanceof URL || input instanceof URI) { return useCache ? new CachingCogImageInputStream(new CogUri(input.toString())) : new DefaultCogImageInputStream(new CogUri(input.toString()).useCache(false)); } throw new IOException("Invalid input."); }
Source:
<code>protected boolean doEquivalent(TopicRef a, TopicRef b) { <START> return ((a.getTopic() == b.getTopic()) <END> && (a.getPublisher() == b.getPublisher())); }</code><technical_language>getTopic() return a string? If equality checked equals ==</technical_language>

Target:
protected boolean doEquivalent(TopicRef a, TopicRef b) { return Objects.equals(a.getTopic(), b.getTopic()) && Objects.equals(a.getPublisher(), b.getPublisher()); }
Source:
<code>public void toExecute(JobExecutionContext context) throws JobExecutionException { JobDataMap map = context.getMergedJobDataMap(); String consumerUuid = map.getString(JobStatus.TARGET_ID); String cdnLabel = map.getString(CDN_LABEL); String webAppPrefix = map.getString(WEBAPP_PREFIX); String apiUrl = map.getString(API_URL); <START> Consumer consumer = validateConsumer(consumerUuid); <END> log.info("Starting async export for {}", consumerUuid); try { ExportResult result = manifestManager.generateAndStoreManifest(consumer, cdnLabel, webAppPrefix, apiUrl); context.setResult(result); log.info("Async export complete."); } catch (Exception e) { throw new JobExecutionException(e.getMessage(), e, false); } }</code><technical_language>sense validate schedule job well</technical_language>

Target:
public void toExecute(JobExecutionContext context) throws JobExecutionException { JobDataMap map = context.getMergedJobDataMap(); String consumerUuid = map.getString(JobStatus.TARGET_ID); String cdnLabel = map.getString(CDN_LABEL); String webAppPrefix = map.getString(WEBAPP_PREFIX); String apiUrl = map.getString(API_URL); Map<String, String> extensionData = (Map<String, String>) map.get(EXTENSION_DATA); log.info("Starting async export for {}", consumerUuid); try { ExportResult result = manifestManager.generateAndStoreManifest(consumerUuid, cdnLabel, webAppPrefix, apiUrl, extensionData); context.setResult(result); log.info("Async export complete."); } catch (Exception e) { throw new JobExecutionException(e.getMessage(), e, false); } }
Source:
<code>public void testLocalVariableSyntaxForLambdaParametersWithJava11() { ASTCompilationUnit compilationUnit = ParserTstUtil.parseAndTypeResolveJava("11", loadSource("LocalVariableSyntaxForLambdaParameters.java")); List<ASTLambdaExpression> lambdas = compilationUnit.findDescendantsOfType(ASTLambdaExpression.class); Assert.assertEquals(4, lambdas.size()); List<ASTFormalParameter> formalParameters = lambdas.get(0).findDescendantsOfType(ASTFormalParameter.class); Assert.assertEquals(1, formalParameters.size()); <START> assertNull(formalParameters.get(0).getTypeNode()); <END> }</code><technical_language>assert isTypeInferred</technical_language>

Target:
public void testLocalVariableSyntaxForLambdaParametersWithJava11() { ASTCompilationUnit compilationUnit = ParserTstUtil.parseAndTypeResolveJava("11", loadSource("LocalVariableSyntaxForLambdaParameters.java")); List<ASTLambdaExpression> lambdas = compilationUnit.findDescendantsOfType(ASTLambdaExpression.class); Assert.assertEquals(4, lambdas.size()); List<ASTFormalParameter> formalParameters = lambdas.get(0).findDescendantsOfType(ASTFormalParameter.class); Assert.assertEquals(1, formalParameters.size()); Assert.assertNull(formalParameters.get(0).getTypeNode()); Assert.assertTrue(formalParameters.get(0).isTypeInferred()); }
Source:
<code>public String resolve(String toResolve) { String str = ""; try { if (specfile == null || toResolve.equals("")) { if (toResolve.length() > 2 && toResolve.substring(2, toResolve.length() - 1) .equals(name)) { return toResolve; } } str = RPMQuery.eval(UiUtils.resolveDefines(specfile, toResolve)).trim(); } catch (CoreException e) { <START> e.printStackTrace(); <END> } return str; }</code><technical_language>Please handle this properly. Printing stack trace console benefits</technical_language>

Target:
public String resolve(String toResolve) { String str = ""; try { if (specfile == null || toResolve.equals("")) { if (toResolve.length() > 2 && toResolve.substring(2, toResolve.length() - 1) .equals(name)) { return toResolve; } } str = RPMQuery.eval(UiUtils.resolveDefines(specfile, toResolve)).trim(); } catch (CoreException e) { SpecfileLog.logError("Unable to evaluate " + toResolve, e); } return str; }
Source:
<code>public static TaggedBlobItem populateTaggedBlobItem(FilterBlobItem filterBlobItem) { <START> Map<String, String> tags = new HashMap<>(); <END> if (filterBlobItem.getTags() != null && filterBlobItem.getTags().getBlobTagSet() != null) { for (BlobTag tag : filterBlobItem.getTags().getBlobTagSet()) { tags.put(tag.getKey(), tag.getValue()); } } return new TaggedBlobItem(filterBlobItem.getContainerName(), filterBlobItem.getName(), tags); }</code><technical_language>Thoughts deferring instantiation of a new map FilterBlobItem tags, if singleton Collections.emptyMap()</technical_language>

Target:
public static TaggedBlobItem populateTaggedBlobItem(FilterBlobItem filterBlobItem) { return new TaggedBlobItem(filterBlobItem.getContainerName(), filterBlobItem.getName(), tagMapFromBlobTags(filterBlobItem.getTags())); }
Source:
<code>@Override public void close() { if (shuttingDown.compareAndSet(false, true)) { try { <START> if (queryHandle != null && queryHandle.isAlive()) { <END> queryHandle.cancel("closing query input source"); } } catch (Exception ex) { firstError.compareAndSet(null, ex); log.error("Error attempting to cancel query:", ex); } try { if (tempDir != null) { Files.deleteDir(tempDir); } } catch (Exception ex) { firstError.compareAndSet(null, ex); log.error("Error attempting to delete temporary directory:", ex); } Throwable error = firstError.get(); if (error != null) { closeFuture.completeExceptionally(error); throw Throwables.propagate(error); } else { closeFuture.complete(null); } } else { closeFuture.join(); } }</code><technical_language>calling Thread.isAlive() a bad sign. I fixing "query engine source single" equivalent considered out of scope</technical_language>

Target:
@Override public void close() { if (shuttingDown.compareAndSet(false, true)) { try { if (queryHandle != null) { queryHandle.cancel("closing query input source"); } } catch (Exception ex) { firstError.compareAndSet(null, ex); log.error("Error attempting to cancel query:", ex); } queryEngine.close(); try { if (tempDir != null) { LessFiles.deleteDir(tempDir); } } catch (Exception ex) { firstError.compareAndSet(null, ex); log.error("Error attempting to delete temporary directory:", ex); } Throwable error = firstError.get(); if (error != null) { closeFuture.completeExceptionally(error); throw Throwables.propagate(error); } else { closeFuture.complete(null); } } else { closeFuture.join(); } }
Source:
<code>private void registerCmEvents(CodeMirror cm) { cm.on("cursorActivity", updateActiveLine(cm)); cm.on("scroll", doScroll(otherCM(cm))); cm.addKeyMap(KeyMap.create().on("'u'", upToChange())); cm.addKeyMap(KeyMap.create().on("'o'", toggleOpenBox(cm))); cm.addKeyMap(KeyMap.create().on("Enter", toggleOpenBox(cm))); if (Gerrit.isSignedIn()) { cm.addKeyMap(KeyMap.create().on("'c'", insertNewDraft(cm))); } <START> CodeMirror.disableUnwantedKey("vim", "A"); <END> CodeMirror.disableUnwantedKey("vim", "C"); CodeMirror.disableUnwantedKey("vim", "D"); CodeMirror.disableUnwantedKey("vim", "I"); CodeMirror.disableUnwantedKey("vim", "O"); CodeMirror.disableUnwantedKey("vim", "P"); CodeMirror.disableUnwantedKey("vim", "R"); CodeMirror.disableUnwantedKey("vim", "S"); CodeMirror.disableUnwantedKey("vim", "U"); CodeMirror.disableUnwantedKey("vim", "X"); CodeMirror.disableUnwantedKey("vim", "Y"); CodeMirror.disableUnwantedKey("vim", "~"); }</code><technical_language>this is shorter: for (String c : new String[]{"A", ...}) { CodeMirror.disableUnwantedKey("vim", c); }</technical_language>

Target:
private void registerCmEvents(CodeMirror cm) { cm.on("cursorActivity", updateActiveLine(cm)); cm.on("scroll", doScroll(otherCM(cm))); cm.on("mousedown", ignoreRightClick()); cm.addKeyMap(KeyMap.create().on("'u'", upToChange())); cm.addKeyMap(KeyMap.create().on("'o'", toggleOpenBox(cm))); cm.addKeyMap(KeyMap.create().on("Enter", toggleOpenBox(cm))); if (Gerrit.isSignedIn()) { cm.addKeyMap(KeyMap.create().on("'c'", insertNewDraft(cm))); } CodeMirror.disableUnwantedKey("vim", "A"); CodeMirror.disableUnwantedKey("vim", "C"); CodeMirror.disableUnwantedKey("vim", "D"); CodeMirror.disableUnwantedKey("vim", "I"); CodeMirror.disableUnwantedKey("vim", "O"); CodeMirror.disableUnwantedKey("vim", "P"); CodeMirror.disableUnwantedKey("vim", "R"); CodeMirror.disableUnwantedKey("vim", "S"); CodeMirror.disableUnwantedKey("vim", "U"); CodeMirror.disableUnwantedKey("vim", "X"); CodeMirror.disableUnwantedKey("vim", "Y"); CodeMirror.disableUnwantedKey("vim", "~"); }
Source:
<code>private boolean connectedRead(EpollRecvByteAllocatorHandle allocHandle, ByteBuf byteBuf, int maxDatagramPacketSize) throws Exception { try { int writable = maxDatagramPacketSize != 0 ? Math.min(byteBuf.writableBytes(), maxDatagramPacketSize) : byteBuf.writableBytes(); allocHandle.attemptedBytesRead(writable); <START> byteBuf.writerIndex(byteBuf.readerIndex() + writable); <END> int read = doReadBytes(byteBuf); if (read <= 0) { allocHandle.lastBytesRead(read); return false; } allocHandle.lastBytesRead(maxDatagramPacketSize <= 0 ? read : writable); DatagramPacket packet = new DatagramPacket(byteBuf, localAddress(), remoteAddress()); allocHandle.incMessagesRead(1); pipeline().fireChannelRead(packet); byteBuf = null; return true; } finally { if (byteBuf != null) { byteBuf.release(); } } }</code><technical_language>this is right.. capacity need reduced in case 0 < maxDatagramPacketSize < byteBuf.writeableBytes()? want do involve reallocation/copying internally..</technical_language>

Target:
private boolean connectedRead(EpollRecvByteAllocatorHandle allocHandle, ByteBuf byteBuf, int maxDatagramPacketSize) throws Exception { try { int writable = maxDatagramPacketSize != 0 ? Math.min(byteBuf.writableBytes(), maxDatagramPacketSize) : byteBuf.writableBytes(); allocHandle.attemptedBytesRead(writable); int writerIndex = byteBuf.writerIndex(); int localReadAmount; if (byteBuf.hasMemoryAddress()) { localReadAmount = socket.readAddress(byteBuf.memoryAddress(), writerIndex, writerIndex + writable); } else { ByteBuffer buf = byteBuf.internalNioBuffer(writerIndex, writable); localReadAmount = socket.read(buf, buf.position(), buf.limit()); } if (localReadAmount <= 0) { allocHandle.lastBytesRead(localReadAmount); return false; } byteBuf.writerIndex(writerIndex + localReadAmount); allocHandle.lastBytesRead(maxDatagramPacketSize <= 0 ? localReadAmount : writable); DatagramPacket packet = new DatagramPacket(byteBuf, localAddress(), remoteAddress()); allocHandle.incMessagesRead(1); pipeline().fireChannelRead(packet); byteBuf = null; return true; } finally { if (byteBuf != null) { byteBuf.release(); } } }
Source:
<code><START> public static CryptoService getConfigured(AccumuloConfiguration conf) { <END> String configuredClass = conf.get(Property.INSTANCE_CRYPTO_SERVICE.getKey()); if (singleton == null) { singleton = loadCryptoService(configuredClass); singleton.init(conf.getAllPropertiesWithPrefix(Property.INSTANCE_CRYPTO_PREFIX)); } else { if (!singleton.getClass().getName().equals(configuredClass)) { singleton = loadCryptoService(configuredClass); singleton.init(conf.getAllPropertiesWithPrefix(Property.INSTANCE_CRYPTO_PREFIX)); } } return singleton; }</code><technical_language>This method multiple concurrency issues. is a race condition thread singleton while another thread is calling init. Also, variable is volatile processors caches others updates. nice avoid synchronization, is avoid issue w/o sync. java private static AtomicReference<CryptoService> singleton = new AtomicReference<>(null); /** * Load singleton class configured in {@link Property#INSTANCE_CRYPTO_SERVICE} */ public static CryptoService getConfigured(AccumuloConfiguration conf) { CryptoService cyptoService = singleton.get(); String configuredClass = conf.get(Property.INSTANCE_CRYPTO_SERVICE.getKey()); if (cyptoService == null || !cyptoService.getClass().getName().equals(configuredClass)) { CryptoService newCryptoService = loadCryptoService(configuredClass); newCryptoService.init(conf.getAllPropertiesWithPrefix(Property.INSTANCE_CRYPTO_PREFIX)); singleton.compareAndSet(cyptoService, newCryptoService); return singleton.get(); } return cyptoService; } singleton in place. Tservers create a single cryptoservice</technical_language>

Target:
public static CryptoService getConfigured(AccumuloConfiguration conf) { String currentClass = singleton.getClass().getName(); String configuredClass = conf.get(Property.INSTANCE_CRYPTO_SERVICE.getKey()); if (!currentClass.equals(configuredClass)) { String msg = String.format("Configured crypto class %s changed since initialization of %s.", configuredClass, currentClass); throw new CryptoService.CryptoException(msg); } return singleton; }
Source:
<code>public void testRacyGitDetection() throws IOException, IllegalStateException, InterruptedException { DirCache dc; TreeSet<Long> modTimes = new TreeSet<Long>(); File lastFile; modTimes.add(fsTick(db.getIndexFile())); addToWorkDir("a", "a"); lastFile = addToWorkDir("b", "b"); modTimes.add(fsTick(lastFile)); addToIndex(modTimes); assertEquals( "[[a, modTime(index/file): t0/t0], [b, modTime(index/file): t0/t0]]", indexState(modTimes)); modTimes.add(Long.valueOf(db.getIndexFile().lastModified())); addToWorkDir("a", "a2"); addToIndex(modTimes); dc = db.readDirCache(); assertTrue(dc.getEntryCount() == 2); assertTrue(dc.getEntry("a").isSmudged()); assertFalse(dc.getEntry("b").isSmudged()); assertEquals( <START> "[[a, modTime(index/file): t0/t0, unsmudged], [b, modTime(index/file): t1/t1]]", <END> indexState(modTimes)); assertEquals( "[[a, modTime(index/file): t0/t0, unsmudged], [b, modTime(index/file): t1/t1]]", indexState(modTimes)); }</code><technical_language>length included in string</technical_language>

Target:
public void testRacyGitDetection() throws IOException, IllegalStateException, InterruptedException { DirCache dc; TreeSet<Long> modTimes = new TreeSet<Long>(); File lastFile; modTimes.add(fsTick(db.getIndexFile())); addToWorkDir("a", "a"); lastFile = addToWorkDir("b", "b"); modTimes.add(fsTick(lastFile)); addToIndex(modTimes); assertEquals( "[[a, modTime(index/file): t0/t0, length(index/file): 1/1," + " mode(index/file): 100644/100644, stage: 0]," + " [b, modTime(index/file): t0/t0, length(index/file): 1/1," + " mode(index/file): 100644/100644, stage: 0]]", indexState(modTimes)); modTimes.add(Long.valueOf(db.getIndexFile().lastModified())); addToWorkDir("a", "a2"); addToIndex(modTimes); dc = db.readDirCache(); assertTrue(dc.getEntryCount() == 2); assertTrue(dc.getEntry("a").isSmudged()); assertFalse(dc.getEntry("b").isSmudged()); assertEquals( "[[a, modTime(index/file): t0/t0, unsmudged," + " length(index/file): 2/2, mode(index/file): 100644/100644," + " stage: 0], [b, modTime(index/file): t1/t1, length(index/file):" + " 1/1, mode(index/file): 100644/100644, stage: 0]]", indexState(modTimes)); }
Source:
<code>public void asyncGetLedgersContainBookies(final Set<BookieSocketAddress> bookies, final GenericCallback<SortedMap<Long, LedgerMetadata>> callback) { final SortedMap<Long, LedgerMetadata> ledgers = new ConcurrentSkipListMap<Long, LedgerMetadata>(); bkc.getLedgerManager().asyncProcessLedgers(new Processor<Long>() { @Override public void process(final Long lid, final AsyncCallback.VoidCallback cb) { bkc.getLedgerManager().readLedgerMetadata(lid) .whenComplete((metadata, exception) -> { <START> if (exception instanceof BKException.BKNoSuchLedgerExistsException) { <END> cb.processResult(BKException.Code.OK, null, null); return; } else if (exception != null) { cb.processResult(BKException.getExceptionCode(exception), null, null); return; } Set<BookieSocketAddress> bookiesInLedger = metadata.getValue().getBookiesInThisLedger(); Sets.SetView<BookieSocketAddress> intersection = Sets.intersection(bookiesInLedger, bookies); if (!intersection.isEmpty()) { ledgers.put(lid, metadata.getValue()); } cb.processResult(BKException.Code.OK, null, null); }); } }, new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { callback.operationComplete(rc, ledgers); } }, null, BKException.Code.OK, BKException.Code.MetaStoreException); }</code><technical_language>exception a CompletionException</technical_language>

Target:
public void asyncGetLedgersContainBookies(final Set<BookieSocketAddress> bookies, final GenericCallback<SortedMap<Long, LedgerMetadata>> callback) { final SortedMap<Long, LedgerMetadata> ledgers = new ConcurrentSkipListMap<Long, LedgerMetadata>(); bkc.getLedgerManager().asyncProcessLedgers(new Processor<Long>() { @Override public void process(final Long lid, final AsyncCallback.VoidCallback cb) { bkc.getLedgerManager().readLedgerMetadata(lid) .whenComplete((metadata, exception) -> { if (BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsException) { cb.processResult(BKException.Code.OK, null, null); return; } else if (exception != null) { cb.processResult(BKException.getExceptionCode(exception), null, null); return; } Set<BookieSocketAddress> bookiesInLedger = metadata.getValue().getBookiesInThisLedger(); Sets.SetView<BookieSocketAddress> intersection = Sets.intersection(bookiesInLedger, bookies); if (!intersection.isEmpty()) { ledgers.put(lid, metadata.getValue()); } cb.processResult(BKException.Code.OK, null, null); }); } }, new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { callback.operationComplete(rc, ledgers); } }, null, BKException.Code.OK, BKException.Code.MetaStoreException); }
Source:
<code>private void onUpdatedShouldRunDecision(RunConditionCheckResult result) { boolean newShouldRunDecision = result.isShouldRun(); boolean reasonsChanged; <START> synchronized (mCurrentCheckResult) { <END> reasonsChanged = !mCurrentCheckResult.get().equals(result); mCurrentCheckResult.set(result); } if (reasonsChanged) { onRunConditionCheckResultChange(result); } if (newShouldRunDecision != mLastDeterminedShouldRun) { Log.i(TAG, "shouldRun decision changed to " + newShouldRunDecision + " according to configured run conditions."); mLastDeterminedShouldRun = newShouldRunDecision; if (newShouldRunDecision) { switch (mCurrentState) { case DISABLED: case INIT: shutdown(State.INIT, () -> { launchStartupTask(); }); break; case STARTING: case ACTIVE: case ERROR: break; default: break; } } else { if (mCurrentState == State.DISABLED) { return; } Log.v(TAG, "Stopping syncthing"); shutdown(State.DISABLED, () -> {}); } } }</code><technical_language>do need synchronize atomic? sense</technical_language>

Target:
private void onUpdatedShouldRunDecision(RunConditionCheckResult result) { boolean newShouldRunDecision = result.isShouldRun(); boolean reasonsChanged = !mCurrentCheckResult.getAndSet(result).equals(result); if (reasonsChanged) { onRunConditionCheckResultChange(result); } if (newShouldRunDecision != mLastDeterminedShouldRun) { Log.i(TAG, "shouldRun decision changed to " + newShouldRunDecision + " according to configured run conditions."); mLastDeterminedShouldRun = newShouldRunDecision; if (newShouldRunDecision) { switch (mCurrentState) { case DISABLED: case INIT: shutdown(State.INIT, () -> { launchStartupTask(); }); break; case STARTING: case ACTIVE: case ERROR: break; default: break; } } else { if (mCurrentState == State.DISABLED) { return; } Log.v(TAG, "Stopping syncthing"); shutdown(State.DISABLED, () -> {}); } } }