auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public StatusInfo getStatusInfo() { StatusInfo.Builder builder = StatusInfo.Builder.newBuilder(); int upReplicasCount = 0; StringBuilder upReplicas = new StringBuilder(); StringBuilder downReplicas = new StringBuilder(); StringBuilder replicaHostNames = new StringBuilder(); for (PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) { if (replicaHostNames.length() > 0) { replicaHostNames.append(", "); } replicaHostNames.append(node.getServiceUrl()); if (isReplicaAvailable(node.getServiceUrl())) { upReplicas.append(node.getServiceUrl()).append(','); upReplicasCount++; } else { downReplicas.append(node.getServiceUrl()).append(','); } } builder.add("registered-replicas", replicaHostNames.toString()); builder.add("available-replicas", upReplicas.toString()); builder.add("unavailable-replicas", downReplicas.toString()); <START> if (peerEurekaNodes.getMinNumberOfAvailablePeers() > 0) { <END> builder.isHealthy(upReplicasCount >= peerEurekaNodes.getMinNumberOfAvailablePeers()); } return builder.build(); }</code><technical_language>a configured default of -1? Technically run a single eureka server (obv recommended), in case legitimately 0 peers</technical_language>

Target:
public StatusInfo getStatusInfo() { StatusInfo.Builder builder = StatusInfo.Builder.newBuilder(); int upReplicasCount = 0; StringBuilder upReplicas = new StringBuilder(); StringBuilder downReplicas = new StringBuilder(); StringBuilder replicaHostNames = new StringBuilder(); for (PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) { if (replicaHostNames.length() > 0) { replicaHostNames.append(", "); } replicaHostNames.append(node.getServiceUrl()); if (isReplicaAvailable(node.getServiceUrl())) { upReplicas.append(node.getServiceUrl()).append(','); upReplicasCount++; } else { downReplicas.append(node.getServiceUrl()).append(','); } } builder.add("registered-replicas", replicaHostNames.toString()); builder.add("available-replicas", upReplicas.toString()); builder.add("unavailable-replicas", downReplicas.toString()); if (peerEurekaNodes.getMinNumberOfAvailablePeers() > -1) { builder.isHealthy(upReplicasCount >= peerEurekaNodes.getMinNumberOfAvailablePeers()); } return builder.build(); }
Source:
<code>JMSContext getDelegate() { boolean inTx = isInTransaction(); AbstractJMSContext jmsContext = inTx ? transactedJMSContext.get() : requestedJMSContext; if(inTx) { Object alreadyRegistered = transactionSynchronizationRegistry.getResource(AfterCompletionSynchronization.class.getName()); if (alreadyRegistered == null) { transactionSynchronizationRegistry.registerInterposedSynchronization(new AfterCompletionSynchronization(jmsContext)); transactionSynchronizationRegistry.putResource(AfterCompletionSynchronization.class.getName(), true); } <START> <END> } ROOT_LOGGER.debugf("using %s to create the injected JMSContext", jmsContext, id); ConnectionFactory connectionFactory = getConnectionFactory(); return jmsContext.getContext(id, info, connectionFactory); }</code><technical_language>jmsContext resource</technical_language>

Target:
JMSContext getDelegate() { boolean inTx = isInTransaction(); AbstractJMSContext jmsContext = inTx ? transactedJMSContext.get() : requestedJMSContext; ROOT_LOGGER.debugf("using %s to create the injected JMSContext", jmsContext, id); ConnectionFactory connectionFactory = getConnectionFactory(); JMSContext contextInstance = jmsContext.getContext(id, info, connectionFactory); if(inTx) { TransactedJMSContext transactedJMSContext = (TransactedJMSContext)jmsContext; transactedJMSContext.registerCleanUpListener(transactionSynchronizationRegistry, contextInstance); } return contextInstance; }
Source:
<code>public List<ITmfStateInterval> queryHistoryRange(int attributeQuark, long t1, long t2, long resolution, IProgressMonitor monitor) throws TimeRangeException, AttributeNotFoundException, StateSystemDisposedException { if (isDisposed) { throw new StateSystemDisposedException(); } List<ITmfStateInterval> intervals = new LinkedList<>(); ITmfStateInterval currentInterval; long ts, tEnd; IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } if (t2 < t1 || resolution <= 0) { throw new TimeRangeException(); } if (t2 > this.getCurrentEndTime()) { tEnd = this.getCurrentEndTime(); } else { tEnd = t2; } for (ts = t1; ts <= tEnd; ts += ((currentInterval.getEndTime() - ts) / resolution + 1) * resolution) { if (mon.isCanceled()) { return intervals; } currentInterval = querySingleState(ts, attributeQuark); intervals.add(currentInterval); } <START> <END> return intervals; }</code><technical_language>Possibly missing interval t2? lines base code</technical_language>

Target:
public List<ITmfStateInterval> queryHistoryRange(int attributeQuark, long t1, long t2, long resolution, IProgressMonitor monitor) throws TimeRangeException, AttributeNotFoundException, StateSystemDisposedException { if (isDisposed) { throw new StateSystemDisposedException(); } List<ITmfStateInterval> intervals = new LinkedList<>(); ITmfStateInterval currentInterval = null; long ts, tEnd; IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } if (t2 < t1 || resolution <= 0) { throw new TimeRangeException(); } if (t2 > this.getCurrentEndTime()) { tEnd = this.getCurrentEndTime(); } else { tEnd = t2; } for (ts = t1; ts <= tEnd; ts += ((currentInterval.getEndTime() - ts) / resolution + 1) * resolution) { if (mon.isCanceled()) { return intervals; } currentInterval = querySingleState(ts, attributeQuark); intervals.add(currentInterval); } if (currentInterval != null && currentInterval.getEndTime() < tEnd) { currentInterval = querySingleState(tEnd, attributeQuark); intervals.add(currentInterval); } return intervals; }
Source:
<code>public static void blockChi(final Player player) { if (Suffocate.isChannelingSphere(player)) { Suffocate.remove(player); } final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } bPlayer.blockChi(); player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ENDERDRAGON_HURT, 2, 0); long start = System.currentTimeMillis(); new BukkitRunnable() { @Override public void run() { <START> ActionBar.sendActionBar(ChatColor.GOLD + "* Chiblocked *", player); <END> if (System.currentTimeMillis() >= start + getDuration()) { bPlayer.unblockChi(); cancel(); } } }.runTaskTimer(ProjectKorra.plugin, 0, 1); }</code><technical_language>get this set Element.CHI.getColor()</technical_language>

