Create Queue wrapper

@param {any} [{ concurrency = 5, interval = 500 }={}] options
18561
function Knack({ concurrency = 5, interval = 500, onDone = () => {} }={}) {
  const q = new Queue(concurrency, interval, onDone)
  /**
   * @func knack
   * @template T
   * @param {function(...args): Promise<T>} func
   * @returns {function(...args): Promise<T>}
   */
  const knack = function(func, {
    priority = 50,
    onTimeout = timeouts.none,
    timeout = 30e3,
    repeats = 3 }={}) {
    return (...args) => q.task(func, { priority, onTimeout, timeout, repeats }, ...args)
  }
  knack.once = ({
    priority = 50,
    onTimeout = timeouts.none,
    timeout = 30e3,
    repeats = 3 }={}) => (func, ...args) => q.task(func, { priority, onTimeout, timeout, repeats }, ...args)
  knack.isHalt = false
  knack.halt = () => {
    q.tryNext = () => {}
    q.task = () => {}
    knack.isHalt = true
  }
  Object.defineProperty(knack, 'active', {
    get: () => q.active
  })
  Object.defineProperty(knack, 'concurrency', {
    get: () => q.concurrency
    // set: parallel => q.concurrency = parallel
  })
  Object.defineProperty(knack, 'interval', {
    get: () => q.interval
    // set: delay => q.interval = delay
  })
  knack.timeouts = timeouts
  return knack
}
865830
function(implClass, modClass) {

	var impls = {
		DelayableQueue : [

			/**
			 * Returns a queueable interface to the original object
			 * This allows us to insert delays between chainable method calls using the .wait() method
			 * Currently this is only implemented for the node class, but it should be possible to use this with any object.
			 */
			'wait', function () {

				/**
				 * Queueable object which implements methods from another interface
				 * @param object Context for the callback
				 */
				function QueueableObject(context) {
					this.queue = [];
					this.context = context;
					this.inWork = false;
				}
				
				QueueableObject.prototype = {
					_add: function(func, args) {

						var self = this;

						self.queue.push({type: 'chain', func: func, args: args});
						if (!self.inWork) {
							return self._process();
						}
					},

					/**
					 * Process the queue
					 * Shifts an item off the queue and waits for it to finish
					 */
					_process: function() {

						var self = this, item;

						self.inWork = true;
						
						if (!self.queue.length) {
							return;
						}
						
						item = self.queue.shift();

						if (item.type == 'wait') {
							setTimeout(function(){
								self._process();
							}, item.duration*1000);
						} else {
							self.context = item.func.apply(self.context, item.args);
							self._process();
						}
						return self;
					},

					/**
					 * Updates the current delay timer
					 */
					wait: function(duration) {
						this.queue.push({type: 'wait', duration: duration});
						return this;
					}
				};
				
				return function (duration) {

					var self = this,
						mockObj = new QueueableObject(self);

					/**
					 * Returns an executable function
					 * uses setTimeout and the total queueTimer
					 */
					getQueuedFunction = function(func) {
						return function() {
							mockObj._add(func, arguments);
							return mockObj;
						}
					};

					/**
					 * Wrap all class functions
					 * We can unwrap at the end if the current wait is 0
					 */
					for( var i in self ) {
						if (typeof self[i] != 'function' || i == 'wait' ) { continue; }
						mockObj[i] = getQueuedFunction(self[i]);
					}

					mockObj.wait(duration);
					
					return mockObj;
				}
			}
		]
	};

	modClass[impls[implClass][0]] = impls[implClass][1]();
}
1207073
function processQueue(){
      try {
        // mark queue as processing to avoid concurrency
        processing = true;

        // process queue
        var item;
        while (item = queue.shift())
          item.fn.call(item.context);
      } finally {
        // queue is not processing anymore
        processing = false;

        // if any function in queue than exception was occured,
        // run rest functions in next code frame
        if (queue.length)
          timer = setImmediate(process);
      }
    }
992443
function ordered (ondelay) {
  var clk = 0
  var queue = []

  var checking = 0
  function check () {
    if (checking++) return

    setImmediate(function () {
      var o = queue.shift()
      clk = o[1]
      ondelay(function () {
        checking = 0
        if (queue.length) check()
        o[0]()
      }, o[2])
    })
  }

  function delay (fn, ms) {
    var len = queue.length, i = 0
    while (queue.length === len) {
      if (queue[i]) {
        if (queue[i][1] > clk + ms) {
          queue.splice(i, 0, [fn, clk + ms, ms])
        }
      } else queue.push([fn, clk + ms, ms])
      ++i
    }
    check()
  }

  return delay
}
819601
function(options) {
        var self = this;

        var params = this.toJSON();
        params.limit = 1;
        var request = this._createRequest(params, options);

        return request.then(function(response) {
          return _.map(response.results, function(json) {
            var obj = self._newObject();
            if (obj._finishFetch) {
              obj._finishFetch(self._processResult(json), true);
            }
            return obj;
          })[0];
        });
      }
