Runs the autocomplete method from the line processor, then reformats its result to be an array.
554818
def autocomplete(line)
      return [] unless @line_processor
      result = @line_processor.autocomplete(line, namespace)
      case result
        when String
          [result]
        when nil
          []
        when Array
          result
        else
          result.to_a
      end
    end
272650
def gather(input):
		""""""
		
		try:
			line = input.next()
		except StopIteration:
			return
		
		lead = True
		buffer = []
		
		# Gather contiguous (uninterrupted) lines of template text.
		while line.kind == 'text':
			value = line.line.rstrip().rstrip('\\') + ('' if line.continued else '\n')
			
			if lead and line.stripped:
				yield Line(line.number, value)
				lead = False
			
			elif not lead:
				if line.stripped:
					for buf in buffer:
						yield buf
					
					buffer = []
					yield Line(line.number, value)
				
				else:
					buffer.append(Line(line.number, value))
			
			try:
				line = input.next()
			except StopIteration:
				line = None
				break
			
		if line:
			input.push(line)
1011365
def each(include_blank = false)
      @lines.each do |line|
        if include_blank || ! (line.is_a?(Array) ? line.empty? : line.blank?)
          yield(line)
        end
      end
    end
851432
def to_code_array(self):
        """"""

        state = None

        # Check if version section starts with first line
        first_line = True

        # Reset pys_file to start to enable multiple calls of this method
        self.pys_file.seek(0)

        for line in self.pys_file:
            if first_line:
                # If Version section does not start with first line then
                # the file is invalid.
                if line == "[Pyspread save file version]\n":
                    first_line = False
                else:
                    raise ValueError(_("File format unsupported."))

            if line in self._section2reader:
                state = line

            elif state is not None:
                self._section2reader[state](line)
1004569
function keywordsToArray(keywords, result) {
      if (typeof keywords === 'string') {
        result = result.concat(keywords.split(','));
      }
      else if (keywords instanceof Array) {
        if (keywords.length > 0) {
          for (var i = 0; i < keywords.length; i++) {
            result = keywordsToArray(keywords[i], result);
          }
        }
      }
      return result;
    }
615248
function toArray(cursor, callback) {
  const Cursor = require('../cursor');

  const items = [];

  // Reset cursor
  cursor.rewind();
  cursor.s.state = Cursor.INIT;

  // Fetch all the documents
  const fetchDocs = () => {
    cursor._next((err, doc) => {
      if (err) {
        return cursor._endSession
          ? cursor._endSession(() => handleCallback(callback, err))
          : handleCallback(callback, err);
      }
      if (doc == null) {
        return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items));
      }

      // Add doc to items
      items.push(doc);

      // Get all buffered objects
      if (cursor.bufferedCount() > 0) {
        let docs = cursor.readBufferedDocuments(cursor.bufferedCount());

        // Transform the doc if transform method added
        if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') {
          docs = docs.map(cursor.s.transforms.doc);
        }

        push.apply(items, docs);
      }

      // Attempt a fetch
      fetchDocs();
    });
  };

  fetchDocs();
}
600550
function processNextAutogenBlock(autogenContext, allData, commentInfo, pos, callback) {

    //Update the position of the next block. If there isn't one, call the callback and break the recursion.
    pos = utils.regexIndexOf(allData, commentInfo.start, pos);

    if (pos == -1) {
        callback(allData);
        return;
    }

    //Extract the information from the autogen definition
    var matchInfo = commentInfo.start.exec(allData.substring(pos));

    //Skip over the start tag
    pos += matchInfo[0].length;

    //Get the data from the autogen tag
    var tagContent = matchInfo[1];
    var autogenTagData = utils.parseAutogenTag(tagContent);

    //Make file name in to a full path
    var filename = path.resolve(autogenContext.templateDir, autogenTagData.templateFileName + ".liquid");

    //Find the end of the line (and the start of content)
    //    Handle both styles of line endings
    var endOfAutogenLine = utils.regexIndexOf(allData, /[\r|\n]/, pos);
    var startBlock = utils.regexIndexOf(allData, /[\n]/, endOfAutogenLine) + 1;
    var endBlock = allData.indexOf(commentInfo.end, startBlock);

    //Prepare and load the required data
    var loadedLiquid = fs.readFileSync(filename);
    //Deep-copy the spec data so that we can add context
    var dataContext = utils.extend({}, autogenContext.specData);

    //Populate the autogen data context with property mappings from autogen tag
    for (var mappingIndex in autogenTagData.propertyMappings) {
        var propertyMapping = autogenTagData.propertyMappings[mappingIndex];

        var propValue = utils.getProp(dataContext, propertyMapping.sourceString);
        utils.setProp(dataContext, propertyMapping.destString, propValue);
    }

    //Populate the autogen data context with value mappings from autogen tag
    for (var mappingIndex in autogenTagData.valueMappings) {
        var valueMapping = autogenTagData.valueMappings[mappingIndex];

        utils.setProp(dataContext, valueMapping.destString, valueMapping.sourceString);
    }

    function insertTemplatedAndContinue(result) {
        //Replace the old contents of the output block with the result from the liquid engine
        var newData =
            allData.substring(0, startBlock)
            + result
            + os.EOL
            + allData.substring(endBlock);

        //Start/continue the recursion, and update the position for the next iteration
        processNextAutogenBlock(autogenContext, newData, commentInfo,
            startBlock
            + result.length
            + os.EOL.length
            + commentInfo.end.length, callback);
    }

    if (autogenContext.clearTemplatedSections)
        insertTemplatedAndContinue('');
    else {
        //Parse and render the liquid using the spec data
        autogenContext.liquidEngine
            .parseAndRender(loadedLiquid, dataContext)
            .then(insertTemplatedAndContinue);
    }
}
931339
function(arr, result) {
  if (arr.length > maxSegments || (encodeURIComponent(arr.join(',')).length > maxGetQueryLen && arr.length !== 1)) {
    var mid = Math.floor(arr.length / 2);
    splitArraysForGoogle(arr.slice(0, mid), result);
    splitArraysForGoogle(arr.slice(mid, arr.length), result);
  } else {
    result.push(arr);
  }
}
930305
protected function populateResult()
    {
        // default: mark that the processor completed succesfully
        $this->result->setSuccess(true);

        // store output array in result data
        $this->result->output = $this->context->output;
    }
