auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.XenServer) { s_logger.debug("Don't know how to fence non XenServer hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); for (HostVO h : hosts) { if (h.getHypervisorType() == HypervisorType.XenServer) { if (h.getStatus() != Status.Up) { continue; } if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { Answer ans = _agentMgr.send(h.getId(), fence); if (!(ans instanceof FenceAnswer)) { s_logger.debug("Answer is not fenceanswer. Result = " + ans.getResult() + "; Details = " + ans.getDetails()); continue; } answer = (FenceAnswer)ans; <START> } catch (AgentUnavailableException | OperationCancelledException | OperationTimedoutException e) { <END> if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } if (answer != null && answer.getResult()) { return true; } } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString()); } return false; }</code><technical_language>For cancelled exception move next host</technical_language>

Target:
public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.XenServer) { s_logger.debug("Don't know how to fence non XenServer hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); for (HostVO h : hosts) { if (h.getHypervisorType() == HypervisorType.XenServer) { if (h.getStatus() != Status.Up) { continue; } if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { Answer ans = _agentMgr.send(h.getId(), fence); if (!(ans instanceof FenceAnswer)) { s_logger.debug("Answer is not fenceanswer. Result = " + ans.getResult() + "; Details = " + ans.getDetails()); continue; } answer = (FenceAnswer)ans; } catch (OperationCancelledException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("cancelling because " + h.toString() + " is unavailable(operation cancelled)"); } break; } catch (AgentUnavailableException | OperationTimedoutException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } if (answer != null && answer.getResult()) { return true; } } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString()); } return false; }
Source:
<code>public void testAllByConnectionId() { <START> List<StorageDomain> domains = dao.getAllByConnectionId(Guid.createGuidFromString("0cc146e8-e5ed-482c-8814-270bc48c297f")); <END> assertEquals("Unexpected number of storage domains by connection id", domains.size(), 1); assertEquals("Wrong storage domain id for search by connection id", domains.get(0).getId(), Guid.createGuidFromString("c2211b56-8869-41cd-84e1-78d7cb96f31d")); }</code><technical_language>new Guid(String) - this literal null</technical_language>

Target:
public void testAllByConnectionId() { List<StorageDomain> domains = dao.getAllByConnectionId(new Guid("0cc146e8-e5ed-482c-8814-270bc48c297f")); assertEquals("Unexpected number of storage domains by connection id", domains.size(), 1); assertEquals("Wrong storage domain id for search by connection id", domains.get(0).getId(), new Guid("c2211b56-8869-41cd-84e1-78d7cb96f31d")); }
Source:
<code>public void testPutIfAbsentHasStoreEntryCacheAccessExceptionHasCacheWriterEntry() throws Exception { final MockStore realStore = new MockStore(Collections.singletonMap("key", "oldValue")); this.store = spy(realStore); doThrow(new CacheAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); final MockCacheWriter realCache = new MockCacheWriter(Collections.singletonMap("key", "oldValue")); this.cacheWriter = spy(realCache); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); final InOrder ordered = inOrder(this.cacheWriter, this.spiedResilienceStrategy); <START> assertThat(ehcache.putIfAbsent("key", "value"), is(nullValue())); END> verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); ordered.verify(this.cacheWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy) .putIfAbsentFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(true)); assertThat(realCache.getEntries().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); }</code><technical_language>I apply logic for org.ehcache.EhcacheBasicPutIfAbsentTest#testPutIfAbsentHasStoreEntryCacheAccessExceptionNoCacheWriter</technical_language>

Target:
public void testPutIfAbsentHasStoreEntryCacheAccessExceptionHasCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "oldValue")); this.store = spy(fakeStore); doThrow(new CacheAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "oldValue")); this.cacheWriter = spy(fakeWriter); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); final InOrder ordered = inOrder(this.cacheWriter, this.spiedResilienceStrategy); ehcache.putIfAbsent("key", "value"); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); ordered.verify(this.cacheWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy) .putIfAbsentFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(true)); assertThat(fakeWriter.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); }
Source:
<code>private GitModelObject handleCacheTree(ObjectId repoId, ObjectId cacheId, String path) throws IOException { <START> String pathKey = path.split("/")[0]; END> GitModelCacheTree cacheTree = cacheTreeMap.get(pathKey); if (cacheTree == null) { cacheTree = new GitModelCacheTree(this, baseCommit, repoId, cacheId, getLocation().append(pathKey), fileFactory); cacheTreeMap.put(pathKey, cacheTree); } cacheTree.addChild(repoId, cacheId, path.substring(path.indexOf('/') + 1)); return cacheTree; }</code><technical_language>Is correct? a file 'a/b/c/f.txt' wont this path.split..[0] construct return 'a' (instead of 'a/b/c' I expect is want). work lastIndexOf('/') substring(). lastSlash = path.lastIndexOf('/'); if (lastSlash>-1) pathKey = path.substring(0, lastSlash);</technical_language>

Target:
private GitModelObject handleCacheTree(ObjectId repoId, ObjectId cacheId, String path) throws IOException { int firstSlash = path.indexOf("/"); String pathKey = path.substring(0, firstSlash); GitModelCacheTree cacheTree = cacheTreeMap.get(pathKey); if (cacheTree == null) { cacheTree = new GitModelCacheTree(this, baseCommit, repoId, cacheId, getLocation().append(pathKey), fileFactory); cacheTreeMap.put(pathKey, cacheTree); } cacheTree.addChild(repoId, cacheId, path.substring(firstSlash + 1)); return cacheTree; }
Source:
<code>public static DataWord of(int num) { <START> return of(ByteBuffer.allocate(4).putInt(num).array()); <END> }</code><technical_language>Integer.BYTES constant</technical_language>

