auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private synchronized void writeInstanceDataSplit( Sheet sheet, InstanceData instanceData, List<QuestionDto> whichQuestions, MessageDigest md, boolean groupSheet) throws NoSuchAlgorithmException { int startRow = sheet.getLastRowNum() + 1; int maxIter = 0; if (!groupSheet) { maxIter = 1; } for (QuestionDto qd : whichQuestions) { final Long questionId = qd.getKeyId(); SortedMap<Long, String> iterationsMap = instanceData.responseMap.get(questionId); if (iterationsMap != null) { maxIter = Math.max(maxIter, iterationsMap.size()); } } for (int i = 0; i < maxIter; i++) { Row iterationRow = getRow(startRow + i, sheet); writeMetadataRow(iterationRow, instanceData, i + 1, groupSheet); for (QuestionDto qd : whichQuestions) { final Long questionId = qd.getKeyId(); final QuestionDto questionDto = questionsById.get(questionId); SortedMap<Long, String> iterationsMap = instanceData.responseMap.get(questionId); if (iterationsMap == null) { continue; } String val = iterationsMap.get(new Long(i)); if (val != null) { writeAnswer(iterationRow, columnIndexMap.get(questionId.toString()), questionDto, val); } } for (Cell cell : iterationRow) { String val = parseCellAsString(cell); if (val != null && !val.equals("")) { md.update(val.getBytes()); } } } }

Target:
private synchronized void writeInstanceDataSplit( Sheet sheet, InstanceData instanceData, List<QuestionDto> whichQuestions, MessageDigest md, boolean groupSheet) throws NoSuchAlgorithmException { int startRow = sheet.getLastRowNum() + 1; int maxIter = 0; if (!groupSheet) { maxIter = 1; } for (QuestionDto qd : whichQuestions) { final Long questionId = qd.getKeyId(); SortedMap<Long, String> iterationsMap = instanceData.responseMap.get(questionId); if (iterationsMap != null) { maxIter = Math.max(maxIter, iterationsMap.size()); } } for (int i = 0; i < maxIter; i++) { Row iterationRow = getRow(startRow + i, sheet); writeMetadataRow(iterationRow, instanceData, i + 1, groupSheet); for (QuestionDto qd : whichQuestions) { final Long questionId = qd.getKeyId(); SortedMap<Long, String> iterationsMap = instanceData.responseMap.get(questionId); if (iterationsMap == null) { continue; } String val = iterationsMap.get(Long.valueOf(i)); if (val != null) { writeAnswer(iterationRow, columnIndexMap.get(questionId.toString()), qd, val); } } for (Cell cell : iterationRow) { String val = parseCellAsString(cell); if (val != null && !val.equals("")) { md.update(val.getBytes()); } } } }
Source:
private boolean validateImagesAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; if (!validateImageAvailability(image, imageGroupId)) { if (!getParameters().isAllowPartialImport()) { return failValidation(EngineMessage.TEMPLATE_IMAGE_NOT_EXIST); } log.warn("Disk image '{}/{}' doesn't exist on any of its storage domains. " + "Ignoring since the 'Allow Partial' flag in on", imageGroupId, image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } } return true; }

Target:
private boolean validateImagesAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; if (!validateImageAvailability(image, imageGroupId)) { if (!getParameters().isAllowPartialImport()) { return failValidation(EngineMessage.TEMPLATE_IMAGE_NOT_EXIST); } log.warn("Disk image '{}/{}' doesn't exist on any of its storage domains. " + "Ignoring since the 'Allow Partial' flag is on", imageGroupId, image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } } return true; }
Source:
protected void executeVdsBrokerCommand() { Guid sessionId = getParameters().getSessionId(); GlusterGeoRepDao geoRepDao = DbFacade.getInstance().getGlusterGeoRepDao(); List<GlusterGeoRepSessionConfiguration> existingSessionConfigs = geoRepDao.getGeoRepSessionConfig(sessionId); GlusterGeoRepSession session = geoRepDao.getById(sessionId); result = getBroker().glusterVolumeGeoRepConfigList(session.getMasterVolumeName(), session.getSlaveHostName(), session.getSlaveVolumeName()); proceedProxyReturnValue(); List<GlusterGeoRepSessionConfiguration> sessionConfigs = result.getSessionConfig(); if (!existingSessionConfigs.containsAll(sessionConfigs)) { for (GlusterGeoRepSessionConfiguration geoRepSessionConfig : sessionConfigs) { if (!existingSessionConfigs.contains(geoRepSessionConfig)) { if (prepareMapOfExistingConfigs(existingSessionConfigs).containsKey(geoRepSessionConfig.getKey())) { geoRepDao.updateConfig(geoRepSessionConfig); } else { geoRepDao.saveConfig(geoRepSessionConfig); } } } } setReturnValue(sessionConfigs); }

Target:
protected void executeVdsBrokerCommand() { result = getBroker().glusterVolumeGeoRepConfigList(getParameters().getVolumeName(), getParameters().getSlaveHost(), getParameters().getSlaveVolume()); proceedProxyReturnValue(); List<GlusterGeoRepSessionConfiguration> sessionConfigs = result.getSessionConfig(); setReturnValue(sessionConfigs); }
Source:
public void begin (int n) { if (n >= passShaderProviders.length) throw new GdxRuntimeException("Pass " + n + " doesn't exist in " + getClass().getName()); currentPass = n; spotCameraIterator = spotCameras.iterator(); spotCameraIterator.reset(); dirCameraIterator = dirCameras.iterator(); dirCameraIterator.reset(); pointCameraIterator = pointCameras.iterator(); pointCameraIterator.reset(); currentPointSide = 6; frameBuffers[n].begin(); beginPass(n); }

Target:
public void begin (int n) { if (n >= passShaderProviders.length) throw new GdxRuntimeException("Pass " + n + " doesn't exist in " + getClass().getName()); currentPass = n; spotCameraIterator = spotCameras.iterator(); dirCameraIterator = dirCameras.iterator(); pointCameraIterator = pointCameras.iterator(); currentPointSide = 6; beginPass(n); }
Source:
public synchronized boolean remove(String key) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (entry == null || entry.currentEditor != null) { return false; } for (int i = 0; i < valueCount; i++) { File file = entry.getCleanFile(i); boolean fileExisted = file.exists(); if (fileExisted && !file.delete()) { throw new IOException("failed to delete " + file); } size -= entry.lengths[i]; entry.lengths[i] = 0; } redundantOpCount++; journalWriter.append(REMOVE + ' ' + key + '\n'); lruEntries.remove(key); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return true; }

