auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Fragment generateFragment() { final Fragment fragment; try { fragment = fragmentClass.newInstance(); } catch (InstantiationException e) { throw new Fragment.InstantiationException( String.format(ERROR_MSG_INSTANTIATION, fragmentClass), e); } catch (IllegalAccessException e) { throw new Fragment.InstantiationException( String.format(ERROR_MSG_INSTANTIATION, fragmentClass), e); } fragment.setArguments(args); return fragment; }

Target:
public Fragment generateFragment() { final Fragment fragment; try { fragment = fragmentClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new Fragment.InstantiationException( String.format(ERROR_MSG_INSTANTIATION, fragmentClass), e); } fragment.setArguments(args); return fragment; }
Source:
public Optional<Startpoint> readStartpoint(SystemStreamPartition ssp) { return readStartpointMap(Collections.singletonMap(null, Collections.singleton(ssp)), false).get(null) .get(ssp); }

Target:
public Optional<Startpoint> readStartpoint(SystemStreamPartition ssp) { Map<String, byte[]> startpointBytes = readWriteStore.all(); return readStartpoint(startpointBytes, ssp, null); }
Source:
private static <I> void checkSupported(Class<I> idClass) { checkNotNull(idClass); Identifier.Type.getType(idClass); }

Target:
public static <I> void checkSupported(Class<I> idClass) { checkNotNull(idClass); Identifier.Type.getType(idClass); }
Source:
private Object readResolve() { if (StringUtils.isNotBlank(collectionUrl) && StringUtils.isNotBlank(username) && password != null && StringUtils.isNotBlank(password.getPlainText())) { try { final URI uri = new URI(collectionUrl); String hostName = uri.getHost(); List<StandardUsernamePasswordCredentials> credentials = TeamCollectionConfiguration.findCredentials(hostName); for (StandardUsernamePasswordCredentials credential : credentials) { if (credential.getUsername().equals(username) && credential.getPassword().getPlainText().equals(password.getPlainText())) { this.credentialsId = credential.getId(); return this; } } this.credentialsId = TeamCollectionConfiguration.setCredentials(hostName, username, password.getPlainText()); } catch (Exception ignore) { } } return this; }

Target:
protected Object readResolve() { if (StringUtils.isNotBlank(collectionUrl) && password != null && StringUtils.isNotBlank(password.getPlainText())) { try { final URI uri = new URI(collectionUrl); String hostName = uri.getHost(); List<StandardUsernamePasswordCredentials> credentials = TeamCollectionConfiguration.findCredentials(hostName); for (StandardUsernamePasswordCredentials credential : credentials) { if ((StringUtils.isBlank(username) || credential.getUsername().equals(username)) && credential.getPassword().getPlainText().equals(password.getPlainText())) { this.credentialsId = credential.getId(); return this; } } this.credentialsId = TeamCollectionConfiguration.setCredentials(hostName, username, password.getPlainText()); } catch (Exception ex) { logger.log(Level.WARNING, String.format("Get or generate credentials for collection url: %s and username: %s failed.", collectionUrl, username), ex); } } return this; }
Source:
public void launchTask(ExecutorDriver driver, TaskInfo taskInfo) { currentTaskId = taskInfo.getTaskId(); TaskInfo crateTask = null; try { crateTask = TaskInfo.parseFrom(taskInfo.getData()); } catch (InvalidProtocolBufferException e) { LOGGER.debug("Could not de-serialize TaskInfo", e); e.printStackTrace(); } if (crateTask != null) { LOGGER.debug("Prepare crateTask: {}", crateTask); boolean prepared = prepare(crateTask); if (prepared) { LOGGER.debug("Launch task: {}", crateTask.getCommand().getValue()); task = new Task(crateTask); startProcess(driver, task); driver.sendStatusUpdate(TaskStatus.newBuilder() .setTaskId(taskInfo.getTaskId()) .setState(TaskState.TASK_RUNNING) .build()); return; } } fail(driver); }

Target:
public void launchTask(ExecutorDriver driver, TaskInfo taskInfo) { currentTaskId = taskInfo.getTaskId(); driver.sendStatusUpdate(TaskStatus.newBuilder() .setTaskId(currentTaskId) .setState(TaskState.TASK_STARTING) .build()); TaskInfo crateTask = null; try { crateTask = TaskInfo.parseFrom(taskInfo.getData()); } catch (InvalidProtocolBufferException e) { LOGGER.debug("Could not de-serialize TaskInfo", e); e.printStackTrace(); } if (crateTask != null) { LOGGER.debug("Prepare crateTask: {}", crateTask); boolean prepared = prepare(crateTask); if (prepared) { LOGGER.debug("Launch task: {}", crateTask.getCommand().getValue()); task = new Task(crateTask); startProcess(driver, task); driver.sendStatusUpdate(TaskStatus.newBuilder() .setTaskId(currentTaskId) .setState(TaskState.TASK_RUNNING) .build()); return; } } fail(driver); }
Source:
public Hardware apply(final VirtualGuest from) { HardwareBuilder builder = new HardwareBuilder().ids(from.getId() + "") .name(from.getHostname()) .hypervisor("XenServer") .processors(ImmutableList.of(new Processor(from.getStartCpus(), 0))) .ram(from.getMaxMemory()); if(from.getVirtualGuestBlockDevices() != null) { builder.volumes( FluentIterable.from(from.getVirtualGuestBlockDevices()).filter(new Predicate<VirtualGuestBlockDevice>() { @Override public boolean apply(VirtualGuestBlockDevice input) { return input.getMountType().equals("Disk"); } }) .transform(new Function<VirtualGuestBlockDevice, Volume>() { @Override public Volume apply(VirtualGuestBlockDevice item) { float volumeSize = item.getVirtualDiskImage().getCapacity(); return new VolumeImpl( item.getId() + "", from.isLocalDiskFlag() ? Volume.Type.LOCAL : Volume.Type.SAN, volumeSize, null, item.getBootableFlag() == 1, false); } }).toSet()); } return builder.build(); }

