auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void test_connectLjava_net_SocketAddressI_setSOTimeout() throws Exception { final <START> Exception[] unexpectedException <END> = new Exception[1]; class SocketConnector extends Thread { private final int timeout; private final Socket theSocket; private final SocketAddress address; @Override public void run() { try { theSocket.connect(address, timeout); } catch (SocketTimeoutException e) { } catch (Exception e) { unexpectedException[0] = e; } } private SocketConnector(int timeout, Socket theSocket, SocketAddress address) { this.timeout = timeout; this.theSocket = theSocket; this.address = address; } } try (final Socket theSocket = new Socket()) { final SocketConnector connector = new SocketConnector(5000, theSocket, UNREACHABLE_ADDRESS); connector.start(); theSocket.setSoTimeout(1000); Thread.sleep(10); assertTrue("Socket option not set during connect: 10 ", Math.abs(1000 - theSocket.getSoTimeout()) <= 10); Thread.sleep(50); theSocket.setSoTimeout(2000); assertTrue("Socket option not set during connect: 50 ", Math.abs(2000 - theSocket.getSoTimeout()) <= 10); connector.join(); assertNull(unexpectedException[0]); } }</code><technical_language>array create a "constant reference a mutable object"</technical_language>

Target:
public void test_connectLjava_net_SocketAddressI_setSOTimeout() throws Exception { class SocketConnector extends Thread { private final int timeout; private final Socket theSocket; private final SocketAddress address; private Exception exception = null; @Override public void run() { try { theSocket.connect(address, timeout); } catch (SocketTimeoutException e) { } catch (Exception e) { exception = e; } } private SocketConnector(int timeout, Socket theSocket, SocketAddress address) { this.timeout = timeout; this.theSocket = theSocket; this.address = address; } private Exception getException() { return exception; } } try (final Socket theSocket = new Socket()) { final SocketConnector connector = new SocketConnector(5000, theSocket, UNREACHABLE_ADDRESS); connector.start(); theSocket.setSoTimeout(1000); Thread.sleep(10); assertTrue("Socket option not set during connect: 10 ", Math.abs(1000 - theSocket.getSoTimeout()) <= 10); Thread.sleep(50); theSocket.setSoTimeout(2000); assertTrue("Socket option not set during connect: 50 ", Math.abs(2000 - theSocket.getSoTimeout()) <= 10); connector.join(); Exception e = connector.getException(); if (e != null) { e.printStackTrace(); } assertNull(e); } }
Source:
<code>public ListEndpointUrlInfoByNhinTargetCommunitiesResponseMessageType listEndpointUrlInfoByNhinTargetCommunities( ListEndpointUrlInfoByNhinTargetCommunitiesRequestMessageType request) { LOG.trace("listEndpointUrlInfoByNhinTargetCommunities--call"); ListEndpointUrlInfoByNhinTargetCommunitiesResponseMessageType response = new ListEndpointUrlInfoByNhinTargetCommunitiesResponseMessageType(); NhinTargetCommunitiesType targets = request.getNhinTargetCommunities(); String serviceName = request.getServiceName(); if (null == targets || StringUtils.isBlank(serviceName)) { <START> response.setMessage("Nhin-Targe-Communities and ServiceName are required."); <END> return response; } try { response.getUrlInfoList().addAll(convertUrlInfoTypeList( getExchangeManager().getEndpointURLFromNhinTargetCommunities(targets, serviceName))); } catch (ExchangeManagerException ex) { LOG.error("listEndpointUrlInfoByNhinTargetCommunities encounter error: {}", ex.getLocalizedMessage(), ex); } return response; }</code><technical_language>Typo in Target</technical_language>

Target:
public ListEndpointUrlInfoByNhinTargetCommunitiesResponseMessageType listEndpointUrlInfoByNhinTargetCommunities( ListEndpointUrlInfoByNhinTargetCommunitiesRequestMessageType request) { LOG.trace("listEndpointUrlInfoByNhinTargetCommunities--call"); ListEndpointUrlInfoByNhinTargetCommunitiesResponseMessageType response = new ListEndpointUrlInfoByNhinTargetCommunitiesResponseMessageType(); NhinTargetCommunitiesType targets = request.getNhinTargetCommunities(); String serviceName = request.getServiceName(); if (null == targets || StringUtils.isBlank(serviceName)) { response.setMessage("Nhin-Target-Communities and ServiceName are required."); return response; } try { response.getUrlInfoList().addAll(convertUrlInfoTypeList( getExchangeManager().getEndpointURLFromNhinTargetCommunities(targets, serviceName))); } catch (ExchangeManagerException ex) { LOG.error("listEndpointUrlInfoByNhinTargetCommunities encounter error: {}", ex.getLocalizedMessage(), ex); } return response; }
Source:
<code>public void close() { try { out.close(); }catch(IOException e){ throw new OutputStreamCloseException(e); } <START> } <END></code><technical_language>a helper method for this? closeUncaught(out) alternatively close method throw IOException</technical_language>

Target:
public void close() { IOExceptionUtils.closeQuietly(out); }
Source:
<code>void doRun() { try { write("+OK POP3"); while (!socket.isClosed()) { String line = reader.readLine(); if ("CAPA".equals(line)) { write("+OK"); write("USER"); write("."); } else if ("USER user".equals(line)) { write("+OK"); } else if ("PASS pw".equals(line)) { write("+OK"); } else if ("STAT".equals(line)) { write("+OK 1 3"); } else if ("NOOP".equals(line)) { write("+OK"); } else if ("RETR 1".equals(line)) { write("+OK"); write("To: foo@bar"); write("From: bar@baz"); write("Subject: Test Email"); write(""); write("foo"); write("."); } else if ("QUIT".equals(line)) { write("+OK"); socket.close(); } <START> } <END> } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>point out this embedded email sever approach ? Thanks</technical_language>

Target:
void doRun() { try { write("+OK POP3"); while (!socket.isClosed()) { String line = reader.readLine(); if ("CAPA".equals(line)) { write("+OK"); write("USER"); write("."); } else if ("USER user".equals(line)) { write("+OK"); } else if ("PASS pw".equals(line)) { write("+OK"); } else if ("STAT".equals(line)) { write("+OK 1 3"); } else if ("NOOP".equals(line)) { write("+OK"); } else if ("RETR 1".equals(line)) { write("+OK"); write(MESSAGE); write("."); } else if ("QUIT".equals(line)) { write("+OK"); socket.close(); } } } catch (IOException e) { e.printStackTrace(); } }
Source:
<code>public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (loc.length() > 0 && ("loc".equals(localName) || "sitemap".equals(localName))) { if (!isAllBlank(loc)) { maybeAddSiteMap(); return; } <START> loc = new StringBuilder(); <END> if ("url".equals(localName)) { locClosed = false; lastMod = null; } } }</code><technical_language>want reset loc, of localName is loc sitemap</technical_language>