Target:
public static DataWord of(int num) { return of(ByteBuffer.allocate(Integer.BYTES).putInt(num).array()); }
Source:
<code>public static FixedDoubleBreakdownHistogram deserialize(SliceInput input) { int bucketCount = input.readInt(); double min = input.readDouble(); double max = input.readDouble(); verifyParameters(bucketCount, min, max); int size = input.readInt(); int[] indices = new int[size]; double[] weights = new double[size]; long[] counts = new long[size]; <START> input.readBytes( <END> Slices.wrappedIntArray(indices), size * SizeOf.SIZE_OF_INT); input.readBytes( Slices.wrappedDoubleArray(weights), size * SizeOf.SIZE_OF_DOUBLE); input.readBytes( Slices.wrappedLongArray(counts), size * SizeOf.SIZE_OF_LONG); return new FixedDoubleBreakdownHistogram(bucketCount, min, max, indices, weights, counts); }</code><technical_language>put arguments line: input.readBytes(Slices.wrappedIntArray(indices), size * SizeOf.SIZE_OF_INT);</technical_language>

Target:
public static FixedDoubleBreakdownHistogram deserialize(SliceInput input) { int bucketCount = input.readInt(); double min = input.readDouble(); double max = input.readDouble(); validateParameters(bucketCount, min, max); int size = input.readInt(); int[] indices = new int[size]; double[] weights = new double[size]; long[] counts = new long[size]; input.readBytes(Slices.wrappedIntArray(indices), size * SizeOf.SIZE_OF_INT); input.readBytes(Slices.wrappedDoubleArray(weights), size * SizeOf.SIZE_OF_DOUBLE); input.readBytes(Slices.wrappedLongArray(counts), size * SizeOf.SIZE_OF_LONG); return new FixedDoubleBreakdownHistogram(bucketCount, min, max, indices, weights, counts); }
Source:
<code>private static void updateTimeoutLogableObject(AuditLogableBase auditLogable, AuditLogType logType) { int duplicateEventsIntrvalValue = (auditLogable.isExternal()) ? Math.max(auditLogable.getEventFloodInSec(), 30) : logType.getDuplicateEventsIntervalValue(); if (duplicateEventsIntrvalValue > 0) { <START> auditLogable.setEndTime(System.currentTimeMillis() + logType.getDuplicateEventsIntervalValue()); <END> auditLogable.setTimeoutObjectId(composeObjectId(auditLogable, logType)); } }</code><technical_language>convert logType.getDuplicateEventsIntervalV millis</technical_language>

Target:
private static void updateTimeoutLogableObject(AuditLogableBase auditLogable, AuditLogType logType) { int duplicateEventsIntrvalValue = (auditLogable.isExternal()) ? Math.max(auditLogable.getEventFloodInSec(), 30) : logType.getDuplicateEventsIntervalValue(); if (duplicateEventsIntrvalValue > 0) { auditLogable.setEndTime(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(logType.getDuplicateEventsIntervalValue())); auditLogable.setTimeoutObjectId(composeObjectId(auditLogable, logType)); } }
Source:
<code>private File doPostAndRetreiveFile(CloseableHttpClient httpClient, HttpRequestBase request, String bundleName) throws ClientProtocolException, IOException { request.addHeader("accept", <START> ContentType.APPLICATION_JSON.getMimeType()); <END> File bundle; CloseableHttpResponse response = AnalyticsServiceStreamsContext .executeAndHandleErrors(httpClient, request); HttpEntity entity = response.getEntity(); try { InputStream is = null; FileOutputStream fos = null; byte[] buffer = new byte[1024]; try{ bundle = new File(bundleName); is = entity.getContent(); fos = new FileOutputStream(bundle); for(int length; (length = is.read(buffer)) > 0;){ fos.write(buffer, 0, length); } } finally{ if(is != null) try {is.close();} catch(IOException e) { throw e; } if(fos != null) try {fos.close();} catch(IOException e) { throw e; } } } finally { response.close(); } return bundle; }</code><technical_language>is returned is application/json, bundle</technical_language>

Target:
private File doPostAndRetreiveFile(CloseableHttpClient httpClient, HttpRequestBase request, String bundleName) throws ClientProtocolException, IOException { request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); File bundle; CloseableHttpResponse response = AnalyticsServiceStreamsContext .executeAndHandleErrors(httpClient, request); HttpEntity entity = response.getEntity(); try { InputStream is = null; FileOutputStream fos = null; byte[] buffer = new byte[1024*1024]; try{ bundle = new File(bundleName); is = entity.getContent(); fos = new FileOutputStream(bundle); for(int length; (length = is.read(buffer)) != -1;){ fos.write(buffer, 0, length); } } finally{ if(is != null) try {is.close();} catch(IOException e) { throw e; } if(fos != null) try {fos.close();} catch(IOException e) { throw e; } } } finally { response.close(); } return bundle; }
Source:
<code><START> public void testValidate() throws ValidationException { <END> Function<Element, LeaseElement> resourcesTypeSupplier = mock(Function.class); LeaseConfigValidator validator = new LeaseConfigValidator(resourcesTypeSupplier); LeaseConfigValidator spyValidator = spy(validator); Element xmlNode1 = mock(Element.class); Element xmlNode2 = mock(Element.class); LeaseElement leaseNode1 = new LeaseElement(); leaseNode1.setTimeUnit(TimeUnit.SECONDS.name()); leaseNode1.setLeaseValue("100"); LeaseElement leaseNode2 = new LeaseElement(); leaseNode2.setTimeUnit(TimeUnit.SECONDS.name()); leaseNode2.setLeaseValue("100"); doReturn(leaseNode1).when(spyValidator).createObject(xmlNode1); doReturn(leaseNode2).when(spyValidator).createObject(xmlNode2); spyValidator.validateAgainst(xmlNode1, xmlNode2); }</code><technical_language>meant element 2 minutes another element 120 seconds for e.g</technical_language>