Target:
public Hardware apply(final VirtualGuest from) { HardwareBuilder builder = new HardwareBuilder().ids(from.getId() + "") .name(from.getHostname()) .hypervisor("XenServer") .processors(ImmutableList.of(new Processor(from.getStartCpus(), 2))) .ram(from.getMaxMemory()); if (from.getVirtualGuestBlockDevices() != null) { builder.volumes( FluentIterable.from(from.getVirtualGuestBlockDevices()).filter(new Predicate<VirtualGuestBlockDevice>() { @Override public boolean apply(VirtualGuestBlockDevice input) { return input.getMountType().equals("Disk"); } }) .transform(new Function<VirtualGuestBlockDevice, Volume>() { @Override public Volume apply(VirtualGuestBlockDevice item) { float volumeSize = item.getVirtualDiskImage().getCapacity(); return new VolumeImpl( item.getId() + "", from.isLocalDiskFlag() ? Volume.Type.LOCAL : Volume.Type.SAN, volumeSize, null, item.getBootableFlag() == 1, false); } }).toSet()); } return builder.build(); }
Source:
public static void hideKeyboard(Activity activity) { if (activity == null) return; final View focusView = activity.getCurrentFocus(); if (focusView == null) return; final InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); if (inputMethodManager == null) return; inputMethodManager.hideSoftInputFromWindow(focusView.getWindowToken(), 0); }

Target:
public static void hideKeyboard(Activity activity) { if(activity == null) return; View view = activity.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } }
Source:
public DirCache call() throws IOException { final File file = new File(repo.getWorkDir(), filepath); if (!file.exists()) { DirCache dc = DirCache.lock(repo); try { if (dc.findEntry(filepath) < 0) { throw new IllegalStateException(MessageFormat.format( "File {0} does not exist", filepath)); } else { return dc; } } finally { dc.unlock(); } } if (file.isDirectory()) throw new IllegalStateException(MessageFormat.format( "Adding directory {0} not yet supported", filepath)); ObjectWriter ow = new ObjectWriter(repo); final ObjectId id = ow.writeBlob(file); DirCache dc = DirCache.lock(repo); try { DirCacheBuilder builder = dc.builder(); final TreeWalk tw = new TreeWalk(repo); tw.reset(); tw.addTree(new DirCacheBuildIterator(builder)); FileTreeIterator fileTreeIterator = new FileTreeIterator( repo.getWorkDir(), repo.getFS()); tw.addTree(fileTreeIterator); tw.setRecursive(true); String lastAddedFile = null; while (tw.next()) { if (tw.getPathString().equals(filepath)) { if (!(filepath.equals(lastAddedFile))) { DirCacheEntry entry = new DirCacheEntry(filepath); entry.setObjectId(id); entry.setFileMode(repo.getFS().canExecute(file) ? FileMode.EXECUTABLE_FILE : FileMode.REGULAR_FILE); entry.setLastModified(file.lastModified()); entry.setLength((int) file.length()); builder.add(entry); lastAddedFile = filepath; } } else { final DirCacheIterator c = tw.getTree(0, DirCacheIterator.class); builder.add(c.getDirCacheEntry()); } } builder.commit(); } finally { dc.unlock(); } return dc; }

Target:
public DirCache call() throws IOException { DirCache dc = DirCache.lock(repo); try { ObjectWriter ow = new ObjectWriter(repo); ObjectId id; DirCacheIterator c; DirCacheBuilder builder = dc.builder(); final TreeWalk tw = new TreeWalk(repo); tw.reset(); tw.addTree(new DirCacheBuildIterator(builder)); FileTreeIterator fileTreeIterator = new FileTreeIterator( repo.getWorkDir(), repo.getFS()); tw.addTree(fileTreeIterator); tw.setRecursive(true); tw.setFilter(PathFilterGroup.createFromStrings(filepatterns)); String lastAddedFile = null; while (tw.next()) { String path = tw.getPathString(); final File file = new File(repo.getWorkDir(), path); if (!(path.equals(lastAddedFile))) { if (file.exists()) { id = ow.writeBlob(file); DirCacheEntry entry = new DirCacheEntry(path); entry.setObjectId(id); entry.setFileMode(repo.getFS().canExecute(file) ? FileMode.EXECUTABLE_FILE : FileMode.REGULAR_FILE); entry.setLastModified(file.lastModified()); entry.setLength((int) file.length()); builder.add(entry); lastAddedFile = path; } else { c = tw.getTree(0, DirCacheIterator.class); builder.add(c.getDirCacheEntry()); } } } builder.commit(); } finally { dc.unlock(); } return dc; }
Source:
public FileConfigurationSource() { this.ymlFileName = "config.yml"; this.yamlFileName = "config.yaml"; this.propertiesFileName = "config.properties"; String configurationFileName = System.getProperty("com.kumuluz.ee.configuration.file"); if (configurationFileName != null && !configurationFileName.isEmpty()) { if (".yml".equals(configurationFileName.substring(configurationFileName.length() - 4))) { this.ymlFileName = configurationFileName; } else if (".yaml".equals(configurationFileName.substring(configurationFileName.length() - 5))) { this.yamlFileName = configurationFileName; } else if (".properties".equals(configurationFileName.substring(configurationFileName.length() - 11))) { this.propertiesFileName = configurationFileName; } } }

Target:
public FileConfigurationSource() { this.ymlFileName = "config.yml"; this.yamlFileName = "config.yaml"; this.propertiesFileName = "config.properties"; String configurationFileName = System.getProperty("com.kumuluz.ee.configuration.file"); if (configurationFileName != null && !configurationFileName.isEmpty()) { this.ymlFileName = configurationFileName; this.yamlFileName = configurationFileName; this.propertiesFileName = configurationFileName; } this.logDeferrer = new LogDeferrer<>(); this.logDeferrer.init(() -> Logger.getLogger(FileConfigurationSource.class.getName())); }
Source:
private static synchronized ITerminalConnector getConnector(IRemoteConnection irc) throws RemoteConnectionException { ITerminalConnector con = cons.get(irc.getAddress()); if(con == null) { con = TerminalConnectorExtension.makeTerminalConnector( "org.eclipse.ptp.remote.internal.terminal.RemoteToolsConnector"); cons.put(irc.getAddress(),con); } else if(irc.isOpen()) { return null; } else { irc.open(new NullProgressMonitor()); return null; } return con; }

Target:
private static synchronized ITerminalConnector getConnector(IRemoteConnection irc) throws RemoteConnectionException { ITerminalConnector con = cons.get(irc.getAddress()); if(con == null) { con = TerminalConnectorExtension.makeTerminalConnector( "org.eclipse.ptp.remote.internal.terminal.RemoteToolsConnector"); cons.put(irc.getAddress(),con); } return con; }
Source:
public void stop() { LOGGER.info("stop called for cluster tiers on {}", this.clusterUri); entityFactory = null; inMaintenance = false; clusterTierEntities.clear(); entity = null; closeConnection(); }