375989
def _process_autocomplete_results(
            self,
            results: pysolr.Results) -> Dict[str, List[AutocompleteResult]]:
        
        # map go-golr fields to standard
        for doc in results.docs:
            if 'entity' in doc:
                doc['id'] = doc['entity']
                doc['label'] = doc['entity_label']

        docs = []
        for doc in results.docs:
            if results.highlighting:
                hl = self._process_highlight(results, doc)
            else:
                hl = Highlight(None, None, None)

            # In some cases a node does not have a category
            category = doc['category'] if 'category' in doc else []

            doc['taxon'] = doc['taxon'] if 'taxon' in doc else ""
            doc['taxon_label'] = doc['taxon_label'] if 'taxon_label' in doc else ""
            doc = AutocompleteResult(
                id=doc['id'],
                label=doc['label'],
                match=hl.match,
                category=category,
                taxon=doc['taxon'],
                taxon_label=doc['taxon_label'],
                highlight=hl.highlight,
                has_highlight=hl.has_highlight
            )
            docs.append(doc)

        payload = {
            'docs': docs
        }
        logging.debug('Docs: {}'.format(len(results.docs)))

        return payload
343710
def __process_results(results):
    
    if 'no match' in results and 'returning 0 elements' in results:
        return []

    result_list = []

    # Splts the result and cuts first and last dataset which are comments
    split = results.split(sep='\n\n')[1:-1]

    for entry in split:
        entry_dict = {}
        for value in entry.split('\n'):
            if len(value) < 1:
                continue
            (desc, val) = value.split(': ')
            entry_dict[desc.replace('-', '')] = val.strip(' ')
        result_list.append(entry_dict)
    return result_list
1272709
protected function prepareToIndent()
    {
        foreach ($this->lines as $lineNumber => $line) {
            $this->lines[$lineNumber] = trim($line);
        }

        $this->outputLines = $this->lines;
    }