Target:
public static void blockChi(final Player player) { if (Suffocate.isChannelingSphere(player)) { Suffocate.remove(player); } final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } bPlayer.blockChi(); player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ENDERDRAGON_HURT, 2, 0); long start = System.currentTimeMillis(); new BukkitRunnable() { @Override public void run() { ActionBar.sendActionBar(Element.CHI.getColor() + "* Chiblocked *", player); if (System.currentTimeMillis() >= start + getDuration()) { bPlayer.unblockChi(); cancel(); } } }.runTaskTimer(ProjectKorra.plugin, 0, 1); }
Source:
<code>public Map<String, List<String>> parseHeader(String experimentAccession) { try (TsvStreamer sdrfStreamer = dataFileHub.getExperimentFiles(experimentAccession).sdrf.get()) { <START> Pattern pattern = Pattern.compile("(.*?)(\\[)(.*?)(].*)"); <END> Map<String, List<String>> headers = new HashMap<>(); Arrays.stream( sdrfStreamer .get() .findFirst() .orElse(new String[0])) .filter(x -> x.toLowerCase().contains("characteristic") || x.toLowerCase().contains("factor")) .forEach(header -> { Matcher matcher = pattern.matcher(header); if (matcher.matches()) { String headerType = matcher.group(1).trim().toLowerCase(); String headerValue = matcher.group(3); if (headers.containsKey(headerType)) { headers.get(headerType).add(headerValue); } else { List<String> headerValues = new ArrayList<>(); headerValues.add(headerValue); headers.put(headerType, headerValues); } } }); return headers; } }</code><technical_language>Funky</technical_language>

Target:
public Map<String, Set<String>> parseHeader(String experimentAccession) { try (TsvStreamer sdrfStreamer = dataFileHub.getExperimentFiles(experimentAccession).sdrf.get()) { Pattern pattern = Pattern.compile("(.*?)(\\[)(.*?)(].*)"); return Arrays.stream( sdrfStreamer .get() .findFirst() .orElse(new String[0])) .filter(x -> x.toLowerCase().contains("characteristic") || x.toLowerCase().contains("factor")) .filter(x -> x.matches(pattern.toString())) .map(header -> { Matcher matcher = pattern.matcher(header); String headerType = ""; String headerValue = ""; if (matcher.matches()) { headerType = StringUtils.trimAllWhitespace(matcher.group(1)).toLowerCase(); headerValue = matcher.group(3).trim().toLowerCase(); } return new ImmutablePair<>(headerType, headerValue); }) .collect( Collectors.groupingBy( ImmutablePair::getLeft, Collectors.mapping( ImmutablePair::getRight, Collectors.toCollection(LinkedHashSet::new)))); } }
Source:
<code>public static void setValue(DBObject entity, String column, Object value) { <START> String[] path = column.split( "\\." ); <END> Object field = entity; int size = path.length; for (int index = 0 ; index < size ; index++) { String node = path[index]; DBObject parent = (DBObject) field; field = parent.get( node ); if ( field == null ) { if ( index == size - 1 ) { field = value; } else { field = new BasicDBObject(); } parent.put( node, field ); } } }</code><technical_language>compile store pattern re-used</technical_language>

Target:
public static void setValue(DBObject entity, String column, Object value) { String[] path = DOT_SEPARATOR_PATTERN.split( column ); Object field = entity; int size = path.length; for (int index = 0 ; index < size ; index++) { String node = path[index]; DBObject parent = (DBObject) field; field = parent.get( node ); if ( field == null ) { if ( index == size - 1 ) { field = value; } else { field = new BasicDBObject(); } parent.put( node, field ); } } }
Source:
<code>public boolean handlesURI(URI uri) { <START> return servers.containsKey(createKey(uri)); <END> }</code><technical_language>calling createKey here</technical_language>

Target:
public boolean handlesURI(URI uri) { checkURI(uri); return SERVERS.containsKey(uri); }
Source:
<code>private void loadProperties(String configFile) { ObjectMapper jsonMapper = new ObjectMapper(); try { props = jsonMapper.readValue( new File(configFile), new TypeReference<Map<String, String>>() { } ); } catch (IOException ex) { throw new RuntimeException(ex); } routerHost = props.get("router_host") + ":" + props.get("router_port"); brokerHost = props.get("broker_host") + ":" + props.get("broker_port"); historicalHost = props.get("historical_host") + ":" + props.get("historical_port"); coordinatorHost = props.get("coordinator_host") + ":" + props.get("coordinator_port"); indexerHost = props.get("indexer_host") + ":" + props.get("indexer_port"); <START> middleManagerHost = props.get("middlemanager_host"); <END> zookeeperHosts = props.get("zookeeper_hosts"); LOG.info ("router: " + routerHost); LOG.info ("broker: " + brokerHost); LOG.info ("coordinator: " + coordinatorHost); LOG.info ("overlord: " + indexerHost); LOG.info ("middle manager: " + middleManagerHost); LOG.info ("zookeepers: " + zookeeperHosts); }</code><technical_language>this change break existing properties file? is this needed</technical_language>

