auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void setArrivalFilter(int selection) { ArrivalFilter newFilter = ArrivalFilter.fromInt(selection); boolean switchedFromOnlyDepartures = mArrivalFilter == ArrivalFilter.ONLY_DEPARTURES && newFilter != ArrivalFilter.ONLY_DEPARTURES; mArrivalFilter = newFilter; ObaContract.Stops.setArrivalFilter(getActivity(), mStopUri, ArrivalFilter.fromInt(selection)); refreshSituations(UIUtils.getAllSituations(getArrivalsLoader().getLastGoodResponse(), mRoutesFilter)); <START> refreshLocal(); <END> if (mArrivalFilter == ArrivalFilter.ONLY_DEPARTURES || switchedFromOnlyDepartures) { setEmptyText(UIUtils.getNoArrivalsMessage(Application.get().getApplicationContext(), getArrivalsLoader().getMinutesAfter(), false, false, mArrivalFilter)); } Button footerButton = (Button) mFooter.findViewById(R.id.load_more_arrivals); Button emptyButton = (Button) mEmptyList.findViewById(R.id.load_more_arrivals); if (mArrivalFilter == ArrivalFilter.ONLY_DEPARTURES) { footerButton.setText(R.string.stop_info_load_more_departures); emptyButton.setText(R.string.stop_info_load_more_departures); } if (switchedFromOnlyDepartures) { footerButton.setText(R.string.stop_info_load_more_arrivals); emptyButton.setText(R.string.stop_info_load_more_arrivals); } }</code><technical_language>I refreshLocal(); moved end of this method triggers adapter update. want UI content (e.g., "load more" text) is updated triggering reload</technical_language>

Target:
private void setArrivalFilter(int selection) { ArrivalFilter newFilter = ArrivalFilter.fromInt(selection); setArrivalFilter(newFilter); }
Source:
<code>private BrokerConfig createBrokerConfig( RuntimeIdentity runtimeId, Collection<PluginMeta> pluginsMeta, List<EnvVar> envVars, String image, Pod pod) { BrokerConfig data = new BrokerConfig(); <START> data.configMapName = generateUniqueName(CONFIG_MAP_NAME_SUFFIX); <END> data.configMapVolume = generateUniqueName(BROKER_VOLUME); data.configMap = newConfigMap(data.configMapName, pluginsMeta); data.container = newContainer(runtimeId, envVars, image, data.configMapVolume); data.machineName = Names.machineName(pod, data.container); data.machineConfig = new InternalMachineConfig(); data.machineConfig.getVolumes().put(PLUGINS_VOLUME_NAME, new VolumeImpl().withPath("/plugins")); return data; }</code><technical_language>for me, brokerConfig variable name simpler</technical_language>

Target:
private BrokerConfig createBrokerConfig( RuntimeIdentity runtimeId, Collection<PluginMeta> pluginsMeta, List<EnvVar> envVars, String image, Pod pod) { BrokerConfig brokerConfig = new BrokerConfig(); brokerConfig.configMapName = generateUniqueName(CONFIG_MAP_NAME_SUFFIX); brokerConfig.configMapVolume = generateUniqueName(BROKER_VOLUME); brokerConfig.configMap = newConfigMap(brokerConfig.configMapName, pluginsMeta); brokerConfig.container = newContainer(runtimeId, envVars, image, brokerConfig.configMapVolume); brokerConfig.machineName = Names.machineName(pod, brokerConfig.container); brokerConfig.machineConfig = new InternalMachineConfig(); brokerConfig .machineConfig .getVolumes() .put(PLUGINS_VOLUME_NAME, new VolumeImpl().withPath("/plugins")); return brokerConfig; }
Source:
<code>public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (signature == null) { return null ; } if(signature.contains(this.ownerClass())) { <START> this.setIsClassSelfReferenced(true); <END> return super.visitField(access, name, desc, signature, value); } typeSignatureByFieldName.put(name, signature); GenericFieldVisitor visitor = new GenericFieldVisitor(); new SignatureReader(signature).acceptType(visitor); Optional<String> declaredType = visitor.declaredType(); if (declaredType.isPresent() && genericTypesOfClass.contains(declaredType.get())) { genericFields.put(name, declaredType.get()); } return super.visitField(access, name, desc, signature, value); }</code><technical_language>need for this. here. - knowing code: .contains check is robust for kind of combination class method signature? (Taking account pathological cases a FQCNs is a suffix of other.)</technical_language>

Target:
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (signature == null) { return null ; } typeSignatureByFieldName.put(name, signature); GenericFieldVisitor visitor = new GenericFieldVisitor(); new SignatureReader(signature).acceptType(visitor); Optional<String> declaredType = visitor.declaredType(); if (declaredType.isPresent() && genericTypesOfClass.contains(declaredType.get())) { genericFields.put(name, declaredType.get()); } return super.visitField(access, name, desc, signature, value); }
Source:
<code>public void executeCommand() { Guid jobId = Guid.newGuid(); persistBlockJobPlaceholder(jobId); persistCommand(getParameters().getParentCommand(), true); try { VDSReturnValue vdsReturnValue = runVdsCommand(VDSCommandType.Merge, createVDSParameters(jobId)); if (vdsReturnValue.getSucceeded()) { setSucceeded(true); log.debug("Merge started successfully, job Id is: {}", (Guid)vdsReturnValue.getReturnValue()); } else { log.error("Failed to start Merge on VDS"); <START> setCommandStatus(CommandStatus.FAILED); <END> } } catch (EngineException e) { log.error("Exception caught while sending Merge command", e); setSucceeded(true); } }</code><technical_language>want remove place holder in case of failure</technical_language>

