auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { try { abvs.reset(); sb.reset(abvs); TaggedValuePointable tvp = args[0]; if (tvp.getTag() == ValueTag.SEQUENCE_TAG) { tvp.getValue(seq); int seqLen = seq.getEntryCount(); for (int j = 0; j < seqLen; ++j) { seq.getEntry(j, p); check(p); ah.atomize(p, ppool, tempTVP); sb.addItem(tempTVP); } } else { check(tvp); ah.atomize(tvp, ppool, tempTVP); sb.addItem(tempTVP); } sb.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001); } }

Target:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { try { abvs.reset(); sb.reset(abvs); TaggedValuePointable tvp = args[0]; if (tvp.getTag() == ValueTag.SEQUENCE_TAG) { tvp.getValue(seq); int seqLen = seq.getEntryCount(); for (int j = 0; j < seqLen; ++j) { seq.getEntry(j, p); ah.atomize(p, ppool, tempTVP); sb.addItem(tempTVP); } } else { ah.atomize(tvp, ppool, tempTVP); sb.addItem(tempTVP); } sb.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001); } }
Source:
private Queue<LeaderElection> createCluster(ICluster seed, int numOfNodes) { Queue<LeaderElection> leaders = new ConcurrentLinkedQueue<LeaderElection>(); for (int i = 0; i < numOfNodes; i++) { exec.execute(new Runnable() { @Override public void run() { ICluster member = Cluster.joinAwait(seed.address()); leaders.add(createLeaderElection(member)); } }); awaitSeconds(2); } return leaders; }

Target:
private Queue<LeaderElection> createCluster(ICluster seed, int numOfNodes) { Queue<LeaderElection> leaders = new ConcurrentLinkedQueue<LeaderElection>(); ICluster member = Cluster.joinAwait(seed.address()); leaders.add(createLeaderElection(member)); return leaders; }
Source:
public static int getDialogTheme(Context context) { String lightTheme = context.getResources().getString(R.string.light_theme_key); String darkTheme = context.getResources().getString(R.string.dark_theme_key); String blackTheme = context.getResources().getString(R.string.black_theme_key); String terminalTheme = context.getResources().getString(R.string.terminal_theme_key); String selectedTheme = getSelectedThemeString(context); int defaultTheme = R.style.DarkTheme; if (selectedTheme.equals(lightTheme)) defaultTheme = R.style.LightDialogTheme; else if (selectedTheme.equals(blackTheme)) defaultTheme = R.style.DarkDialogTheme; else if (selectedTheme.equals(darkTheme)) defaultTheme = R.style.DarkDialogTheme; else if (selectedTheme.equals(terminalTheme)) defaultTheme = R.style.TerminalDialogTheme; return defaultTheme; }

Target:
public static int getDialogTheme(Context context) { String selectedTheme = getSelectedThemeString(context); int defaultTheme = R.style.DarkTheme; if (selectedTheme.equals(lightTheme)) defaultTheme = R.style.LightDialogTheme; else if (selectedTheme.equals(blackTheme)) defaultTheme = R.style.DarkDialogTheme; else if (selectedTheme.equals(darkTheme)) defaultTheme = R.style.DarkDialogTheme; else if (selectedTheme.equals(terminalTheme)) defaultTheme = R.style.TerminalDialogTheme; return defaultTheme; }
Source:
public UserType getType() { if (isAdmin) { return UserType.ADMINISTRATOR; } else if (isTeacher){ return UserType.TEACHER; } else { return null; } }

Target:
public UserType getType() { if (isAdmin) { return UserType.ADMINISTRATOR; } else if (isTeacher){ return UserType.TEACHER; } else { return UserType.OTHER_STAFF; } }
Source:
public DeviceStatusBreakdown getDeviceStatusBreakdown(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("start_ts") final Long startTs, @QueryParam("end_ts") final Long endTs) { final Jedis jedis = jedisPool.getResource(); Long sensesCount = -1L; Long pillsCount = -1L; try { sensesCount = jedis.zcount(ActiveDevicesTrackerConfiguration.SENSE_ACTIVE_SET_KEY, startTs, endTs); pillsCount = jedis.zcount(ActiveDevicesTrackerConfiguration.PILL_ACTIVE_SET_KEY, startTs, endTs); } catch (Exception e) { LOGGER.error("Failed to get active senses count because {}", e.getMessage()); throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(e.getMessage()).build()); } finally { jedisPool.returnResource(jedis); } LOGGER.debug("Senses count is from to {}", sensesCount, startTs, endTs); LOGGER.debug("Pills count is from to {}", pillsCount, startTs, endTs); return new DeviceStatusBreakdown(sensesCount, pillsCount); }

