auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Money parse(String amountStr) { ArgChecker.notNull(amountStr, "amountStr"); List<String> split = Splitter.on(' ').splitToList(amountStr); if (split.size() != 2) { throw new IllegalArgumentException("Unable to parse amount, invalid format: " + amountStr); } try { Currency cur = Currency.parse(split.get(0)); <START> double amount = Double.parseDouble(split.get(1)); <END> return new Money(cur, BigDecimal.valueOf(amount)); } catch (RuntimeException ex) { throw new IllegalArgumentException("Unable to parse amount: " + amountStr, ex); } }</code><technical_language>create BigDecimal string creating a double (which able express amount) creating a BigDecimal that. new BigDecimal(split.get(1));</technical_language>

Target:
public static Money parse(String amountStr) { ArgChecker.notNull(amountStr, "amountStr"); List<String> split = Splitter.on(' ').splitToList(amountStr); if (split.size() != 2) { throw new IllegalArgumentException("Unable to parse amount, invalid format: " + amountStr); } try { Currency cur = Currency.parse(split.get(0)); return new Money(cur, new BigDecimal(split.get(1))); } catch (RuntimeException ex) { throw new IllegalArgumentException("Unable to parse amount: " + amountStr, ex); } }
Source:
<code>public void start() { if (memoryConfiguration.storageType() == StorageType.OFF_HEAP) { minSize = UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(memoryConfiguration.addressCount() << 3); currentSize.set(minSize); } <START> if (container instanceof InternalDataContainer) { <END> listener = this::entriesRemoved; ((InternalDataContainer) container).addRemovalListener(listener); } if (!cache.getCacheConfiguration().clustering().cacheMode().isClustered()) { cache.getAdvancedCache().withEncoding(IdentityEncoder.class).withWrapping(IdentityWrapper.class).addListener(this); } }</code><technical_language>longer necessary</technical_language>

Target:
public void start() { if (memoryConfiguration.storageType() == StorageType.OFF_HEAP) { minSize = UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(memoryConfiguration.addressCount() << 3); currentSize.set(minSize); } listener = this::entriesRemoved; container.addRemovalListener(listener); if (!cache.getCacheConfiguration().clustering().cacheMode().isClustered()) { cache.getAdvancedCache().withEncoding(IdentityEncoder.class).withWrapping(IdentityWrapper.class).addListener(this); } }
Source:
<code>public FileStore fileStore() { <START> String currentDir = System.getProperty("user.dir"); <END> if (!currentDir.endsWith(File.separator)) { currentDir = currentDir + File.separator; } String molgenisFileStoreDirStr = currentDir + "data" + File.separator + "filestore"; File molgenisDataDir = new File(molgenisFileStoreDirStr); if (!molgenisDataDir.exists() && !molgenisDataDir.mkdirs()) { throw new RuntimeException("failed to create directory: " + molgenisFileStoreDirStr); } return new FileStore(molgenisFileStoreDirStr); }</code><technical_language>user.dir is molgenis home directory. create a random folder in OS temp dir</technical_language>

Target:
public FileStore fileStore() { String currentDir = System.getProperty("java.io.tmpdir") + File.separator + UUID.randomUUID() .toString() .replaceAll("-", ""); if (!currentDir.endsWith(File.separator)) { currentDir = currentDir + File.separator; } String molgenisFileStoreDirStr = currentDir + "data" + File.separator + "filestore"; File molgenisDataDir = new File(molgenisFileStoreDirStr); if (!molgenisDataDir.exists() && !molgenisDataDir.mkdirs()) { throw new RuntimeException("failed to create directory: " + molgenisFileStoreDirStr); } return new FileStore(molgenisFileStoreDirStr); }
Source:
<code>public void onLocationChanged(Location location) { this.location = toGeoPointData(location); Log.i("HereFunctionHandler", "location has been set to " + this.location.getDisplayText()); <START> if (this.location.getAccuracy() <= GeoUtils.ACCEPTABLE_ACCURACY) { <END> locationGoodEnough = true; forbidGpsUse(); } if (entitySelectActivity != null) { entitySelectActivity.onLocationChanged(); } }</code><technical_language>getAccuracy in current master branch of javarosa. create a cross-requested javarosa PR this merged break everyone's master builds</technical_language>

Target:
public void onLocationChanged(Location location) { this.location = toGeoPointData(location); Log.i("HereFunctionHandler", "location has been set to " + this.location.getDisplayText()); if (this.location.getAccuracy() <= GeoUtils.ACCEPTABLE_ACCURACY) { locationGoodEnough = true; forbidGpsUse(); } if (entitySelectActivity != null) { entitySelectActivity.onEvalLocationChanged(); } }
Source:
<code>private void navigate(@NonNull NavDestination node, @Nullable Bundle args, @Nullable NavOptions navOptions, @Nullable Navigator.Extras navigatorExtras) { boolean popped = false; if (navOptions != null) { if (navOptions.getPopUpTo() != -1) { popped = popBackStackInternal(navOptions.getPopUpTo(), navOptions.isPopUpToInclusive()); } } Navigator<NavDestination> navigator = mNavigatorProvider.getNavigator( node.getNavigatorName()); Bundle finalArgs = node.addInDefaultArgs(args); NavDestination newDest = navigator.navigate(node, finalArgs, navOptions, navigatorExtras); if (newDest != null) { if (mBackStack.isEmpty()) { mBackStack.add(new NavBackStackEntry(mGraph, finalArgs)); } ArrayDeque<NavBackStackEntry> hierarchy = new ArrayDeque<>(); NavDestination destination = newDest; while (destination != null && findDestination(destination.getId()) == null) { NavGraph parent = destination.getParent(); if (parent != null) { hierarchy.addFirst(new NavBackStackEntry(parent, finalArgs)); if (!node.getNavigatorName().equals(parent.getNavigatorName())) { Navigator<NavGraph> parentNavigator = mNavigatorProvider.getNavigator( parent.getNavigatorName()); <START> parentNavigator.navigate(parent, <END> finalArgs, navOptions, navigatorExtras); navigator.popBackStack(); } } destination = parent; } mBackStack.addAll(hierarchy); NavBackStackEntry newBackStackEntry = new NavBackStackEntry(newDest, newDest.addInDefaultArgs(finalArgs)); mBackStack.add(newBackStackEntry); } updateOnBackPressedCallbackEnabled(); if (popped || newDest != null) { dispatchOnDestinationChanged(); } }</code><technical_language>This is add in wrong order if multiple steps (i.e., a <navigation> node a <navigation> node start destination)</technical_language>