Target:
private void loadProperties(String configFile) { ObjectMapper jsonMapper = new ObjectMapper(); try { props = jsonMapper.readValue( new File(configFile), new TypeReference<Map<String, String>>() { } ); } catch (IOException ex) { throw new RuntimeException(ex); } routerHost = props.get("router_host") + ":" + props.get("router_port"); brokerHost = props.get("broker_host") + ":" + props.get("broker_port"); historicalHost = props.get("historical_host") + ":" + props.get("historical_port"); coordinatorHost = props.get("coordinator_host") + ":" + props.get("coordinator_port"); indexerHost = props.get("indexer_host") + ":" + props.get("indexer_port"); middleManagerHost = props.get("middlemanager_host"); zookeeperHosts = props.get("zookeeper_hosts"); LOG.info ("router: [%s]", routerHost); LOG.info ("broker [%s]: ", brokerHost); LOG.info ("coordinator: [%s]", coordinatorHost); LOG.info ("overlord: [%s]", indexerHost); LOG.info ("middle manager: [%s]", middleManagerHost); LOG.info ("zookeepers: [%s]", zookeeperHosts); }
Source:
<code>private Iterable<T> filter(Iterable<T> messages, StreamObserver<IsSent> observer) { checkNotNull(messages); checkNotNull(observer); <START> final Collection<T> result = new LinkedList<>(); <END> for (T message : messages) { final Optional<IsSent> response = preProcess(toEnvelope(message)); if (response.isPresent()) { observer.onNext(response.get()); } else { result.add(message); } } return result; }</code><technical_language>newLinkedList()</technical_language>

Target:
private Iterable<T> filter(Iterable<T> messages, StreamObserver<IsSent> observer) { checkNotNull(messages); checkNotNull(observer); final Collection<T> result = newLinkedList(); for (T message : messages) { final Optional<IsSent> response = preProcess(toEnvelope(message)); if (response.isPresent()) { observer.onNext(response.get()); } else { result.add(message); } } return result; }
Source:
<code>public void updateNetworks(final Guid vmId, final List<NicWithLogicalNetworks> nicsWithLogicalNetworks) { ArrayList<VdcActionParametersBase> parameters = createAddVmInterfaceParams(vmId, nicsWithLogicalNetworks); <START> if (parameters.size() == 0) { <END> callback.networkCreated(); return; } updateNetworksFromParams(vmId, parameters); }</code><technical_language>updateNetworksFromParams() code. do need here</technical_language>

Target:
public void updateNetworks(final Guid vmId, final List<NicWithLogicalNetworks> nicsWithLogicalNetworks) { updateNetworksFromParams(vmId, createAddVmInterfaceParams(vmId, nicsWithLogicalNetworks)); }
Source:
<code>public JSONArray getPlatformPluginList() { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); JSONArray initialPluginList = null; updateSiteList: for (UpdateSite updateSite : Jenkins.getInstance().getUpdateCenter().getSiteList()) { String updateCenterJsonUrl = updateSite.getUrl(); String suggestedPluginUrl = updateCenterJsonUrl.replace("/update-center.json", "/platform-plugins.json"); try { URLConnection connection = ProxyConfiguration.open(new URL(suggestedPluginUrl)); try { if(connection instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection)connection).getResponseCode(); if(HttpURLConnection.HTTP_OK != responseCode) { throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + suggestedPluginUrl, responseCode); } } String initialPluginJson = IOUtils.toString(connection.getInputStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); break updateSiteList; } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); <START> continue updateSiteList; <END> } } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); } } if (initialPluginList == null) { try { ClassLoader cl = getClass().getClassLoader(); URL localPluginData = cl.getResource("jenkins/install/platform-plugins.json"); String initialPluginJson = IOUtils.toString(localPluginData.openStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } return initialPluginList; }</code><technical_language>work..? updateSiteList is of loop.</technical_language>

Target:
JSONArray getPlatformPluginList() { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); JSONArray initialPluginList = null; updateSiteList: for (UpdateSite updateSite : Jenkins.getInstance().getUpdateCenter().getSiteList()) { String updateCenterJsonUrl = updateSite.getUrl(); String suggestedPluginUrl = updateCenterJsonUrl.replace("/update-center.json", "/platform-plugins.json"); try { URLConnection connection = ProxyConfiguration.open(new URL(suggestedPluginUrl)); try { if(connection instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection)connection).getResponseCode(); if(HttpURLConnection.HTTP_OK != responseCode) { throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + suggestedPluginUrl, responseCode); } } String initialPluginJson = IOUtils.toString(connection.getInputStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); break updateSiteList; } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); continue updateSiteList; } } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); } } if (initialPluginList == null) { try { ClassLoader cl = getClass().getClassLoader(); URL localPluginData = cl.getResource("jenkins/install/platform-plugins.json"); String initialPluginJson = IOUtils.toString(localPluginData.openStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } return initialPluginList; }
Source:
<code>protected void executeCommand() { VDSGroup vdsGroup = getVdsGroup(); if (vdsGroup.supportsVirtService()) { setSucceeded(initVirtResources()); } if (vdsGroup.supportsGlusterService()) { setSucceeded(initGlusterPeerProcess()); } <START> <END> runVdsCommand(VDSCommandType.GetBiosInfo, new VdsIdAndVdsVDSCommandParametersBase(getVds())); }</code><technical_language>triggered if success. if fail a host moved NonOperational if is intention , add a try catch, if is add failure reason of failure AuditLog</technical_language>

Target:
protected void executeCommand() { VDSGroup vdsGroup = getVdsGroup(); if (vdsGroup.supportsVirtService()) { setSucceeded(initVirtResources()); } if (vdsGroup.supportsGlusterService()) { setSucceeded(initGlusterPeerProcess()); } }
Source:
<code>private void populateCommands(final PatchSetDetail detail) { for (final UiCommandDetail cmd : detail.getCommands()) { final Button b = new Button(cmd.label); b.setEnabled(cmd.enabled); b.setTitle(cmd.title); b.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { b.setEnabled(false); AsyncCallback<NativeString> cb = new AsyncCallback<NativeString>() { @Override public void onFailure(Throwable caught) { b.setEnabled(true); new ErrorDialog(caught).center(); } @Override public void onSuccess(NativeString msg) { b.setEnabled(true); <START> if (!msg.toString().isEmpty()) { <END> Window.alert(msg.asString()); } } }; RestApi api = ChangeApi.revision(patchSet.getId()).view(cmd.id); if ("PUT".equalsIgnoreCase(cmd.method)) { api.put(JavaScriptObject.createObject(), cb); } else if ("DELETE".equalsIgnoreCase(cmd.method)) { api.delete(cb); } else { api.post(JavaScriptObject.createObject(), cb); } } }); actionsPanel.add(b); } }</code><technical_language>this if (msg != null && !msg.toString().isEmpty()) {</technical_language>

Target:
private void populateCommands(final PatchSetDetail detail) { for (final UiCommandDetail cmd : detail.getCommands()) { final Button b = new Button(cmd.label); b.setEnabled(cmd.enabled); b.setTitle(cmd.title); b.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { b.setEnabled(false); AsyncCallback<NativeString> cb = new AsyncCallback<NativeString>() { @Override public void onFailure(Throwable caught) { b.setEnabled(true); new ErrorDialog(caught).center(); } @Override public void onSuccess(NativeString msg) { b.setEnabled(true); if (msg != null && !msg.asString().isEmpty()) { Window.alert(msg.asString()); } } }; RestApi api = ChangeApi.revision(patchSet.getId()).view(cmd.id); if ("PUT".equalsIgnoreCase(cmd.method)) { api.put(JavaScriptObject.createObject(), cb); } else if ("DELETE".equalsIgnoreCase(cmd.method)) { api.delete(cb); } else { api.post(JavaScriptObject.createObject(), cb); } } }); actionsPanel.add(b); } }
Source:
<code>public static Builder fromEnv() throws DockerCertificateException { final DockerUtils dockerUtils = new DockerUtils(); <START> final String endpoint = fromNullable(getenv("DOCKER_HOST")) <END> .or(dockerUtils.defaultDockerEndpoint()); final Path dockerCertPath = Paths.get(fromNullable(getenv("DOCKER_CERT_PATH")) .or(dockerUtils.defaultCertPath())); final Builder builder = new Builder(); final Optional<DockerCertificates> certs = DockerCertificates.builder() .dockerCertPath(dockerCertPath).build(); if (endpoint.startsWith(UNIX_SCHEME + "://")) { builder.uri(endpoint); } else { final String stripped = endpoint.replaceAll(".*://", ""); final HostAndPort hostAndPort = HostAndPort.fromString(stripped); final String hostText = hostAndPort.getHostText(); final String scheme = certs.isPresent() ? "https" : "http"; final int port = hostAndPort.getPortOrDefault(DEFAULT_PORT); final String address = isNullOrEmpty(hostText) ? DEFAULT_HOST : hostText; builder.uri(scheme + "://" + address + ":" + port); } if (certs.isPresent()) { builder.dockerCertificates(certs.get()); } return builder; }</code><technical_language>This exact series of method calls-fromNullable(getenv("DOCKER_HOST")).or(dockerUtils.defaultDockerEndpoint());-is multiple times in places. this a single method in DockerUtils, getHost(). fromNullable(getenv("DOCKER_CERT_PATH")).or(dockerUtils.defaultCertPath())</technical_language>