Target:
public void testValidate() throws ValidationException { Function<Element, LeaseElement> resourcesTypeSupplier = mock(Function.class); LeaseConfigValidator validator = new LeaseConfigValidator(resourcesTypeSupplier); LeaseConfigValidator spyValidator = spy(validator); Element xmlNode1 = mock(Element.class); Element xmlNode2 = mock(Element.class); LeaseElement leaseNode1 = new LeaseElement("100",TimeUnit.SECONDS.name()); LeaseElement leaseNode2 = new LeaseElement("100", TimeUnit.SECONDS.name()); doReturn(leaseNode1).when(spyValidator).createObject(xmlNode1); doReturn(leaseNode2).when(spyValidator).createObject(xmlNode2); spyValidator.validateAgainst(xmlNode1, xmlNode2); }
Source:
<code>public void globalVerify() throws Exception { IList<MapOperationsCount> results = targetInstance.getList(basename + "report"); MapOperationsCount total = new MapOperationsCount(); for (MapOperationsCount i : results) { total.add(i); } log.info(basename + ": " + total + " total of " + results.size()); final IMap map = targetInstance.getMap(basename); TestUtils.assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(basename + ": Map Size not 0, some TTL events not processed", 0, map.size()); } <START> }, 300); <END> }</code><technical_language>pull this out a property</technical_language>

Target:
public void globalVerify() throws Exception { IList<MapOperationsCount> results = targetInstance.getList(basename + "report"); MapOperationsCount total = new MapOperationsCount(); for (MapOperationsCount i : results) { total.add(i); } log.info(basename + ": " + total + " total of " + results.size()); final IMap map = targetInstance.getMap(basename); TestUtils.assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(basename + ": Map Size not 0, some TTL events not processed", 0, map.size()); } }); }
Source:
<code>public void singleDigitsAreArmstrongNumbers() { int input = 5; boolean expected = true; <START> assertEquals(expected, armstrongNumbers.isArmstrongNumber(input)); <END> }</code><technical_language>assertTrue assertFalse instead of assertEquals for tests :)</technical_language>

Target:
public void singleDigitsAreArmstrongNumbers() { int input = 5; assertTrue(armstrongNumbers.isArmstrongNumber(input)); }
Source:
<code>public Transaction getTransaction(Xid xid) throws XAException { <START> Transaction transaction = com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple <END> .getTransaction(new XidImple(xid).getTransactionUid()); if(transaction == null) { transaction = SubordinationManager.getTransactionImporter().getImportedTransaction(xid); } return transaction; }</code><technical_language>I is a good chance is existing bug here. I is wrong try get ArjunaCore TransactionImple here, a JTS a copy/paste error here: <LINK_0> do @mmusgrov</technical_language>

Target:
public Transaction getTransaction(Xid xid) throws XAException { Transaction transaction = TransactionImple.getTransaction(new XidImple(xid).getTransactionUid()); if(transaction == null) { transaction = SubordinationManager.getTransactionImporter().getImportedTransaction(xid); } return transaction; }
Source:
<code>public void writeUserPrefs(CommandWithArg<Boolean> onCompleted) { <START> UpdatePrefs(session_.getSessionInfo().getPrefs()); <END> server_.setUserPrefs( session_.getSessionInfo().getUserPrefs(), new ServerRequestCallback<Void>() { @Override public void onResponseReceived(Void v) { UserPrefsChangedEvent event = new UserPrefsChangedEvent( session_.getSessionInfo().getUserPrefLayer()); if (Satellite.isCurrentWindowSatellite()) { RStudioGinjector.INSTANCE.getEventBus() .fireEventToMainWindow(event); } else { satelliteManager_.dispatchCrossWindowEvent(event); } if (onCompleted != null) { onCompleted.execute(true); } } @Override public void onError(ServerError error) { if (onCompleted != null) { onCompleted.execute(false); } Debug.logError(error); } }); }</code><technical_language>nit: method name camelCase</technical_language>

Target:
public void writeUserPrefs(CommandWithArg<Boolean> onCompleted) { updatePrefs(session_.getSessionInfo().getPrefs()); server_.setUserPrefs( session_.getSessionInfo().getUserPrefs(), new ServerRequestCallback<Void>() { @Override public void onResponseReceived(Void v) { UserPrefsChangedEvent event = new UserPrefsChangedEvent( session_.getSessionInfo().getUserPrefLayer()); if (Satellite.isCurrentWindowSatellite()) { RStudioGinjector.INSTANCE.getEventBus() .fireEventToMainWindow(event); } else { satelliteManager_.dispatchCrossWindowEvent(event); } if (onCompleted != null) { onCompleted.execute(true); } } @Override public void onError(ServerError error) { if (onCompleted != null) { onCompleted.execute(false); } Debug.logError(error); } }); }
Source:
<code>private void zipFileSystem(FileSystem fs, ZipOutputStream zos) { Path root = fs.getRootDirectories().iterator().next(); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { try { String location = fs.getName() + path.toString(); zipFile(path.toFile(), location, zos); return FileVisitResult.CONTINUE; } catch (Exception e) { <START> e.printStackTrace(); <END> return FileVisitResult.TERMINATE; } } }); }</code><technical_language>I suggest logging this exception instead of printing stacktrace</technical_language>

