Reorders the positions of all items between two affected positions.

@param integer      $positionBefore
@param integer      $positionAfter
@param null|integer $ignoreId
502481
protected function reorderPositionsOnItemsBetween($positionBefore, $positionAfter, $ignoreId = null)
    {
        if ($positionBefore == $positionAfter) {
            return;
        }

        $query = $this->listifyScopedQuery();

        if ($ignoreId) {
            $query->where($this->getPrimaryKey(), '!=', $ignoreId);
        }

        if ($positionBefore < $positionAfter) {
            // increment the in-between positions

            $query
                ->where($this->positionColumn(), '>', $positionBefore)
                ->where($this->positionColumn(), '<=', $positionAfter)
                ->decrement($this->positionColumn());

        } else {
            // decrement the in-between positions

            $query
                ->where($this->positionColumn(), '>=', $positionAfter)
                ->where($this->positionColumn(), '<', $positionBefore)
                ->increment($this->positionColumn());
        }
    }
1158626
public function setItemPosition($position)
    {
        if ((int)$position >= 0) {
            // check if given position is larger as possible position
            if ($position >= ($countItems = $this->countItems())) {
                // set position to max possible position
                $position = $countItems - 1;
            }

            if ($position <= ($this->countItems() / 2)) {
                reset($this->_items);
                $this->_itemValid = true;
                $this->_itemPosition = 0;

                // go with next
                while ($position != $this->_itemPosition) {
                    if (!next($this->_items)) {
                        $this->_itemValid = false;
                        throw new IteratorException('Specified position is not valid (next).', E_NOTICE);
                        break;
                    } else {
                        $this->_itemValid = true;
                        $this->_itemPosition++;
                    }
                }
            } else {
                if (!end($this->_items)) {
                    $this->_itemValid = false;
                    $this->_itemPosition = 0;
                } else {
                    if (($countItems = $this->countItems()) > 0) {
                        $this->_itemValid = true;
                        $this->_itemPosition = $countItems - 1;
                    } else {
                        $this->_itemValid = false;
                        $this->_itemPosition = 0;
                    }
                }

                // go with prev
                while ($position != $this->_itemPosition) {
                    if (!prev($this->_items)) {
                        $this->_itemValid = false;
                        throw new IteratorException('Specified position is not valid (previous).', E_NOTICE);
                        break;
                    } else {
                        $this->_itemValid = true;
                        $this->_itemPosition--;
                    }
                }
            }
        } else {
            throw new IteratorException('Specified position is not valid.', E_WARNING);
        }
    }
454601
public function reorder($elementToBeAfterID = 0)
    {
        $element = $this->element;
        $parentId = $element->ParentID;
        $currentPosition = (int) $element->Sort;
        $sortAfterPosition = 0;

        if ($elementToBeAfterID) {
            /** @var BaseElement $afterBlock */
            $afterElement = BaseElement::get()->byID($elementToBeAfterID);

            if (!$afterElement) {
                throw new InvalidArgumentException(sprintf(
                    '%s#%s not found',
                    BaseElement::class,
                    $elementToBeAfterID
                ));
            }

            // Must be weak comparison as sometimes integers are returned from the DB as strings
            if ($afterElement->ParentID != $parentId) {
                throw new InvalidArgumentException(
                    'Trying to sort element to be placed after an element from a different elemental area'
                );
            }

            $sortAfterPosition = (int) $afterElement->Sort;
        }

        // We are updating records with SQL queries to avoid the ORM triggering the creation of new versions
        // for each element that is affected by this reordering.
        $baseTableName = Convert::raw2sql(DataObject::getSchema()->tableName(BaseElement::class));

        // Update both the draft and live versions of the records
        $tableNames = [$baseTableName];
        if (BaseElement::has_extension(Versioned::class)) {
            $tableNames[] = $element->stageTable($baseTableName, Versioned::LIVE);
        }

        foreach ($tableNames as $tableName) {
            $tableName = sprintf('"%s"', $tableName);

            if ($sortAfterPosition < $currentPosition) {
                $operator = '+';
                $filter = "$tableName.\"Sort\" > $sortAfterPosition AND $tableName.\"Sort\" < $currentPosition";
                $newBlockPosition = $sortAfterPosition + 1;
            } else {
                $operator = '-';
                $filter = "$tableName.\"Sort\" <= $sortAfterPosition AND $tableName.\"Sort\" > $currentPosition";
                $newBlockPosition = $sortAfterPosition;
            }

            $query = SQLUpdate::create()
                ->setTable("$tableName")
                ->assignSQL('"Sort"', "$tableName.\"Sort\" $operator 1")
                ->addWhere([$filter, "$tableName.\"ParentID\"" => $parentId]);

            $query->execute();
        }

        // Now use the ORM to write a new version of the record that we are directly reordering
        $element->Sort = $newBlockPosition;
        $element->write();

        return $element;
    }