Target:
private void navigate(@NonNull NavDestination node, @Nullable Bundle args, @Nullable NavOptions navOptions, @Nullable Navigator.Extras navigatorExtras) { boolean popped = false; if (navOptions != null) { if (navOptions.getPopUpTo() != -1) { popped = popBackStackInternal(navOptions.getPopUpTo(), navOptions.isPopUpToInclusive()); } } Navigator<NavDestination> navigator = mNavigatorProvider.getNavigator( node.getNavigatorName()); Bundle finalArgs = node.addInDefaultArgs(args); NavDestination newDest = navigator.navigate(node, finalArgs, navOptions, navigatorExtras); if (newDest != null) { if (mBackStack.isEmpty()) { mBackStack.add(new NavBackStackEntry(mGraph, finalArgs)); } ArrayDeque<NavBackStackEntry> hierarchy = new ArrayDeque<>(); NavDestination destination = newDest; while (destination != null && findDestination(destination.getId()) == null) { NavGraph parent = destination.getParent(); if (parent != null) { hierarchy.addFirst(new NavBackStackEntry(parent, finalArgs)); } destination = parent; } mBackStack.addAll(hierarchy); NavBackStackEntry newBackStackEntry = new NavBackStackEntry(newDest, newDest.addInDefaultArgs(finalArgs)); mBackStack.add(newBackStackEntry); } updateOnBackPressedCallbackEnabled(); if (popped || newDest != null) { dispatchOnDestinationChanged(); } }
Source:
<code><START> public void testSuccessfullIdx() throws IOException { <END> final List<Pass> list = new ArrayList<Pass>(2); list.add(new PsFake(true)); list.add(new PsFake(true)); final Opt<Identity> identity = new PsAll(list, 1).enter(new RqFake()); MatcherAssert.assertThat( identity.has(), Matchers.is(true) ); }</code><technical_language>@lautarobock ditto, throws Exception</technical_language>

Target:
public void testSuccessfullIdx() throws Exception { final List<Pass> list = new ArrayList<Pass>(2); list.add(new PsFake(true)); list.add(new PsFake(true)); final Opt<Identity> identity = new PsAll(list, 1).enter(new RqFake()); MatcherAssert.assertThat( identity.has(), Matchers.is(true) ); }
Source:
<code>public void testGet() { Path path = new Path("/path"); PathMetadata pathMeta1 = new PathMetadata( new S3AFileStatus(true, new Path(path, "dir1"), TEST_OWNER)); PathMetadata pathMeta2 = new PathMetadata( new S3AFileStatus(true, new Path(path, "dir2"), TEST_OWNER)); PathMetadata pathMeta3 = new PathMetadata( new S3AFileStatus(123, 456, new Path(path, "file1"), 8192, TEST_OWNER, <START> "abc", "def")); <END> List<PathMetadata> listing = Arrays.asList(pathMeta1, pathMeta2, pathMeta3); DirListingMetadata meta = new DirListingMetadata(path, listing, false); assertEquals(path, meta.getPath()); assertNotNull(meta.getListing()); assertFalse(meta.getListing().isEmpty()); assertTrue(meta.getListing().contains(pathMeta1)); assertTrue(meta.getListing().contains(pathMeta2)); assertTrue(meta.getListing().contains(pathMeta3)); assertFalse(meta.isAuthoritative()); assertEquals(pathMeta1, meta.get(pathMeta1.getFileStatus().getPath())); assertEquals(pathMeta2, meta.get(pathMeta2.getFileStatus().getPath())); assertEquals(pathMeta3, meta.get(pathMeta3.getFileStatus().getPath())); assertNull(meta.get(new Path(path, "notfound"))); }</code><technical_language>TEST_ETAG TEST_VERSIONID here</technical_language>