Target:
private void zipFileSystem(FileSystem fs, ZipOutputStream zos) { Path root = fs.getRootDirectories().iterator().next(); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) { try { String location = fs.getName() + path.toString(); zipFile(path.toFile(), location, zos); return FileVisitResult.CONTINUE; } catch (Exception e) { LOGGER.error(e.getMessage(), e); return FileVisitResult.TERMINATE; } } }); }
Source:
<code>public void teardown() { closeQuietly(handle); <START> mySqlServer.close(); <END> }</code><technical_language>closeQuietly(mySqlServer, handle)</technical_language>

Target:
public void teardown() { closeQuietly(mySqlServer, handle); }
Source:
<code>private void parseMakeRequest() throws CommCareSessionException { String command = sessionWrapper.getCommand(); Entry commandEntry = sessionWrapper.getPlatform().getEntry(command); if (commandEntry instanceof RemoteRequestEntry) { PostRequest syncPost = ((RemoteRequestEntry)commandEntry).getPostRequest(); Response response = makeSyncRequest(syncPost); if (response == null || !response.isSuccessful()) { printStream.println(String.format("Sync failed with response %s", response)); printStream.println("Press 'enter' to retry."); return; } syncSuccessful = true; ApplicationHost.restoreUserToSandbox(sessionWrapper.getSandbox(), sessionWrapper, sessionWrapper.getPlatform(), username, password); printStream.println(String.format("Sync successful with response %s", response)); printStream.println("Press 'enter' to continue."); } else { <START> throw new CommCareSessionException("Initialized sync request while not on sync screen"); <END> } }</code><technical_language>issues I/O process response re-tryable kill session in event of network issues. revisit making I/O part of this a binary process? Also: primary purpose of CLI is Debugging, swallowing issues vague errors lazt line of defense. intentional fail right step retain roper context. commit output a useful error message before..</technical_language>

Target:
private void parseMakeRequest() throws CommCareSessionException { String command = sessionWrapper.getCommand(); Entry commandEntry = sessionWrapper.getPlatform().getEntry(command); if (!(commandEntry instanceof RemoteRequestEntry)) { throw new CommCareSessionException("Initialized sync request while not on sync screen"); } PostRequest syncPost = ((RemoteRequestEntry)commandEntry).getPostRequest(); try { Response response = makeSyncRequest(syncPost); if (!response.isSuccessful()) { printStream.println(String.format("Sync request failed with response code %s and message %s", response.code(), response.body())); printStream.println("Press 'enter' to retry."); return; } syncSuccessful = true; SessionUtils.restoreUserToSandbox(sessionWrapper.getSandbox(), sessionWrapper, sessionWrapper.getPlatform(), username, password, printStream); printStream.println(String.format("Sync successful with response %s", response)); printStream.println("Press 'enter' to continue."); } catch (IOException e) { e.printStackTrace(); printStream.println(String.format("Sync failed with exception %s", e.getMessage())); printStream.println("Press 'enter' to retry."); } }
Source:
<code>private boolean isMetacardTagsSet(Metacard metacard) { <START> Attribute attribute = metacard.getAttribute(Core.METACARD_TAGS); <END> if (attribute == null) { return false; } return CollectionUtils.isNotEmpty(attribute.getValues()); }</code><technical_language>return !metacard.getTags().isEmpty();</technical_language>

Target:
private boolean isMetacardTagsSet(Metacard metacard) { return !metacard.getTags().isEmpty(); }
Source:
<code>@After public void tearDown() throws Exception { if (socksProxy != null) { socksProxy.shutdown(); } if (cache != null) { cache.delete(); } client.connectionPool().evictAll(); <START> if (client.connectionPool().connectionCount() > 0) { <END> System.out.println("Delaying to avoid flakes"); Thread.sleep(500L); System.out.println("After delay: " + client.connectionPool().connectionCount()); } }</code><technical_language>.. assertion for this. replace assertion this</technical_language>

Target:
@After public void tearDown() throws Exception { if (socksProxy != null) { socksProxy.shutdown(); } if (cache != null) { cache.delete(); } }
Source:
<code>public static X509Certificate publicKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); if (!matcher.find()) { <START> throw LOGGER.logErrorAndThrow(new IllegalArgumentException("PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); <END> } try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream stream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8)); return (X509Certificate) factory.generateCertificate(stream); } catch (CertificateException e) { throw LOGGER.logErrorAndThrow(new IllegalStateException(e)); } }</code><technical_language>logErrorAndThrow() throw RuntimeError internally. A ClientLogger static naming of ClientLogger variable 'logger'. applies other changes well</technical_language>

Target:
public static X509Certificate publicKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); if (!matcher.find()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); } try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream stream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8)); return (X509Certificate) factory.generateCertificate(stream); } catch (CertificateException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } }
Source:
<code>public void testListSnapshotsWithNullAndEmptyString() { Exception actualError = null; try { listSnapshotsSize((String) null); } catch (Exception ex) { actualError = ex; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); actualError = null; <START> try { <END> assertEquals(0, listSnapshotsSize((Pattern) null)); } catch (Exception ex) { actualError = ex; } assertNull(actualError); actualError = null; try { assertEquals(0, listSnapshotsSize("")); } catch (Exception ex) { actualError = ex; } assertNull(actualError); }</code><technical_language>else, please remove unnecessary try blocks</technical_language>