Target:
public DeviceStatusBreakdown getDeviceStatusBreakdown(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("start_ts") final Long startTs, @QueryParam("end_ts") final Long endTs) { if (startTs == null || endTs == null) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Require start_ts & end_ts").build()); } final Jedis jedis = jedisPool.getResource(); Long sensesCount = -1L; Long pillsCount = -1L; try { sensesCount = jedis.zcount(ActiveDevicesTrackerConfiguration.SENSE_ACTIVE_SET_KEY, startTs, endTs); pillsCount = jedis.zcount(ActiveDevicesTrackerConfiguration.PILL_ACTIVE_SET_KEY, startTs, endTs); } catch (Exception e) { LOGGER.error("Failed to get active senses count because {}", e.getMessage()); throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(e.getMessage()).build()); } finally { jedisPool.returnResource(jedis); } LOGGER.debug("Senses count is from to {}", sensesCount, startTs, endTs); LOGGER.debug("Pills count is from to {}", pillsCount, startTs, endTs); return new DeviceStatusBreakdown(sensesCount, pillsCount); }
Source:
public void testLastDDLTimestampBootstrap() throws Exception { String schemaName = "S_" + generateUniqueName(); String tableName = "T_" + generateUniqueName(); String viewName = "V_" + generateUniqueName(); String fullTableName = SchemaUtil.getTableName(schemaName, tableName); String fullViewName = SchemaUtil.getTableName(schemaName, viewName); try (Connection conn = getConnection(false, null)) { conn.createStatement().execute( "CREATE TABLE " + fullTableName + " (PK1 VARCHAR NOT NULL, PK2 VARCHAR, KV1 VARCHAR, KV2 VARCHAR CONSTRAINT " + "PK PRIMARY KEY(PK1, PK2)) "); conn.createStatement().execute( "CREATE VIEW " + fullViewName + " AS SELECT * FROM " + fullTableName); nullDDLTimestamps(conn); conn.commit(); long tableTS = getRowTimestampForMetadata(conn, schemaName, tableName, PTableType.TABLE); long viewTS = getRowTimestampForMetadata(conn, schemaName, viewName, PTableType.VIEW); UpgradeUtil.bootstrapLastDDLTimestamp(conn.unwrap(PhoenixConnection.class)); long actualTableTS = getLastTimestampForMetadata(conn, schemaName, tableName, PTableType.TABLE); long actualViewTS = getLastTimestampForMetadata(conn, schemaName, viewName, PTableType.VIEW); assertEquals(tableTS, actualTableTS); assertEquals(viewTS, actualViewTS); } }

Target:
public void testLastDDLTimestampBootstrap() throws Exception { String schemaName = "S_" + generateUniqueName(); String tableName = "T_" + generateUniqueName(); String viewName = "V_" + generateUniqueName(); String fullTableName = SchemaUtil.getTableName(schemaName, tableName); String fullViewName = SchemaUtil.getTableName(schemaName, viewName); try (Connection conn = getConnection(false, null)) { conn.createStatement().execute( "CREATE TABLE " + fullTableName + " (PK1 VARCHAR NOT NULL, PK2 VARCHAR, KV1 VARCHAR, KV2 VARCHAR CONSTRAINT " + "PK PRIMARY KEY(PK1, PK2)) "); conn.createStatement().execute( "CREATE VIEW " + fullViewName + " AS SELECT * FROM " + fullTableName); nullDDLTimestamps(conn); long tableTS = getRowTimestampForMetadata(conn, schemaName, tableName, PTableType.TABLE); long viewTS = getRowTimestampForMetadata(conn, schemaName, viewName, PTableType.VIEW); UpgradeUtil.bootstrapLastDDLTimestamp(conn.unwrap(PhoenixConnection.class)); long actualTableTS = getLastTimestampForMetadata(conn, schemaName, tableName, PTableType.TABLE); long actualViewTS = getLastTimestampForMetadata(conn, schemaName, viewName, PTableType.VIEW); assertEquals(tableTS, actualTableTS); assertEquals(viewTS, actualViewTS); } }
Source:
private String getProcessName(String tid) { String execName = fProcessNameMap.get(tid); if (execName != null) { return execName; } ITmfTrace trace = getTrace(); if (trace == null) { return tid; } ITmfStateSystem kernelSs = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID); if (kernelSs == null) { return tid; } try { int cpusNode = kernelSs.getQuarkAbsolute(Attributes.THREADS); List<Integer> cpuNodes = kernelSs.getSubAttributes(cpusNode, false); for (Integer tidQuark : cpuNodes) { if (kernelSs.getAttributeName(tidQuark).equals(tid)) { int execNameQuark; List<ITmfStateInterval> execNameIntervals; try { execNameQuark = kernelSs.getQuarkRelative(tidQuark, Attributes.EXEC_NAME); execNameIntervals = StateSystemUtils.queryHistoryRange(kernelSs, execNameQuark, getStartTime(), getEndTime()); } catch (AttributeNotFoundException e) { continue; } catch (StateSystemDisposedException e) { break; } for (ITmfStateInterval execNameInterval : execNameIntervals) { if (!execNameInterval.getStateValue().isNull() && execNameInterval.getStateValue().getType() == ITmfStateValue.Type.STRING) { execName = execNameInterval.getStateValue().unboxStr(); fProcessNameMap.put(tid, execName); return execName; } } } } } catch (AttributeNotFoundException e) { } return tid; }

Target:
private String getProcessName(String tid) { String execName = fProcessNameMap.get(tid); if (execName != null) { return execName; } ITmfTrace trace = getTrace(); if (trace == null) { return tid; } ITmfStateSystem kernelSs = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID); if (kernelSs == null) { return tid; } try { int cpusNode = kernelSs.getQuarkAbsolute(Attributes.THREADS); List<Integer> cpuNodes = kernelSs.getSubAttributes(cpusNode, false); for (Integer tidQuark : cpuNodes) { if (kernelSs.getAttributeName(tidQuark).equals(tid)) { int execNameQuark; List<ITmfStateInterval> execNameIntervals; try { execNameQuark = kernelSs.getQuarkRelative(tidQuark, Attributes.EXEC_NAME); execNameIntervals = StateSystemUtils.queryHistoryRange(kernelSs, execNameQuark, getStartTime(), getEndTime()); } catch (TimeRangeException | AttributeNotFoundException e) { continue; } catch (StateSystemDisposedException e) { break; } for (ITmfStateInterval execNameInterval : execNameIntervals) { if (!execNameInterval.getStateValue().isNull() && execNameInterval.getStateValue().getType() == ITmfStateValue.Type.STRING) { execName = execNameInterval.getStateValue().unboxStr(); fProcessNameMap.put(tid, execName); return execName; } } } } } catch (AttributeNotFoundException e) { } return tid; }
Source:
public void initialize() { delayTimeline = new Timeline( new KeyFrame(Duration.ZERO, event -> updateWatchButtonTimer()), new KeyFrame(Duration.seconds(1)) ); delayTimeline.setCycleCount(Timeline.INDEFINITE); watchButton.setDisable(true); watchButton.setOnAction(event -> { var player = getAnyPlayer(game); if (player.isPresent()) { replayService.runLiveReplay(game.getId(), player.get().getId()); } }); }

Target:
public void initialize() { delayTimeline = new Timeline( new KeyFrame(Duration.ZERO, event -> updateWatchButtonTimer()), new KeyFrame(Duration.seconds(1)) ); delayTimeline.setCycleCount(Timeline.INDEFINITE); watchButton.setDisable(true); watchButton.setOnAction(event -> replayService.runLiveReplay(game.getId())); }
Source:
protected Collection<VView> getViews(ExecutionEvent event) { final IStructuredSelection selection = (IStructuredSelection) HandlerUtil .getCurrentSelection(event); final List<VView> views = new LinkedList<VView>(); final List<IFile> failedFiles = new LinkedList<IFile>(); @SuppressWarnings("unchecked") final Iterator<Object> it = selection.iterator(); while (it.hasNext()) { final Object selectedObject = it.next(); if (selectedObject instanceof IFile) { final IFile file = (IFile) selectedObject; VView view = null; try { view = ViewModelHelper.loadView(file, registeredEcores); } catch (final IOException ex) { Activator.logException(ex); } if (view == null) { failedFiles.add(file); continue; } views.add(view); } } if (!failedFiles.isEmpty()) { showErrorMessage(failedFiles, views.isEmpty()); if (views.isEmpty()) { return null; } } return views; }

