Allocate specified segment.

        If segment exists, then try to allocate it and return db object
        If segment does not exists, then try to create it and return db object
        If allocation/creation failed (duplicates), then return None
327933
def _allocate_specified_segment(self, session, seg_id, source):
        
        try:
            with session.begin(subtransactions=True):
                alloc = (session.query(self.model).filter_by(
                    segmentation_id=seg_id).first())
                if alloc:
                    if alloc.allocated:
                        # Segment already allocated
                        return
                    else:
                        # Segment not allocated
                        count = (session.query(self.model).
                                 filter_by(allocated=False,
                                           segmentation_id=seg_id).update(
                                               {"allocated": True}))
                        if count:
                            return alloc

                # Segment to create or already allocated
                alloc = self.model(segmentation_id=seg_id,
                                   allocated=True, source=source)
                session.add(alloc)

        except db_exc.DBDuplicateEntry:
            # Segment already allocated (insert failure)
            alloc = None

        return alloc
523969
protected void init() {
        try {
            // Initialize the current working segment
            _segment = _segmentManager.nextSegment();
            
            // Segment index buffer is enabled by default!
            _sib = _segmentManager.openSegmentIndexBuffer(_segment.getSegmentId());
            if(!_sibEnabled) _sib.markAsDirty();
            
            _log.info("Segment " + _segment.getSegmentId() + " online: " + _segment.getStatus());
        } catch(IOException ioe) {
            _log.error(ioe.getMessage(), ioe);
            throw new SegmentException("Instantiation failed due to " + ioe.getMessage());
        }
    }
376347
@Override
    public synchronized CommsServerByteBuffer allocate() {
        if (tc.isEntryEnabled())
            SibTr.entry(this, tc, "allocate");

        CommsServerByteBuffer buff = (CommsServerByteBuffer) super.allocate();

        if (tc.isEntryEnabled())
            SibTr.exit(this, tc, "allocate", buff);
        return buff;
    }
161430
private void allocateConnection() throws SQLException
   {
      if (m_connection == null)
      {
         m_connection = m_dataSource.getConnection();
         m_allocatedConnection = true;
         queryDatabaseMetaData();
      }
   }
839135
private void allocateNormal(PooledByteBuf<T> buf, int reqCapacity, int normCapacity) {
        if (q050.allocate(buf, reqCapacity, normCapacity) || q025.allocate(buf, reqCapacity, normCapacity) ||
            q000.allocate(buf, reqCapacity, normCapacity) || qInit.allocate(buf, reqCapacity, normCapacity) ||
            q075.allocate(buf, reqCapacity, normCapacity)) {
            return;
        }

        // Add a new chunk.
        PoolChunk<T> c = newChunk(pageSize, maxOrder, pageShifts, chunkSize);
        boolean success = c.allocate(buf, reqCapacity, normCapacity);
        assert success;
        qInit.add(c);
    }
732627
def allocate(self, dut_configuration_list, args=None):
        
        dut_config_list = dut_configuration_list.get_dut_configuration()
        # if we need one or more local hardware duts let's search attached
        # devices using DutDetection
        if not isinstance(dut_config_list, list):
            raise AllocationError("Invalid dut configuration format!")

        if next((item for item in dut_config_list if item.get("type") == "hardware"), False):
            self._available_devices = DutDetection().get_available_devices()
            if len(self._available_devices) < len(dut_config_list):
                raise AllocationError("Required amount of devices not available.")

        # Enumerate all required DUT's
        try:
            for dut_config in dut_config_list:
                if not self.can_allocate(dut_config.get_requirements()):
                    raise AllocationError("Resource type is not supported")
                self._allocate(dut_config)
        except AllocationError:
            # Locally allocated don't need to be released any way for
            # now, so just re-raise the error
            raise
        alloc_list = AllocationContextList()
        res_id = None
        for conf in dut_config_list:
            if conf.get("type") == "mbed":
                res_id = conf.get("allocated").get("target_id")
            context = AllocationContext(resource_id=res_id, alloc_data=conf)
            alloc_list.append(context)

        alloc_list.set_dut_init_function("serial", init_generic_serial_dut)
        alloc_list.set_dut_init_function("process", init_process_dut)
        alloc_list.set_dut_init_function("mbed", init_mbed_dut)

        return alloc_list