Target:
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (loc.length() > 0 && ("loc".equals(localName) || "sitemap".equals(localName))) { if (!isAllBlank(loc)) { maybeAddSiteMap(); return; } loc = new StringBuilder(); if ("sitemap".equals(localName)) { locClosed = false; lastMod = null; } } }
Source:
<code>private void markTasksAsScheduled(Database database, JSONObject batch) { try { database.createQuery("UPDATE sqlreplicationtask " + "SET scheduled = ${scheduled} " <START> + "WHERE id >= ${lowerBound}" <END> + " AND id <= ${upperBound}" + " AND failed = 0" + " AND earliestExecution < ${executionLimit}") .set("scheduled", LocalDateTime.now()) .set("executionLimit", LocalDateTime.now()) .set("lowerBound", batch.getLongValue(SQLEntityBatchEmitter.START_ID)) .set("upperBound", batch.getLongValue(SQLEntityBatchEmitter.END_ID)) .set("scheduled", LocalDateTime.now()) .executeUpdate(); } catch (SQLException e) { Exceptions.handle() .to(StorageUtils.LOG) .error(e) .withSystemErrorMessage( "Layer 1/replication: Failed to mark SQL replication tasks as scheduled: %s (%s)") .handle(); } }</code><technical_language>formatting query (spaces line end mixed spaces line start)</technical_language>

Target:
private void markTasksAsScheduled(Database database, JSONObject batch) { try { database.createQuery("UPDATE sqlreplicationtask" + " SET scheduled = ${scheduled}" + " WHERE id >= ${lowerBound}" + " AND id <= ${upperBound}" + " AND failed = 0" + " AND earliestExecution < ${executionLimit}") .set("scheduled", LocalDateTime.now()) .set("executionLimit", LocalDateTime.now()) .set("lowerBound", batch.getLongValue(SQLEntityBatchEmitter.START_ID)) .set("upperBound", batch.getLongValue(SQLEntityBatchEmitter.END_ID)) .executeUpdate(); } catch (SQLException e) { Exceptions.handle() .to(StorageUtils.LOG) .error(e) .withSystemErrorMessage( "Layer 1/replication: Failed to mark SQL replication tasks as scheduled: %s (%s)") .handle(); } }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GatewayDevice that = (GatewayDevice) o; <START> return Objects.equals(id, that.id) && <END> Objects.equals(resourceId, that.resourceId) && Objects.equals(tunnelIps, that.tunnelIps) && Objects.equals(managementIp, that.managementIp) && Objects.equals(managementPort, that.managementPort) && Objects.equals(managementProtocol, that.managementProtocol) && Objects.equals(remoteMacEntries, that.remoteMacEntries); }</code><technical_language>type</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GatewayDevice that = (GatewayDevice) o; return Objects.equals(id, that.id) && Objects.equals(type, that.type) && Objects.equals(resourceId, that.resourceId) && Objects.equals(tunnelIps, that.tunnelIps) && Objects.equals(managementIp, that.managementIp) && Objects.equals(managementPort, that.managementPort) && Objects.equals(managementProtocol, that.managementProtocol) && Objects.equals(remoteMacEntries, that.remoteMacEntries); }
Source:
<code>protected SearchSourceBuilder createSearchSourceBuilder(String query) { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.emptyList()); try { try (XContentParser parser = XContentFactory.xContent(XContentType.JSON) .createParser(new NamedXContentRegistry(searchModule.getNamedXContents()), query)) { searchSourceBuilder.parseXContent(new QueryParseContext(parser)); } } catch (IOException e) { <START> log.error("Invalid query: " + query + ": " + e.getMessage(), e); <END> throw new IllegalArgumentException("Bad query: " + query); } return searchSourceBuilder; }</code><technical_language>log.error throw</technical_language>

Target:
protected SearchSourceBuilder createSearchSourceBuilder(String query) { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.emptyList()); try { try (XContentParser parser = XContentFactory.xContent(XContentType.JSON) .createParser(new NamedXContentRegistry(searchModule.getNamedXContents()), query)) { searchSourceBuilder.parseXContent(new QueryParseContext(parser)); } } catch (IOException | ParsingException e) { log.error("Invalid query: " + query + ": " + e.getMessage(), e); throw new IllegalArgumentException("Bad query: " + query); } return searchSourceBuilder; }
Source:
<code>public AsyncJobStatusDTO hypervisorHeartbeatUpdate( @Verify(value = Owner.class, require = Access.READ_ONLY, subResource = SubResource.HYPERVISOR) final String ownerKey, final String reporterId) { if (reporterId == null || reporterId.isEmpty()) { throw new BadRequestException("reporter_id is absent or empty"); } final Owner owner = this.getOwner(ownerKey); JobConfig config = HypervisorHeartbeatUpdateJob.createJobConfig() .setOwner(owner) .setReporterId(reporterId); try { AsyncJobStatus job = this.jobManager.queueJob(config); return this.translator.translate(job, AsyncJobStatusDTO.class); } catch (JobException e) { String errmsg = this.i18n.tr("An unexpected exception occurred while scheduling job \"{0}\"", config.getJobKey()); <START> throw new IseException(errmsg, e); <END> } }</code><technical_language>here: add log.error(errmsg, e) throwing also, need rebase PR due RoleResource merged earlier</technical_language>

