auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public final ProcStatCoreLoads computeLoads(final ProcStatCounters old) { ProcStatCoreLoads loads = new ProcStatCoreLoads(); float load; int diffIdle; int diffActive; OneCoreTickCounters coreCountersOld; OneCoreTickCounters coreCountersNew; for(String coreId: fTickCounters.keySet()) { coreCountersNew = fTickCounters.get(coreId); if (old != null) { coreCountersOld = old.fTickCounters.get(coreId); diffIdle = coreCountersNew.getIdleTicks() - coreCountersOld.getIdleTicks(); diffActive = coreCountersNew.getActiveTicks() - coreCountersOld.getActiveTicks(); load = diffActive / (float)(diffActive + diffIdle); loads.put(coreId, load * 100.0f); } else { diffIdle = coreCountersNew.getIdleTicks(); diffActive = coreCountersNew.getActiveTicks(); load = diffActive / (float)(diffActive + diffIdle); loads.put(coreId, load * 100.0f); } } return loads; }

Target:
public final ProcStatCoreLoads computeLoads(final ProcStatCounters old) { ProcStatCoreLoads loads = new ProcStatCoreLoads(); for(String coreId: fTickCounters.keySet()) { OneCoreTickCounters coreCountersNew = fTickCounters.get(coreId); if (old != null) { OneCoreTickCounters coreCountersOld = old.fTickCounters.get(coreId); int diffIdle = coreCountersNew.getIdleTicks() - coreCountersOld.getIdleTicks(); int diffActive = coreCountersNew.getActiveTicks() - coreCountersOld.getActiveTicks(); float load; if (diffIdle + diffActive != 0) { load = diffActive / (float)(diffActive + diffIdle); } else { load = 0; } loads.put(coreId, load * 100.0f); } else { int diffIdle = coreCountersNew.getIdleTicks(); int diffActive = coreCountersNew.getActiveTicks(); assert (diffActive + diffIdle != 0); float load = diffActive / (float)(diffActive + diffIdle); loads.put(coreId, load * 100.0f); } } return loads; }
Source:
private void doQueryCursorSpliteratorCalls(Query<?> qry) { Ignite client = grid(0); IgniteCache<Object, String> cache = client.getOrCreateCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME)); try (QueryCursor<?> cur = cache.query(qry)) { cur.iterator(); cur.spliterator(); GridTestUtils.assertThrows(log, IgniteException.class, "Iterator is already fetched or query was cancelled.", cur, "iterator"); } }

Target:
private void doQueryCursorSpliteratorCalls(Query<?> qry) { Ignite client = grid(0); IgniteCache<Object, String> cache = client.getOrCreateCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME)); Set<Object> iterData = new HashSet<>(); Set<Object> spliterData = new HashSet<>(); try (QueryCursor<?> cur = cache.query(qry)) { Iterator<Object> iter = (Iterator<Object>)cur.iterator(); while (iter.hasNext()) iterData.add(iter.next()); assertEquals(iterData.size(), 3); Spliterator<Object> spliter = (Spliterator<Object>)cur.spliterator(); assertEquals(spliter.getExactSizeIfKnown(), -1); GridTestUtils.assertThrows(log, IgniteException.class, "Iterator is already fetched or query was cancelled.", cur, "iterator"); } try (QueryCursor<?> cur = cache.query(qry)) { Spliterator<Object> spliter = (Spliterator<Object>)cur.spliterator(); assertEquals(spliter.getExactSizeIfKnown(), -1); spliter.forEachRemaining(spliterData::add); assertEquals(spliterData.size(), 3); Iterator<Object> iter = (Iterator<Object>)cur.iterator(); assertFalse((qry instanceof ScanQuery) && iter.hasNext()); GridTestUtils.assertThrows(log, IgniteException.class, "Iterator is already fetched or query was cancelled.", cur, "iterator"); } assertEquals(iterData.size(), spliterData.size()); }
Source:
public static Kind fromValue(final String value) { for (Kind kind : Kind.values()) { if (kind.value.equals(value)) { return kind; } } throw new IllegalArgumentException(value); }

Target:
public static Kind fromValue(final String value) { for (Kind kind : Kind.values()) { if (Objects.equals(kind.value, value)) { return kind; } } throw new IllegalArgumentException("FunctionKind [" + value + "] is not supported."); }
Source:
public GlusterVolumeEntity() { options = new LinkedHashMap<String, GlusterVolumeOptionEntity>(); bricks = new ArrayList<GlusterBrickEntity>(); status = GlusterStatus.DOWN; accessProtocols = new LinkedHashSet<AccessProtocol>(Arrays.asList(new AccessProtocol[]{ AccessProtocol.GLUSTER, AccessProtocol.NFS})); transportTypes = new LinkedHashSet<TransportType>(); volumeType = GlusterVolumeType.DISTRIBUTE; asyncTask = new GlusterAsyncTask(); }

Target:
public GlusterVolumeEntity() { options = new LinkedHashMap<String, GlusterVolumeOptionEntity>(); bricks = new ArrayList<GlusterBrickEntity>(); status = GlusterStatus.DOWN; accessProtocols = new LinkedHashSet<AccessProtocol>(Arrays.asList(new AccessProtocol[]{ AccessProtocol.GLUSTER, AccessProtocol.NFS})); transportTypes = new LinkedHashSet<TransportType>(); volumeType = GlusterVolumeType.DISTRIBUTE; asyncTask = new GlusterAsyncTask(); advancedDetails = new GlusterVolumeAdvancedDetails(); }
Source:
protected void addView(TextAnnotation ta) throws AnnotatorException { Annotation document = new Annotation(ta.text); pipeline.annotate(document); SpanLabelView vu = new SpanLabelView(viewName, ta); String outputString = ""; for (CoreMap sentence : document.get(CoreAnnotations.SentencesAnnotation.class)) { for (CoreLabel token : sentence.get(CoreAnnotations.TokensAnnotation.class)) { String truecase = token.get(CoreAnnotations.TrueCaseTextAnnotation.class); outputString += " " + truecase; } } Constituent c = new Constituent(outputString, viewName, ta,0, ta.getTokens().length); vu.addConstituent(c); ta.addView(viewName, vu); }

