auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void send(MessageContext synCtx) { try { oauthHandler.setOAuthHeader(synCtx); } catch (OAuthException e) { handleError(synCtx, "Could not generate access token for oauth configured http endpoint " + this.getName(), e); <START> } <END> if (synCtx.getProperty(SynapseConstants.BLOCKING_MSG_SENDER) != null) { org.apache.axis2.context.MessageContext axis2Ctx = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); axis2Ctx.setProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES, String.valueOf(OAuthConstants.HTTP_SC_UNAUTHORIZED)); } try { MessageContext cloneMessageContext = MessageHelper.cloneMessageContext(synCtx); MessageCache.getInstance().addMessageContext(synCtx.getMessageID(), cloneMessageContext); } catch (AxisFault axisFault) { handleError(synCtx, "Error cloning the message context for oauth configured http endpoint " + this.getName(), axisFault); } super.send(synCtx); }</code><technical_language>merge try catch blocks logic that</technical_language>

Target:
public void send(MessageContext synCtx) { try { oAuthHandler.setOAuthHeader(synCtx); if (synCtx.getProperty(SynapseConstants.BLOCKING_MSG_SENDER) != null) { org.apache.axis2.context.MessageContext axis2Ctx = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); axis2Ctx.setProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES, String.valueOf(OAuthConstants.HTTP_SC_UNAUTHORIZED)); } MessageContext cloneMessageContext = MessageHelper.cloneMessageContext(synCtx); MessageCache.getInstance().addMessageContext(synCtx.getMessageID(), cloneMessageContext); super.send(synCtx); } catch (OAuthException e) { handleError(synCtx, "Could not generate access token for oauth configured http endpoint " + this.getName(), e); } catch (AxisFault axisFault) { handleError(synCtx, "Error cloning the message context for oauth configured http endpoint " + this.getName(), axisFault); } }
Source:
<code>private void internalLoad(Properties props, Set<String> seenUrls, ClassLoader loader, URL url, StrInterpolator strInterpolator, StrInterpolator.Lookup lookup) { LOG.debug("Attempting to load : {}", url.toExternalForm()); if (!seenUrls.contains(url.toExternalForm())) { seenUrls.add(url.toExternalForm()); try { Map<String, Object> p = new URLConfigReader(url).call().getToAdd(); LOG.debug("Loaded : {}", url.toExternalForm()); props.putAll(p); Object next = p.get(INCLUDE_KEY); <START> if (next != null && next instanceof String) { <END> p.remove(INCLUDE_KEY); for (String urlString : ((String) next).split(",")) { URL nextUrl = getResource(loader, strInterpolator.create(lookup).resolve(urlString)); if (nextUrl != null) { internalLoad(props, seenUrls, loader, nextUrl, strInterpolator, lookup); } } } } catch (IOException e) { LOG.debug("Unable to load configuration file {}. {}", url, e.getMessage()); } } else { LOG.debug("Circular dependency trying to load url : {}", url.toExternalForm()); } }</code><technical_language>Next a string. OK next a String. String next = (String)p.get(INCLUDE_KEY);</technical_language>

Target:
private void internalLoad(Properties props, Set<String> seenUrls, ClassLoader loader, URL url, StrInterpolator strInterpolator, StrInterpolator.Lookup lookup) { LOG.debug("Attempting to load : {}", url.toExternalForm()); if (!seenUrls.contains(url.toExternalForm())) { seenUrls.add(url.toExternalForm()); try { Map<String, Object> p = new URLConfigReader(url).call().getToAdd(); LOG.debug("Loaded : {}", url.toExternalForm()); props.putAll(p); String next = (String) p.get(INCLUDE_KEY); if (next != null) { p.remove(INCLUDE_KEY); for (String urlString : next.split(",")) { URL nextUrl = getResource(loader, strInterpolator.create(lookup).resolve(urlString)); if (nextUrl != null) { internalLoad(props, seenUrls, loader, nextUrl, strInterpolator, lookup); } } } } catch (IOException e) { LOG.debug("Unable to load configuration file {}. {}", url, e.getMessage()); } } else { LOG.debug("Circular dependency trying to load url : {}", url.toExternalForm()); } }
Source:
<code>public PositionedCryptoInputStream(Properties props, ReadableByteChannel in, byte[] key, byte[] iv, long streamOffset) throws IOException { <START> this(in, Utils.getCipherInstance(props), Utils.getBufferSize(props), key, iv, streamOffset); <END> }</code><technical_language>above. I stop pointing this out</technical_language>

Target:
public PositionedCryptoInputStream(Properties props, ReadableByteChannel in, byte[] key, byte[] iv, long streamOffset) throws IOException { this(in, CipherFactory.getInstance(props), Utils.getBufferSize(props), key, iv, streamOffset); }
Source:
<code><START> public static BBox createBBox(NodeAccess na, EdgeIteratorState edgeState) { <END> return BBox.fromPoints(na.getLatitude(edgeState.getBaseNode()), na.getLongitude(edgeState.getBaseNode()), na.getLatitude(edgeState.getAdjNode()), na.getLongitude(edgeState.getAdjNode())); }</code><technical_language>This duplicate private</technical_language>

Target:
private static BBox createBBox(NodeAccess na, EdgeIteratorState edgeState) { return BBox.fromPoints(na.getLatitude(edgeState.getBaseNode()), na.getLongitude(edgeState.getBaseNode()), na.getLatitude(edgeState.getAdjNode()), na.getLongitude(edgeState.getAdjNode())); }
Source:
<code>public CompoundSlotProvider add(InventoryAdapter<TInventory, TStack> adapter) { for (Inventory slot : adapter.slots()) { SlotLens slotLens = ((SlotLens<IInventory, ItemStack>) ((SlotAdapter) slot).getRootLens()); <START> if (!slotList.contains(slotLens)) { <END> slotList.add(slotLens); } } return this; }</code><technical_language>this. (and next line)</technical_language>