Target:
protected Collection<VView> getViews(ExecutionEvent event) { final IStructuredSelection selection = (IStructuredSelection) HandlerUtil .getCurrentSelection(event); final List<VView> views = new LinkedList<VView>(); final List<IFile> failedFiles = new LinkedList<IFile>(); @SuppressWarnings("unchecked") final Iterator<Object> it = selection.iterator(); while (it.hasNext()) { final Object selectedObject = it.next(); if (selectedObject instanceof IFile) { final IFile file = (IFile) selectedObject; VView view = null; try { view = ViewModelHelper.loadView(file, registeredEcores); } catch (final IOException ex) { Activator.logException(ex); } if (view == null || !ViewModelHelper.viewIsResolved(view)) { failedFiles.add(file); continue; } views.add(view); } } if (!failedFiles.isEmpty()) { showErrorMessage(failedFiles, views.isEmpty()); if (views.isEmpty()) { return null; } } return views; }
Source:
public void setTopItem (TreeItem item) { if (item == null) error (SWT.ERROR_NULL_ARGUMENT); if (item.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); if (item.parent != this) return; long vAdjustment; if (OS.GTK3) { vAdjustment = OS.gtk_scrollable_get_vadjustment(handle); } else { vAdjustment = OS.gtk_tree_view_get_vadjustment(handle); } cachedAdjustment = OS.gtk_adjustment_get_value(vAdjustment); topItem= item; }

Target:
public void setTopItem (TreeItem item) { if (item == null) error (SWT.ERROR_NULL_ARGUMENT); if (item.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); if (item.parent != this) return; long path = OS.gtk_tree_model_get_path (modelHandle, item.handle); showItem (path, false); OS.gtk_tree_view_scroll_to_cell (handle, path, 0, true, 0, 0); OS.gtk_tree_path_free (path); long vAdjustment; if (OS.GTK3) { vAdjustment = OS.gtk_scrollable_get_vadjustment(handle); } else { vAdjustment = OS.gtk_tree_view_get_vadjustment(handle); } cachedAdjustment = OS.gtk_adjustment_get_value(vAdjustment); topItem = item; }
Source:
void shutdown() { LOGGER.info("Shutdown requested. Please wait when cleaning up..."); for (WorkerSubQuery p : executingSubQueries.values()) { p.kill(); } if (!connectionPool.isShutdown()) { if (!abruptShutdown) { connectionPool.shutdown(); } else { connectionPool.shutdownNow(); } } connectionPool.releaseExternalResources(); if (pipelineExecutor != null && !pipelineExecutor.isShutdown()) { pipelineExecutor.shutdown(); } if (LOGGER.isInfoEnabled()) { LOGGER.info("shutdown IPC completed"); } messageProcessingExecutor.shutdownNow(); queryExecutor.shutdown(); apiServer.shutdownNow(); if (LOGGER.isInfoEnabled()) { LOGGER.info("Worker #" + myID + " shutdown completed"); } }

Target:
void shutdown() { LOGGER.info("Shutdown requested. Please wait when cleaning up..."); for (WorkerSubQuery p : executingSubQueries.values()) { p.kill(); } if (!connectionPool.isShutdown()) { if (!abruptShutdown) { connectionPool.shutdown(); } else { connectionPool.shutdownNow(); } } connectionPool.releaseExternalResources(); if (pipelineExecutor != null && !pipelineExecutor.isShutdown()) { pipelineExecutor.shutdown(); } if (LOGGER.isInfoEnabled()) { LOGGER.info("shutdown IPC completed"); } messageProcessingExecutor.shutdownNow(); queryExecutor.shutdownNow(); apiServer.shutdownNow(); if (LOGGER.isInfoEnabled()) { LOGGER.info("Worker #" + myID + " shutdown completed"); } }
Source:
public File findHook(Repository repository, String hookName) { if (hookName == null) { return null; } File hookDir = getHooksDirectory(repository); if (hookDir == null) { return null; } File hookFile = new File(hookDir, hookName); if (hookFile.isAbsolute()) { if (!hookFile.exists() || FS.DETECTED.supportsExecute() && !FS.DETECTED.canExecute(hookFile)) { return null; } return hookFile; } else { try { File runDirectory = getRunDirectory(repository, hookName); if (runDirectory == null) { return null; } Path hookPath = runDirectory.getAbsoluteFile().toPath() .resolve(hookFile.toPath()); FS fs = repository.getFS(); if (fs == null) { fs = FS.DETECTED; } if (!Files.exists(hookPath) || fs.supportsExecute() && !fs.canExecute(hookPath.toFile())) { return null; } return hookPath.toFile(); } catch (InvalidPathException e) { LOG.warn(MessageFormat.format(JGitText.get().invalidHooksPath, hookFile)); return null; } } }

Target:
public File findHook(Repository repository, String hookName) { if (hookName == null) { return null; } File hookDir = getHooksDirectory(repository); if (hookDir == null) { return null; } File hookFile = new File(hookDir, hookName); if (hookFile.isAbsolute()) { if (!hookFile.exists() || FS.DETECTED.supportsExecute() && !FS.DETECTED.canExecute(hookFile)) { return null; } } else { try { File runDirectory = getRunDirectory(repository, hookName); if (runDirectory == null) { return null; } Path hookPath = runDirectory.getAbsoluteFile().toPath() .resolve(hookFile.toPath()); FS fs = repository.getFS(); if (fs == null) { fs = FS.DETECTED; } if (!Files.exists(hookPath) || fs.supportsExecute() && !fs.canExecute(hookPath.toFile())) { return null; } hookFile = hookPath.toFile(); } catch (InvalidPathException e) { LOG.warn(MessageFormat.format(JGitText.get().invalidHooksPath, hookFile)); return null; } } return hookFile; }
Source:
protected void executeVmCommand() { Guid newActiveSnapshotId = Guid.NewGuid(); Guid createdSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); getParameters().setSnapshotType(determineSnapshotType()); getParameters().setInitialVmStatus(getVm().getStatus()); getSnapshotDao().updateId(createdSnapshotId, newActiveSnapshotId); setActionReturnValue(createdSnapshotId); addSnapshotToDB(createdSnapshotId); createSnapshotsForDisks(getDisksList(), newActiveSnapshotId); if (getTaskIdList().isEmpty()) { getParameters().setTaskGroupSuccess(true); incrementVmGeneration(); } setSucceeded(true); }