Target:
protected void addView(TextAnnotation ta) throws AnnotatorException { Annotation document = new Annotation(ta.text); pipeline.annotate(document); TokenLabelView vu = new TokenLabelView(viewName, ta); for (CoreMap sentence : document.get(CoreAnnotations.SentencesAnnotation.class)) { for (CoreLabel token : sentence.get(CoreAnnotations.TokensAnnotation.class)) { String trueCase = token.get(CoreAnnotations.TrueCaseTextAnnotation.class); int beginCharOffsetS = token.beginPosition(); int endCharOffset = token.endPosition() - 1; List<Constituent> overlappingCons = ta.getView(ViewNames.TOKENS).getConstituentsOverlappingCharSpan(beginCharOffsetS, endCharOffset); int endIndex = overlappingCons.stream().max(Comparator.comparing(Constituent::getEndSpan)).get().getEndSpan(); Constituent c = new Constituent(trueCase, viewName, ta, endIndex - 1, endIndex); vu.addConstituent(c); } } ta.addView(viewName, vu); }
Source:
public int hashCode() { return this.deviceIdentification != null ? this.deviceIdentification.hashCode() : 0; }

Target:
public int hashCode() { return Objects.hashCode(this.deviceIdentification); }
Source:
protected void resolveLineTagLocations(String sourceName, String... tags) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(SOURCE_PATH + sourceName))) { Set<String> tagsToFind = new HashSet<>(Arrays.asList(tags)); Set<String> tagsFound = new HashSet<>(); String line; int lineNumber = 1; fTagLocations.clear(); line = reader.readLine(); while (line != null) { for (String tag : tagsToFind) { if (line.contains(tag)) { if (tagsFound.contains(tag)) { throw new RuntimeException("Tag " + tag + " was found twice in " + sourceName); } fTagLocations.put(tag, lineNumber); tagsFound.add(tag); break; } } lineNumber++; line = reader.readLine(); } if (tagsToFind.size() != tagsFound.size()) { throw new RuntimeException( "Some tags were not found in " + sourceName); } } }

Target:
protected void resolveLineTagLocations(String sourceName, String... tags) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(SOURCE_PATH + sourceName))) { Set<String> tagsToFind = new HashSet<>(Arrays.asList(tags)); String line; int lineNumber = 1; fTagLocations.clear(); line = reader.readLine(); while (line != null) { for (String tag : tagsToFind) { if (line.contains(tag)) { if (fTagLocations.containsKey(tag)) { throw new RuntimeException("Tag " + tag + " was found twice in " + sourceName); } fTagLocations.put(tag, lineNumber); tagsToFind.remove(tag); break; } } lineNumber++; line = reader.readLine(); } if (tagsToFind.size() > 0) { throw new RuntimeException( "Some tags were not found in " + sourceName); } } }
Source:
public ClusterDataToSamConverter withMolecularIndexQualityTag(final String molecularIndexQualityTag) { this.molecularIndexQualityTag = molecularIndexQualityTag; return this; }

Target:
public ClusterDataToSamConverter withMolecularIndexQualityTag(final String molecularIndexQualityTag) { if (molecularIndexQualityTag == null) throw new IllegalArgumentException("Molecular index quality tag was null"); this.molecularIndexQualityTag = molecularIndexQualityTag; return this; }
Source:
private static void addPublicationTypes(Result result, String... types) { for (String type : types) { Instance instance = new Instance(); Qualifier instanceType = new Qualifier(); instanceType.setClassid(type); instance.setInstancetype(instanceType); if (result.getInstance() == null) { result.setInstance(Lists.newArrayList()); } result.getInstance().add(instance); } }

Target:
private static void addPublicationTypes(Result result, String... types) { if (types.length > 0) { if (result.getInstance() == null) { result.setInstance(Lists.newArrayList()); } Arrays.asList(types).stream().map(type -> { Instance instance = new Instance(); Qualifier instanceType = new Qualifier(); instanceType.setClassid(type); instance.setInstancetype(instanceType); return instance; }).forEach(result.getInstance()::add); } }
Source:
private List<DiskImage> initializeListForCopiedImages() { List<DiskImage> clonedDiskImages = new ArrayList<>(getImages()); ArrayList<Guid> storageDomains = new ArrayList<>(); for (DiskImage clonedDiskImage : clonedDiskImages) { clonedDiskImage.setStorageIds(storageDomains); } return clonedDiskImages; }

Target:
private List<DiskImage> initializeListForCopiedImages() { List<DiskImage> clonedDiskImages = getClonedDiskImagesList(); ArrayList<Guid> storageDomains = new ArrayList<>(); for (DiskImage clonedDiskImage : clonedDiskImages) { clonedDiskImage.setStorageIds(storageDomains); } return clonedDiskImages; }
Source:
private void receiveAndReply() { byte[] value = null; try { value = this.boundListOperations.rightPop(this.receiveTimeout, TimeUnit.MILLISECONDS); } catch (Exception e) { handlePopException(e); return; } String uuid = null; if (value != null) { uuid = stringSerializer.deserialize(value); try { value = template.boundListOps(uuid).rightPop(this.receiveTimeout, TimeUnit.MILLISECONDS); } catch (Exception e) { handlePopException(e); return; } Object messageBody = null; if (value != null) { if (this.expectMessage) { if (this.serializer != null) { try { messageBody = this.serializer.deserialize(value); } catch (Exception e) { throw new MessagingException("Deserialization of Message failed.", e); } } else { messageBody = value; } } else { Object payload = value; if (this.serializer != null) { payload = this.serializer.deserialize(value); } messageBody = this.getMessageBuilderFactory().withPayload(payload).build(); } Message<?> replyMessage = this.sendAndReceiveMessage(messageBody); if (replyMessage != null) { if (!(replyMessage.getPayload() instanceof byte[])) { if (replyMessage.getPayload() instanceof String && !serializerExplicitlySet) { value = stringSerializer.serialize((String) replyMessage.getPayload()); } else { value = ((RedisSerializer<Object>) serializer).serialize(replyMessage.getPayload()); } } else { value = (byte[]) replyMessage.getPayload(); } template.boundListOps(uuid + ".reply").leftPush(value); } } } }

