Creates batches by grouping commands by their associated client
{@inheritdoc}
515863
public function createBatches(\SplQueue $queue)
    {
        $groups = new \SplObjectStorage();
        foreach ($queue as $item) {
            if (!$item instanceof CommandInterface) {
                throw new InvalidArgumentException('All items must implement Guzzle\Service\Command\CommandInterface');
            }
            $client = $item->getClient();
            if (!$groups->contains($client)) {
                $groups->attach($client, new \ArrayObject(array($item)));
            } else {
                $groups[$client]->append($item);
            }
        }

        $batches = array();
        foreach ($groups as $batch) {
            $batches = array_merge($batches, array_chunk($groups[$batch]->getArrayCopy(), $this->batchSize));
        }

        return $batches;
    }
364129
@Override
    protected HystrixCommand<List<Object>> createCommand(
            Collection<CollapsedRequest<Object, Object>> collapsedRequests) {
       return new BatchHystrixCommand(HystrixCommandBuilderFactory.getInstance().create(metaHolder, collapsedRequests));
    }
1254037
def _select_batched(self, table, cols, num_rows, limit, queries_per_batch=3, execute=True):
        """"""
        # Execute select queries in small batches to avoid connection timeout
        commands, offset = [], 0
        while num_rows > 0:
            # Use number of rows as limit if num_rows < limit
            _limit = min(limit, num_rows)

            # Execute select_limit query
            commands.append(self._select_limit_statement(table, cols=cols, offset=offset, limit=limit))
            offset += _limit
            num_rows += -_limit

        # Execute commands
        if execute:
            rows = []
            til_reconnect = queries_per_batch
            for c in commands:
                if til_reconnect == 0:
                    self.disconnect()
                    self.reconnect()
                    til_reconnect = queries_per_batch
                rows.extend(self.fetch(c, False))
                til_reconnect += -1
            del commands
            return rows
        # Return commands
        else:
            return commands
685477
function executeBatch(bulkOperation, batch, options, callback) {
  function resultHandler(err, result) {
    // Error is a driver related error not a bulk op error, terminate
    if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
      return handleCallback(callback, err);
    }

    // If we have and error
    if (err) err.ok = 0;
    if (err instanceof MongoWriteConcernError) {
      return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, false, err, callback);
    }
    handleCallback(
      callback,
      null,
      mergeBatchResults(false, batch, bulkOperation.s.bulkResult, err, result)
    );
  }

  bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
}
741806
public function createBinaryBatch(Api\MtBatchBinarySmsCreate $batch)
    {
        $json = Serialize::binaryBatch($batch);
        $result = $this->_post($this->_url('/batches'), $json);
        return Deserialize::batchResponse($result);
    }
898861
public function apply($perBatch = 50)
    {
        $this->iterated = $this->batches = $batches = 0;
        $that = $this;
        $it = $this->iterator;
        $callback = $this->callback;

        $batch = BatchBuilder::factory()
            ->createBatchesWith(new BatchSizeDivisor($perBatch))
            ->transferWith(new BatchClosureTransfer(function (array $batch) use ($that, $callback, &$batches, $it) {
                $batches++;
                $that->dispatch('iterator_batch.before_batch', array('iterator' => $it, 'batch' => $batch));
                call_user_func_array($callback, array($it, $batch));
                $that->dispatch('iterator_batch.after_batch', array('iterator' => $it, 'batch' => $batch));
            }))
            ->autoFlushAt($perBatch)
            ->build();

        $this->dispatch('iterator_batch.created_batch', array('batch' => $batch));

        foreach ($this->iterator as $resource) {
            $this->iterated++;
            $batch->add($resource);
        }

        $batch->flush();
        $this->batches = $batches;

        return $this->iterated;
    }
1341301
function executeCommands(bulkOperation, options, callback) {
  if (bulkOperation.s.batches.length === 0) {
    return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult));
  }

  // Ordered execution of the command
  const batch = bulkOperation.s.batches.shift();

  function resultHandler(err, result) {
    // Error is a driver related error not a bulk op error, terminate
    if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
      return handleCallback(callback, err);
    }

    // If we have and error
    if (err) err.ok = 0;
    if (err instanceof MongoWriteConcernError) {
      return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, true, err, callback);
    }

    // Merge the results together
    const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
    const mergeResult = mergeBatchResults(true, batch, bulkOperation.s.bulkResult, err, result);
    if (mergeResult != null) {
      return handleCallback(callback, null, writeResult);
    }

    if (bulkOperation.handleWriteError(callback, writeResult)) return;

    // Execute the next command in line
    executeCommands(bulkOperation, options, callback);
  }

  bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
}
1121370
def simple_generate_batch(klass, create, size, **kwargs):
    """"""
    return make_factory(klass, **kwargs).simple_generate_batch(create, size)