Target:
public void executeCommand() { Guid jobId = Guid.newGuid(); persistBlockJobPlaceholder(jobId); persistCommand(getParameters().getParentCommand(), true); try { VDSReturnValue vdsReturnValue = runVdsCommand(VDSCommandType.Merge, createVDSParameters(jobId)); if (vdsReturnValue.getSucceeded()) { setSucceeded(true); log.debug("Merge started successfully, job Id is: {}", (Guid)vdsReturnValue.getReturnValue()); } else { log.error("Failed to start Merge on VDS"); DbFacade.getInstance().getVmJobDao().remove(jobId); setCommandStatus(CommandStatus.FAILED); } } catch (EngineException e) { log.error("Exception caught while sending Merge command", e); setSucceeded(true); } }
Source:
<code>private String discoverNodeName() { if (DiscoveryMode.KUBERNETES_API.equals(config.getMode())) { try { <START> String podName = System.getenv("POD_NAME"); <END> if (podName == null) { podName = System.getenv("HOSTNAME"); } if (podName == null) { podName = InetAddress.getLocalHost().getHostName(); } String nodeName = client.nodeName(podName); if (nodeName != null) { getLogger().info(String.format("Kubernetes plugin extracted node name: %s", nodeName)); return nodeName; } } catch (Exception e) { getLogger().finest(e); } getLogger().warning("Cannot fetch name of the node, NODE_AWARE feature is disabled"); } return "unknown"; }</code><technical_language>lines in discoverZone(). extract a method String podName()</technical_language>

Target:
private String discoverNodeName() { if (DiscoveryMode.KUBERNETES_API.equals(config.getMode())) { try { String nodeName = client.nodeName(podName()); if (nodeName != null) { getLogger().info(String.format("Kubernetes plugin discovered node name: %s", nodeName)); return nodeName; } } catch (Exception e) { getLogger().finest(e); } getLogger().warning("Cannot fetch name of the node, NODE_AWARE feature is disabled"); } return "unknown"; }
Source:
<code>private static String findNewQualityGateName(Context context) throws SQLException { if (isQualityGateNameAvailable(context, SONARQUBE_WAY_QUALITY_GATE_OUTDATED)) { return SONARQUBE_WAY_QUALITY_GATE_OUTDATED; } <START> for (int i = 0; i < 10; i++) { <END> String newName = SONARQUBE_WAY_QUALITY_GATE_OUTDATED + " " + RANDOM.nextInt(1000); if (isQualityGateNameAvailable(context, newName)) { return newName; } } throw new IllegalStateException(format("There are too many quality profiles starting with [%s]", SONARQUBE_WAY_QUALITY_GATE_OUTDATED)); }</code><technical_language>Instead of testing 10 times a random name, I recommend "only" append a timestamp (system2.now()) in name of quality gate</technical_language>

Target:
private String findNewQualityGateName(Context context) throws SQLException { if (isQualityGateNameAvailable(context, SONARQUBE_WAY_QUALITY_GATE_OUTDATED)) { return SONARQUBE_WAY_QUALITY_GATE_OUTDATED; } String newName = SONARQUBE_WAY_QUALITY_GATE_OUTDATED + " " + system2.now(); if (isQualityGateNameAvailable(context, newName)) { return newName; } throw new IllegalStateException(format("There are already two quality profiles with name [%s,%s]", SONARQUBE_WAY_QUALITY_GATE_OUTDATED, newName)); }
Source:
<code>public synchronized void await(final Lambda pred) { if ((Boolean)TransactionManager.apply(new Lambda() { public Object apply(final Object unit) { TransactionManager.own(box); if (!(Boolean)pred.apply(box.getValue())) { updates = new LinkedList<Object>(); box.addReactor(Waiter.this); return true; } return false; } })) { Object val; do { <START> if (updates.isEmpty()) <END> { try { wait(); } catch (InterruptedException e) { Logging.warning("interrupted during wait()"); } } val = updates.remove(); } while (!(Boolean)pred.apply(val)); TransactionManager.apply(new Lambda() { public Object apply(final Object unit) { TransactionManager.own(box); box.removeReactor(Waiter.this); return null; } }); } }</code><technical_language>too, a 'while' is required</technical_language>

Target:
public synchronized void await(final Lambda pred) { if ((Boolean)TransactionManager.apply(new Lambda() { public Object apply(final Object unit) { TransactionManager.own(box); if (!(Boolean)pred.apply(box.getValue())) { updates = new LinkedList<Object>(); box.addReactor(Waiter.this); return true; } return false; } })) { Object val; do { while (updates.isEmpty()) { try { wait(); } catch (InterruptedException e) { Logging.warning("interrupted during wait()"); } } val = updates.remove(); } while (!(Boolean)pred.apply(val)); TransactionManager.apply(new Lambda() { public Object apply(final Object unit) { TransactionManager.own(box); box.removeReactor(Waiter.this); return null; } }); } }
Source:
<code>public String getItemString(ITmfEvent event) { <START> final String EMPTY_STRING = ""; END> for (ITmfEventAspect<?> aspect : fAspects) { String eventString = NonNullUtils.nullToEmptyString(aspect.resolve(event)); if(eventString != EMPTY_STRING) { return eventString; } } return EMPTY_STRING; }</code><technical_language>This a private static final String field of class. Please put top of class, fAspect field declaration</technical_language>

Target:
public String getItemString(ITmfEvent event) { for (ITmfEventAspect<?> aspect : fAspects) { String eventString = NonNullUtils.nullToEmptyString(aspect.resolve(event)); if (eventString != EMPTY_STRING) { return eventString; } } return EMPTY_STRING; }
Source:
<code>private void confirmProjectProperties() { new DefaultShell(PROJECT_PROPERTIES); Button applyAndCloseButton = getApplyAndCloseButton(); assertTrue("Apply and Close Button should be enabled.", applyAndCloseButton.isEnabled()); applyAndCloseButton.click(); new WaitWhile(new JobIsRunning(), TimePeriod.getCustom(20), false); <START> new WaitWhile(new ShellIsActive(PROJECT_PROPERTIES)); <END> }</code><technical_language>ShellIsAvailable</technical_language>