Target:
public void testGet() { Path path = new Path("/path"); PathMetadata pathMeta1 = new PathMetadata( new S3AFileStatus(true, new Path(path, "dir1"), TEST_OWNER)); PathMetadata pathMeta2 = new PathMetadata( new S3AFileStatus(true, new Path(path, "dir2"), TEST_OWNER)); PathMetadata pathMeta3 = new PathMetadata( new S3AFileStatus(123, 456, new Path(path, "file1"), 8192, TEST_OWNER, TEST_ETAG, TEST_VERSION_ID)); List<PathMetadata> listing = Arrays.asList(pathMeta1, pathMeta2, pathMeta3); DirListingMetadata meta = new DirListingMetadata(path, listing, false); assertEquals(path, meta.getPath()); assertNotNull(meta.getListing()); assertFalse(meta.getListing().isEmpty()); assertTrue(meta.getListing().contains(pathMeta1)); assertTrue(meta.getListing().contains(pathMeta2)); assertTrue(meta.getListing().contains(pathMeta3)); assertFalse(meta.isAuthoritative()); assertEquals(pathMeta1, meta.get(pathMeta1.getFileStatus().getPath())); assertEquals(pathMeta2, meta.get(pathMeta2.getFileStatus().getPath())); assertEquals(pathMeta3, meta.get(pathMeta3.getFileStatus().getPath())); assertNull(meta.get(new Path(path, "notfound"))); }
Source:
<code>public void testSyncDoSet() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s/%s", _rootPath, "msg_0", "submsg_0"); ZNRecord record = new ZNRecord("submsg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); <START> AccessResult result = accessor.doSet(_gZkClient, path, record, -1, AccessOption.PERSISTENT); <END> Assert.assertEquals(result._retCode, RetCode.OK); Assert.assertEquals(result._pathCreated.size(), 3); Assert.assertTrue(result._pathCreated.contains(String.format("/%s/%s", _rootPath, "msg_0"))); Assert.assertTrue(result._pathCreated.contains(path)); Assert.assertTrue(_gZkClient.exists(String.format("/%s/%s", _rootPath, "msg_0"))); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "submsg_0"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); }</code><technical_language>If public API instead of removing, need change this all. In other words, diffs here</technical_language>

Target:
public void testSyncDoSet() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s/%s", _rootPath, "msg_0", "submsg_0"); ZNRecord record = new ZNRecord("submsg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); AccessResult result = accessor.doSet(path, record, -1, AccessOption.PERSISTENT); Assert.assertEquals(result._retCode, RetCode.OK); Assert.assertEquals(result._pathCreated.size(), 3); Assert.assertTrue(result._pathCreated.contains(String.format("/%s/%s", _rootPath, "msg_0"))); Assert.assertTrue(result._pathCreated.contains(path)); Assert.assertTrue(_gZkClient.exists(String.format("/%s/%s", _rootPath, "msg_0"))); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "submsg_0"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); }
Source:
<code>protected <T extends Connection> void parseConnectionList(EClass conType, EList<T> connectionlist, String parentNodeName) throws XMLStreamException, TypeImportException { processChildren(parentNodeName, name -> { if <START> (name.equals(LibraryElementTags.CONNECTION_ELEMENT)) { <END> T connection = parseConnection(conType); if (null != connection) { connectionlist.add(connection); } proceedToEndElementNamed(LibraryElementTags.CONNECTION_ELEMENT); return true; } return false; }); }</code><technical_language>call constant</technical_language>

Target:
protected <T extends Connection> void parseConnectionList(EClass conType, EList<T> connectionlist, String parentNodeName) throws XMLStreamException, TypeImportException { processChildren(parentNodeName, name -> { if (LibraryElementTags.CONNECTION_ELEMENT.equals(LibraryElementTags.CONNECTION_ELEMENT)) { T connection = parseConnection(conType); if (null != connection) { connectionlist.add(connection); } proceedToEndElementNamed(LibraryElementTags.CONNECTION_ELEMENT); return true; } return false; }); }
Source:
<code>protected MqttAsyncClient createAndConnectClient() throws MqttException, ConfigurationException { StringBuilder serverURI = new StringBuilder(); serverURI.append((secure ? "ssl://" : "tcp://")); serverURI.append(host); serverURI.append(":"); serverURI.append(port); <START> Path tmpDir = Paths.get(ConfigConstants.DEFAULT_USERDATA_FOLDER); <END> try { if (!tmpDir.isAbsolute()) { throw new IOException("User path not absolute!"); } tmpDir = Files.createDirectories(tmpDir).resolve("mqtt").resolve(host); } catch (IOException e) { throw new MqttException(e); } MqttClientPersistence dataStore = new MqttDefaultFilePersistence(tmpDir.toString()); MqttAsyncClient _client; try { _client = new MqttAsyncClient(serverURI.toString(), clientId, dataStore); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } _client.setCallback(clientCallbacks); try { connectionToken = _client.connect(createMqttOptions(), null, connectionCallbacks); logger.info("Starting MQTT broker connection to '{}' with clientid and file store '{}'", host, getClientId(), tmpDir); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } return _client; }</code><technical_language>"real" user data folder (as returned getUserDataFolder() method) default one</technical_language>

Target:
protected MqttAsyncClient createAndConnectClient() throws MqttException, ConfigurationException { StringBuilder serverURI = new StringBuilder(); serverURI.append((secure ? "ssl://" : "tcp://")); serverURI.append(host); serverURI.append(":"); serverURI.append(port); Path tmpDir = Paths.get(ConfigConstants.getUserDataFolder()); try { tmpDir = Files.createDirectories(tmpDir.resolve("mqtt").resolve(host)); } catch (IOException e) { throw new MqttException(e); } MqttClientPersistence dataStore = new MqttDefaultFilePersistence(tmpDir.toString()); MqttAsyncClient _client; try { _client = new MqttAsyncClient(serverURI.toString(), clientId, dataStore); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } _client.setCallback(clientCallbacks); try { connectionToken = _client.connect(createMqttOptions(), null, connectionCallbacks); logger.info("Starting MQTT broker connection to '{}' with clientid and file store '{}'", host, getClientId(), tmpDir); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } return _client; }
Source:
<code>private void addParametersToStartBlock(StatementList statementList) { if (statementList.parent().is(Tree.Kind.FUNCDEF)) { ParameterList parameterList = ((FunctionDef) statementList.parent()).parameters(); if (parameterList != null) { PythonCfgSimpleBlock parametersBlock = createSimpleBlock(start); <START> parameterList.all().forEach(parameter -> { <END> if (parameter.is(Tree.Kind.PARAMETER)) { parametersBlock.addElement(parameter); return; } addTupleParam((TupleParameter) parameter, parametersBlock); }); start = parametersBlock; } } }</code><technical_language>a duplication logic PARAMETER/TUPLE_PARAMETER. simplify with: java PythonCfgSimpleBlock parametersBlock = createSimpleBlock(start); addParameters(parameterList.all(), parametersBlock); start = parametersBlock; ... java private static void addParameters(List<AnyParameter> parameters, PythonCfgSimpleBlock parametersBlock) { for (AnyParameter parameter : parameters) { if (parameter.is(Tree.Kind.TUPLE_PARAMETER)) { addParameters(((TupleParameter) parameter).parameters(), parametersBlock); } else { parametersBlock.addElement(parameter); } } }</technical_language>