Target:
public synchronized boolean remove(String key) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (entry == null || entry.currentEditor != null) { return false; } for (int i = 0; i < valueCount; i++) { File file = entry.getCleanFile(i); if (file.exists() && !file.delete()) { throw new IOException("failed to delete " + file); } size -= entry.lengths[i]; entry.lengths[i] = 0; } redundantOpCount++; journalWriter.append(REMOVE + ' ' + key + '\n'); lruEntries.remove(key); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return true; }
Source:
public PropertyKey cloudConfig() { return new PropertyKey(CONFIGS, ConfigScopeProperty.CLOUD, CloudConfig.class, _clusterName, ConfigScopeProperty.CLOUD.toString(), _clusterName); }

Target:
public PropertyKey cloudConfig() { return new PropertyKey(CONFIGS, ConfigScopeProperty.CLOUD, CloudConfig.class, _clusterName, ConfigScopeProperty.CLOUD.name(), _clusterName); }
Source:
public Observable<Throwable> postErrorObservable(){ return this.postSucces.compose(ResponseOrError.<Response>onlyError()); }

Target:
public Observable<Throwable> postErrorObservable() { return postErrorSubject; }
Source:
static BlobId getBlobIdFromString(String blobIdString, ClusterMap clusterMap) throws RouterException { if (blobIdString == null || blobIdString.length() == 0) { logger.error("BlobIdString argument is null or zero length: {}", blobIdString); throw new RouterException("BlobId is empty.", RouterErrorCode.InvalidBlobId); } BlobId blobId; try { blobId = new BlobId(blobIdString, clusterMap); logger.trace("BlobId created " + blobId + " with partition " + blobId.getPartition()); } catch (Exception e) { logger.error("Caller passed in invalid BlobId " + blobIdString); throw new RouterException("BlobId is invalid " + blobIdString, RouterErrorCode.InvalidBlobId); } return blobId; }

Target:
static BlobId getBlobIdFromString(String blobIdString, ClusterMap clusterMap) throws RouterException { BlobId blobId; try { blobId = new BlobId(blobIdString, clusterMap); logger.trace("BlobId created " + blobId + " with partition " + blobId.getPartition()); } catch (Exception e) { logger.error("Caller passed in invalid BlobId " + blobIdString); throw new RouterException("BlobId is invalid " + blobIdString, RouterErrorCode.InvalidBlobId); } return blobId; }
Source:
protected String[] getTransformedSelection() { System.out.println(this.selectionStateMap); List<String> selectedItems = new ArrayList<String>(); for (String item : this.selectionStateMap.keySet()) { Boolean isSelected = this.selectionStateMap.get(item); if (isSelected != null && isSelected) { selectedItems.add(item); } } return selectedItems.toArray(new String[selectedItems.size()]); }

Target:
protected String[] getTransformedSelection() { List<String> selectedItems = new ArrayList<String>(); for (String item : this.selectionStateMap.keySet()) { Boolean isSelected = this.selectionStateMap.get(item); if (isSelected != null && isSelected) { selectedItems.add(item); } } return selectedItems.toArray(new String[selectedItems.size()]); }
Source:
private static String convertHost(final String host) { if (host == null) { return null; } return stripDotSuffix(host).toUpperCase(); }

Target:
private static String convertHost(final String host) { return host != null ? stripDotSuffix(host).toUpperCase() : null; }
Source:
public void testParse() { assertEquals("1.6", parse("git/1.6.6-rc0")); assertEquals("1.6.6", parse("git/1.6.6")); assertEquals("1.7.5", parse("git/1.7.5.GIT")); assertEquals("1.7.6.1", parse("git/1.7.6.1.45.gbe0cc")); assertEquals("1.5.4.3", parse("git/1.5.4.3,gzip(proxy)")); assertEquals("1.7.0.2", parse("git/1.7.0.2.msysgit.0.14.g956d7,gzip")); assertEquals("1.7.10.2", parse("git/1.7.10.2 (Apple Git-33)")); assertEquals(ClientVersionUtil.toString(invalidVersion()), parse("foo")); }

Target:
public void testParse() { assertEquals("1.6.5", parseVersion("git/1.6.6-rc0")); assertEquals("1.6.6", parseVersion("git/1.6.6")); assertEquals("1.7.5", parseVersion("git/1.7.5.GIT")); assertEquals("1.7.6.1", parseVersion("git/1.7.6.1.45.gbe0cc")); assertEquals("1.5.4.3", parseVersion("git/1.5.4.3,gzip(proxy)")); assertEquals("1.7.0.2", parseVersion("git/1.7.0.2.msysgit.0.14.g956d7,gzip")); assertEquals("1.7.10.2", parseVersion("git/1.7.10.2 (Apple Git-33)")); assertEquals(ClientVersionUtil.toString(invalidVersion()), parseVersion("foo")); }
Source:
private void verifyFileStatus(FileStatus[] listResult, Path parentPath, int startIndexInSortedName) throws IOException { if (startIndexInSortedName == -1) { Assert.assertTrue("Expected empty FileStatus array", listResult.length == 0); return; } FileStatus[] allFileStatuses = fs.listStatus(parentPath); Assert.assertTrue("number of dir/file doesn't match", allFileStatuses.length == SORTED_ENTRY_NAMES.length); int indexInResult = 0; for (int index = startIndexInSortedName; index < SORTED_ENTRY_NAMES.length; index++) { Assert.assertEquals("fileStatus doesn't match", allFileStatuses[index], listResult[indexInResult++]); } }

Target:
private void verifyFileStatus(FileStatus[] listResult, Path parentPath, int startIndexInSortedName) throws IOException { if (startIndexInSortedName == -1) { Assert.assertEquals("Expected empty FileStatus array", 0, listResult.length); return; } FileStatus[] allFileStatuses = fs.listStatus(parentPath); Assert.assertEquals("number of dir/file doesn't match", SORTED_ENTRY_NAMES.length, allFileStatuses.length); int indexInResult = 0; for (int index = startIndexInSortedName; index < SORTED_ENTRY_NAMES.length; index++) { Assert.assertEquals("fileStatus doesn't match", allFileStatuses[index], listResult[indexInResult++]); } }
Source:
private static void checkPort(int port, AddressFamily addrFamily) { switch (addrFamily) { case AF_IPv6: case AF_IPv4: if (port < 0 || port > 65535) { throw new IllegalArgumentException("invalid port: " + port + " (expected: 1 ~ 65535)"); } break; case AF_UNIX: case AF_UNSPEC: if (port != 0) { throw new IllegalArgumentException("port cannot be specified with addrFamily: " + addrFamily); } break; default: throw new IllegalArgumentException("unexpected addrFamily: " + addrFamily); } }