1202668
public function call_moveAfter(\Asgard\Entity\Entity $entity, $after_id) {
		$orm = $entity::orm();
		if($this->category)
			$orm->where($this->category, $entity->get($this->category));

		if($after_id == 0) {
			$min = $orm::min('position');
			$entity->save(['position' => $min-1]);
		}
		else {
			$i = 0;
			foreach($orm as $one) {
				if($one->id === $entity->id)
					continue;

				$one->save(['position' => $i++]);
				if($one->id == $after_id)
					$entity->save(['position' => $i++]);
			}
		}
	}
1290307
protected function incrementPositionsOfItemsAbove($position = null)
    {
        if ($this->isNotInList()) return;

        if (null === $position) {
            $position = $this->getListifyPosition();
        }

        $this->listifyScopedQuery()
            ->where($this->positionColumn(), '<', $position)
            ->increment($this->positionColumn());
    }
342928
public static void lazyInsertBefore(Element newElement, Element before) {
        if (!before.parentNode.contains(newElement)) {
            before.parentNode.insertBefore(newElement, before);
        }
    }
317981
public function reorderNodeInPublicWorkspace(ReorderEvent $event)
    {
        $node = $this->getLiveNode($event->getDocument());

        $this->nodeHelper->reorder($node, $event->getDestId());

        // FIXME duplicating logic of OrderSubscriber, maybe move to NodeHelper?
        $count = 1;
        foreach ($node->getParent()->getNodes() as $childNode) {
            $childNode->setProperty($this->propertyEncoder->systemName('order'), $count * 10);
            ++$count;
        }
    }
1266542
public function insertNewRowBefore($pBefore = 1, $pNumRows = 1)
    {
        if ($pBefore >= 1) {
            $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance();
            $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this);
        } else {
            throw new PHPExcel_Exception("Rows can only be inserted before at least row 1.");
        }
        return $this;
    }
347651
public function moveAction($id, $childId = null, $position)
    {

        $objectId = $childId !== null ? $childId : $id;

        $object = $this->admin->getObject($objectId);

        $sortableHandler = $this->get('picoss.sonataextraadmin.handler.sortable');
        $lastPosition = $sortableHandler->getLastPosition($object);
        $position = $sortableHandler->getPosition($object, $position, $lastPosition);

        $object->setPosition($position);
        $this->admin->update($object);

        if ($this->isXmlHttpRequest()) {
            return $this->renderJson(array(
                'result' => 'ok',
                'objectId' => $this->admin->getNormalizedIdentifier($object)
            ));
        }
        $this->addFlash('sonata_flash_info', $this->get('translator')->trans('flash_position_updated_successfully', array(), 'PicossSonataExtraAdminBundle'));

        return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
    }
1012651
def dfs_postorder(self, reverse=False):
        """"""
        stack = deque()
        stack.append(self)
        visited = set()
        while stack:
            node = stack.pop()
            if node in visited:
                yield node
            else:
                visited.add(node)
                stack.append(node)
                if hasattr(node, "childs"):
                    if reverse:
                        stack.extend(node.childs)
                    else:
                        stack.extend(node.childs[::-1])
227862
public static void insertAfter(Element newElement, Element after) {
        after.parentNode.insertBefore(newElement, after.nextSibling);
    }
267724
private static void addOrder(Criteria c, String sort, String order, boolean ignoreCase) {
        if (ORDER_DESC.equals(order)) {
            c.addOrder(ignoreCase ? Order.desc(sort).ignoreCase() : Order.desc(sort));
        }
        else {
            c.addOrder(ignoreCase ? Order.asc(sort).ignoreCase() : Order.asc(sort));
        }
    }