Target:
private void addParametersToStartBlock(StatementList statementList) { if (statementList.parent().is(Tree.Kind.FUNCDEF)) { ParameterList parameterList = ((FunctionDef) statementList.parent()).parameters(); if (parameterList != null) { PythonCfgSimpleBlock parametersBlock = createSimpleBlock(start); addParameters(parameterList.all(), parametersBlock); start = parametersBlock; } } }
Source:
<code>void execute() throws AzureBlobFileSystemException { int retryCount = 0; LOG.debug("First execution of REST operation - " + operationType); while (!executeHttpOperation(retryCount++)) { try { <START> LOG.debug("Retrying REST operation " + operationType + ". RetryCount" <END> + "=" + retryCount); Thread.sleep(client.getRetryPolicy().getRetryInterval(retryCount)); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } if (result.getStatusCode() >= HttpURLConnection.HTTP_BAD_REQUEST) { throw new AbfsRestOperationException(result.getStatusCode(), result.getStorageErrorCode(), result.getStorageErrorMessage(), null, result); } }</code><technical_language>nit: String.format</technical_language>

Target:
void execute() throws AzureBlobFileSystemException { String latencyHeader = this.client.getAbfsPerfTracker().getClientLatency(); if (latencyHeader != null && !latencyHeader.isEmpty()) { AbfsHttpHeader httpHeader = new AbfsHttpHeader(HttpHeaderConfigurations.X_MS_ABFS_CLIENT_LATENCY, latencyHeader); requestHeaders.add(httpHeader); } int retryCount = 0; LOG.debug("First execution of REST operation - {}", operationType); while (!executeHttpOperation(retryCount++)) { try { LOG.debug("Retrying REST operation {}. RetryCount = {}", operationType, retryCount); Thread.sleep(client.getRetryPolicy().getRetryInterval(retryCount)); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } if (result.getStatusCode() >= HttpURLConnection.HTTP_BAD_REQUEST) { throw new AbfsRestOperationException(result.getStatusCode(), result.getStorageErrorCode(), result.getStorageErrorMessage(), null, result); } }
Source:
<code>public void shouldCreateStandaloneClientWithZookeeper() { RatelClientFactory ratelStandaloneFactory = RatelStandaloneFactory.fromZookeeperServer(ZK_HOST); <START> TestService testedService = ratelStandaloneFactory.getServiceProxy(TestService.class, null); <END> then(testedService.hello()).isEqualTo("success"); }</code><technical_language>null better</technical_language>

Target:
public void shouldCreateStandaloneClientWithZookeeper() { RatelClientFactory ratelStandaloneFactory = RatelStandaloneFactory.fromZookeeperServer(ZK_HOST); TestService testedService = ratelStandaloneFactory.getServiceProxy(TestService.class); then(testedService.hello()).isEqualTo("success"); }
Source:
<code>public void testAddClusterAzureProvider() throws Exception { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; System.setProperty(SystemPropertyKeys.CLOUD_ID, "TestID"); <START> System.setProperty(SystemPropertyKeys.CLOUD_INFO_SOURCE, "TestURL"); <END> System.setProperty(SystemPropertyKeys.CLOUD_PROVIDER, CloudProvider.AZURE.name()); System.setProperty(SystemPropertyKeys.CLOUD_INFO_PROCESSOR_NAME, "TestProcessor"); _clusterSetup.addCluster(clusterName, false,true); ConfigAccessor _configAccessor = new ConfigAccessor(_gZkClient); CloudConfig cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName); Assert.assertTrue(cloudConfigFromZk.isCloudEnabled()); Assert.assertEquals(cloudConfigFromZk.getCloudID(), "TestID"); List<String> listUrlFromZk = cloudConfigFromZk.getCloudInfoSources(); Assert.assertNull(listUrlFromZk); Assert.assertNull(cloudConfigFromZk.getCloudInfoProcessorName()); Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.AZURE.name()); System.clearProperty(SystemPropertyKeys.CLOUD_ID); System.clearProperty(SystemPropertyKeys.CLOUD_PROVIDER); System.clearProperty(SystemPropertyKeys.CLOUD_INFO_SOURCE); System.clearProperty(SystemPropertyKeys.CLOUD_INFO_PROCESSOR_NAME); }</code><technical_language>This test case test real scenario for Azure. assume "provider", "ID", "enabled" input, other not. expect customer other two</technical_language>