Target:
public AsyncJobStatusDTO hypervisorHeartbeatUpdate( @Verify(value = Owner.class, require = Access.READ_ONLY, subResource = SubResource.HYPERVISOR) final String ownerKey, final String reporterId) { if (reporterId == null || reporterId.isEmpty()) { throw new BadRequestException("reporter_id is absent or empty"); } final Owner owner = this.getOwner(ownerKey); JobConfig config = HypervisorHeartbeatUpdateJob.createJobConfig() .setOwner(owner) .setReporterId(reporterId); try { AsyncJobStatus job = this.jobManager.queueJob(config); return this.translator.translate(job, AsyncJobStatusDTO.class); } catch (JobException e) { String errmsg = this.i18n.tr("An unexpected exception occurred while scheduling job \"{0}\"", config.getJobKey()); log.error(errmsg, e); throw new IseException(errmsg, e); } }
Source:
<code>public static void main(String[] args) throws Exception { String corpusDirectory = "/shared/corpora/corporaWeb/written/eng/MASC-3.0.0/xces"; String outputDirectory = "/shared/corpora/corporaWeb/written/eng/MASC-3.0.0/json"; MascXCESReader reader = new MascXCESReader("MASC-3.0.0", corpusDirectory, ".xml"); <START> for (TextAnnotation ta : reader) { <END> String outputFile = Paths.get(outputDirectory, ta.getId()).toAbsolutePath().toString(); new File(outputFile).getParentFile().mkdirs(); SerializationHelper.serializeTextAnnotationToFile(ta, outputFile + ".json", true, true); } }</code><technical_language>if catch exceptions failure process a file a portion of a file's content, please add list of files message text indicating failures report generate</technical_language>

Target:
public static void main(String[] args) throws Exception { String corpusDirectory = "/shared/corpora/corporaWeb/written/eng/MASC-3.0.0/xces"; String outputDirectory = "/shared/corpora/corporaWeb/written/eng/MASC-3.0.0/json"; if (args.length >= 2) { corpusDirectory = args[0]; outputDirectory = args[1]; } MascXCESReader reader = new MascXCESReader("MASC-3.0.0", corpusDirectory, ".xml"); for (TextAnnotation ta : reader) { String outputFile = Paths.get(outputDirectory, ta.getId()).toAbsolutePath().toString(); new File(outputFile).getParentFile().mkdirs(); SerializationHelper.serializeTextAnnotationToFile(ta, outputFile + ".json", true, true); } System.out.print(reader.generateReport()); }
Source:
<code>public void processModule(Module module, String group, int index) { if (!"trigger".equalsIgnoreCase(module.getType())) { return; } final BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CronTrigger.class); builder.addConstructorArgValue(module.getProperties().get("cron")); <START> final BeanDefinitionAddingPostProcessor postProcessor = new BeanDefinitionAddingPostProcessor(); <END> postProcessor.addBeanDefinition(group, builder.getBeanDefinition()); Assert.notNull(commonApplicationContext, "The 'commonApplicationContext' property must not be null."); this.commonApplicationContext.addBeanFactoryPostProcessor(postProcessor); this.commonApplicationContext.refresh(); }</code><technical_language>worth creating a base class for Plugins takes care of this (now thing). allow hide commonApplicationContext BeanDefinitionAddingPostProcessor for common cases, instead exposing a simple addBeanDefinition method sub-classes</technical_language>

Target:
public void processModule(Module module, String group, int index) { if (!"trigger".equalsIgnoreCase(module.getType())) { return; } final BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CronTrigger.class); builder.addConstructorArgValue(module.getProperties().get("cron")); final BeanDefinitionAddingPostProcessor postProcessor = new BeanDefinitionAddingPostProcessor(); postProcessor.addBeanDefinition(BEAN_NAME_PREFIX + group, builder.getBeanDefinition()); Assert.notNull(commonApplicationContext, "The 'commonApplicationContext' property must not be null."); this.commonApplicationContext.addBeanFactoryPostProcessor(postProcessor); configureProperties(module, group); this.commonApplicationContext.refresh(); }
Source:
<code><START> protected boolean isSupported(final AggregationOp aggOp) { <END> return true; }</code><technical_language>This a dangerous approach in case added AggregationOps sense for double (say boolean operators)</technical_language>

Target:
protected boolean isSupported(final AggregationOp aggOp) { return ImmutableSet.of( AggregationOp.COUNT, AggregationOp.MIN, AggregationOp.MAX, AggregationOp.SUM, AggregationOp.AVG, AggregationOp.STDEV, AggregationOp.SUM_SQUARED) .contains(aggOp); }
Source:
<code>public void execute() throws MojoExecutionException, MojoFailureException { try { if (profile == null) { profile = P2Constants.DEFAULT_PROFILE_ID; } deployRepository(); File profileConfigIni = FileManagementUtil.getProfileConfigIniFile(targetPath.getPath(), profile); FileManagementUtil.changeConfigIniProperty(profileConfigIni, "eclipse.p2.data.area", <START> "@config.dir/../lib/p2/", this.getLog()); <END> } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }</code><technical_language>path moved constants is in FeatureInstaller.java</technical_language>

Target:
public void execute() throws MojoExecutionException, MojoFailureException { try { if (profile == null) { profile = P2Constants.DEFAULT_PROFILE_ID; } deployRepository(); File profileConfigIni = FileManagementUtil.getProfileConfigIniFile(targetPath.getPath(), profile); FileManagementUtil.changeConfigIniProperty(profileConfigIni, "eclipse.p2.data.area", P2Constants.P2_DIRECTORY, this.getLog()); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
Source:
<code>public void canSetAndGetOnCancelListener() { Dialog dialog = new Dialog(RuntimeEnvironment.application); DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { } }; dialog.setOnCancelListener(onCancelListener); <START> assertSame(onCancelListener, shadowOf(dialog).getOnCancelListener()); <END> }</code><technical_language>Please AssertJ matchers (i.e assertThat(foo).isSameAs(bar)) instead of Junit ones</technical_language>

Target:
public void canSetAndGetOnCancelListener() { Dialog dialog = new Dialog(RuntimeEnvironment.application); DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { } }; dialog.setOnCancelListener(onCancelListener); assertThat(onCancelListener).isSameAs(shadowOf(dialog).getOnCancelListener()); }
Source:
<code>public void endToEndSSLTest() throws InterruptedException, IOException, InstantiationException { int basePort = generateBasePort(); <START> int baseSSLPort = generateBaseSSLPort(); <END> endToEndTest(basePort, baseSSLPort, new Port(baseSSLPort, PortType.SSL), true, "DC1", "DC2,DC3", "DC1,DC3", "DC1,DC2"); }</code><technical_language>names defined static ints</technical_language>

