Stream all closed subsegments to the daemon
        and remove reference to the parent segment.
        No-op for a not sampled segment.
545862
def stream_subsegments(self):
        
        segment = self.current_segment()

        if self.streaming.is_eligible(segment):
            self.streaming.stream(segment, self._stream_subsegment_out)
506790
public void closeNewList() throws IOException {
    if (!closed) {
      if (segmentRegistration != null) {
        this.segmentName = null;
      }
      if (newSize > 0) {
        // add remaining old
        while (position < getSize()) {
          if (newPosition == newSize) {
            increaseNewListSize();
          }
          newKeyList[newPosition] = keyList[position];
          newSourceNumberList[newPosition] = sourceNumberList[position];
          newErrorNumber[newPosition] = errorNumber[position];
          newErrorList[newPosition] = errorList[position];
          if (hasSub) {
            newSubCollectorListNextLevel[newPosition] = subCollectorListNextLevel[position];
          }
          copyToNew(position, newPosition);
          position++;
          newPosition++;
        }
        // copy
        keyList = newKeyList;
        sourceNumberList = newSourceNumberList;
        errorNumber = newErrorNumber;
        errorList = newErrorList;
        subCollectorListNextLevel = newSubCollectorListNextLevel;
        copyFromNew();
        size = newPosition;
        // sort and merge
        if (!sortedAndUnique(keyList, getSize())) {
          remapData(computeSortAndUniqueMapping(keyList, getSize()));
        }
      }
      position = 0;
      newSize = 0;
      newPosition = 0;
      newCurrentPosition = 0;
    }
  }
1229686
public synchronized boolean freeSegment(Segment seg) throws IOException {
        if (seg == null)
            return false;

        int segId = seg.getSegmentId();
        if (segId < _segList.size() && _segList.get(segId) == seg) {
            _segList.set(segId, null);
            seg.close(false);
            
            if(segId == (_segList.size() - 1)) {
                try {
                    // Delete last segment.
                    _segList.remove(segId);
                    
                    File segFile = seg.getSegmentFile();
                    if(segFile.exists()) segFile.delete();
                    
                    File sibFile = getSegmentIndexBufferFile(segId);
                    if(sibFile.exists()) sibFile.delete();
                    
                    _log.info("Segment " + seg.getSegmentId() + " deleted");
                } catch(Exception e) {
                    _log.warn("Segment " + seg.getSegmentId() + " not deleted", e);
                }
            } else {
                if (seg.isRecyclable() && recycle(seg)) {
                    _log.info("Segment " + seg.getSegmentId() + " recycled");
                } else {
                    _log.info("Segment " + seg.getSegmentId() + " freed");
                }
            }
            
            return true;
        }
        
        return false;
    }
1028556
def close(self):
        
        self.closed = True
        self._flush_bits_to_stream()
        self._stream.close()
546724
private synchronized void resetCurrentSegment() {
    JournalSegment<E> lastSegment = getLastSegment();
    if (lastSegment != null) {
      currentSegment = lastSegment;
    } else {
      JournalSegmentDescriptor descriptor = JournalSegmentDescriptor.builder()
          .withId(1)
          .withIndex(1)
          .withMaxSegmentSize(maxSegmentSize)
          .withMaxEntries(maxEntriesPerSegment)
          .build();

      currentSegment = createSegment(descriptor);

      segments.put(1L, currentSegment);
    }
  }
948057
@Override
	public void recycle(MemorySegment segment) {
		int numAddedBuffers;

		synchronized (bufferQueue) {
			// Similar to notifyBufferAvailable(), make sure that we never add a buffer
			// after releaseAllResources() released all buffers (see below for details).
			if (isReleased.get()) {
				try {
					inputGate.returnExclusiveSegments(Collections.singletonList(segment));
					return;
				} catch (Throwable t) {
					ExceptionUtils.rethrow(t);
				}
			}
			numAddedBuffers = bufferQueue.addExclusiveBuffer(new NetworkBuffer(segment, this), numRequiredBuffers);
		}

		if (numAddedBuffers > 0 && unannouncedCredit.getAndAdd(numAddedBuffers) == 0) {
			notifyCreditAvailable();
		}
	}
1222575
def add_subsegment(self, subsegment):
        
        super(Subsegment, self).add_subsegment(subsegment)
        self.parent_segment.increment()
864161
void discardUnusedTail()
    {
        // we guard this with the OpOrdering instead of synchronised due to potential dead-lock with CLSM.advanceAllocatingFrom()
        // this actually isn't strictly necessary, as currently all calls to discardUnusedTail occur within a block
        // already protected by this OpOrdering, but to prevent future potential mistakes, we duplicate the protection here
        // so that the contract between discardUnusedTail() and sync() is more explicit.
        try (OpOrder.Group group = appendOrder.start())
        {
            while (true)
            {
                int prev = allocatePosition.get();
                // we set allocatePosition past buffer.capacity() to make sure we always set discardedTailFrom
                int next = buffer.capacity() + 1;
                if (prev == next)
                    return;
                if (allocatePosition.compareAndSet(prev, next))
                {
                    discardedTailFrom = prev;
                    return;
                }
            }
        }
    }