Target:
private static void checkPort(int port, AddressFamily addrFamily) { switch (addrFamily) { case AF_IPv6: case AF_IPv4: if (port < 0 || port > 65535) { throw new IllegalArgumentException("invalid port: " + port + " (expected: 0 ~ 65535)"); } break; case AF_UNIX: case AF_UNSPEC: if (port != 0) { throw new IllegalArgumentException("port cannot be specified with addrFamily: " + addrFamily); } break; default: throw new IllegalArgumentException("unexpected addrFamily: " + addrFamily); } }
Source:
private static String encodeChunk(String value, Charset charset, boolean allowReserved) { if (isEncoded(value, charset)) { return value; } byte[] data = value.getBytes(charset); try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { for (byte b : data) { if (isUnreserved((char) b)) { bos.write(b); } else if (isReserved((char) b) && allowReserved) { bos.write(b); } else { pctEncode(b, bos); } } return new String(bos.toByteArray()); } catch (IOException ioe) { throw new IllegalStateException("Error occurred during encoding of the uri: " + ioe.getMessage(), ioe); } }

Target:
private static String encodeChunk(String value, Charset charset, boolean allowReserved) { if (isEncoded(value, charset)) { return value; } byte[] data = value.getBytes(charset); try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { for (byte b : data) { if (isUnreserved((char) b)) { bos.write(b); } else if (isReserved((char) b) && allowReserved) { bos.write(b); } else { pctEncode(b, bos); } } return new String(bos.toByteArray(), charset); } catch (IOException ioe) { throw new IllegalStateException("Error occurred during encoding of the uri: " + ioe.getMessage(), ioe); } }
Source:
public void activate() { super.activate(); diagram = (Diagram) ((GraphicalEditPart) getHost()).getNotationView().getElement(); previewImage = DiagramRenderUtil.renderToSWTImage(diagram); }

Target:
public void activate() { super.activate(); if (getHost() instanceof GraphicalEditPart) { if (((GraphicalEditPart) getHost()).getNotationView() != null && ((GraphicalEditPart) getHost()).getNotationView().getElement() instanceof Diagram) { diagram = (Diagram) ((GraphicalEditPart) getHost()).getNotationView().getElement(); } try { previewImage = DiagramRenderUtil.renderToSWTImage(diagram); } catch(Exception e) { Activator.log.error(e); } } }
Source:
public static long xxHash64(@SqlType(StandardTypes.TINYINT) long value) { return XxHash64.hash((byte) value); }

Target:
public static long xxHash64(@SqlType(StandardTypes.TINYINT) long value) { return XxHash64.hash(value); }
Source:
public void onBannerFailedToLoad(BannerView bannerView, BannerErrorInfo bannerErrorInfo) { if(bannerErrorInfo.errorCode == BannerErrorCode.NO_FILL){ Log.e(TAG, "Unity Ads Banner returned NO FILL"); } else { Log.e(TAG, "Unity Ads Banner encountered an error: " + bannerErrorInfo.errorMessage); } }

Target:
public void onBannerFailedToLoad(BannerView bannerView, BannerErrorInfo bannerErrorInfo) { Log.w(TAG, "Unity Ads Banner encountered an error: " + bannerErrorInfo.errorMessage); if (bannerErrorInfo.errorCode == BannerErrorCode.NO_FILL) { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_NO_FILL); } else { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); } }
Source:
public Builder axonFrameworkVersionResolver(Supplier<String> axonFrameworkVersionResolver) { assertNonNull(axonFrameworkVersionResolver, "AxonConnectorProperties may not be null"); this.axonFrameworkVersionResolver = axonFrameworkVersionResolver; return this; }

Target:
public Builder axonFrameworkVersionResolver(Supplier<String> axonFrameworkVersionResolver) { assertNonNull(axonFrameworkVersionResolver, "Axon Framework Version Resolver may not be null"); this.axonFrameworkVersionResolver = axonFrameworkVersionResolver; return this; }
Source:
public int run() throws Exception { SitePaths sitePaths = new SitePaths(getSitePath()); File newSecureStoreFile = new File(newSecureStoreLib); if (!newSecureStoreFile.exists()) { throw new RuntimeException(String.format("File %s doesn't exists", newSecureStoreFile.getAbsolutePath())); } String newSecureStore = getNewSecureStore(newSecureStoreFile); String currentSecureStoreName = getCurrentSecureStoreName(sitePaths); if (currentSecureStoreName.equals(newSecureStore)) { log.error("Old and new SecureStore implementation names are the same. Migration will not work"); return -1; } IoUtil.loadJARs(newSecureStoreFile); SiteLibraryLoaderUtil.loadSiteLib(sitePaths.lib_dir); Injector dbInjector = createDbInjector(SINGLE_USER); SecureStore currentStore = getSecureStore(currentSecureStoreName, dbInjector); SecureStore newStore = getSecureStore(newSecureStore, dbInjector); migrateProperties(currentStore, newStore); removeOldLib(sitePaths, currentSecureStoreName); copyNewLib(sitePaths, newSecureStoreFile); updateGerritConfig(sitePaths, newSecureStore); return 0; }

Target:
public int run() throws Exception { SitePaths sitePaths = new SitePaths(getSitePath()); File newSecureStoreFile = new File(newSecureStoreLib); if (!newSecureStoreFile.exists()) { throw new RuntimeException(String.format("File %s doesn't exists", newSecureStoreFile.getAbsolutePath())); } String newSecureStore = getNewSecureStoreClassName(newSecureStoreFile); String currentSecureStoreName = getCurrentSecureStoreClassName(sitePaths); if (currentSecureStoreName.equals(newSecureStore)) { log.error("Old and new SecureStore implementation names are the same. Migration will not work"); return -1; } IoUtil.loadJARs(newSecureStoreFile); SiteLibraryLoaderUtil.loadSiteLib(sitePaths.lib_dir); log.info("Current secureStoreClass property ({}) will be replaced with {}", currentSecureStoreName, newSecureStore); Injector dbInjector = createDbInjector(SINGLE_USER); SecureStore currentStore = getSecureStore(currentSecureStoreName, dbInjector); SecureStore newStore = getSecureStore(newSecureStore, dbInjector); migrateProperties(currentStore, newStore); removeOldLib(sitePaths, currentSecureStoreName); copyNewLib(sitePaths, newSecureStoreFile); updateGerritConfig(sitePaths, newSecureStore); return 0; }
Source:
public void test() { RemoteService remoteService = RemoteService.getRemoteService(); long result = remoteService.doRemoteFunction(10); assert result == 100 || result == -1; }