Target:
public void endToEndSSLTest() throws InterruptedException, IOException, InstantiationException { cluster = new MockCluster(notificationSystem, true, "DC1,DC2,DC3"); DataNodeId dataNodeId = cluster.getClusterMap().getDataNodeIds().get(0); endToEndTest(new Port(dataNodeId.getSSLPort(), PortType.SSL), "DC1", "DC2,DC3"); }
Source:
<code><START> public void addParserThread(ParserThread thread) { <END> parserThreads.add(thread); }</code><technical_language>package accessibility</technical_language>

Target:
protected void addParserThread(ParserThread thread) { parserThreads.add(thread); }
Source:
<code>public void shouldAuthorise3dsResponseIfMatchesWithEpdqStatus() { mockPaymentProviderResponse(200, successAuthorisedQueryResponse()); Gateway3DSAuthorisationResponse response = provider.authorise3dsResponse(buildTestAuthorisation3dsVerifyRequest("AUTHORISED")); verifyPaymentProviderRequest(successAuthQueryRequest()); assertTrue(response.isSuccessful()); <START> assertThat(response.isSuccessful(), is(true)); <END> }</code><technical_language>I this line removed is above</technical_language>

Target:
public void shouldAuthorise3dsResponseIfMatchesWithEpdqStatus() { mockPaymentProviderResponse(200, successAuthorisedQueryResponse()); Gateway3DSAuthorisationResponse response = provider.authorise3dsResponse(buildTestAuthorisation3dsVerifyRequest("AUTHORISED")); verifyPaymentProviderRequest(successAuthQueryRequest()); assertTrue(response.isSuccessful()); }
Source:
<code>protected void doExecute() { EObject applyStereotype = element.getStereotypeApplication(stereotypeInTargetContext); if (null == applyStereotype && null != element.eContainer()) { applyStereotype = element.applyStereotype(stereotypeInTargetContext); } EList<EStructuralFeature> eStructuralFeatures = applyStereotype.eClass().getEAllStructuralFeatures(); for (EStructuralFeature eStructuralFeature : eStructuralFeatures) { String name = eStructuralFeature.getName(); if (!name.startsWith(Extension.METACLASS_ROLE_PREFIX) && eStructuralFeature.isChangeable()) { if (eStructuralFeature instanceof EReference && ((EReference) eStructuralFeature).isContainment()) { Object value = stereotypeApplication.eGet(eStructuralFeature); if <START> (value instanceof <END> EObject) { EObject valueCopy = EcoreUtil.copy((EObject) value); applyStereotype.eSet(eStructuralFeature, valueCopy); } } else { applyStereotype.eSet(eStructuralFeature, stereotypeApplication.eGet(eStructuralFeature)); } } } }</code><technical_language>work for multi reference + complete tests please</technical_language>

Target:
protected void doExecute() { EObject applyStereotype = element.getStereotypeApplication(stereotypeInTargetContext); if (null == applyStereotype && null != element.eContainer()) { applyStereotype = element.applyStereotype(stereotypeInTargetContext); } EList<EStructuralFeature> eStructuralFeatures = applyStereotype.eClass().getEAllStructuralFeatures(); for (EStructuralFeature eStructuralFeature : eStructuralFeatures) { String name = eStructuralFeature.getName(); if (!name.startsWith(Extension.METACLASS_ROLE_PREFIX) && eStructuralFeature.isChangeable()) { if (eStructuralFeature instanceof EReference && ((EReference) eStructuralFeature).isContainment()) { Object value = stereotypeApplication.eGet(eStructuralFeature); if (value instanceof EObject) { EObject valueCopy = EcoreUtil.copy((EObject) value); applyStereotype.eSet(eStructuralFeature, valueCopy); } else if (value instanceof Collection<?>) { Collection<?> listValue = (Collection<?>) value; if (listValue.stream().allMatch(v -> v instanceof EObject)) { Collection<?> valueCopy = EcoreUtil.copyAll(listValue); applyStereotype.eSet(eStructuralFeature, valueCopy); } } } else { applyStereotype.eSet(eStructuralFeature, stereotypeApplication.eGet(eStructuralFeature)); } } } }
Source:
<code>private InetSocketAddress getBindingForPort(DockerAPI api, InspectContainerResponse ir, int internalPort) { ExposedPort sshPort = new ExposedPort(internalPort); Integer port = 22; final NetworkSettings networkSettings = ir.getNetworkSettings(); final Ports ports = networkSettings.getPorts(); final Map<ExposedPort, Ports.Binding[]> bindings = ports.getBindings(); final Ports.Binding[] sshBindings = bindings.get(sshPort); for (Ports.Binding b : sshBindings) { String hps = b.getHostPortSpec(); port = Integer.valueOf(hps); } String host = getExternalIP(api, ir, networkSettings, sshBindings); <START> return new InetSocketAddress("127.0.0.1", port); <END> }</code><technical_language>This work if Jenkins is running host docker daemon. work in general case Jenkins is a separate host docker hosts/swarms talking to</technical_language>