854588
function many (urls, options = {}) {
  let flowMethod = (options.waitTime) ? flow.series : flow.parallel

  // Call the single method while respecting the wait time in between tasks
  const callSingle = (url) => single(url, options)
    .then(content => wait(() => content, options.waitTime))

  // Map over the urls and call them using the method the user chose
  let promises = urls.map(url => () => callSingle(url))
  return flowMethod(promises)
}
258935
function (options) {
    this.queue = [];
    this.ownerTokenId = null;
    this.options = _.extend({}, AsyncLock.defaultOptions, options);
}
1195894
function Scheduler(async) {
		this._async = async;
		this._running = false;

		this._queue = this;
		this._queueLen = 0;
		this._afterQueue = {};
		this._afterQueueLen = 0;

		var self = this;
		this.drain = function() {
			self._drain();
		};
	}
355494
function(id) {
        var q = queues[id], sc;
        if (q.onTimeout) {
            sc = q.context || q;
            q.onTimeout.call(sc, _returnData(q));
        }

        _end(id, 'timeout', 'timeout');
    }
1252804
function(fn) {
				if (typeof fn === 'object' && fn.then && fn.catch) {
					var defer = fn;
					fn = function(resolve, reject) {
						defer.then(resolve).catch(reject);
					};
				}
				funcGuard(fn);
				if (err !== undefined) {
					return;
				} else if (complete) {
					throw new Error('Queue already completed');
				}

				tasks.push(fn);
				++remaining;
				pop();
				return q;
			}
1160279
function() {
        if(concurrentQueries < concurrentLimit) {
            gaExecuteQuery.apply(this, arguments);
        } else {
            var args = Array.prototype.slice.call(arguments);
            queryQueue.push(args);
        }
    }
1075020
function chainCallback(cb, next) {
    var browser = this;

    return function queueWrapped() {
        try {
            if (cb) {cb.apply(browser, arguments);}
            next();
        } catch (e) {
            next(e);
        }
    };
}
771867
def add(self, arg, options=None):
    
    fut = tasklets.Future('%s.add(%s, %s)' % (self, arg, options))
    todo = self._queues.get(options)
    if todo is None:
      utils.logging_debug('AutoBatcher(%s): creating new queue for %r',
                          self._todo_tasklet.__name__, options)
      if not self._queues:
        eventloop.add_idle(self._on_idle)
      todo = self._queues[options] = []
    todo.append((fut, arg))
    if len(todo) >= self._limit:
      del self._queues[options]
      self.run_queue(options, todo)
    return fut
1048619
function(source, callback) {
        callback = callback || noop;

        //if there's a queue
        if (queue[source] instanceof Array) {
            //just add it
            return queue[source].push(callback);
        }

        //otherwise there is not a queue
        //so let's create one
        queue[source] = [callback];

        var script = document.createElement('script');
        var head = document.getElementsByTagName('head')[0];

        script.async = 1;

        head.appendChild(script);

        script.onload = script.onreadystatechange = function( _, isAbort ) {
            if(isAbort || !script.readyState || /loaded|complete/.test(script.readyState) ) {
                script.onload = script.onreadystatechange = null;
                script = undefined;

                if(!isAbort) {
                    queue[source].forEach(function(callback) {
                        callback();
                    });

                    delete queue[source];
                }
            }
        };

        script.src = source;
    }