Target:
public void test() { long result = RemoteService.getRemoteService().doRemoteFunction(10); assert result == 100 || result == -1; }
Source:
public boolean conflictExist(Project firstProject, Project secondProject) { List<UserList> globalListConflict = getGlobalListConflicts(firstProject, secondProject); List<UserVariable> globalVariableConflict = getGlobalVariableConflicts(firstProject, secondProject); if (!globalListConflict.isEmpty() || !globalVariableConflict.isEmpty()) { return true; } return false; }

Target:
public boolean conflictExist(Project firstProject, Project secondProject) { return (getGlobalListConflicts(firstProject.getUserLists(), secondProject.getUserLists()) || getGlobalVariableConflicts(firstProject.getUserVariables(), secondProject.getUserVariables())); }
Source:
public void isTestMode_shouldReturnTrueIfFunctionalTestModeIsEnabled() { System.setProperty("FUNCTIONAL_TEST_MODE", Boolean.toString(true)); assertTrue(OpenmrsUtil.isTestMode()); }

Target:
public void isTestMode_shouldReturnTrueIfFunctionalTestModeIsEnabled() { System.setProperty("FUNCTIONAL_TEST_MODE", "true"); assertTrue(OpenmrsUtil.isTestMode()); }
Source:
public DefaultLightblueMetadataResponse metadata(LightblueRequest lightblueRequest) throws LightblueParseException, LightblueResponseException, LightblueHttpClientException { LOGGER.debug("Calling metadata service with lightblueRequest: {}", lightblueRequest.toString()); return new DefaultLightblueMetadataResponse( callService(lightblueRequest, configuration.getMetadataServiceURI()), mapper); }

Target:
public DefaultLightblueMetadataResponse metadata(LightblueRequest lightblueRequest) throws LightblueParseException, LightblueResponseException, LightblueHttpClientException, LightblueException { LOGGER.debug("Calling metadata service with lightblueRequest: {}", lightblueRequest.toString()); return new DefaultLightblueMetadataResponse( callService(lightblueRequest, configuration.getMetadataServiceURI()), mapper); }
Source:
public String[] getSupportedExtensions() { return new String[] { "aiff", "aif" }; }

Target:
public String[] getSupportedExtensions() { return new String[] { "aif", "aiff", "aifc" }; }
Source:
private void parseFileInfo(Lexer lexer) throws AbsentInformationException { int lexemType = lexer.lexemType(); switch (lexemType) { case Lexer.NUMBER: { int fileId = integerValue(lexer.lexem()); if (isAsteriskLexem(lexer.nextLexem())) { throw new AbsentInformationException( JDIMessages.SourceDebugExtensionParser_16); } fCurrentStratum.addFileInfo(fileId, getNonAsteriskString(lexer)); break; } case Lexer.PLUS: { if (lexer.nextLexem() != Lexer.NUMBER) { throw new AbsentInformationException( JDIMessages.SourceDebugExtensionParser_17); } int fileId = integerValue(lexer.lexem()); if (isAsteriskLexem(lexer.nextLexem())) { throw new AbsentInformationException( JDIMessages.SourceDebugExtensionParser_16); } String fileName = getNonAsteriskString(lexer); if (isAsteriskLexem(lexer.lexemType())) { throw new AbsentInformationException( JDIMessages.SourceDebugExtensionParser_19); } fCurrentStratum.addFileInfo(fileId, fileName, getNonAsteriskString(lexer)); break; } default: throw new AbsentInformationException(NLS.bind( JDIMessages.SourceDebugExtensionParser_12, new String[] { new String(lexer.lexem()) })); } }

Target:
private void parseFileInfo(Lexer lexer) throws AbsentInformationException { int lexemType = lexer.lexemType(); switch (lexemType) { case Lexer.NUMBER: int fileId = integerValue(lexer.lexem()); if (isAsteriskLexem(lexer.nextLexem())) { throw new AbsentInformationException( JDIMessages.SourceDebugExtensionParser_16); } fCurrentStratum.addFileInfo(fileId, getNonAsteriskString(lexer)); break; case Lexer.PLUS: if (lexer.nextLexem() != Lexer.NUMBER) { throw new AbsentInformationException( JDIMessages.SourceDebugExtensionParser_17); } fileId = integerValue(lexer.lexem()); if (isAsteriskLexem(lexer.nextLexem())) { throw new AbsentInformationException( JDIMessages.SourceDebugExtensionParser_16); } String fileName = getNonAsteriskString(lexer); if (isAsteriskLexem(lexer.lexemType())) { throw new AbsentInformationException( JDIMessages.SourceDebugExtensionParser_19); } fCurrentStratum.addFileInfo(fileId, fileName, getNonAsteriskString(lexer)); break; default: throw new AbsentInformationException(NLS.bind(JDIMessages.SourceDebugExtensionParser_12, new String[] { new String(lexer.lexem()) })); } }
Source:
static public void addQueryParams(final StringBuilder urlString, final Map<String, String[]> requestParams) throws UnsupportedEncodingException { if (requestParams == null) return; boolean first = true; if (urlString.indexOf("?") > 0) { first = false; } for (Map.Entry<String, String[]> e : requestParams.entrySet()) { final String name = e.getKey(); final String[] vals = e.getValue(); if (vals == null) { urlString.append(first ? "?" : "&"); first = false; urlString.append(URLEncoder.encode(name, RemoteRepository.UTF8)); } else { for (String val : vals) { urlString.append(first ? "?" : "&"); first = false; urlString.append(URLEncoder.encode(name, RemoteRepository.UTF8)); urlString.append("="); if(val!=null) urlString.append(URLEncoder.encode(val, RemoteRepository.UTF8)); } } } }