Target:
private void confirmProjectProperties() { new DefaultShell(PROJECT_PROPERTIES); Button applyAndCloseButton = getApplyAndCloseButton(); assertTrue("Apply and Close Button should be enabled.", applyAndCloseButton.isEnabled()); applyAndCloseButton.click(); new WaitWhile(new JobIsRunning(), TimePeriod.getCustom(20), false); new WaitWhile(new ShellIsAvailable(PROJECT_PROPERTIES)); }
Source:
<code>protected void addListItem(ListItemBlock item) { <START> if (item != null) { <END> count++; } }</code><technical_language>is this null check necessary? checkNotNull(item) this</technical_language>

Target:
protected void addListItem(ListItemBlock item) { checkNotNull(item); count++; }
Source:
<code>public void testStringToByteArray() { deployStream( "stringToBytes", "source --outputType=application/octet-stream | sink"); MessageTest test = new MessageTest() { @Override public void test(Message<?> message) throws MessagingException { assertTrue(byte[].class.isAssignableFrom(message.getPayload().getClass())); assertEquals(MimeType.valueOf("text/plain;charset=UTF-8"), contentTypeResolver.resolve(message.getHeaders())); try { assertEquals("hello", new String((byte[]) message.getPayload(), "UTF-8")); } catch (UnsupportedEncodingException e) { } } }; <START> Message<String> msg = MessageBuilder.withPayload("hello"). <END> copyHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "text/plain;charset=UTF-8")).build(); sendMessageAndVerifyOutput("stringToBytes", msg, test); }</code><technical_language>I a payload byte[] transformation is trivial, if charset is properly care of, this unnoticed</technical_language>

Target:
public void testStringToByteArray() { deployStream( "stringToBytes", "source --outputType=application/octet-stream | sink"); MessageTest test = new MessageTest() { @Override public void test(Message<?> message) throws MessagingException { assertTrue(byte[].class.isAssignableFrom(message.getPayload().getClass())); assertEquals(MimeType.valueOf("text/plain;charset=UTF-8"), contentTypeResolver.resolve(message.getHeaders())); try { assertEquals("hello\u00F6\u00FF", new String((byte[]) message.getPayload(), "UTF-8")); } catch (UnsupportedEncodingException e) { } } }; Message<String> msg = MessageBuilder.withPayload("hello\u00F6\u00FF"). copyHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "text/plain;charset=UTF-8")).build(); sendMessageAndVerifyOutput("stringToBytes", msg, test); }
Source:
<code>@Override public void createNewItem(final String userId, final String authId, final String itemId, final School.ItemType itemType, final String parentId, final Authenticator authChecker) throws AuthenticationException { if (identityService == null) { identityService = Identity.IdentityService.newBlockingStub(getRpcChannel()); } final Identity.IdentityRequest request = Identity.IdentityRequest.newBuilder() .setAuthId(authId) .setUserId(userId) .setItemId(itemId) .setItemType(itemType) .build(); final Identity.IdentityCreationRequest.Builder creationRequestBuilder = Identity.IdentityCreationRequest.newBuilder() .setItemRequest(request); if (parentId == null && School.ItemType.COURSE != itemType && School.ItemType.BANK_PROBLEM != itemType) { throw new AuthenticationException("Parent Id can only be null when inserting a course", AuthenticationException.NO_AUTH_SENT); } if (parentId != null) { creationRequestBuilder.setParentItemId(parentId); } Message.DefaultResponse response = null; try { final Identity.IdentityCreationRequest creationRequest = creationRequestBuilder.build(); response = identityService.createNewItem(getNewRpcController(), creationRequest); if (response.hasException()) { final AuthenticationException authExcep = new AuthenticationException("Exception with authentication server", AuthenticationException.OTHER); authExcep.setProtoException(response.getException()); throw authExcep; } } catch (ServiceException e) { <START> throw new AuthenticationException(e); <END> } }</code><technical_language>print stack trace here</technical_language>

