Insert byes group alternated with full groups.

@param Collection $fighters - List of fighters
@param integer $numByeTotal - Quantity of byes to insert
@return Collection - Full list of fighters including byes
426235
private function insertByes(Collection $fighters, $numByeTotal)
    {
        $bye = $this->createByeFighter();
        $groupSize = $this->firstRoundGroupSize();
        $frequency = $groupSize != 0
            ? (int)floor(count($fighters) / $groupSize / $groupSize)
            : -1;
        if ($frequency < $groupSize) {
            $frequency = $groupSize;
        }

        $newFighters = new Collection();
        $count = 0;
        $byeCount = 0;
        foreach ($fighters as $fighter) {
            // Each $frequency(3) try to insert $groupSize byes (3)
            // Not the first iteration, and at the good frequency, and with $numByeTotal as limit
            if ($this->shouldInsertBye($frequency, $count, $byeCount, $numByeTotal)) { //
                for ($i = 0; $i < $groupSize; $i++) {
                    if ($byeCount < $numByeTotal) {
                        $newFighters->push($bye);
                        $byeCount++;
                    }
                }
            }
            $newFighters->push($fighter);
            $count++;
        }
        return $newFighters;
    }
590110
public static function add($spacing = 0, $iscustom = false)
    {
        if (!$spacing) {
            $spacing = 0; // just in case
        }
        if (!$iscustom) {
            $iscustom = 0;
        } else {
            $iscustom = 1;
        }

        $db = Loader::db();
        $db->Execute('insert into AreaLayouts (arLayoutSpacing, arLayoutIsCustom, arLayoutUsesThemeGridFramework) values (?, ?, ?)', array($spacing, $iscustom, 0));
        $arLayoutID = $db->Insert_ID();
        if ($arLayoutID) {
            $ar = static::getByID($arLayoutID);

            return $ar;
        }
    }
975557
protected function getByeGroup($fighters)
    {
        $fighterCount = $fighters->count();
        $firstRoundGroupSize = $this->firstRoundGroupSize(); // Get the size of groups in the first round (2,3,4)
        // Max number of fighters for the first round
        $treeSize = $this->getTreeSize($fighterCount, $firstRoundGroupSize);
        $byeCount = $treeSize - $fighterCount;
        return $this->createByeGroup($byeCount);
    }
434858
public function sendTextMsg($content, array $atMobiles = [], $isAtAll = false)
    {
        $query = [
            'msgtype' => 'text',
            'text' => [
                'content' => $content,
            ],
            'at' => [
                'isAtAll' => $isAtAll
            ],
        ];
        if (is_array($atMobiles) && count($atMobiles)>0) {
            $query['at']['atMobiles'] = $atMobiles;
        }
        return $this->sendMsg($query);
    }
148945
public function createByeGroup($groupSize): Collection
    {
        $byeFighter = $this->createByeFighter();
        $group = new Collection();
        for ($i = 0; $i < $groupSize; $i++) {
            $group->push($byeFighter);
        }

        return $group;
    }
331516
public function syncTeams($fighters)
    {
        $this->teams()->detach();
        foreach ($fighters as $fighter) {
            if ($fighter != null) {
                $this->teams()->attach($fighter);
            } else {
                // Insert row manually
                DB::table('fighters_group_team')->insertGetId(
                    ['team_id' => null, 'fighters_group_id' => $this->id]
                );
            }
        }
    }
1095888
protected function fillForm($buttonText, $inputs = [])
    {
        if (! is_string($buttonText)) {
            $inputs = $buttonText;

            $buttonText = null;
        }

        return $this->getForm($buttonText)->setValues($inputs);
    }
317769
public function toCollection($nullValue = null, $calculateFormulas = false, $formatData = true): Collection
    {
        return new Collection($this->toArray($nullValue, $calculateFormulas, $formatData));
    }
669455
private
    function repart($fighterGroups, $max)
    {
        $fighters = new Collection();
        for ($i = 0; $i < $max; $i++) {
            foreach ($fighterGroups as $fighterGroup) {
                $fighter = $fighterGroup->values()->get($i);
                if ($fighter != null) {
                    $fighters->push($fighter);
                }
            }
        }
        return $fighters;
    }
119048
public static function saveFights(Collection $groups, $numGroup = 1)
    {
        $competitor1 = $competitor2 = null;
        $order = 1;

        foreach ($groups as $group) {
            $fighters = $group->getFightersWithBye();

            $fighter1 = $fighters->get(0);
            $fighter2 = $fighters->get(1);
            $fighter3 = $fighters->get(2);

            switch ($numGroup) {
                case 1:
                    $competitor1 = $fighter1;
                    $competitor2 = $fighter2;
                    break;
                case 2:
                    $competitor1 = $fighter2;
                    $competitor2 = $fighter3;
                    break;
                case 3:
                    $competitor1 = $fighter3;
                    $competitor2 = $fighter1;
                    break;
            }
            $order = self::saveFight($group, $competitor1, $competitor2, $order);
        }
    }
781662
protected function addTableAction($action, $row, $btn)
    {
        if (empty($this->tableActions)) {
            $this->tableActions = new Collection();
        }
        $path = uri();
        Event::fire('datatables:' . $path . ':before.action.' . $action, [$this->tableActions, $row]);
        Event::fire(new BeforeTableAction($path, $action, $row, $this->tableActions));
        $this->tableActions->push($btn);
        Event::fire('datatables:' . $path . ':after.action.' . $action, [$this->tableActions, $row]);
        Event::fire(new AfterTableAction($path, $action, $row, $this->tableActions));
        Event::fire('datatables.' . get_class($this) . '.after.action.' . $action, [$this->tableActions, $row]);
        return $this;
    }