Target:
public void testAddClusterAzureProvider() throws Exception { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; CloudConfig.Builder cloudConfigInitBuilder = new CloudConfig.Builder(); cloudConfigInitBuilder.setCloudEnabled(true); cloudConfigInitBuilder.setCloudID("TestID"); cloudConfigInitBuilder.setCloudProvider(CloudProvider.AZURE); CloudConfig cloudConfigInit = cloudConfigInitBuilder.build(); _clusterSetup.addCluster(clusterName, false, cloudConfigInit); ConfigAccessor _configAccessor = new ConfigAccessor(_gZkClient); CloudConfig cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName); Assert.assertTrue(cloudConfigFromZk.isCloudEnabled()); Assert.assertEquals(cloudConfigFromZk.getCloudID(), "TestID"); List<String> listUrlFromZk = cloudConfigFromZk.getCloudInfoSources(); Assert.assertNull(listUrlFromZk); Assert.assertNull(cloudConfigFromZk.getCloudInfoProcessorName()); Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.AZURE.name()); }
Source:
<code>private String convertCharacterProxyData(CharacterDataProxy dp) { String toWrite = dp.getValueAsString(); if (toWrite.length() > 1024) { <START> toWrite = "truncated: " + toWrite.substring(0, 1023); <END> } if (toWrite.length() == 0) { toWrite += " "; } return AXml.textToXml(toWrite); }</code><technical_language>do trim string more? (i.e. 1024 is max)? if so, adding "truncated: " 1024 chars greater</technical_language>

Target:
private String convertCharacterProxyData(CharacterDataProxy dp) { String toWrite = dp.getValueAsString(); return AXml.textToXml(toWrite); }
Source:
<code>public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) { <START> return new HashMap<>(); <END> }</code><technical_language>Collections.EMPTY_MAP for a static empty immutable map</technical_language>