Target:
public void testListSnapshotsWithNullAndEmptyString() throws IOException { Exception actualError = null; try { listSnapshotsSize((String) null); } catch (Exception ex) { actualError = ex; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); assertEquals(0, listSnapshotsSize((Pattern) null)); assertEquals(0, listSnapshotsSize("")); }
Source:
<code>private AlleleFractionState.MinorFractions estimateMinorFractions(final AlleleFractionData data) { <START> AlleleFractionState.MinorFractions result = new AlleleFractionState.MinorFractions(); <END> for (int segment = 0; segment < data.numSegments(); segment++) { result.add(estimateMinorFraction(segment, data)); } return result; }</code><technical_language>final (or this a liner streams, if like)</technical_language>

Target:
private AlleleFractionState.MinorFractions estimateMinorFractions(final AlleleFractionData data) { return new AlleleFractionState.MinorFractions( IntStream.range(0, data.numSegments()) .mapToDouble(segment -> estimateMinorFraction(segment, data)) .boxed().collect(Collectors.toList())); }
Source:
<code>private void invokeExceptionCaughtFromOutbound(Throwable t) { if ((executionMask & MASK_EXCEPTION_CAUGHT) != 0) { <START> invokeExceptionCaught(t); <END> } else { findContextInbound(MASK_EXCEPTION_CAUGHT).invokeExceptionCaught(t); } }</code><technical_language>notifyHandlerException()? inExceptionCaught() checks, apply else</technical_language>

Target:
private void invokeExceptionCaughtFromOutbound(Throwable t) { if ((executionMask & MASK_EXCEPTION_CAUGHT) != 0) { notifyHandlerException(t); } else { findContextInbound(MASK_EXCEPTION_CAUGHT).notifyHandlerException(t); } }
Source:
<code>private CacheEntryEvent<? extends K, ? extends V> launderEvent( CacheEntryEvent<? extends K, ? extends V> e, CacheEntryListenerConfiguration<K, V> cfg) { switch (e.getEventType()) { case UPDATED: case REMOVED: case EXPIRED: if (cfg.isOldValueRequired()) <START> return new RICacheEntryEvent<>(e.getSource(), e.getKey(), e.getValue(), e.getOldValue(), e.getEventType()); <END> if (e.getEventType() == EventType.REMOVED || e.getEventType() == EventType.EXPIRED) return new RICacheEntryEvent<>(e.getSource(), e.getKey(), null, null, e.getEventType(), false); return new RICacheEntryEvent(e.getSource(), e.getKey(), e.getValue(), null, e.getEventType(), false); default: return e; } }</code><technical_language>return event creating a new instance</technical_language>

Target:
private CacheEntryEvent<? extends K, ? extends V> launderEvent( CacheEntryEvent<? extends K, ? extends V> e, CacheEntryListenerConfiguration<K, V> cfg) { switch (e.getEventType()) { case UPDATED: case REMOVED: case EXPIRED: if (cfg.isOldValueRequired()) return e; if (e.getEventType() == EventType.REMOVED || e.getEventType() == EventType.EXPIRED) return new RICacheEntryEvent<>(e.getSource(), e.getKey(), null, null, e.getEventType(), false); return new RICacheEntryEvent(e.getSource(), e.getKey(), e.getValue(), e.getEventType()); default: return e; } }
Source:
<code>IndexValue(String logSegmentName, ByteBuffer value, short version) { this.version = version; switch (version) { case PersistentIndex.VERSION_0: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V0) { throw new IllegalArgumentException("Invalid buffer size for version 0"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); expiresAtMs = value.getLong(); originalMessageOffset = value.getLong(); operationTimeInMs = (int) Utils.Infinite_Time; serviceId = SERVICE_CONTAINER_ID_DEFAULT_VALUE; containerId = SERVICE_CONTAINER_ID_DEFAULT_VALUE; break; case PersistentIndex.VERSION_1: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V1) { throw new IllegalArgumentException("Invalid buffer size for version 1"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); int expiresAt = value.getInt(); <START> expiresAtMs = expiresAt != Utils.Infinite_Time ? ((long) expiresAt * Time.MsPerSec) : Utils.Infinite_Time; <END> originalMessageOffset = value.getLong(); int operationTimeInSecs = value.getInt(); operationTimeInMs = operationTimeInSecs != Utils.Infinite_Time ? ((long) operationTimeInSecs * Time.MsPerSec) : Utils.Infinite_Time; serviceId = value.getShort(); containerId = value.getShort(); break; default: throw new IllegalArgumentException("Unsupported version " + version + " passed in for IndexValue "); } }</code><technical_language>declare expiresAt a long with</technical_language>

Target:
IndexValue(String logSegmentName, ByteBuffer value, short version) { this.version = version; switch (version) { case PersistentIndex.VERSION_0: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V0) { throw new IllegalArgumentException("Invalid buffer size for version 0"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); expiresAtMs = value.getLong(); originalMessageOffset = value.getLong(); operationTimeInMs = (int) Utils.Infinite_Time; serviceId = SERVICE_CONTAINER_ID_DEFAULT_VALUE; containerId = SERVICE_CONTAINER_ID_DEFAULT_VALUE; break; case PersistentIndex.VERSION_1: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V1) { throw new IllegalArgumentException("Invalid buffer size for version 1"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); long expiresAt = value.getInt(); expiresAtMs = expiresAt != Utils.Infinite_Time ? (expiresAt * Time.MsPerSec) : Utils.Infinite_Time; originalMessageOffset = value.getLong(); long operationTimeInSecs = value.getInt(); operationTimeInMs = operationTimeInSecs != Utils.Infinite_Time ? (operationTimeInSecs * Time.MsPerSec) : Utils.Infinite_Time; serviceId = value.getShort(); containerId = value.getShort(); break; default: throw new IllegalArgumentException("Unsupported version " + version + " passed in for IndexValue "); } }
Source:
<code>public void stop() { <START> if (Objects.nonNull(metadataStore)) { <END> metadataStore.flush(); metadataStore.close(); metadataStore = null; LOG.info("StartpointManager has stopped and this instance can no longer be used."); } else { LOG.warn("StartpointManager has already stopped"); } }</code><technical_language>1. Do need stop idempotent? 2. do need set metadatastore null here. a boolean variable stop idempotent</technical_language>