Target:
@Override public void createNewItem(final String userId, final String authId, final String itemId, final School.ItemType itemType, final String parentId, final Authenticator authChecker) throws AuthenticationException { if (identityService == null) { identityService = Identity.IdentityService.newBlockingStub(getRpcChannel()); } final Identity.IdentityRequest request = Identity.IdentityRequest.newBuilder() .setAuthId(authId) .setUserId(userId) .setItemId(itemId) .setItemType(itemType) .build(); final Identity.IdentityCreationRequest.Builder creationRequestBuilder = Identity.IdentityCreationRequest.newBuilder() .setItemRequest(request); if (parentId == null && School.ItemType.COURSE != itemType && School.ItemType.BANK_PROBLEM != itemType) { throw new AuthenticationException("Parent Id can only be null when inserting a course", AuthenticationException.NO_AUTH_SENT); } if (parentId != null) { creationRequestBuilder.setParentItemId(parentId); } Message.DefaultResponse response = null; try { final Identity.IdentityCreationRequest creationRequest = creationRequestBuilder.build(); response = identityService.createNewItem(getNewRpcController(), creationRequest); if (response.hasException()) { final AuthenticationException authExcep = new AuthenticationException("Exception with authentication server", AuthenticationException.OTHER); authExcep.setProtoException(response.getException()); throw authExcep; } } catch (ServiceException e) { throw new AuthenticationException("Service exception occurred when talking to the identity database.", e); } }
Source:
<code>public ThriftClient(ThriftClientManager clientManager, Class<T> clientType, ThriftClientConfig clientConfig, String clientName) { <START> this(clientManager, clientType, defaultChannelFactory, clientConfig, clientName); <END> }</code><technical_language>a default in middle of arguments (one c'tor A, B, C, D, E, other A, B, D, E) strange</technical_language>

Target:
public ThriftClient( ThriftClientManager clientManager, Class<T> clientType, ThriftClientConfig clientConfig, String clientName) { this(clientManager, clientType, clientConfig, clientName, defaultChannelFactory); }
Source:
<code>public BlockUseHandler getItemHandler() { return e -> { e.cancel(); Block b = e.getClickedBlock().get(); Player p = e.getPlayer(); if (p.hasPermission("slimefun.inventory.bypass") || (SlimefunPlugin.getProtectionManager().hasPermission( p, b.getLocation(), ProtectableAction.ACCESS_INVENTORIES)) && Slimefun.hasUnlocked(e.getPlayer(), item, false) ) { SlimefunPlugin.getGPSNetwork().getResourceManager().scan(p, b, 0); <START> } else { <END> SlimefunPlugin.getLocalization().sendMessage(p, "inventory.no-access", true); } }; }</code><technical_language>else next line bracket</technical_language>

Target:
public BlockUseHandler getItemHandler() { return e -> { e.cancel(); Block b = e.getClickedBlock().get(); Player p = e.getPlayer(); if (p.hasPermission("slimefun.gps.bypass") || (SlimefunPlugin.getProtectionManager().hasPermission( p, b.getLocation(), ProtectableAction.ACCESS_INVENTORIES)) ) { SlimefunPlugin.getGPSNetwork().getResourceManager().scan(p, b, 0); } else { SlimefunPlugin.getLocalization().sendMessage(p, "inventory.no-access", true); } }; }
Source:
<code>public void checkWorkspaceActions() { workspaces.clickOnWorkspaceConfigureButton(workspaceName1); workspaceDetails.waitToolbarTitleName(workspaceName1); workspaceConfig.waitConfigForm(); <START> seleniumWebDriver.navigate().back(); <END> workspaces.waitWorkspaceIsPresent(workspaceName1); dashboard.selectWorkspacesItemOnDashboard(); workspaces.clickOnWorkspaceAddProjectButton(workspaceName2); workspaceDetails.waitToolbarTitleName(workspaceName2); workspaceProjects.waitProjectIsPresent(WEB_JAVA_SPRING); seleniumWebDriver.navigate().back(); workspaces.waitWorkspaceIsPresent(workspaceName1); workspaces.waitWorkspaceStatusIs(workspaceName1, Statuses.STOPPED); workspaces.waitWorkspaceStatusIs(workspaceName2, Statuses.STOPPED); workspaces.waitWorkspaceStatusIs(workspaceName3, Statuses.STOPPED); dashboard.selectWorkspacesItemOnDashboard(); Assert.assertEquals(workspaces.getWorkspaceStatus(workspaceName3), Statuses.STOPPED); workspaces.clickOnWorkspaceActionsButton(workspaceName3); workspaces.waitWorkspaceStatusIs(workspaceName3, Statuses.RUNNING); }</code><technical_language>strange here. this step test? If helps check workspace name appearance, workspace list direct link in Dashboard</technical_language>

Target:
public void checkWorkspaceActions() { workspaces.clickOnWorkspaceConfigureButton(workspaceName1); workspaceDetails.waitToolbarTitleName(workspaceName1); workspaceConfig.waitConfigForm(); dashboard.selectWorkspacesItemOnDashboard(); workspaces.waitWorkspaceIsPresent(workspaceName1); workspaces.clickOnWorkspaceAddProjectButton(workspaceName2); workspaceDetails.waitToolbarTitleName(workspaceName2); workspaceProjects.waitProjectIsPresent(WEB_JAVA_SPRING); dashboard.selectWorkspacesItemOnDashboard(); workspaces.waitWorkspaceIsPresent(workspaceName1); workspaces.waitWorkspaceStatusIs(workspaceName1, Statuses.STOPPED); workspaces.waitWorkspaceStatusIs(workspaceName2, Statuses.STOPPED); workspaces.waitWorkspaceStatusIs(workspaceName3, Statuses.STOPPED); Assert.assertEquals(workspaces.getWorkspaceStatus(workspaceName3), Statuses.STOPPED); workspaces.clickOnWorkspaceActionsButton(workspaceName3); workspaces.waitWorkspaceStatusIs(workspaceName3, Statuses.RUNNING); }
Source:
<code>public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); context.addRoutes(new RouteBuilder() { @Override <START> public void configure() throws Exception { <END> from("direct:greetings").to("stream:out"); } }); context.start(); context.getRoutes().stream().forEach((r) -> System.out.println(r)); context.stop(); }</code><technical_language>more route, stream:in direct:greetings? This places emphasis point endpoints need other</technical_language>

Target:
public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("stream:in").to("direct:greetings"); from("direct:greetings").to("stream:out"); } }); context.start(); context.getRoutes().stream().forEach((r) -> System.out.println(r)); context.stop(); }
Source:
<code>public void url_validURIs() { <START> String[] validUrls = { "*", "http://foo/bar/baz", "realm://foo.bar/~/default" }; <END> for (String url : validUrls) { PermissionRequest request = new PermissionRequest(UserCondition.userId("id"), url, AccessLevel.ADMIN); assertEquals(url, request.getUrl()); } }</code><technical_language>https:// realms://</technical_language>

Target:
public void url_validURIs() { String[] validUrls = { "*", "http://foo/bar/baz", "https://foo/bar/baz", "realm://foo.bar/~/default", "realms://foo.bar/~/default" }; for (String url : validUrls) { PermissionRequest request = new PermissionRequest(UserCondition.userId("id"), url, AccessLevel.ADMIN); assertEquals(url, request.getUrl()); } }
Source:
<code>public static void detectLogo() throws Exception { <START> String localFilePath = "resources/googlework_short.mp4"; <END> detectLogo(localFilePath); }</code><technical_language>suggestion String localFilePath = "path/to/your/video.mp4";</technical_language>