Target:
private void receiveAndReply() { byte[] value = null; try { value = this.boundListOperations.rightPop(this.receiveTimeout, TimeUnit.MILLISECONDS); } catch (Exception e) { handlePopException(e); return; } String uuid = null; if (value != null) { uuid = stringSerializer.deserialize(value); try { value = template.boundListOps(uuid).rightPop(this.receiveTimeout, TimeUnit.MILLISECONDS); } catch (Exception e) { handlePopException(e); return; } Message<Object> requestMessage = null; if (value != null) { if (this.extractPayload) { Object payload = value; if (this.serializer != null) { payload = this.serializer.deserialize(value); } requestMessage = this.getMessageBuilderFactory().withPayload(payload).build(); } else { try { requestMessage = (Message<Object>) this.serializer.deserialize(value); } catch (Exception e) { throw new MessagingException("Deserialization of Message failed.", e); } } Message<?> replyMessage = this.sendAndReceiveMessage(requestMessage); if (replyMessage != null) { if (this.extractPayload == true) { if (!(replyMessage.getPayload() instanceof byte[])) { if (replyMessage.getPayload() instanceof String && !serializerExplicitlySet) { value = stringSerializer.serialize((String) replyMessage.getPayload()); } else { value = ((RedisSerializer<Object>) serializer).serialize(replyMessage.getPayload()); } } else { value = (byte[]) replyMessage.getPayload(); } template.boundListOps(uuid + ".reply").leftPush(value); } else { if (this.serializer != null) { value = ((RedisSerializer<Object>) serializer).serialize(replyMessage); template.boundListOps(uuid + ".reply").leftPush(value); } } } } } }
Source:
public void dispose() { app.getChildren().remove(windowModel); coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); windowModel.setToBeRendered(false); ((Shell) windowModel.getWidget()).dispose(); }

Target:
public void dispose() { app.getChildren().remove(windowModel); coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); windowModel.setToBeRendered(false); windowModel.getContext().deactivate(); windowModel.getContext().dispose(); ((Shell) windowModel.getWidget()).dispose(); }
Source:
public TmfAttributePool(ITmfStateSystemBuilder ss, Integer baseQuark, QueueType type) { fSs = ss; try { ss.getParentAttributeQuark(baseQuark); fBaseQuark = baseQuark; } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("The quark used as base for the attribute pool is out of bounds"); } switch (type) { case DEFAULT: case FIFO: fAvailableQuarks = new LinkedList<>(); break; case PRIORITY: fAvailableQuarks = new PriorityQueue<>(); break; default: throw new IllegalArgumentException("Wrong queue type"); } }

Target:
public TmfAttributePool(ITmfStateSystemBuilder ss, Integer baseQuark, QueueType type) { fSs = ss; try { ss.getParentAttributeQuark(baseQuark); fBaseQuark = baseQuark; } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("The quark used as base for the attribute pool does not exist"); } switch (type) { case FIFO: fAvailableQuarks = new LinkedList<>(); break; case PRIORITY: fAvailableQuarks = new PriorityQueue<>(); break; default: throw new IllegalArgumentException("Wrong queue type"); } }
Source:
void setActive(boolean isActive) { CallbackToFutureAdapter.Completer<Void> completerToSetException = null; boolean toResetDefault = false; synchronized (mActiveLock) { mIsActive = isActive; if (!mIsActive) { synchronized (mCompleterLock) { if (mPendingZoomRatioCompleter != null) { completerToSetException = mPendingZoomRatioCompleter; mPendingZoomRatioCompleter = null; } } toResetDefault = true; } } if (toResetDefault) { setLiveDataValue(mZoomRatioLiveData, DEFAULT_ZOOM_RATIO); setLiveDataValue(mMaxZoomRatioLiveData, getMaxDigitalZoom()); setLiveDataValue(mMinZoomRatioLiveData, MIN_ZOOM); setLiveDataValue(mZoomPercentageLiveData, 0f); } if (completerToSetException != null) { completerToSetException .setException(new OperationCanceledException("Camera is not active.")); } }

Target:
void setActive(boolean isActive) { CallbackToFutureAdapter.Completer<Void> completerToSetException = null; boolean shouldResetDefault = false; synchronized (mActiveLock) { mIsActive = isActive; if (!mIsActive) { synchronized (mCompleterLock) { if (mPendingZoomRatioCompleter != null) { completerToSetException = mPendingZoomRatioCompleter; mPendingZoomRatioCompleter = null; } } shouldResetDefault = true; } } if (shouldResetDefault) { setLiveDataValue(mZoomRatioLiveData, DEFAULT_ZOOM_RATIO); setLiveDataValue(mMaxZoomRatioLiveData, getMaxDigitalZoom()); setLiveDataValue(mMinZoomRatioLiveData, MIN_ZOOM); setLiveDataValue(mZoomPercentageLiveData, 0f); } if (completerToSetException != null) { completerToSetException .setException(new OperationCanceledException("Camera is not active.")); } }
Source:
public void channelActive(ChannelHandlerContext ctx) throws Exception { if (handshakeTimeout > 0) { timeoutFuture = scheduledThreadPool.schedule(new Runnable() { @Override public void run() { ActiveMQClientLogger.LOGGER.readTimeout(); ctx.channel().close(); } }, handshakeTimeout, TimeUnit.SECONDS); } }

Target:
public void channelActive(ChannelHandlerContext ctx) throws Exception { if (handshakeTimeout > 0) { timeoutFuture = scheduledThreadPool.schedule( () -> { ActiveMQServerLogger.LOGGER.handshakeTimeout(handshakeTimeout); ctx.channel().close(); }, handshakeTimeout, TimeUnit.SECONDS); } }
Source:
private RoutingType getRoutingType(Symbol[] symbols, SimpleString address) { if (symbols != null) { for (Symbol symbol : symbols) { if (AmqpSupport.TEMP_TOPIC_CAPABILITY.equals(symbol) || AmqpSupport.TOPIC_CAPABILITY.equals(symbol)) { return RoutingType.MULTICAST; } else if (AmqpSupport.TEMP_QUEUE_CAPABILITY.equals(symbol) || AmqpSupport.QUEUE_CAPABILITY.equals(symbol)) { return RoutingType.ANYCAST; } } } final AddressInfo addressInfo = sessionSPI.getAddress(address); if (addressInfo != null && !addressInfo.getRoutingTypes().isEmpty()) { if (addressInfo.getRoutingTypes().size() == 1) { return addressInfo.getRoutingType(); } final RoutingType defaultRoutingType = sessionSPI.getDefaultRoutingType(address); if (defaultRoutingType != null && addressInfo.getRoutingTypes().contains(defaultRoutingType)) { return defaultRoutingType; } return addressInfo.getRoutingType(); } return sessionSPI.getDefaultRoutingType(address); }