Target:
public void stop() { LOGGER.info("Closing connection to cluster {}", this.clusterUri); entityFactory = null; inMaintenance = false; clusterTierEntities.clear(); entity = null; closeConnection(); }
Source:
private void addAndDismiss(final ReadingList readingList) { final ReadingListPage page = ReadingListDaoProxy.page(readingList, pageTitle); ReadingList.DAO.listContainsTitleAsync(readingList, page, new CallbackTask.Callback<Boolean>() { @Override public void success(Boolean contains) { if (isAdded()) { if (contains) { ((PageActivity) getActivity()) .showReadingListAddedSnackbar(getString(R.string.reading_list_already_exists), isOnboarding); } else { ((PageActivity) getActivity()) .showReadingListAddedSnackbar(TextUtils.isEmpty(readingList.getTitle()) ? getString(R.string.reading_list_added_to_unnamed) : String.format(getString(R.string.reading_list_added_to_named), readingList.getTitle()), isOnboarding); new ReadingListsFunnel(pageTitle.getSite()).logAddToList(readingList, readingLists.size(), invokeSource); ReadingList.DAO.makeListMostRecent(readingList); } } } }); ReadingList.DAO.addTitleToList(readingList, page); page.savedOrSaving(); dismiss(); }

Target:
private void addAndDismiss(final ReadingList readingList) { final ReadingListPage page = ReadingListDaoProxy.page(readingList, pageTitle); ReadingList.DAO.listContainsTitleAsync(readingList, page, new CallbackTask.Callback<Boolean>() { @Override public void success(Boolean contains) { if (isAdded()) { if (contains) { ((PageActivity) getActivity()) .showReadingListAddedSnackbar(getString(R.string.reading_list_already_exists), isOnboarding); } else { ((PageActivity) getActivity()) .showReadingListAddedSnackbar(TextUtils.isEmpty(readingList.getTitle()) ? getString(R.string.reading_list_added_to_unnamed) : String.format(getString(R.string.reading_list_added_to_named), readingList.getTitle()), isOnboarding); new ReadingListsFunnel(pageTitle.getSite()).logAddToList(readingList, readingLists.size(), invokeSource); ReadingList.DAO.makeListMostRecent(readingList); } } } }); L.d("filename will be: " + getBaseDir(pageTitle)); ReadingList.DAO.addTitleToList(readingList, page, getBaseDir(pageTitle)); page.savedOrSaving(); dismiss(); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; if (svc.equals(req.getParameter("service"))) { final HttpServletResponse rsp = (HttpServletResponse) response; nocache(rsp); try { final Repository db = getRepository(req); final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final PacketLineOut out = new PacketLineOut(buf); out.writeString("# service=" + svc + "\n"); out.end(); advertise(req, db, new PacketLineOutRefAdvertiser(out)); rsp.setContentType("application/x-" + svc + "-advertisement"); send(buf.toByteArray(), req, rsp); } catch (ServiceNotAuthorizedException e) { rsp.sendError(SC_UNAUTHORIZED); } catch (ServiceNotEnabledException e) { rsp.sendError(SC_FORBIDDEN); } } else { chain.doFilter(request, response); } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; if (svc.equals(req.getParameter("service"))) { final HttpServletResponse rsp = (HttpServletResponse) response; try { final Repository db = getRepository(req); final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final PacketLineOut out = new PacketLineOut(buf); out.writeString("# service=" + svc + "\n"); out.end(); advertise(req, db, new PacketLineOutRefAdvertiser(out)); rsp.setContentType("application/x-" + svc + "-advertisement"); send(buf.toByteArray(), req, rsp); } catch (ServiceNotAuthorizedException e) { rsp.sendError(SC_UNAUTHORIZED); } catch (ServiceNotEnabledException e) { rsp.sendError(SC_FORBIDDEN); } } else { chain.doFilter(request, response); } }
Source:
public int hashCode() { return Objects.hashCode(this.getConverters()); }

Target:
public int hashCode() { return Objects.hash(this.getConverters(), this.getName()); }
Source:
public static synchronized @Nullable SegmentStoreTableDataProvider getOrCreate(ITmfTrace trace, @Nullable ISegmentStoreProvider provider) { if (provider == null) { return null; } return PROVIDER_MAP.computeIfAbsent(provider, p -> { if (p instanceof IAnalysisModule) { ((IAnalysisModule) p).schedule(); } return new SegmentStoreTableDataProvider(trace, p); }); }

Target:
public static synchronized @Nullable SegmentStoreTableDataProvider getOrCreate(ITmfTrace trace, @Nullable ISegmentStoreProvider provider) { if (provider == null) { return null; } return PROVIDER_MAP.computeIfAbsent(provider, p -> { if (p instanceof IAnalysisModule) { ((IAnalysisModule) p).schedule(); } return new SegmentStoreTableDataProvider(trace, p, ID); }); }
Source:
public void done(CarbonMessage carbonMessage) { if (carbonMessage.getProperty(JMSConstants.JMS_MESSAGE_DELIVERY_STATUS).toString() .equalsIgnoreCase(JMSConstants.JMS_MESSAGE_DELIVERY_SUCCESS)) { try { message.acknowledge(); } catch (JMSException e) { logger.error("Error while acknowledging the message. " + e.getMessage(), e); throw new RuntimeException("Error while acknowledging the message. " + e.getMessage(), e); } } else { try { session.recover(); } catch (JMSException e) { logger.error("Error while recovering the session. " + e.getMessage(), e); throw new RuntimeException("Error while recovering the session. " + e.getMessage(), e); } } }

Target:
public void done(CarbonMessage carbonMessage) { if (carbonMessage.getProperty(JMSConstants.JMS_MESSAGE_DELIVERY_STATUS).toString() .equalsIgnoreCase(JMSConstants.JMS_MESSAGE_DELIVERY_SUCCESS)) { try { message.acknowledge(); } catch (JMSException e) { throw new RuntimeException("Error while acknowledging the message. ", e); } } else { try { session.recover(); } catch (JMSException e) { throw new RuntimeException("Error while recovering the session. ", e); } } }
Source:
private static Map<String, List<JsonNode>> removeDuplicates( Map<String, List<JsonNode>> subClasses) { List<String> ids = new ArrayList<>(subClasses.keySet()); Collections.sort(ids, Comparator.comparingInt(s -> Integer .parseInt(s.substring("<LINK_0>".length())))); for (int i = 0; i < ids.size(); i++) { String key = ids.get(i); final int j = i + 1; subClasses.put(key, subClasses.get(key).stream() .filter(unique(subClasses, ids, j)).collect(Collectors.toList())); } return subClasses; }

