Insert a batch of tasks into the specified queue. If an error occurs
    during insertion, split the batch and retry until they are successfully
    inserted. Return the number of successfully inserted tasks.
963996
def _insert_tasks(tasks, queue, transactional=False,
                  retry_transient_errors=True,
                  retry_delay=RETRY_SLEEP_SECS):
    
    from google.appengine.api import taskqueue

    if not tasks:
        return 0

    try:
        taskqueue.Queue(name=queue).add(tasks, transactional=transactional)
        return len(tasks)
    except (taskqueue.BadTaskStateError,
            taskqueue.TaskAlreadyExistsError,
            taskqueue.TombstonedTaskError):
        if len(tasks) <= 1:
            # Task has already been inserted, no reason to report an error here.
            return 0

        # If a list of more than one Tasks is given, a raised exception does
        # not guarantee that no tasks were added to the queue (unless
        # transactional is set to True). To determine which tasks were
        # successfully added when an exception is raised, check the
        # Task.was_enqueued property.
        reinsert = _tasks_to_reinsert(tasks, transactional)
        count = len(reinsert)
        inserted = len(tasks) - count
        inserted += _insert_tasks(reinsert[:count / 2], queue, transactional,
                                  retry_transient_errors, retry_delay)
        inserted += _insert_tasks(reinsert[count / 2:], queue, transactional,
                                  retry_transient_errors, retry_delay)

        return inserted
    except taskqueue.TransientError:
        # Always re-raise for transactional insert, or if specified by
        # options.
        if transactional or not retry_transient_errors:
            raise

        reinsert = _tasks_to_reinsert(tasks, transactional)

        # Retry with a delay, and then let any errors re-raise.
        time.sleep(retry_delay)

        taskqueue.Queue(name=queue).add(reinsert, transactional=transactional)
        return len(tasks)
1098911
@Override
    public void requeue(Task task) {
        this.inprocess.remove(task);
        task.incrementAttempts();
        this.queue.add(task);
    }
934493
def _append_task(t):
    
    task_queue = _get_task_queue()
    if t not in task_queue:
        log.debug('Appended new task to the queue: %s.', t)
        task_queue.append(t)
    else:
        log.debug('Did not append duplicate task to the queue: %s.', t)
    return None
465671
function queue (job, value, put) {
      var ts = timestamp()
      var key = toKey(job, ts)

      var id = hash(job+':'+value)
      if(pending[id]) return null //this job is already queued.
      pending[id] = Date.now()

      if(put === false) {
        //return the job to be queued, to include it in a batch insert.
          return {
          type: 'put', 
          key: Buffer.isBuffer(key) ? key : new Buffer(key), 
          value: Buffer.isBuffer(key) ? value : new Buffer(value)
        }
      } else {
        db.put(key, value)
      }
    }
327138
public void submit(Task task,Integer index) {
        task.activate(false);
        taskQueues[index].accept(task);
    }
1318217
synchronized void insertRowInTable(final VoltBulkLoaderRow nextRow) throws InterruptedException {
        m_partitionRowQueue.put(nextRow);
        if (m_partitionRowQueue.size() == m_minBatchTriggerSize) {
            m_es.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (m_partitionRowQueue.size() >= m_minBatchTriggerSize) {
                            loadTable(buildTable(), m_table);
                        }
                    } catch (Exception e) {
                        loaderLog.error("Failed to load batch", e);
                    }
                }
            });
        }
    }
558011
def count(self):
        
        if self._batch:
            raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode")

        if self._result_cache is None:
            query = self._select_query()
            query.count = True
            result = self._execute(query)
            return result[0]['count']
        else:
            return len(self._result_cache)
64502
public void put(QueueData queueData, short msgBatch) // f200337
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "put", new Object[] {queueData, ""+msgBatch});

      synchronized(this)
      {
         if (!ordered && batchesReady == 1)
         {
            // A non-ordered async consumer proxy queue only caches one batch at a time. Therefore
            // if we are trying to put messages on when there is a batch already ready, we
            // messed up.
            SIErrorException e = new SIErrorException(
               nls.getFormattedMessage("ASYNC_BATCH_ALREADY_READY_SICO1031", null, null)
            );

            FFDCFilter.processException(e, CLASS_NAME + ".put",
                                        CommsConstants.ASYNCHPQ_PUT_01, this);

            throw e;
         }

         queue.addLast(queueData);

         // If the data added to the queue was not a chunked message, then we have received an
         // entire message - so update counters etc
         if (!queueData.isChunkedMessage())
         {
            notifyMessageReceived(queueData.isLastInBatch());
         }

      }

      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Put has completed: " + this);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "put");
   }