295214
public function create(array $objects) {
        $requests = [];

        foreach ($objects as $object) {
            $requests[] = [
                'method' => 'cmdb.object.create',
                'params' => $object
            ];
        }

        $result = $this->api->batchRequest($requests);

        $objectIDs = [];

        foreach ($result as $object) {
            $objectIDs[] = $object['id'];
        }

        return $objectIDs;
    }
1031284
public static function send($client, $batchParts)
    {
        /** @var AbstractHttpRequest $request */
        $request         = new $client->requestClass($client);
        $request->client = $client;

        return $request->sendBatch($batchParts);
    }
489458
public function batchMove($srcBucket, $keys, $destBucket, $prefix='', $suffix='', $force=true){
        $keyPairs = array();
        foreach ($keys as $key) {
            $keyPairs[$key] = $prefix."_".$key."_".$suffix;
        }
        $ops = $this->bucketManager->buildBatchMove($srcBucket, $keyPairs, $destBucket, $force);
        list($ret, $err) = $this->bucketManager->batch($ops);
        if($err){
            return $this->error($err->message(), ['errorCode'=>$err->code()]);
        }
        return $this->success('操作成功', $ret);
    }
657778
function batch(ops) {
  var commands = [], url;

  for (let i = 0; i < ops.length; i++) {
    let { key, value } = ops[i],
      { table, schema } = findSchemaAndTable(key),
      map = columnToValueMap('id', key);

    columnToValueMap('data', wrapJSONStringInObject(key, value), map);

    // add url column to map if putting a uri
    if (isUri(key)) {
      url = decode(key.split('/_uris/').pop());

      columnToValueMap('url', url, map);
    }

    commands.push(onConflictPut(map, schema, table).then(() => map.data));
  }

  return Promise.all(commands);
}
777058
public function batchAction()
    {
        $request = $this->getRequest();
        $restMethod = $this->getRestMethod();

        if ('POST' !== $restMethod) {
            throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod));
        }

        // check the csrf token
        $this->validateCsrfToken('sonata.batch');

        $confirmation = $request->get('confirmation', false);

        if ($data = json_decode((string) $request->get('data'), true)) {
            $action = $data['action'];
            $idx = $data['idx'];
            $allElements = $data['all_elements'];
            $request->request->replace(array_merge($request->request->all(), $data));
        } else {
            $request->request->set('idx', $request->get('idx', []));
            $request->request->set('all_elements', $request->get('all_elements', false));

            $action = $request->get('action');
            $idx = $request->get('idx');
            $allElements = $request->get('all_elements');
            $data = $request->request->all();

            unset($data['_sonata_csrf_token']);
        }

        // NEXT_MAJOR: Remove reflection check.
        $reflector = new \ReflectionMethod($this->admin, 'getBatchActions');
        if ($reflector->getDeclaringClass()->getName() === \get_class($this->admin)) {
            @trigger_error('Override Sonata\AdminBundle\Admin\AbstractAdmin::getBatchActions method'
                .' is deprecated since version 3.2.'
                .' Use Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions instead.'
                .' The method will be final in 4.0.', E_USER_DEPRECATED
            );
        }
        $batchActions = $this->admin->getBatchActions();
        if (!\array_key_exists($action, $batchActions)) {
            throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
        }

        $camelizedAction = Inflector::classify($action);
        $isRelevantAction = sprintf('batchAction%sIsRelevant', $camelizedAction);

        if (method_exists($this, $isRelevantAction)) {
            $nonRelevantMessage = \call_user_func([$this, $isRelevantAction], $idx, $allElements, $request);
        } else {
            $nonRelevantMessage = 0 !== \count($idx) || $allElements; // at least one item is selected
        }

        if (!$nonRelevantMessage) { // default non relevant message (if false of null)
            $nonRelevantMessage = 'flash_batch_empty';
        }

        $datagrid = $this->admin->getDatagrid();
        $datagrid->buildPager();

        if (true !== $nonRelevantMessage) {
            $this->addFlash(
                'sonata_flash_info',
                $this->trans($nonRelevantMessage, [], 'SonataAdminBundle')
            );

            return $this->redirectToList();
        }

        $askConfirmation = $batchActions[$action]['ask_confirmation'] ??
            true;

        if ($askConfirmation && 'ok' !== $confirmation) {
            $actionLabel = $batchActions[$action]['label'];
            $batchTranslationDomain = $batchActions[$action]['translation_domain'] ??
                $this->admin->getTranslationDomain();

            $formView = $datagrid->getForm()->createView();
            $this->setFormTheme($formView, $this->admin->getFilterTheme());

            // NEXT_MAJOR: Remove these lines and use commented lines below them instead
            $template = !empty($batchActions[$action]['template']) ?
                $batchActions[$action]['template'] :
                $this->admin->getTemplate('batch_confirmation');
            // $template = !empty($batchActions[$action]['template']) ?
            //     $batchActions[$action]['template'] :
            //     $this->templateRegistry->getTemplate('batch_confirmation');

            return $this->renderWithExtraParams($template, [
                'action' => 'list',
                'action_label' => $actionLabel,
                'batch_translation_domain' => $batchTranslationDomain,
                'datagrid' => $datagrid,
                'form' => $formView,
                'data' => $data,
                'csrf_token' => $this->getCsrfToken('sonata.batch'),
            ], null);
        }

        // execute the action, batchActionXxxxx
        $finalAction = sprintf('batchAction%s', $camelizedAction);
        if (!method_exists($this, $finalAction)) {
            throw new \RuntimeException(sprintf('A `%s::%s` method must be callable', \get_class($this), $finalAction));
        }

        $query = $datagrid->getQuery();

        $query->setFirstResult(null);
        $query->setMaxResults(null);

        $this->admin->preBatchAction($action, $query, $idx, $allElements);

        if (\count($idx) > 0) {
            $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
        } elseif (!$allElements) {
            $this->addFlash(
                'sonata_flash_info',
                $this->trans('flash_batch_no_elements_processed', [], 'SonataAdminBundle')
            );

            return $this->redirectToList();
        }

        return \call_user_func([$this, $finalAction], $query, $request);
    }