Target:
public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) { return Collections.EMPTY_MAP; }
Source:
<code>private void addContents(@NonNull Container container, final @NonNull Node node) { Computer c = node.toComputer(); if (c == null) { return; } String name; if (node instanceof Jenkins) { name = "master"; } else { name = "slave/" + node.getNodeName(); } container.add( new Content("nodes/" + name + "/RootCA.txt") { @Override public void writeTo(OutputStream os) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf-8"))); try { <START> out.println(getRootCA(node)); <END> } catch (IOException e) { e.printStackTrace(out); } finally { out.flush(); } } } ); }</code><technical_language>is purpose of printing a Future<String>? (Which null for offline node?)</technical_language>

Target:
private void addContents(@NonNull Container container, final @NonNull Node node) { Computer c = node.toComputer(); if (c == null) { return; } String name; if (node instanceof Jenkins) { name = "master"; } else { name = "slave/" + node.getNodeName(); } container.add( new Content("nodes/" + name + "/RootCA.txt") { @Override public void writeTo(OutputStream os) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf-8"))); try { out.println(getRootCA(node)); } catch (IOException e) { e.printStackTrace(out); } catch (InterruptedException e) { e.printStackTrace(out); } finally { out.flush(); } } } ); }
Source:
<code>public static double calculateGenotypeQualityFromPLs(final Genotype genotype) { Utils.nonNull(genotype); if (!genotype.hasPL()) { return Double.NaN; } else { int[] PLs = genotype.getPL(); if (PLs.length <= 1) { return Double.NaN; } else { int best = PLs[0], secondBest = Integer.MAX_VALUE; <START> for (int i = 1; i < PLs.length; i++) { <END> final int next = PLs[i]; if (next <= best) { secondBest = best; best = next; } else if (next < secondBest) { secondBest = next; } } return secondBest - best; } } }</code><technical_language>This motif of earlier in this PR. extract a method for this</technical_language>

Target:
public static double calculateGenotypeQualityFromPLs(final Genotype genotype) { Utils.nonNull(genotype); if (!genotype.hasPL()) { return Double.NaN; } else { final int GQ = GATKProtectedMathUtils.secondSmallestMinusSmallest(genotype.getPL(), -1); return GQ < 0 ? Double.NaN : (double) GQ; } }
Source:
<code>public String getSystemProperty(String key) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertyAccess(key); } try { return Objects.toString(importedSystemProperties.get(key), null); <START> } catch (NullPointerException e) { <END> throw new MigrationException(ImportMigrationContextImpl.INVALID_NULL_SYS_PROPS, e); } }</code><technical_language>Code protected runtime exceptions this. Instead prevent triggering code throw exception a null parameter is passed checking for null first. In this case, system properties? If null returned error generated</technical_language>

Target:
public String getSystemProperty(String key) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertyAccess(key); } return Objects.toString(importedSystemProperties.get(key), null); }
Source:
<code>static ByteAmount getContainerRam(int components, int containers) { final int componentsPerContainer = Math.max(components / containers, 1); <START> return ByteAmount.fromMegabytes(COMPONENT_RAM_MB * (componentsPerContainer + 2)); <END> }</code><technical_language>give 2 a meaningful name instead of a magic number</technical_language>

Target:
static ByteAmount getContainerRam(int components, int containers) { final int componentsPerContainer = Math.max(components / containers, 1); return ByteAmount.fromMegabytes(COMPONENT_RAM_MB * componentsPerContainer + DEFAULT_RAM_PADDING_PER_CONTAINER); }
Source:
<code>public boolean isTotalOrderCache(String cacheName) { if (!running) { <START> if (log.isTraceEnabled()) { <END> log.tracef("isTotalOrderCache(%s) returning false because the local cache manager is not running", cacheName); } return false; } LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning false because the cache doesn't exist locally", cacheName); } return false; } boolean totalOrder = cacheStatus.getJoinInfo().isTotalOrder(); if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning %s", cacheName, totalOrder); } return totalOrder; }</code><technical_language>_isTraceEnabled()_ needed</technical_language>

Target:
public boolean isTotalOrderCache(String cacheName) { if (!running) { log.tracef("isTotalOrderCache(%s) returning false because the local cache manager is not running", cacheName); return false; } LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { log.tracef("isTotalOrderCache(%s) returning false because the cache doesn't exist locally", cacheName); return false; } boolean totalOrder = cacheStatus.getJoinInfo().isTotalOrder(); log.tracef("isTotalOrderCache(%s) returning %s", cacheName, totalOrder); return totalOrder; }
Source:
<code>public void testAllocateSimpleSlot() throws Exception { CompletableFuture<SlotRequest> slotRequestFuture = new CompletableFuture<>(); resourceManagerGateway.setRequestSlotConsumer(slotRequestFuture::complete); try (SlotPoolImpl slotPool = createAndSetUpSlotPool()) { slotPool.registerTaskManager(taskManagerLocation.getResourceID()); SlotRequestId requestId = new SlotRequestId(); <START> CompletableFuture<PhysicalSlot> future = requestNewAllocatedSlot(slotPool, requestId); <END> assertFalse(future.isDone()); final SlotRequest slotRequest = slotRequestFuture.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS); final SlotOffer slotOffer = new SlotOffer( slotRequest.getAllocationId(), 0, DEFAULT_TESTING_PROFILE); assertTrue(slotPool.offerSlot(taskManagerLocation, taskManagerGateway, slotOffer)); PhysicalSlot physicalSlot = future.get(1, TimeUnit.SECONDS); assertTrue(future.isDone()); assertEquals(taskManagerLocation, physicalSlot.getTaskManagerLocation()); assertEquals(slotRequest.getAllocationId(), physicalSlot.getAllocationId()); } }</code><technical_language>final</technical_language>

Target:
public void testAllocateSimpleSlot() throws Exception { CompletableFuture<SlotRequest> slotRequestFuture = new CompletableFuture<>(); resourceManagerGateway.setRequestSlotConsumer(slotRequestFuture::complete); try (SlotPoolImpl slotPool = createAndSetUpSlotPool(resourceManagerGateway)) { final SlotRequestId requestId = new SlotRequestId(); final CompletableFuture<PhysicalSlot> future = requestNewAllocatedSlot(slotPool, requestId); assertFalse(future.isDone()); final SlotRequest slotRequest = slotRequestFuture.get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS); assertTrue(registerAndOfferSlot(taskManagerLocation, slotPool, slotRequest.getAllocationId())); final PhysicalSlot physicalSlot = future.get(1, TimeUnit.SECONDS); assertTrue(future.isDone()); assertEquals(taskManagerLocation, physicalSlot.getTaskManagerLocation()); assertEquals(slotRequest.getAllocationId(), physicalSlot.getAllocationId()); } }
Source:
<code>protected DeviceAnonymized(UUID id, UserAnonymized userAnonymized, int deviceId) { super(id); <START> Objects.requireNonNull(userAnonymized); <END> this.userAnonymized = userAnonymized; this.deviceId = deviceId; }</code><technical_language>write this this.userAnonymized = Objects.requireNonNull(userAnonymized)</technical_language>

Target:
protected DeviceAnonymized(UUID id, UserAnonymized userAnonymized, int deviceId) { super(id); this.userAnonymized = Objects.requireNonNull(userAnonymized); this.deviceId = deviceId; }
Source:
<code>int getSchemaVersion() { int version; try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { String selectVersionSql = "SELECT \"id\" FROM \"Version\""; ResultSet resultSet = statement.executeQuery(selectVersionSql); if (resultSet.next()) { version = resultSet.getInt("id"); } else { throw new SQLException("Expected non-empty result set"); } } } catch (SQLException e) { <START> throw new RuntimeException(e); <END> } return version; }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Define throw a dedicated exception instead of a generic one. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
int getSchemaVersion() { int version; try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { String selectVersionSql = "SELECT \"id\" FROM \"Version\""; try (ResultSet resultSet = statement.executeQuery(selectVersionSql)) { if (resultSet.next()) { version = resultSet.getInt("id"); } else { throw new SQLException("Expected non-empty result set"); } } } } catch (SQLException e) { throw new UncheckedSqlException(e); } return version; }
Source:
<code>static Boolean isCookiesAuthEnabled(Map<String, String> attributes) { String val = attributes.get(SECURE_SERVER_COOKIES_AUTH_ENABLED_ATTRIBUTE); <START> return val == null ? null : Boolean.parseBoolean(val); <END> }</code><technical_language>Please change java doc clearer result is nullable</technical_language>

Target:
static @Nullable Boolean isCookiesAuthEnabled(Map<String, String> attributes) { String val = attributes.get(SECURE_SERVER_COOKIES_AUTH_ENABLED_ATTRIBUTE); return val == null ? null : Boolean.parseBoolean(val); }
Source:
<code>private ValidationResult validateRequiredNetworksAvailable(VDS vds, VM vm, List<VmNetworkInterface> vmNICs, Network displayNetwork, Map<String, Network> networksByName, List<String> hostNetworks, VdsNetworkInterface displayNic) { List<String> missingIfs = new ArrayList<>(); boolean onlyRequiredNetworks = Config.<Boolean> getValue(ConfigValues.OnlyRequiredNetworksMandatoryForVdsSelection); for (final VmNetworkInterface vmIf : vmNICs) { boolean found = false; boolean skipNetworkExistenceCheckForVnicPassthrough = vmIf.isPassthrough(); if <START> (vmIf.getNetworkName() == null) { <END> found = true; } else { for (String networkName : hostNetworks) { if (skipNetworkExistenceCheckForVnicPassthrough || !networkRequiredOnVds(vmIf, networksByName, onlyRequiredNetworks) || StringUtils.equals(vmIf.getNetworkName(), networkName)) { found = true; break; } } } if (!found) { missingIfs.add(vmIf.getNetworkName()); } Network network = networksByName.get(vmIf.getNetworkName()); if (network.isExternal()) { checkExternalNetworkConnection(network, hostNetworks).ifPresent(missingIfs::add); } } if (!missingIfs.isEmpty()) { String nics = StringUtils.join(missingIfs, ", "); log.warn("host is missing networks required by VM nics {}", vds.getName(), nics); return new ValidationResult(EngineMessage.VAR__DETAIL__NETWORK_MISSING, String.format("$networkNames %1$s", nics)); } return validateDisplayNetworkAvailability(vds, onlyRequiredNetworks, displayNic, displayNetwork); }</code><technical_language>network name 'null'? If is, NPE network is accessed line 164</technical_language>