185219
function WorkingQueue(concurrency) {
    // Parallelization degree, if not mentioned use 64
    // Don't forget that we are in a SINGLE-threaded process
    // All we want it to somewhat limit the number of simultaneous
    // I/O requests
    concurrency = concurrency || 64;


    // The queue contains tuples :
    // [job, arg1, arg2, arg3...]
    var queue = [];
    var workers = 0;
    var onceDoneCallbacks = [];
    var held = false;
    var added = false;

    // This function launches a new worker, if possible
    // It returns true if a new worker was launched, false otherwise.
    function _go() {
        if(workers < concurrency) {
            var job = queue.shift();
            if(job !== undefined) {
                var worker = job.shift();
                job.push(over);
                workers++;
                process.nextTick(function nextTickWorker() {
                    worker.apply(null, job);
                });
                return true;
            }
        }
        return false;
    }

    // This function is passed to each job, it must be called
    // when the job is done.
    function over() {
        workers--;

        if(!held) { _go(); }

        checkDone();
    }

    function checkDone() {
        if(queue.length === 0 && workers === 0) {
            var i, l;

            for(i=0, l=onceDoneCallbacks.length; i < l; i++) {
                process.nextTick(onceDoneCallbacks[i]);
            }

            // Reset callbacks & status
            onceDoneCallbacks = [];
            added = false;
        }
    }

    // Enqueue a new job and ends the current one
    over.then = function overThen(/*...*/) {
        // Since it is only possible to get the over function
        // while running a job, no need to call this.perform
        queue.push(Array.prototype.slice.call(arguments, 0));
        added = true;
        return over();
    };

    // Main method : launches a job immediatly or queue it
    // if maximum number of workers has been reached
    this.perform = function perform(/*...*/) {
        queue.push(Array.prototype.slice.call(arguments, 0));
        added = true;
        if(!held) { _go(); }
        return this;
    };

    // Apply the worker function to each element in the list
    // The worker is in the form function(index, element /*, ...*/, over)
    this.processList = function processList(worker, list /*, ... */) {
        var length = list.length;
        var args, extra;

        if(length>0) {
            extra = Array.prototype.slice.call(arguments, 2);

            for(var i=0;i<length;i++) {
                args = [worker, i, list[i]].concat(extra);
                queue.push(args);
            }

            added = true;
            if(!held) { _go(); }
        }

        return this;
    };

    // Apply the worker function to each element in the dictionary
    // The worker is in the form function(key, value, /*, ... */, over)
    this.processObject = function processObject(worker, dict /*, ... */) {
        var args;
        var extra = Array.prototype.slice.call(arguments, 2);

        for(var key in dict) {
            args = [worker, key, dict[key]].concat(extra);
            queue.push(args);
            added = true;
        }

        if(!held) { _go(); }
        return this;
    };

    // Register a callback that will be called when
    // all jobs have been done.
    // If a callback is registered after the jobs are over,
    // it is called immediatly
    this.onceDone = function onceDone(fun) {
        onceDoneCallbacks.push(fun);
        if(added) { checkDone(); }
    };

    this.whenDone = util.deprecate(this.onceDone, "capisce.WorkingQueue.whenDone is deprecated, use onceDone instead.");

    this.doneAddingJobs = function doneAddingJobs() {
        if(!added) { checkDone(); }
    };

    // Holds the WorkingQueue. No job will be executed until
    // the go() method is called
    this.hold = function hold() {
        held = true;
    };

    // Launches the scheduled jobs
    this.go = function go() {
        if(held) {
            held = false;

            // Loop to launch as many workers as possible
            while(_go()) {}
        }
    };

    // This method is used for a little DSL that can build sequence of
    // jobs, as well as concurrent sections within those sequences.
    this.then = function then(block, concurrency2) {
        if(concurrency>1) { throw 'Cannot use then in a concurrent section'; }

        if(block.length === 1) {
            if(arguments.length !== 1) {
                throw 'Cannot specifiy a concurrency level for sequences';
            }
            this.perform(block);
        } else if(block.length === 2) {
            this.perform(function worker(over) {
                var concurrently = new WorkingQueue(concurrency2);
                block(concurrently, function over2() {
                    concurrently.onceDone(over);
                });
            });
        } else {
            throw 'then accepts building function with one (sequence) or two (concurrent) arguments';
        }

        return this;
    };

    function waiter(timeout, job, over) {
       setTimeout(function waiter() {
            if(job.length>0) {
                var func = job.shift();
                job.push(over);
                return func.apply(null, job);
            }
            else {
                return over();
            }
       }, timeout);
    }

    // This method waits the given timeout then executes the facultative
    // job.
    // This can be used in two ways :
    // sequence().wait(5000).then(function(over) {...})
    // OR
    // sequence().wait(5000,function(over) {...})s
    this.wait = function wait(timeout /*...*/) {
        var job = Array.prototype.slice.call(arguments, 1);
        this.perform(waiter, timeout, job);
        return this;
    };
}
1072882
function addToQueue( callback, prioritize, seed ) {
	if ( prioritize ) {
		config.queue.splice( priorityCount++, 0, callback );
	} else if ( seed ) {
		if ( !unitSampler ) {
			unitSampler = unitSamplerGenerator( seed );
		}

		// Insert into a random position after all prioritized items
		const index = Math.floor( unitSampler() * ( config.queue.length - priorityCount + 1 ) );
		config.queue.splice( priorityCount + index, 0, callback );
	} else {
		config.queue.push( callback );
	}
}
508934
function createRunQueue(modules) {

	return modules
		.map((mod) => mod._runQueue)
		.reduce((acc, res) => acc.concat(res), []);

}