Target:
private RoutingType getRoutingType(Symbol[] symbols, SimpleString address) { if (symbols != null) { for (Symbol symbol : symbols) { if (AmqpSupport.TEMP_TOPIC_CAPABILITY.equals(symbol) || AmqpSupport.TOPIC_CAPABILITY.equals(symbol)) { return RoutingType.MULTICAST; } else if (AmqpSupport.TEMP_QUEUE_CAPABILITY.equals(symbol) || AmqpSupport.QUEUE_CAPABILITY.equals(symbol)) { return RoutingType.ANYCAST; } } } final AddressInfo addressInfo = sessionSPI.getAddress(address); if (addressInfo != null && !addressInfo.getRoutingTypes().isEmpty()) { if (addressInfo.getRoutingTypes().size() == 1) { return addressInfo.getRoutingType(); } } RoutingType defaultRoutingType = sessionSPI.getDefaultRoutingType(address); defaultRoutingType = defaultRoutingType == null ? ActiveMQDefaultConfiguration.getDefaultRoutingType() : defaultRoutingType; return defaultRoutingType; }
Source:
private List<String> getReconnectServerList() { if (options.isNoRandomize()) { return getServersList(); } List<String> servers = new ArrayList<>(); addDiscoveredServers(servers); shuffleWithoutCurrent(servers); List<String> configured = new ArrayList<>(); addConfiguredServers(configured); shuffleWithoutCurrent(configured); servers.addAll(configured); if (currentServer != null) { servers.add(currentServer); } return servers; }

Target:
private List<String> getReconnectServerList() { return options.isNoRandomize() ? getServersList() : shuffle(getServersList()); }
Source:
public void popUpForEdit(SessionDataDto currentSession, SessionComparisonPanel.TreeItem item, List<TagDto> allTags) { getApplyButton().removeFromParent(); this.currentSession=currentSession; setText("Session " +currentSession.getSessionId()); setGrids(allTags, currentSession.getTags()); currentTreeItem = item; show(); }

Target:
public void popUpForEdit(SessionDataDto currentSession, SessionComparisonPanel.TreeItem item, List<TagDto> allTags) { if (currentSession == null) { new ExceptionPanel("The session data has a value null. The session's id is wrong."); } getApplyButton().removeFromParent(); this.currentSession = currentSession; setText("Session " + currentSession.getSessionId()); setGrids(allTags, currentSession.getTags()); currentTreeItem = item; show(); }
Source:
protected void ExecuteVdsBrokerCommand() { GlusterVolumeAdvancedDetails volumeAdvancedDetails = new GlusterVolumeAdvancedDetails(); executeVolumeStatusInfo(""); volumeAdvancedDetails = result.getVolumeAdvancedDetails(); if (getParameters().detailsRequired()) { if (getSucceeded()) { executeVolumeStatusInfo(GlusterVolumeStatusOption.DETAIL.name().toLowerCase()); if (getSucceeded()) { volumeAdvancedDetails.copyDetailsFrom(result.getVolumeAdvancedDetails()); executeVolumeStatusInfo(GlusterVolumeStatusOption.CLIENTS.name().toLowerCase()); if (getSucceeded()) { volumeAdvancedDetails.copyClientsFrom(result.getVolumeAdvancedDetails()); executeVolumeStatusInfo(GlusterVolumeStatusOption.MEM.name().toLowerCase()); if (getSucceeded()) { volumeAdvancedDetails.copyMemoryFrom(result.getVolumeAdvancedDetails()); } } } } } setReturnValue(volumeAdvancedDetails); }

Target:
protected void ExecuteVdsBrokerCommand() { executeVolumeStatusInfo(""); GlusterVolumeAdvancedDetails volumeAdvancedDetails = result.getVolumeAdvancedDetails(); if (getParameters().detailsRequired()) { if (getSucceeded()) { executeVolumeStatusInfo(GlusterVolumeStatusOption.DETAIL.name().toLowerCase()); if (getSucceeded()) { volumeAdvancedDetails.copyDetailsFrom(result.getVolumeAdvancedDetails()); executeVolumeStatusInfo(GlusterVolumeStatusOption.CLIENTS.name().toLowerCase()); if (getSucceeded()) { volumeAdvancedDetails.copyClientsFrom(result.getVolumeAdvancedDetails()); executeVolumeStatusInfo(GlusterVolumeStatusOption.MEM.name().toLowerCase()); if (getSucceeded()) { volumeAdvancedDetails.copyMemoryFrom(result.getVolumeAdvancedDetails()); } } } } } setReturnValue(volumeAdvancedDetails); }
Source:
private Consumer<String> fsEventConsumer(String endpointId, String wsPath) { return it -> { try { String normalizedPath = wsPath.startsWith("/") ? wsPath.substring(1) : wsPath; String itemPath = normalizedPath.substring(normalizedPath.indexOf("/") + 1); String projectName = normalizedPath.split("/")[0]; if (!projectManager.isRegistered(absolutize(projectName))) { throw new NotFoundException("Project '" + projectName + "' is not found"); } String projectFsPath = pathTransformer.transform(projectName).toString(); GitConnection gitConnection = gitConnectionFactory.getConnection(projectFsPath); Status status = gitConnection.status(singletonList(itemPath)); FileChangedEventDto.Status fileStatus; if (status.getAdded().contains(itemPath)) { fileStatus = ADDED; } else if (status.getUntracked().contains(itemPath)) { fileStatus = UNTRACKED; } else if (status.getModified().contains(itemPath) || status.getChanged().contains(itemPath)) { fileStatus = MODIFIED; } else { fileStatus = NOT_MODIFIED; } transmitter .newRequest() .endpointId(endpointId) .methodName(EVENT_GIT_FILE_CHANGED) .paramsAsDto( newDto(FileChangedEventDto.class) .withPath(wsPath) .withStatus(fileStatus) .withEditedRegions(gitConnection.getEditedRegions(itemPath))) .sendAndSkipResult(); } catch (NotFoundException | ServerException e) { if (!(e instanceof NotAGitRepositoryException) && !(e instanceof GitCommitInProgressException)) { LOG.error(e.getMessage()); } } }; }