Target:
static public void addQueryParams(final StringBuilder urlString, final Map<String, String[]> requestParams) throws UnsupportedEncodingException { if (requestParams == null) return; boolean first = true; if (urlString.indexOf("?") >= 0) { first = false; } for (Map.Entry<String, String[]> e : requestParams.entrySet()) { final String name = e.getKey(); final String[] vals = e.getValue(); if (vals == null) { urlString.append(first ? "?" : "&"); first = false; urlString.append(URLEncoder.encode(name, RemoteRepository.UTF8)); } else { for (String val : vals) { urlString.append(first ? "?" : "&"); first = false; urlString.append(URLEncoder.encode(name, RemoteRepository.UTF8)); urlString.append("="); if(val!=null) urlString.append(URLEncoder.encode(val, RemoteRepository.UTF8)); } } } }
Source:
public void testTagDelete() throws Exception { git.tag().setName("test").call(); assertTrue(getTags().filter(r -> r.getName().equals("refs/tags/test")) .findAny().isPresent()); assertEquals("", executeUnchecked("git tag -d test")[0]); assertFalse(getTags().filter(r -> r.getName().equals("refs/tags/test")) .findAny().isPresent()); }

Target:
public void testTagDelete() throws Exception { git.tag().setName("test").call(); assertNotNull(git.getRepository().exactRef("refs/tags/test")); assertEquals("", executeUnchecked("git tag -d test")[0]); assertNull(git.getRepository().exactRef("refs/tags/test")); }
Source:
public static SessionMap create(Config config) { Tracer tracer = new LoggingOptions(config).getTracer(); SessionMapOptions sessionMapOptions = new SessionMapOptions(config); String tableName = sessionMapOptions.getJdbcTableName(); Connection connection = null; try { connection = sessionMapOptions.getJdbcConnection(); } catch (SQLException e) { } return new JdbcBackedSessionMap(tracer, connection, tableName); }

Target:
public static SessionMap create(Config config) { Tracer tracer = new LoggingOptions(config).getTracer(); EventBus bus = new EventBusOptions(config).getEventBus(); JdbcSessionMapOptions sessionMapOptions = new JdbcSessionMapOptions(config); Connection connection; try { connection = sessionMapOptions.getJdbcConnection(); } catch (SQLException e) { throw new ConfigException(e); } return new JdbcBackedSessionMap(tracer, connection, bus); }
Source:
public void cleanup( final CommandContext commandContext, final Config state) throws IOException { final TaskRequest request = commandContext.getTaskRequest(); final long attemptId = request.getAttemptId(); final long taskId = request.getTaskId(); final Config taskConfig = request.getConfig(); final ObjectNode commandStatus = state.get("commandStatus", ObjectNode.class); final String clusterName = commandStatus.get("cluster_name").asText(); final String taskArn = commandStatus.get("task_arn").asText(); final EcsClientConfig clientConfig = createEcsClientConfig(Optional.of(clusterName), systemConfig, taskConfig); try (final EcsClient client = ecsClientFactory.createClient(clientConfig)) { final Task task; try { task = client.getTask(clusterName, taskArn); } catch (TaskSetNotFoundException e) { final String message = s("Cannot get the ECS task status. attemptId=%d, taskId=%d", attemptId, taskId); logger.warn(message); throw new TaskExecutionException(message); } final String message = s("Command task execution cancel requested: attemptId=%d, taskId=%d", attemptId, taskId); logger.info(message); logger.debug(s("Stop command task %s", task.getTaskArn())); client.stopTask(clusterName, task.getTaskArn()); throw new TaskExecutionException(message); } }

Target:
public void cleanup( final CommandContext commandContext, final Config state) throws IOException { final TaskRequest request = commandContext.getTaskRequest(); final long attemptId = request.getAttemptId(); final long taskId = request.getTaskId(); final Config taskConfig = request.getConfig(); final ObjectNode commandStatus = state.get("commandStatus", ObjectNode.class); final String clusterName = commandStatus.get("cluster_name").asText(); final String taskArn = commandStatus.get("task_arn").asText(); final EcsClientConfig clientConfig = createEcsClientConfig(Optional.of(clusterName), systemConfig, taskConfig); try (final EcsClient client = ecsClientFactory.createClient(clientConfig)) { final Task task = client.getTask(clusterName, taskArn); final String message = s("Command task execution will be stopped: attempt_id=%d, task_id=%d", attemptId, taskId); logger.info(message); logger.debug(s("Stop command task: %s", task.getTaskArn())); client.stopTask(clusterName, task.getTaskArn()); } }
Source:
private void initializeContainmentInput(EObject eObject, EReference eContainementReference) { List<Object> values = new ArrayList<>(); Adapter adapter = this.composedAdapterFactory.adapt(eObject, IEditingDomainItemProvider.class); if (adapter instanceof IEditingDomainItemProvider) { IEditingDomainItemProvider itemProviderAdapter = (IEditingDomainItemProvider) adapter; Collection<?> newChildDescriptors = itemProviderAdapter.getNewChildDescriptors(eObject, this.editingContextAdapter.getEditingDomain(), null); for (Object newChildDescriptor : newChildDescriptors) { if (newChildDescriptor instanceof CommandParameter) { CommandParameter commandParameter = (CommandParameter) newChildDescriptor; if (this.eReference.getEReferenceType().isSuperTypeOf(commandParameter.getEReference().getEReferenceType())) { values.add(commandParameter.getValue()); } } } } this.eClassInstanceComboViewer.setInput(values); if (values.size() > 0) { this.eClassInstanceComboViewer.setSelection(new StructuredSelection(values.get(0))); } else { this.eClassInstanceComboViewer.setSelection(new StructuredSelection()); } }