Target:
private ValidationResult validateRequiredNetworksAvailable(VDS vds, VM vm, List<VmNetworkInterface> vmNICs, Network displayNetwork, Map<String, Network> networksByName, List<String> hostNetworks, VdsNetworkInterface displayNic) { List<String> missingIfs = new ArrayList<>(); boolean onlyRequiredNetworks = Config.<Boolean> getValue(ConfigValues.OnlyRequiredNetworksMandatoryForVdsSelection); for (final VmNetworkInterface vmIf : vmNICs) { boolean found = false; boolean skipNetworkExistenceCheckForVnicPassthrough = vmIf.isPassthrough(); if (vmIf.getNetworkName() == null) { found = true; } else { for (String networkName : hostNetworks) { if (skipNetworkExistenceCheckForVnicPassthrough || !networkRequiredOnVds(vmIf, networksByName, onlyRequiredNetworks) || StringUtils.equals(vmIf.getNetworkName(), networkName)) { found = true; break; } } Network network = networksByName.get(vmIf.getNetworkName()); if (network.isExternal()) { findPhysicalNetworkNotConnectedAndLinkedTo(network, hostNetworks).ifPresent(missingIfs::add); } } if (!found) { missingIfs.add(vmIf.getNetworkName()); } } if (!missingIfs.isEmpty()) { String nics = StringUtils.join(missingIfs, ", "); log.warn("host is missing networks required by VM nics {}", vds.getName(), nics); return new ValidationResult(EngineMessage.VAR__DETAIL__NETWORK_MISSING, String.format("$networkNames %1$s", nics)); } return validateDisplayNetworkAvailability(vds, onlyRequiredNetworks, displayNic, displayNetwork); }
Source:
<code>public synchronized void deploy(String verticle, Vertx vertx, DeploymentOptions options, Handler<AsyncResult<String>> completionHandler) { if (manager == null) { manager = newInstance(); } final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classloader); Method method = manager.getClass().getMethod("deploy", String.class, Vertx.class, DeploymentOptions.class, Handler.class); method.invoke(manager, verticle, vertx, options, completionHandler); <START> } catch (Exception e) { <END> log.error("Failed to deploy verticle " + verticle, e); } finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } }</code><technical_language>handle InvocationException specially unwrap log</technical_language>

Target:
public synchronized void deploy(String verticle, Vertx vertx, DeploymentOptions options, Handler<AsyncResult<String>> completionHandler) { if (manager == null) { manager = newInstance(); } final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classloader); Method method = manager.getClass().getMethod("deploy", String.class, Vertx.class, DeploymentOptions.class, Handler.class); method.invoke(manager, verticle, vertx, options, completionHandler); } catch (InvocationTargetException e) { log.error("Failed to deploy verticle " + verticle, e.getCause()); } catch (Exception e) { log.error("Failed to deploy verticle " + verticle, e); } finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } }
Source:
<code><START> public long getEngineSessionSeqId(String sessionId) { <END> return sessionInfoMap.containsKey(sessionId) ? (Long) sessionInfoMap.get(sessionId).contentOfSession.get(ENGINE_SESSION_SEQ_ID) : -1; }</code><technical_language>rename previous patch reduce diff</technical_language>

Target:
public long getEngineSessionSeqId(String sessionId) { if (!sessionInfoMap.containsKey(sessionId)) { throw new RuntimeException("Session not found for sessionId " + sessionId); } return (Long) sessionInfoMap.get(sessionId).contentOfSession.get(ENGINE_SESSION_SEQ_ID); }
Source:
<code>private byte decodeRecordToJson(GenericRecord record) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(schema, outputStream); writer.write(record, jsonEncoder); jsonEncoder.flush(); <START> outputStream.close(); <END> return outputStream.toByteArray(); }</code><technical_language>try-with-resources concentrate type of OutputStrem is</technical_language>

Target:
private byte decodeRecordToJson(GenericRecord record) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(schema, outputStream); writer.write(record, jsonEncoder); jsonEncoder.flush(); return outputStream.toByteArray(); }
Source:
<code>private static boolean isDeckPackage(String filename) { <START> return filename != null && (filename.toLowerCase().endsWith(".apkg") || filename.toLowerCase().endsWith(".apkg.zip")) && !filename.equals("collection.apkg"); <END> }</code><technical_language>I of handle if do? suggestion return filename != null && (filename.toLowerCase().endsWith(".apkg") || filename.toLowerCase().endsWith(".apkg.zip")) && !(filename.equals("collection.apkg") || filename.equals("collection.apkg.zip"));</technical_language>