Target:
private Consumer<String> fsEventConsumer(String endpointId, String wsPath) { return it -> { try { String normalizedPath = wsPath.startsWith("/") ? wsPath.substring(1) : wsPath; String itemPath = normalizedPath.substring(normalizedPath.indexOf("/") + 1); String projectName = normalizedPath.split("/")[0]; if (!projectManager.isRegistered(absolutize(projectName))) { throw new NotFoundException("Project '" + projectName + "' is not found"); } String projectFsPath = pathTransformer.transform(projectName).toString(); GitConnection gitConnection = gitConnectionFactory.getConnection(projectFsPath); Status status = gitConnection.status(singletonList(itemPath)); FileChangedEventDto.Status fileStatus; if (status.getAdded().contains(itemPath)) { fileStatus = ADDED; } else if (status.getUntracked().contains(itemPath)) { fileStatus = UNTRACKED; } else if (status.getModified().contains(itemPath) || status.getChanged().contains(itemPath)) { fileStatus = MODIFIED; } else { fileStatus = NOT_MODIFIED; } transmitter .newRequest() .endpointId(endpointId) .methodName(EVENT_GIT_FILE_CHANGED) .paramsAsDto( newDto(FileChangedEventDto.class) .withPath(wsPath) .withStatus(fileStatus) .withEditedRegions(gitConnection.getEditedRegions(itemPath))) .sendAndSkipResult(); } catch (GitCommitInProgressException | GitInvalidRepositoryException e) { } catch (ServerException | NotFoundException e) { LOG.error(e.getMessage()); } }; }
Source:
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException { Statement stmt = ((JdbcSchema) db).getConnection().createStatement(); try { ResultSet result = stmt.executeQuery("SELECT account_id, default_context FROM accounts"); while (result.next()) { int accountId = result.getInt(1); short defaultContext = result.getShort(2); AccountDiffPreference diffPref = AccountDiffPreference.createDefault(new Account.Id(accountId)); diffPref.setContext(defaultContext); db.accountDiffPreferences().insert(Collections.singleton(diffPref)); } } finally { stmt.close(); } }

Target:
protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException { Statement stmt = ((JdbcSchema) db).getConnection().createStatement(); try { stmt.execute("DROP INDEX account_project_watches_ntNew"); stmt.execute("DROP INDEX account_project_watches_ntCmt"); stmt.execute("DROP INDEX account_project_watches_ntSub"); stmt.execute("CREATE INDEX account_project_watches_byProject" + " ON account_project_watches (project_name)"); } finally { stmt.close(); } }
Source:
public String getLocation() { String location = OpenShiftCorePreferences.INSTANCE.getOCBinaryLocation(); if (StringUtils.isBlank(location)) { location = findLocation(); } return location; }

Target:
public String getLocation() { String location = OpenShiftCorePreferences.INSTANCE.getOCBinaryLocation(); if (StringUtils.isBlank(location)) { location = getSystemPathLocation(); } return location; }
Source:
protected void releaseInstance(T instance) throws IOException { AtomicInteger currentCount = providedVsCount.get(instance); if(currentCount != null) { if(currentCount.decrementAndGet() < 0) { currentCount.incrementAndGet(); throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider"); } } else { throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider"); } if(instantiated.contains(instance) && instance instanceof Closeable) { ((Closeable)instance).close(); } instantiated.remove(instance); }

Target:
protected void releaseInstance(T instance) throws IOException { AtomicInteger currentCount = providedVsCount.get(instance); if(currentCount != null) { if(currentCount.decrementAndGet() < 0) { currentCount.incrementAndGet(); throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider"); } } else { throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider"); } if(instantiated.remove(instance) && instance instanceof Closeable) { ((Closeable)instance).close(); } }
Source:
public TestingConnectorSession(List<PropertyMetadata<?>> properties) { this("user", Optional.of("test"), UTC_KEY, ENGLISH, System.currentTimeMillis(), properties, ImmutableMap.of(), true); }

Target:
public TestingConnectorSession(List<PropertyMetadata<?>> properties) { this("user", Optional.of("test"), UTC_KEY, ENGLISH, System.currentTimeMillis(), properties, ImmutableMap.of(), false); }
Source:
protected void damageTool(GlowPlayer player, ItemStack holding, int damage) { if (player.getGameMode() == GameMode.CREATIVE || damage == 0) { return; } holding.setDurability((short) (holding.getDurability() + damage)); if (holding.getDurability() == maxDurability + damage) { EventFactory.callEvent(new PlayerItemBreakEvent(player, holding)); player.getInventory().remove(holding); } }

Target:
protected void damageTool(GlowPlayer player, ItemStack holding, int damage) { if (holding == null || player.getGameMode() == GameMode.CREATIVE || damage == 0) { return; } holding.setDurability((short) (holding.getDurability() + damage)); if (holding.getDurability() > maxDurability) { EventFactory.callEvent(new PlayerItemBreakEvent(player, holding)); player.getInventory().remove(holding); } }
Source:
private Map<String, String> addBuildArgs(BuildContext buildContext) { Map<String, String> buildArgsFromProject = addBuildArgsFromProperties(buildContext.getMojoParameters().getProject().getProperties()); Map<String, String> buildArgsFromSystem = addBuildArgsFromProperties(System.getProperties()); Map<String, String> buildArgsFromDockerConfig = addBuildArgsFromDockerConfig(); return ImmutableMap.<String, String>builder() .putAll(buildContext.getBuildArgs() != null ? buildContext.getBuildArgs() : Collections.<String, String>emptyMap()) .putAll(buildArgsFromProject) .putAll(buildArgsFromSystem) .putAll(buildArgsFromDockerConfig) .build(); }

Target:
private Map<String, String> addBuildArgs(BuildContext buildContext) { Map<String, String> buildArgsFromProject = addBuildArgsFromProperties(buildContext.getMojoParameters().getProject().getProperties()); Map<String, String> buildArgsFromSystem = addBuildArgsFromProperties(System.getProperties()); Map<String, String> buildArgsFromDockerConfig = addBuildArgsFromDockerConfig(); return ImmutableMap.<String, String>builder() .putAll(buildArgsFromDockerConfig) .putAll(buildContext.getBuildArgs() != null ? buildContext.getBuildArgs() : Collections.<String, String>emptyMap()) .putAll(buildArgsFromProject) .putAll(buildArgsFromSystem) .build(); }
Source:
private int getReportTotalRows( final String key ) { final Map<String, Serializable> metaData = getCachedMetaData( key ); if ( metaData != null ) { final Object reportTotalRows = metaData.get( REPORT_ROWS ); if ( reportTotalRows != null ) { return (int) reportTotalRows; } } return 0; }

Target:
private int getReportTotalRows( final String key ) { final Map<String, Serializable> metaData = getCachedMetaData( key ); if ( metaData != null ) { final Object reportTotalRows = metaData.get( REPORT_ROWS ); if ( reportTotalRows != null ) { return (int) reportTotalRows; } } return -1; }
Source:
public void testUpdateMetadataAllowedImmediatelyAfterBootstrap() { MockTime time = new MockTime(); Metadata metadata = new Metadata(refreshBackoffMs, metadataExpireMs, new LogContext(), new ClusterResourceListeners()); metadata.bootstrap(Collections.singletonList(new InetSocketAddress("localhost", 9002))); metadata.requestUpdate(); assertEquals(0, metadata.timeToAllowUpdate(time.milliseconds())); assertEquals(0, metadata.timeToNextUpdate(time.milliseconds())); }