Target:
public static void detectLogo() throws Exception { String localFilePath = "path/to/your/video.mp4"; detectLogo(localFilePath); }
Source:
<code>public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap map = context.getMergedJobDataMap(); Server server = (Server) map.get(Server.class.getName()); log.debug("+++++ Started server job: {}", server); JMXConnector conn = null; JMXConnectionParams connectionParams = null; try { <START> JMXServiceURL jmxUrl; <END> if(server.getPid() != null) { jmxUrl = extractJMXServiceURLFromPid(server.getPid()); } else { jmxUrl = new JMXServiceURL(server.getUrl()); } connectionParams = new JMXConnectionParams(jmxUrl, server.getEnvironment()); if (!server.isLocal()) { conn = jmxPool.borrowObject(connectionParams); } jmxUtils.processServer(server, conn); } catch (Exception e) { log.error("Error in job for server: " + server, e); throw new JobExecutionException(e); } finally { try { jmxPool.returnObject(connectionParams, conn); } catch (Exception ex) { log.error("Error returning object to pool for server: " + server); } } log.debug("+++++ Finished server job: {}", server); }</code><technical_language>concept of a ServerJob a LocalJob. reflect this in class hierarchy instead of increasing cyclomatic complexity of ServerJob ? encapsulate construction of jmxUrl a bit</technical_language>

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap map = context.getMergedJobDataMap(); Server server = (Server) map.get(Server.class.getName()); log.debug("+++++ Started server job: {}", server); JMXConnector conn = null; JMXConnectionParams connectionParams = null; try { JMXServiceURL jmxUrl = server.getJmxServiceURL(); connectionParams = new JMXConnectionParams(jmxUrl, server.getEnvironment()); if (!server.isLocal()) { conn = jmxPool.borrowObject(connectionParams); } jmxUtils.processServer(server, conn); } catch (Exception e) { log.error("Error in job for server: " + server, e); throw new JobExecutionException(e); } finally { try { jmxPool.returnObject(connectionParams, conn); } catch (Exception ex) { log.error("Error returning object to pool for server: " + server); } } log.debug("+++++ Finished server job: {}", server); }
Source:
<code><START> public void setDefaultValues() <END> { super.setDefaultValues(); setType(SORTA_MATCH_JOB_TYPE); }</code><technical_language>get rid of setDefaultValues? move setType factory class</technical_language>

Target:
private void setDefaultValues() { setType(SORTA_MATCH_JOB_TYPE); }
Source:
<code>public boolean equals(Object o) { if (o instanceof MultipleInstanceCollectionOutput) { MultipleInstanceCollectionOutput other = (MultipleInstanceCollectionOutput) o; <START> return (null != value) ? value.equals(other.value) : null == other.value; <END> } return false; }</code><technical_language>Objects.equals</technical_language>