Target:
public static Builder fromEnv() throws DockerCertificateException { final String endpoint = DockerHost.endpointFromEnv(); final Path dockerCertPath = Paths.get(DockerHost.certPathFromEnv()); final Builder builder = new Builder(); final Optional<DockerCertificates> certs = DockerCertificates.builder() .dockerCertPath(dockerCertPath).build(); if (endpoint.startsWith(UNIX_SCHEME + "://")) { builder.uri(endpoint); } else { final String stripped = endpoint.replaceAll(".*://", ""); final HostAndPort hostAndPort = HostAndPort.fromString(stripped); final String hostText = hostAndPort.getHostText(); final String scheme = certs.isPresent() ? "https" : "http"; final int port = hostAndPort.getPortOrDefault(DockerHost.defaultPort()); final String address = isNullOrEmpty(hostText) ? DockerHost.defaultAddress() : hostText; builder.uri(scheme + "://" + address + ":" + port); } if (certs.isPresent()) { builder.dockerCertificates(certs.get()); } return builder; }
Source:
<code>public void removeExpiredEntriesFromListing(long ttl, long now) { final Iterator<Map.Entry<Path, PathMetadata>> iterator = listMap.entrySet().iterator(); <START> while(iterator.hasNext()) { <END> final Map.Entry<Path, PathMetadata> entry = iterator.next(); if (entry.getValue().getLastUpdated() != 0 && (entry.getValue().getLastUpdated() + ttl) <= now) { iterator.remove(); } } }</code><technical_language>nit: add a space while</technical_language>

Target:
public synchronized void removeExpiredEntriesFromListing(long ttl, long now) { final Iterator<Map.Entry<Path, PathMetadata>> iterator = listMap.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<Path, PathMetadata> entry = iterator.next(); if (entry.getValue().getLastUpdated() != 0 && (entry.getValue().getLastUpdated() + ttl) <= now) { iterator.remove(); } } }
Source:
<code>public final void handle(EventMessage<?> event) { if (isActive) { metaModel.findHandlerMethods(event).stream() .filter(h -> h.unwrap(SagaMethodMessageHandlingMember.class) .map(sh -> getAssociationValues().contains(sh.getAssociationValue(event))) .orElse(true)) .findFirst().ifPresent(h -> { <START> try { <END> executeWithResult(() -> h.handle(event, sagaInstance)); if (event instanceof TrackedEventMessage) { this.trackingToken.set(((TrackedEventMessage) event).trackingToken()); } } catch (RuntimeException | Error e) { throw e; } catch (Exception e) { throw new SagaExecutionException("Exception while handling an Event in a Saga", e); } finally { if (isEndingHandler(h)) { doEnd(); } } }); } }</code><technical_language>do</technical_language>