Target:
public CompoundSlotProvider add(InventoryAdapter<TInventory, TStack> adapter) { for (Inventory slot : adapter.slots()) { SlotLens slotLens = ((SlotLens<IInventory, ItemStack>) ((SlotAdapter) slot).getRootLens()); if (!this.slotList.contains(slotLens)) { this.slotList.add(slotLens); } } return this; }
Source:
<code>protected EntitySpec<?> getMemberSpec() { EntitySpec<?> spec = config().get(MEMBER_SPEC); if (spec == null) { <START> spec = EntitySpec.create(MongoDBServer.class); <END> } MongoDBAuthenticationUtils.setAuthenticationConfig(spec, this); return spec; }</code><technical_language>setConfig too</technical_language>

Target:
protected EntitySpec<?> getMemberSpec() { EntitySpec<?> spec = config().get(MEMBER_SPEC); if (spec == null) { spec = EntitySpec.create(MongoDBServer.class); config().set(MEMBER_SPEC, spec); } MongoDBAuthenticationUtils.setAuthenticationConfig(spec, this); return spec; }
Source:
<code>public void processLeftData(final MistDataEvent input) { S state = initializeStateSup.get(); try { final Collection<IN> value = ((WindowData<IN>) input.getValue()).getDataCollection(); final Iterator<IN> iterator = value.iterator(); while (iterator.hasNext()) { final IN data = iterator.next(); state = updateStateFunc.apply(data, state); } input.setValue(produceResultFunc.apply(state)); outputEmitter.emitData(input); <START> } catch (ClassCastException e) { <END> throw e; } }</code><technical_language>final</technical_language>

Target:
public void processLeftData(final MistDataEvent input) { S state = initializeStateSup.get(); try { final Collection<IN> value = ((WindowData<IN>) input.getValue()).getDataCollection(); final Iterator<IN> iterator = value.iterator(); while (iterator.hasNext()) { final IN data = iterator.next(); state = updateStateFunc.apply(data, state); } input.setValue(produceResultFunc.apply(state)); outputEmitter.emitData(input); } catch (final ClassCastException e) { throw e; } }
Source:
<code>public void getConceptsByClass_shouldGetConceptsByClass() { ConceptClass cc = new ConceptClass(3); List<Concept> concepts = conceptService.getConceptsByClass(cc); <START> Assert.assertEquals(4, concepts.size()); <END> }</code><technical_language>verify 4 concepts expected</technical_language>

Target:
public void getConceptsByClass_shouldGetConceptsByClass() { List<Concept> actualConcepts = conceptService.getConceptsByClass(new ConceptClass(3)); Assert.assertThat(actualConcepts.size(), is(4)); Assert.assertThat(actualConcepts, containsInAnyOrder(conceptService.getConcept(3), conceptService.getConcept(60), conceptService.getConcept(88), conceptService.getConcept(792))); }
Source:
<code>public Response associatePlatformAlert(@PathParam("alert") String alert, @QueryParam("type") String type) { alertService.applyDefaults(alert, AlertReferenceType.valueOf(type.toUpperCase())); <START> return Response.noContent().build(); <END> }</code><technical_language>right. a breaking change some users, API UI, affected this kind of changes. Please revert</technical_language>

Target:
public Response associatePlatformAlert(@PathParam("alert") String alert, @QueryParam("type") String type) { alertService.applyDefaults(alert, AlertReferenceType.valueOf(type.toUpperCase())); return Response.ok().build(); }
Source:
<code><START> public void autoConfirm() { <END> if (!isAcknowledgementSent) { confirmMessage(); } }</code><technical_language>do need non-interface methods? invoke confirmMessage autoReject place</technical_language>

Target:
public void autoConfirm() { executeAutoAck(() -> { confirmMessage(); LOG.debug(String.format("[consumer tag: %s] A message was automatically confirmed after message processing", consumerTag)); }); }
Source:
<code>public void process(Exchange exchange) throws Exception { final Message in = exchange.getIn(); String fcrepoBinaryUri = (String) in.getHeader(FCREPO_URI); <START> PIDs.setRepository(repository); <END> int retryAttempt = 0; while (true) { try { SolrUpdateRequest updateRequest = new SolrUpdateRequest(fcrepoBinaryUri, IndexingActionType.ADD); DocumentIndexingPackage dip = updateRequest.getDocumentIndexingPackage(); dip = factory.createDip(updateRequest.getPid()); updateRequest.setDocumentIndexingPackage(dip); pipeline.process(dip); solrUpdateDriver.addDocument(dip.getDocument()); } catch (Exception e) { if (retryAttempt == maxRetries) { throw e; } retryAttempt++; log.info("Unable to update solr for {}. Retrying, attempt {}", fcrepoBinaryUri, retryAttempt); TimeUnit.MILLISECONDS.sleep(retryDelay); } } }</code><technical_language>This happening here, care of in context files beginning of a unit test. want reset this application startup</technical_language>

Target:
public void process(Exchange exchange) throws Exception { final Message in = exchange.getIn(); String fcrepoBinaryUri = (String) in.getHeader(FCREPO_URI); int retryAttempt = 0; while (true) { try { SolrUpdateRequest updateRequest = new SolrUpdateRequest(fcrepoBinaryUri, IndexingActionType.ADD); DocumentIndexingPackage dip = factory.createDip(updateRequest.getPid()); updateRequest.setDocumentIndexingPackage(dip); pipeline.process(dip); solrUpdateDriver.addDocument(dip.getDocument()); return; } catch (Exception e) { if (retryAttempt == maxRetries) { throw e; } retryAttempt++; log.info("Unable to update solr for {}. Retrying, attempt {}", fcrepoBinaryUri, retryAttempt); TimeUnit.MILLISECONDS.sleep(retryDelay); } } }
Source:
<code>default BundleSpecBuilder addConfiguration(URL url) { <START> return requireCapability("osgi.extender").filter("(osgi.extender=osgi.configurator)") <END> .addResource(CONFIGURATION_JSON, url); }</code><technical_language>if want constants "osgi.configurator"= org.osgi.service.configurator.ConfiguratorConstants.CONFIGURATOR_EXTENDER_NAME "osgi.extender" = org.osgi.namespace.extender.ExtenderNamespace.EXTENDER_NAMESPACE</technical_language>