Target:
protected void executeVmCommand() { Guid newActiveSnapshotId = Guid.NewGuid(); Guid createdSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); getParameters().setSnapshotType(determineSnapshotType()); getParameters().setInitialVmStatus(getVm().getStatus()); getSnapshotDao().updateId(createdSnapshotId, newActiveSnapshotId); setActionReturnValue(createdSnapshotId); addSnapshotToDB(createdSnapshotId); createSnapshotsForDisks(newActiveSnapshotId); if (getTaskIdList().isEmpty()) { getParameters().setTaskGroupSuccess(true); incrementVmGeneration(); } setSucceeded(true); }
Source:
protected Collection<ICompletionProposal> getCompletionProposals(Collection<Proposal> proposals, String prefix, int offset) { final List<ICompletionProposal> result = new ArrayList<>(); prefix = "".equals(prefix) ? null : prefix; for (Proposal proposal : proposals) { StyledCompletionProposal styledProposal = proposal.asStyledCompletionProposal(prefix, offset); if (styledProposal != null) { result.add(styledProposal); } } return result; }

Target:
protected Collection<ICompletionProposal> getCompletionProposals(Collection<Proposal> proposals, String prefix, int offset) { final List<ICompletionProposal> result = new ArrayList<>(); prefix = StringUtils.emptyToNull(prefix); for (Proposal proposal : proposals) { StyledCompletionProposal styledProposal = proposal.asStyledCompletionProposal(prefix, offset); if (styledProposal != null) { result.add(styledProposal); } } return result; }
Source:
protected SQLException logAndConvert(Throwable ex) { SQLException e = null; try { e = DbException.toSQLException(ex); if (trace == null) { DbException.traceThrowable(e); } else { int errorCode = e.getErrorCode(); if (errorCode >= 23000 && errorCode < 24000) { trace.info(e, "exception"); } else { trace.error(e, "exception"); } } } catch(Throwable another) { if (e == null) { try { e = new SQLException("GeneralError", "HY000", ErrorCode.GENERAL_ERROR_1, ex); } catch (OutOfMemoryError | NoClassDefFoundError ignored) { e = DbException.SQL_OOME; } } e.addSuppressed(another); } return e; }