Target:
public void stop() { if (started) { metadataStore.close(); started = false; } else { LOG.warn("StartpointManager already stopped."); } }
Source:
<code><START> protected File atomicFileCreate(String filename) throws FileNotFoundException, IOException { <END> File file = new File(ROOT_DIR, filename + ".tmp"); File fileFinal = new File(ROOT_DIR, "test.txt"); file.delete(); file.deleteOnExit(); fileFinal.delete(); fileFinal.deleteOnExit(); FileOutputStream fos = new FileOutputStream(file); fos.write("this is a test\nline2\n".getBytes()); fos.close(); assertTrue(file.renameTo(fileFinal)); return fileFinal; }</code><technical_language>I understand why, if this method takes a parameter, name of "hidden" file</technical_language>

Target:
protected File atomicFileCreate(String filename) throws FileNotFoundException, IOException { File file = new File(ROOT_DIR, filename + ".tmp"); File fileFinal = new File(ROOT_DIR, filename); file.delete(); file.deleteOnExit(); fileFinal.delete(); fileFinal.deleteOnExit(); FileOutputStream fos = new FileOutputStream(file); fos.write("this is a test\nline2\n".getBytes()); fos.close(); assertTrue(file.renameTo(fileFinal)); return fileFinal; }
Source:
<code>public LogReplicationSourceManager(LogReplicationRuntimeParameters params, LogReplicationClient client, LogReplicationMetadataManager metadataManager) { this.runtime = CorfuRuntime.fromParameters(CorfuRuntimeParameters.builder() .trustStore(params.getTrustStore()) .tsPasswordFile(params.getTsPasswordFile()) .keyStore(params.getKeyStore()) .ksPasswordFile(params.getKsPasswordFile()) .tlsEnabled(params.isTlsEnabled()).build()); runtime.parseConfigurationString(params.getLocalCorfuEndpoint()).connect(); this.parameters = params; this.config = parameters.getReplicationConfig(); if (config.getStreamsToReplicate() == null || config.getStreamsToReplicate().isEmpty()) { throw new IllegalArgumentException("Invalid Log Replication: Streams to replicate is EMPTY"); } DataSender dataSender = new CorfuDataSender(client); ExecutorService logReplicationFSMWorkers = Executors.newFixedThreadPool(DEFAULT_FSM_WORKER_THREADS, new ThreadFactoryBuilder().setNameFormat("state-machine-worker").build()); ReadProcessor readProcessor = new DefaultReadProcessor(runtime); this.logReplicationFSM = new LogReplicationFSM(this.runtime, config, params.getRemoteClusterDescriptor(), dataSender, readProcessor, logReplicationFSMWorkers); this.logReplicationFSM.setTopologyConfigId(params.getTopologyConfigId()); this.metadataManager = metadataManager; <START> lastAckedTsPoller.scheduleWithFixedDelay(new TsPollingTask(), 0, 15, TimeUnit.SECONDS); <END> }</code><technical_language>poll interval a static field? want move this param configurable need adjust UI / SM polling frequency</technical_language>

Target:
public LogReplicationSourceManager(LogReplicationRuntimeParameters params, LogReplicationClient client, LogReplicationMetadataManager metadataManager) { this(params, metadataManager, new CorfuDataSender(client)); }
Source:
<code>public static void disableLinks(Browser browser) { if (browser != null && !browser.isDisposed()) { String disableHrefScript = (PlatformUtil.isWindows()) ? "'#'" : "'javascript: void(0);'"; String disablerScript = "var anchors = document.getElementsByTagName('a');" + "for (var i = 0; i < anchors.length; i++) {" + <START> "if (anchors[i].href.indexOf('#') == -1) {" + END> "anchors[i].href = " + disableHrefScript + ";" + "anchors[i].target = '';" + "}" + "};"; browser.execute("(setTimeout(function() { " + disablerScript + "}, 10))();"); disableDynamic(browser, disablerScript); } }</code><technical_language>wont this ignore: <LINK_0></technical_language>

Target:
public static void disableLinks(Browser browser) { if (browser != null && !browser.isDisposed()) { String disableHrefScript = (PlatformUtil.isWindows()) ? "'#'" : "'javascript: void(0);'"; String disablerScript = "var anchors = document.getElementsByTagName('a');" + "for (var i = 0; i < anchors.length; i++) {" + "if (anchors[i].href.indexOf('#') == -1 || anchors[i].href.indexOf('://localhost:') == -1) {" + "anchors[i].href = " + disableHrefScript + ";" + "anchors[i].target = '';" + "}" + "};"; browser.execute("(setTimeout(function() { " + disablerScript + "}, 10))();"); disableDynamic(browser, disablerScript); } }
Source:
<code>public void testGetAllForVdsGroupWithPermissionsForUnpriviligedUser() { List<VDS> result = dao.getAllForVdsGroup(existingVds.getvds_group_id(), UNPRIVILEGED_USER_ID, true); assertNotNull(result); <START> assertTrue(result.size() == 0); <END> }</code><technical_language>isEmpty()</technical_language>