Target:
default BundleSpecBuilder addConfiguration(URL url) { return requireCapability(ExtenderNamespace.EXTENDER_NAMESPACE) .filter(String.format("(%s=%s)", ExtenderNamespace.EXTENDER_NAMESPACE, ConfiguratorConstants.CONFIGURATOR_EXTENDER_NAME)) .addResource(CONFIGURATION_JSON, url); }
Source:
<code>protected AbstractNodeMonitorDescriptor(Class<? extends NodeMonitor> clazz) { <START> this(clazz,TimeUnit.MINUTES.toMillis(PERIOD_MINUTES)); <END> }</code><technical_language>suggestion this(clazz,PERIOD);</technical_language>

Target:
protected AbstractNodeMonitorDescriptor(Class<? extends NodeMonitor> clazz) { this(clazz, PERIOD); }
Source:
<code>public void addTable(Table table) { String version = table.getVersion(); <START> EntityDictionary dictionary = hashMapDataStores.computeIfAbsent(version, ERROR_OUT).getDictionary(); <END> tables.put(dictionary.getEntityClass(table.getName(), version), table); addMetaData(table, version); table.getColumns().forEach(this::addColumn); }</code><technical_language>This throw internal error (as relate client request, setup of server)</technical_language>

Target:
public void addTable(Table table) { String version = table.getVersion(); EntityDictionary dictionary = hashMapDataStores.computeIfAbsent(version, SERVER_ERROR).getDictionary(); tables.put(dictionary.getEntityClass(table.getName(), version), table); addMetaData(table, version); table.getColumns().forEach(this::addColumn); }
Source:
<code>protected boolean runScript(ResourceResolver resourceResolver, OnDeployScript script) { Resource statusResource = getOrCreateStatusTrackingResource(resourceResolver, script.getClass()); String status = getScriptStatus(statusResource); if (status == null || status.equals(SCRIPT_STATUS_FAIL)) { trackScriptStart(statusResource); try { script.execute(resourceResolver); logger.info("On-deploy script completed successfully: {}", statusResource.getPath()); <START> trackScriptEnd(statusResource, SCRIPT_STATUS_SUCCESS, null); <END> return true; } catch (Exception e) { String errMsg = "On-deploy script failed: " + statusResource.getPath(); logger.error(errMsg, e); trackScriptEnd(statusResource, SCRIPT_STATUS_FAIL, ExceptionUtils.getStackTrace(e.getCause())); throw new OnDeployEarlyTerminationException(new RuntimeException(errMsg)); } } else if (!status.equals(SCRIPT_STATUS_SUCCESS)) { String errMsg = "On-deploy script is already running or in an otherwise unknown state: " + statusResource.getPath() + " - status: " + status; logger.error(errMsg); throw new OnDeployEarlyTerminationException(new RuntimeException(errMsg)); } else { logger.debug("Skipping on-deploy script, as it is already complete: {}", statusResource.getPath()); } return false; }</code><technical_language>trackScriptStart updated null out output property status node well</technical_language>

Target:
protected boolean runScript(ResourceResolver resourceResolver, OnDeployScript script) { Resource statusResource = getOrCreateStatusTrackingResource(resourceResolver, script.getClass()); String status = getScriptStatus(statusResource); if (status == null || status.equals(SCRIPT_STATUS_FAIL)) { trackScriptStart(statusResource); try { script.execute(resourceResolver); logger.info("On-deploy script completed successfully: {}", statusResource.getPath()); trackScriptEnd(statusResource, SCRIPT_STATUS_SUCCESS, ""); return true; } catch (Exception e) { String errMsg = "On-deploy script failed: " + statusResource.getPath(); logger.error(errMsg, e); trackScriptEnd(statusResource, SCRIPT_STATUS_FAIL, ExceptionUtils.getStackTrace(e.getCause())); throw new OnDeployEarlyTerminationException(new RuntimeException(errMsg)); } } else if (!status.equals(SCRIPT_STATUS_SUCCESS)) { String errMsg = "On-deploy script is already running or in an otherwise unknown state: " + statusResource.getPath() + " - status: " + status; logger.error(errMsg); throw new OnDeployEarlyTerminationException(new RuntimeException(errMsg)); } else { logger.debug("Skipping on-deploy script, as it is already complete: {}", statusResource.getPath()); } return false; }
Source:
<code>private static void assertSetElements(final SortedSet<String> expectedSet, final SortedSet<String> actualSet) { final Iterator<String> expectedIterator = expectedSet.iterator(); final Iterator<String> actualIterator = actualSet.iterator(); for (int i = 0; i < expectedSet.size(); i++) { String expected = expectedIterator.next(); String actual = actualIterator.next(); try { Assert.assertEquals(expected, actual); } catch (AssertionError e) { LOG.error("Expected: " + expected + "\n but was:" + actual); <START> } <END> } }</code><technical_language>catch assertion error? test throw fails, no</technical_language>

Target:
private static void assertSetElements(final SortedSet<String> expectedSet, final SortedSet<String> actualSet) { final Iterator<String> expectedIterator = expectedSet.iterator(); final Iterator<String> actualIterator = actualSet.iterator(); for (int i = 0; i < expectedSet.size(); i++) { String expected = expectedIterator.next(); String actual = actualIterator.next(); if (!expected.equals(actual)) { LOG.error("Expected: " + expected + "\n but was:" + actual); } } Assert.assertEquals(expectedSet, actualSet); }
Source:
<code>public void run() { InitializerWizard wizard = new InitializerWizard(this.editingDomain.getResourceSet(), selection); WizardDialog dialog = new WizardDialog(null, wizard); dialog.create(); if (dialog.open() == Window.OK) { this.result = wizard.getCommand(); <START> result.execute(); <END> } }</code><technical_language>said, execute command this. In previsou patch set I put some ref existing code execute command command staticc of current editing domain (to support undo/redo, ...) try ecitingDomain.getCommandStack().execute(cmd); check undo/redo works</technical_language>