763896
def remove_subsegment(self, subsegment):
        
        super(Segment, self).remove_subsegment(subsegment)
        self.decrement_subsegments_size()
189317
def remove_segments(self, segments_to_remove):
        ''' 
        '''
        v_ind = self.vertex_indices_in_segments(segments_to_remove)
        self.segm = {name: faces for name, faces in self.segm.iteritems() if name not in segments_to_remove}
        self.remove_vertices(v_ind)
1242994
@Override
	public void release(MemorySegment segment) {
		// check if segment is null or has already been freed
		if (segment == null || segment.isFreed() || !(segment instanceof DefaultMemorySegment)) {
			return;
		}
		
		final DefaultMemorySegment defSeg = (DefaultMemorySegment) segment;
		final AbstractInvokable owner = defSeg.owner;
		
		// -------------------- BEGIN CRITICAL SECTION -------------------
		synchronized (this.lock)
		{
			if (this.isShutDown) {
				throw new IllegalStateException("Memory manager has been shut down.");
			}

			// remove the reference in the map for the owner
			try {
				Set<DefaultMemorySegment> segsForOwner = this.allocatedSegments.get(owner);
				
				if (segsForOwner != null) {
					segsForOwner.remove(defSeg);
					if (segsForOwner.isEmpty()) {
						this.allocatedSegments.remove(owner);
					}
				}
			}
			catch (Throwable t) {
				LOG.error("Error removing book-keeping reference to allocated memory segment.", t);
			}
			finally {
				// release the memory in any case
				byte[] buffer = defSeg.destroy();
				this.freeSegments.add(buffer);
			}
		}
		// -------------------- END CRITICAL SECTION -------------------
	}
1148123
function process(segments, parent) {
  var last = segments.pop();
  if (last) {
    parent[last] = parent[last] || {};
    process(segments, parent[last]);
  } else {
    parent[true] = true;
  }
}
1219142
def write_segment(self, objects):
        
        segment = TdmsSegment(objects)
        segment.write(self._file)
1166489
public synchronized Segment nextSegment() {
    assertOpen();
    Segment lastSegment = lastSegment();
    SegmentDescriptor descriptor = SegmentDescriptor.builder()
      .withId(lastSegment != null ? lastSegment.descriptor().id() + 1 : 1)
      .withVersion(1)
      .withIndex(currentSegment.lastIndex() + 1)
      .withMaxSegmentSize(storage.maxSegmentSize())
      .withMaxEntries(storage.maxEntriesPerSegment())
      .build();
    descriptor.lock();

    currentSegment = createSegment(descriptor);

    segments.put(descriptor.index(), currentSegment);
    return currentSegment;
  }
161943
def purge_stream(self, stream_id, remove_definition=False, sandbox=None):
        
        super(AssetsChannel, self).purge_stream(
            stream_id=stream_id, remove_definition=remove_definition, sandbox=sandbox)
264831
@Override
	public List<MemorySegment> close() throws IOException {
		if (this.closed) {
			throw new IllegalStateException("Already closed.");
		}
		this.closed = true;

		// re-collect all memory segments
		ArrayList<MemorySegment> list = this.freeMem;
		final MemorySegment current = getCurrentSegment();
		if (current != null) {
			list.add(current);
		}
		clear();

		// close the writer and gather all segments
		final LinkedBlockingQueue<MemorySegment> queue = this.reader.getReturnQueue();
		this.reader.close();

		while (list.size() < this.numSegments) {
			final MemorySegment m = queue.poll();
			if (m == null) {
				// we get null if the queue is empty. that should not be the case if the reader was properly closed.
				throw new RuntimeException("Bug in ChannelReaderInputView: MemorySegments lost.");
			}
			list.add(m);
		}
		return list;
	}
908925
void recycleSegment(final CommitLogSegment segment)
    {
        boolean archiveSuccess = CommitLog.instance.archiver.maybeWaitForArchiving(segment.getName());
        activeSegments.remove(segment);
        if (!archiveSuccess)
        {
            // if archiving (command) was not successful then leave the file alone. don't delete or recycle.
            discardSegment(segment, false);
            return;
        }
        if (isCapExceeded())
        {
            discardSegment(segment, true);
            return;
        }

        logger.debug("Recycling {}", segment);
        segmentManagementTasks.add(new Callable<CommitLogSegment>()
        {
            public CommitLogSegment call()
            {
                return segment.recycle();
            }
        });
    }