Target:
public final void handle(EventMessage<?> event) { if (isActive) { metaModel.findHandlerMethods(event).stream() .filter(handler -> handler.unwrap(SagaMethodMessageHandlingMember.class) .map(sh -> getAssociationValues() .contains(sh.getAssociationValue(event))) .orElse(true)) .findFirst() .ifPresent(handler -> handle(handler, event)); } }
Source:
<code>public void executeAction(final WorkflowProcessor processor, <START> final Map<String, WorkflowActionClassParameter> params) throws WorkflowActionFailureException { <END> try { final Contentlet contentlet = processor.getContentlet(); Logger.debug(this, "Saving the content of the contentlet: " + contentlet.getIdentifier()); final Contentlet checkoutContentlet = this.contentletAPI.checkout (contentlet.getInode(), processor.getUser(), false); checkoutContentlet.setProperty(Contentlet.WORKFLOW_IN_PROGRESS, Boolean.TRUE); this.contentletAPI.checkin( checkoutContentlet, processor.getUser(), false); Logger.debug(this, "content version already saved for the contentlet: " + contentlet.getIdentifier()); } catch (Exception e) { Logger.error(this.getClass(),e.getMessage(),e); throw new WorkflowActionFailureException(e.getMessage()); } }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove declaration of thrown exception 'com.dotmarketing.portlets.workflows.model.WorkflowActionFailureException' is a runtime exception. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public void executeAction(final WorkflowProcessor processor, final Map<String, WorkflowActionClassParameter> params) throws WorkflowActionFailureException { try { final Contentlet contentlet = processor.getContentlet(); Logger.debug(this, "Saving the content of the contentlet: " + contentlet.getIdentifier()); final Contentlet checkoutContentlet = this.contentletAPI.checkout (contentlet.getInode(), processor.getUser(), false); final String inode = checkoutContentlet.getInode(); this.contentletAPI.copyProperties(checkoutContentlet, contentlet.getMap()); checkoutContentlet.setInode(inode); checkoutContentlet.setProperty(Contentlet.WORKFLOW_IN_PROGRESS, Boolean.TRUE); final Contentlet contentletNew = this.contentletAPI.checkin( checkoutContentlet, processor.getUser(), false); processor.setContentlet(contentletNew); Logger.debug(this, "content version already saved for the contentlet: " + contentlet.getIdentifier()); } catch (Exception e) { Logger.error(this.getClass(),e.getMessage(),e); throw new WorkflowActionFailureException(e.getMessage()); } }
Source:
<code>protected void onHandleIntent(Intent intent) { <START> if (sWasRun) <END> return; scheduleDeckReminder(); scheduleNotification(this); sWasRun = true; }</code><technical_language>Please braces one-line if statements</technical_language>

Target:
protected void onHandleIntent(Intent intent) { if (sWasRun) { return; } scheduleDeckReminder(); scheduleNotification(this); sWasRun = true; }
Source:
<code>public void signInWithIntentToParticipate() throws Exception { account.setId(USER_ID); <START> Account consentedAccount = new GenericAccount(); <END> StudyParticipant consentedParticipant = new StudyParticipant.Builder().build(); doReturn(account).when(accountDao).authenticate(study, EMAIL_PASSWORD_SIGN_IN); doReturn(PARTICIPANT).when(participantService).getParticipant(study, account, false); doReturn(UNCONSENTED_STATUS_MAP).when(consentService).getConsentStatuses(any(), eq(account)); doReturn(consentedAccount).when(accountDao).getAccount(any()); doReturn(consentedParticipant).when(participantService).getParticipant(study, consentedAccount, false); doReturn(CONSENTED_STATUS_MAP).when(consentService).getConsentStatuses(any(), eq(consentedAccount)); when(intentService.registerIntentToParticipate(study, account)).thenReturn(true); service.signIn(study, CONTEXT, EMAIL_PASSWORD_SIGN_IN); }</code><technical_language>create a Account.create() references GenericAccount everywhere. (Here other places in this PR.)</technical_language>

Target:
public void signInWithIntentToParticipate() throws Exception { account.setId(USER_ID); Account consentedAccount = Account.create(); StudyParticipant consentedParticipant = new StudyParticipant.Builder().build(); doReturn(account).when(accountDao).authenticate(study, EMAIL_PASSWORD_SIGN_IN); doReturn(PARTICIPANT).when(participantService).getParticipant(study, account, false); doReturn(UNCONSENTED_STATUS_MAP).when(consentService).getConsentStatuses(any(), eq(account)); doReturn(consentedAccount).when(accountDao).getAccount(any()); doReturn(consentedParticipant).when(participantService).getParticipant(study, consentedAccount, false); doReturn(CONSENTED_STATUS_MAP).when(consentService).getConsentStatuses(any(), eq(consentedAccount)); when(intentService.registerIntentToParticipate(study, account)).thenReturn(true); service.signIn(study, CONTEXT, EMAIL_PASSWORD_SIGN_IN); }
Source:
<code>private Map<Integer, Question> getPreGeneratedQuestions(final Long accountId, final DateTime today) { final DateTime expiration = today.plusDays(1); final ImmutableList<AccountQuestion> questionIds = this.questionResponseDAO.getAccountQuestions(accountId, expiration); if (questionIds == null || questionIds.size() == 0) { return Collections.emptyMap(); } <START> Map<Integer, Question> questions = new HashMap<>(); <END> for (final AccountQuestion question : questionIds) { final Integer qid = question.questionId; if (!questions.containsKey(qid)) { final Long accountQId = question.id; questions.put(qid, Question.withAskTimeAccountQId(this.questionIdMap.get(qid), accountQId, today)); } } return questions; }</code><technical_language>final</technical_language>