Target:
private InetSocketAddress getBindingForPort(DockerAPI api, InspectContainerResponse ir, int internalPort) { ExposedPort sshPort = new ExposedPort(internalPort); Integer port = 22; final NetworkSettings networkSettings = ir.getNetworkSettings(); final Ports ports = networkSettings.getPorts(); final Map<ExposedPort, Ports.Binding[]> bindings = ports.getBindings(); final Ports.Binding[] sshBindings = bindings.get(sshPort); for (Ports.Binding b : sshBindings) { String hps = b.getHostPortSpec(); port = Integer.valueOf(hps); } String host = getExternalIP(api, ir, networkSettings, sshBindings); return new InetSocketAddress(host, port); }
Source:
<code>private String getArchitectureSuffix(String prefix) { String arch = System.getProperty("os.arch").toLowerCase(Locale.US).replaceAll("\\W", ""); switch (prefix) { case OS_MAC: return null; case OS_LINUX: switch (arch) { case "i386": case "x86": return "i386"; case "x86_64": case "amd64": return "amd64"; } case OS_WIN: switch (arch){ <START> case "x86": <END> return "x86"; case "x86_64": case "amd64": return "x64"; } } throw new UnsupportedOperationException("Architecture '" + arch + "' is not supported by SQLite library"); }</code><technical_language>please add a break statement this avoid fallthrough (ErrorProne complains this)</technical_language>

Target:
private String getArchitectureSuffix(String prefix) { String arch = System.getProperty("os.arch").toLowerCase(Locale.US).replaceAll("\\W", ""); switch (prefix) { case OS_MAC: return null; case OS_LINUX: switch (arch) { case "i386": case "x86": return "i386"; case "x86_64": case "amd64": return "amd64"; } break; case OS_WIN: switch (arch) { case "x86": return "x86"; case "x86_64": case "amd64": return "x64"; } break; } throw new UnsupportedOperationException( "Architecture \'" + arch + "\' is not supported by SQLite library"); }
Source:
<code>private void initPlaceHandlers() { btnIsAPlace.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean selected = btnIsAPlace.isSelected(); if (selected) { <START> nameToken.setEnabled(true); <END> btnIsCrawlable.setEnabled(true); nameToken.grabFocus(); } else { nameToken.setEnabled(false); btnIsCrawlable.setEnabled(false); nameToken.setText(""); } } }); }</code><technical_language>refactoring: nameToken.setEnabled(selected); btnIsCrawlable.setEnabled(selected); if(selected) { nameToken.grabFocus(); } else { nameToken.setText(""); }</technical_language>

Target:
private void initPlaceHandlers() { usePlace.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean selected = usePlace.isSelected(); nameToken.setEnabled(selected); useCrawlable.setEnabled(selected); if (selected) { nameToken.grabFocus(); } else { nameToken.setText(""); } } }); }
Source:
<code>public static void parseJaggeryScript(final String fileURL) { try { RhinoEngine.enterGlobalContext(); final FileInputStream fstream = new FileInputStream(fileURL); final RhinoEngine engine = CommandLineManager.getCommandLineEngine(); final ScriptableObject scope = engine.getRuntimeScope(); final JaggeryContext jaggeryContext = new JaggeryContext(); <START> jaggeryContext.setTenantDomain("0"); <END> jaggeryContext.setEngine(engine); jaggeryContext.setScope(scope); jaggeryContext.addProperty(CommonManager.JAGGERY_OUTPUT_STREAM, System.out); RhinoEngine.putContextProperty("jaggeryContext", jaggeryContext); final Reader source = new ScriptReader(new BufferedInputStream(fstream)); out.println("\n"); ShellUtilityService.initializeUtilityServices(); engine.exec(source, scope, null); ShellUtilityService.destroyUtilityServices(); out.flush(); out.println("\n"); } catch (Exception e) { out.println("\n"); out.println("Error: " + e.getMessage()); out.println("\n"); } }</code><technical_language>Add default tenant domain here</technical_language>