Target:
public void run() { InitializerWizard wizard = new InitializerWizard(this.editingDomain.getResourceSet(), selection); WizardDialog dialog = new WizardDialog(null, wizard); dialog.create(); if (dialog.open() == Window.OK) { this.result = wizard.getCommand(); editingDomain.getCommandStack().execute(result); } }
Source:
<code>public ResponseEntity<?> createEventType(@Valid @RequestBody final EventType eventType, final Errors errors, final NativeWebRequest nativeWebRequest) { if (errors.hasErrors()) { return create(new ValidationProblem(errors), nativeWebRequest); } try { validateSchema(eventType); validatePartitioningStrategy(eventType); eventTypeRepository.saveEventType(eventType); topicRepository.createTopic(eventType.getName()); return status(HttpStatus.CREATED).build(); } catch (final InvalidEventTypeException | NoSuchPartitioningStrategyException | DuplicatedEventTypeNameException e) { <START> LOG.warn(e.getMessage(), e); <END> return create(e.asProblem(), nativeWebRequest); } catch (final TopicCreationException e) { LOG.error("Problem creating kafka topic. Rolling back event type database registration.", e); try { eventTypeRepository.removeEventType(eventType.getName()); } catch (final NakadiException e1) { return create(e.asProblem(), nativeWebRequest); } return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.error("Error creating event type " + eventType, e); return create(e.asProblem(), nativeWebRequest); } }</code><technical_language>semantics of a warning</technical_language>

Target:
public ResponseEntity<?> createEventType(@Valid @RequestBody final EventType eventType, final Errors errors, final NativeWebRequest nativeWebRequest) { if (errors.hasErrors()) { return create(new ValidationProblem(errors), nativeWebRequest); } try { validateSchema(eventType); validatePartitioningStrategy(eventType); eventTypeRepository.saveEventType(eventType); topicRepository.createTopic(eventType.getName()); return status(HttpStatus.CREATED).build(); } catch (final InvalidEventTypeException | NoSuchPartitioningStrategyException | DuplicatedEventTypeNameException e) { LOG.debug("Failed to create EventType.", e); return create(e.asProblem(), nativeWebRequest); } catch (final TopicCreationException e) { LOG.error("Problem creating kafka topic. Rolling back event type database registration.", e); try { eventTypeRepository.removeEventType(eventType.getName()); } catch (final NakadiException e1) { return create(e.asProblem(), nativeWebRequest); } return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.error("Error creating event type " + eventType, e); return create(e.asProblem(), nativeWebRequest); } }
Source:
<code>public void edit(String code, LocalizedString description) { if (Bennu.getInstance().getPaymentMethodSet().stream().filter(i -> !i.equals(this)) .noneMatch(i -> i.getCode().equals(code))) { if(!this.getCode().equals(code) || !this.getDescription().equals(description)) { createLog(Bundle.MESSAGING, "log.paymentMethod.edited", getCode(), code, getLocalizedName(), description.getContent(I18N.getLocale())); <START> setBennu(Bennu.getInstance()); <END> setCode(code); setDescription(description); } } else { throw new DomainException(Optional.of(Bundle.ACCOUNTING), "error.payment.method.already.exists", code); } }</code><technical_language>this is necessary is connected Bennu</technical_language>

Target:
public void edit(String code, LocalizedString description) { if (Bennu.getInstance().getPaymentMethodSet().stream().filter(i -> !i.equals(this)) .noneMatch(i -> i.getCode().equals(code))) { if (!this.getCode().equals(code) || !this.getDescription().equals(description)) { createLog(Bundle.MESSAGING, "log.paymentMethod.edited", getCode(), code, getFormattedDescriptionForLog(getDescription()), getFormattedDescriptionForLog(description)); setCode(code); setDescription(description); } } else { throw new DomainException(Optional.of(Bundle.ACCOUNTING), "error.payment.method.already.exists", code); } }
Source:
<code>public void testReplaceTitle() throws Exception { PID pid = makePid(); String oldTitle = "old_work_title"; Model workModel = ModelFactory.createDefaultModel(); <START> workModel.add(workModel.createResource(pid.getRepositoryPath()), DcElements.title, <END> oldTitle); WorkObject work = repositoryObjectFactory.createWorkObject(pid, workModel); String newTitle = "new_work_title"; MvcResult result = mvc.perform(put("/edit/title/" + pid.getUUID()) .param("title", newTitle)) .andExpect(status().is2xxSuccessful()) .andReturn(); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(pid.getUUID(), respMap.get("pid")); assertEquals("editTitle", respMap.get("action")); hasTitleValue(getUpdatedDescriptionDocument(work.getDescription()), newTitle); }</code><technical_language>want testing replacing a MODS title a DC title</technical_language>