Target:
private Map<Integer, Question> getPreGeneratedQuestions(final Long accountId, final DateTime today) { final DateTime expiration = today.plusDays(1); final ImmutableList<AccountQuestion> questionIds = this.questionResponseDAO.getAccountQuestions(accountId, expiration); if (questionIds == null || questionIds.size() == 0) { return Collections.emptyMap(); } final Map<Integer, Question> questions = new HashMap<>(); for (final AccountQuestion question : questionIds) { final Integer qid = question.questionId; if (!questions.containsKey(qid)) { final Long accountQId = question.id; questions.put(qid, Question.withAskTimeAccountQId(this.questionIdMap.get(qid), accountQId, today)); } } return questions; }
Source:
<code>public boolean hasCompatibleAnalyzer(ElasticsearchFieldPredicateBuilderFactory other) { if ( !getClass().equals( other.getClass() ) ) { return false; } ElasticsearchTextFieldPredicateBuilderFactory castedOther = (ElasticsearchTextFieldPredicateBuilderFactory) other; return Objects.equals( analyzer, castedOther.analyzer ) && <START> Objects.equals( searchAnalyzer, castedOther.searchAnalyzer ) && <END> Objects.equals( normalizer, castedOther.normalizer ); }</code><technical_language>If search analyzers analyzers different, this return true, I think. tests reflect that... ? In fact, solve this easily keeping search analyzer in this class, analyzer a default search analyzer is null</technical_language>

Target:
public boolean hasCompatibleAnalyzer(ElasticsearchFieldPredicateBuilderFactory other) { if ( !getClass().equals( other.getClass() ) ) { return false; } ElasticsearchTextFieldPredicateBuilderFactory castedOther = (ElasticsearchTextFieldPredicateBuilderFactory) other; return Objects.equals( analyzer, castedOther.analyzer ) && Objects.equals( normalizer, castedOther.normalizer ); }
Source:
<code>private String getLabel(String mode) { String label = OpenShiftCoreMessages.RunOnOpenshift; <START> if (ILaunchManager.PROFILE_MODE.equals(mode)) { <END> label = OpenShiftCoreMessages.ProfileOnOpenshift; } else if (ILaunchManager.DEBUG_MODE.equals(mode)) { label = OpenShiftCoreMessages.DebugOnOpenshift; } return label; }</code><technical_language>a niggle: i switch-case "RunOnOpenshift" default more readable</technical_language>

Target:
private String getLabel(String mode) { String label; switch (mode) { case ILaunchManager.DEBUG_MODE: label = OpenShiftCoreMessages.DebugOnOpenshift; break; case ILaunchManager.PROFILE_MODE: label = OpenShiftCoreMessages.ProfileOnOpenshift; break; default: label = OpenShiftCoreMessages.RunOnOpenshift; break; } return label; }
Source:
<code>private void parseServiceSequence(final FBType type) throws TypeImportException, XMLStreamException { ServiceSequence serviceSequence = LibraryElementFactory.eINSTANCE.createServiceSequence(); readNameCommentAttributes(serviceSequence); processChildren(LibraryElementTags.SERVICE_SEQUENCE_ELEMENT, name -> { if <START> (name.equals(LibraryElementTags.SERVICE_TRANSACTION_ELEMENT)) { <END> parseServiceTransaction(serviceSequence, type); return true; } return false; }); type.getService().getServiceSequence().add(serviceSequence); }</code><technical_language>call equals constant</technical_language>

Target:
private void parseServiceSequence(final FBType type) throws TypeImportException, XMLStreamException { ServiceSequence serviceSequence = LibraryElementFactory.eINSTANCE.createServiceSequence(); readNameCommentAttributes(serviceSequence); processChildren(LibraryElementTags.SERVICE_SEQUENCE_ELEMENT, name -> { if (LibraryElementTags.SERVICE_TRANSACTION_ELEMENT.equals(name)) { parseServiceTransaction(serviceSequence, type); return true; } return false; }); type.getService().getServiceSequence().add(serviceSequence); }
Source:
<code>private void close(TableItem ti) { if (ti.getData() instanceof EditorReference) { int index = table.indexOf(ti); EditorReference ed = (EditorReference) ti.getData(); page.closeEditors(new IEditorReference[] { ed }, false); table.setFocus(); tableViewer.setInput(getInput(page)); if (table.getItemCount() == 0) { cancel(dialog); } if (table.isDisposed()) <START> { <END> return; } if (index > 0 && index <= table.getItemCount()) { index -= 1; } table.setSelection(index); } }</code><technical_language>Please curly braces if/else</technical_language>

Target:
private void close(TableItem ti) { if (ti.getData() instanceof EditorReference) { int index = table.indexOf(ti); EditorReference ed = (EditorReference) ti.getData(); bypassFocusLost = true; page.closeEditors(new IEditorReference[] { ed }, true); bypassFocusLost = false; table.setFocus(); tableViewer.setInput(getInput(page)); if (table.getItemCount() == 0) { cancel(dialog); } if (table.isDisposed()) { return; } if (index > 0 && index <= table.getItemCount()) { index -= 1; } table.setSelection(index); } }
Source:
<code>public JobHandle scheduleJob(Job job, JobContext ctx, Trigger trigger) { <START> if (ctx instanceof ProcessJobContext && !(ctx instanceof StartProcessJobContext)) { <END> ProcessJobContext processCtx = (ProcessJobContext) ctx; List<GlobalJobHandle> jobHandles = timerJobsPerSession.get(processCtx.getSessionId()); if (jobHandles == null) { jobHandles = new CopyOnWriteArrayList<GlobalJobHandle>(); timerJobsPerSession.put(processCtx.getSessionId(), jobHandles); } else { for (GlobalJobHandle handle : jobHandles) { long timerId = handle.getTimerId(); if (timerId == processCtx.getTimer().getId()) { return handle; } } } GlobalJobHandle jobHandle = (GlobalJobHandle) this.schedulerService.scheduleJob(job, ctx, trigger); if (jobHandle != null) { jobHandles.add(jobHandle); } return jobHandle; } GlobalJobHandle jobHandle = (GlobalJobHandle) this.schedulerService.scheduleJob(job, ctx, trigger); return jobHandle; }</code><technical_language>This kind of sense job is fired process is started I is reason hold this in memory probably? If is a timer in middle of process instance, useful "track" progress, otherwise... is point of saving this in memory is clear right now. is serialized somewhere</technical_language>

