Produce more hands for the work needed

@return void
493210
private function familyPlanning()
    {
        list($total, $available) = $this->countWorkers();
        if ($this->shutdownGracefully) {
            if ($total > 0) {
                $this->verboseOutput("<info>Shutting down</info> $total remaining children");
                foreach ($this->family as $cnr => $child) {
                    $this->verboseOutput("<info>Child: $cnr </info>" . $child->status);
                }
                $this->tellChildrenToPrepareForBed();

            } else {
                $this->keepWorking = false;
            }
            return;
        }
        list($shouldHaveLessWorkers, $shouldHaveMoreWorkers) = $this->moreOrLess($total, $available);
        if ($shouldHaveMoreWorkers) {
            $this->family[] = $this->spawnChild();
        }
        if ($shouldHaveLessWorkers) {
            //find one of the family members not doing anything and cap it!
            if ($this->findDisposableWorkers()) {
                //we found one
                $this->verboseOutput("<info>Found a disposable worker</info>");
            }
        }
    }
709879
protected function spawnMinimumWorkers()
    {
        $this->logger->debug('verify that the minimum number ['.$this->min_children.'] of workers are running', [
            'category' => get_class($this),
        ]);

        for ($i = $this->count(); $i < $this->min_children; ++$i) {
            $this->spawnWorker();
        }
    }
1038
protected function _handle()
    {
        list($finder, $options) = $this->_extractFinder();
        $query = $this->_table()->find($finder, $options);
        $subject = $this->_subject(['success' => true, 'query' => $query]);

        $this->_trigger('beforePaginate', $subject);
        $items = $this->_controller()->paginate($subject->query);
        $subject->set(['entities' => $items]);

        $this->_trigger('afterPaginate', $subject);
        $this->_trigger('beforeRender', $subject);
    }
355749
public function next()
    {
        if (!isset($this->tokens[$this->position])) {
            throw new SyntaxError('Unexpected end of expression', $this->current->cursor);
        }

        ++$this->position;

        $this->current = $this->tokens[$this->position];
    }
567553
protected function assemble()
    {
        $this->push('DELETE FROM');
        $this->pushTable();
        $this->pushWhere();
        $this->pushOrder();
        $this->pushLimit();

        $this->query = join(' ', $this->parts);
    }
674
protected function job(): void
    {
        CorporationDivision::where('corporation_id', $this->getCorporationId())->get()
            ->each(function ($division) {

                // retrieve last known entry for the current division and active corporation
                $last_known_entry = CorporationWalletJournal::where('corporation_id', $this->getCorporationId())
                                                            ->where('division', $division->division)
                                                            ->orderBy('date', 'desc')
                                                            ->first();

                $this->last_known_entry_id = is_null($last_known_entry) ? 0 : $last_known_entry->id;

                // Perform a journal walk backwards to get all of the
                // entries as far back as possible. When the response from
                // ESI is empty, we can assume we have everything.
                while (true) {

                    $journal = $this->retrieve([
                        'corporation_id' => $this->getCorporationId(),
                        'division'       => $division->division,
                    ]);

                    if ($journal->isCachedLoad()) return;

                    $entries = collect($journal);

                    // If we have no more entries, break the loop.
                    if ($entries->count() === 0)
                        break;

                    $entries->chunk(1000)->each(function ($chunk) use ($division) {

                        // if we've reached the last known entry - abort the process
                        if ($this->at_last_entry)
                            return false;

                        // if we have reached the last known entry, exclude all entries which are lower or equal to the
                        // last known entry and flag the reached status.
                        if ($chunk->where('id', $this->last_known_entry_id)->isNotEmpty()) {
                            $chunk = $chunk->where('id', '>', $this->last_known_entry_id);

                            $this->at_last_entry = true;
                        }

                        $records = $chunk->map(function ($entry, $key) use ($division) {

                            return [
                                'corporation_id'  => $this->getCorporationId(),
                                'division'        => $division->division,
                                'id'              => $entry->id,
                                'date'            => carbon($entry->date),
                                'ref_type'        => $entry->ref_type,
                                'first_party_id'  => $entry->first_party_id ?? null,
                                'second_party_id' => $entry->second_party_id ?? null,
                                'amount'          => $entry->amount ?? null,
                                'balance'         => $entry->balance ?? null,
                                'reason'          => $entry->reason ?? null,
                                'tax_receiver_id' => $entry->tax_receiver_id ?? null,
                                'tax'             => $entry->tax ?? null,
                                // introduced in v4
                                'description'     => $entry->description,
                                'context_id'      => $entry->context_id ?? null,
                                'context_id_type' => $entry->context_id_type ?? null,
                                'created_at'      => carbon(),
                                'updated_at'      => carbon(),
                            ];
                        });

                        CorporationWalletJournal::insertIgnore($records->toArray());
                    });

                    // in case the last known entry has been reached or we non longer have pages, terminate the job.
                    if (! $this->nextPage($journal->pages) || $this->at_last_entry)
                        break;
                }

                // Reset the page for the next wallet division.
                $this->page = 1;

                // Reset the last known entry for the next wallet division.
                $this->last_known_entry_id = 0;

                // Reset the last known entry status for the next wallet division.
                $this->at_last_entry = false;
            });
    }