141485
public void run() {
    final Scanner scanner = getScanner();

    // start the process by loading all of the trees in the system
    final List<Tree> trees;
    try {
      trees = Tree.fetchAllTrees(tsdb).joinUninterruptibly();
      LOG.info("[" + thread_id + "] Complete");
    } catch (Exception e) {
      LOG.error("[" + thread_id + "] Unexpected Exception", e);
      throw new RuntimeException("[" + thread_id + "] Unexpected exception", e);
    }
    
    if (trees == null) {
      LOG.warn("No tree definitions were found");
      return;
    } else {
      boolean has_enabled_tree = false;
      for (Tree tree : trees) {
        if (tree.getEnabled()) {
          has_enabled_tree = true;
          break;
        }
      }
      if (!has_enabled_tree) {
        LOG.warn("No enabled trees were found");
        return;
      }
      LOG.info("Found [" + trees.size() + "] trees");
    }
    
    // setup an array for storing the tree processing calls so we can block 
    // until each call has completed
    final ArrayList<Deferred<Boolean>> tree_calls = 
      new ArrayList<Deferred<Boolean>>();
    
    final Deferred<Boolean> completed = new Deferred<Boolean>();

    /**
     * Scanner callback that loops through the UID table recursively until 
     * the scanner returns a null row set.
     */
    final class TsuidScanner implements Callback<Deferred<Boolean>, 
      ArrayList<ArrayList<KeyValue>>> {

      /**
       * Fetches the next set of rows from the scanner, adding this class as a 
       * callback
       * @return A meaningless deferred used to wait on until processing has
       * completed
       */
      public Deferred<Boolean> scan() {
        return scanner.nextRows().addCallbackDeferring(this);
      }
      
      @Override
      public Deferred<Boolean> call(ArrayList<ArrayList<KeyValue>> rows)
          throws Exception {
        if (rows == null) {
          completed.callback(true);
          return null;
        }
        
        for (final ArrayList<KeyValue> row : rows) {
          // convert to a string one time
          final String tsuid = UniqueId.uidToString(row.get(0).key());
          
          /**
           * A throttling callback used to wait for the current TSMeta to 
           * complete processing through the trees before continuing on with 
           * the next set.
           */
          final class TreeBuilderBufferCB implements Callback<Boolean, 
            ArrayList<ArrayList<Boolean>>> {

            @Override
            public Boolean call(ArrayList<ArrayList<Boolean>> builder_calls)
                throws Exception {
              //LOG.debug("Processed [" + builder_calls.size() + "] tree_calls");
              return true;
            }
            
          }
          
          /**
           * Executed after parsing a TSMeta object and loading all of the
           * associated UIDMetas. Once the meta has been loaded, this callback
           * runs it through each of the configured TreeBuilder objects and
           * stores the resulting deferred in an array. Once processing of all
           * of the rules has completed, we group the deferreds and call
           * BufferCB() to wait for their completion.
           */
          final class ParseCB implements Callback<Deferred<Boolean>, TSMeta> {

            final ArrayList<Deferred<ArrayList<Boolean>>> builder_calls = 
              new ArrayList<Deferred<ArrayList<Boolean>>>();
            
            @Override
            public Deferred<Boolean> call(TSMeta meta) throws Exception {
              if (meta != null) {
                LOG.debug("Processing TSMeta: " + meta + " w value: " + 
                    JSON.serializeToString(meta));
                
                // copy the trees into a tree builder object and iterate through
                // each builder. We need to do this as a builder is not thread
                // safe and cannot be used asynchronously.
                final ArrayList<TreeBuilder> tree_builders = 
                new ArrayList<TreeBuilder>(trees.size());
                for (Tree tree : trees) {
                  if (!tree.getEnabled()) {
                    continue;
                  }
                  final TreeBuilder builder = new TreeBuilder(tsdb, tree);
                  tree_builders.add(builder);
                }
                
                for (TreeBuilder builder : tree_builders) {
                  builder_calls.add(builder.processTimeseriesMeta(meta));
                }
                return Deferred.group(builder_calls)
                  .addCallback(new TreeBuilderBufferCB());
              } else {
                return Deferred.fromResult(false);
              }
            }
            
          }
          
          /**
           * An error handler used to catch issues when loading the TSMeta such
           * as a missing UID name. In these situations we want to log that the 
           * TSMeta had an issue and continue on.
           */
          final class ErrBack implements Callback<Deferred<Boolean>, Exception> {
            
            @Override
            public Deferred<Boolean> call(Exception e) throws Exception {
              
              if (e.getClass().equals(IllegalStateException.class)) {
                LOG.error("Invalid data when processing TSUID [" + tsuid + "]", e);
              } else if (e.getClass().equals(IllegalArgumentException.class)) {
                LOG.error("Invalid data when processing TSUID [" + tsuid + "]", e);
              } else if (e.getClass().equals(NoSuchUniqueId.class)) {
                LOG.warn("Timeseries [" + tsuid + 
                    "] includes a non-existant UID: " + e.getMessage());
              } else {
                LOG.error("[" + thread_id + "] Exception while processing TSUID [" + 
                    tsuid + "]", e);
              }
              
              return Deferred.fromResult(false);
            }
            
          }

          // matched a TSMeta column, so request a parsing and loading of
          // associated UIDMeta objects, then pass it off to callbacks for 
          // parsing through the trees.
          final Deferred<Boolean> process_tsmeta = 
            TSMeta.parseFromColumn(tsdb, row.get(0), true)
              .addCallbackDeferring(new ParseCB());
          process_tsmeta.addErrback(new ErrBack());
          tree_calls.add(process_tsmeta);
        }
        
        /**
         * Another buffer callback that waits for the current set of TSMetas to
         * complete their tree calls before we fetch another set of rows from
         * the scanner. This necessary to avoid OOM issues.
         */
        final class ContinueCB implements Callback<Deferred<Boolean>, 
          ArrayList<Boolean>> {

          @Override
          public Deferred<Boolean> call(ArrayList<Boolean> tsuids)
              throws Exception {
            LOG.debug("Processed [" + tsuids.size() + "] tree_calls, continuing");
            tree_calls.clear();
            return scan();
          }
          
        }
        
        // request the next set of rows from the scanner, but wait until the
        // current set of TSMetas has been processed so we don't slaughter our
        // host
        Deferred.group(tree_calls).addCallback(new ContinueCB());
        return Deferred.fromResult(null);
      }
      
    }
    
    /**
     * Used to capture unhandled exceptions from the scanner callbacks and 
     * exit the thread properly
     */
    final class ErrBack implements Callback<Deferred<Boolean>, Exception> {
      
      @Override
      public Deferred<Boolean> call(Exception e) throws Exception {
        LOG.error("Unexpected exception", e);
        completed.callback(false);
        return Deferred.fromResult(false);
      }
      
    }
    
    final TsuidScanner tree_scanner = new TsuidScanner();
    tree_scanner.scan().addErrback(new ErrBack());
    try {
      completed.joinUninterruptibly();
      LOG.info("[" + thread_id + "] Complete");
    } catch (Exception e) {
      LOG.error("[" + thread_id + "] Scanner Exception", e);
      throw new RuntimeException("[" + thread_id + "] Scanner exception", e);
    }
    return;
  }