Target:
public JobHandle scheduleJob(Job job, JobContext ctx, Trigger trigger) { if (ctx instanceof StartProcessJobContext) { GlobalJobHandle jobHandle = (GlobalJobHandle) this.schedulerService.scheduleJob(job, ctx, trigger); if (jobHandle != null) { startTimerJobs.add(jobHandle); } return jobHandle; } else if (ctx instanceof ProcessJobContext) { ProcessJobContext processCtx = (ProcessJobContext) ctx; List<GlobalJobHandle> jobHandles = timerJobsPerSession.get(processCtx.getSessionId()); if (jobHandles == null) { jobHandles = new CopyOnWriteArrayList<GlobalJobHandle>(); timerJobsPerSession.put(processCtx.getSessionId(), jobHandles); } else { for (GlobalJobHandle handle : jobHandles) { long timerId = handle.getTimerId(); if (timerId == processCtx.getTimer().getId()) { return handle; } } } GlobalJobHandle jobHandle = (GlobalJobHandle) this.schedulerService.scheduleJob(job, ctx, trigger); if (jobHandle != null) { jobHandles.add(jobHandle); } return jobHandle; } GlobalJobHandle jobHandle = (GlobalJobHandle) this.schedulerService.scheduleJob(job, ctx, trigger); return jobHandle; }
Source:
<code>protected Pair<Q, E> pollNext() { <START> final int timeout = 10; <END> final TimeUnit timeUnit = TimeUnit.MINUTES; Pair<Q, E> next = null; try { next = getPairQueue().poll(timeout, timeUnit); } catch (InterruptedException ignored) { } if (next == null) { throw new IllegalStateException(String.format("Didn't manage to poll the next pair during %s %s", String.valueOf(timeout), timeUnit)); } return next; }</code><technical_language>configurable</technical_language>

Target:
protected Pair<Q, E> pollNext() { Pair<Q, E> next = null; try { next = getPairQueue().poll(pollTimeout.getValue(), TimeUnit.MILLISECONDS); } catch (InterruptedException ignored) { } if (next == null) { throw new IllegalStateException(String.format("Didn't manage to poll the next pair. Timeout %s", pollTimeout)); } return next; }
Source:
<code>private void runInHarvesterThread() { Buffer buf; DatagramPacket pkt = null; MySocket destinationSocket; InetSocketAddress remoteAddress; do { if (close) { break; } buf = getFreeBuffer(); if (pkt == null) pkt = new DatagramPacket(buf.buffer, 0, buf.buffer.length); else pkt.setData(buf.buffer, 0, buf.buffer.length); try { socket.receive(pkt); } catch (IOException ioe) { if (!close) { logger.severe("Failed to receive from socket: " + ioe); } break; } buf.len = pkt.getLength(); remoteAddress = (InetSocketAddress) pkt.getSocketAddress(); destinationSocket = sockets.get(remoteAddress); if (destinationSocket != null) { destinationSocket.addBuffer(buf); } else { String ufrag = getUfrag(buf.buffer, 0, buf.len); if (ufrag == null) { continue; } maybeAcceptNewSession(buf, remoteAddress, ufrag); } } while (true); for (MySocket candidateSocket : sockets.values()) { candidateSocket.close(); } <START> socket.close(); <END> }</code><technical_language>AbstractUdpListener.socket.close() is called here, in AbstractUdpListener.close(). Is a reason</technical_language>

Target:
private void runInHarvesterThread() { Buffer buf; DatagramPacket pkt = null; MySocket destinationSocket; InetSocketAddress remoteAddress; do { if (close) { break; } buf = getFreeBuffer(); if (pkt == null) pkt = new DatagramPacket(buf.buffer, 0, buf.buffer.length); else pkt.setData(buf.buffer, 0, buf.buffer.length); try { socket.receive(pkt); } catch (IOException ioe) { if (!close) { logger.severe("Failed to receive from socket: " + ioe); } break; } buf.len = pkt.getLength(); remoteAddress = (InetSocketAddress) pkt.getSocketAddress(); destinationSocket = sockets.get(remoteAddress); if (destinationSocket != null) { destinationSocket.addBuffer(buf); } else { String ufrag = getUfrag(buf.buffer, 0, buf.len); if (ufrag == null) { continue; } maybeAcceptNewSession(buf, remoteAddress, ufrag); } } while (true); for (MySocket candidateSocket : new ArrayList<>(sockets.values())) { candidateSocket.close(); } socket.close(); }
Source:
<code>public final void addListener(TransactionCompletedListener listener) { <START> notifier.thenRunAsync(listener::onCompletion); <END> }</code><technical_language>async methods explicit thread pool parameter, common pool</technical_language>

Target:
public final void addListener(TransactionCompletedListener listener) { notifier.thenRun(listener::onCompletion); }
Source:
<code>public Object[] getFiniteSupport() { <START> booldist.getFiniteSupport(); <END> return finiteSupport; }</code><technical_language>@datang1992 is this line useful</technical_language>

Target:
public Object[] getFiniteSupport() { return finiteSupport; }
Source:
<code>public void testPick() throws Exception { EasyMock.expect(serviceProvider.getInstance()).andReturn(instance).anyTimes(); EasyMock.expect(instance.getAddress()).andReturn(ADDRESS).anyTimes(); EasyMock.expect(instance.getPort()).andReturn(PORT).anyTimes(); EasyMock.replay(instance, serviceProvider); Server server = serverDiscoverySelector.pick(); Assert.assertEquals(PORT, server.getPort()); Assert.assertEquals(ADDRESS, server.getAddress()); Assert.assertTrue(server.getHost().contains(new Integer(PORT).toString())); Assert.assertTrue(server.getHost().contains(ADDRESS)); Assert.assertEquals(new String("http"), server.getScheme()); EasyMock.verify(instance, serviceProvider); <START> final URI uri = new URI(String.format("%s://%s%s", server.getScheme(), server.getHost(), "/druid/indexer/v1/action")); <END> Assert.assertEquals(PORT, uri.getPort()); Assert.assertEquals(ADDRESS, uri.getHost()); Assert.assertEquals("http", uri.getScheme()); }</code><technical_language>this PR is removing potentially bad String.format assumptions, new URI(scheme, host, path, null) instead of String.format :)</technical_language>