Target:
public static void parseJaggeryScript(final String fileURL) { try { RhinoEngine.enterGlobalContext(); final FileInputStream fstream = new FileInputStream(fileURL); final RhinoEngine engine = CommandLineManager.getCommandLineEngine(); final ScriptableObject scope = engine.getRuntimeScope(); final JaggeryContext jaggeryContext = new JaggeryContext(); jaggeryContext.setTenantDomain(DEFAULT_TENANTDOMAIN); jaggeryContext.setEngine(engine); jaggeryContext.setScope(scope); jaggeryContext.addProperty(CommonManager.JAGGERY_OUTPUT_STREAM, System.out); RhinoEngine.putContextProperty("jaggeryContext", jaggeryContext); final Reader source = new ScriptReader(new BufferedInputStream(fstream)); out.println("\n"); ShellUtilityService.initializeUtilityServices(); engine.exec(source, scope, null); ShellUtilityService.destroyUtilityServices(); out.flush(); out.println("\n"); } catch (Exception e) { out.println("\n"); out.println("Error: " + e.getMessage()); out.println("\n"); } }
Source:
<code>public void testRawQueryWithBlob() throws ErrnoException { for (Network network : getTestableNetworks()) { CountDownLatch latch = new CountDownLatch(1); final int TIMEOUT_MS = 12_000; final byte[] blob = new byte[]{ 0x55, 0x66, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01 }; <START> String msg <END> = "Raw query with blob " + byteArrayToHexString(blob); mDns.query(network, blob, FLAG_NO_CACHE_LOOKUP, mHandler, answer -> { if (answer == null) { fail(msg + " no answer returned"); } try { new CheckedDnsPacket(answer); Log.d(TAG, "Reported blob:" + byteArrayToHexString(answer)); latch.countDown(); } catch (DnsPacket.ParseException e) { Log.d(TAG, e.getMessage()); fail(msg + " no valid answer"); } } ); try { assertTrue(msg + " but no answer after " + TIMEOUT_MS + "ms.", latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }</code><technical_language>final</technical_language>

Target:
public void testRawQueryWithBlob() throws ErrnoException { final byte[] blob = new byte[]{ 0x55, 0x66, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01 }; final String msg = "Raw query with blob " + byteArrayToHexString(blob); for (Network network : getTestableNetworks()) { final CountDownLatch latch = new CountDownLatch(1); mDns.query(network, blob, FLAG_NO_CACHE_LOOKUP, mHandler, answer -> { if (answer == null) { fail(msg + " no answer returned"); } try { assertValidAnswer(msg, new DnsAnswer(answer)); Log.d(TAG, "Reported blob:" + byteArrayToHexString(answer)); latch.countDown(); } catch (DnsPacket.ParseException e) { fail(msg + e.getMessage()); } } ); try { assertTrue(msg + " but no answer after " + TIMEOUT_MS + "ms.", latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }
Source:
<code>public Path generateArtifact(URI uri, int size) throws IOException { try { <START> NugetArtifactCoordinates nugetArtCoords = NugetArtifactCoordinates.parse(Paths.get(uri).toString()); <END> generateNugetPackage(nugetArtCoords.getId(), nugetArtCoords.getVersion()); }catch(JAXBException | NoSuchAlgorithmException | NugetFormatException e){ logger.error(e.getMessage(),e); } return Paths.get(uri); }</code><technical_language>Cosmetic: please call variable coordinates</technical_language>

Target:
public Path generateArtifact(URI uri, int size) throws IOException { NugetArtifactCoordinates coordinates = NugetArtifactCoordinates.parse(uri.toString()); try { generateNugetPackage(coordinates.getId(), coordinates.getVersion()); } catch(JAXBException | NoSuchAlgorithmException | NugetFormatException e) { throw new IOException(e); } return basedir.resolve(coordinates.toPath()).normalize().toAbsolutePath(); }
Source:
<code>public static void checkOnGraph(GraphData graph, RelationNode... nodes) throws OseeCoreException { checkNotNull(graph, "graph"); for (RelationNode node : nodes) { checkNotNull(node, "node"); IOseeBranch branchnode = node.getBranch(); IOseeBranch branchgraph = graph.getBranch(); <START> checkExpressionFailOnTrue(!branchgraph.equals(branchnode), <END> "Error - Node[%s] is on branch[%s] but should be on branch[%s]", node, branchnode, branchgraph); } }</code><technical_language>is example of checking for null</technical_language>

Target:
public static void checkOnGraph(GraphData graph, RelationNode... nodes) throws OseeCoreException { checkNotNull(graph, "graph"); for (RelationNode node : nodes) { checkNotNull(node, "node"); GraphData graph2 = node.getGraph(); checkExpressionFailOnTrue(!graph.equals(graph2), "Error - Node[%s] is on graph[%s] but should be on graph[%s]", node, graph2, graph); } }
Source:
<code>public boolean equals(Object o) { if (o instanceof StartMessageEvent) { StartMessageEvent other = (StartMessageEvent) o; return super.equals(other) && <START> (other.executionSet == null ? executionSet == null : other.executionSet.equals(executionSet)) && <END> (other.dataIOSet == null ? dataIOSet == null : other.dataIOSet.equals(dataIOSet)); } return false; }</code><technical_language>Sorry, a "better way": java Objects.equals(executionSet, other.executionSet); optional</technical_language>

Target:
public boolean equals(Object o) { if (o instanceof StartMessageEvent) { StartMessageEvent other = (StartMessageEvent) o; return super.equals(other) && Objects.equals(executionSet, other.executionSet) && Objects.equals(dataIOSet, other.dataIOSet) && Objects.equals(labels, other.labels); } return false; }
Source:
<code>private Collection<DetailedLink> getLinks() { <START> ApplicationMode appMode = getCurrent().get(ApplicationMode.class); <END> if (appMode == ApplicationMode.GlusterOnly) { return getGlusterOnlyLinks(); } Collection<DetailedLink> links = new LinkedList<DetailedLink>(); links.add(createLink("capabilities")); links.add(createLink("clusters", LinkFlags.SEARCHABLE)); links.add(createLink("datacenters", LinkFlags.SEARCHABLE)); links.add(createLink("events", LinkFlags.SEARCHABLE, getEventParams())); links.add(createLink("hosts", LinkFlags.SEARCHABLE)); links.add(createLink("networks")); links.add(createLink("roles")); links.add(createLink("storagedomains", LinkFlags.SEARCHABLE)); links.add(createLink("tags")); links.add(createLink("templates", LinkFlags.SEARCHABLE)); links.add(createLink("users", LinkFlags.SEARCHABLE)); links.add(createLink("groups", LinkFlags.SEARCHABLE)); links.add(createLink("domains")); links.add(createLink("vmpools", LinkFlags.SEARCHABLE)); links.add(createLink("vms", LinkFlags.SEARCHABLE)); links.add(createLink("disks", LinkFlags.SEARCHABLE)); return links; }</code><technical_language>/getCurrent().get(ApplicationMode.class);/ times in methods sense adding cls-var initializing in .ctr</technical_language>

Target:
private Collection<DetailedLink> getLinks() { Collection<DetailedLink> links = new LinkedList<DetailedLink>(); links.add(createLink("capabilities")); links.add(createLink("clusters", LinkFlags.SEARCHABLE)); links.add(createLink("datacenters", LinkFlags.SEARCHABLE)); links.add(createLink("events", LinkFlags.SEARCHABLE, getEventParams())); links.add(createLink("hosts", LinkFlags.SEARCHABLE)); links.add(createLink("networks")); links.add(createLink("roles")); links.add(createLink("storagedomains", LinkFlags.SEARCHABLE)); links.add(createLink("tags")); links.add(createLink("templates", LinkFlags.SEARCHABLE)); links.add(createLink("users", LinkFlags.SEARCHABLE)); links.add(createLink("groups", LinkFlags.SEARCHABLE)); links.add(createLink("domains")); links.add(createLink("vmpools", LinkFlags.SEARCHABLE)); links.add(createLink("vms", LinkFlags.SEARCHABLE)); links.add(createLink("disks", LinkFlags.SEARCHABLE)); return links; }
Source:
<code>private Map<String, Object> toMap(ServerConfiguration conf) { Map<String, Object> configMap = new HashMap<>(); Iterator iterator = conf.getKeys(); while (iterator.hasNext()) { String key = iterator.next().toString(); List values = conf.getList(key); <START> if (values.size() > 0) { <END> configMap.put(key, values.get(0)); } } return configMap; }</code><technical_language>lists of more</technical_language>

Target:
private Map<String, Object> toMap(ServerConfiguration conf) { Map<String, Object> configMap = new HashMap<>(); Iterator iterator = conf.getKeys(); while (iterator.hasNext()) { String key = iterator.next().toString(); Object property = conf.getProperty(key); if (property != null) { configMap.put(key, property.toString()); } } return configMap; }
Source:
<code>protected void build(UnitVmModel model, T vm) { vm.setMemSizeMb(model.getMemSize().getEntity()); if (model.getIoThreadsEnabled().getEntity()) { vm.setNumOfIoThreads(model.getNumOfIoThreads().getEntity()); } else { vm.setNumOfIoThreads(0); } vm.setNumOfSockets(model.getNumOfSockets().getSelectedItem()); vm.setCpuPerSocket(Integer.parseInt(model.getTotalCPUCores().getEntity()) / model.getNumOfSockets().getSelectedItem()); vm.setDefaultDisplayType(model.getDisplayType().getSelectedItem()); vm.setNumOfMonitors(model.getNumOfMonitors().getSelectedItem()); vm.setSmartcardEnabled(model.getIsSmartcardEnabled().getEntity()); vm.setSsoMethod(model.extractSelectedSsoMethod()); vm.setMinAllocatedMem(model.getMinAllocatedMemory().getEntity()); vm.setDefaultBootSequence(model.getBootSequence()); vm.setSingleQxlPci(model.getIsSingleQxlEnabled().getEntity()); vm.setCustomEmulatedMachine(model.getEmulatedMachine().getSelectedItem()); vm.setCustomCpuName(model.getCustomCpu().getSelectedItem()); <START> vm.setCompatibilityVersion(model.getCompatibilityVersion().getSelectedItem()); <END> }</code><technical_language>This - this is shared instance types blank templates (which dependant cluster) in CoreUnitToVmBaseBuilder is typical place add</technical_language>

Target:
protected void build(UnitVmModel model, T vm) { vm.setMemSizeMb(model.getMemSize().getEntity()); if (model.getIoThreadsEnabled().getEntity()) { vm.setNumOfIoThreads(model.getNumOfIoThreads().getEntity()); } else { vm.setNumOfIoThreads(0); } vm.setNumOfSockets(model.getNumOfSockets().getSelectedItem()); vm.setCpuPerSocket(Integer.parseInt(model.getTotalCPUCores().getEntity()) / model.getNumOfSockets().getSelectedItem()); vm.setDefaultDisplayType(model.getDisplayType().getSelectedItem()); vm.setNumOfMonitors(model.getNumOfMonitors().getSelectedItem()); vm.setSmartcardEnabled(model.getIsSmartcardEnabled().getEntity()); vm.setSsoMethod(model.extractSelectedSsoMethod()); vm.setMinAllocatedMem(model.getMinAllocatedMemory().getEntity()); vm.setDefaultBootSequence(model.getBootSequence()); vm.setSingleQxlPci(model.getIsSingleQxlEnabled().getEntity()); vm.setCustomEmulatedMachine(model.getEmulatedMachine().getSelectedItem()); vm.setCustomCpuName(model.getCustomCpu().getSelectedItem()); }
Source:
<code>public void createDirectory(CreateDirectoryPRequest request, StreamObserver<CreateDirectoryPResponse> responseObserver) { CreateDirectoryPOptions options = request.getOptions(); RpcUtils.call(LOG, () -> { AlluxioURI pathUri = getAlluxioURI(request.getPath()); mFileSystemMaster.createDirectory(pathUri, (CreateDirectoryContext) CreateDirectoryContext <START> .create(options.toBuilder()).withTracker(new GrpcCallTracker(responseObserver))); <END> return CreateDirectoryPResponse.newBuilder().build(); }, "CreateDirectory", "request=%s", responseObserver, request); }</code><technical_language>if withTracker returns generic type of OperationContext (C in implementation), is necessary include cast CreateDirectoryContext? clean. edit - I looked figured out issue. Poor of generics. Change class definition of CreatePathContext remove need cast old: java public abstract class CreatePathContext<T extends GeneratedMessageV3.Builder<?>, K> extends OperationContext<T, CreatePathContext> { new: java public abstract class CreatePathContext<T extends GeneratedMessageV3.Builder<?>, extends OperationContext> extends OperationContext<T, K> {</technical_language>

Target:
public void createDirectory(CreateDirectoryPRequest request, StreamObserver<CreateDirectoryPResponse> responseObserver) { CreateDirectoryPOptions options = request.getOptions(); RpcUtils.call(LOG, () -> { AlluxioURI pathUri = getAlluxioURI(request.getPath()); mFileSystemMaster.createDirectory(pathUri, CreateDirectoryContext.create(options.toBuilder()) .withTracker(new GrpcCallTracker(responseObserver))); return CreateDirectoryPResponse.newBuilder().build(); }, "CreateDirectory", "request=%s", responseObserver, request); }
Source:
<code>public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement function = descriptor.getStartElement().getParent(); GoSignature signature = (function != null && function instanceof GoFunctionDeclaration) ? ((GoFunctionDeclaration)function).getSignature() : null; if (signature == null) return; PsiFile file = signature.getContainingFile(); if (!(file instanceof GoFile)) return; if (myType == GoTestFunctionType.EXAMPLE) { signature.replace(GoElementFactory.createFunctionSignatureFromText(project, "")); return; } GoImportSpec testingImportSpec = (((GoFile)file).getImportedPackagesMap().get(GoConstants.TESTING_PATH)); if (testingImportSpec == null) { ((GoFile)file).addImport(GoConstants.TESTING_PATH, null); } String paramType = getProperParamType(getTestingAlias(testingImportSpec), myType); signature.replace(GoElementFactory.createFunctionSignatureFromText(project, myType.getParamType().toLowerCase() + " " + paramType)); <START> } <END></code><technical_language>add locale toLowerCase invokation</technical_language>

Target:
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement function = descriptor.getStartElement().getParent(); GoSignature signature = (function != null && function instanceof GoFunctionDeclaration) ? ((GoFunctionDeclaration)function).getSignature() : null; if (signature == null) return; PsiFile file = signature.getContainingFile(); if (!(file instanceof GoFile)) return; if (myType == GoTestFunctionType.EXAMPLE) { signature.replace(GoElementFactory.createFunctionSignatureFromText(project, "")); return; } GoImportSpec testingImportSpec = (((GoFile)file).getImportedPackagesMap().get(GoConstants.TESTING_PATH)); if (testingImportSpec == null) { ((GoFile)file).addImport(GoConstants.TESTING_PATH, null); } String paramType = getProperParamType(getTestingAlias(testingImportSpec), myType); signature .replace(GoElementFactory.createFunctionSignatureFromText(project, myType.getParamType().toLowerCase(Locale.US) + " " + paramType)); }
Source:
<code>public boolean validate(IOperationMonitor monitor) throws BugzillaRestException { RepositoryLocation location = getClient().getLocation(); <START> if (Boolean.parseBoolean(location.getProperty(IBugzillaRestConstants.REPOSITORY_USE_API_KEY))) { <END> UserCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY); if (credentials == null) { throw new IllegalStateException("Authentication requested without valid credentials"); } String url = MessageFormat.format("/valid_login?login={0}&api_key={1}", new Object[] { credentials.getUserName(), location.getProperty(IBugzillaRestConstants.REPOSITORY_API_KEY) }); BooleanResult response = new BugzillaRestUnauthenticatedGetRequest<BooleanResult>(client, url, new TypeToken<BooleanResult>() { }).run(monitor); return response.getResult(); } else { LoginToken validateResponse = new BugzillaRestLoginRequest(client).run(monitor); if (validateResponse != null && !Strings.isNullOrEmpty(validateResponse.getId())) { String url = MessageFormat.format("/logout?token={0}", new Object[] { validateResponse.getToken() }); new BugzillaRestUnauthenticatedGetRequest<BooleanResult>(client, url, new TypeToken<BooleanResult>() { }).run(monitor); return true; } } return false; }</code><technical_language>RepositoryLocation a getBooleanProperty method is nullsafe want</technical_language>

Target:
public boolean validate(IOperationMonitor monitor) throws BugzillaRestException { RepositoryLocation location = getClient().getLocation(); if (location.getBooleanPropery(IBugzillaRestConstants.REPOSITORY_USE_API_KEY)) { UserCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY); if (credentials == null) { throw new IllegalStateException("Authentication requested without valid credentials"); } String url = MessageFormat.format("/valid_login?login={0}&api_key={1}", new Object[] { credentials.getUserName(), location.getProperty(IBugzillaRestConstants.REPOSITORY_API_KEY) }); BooleanResult response = new BugzillaRestUnauthenticatedGetRequest<BooleanResult>(client, url, new TypeToken<BooleanResult>() { }).run(monitor); return response.getResult(); } else { LoginToken validateResponse = new BugzillaRestLoginRequest(client).run(monitor); if (validateResponse != null && !Strings.isNullOrEmpty(validateResponse.getId())) { String url = MessageFormat.format("/logout?token={0}", new Object[] { validateResponse.getToken() }); new BugzillaRestUnauthenticatedGetRequest<BooleanResult>(client, url, new TypeToken<BooleanResult>() { }).run(monitor); return true; } } return false; }
Source:
<code>public void setParameterExpressions(Map<String, String> parameterExpressions) { Map<String, Expression[]> paramExpressions = new HashMap<String, Expression[]>(parameterExpressions.size()); <START> for (String paramName : parameterExpressions.keySet()) { <END> String expression = parameterExpressions.get(paramName); Expression[] expressions = new Expression[] { PARSER.parseExpression(expression), PARSER.parseExpression("#root.![" + expression + "]") }; paramExpressions.put(paramName, expressions); } this.parameterExpressions = paramExpressions; }</code><technical_language>More efficient iterate entrySet()</technical_language>

Target:
public void setParameterExpressions(Map<String, String> parameterExpressions) { Map<String, Expression[]> paramExpressions = new HashMap<String, Expression[]>(parameterExpressions.size()); for (Map.Entry<String, String> entry : parameterExpressions.entrySet()) { String key = entry.getKey(); String expression = entry.getValue(); Expression[] expressions = new Expression[] { PARSER.parseExpression(expression), PARSER.parseExpression("#root.![" + expression + "]") }; paramExpressions.put(key, expressions); } this.parameterExpressions = paramExpressions; }
Source:
<code>public static void show(AppCompatActivity activity, Integer containerViewId, ObaStop stop, Callback callback) { FragmentManager fm = activity.getSupportFragmentManager(); SimpleArrivalListFragment fragment = new SimpleArrivalListFragment(); fragment.setObaStop(stop); Intent intent = new Intent(activity, SimpleArrivalListFragment.class); intent.setData(Uri.withAppendedPath(ObaContract.Stops.CONTENT_URI, stop.getId())); fragment.setArguments(FragmentUtils.getIntentArgs(intent)); fragment.setCallback(callback); try { FragmentTransaction ft = fm.beginTransaction(); ft.replace(containerViewId, fragment, TAG); ft.addToBackStack(null); ft.commit(); } catch (IllegalStateException e) { <START> Log.v("ArrivalListFragment", "Cannot show SimpleArrivalListFragment"); <END> } }</code><technical_language>@cagryInside change this error level logging move tag TAG variable? So: Log.e(TAG, "Cannot show SimpleArrivalListFragment"); ...and TAG declared SimpleArrivalListFragment in entry in Fragment</technical_language>

Target:
public static void show(AppCompatActivity activity, Integer containerViewId, ObaStop stop, Callback callback) { FragmentManager fm = activity.getSupportFragmentManager(); SimpleArrivalListFragment fragment = new SimpleArrivalListFragment(); fragment.setObaStop(stop); Intent intent = new Intent(activity, SimpleArrivalListFragment.class); intent.setData(Uri.withAppendedPath(ObaContract.Stops.CONTENT_URI, stop.getId())); fragment.setArguments(FragmentUtils.getIntentArgs(intent)); fragment.setCallback(callback); try { FragmentTransaction ft = fm.beginTransaction(); ft.replace(containerViewId, fragment, TAG); ft.addToBackStack(null); ft.commit(); } catch (IllegalStateException e) { Log.e(TAG, "Cannot show SimpleArrivalListFragment after onSaveInstanceState has been called"); } }