Target:
private static Map<String, List<JsonNode>> removeDuplicates( Map<String, List<JsonNode>> subClasses) { List<String> ids = new ArrayList<>(subClasses.keySet()); Collections.sort(ids, Comparator.comparingInt( s -> Integer.parseInt(s.substring((NWBIB_SPATIAL + "Q").length())))); for (int i = 0; i < ids.size(); i++) { String key = ids.get(i); final int j = i + 1; subClasses.put(key, subClasses.get(key).stream() .filter(unique(subClasses, ids, j)).collect(Collectors.toList())); } return subClasses; }
Source:
public CompletionStage<PreparedStatement> process( PrepareRequest request, DefaultSession session, InternalDriverContext context, String sessionLogPrefix) { try { return cache.get( request, () -> new CqlPrepareHandler(request, session, context, sessionLogPrefix).handle()); } catch (ExecutionException e) { return CompletableFutures.failedFuture(e.getCause()); } }

Target:
public CompletionStage<PreparedStatement> process( PrepareRequest request, DefaultSession session, InternalDriverContext context, String sessionLogPrefix) { try { CompletableFuture<PreparedStatement> result = cache.getIfPresent(request); if (result == null) { CompletableFuture<PreparedStatement> mine = new CompletableFuture<>(); result = cache.get(request, () -> mine); if (result == mine) { new CqlPrepareHandler(request, session, context, sessionLogPrefix) .handle() .whenComplete( (preparedStatement, error) -> { if (error != null) { mine.completeExceptionally(error); cache.invalidate(request); } else { mine.complete(preparedStatement); } }); } } return result; } catch (ExecutionException e) { return CompletableFutures.failedFuture(e.getCause()); } }
Source:
public MiniSet(T... entries) { if (entries.length == 0) { } else if (entries.length == 1) { holder = entries[0]; if (holder == null) throw new IllegalArgumentException(); type = Type.SINGLE; } else if (entries.length < ARRAY_SIZE) { Object[] array = new Object[ARRAY_SIZE]; for (int i = 0; i < ARRAY_SIZE; ++i) { if (i > entries.length) break; if (entries[i] == null) throw new IllegalArgumentException(); array[i] = entries[i]; } holder = array; type = Type.ARRAY; } else { Map<T, Object> map = new HashMap<>(); for (T entry : entries) { if (entry == null) throw new IllegalArgumentException(); map.put(entry, DUMMY); } holder = map; type = Type.MAP; } }

Target:
public MiniSet(T... entries) { if (entries.length == 0) { type = Type.EMPTY; } else if (entries.length == 1) { holder = entries[0]; if (holder == null) throw new IllegalArgumentException(); type = Type.SINGLE; } else if (entries.length < ARRAY_SIZE) { holder = new Object[ARRAY_SIZE]; type = Type.ARRAY; for (T entry : entries) { add(entry); } } else { Map<T, Object> map = new HashMap<>(); for (T entry : entries) { if (entry == null) throw new IllegalArgumentException(); map.put(entry, DUMMY); } holder = map; type = Type.MAP; } }
Source:
public ByteBuffer toByteBuffer(){ ByteBuffer byteBuffer = ByteBuffer.allocate(44+210+1); byteBuffer.position(1); byteBuffer.put((byte) 0); byteBuffer.put((byte) 0); byteBuffer.put((byte) 0); byteBuffer.putShort((short)0); try{ byte[] byteSequence = sequence.getBytes("ASCII"); byteBuffer.put((byte)(byteSequence.length)); } catch(UnsupportedEncodingException e){ } byteBuffer.put((byte)frequency); byte modeFlags = 0; if(startBit) modeFlags = (byte) (modeFlags | 1); if(repeatStartBit) modeFlags = (byte) (modeFlags | 2); if(rc5) modeFlags = (byte)(modeFlags | 4); if(rc6) modeFlags = (byte)(modeFlags | 8); byteBuffer.put(modeFlags); for(int i=0;i<pulsePairs.size();i++){ byteBuffer.putShort((short)Math.round(pulsePairs.get(i).Pause/8)); } for(int i=pulsePairs.size();i<=7;i++){ byteBuffer.putShort((short)0); } for(int i=0;i<pulsePairs.size();i++){ byteBuffer.putShort((short)Math.round(pulsePairs.get(i).Pulse/8)); } for(int i=pulsePairs.size();i<=7;i++){ byteBuffer.putShort((short)0); } byteBuffer.put((byte)pulsePairs.size()); byte repeat = (byte)0; repeat=(byte)numberOfRepeats; if(frameLength >0) { repeat = (byte) (repeat | 128); } byteBuffer.put(repeat); if((repeat & 128)==128) { byteBuffer.put((byte)frameLength); } else { byteBuffer.put((byte)pause); } try { byteBuffer.put(sequence.getBytes("ASCII")); } catch(UnsupportedEncodingException e) { } byteBuffer.put((byte)((char)13)); byteBuffer.flip(); byteBuffer.position(0); byteBuffer.put((byte)(byteBuffer.limit()-1)); byteBuffer.position(0); return byteBuffer; }