Target:
public void testPick() throws Exception { EasyMock.expect(serviceProvider.getInstance()).andReturn(instance).anyTimes(); EasyMock.expect(instance.getAddress()).andReturn(ADDRESS).anyTimes(); EasyMock.expect(instance.getPort()).andReturn(PORT).anyTimes(); EasyMock.replay(instance, serviceProvider); Server server = serverDiscoverySelector.pick(); Assert.assertEquals(PORT, server.getPort()); Assert.assertEquals(ADDRESS, server.getAddress()); Assert.assertTrue(server.getHost().contains(Integer.toString(PORT))); Assert.assertTrue(server.getHost().contains(ADDRESS)); Assert.assertEquals("http", server.getScheme()); EasyMock.verify(instance, serviceProvider); final URI uri = new URI( server.getScheme(), null, server.getAddress(), server.getPort(), "/druid/indexer/v1/action", null, null ); Assert.assertEquals(PORT, uri.getPort()); Assert.assertEquals(ADDRESS, uri.getHost()); Assert.assertEquals("http", uri.getScheme()); }
Source:
<code>public void onNext(Map<String, Object> map) { try { refreshHost(); <START> <END> } finally { subscription.request(1); } }</code><technical_language>please remove this empty line</technical_language>

Target:
public void onNext(Map<String, Object> map) { try { vdsManager.refreshHost(); } finally { subscription.request(1); } }
Source:
<code>public int read() throws IOException { int outByte = inputStream.read(); if (cacheValidationEnabled) { verify(originInputStream.read() == outByte, "corrupted buffer at position " + getPos()); } <START> return outByte; <END> }</code><technical_language>bytes</technical_language>

Target:
public int read() throws IOException { int outByte = inputStream.read(); if (cacheValidationEnabled) { verify(dataTierInputStream.get().read() == outByte, "corrupted buffer at position " + getPos()); } return outByte; }
Source:
<code>protected boolean validate() { if (!super.validate()) { return false; } macPool = getMacPool(); Map<Guid, StorageDomain> domainsMap = new HashMap<>(); if (!validateBeforeCloneVm(domainsMap)) { return false; } <START> List<VmNetworkInterface> vmNetworkInterfaces = getVm().getInterfaces(); vmNicMacsUtils.replaceInvalidEmptyStringMacAddressesWithNull(vmNetworkInterfaces); <END> if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); if (getVm().getInterfaces().size() > macPool.getAvailableMacsCount()) { return failValidation(EngineMessage.MAC_POOL_NOT_ENOUGH_MAC_ADDRESSES); } } if (!validateBallonDevice()) { return false; } if (!validateSoundDevice()) { return false; } return validateAfterCloneVm(domainsMap); }</code><technical_language>this in validateBeforeCloneVm method? other hand this is related executeCommand method validate one</technical_language>

Target:
protected boolean validate() { if (!super.validate()) { return false; } macPool = getMacPool(); Map<Guid, StorageDomain> domainsMap = new HashMap<>(); if (!validateBeforeCloneVm(domainsMap)) { return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); if (getVm().getInterfaces().size() > macPool.getAvailableMacsCount()) { return failValidation(EngineMessage.MAC_POOL_NOT_ENOUGH_MAC_ADDRESSES); } } if (!validateBallonDevice()) { return false; } if (!validateSoundDevice()) { return false; } return validateAfterCloneVm(domainsMap); }
Source:
<code>public void run() { while (running) { <START> if (!tc.isConnected()) <END> connectTelnetClient(); boolean end_loop = false; byte[] buff = new byte[135]; int ret_read = 0; InputStream instr = tc.getInputStream(); do { try { ret_read = instr.read(buff); if(ret_read > 0) { String line = new String(buff, 0, ret_read).trim(); for (String cmd : line.split("\r")) { if (!StringUtils.isBlank(line)) { logger.trace("Received from {}: {}", connection.getHost(), cmd); callback.updateReceived(cmd); } } } } catch (IOException e) { logger.error("Error in telnet connection", e); end_loop = true; } } while(running && end_loop == false); } }</code><technical_language>add curly braces event this is One-liner</technical_language>

Target:
public void run() { while (running) { if (!tc.isConnected()) { connectTelnetClient(); } boolean end_loop = false; BufferedReader reader = new BufferedReader(new InputStreamReader(tc.getInputStream())); do { try { String line = reader.readLine(); if (!StringUtils.isBlank(line)) { logger.trace("Received from {}: {}", connection.getHost(), line); callback.updateReceived(line); } } catch (IOException e) { logger.warn("Error in telnet connection", e); end_loop = true; } } while(running && end_loop == false); } }
Source:
<code>private void removeFromEstablishedSessions(Connection connection) { DTLSSession establishedSession = connection.getEstablishedSession(); if (establishedSession != null) { SessionId sessionId = establishedSession.getSessionIdentifier(); Connection removedConnection = connectionsByEstablishedSession.remove(sessionId); if (removedConnection != null && removedConnection != connection) { connectionsByEstablishedSession.put(sessionId, removedConnection); } <START> } <END> }</code><technical_language>removedConnection null before</technical_language>

Target:
private void removeFromEstablishedSessions(Connection connection) { DTLSSession establishedSession = connection.getEstablishedSession(); if (establishedSession != null) { SessionId sessionId = establishedSession.getSessionIdentifier(); connectionsByEstablishedSession.remove(sessionId, connection); } }