Target:
public boolean equals(Object o) { if (o instanceof MultipleInstanceCollectionOutput) { MultipleInstanceCollectionOutput other = (MultipleInstanceCollectionOutput) o; return Objects.equals(value, other.value); } return false; }
Source:
<code>public static void notifyCurrentUser(String instructorName, String instructorEmail, String inviteEmail){ String to = instructorEmail; String from = contactEmail; String subjectLine = "Friend Accounts Integration Email"; String host = "deluxe.dsc.umich.edu"; System.out.println("Setting up props"); Properties properties = System.getProperties(); properties.put("mail.smtp.auth", "false"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", host); properties.put("mail.debug", "true"); System.out.println("Initiating Session"); Session session = Session.getInstance(properties); try{ <START> emailMessage = Friend.readFile(requesterEmailFile, StandardCharsets.UTF_8); <END> emailMessage = emailMessage.replace("<instructor>", instructorName); emailMessage = emailMessage.replace("<friend>", inviteEmail); System.out.println("Setting up message"); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subjectLine); message.setText(emailMessage); System.out.println("Sending message"); Transport.send(message); System.out.println("Message sent to " + instructorName); }catch (Exception e){ System.out.println("quasiNotifyCurrentUser exception:"); e.printStackTrace(); } }</code><technical_language>a single method read a file replace macros finds</technical_language>

Target:
public static void notifyCurrentUser(String instructorName, String instructorEmail, String inviteEmail){ M_log.debug("Friend notifyCurrentUser() called"); String to = instructorEmail; String from = contactEmail; String host = mailHost; M_log.info("Setting up mailProps"); Properties properties = System.getProperties(); properties.put(MAIL_SMTP_AUTH, "false"); properties.put(MAIL_SMTP_STARTTLS, "true"); properties.put(MAIL_SMTP_HOST, host); properties.put(MAIL_DEBUG, "true"); M_log.debug("Initiating Session for sendMail"); Session session = Session.getInstance(properties); try{ HashMap<String, String> map = new HashMap<String,String>(); map.put("<instructor>", instructorName); map.put("<friend>", inviteEmail); emailMessage = Friend.readFile(requesterEmailFile, StandardCharsets.UTF_8); emailMessage = replacePlaceHolders(emailMessage, map); M_log.debug("Setting up message for sendMail"); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subjectLine); message.setText(emailMessage); M_log.info("Sending message"); Transport.send(message); M_log.info("Message sent to " + instructorName); }catch (Exception e){ M_log.error("notifyCurrentUser exception: " + e.getMessage()); } }
Source:
<code>private void loadBatch(Long[] ids) { Twitter client = getTwitterClient(); int keepTrying = 0; while (keepTrying < 1) { try { long[] toQuery = new long[ids.length]; for(int i = 0; i < ids.length; i++) toQuery[i] = ids[i]; for (User tStat : client.lookupUsers(toQuery)) { String json = DataObjectFactory.getRawJSON(tStat); <START> providerQueue.offer(new StreamsDatum(json)); <END> } keepTrying = 10; } catch(TwitterException twitterException) { keepTrying += TwitterErrorHandler.handleTwitterError(client, twitterException); } catch(Exception e) { keepTrying += TwitterErrorHandler.handleTwitterError(client, e); } } }</code><technical_language>succeed. Try utility method noted</technical_language>

Target:
private void loadBatch(Long[] ids) { Twitter client = getTwitterClient(); int keepTrying = 0; while (keepTrying < 1) { try { long[] toQuery = new long[ids.length]; for(int i = 0; i < ids.length; i++) toQuery[i] = ids[i]; for (User tStat : client.lookupUsers(toQuery)) { String json = DataObjectFactory.getRawJSON(tStat); ComponentUtils.offerUntilSuccess(new StreamsDatum(json), providerQueue); } keepTrying = 10; } catch(TwitterException twitterException) { keepTrying += TwitterErrorHandler.handleTwitterError(client, twitterException); } catch(Exception e) { keepTrying += TwitterErrorHandler.handleTwitterError(client, e); } } }
Source:
<code>public void unselectsSelection() throws Exception { bot.radio("SWT.MULTI").click(); bot.checkBox("Listen").select(); bot.button("Clear").click(); table = bot.tableInGroup("Table"); table.select(new int[] { 1, 2, 3 }); SWTBotText text = bot.textInGroup("Listeners"); bot.button("Clear").click(); table.unselect(); assertEquals(0, table.selectionCount()); assertEventMatches(text, "MouseDown [3]: MouseEvent{Table <START> time=-550222259 data=null <END> button=1 stateMask=0x40000 x=0 y=0 count=1}"); assertEventMatches(text, "Selection [13]: SelectionEvent{Table time=-550222256 data=null item=TableItem {Index:1} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); assertEventMatches(text, "MouseUp [4]: MouseEvent{Table time=-550222255 data=null button=1 stateMask=0xc0000 x=0 y=0 count=1}"); assertEventMatches(text, "Selection [13]: SelectionEvent{Table time=-550222256 data=null item=TableItem {Index:2} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); assertEventMatches(text, "Selection [13]: SelectionEvent{Table time=-550222256 data=null item=TableItem {Index:3} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); table.select(new int[] { 1, 2, 3 }); assertEquals(3, table.selectionCount()); table.select(new int[] {}); assertEquals(0, table.selectionCount()); }</code><technical_language>For assertions, I find strange a random time in expected string... matter for test success. I change time=0</technical_language>

Target:
public void unselectsSelection() throws Exception { bot.radio("SWT.MULTI").click(); bot.checkBox("Listen").select(); bot.button("Clear").click(); table = bot.tableInGroup("Table"); table.select(new int[] { 1, 2, 3 }); SWTBotText text = bot.textInGroup("Listeners"); bot.button("Clear").click(); table.unselect(); assertEquals(0, table.selectionCount()); assertEventMatches(text, "MouseDown [3]: MouseEvent{Table time=0 data=null button=1 stateMask=0x40000 x=0 y=0 count=1}"); assertEventMatches(text, "Selection [13]: SelectionEvent{Table time=0 data=null item=TableItem {Index:1} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); assertEventMatches(text, "MouseUp [4]: MouseEvent{Table time=0 data=null button=1 stateMask=0xc0000 x=0 y=0 count=1}"); assertEventMatches(text, "Selection [13]: SelectionEvent{Table time=0 data=null item=TableItem {Index:2} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); assertEventMatches(text, "Selection [13]: SelectionEvent{Table time=0 data=null item=TableItem {Index:3} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); }
Source:
<code>public void testBug331795_1() { MApplication application = ems.createModelElement(MApplication.class); MWindow window = ems.createModelElement(MWindow.class); application.getChildren().add(window); application.setSelectedElement(window); MPart part = ems.createModelElement(MPart.class); part.setContributionURI("bundleclass://org.eclipse.e4.ui.tests/org.eclipse.e4.ui.tests.workbench.SampleView"); window.getChildren().add(part); window.setSelectedElement(part); application.setContext(appContext); appContext.set(MApplication.class, application); wb = new E4Workbench(application, appContext); wb.createAndRunUI(window); assertNotNull(part.getObject()); assertNotNull(part.getContext()); addRuntimeExceptionHandler(); SampleView view = (SampleView) part.getObject(); view.errorOnWidgetDisposal = true; part.setToBeRendered(false); assertTrue("The view should have been destroyed", view.isDestroyed()); assertNull(part.getObject()); assertNull(part.getContext()); <START> resetRuntimeExceptionHandler(); <END> }</code><technical_language>this finally block tearDown, for cases below</technical_language>

Target:
public void testBug331795_1() { MApplication application = ems.createModelElement(MApplication.class); MWindow window = ems.createModelElement(MWindow.class); application.getChildren().add(window); application.setSelectedElement(window); MPart part = ems.createModelElement(MPart.class); part.setContributionURI("bundleclass://org.eclipse.e4.ui.tests/org.eclipse.e4.ui.tests.workbench.SampleView"); window.getChildren().add(part); window.setSelectedElement(part); application.setContext(appContext); appContext.set(MApplication.class, application); wb = new E4Workbench(application, appContext); wb.createAndRunUI(window); assertNotNull(part.getObject()); assertNotNull(part.getContext()); addRuntimeExceptionHandler(); SampleView view = (SampleView) part.getObject(); view.errorOnWidgetDisposal = true; part.setToBeRendered(false); assertTrue("The view should have been destroyed", view.isDestroyed()); assertNull(part.getObject()); assertNull(part.getContext()); }
Source:
<code>public List<EmailWrapper> generateFeedbackSessionOpeningEmails(FeedbackSessionAttributes session) { String template = EmailTemplates.USER_FEEDBACK_SESSION; CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); boolean isEmailNeeded = fsLogic.isFeedbackSessionForStudentsToAnswer(session); List<InstructorAttributes> instructors = isEmailNeeded ? instructorsLogic.getInstructorsForCourse(session.getCourseId()) <START> : new ArrayList<InstructorAttributes>(); <END> List<StudentAttributes> students = isEmailNeeded ? studentsLogic.getStudentsForCourse(session.getCourseId()) : new ArrayList<StudentAttributes>(); String templateWithSupportFragment = template.replace("${supportFragment}", EmailTemplates.DEFAULT_FRAGMENT_FEEDBACK_SESSION_SUPPORT); List<EmailWrapper> emails = generateFeedbackSessionEmailBases(course, session, students, instructors, templateWithSupportFragment, EmailType.FEEDBACK_OPENING.getSubject()); for (EmailWrapper email : emails) { email.setContent(email.getContent().replace("${status}", "is now open")); } return emails; }</code><technical_language>Revert changes</technical_language>

Target:
public List<EmailWrapper> generateFeedbackSessionOpeningEmails(FeedbackSessionAttributes session) { String template = EmailTemplates.USER_FEEDBACK_SESSION; CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); boolean isEmailNeeded = fsLogic.isFeedbackSessionForStudentsToAnswer(session); List<InstructorAttributes> instructors = isEmailNeeded ? instructorsLogic.getInstructorsForCourse(session.getCourseId()) : new ArrayList<InstructorAttributes>(); List<StudentAttributes> students = isEmailNeeded ? studentsLogic.getStudentsForCourse(session.getCourseId()) : new ArrayList<StudentAttributes>(); List<EmailWrapper> emails = generateFeedbackSessionEmailBases(course, session, students, instructors, template, EmailType.FEEDBACK_OPENING.getSubject()); for (EmailWrapper email : emails) { email.setContent(email.getContent().replace("${status}", FEEDBACK_STATUS_SESSION_OPENING)); } return emails; }
Source:
<code>private int findInsertPosition(KeyValuePairModell keyValuePair) { ArrayList<String> keys= new ArrayList<>(); for (KeyValuePairModell <START> fKeyValuePair : <END> fKeyValuePairs) { KeyValuePairModell element = fKeyValuePair; if (! (element instanceof LastKeyValuePair)) keys.add(element.getKey()); } int insertIndex= NLSUtil.getInsertionPosition(keyValuePair.getKey(), keys); if (insertIndex < fKeyValuePairs.size() - 1) { insertIndex++; } return insertIndex; }</code><technical_language>rename keyValuePair</technical_language>

Target:
private int findInsertPosition(KeyValuePairModell keyValuePair) { ArrayList<String> keys= new ArrayList<>(); for (KeyValuePairModell keyValuePairmodel : fKeyValuePairs) { KeyValuePairModell element = keyValuePairmodel; if (! (element instanceof LastKeyValuePair)) keys.add(element.getKey()); } int insertIndex= NLSUtil.getInsertionPosition(keyValuePair.getKey(), keys); if (insertIndex < fKeyValuePairs.size() - 1) { insertIndex++; } return insertIndex; }
Source:
<code>public boolean isValid (ZestResponse response) { <START> if(rootExpression==null) <END> return true; return rootExpression.evaluate(response); }</code><technical_language>This one? ;)</technical_language>

Target:
public boolean isValid (ZestResponse response) { if(rootExpression==null){ return false; } return rootExpression.evaluate(response); }
Source:
<code>protected void onInit() throws Exception { super.onInit(); BeanFactory beanFactory = this.getBeanFactory(); if (beanFactory != null) { <START> getMessagingTemplate().setBeanFactory(beanFactory); <END> Assert.state(!(this.discardChannelName != null && this.discardChannel != null), "'discardChannelName' and 'discardChannel' are mutually exclusive."); Assert.state(!(getOutputChannelName() != null && getOutputChannel() != null), "'outputChannelName' and 'outputChannel' are mutually exclusive."); if (this.outputProcessor instanceof BeanFactoryAware) { ((BeanFactoryAware) this.outputProcessor).setBeanFactory(beanFactory); } if (this.correlationStrategy instanceof BeanFactoryAware) { ((BeanFactoryAware) this.correlationStrategy).setBeanFactory(beanFactory); } if (this.releaseStrategy instanceof BeanFactoryAware) { ((BeanFactoryAware) this.releaseStrategy).setBeanFactory(beanFactory); } } if (this.discardChannel == null) { this.discardChannel = new NullChannel(); } if (this.releasePartialSequences) { Assert.isInstanceOf(SequenceSizeReleaseStrategy.class, this.releaseStrategy, "Release strategy of type [" + this.releaseStrategy.getClass().getSimpleName() + "] cannot release partial sequences. Use the default SequenceSizeReleaseStrategy instead."); ((SequenceSizeReleaseStrategy)this.releaseStrategy).setReleasePartialSequences(releasePartialSequences); } this.lockRegistrySet = true; }</code><technical_language>I remove this getter..</technical_language>

Target:
protected void onInit() throws Exception { super.onInit(); BeanFactory beanFactory = this.getBeanFactory(); if (beanFactory != null) { this.messagingTemplate.setBeanFactory(beanFactory); Assert.state(!(this.discardChannelName != null && this.discardChannel != null), "'discardChannelName' and 'discardChannel' are mutually exclusive."); Assert.state(!(getOutputChannelName() != null && getOutputChannel() != null), "'outputChannelName' and 'outputChannel' are mutually exclusive."); if (this.outputProcessor instanceof BeanFactoryAware) { ((BeanFactoryAware) this.outputProcessor).setBeanFactory(beanFactory); } if (this.correlationStrategy instanceof BeanFactoryAware) { ((BeanFactoryAware) this.correlationStrategy).setBeanFactory(beanFactory); } if (this.releaseStrategy instanceof BeanFactoryAware) { ((BeanFactoryAware) this.releaseStrategy).setBeanFactory(beanFactory); } } if (this.discardChannel == null) { this.discardChannel = new NullChannel(); } if (this.releasePartialSequences) { Assert.isInstanceOf(SequenceSizeReleaseStrategy.class, this.releaseStrategy, "Release strategy of type [" + this.releaseStrategy.getClass().getSimpleName() + "] cannot release partial sequences. Use the default SequenceSizeReleaseStrategy instead."); ((SequenceSizeReleaseStrategy)this.releaseStrategy).setReleasePartialSequences(releasePartialSequences); } this.lockRegistrySet = true; }
Source:
<code>private void initOptionsList(FileReportSettings settings) { if (settings != null && settings.getFileProperties() != null && !settings.getFileProperties().isEmpty()) { for (Entry<FileReportDataTypes, Boolean> entry : settings.getFileProperties().entrySet()) { optionStates.put(entry.getKey(), entry.getValue()); options.add(entry.getKey()); } } else { options = Arrays.asList(FileReportDataTypes.values()); for (FileReportDataTypes entry : options) { optionStates.put(entry, Boolean.TRUE); } } model = new OptionsListModel(); optionsList.setModel(model); optionsList.setCellRenderer(new OptionsListRenderer()); optionsList.setVisibleRowCount(-1); selectAllButton.setEnabled(false); deselectAllButton.setEnabled(true); <START> wizPanel.setFinish(true); <END> optionsList.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent evt) { int index = optionsList.locationToIndex(evt.getPoint()); FileReportDataTypes value = model.getElementAt(index); optionStates.put(value, !optionStates.get(value)); optionsList.repaint(); boolean anySelected = anySelected(); deselectAllButton.setEnabled(anySelected); wizPanel.setFinish(anySelected); selectAllButton.setEnabled(notAllSelected()); } }); }</code><technical_language>works in cases get edge case click finish items selected, Jira for steps create edge case</technical_language>

Target:
private void initOptionsList(FileReportSettings settings) { if (settings != null && settings.getFileProperties() != null && !settings.getFileProperties().isEmpty()) { for (Entry<FileReportDataTypes, Boolean> entry : settings.getFileProperties().entrySet()) { optionStates.put(entry.getKey(), entry.getValue()); options.add(entry.getKey()); } } else { options = Arrays.asList(FileReportDataTypes.values()); for (FileReportDataTypes entry : options) { optionStates.put(entry, Boolean.TRUE); } } model = new OptionsListModel(); optionsList.setModel(model); optionsList.setCellRenderer(new OptionsListRenderer()); optionsList.setVisibleRowCount(-1); selectAllButton.setEnabled(notAllSelected()); deselectAllButton.setEnabled(anySelected()); wizPanel.setFinish(anySelected()); optionsList.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent evt) { int index = optionsList.locationToIndex(evt.getPoint()); FileReportDataTypes value = model.getElementAt(index); optionStates.put(value, !optionStates.get(value)); optionsList.repaint(); boolean anySelected = anySelected(); deselectAllButton.setEnabled(anySelected); wizPanel.setFinish(anySelected); selectAllButton.setEnabled(notAllSelected()); } }); }
Source:
<code>private static FilteredDropEditPolicy filter(EditPolicy delegate) { BiPredicate<EObject, EditPart> baseFilter = FilteredDropEditPolicy::hasView; BiPredicate<EObject, EditPart> invalidPortOnPart = RTCapsuleStructureDiagramDragDropEditPolicy::isInvalidPortOnCapsulePart; BiPredicate<EObject, EditPart> invalidPortOnCapsule = RTCapsuleStructureDiagramDragDropEditPolicy::isInvalidPortOnCapsule; return new FilteredDropEditPolicy(delegate, <START> (baseFilter.or(invalidPortOnPart)).or(invalidPortOnCapsule)); <END> }</code><technical_language>[nit] This is, strictly speaking, a redundant paren. .or invocations chain naturally</technical_language>