Target:
public ByteBuffer toByteBuffer(){ ByteBuffer byteBuffer = ByteBuffer.allocate(44+210+1); byteBuffer.position(1); byteBuffer.put((byte) 0); byteBuffer.put((byte) 0); byteBuffer.put((byte) 0); byteBuffer.putShort((short)0); try{ byte[] byteSequence = sequence.getBytes("ASCII"); byteBuffer.put((byte)(byteSequence.length)); } catch(UnsupportedEncodingException e){ logger.debug("An exception occurred while encoding a bytebuffer"); } byteBuffer.put((byte)frequency); byte modeFlags = 0; if(startBit) modeFlags = (byte) (modeFlags | 1); if(repeatStartBit) modeFlags = (byte) (modeFlags | 2); if(rc5) modeFlags = (byte)(modeFlags | 4); if(rc6) modeFlags = (byte)(modeFlags | 8); byteBuffer.put(modeFlags); for(int i=0;i<pulsePairs.size();i++){ byteBuffer.putShort((short)Math.round(pulsePairs.get(i).Pause/8)); } for(int i=pulsePairs.size();i<=7;i++){ byteBuffer.putShort((short)0); } for(int i=0;i<pulsePairs.size();i++){ byteBuffer.putShort((short)Math.round(pulsePairs.get(i).Pulse/8)); } for(int i=pulsePairs.size();i<=7;i++){ byteBuffer.putShort((short)0); } byteBuffer.put((byte)pulsePairs.size()); byte repeat = (byte)0; repeat=(byte)numberOfRepeats; if(frameLength >0) { repeat = (byte) (repeat | 128); } byteBuffer.put(repeat); if((repeat & 128)==128) { byteBuffer.put((byte)frameLength); } else { byteBuffer.put((byte)pause); } try { byteBuffer.put(sequence.getBytes("ASCII")); } catch(UnsupportedEncodingException e) { } byteBuffer.put((byte)((char)13)); byteBuffer.flip(); byteBuffer.position(0); byteBuffer.put((byte)(byteBuffer.limit()-1)); byteBuffer.position(0); return byteBuffer; }
Source:
public static void startOrRestartServer(final IServer liveReloadServer, final int timeout, final TimeUnit unit) throws TimeoutException, InterruptedException, ExecutionException { Future<?> future = Executors.newSingleThreadExecutor().submit(new Runnable() { @Override public void run() { try { if (liveReloadServer.getServerState() == IServer.STATE_STARTED && liveReloadServer.getServerRestartState()) { Logger.info("Restarting the server {}", liveReloadServer.getName()); liveReloadServer.restart(ILaunchManager.RUN_MODE, new NullProgressMonitor()); } else if (liveReloadServer.getServerState() == IServer.STATE_STOPPED) { Logger.info("Starting the server {}", liveReloadServer.getName()); liveReloadServer.start(ILaunchManager.RUN_MODE, new NullProgressMonitor()); } while (liveReloadServer.getServerState() != IServer.STATE_STARTED) { Thread.sleep(500); } } catch (Exception e) { Logger.error("Failed (re)start Livereload Server", e); } } }); future.get(timeout, unit); }

Target:
public static void startOrRestartServer(final IServer liveReloadServer, final int timeout, final TimeUnit unit) throws TimeoutException, InterruptedException, ExecutionException { Future<?> future = Executors.newSingleThreadExecutor().submit(new Runnable() { @Override public void run() { try { final Long limitTime = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(timeout, unit); if (liveReloadServer.getServerState() == IServer.STATE_STARTED && liveReloadServer.getServerRestartState()) { Logger.info("Restarting the server {}", liveReloadServer.getName()); liveReloadServer.restart(ILaunchManager.RUN_MODE, new NullProgressMonitor()); } else if (liveReloadServer.getServerState() == IServer.STATE_STOPPED) { Logger.info("Starting the server {}", liveReloadServer.getName()); liveReloadServer.start(ILaunchManager.RUN_MODE, new NullProgressMonitor()); } while (liveReloadServer.getServerState() != IServer.STATE_STARTED && System.currentTimeMillis() < limitTime) { TimeUnit.MILLISECONDS.sleep(500); } } catch (Exception e) { Logger.error("Failed (re)start Livereload Server", e); } } }); future.get(timeout, unit); }
Source:
private boolean impl$addNewOfferToTempMap(MerchantOffers merchantOffers, MerchantOffer offer) { if ((Object) this instanceof VillagerEntity) { return this.impl$newOffers.add(offer); } return merchantOffers.add(offer); }

Target:
protected boolean impl$addNewOfferToTempMap(MerchantOffers merchantOffers, MerchantOffer offer) { return merchantOffers.add(offer); }
Source:
protected List<DiskImage> getSnappableVmDisks() { if (!getParameters().getDiskIdsToIgnoreInChecks().isEmpty()) { return Collections.EMPTY_LIST; } List<Disk> disks = getDiskDao().getAllForVm(getVm().getId()); return ImagesHandler.filterImageDisks(disks, false, true, false); }

Target:
protected List<DiskImage> getSnappableVmDisks() { if (!getParameters().getDiskIdsToIgnoreInChecks().isEmpty()) { return Collections.emptyList(); } List<Disk> disks = getDiskDao().getAllForVm(getVm().getId()); return ImagesHandler.filterImageDisks(disks, false, true, false); }
Source:
public TrackingToken fetchToken(String processorName, int segment) throws UnableToClaimTokenException { RedisTokenEntry redisTokenEntry = redisTokenRepository.fetchTokenEntry(processorName, segment, nodeId, clock.instant(), clock.instant().minus(claimTimeout)); if(redisTokenEntry != null) { return redisTokenEntry.getToken(serializer); } else { throw new UnableToClaimTokenException("Unable to claim token."); } }

Target:
public TrackingToken fetchToken(String processorName, int segment) throws UnableToClaimTokenException { RedisTokenEntry redisTokenEntry = redisTokenRepository.fetchTokenEntry(processorName, segment, nodeId, clock.instant(), clock.instant().minus(claimTimeout)); if(redisTokenEntry != null) { if(!nodeId.equals(redisTokenEntry.getOwner())) { throw new UnableToClaimTokenException( format("Unable to claim token '%s[%s]'. It is owned by '%s'", processorName, segment, redisTokenEntry.getOwner())); } return redisTokenEntry.getToken(serializer); } else { throw new UnableToClaimTokenException(format("Unable to claim token '%s[%s]'.", processorName, segment)); } }
Source:
private List<ProducerBatch> getChildrenProducerBatch() { if (childrenProducerBatch == null) { return Collections.emptyList(); } return childrenProducerBatch; }

Target:
private synchronized List<ProducerBatch> getChildrenProducerBatch() { if (childrenProducerBatch == null) { return Collections.emptyList(); } return childrenProducerBatch; }
Source:
protected PreparedStatement getPreparedStatement(String query) throws SQLException { return (connection.prepareStatement(query)); }