775722
public static AllocationShape buildAllocationShape(DataBuffer buffer) {
        AllocationShape shape = new AllocationShape();
        shape.setDataType(buffer.dataType());
        shape.setLength(buffer.length());

        return shape;
    }
1193262
def newFile(self, *path):
        
        assert len(path) > 0, "newFile requires a nonzero number of segments"
        if self.dbdir is None:
            if self.filesdir is None:
                raise RuntimeError("This in-memory store has no file directory")
            else:
                tmpbase = self.filesdir
        else:
            tmpbase = self.dbdir
        tmpname = tmpbase.child('temp').child(str(tempCounter.next()) + ".tmp")
        return AtomicFile(tmpname.path, self.newFilePath(*path))
809997
def append_segment(self, apdu):
        """"""
        if _debug: SSM._debug("append_segment %r", apdu)

        # check for no context
        if not self.segmentAPDU:
            raise RuntimeError("no segmentation context established")

        # append the data
        self.segmentAPDU.put_data(apdu.pduData)
198928
def alloc_seg(self, net_id):
        
        segmentation_id = self.service_segs.allocate_segmentation_id(
            net_id, source=fw_const.FW_CONST)
        return segmentation_id
95719
function allocate(height, length) {
	var node = new Array(length);
	node.height = height;
	if (height > 0) {
		node.sizes = new Array(length);
	}
	return node;
}
37628
def allocated_chunks(self):
        
        raise NotImplementedError("%s not implemented for %s" % (self.allocated_chunks.__func__.__name__,
                                                                 self.__class__.__name__))
1173947
private void advanceAllocatingFrom(CommitLogSegment old)
    {
        while (true)
        {
            CommitLogSegment next;
            synchronized (this)
            {
                // do this in a critical section so we can atomically remove from availableSegments and add to allocatingFrom/activeSegments
                // see https://issues.apache.org/jira/browse/CASSANDRA-6557?focusedCommentId=13874432&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-13874432
                if (allocatingFrom != old)
                    return;
                next = availableSegments.poll();
                if (next != null)
                {
                    allocatingFrom = next;
                    activeSegments.add(next);
                }
            }

            if (next != null)
            {
                if (old != null)
                {
                    // Now we can run the user defined command just after switching to the new commit log.
                    // (Do this here instead of in the recycle call so we can get a head start on the archive.)
                    CommitLog.instance.archiver.maybeArchive(old);

                    // ensure we don't continue to use the old file; not strictly necessary, but cleaner to enforce it
                    old.discardUnusedTail();
                }

                // request that the CL be synced out-of-band, as we've finished a segment
                CommitLog.instance.requestExtraSync();
                return;
            }

            // no more segments, so register to receive a signal when not empty
            WaitQueue.Signal signal = hasAvailableSegments.register(CommitLog.instance.metrics.waitingOnSegmentAllocation.time());

            // trigger the management thread; this must occur after registering
            // the signal to ensure we are woken by any new segment creation
            wakeManager();

            // check if the queue has already been added to before waiting on the signal, to catch modifications
            // that happened prior to registering the signal; *then* check to see if we've been beaten to making the change
            if (!availableSegments.isEmpty() || allocatingFrom != old)
            {
                signal.cancel();
                // if we've been beaten, just stop immediately
                if (allocatingFrom != old)
                    return;
                // otherwise try again, as there should be an available segment
                continue;
            }

            // can only reach here if the queue hasn't been inserted into
            // before we registered the signal, as we only remove items from the queue
            // after updating allocatingFrom. Can safely block until we are signalled
            // by the allocator that new segments have been published
            signal.awaitUninterruptibly();
        }
    }
1105531
def allocate_stack(size=DEFAULT_STACK_SIZE):
    
    # Allocate memory with appropriate flags for a stack as in https://blog.fefe.de/?ts=a85c8ba7
    base = libc.mmap(
        None,
        size + GUARD_PAGE_SIZE,
        libc.PROT_READ | libc.PROT_WRITE,
        libc.MAP_PRIVATE | libc.MAP_ANONYMOUS | libc.MAP_GROWSDOWN | libc.MAP_STACK,
        -1, 0)

    try:
        # create a guard page that crashes the application when it is written to (on stack overflow)
        libc.mprotect(base, GUARD_PAGE_SIZE, libc.PROT_NONE)

        yield ctypes.c_void_p(base + size + GUARD_PAGE_SIZE)
    finally:
        libc.munmap(base, size + GUARD_PAGE_SIZE)