Target:
public void testGetAllForVdsGroupWithPermissionsForUnpriviligedUser() { List<VDS> result = dao.getAllForVdsGroup(existingVds.getvds_group_id(), UNPRIVILEGED_USER_ID, true); assertNotNull(result); assertTrue(result.isEmpty()); }
Source:
<code>private void dismissPreparingDialog() { <START> PrepareDialogFragment fragment = (PrepareDialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.prepare_dialog)); <END> if (fragment != null && fragment.isAdded()) { fragment.dismiss(); } }</code><technical_language>I dont reason for adding this string.xml. is a string resource, is more of id. want this change if decide translate App strings later. A move Constants class</technical_language>

Target:
private void dismissPreparingDialog() { PrepareDialogFragment fragment = (PrepareDialogFragment) getSupportFragmentManager().findFragmentByTag("prepare_dialog"); if (fragment != null && fragment.isAdded()) { fragment.dismiss(); } }
Source:
<code>static List<HostSpecStatus> getCandidateHosts(HostSpec[] hostSpecs, HostRequirement targetServerType, long hostRecheckMillis) { List<HostSpecStatus> candidates = new ArrayList<HostSpecStatus>(hostSpecs.length); long latestAllowedUpdate = currentTimeMillis() - hostRecheckMillis; synchronized (hostStatusMap) { for (HostSpec hostSpec : hostSpecs) { HostSpecStatus hostInfo = hostStatusMap.get(hostSpec); if (hostInfo == null) { hostInfo = new HostSpecStatus(hostSpec, null, Long.MAX_VALUE); } if (hostInfo.status == null <START> || hostInfo.lastUpdated < latestAllowedUpdate <END> || targetServerType.allowConnectingTo(hostInfo.status)) { candidates.add(hostInfo); } } } return candidates; }</code><technical_language>is due "host recheck", forget master/slave status of host. ends (host1==master, host2==slave, host3==unknown, host4==unknown) kind of states. In case, for loadBalance=true; connect=preferSlave try connecting unknown hosts try finding a slave (between unknowns known-slaves). I see, change "never reset status", I do is a good change</technical_language>

Target:
static List<HostSpec> getCandidateHosts(HostSpec[] hostSpecs, HostRequirement targetServerType, long hostRecheckMillis) { List<HostSpec> candidates = new ArrayList<HostSpec>(hostSpecs.length); long latestAllowedUpdate = currentTimeMillis() - hostRecheckMillis; synchronized (hostStatusMap) { for (HostSpec hostSpec : hostSpecs) { HostSpecStatus hostInfo = hostStatusMap.get(hostSpec); if (hostInfo == null || hostInfo.lastUpdated < latestAllowedUpdate || targetServerType.allowConnectingTo(hostInfo.status)) { candidates.add(hostSpec); } } } return candidates; }
Source:
<code>public static Lyrics parse(Song song, String data) { Lyrics lyrics = new SynchronizedLyricsLRC(song, data); if (lyrics.isValid()) { return lyrics.parse(false); } else { <START> return new Lyrics(song, data).parse(false); <END> } }</code><technical_language>a bit unsure specifically SynchronizedLyricsLRC in base Lyrics class. complicated if/when add more formats</technical_language>

Target:
public static Lyrics parse(Song song, String data) { for (Class<? extends Lyrics> format : Lyrics.FORMATS) { try { Lyrics lyrics = format.newInstance().setData(song, data); if (lyrics.isValid()) return lyrics.parse(false); } catch (Exception e) { e.printStackTrace(); } } return new Lyrics().setData(song, data).parse(false); }
Source:
<code>private boolean tryAssignTask(final Task task, final RemoteTaskRunnerWorkItem taskRunnerWorkItem) throws Exception { Preconditions.checkNotNull(task, "task"); Preconditions.checkNotNull(taskRunnerWorkItem, "taskRunnerWorkItem"); Preconditions.checkArgument(task.getId().equals(taskRunnerWorkItem.getTaskId()), "task id != workItem id"); if (runningTasks.containsKey(task.getId()) || findWorkerRunningTask(task.getId()) != null) { log.info("Task[%s] already running.", task.getId()); return true; } else { <START> Optional<ZkWorker> zkWorker = strategy.findWorkerForTask(zkWorkers, task); <END> if (zkWorker.isPresent()) { announceTask(task, zkWorker.get(), taskRunnerWorkItem); return true; } else { return false; } } }</code><technical_language>Similar issue ZkWorker objects themselves; cool ImmutableZkWorker coordinator for druid servers get that</technical_language>