1208024
public function createBatches(\SplQueue $queue)
    {
        // Create batches by client objects
        $groups = new \SplObjectStorage();
        foreach ($queue as $item) {
            if (!$item instanceof RequestInterface) {
                throw new InvalidArgumentException('All items must implement Guzzle\Http\Message\RequestInterface');
            }
            $client = $item->getClient();
            if (!$groups->contains($client)) {
                $groups->attach($client, array($item));
            } else {
                $current = $groups[$client];
                $current[] = $item;
                $groups[$client] = $current;
            }
        }

        $batches = array();
        foreach ($groups as $batch) {
            $batches = array_merge($batches, array_chunk($groups[$batch], $this->batchSize));
        }

        return $batches;
    }
1140233
def make_batches(paths: Sequence[Path], batch_size: int) -> List[Sequence[Path]]:
    

    return [paths[i:i+batch_size]
            for i in range(0, len(paths), batch_size)]
1306989
public function flush(?int $batchSize = null): \Generator
    {
        if (null === $this->notifications || empty($this->notifications)) {
            yield from [];
            return;
        }

        if (null === $batchSize) {
            $batchSize = $this->defaultOptions['batchSize'];
        }

        $batches = array_chunk($this->notifications, $batchSize);

        // reset queue
        $this->notifications = [];

        foreach ($batches as $batch) {
            // for each endpoint server type
            $requests = $this->prepare($batch);

            $promises = [];

            foreach ($requests as $request) {
                $promises[] = $this->client->sendAsync($request)
                    ->then(function ($response) use ($request) {
                        /** @var ResponseInterface $response * */
                        return new MessageSentReport($request, $response);
                    })
                    ->otherwise(function ($reason) {
                        /** @var RequestException $reason **/
                        return new MessageSentReport($reason->getRequest(), $reason->getResponse(), false, $reason->getMessage());
                    });
            }

            foreach ($promises as $promise) {
                yield $promise->wait();
            }
        }

        if ($this->reuseVAPIDHeaders) {
            $this->vapidHeaders = [];
        }
    }
338924
protected function segmentBatches($source)
    {
        // Measure batch_size
        $batchSize = static::config()->get('batch_size');
        if ($batchSize === 0) {
            return array($source);
        }
        $softCap = static::config()->get('batch_soft_cap');

        // Clear batches
        $batches = array();
        $current = array();
        $currentSize = 0;

        // Build batches from data
        foreach ($source as $base => $statefulids) {
            if (!$statefulids) {
                continue;
            }

            foreach ($statefulids as $stateKey => $statefulid) {
                $state = $statefulid['state'];
                $ids = $statefulid['ids'];
                if (!$ids) {
                    continue;
                }

                // Extract items from $ids until empty
                while ($ids) {
                    // Estimate maximum number of items to take for this iteration, allowing for the soft cap
                    $take = $batchSize - $currentSize;
                    if (count($ids) <= $take + $softCap) {
                        $take += $softCap;
                    }
                    $items = array_slice($ids, 0, $take, true);
                    $ids = array_slice($ids, count($items), null, true);

                    // Update batch
                    $currentSize += count($items);
                    $merge = array(
                        $base => array(
                            $stateKey => array(
                                'state' => $state,
                                'ids' => $items
                            )
                        )
                    );
                    $current = $current ? array_merge_recursive($current, $merge) : $merge;
                    if ($currentSize >= $batchSize) {
                        $batches[] = $current;
                        $current = array();
                        $currentSize = 0;
                    }
                }
            }
        }
        // Add incomplete batch
        if ($currentSize) {
            $batches[] = $current;
        }

        return $batches;
    }