1033894
def reorder_nodes_before_add_or_move(self, pos, newpos, newdepth, target,
                                         siblings, oldpath=None,
                                         movebranch=False):
        
        if (
                (pos == 'last-sibling') or
                (pos == 'right' and target == target.get_last_sibling())
        ):
            # easy, the last node
            last = target.get_last_sibling()
            newpath = last._inc_path()
            if movebranch:
                self.stmts.append(
                    self.get_sql_newpath_in_branches(oldpath, newpath))
        else:
            # do the UPDATE dance

            if newpos is None:
                siblings = target.get_siblings()
                siblings = {'left': siblings.filter(path__gte=target.path),
                            'right': siblings.filter(path__gt=target.path),
                            'first-sibling': siblings}[pos]
                basenum = target._get_lastpos_in_path()
                newpos = {'first-sibling': 1,
                          'left': basenum,
                          'right': basenum + 1}[pos]

            newpath = self.node_cls._get_path(target.path, newdepth, newpos)

            # If the move is amongst siblings and is to the left and there
            # are siblings to the right of its new position then to be on
            # the safe side we temporarily dump it on the end of the list
            tempnewpath = None
            if movebranch and len(oldpath) == len(newpath):
                parentoldpath = self.node_cls._get_basepath(
                    oldpath,
                    int(len(oldpath) / self.node_cls.steplen) - 1
                )
                parentnewpath = self.node_cls._get_basepath(
                    newpath, newdepth - 1)
                if (
                    parentoldpath == parentnewpath and
                    siblings and
                    newpath < oldpath
                ):
                    last = target.get_last_sibling()
                    basenum = last._get_lastpos_in_path()
                    tempnewpath = self.node_cls._get_path(
                        newpath, newdepth, basenum + 2)
                    self.stmts.append(
                        self.get_sql_newpath_in_branches(
                            oldpath, tempnewpath))

            # Optimisation to only move siblings which need moving
            # (i.e. if we've got holes, allow them to compress)
            movesiblings = []
            priorpath = newpath
            for node in siblings:
                # If the path of the node is already greater than the path
                # of the previous node it doesn't need shifting
                if node.path > priorpath:
                    break
                # It does need shifting, so add to the list
                movesiblings.append(node)
                # Calculate the path that it would be moved to, as that's
                # the next "priorpath"
                priorpath = node._inc_path()
            movesiblings.reverse()

            for node in movesiblings:
                # moving the siblings (and their branches) at the right of the
                # related position one step to the right
                sql, vals = self.get_sql_newpath_in_branches(
                    node.path, node._inc_path())
                self.stmts.append((sql, vals))

                if movebranch:
                    if oldpath.startswith(node.path):
                        # if moving to a parent, update oldpath since we just
                        # increased the path of the entire branch
                        oldpath = vals[0] + oldpath[len(vals[0]):]
                    if target.path.startswith(node.path):
                        # and if we moved the target, update the object
                        # django made for us, since the update won't do it
                        # maybe useful in loops
                        target.path = vals[0] + target.path[len(vals[0]):]
            if movebranch:
                # node to move
                if tempnewpath:
                    self.stmts.append(
                        self.get_sql_newpath_in_branches(
                            tempnewpath, newpath))
                else:
                    self.stmts.append(
                        self.get_sql_newpath_in_branches(
                            oldpath, newpath))
        return oldpath, newpath
1111410
public static function reorder_plan_competency($planid, $competencyidfrom, $competencyidto) {
        $params = self::validate_parameters(self::reorder_plan_competency_parameters(), array(
            'planid' => $planid,
            'competencyidfrom' => $competencyidfrom,
            'competencyidto' => $competencyidto,
        ));

        $plan = api::read_plan($params['planid']);
        self::validate_context($plan->get_context());

        return api::reorder_plan_competency($params['planid'], $params['competencyidfrom'], $params['competencyidto']);
    }
324732
public function moveAsPrevSiblingOf(NodeInterface $beforeNode)
	{
		$pos = $beforeNode->getLeftValue();
		$level = $beforeNode->getLevel();
		$this->move($pos, $level);
		
		return $this;
	}
199212
public function move(string $id, $position): self
    {
        if (is_numeric($position)) {
            return $this->toPosition($id, $position);
        }

        if (starts_with($position, 'before:')) {
            return $this->moveBefore($id, substr($position, 7));
        }

        if (starts_with($position, 'after:')) {
            return $this->moveAfter($id, substr($position, 6));
        }

        throw new Exception("Unknown moving direction: {$position}");
    }
262462
public function create(NodeInterface $referenceNode, array $nodeData, $position)
    {
        if (!in_array($position, ['before', 'into', 'after'], true)) {
            throw new \InvalidArgumentException('The position should be one of the following: "before", "into", "after".', 1347133640);
        }
        $nodeType = $this->nodeTypeManager->getNodeType($nodeData['nodeType']);

        if ($nodeType->isOfType('Neos.Neos:Document') && !isset($nodeData['properties']['uriPathSegment']) && isset($nodeData['properties']['title'])) {
            $nodeData['properties']['uriPathSegment'] = $this->nodeUriPathSegmentGenerator->generateUriPathSegment($referenceNode, $nodeData['properties']['title']);
        }

        $proposedNodeName = isset($nodeData['nodeName']) ? $nodeData['nodeName'] : null;
        $nodeData['nodeName'] = $this->nodeService->generateUniqueNodeName($this->getDesignatedParentNode($referenceNode, $position)->getPath(), $proposedNodeName);

        if ($position === 'into') {
            $newNode = $referenceNode->createNode($nodeData['nodeName'], $nodeType);
        } else {
            $parentNode = $referenceNode->getParent();
            $newNode = $parentNode->createNode($nodeData['nodeName'], $nodeType);

            if ($position === 'before') {
                $newNode->moveBefore($referenceNode);
            } else {
                $newNode->moveAfter($referenceNode);
            }
        }

        if (isset($nodeData['properties']) && is_array($nodeData['properties'])) {
            foreach ($nodeData['properties'] as $propertyName => $propertyValue) {
                $newNode->setProperty($propertyName, $propertyValue);
            }
        }

        return $newNode;
    }