Target:
public void testUpdateMetadataAllowedImmediatelyAfterBootstrap() { MockTime time = new MockTime(); Metadata metadata = new Metadata(refreshBackoffMs, metadataExpireMs, new LogContext(), new ClusterResourceListeners()); metadata.bootstrap(Collections.singletonList(new InetSocketAddress("localhost", 9002))); assertEquals(0, metadata.timeToAllowUpdate(time.milliseconds())); assertEquals(0, metadata.timeToNextUpdate(time.milliseconds())); }
Source:
public List<Predicate<ItemStackSnapshot>> getIngredientPredicates() { return ingredients; }

Target:
public List<Predicate<ItemStackSnapshot>> getIngredientPredicates() { return this.ingredients; }
Source:
public void hasAnnotatedAllParameters(ExecutableElement element, ElementValidation validation) { if (!validation.isValid()) { return; } Set<String> urlVariableNames = restAnnotationHelper.extractUrlVariableNames(element); if (urlVariableNames.size() != numberOfPathAnnotatedParameter(element) + numberOfRequiresCookieInUrl(element)) { validation.addError(element, "%s parameters must add annotations"); } for (VariableElement variableElement : element.getParameters()) { if (!restAnnotationHelper.hasRequestParameterAnnotation(variableElement)) { validation.addError(element, "%s method parameters '" + variableElement + "' must be annotated"); } } }

Target:
public void hasAnnotatedAllParameters(ExecutableElement element, ElementValidation validation) { if (!validation.isValid()) { return; } Set<String> urlVariableNames = restAnnotationHelper.extractUrlVariableNames(element); if (urlVariableNames.size() != numberOfPathAnnotatedParameter(element) + numberOfRequiresCookieInUrl(element)) { validation.addError(element, "%s must have url variables corresponding to the @Path or @RequiresCookieInUrl annotation"); } for (VariableElement variableElement : element.getParameters()) { if (!restAnnotationHelper.hasRestApiMethodParameterAnnotation(variableElement)) { validation.addError(element, "%s method parameters '" + variableElement + "' must be annotated"); } } }
Source:
public void readTraces() { if (fTraceEnum.getNbEvents() != -1) { try (CTFTrace trace = new CTFTrace(fTraceEnum.getPath()); CTFTraceReader reader = new CTFTraceReader(trace)) { EventDefinition currentEventDef = reader.getCurrentEventDef(); double start = currentEventDef.getTimestamp(); long count = 0; double end = start; while (reader.hasMoreEvents()) { reader.advance(); count++; currentEventDef = reader.getCurrentEventDef(); if (currentEventDef != null) { end = currentEventDef.getTimestamp(); if (currentEventDef.getDeclaration().getName().equals(CTFStrings.LOST_EVENT_NAME)) { count += ((IntegerDefinition) currentEventDef.getFields().getDefinition(CTFStrings.LOST_EVENTS_FIELD)).getValue() - 1; } } } assertEquals("Event count", fTraceEnum.getNbEvents(), count); assertEquals("Trace duration", fTraceEnum.getDuration(), (end - start) / 1000000000.0, 1.0); } catch (CTFReaderException e) { fail(fTraceEnum.getPath() + " " + e.getMessage()); } } else{ assumeTrue("Trace did not specify events count",false); } }

Target:
public void readTraces() { if (fTraceEnum.getNbEvents() != -1) { try (CTFTraceReader reader = new CTFTraceReader(new CTFTrace(fTraceEnum.getPath()))) { EventDefinition currentEventDef = reader.getCurrentEventDef(); double start = currentEventDef.getTimestamp(); long count = 0; double end = start; while (reader.hasMoreEvents()) { reader.advance(); count++; currentEventDef = reader.getCurrentEventDef(); if (currentEventDef != null) { end = currentEventDef.getTimestamp(); if (currentEventDef.getDeclaration().getName().equals(CTFStrings.LOST_EVENT_NAME)) { count += ((IntegerDefinition) currentEventDef.getFields().getDefinition(CTFStrings.LOST_EVENTS_FIELD)).getValue() - 1; } } } assertEquals("Event count", fTraceEnum.getNbEvents(), count); assertEquals("Trace duration", fTraceEnum.getDuration(), (end - start) / 1000000000.0, 1.0); } catch (CTFReaderException e) { fail(fTraceEnum.getPath() + " " + e.getMessage()); } } else { assumeTrue("Trace did not specify events count", false); } }
Source:
public LdapIdentityProvider( @Nonnull String stsEndpoint, @Nonnull String ldapUsername, @Nonnull String ldapPassword, @Nullable OkHttpClient customHttpClient) { super(customHttpClient); stsEndpoint = Objects.requireNonNull(stsEndpoint, "STS endpoint cannot be empty"); HttpUrl url = Objects.requireNonNull(HttpUrl.parse(stsEndpoint), "Invalid STS endpoint"); Objects.requireNonNull(ldapUsername, "LDAP username must not be null"); if (ldapUsername.isEmpty()) { throw new IllegalArgumentException("LDAP username must not be empty"); } Objects.requireNonNull(ldapPassword, "LDAP password must not be null"); HttpUrl.Builder urlBuilder = newUrlBuilder(url, "AssumeRoleWithLDAPIdentity", 0, null, null, null); url = urlBuilder .addQueryParameter("LDAPUsername", ldapUsername) .addQueryParameter("LDAPPassword", ldapPassword) .build(); this.request = new Request.Builder().url(url).method("POST", EMPTY_BODY).build(); }

Target:
public LdapIdentityProvider( @Nonnull String stsEndpoint, @Nonnull String ldapUsername, @Nonnull String ldapPassword, @Nullable OkHttpClient customHttpClient) { super(customHttpClient); stsEndpoint = Objects.requireNonNull(stsEndpoint, "STS endpoint cannot be empty"); HttpUrl url = Objects.requireNonNull(HttpUrl.parse(stsEndpoint), "Invalid STS endpoint"); if (ldapUsername == null || ldapUsername.isEmpty()) { throw new IllegalArgumentException("LDAP username must be provided"); } Objects.requireNonNull(ldapPassword, "LDAP password must not be null"); HttpUrl.Builder urlBuilder = newUrlBuilder(url, "AssumeRoleWithLDAPIdentity", 0, null, null, null); url = urlBuilder .addQueryParameter("LDAPUsername", ldapUsername) .addQueryParameter("LDAPPassword", ldapPassword) .build(); this.request = new Request.Builder().url(url).method("POST", EMPTY_BODY).build(); }
Source:
public CtfLocation clone() { return new CtfLocation(this.getLocation()); }