Target:
private void initializeContainmentInput(EObject eObject, EReference eContainementReference) { List<Object> values = new ArrayList<>(); Adapter adapter = this.composedAdapterFactory.adapt(eObject, IEditingDomainItemProvider.class); if (adapter instanceof IEditingDomainItemProvider) { IEditingDomainItemProvider itemProviderAdapter = (IEditingDomainItemProvider) adapter; Collection<?> newChildDescriptors = itemProviderAdapter.getNewChildDescriptors(eObject, this.editingContextAdapter.getEditingDomain(), null); for (Object newChildDescriptor : newChildDescriptors) { if (newChildDescriptor instanceof CommandParameter) { CommandParameter commandParameter = (CommandParameter) newChildDescriptor; Object value = commandParameter.getValue(); if (commandParameter.getEReference().equals(eContainementReference) && value instanceof EObject && this.eReference.getEReferenceType().isSuperTypeOf(((EObject) value).eClass())) { values.add(commandParameter.getValue()); } } } } this.eClassInstanceComboViewer.setInput(values); if (values.size() > 0) { this.eClassInstanceComboViewer.setSelection(new StructuredSelection(values.get(0))); } else { this.eClassInstanceComboViewer.setSelection(new StructuredSelection()); } }
Source:
public CurrentUserPopupPanel(Account account, boolean canLogOut) { super( true, false); setWidget(binder.createAndBindUi(this)); if (account.getFullName() != null) { userName.setText(account.getFullName()); } if (account.getPreferredEmail() != null) { userEmail.setText(account.getPreferredEmail()); } settings.setHref(PageLinks.SETTINGS); if (!canLogOut) { logout.setVisible(false); } else { logout.setHref(Gerrit.selfRedirect("/logout")); } }

Target:
public CurrentUserPopupPanel(Account account, boolean canLogOut) { super( true, false); setWidget(binder.createAndBindUi(this)); setStyleName(Gerrit.RESOURCES.css().userInfoPopup()); if (account.getFullName() != null) { userName.setText(account.getFullName()); } if (account.getPreferredEmail() != null) { userEmail.setText(account.getPreferredEmail()); } if (!canLogOut) { logout.setVisible(false); } else { logout.setHref(Gerrit.selfRedirect("/logout")); } }
Source:
private LayoutParams calculateLayoutParams(Boolean isInline, Boolean showAsSwitcher) { if (showAsSwitcher && !isInline) { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } else { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f); } }

Target:
private LayoutParams calculateLayoutParams(Boolean isInline, Boolean showAsSwitcher) { LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); if (!showAsSwitcher || isInline) { layoutParams.width = LayoutParams.WRAP_CONTENT; layoutParams.weight = 1.0f; } return layoutParams; }
Source:
public InputStream interpretResponseStream(@Nullable InputStream responseStream) { throwIfNoConnection(); if (isStethoEnabled()) { String contentEncoding = mConnection.getHeaderField("Content-Encoding"); responseStream = mStethoHook.interpretResponseStream( getStethoRequestId(), mConnection.getHeaderField("Content-Type"), contentEncoding, responseStream, contentEncoding != null ? new ContentLengthResponseHandler( mStethoHook, getStethoRequestId(), mConnection.getContentLength()) : new DefaultResponseHandler(mStethoHook, getStethoRequestId())); } return responseStream; }

Target:
public InputStream interpretResponseStream(@Nullable InputStream responseStream) { throwIfNoConnection(); if (isStethoEnabled()) { responseStream = mStethoHook.interpretResponseStream( getStethoRequestId(), mConnection.getHeaderField("Content-Type"), mConnection.getHeaderField("Content-Encoding"), responseStream, new DefaultResponseHandler(mStethoHook, getStethoRequestId())); } return responseStream; }
Source:
public void mercury_search_navigateUsingSearchSuggestionsOnDesktop() { String clickedSuggestion = new ArticlePage() .open("/d/") .getTopBar() .openSearch() .typeInSearch(SEARCH_PHRASE) .clickSearchSuggestion(0); Assertion.assertTrue(new SkinHelper(driver).isSkin(Skin.OASIS)); Assertion.assertEquals(clickedSuggestion.toLowerCase(), new ArticlePageObject().getArticleName().toLowerCase()); }

Target:
public void mercury_search_navigateUsingSearchSuggestionsOnDesktop() { String clickedSuggestion = new DiscussionsPage() .getTopBar() .openSearch() .typeInSearch(SEARCH_PHRASE) .clickSearchSuggestion(0); Assertion.assertTrue(new SkinHelper(driver).isSkin(Skin.OASIS)); Assertion.assertEquals(clickedSuggestion.toLowerCase(), new ArticlePageObject().getArticleName().toLowerCase()); }
Source:
private Cluster getClusterWithAuthenticationToken(OAuth2AuthenticationToken authentication) { OAuth2AuthorizedClient authorizedClient = getAuthorizedClient(authentication); if (isExpired(authorizedClient.getAccessToken())) { return reconnectedClusterForExpiredClient(authentication, authorizedClient); } return getClusterWithAuthorizedClient(authorizedClient); }

Target:
private Cluster getClusterWithAuthenticationToken(OAuth2AuthenticationToken authentication) { OAuth2AuthorizedClient authorizedClient = getAuthorizedClient(authentication); if (isExpired(authorizedClient.getAccessToken())) { return reconnectedClusterForExpiredClient(authentication, authorizedClient); } String credentials = authorizedClient.getAccessToken().getTokenValue(); String subject = getSubject(authentication); return getClusterWithCredentials(subject, credentials); }
Source:
Axis(final Vector3d vector3d) { this.direction = vector3d; }

Target:
private Axis(final Vector3d vector3d) { this.direction = vector3d; }
Source:
private List<String> filterGroups(DocumentModel registrationDoc, UserRegistrationConfiguration configuration) { List<String> wantedGroup = (List<String>) registrationDoc.getPropertyValue( configuration.getUserInfoGroupsField()); String originatingUser = registrationDoc.getProperty(UserInvitationComponent.PARAM_ORIGINATING_USER) .getValue(String.class); UserManager userManager = Framework.getService(UserManager.class); NuxeoPrincipal originatingPrincipal = userManager.getPrincipal(originatingUser); return wantedGroup.stream().filter(g -> acceptGroup(originatingPrincipal, g)).collect(Collectors.toList()); }