Target:
private static FilteredDropEditPolicy filter(EditPolicy delegate) { BiPredicate<EObject, EditPart> baseFilter = FilteredDropEditPolicy::hasView; BiPredicate<EObject, EditPart> invalidPortOnPart = RTCapsuleStructureDiagramDragDropEditPolicy::isInvalidPortOnCapsulePart; BiPredicate<EObject, EditPart> invalidTypeOnCapsule = RTCapsuleStructureDiagramDragDropEditPolicy::isInvalidTypeOnCapsule; BiPredicate<EObject, EditPart> invalidPortOnCapsule = RTCapsuleStructureDiagramDragDropEditPolicy::isInvalidPortOnCapsule; return new FilteredDropEditPolicy(delegate, baseFilter.or(invalidPortOnPart).or(invalidTypeOnCapsule).or(invalidPortOnCapsule)); }
Source:
<code>public static <T> List<T> convertMultiValue(Pattern separatorPattern, Function<Object, T> elementConverter, Object value) { if ( value instanceof Collection ) { return ( (Collection<?>) value ).stream() .map( ConvertUtils::trimIfString ) .filter( Objects::nonNull ) .map( elementConverter ) .collect( Collectors.toList() ); } else if ( value instanceof String ) { <START> return separatorPattern.splitAsStream( (CharSequence) value ) <END> .map( ConvertUtils::trimIfString ) .filter( Objects::nonNull ) .map( elementConverter ) .collect( Collectors.toList() ); } else { throw log.invalidMultiPropertyValue(); } }</code><technical_language>This consistent instanceof above, other convert methods in class. in favor of leaving this as-is</technical_language>