Target:
public CtfLocation clone() { return new CtfLocation(this.getLocationData()); }
Source:
public void testMoshi() throws Exception { final DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); String birthdate = "2007-11-11"; Date date = df.parse(birthdate); Moshi moshi = SampleTypeAdapterFactory.configureMoshiBuilder(new Moshi.Builder()) .build(); Person person = Person.builder() .name("Piasy") .gender(1) .age(23) .birthdate(date) .address(Address.create("street", "city")) .build(); String json = "{\"name\":\"Piasy\",\"gender\":1," + "\"age\":23,\"birthdate\":\"" + birthdate + "\",\"address\":{\"street-name\":\"street\",\"city\":\"city\"}}"; JsonAdapter<Person> jsonAdapter = moshi.adapter(Person.class); String toJson = jsonAdapter.toJson(person); Assert.assertEquals(json, toJson); Person fromJson = jsonAdapter.fromJson(json); Assert.assertEquals("Piasy", fromJson.name()); Assert.assertEquals(23, fromJson.age()); Assert.assertEquals(1, fromJson.gender()); Assert.assertEquals(date, fromJson.birthdate()); }

Target:
public void testMoshi() throws Exception { final DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); Moshi moshi = new Moshi.Builder() .add(SampleTypeAdapterFactory.create()) .build(); Person person = Person.builder() .name("Piasy") .gender(1) .age(23) .address(Address.create("street", "city")) .build(); String json = "{\"name\":\"Piasy\",\"gender\":1," + "\"age\":23,\"address\":{\"street-name\":\"street\",\"city\":\"city\"}}"; JsonAdapter<Person> jsonAdapter = moshi.adapter(Person.class); String toJson = jsonAdapter.toJson(person); assertEquals(json, toJson); Person fromJson = jsonAdapter.fromJson(json); assertEquals("Piasy", fromJson.name()); assertEquals(23, fromJson.age()); assertEquals(1, fromJson.gender()); }
Source:
public void testTopicNotFromConfHeader() throws UnsupportedEncodingException { Sink kafkaSink = new KafkaSink(); Context context = prepareDefaultContext(); context.put(KafkaSinkConstants.ALLOW_TOPIC_OVERRIDE_HEADER, "false"); context.put(KafkaSinkConstants.TOPIC_OVERRIDE_HEADER, "foo"); context.put(KafkaSinkConstants.TOPIC_OVERRIDE_HEADER, "bar"); Configurables.configure(kafkaSink, context); Channel memoryChannel = new MemoryChannel(); Configurables.configure(memoryChannel, context); kafkaSink.setChannel(memoryChannel); kafkaSink.start(); String msg = "test-topic-from-config-header"; Map<String, String> headers = new HashMap<String, String>(); headers.put(KafkaSinkConstants.DEFAULT_TOPIC_OVERRIDE_HEADER, TestConstants.CUSTOM_TOPIC); headers.put("key", TestConstants.CUSTOM_KEY); Transaction tx = memoryChannel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody(msg.getBytes(), headers); memoryChannel.put(event); tx.commit(); tx.close(); try { Sink.Status status = kafkaSink.process(); if (status == Sink.Status.BACKOFF) { fail("Error Occurred"); } } catch (EventDeliveryException ex) { } MessageAndMetadata fetchedMsg = testUtil.getNextMessageFromConsumer(DEFAULT_TOPIC); assertEquals(msg, new String((byte[]) fetchedMsg.message(), "UTF-8")); assertEquals(TestConstants.CUSTOM_KEY, new String((byte[]) fetchedMsg.key(), "UTF-8")); }

Target:
public void testTopicNotFromConfHeader() throws UnsupportedEncodingException { Sink kafkaSink = new KafkaSink(); Context context = prepareDefaultContext(); context.put(KafkaSinkConstants.ALLOW_TOPIC_OVERRIDE_HEADER, "false"); context.put(KafkaSinkConstants.TOPIC_OVERRIDE_HEADER, "foo"); Configurables.configure(kafkaSink, context); Channel memoryChannel = new MemoryChannel(); Configurables.configure(memoryChannel, context); kafkaSink.setChannel(memoryChannel); kafkaSink.start(); String msg = "test-topic-from-config-header"; Map<String, String> headers = new HashMap<String, String>(); headers.put(KafkaSinkConstants.DEFAULT_TOPIC_OVERRIDE_HEADER, TestConstants.CUSTOM_TOPIC); headers.put("foo", TestConstants.CUSTOM_TOPIC); Transaction tx = memoryChannel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody(msg.getBytes(), headers); memoryChannel.put(event); tx.commit(); tx.close(); try { Sink.Status status = kafkaSink.process(); if (status == Sink.Status.BACKOFF) { fail("Error Occurred"); } } catch (EventDeliveryException ex) { } MessageAndMetadata<?, ?> fetchedMsg = testUtil.getNextMessageFromConsumer(DEFAULT_TOPIC); assertEquals(msg, new String((byte[]) fetchedMsg.message(), "UTF-8")); }
Source:
public HadoopDruidIndexerConfig( final @JsonProperty("spec") HadoopIngestionSpec spec ) { this.schema = spec; this.pathSpec = JSON_MAPPER.convertValue(spec.getIOConfig().getPathSpec(), PathSpec.class); for (Map.Entry<DateTime, List<HadoopyShardSpec>> entry : spec.getTuningConfig().getShardSpecs().entrySet()) { if (entry.getValue() == null || entry.getValue().isEmpty()) { continue; } final ShardSpec actualSpec = entry.getValue().get(0).getActualSpec(); shardSpecLookups.put( entry.getKey(), actualSpec.getLookup( Lists.transform( entry.getValue(), new Function<HadoopyShardSpec, ShardSpec>() { @Override public ShardSpec apply(HadoopyShardSpec input) { return input.getActualSpec(); } } ) ) ); Map<ShardSpec, HadoopyShardSpec> hadoopyShardSpecLookup = Maps.newHashMap(); for (HadoopyShardSpec hadoopyShardSpec : entry.getValue()) { hadoopyShardSpecLookup.put(hadoopyShardSpec.getActualSpec(), hadoopyShardSpec); } hadoopShardSpecLookup.put(entry.getKey(), hadoopyShardSpecLookup); } this.rollupGran = spec.getDataSchema().getGranularitySpec().getQueryGranularity(); }