865049
protected function job(): void
    {
        // Get the assets for this character, chunked in a number of blocks
        // that the endpoint will accept.
        CorporationAsset::join('invTypes', 'type_id', '=', 'typeID')
            ->join('invGroups', 'invGroups.groupID', '=', 'invTypes.groupID')
            ->where('corporation_id', $this->getCorporationId())
            ->where('is_singleton', true)// only singleton items may be named
            // it seems only items from that categories can be named
            // 2  : Celestial
            // 6  : Ship
            // 22 : Deployable
            // 23 : Starbase
            // 46 : Orbitals
            // 65 : Structure
            ->whereIn('categoryID', [2, 6, 22, 23, 46, 65])// it seems only items from that categories can be named
            ->select('item_id')
            ->chunk($this->item_id_limit, function ($item_ids) {

                $this->request_body = $item_ids->pluck('item_id')->all();

                $names = $this->retrieve([
                    'corporation_id' => $this->getCorporationId(),
                ]);

                collect($names)->each(function ($name) {

                    // "None" seems to indidate that no name is set.
                    if ($name->name === 'None')
                        return;

                    CorporationAsset::where('corporation_id', $this->getCorporationId())
                        ->where('item_id', $name->item_id)
                        ->update(['name' => $name->name]);
                });
            });
    }
300373
protected function job(): void
    {
        $mining_extractions = $this->retrieve([
            'corporation_id' => $this->getCorporationId(),
        ]);

        if ($mining_extractions->isCachedLoad()) return;

        collect($mining_extractions)->each(function ($extraction) {

            CorporationIndustryMiningExtraction::firstOrNew([
                'corporation_id' => $this->getCorporationId(),
                'structure_id'   => $extraction->structure_id,
            ])->fill([
                'extraction_start_time' => carbon($extraction->extraction_start_time),
                'moon_id'               => $extraction->moon_id,
                'chunk_arrival_time'    => carbon($extraction->chunk_arrival_time),
                'natural_decay_time'    => carbon($extraction->natural_decay_time),
            ])->save();
        });
    }
1145059
public function proccess()
    {
        foreach ($this->runningJobs as $jobData) {
            $this->isRunning($jobData->job);
        }

        foreach ($this->pendingJobs as $job) {
            $this->start($job);
        }
    }
988745
protected function inputEndHandler(): void
    {
        $this->input['value'] = $this->text;
        if (!isset($this->data['inputs'])) {
            $this->data['inputs'] = [];
        }
        $this->data['inputs'][] = $this->input;
        $this->text             = '';
    }
84741
protected function job(): void
    {
        while (true) {

            $customs_offices = $this->retrieve([
                'corporation_id' => $this->getCorporationId(),
            ]);

            if ($customs_offices->isCachedLoad()) return;

            collect($customs_offices)->each(function ($customs_office) {

                CorporationCustomsOffice::firstOrNew([
                    'corporation_id' => $this->getCorporationId(),
                    'office_id'      => $customs_office->office_id,
                ])->fill([
                    'system_id'                   => $customs_office->system_id,
                    'reinforce_exit_start'        => $customs_office->reinforce_exit_start,
                    'reinforce_exit_end'          => $customs_office->reinforce_exit_end,
                    'corporation_tax_rate'        => $customs_office->corporation_tax_rate ?? null,
                    'allow_alliance_access'       => $customs_office->allow_alliance_access,
                    'alliance_tax_rate'           => $customs_office->alliance_tax_rate ?? null,
                    'allow_access_with_standings' => $customs_office->allow_access_with_standings,
                    'standing_level'              => $customs_office->standing_level ?? null,
                    'excellent_standing_tax_rate' => $customs_office->excellent_standing_tax_rate ?? null,
                    'good_standing_tax_rate'      => $customs_office->good_standing_tax_rate ?? null,
                    'neutral_standing_tax_rate'   => $customs_office->neutral_standing_tax_rate ?? null,
                    'bad_standing_tax_rate'       => $customs_office->bad_standing_tax_rate ?? null,
                    'terrible_standing_tax_rate'  => $customs_office->terrible_standing_tax_rate ?? null,
                ])->save();

                $this->known_structures->push($customs_office->office_id);

            });

            if (! $this->nextPage($customs_offices->pages))
                break;
        }

        // Cleanup customs offices that were not in the response.
        CorporationCustomsOffice::where('corporation_id', $this->getCorporationId())
            ->whereNotIn('office_id', $this->known_structures->flatten()->all())
            ->delete();
    }