Target:
protected List<String> filterGroups(DocumentModel registrationDoc, UserRegistrationConfiguration configuration) { List<String> wantedGroup = (List<String>) registrationDoc.getPropertyValue( configuration.getUserInfoGroupsField()); NuxeoPrincipal originatingPrincipal = getOriginatingPrincipal(registrationDoc); if (originatingPrincipal == null) { return Collections.emptyList(); } return wantedGroup.stream().filter(g -> acceptGroup(originatingPrincipal, g)).collect(Collectors.toList()); }
Source:
public File deobfBinary(File original, String mappings, String... cachePath) throws IOException { project.getLogger().debug("Deobfuscating binary file with mappings {}", original.getName(), mappings); File names = findMapping(mappings); if (names == null || !names.exists()) { return null; } File cacheDir = getOrCreateCacheDir(cachePath); String mappedName = addMappingsToName(original.getName(), mappings); File input = new File(cacheDir, mappedName + ".input"); File output = new File(cacheDir, mappedName); HashStore cache = new HashStore() .load(input) .add("names", names) .add("orig", original); if (!cache.isSame() || !output.exists()) { SrgJarRenamer.rename(original, output, names); Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; }

Target:
public File deobfBinary(File original, String mappings, String... cachePath) throws IOException { project.getLogger().debug("Deobfuscating binary file with mappings {}", original.getName(), mappings); File names = findMapping(mappings); if (names == null || !names.exists()) { return null; } File output = getCacheFile(cachePath); File input = new File(output.getParent(), output.getName() + ".input"); HashStore cache = new HashStore() .load(input) .add("names", names) .add("orig", original); if (!cache.isSame() || !output.exists()) { SrgJarRenamer.rename(original, output, names); Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; }
Source:
public void registerSelf(final String authId, final String itemId, final School.ItemType itemType, final String registrationKey, final DbAuthChecker authChecker) throws AuthenticationException, DatabaseAccessException { if (!School.ItemType.COURSE.equals(itemType) && !School.ItemType.BANK_PROBLEM.equals(itemType)) { throw new AuthenticationException("Can only register users in a course or a bank problem", AuthenticationException.OTHER); } final DBCollection collection = database.getCollection(getCollectionFromType(itemType)); final DBObject result = collection.findOne(new ObjectId(itemId), new BasicDBObject(DatabaseStringConstants.USER_LIST, true) .append(DatabaseStringConstants.REGISTRATION_KEY, true)); if (result == null) { throw new DatabaseAccessException("The item with the id " + itemId + " Was not found in the database"); } if (!result.get(DatabaseStringConstants.REGISTRATION_KEY).equals(registrationKey)) { throw new AuthenticationException("Invalid Registration key", AuthenticationException.INVALID_PERMISSION); } final List<String> userGroups = (List<String>) result.get(DatabaseStringConstants.USER_LIST); insertUserIntoGroup(authId, userGroups.get(0), Authentication.AuthResponse.PermissionLevel.STUDENT); }

Target:
public void registerSelf(final String authId, final String itemId, final School.ItemType itemType, final String registrationKey, final DbAuthChecker authChecker) throws AuthenticationException, DatabaseAccessException { if (!School.ItemType.COURSE.equals(itemType) && !School.ItemType.BANK_PROBLEM.equals(itemType)) { throw new AuthenticationException("Can only register users in a course or a bank problem.", AuthenticationException.OTHER); } final DBCollection collection = database.getCollection(getCollectionFromType(itemType)); final DBObject result = collection.findOne(new ObjectId(itemId), new BasicDBObject(DatabaseStringConstants.USER_LIST, true) .append(DatabaseStringConstants.REGISTRATION_KEY, true)); if (result == null) { throw new DatabaseAccessException("The item with the id: " + itemId + " was not found in the database."); } if (!result.get(DatabaseStringConstants.REGISTRATION_KEY).equals(registrationKey)) { throw new AuthenticationException("Invalid Registration key", AuthenticationException.INVALID_PERMISSION); } final List<String> userGroups = (List<String>) result.get(DatabaseStringConstants.USER_LIST); insertUserIntoGroup(authId, userGroups.get(0), Authentication.AuthResponse.PermissionLevel.STUDENT); }
Source:
protected byte[] bufferForTransferring( Resource resource ) { long contentLength = resource.getContentLength(); if ( contentLength <= 0 ) { return new byte[DEFAULT_BUFFER_SIZE]; } int numberOf4KbSegmentsFor100Chunks = ( ( int ) ( contentLength / ( 4 * 1024 * 100 ) ) ); int bufferSizeFor100Chunks = numberOf4KbSegmentsFor100Chunks * 4 * 1024; int effectiveBufferSize = min( MAXIMUM_BUFFER_SIZE, max( DEFAULT_BUFFER_SIZE, bufferSizeFor100Chunks ) ); return new byte[effectiveBufferSize]; }

Target:
protected byte[] bufferForTransferring( Resource resource ) { final long contentLength = resource.getContentLength(); if ( contentLength <= 0 ) { return new byte[DEFAULT_BUFFER_SIZE]; } final int numberOfBufferSegments = ( ( int ) ( contentLength / ( BUFFER_SEGMENT_SIZE * MINIMUM_AMOUNT_OF_TRANSFER_CHUNKS ) ) ); final int potentialBufferSize = numberOfBufferSegments * BUFFER_SEGMENT_SIZE; final int effectiveBufferSize = min( MAXIMUM_BUFFER_SIZE, max( DEFAULT_BUFFER_SIZE, potentialBufferSize ) ); return new byte[effectiveBufferSize]; }
Source:
public static Actor buildActor(Tweet tweet) { Actor actor = new Actor(); User user = tweet.getUser(); actor.setId(formatId( Optional.fromNullable( user.getIdStr()) .or(Optional.of(user.getId().toString())) .orNull() )); actor.setDisplayName(user.getName()); actor.setAdditionalProperty("handle", user.getScreenName()); actor.setSummary(user.getDescription()); if (user.getUrl()!=null){ actor.setUrl(user.getUrl()); } Map<String, Object> extensions = new HashMap<String, Object>(); extensions.put("location", user.getLocation()); extensions.put("posts", user.getStatusesCount()); extensions.put("favorites", user.getFavouritesCount()); extensions.put("followers", user.getFollowersCount()); Map<String, Object> image = new HashMap<String, Object>(); image.put("url", user.getProfileImageUrlHttps()); extensions.put("image", image); extensions.put("screenName", user.getScreenName()); actor.setAdditionalProperty("extensions", extensions); return actor; }

Target:
public static Actor buildActor(Tweet tweet) { Actor actor = new Actor(); User user = tweet.getUser(); actor.setId(formatId( Optional.fromNullable( user.getIdStr()) .or(Optional.of(user.getId().toString())) .orNull() )); actor.setDisplayName(user.getName()); actor.setAdditionalProperty("handle", user.getScreenName()); actor.setSummary(user.getDescription()); if (user.getUrl()!=null){ actor.setUrl(user.getUrl()); } Map<String, Object> extensions = new HashMap<String, Object>(); extensions.put("location", user.getLocation()); extensions.put("posts", user.getStatusesCount()); extensions.put("favorites", user.getFavouritesCount()); extensions.put("followers", user.getFollowersCount()); Image profileImage = new Image(); profileImage.setUrl(user.getProfileImageUrlHttps()); actor.setImage(profileImage); extensions.put("screenName", user.getScreenName()); actor.setAdditionalProperty("extensions", extensions); return actor; }
Source:
public static String buildThreadDiagnosticString() { StringWriter sw = new StringWriter(); PrintWriter output = new PrintWriter(sw); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS"); output.println(String.format("Timestamp: %s", dateFormat.format(new Date()))); output.println(); output.println(buildThreadsDump()); String deadlocksInfo = buildDeadlockInfo(); if (deadlocksInfo != null) { output.println("====> DEADLOCKS DETECTED <===="); output.println(); output.println(deadlocksInfo); } return sw.toString(); }

Target:
public static String buildThreadDiagnosticString() { StringBuilder sb = new StringBuilder(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS"); sb.append(String.format("Timestamp: %s", dateFormat.format(new Date()))); sb.append(System.getProperty("line.separator")); sb.append(System.getProperty("line.separator")); sb.append(System.getProperty("line.separator")); sb.append(buildThreadsDump()); String deadlocksInfo = buildDeadlockInfo(); if (deadlocksInfo != null) { sb.append("====> DEADLOCKS DETECTED <===="); sb.append(System.getProperty("line.separator")); sb.append(System.getProperty("line.separator")); sb.append(deadlocksInfo); sb.append(System.getProperty("line.separator")); } return sb.toString(); }
Source:
public ListenableFuture<Image> createImage(ImageTemplate template) { checkState(template instanceof CloneImageTemplate, " digitalocean only supports creating images through cloning."); final CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; int powerOffEvent = api.getDropletApi().powerOff(Integer.parseInt(cloneTemplate.getSourceNodeId())); nodeStoppedPredicate.apply(powerOffEvent); int snapshotEvent = api.getDropletApi().snapshot(Integer.parseInt(cloneTemplate.getSourceNodeId()), cloneTemplate.getName()); logger.info(">> registered new Image, waiting for it to become available"); imageAvailablePredicate.apply(snapshotEvent); Optional<org.jclouds.digitalocean.domain.Image> snapshot = tryFind(api.getImageApi().list(), new Predicate<org.jclouds.digitalocean.domain.Image>() { @Override public boolean apply(org.jclouds.digitalocean.domain.Image input) { return input.getName().equals(cloneTemplate.getName()); } }); if (!snapshot.isPresent()) { throw new NoSuchElementException("Cannot find image with name: " + cloneTemplate.getName()); } return immediateFuture(imageTransformer.apply(snapshot.get())); }

Target:
public ListenableFuture<Image> createImage(ImageTemplate template) { checkState(template instanceof CloneImageTemplate, "DigitalOcean only supports creating images through cloning."); final CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; int powerOffEvent = api.getDropletApi().powerOff(Integer.parseInt(cloneTemplate.getSourceNodeId())); nodeStoppedPredicate.apply(powerOffEvent); int snapshotEvent = api.getDropletApi().snapshot(Integer.parseInt(cloneTemplate.getSourceNodeId()), cloneTemplate.getName()); logger.info(">> registered new Image, waiting for it to become available"); imageAvailablePredicate.apply(snapshotEvent); org.jclouds.digitalocean.domain.Image snapshot = find(api.getImageApi().list(), new Predicate<org.jclouds.digitalocean.domain.Image>() { @Override public boolean apply(org.jclouds.digitalocean.domain.Image input) { return input.getName().equals(cloneTemplate.getName()); } }); return immediateFuture(imageTransformer.apply(snapshot)); }
Source:
byte[] toBytes() { List<byte[]> segmentNamesBytes = new ArrayList<>(); int size = VERSION_SIZE + REFERENCE_TIME_SIZE + SEGMENT_COUNT_SIZE + logSegmentsUnderCompaction.size() * SEGMENT_NAME_LENGTH_SIZE; for (String segmentName : logSegmentsUnderCompaction) { byte[] segmentNameBytes = segmentName.getBytes(); segmentNamesBytes.add(segmentNameBytes); size += segmentNameBytes.length; } byte[] extraSegmentNameBytes = extraSegmentName == null ? ZERO_LENGTH_ARRAY : extraSegmentName.getBytes(); size += SEGMENT_NAME_LENGTH_SIZE + extraSegmentNameBytes.length + SWAP_SPACE_COUNT_SIZE; byte[] buf = new byte[size]; ByteBuffer bufWrap = ByteBuffer.wrap(buf); bufWrap.putShort(VERSION_0); bufWrap.putLong(referenceTime); bufWrap.putInt(logSegmentsUnderCompaction.size()); for (byte[] segmentNameBytes : segmentNamesBytes) { bufWrap.putInt(segmentNameBytes.length); bufWrap.put(segmentNameBytes); } bufWrap.putInt(extraSegmentNameBytes.length); bufWrap.put(extraSegmentNameBytes); bufWrap.putInt(swapSpaceCount); return buf; }

Target:
byte[] toBytes() { List<byte[]> segmentNameBytesList = new ArrayList<>(); int size = VERSION_SIZE + REFERENCE_TIME_SIZE + SEGMENT_COUNT_SIZE; for (String segmentName : logSegmentsUnderCompaction) { byte[] segmentNameBytes = segmentName.getBytes(); segmentNameBytesList.add(segmentNameBytes); size += SEGMENT_NAME_LENGTH_SIZE + segmentNameBytes.length; } byte[] extraSegmentNameBytes = extraSegmentName == null ? ZERO_LENGTH_ARRAY : extraSegmentName.getBytes(); size += SEGMENT_NAME_LENGTH_SIZE + extraSegmentNameBytes.length + SWAP_SPACE_COUNT_SIZE; byte[] buf = new byte[size]; ByteBuffer bufWrap = ByteBuffer.wrap(buf); bufWrap.putShort(VERSION_0); bufWrap.putLong(referenceTime); bufWrap.putInt(logSegmentsUnderCompaction.size()); for (byte[] segmentNameBytes : segmentNameBytesList) { bufWrap.putInt(segmentNameBytes.length); bufWrap.put(segmentNameBytes); } bufWrap.putInt(extraSegmentNameBytes.length); bufWrap.put(extraSegmentNameBytes); bufWrap.putInt(swapSpaceCount); return buf; }