Target:
public HadoopDruidIndexerConfig( final @JsonProperty("spec") HadoopIngestionSpec spec ) { this.schema = spec; this.pathSpec = JSON_MAPPER.convertValue(spec.getIOConfig().getPathSpec(), PathSpec.class); for (Map.Entry<DateTime, List<HadoopyShardSpec>> entry : spec.getTuningConfig().getShardSpecs().entrySet()) { if (entry.getValue() == null || entry.getValue().isEmpty()) { continue; } final ShardSpec actualSpec = entry.getValue().get(0).getActualSpec(); shardSpecLookups.put( entry.getKey(), actualSpec.getLookup( Lists.transform( entry.getValue(), new Function<HadoopyShardSpec, ShardSpec>() { @Override public ShardSpec apply(HadoopyShardSpec input) { return input.getActualSpec(); } } ) ) ); Map<ShardSpec, HadoopyShardSpec> innerHadoopShardSpecLookup = Maps.newHashMap(); for (HadoopyShardSpec hadoopyShardSpec : entry.getValue()) { innerHadoopShardSpecLookup.put(hadoopyShardSpec.getActualSpec(), hadoopyShardSpec); } hadoopShardSpecLookup.put(entry.getKey(), innerHadoopShardSpecLookup); } this.rollupGran = spec.getDataSchema().getGranularitySpec().getQueryGranularity(); }
Source:
public static List<List<Integer>> sortHostIdByHGDistance(int hostId, Map<Integer, String> hostGroups) { String localHostGroup = hostGroups.get(hostId); Preconditions.checkArgument(localHostGroup != null); List<Integer> sortedList = hostGroups.keySet().stream() .filter(hid -> hid != hostId) .sorted((hid1, hid2) -> computeHADistance(localHostGroup, hostGroups.get(hid2)) - computeHADistance(localHostGroup, hostGroups.get(hid1)) ) .collect(Collectors.toList()); List<List<Integer>> result = Lists.newArrayList(); if (sortedList.size() == 1) { result.add(sortedList); return result; } List<Integer> subgroup = Lists.newArrayList(); subgroup.add(sortedList.get(0)); for (int i = 1; i < sortedList.size(); i++) { int hid1 = sortedList.get(i - 1); int hid2 = sortedList.get(i); int distance1 = computeHADistance(localHostGroup, hostGroups.get(hid1)); int distance2 = computeHADistance(localHostGroup, hostGroups.get(hid2)); if (distance1 == distance2) { subgroup.add(hid2); } else { result.add(subgroup); subgroup = Lists.newArrayList(); subgroup.add(hid2); } } if (!subgroup.isEmpty()) { result.add(subgroup); } return result; }

Target:
public static List<Collection<Integer>> sortHostIdByHGDistance(int hostId, Map<Integer, String> hostGroups) { String localHostGroup = hostGroups.get(hostId); Preconditions.checkArgument(localHostGroup != null); Multimap<Integer, Integer> distanceMap = LinkedListMultimap.create(); for (Map.Entry<Integer, String> entry : hostGroups.entrySet()) { if (hostId == entry.getKey()) continue; distanceMap.put(computeHADistance(localHostGroup, entry.getValue()), entry.getKey()); } List<Collection<Integer>> result = distanceMap.asMap().entrySet().stream() .sorted(Comparator.comparingInt(k->((Entry<Integer, Integer>) k).getKey()).reversed()) .map(x->x.getValue()) .collect(Collectors.toList()); return result; }
Source:
private void markUnusedWALs() { Set<DfsLogger> candidates; synchronized (closedLogs) { candidates = new HashSet<>(closedLogs); } for (Tablet tablet : getOnlineTablets()) { tablet.removeInUseLogs(candidates); if (candidates.size() == 0) { break; } } try { TServerInstance session = this.getTabletSession(); for (DfsLogger candidate : candidates) { log.info("Marking " + candidate.getPath() + " as unreferenced"); walMarker.walUnreferenced(session, candidate.getPath()); } synchronized (closedLogs) { closedLogs.removeAll(candidates); } } catch (WalMarkerException ex) { log.info(ex.toString(), ex); } }

Target:
private void markUnusedWALs() { Set<DfsLogger> candidates; synchronized (closedLogs) { candidates = new HashSet<>(closedLogs); } for (Tablet tablet : getOnlineTablets()) { tablet.removeInUseLogs(candidates); if (candidates.isEmpty()) { break; } } try { TServerInstance session = this.getTabletSession(); for (DfsLogger candidate : candidates) { log.info("Marking " + candidate.getPath() + " as unreferenced"); walMarker.walUnreferenced(session, candidate.getPath()); } synchronized (closedLogs) { closedLogs.removeAll(candidates); } } catch (WalMarkerException ex) { log.info(ex.toString(), ex); } }
Source:
public OSService[] getServices() { OSProcess[] process = getChildProcesses(1, 0, OperatingSystem.ProcessSort.PID); File etc = new File("/etc/init"); File[] files = etc.listFiles(); OSService[] svcArray = new OSService[files.size()]; for (int i = 0; i < files.length; i++) { svcArray[i].setName(files[i].getName()); for (int j = 0; j < process.length; j++) { if(process[j].getName().equals(files[i].getName())) { svcArray[i].setProcessId(process[j].getProcessID()); svcArray[i].setState(OSService.State.RUNNING); } else { svcArray[i].setState(OSService.State.STOPPED); } } } return svcArray; }

Target:
public OSService[] getServices() { List<OSService> services = new ArrayList<>(); Set<String> running = new HashSet<>(); for (OSProcess p : getChildProcesses(1, 0, ProcessSort.PID)) { OSService s = new OSService(p.getName(), p.getProcessID(), RUNNING); ; services.add(s); running.add(p.getName()); } File dir = new File("/etc/init"); if (dir.exists() && dir.isDirectory()) { for (File f : dir.listFiles((f, name) -> name.toLowerCase().endsWith(".conf"))) { String name = f.getName().substring(0, f.getName().length() - 5); int index = name.lastIndexOf('.'); String shortName = (index < 0 || index > name.length() - 2) ? name : name.substring(index + 1); if (!running.contains(name) && !running.contains(shortName)) { OSService s = new OSService(name, 0, STOPPED); services.add(s); } } } else { LOG.error("Directory: /etc/init does not exist"); } return services.toArray(new OSService[0]); }