Target:
private boolean tryAssignTask(final Task task, final RemoteTaskRunnerWorkItem taskRunnerWorkItem) throws Exception { Preconditions.checkNotNull(task, "task"); Preconditions.checkNotNull(taskRunnerWorkItem, "taskRunnerWorkItem"); Preconditions.checkArgument(task.getId().equals(taskRunnerWorkItem.getTaskId()), "task id != workItem id"); if (runningTasks.containsKey(task.getId()) || findWorkerRunningTask(task.getId()) != null) { log.info("Task[%s] already running.", task.getId()); return true; } else { final Optional<ImmutableZkWorker> immutableZkWorker = strategy.findWorkerForTask( ImmutableMap.copyOf( Maps.transformEntries( zkWorkers, new Maps.EntryTransformer<String, ZkWorker, ImmutableZkWorker>() { @Override public ImmutableZkWorker transformEntry( String key, ZkWorker value ) { return value.toImmutable(); } } ) ), task ); if (immutableZkWorker.isPresent()) { final ZkWorker zkWorker = zkWorkers.get(immutableZkWorker.get().getWorker().getHost()); announceTask(task, zkWorker, taskRunnerWorkItem); return true; } else { log.debug("Worker nodes %s do not have capacity to run any more tasks!", zkWorkers.values()); return false; } } }
Source:
<code>public String toString() { return "BackupMultiKeyWriteRpcCommand{" + <START> "commandInvocationId=" + commandInvocationId + <END> ", map=" + map + ", metadata=" + metadata + ", flags=" + EnumUtil.prettyPrintBitSet(flags, Flag.class) + ", topologyId=" + topologyId + ", sequence=" + sequence + '}'; }</code><technical_language>pls update</technical_language>

Target:
public String toString() { return "BackupMultiKeyWriteRpcCommand{" + "operation=" + operation + ", commandInvocationId=" + commandInvocationId + ", entries=" + entries + ", metadata=" + metadata + ", flags=" + EnumUtil.prettyPrintBitSet(flags, Flag.class) + ", topologyId=" + topologyId + ", sequence=" + sequence + ", function=" + function + ", params=" + params + ", keyDataConversion=" + keyDataConversion + ", valueDataConversion=" + valueDataConversion + ", cacheName=" + cacheName + '}'; }
Source:
<code>public void uninstall() { <START> CommCareApplication._().logout(); <END> CommCareApplication._().initializeAppResources(new CommCareApp(appRecord)); CommCareApp app = CommCareApplication._().getCurrentApp(); app.teardownSandbox(); SqlStorage<UserKeyRecord> userDatabase = CommCareApplication._().getAppStorage(UserKeyRecord.class); for (UserKeyRecord user : userDatabase) { this.getDatabasePath(CommCareUserOpenHelper.getDbName(user.getUuid())).delete(); } this.getDatabasePath(DatabaseAppOpenHelper.getDbName(app.getAppRecord().getApplicationId())).delete(); CommCareApplication._().getGlobalStorage(ApplicationRecord.class).remove(appRecord.getID()); CommCareApplication._().setAppResourceState(CommCareApplication.STATE_UNINSTALLED); rebootCommCare(); }</code><technical_language>do a good of attempting try database ops atomic clean possible? IE: do this set resource state (or some variable) "STATE_DELETE_REQUESTED", try delete, remote record entirely. In this state easy for some of actions complete others in a oculd leave app in a bad state (We set uninstalled flag very, end, if get 2/3 app 2/3 deleted why</technical_language>

Target:
private void uninstall() { CommCareApplication._().expireUserSession(); CommCareApplication._().uninstall(appRecord); rebootCommCare(); }
Source:
<code>protected MistDataEvent generateEvent(final I input) { if (extractTimestampFunc == null) { <START> return new MistDataEvent(input, TimestampGenerator.getCurrentTimestamp()); <END> } else { Tuple<V, Long> extractionResult = extractTimestampFunc.apply(input); if (extractionResult.getKey() == null || extractionResult.getValue() == null) { throw new IllegalArgumentException("Timestamp extraction from input data is failed. Data is " + extractionResult.getKey().toString() + ", timestamp is " + extractionResult.getValue().toString()); } return new MistDataEvent(extractionResult.getKey(), extractionResult.getValue()); } }</code><technical_language>This separate event generators ordered</technical_language>

Target:
protected MistDataEvent generateEvent(final I input) { if (extractTimestampFunc == null) { return new MistDataEvent(input, getCurrentTimestamp()); } else { Tuple<V, Long> extractionResult = extractTimestampFunc.apply(input); if (extractionResult.getKey() == null || extractionResult.getValue() == null) { throw new IllegalArgumentException("Timestamp extraction from input data is failed. Data is " + extractionResult.getKey().toString() + ", timestamp is " + extractionResult.getValue().toString()); } return new MistDataEvent(extractionResult.getKey(), extractionResult.getValue()); } }
Source:
<code>public String getRequestor(final AllocatedEvaluator allocatedEvaluator) { final String evaluatorId = allocatedEvaluator.getId(); if (!idMap.containsKey(evaluatorId)) { <START> final Map.Entry<String, EventHandler<ActiveContext>> value = requestQueue.poll(); <END> if (value == null) { LOG.severe("Failed to find a requestor for " + allocatedEvaluator.toString()); return null; } else { final String requestorId = value.getKey(); final EventHandler<ActiveContext> handler = value.getValue(); idMap.put(evaluatorId, requestorId); resourceRequestCallbackRouter.register(evaluatorId, handler); return requestorId; } } else { return idMap.get(evaluatorId); } }</code><technical_language>assuming if is outstanding request? a request request multiple evaluators. do match</technical_language>

Target:
public String getRequestor(final AllocatedEvaluator allocatedEvaluator) { final String evaluatorId = allocatedEvaluator.getId(); if (!idMap.containsKey(evaluatorId)) { final Map.Entry<String, EventHandler<ActiveContext>> value = requestQueue.poll(); if (value == null) { LOG.severe("Failed to find a requestor for " + allocatedEvaluator.toString()); return null; } else { final String requestorId = value.getKey(); final EventHandler<ActiveContext> handler = value.getValue(); idMap.put(evaluatorId, requestorId); handlerMap.put(evaluatorId, handler); return requestorId; } } else { return idMap.get(evaluatorId); } }