414086
public static function deleteWinners($campaignId, $isAll = TRUE) {
    $connection = \Drupal::service('database');
    /** @var \Drupal\Core\Database\Query\Select $query */
    $query = $connection->select('openy_campaign_winner', 'w');
    $query->fields('w', ['id']);
    $query->join('openy_campaign_member_campaign', 'mc', 'w.member_campaign = mc.id');

    // Delete only winners with defined activity.
    if (!$isAll) {
      $query->condition('w.activity', 0, '!=');
    }
    $query->condition('mc.campaign', $campaignId);

    $winnerIDs = $query->execute()->fetchCol();

    /** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
    $storage = \Drupal::service('entity_type.manager')->getStorage('openy_campaign_winner');
    $winners = $storage->loadMultiple($winnerIDs);
    $storage->delete($winners);
  }
1355435
public function insertToken(string $lockTo = '', bool $echo = true): string
    {
        $token_array = $this->getTokenArray($lockTo);
        $ret = \implode(
            \array_map(
                function(string $key, string $value): string {
                    return "<!--\n-->".
                        "<input type=\"hidden\"" .
                        " name=\"" . $key . "\"" .
                        " value=\"" . self::noHTML($value) . "\"" .
                        " />";
                },
                \array_keys($token_array),
                $token_array
            )
        );
        if ($echo) {
            echo $ret;
            return '';
        }
        return $ret;
    }
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;
    }
263996
public function insert_many($data, $skip_validation = FALSE)
    {
        $ids = array();

        foreach ($data as $key => $row)
        {
            $ids[] = $this->insert($row, $skip_validation, ($key == count($data) - 1));
        }

        return $ids;
    }
895466
public function campaignContactsExportAction($campaignId, $dateFrom, $dateTo)
    {
        $start = 0;
        $limit = 1000;

        if (empty($campaignId)) {
            return $this->notFound('mautic.campaignwatch.export.notfound');
        }

        $campaignId = (int) $campaignId;
        $campaign   = $this->getModel('campaign')->getEntity($campaignId);

        if (!$this->get('mautic.security')->hasEntityAccess(
            'campaign:campaigns:viewown',
            'campaign:campaigns:viewother',
            $campaign->getCreatedBy()
        )) {
            return $this->accessDenied();
        }
        $entityManager = $this->get('doctrine.orm.entity_manager');

        list($dateFrom, $dateTo) = $this->convertDateParams($dateFrom, $dateTo);
        $contactIds              = $this->getCampaignLeadIdsForExport($campaignId, $dateFrom, $dateTo, $start, $limit);

        if (empty($contactIds)) {
            return $this->notFound('mautic.campaignwatch.export.nocontacts');
        }

        //testing
        /** @var OverrideLeadRepository $contactRepo */
        $contactRepo = $this->getModel('lead')->getRepository();

        $fileName = sprintf('ContactsExportFrom%s.csv', str_replace(' ', '', $campaign->getName()));

        $response = new StreamedResponse(
            function () use (
                $contactRepo,
                $entityManager,
                $campaignId,
                $dateFrom,
                $dateTo,
                $start,
                $limit,
                $contactIds
            ) {
                ini_set('max_execution_time', 0);
                $handle = fopen('php://output', 'w');

                while (count($contactIds)) {
                    $fieldNames = [];
                    // adjust $size for memory vs. speed
                    $batches = array_chunk($contactIds, 100);
                    foreach ($batches as $batch) {
                        //$leads = $contactRepo->getEntitiesWithCustomFields('lead', ['ids' => $batch]);
                        $leads = $contactRepo->getEntities(
                            [
                                'ids'              => $batch,
                                '',
                                'withTotalCounts'  => 0,
                                'withChannelRules' => 1,
                                'ignore_paginator' => 1,
                            ]
                        );
                        /**
                         * @var int
                         * @var Lead $lead
                         */
                        foreach ($leads as $id => $lead) {
                            if (empty($fieldNames)) {
                                $fields      = $lead->getFields(true);
                                $columnNames = array_map(
                                    function ($f) {
                                        return $f['label'];
                                    },
                                    $fields
                                );
                                $columnNames = array_merge(['Id', 'IP'], $columnNames);
                                fputcsv($handle, $columnNames);
                                $fieldNames = array_map(
                                    function ($f) {
                                        return $f['alias'];
                                    },
                                    $fields
                                );
                            }
                            $ipAddresses = $lead->getIpAddresses()->last();
                            $ip = !$ipAddresses ? '' : $ipAddresses->getIpAddress();
                            $values = [$id, $ip];
                            foreach ($fieldNames as $fieldName) {
                                $values[] = $lead->getFieldValue($fieldName);
                            }
                            fputcsv($handle, $values);
                        }
                        $entityManager->flush();
                        $entityManager->clear();
                    }
                    $start += count($contactIds);
                    $contactIds = $this->getCampaignLeadIdsForExport(
                        $campaignId,
                        $dateFrom,
                        $dateTo,
                        $start,
                        $limit
                    );
                }

                fclose($handle);
            },
            200,
            [
                'Content-Type'        => 'application/csv; charset=utf-8',
                'Content-Disposition' => 'attachment; filename="'.$fileName.'"',
            ]
        );

        return $response;
    }
464398
protected function chunk(Collection $fightersByEntity)
    {
        if ($this->championship->hasPreliminary()) {
            $fightersGroup = $fightersByEntity->chunk($this->settings->preliminaryGroupSize);
            return $fightersGroup;
        }

        return $fightersByEntity->chunk($fightersByEntity->count());
    }