Target:
protected SQLException logAndConvert(Throwable ex) { SQLException e = null; try { e = DbException.toSQLException(ex); if (trace == null) { DbException.traceThrowable(e); } else { int errorCode = e.getErrorCode(); if (errorCode >= 23000 && errorCode < 24000) { trace.info(e, "exception"); } else { trace.error(e, "exception"); } } } catch(Throwable another) { if (e == null) { try { e = new SQLException("GeneralError", "HY000", ErrorCode.GENERAL_ERROR_1, ex); } catch (OutOfMemoryError | NoClassDefFoundError ignored) { return DbException.SQL_OOME; } } e.addSuppressed(another); } return e; }
Source:
public void dataReceived(byte[] data) { String dataString = new String(data); END'. if (dataString.equals(MSG_START)) { if (receivedFile != null && receivedFile.exists()) receivedFile.delete(); try { String dateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); receivedFile = new File(String.format(FILE_NAME, dateTime)); receivedFile.createNewFile(); if (fileOutputStream != null) fileOutputStream.close(); fileOutputStream = new FileOutputStream(receivedFile); } catch (IOException e) { e.printStackTrace(); } System.out.println(">> START message received, saving data to file..."); sendAck(); } else if (dataString.equals(MSG_END)) { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException ignore) fileOutputStream = null; } System.out.format(">> END message received, file '%s'\n\n", receivedFile.getAbsolutePath()); sendAck(); } else if (fileOutputStream != null) { byte[] payload = Arrays.copyOfRange(data, 0, data.length - 1); int checksum = ByteUtils.byteToInt(data[data.length - 1]); XBeeChecksum chk = new XBeeChecksum(); chk.add(payload); if (chk.generate() == checksum) { try { fileOutputStream.write(payload); } catch (IOException e) { e.printStackTrace(); } sendAck(); } } }

Target:
public void dataReceived(byte[] data) { String dataString = new String(data); END'. if (dataString.startsWith(MSG_START)) { String fileName = dataString.split(SEPARATOR)[1]; try { receivedFile = new File(fileName); if (receivedFile.exists()) receivedFile.delete(); receivedFile.createNewFile(); if (fileOutputStream != null) fileOutputStream.close(); fileOutputStream = new FileOutputStream(receivedFile); } catch (IOException e) { e.printStackTrace(); } System.out.println(">> START message received, saving data to file..."); sendAck(); } else if (dataString.equals(MSG_END)) { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException ignore) fileOutputStream = null; } System.out.format(">> END message received, file '%s'\n\n", receivedFile.getAbsolutePath()); sendAck(); } else if (fileOutputStream != null) { byte[] payload = Arrays.copyOfRange(data, 0, data.length - 1); int checksum = ByteUtils.byteToInt(data[data.length - 1]); XBeeChecksum chk = new XBeeChecksum(); chk.add(payload); if (chk.generate() == checksum) { try { fileOutputStream.write(payload); } catch (IOException e) { e.printStackTrace(); } sendAck(); } } }
Source:
private List<Record> getRecordsForXLSX(InputStream xls) throws IOException { List<Record> records = new ArrayList<>(); XSSFWorkbook wb = new XSSFWorkbook(xls); XSSFSheet sheet = wb.getSheetAt(0); for (int j = 0; j <= sheet.getLastRowNum(); j++) { XSSFRow row = sheet.getRow(j); if (row != null) { for (int i = 0; i < row.getLastCellNum(); i++) { XSSFCell cell = row.getCell(i); cell.setCellType(HSSFCell.CELL_TYPE_STRING); Record record = changeCellTypeToString(cell, i, j); if (record != null) { records.add(record); } } } } return records; }

Target:
private List<Record> getRecordsForXLSX(InputStream xls) throws IOException { List<Record> records = new ArrayList<>(); XSSFWorkbook wb = new XSSFWorkbook(xls); XSSFSheet sheet = wb.getSheetAt(0); for (int j = 0; j <= sheet.getLastRowNum(); j++) { XSSFRow row = sheet.getRow(j); if (Objects.nonNull(row)) { for (int i = 0; i < row.getLastCellNum(); i++) { XSSFCell cell = row.getCell(i); cell.setCellType(HSSFCell.CELL_TYPE_STRING); Record record = changeCellTypeToString(cell, i, j); if (Objects.nonNull(record)) { records.add(record); } } } } return records; }
Source:
private static int decodeBucketIndex(int entry) { return entry >>> (Integer.SIZE - EXTENDED_PREFIX_BITS); }

Target:
private static int decodeBucketIndex(int entry) { return decodeBucketIndex(EXTENDED_PREFIX_BITS, entry); }
Source:
public DimFilter optimize() { if (this.getExtractionFn() instanceof LookupExtractionFn && ((LookupExtractionFn) this.getExtractionFn()).isOptimize()) { LookupExtractionFn exFn = (LookupExtractionFn) this.getExtractionFn(); if (exFn.isRetainMissingValue()) { return this; } if (Objects.equals(Strings.emptyToNull(this.getValue()), exFn.getReplaceMissingValueWith())) { return this; } LookupExtractor lookup = exFn.getLookup(); final List<String> keys = lookup.unapply(this.getValue()); final String dimensionName = this.getDimension(); if (!keys.isEmpty()) { return new InDimFilter(dimensionName, keys, null); } } return this; }

Target:
public DimFilter optimize() { return new SelectorDimFilter(dimension, value, extractionFn).optimize(); }
Source:
default String toIndentedString() { class Local { String toString(Tree<T> tree, int depth) { if (tree.isEmpty()) { return ""; } else { final String indent = repeat(' ', depth * 2); final String value = String.valueOf(tree.getValue()).replaceAll("\\s+", " ").trim(); if (tree.isLeaf()) { return "\n" + indent + value; } else { final String children = tree.getChildren() .map(child -> toString(child, depth + 1)) .join(); return String.format("%n%s%s%s", indent, value, children); } } } String repeat(char c, int n) { final char[] buf = new char[n]; Arrays.fill(buf, c); return String.valueOf(buf); } } return new Local().toString(this, 0); }

Target:
default String toIndentedString() { class Local { String toString(Tree<T> tree, int depth) { if (tree.isEmpty()) { return ""; } else { final String indent = repeat(' ', depth * 2); final String value = String.valueOf(tree.getValue()).replaceAll("\\s+", " ").trim(); if (tree.isLeaf()) { return "\n" + indent + value; } else { final String children = tree.getChildren() .map(child -> toString(child, depth + 1)) .join(); return "\n" + indent + value + children; } } } String repeat(char c, int n) { final char[] buf = new char[n]; Arrays.fill(buf, c); return String.valueOf(buf); } } return new Local().toString(this, 0); }
Source:
public Digest() { super(new Column[] { new Column("org/apache/tajo/storage/text", TajoDataTypes.Type.TEXT) }); }

Target:
public Digest() { super(new Column[] { new Column("text", TajoDataTypes.Type.TEXT) }); }
Source:
public int getGracePeriodMinutes() { return (int) gracePeriod.toMinutes(); }

Target:
public long getGracePeriodMinutes() { return gracePeriod.toMinutes(); }
Source:
public Object circuitBreakerAroundAdvice(ProceedingJoinPoint proceedingJoinPoint, @Nullable CircuitBreaker circuitBreakerAnnotation) throws Throwable { Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod(); String methodName = method.getDeclaringClass().getName() + "#" + method.getName(); if (circuitBreakerAnnotation == null) { circuitBreakerAnnotation = getCircuitBreakerAnnotation(proceedingJoinPoint); } if(circuitBreakerAnnotation == null) { return proceedingJoinPoint.proceed(); } String backend = circuitBreakerAnnotation.name(); io.github.resilience4j.circuitbreaker.CircuitBreaker circuitBreaker = getOrCreateCircuitBreaker(methodName, backend); Class<?> returnType = method.getReturnType(); if (StringUtils.isEmpty(circuitBreakerAnnotation.fallbackMethod())) { return proceed(proceedingJoinPoint, methodName, circuitBreaker, returnType); } FallbackMethod fallbackMethod = FallbackMethod.builder().recoveryMethodName(circuitBreakerAnnotation.fallbackMethod()) .originalMethod(method).originalMethodArgs(proceedingJoinPoint.getArgs()) .targetObject(proceedingJoinPoint.getTarget()).build(); return fallbackDecorators.decorate(fallbackMethod, () -> proceed(proceedingJoinPoint, methodName, circuitBreaker, returnType)).apply(); }

Target:
public Object circuitBreakerAroundAdvice(ProceedingJoinPoint proceedingJoinPoint, @Nullable CircuitBreaker circuitBreakerAnnotation) throws Throwable { Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod(); String methodName = method.getDeclaringClass().getName() + "#" + method.getName(); if (circuitBreakerAnnotation == null) { circuitBreakerAnnotation = getCircuitBreakerAnnotation(proceedingJoinPoint); } if(circuitBreakerAnnotation == null) { return proceedingJoinPoint.proceed(); } String backend = circuitBreakerAnnotation.name(); io.github.resilience4j.circuitbreaker.CircuitBreaker circuitBreaker = getOrCreateCircuitBreaker(methodName, backend); Class<?> returnType = method.getReturnType(); if (StringUtils.isEmpty(circuitBreakerAnnotation.fallbackMethod())) { return proceed(proceedingJoinPoint, methodName, circuitBreaker, returnType); } FallbackMethod fallbackMethod = FallbackMethod.create(circuitBreakerAnnotation.fallbackMethod(), method, proceedingJoinPoint.getArgs(), proceedingJoinPoint.getTarget()); return fallbackDecorators.decorate(fallbackMethod, () -> proceed(proceedingJoinPoint, methodName, circuitBreaker, returnType)).apply(); }
Source:
public LiveMigrateDiskCommand(T parameters) { super(parameters); setStoragePoolId(getVm().getStoragePoolId()); getParameters().setStoragePoolId(getStoragePoolId().getValue()); getParameters().setVdsId(getVdsId()); getParameters().setDiskAlias(getDiskAlias()); getParameters().setImageGroupID(getImageGroupId()); getParameters().setCommandType(getActionType()); getParameters().setTaskGroupSuccess(getParameters().getTaskGroupSuccess() && (getVm().getStatus() == VMStatus.Up || getVm().getStatus() == VMStatus.Paused)); }

Target:
public LiveMigrateDiskCommand(T parameters) { super(parameters); setStoragePoolId(getVm().getStoragePoolId()); getParameters().setStoragePoolId(getStoragePoolId().getValue()); getParameters().setVdsId(getVdsId()); getParameters().setDiskAlias(getDiskAlias()); getParameters().setImageGroupID(getImageGroupId()); getParameters().setCommandType(getActionType()); getParameters().setTaskGroupSuccess(getParameters().getTaskGroupSuccess() && getVm().getStatus().isUpOrPaused()); }
Source:
public void testThreads() throws InterruptedException { final Logger logger = Mockito.mock(Logger.class); final int totalCount = Runtime.getRuntime().availableProcessors(); List<Future<?>> futures = new ArrayList<>(); Mockito.when(logger.isLoggable(any())).thenReturn(true); ExecutorService executor = Executors.newFixedThreadPool(totalCount); System.out.println(String.format("Will run %d threads", totalCount)); try (final Progress progress = new Progress(logger, "foo", totalCount)) { while (progress.getLoggerThread().getState() != Thread.State.WAITING) { System.out.println("Waiting for the logger thread to reach the initial wait()"); TimeUnit.MILLISECONDS.sleep(10); } for (int i = 0; i < totalCount; i++) { futures.add(executor.submit(progress::increment)); } } System.out.println("Waiting for threads to finish"); futures.forEach(future -> { try { future.get(); } catch (Exception e) { Assert.fail(); } }); executor.shutdown(); System.out.println("Verifying"); Mockito.verify(logger, atLeast(1)).log(any(), anyString(), any(Object[].class)); }

Target:
public void testThreads() throws InterruptedException { final Logger logger = Mockito.mock(Logger.class); final int totalCount = Runtime.getRuntime().availableProcessors(); List<Future<?>> futures = new ArrayList<>(); Mockito.when(logger.isLoggable(any())).thenReturn(true); ExecutorService executor = Executors.newFixedThreadPool(totalCount); System.out.println(String.format("Will run %d threads", totalCount)); try (final Progress progress = new Progress(logger, "foo", totalCount)) { while (progress.getLoggerThread().getState() != Thread.State.WAITING) { System.out.println("Waiting for the logger thread to reach the initial wait()"); TimeUnit.MILLISECONDS.sleep(10); } for (int i = 0; i < totalCount; i++) { futures.add(executor.submit(progress::increment)); } System.out.println("Waiting for threads to finish"); futures.forEach(future -> { try { future.get(); } catch (Exception e) { Assert.fail(); } }); } executor.shutdown(); System.out.println("Verifying"); Mockito.verify(logger, atLeast(1)).log(any(), anyString(), any(Object[].class)); }
Source:
private HttpUriBuilder(URI previous) { scheme = previous.getScheme(); host = previous.getHost(); port = previous.getPort(); path = isNull(previous.getRawPath()) ? null : percentDecode(previous.getRawPath()); params.putAll(parseParams(previous.getRawQuery())); }

Target:
private HttpUriBuilder(URI previous) { scheme = previous.getScheme(); host = previous.getHost(); port = previous.getPort(); path = Optional.ofNullable(previous.getRawPath()).map(HttpUriBuilder::percentDecode).orElse(null); params.putAll(parseParams(previous.getRawQuery())); }
Source:
public void loadConfig() throws IOException { final Resource config = configPathDir.get(CONFIG_FILE_NAME); InputStream fis = config.in(); try { this.configuration.load(fis); } finally { fis.close(); } }

Target:
public void loadConfig() throws IOException { Resource config = configPathDir.get(CONFIG_FILE_NAME); try (InputStream fis = config.in()) { this.configuration.load(fis); } }
Source:
private void updateSelectedList() { Set<Integer> indexes = new HashSet<Integer>(); selectedList.clear(); ListBox listBox = asListBox(); while (listBox.getSelectedIndex() >= 0) { int index = listBox.getSelectedIndex(); listBox.setItemSelected(index, false); String selectedElem = listBox.getItemText(index); T value = getTypedValue(selectedElem); selectedList.add(value); indexes.add(index); } for (Integer index : indexes) { listBox.setItemSelected(index, true); } }

Target:
private void updateSelectedList() { Set<Integer> indexes = new HashSet<Integer>(); selectedList.clear(); ListBox listBox = asListBox(); while (listBox.getSelectedIndex() >= 0) { int index = listBox.getSelectedIndex(); listBox.setItemSelected(index, false); if (index >= 0 && index < typedItemList.size()) { T value = typedItemList.get(index); selectedList.add(value); } indexes.add(index); } for (Integer index : indexes) { listBox.setItemSelected(index, true); } }
Source:
public String getShortName() { return "JBoss"; }

Target:
public String getShortName() { return "JBossAS7"; }
Source:
public void cli(Configuration config) { if (config.m_startAction != StartAction.GET) { System.err.println("This can only be called for GET action."); VoltDB.exit(-1); } if (!config.m_voltdbRoot.exists() || !config.m_voltdbRoot.canRead() || !config.m_voltdbRoot.canExecute() || !config.m_voltdbRoot.isDirectory()) { try { System.err.println("Invalid Voltdbroot directory: " + config.m_voltdbRoot.getCanonicalPath()); } catch (IOException ex) { } VoltDB.exit(-1); } ConfigFactory.clearProperty(Settings.CONFIG_DIR); switch (config.m_getOption) { case DEPLOYMENT: outputDeployment(config); break; case SCHEMA: outputSchema(config); break; case CLASSES: outputProcedure(config); break; } VoltDB.exit(0); }

Target:
public void cli(Configuration config) { if (config.m_startAction != StartAction.GET) { System.err.println("This can only be called for GET action."); VoltDB.exit(-1); } if (!config.m_voltdbRoot.exists() || !config.m_voltdbRoot.canRead() || !config.m_voltdbRoot.canExecute() || !config.m_voltdbRoot.isDirectory()) { try { System.err.println("FATAL: Invalid Voltdbroot directory: " + config.m_voltdbRoot.getCanonicalPath()); } catch (IOException ex) { } VoltDB.exit(-1); } ConfigFactory.clearProperty(Settings.CONFIG_DIR); switch (config.m_getOption) { case DEPLOYMENT: outputDeployment(config); break; case SCHEMA: outputSchema(config); break; } VoltDB.exit(0); }
Source:
public Store open(URI address) throws IllegalAddressException, NoSuitableDriverException, StoreException { if (address == null) { throw new NullPointerException("address"); } String scheme = address.getScheme(); if (scheme == null) { throw new IllegalAddressException(address.toString(), context.getStrings().get("storage.address.no_scheme")); } scheme = scheme.toLowerCase(); InstalledDriver driver; List<InstalledDriver> installedDrivers = null; lock.lock(); try { driver = drivers.get(scheme); if (driver == null) { installedDrivers = getInstalledDrivers(); } } finally { lock.unlock(); } if (driver != null) { return new Store(driver, address).open(); } for (InstalledDriver idriver : installedDrivers) { try { return new Store(idriver, address).open(); } catch (IllegalAddressException ex) { } catch (StoreException ex) { } } throw new NoSuitableDriverException(address); }

Target:
public Store open(URI address) throws IllegalAddressException, NoSuitableDriverException, StoreException { if (address == null) { throw new NullPointerException("address"); } String scheme = address.getScheme(); if (scheme != null) { scheme = scheme.toLowerCase(); } InstalledDriver driver; List<InstalledDriver> installedDrivers = null; synchronized (drivers) { driver = (scheme == null ? null : drivers.get(scheme)); if (driver == null) { installedDrivers = getInstalledDrivers(); } } if (driver != null) { return new Store(driver, address).open(); } for (InstalledDriver idriver : installedDrivers) { try { return new Store(idriver, address).open(); } catch (IllegalAddressException ex) { } catch (StoreException ex) { } } throw new NoSuitableDriverException(address); }
Source:
public StudentProfileAttributes getCopy() { return new StudentProfileAttributes(this.toEntity()); }

Target:
public StudentProfileAttributes getCopy() { StudentProfileAttributes newSpa = new StudentProfileAttributes(this.toEntity()); newSpa.modifiedDate = this.modifiedDate; return newSpa; }
Source:
public static void logRetriesExhaustedWithDetailsException( Logger log, String context, RetriesExhaustedWithDetailsException exception) { if (log.isDebugEnabled()) { log.error("For context {}: exception occured during a bulk operation: {}", context, exception.getExhaustiveDescription()); } log.error("For context {}: exception occured during a bulk operation: {}", context, exception.getMessage()); log.error("For context {}: First bulk operation exception", exception.getCause(0), context); Map<String, Integer> furtherInfo = new TreeMap<>(); List<Throwable> causes = exception.getCauses(); for (Throwable throwable : causes) { String message = throwable.getMessage(); Integer count = furtherInfo.get(message); if (count == null) { furtherInfo.put(message, 1); } else { furtherInfo.put(message, 1 + count); } } for (Entry<String, Integer> entry : furtherInfo.entrySet()) { log.error( "For context {}: The follow exception occurred times: '{}'.", context, entry.getValue(), entry.getKey()); } }

Target:
public static void logRetriesExhaustedWithDetailsException( Logger log, String context, RetriesExhaustedWithDetailsException exception) { if (log.isDebugEnabled()) { log.error("For context {}: exception occured during a bulk operation: {}", context, exception.getExhaustiveDescription()); } if (exception.getNumExceptions() == 0) { log.error( "For context {}: Got a RetriesExhaustedWithDetailsException without any details.", exception); return; } Map<String, Integer> furtherInfo = new TreeMap<>(); List<Throwable> causes = exception.getCauses(); for (Throwable throwable : causes) { String message = throwable.getMessage(); Integer count = furtherInfo.get(message); if (count == null) { furtherInfo.put(message, 1); } else { furtherInfo.put(message, 1 + count); } } log.error( String.format( "For context %s: %d exceptions occured during a bulk operation:\n\t%s.\n" + "The stack trace is a sample exception, of the first exception.\n" + "Breakdown of exceptions {type - count}: %s", context, exception.getNumExceptions(), exception.getMessage(), furtherInfo), exception.getCause(0)); }
Source:
public FBOConfig getFboConfig(ResourceUrn fboName) { FBOConfig fboConfig = fboConfigs.get(fboName); if (fboConfigs == null) { logger.error("Failed to retrieve FBOConfig '" + fboName + "'!"); } return fboConfig; }

Target:
public FBOConfig getFboConfig(ResourceUrn fboName) { FBOConfig fboConfig = fboConfigs.get(fboName); if (fboConfig == null) { logger.warn("Failed to retrieve FBOConfig '" + fboName + "'!"); } return fboConfig; }
Source:
public String display() { String nl = System.lineSeparator(); return "Task \'" + name + "\' : " + nl + LogFormatter.addIndent("Description = '" + description + "'" + nl + (restartTaskOnError.isSet() ? "restartTaskOnError = '" + restartTaskOnError.getValue() + '\'' + nl : "") + (onTaskError.isSet() ? "onTaskError = '" + onTaskError.getValue() + '\'' + nl : "") + (maxNumberOfExecution.isSet() ? "maxNumberOfExecution = '" + maxNumberOfExecution.getValue() .getIntegerValue() + '\'' + nl : "") + "tag = " + tag + nl + LogFormatter.displayMap("variables", variables) + nl + LogFormatter.displayMap("genericInformation", genericInformation) + nl + "InputFiles = " + inputFiles + nl + "OutputFiles = " + outputFiles + nl + "ParallelEnvironment = " + parallelEnvironment + nl + "FlowBlock = '" + flowBlock + "'" + nl + "SelectionScripts = " + displaySelectionScripts() + nl + "ForkEnvironment = " + forkEnvironment + nl + "PreScript = " + ((preScript != null) ? preScript.display() : null) + nl + "PostScript = " + ((postScript != null) ? postScript.display() : null) + nl + "CleanScript = " + ((cScript != null) ? cScript.display() : null) + nl + "FlowScript = " + ((flowScript != null) ? flowScript.display() : null) + nl + "PreciousResult = " + preciousResult + nl + "PreciousLogs = " + preciousLogs + nl + "RunAsMe = " + runAsMe + nl + "WallTime = " + wallTime + nl + "Dependences = " + dependences); }

Target:
public String display() { return "Task '" + name + "' : " + System.lineSeparator() + addIndent(Stream.of(lineWithQuotes("Description", description), line("restartTaskOnError", restartTaskOnError), line("onTaskError", onTaskError), line("maxNumberOfExecution", maxNumberOfExecution, () -> maxNumberOfExecution.getValue().getIntegerValue()), line("tag", tag), line("variables", variables), line("genericInformation", genericInformation), line("InputFiles", inputFiles), line("OutputFiles", outputFiles), line("ParallelEnvironment", parallelEnvironment), lineWithQuotes("FlowBlock", flowBlock), line("SelectionScripts", displaySelectionScripts()), line("ForkEnvironment", forkEnvironment), line("PreScript", preScript, () -> preScript.display()), line("PostScript", postScript, () -> postScript.display()), line("CleanScript", cScript, () -> cScript.display()), line("FlowScript", flowScript, () -> flowScript.display()), line("PreciousResult", preciousResult), line("PreciousLogs", preciousLogs), line("RunAsMe", runAsMe), line("WallTime", wallTime), line("Dependences", dependences)) .filter(s -> !s.isEmpty()) .collect(Collectors.joining(System.lineSeparator()))); }
Source:
public SubChannel(String service, @NotNull TChannel topChannel, Connection.Direction preferredDirection) { if (topChannel == null) { throw new NullPointerException("`topChannel` cannot be null"); } if (preferredDirection == null) { throw new NullPointerException("`preferredDirection` cannot be null"); } this.service = service; this.topChannel = topChannel; this.peerManager = topChannel.getPeerManager(); this.initTimeout = topChannel.getInitTimeout(); this.preferredDirection = preferredDirection; }

Target:
public SubChannel(String service, @NotNull TChannel topChannel, Connection.Direction preferredDirection) { this.service = service; this.topChannel = topChannel; this.peerManager = topChannel.getPeerManager(); this.initTimeout = topChannel.getInitTimeout(); this.preferredDirection = preferredDirection; }
Source:
public CompletableFuture<Void> downloadAndInstallMod(String uid) { return fafService.getMod(uid).thenAccept(mod -> downloadAndInstallMod(mod, null, null)) .exceptionally(throwable -> { logger.warn("Mod for modupdate not found", throwable); return null; }); }

Target:
public CompletableFuture<Void> downloadAndInstallMod(String uid) { return fafService.getMod(uid).thenAccept(mod -> downloadAndInstallMod(mod, null, null)); }
Source:
void onNewDocument() { final Path contextPath = context.getActivePackage().getPackageMainResourcesPath(); helper.createNewGuidedDecisionTable( contextPath, "", GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, view, ( path ) -> onOpenDocumentsInEditor( new ArrayList<Path>() {{ add( path ); }} ) ); }

Target:
void onNewDocument() { final Path contextPath = context.getActivePackage().getPackageMainResourcesPath(); helper.createNewGuidedDecisionTable( contextPath, "", GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, view, ( path ) -> onOpenDocumentsInEditor( Collections.singletonList( path ) ) ); }
Source:
private static <ViewModelType extends ViewModel> Method getInitializeMethod(ViewModelType viewModel) { for (Method method : viewModel.getClass().getDeclaredMethods()) { if(method.isAnnotationPresent(Initialize.class)) { method.setAccessible(true); return method; } } return null; }

Target:
private static <ViewModelType extends ViewModel> Method getInitializeMethod(ViewModelType viewModel) { for (Method method : viewModel.getClass().getDeclaredMethods()) { if(method.isAnnotationPresent(Initialize.class)) { return method; } } return null; }
Source:
public void setText (String string) { checkWidget(); if (string == null) error (SWT.ERROR_NULL_ARGUMENT); if ((style & SWT.SEPARATOR) != 0) return; if (text.equals (string)) return; super.setText (string); String accelString = ""; int index = string.indexOf ('\t'); if (index != -1) { boolean isRTL = (parent.style & SWT.RIGHT_TO_LEFT) != 0; accelString = (isRTL? "" : " ") + string.substring (index+1, string.length()) + (isRTL? " " : ""); string = string.substring (0, index); } char chars = fixMnemonic (string); byte buffer = Converter.wcsToMbcs (null, chars, true); long label = OS.gtk_bin_get_child (handle); if (label != 0 && OS.GTK_IS_LABEL(label)) { OS.gtk_label_set_text_with_mnemonic (label, buffer); if (OS.GTK_IS_ACCEL_LABEL(label)) { if (OS.GTK3) { OS.gtk_accel_label_set_accel_widget(label, handle); MaskKeysym maskKeysym = getMaskKeysym(); if (maskKeysym != null) { OS.gtk_accel_label_set_accel(label, maskKeysym.keysym, maskKeysym.mask); } } else { buffer = Converter.wcsToMbcs (null, accelString, true); long ptr = OS.g_malloc (buffer.length); OS.memmove (ptr, buffer, buffer.length); long oldPtr = OS.GTK_ACCEL_LABEL_GET_ACCEL_STRING (label); OS.GTK_ACCEL_LABEL_SET_ACCEL_STRING (label, ptr); if (oldPtr != 0) OS.g_free (oldPtr); } } } }

Target:
public void setText (String string) { checkWidget(); if (string == null) error (SWT.ERROR_NULL_ARGUMENT); if ((style & SWT.SEPARATOR) != 0) return; if (text.equals (string)) return; super.setText (string); String accelString = ""; int index = string.indexOf ('\t'); if (index != -1) { boolean isRTL = (parent.style & SWT.RIGHT_TO_LEFT) != 0; accelString = (isRTL? "" : " ") + string.substring (index+1, string.length()) + (isRTL? " " : ""); string = string.substring (0, index); } char chars = fixMnemonic (string); byte buffer = Converter.wcsToMbcs (null, chars, true); long label = OS.gtk_bin_get_child (handle); if (label != 0 && OS.GTK_IS_LABEL(label)) { OS.gtk_label_set_text_with_mnemonic (label, buffer); if (OS.GTK_IS_ACCEL_LABEL(label)) { if (OS.GTK3) { OS.gtk_accel_label_set_accel_widget(label, handle); if (OS.GTK_VERSION >= OS.VERSION(3, 6, 0)) { MaskKeysym maskKeysym = getMaskKeysym(); if (maskKeysym != null) { OS.gtk_accel_label_set_accel(label, maskKeysym.keysym, maskKeysym.mask); } } } else { buffer = Converter.wcsToMbcs (null, accelString, true); long ptr = OS.g_malloc (buffer.length); OS.memmove (ptr, buffer, buffer.length); long oldPtr = OS.GTK_ACCEL_LABEL_GET_ACCEL_STRING (label); OS.GTK_ACCEL_LABEL_SET_ACCEL_STRING (label, ptr); if (oldPtr != 0) OS.g_free (oldPtr); } } } }