289111
function procesArray(array) {
  if (!array || !Array.isArray(array)) {
    return array;
  }
  return array.map((item, index) => {
    if (typeof item === "string") {
      return localizeString(item);
    }
    return item;
  });
}
170443
def array_elements(buffer = '')
      if (term = expression)
        buffer += term[@value]
        # If there is an array_terminator ",", recursively gather the next
        # array element into the buffer
        if (terminator = accept_stripped :comma)
          accept_newline
          buffer += array_elements terminator
        end
      end

      # Array ended prematurely with a trailing comma, therefore the current
      # parsing process will stop
      error :array_elements_terminator if buffer.strip[-1] == ','

      buffer
    end
666706
def validate_result(self, (result_array, result_keywords, )):
        '''
        
        '''
        if len(result_array) != 1 or len(result_keywords) > 0:
            raise BadSyntax('Syntax error processing line: %s' %\
                            self._last_line)
        return result_array[0]
46173
def to_array(self):
        
        array = super(InlineQueryResultCachedMpeg4Gif, self).to_array()
        array['type'] = u(self.type)  # py2: type unicode, py3: type str

        array['id'] = u(self.id)  # py2: type unicode, py3: type str

        array['mpeg4_file_id'] = u(self.mpeg4_file_id)  # py2: type unicode, py3: type str

        if self.title is not None:
            array['title'] = u(self.title)  # py2: type unicode, py3: type str

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

        if self.reply_markup is not None:
            array['reply_markup'] = self.reply_markup.to_array()  # type InlineKeyboardMarkup

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array