Target:
public static <T> List<T> convertMultiValue(Pattern separatorPattern, Function<Object, T> elementConverter, Object value) { if ( value instanceof Collection ) { return ( (Collection<?>) value ).stream() .map( ConvertUtils::trimIfString ) .filter( Objects::nonNull ) .map( elementConverter ) .collect( Collectors.toList() ); } else if ( value instanceof String ) { return separatorPattern.splitAsStream( (String) value ) .map( ConvertUtils::trimIfString ) .filter( Objects::nonNull ) .map( elementConverter ) .collect( Collectors.toList() ); } else { throw log.invalidMultiPropertyValue(); } }
Source:
<code>public String originalToString() { StringBuilder sb = new StringBuilder(); <START> Iterator it = edges.entrySet() .iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if (!((Edge) pair.getValue()).isPrinted()) { sb.append(getLabel()); sb.append(" --- "); sb.append(((Edge) pair.getValue()).getWeight()); sb.append(" --- "); sb.append(((Vertex) pair.getKey()).getLabel()); sb.append("\n"); ((Edge) pair.getValue()).setPrinted(true); } } <END> return sb.toString(); }</code><technical_language>Typed iterator</technical_language>

Target:
public String originalToString(){ StringBuilder sb = new StringBuilder(); Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (!pair.getValue().isPrinted()) { sb.append(getLabel()); sb.append(" --- "); sb.append(pair.getValue().getWeight()); sb.append(" --- "); sb.append(pair.getKey().getLabel()); sb.append("\n"); pair.getValue().setPrinted(true); } } return sb.toString(); }