396886
protected function job(): void
    {
        $member_titles = $this->retrieve([
            'corporation_id' => $this->getCorporationId(),
        ]);

        if ($member_titles->isCachedLoad()) return;

        collect($member_titles)->filter(function ($member) {

            // Filter out members that do not have any titles.
            return count($member->titles) > 0;

        })->each(function ($member) {

            // Attach each title to the member
            collect($member->titles)->each(function ($title) use ($member) {

                CorporationMemberTitle::firstOrCreate([
                    'corporation_id' => $this->getCorporationId(),
                    'character_id'   => $member->character_id,
                    'title_id'       => $title,
                ]);
            });
        });

        // Cleanup members of this corporation that may no longer have any titles.
        CorporationMemberTitle::where('corporation_id', $this->getCorporationId())
            ->whereNotIn('character_id', collect($member_titles)->filter(function ($member) {

                return count($member->titles) > 0;

            })->pluck('character_id')->flatten()->all())
            ->delete();
    }
192372
public function yieldify()
    {
        foreach ($this->storage as $key => $value) {
            yield (object) [
                'value' => $value,
                'key' => $key,
                'done' => false
            ];
        }

        yield (object) [
            'value' => null,
            'key' => null,
            'done' => true
        ];
    }
728468
private function fillRunQueue()
    {
        $opts = $this->options;
        while (\count($this->pending) && \count($this->running) < $opts->processes) {
            $tokenData = $this->getNextAvailableToken();
            if ($tokenData !== false) {
                $this->acquireToken($tokenData['token']);
                $env = ['TEST_TOKEN' => $tokenData['token'], 'UNIQUE_TEST_TOKEN' => $tokenData['unique']] + Habitat::getAll();
                $this->running[$tokenData['token']] = array_shift($this->pending)->run($opts->phpunit, $opts->filtered, $env, $opts->passthru, $opts->passthruPhp);
                if ($opts->verbose) {
                    $cmd = $this->running[$tokenData['token']];
                    echo "\nExecuting test via: {$cmd->getLastCommand()}\n";
                }
            }
        }
    }
441101
protected function assemble()
    {
        $this->push('SELECT');
        $this->pushDistinct();
        $this->pushColumns();
        $this->push('FROM');
        $this->pushTable();
        $this->pushHint();
        $this->pushJoin();
        $this->pushWhere();
        $this->pushGroup();
        $this->pushOrder();
        $this->pushLimit();
    }
46113
public function fill()
    {
        $languages = $this->languageRepository->activeLanguages();
        $this->initPages($languages);
        $this->initBasePages($languages);
    }
299545
protected function job(): void
    {
        $empty_contracts = CorporationContract::join('contract_details',
            'corporation_contracts.contract_id', '=',
            'contract_details.contract_id')
            ->where('corporation_id', $this->getCorporationId())
            ->where('type', '<>', 'courier')
            ->where('status', '<>', 'deleted')
            ->where('volume', '>', 0)
            ->whereNotIn('corporation_contracts.contract_id', function ($query) {

                $query->select('contract_id')
                    ->distinct()
                    ->from((new ContractItem)->getTable());

            })
            ->pluck('corporation_contracts.contract_id');

        $empty_contracts->each(function ($contract_id) {

            $this->iteration_count++;

            try {
                $items = $this->retrieve([
                    'corporation_id' => $this->getCorporationId(),
                    'contract_id' => $contract_id,
                ]);

                if ($items->isCachedLoad()) return;

                collect($items)->each(function ($item) use ($contract_id) {

                    ContractItem::upsert([
                        'contract_id' => $contract_id,
                        'record_id' => $item->record_id,
                        'type_id' => $item->type_id,
                        'quantity' => $item->quantity,
                        'raw_quantity' => $item->raw_quantity ?? null,
                        'is_singleton' => $item->is_singleton,
                        'is_included' => $item->is_included,
                    ], [
                        'contract_id', 'record_id',
                    ]);
                });

                // Check if we should be stopping this job all together.
                // The next time a job is queued it will just continue
                // where it left off.
                if ($this->job_start_time->copy()->addSeconds($this->max_job_runtime) < carbon('now'))
                    return false;

                // Check if we should be sleeping. This should be true if we
                // have made 20 requests in the last 10 seconds.
                // If the time we started, plus 10 seconds is more than the current
                // time, wait for the remainder of the time.
                if ($this->iteration_count >= $this->max_cycle_requests &&
                    $this->cycle_start_time->copy()->addSeconds($this->cycle_duration) < carbon('now')) {

                    $wait_duration = $this->cycle_start_time->copy()->addSeconds($this->cycle_duration)
                        ->diffInSeconds(carbon('now'));

                    sleep($wait_duration);

                    // Reset the cycle start time as well as the iteration count.
                    $this->cycle_start_time = carbon('now');
                    $this->iteration_count = 0;
                }

                // Check if we should just reset the iteration & cycle count as a result of
                // us not using the full 20 requests in a 10 second window.
                if ($this->cycle_start_time->copy()->addSeconds($this->cycle_duration) < carbon('now')) {

                    $this->cycle_start_time = carbon('now');
                    $this->iteration_count = 0;

                }
            } catch (RequestFailedException $e) {
                if (strtolower($e->getError()) == 'contract not found!') {
                    ContractDetail::where('contract_id', $contract_id)
                                  ->update([
                                      'status' => 'deleted',
                                  ]);

                    return;
                }

                throw $e;
            }
        });
    }