1082116
async def insert(self, task: Task) -> None:
        ''''''

        if not isinstance(task, Task):
            task = task()

        if task.name not in self.all_tasks:
            task.tasky = self
            self.all_tasks[task.name] = task

            await task.init()

        elif task != self.all_tasks[task.name]:
            raise Exception('Duplicate task %s' % task.name)

        if task.enabled:
            task.task = asyncio.ensure_future(self.start_task(task))
            self.running_tasks.add(task)
        else:
            task.task = None

        return task
636738
public void accept(Task task) {
    	if((activeIndex+1)%2==0)
    	{
    		if(!task.isInQueue0())
    		{
    			taskList[0].offer(task);
    			task.storedInQueue0();
    		}
    	}
    	else
    	{
    		if(!task.isInQueue1())
    		{
    			taskList[1].offer(task);
    			task.storedInQueue1();
    		}
    	}    	    	    
    }
1082520
void put(final AbstractBatchEntry batchEntry) {
    try {
        this.queue.put(batchEntry);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    if (this.queue.size() >= this.actions) {
      this.scheduler.submit(new Runnable() {
        @Override
        public void run() {
          write();
        }
      });
    }
  }
543
public void addTask (ExecutorTask task)
    {
        for (int ii=0, nn=_queue.size(); ii < nn; ii++) {
            ExecutorTask taskOnQueue = _queue.get(ii);
            if (taskOnQueue.merge(task)) {
                return;
            }
        }

        // otherwise, add it on
        _queue.add(task);

        // and perhaps start it going now
        if (!_executingNow) {
            checkNext();
        }
    }
1226575
def insert(queue, items):
    '''
    
    '''
    handle_queue_creation(queue)

    with _conn(commit=True) as cur:
        if isinstance(items, dict):
            items = salt.utils.json.dumps(items)
            cmd = str('''INSERT INTO {0}(data) VALUES('{1}')''').format(queue, items)  # future lint: disable=blacklisted-function
            log.debug('SQL Query: %s', cmd)
            try:
                cur.execute(cmd)
            except psycopg2.IntegrityError as esc:
                return ('Item already exists in this queue. '
                        'postgres error: {0}'.format(esc))
        if isinstance(items, list):
            items = [(salt.utils.json.dumps(el),) for el in items]
            cmd = str("INSERT INTO {0}(data) VALUES (%s)").format(queue)  # future lint: disable=blacklisted-function
            log.debug('SQL Query: %s', cmd)
            try:
                cur.executemany(cmd, items)
            except psycopg2.IntegrityError as esc:
                return ('One or more items already exists in this queue. '
                        'postgres error: {0}'.format(esc))
    return True
1178715
def reenqueue(self, batch):
        """"""
        now = time.time()
        batch.attempts += 1
        batch.last_attempt = now
        batch.last_append = now
        batch.set_retry()
        assert batch.topic_partition in self._tp_locks, 'TopicPartition not in locks dict'
        assert batch.topic_partition in self._batches, 'TopicPartition not in batches'
        dq = self._batches[batch.topic_partition]
        with self._tp_locks[batch.topic_partition]:
            dq.appendleft(batch)
526601
private void batch_insert(Collection<Integer> set, boolean parallel)
    {
        for(int i : set)
            store[size++] = i;
        if(parallel)
            Arrays.parallelSort(store, 0, size);
        else
            Arrays.sort(store, 0, size);
    }
210074
def submitBatches(self, batches):
    
    self._seqid += 1
    future = self._reqs[self._seqid] = concurrent.Future()
    self.send_submitBatches(batches)
    return future
409603
def _add_sub_tasks_to_executor(self, parent_task, parent_task_result):
        
        for sub_task in self.waiting_task_list.get_next_tasks(parent_task.id):
            self.executor.add_task(sub_task, parent_task_result)