Target:
protected PreparedStatement getPreparedStatement(String query) throws SQLException { return connection.prepareStatement(query); }
Source:
public static Map<String, Object> readAttributesForPreservation(Path path) throws IOException { Map<String, Object> attrs = new HashMap<>(); if (Files.exists(path)) { Set<String> supportedViews = path.getFileSystem().supportedFileAttributeViews(); if (supportedViews.contains("posix")) { attrs.putAll(Files.readAttributes(path, "posix:permissions") .entrySet().stream().collect(Collectors.toMap(e -> "posix:" + e.getKey(), e -> e.getValue()))); } if (supportedViews.contains("dos")) { attrs.putAll(Files.readAttributes(path, "dos:readonly,hidden,archive,system") .entrySet().stream().collect(Collectors.toMap(e -> "dos:" + e.getKey(), e -> e.getValue()))); } if (supportedViews.contains("acl")) { attrs.putAll(Files.readAttributes(path, "acl:acl") .entrySet().stream().collect(Collectors.toMap(e -> "acl:" + e.getKey(), e -> e.getValue()))); } } return attrs; }

Target:
public static Map<String, Object> readAttributesForPreservation(Path path) throws IOException { Map<String, Object> attrs = new HashMap<>(); if (Files.exists(path)) { Set<String> supportedViews = path.getFileSystem().supportedFileAttributeViews(); if (supportedViews.contains("posix")) { readAttributesForView(path, "posix:", "posix:permissions", attrs); } if (supportedViews.contains("dos")) { readAttributesForView(path, "dos:", "dos:readonly,hidden,archive,system", attrs); } if (supportedViews.contains("acl")) { readAttributesForView(path, "acl:", "acl:acl", attrs); } } return attrs; }
Source:
public Work<?> addPage(Page page) { Work<?> work = hash.addPage(page); return work; }

Target:
public Work<?> addPage(Page page) { return hash.addPage(page); }
Source:
public static String fromBase64(String base64) { if (base64 == null) { return null; } try { base64 = base64.replaceAll("[\\t\\n\\r ]", ""); return new String(Base64.getDecoder().decode(base64.getBytes(UTF_8)), UTF_8); } catch (IllegalArgumentException e) { return null; } }

Target:
public static ByteString fromBase64(String base64) { try { base64 = FROM_BASE64_REGEXP.matcher(base64).replaceAll(""); return new ByteString(Base64.getDecoder().decode(base64)); } catch (IllegalArgumentException e) { return null; } }
Source:
public String getServiceUrl() throws MalformedURLException { String context = getContext(); if ("HIVE".equals(getServiceName())) { return String.format(Locale.ROOT, "jdbc:hive2://%s:%d/;?hive.server2.transport.mode=http;hive.server2.thrift.http.path=/%s/%s%s", request.getServerName(), request.getServerPort(), gatewayPath, topologyName, context); } else { final String backendUrlString = getBackendServiceUrl(); if (context.indexOf("{{BACKEND_HOST}}") > -1) { context = context.replace("{{BACKEND_HOST}}", backendUrlString); } if (context.indexOf("{{SCHEME}}") > -1 || context.indexOf("{{HOST}}") > -1 || context.indexOf("{{PORT}}") > -1) { final URL backendUrl = new URL(backendUrlString); if (context.indexOf("{{SCHEME}}") > -1) { context = context.replace("{{SCHEME}}", backendUrl.getProtocol()); } if (context.indexOf("{{HOST}}") > -1) { context = context.replace("{{HOST}}", backendUrl.getHost()); } if (context.indexOf("{{PORT}}") > -1) { context = context.replace("{{PORT}}", String.valueOf(backendUrl.getPort())); } } return String.format(Locale.ROOT, "%s://%s:%s/%s/%s%s", request.getScheme(), request.getServerName(), request.getServerPort(), gatewayPath, topologyName, context); } }

Target:
public String getServiceUrl() throws MalformedURLException { String context = getContext(); if ("HIVE".equals(getServiceName())) { return String.format(Locale.ROOT, "jdbc:hive2://%s:%d/;?hive.server2.transport.mode=http;hive.server2.thrift.http.path=/%s/%s%s", request.getServerName(), request.getServerPort(), gatewayPath, topologyName, context); } else { final String backendUrlString = getBackendServiceUrl(); if (context.indexOf("{{BACKEND_HOST}}") > -1) { context = context.replace("{{BACKEND_HOST}}", backendUrlString); } if (context.indexOf("{{SCHEME}}") > -1 || context.indexOf("{{HOST}}") > -1 || context.indexOf("{{PORT}}") > -1) { final URL backendUrl = new URL(backendUrlString); context = context.replace("{{SCHEME}}", backendUrl.getProtocol()); context = context.replace("{{HOST}}", backendUrl.getHost()); context = context.replace("{{PORT}}", String.valueOf(backendUrl.getPort())); } return String.format(Locale.ROOT, "%s://%s:%s/%s/%s%s", request.getScheme(), request.getServerName(), request.getServerPort(), gatewayPath, topologyName, context); } }
Source:
private Text decode(final String text, final boolean decode) { if (text.isBlank()) return null; return decode ? new Text(Base64.getDecoder().decode(text)) : new Text(text); }

Target:
private Text decode(final String text, final boolean decode) { if (requireNonNull(text).isBlank()) return null; return decode ? new Text(Base64.getDecoder().decode(text)) : new Text(text); }
Source:
public String getDisplayName() { return this.name; }

Target:
public String getDisplayName() { return getName(); }
Source:
private void clearBitmap(){ if(mSignatureBitmapCanvas != null){ mSignatureBitmapCanvas.setBitmap(null); mSignatureBitmapCanvas = null; } if(mSignatureBitmap != null){ if(!mSignatureBitmap.isRecycled()) { mSignatureBitmap.recycle(); } mSignatureBitmap = null; } System.gc(); }

Target:
public void clearBitmap(){ if(mSignatureBitmapCanvas != null){ mSignatureBitmapCanvas.setBitmap(null); mSignatureBitmapCanvas = null; } if(mSignatureBitmap != null){ if(!mSignatureBitmap.isRecycled()) { mSignatureBitmap.recycle(); } mSignatureBitmap = null; } System.gc(); }
Source:
public static void setUp() throws Exception { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); final Github github = new RtGithub(key); repos = github.repos(); repo = repos.create( new Repos.NewRepoSettings( RandomStringUtils.randomAlphanumeric(Tv.TEN), false ).withAutoInit(true) ); }

