auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void runAutomated(AutomatedInstallData idata, IXMLElement panelRoot) throws InstallerException { IXMLElement locations = panelRoot.getFirstChildNamed(LOCATIONS_NODE_NAME); if (locations != null && locations.getContent() != null) { idata.setVariable(Unpacker.INSTALL_RT_LOCATIONS_VAR, locations.getContent()); } <START> String installPath = idata.getVariable("INSTALL_PATH"); <END> File folder = new File(installPath, P2DirectorStarterListener.DEVSTUDIO_LOCATION); Properties servers = (Properties) idata.getAttribute("AS_SERVERS"); if (servers == null || servers.isEmpty()) { servers = new Properties(); File runtimesFolder = new File (installPath, "runtimes"); RuntimePath runtimesPath = new RuntimePath(runtimesFolder.getAbsolutePath(), true); servers.put("server1", runtimesPath.toString()); } if (!folder.exists()) folder.mkdirs(); File file = new File(folder, "runtime_locations.properties"); FileOutputStream stream = null; try { stream = new FileOutputStream(file); servers.store(stream, null); stream.flush(); stream.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e1) { Debug.trace(e1); } } } }</code><technical_language>I sorry, suggestion wrong. I thought saving configuration specific additional runtimes, if runtime_locations.properties is saved means problem is in CreateLinkPane.java CreateLinkPanelAutomationHelper.java. added code is needed here. Instead method saves runtime_locations.properties moved CreateLinkPanel.java AutomationHelper static method, classes CreateLinkPane.java CreateLinkPanelAutomationHelper.java save configuration runtime_locations.properties runtime detection plugin</technical_language>

Target:
public void runAutomated(AutomatedInstallData idata, IXMLElement panelRoot) throws InstallerException { IXMLElement locations = panelRoot.getFirstChildNamed(LOCATIONS_NODE_NAME); if (locations != null && locations.getContent() != null) { idata.setVariable(Unpacker.INSTALL_RT_LOCATIONS_VAR, locations.getContent()); } }
Source:
<code><START> public MixedOperation<Route, RouteList, Resource<RouteRoute>> routes() { <END> return new RouteOperationsImpl(this.getHttpClient(), this.getConfiguration()); }</code><technical_language>That, subsequent right RouteRoute</technical_language>

Target:
public MixedOperation<Route, RouteList, Resource<Route>> routes() { return new RouteOperationsImpl(this.getHttpClient(), this.getConfiguration()); }
Source:
<code><START> public boolean compile(File dir) { <END> try { if (dir.equals(sourceDirectory)) { log.info("Running maven-compiler-plugin:compile"); runMojo("org.apache.maven.plugins:maven-compiler-plugin", "compile", null, null); log.info("Running maven-compiler-plugin:resources"); runMojo("org.apache.maven.plugins:maven-resources-plugin", "resources", null, null); } if (dir.equals(testSourceDirectory)) { log.info("Running maven-compiler-plugin:testCompile"); runMojo("org.apache.maven.plugins:maven-compiler-plugin", "testCompile", null, null); log.info("Running maven-compiler-plugin:testResources"); runMojo("org.apache.maven.plugins:maven-resources-plugin", "testResources", null, null); } return true; } catch (Exception e) { log.debug("Unable to compile", e); return false; } }</code><technical_language>Add Override annotation</technical_language>

Target:
public boolean compile(File dir) { try { if (dir.equals(sourceDirectory)) { log.info("Running maven-compiler-plugin:compile"); runMojo("org.apache.maven.plugins:maven-compiler-plugin", "compile", null, null); log.info("Running maven-compiler-plugin:resources"); runMojo("org.apache.maven.plugins:maven-resources-plugin", "resources", null, null); } if (dir.equals(testSourceDirectory)) { log.info("Running maven-compiler-plugin:testCompile"); runMojo("org.apache.maven.plugins:maven-compiler-plugin", "testCompile", null, null); log.info("Running maven-compiler-plugin:testResources"); runMojo("org.apache.maven.plugins:maven-resources-plugin", "testResources", null, null); } return true; } catch (MojoExecutionException e) { log.error("Unable to compile", e); return false; } }
Source:
<code><START> protected void firePropertyChange(int propertyId) { <END> if (multiEditorManager instanceof AbstractMultiPageSashEditor) ((AbstractMultiPageSashEditor) multiEditorManager).handlePropertyChange(propertyId); }</code><technical_language>call AbstractMultiPageSashEditor !! Instead, observer/observee pattern: SashWindowsContainer is observe, firing required event. AbstractMultiPageSashEditor observe for event, call required method</technical_language>

Target:
protected void firePropertyChange(int propertyId) { for(Object obj : propertyListeners.getListeners()) ((IPropertyListener)obj).handlePropertyChange(this, propertyId); }
Source:
<code><START> public Window<PublisherPush> getStream() { <END> return pushStreamIterator; }</code><technical_language>I PublisherStream.Window is clearer</technical_language>

Target:
public PublisherStream.Window getStream() { return pushStreamIterator; }
Source:
<code>public void testListStatusThrowsExceptionForUnreadableDir() throws Exception { assumePermissionsSupported(); Path testRootDir = getTestRootPath(fSys, "test/hadoop/dir"); Path obscuredDir = new Path(testRootDir, "foo"); Path subDir = new Path(obscuredDir, "bar"); fSys.mkdirs(subDir); fSys.setPermission(obscuredDir, new FsPermission((short)0)); try { <START> intercept(IOException.class, () -> <END> fSys.listStatus(obscuredDir)); } finally { fSys.setPermission(obscuredDir, new FsPermission((short)0755)); } }</code><technical_language>here, I permission check for listStatus [HdfsPermissionsGuide](<LINK_0></technical_language>

Target:
public void testListStatusThrowsExceptionForUnreadableDir() throws Exception { assumePermissionsSupported(); Path testRootDir = getTestRootPath(fSys, "test/hadoop/dir"); Path obscuredDir = new Path(testRootDir, "foo"); Path subDir = new Path(obscuredDir, "bar"); fSys.mkdirs(subDir); fSys.setPermission(obscuredDir, new FsPermission((short)0)); try { fSys.listStatus(obscuredDir); Assert.fail("Should throw IOException"); } catch (IOException ioe) { } finally { fSys.setPermission(obscuredDir, new FsPermission((short)0755)); } }
Source:
<code>public void setUp() { HttpServletRequest request = mock(HttpServletRequest.class); Map<String, String[]> params = new HashMap<String, String[]>(); params.put("account", new String[]{"Acme Co"}); params.put("name", new String[]{"Bill"}); when(request.getParameterMap()).thenReturn(params); when(request.getMethod()).thenReturn("PATCH"); when(request.getRequestURL()).thenReturn(new StringBuffer("/foo/bar")); when(request.getRequestURI()).thenReturn("/foo/bar"); when(request.getRemoteAddr()).thenReturn("12.0.4.57"); <START> Enumeration<String> headers = new Vector<String>( <END> Arrays.asList("Content-Type", "Content-Length", "X-Custom-Header")).elements(); when(request.getHeaderNames()).thenReturn(headers); when(request.getHeaders("Content-Type")).thenReturn( new Vector<String>(Collections.singletonList("application/json")).elements()); when(request.getHeaders("Content-Length")).thenReturn( new Vector<String>(Collections.singletonList("54")).elements()); when(request.getHeaders("X-Custom-Header")).thenReturn( new Vector<String>(Arrays.asList("some-data-1", "some-data-2")).elements()); ServletContext context = mock(ServletContext.class); BugsnagServletRequestListener listener = new BugsnagServletRequestListener(); listener.requestInitialized(new ServletRequestEvent(context, request)); }</code><technical_language>I a Vector is required a regular ArrayList some other Collection - I missed important</technical_language>

Target:
public void setUp() { HttpServletRequest request = mock(HttpServletRequest.class); Map<String, String[]> params = new HashMap<String, String[]>(); params.put("account", new String[]{"Acme Co"}); params.put("name", new String[]{"Bill"}); when(request.getParameterMap()).thenReturn(params); when(request.getMethod()).thenReturn("PATCH"); when(request.getRequestURL()).thenReturn(new StringBuffer("/foo/bar")); when(request.getRequestURI()).thenReturn("/foo/bar"); when(request.getRemoteAddr()).thenReturn("12.0.4.57"); when(request.getHeaderNames()).thenReturn( stringsToEnumeration( "Content-Type", "Content-Length", "X-Custom-Header", "Authorization")); when(request.getHeaders("Content-Type")).thenReturn( stringsToEnumeration("application/json")); when(request.getHeaders("Content-Length")).thenReturn( stringsToEnumeration("54")); when(request.getHeaders("X-Custom-Header")).thenReturn( stringsToEnumeration("some-data-1", "some-data-2")); when(request.getHeaders("Authorization")).thenReturn( stringsToEnumeration("Basic ABC123")); ServletContext context = mock(ServletContext.class); BugsnagServletRequestListener listener = new BugsnagServletRequestListener(); listener.requestInitialized(new ServletRequestEvent(context, request)); }
Source:
<code>@Override public OutputStream decorateLogger(AbstractBuild _ignore, final OutputStream logger) throws IOException, InterruptedException { final Pattern p = Pattern.compile(pattern.getPlainText()); return new LineTransformationOutputStream() { @Override protected void eol(byte[] b, int len) throws IOException { <START> Matcher m = p.matcher(new String(b, 0, len, Charsets.UTF_8)); <END> if (m.find()) { logger.write(m.replaceAll("****").getBytes(Charsets.UTF_8)); } else { logger.write(b, 0, len); } } }; }</code><technical_language>bug: this Run.getCharset. (As noted in <LINK_0>, is hard test realistically.)</technical_language>

Target:
@Override public OutputStream decorateLogger(AbstractBuild _ignore, final OutputStream logger) throws IOException, InterruptedException { final Pattern p = Pattern.compile(pattern.getPlainText()); return new LineTransformationOutputStream() { @Override protected void eol(byte[] b, int len) throws IOException { Matcher m = p.matcher(new String(b, 0, len, charsetName)); if (m.find()) { logger.write(m.replaceAll("****").getBytes(charsetName)); } else { logger.write(b, 0, len); } } }; }
Source:
<code>public void run() { long startTime = System.currentTimeMillis(); try { mimeMsg = mailSender.createMimeMessage(); msg = new MimeMessageHelper(mimeMsg, MimeMessageHelper.MULTIPART_MODE_MIXED); } catch (MessagingException e) { log.error("Failed to send email to " + userEmail + " for update " + importFile.getAbsolutePath(), e); } try { initializeXMLReader(); try { <START> getNextUpdate(); <END> log.info("Finished metadata import for objects in {}ms for user {}", new Object[] {objectCount, System.currentTimeMillis() - startTime, username}); sendCompletedEmail(updated, failed); } catch (XMLStreamException e) { log.info("Errors reading XML during update " + username, e); failed.put(importFile.getAbsolutePath(), "The import file contains XML errors"); sendValidationFailureEmail(failed); } } catch (UpdateException e) { failed.put(importFile.getAbsolutePath(), "Failed to read metadata update package for " + username); sendValidationFailureEmail(failed); } finally { close(); cleanup(); } }</code><technical_language>I this I worried job processing update. of renaming seekNextUpdate processUpdates? leave getNextUpdate out for time being</technical_language>

Target:
public void run() { long startTime = System.currentTimeMillis(); try { mimeMsg = mailSender.createMimeMessage(); msg = new MimeMessageHelper(mimeMsg, MimeMessageHelper.MULTIPART_MODE_MIXED); } catch (MessagingException e) { log.error("Failed to send email to " + userEmail + " for update " + importFile.getAbsolutePath(), e); } try { initializeXMLReader(); processUpdates(); log.info("Finished metadata import for objects in {}ms for user {}", new Object[] {objectCount, System.currentTimeMillis() - startTime, username}); sendCompletedEmail(updated, failed); } catch (UpdateException | XMLStreamException e) { log.info("Errors reading XML during update " + username, e); failed.put(importFile.getAbsolutePath(), "The import file contains XML errors"); sendValidationFailureEmail(failed); } finally { close(); cleanup(); } }
Source:
<code>private static String renderAxiomWithImpact( List<OWLAxiom> axioms, int impact, OWLObjectRenderer renderer, Map<OWLAxiom, Set<String>> associatedOntologyIds) { StringBuilder builder = new StringBuilder(); <START> builder.append("## Axioms used " + impact + " times" + "\n"); <END> for (OWLAxiom ax : axioms) { builder.append( "- " + renderer.render(ax) + " [" + String.join(",", associatedOntologyIds.get(ax)) + "]\n"); } builder.append("\n"); return builder.toString(); }</code><technical_language>String concats in StringBuilders chained builder calls (better performance): builder.append("## Axiom ").append(impact).append(" times\n");</technical_language>

Target:
private static String renderAxiomWithImpact( List<OWLAxiom> axioms, int impact, OWLObjectRenderer renderer, Map<OWLAxiom, Set<String>> associatedOntologyIds) { StringBuilder builder = new StringBuilder(); builder.append("## Axioms used ").append(impact).append(" times").append("\n"); for (OWLAxiom ax : axioms) { builder.append("- ").append(renderer.render(ax)).append(" [").append(String.join(",", associatedOntologyIds.get(ax))).append("]\n"); } builder.append("\n"); return builder.toString(); }
Source:
<code>private static PlanFragment createTableScanPlanFragment(String name) { Symbol symbol = new Symbol("column"); PlanNode planNode = new TableScanNode( new PlanNodeId(name), new TableHandle( new ConnectorId("test"), new TestingTableHandle(), TestingTransactionHandle.create(), <START> Optional.of(TestingHandle.INSTANCE)), <END> ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column"))); return createFragment(planNode); }</code><technical_language>here, Optional.empty()</technical_language>

Target:
private static PlanFragment createTableScanPlanFragment(String name) { Symbol symbol = new Symbol("column"); PlanNode planNode = new TableScanNode( new PlanNodeId(name), new TableHandle( new ConnectorId("test"), new TestingTableHandle(), TestingTransactionHandle.create(), Optional.empty()), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column"))); return createFragment(planNode); }
Source:
<code>public void onDamaged(OnDamagedEvent event, EntityRef entity) { <START> Prefab particleEffectPrefab = prefabManager.getPrefab("LightAndShadowResources:cardParticleEffect"); <END> for (Component c : particleEffectPrefab.iterateComponents()) { entity.addComponent(c); } audioManager.playSound(Assets.getSound("engine:Dig").get(), 1.0f); }</code><technical_language>More update particle texture this a utility function. entity.AddAllComponents(Prefab prefab) some static method a Particle class addEffects(Prefab effectsPrefab, EntityRef targetEntityRef) If supported ES level more of a TODO for adding extracted gestalt-entity-system however. a note - long this is for adding particle effects in new system</technical_language>

Target:
public void onDamaged(OnDamagedEvent event, EntityRef entity) { ParticleEmitterComponent emitter = entity.getComponent(ParticleEmitterComponent.class); emitter.particleSpawnsLeft = emitter.maxParticles; entity.saveComponent(emitter); audioManager.playSound(Assets.getSound("engine:Dig").get(), 1.0f); logger.info("current health: {}", entity.getComponent(HealthComponent.class).currentHealth); }
Source:
<code>public void transform(KeyValue<LongWritable, Object> input, Emitter<StructuredRecord> emitter) throws Exception { Map<String, String> xmlRecord = (Map<String, String>) input.getValue(); String fileName = ""; String record = ""; for (String key : xmlRecord.keySet()) { fileName = key; record = xmlRecord.get(key); } StructuredRecord output = StructuredRecord.builder(DEFAULT_XML_SCHEMA) .set("offset", input.getKey().get()) <START> .set("fileName", fileName) <END> .set("record", record) .build(); emitter.emit(output); }</code><technical_language>filename</technical_language>

Target:
public void transform(KeyValue<LongWritable, Object> input, Emitter<StructuredRecord> emitter) throws Exception { Map<String, String> xmlRecord = (Map<String, String>) input.getValue(); Set<String> keySet = xmlRecord.keySet(); Iterator<String> itr = keySet.iterator(); String fileName = Iterators.getOnlyElement(itr); String record = xmlRecord.get(fileName); StructuredRecord output = StructuredRecord.builder(DEFAULT_XML_SCHEMA) .set("offset", input.getKey().get()) .set("filename", fileName) .set("record", record) .build(); emitter.emit(output); }
Source:
<code>private synchronized void createGroupIfNecessary(SelectionContext<C> context, Executor executor) { ResourceGroupId id = context.getResourceGroupId(); if (!groups.containsKey(id)) { InternalResourceGroup group; if (id.getParent().isPresent()) { createGroupIfNecessary(new SelectionContext<>(id.getParent().get(), context.getContext()), executor); InternalResourceGroup parent = groups.get(id.getParent().get()); requireNonNull(parent, "parent is null"); int subGroupSegmentIndex = parent.getId().getSegments().size(); <START> group = parent.getOrCreateSubGroup(id.getLastSegment(), (context.getFirstDynamicSegmentPosition().equals(OptionalInt.of(subGroupSegmentIndex)))); <END> } else { RootInternalResourceGroup root = new RootInternalResourceGroup(id.getSegments().get(0), this::exportGroup, executor); group = root; rootGroups.add(root); } configurationManager.get().configure(group, context); checkState(groups.put(id, group) == null, "Unexpected existing resource group"); } }</code><technical_language>i this logic works identify resource group is static not. a cleaner be, if mark segment of ResourceGroupId static create group.expandTemplate call, easily put flag here. need rely context. i.e. this line this group = parent.getOrCreateSubGroup(id.getLastSegment().getValue(), id.getLastSegment().isStatic()); i this happen, need change segments in ResourceGroupId class string a class Segment this: class Segment { String value; String isStatic; }</technical_language>

Target:
private synchronized void createGroupIfNecessary(SelectionContext<C> context, Executor executor) { ResourceGroupId id = context.getResourceGroupId(); if (!groups.containsKey(id)) { InternalResourceGroup group; if (id.getParent().isPresent()) { createGroupIfNecessary(new SelectionContext<>(id.getParent().get(), context.getContext()), executor); InternalResourceGroup parent = groups.get(id.getParent().get()); requireNonNull(parent, "parent is null"); int subGroupSegmentIndex = parent.getId().getSegments().size(); group = parent.getOrCreateSubGroup(id.getLastSegment(), !context.getFirstDynamicSegmentPosition().equals(OptionalInt.of(subGroupSegmentIndex))); } else { RootInternalResourceGroup root = new RootInternalResourceGroup(id.getSegments().get(0), this::exportGroup, executor); group = root; rootGroups.add(root); } configurationManager.get().configure(group, context); checkState(groups.put(id, group) == null, "Unexpected existing resource group"); } }
Source:
<code>public Response work2(@HeaderParam(LRA_HTTP_HEADER) String lraId) throws NotFoundException { if (lraId != null) { return Response.status(Response.Status.PRECONDITION_FAILED).entity(Entity.text("Unexpected LRA context")).build(); } <START> WebTarget resourcePath = ClientBuilder.newClient().target(context.getBaseUri()).path(ACTIVITIES_PATH).path("nestedActivity"); <END> Response response = resourcePath.request().put(Entity.text("")); String id = null; if (response.hasEntity()) id = response.readEntity(String.class); if (id == null) { return Response.status(Response.Status.PRECONDITION_FAILED).entity(Entity.text("LRA context was not propagated")).build(); } return Response.ok().build(); }</code><technical_language>I assuming nestedActivity is defined in project</technical_language>

Target:
public Response work2(@HeaderParam(LRA_HTTP_HEADER) String lraId) throws NotFoundException { if (lraId != null) { return Response.status(Response.Status.PRECONDITION_FAILED).entity(Entity.text("Unexpected LRA context")).build(); } WebTarget resourcePath = ClientBuilder.newClient().target(context.getBaseUri()) .path(ACTIVITIES_PATH) .path(ActivityController.MANDATORY_LRA_RESOURCE_PATH); Response response = resourcePath.request().put(Entity.text("")); String id = checkStatusAndClose(response, Response.Status.OK.getStatusCode(), true, resourcePath); if (id == null) { return Response.status(Response.Status.PRECONDITION_FAILED).entity(Entity.text("LRA context was not propagated")).build(); } return Response.ok().build(); }
Source:
<code>public void verifyBioAndHireable() throws IOException { GHUser u = gitHub.getUser("GitHub"); assertNotNull(u.getBio()); <START> assertNotNull(u.isHireable()); <END> }</code><technical_language>boolean is null. Please find a user is true</technical_language>

Target:
public void verifyBioAndHireable() throws IOException { GHUser u = gitHub.getUser("Chew"); assertThat(u.getBio(), equalTo("I like to program things and I hope to program something cool one day :D")); assertTrue(u.isHireable()); assertNotNull(u.getTwitterUsername()); }
Source:
<code>public static String deleteProtocolPrefixIfExist(String url) { if (url.matches("^\\w+://.*")) { return url.split(" } <START> return url; <END> }</code><technical_language>return url.replaceFirst("^\\w+://", "");</technical_language>

Target:
public static String deleteProtocolPrefixIfExist(String url) { return url.replaceFirst("^\\w+://", ""); }
Source:
<code>public void testSamePublicAndPrivateAddressAcrossNodes() { <START> Node node1 = Node.newDefaultNode("foo1", "host1").setNodeGroupPort(9410).setNodePublicHostname("host2").setNodePublicPort(9410); <END> Node node2 = Node.newDefaultNode("foo2", "host2").setNodeGroupPort(9410).setNodePublicHostname("host1").setNodePublicPort(9410); new ClusterValidator(newDefaultCluster(new Stripe(node1, node2))).validate(); }</code><technical_language>nodePort, nodeGroupPort</technical_language>

Target:
public void testSamePublicAndPrivateAddressAcrossNodes() { Node node1 = Node.newDefaultNode("foo1", "host1").setNodePort(9410).setNodePublicHostname("host2").setNodePublicPort(9410); Node node2 = Node.newDefaultNode("foo2", "host2").setNodePort(9410).setNodePublicHostname("host1").setNodePublicPort(9410); new ClusterValidator(newDefaultCluster(new Stripe(node1, node2))).validate(); }
Source:
<code>public KeenProject(String projectId, String writeKey, String readKey, String masterKey) { <START> if (projectId == null || projectId.trim().isEmpty()) { <END> throw new IllegalArgumentException("Invalid project id specified: " + projectId); } this.projectId = projectId; this.writeKey = writeKey; this.readKey = readKey; this.masterKey = masterKey; }</code><technical_language>Do care do sort of key validation here? Is done already</technical_language>

Target:
public KeenProject(String projectId, String writeKey, String readKey, String masterKey) { if (null == projectId || projectId.trim().isEmpty()) { throw new IllegalArgumentException("Invalid project id specified: " + projectId); } if ((null == writeKey || writeKey.trim().isEmpty()) && (null == readKey || readKey.trim().isEmpty()) && (null == masterKey || masterKey.trim().isEmpty())) { throw new IllegalArgumentException("At least one of the keys given must be non-null " + "and non-empty."); } this.projectId = projectId; this.writeKey = writeKey; this.readKey = readKey; this.masterKey = masterKey; }
Source:
<code>public void testSimpleSpatialAnnotationOnClassLevel() throws Exception { SimpleHotel hotel = new SimpleHotel( 1, "Plazza Athénée", 24.0d, 32.0d, "Luxurious" ); FullTextSession fullTextSession = Search.getFullTextSession( openSession() ); Transaction tx = fullTextSession.beginTransaction(); fullTextSession.save( hotel ); tx.commit(); tx = fullTextSession.beginTransaction(); double centerLatitude= 24; double centerLongitude= 31.5; <START> QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( SimpleHotel.class ).get(); <END> org.apache.lucene.search.Query luceneQuery = SpatialQueryBuilder.buildSimpleSpatialQuery( centerLatitude, centerLongitude, 50 ); org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery( luceneQuery, SimpleHotel.class ); List results = hibQuery.list(); Assert.assertEquals( 0, results.size() ); org.apache.lucene.search.Query luceneQuery2 = SpatialQueryBuilder.buildSimpleSpatialQuery( centerLatitude, centerLongitude, 51 ); org.hibernate.Query hibQuery2 = fullTextSession.createFullTextQuery( luceneQuery2, SimpleHotel.class ); List results2 = hibQuery2.list(); Assert.assertEquals( 1, results2.size() ); List<?> events = fullTextSession.createQuery( "from " + SimpleHotel.class.getName() ).list(); for (Object entity : events) { fullTextSession.delete( entity ); } tx.commit(); fullTextSession.close(); }</code><technical_language>This queryBuilder is used</technical_language>

Target:
public void testSimpleSpatialAnnotationOnClassLevel() throws Exception { SimpleHotel hotel = new SimpleHotel( 1, "Plazza Athénée", 24.0d, 32.0d, "Luxurious" ); FullTextSession fullTextSession = Search.getFullTextSession( openSession() ); Transaction tx = fullTextSession.beginTransaction(); fullTextSession.save( hotel ); tx.commit(); tx = fullTextSession.beginTransaction(); double centerLatitude= 24; double centerLongitude= 31.5; org.apache.lucene.search.Query luceneQuery = SpatialQueryBuilder.buildSimpleSpatialQuery( centerLatitude, centerLongitude, 50 ); org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery( luceneQuery, SimpleHotel.class ); List results = hibQuery.list(); Assert.assertEquals( 0, results.size() ); org.apache.lucene.search.Query luceneQuery2 = SpatialQueryBuilder.buildSimpleSpatialQuery( centerLatitude, centerLongitude, 51 ); org.hibernate.Query hibQuery2 = fullTextSession.createFullTextQuery( luceneQuery2, SimpleHotel.class ); List results2 = hibQuery2.list(); Assert.assertEquals( 1, results2.size() ); List<?> events = fullTextSession.createQuery( "from " + SimpleHotel.class.getName() ).list(); for (Object entity : events) { fullTextSession.delete( entity ); } tx.commit(); fullTextSession.close(); }
Source:
<code>public JsonObject getAllLoggers() { accessControl(Group.managers()); <START> return Holder.getAllLoggers(); <END> }</code><technical_language>This work properly, invoking method Holder initialize it, SLF4J backend is Logback, initialization for fail. such, this fallback done here</technical_language>

Target:
public JsonObject getAllLoggers() { accessControl(Group.managers()); if (available) { return Holder.getAllLoggers(); } JsonObject empty = new JsonObject(); empty.add("loggers", new JsonArray()); return empty; }
Source:
<code>public List<Long> getBytesList(String path) { return getMemorySizeList(path).stream() <START> .map(ConfigMemorySize::toBytes) <END> .collect(Collectors.toList()); }</code><technical_language>changed ConfigException.BadValue IllegalArgumentException I think; a toBytes takes origin/path solve</technical_language>

Target:
public List<Long> getBytesList(String path) { ConfigValue v = find(path, ConfigValueType.LIST); return getBytesListBigInteger(path).stream() .map(bytes -> toLong(bytes, v.origin(), path)) .collect(Collectors.toList()); }
Source:
<code>private void performBackup() throws IOException { String backupFileName = PREFIX + DateTime.now().toString("yyyy-MM-dd'T'HH:mm") + ".zip"; <START> File backupFile = new File(destination, backupFileName); <END> LOGGER.info("Performing backup to " + backupFile); String schedulerHome = ClasspathUtils.findSchedulerHome(); String[] foldersToZip = targets.stream() .map(target -> (new File(schedulerHome, target)).getAbsolutePath()) .toArray(String[]::new); ZipUtils.zip(foldersToZip, backupFile, null); }</code><technical_language>destination accept absolute relative paths (in case relative scheduler home current folder)</technical_language>

Target:
private void performBackup() throws IOException { String backupFileName = PREFIX + DateTime.now().toString("yyyy-MM-dd'T'HH-mm") + ".zip"; File destinationFolder = new File(destination); if (!destinationFolder.isAbsolute()) { destinationFolder = new File(PASchedulerProperties.SCHEDULER_HOME.getValueAsString(), destination); } if (destinationFolder.exists() && destinationFolder.isDirectory() && destinationFolder.canWrite()) { File backupFile = new File(destination, backupFileName); LOGGER.info("Performing backup to " + backupFile); String[] foldersToZip = targets.stream() .map(target -> (new File(PASchedulerProperties.SCHEDULER_HOME.getValueAsString(), target)).getAbsolutePath()) .toArray(String[]::new); ZipUtils.zip(foldersToZip, backupFile, null); } else { LOGGER.error("Cannot save a backup because backup destination folder does not exist: " + destination); } }
Source:
<code><START> void givenGraphQuery_whenListEvents_thenReturnAllEvents() { <END> Map<String, Object> requestBody = new HashMap<>(); requestBody.put("query", "query ListEvents { listEvents { items { id name where when description } } }"); requestBody.put("variables", ""); requestBody.put("operationName", "ListEvents"); String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody) .bodyToMono(String.class).block(); assertNotNull(bodyString); assertTrue(bodyString.contains("My First Event")); assertTrue(bodyString.contains("where")); assertTrue(bodyString.contains("when")); }</code><technical_language>Indentations 4 spaces</technical_language>

Target:
void givenGraphQuery_whenListEvents_thenReturnAllEvents() { Map<String, Object> requestBody = new HashMap<>(); requestBody.put("query", "query ListEvents {" + " listEvents {" + " items {" + " id" + " name" + " where" + " when" + " description" + " }" + " }" + "}"); requestBody.put("variables", ""); requestBody.put("operationName", "ListEvents"); String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody) .bodyToMono(String.class).block(); assertNotNull(bodyString); assertTrue(bodyString.contains("My First Event")); assertTrue(bodyString.contains("where")); assertTrue(bodyString.contains("when")); }
Source:
<code>public Statement apply(Statement base, Description description) { KuduClusterTestContext testContext = description.getAnnotation(KuduClusterTestContext.class); String masterHostsValue = System.getProperty(KUDU_MASTER_HOSTS_STRING_ENV); boolean runThisTest = true; if ( testContext != null) { if ((masterHostsValue != null) && (testContext.kuduClusterBasedTest())) { runThisTest = true; } if ((masterHostsValue != null) && (!testContext.kuduClusterBasedTest())) { runThisTest = false; } if ((masterHostsValue == null) && (testContext.kuduClusterBasedTest())) { runThisTest = false; } if ((masterHostsValue == null) && (!testContext.kuduClusterBasedTest())) { runThisTest = true; } } if (runThisTest) { if ((testContext != null ) && (testContext.kuduClusterBasedTest())) { try { initRealKuduClusterSetup(masterHostsValue); } catch (Exception e) { <START> LOG.error(e.getMessage(), e); <END> } } else { try { KuduInputOperatorCommons.initCommonConfigsForAllTypesOfTests(); } catch (Exception e) { LOG.error(e.getMessage(),e); } } return base; } else { return new Statement() { @Override public void evaluate() throws Throwable { } }; } }</code><technical_language>LOG.error? If is a real problem, propagate exception</technical_language>

Target:
public Statement apply(Statement base, Description description) { KuduClusterTestContext testContext = description.getAnnotation(KuduClusterTestContext.class); String masterHostsValue = System.getProperty(KUDU_MASTER_HOSTS_STRING_ENV); boolean runThisTest = true; if ( testContext != null) { if ((masterHostsValue != null) && (testContext.kuduClusterBasedTest())) { runThisTest = true; } if ((masterHostsValue != null) && (!testContext.kuduClusterBasedTest())) { runThisTest = false; } if ((masterHostsValue == null) && (testContext.kuduClusterBasedTest())) { runThisTest = false; } if ((masterHostsValue == null) && (!testContext.kuduClusterBasedTest())) { runThisTest = true; } } if (runThisTest) { if ((testContext != null ) && (testContext.kuduClusterBasedTest())) { try { initRealKuduClusterSetup(masterHostsValue); } catch (Exception e) { throw new RuntimeException("Not able to initialize kudu cluster",e); } } else { try { KuduInputOperatorCommons.initCommonConfigsForAllTypesOfTests(); } catch (Exception e) { throw new RuntimeException("Could not initialize commn configs required for Kudu cluster connectivity",e); } } return base; } else { return new Statement() { @Override public void evaluate() throws Throwable { } }; } }
Source:
<code>public static Boolean stSphericalContains(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice left, @SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice right) { OGCGeometry leftGeometry = deserialize(left); if (leftGeometry.isEmpty()) { <START> return null; <END> } OGCGeometry rightGeometry = deserialize(right); if (rightGeometry.isEmpty()) { return null; } validateSphericalType("ST_Contains", leftGeometry, EnumSet.of(POLYGON)); validateSphericalType("ST_Contains", rightGeometry, EnumSet.of(POINT)); Polygon polygon = (Polygon) leftGeometry.getEsriGeometry(); Point point = (Point) rightGeometry.getEsriGeometry(); if (point.getY() == MAX_LATITUDE || point.getY() == MIN_LATITUDE) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "When applied to SphericalGeography inputs, ST_Contains only supports points which are not poles."); } if (containsEitherPole(polygon)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "When applied to SphericalGeography inputs, ST_Contains only supports polygons which do not enclose poles."); } int k = getNumberIntersectionsWithPolygon(polygon, point); if (k % 2 == 1) { return true; } else { return false; } }</code><technical_language>Empty geometries geometries points; null geometries. Empty geometries do anything: is "point of interior of left". do satisfy condition in docstring, this return false</technical_language>

Target:
public static Boolean stSphericalContains(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice left, @SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice right) { OGCGeometry leftGeometry = deserialize(left); if (leftGeometry.isEmpty()) { return false; } OGCGeometry rightGeometry = deserialize(right); if (rightGeometry.isEmpty()) { return false; } validateSphericalType("ST_Contains", leftGeometry, EnumSet.of(POLYGON)); validateSphericalType("ST_Contains", rightGeometry, EnumSet.of(POINT)); Polygon polygon = (Polygon) leftGeometry.getEsriGeometry(); Point point = (Point) rightGeometry.getEsriGeometry(); if (point.getY() == MAX_LATITUDE || point.getY() == MIN_LATITUDE) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "When applied to SphericalGeography inputs, ST_Contains only supports points which are not poles."); } if (SphericalCalculator.containsPole(polygon)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "When applied to SphericalGeography inputs, ST_Contains only supports polygons which do not enclose poles."); } return contains(polygon, point); }
Source:
<code>@Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double rowCount = mq.getRowCount(getInput()); double bytesPerRow = getRowType().getFieldCount() * IgniteCost.AVERAGE_FIELD_SIZE; double totalBytes = rowCount * bytesPerRow; IgniteCostFactory costFactory = (IgniteCostFactory)planner.getCostFactory(); if (RelDistributions.BROADCAST_DISTRIBUTED.equals(distribution)) totalBytes *= 5; <START> return costFactory.makeCost(rowCount, rowCount * IgniteCost.ROW_PASS_THROUGH_COST, 0D, 0D, totalBytes); <END> }</code><technical_language>case notation more frequent 0d, u of course</technical_language>

Target:
@Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double rowCount = mq.getRowCount(getInput()); double bytesPerRow = getRowType().getFieldCount() * IgniteCost.AVERAGE_FIELD_SIZE; double totalBytes = rowCount * bytesPerRow; IgniteCostFactory costFactory = (IgniteCostFactory)planner.getCostFactory(); if (RelDistributions.BROADCAST_DISTRIBUTED.equals(distribution)) totalBytes *= IgniteCost.BROADCAST_DISTRIBUTION_PENALTY; return costFactory.makeCost(rowCount, rowCount * IgniteCost.ROW_PASS_THROUGH_COST, 0, 0, totalBytes); }
Source:
<code><START> public void validateTicketFromInvalid() { <END> Ticket ticket = persistTicket(); ticket.setValid(false); testEntityManager.persist(ticket); assertEquals(false, ticket.isValid()); ticketService.validateTicket(ticket.getId()); assertEquals(true, ticket.isValid()); }</code><technical_language>Test name changed validateTicket, this is 'base' test. A more test a more specific name</technical_language>

Target:
public void validateTicketFromInvalid() { Ticket ticket = persistTicket(); ticket.setValid(false); ticket = testEntityManager.persist(ticket); assertEquals(false, ticket.isValid()); ticketService.validateTicket(ticket.getId()); assertEquals(true, testEntityManager.find(Ticket.class, ticket.getId()).isValid()); }
Source:
<code>public static Expression combineConjuncts(Collection<Expression> expressions) { requireNonNull(expressions, "expressions is null"); List<Expression> conjuncts = expressions.stream() <START> .flatMap(e -> ExpressionUtils.extractConjuncts(e).stream()) <END> .filter(e -> !e.equals(TRUE_LITERAL)) .collect(toList()); conjuncts = removeDuplicates(conjuncts); if (conjuncts.contains(FALSE_LITERAL)) { return FALSE_LITERAL; } return conjuncts.isEmpty() ? TRUE_LITERAL : and(conjuncts); }</code><technical_language>for combineDisjuncts</technical_language>

Target:
public static Expression combineConjuncts(Collection<Expression> expressions) { requireNonNull(expressions, "expressions is null"); List<Expression> conjuncts = expressions.stream() .flatMap(e -> ExpressionUtils.extractConjuncts(e).stream()) .filter(e -> !e.equals(TRUE_LITERAL)) .collect(toList()); conjuncts = removeDuplicates(conjuncts); if (conjuncts.contains(FALSE_LITERAL)) { return FALSE_LITERAL; } return and(conjuncts); }
Source:
<code>private File getMinishiftBinary(File root) { <START> return new File(root, "minishift"); <END> }</code><technical_language>extract a constant increases visibility for this hard-coded value</technical_language>

Target:
private File getMinishiftBinary(File root) { return new File(root, MINISHIFT); }
Source:
<code>private boolean isStackOrClusterDrStatusComplete(Status status) { <START> return (Status.BACKUP_FINISHED.equals(status) || Status.RESTORE_FINISHED.equals(status)) ? true : false; <END> }</code><technical_language>return Status.BACKUP_FINISHED.equals(status) || Status.RESTORE_FINISHED.equals(status);</technical_language>

Target:
private boolean isStackOrClusterDrStatusComplete(Status status) { return Status.AVAILABLE.equals(status); }
Source:
<code>public ParseTexResultViewModel(TexBibEntriesResolverResult resolverResult, BibDatabaseContext databaseContext) { this.resolverResult = resolverResult; this.databaseContext = databaseContext; this.referenceList = FXCollections.observableArrayList(); this.citationList = FXCollections.observableArrayList(); Set<String> newEntryKeys = resolverResult.getNewEntries().stream().map(entry -> entry.getCiteKeyOptional().orElse("")).collect(Collectors.toSet()); <START> resolverResult.getCitations().asMap().forEach((entry, citations) -> <END> referenceList.add(new ReferenceViewModel(entry, newEntryKeys.contains(entry), citations))); this.importButtonDisabled = new SimpleBooleanProperty(referenceList.stream().noneMatch(ReferenceViewModel::isHighlighted)); }</code><technical_language>Please extract for loop a separate school for loop, read</technical_language>

Target:
public ParseTexResultViewModel(TexBibEntriesResolverResult resolverResult, BibDatabaseContext databaseContext) { this.resolverResult = resolverResult; this.databaseContext = databaseContext; this.referenceList = FXCollections.observableArrayList(); this.citationList = FXCollections.observableArrayList(); Set<String> newEntryKeys = resolverResult.getNewEntries().stream().map(entry -> entry.getCiteKeyOptional().orElse("")).collect(Collectors.toSet()); for (Map.Entry<String, Collection<Citation>> entry : resolverResult.getCitations().asMap().entrySet()) { String key = entry.getKey(); referenceList.add(new ReferenceViewModel(key, newEntryKeys.contains(key), entry.getValue())); } this.importButtonDisabled = new SimpleBooleanProperty(referenceList.stream().noneMatch(ReferenceViewModel::isHighlighted)); }
Source:
<code>public String render(final GetCacheStateResult obj) throws JsonProcessingException { final CommonJsonView view = CommonJsonView.newView(CommonJsonView.Status.OK); final List<CacheFilesystemInformation> cacheFilesystemInfo = obj.getResult(); <START> if( (cacheFilesystemInfo == null) || (cacheFilesystemInfo.size() < 1)){ <END> return "No valid Cache Filesystems on remote appliance"; } return JsonMapper.toJson(view.data(cacheFilesystemInfo)); }</code><technical_language>a null guard instead</technical_language>

Target:
public String render(final GetCacheStateResult obj) throws JsonProcessingException { final CommonJsonView view = CommonJsonView.newView(CommonJsonView.Status.OK); final List<CacheFilesystemInformation> cacheFilesystemInfo = obj.getResult(); if(Guard.isNullOrEmpty(cacheFilesystemInfo)){ return "No valid Cache Filesystems on remote appliance"; } return JsonMapper.toJson(view.data(cacheFilesystemInfo)); }
Source:
<code>private static Stream<AssignmentExpressionTree> usageInAssignment(IdentifierTree usage) { Tree parent = usage.parent(); while (parent != null && !parent.is(Tree.Kind.ASSIGNMENT)) { parent = parent.parent(); } if (parent == null) { return Stream.empty(); } AssignmentExpressionTree assignment = (AssignmentExpressionTree) parent; <START> if (ExpressionUtils.skipParentheses(assignment.variable()).equals(usage)) { <END> return Stream.of(assignment); } return Stream.empty(); }</code><technical_language>This work if assignment is done member access: this.myField = new CopyOnWriteArrayList<String>(); While parents, check that, coming variable() side of assignment, expression() side. Checking for IdentifierTree is precise enough, need check for later. starting point</technical_language>

Target:
private static Stream<AssignmentExpressionTree> usageInAssignment(IdentifierTree usage) { Tree prevParent = usage; Tree parent = usage.parent(); while (parent != null && !parent.is(Tree.Kind.ASSIGNMENT) && parent.is(Tree.Kind.MEMBER_SELECT, Tree.Kind.IDENTIFIER)) { prevParent = parent; parent = parent.parent(); } if (parent != null && parent.is(Tree.Kind.ASSIGNMENT)) { AssignmentExpressionTree assignment = (AssignmentExpressionTree) parent; if (assignment.variable().equals(prevParent)) { return Stream.of(assignment); } } return Stream.empty(); }
Source:
<code>private BuildCommand sync(String workingDir, String revision) { <START> return exec("p4", "-d", workingDir, "sync", "@" + parseLong(revision)); <END> }</code><technical_language>Based directory is cleaned, etc. a [different sync happening](<LINK_0></technical_language>

Target:
private BuildCommand sync(String workingDir, String revision) { return exec("p4", "-d", workingDir, "sync", "-f", "@" + parseLong(revision)).setCommandEnvVars(envVars()); }
Source:
<code>protected void executeQueryCommand() { Set<AdditionalClusterFeature> <START> clusterFeaturesList = <END> getDbFacade().getClusterFeatureDao() .getClusterFeaturesForVersionAndCategory(getParameters().getVersion().getValue(), getParameters().getCategory()); getQueryReturnValue().setReturnValue(clusterFeaturesList); }</code><technical_language>List part of name. clusterFeatures is enough</technical_language>

Target:
protected void executeQueryCommand() { Set<AdditionalClusterFeature> additionalClusterFeatures = clusterFeatureDao.getClusterFeaturesForVersionAndCategory(getParameters().getVersion().getValue(), getParameters().getCategory()); getQueryReturnValue().setReturnValue(additionalClusterFeatures); }
Source:
<code>public void registerAttributes(ManagementResourceRegistration registry) { for (AttributeDefinition attr : ATTRIBUTES) { <START> registry.registerReadWriteAttribute(attr, null, new ReloadRequiredWriteAttributeHandler(ATTRIBUTES)); <END> } for (AttributeDefinition attr : READONLY_ATTRIBUTES) { registry.registerReadOnlyAttribute(attr, JMSBridgeHandler.INSTANCE); } }</code><technical_language>move out of loop</technical_language>

Target:
public void registerAttributes(ManagementResourceRegistration registry) { ReloadRequiredWriteAttributeHandler reloadRequiredWriteAttributeHandler = new ReloadRequiredWriteAttributeHandler(ATTRIBUTES); for (AttributeDefinition attr : ATTRIBUTES) { registry.registerReadWriteAttribute(attr, null, reloadRequiredWriteAttributeHandler); } for (AttributeDefinition attr : READONLY_ATTRIBUTES) { registry.registerReadOnlyAttribute(attr, JMSBridgeHandler.INSTANCE); } }
Source:
<code>public static void GetTemplateListByDataCenter(AsyncQuery aQuery, Guid dataCenterId) { aQuery.converterCallback = new IAsyncConverter() { <START> @Override <END> public Object Convert(Object source, AsyncQuery _asyncQuery) { ArrayList<VmTemplate> list = new ArrayList<VmTemplate>(); if (source != null) { VmTemplate blankTemplate = null; for (VmTemplate template : (ArrayList<VmTemplate>) source) { if (template.getId().equals(Guid.Empty)) { blankTemplate = template; } else if (template.getstatus() == VmTemplateStatus.OK) { list.add(template); } } Collections.sort(list, new Linq.VmTemplateByNameComparer()); if (blankTemplate != null) { list.add(0, blankTemplate); } } return list; } }; Frontend.RunQuery(VdcQueryType.GetVmTemplatesByStoragePoolId, new GetVmTemplatesByStoragePoolIdParameters(dataCenterId), aQuery); }</code><technical_language>convert code repeats in calls - consider extracting a helper method/class</technical_language>

Target:
public static void GetTemplateListByDataCenter(AsyncQuery aQuery, Guid dataCenterId) { aQuery.converterCallback = new TemplateConverter(); Frontend.RunQuery(VdcQueryType.GetVmTemplatesByStoragePoolId, new GetVmTemplatesByStoragePoolIdParameters(dataCenterId), aQuery); }
Source:
<code>public ReplicaList filter(Predicate<Replica> predicate) { ArrayList<Replica> newReplicaList = new ArrayList<>(size()); <START> for (Replica replica: replicaList) <END> { if (predicate.test(replica)) { newReplicaList.add(replica); } } return new ReplicaList(newReplicaList); }</code><technical_language>Iterate index iterator</technical_language>

Target:
public ReplicaList filter(Predicate<Replica> predicate) { ArrayList<Replica> newReplicaList = size() < 10 ? new ArrayList<>(size()) : new ArrayList<>(); for (int i=0; i<size(); i++) { Replica replica = replicaList.get(i); if (predicate.test(replica)) { newReplicaList.add(replica); } } return new ReplicaList(newReplicaList); }
Source:
<code>public static String getString(String key, String def) { String value = System.getProperty(key); if (value != null) { if (LOGGER.isLoggable(Level.INFO)) { <START> LOGGER.log(Level.INFO, "Property (system): {0} => {1}", new Object[] {key, value}); <END> } } else if (theContext != null) { value = theContext.getInitParameter(key); if (value != null) { if(LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Property (context): {0} => {1}", new Object[] {key, value}); } } } if (value == null) { value = def; if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Property (default): {0} => {1}", new Object[] {key, value}); } } return value; }</code><technical_language>Logging sense for static properties, initialized Jenkins log writers</technical_language>

Target:
public static String getString(String key, String def) { String value = System.getProperty(key); if (value != null) { if (LOGGER.isLoggable(Level.CONFIG)) { LOGGER.log(Level.CONFIG, "Property (system): {0} => {1}", new Object[] {key, value}); } } else if (theContext != null) { value = theContext.getInitParameter(key); if (value != null) { if(LOGGER.isLoggable(Level.CONFIG)) { LOGGER.log(Level.CONFIG, "Property (context): {0} => {1}", new Object[] {key, value}); } } } if (value == null) { value = def; if (LOGGER.isLoggable(Level.CONFIG)) { LOGGER.log(Level.CONFIG, "Property (default): {0} => {1}", new Object[] {key, value}); } } return value; }