428826
def allocate(vertices_resources, nets, machine, constraints, placements):
    
    allocation = {}

    # Globally reserved resource ranges {resource, [slice, ...], ...}
    globally_reserved = defaultdict(list)
    # Locally reserved resource ranges {(x, y): {resource, [slice, ...], ...}}
    locally_reserved = defaultdict(lambda: defaultdict(list))

    # Alignment of each resource
    alignments = defaultdict(lambda: 1)

    # Collect constraints
    for constraint in constraints:
        if isinstance(constraint, ReserveResourceConstraint):
            if constraint.location is None:
                globally_reserved[constraint.resource].append(
                    constraint.reservation)
            else:
                locally_reserved[constraint.location][
                    constraint.resource].append(constraint.reservation)
        elif isinstance(constraint, AlignResourceConstraint):
            alignments[constraint.resource] = constraint.alignment

    # A dictionary {(x, y): [vertex, ...], ...}
    chip_contents = defaultdict(list)
    for vertex, xy in iteritems(placements):
        chip_contents[xy].append(vertex)

    for xy, chip_vertices in iteritems(chip_contents):
        # Index of the next free resource in the current chip
        resource_pointers = {resource: 0
                             for resource in machine.chip_resources}

        for vertex in chip_vertices:
            vertex_allocation = {}

            # Make allocations, advancing resource pointers
            for resource, requirement in iteritems(vertices_resources[vertex]):
                proposed_allocation = None
                proposal_overlaps = True
                while proposal_overlaps:
                    # Check that the proposed allocation doesn't overlap a
                    # reserved area.
                    start = align(resource_pointers[resource],
                                  alignments[resource])
                    proposed_allocation = slice(start, start + requirement)
                    proposal_overlaps = False
                    if proposed_allocation.stop > machine[xy][resource]:
                        raise InsufficientResourceError(
                            "{} over-allocated on chip {}".format(resource,
                                                                  xy))
                    for reservation in globally_reserved[resource]:
                        if slices_overlap(proposed_allocation, reservation):
                            resource_pointers[resource] = reservation.stop
                            proposal_overlaps = True
                    local_reservations \
                        = locally_reserved.get(xy, {}).get(resource, [])
                    for reservation in local_reservations:
                        if slices_overlap(proposed_allocation, reservation):
                            resource_pointers[resource] = reservation.stop
                            proposal_overlaps = True

                # Getting here means the proposed allocation is not blocked
                # by any reservations
                vertex_allocation[resource] = proposed_allocation
                resource_pointers[resource] = proposed_allocation.stop

            allocation[vertex] = vertex_allocation

    return allocation
696708
@Override
  public long getAllocatedMemory() {
    long sum = 0;
    for (MapInternals m : segments) {
      sum += m.getAllocatedMemory();
    }
    return sum;
  }
692484
@POST
  @Path("/segment/allocate")
  @Produces(SmileMediaTypes.APPLICATION_JACKSON_SMILE)
  @Consumes(SmileMediaTypes.APPLICATION_JACKSON_SMILE)
  public Response allocateSegment(DateTime timestamp, @Context final HttpServletRequest req)
  {
    ChatHandlers.authorizationCheck(
        req,
        Action.READ,
        getDataSource(),
        authorizerMapper
    );

    if (toolbox == null) {
      return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("task is not running yet").build();
    }

    try {
      final SegmentIdWithShardSpec segmentIdentifier = allocateNewSegment(timestamp);
      return Response.ok(toolbox.getObjectMapper().writeValueAsBytes(segmentIdentifier)).build();
    }
    catch (IOException | IllegalStateException e) {
      return Response.serverError().entity(Throwables.getStackTraceAsString(e)).build();
    }
    catch (IllegalArgumentException e) {
      return Response.status(Response.Status.BAD_REQUEST).entity(Throwables.getStackTraceAsString(e)).build();
    }
  }