Target:
public static void setUp() throws Exception { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); final Github github = new RtGithub(key); repos = github.repos(); repo = repos.create( new Repos.RepoCreate( RandomStringUtils.randomAlphanumeric(Tv.TEN), false ).withAutoInit(true) ); }
Source:
public void setTriggerConfigURL(String triggerConfigURL) { if (triggerConfigURL == null) { if (this.triggerConfigURL != null) { this.dynamicConfigurationChangedFromLastStart = true; } } else { if (!triggerConfigURL.equals(this.triggerConfigURL)) { this.dynamicConfigurationChangedFromLastStart = true; } else { this.dynamicConfigurationChangedFromLastStart = false; } } this.triggerConfigURL = triggerConfigURL; }

Target:
public void setTriggerConfigURL(String triggerConfigURL) { this.triggerConfigURL = triggerConfigURL; }
Source:
public static Optional<HiveBucketProperty> getBucketProperty(Map<String, Object> tableProperties) { List<String> bucketedBy = getBucketedBy(tableProperties); List<HiveSortOrder> sortedBy = getSortedBy(tableProperties); int bucketCount = (Integer) tableProperties.get(BUCKET_COUNT_PROPERTY); if ((bucketedBy.isEmpty()) && (bucketCount == 0)) { if (!sortedBy.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s could be specified only when %s is specified", SORTED_BY_PROPERTY, BUCKETED_BY_PROPERTY)); } return Optional.empty(); } if (bucketCount < 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s must be greater than zero", BUCKET_COUNT_PROPERTY)); } if (bucketedBy.isEmpty() || bucketCount == 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s and %s must be specified together", BUCKETED_BY_PROPERTY, BUCKET_COUNT_PROPERTY)); } return Optional.of(new HiveBucketProperty(bucketedBy, bucketCount, sortedBy)); }

Target:
public static Optional<HiveBucketProperty> getBucketProperty(Map<String, Object> tableProperties) { List<String> bucketedBy = getBucketedBy(tableProperties); List<HiveSortOrder> sortedBy = getSortedBy(tableProperties); int bucketCount = (Integer) tableProperties.get(BUCKET_COUNT_PROPERTY); if ((bucketedBy.isEmpty()) && (bucketCount == 0)) { if (!sortedBy.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s may be specified only when %s is specified", SORTED_BY_PROPERTY, BUCKETED_BY_PROPERTY)); } return Optional.empty(); } if (bucketCount < 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s must be greater than zero", BUCKET_COUNT_PROPERTY)); } if (bucketedBy.isEmpty() || bucketCount == 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s and %s must be specified together", BUCKETED_BY_PROPERTY, BUCKET_COUNT_PROPERTY)); } return Optional.of(new HiveBucketProperty(bucketedBy, bucketCount, sortedBy)); }
Source:
public boolean supports(String feature) { if (properties.containsKey(feature)) { return Boolean.parseBoolean(get(feature).trim()); } return false; }

Target:
public boolean supports(String feature) { if (has(feature)) { return Boolean.parseBoolean(get(feature).trim()); } return false; }
Source:
private Optional<CeTask> tryAndFindTaskToExecute() { try { return queue.peek("uuid" + counter.addAndGet(100)); } catch (Exception e) { LOG.error("Failed to pop the queue of analysis reports", e); } return Optional.empty(); }

Target:
private Optional<CeTask> tryAndFindTaskToExecute() { try { return queue.peek(uuid); } catch (Exception e) { LOG.error("Failed to pop the queue of analysis reports", e); } return Optional.empty(); }
Source:
private NumericNode getMetric(String query, String ... params) { NumericNode retVal = new IntNode(0); query = String.format(query, params); if (promUrl == null) { return retVal; } CloseableHttpResponse response = request(query); if (response == null) { return retVal; } if (response.getStatusLine().getStatusCode() >= 300) { String body; try { body = EntityUtils.toString(response.getEntity()); log.warn("Failed to fetch metric {}: {}", query, body); } catch (ParseException | IOException e) { log.warn("Failed to parse failed fetch metric for {}", query); } return retVal; } try { JsonNode node = mapper.readTree(EntityUtils.toByteArray(response.getEntity())); if (node.has("status")) { if (node.get("status").asText().equals("success")) { JsonNode result = node.get("data").get("result"); if (result.size() > 0) { JsonNode value = result.get(0).get("value"); return new DoubleNode(Double.parseDouble(value.get(1).asText())); } } else { log.warn("Query '{}' failed to execute: - {}", query, node.get("status"), node.get("error")); } } } catch (JsonProcessingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return retVal; }

Target:
private NumericNode getMetric(String query, String ... params) { NumericNode retVal = new IntNode(0); query = String.format(query, params); if (promUrl == null) { return retVal; } try (CloseableHttpResponse response = request(query)) { if (response == null) { return retVal; } if (response.getStatusLine().getStatusCode() >= 300) { String body; try { body = EntityUtils.toString(response.getEntity()); log.warn("Failed to fetch metric {}: {}", query, body); } catch (ParseException | IOException e) { log.warn("Failed to parse failed fetch metric for {}", query); } return retVal; } try { JsonNode node = mapper.readTree(EntityUtils.toByteArray(response.getEntity())); if (node.has("status")) { if (node.get("status").asText().equals("success")) { JsonNode result = node.get("data").get("result"); if (result.size() > 0) { JsonNode value = result.get(0).get("value"); return new DoubleNode(Double.parseDouble(value.get(1).asText())); } } else { log.warn("Query '{}' failed to execute: - {}", query, node.get("status"), node.get("error")); } } } catch (JsonProcessingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } catch (IOException e) { throw new RuntimeException(e); } return retVal; }
Source:
void authorizeRoleInTree(String roleName, String resourceId, String action, boolean updateCache ) throws UserStoreException { write.lock(); try { SearchResult sr = getNode(root, PermissionTreeUtil.toComponenets(resourceId)); if (sr.getUnprocessedPaths() != null) { List<String> paths = sr.getUnprocessedPaths(); TreeNode tn = sr.getLastNode().create(paths); tn.authorizeRole(roleName, PermissionTreeUtil.actionToPermission(action)); } else { sr.getLastNode().authorizeRole(roleName, PermissionTreeUtil.actionToPermission(action)); } if (updateCache) { invalidateCache(root); } } catch (Exception e) { throw new UserStoreException(e.getMessage(),e); } finally { write.unlock(); } }

Target:
void authorizeRoleInTree(String roleName, String resourceId, String action, boolean updateCache ) throws UserStoreException { write.lock(); try { SearchResult sr = getNode(root, PermissionTreeUtil.toComponenets(resourceId)); if (sr.getUnprocessedPaths() != null) { List<String> paths = sr.getUnprocessedPaths(); TreeNode tn = sr.getLastNode().create(paths); tn.authorizeRole(roleName, PermissionTreeUtil.actionToPermission(action)); } else { sr.getLastNode().authorizeRole(roleName, PermissionTreeUtil.actionToPermission(action)); } if (updateCache) { invalidateCache(root); } } catch (IllegalArgumentException e) { throw new UserStoreException("Error while authorizing role: " + roleName + "in permission tree for resource id: " + resourceId + "for action: " + action, e); } finally { write.unlock(); } }
Source:
public List<String> getExpectedInitialColumns() { List<String> initColumns = new ArrayList<String>(); initColumns.add(COL_ID_PROCESSNAME); initColumns.add(COL_ID_PROCESSVERSION); initColumns.add(COL_ID_PROJECT); initColumns.add("Actions"); return initColumns; }

Target:
public List<String> getExpectedInitialColumns() { List<String> initColumns = new ArrayList<String>(); initColumns.add(COL_ID_PROCESSNAME); initColumns.add(COL_ID_PROCESSVERSION); initColumns.add(COL_ID_PROJECT); initColumns.add(COL_ID_ACTIONS); return initColumns; }
Source:
static <T> Task<T> withSideEffect(final Callable<Task<T>> func) { return Task.withSideEffect("sideEffect", func); }

Target:
static <T> Task<Void> withSideEffect(final Callable<Task<T>> func) { return Task.withSideEffect("withSideEffect", func); }
Source:
public void compare() { setUpWithJson(SAMPLE_JSON); List<Element> elements = Arrays.stream(getFeatureByName("Second feature").getElements()) .filter(Element::isScenario) .collect(Collectors.toList()); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isEqualTo(elements.get(0)); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isNotEqualTo(elements.get(1)); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isNotEqualTo(null); }

Target:
public void compare() { setUpWithJson(SAMPLE_JSON); List<Element> elements = Arrays.stream(getFeatureByName("Second feature").getElements()) .filter(Element::isScenario) .collect(Collectors.toList()); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isEqualTo(elements.get(0)); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isNotEqualTo(elements.get(1)); assertThat(elements.get(0)).usingComparator(new ElementComparator()).isNotNull(); }
Source:
public void deserializeTest() throws IOException { final DefaultObjectMapper mapper = new DefaultObjectMapper(); final ResponseContext ctx = ResponseContext.deserialize( mapper.writeValueAsString(ImmutableMap.of("ETag", "string-value", "count", 100)), mapper ); Assert.assertEquals("string-value", ctx.get(ResponseContext.Key.ETAG)); Assert.assertEquals(100, ctx.get(ResponseContext.Key.NUM_SCANNED_ROWS)); ctx.add(ResponseContext.Key.NUM_SCANNED_ROWS, 10L); Assert.assertEquals(110L, ctx.get(ResponseContext.Key.NUM_SCANNED_ROWS)); }

Target:
public void deserializeTest() throws IOException { final DefaultObjectMapper mapper = new DefaultObjectMapper(); final ResponseContext ctx = ResponseContext.deserialize( mapper.writeValueAsString( ImmutableMap.of( "ETag", "string-value", "count", 100L, "cpuConsumed", 100000L ) ), mapper ); Assert.assertEquals("string-value", ctx.get(ResponseContext.Key.ETAG)); Assert.assertEquals(100, ctx.get(ResponseContext.Key.NUM_SCANNED_ROWS)); Assert.assertEquals(100000, ctx.get(ResponseContext.Key.CPU_CONSUMED_NANOS)); ctx.add(ResponseContext.Key.NUM_SCANNED_ROWS, 10L); Assert.assertEquals(110L, ctx.get(ResponseContext.Key.NUM_SCANNED_ROWS)); ctx.add(ResponseContext.Key.CPU_CONSUMED_NANOS, 100); Assert.assertEquals(100100L, ctx.get(ResponseContext.Key.CPU_CONSUMED_NANOS)); }
Source:
public static State forValue( @NotNull(message = "ident is never NULL") final String ident ) { for (final State state : State.values()) { if (state.identifier().equalsIgnoreCase(ident)) { return state; } } throw new IllegalArgumentException( String.format("No enum value found for %s", ident) ); }

Target:
public static State forValue( @NotNull(message = "ident is never NULL") final String ident ) { return State.valueOf(ident.toUpperCase(Locale.ENGLISH)); }
Source:
private void announceIfEnabled(MetricAttribute metricAttribute, String metricName, String group, double value, String units) throws GangliaException { if (isMetricAttributeDisabled(metricAttribute)) { return; } final String string = Math.abs(value) < MIN_VAL ? "0" : Double.toString(value); announce(prefix(metricName, metricAttribute.getCode()), group, string, GMetricType.DOUBLE, units); }

Target:
private void announceIfEnabled(MetricAttribute metricAttribute, String metricName, String group, double value, String units) throws GangliaException { if (getDisabledMetricAttributes().contains(metricAttribute)) { return; } final String string = Math.abs(value) < MIN_VAL ? "0" : Double.toString(value); announce(prefix(metricName, metricAttribute.getCode()), group, string, GMetricType.DOUBLE, units); }
Source:
public void run() { if (file == null) return; String path = file.getFullPath().toOSString(); try { final URI uri = URI.createPlatformResourceURI(path, true); if (shouldBeAbleToLoad()) { res = set.getResource(uri, true); if (!res.getErrors().isEmpty()) { unload(); } res.load(getOptions()); } } catch (final WrappedException e) { error(path, e); } catch (final RuntimeException e) { error(path, e); } catch (final IOException e) { error(path, e); } }

Target:
public void run() { String path = file.getFullPath().toOSString(); try { final URI uri = URI.createPlatformResourceURI(path, true); if (shouldBeAbleToLoad()) { res = set.getResource(uri, true); if (!res.getErrors().isEmpty()) { unload(); } res.load(getOptions()); } } catch (final RuntimeException e) { error(path, e); } catch (final IOException e) { error(path, e); } }