Target:
public void testReplaceTitle() throws Exception { PID pid = makePid(); String oldTitle = "old_work_title"; WorkObject work = repositoryObjectFactory.createWorkObject(pid, null); Document document = new Document(); document.addContent(new Element("mods", MODS_V3_NS) .addContent(new Element("titleInfo", MODS_V3_NS) .addContent(new Element("title", MODS_V3_NS).setText(oldTitle)))); File workModsFile = writeToFile(document); work.setDescription(workModsFile.toPath().toUri()); String newTitle = "new_work_title"; MvcResult result = mvc.perform(put("/edit/title/" + pid.getUUID()) .param("title", newTitle)) .andExpect(status().is2xxSuccessful()) .andReturn(); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(pid.getUUID(), respMap.get("pid")); assertEquals("editTitle", respMap.get("action")); hasTitleValue(getUpdatedDescriptionDocument(work.getDescription()), newTitle); }
Source:
<code>protected static Iterator<BucketResult> getResultsIterator(@AggregationState PrecisionRecallState state) { if (state.getTrueWeights() == null) { return Collections.<BucketResult>emptyList().iterator(); } <START> final Double totalTrueWeight = Streams.stream(state.getTrueWeights().iterator()) <END> .mapToDouble(c -> c.weight) .sum(); final Double totalFalseWeight = Streams.stream(state.getFalseWeights().iterator()) .mapToDouble(c -> c.weight) .sum(); return new Iterator<BucketResult>() { Iterator<FixedDoubleHistogram.Bin> trueIt = state.getTrueWeights().iterator(); Iterator<FixedDoubleHistogram.Bin> falseIt = state.getFalseWeights().iterator(); Double runningFalseWeight = 0.0; Double runningTrueWeight = 0.0; @Override public boolean hasNext() { return trueIt.hasNext() && totalTrueWeight > runningTrueWeight; } @Override public BucketResult next() { final FixedDoubleHistogram.Bin trueResult = trueIt.next(); final FixedDoubleHistogram.Bin falseResult = falseIt.next(); final BucketResult result = new BucketResult( trueResult.left, trueResult.right, totalTrueWeight, totalFalseWeight, runningTrueWeight, runningFalseWeight); runningTrueWeight += trueResult.weight; runningFalseWeight += falseResult.weight; return result; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }</code><technical_language>This small D double</technical_language>

Target:
protected static Iterator<BucketResult> getResultsIterator(@AggregationState PrecisionRecallState state) { if (state.getTrueWeights() == null) { return Collections.<BucketResult>emptyList().iterator(); } final double totalTrueWeight = Streams.stream(state.getTrueWeights().iterator()) .mapToDouble(c -> c.weight) .sum(); final double totalFalseWeight = Streams.stream(state.getFalseWeights().iterator()) .mapToDouble(c -> c.weight) .sum(); return new Iterator<BucketResult>() { Iterator<FixedDoubleHistogram.Bin> trueIt = state.getTrueWeights().iterator(); Iterator<FixedDoubleHistogram.Bin> falseIt = state.getFalseWeights().iterator(); double runningFalseWeight; double runningTrueWeight; @Override public boolean hasNext() { return trueIt.hasNext() && totalTrueWeight > runningTrueWeight; } @Override public BucketResult next() { if (!trueIt.hasNext() || !falseIt.hasNext()) { throw new NoSuchElementException(); } final FixedDoubleHistogram.Bin trueResult = trueIt.next(); final FixedDoubleHistogram.Bin falseResult = falseIt.next(); final BucketResult result = new BucketResult( trueResult.left, trueResult.right, totalTrueWeight, totalFalseWeight, runningTrueWeight, runningFalseWeight); runningTrueWeight += trueResult.weight; runningFalseWeight += falseResult.weight; return result; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
Source:
<code>public WriteResult<Brand, Content> visit(Brand brand) { <START> metricRegistry.meter(visit + "Brand" + METER_CALLED).mark(); <END> try { Optional<Content> previous = getPreviousContent(brand); brand.setItemRefs(ImmutableSet.of()); brand.setSeriesRefs(ImmutableSet.of()); if (previous.isPresent()) { return writeBrandWithPrevious(brand, previous.get()); } updateTimes(brand); handleContainer(brand, Optional.absent()); write(brand, NO_PREVIOUS); return WriteResult.<Brand, Content>written(brand).build(); } catch (RuntimeException e) { metricRegistry.meter(visit + METER_FAILURE).mark(); throw Throwables.propagate(e); } }</code><technical_language>visitMeterPrefix a bit clearer</technical_language>

Target:
public WriteResult<Brand, Content> visit(Brand brand) { metricRegistry.meter(visitMeterPrefix + "Brand." + METER_CALLED).mark(); try { Optional<Content> previous = getPreviousContent(brand); brand.setItemRefs(ImmutableSet.of()); brand.setSeriesRefs(ImmutableSet.of()); if (previous.isPresent()) { return writeBrandWithPrevious(brand, previous.get()); } updateTimes(brand); handleContainer(brand, Optional.absent()); write(brand, NO_PREVIOUS); return WriteResult.<Brand, Content>written(brand).build(); } catch (RuntimeException e) { metricRegistry.meter(visitMeterPrefix + "Brand." + METER_FAILURE).mark(); throw Throwables.propagate(e); } }
Source:
<code>public boolean handleError(RowWithMetaData metaData, ClientResponse response, String error) { if (m_args.maxerrors <= 0) return false; <START> if (response != null) { <END> byte status = response.getStatus(); if (status != ClientResponse.SUCCESS) { m_log.error("Failed to Insert Row: error=" + error + " response=" + ((ClientResponseImpl)response).toJSONString() + " data=" + metaData.rawLine); long fc = m_failedCount.incrementAndGet(); String errMsg = null; if (m_args.maxerrors > 0 && fc > m_args.maxerrors) { errMsg = "Max error count reached, exiting."; } else if (status != ClientResponse.USER_ABORT && status != ClientResponse.GRACEFUL_FAILURE) { errMsg = "Error response received from database, exiting; status=" + Byte.toString(status); } if (errMsg != null) { m_log.error(errMsg); try { closeExecutors(); } catch (InterruptedException e) { } return true; } } else { if (metaData.procedureCallback != null) { try { metaData.procedureCallback.clientCallback(response); } catch (Exception e) { } } } } return false; }</code><technical_language>this true</technical_language>

Target:
public boolean handleError(RowWithMetaData metaData, ClientResponse response, String error) { if (m_args.maxerrors <= 0) return false; if (response != null) { byte status = response.getStatus(); if (status != ClientResponse.SUCCESS) { m_log.error("Failed to Insert Row: error=" + error + " response=" + ((ClientResponseImpl)response).toJSONString() + " data=" + metaData.rawLine); long failCount = m_failedCount.incrementAndGet(); String errMsg = null; if (m_args.maxerrors > 0 && failCount > m_args.maxerrors) { errMsg = "Max error count reached, exiting."; } else if (status != ClientResponse.USER_ABORT && status != ClientResponse.GRACEFUL_FAILURE) { errMsg = "Error response received from database, exiting; status=" + Byte.toString(status); } if (errMsg != null) { m_log.error(errMsg); try { closeExecutors(); } catch (InterruptedException e) { } return true; } } else { if (metaData.procedureCallback != null) { try { metaData.procedureCallback.clientCallback(response); } catch (Exception e) { } } } } return false; }
Source:
<code>public static void store(BaseObject baseObject, File f) { if (baseObject.getName().contains("?") && <START> baseObject instanceof DataCenter){ <END> baseObject.setName(baseObject.getId()); } ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream(f)); oos.writeObject(baseObject); } catch (Exception e) { log.error("Cannot save object", e); throw new RuntimeException("Cannot save object", e); } finally { IOUtils.closeQuietly(oos); baseObject.setLastUpdate(f.lastModified()); } }</code><technical_language>please check type first. save some time for other objects</technical_language>

Target:
public static void store(BaseObject baseObject, File f) { if (baseObject instanceof DataCenter && baseObject.getName().contains("?")){ baseObject.setName(baseObject.getId()); } ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream(f)); oos.writeObject(baseObject); } catch (Exception e) { log.error("Cannot save object", e); throw new RuntimeException("Cannot save object", e); } finally { IOUtils.closeQuietly(oos); baseObject.setLastUpdate(f.lastModified()); } }
Source:
<code>private boolean createResumeFromCacheFile( MavenExecutionResult result, String resumeFromProject ) { String buildDirectory = result.getProject().getBuild().getDirectory(); File buildDirectoryFile = new File( buildDirectory ); <START> boolean isBuildDirectoryPresent = ( buildDirectoryFile.exists() || buildDirectoryFile.mkdirs() ); <END> if ( isBuildDirectoryPresent ) { Path resumeFromCache = Paths.get( buildDirectory, "resume-from-cache" ); try { Files.write( resumeFromCache, resumeFromProject.getBytes() ); return true; } catch ( IOException e ) { slf4jLogger.debug( "Failed writing last failed project to resume-from-cache file at: {}", resumeFromCache, e ); return false; } } else { slf4jLogger.debug( "Failed creating build directory for root project to store resume-from-cache file" ); return false; } }</code><technical_language>Nitpicking: brackets needed</technical_language>

Target:
private boolean createResumeFromCacheFile( MavenExecutionResult result, String resumeFromProject ) { String buildDirectory = result.getProject().getBuild().getDirectory(); File buildDirectoryFile = new File( buildDirectory ); boolean isBuildDirectoryPresent = buildDirectoryFile.exists() || buildDirectoryFile.mkdirs(); if ( isBuildDirectoryPresent ) { Path resumeFromCache = Paths.get( buildDirectory, "resume-from-cache" ); try { Files.write( resumeFromCache, resumeFromProject.getBytes() ); return true; } catch ( IOException e ) { slf4jLogger.info( "Failed writing last failed project to resume-from-cache file at: {}", resumeFromCache, e ); return false; } } else { slf4jLogger.info( "Failed creating build directory for root project to store resume-from-cache file" ); return false; } }
Source:
<code>private static HaxeFunctionDescription tryGetDescription(HaxeCallExpression callExpression) { final HaxeReference expression = (HaxeReference)callExpression.getExpression(); final PsiElement target = expression.resolve(); <START> final boolean isExtension = expression.resolveIsExtension(); <END> if (target instanceof HaxeMethod) { final HaxeClass targetParent = (HaxeClass) ((HaxeMethod) target).getContainingClass(); final HaxeClassResolveResult resolveResult = HaxeClassResolveResult.create(targetParent); return HaxeFunctionDescription.createDescription((HaxeNamedComponent) target, resolveResult, isExtension); } return null; }</code><technical_language>Hmm. a while figure out isExtension means is a static extension. is_Static_Extension a name. a big deal, though</technical_language>

Target:
private static HaxeFunctionDescription tryGetDescription(HaxeCallExpression callExpression) { final HaxeReference expression = (HaxeReference)callExpression.getExpression(); final PsiElement target = expression.resolve(); final boolean isStaticExtension = expression.resolveIsStaticExtension(); if (target instanceof HaxeMethod) { final HaxeClass targetParent = (HaxeClass) ((HaxeMethod) target).getContainingClass(); final HaxeClassResolveResult resolveResult = HaxeClassResolveResult.create(targetParent); return HaxeFunctionDescription.createDescription((HaxeNamedComponent) target, resolveResult, isStaticExtension); } return null; }
Source:
<code>private void initialize() { this.setOrder(26); this.setName(NAME); <START> if (View.isInitialised()) { <END> getScanStatus(); } }</code><technical_language>Is this needed here? (It initialised in hook.)</technical_language>

Target:
private void initialize() { this.setOrder(26); this.setName(NAME); }
Source:
<code>public static int totalVideoRAMSizeMb(VM vm) { Map<String, Integer> params = getVideoDeviceParams(vm.getStaticData()); <START> return (params.getOrDefault(VdsProperties.VIDEO_RAM, 0) + params.getOrDefault(VdsProperties.VIDEO_VRAM, 0) + 1023) / 1024; <END> }</code><technical_language>Please, format line</technical_language>

Target:
public static int totalVideoRAMSizeMb(VM vm) { Map<String, Integer> params = getVideoDeviceRAMSettings(vm.getStaticData()); return (params.getOrDefault(VdsProperties.VIDEO_RAM, 0) + params.getOrDefault(VdsProperties.VIDEO_VRAM, 0) + 1023) / 1024; }
Source:
<code>public ServiceInfo getAssertionConsumerService( AuthnRequest request, Binding preferred, Integer index) { ServiceInfo si = null; if (request != null && request.getAssertionConsumerServiceURL() != null) { si = getAssertionConsumerServiceInfoByUrl(request); if (si.getBinding().getUri().equals(SamlProtocol.POST_BINDING)) { return si; } } if (index != null) { si = assertionConsumerServices .values() .stream() <START> .filter(serviceInfo -> index.equals(serviceInfo.getIndex())) <END> .filter(serviceInfo -> serviceInfo.getBinding() != null) .filter(serviceInfo -> serviceInfo.getBinding().equals(Binding.HTTP_POST)) .findFirst() .orElse(null); if (si != null) { return si; } } if (request != null && request.getProtocolBinding() != null && request.getProtocolBinding().equals(SamlProtocol.POST_BINDING) && supportedBindings.contains(Binding.from(request.getProtocolBinding()))) { si = assertionConsumerServices.get(Binding.from(request.getProtocolBinding())); if (si != null) { return si; } } Binding binding = preferred != null ? preferred : PREFERRED_BINDING; si = assertionConsumerServices.get(binding); if (si != null) { return si; } if (defaultAssertionConsumerService != null) { return defaultAssertionConsumerService; } return assertionConsumerServices.values().stream().findFirst().orElse(null); }</code><technical_language>is this if statement in here? filtering for POST binding in getAssertionConsumerServiceInfoByUrl method</technical_language>

Target:
public ServiceInfo getAssertionConsumerService( AuthnRequest request, Binding preferred, Integer index) { ServiceInfo si = null; if (request != null && request.getAssertionConsumerServiceURL() != null) { si = getAssertionConsumerServiceInfoByUrl(request); if (si != null) { return si; } } if (index != null) { si = getAssertionConsumerServiceInfoByIndex(index); if (si != null) { return si; } } if (request != null && request.getProtocolBinding() != null) { si = getAssertionConsumerServiceInfoByProtocolBinding(request); if (si != null) { return si; } } Binding binding = preferred != null ? preferred : PREFERRED_BINDING; si = assertionConsumerServices.get(binding); if (si != null) { return si; } if (defaultAssertionConsumerService != null) { return defaultAssertionConsumerService; } return assertionConsumerServices.values().stream().findFirst().orElse(null); }
Source:
<code>public Command <START> transactionAboutToCommit(ResourceSetChangeEvent <END> event) throws RollbackException { List<Notification> filteredNotificationsList = event.getNotifications(); CompoundCommand commands = new CompoundCommand(); for (Notification notification : filteredNotificationsList) { Command refactorCommand = handleFilteredNotification(notification); if (null != refactorCommand) { commands.append(refactorCommand); } } return commands.isEmpty() ? null : commands; }</code><technical_language>If this is a pre-commit listener (which I agree more sense a post-commit listener), I needs aggregate pre-commit listener, meaning invoked commit of top-most transaction. Otherwise, in case of nested transactions, end running a refactoring operation (with user interaction time?) for nested transaction commits</technical_language>

Target:
public Command transactionAboutToCommit(ResourceSetChangeEvent event) throws RollbackException { List<Notification> filteredNotificationsList = event.getNotifications(); Command refactorCommand = null; if (!filteredNotificationsList.isEmpty()) { refactorCommand = handleFilteredNotification(filteredNotificationsList.get(0)); } return refactorCommand; }
Source:
<code>public ExpressionTree POWER_EXPR() { return b.<ExpressionTree>nonterminal(PHPLexicalGrammar.POWER_EXPR).is( f.powerExpr( b.zeroOrMore(f.newTuple73( CONCATENATION_EXPR(), b.token(POWER))), <START> CONCATENATION_EXPR())); <END> }</code><technical_language>not: f.powerExpr( CONCATENATION_EXPR(), b.zeroOrMore(f.newTuple73( b.token(POWER), CONCATENATION_EXPR(), )) ); I a significant difference in performance</technical_language>

Target:
public ExpressionTree POWER_EXPR() { return b.<ExpressionTree>nonterminal(PHPLexicalGrammar.POWER_EXPR).is( f.powerExpr( CONCATENATION_EXPR(), b.zeroOrMore(f.newTuple73( b.token(STAR_STAR), CONCATENATION_EXPR())))); }
Source:
<code>private List<IFile> getDependencies(IStorage storage, IContainer c) throws CoreException, IOException { List<IFile> result = new ArrayList<>(); try (InputStream contents = storage.getContents();) { BufferedReader r = new BufferedReader( <START> new InputStreamReader(contents)); <END> try { while (true) { String line = r.readLine(); IFile dep = c.getFile(new Path(line)); result.add(dep); } } catch (Exception e) { } } return result; }</code><technical_language>Please specifiy encoding</technical_language>

Target:
private List<IFile> getDependencies(IStorage storage, IContainer c) throws CoreException, IOException { List<IFile> result = new ArrayList<>(); try (InputStream contents = storage.getContents();) { BufferedReader r = new BufferedReader( new InputStreamReader(contents, Charset.forName("UTF-8"))); try { while (true) { String line = r.readLine(); IFile dep = c.getFile(new Path(line)); result.add(dep); } } catch (Exception e) { } } return result; }
Source:
<code>public static boolean removeAllElementChildren(final Node node) { <START> final boolean hadChildren = node.lastChild != null; <END> while (node.lastChild != null) { node.removeChild(node.lastChild); } return hadChildren; }</code><technical_language>more defensive: final boolean hadChildren = node != null && node.lastChild != null;, do think</technical_language>

Target:
public boolean removeAllElementChildren(final Node node) { final boolean hadChildren = node.lastChild != null; while (node.lastChild != null) { node.removeChild(node.lastChild); } return hadChildren; }
Source:
<code>public final Object fileOpen(final SFileDescriptor file, final SBlock handler) { file.openFile(handler); <START> return Nil.nilObject; <END> }</code><technical_language>nicer return file</technical_language>

Target:
public final Object fileOpen(final SFileDescriptor file, final SBlock handler) { file.openFile(handler, dispatchHandler); return file; }
Source:
<code>public void testSetEventCall() { setting.subscribe(listener); Random random = new FastRandom(); <START> final int n = 50; <END> int expectedEventCallCount = 0; for (int i = 0; i < n; i++) { int r = random.nextInt(-50, 150); expectedEventCallCount += setting.setValue(r) ? 1 : 0; } assertEquals(expectedEventCallCount, eventCallCount); }</code><technical_language>n, i, r: abbreviate please, meaningful names for of them</technical_language>

Target:
public void testSetEventCall() { setting.subscribe(listener); Random random = new FastRandom(); final int MAX_SET_VALUE_COUNT = 50; int expectedEventCallCount = 0; for (int i = 0; i < MAX_SET_VALUE_COUNT; i++) { int randomInt = random.nextInt(-50, 150); expectedEventCallCount += setting.setValue(randomInt) ? 1 : 0; } assertEquals(expectedEventCallCount, eventCallCount); }
Source:
<code>public void afterBeanDiscovery(@Observes AfterBeanDiscovery event, BeanManager manager) { Set<Bean<?>> beans = manager.getBeans(TransactionSynchronizationRegistry.class); if (beans == null || beans.isEmpty()) { event.addBean(new JNDIBean<>(jtaPropertyManager.getJTAEnvironmentBean().getTransactionSynchronizationRegistryJNDIContext(), TransactionSynchronizationRegistry.class)); beans = manager.getBeans(InitialContext.class); if (beans == null || beans.isEmpty()) { <START> event.addBean(new AbstractBean<InitialContext>() { <END> @Override public final Set<Type> getTypes() { return Collections.singleton(InitialContext.class); } @Override public final Class<? extends Annotation> getScope() { return Singleton.class; } @Override protected String getTypeName() { return InitialContext.class.getName(); } @Override public final InitialContext create(final CreationalContext<InitialContext> cc) { try { return new InitialContext(); } catch (final NamingException namingException) { throw new CreationException(namingException.getMessage(), namingException); } } @Override public final void destroy(final InitialContext context, final CreationalContext<InitialContext> cc) { if (context != null) { try { context.close(); } catch (final NamingException namingException) { } } } }); } } event.addContext(new TransactionContext(() -> { final Bean<?> tmBean = manager.resolve(manager.getBeans(TransactionManager.class)); return (TransactionManager)manager.getReference(tmBean, TransactionManager.class, manager.createCreationalContext(tmBean)); }, () -> { final Bean<?> tsrBean = manager.resolve(manager.getBeans(TransactionSynchronizationRegistry.class)); return (TransactionSynchronizationRegistry)manager.getReference(tsrBean, TransactionSynchronizationRegistry.class, manager.createCreationalContext(tsrBean)); })); }</code><technical_language>@ljnelson for asking a bit unrelated this PR code thinking this part is created new AbstractBean<InitialContext> is a bit hard read. Do reasonable pull definition creating a new class referenced here? Similar JNDIBean is defined</technical_language>

Target:
public void afterBeanDiscovery(@Observes AfterBeanDiscovery event, BeanManager manager) { Set<Bean<?>> beans = manager.getBeans(TransactionSynchronizationRegistry.class); if (beans == null || beans.isEmpty()) { event.addBean(new JNDIBean<>(jtaPropertyManager.getJTAEnvironmentBean().getTransactionSynchronizationRegistryJNDIContext(), TransactionSynchronizationRegistry.class, Singleton.class)); } event.addContext(new TransactionContext(() -> { final Bean<?> tmBean = manager.resolve(manager.getBeans(TransactionManager.class)); return (TransactionManager)manager.getReference(tmBean, TransactionManager.class, manager.createCreationalContext(tmBean)); }, () -> { final Bean<?> tsrBean = manager.resolve(manager.getBeans(TransactionSynchronizationRegistry.class)); return (TransactionSynchronizationRegistry)manager.getReference(tsrBean, TransactionSynchronizationRegistry.class, manager.createCreationalContext(tsrBean)); })); }
Source:
<code>public <RESP extends J4pResponse<REQ>, REQ extends J4pRequest> RESP extract(REQ pRequest, JSONObject pJsonResp) throws J4pRemoteException { int status = 0; <START> if( pJsonResp.containsKey("status") { <END> status = pJsonResp.get("status") instanceof Long ? ((Long) pJsonResp.get("status")).intValue() : 0; } if (!allowedCodes.contains(status)) { throw new J4pRemoteException(pRequest, pJsonResp); } return status == 200 ? pRequest.<RESP>createResponse(pJsonResp) : null; }</code><technical_language>miss a closing ')' end of "if" clase)</technical_language>

Target:
public <RESP extends J4pResponse<REQ>, REQ extends J4pRequest> RESP extract(REQ pRequest, JSONObject pJsonResp) throws J4pRemoteException { int status = 0; if( pJsonResp.containsKey("status")) { Object o = pJsonResp.get("status"); if( o instanceof Long ) { status = ((Long)o).intValue(); } } if (!allowedCodes.contains(status)) { throw new J4pRemoteException(pRequest, pJsonResp); } return status == 200 ? pRequest.<RESP>createResponse(pJsonResp) : null; }
Source:
<code>public Response streamingPredict(@Multipart("modelId") long modelId, @Multipart("dataFormat") String dataFormat, @Multipart("file") InputStream inputStream) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); int tenantId = carbonContext.getTenantId(); String userName = carbonContext.getUsername(); try { if (inputStream == null || inputStream.available() == 0) { <START> logger.error("Cannot read the file."); <END> return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Cannot read the file").build(); } final String predictions = mlModelHandler.streamingPredict(tenantId, userName, modelId, dataFormat, inputStream); StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream outputStream) throws IOException { Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(predictions); writer.flush(); writer.close(); } }; return Response.ok(stream).header("Content-disposition", "attachment; filename=predictions.csv").build(); } catch (Exception e) { String msg = MLUtils.getErrorMsg(String.format( "Error occurred while predicting from model [id] %s of tenant [id] %s and [user] %s.", modelId, tenantId, userName), e); logger.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } }</code><technical_language>define a String msg assign error message it. in error message please add for model id etc</technical_language>

Target:
public Response streamingPredict(@Multipart("modelId") long modelId, @Multipart("dataFormat") String dataFormat, @Multipart("file") InputStream inputStream) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); int tenantId = carbonContext.getTenantId(); String userName = carbonContext.getUsername(); try { if (inputStream == null || inputStream.available() == 0) { String msg = String.format( "Error occurred while reading the file for model [id] %s of tenant [id] %s and [user] %s .", modelId, tenantId, userName); logger.error(msg); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } final String predictions = mlModelHandler.streamingPredict(tenantId, userName, modelId, dataFormat, inputStream); StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream outputStream) throws IOException { Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(predictions); writer.flush(); writer.close(); } }; return Response.ok(stream).header("Content-disposition", "attachment; filename=Predictions_" + modelId + "_" + MLUtils.getDate() + MLConstants.CSV).build(); } catch (Exception e) { String msg = MLUtils.getErrorMsg(String.format( "Error occurred while predicting from model [id] %s of tenant [id] %s and [user] %s.", modelId, tenantId, userName), e); logger.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } }