auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void checkTime() throws Exception { m_out.print("- checking if time of database \"" + getDatabaseName() + "\" is matching system time... "); try (Statement st = getConnection().createStatement()) { try (ResultSet rs = st.executeQuery("SELECT NOW()")) { if (rs.next()) { final Timestamp currentDatabaseTime = rs.getTimestamp(1); final long currentSystemTime = System.currentTimeMillis(); final long diff = currentDatabaseTime.getTime() - currentSystemTime; if (Math.abs(diff) > 1000) { m_out.println("NOT OK"); <START> throw new Exception("Database time and system time differ. Please update either the database time or the system time"); <END> } m_out.println("OK"); } } } }</code><technical_language>a good idea include (formatted) timestamps delta in exception message</technical_language>

Target:
public void checkTime() throws Exception { m_out.print("- checking if time of database \"" + getDatabaseName() + "\" is matching system time... "); try (Statement st = getConnection().createStatement()) { final long beforeQueryTime = System.currentTimeMillis(); try (ResultSet rs = st.executeQuery("SELECT NOW()")) { if (rs.next()) { final Timestamp currentDatabaseTime = rs.getTimestamp(1); final long currentSystemTime = System.currentTimeMillis(); final long diff = currentDatabaseTime.getTime() - currentSystemTime; final long queryExecuteDelta = Math.abs(currentSystemTime - beforeQueryTime); if (Math.abs(diff) > 1000 + queryExecuteDelta) { m_out.println("NOT OK"); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); final String databaseDateString = simpleDateFormat.format(new Date(currentDatabaseTime.getTime())); final String systemTimeDateString = simpleDateFormat.format(new Date(currentSystemTime)); throw new Exception("Database time and system time differ." + "System time: " + systemTimeDateString + ", database time: " + databaseDateString + ", diff: " + Math.abs(diff) + "ms. The maximum allowed difference is 1000ms." + " Please update either the database time or system time"); } m_out.println("OK"); } } } }
Source:
<code>public void OnPnoNetworkFound() { Log.d(TAG, "Pno scan result event"); <START> mWifiMonitor.broadcastSchedScanResultEvent(mClientInterfaceName); <END> }</code><technical_language>Do want more specific is PNO scan results other type of scheduled scans</technical_language>

Target:
public void OnPnoNetworkFound() { Log.d(TAG, "Pno scan result event"); mWifiMonitor.broadcastPnoScanResultEvent(mClientInterfaceName); }
Source:
<code>int getSwapSegmentsInUse() throws StoreException { String[] tempSegments = dataDir.list(TEMP_LOG_SEGMENTS_FILTER); if (tempSegments == null) { throw new StoreException("Error occurred while listing files in data dir:" + dataDir.getAbsolutePath(), StoreErrorCodes.Unknown_Error); } return tempSegments.length; <START> } <END></code><technical_language>this qualifies IOError</technical_language>

Target:
int getSwapSegmentsInUse() throws StoreException { String[] tempSegments = dataDir.list(TEMP_LOG_SEGMENTS_FILTER); if (tempSegments == null) { throw new StoreException("Error occurred while listing files in data dir:" + dataDir.getAbsolutePath(), StoreErrorCodes.IOError); } return tempSegments.length; }
Source:
<code>private void lsRefsV2() throws IOException { PacketLineOutRefAdvertiser adv = new PacketLineOutRefAdvertiser(pckOut); Map<String, Ref> refs = getAdvertisedOrDefaultRefs(); String line; String refPrefix = null; adv.setUseProtocolV2(true); line = pckIn.readString(); END if not. if (line == PacketLineIn.DELIM) { while ((line = pckIn.readString()) != PacketLineIn.END) { if (line.equals("peel")) { adv.setDerefTags(true); } else if (line.equals("symrefs")) { findSymrefs(adv, refs); } else if (line.startsWith("ref-prefix ")) { <START> refPrefix = <END> line.substring("ref-prefix ".length()); } else { throw new PackProtocolException("unexpected " + line); } } } else if (line != PacketLineIn.END) { throw new PackProtocolException("unexpected " + line); } if (refPrefix != null) { HashMap<String, Ref> refsToSend = new HashMap<>(); for (Map.Entry<String, Ref> entry : refs.entrySet()) { if (!entry.getKey().startsWith(refPrefix)) { continue; } refsToSend.put(entry.getKey(), entry.getValue()); } refs = refsToSend; } adv.send(refs); adv.end(); }</code><technical_language>multiple ref-prefix? If refPrefix get overwritten. more DELIM a line</technical_language>

Target:
private void lsRefsV2() throws IOException { PacketLineOutRefAdvertiser adv = new PacketLineOutRefAdvertiser(pckOut); Map<String, Ref> refs = getAdvertisedOrDefaultRefs(); String line; ArrayList<String> refPrefixes = new ArrayList<>(); adv.setUseProtocolV2(true); line = pckIn.readString(); END if not. if (line == PacketLineIn.DELIM) { while ((line = pckIn.readString()) != PacketLineIn.END) { if (line.equals("peel")) { adv.setDerefTags(true); } else if (line.equals("symrefs")) { findSymrefs(adv, refs); } else if (line.startsWith("ref-prefix ")) { refPrefixes.add(line.substring("ref-prefix ".length())); } else { throw new PackProtocolException("unexpected " + line); } } } else if (line != PacketLineIn.END) { throw new PackProtocolException("unexpected " + line); } if (!refPrefixes.isEmpty()) { HashMap<String, Ref> refsToSend = new HashMap<>(); for (Map.Entry<String, Ref> entry : refs.entrySet()) { for (String refPrefix : refPrefixes) { if (entry.getKey().startsWith(refPrefix)) { refsToSend.put(entry.getKey(), entry.getValue()); continue; } } } refs = refsToSend; } adv.send(refs); adv.end(); }
Source:
<code>public void removeClientListener(byte[] listenerId) { <START> EventDispatcher dispatcher = clientListeners.get(listenerId); <END> dispatcher.transport.release(); clientListeners.remove(listenerId); if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId)); }</code><technical_language>this remove instead, need called 2 lines down</technical_language>

Target:
public void removeClientListener(byte[] listenerId) { EventDispatcher dispatcher = clientListeners.remove(listenerId); dispatcher.transport.release(); if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId)); }
Source:
<code>public void testCast() throws Exception { <START> final DefaultConfiguration configurationForTestCast = <END> createCheckConfig(WhitespaceAfterCheck.class); configurationForTestCast.addAttribute("tokens", "TYPECAST"); final String[] expected = { "88:21: " + getCheckMessage(MSG_WS_TYPECAST), }; verify(configurationForTestCast, getPath("InputWhitespace.java"), expected); }</code><technical_language>please name configurationTypeCast, please do approach for other naming</technical_language>

Target:
public void testCast() throws Exception { final DefaultConfiguration configurationTestCast = createCheckConfig(WhitespaceAfterCheck.class); configurationTestCast.addAttribute("tokens", "TYPECAST"); final String[] expected = { "88:21: " + getCheckMessage(MSG_WS_TYPECAST), }; verify(configurationTestCast, getPath("InputWhitespace.java"), expected); }
Source:
<code>public void runForPPC64() { VmDevice dbSpaprVscsiController = devices.stream().filter(d -> d.getType().equals(VmDeviceGeneralType.CONTROLLER)) .filter(d -> d.getDevice().equals(VdsProperties.Scsi)) .filter(d -> { Map<String, String> addressMap = StringMapUtils.string2Map(d.getAddress()); if (!addressMap.isEmpty() && <START> addressMap.get("type").equals(VdsProperties.spapr_vio)) <END> { return true; } return false; }).findFirst() .orElse(null); if (dbSpaprVscsiController != null) { return; } Map<String, Object> specParams = new HashMap<>(); Map<String, String> spaprAddress = new HashMap<>(); specParams.put(VdsProperties.Index, "0"); spaprAddress.put(VdsProperties.Type, VdsProperties.spapr_vio); dbSpaprVscsiController = new VmDevice( null, VmDeviceGeneralType.CONTROLLER, VdsProperties.Scsi, spaprAddress.toString(), specParams, false, true, false, "", null, null, null); devices.add(dbSpaprVscsiController); }</code><technical_language>note this part return null do other around: VdsProperties.spapr_vio.equals(addressMap.get("type")) check of map is empty is needed</technical_language>

Target:
public void runForPPC64() { boolean dbSpaprVscsiControllerExist = devices.stream().filter(d -> d.getType().equals(VmDeviceGeneralType.CONTROLLER)) .filter(d -> d.getDevice().equals(VdsProperties.Scsi)) .anyMatch(d -> { Map<String, String> addressMap = StringMapUtils.string2Map(d.getAddress()); return VdsProperties.spapr_vio.equals(addressMap.get("type")); }); if (dbSpaprVscsiControllerExist) { return; } Map<String, Object> specParams = new HashMap<>(); Map<String, String> spaprAddress = new HashMap<>(); specParams.put(VdsProperties.Index, "0"); spaprAddress.put(VdsProperties.Type, VdsProperties.spapr_vio); VmDevice dbSpaprVscsiController = new VmDevice( null, VmDeviceGeneralType.CONTROLLER, VdsProperties.Scsi, spaprAddress.toString(), specParams, false, true, false, "", null, null, null); devices.add(dbSpaprVscsiController); }
Source:
<code>private synchronized void display() { try { token.acquire(); if ((searchFilteredList.size() > 0) && (pageIndex <= searchFilteredList.size())) { <START> builder.append(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4( <END> buildString(searchFilteredList.get(pageIndex-1).getMessages()))); }else{ builder.replace(0, builder.length(), ""); builder.append("<b>") .append(Res.getString("message.no.history.found")) .append("</b>"); } window.setText(builder.toString()); builder.replace(0, builder.length(), ""); if (window.getText().length() > 0) window.setCaretPosition(0); pageCounter.setText(pageIndex + " / " + maxPages); token.release(); } catch (InterruptedException e) { Log.error(e); e.printStackTrace(); } }</code><technical_language>import statement? way, do StringEscapeUtils.unescapeHtml4 instead of org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4 - code more readable</technical_language>

Target:
private synchronized void display() { try { token.acquire(); if ((searchFilteredList.size() > 0) && (pageIndex <= searchFilteredList.size())) { builder.append(unescapeHtml4(buildString(searchFilteredList.get(pageIndex-1).getMessages()))); }else{ builder.replace(0, builder.length(), ""); builder.append("<b>") .append(Res.getString("message.no.history.found")) .append("</b>"); } window.setText(builder.toString()); builder.replace(0, builder.length(), ""); if (window.getText().length() > 0) window.setCaretPosition(0); pageCounter.setText(pageIndex + " / " + maxPages); token.release(); } catch (InterruptedException e) { Log.error(e); e.printStackTrace(); } }
Source:
<code>private UUID mapId(FIELD col, int val) throws SQLException { if (col == FIELD.owningComm) { Community comm = communityService.findByLegacyId(context, val); return comm == null ? null : comm.getID(); } if (col == FIELD.owningColl) { org.dspace.content.Collection coll = collectionService.findByLegacyId(context, val); return coll == null ? null : coll.getID(); } if (col == FIELD.owningItem) { Item item = itemService.findByLegacyId(context, val); <START> return item == null ? null : item.getID(); <END> } return null; }</code><technical_language>I Communities Collections in Hibernate cache (because number is limited), I uncache items. be: Item item = itemService.findByLegacyId(context, val); UUID itemId = item == null ? null : item.getID(); context.uncacheEntity(item); return itemId;</technical_language>

Target:
private UUID mapId(FIELD col, int val) throws SQLException { if (col == FIELD.owningComm) { Community comm = communityService.findByLegacyId(context, val); return comm == null ? null : comm.getID(); } if (col == FIELD.owningColl) { org.dspace.content.Collection coll = collectionService.findByLegacyId(context, val); return coll == null ? null : coll.getID(); } if (col == FIELD.owningItem) { Item item = itemService.findByLegacyId(context, val); checkLastItem(item); return item == null ? null : item.getID(); } if (col == FIELD.epersonid) { EPerson per = epersonService.findByLegacyId(context, val); return per == null ? null : per.getID(); } return null; }
Source:
<code>void saveEventType(EventType eventType) throws InternalNakadiException, DuplicatedEventTypeNameException; EventType findByName(String name) throws InternalNakadiException, NoSuchEventTypeException; void update(EventType eventType) throws InternalNakadiException, NoSuchEventTypeException; List<EventType> list(); void removeEventType(String name) throws InternalNakadiException, NoSuchEventTypeException; <START> default Optional<EventType> findByNameO(String eventTypeName) throws InternalNakadiException { <END> try { return Optional.of(findByName(eventTypeName)); } catch (NoSuchEventTypeException e) { return Optional.empty(); } catch (InternalNakadiException e) { throw e; } }</code><technical_language>final</technical_language>

Target:
void saveEventType(EventType eventType) throws InternalNakadiException, DuplicatedEventTypeNameException; EventType findByName(String name) throws InternalNakadiException, NoSuchEventTypeException; void update(EventType eventType) throws InternalNakadiException, NoSuchEventTypeException; List<EventType> list(); void removeEventType(String name) throws InternalNakadiException, NoSuchEventTypeException; default Optional<EventType> findByNameO(final String eventTypeName) throws InternalNakadiException { try { return Optional.of(findByName(eventTypeName)); } catch (final NoSuchEventTypeException e) { return Optional.empty(); } catch (final InternalNakadiException e) { throw e; } }
Source:
<code>private void checkWorkspaceStatusAndDelete(String workspaceName) throws Exception { <START> if (!testWorkspaceServiceClient.exists(workspaceName, defaultTestUser.getName())) { <END> return; } testWorkspaceServiceClient.delete(workspaceName, defaultTestUser.getName()); }</code><technical_language>Next variant simpler IMHO/ if (testWorkspaceServiceClient.exists(workspaceName, defaultTestUser.getName())) { testWorkspaceServiceClient.delete(workspaceName, defaultTestUser.getName()); }</technical_language>

Target:
private void checkWorkspaceStatusAndDelete(String workspaceName) throws Exception { if (testWorkspaceServiceClient.exists(workspaceName, defaultTestUser.getName())) { testWorkspaceServiceClient.delete(workspaceName, defaultTestUser.getName()); } }
Source:
<code>public void clickOnOkBtn() { <START> webDriverHelper.waitAndClick((saveBtn)); <END> loader.waitOnClosed(); }</code><technical_language>redundant pair "()"</technical_language>

Target:
public void clickOnOkBtn() { webDriverHelper.waitAndClick(saveBtn); loader.waitOnClosed(); }
Source:
<code><START> JobRecoveryException(final String message) { <END> super(message); }</code><technical_language>this a public constructor</technical_language>

Target:
public JobRecoveryException(final String message) { super(message); }
Source:
<code>public String getPattern() { <START> return rule.toString(); <END> }</code><technical_language>This is OK. This needs pattern "!" in case of negation. I looked new API a function query pattern. need remove leading ! store pattern in this class</technical_language>

Target:
public String getPattern() { String pattern = rule.toString(); if (pattern.startsWith("!")) { pattern = pattern.substring(1); } return rule.toString(); }
Source:
<code>public Object decode(Response response, Type type) throws IOException, FeignException { if (HeaderAccessUtils.shortcircuitingCaseInsensitiveContainsEntry( response.headers(), <START> HttpHeaders.CONTENT_TYPE, <END> MediaType.TEXT_PLAIN)) { return stringDecoder.decode(response, type); } return delegate.decode(response, type); }</code><technical_language>wondering if is worth a pre-upper case header, current equalsIgnoreCase implementation converts chars upper case for comparison, this over-optimization current equalsIgnoreCase implementation, JMH benchmark show worth it: private static final String CONTENT_TYPE = HttpHeaders.CONTENT_TYPE.toUpperCase(); ... if (HeaderAccessUtils.shortcircuitingCaseInsensitiveContainsEntry( response.headers(), CONTENT_TYPE, MediaType.TEXT_PLAIN)) { return stringDecoder.decode(response, type); }</technical_language>

Target:
public Object decode(Response response, Type type) throws IOException, FeignException { if (HeaderAccessUtils.shortcircuitingCaseInsensitiveContainsEntry( response.headers(), CONTENT_TYPE, MediaType.TEXT_PLAIN)) { return stringDecoder.decode(response, type); } return delegate.decode(response, type); }
Source:
<code>public static String formatCourseDate(String date) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM dd, yyyy"); Date startDate = DateUtil.convertToDate(date); String formattedDate = dateFormat.format(startDate); <START> return formattedDate; <END> } catch (Exception e) { logger.error(e); return ""; } }</code><technical_language>return value</technical_language>

Target:
public static String formatCourseDate(String date) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM dd, yyyy"); Date startDate = DateUtil.convertToDate(date); return dateFormat.format(startDate); } catch (Exception e) { logger.error(e); } return ""; }
Source:
<code>public void setup(StreamContext context) { StreamCodec<?> codec = context.get(StreamContext.CODEC); if (codec == null) { statefulSerde = ((StatefulStreamCodec<Object>)StreamContext.CODEC.defaultValue).newInstance(); } else if (codec instanceof StatefulStreamCodec) { statefulSerde = ((StatefulStreamCodec<Object>)codec).newInstance(); <START> if (!codec.getClass().isAssignableFrom(statefulSerde.getClass())) { <END> throw new RuntimeException(String.format("%s newInstance returned incompatible object of class %s", codec.getClass().getName(), statefulSerde.getClass().getName())); } } else { serde = (StreamCodec<Object>)codec; } }</code><technical_language>is check necessary if validation checks for correct implementation of newInstance()</technical_language>

Target:
public void setup(StreamContext context) { StreamCodec<?> codec = context.get(StreamContext.CODEC); if (codec == null) { statefulSerde = ((StatefulStreamCodec<Object>)StreamContext.CODEC.defaultValue).newInstance(); } else if (codec instanceof StatefulStreamCodec) { statefulSerde = ((StatefulStreamCodec<Object>)codec).newInstance(); } else { serde = (StreamCodec<Object>)codec; } }
Source:
<code>public void shouldFailWhenMakeGeoBoundingBoxESHintQueryWithIllegalArguments() { Optional<ESHintQueryBuilder> geoBoundingBoxESHintQueryBuilder = elasticSearchAdmin.getHintByOperator( GeoBoundingBoxQueryBuilder.NAME); assertTrue(geoBoundingBoxESHintQueryBuilder.isPresent()); try { geoBoundingBoxESHintQueryBuilder.get().make(null, ANY_FIELD_NAME, new String[5]); fail("Should raise an IllegalArgumentException"); } catch (IllegalArgumentException ia) { assertEquals( <START> "Hint: org.nuxeo.elasticsearch.hint.GeoBoundingBoxESHintQueryBuilder requires 2 parameters: bottomLeft and topRight point", <END> ia.getMessage()); } }</code><technical_language>simple class name es hint name is enough, wdyt</technical_language>

Target:
public void shouldFailWhenMakeGeoBoundingBoxESHintQueryWithIllegalArguments() { Optional<ESHintQueryBuilder> geoBoundingBoxESHintQueryBuilder = elasticSearchAdmin.getHintByOperator( GeoBoundingBoxQueryBuilder.NAME); assertTrue(geoBoundingBoxESHintQueryBuilder.isPresent()); try { geoBoundingBoxESHintQueryBuilder.get().make(null, ANY_FIELD_NAME, new String[5]); fail("Should raise a NuxeoException"); } catch (NuxeoException ne) { assertEquals("Hints: GeoBoundingBoxESHintQueryBuilder requires 2 parameters: bottomLeft and topRight point", ne.getMessage()); assertEquals(SC_BAD_REQUEST, ne.getStatusCode()); } }
Source:
<code>public RelationSupportInternal<CatalogItem<T,SpecT>> relations() { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>I return immutable empty RelationSupport object instead. This allow avoid special casing CatalogItem working BrooklynObjects</technical_language>

Target:
public RelationSupportInternal<CatalogItem<T,SpecT>> relations() { return new EmptyRelationSupport<CatalogItem<T,SpecT>>(this); }
Source:
<code>public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException { CCMBridge ccm = null; Cluster cluster = null; QueryPlanCountingPolicy loadBalancingPolicy = new QueryPlanCountingPolicy(Policies.defaultLoadBalancingPolicy()); AtomicInteger reconnectionAttempts = loadBalancingPolicy.counter; ReconnectionPolicy reconnectionPolicy = new ReconnectionPolicy() { @Override public ReconnectionSchedule newSchedule() { return new ReconnectionSchedule() { @Override public long nextDelayMs() { return 60 * 1000; } }; } }; try { <START> ccm = CCMBridge.builder().withNodes(2).build(); <END> cluster = Cluster.builder() .addContactPoint(CCMBridge.ipOfNode(1)) .withReconnectionPolicy(reconnectionPolicy) .withLoadBalancingPolicy(loadBalancingPolicy) .build(); cluster.init(); ccm.stop(1); TimeUnit.SECONDS.sleep(1); assertThat(reconnectionAttempts.get()).isEqualTo(1); ccm.stop(2); TimeUnit.SECONDS.sleep(1); assertThat(reconnectionAttempts.get()).isEqualTo(2); } finally { if (cluster != null) cluster.close(); if (ccm != null) ccm.remove(); } }</code><technical_language>This test expressed CCMTestsSupport it? need done here, thinking if is possible, I able java @CCMTestMode(PER_METHOD) .... // For method @CCMConfig(numberOfNodes=X, createCluster=false)</technical_language>

Target:
public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException { Cluster cluster = null; QueryPlanCountingPolicy loadBalancingPolicy = new QueryPlanCountingPolicy(Policies.defaultLoadBalancingPolicy()); AtomicInteger reconnectionAttempts = loadBalancingPolicy.counter; ReconnectionPolicy reconnectionPolicy = new ReconnectionPolicy() { @Override public ReconnectionSchedule newSchedule() { return new ReconnectionSchedule() { @Override public long nextDelayMs() { return 60 * 1000; } }; } }; try { cluster = Cluster.builder() .addContactPointsWithPorts(singleton(ccmSupport.getContactPoints().get(0))) .withAddressTranslater(ccmSupport.getAddressTranslator()) .withReconnectionPolicy(reconnectionPolicy) .withLoadBalancingPolicy(loadBalancingPolicy) .build(); cluster.init(); ccmSupport.ccmBridge().stop(1); TimeUnit.SECONDS.sleep(1); assertThat(reconnectionAttempts.get()).isEqualTo(1); ccmSupport.ccmBridge().stop(2); TimeUnit.SECONDS.sleep(1); assertThat(reconnectionAttempts.get()).isEqualTo(2); } finally { if (cluster != null) cluster.close(); } }
Source:
<code>public String translate(Enum<?> key) { if(key == null) { <START> logger.log(Level.INFO, "trying to localize null, probable error. " + <END> "Exception is not thrown, returning '"+ constants.notAvailableLabel()+"'", new RuntimeException()); return constants.notAvailableLabel(); } try { final String translatedString = enums.getString(keyToTranslate(key)); return translatedString != null? translatedString : notLocalizedKey(key); } catch (MissingResourceException e) { return notLocalizedKey(key, e); } }</code><technical_language>This logged a WARNING instead of INFO</technical_language>

Target:
public String translate(Enum<?> key) { if (key == null) { final String result = constants.notAvailableLabel(); logger.warning("trying to localize null, probable error. " + "Exception is not thrown, returning '" + result + "'"); return result; } try { final String translatedString = enums.getString(keyToTranslate(key)); return translatedString != null ? translatedString : notLocalizedKey(key); } catch (MissingResourceException e) { return notLocalizedKey(key, e); } }
Source:
<code>public Archive<?> createAuxiliaryArchive() { JavaArchive archive = ShrinkWrap.create(JavaArchive.class); archive .addPackages(true, org.eclipse.microprofile.lra.annotation.Compensate.class.getPackage()); archive.addPackages(true, io.narayana.lra.client.NarayanaLRAClient.class.getPackage()) <START> .addPackages(true, io.narayana.lra.Current.class.getPackage()) <END> .addPackage(LRACDIExtension.class.getPackage()) .addAsResource("META-INF/services/javax.enterprise.inject.spi.Extension") .addClass(org.jboss.weld.exceptions.DefinitionException.class) .addAsManifestResource(new StringAsset("<beans version=\"1.1\" bean-discovery-mode=\"annotated\"></beans>"), "beans.xml"); String filtersAsset = String.format("%s%n%s", io.narayana.lra.filter.ClientLRAResponseFilter.class.getName(), io.narayana.lra.filter.ClientLRARequestFilter.class.getName()); archive.addPackages(true, io.narayana.lra.filter.ClientLRARequestFilter.class.getPackage()) .addAsResource(new StringAsset(filtersAsset), "META-INF/services/javax.ws.rs.ext.Providers") .addAsResource(new StringAsset("org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder"), "META-INF/services/javax.ws.rs.client.ClientBuilder"); return archive; }</code><technical_language>I this is code formatting, if required I favour adding aid readability</technical_language>

Target:
public Archive<?> createAuxiliaryArchive() { JavaArchive archive = ShrinkWrap.create(JavaArchive.class) .addPackages(true, org.eclipse.microprofile.lra.annotation.Compensate.class.getPackage()); archive.addPackages(true, io.narayana.lra.client.NarayanaLRAClient.class.getPackage()) .addPackages(true, io.narayana.lra.Current.class.getPackage()) .addPackage(LRACDIExtension.class.getPackage()) .addAsResource("META-INF/services/javax.enterprise.inject.spi.Extension") .addClass(org.jboss.weld.exceptions.DefinitionException.class) .addAsManifestResource(new StringAsset("<beans version=\"1.1\" bean-discovery-mode=\"annotated\"></beans>"), "beans.xml"); String filtersAsset = String.format("%s%n%s", io.narayana.lra.filter.ClientLRAResponseFilter.class.getName(), io.narayana.lra.filter.ClientLRARequestFilter.class.getName()); archive.addPackages(true, io.narayana.lra.filter.ClientLRARequestFilter.class.getPackage()) .addAsResource(new StringAsset(filtersAsset), "META-INF/services/javax.ws.rs.ext.Providers") .addAsResource(new StringAsset("org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder"), "META-INF/services/javax.ws.rs.client.ClientBuilder"); return archive; }
Source:
<code>public void canRecalculateCommandWhenFileOrOptionsChanged() throws IOException { File firstFile = File.createTempFile("first", ".txt"); String firstOptions = "-f options"; File secondFile = File.createTempFile("second", ".txt"); String secondOptions = "-f newoptions"; OSDelegatingFileTailingMessageProducer adapter = new OSDelegatingFileTailingMessageProducer(); adapter.setFile(firstFile); adapter.setOptions(firstOptions); adapter.setOutputChannel(new QueueChannel()); adapter.setTailAttemptsDelay(500); adapter.setBeanFactory(mock(BeanFactory.class)); adapter.afterPropertiesSet(); assertEquals("tail " + firstOptions + " " + firstFile.getAbsolutePath(), adapter.getCommand()); adapter.setFile(secondFile); assertEquals("tail " + firstOptions + " " + secondFile.getAbsolutePath(), adapter.getCommand()); adapter.setOptions(secondOptions); <START> assertEquals("tail " + secondOptions + " " + secondFile.getAbsolutePath(), adapter.getCommand()); <END> }</code><technical_language>this reconfiguration test a real one? Similar testOS()</technical_language>

Target:
public void canRecalculateCommandWhenFileOrOptionsChanged() throws IOException { File firstFile = File.createTempFile("first", ".txt"); String firstOptions = "-f options"; File secondFile = File.createTempFile("second", ".txt"); String secondOptions = "-f newoptions"; OSDelegatingFileTailingMessageProducer adapter = new OSDelegatingFileTailingMessageProducer(); adapter.setFile(firstFile); adapter.setOptions(firstOptions); adapter.setOutputChannel(new QueueChannel()); adapter.setTailAttemptsDelay(500); adapter.setBeanFactory(mock(BeanFactory.class)); adapter.afterPropertiesSet(); adapter.start(); assertEquals("tail " + firstOptions + " " + firstFile.getAbsolutePath(), adapter.getCommand()); adapter.stop(); adapter.setFile(secondFile); adapter.start(); assertEquals("tail " + firstOptions + " " + secondFile.getAbsolutePath(), adapter.getCommand()); adapter.stop(); adapter.setOptions(secondOptions); adapter.start(); assertEquals("tail " + secondOptions + " " + secondFile.getAbsolutePath(), adapter.getCommand()); adapter.stop(); }
Source:
<code>public ImmutableValue<Boolean> persists() { <START> return cachedValue; <END> }</code><technical_language>replace getValueGetter() is cached for you</technical_language>

Target:
public ImmutableValue<Boolean> persists() { return getValueGetter(); }
Source:
<code>private void storeCookiesIntoCookieJar(Map<String, Object> requestHeadersParam) { try { if (requestHeadersParam.containsKey("Cookie") && requestHeadersParam.get("Cookie") instanceof String) { String cookieString = (String) requestHeadersParam.get("Cookie"); if (remote != null) { Cookie cookie = Cookie.parse(HttpUrl.get(remote), cookieString); <START> if (cookie != null && replicationInternal != null) { <END> replicationInternal.setCookie(cookie); } } } } catch (Exception e) { Log.e(Log.TAG_SYNC, "Failed to store SyncGatewaySession into the CookieJar.", e); } }</code><technical_language>I need check if replicationInternal is null null</technical_language>

Target:
private void storeCookiesIntoCookieJar(Map<String, Object> requestHeadersParam) { try { if (requestHeadersParam != null && requestHeadersParam.containsKey("Cookie") && requestHeadersParam.get("Cookie") instanceof String) { String cookieString = (String) requestHeadersParam.get("Cookie"); if (remote != null) { Cookie cookie = Cookie.parse(HttpUrl.get(remote), cookieString); if (cookie != null) { replicationInternal.setCookie(cookie); requestHeadersParam.remove("Cookie"); } } } } catch (Exception e) { Log.e(Log.TAG_SYNC, "Failed to store SyncGatewaySession into the CookieJar.", e); } }
Source:
<code>public static Field lookupWriterField(final Schema writerSchema, final Field readerField) { assert (writerSchema.getType() == Type.RECORD); final List<Field> writerFields = new ArrayList<>(); final Field direct = writerSchema.getField(readerField.name()); if (direct != null) { writerFields.add(direct); } for (final String readerFieldAliasName : readerField.aliases()) { final Field writerField = writerSchema.getField(readerFieldAliasName); if (writerField != null) { writerFields.add(writerField); } } switch (writerFields.size()) { <START> case 0: <END> return null; case 1: return writerFields.get(0); default: { throw new AvroRuntimeException(String.format( "Reader record field %s matches multiple fields in writer record schema %s", readerField, writerSchema)); } } }</code><technical_language>This is more tricky, I personally revert this, code more readable, a change functionally changes code - this argued about</technical_language>

Target:
public static Field lookupWriterField(final Schema writerSchema, final Field readerField) { assert (writerSchema.getType() == Type.RECORD); final List<Field> writerFields = new ArrayList<Field>(); final Field direct = writerSchema.getField(readerField.name()); if (direct != null) { writerFields.add(direct); } for (final String readerFieldAliasName : readerField.aliases()) { final Field writerField = writerSchema.getField(readerFieldAliasName); if (writerField != null) { writerFields.add(writerField); } } switch (writerFields.size()) { case 0: return null; case 1: return writerFields.get(0); default: { throw new AvroRuntimeException(String.format( "Reader record field %s matches multiple fields in writer record schema %s", readerField, writerSchema)); } } }
Source:
<code>public URL getURL() { <START> try { return new URL(url.toString()); } catch (MalformedURLException e) { return null; } <END> }</code><technical_language>return url</technical_language>

Target:
public URL getURL() { return url; }
Source:
<code>public void close() { if (client == null) { return; } try { client.close(); } catch (Exception e) { <START> log.warn("Error closing client", e); <END> } }</code><technical_language>change order of parameters? In airlift (e, message)</technical_language>

Target:
public void close() { if (client == null) { return; } try { client.close(); } catch (Exception e) { log.warn(e, "Error closing client"); } client = null; }
Source:
<code>protected void updateServer() { updateServer(false); <START> if (logDiagnosticEvents) { <END> Diagnostics.getLogger().flushEvents(); } }</code><technical_language>is this boolean necessary here? delegate check if diagnostics enabled diagnostics logger</technical_language>

Target:
protected void updateServer() { updateServer(false); Diagnostics.getLogger().flushEvents(); }
Source:
<code><START> public void setMethod(final ZonemasterRequest.Method method) { <END> this.method = method.getMethod(); this.id = method.getId(); }</code><technical_language>a protected method</technical_language>

Target:
protected void setMethod(final ZonemasterRequest.Method method) { this.method = method.getMethod(); this.id = method.getId(); }
Source:
<code>protected boolean canDoAction() { init(); if (isImagesAlreadyOnTarget()) { if (ovfEntityData == null && !getParameters().isImportAsNewEntity()) { return false; } setStorageDomainId(ovfEntityData.getStorageDomainId()); if (!validate(new StorageDomainValidator(getStorageDomain()).isDomainExistAndActive())) { return false; } if (!getStorageDomain().getStorageDomainType().isDataDomain()) { addCanDoActionMessage("$domainId " + getParameters().getStorageDomainId()); addCanDoActionMessage("$domainType " + getStorageDomain().getStorageDomainType()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_UNSUPPORTED); <START> return false; <END> } } getParameters().setImages(getVmTemplate().getImages()); return super.canDoAction(); }</code><technical_language>in previous patch - failCan... method instead</technical_language>

Target:
protected boolean canDoAction() { init(); if (isImagesAlreadyOnTarget()) { if (ovfEntityData == null && !getParameters().isImportAsNewEntity()) { return false; } setStorageDomainId(ovfEntityData.getStorageDomainId()); if (!validate(new StorageDomainValidator(getStorageDomain()).isDomainExistAndActive())) { return false; } if (!getStorageDomain().getStorageDomainType().isDataDomain()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_UNSUPPORTED, String.format("$domainId %1$s", getParameters().getStorageDomainId()), String.format("$domainType %1$s", getStorageDomain().getStorageDomainType())); } } getParameters().setImages(getVmTemplate().getImages()); return super.canDoAction(); }
Source:
<code>protected void selectionUpdatedHandler(SelectionUpdatedEvent event) { ListGridRecord[] selectedRecords = this.getSelectedRecords(); <START> ArrayList<Integer> selectedJobsIds = new ArrayList<>(); <END> for (ListGridRecord selectedRecord : selectedRecords) { selectedJobsIds.add(JobRecord.getJob(selectedRecord).getId()); } controller.getModel().setSelectedJobsIds(selectedJobsIds); }</code><technical_language>lenght of ArrayList<>() new ArrayList<>(selectedRecords.length)</technical_language>

Target:
protected void selectionUpdatedHandler(SelectionUpdatedEvent event) { ListGridRecord[] selectedRecords = this.getSelectedRecords(); List<Integer> selectedJobsIds = new ArrayList<>(selectedRecords.length); for (ListGridRecord selectedRecord : selectedRecords) { selectedJobsIds.add(JobRecord.getJob(selectedRecord).getId()); } controller.getModel().setSelectedJobsIds(selectedJobsIds); }
Source:
<code>public String filterAll() { try { List<TaskDTO> tasks; if (!showAutomaticTasks) { if (hideCorrectionTasks) { tasks = serviceManager.getTaskService() .findOpenNotAutomaticTasksWithoutCorrectionForCurrentUser(sortList()); } else { tasks = serviceManager.getTaskService().findOpenNotAutomaticTasksForCurrentUser(sortList()); } } else { if (hideCorrectionTasks) { tasks = serviceManager.getTaskService().findOpenTasksWithoutCorrectionForCurrentUser(sortList()); } else { tasks = serviceManager.getTaskService().findOpenTasksForCurrentUser(sortList()); } } this.page = new Page<>(0, tasks); } catch (DataException e) { Helper.setFehlerMeldung("Error on reading ElasticSearch: ", e.getMessage()); return null; } <START> return redirectToList("?faces-redirect=true"); <END> }</code><technical_language>Please change code changes @solth in BenutzergruppenForm, DocketForm ProjekteForm: constant BasisForm add this method a method parameter</technical_language>

Target:
public String filterAll() { try { List<TaskDTO> tasks; if (!showAutomaticTasks) { if (hideCorrectionTasks) { tasks = serviceManager.getTaskService() .findOpenNotAutomaticTasksWithoutCorrectionForCurrentUser(sortList()); } else { tasks = serviceManager.getTaskService().findOpenNotAutomaticTasksForCurrentUser(sortList()); } } else { if (hideCorrectionTasks) { tasks = serviceManager.getTaskService().findOpenTasksWithoutCorrectionForCurrentUser(sortList()); } else { tasks = serviceManager.getTaskService().findOpenTasksForCurrentUser(sortList()); } } this.page = new Page<>(0, tasks); } catch (DataException e) { Helper.setFehlerMeldung("Error on reading ElasticSearch: ", e.getMessage()); return null; } return redirectToList(); }
Source:
<code>public Material getType() { Material mat = Material.getMaterial(getTypeId()); <START> return (mat == null ? Material.AIR : mat); <END> }</code><technical_language>is unknown type is air</technical_language>

Target:
public Material getType() { return Material.getMaterial(getTypeId()); }
Source:
<code>public void onErrorThrows() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { final List<Object> received = new ArrayList<Object>(); BoundedSubscriber<Object> o = new BoundedSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { received.add(o); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { throw new TestException("Inner"); } }, new Action() { @Override <START> public void run() throws Exception { <END> received.add(1); } }, new Functions.BoundedConsumer(128) { @Override public void accept(Subscription subscription) throws Exception { subscription.request(bufferSize); } }); assertFalse(o.isDisposed()); Flowable.<Integer>error(new TestException("Outer")).subscribe(o); assertTrue(received.toString(), received.isEmpty()); assertTrue(o.isDisposed()); TestHelper.assertError(errors, 0, CompositeException.class); List<Throwable> ce = TestHelper.compositeList(errors.get(0)); TestHelper.assertError(ce, 0, TestException.class, "Outer"); TestHelper.assertError(ce, 1, TestException.class, "Inner"); } finally { RxJavaPlugins.reset(); } }</code><technical_language>Place a breakpoint debug test. reveal code coverage execute code in BoundedSubscriber</technical_language>

Target:
public void onErrorThrows() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { final List<Object> received = new ArrayList<Object>(); BoundedSubscriber<Object> o = new BoundedSubscriber<Object>(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { received.add(o); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { throw new TestException("Inner"); } }, new Action() { @Override public void run() throws Exception { received.add(1); } }, new Consumer<Subscription>() { @Override public void accept(Subscription subscription) throws Exception { subscription.request(128); } }, 128); assertFalse(o.isDisposed()); Flowable.<Integer>error(new TestException("Outer")).subscribe(o); assertTrue(received.toString(), received.isEmpty()); assertTrue(o.isDisposed()); TestHelper.assertError(errors, 0, CompositeException.class); List<Throwable> ce = TestHelper.compositeList(errors.get(0)); TestHelper.assertError(ce, 0, TestException.class, "Outer"); TestHelper.assertError(ce, 1, TestException.class, "Inner"); } finally { RxJavaPlugins.reset(); } }
Source:
<code>public void visitIdentifier(IdentifierTree tree) { Type type = tree.symbolType(); <START> if (!classType.is(type.fullyQualifiedName()) && type.isSubtypeOf(classType)) { <END> reportIssue(tree, String.format("Remove this reference to \"%s\".", type.symbol().name())); } }</code><technical_language>This bothers sounds working API adressing real issue. improve method type, is method improved handle cases... I do if want "is" answer true compare classtype methodtype. IMO of action explicit instanceof here. dealt in other checks</technical_language>

Target:
public void visitIdentifier(IdentifierTree tree) { Type type = tree.symbolType(); if (type instanceof MethodJavaType) { type = ((MethodJavaType) type).resultType(); } if (!classType.equals(type) && type.isSubtypeOf(classType)) { reportIssue(tree, String.format("Remove this reference to \"%s\".", type.symbol().name())); } }
Source:
<code>private void init() { inflate(getContext(), R.layout.filtered_list_component, this); int spacingHorizontal = 0; int spacingVertical = DisplayUtils.dpToPx(getContext(), 1); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.addItemDecoration(new RecyclerItemDecoration(spacingHorizontal, spacingVertical)); mToolbar = (Toolbar) findViewById(R.id.toolbar_with_spinner); mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar_layout); mEmptyView = (TextView) findViewById(R.id.empty_view); mProgressLoadMore = (ProgressBar) findViewById(R.id.progress_loading); mProgressLoadMore.setVisibility(View.GONE); mSwipeToRefreshHelper = new SwipeToRefreshHelper( (CustomSwipeRefreshLayout) findViewById(R.id.ptr_layout), new SwipeToRefreshHelper.RefreshListener() { @Override public void onRefreshStarted() { post(new Runnable() { @Override public void run() { if (!NetworkUtils.checkConnection(getContext())) { mSwipeToRefreshHelper.setRefreshing(false); updateEmptyView(EmptyViewMessageType.NETWORK_ERROR); return; } if (mFilterListener != null){ mFilterListener.onLoadData(); } } }); } }, <START> R.color.color_primary, R.color.color_accent <END> ); if (mSpinner == null) { mSpinner = (Spinner) findViewById(R.id.filter_spinner); } }</code><technical_language>setting colors is a bit repetitive so, defining a helper method in main WordPress module (say, in util package) return a new SwipeToRefreshHelper colors set</technical_language>

Target:
private void init() { inflate(getContext(), R.layout.filtered_list_component, this); int spacingHorizontal = 0; int spacingVertical = DisplayUtils.dpToPx(getContext(), 1); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.addItemDecoration(new RecyclerItemDecoration(spacingHorizontal, spacingVertical)); mToolbar = (Toolbar) findViewById(R.id.toolbar_with_spinner); mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar_layout); mEmptyView = (TextView) findViewById(R.id.empty_view); mProgressLoadMore = (ProgressBar) findViewById(R.id.progress_loading); mProgressLoadMore.setVisibility(View.GONE); mSwipeToRefreshHelper = buildSwipeToRefreshHelper( (CustomSwipeRefreshLayout) findViewById(R.id.ptr_layout), new SwipeToRefreshHelper.RefreshListener() { @Override public void onRefreshStarted() { post(new Runnable() { @Override public void run() { if (!NetworkUtils.checkConnection(getContext())) { mSwipeToRefreshHelper.setRefreshing(false); updateEmptyView(EmptyViewMessageType.NETWORK_ERROR); return; } if (mFilterListener != null){ mFilterListener.onLoadData(); } } }); } } ); if (mSpinner == null) { mSpinner = (Spinner) findViewById(R.id.filter_spinner); } }
Source:
<code>public static String toCanonicalFilePath(URL fileURL) throws URISyntaxException, IOException { if (fileURL == null) { return null; } <START> if (!fileURL.getProtocol().equals("jar") && !fileURL.getProtocol().equals("file")) { <END> return null; } if (fileURL.getProtocol().equals("jar")) { JarURLConnection jarURLConnection = (JarURLConnection) fileURL.openConnection(); fileURL = jarURLConnection.getJarFileURL(); } URI fileURI = fileURL.toURI(); File file = new File(fileURI); File canonicalFile = file.getCanonicalFile(); return canonicalFile.toURI().toString(); }</code><technical_language>nit: prefer "constant".equals .equals("constant") avoid NPE .. is issue a good practice</technical_language>

Target:
public static String toCanonicalFilePath(URL fileURL) throws URISyntaxException, IOException { if (fileURL == null) { return null; } if (!"jar".equals(fileURL.getProtocol()) && !"file".equals(fileURL.getProtocol())) { return null; } if ("jar".equals(fileURL.getProtocol())) { JarURLConnection jarURLConnection = (JarURLConnection) fileURL.openConnection(); fileURL = jarURLConnection.getJarFileURL(); } URI fileURI = fileURL.toURI(); File file = new File(fileURI); File canonicalFile = file.getCanonicalFile(); return canonicalFile.toURI().toString(); }
Source:
<code>protected void updateDatastreamProperties(ObjectReference obj, DatastreamVersion v, FedoraDatastream ds) { QuadDataAcc triplesToInsert = new QuadDataAcc(); QuadAcc triplesToRemove = new QuadAcc(); String createdDate = v.getCreated(); if (v.isFirstVersionIn(obj)) { String dsid = v.getDatastreamInfo().getDatastreamId(); if (dsid != null) { updateTriple(triplesToRemove, triplesToInsert, "<LINK_1>", dsid); } if (createdDate != null) { updateDateTriple(triplesToRemove, triplesToInsert, "<LINK_6>", createdDate); } } if (createdDate != null) { updateModifiedDate(triplesToRemove, triplesToInsert, createdDate); <START> } <END> String label = v.getLabel(); if (label != null) { updateTriple(triplesToRemove, triplesToInsert, "<LINK_2>", label); } String state = v.getDatastreamInfo().getState(); if (state != null) { updateTriple(triplesToRemove, triplesToInsert, "<LINK_0>", state); } String formatUri = v.getFormatUri(); if (formatUri != null) { updateTriple(triplesToRemove, triplesToInsert, "<LINK_5>", formatUri); } if (!triplesToInsert.getQuads().isEmpty() && !triplesToRemove.getQuads().isEmpty()) { updateResourceProperties(ds, triplesToRemove, triplesToInsert); } }</code><technical_language>leave this out for now</technical_language>

Target:
protected void updateDatastreamProperties(ObjectReference obj, DatastreamVersion v, FedoraDatastream ds) { QuadDataAcc triplesToInsert = new QuadDataAcc(); QuadAcc triplesToRemove = new QuadAcc(); String createdDate = v.getCreated(); if (v.isFirstVersionIn(obj)) { String now = getCurrentTimeInXSDDateTime(); if (now != null) { addDateEvent(triplesToInsert, "<LINK_3>", getCurrentTimeInXSDDateTime()); } if (createdDate != null) { updateDateTriple(triplesToRemove, triplesToInsert, "<LINK_6>", createdDate); } } if (v.isLastVersionIn(obj)) { String dsid = v.getDatastreamInfo().getDatastreamId(); if (dsid != null) { updateTriple(triplesToRemove, triplesToInsert, "<LINK_1>", dsid); } if (createdDate != null) { addDateEvent(triplesToInsert, "<LINK_4>", createdDate); } String label = v.getLabel(); if (label != null) { updateTriple(triplesToRemove, triplesToInsert, "<LINK_2>", label); } String state = v.getDatastreamInfo().getState(); if (state != null) { updateTriple(triplesToRemove, triplesToInsert, "<LINK_0>", state); } String formatUri = v.getFormatUri(); if (formatUri != null) { updateTriple(triplesToRemove, triplesToInsert, "<LINK_5>", formatUri); } } if (!triplesToInsert.getQuads().isEmpty() && !triplesToRemove.getQuads().isEmpty()) { updateResourceProperties(ds, triplesToRemove, triplesToInsert); } }