Target:
private static boolean isDeckPackage(String filename) { return filename != null && (filename.toLowerCase().endsWith(".apkg") || filename.toLowerCase().endsWith(".apkg.zip")) && !(filename.equals("collection.apkg") || filename.equals("collection.apkg.zip")); }
Source:
<code>public void onNavigationDrawerItemSelected(int position) { if (position != menu_position) { startActivity(intent_list.get(position)); Set<String> categories = getIntent().getCategories(); getIntent().getAction(); <START> if(categories == null || ! (categories.contains("android.intent.category.LAUNCHER") || getMenuName().equalsIgnoreCase(Home.menu_name))){ <END> finish(); } } }</code><technical_language>I writing this more clear. adding another () (no real change though): if(categories == null || ! ((categories.contains("android.intent.category.LAUNCHER") || getMenuName().equalsIgnoreCase(Home.menu_name))))</technical_language>

Target:
public void onNavigationDrawerItemSelected(int position) { if (position != menu_position) { startActivity(intent_list.get(position)); if (!getMenuName().equalsIgnoreCase(Home.menu_name)) { finish(); } } }
Source:
<code>public void inspectAddresses(CorfuPayloadMsg<InspectAddressesRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { log.trace("inspectAddresses: {}", msg.getPayload().getAddresses()); InspectAddressesResponse inspectResponse = new InspectAddressesResponse(); try { for (long address : msg.getPayload().getAddresses()) { if (!streamLog.contains(address)) { inspectResponse.add(address); } } r.sendResponse(ctx, msg, CorfuMsgType.INSPECT_ADDRESSES_RESPONSE.payloadMsg(inspectResponse)); } catch (TrimmedException te) { <START> r.sendResponse(ctx, msg, CorfuMsgType.ERROR_TRIMMED.msg()); <END> } catch (DataCorruptionException dce) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_DATA_CORRUPTION.msg()); } }</code><technical_language>timing out? pass current read address</technical_language>

Target:
public void inspectAddresses( CorfuPayloadMsg<InspectAddressesRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { List<Long> addresses = msg.getPayload().getAddresses(); log.trace("inspectAddresses: {}", addresses); InspectAddressesResponse inspectResponse = new InspectAddressesResponse(); for (long address : addresses) { try { if (!streamLog.contains(address)) { inspectResponse.add(address); } } catch (TrimmedException te) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_TRIMMED.msg()); return; } catch (DataCorruptionException dce) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_DATA_CORRUPTION.payloadMsg(address)); return; } } r.sendResponse(ctx, msg, CorfuMsgType.INSPECT_ADDRESSES_RESPONSE.payloadMsg(inspectResponse)); }
Source:
<code>public boolean provides(IDiagramElementEditPart editPart) { boolean provides = false; if (editPart instanceof GraphicalEditPart || editPart instanceof AbstractConnectionEditPart) { View view = (View) editPart.getModel(); if (view != null) { if <START> (view instanceof Edge || <END> view.isSetElement()) { EditDomain ed = editPart.getViewer().getEditDomain(); if (ed instanceof DiagramEditDomain) { EObject model = view.getElement(); provides = model instanceof DNode || model instanceof DDiagramElementContainer; } } } } return provides; }</code><technical_language>this condition is unusefull (as check "model instanceof DNode || model instanceof DDiagramElementContainer")</technical_language>

Target:
public boolean provides(IDiagramElementEditPart editPart) { if (editPart instanceof GraphicalEditPart || editPart instanceof AbstractConnectionEditPart) { Optional<View> view = Optional.ofNullable((View) editPart.getModel()); return view.filter(View::isSetElement).map(View::getElement).filter(model -> model instanceof DNode || model instanceof DDiagramElementContainer).isPresent(); } return false; }
Source:
<code><START> private static Timeline createTimeline( <END> final Storage storage, final UUID id, final int order, final String topic, final String eventType, final Date createdAt, final Date switchedAt, final Date cleanupAt, final Timeline.StoragePosition latestPosition) { final Timeline timeline = new Timeline(); timeline.setId(id); timeline.setStorage(storage); timeline.setOrder(order); timeline.setTopic(topic); timeline.setEventType(eventType); timeline.setCreatedAt(createdAt); timeline.setSwitchedAt(switchedAt); timeline.setCleanupAt(cleanupAt); timeline.setLatestPosition(latestPosition); return timeline; }</code><technical_language>do builder pattern for event types</technical_language>

Target:
private static Timeline createTimeline( final Storage storage, final UUID id, final int order, final String topic, final String eventType, final Date createdAt, final Date switchedAt, final Date cleanupAt, final Timeline.StoragePosition latestPosition) { final Timeline timeline = new Timeline(eventType, order, storage, topic, createdAt); timeline.setId(id); timeline.setSwitchedAt(switchedAt); timeline.setCleanupAt(cleanupAt); timeline.setLatestPosition(latestPosition); return timeline; }
Source:
<code>public String getMessage() { StringBuilder builder; if (message != null) { <START> builder = new StringBuilder().append(message); <END> } else { builder = new StringBuilder().append(error); } if (!elements.isEmpty()) { builder.append(" ").append(elements); } return builder.toString(); }</code><technical_language>assign StringBuilder mutate append(message), possibly ternary ?: operator</technical_language>

Target:
public String getMessage() { StringBuilder builder = new StringBuilder().append(super.getMessage()); if (!elements.isEmpty()) { builder.append(" ").append(elements); } return builder.toString(); }
Source:
<code>public int getItemCount() { <START> if (currentPath == null) return 0; <END> else return entries.size(); }</code><technical_language>Please prefer brackets, if is a short statement</technical_language>

Target:
public int getItemCount() { if (currentPath == null) { return 0; } else { return entries.size(); } }