Perform Trac search
438027
def search(query, parent, options):
        
        # Extend the default max number of tickets to be fetched
        query = "{0}&max={1}".format(query, MAX_TICKETS)
        log.debug("Search query: {0}".format(query))
        try:
            result = parent.proxy.ticket.query(query)
        except xmlrpclib.Fault as error:
            log.error("An error encountered, while searching for tickets.")
            raise ReportError(error)
        except xmlrpclib.ProtocolError as error:
            log.debug(error)
            log.error("Trac url: {0}".format(parent.url))
            raise ReportError(
                "Unable to contact Trac server. Is the url above correct?")
        log.debug("Search result: {0}".format(result))
        # Fetch tickets and their history using multicall
        multicall = xmlrpclib.MultiCall(parent.proxy)
        for ticket_id in sorted(result):
            multicall.ticket.get(ticket_id)
            multicall.ticket.changeLog(ticket_id)
        log.debug(u"Fetching trac tickets and their history")
        result = list(multicall())
        tickets = result[::2]
        changelogs = result[1::2]
        # Print debugging info
        for ticket, changelog in zip(tickets, changelogs):
            log.debug("Fetched ticket #{0}".format(ticket[0]))
            log.debug(pretty(ticket))
            log.debug("Changelog:")
            log.debug(pretty(changelog))
        # Return the list of ticket objects
        return [
            Trac(ticket, changelg, parent=parent, options=options)
            for ticket, changelg in zip(tickets, changelogs)]
923720
def search(self, query, indices=None, doc_types=None, model=None, scan=False, headers=None, **query_params):
        
        if isinstance(query, Search):
            search = query
        elif isinstance(query, (Query, dict)):
            search = Search(query)
        else:
            raise InvalidQuery("search() must be supplied with a Search or Query object, or a dict")

        if scan:
            query_params.setdefault("search_type", "scan")
            query_params.setdefault("scroll", "10m")

        return ResultSet(self, search, indices=indices, doc_types=doc_types,
                         model=model, query_params=query_params, headers=headers)
1264091
def searchAccession(acc):
    
    # try genbank file
    # genome database
    out, error = entrez('genome', acc)
    for line in out.splitlines():
        line = line.decode('ascii').strip()
        if 'Assembly_Accession' in line or 'BioSample' in line:
            newAcc = line.split('>')[1].split('<')[0].split('.')[0].split(',')[0]
            if len(newAcc) > 0:
                return (True, acc, newAcc)
    # nucleotide database
    out, error = entrez('nucleotide', acc)
    for line in out.splitlines():
        line = line.decode('ascii').strip()
        if 'Assembly_Accession' in line or 'BioSample' in line:
            newAcc = line.split('>')[1].split('<')[0].split('.')[0].split(',')[0]
            if len(newAcc) > 0:
                return (True, acc, newAcc)
    # assembly database
    out, error = entrez('assembly', acc)
    for line in out.splitlines():
        line = line.decode('ascii').strip()
        if 'Assembly_Accession' in line or 'BioSample' in line:
            newAcc = line.split('>')[1].split('<')[0].split('.')[0].split(',')[0]
            if len(newAcc) > 0:
                return (True, acc, newAcc)
    for error in error.splitlines():
        error = error.decode('ascii').strip()
        if '500 Can' in error:
            return (False, acc, 'no network')
    return (False, acc, 'efetch failed')
1336206
def search(self, term, keywords=None, sortAscending=True):
        
        if sortAscending:
            direction = 'ASC'
        else:
            direction = 'DESC'

        return [_SQLiteResultWrapper(r[0]) for r in
                self.store.querySQL(self.searchSQL % (direction,), (term,))]
946399
def preprocess_search_hit(pid, record_hit, links_factory=None, **kwargs):
        """"""
        links_factory = links_factory or (lambda x, **k: dict())
        record = dict(
            pid=pid,
            metadata=record_hit['_source'],
            links=links_factory(pid, record_hit=record_hit, **kwargs),
            revision=record_hit['_version'],
            created=None,
            updated=None,
        )
        # Move created/updated attrs from source to object.
        for key in ['_created', '_updated']:
            if key in record['metadata']:
                record[key[1:]] = record['metadata'][key]
                del record['metadata'][key]
        return record
335839
def cli(obj, ids, query, filters):
    """"""
    client = obj['client']
    if ids:
        query = [('id', x) for x in ids]
    elif query:
        query = [('q', query)]
    else:
        query = build_query(filters)
    alerts = client.search(query)

    headers = {'id': 'ID', 'rawData': 'RAW DATA'}
    click.echo(
        tabulate([{'id': a.id, 'rawData': a.raw_data} for a in alerts], headers=headers, tablefmt=obj['output']))
909802
def run(bam, chrom, pos1, pos2, reffa, chr_reffa, parameters):
    """"""

    # check for chr ref
    is_chr_query = chrom.startswith('chr')
    if is_chr_query and chr_reffa is None:
        chr_reffa = reffa

    # check bam ref type
    bam_header = subprocess.check_output("samtools view -H {}".format(bam), shell=True)
    is_chr_bam = bam_header.find('SN:chr') != -1
    if is_chr_bam:
        reffa = chr_reffa
    if not is_chr_query and is_chr_bam:
        chrom = 'chr' + chrom
    if is_chr_query and not is_chr_bam:
        chrom = re.sub(r'^chr', '', chrom)

    posmin = min(pos1, pos2)
    posmax = max(pos1, pos2)
    cmd = "samtools view -bh {bam} {chrom}:{pos1}-{pos2} " \
        "| samtools mpileup {parameters} -f {reffa} -".format(bam=bam, chrom=chrom,
                                                              pos1=posmin, pos2=posmax,
                                                              reffa=reffa, parameters=parameters)
    if pos1 == pos2:
        cmd += " | awk '$2 == {pos}'".format(pos=pos1)
    else:
        cmd += " | tail -n +2 | awk '$2 >= {posmin} && $2 <= {posmax}'".format(posmin=posmin, posmax=posmax)
    sys.stderr.write("Running:\n{}\n".format(cmd))
    child = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    stdout, stderr = child.communicate()
    if child.returncode != 0:
        if len(stdout) == 0 and stderr is None:
            warnings.warn("Command:\n{cmd}\n did not exit with zero exit code. "
                          "Possibly no coverage for sample.".format(cmd=cmd))
        else:
            raise(Exception("Command:\n{cmd}\n did not exit with zero exit code. "
                            "Check command.".format(cmd=cmd)))
    else:
        return stdout
260771
def do_search(self, arg=None):
        """"""
        new_cats = []
        for cat in self.cats:
            new_cat = cat.search(self.inputs.text,
                                 depth=self.inputs.depth)
            if len(list(new_cat)) > 0:
                new_cats.append(new_cat)
        if len(new_cats) > 0:
            self.done_callback(new_cats)
            self.visible = False
932033
function searchPathsRec(thisPath, pathsToIgnore) {
		const subLogPrefix = logPrefix + 'searchPathsRec() - ';

		let result = [];
		let thisPaths;

		if (! pathsToIgnore) pathsToIgnore = [];

		try {
			if (that.fs.existsSync(thisPath + '/' + target) && result.indexOf(path.normalize(thisPath + '/' + target)) === - 1 && pathsToIgnore.indexOf(thisPath) === - 1) {
				result.push(path.normalize(thisPath + '/' + target));
			}

			if (! that.fs.existsSync(thisPath)) {
				return result;
			}

			thisPaths	= that.fs.readdirSync(thisPath);
		} catch (err) {
			that.log.error(subLogPrefix + 'throwed fs error: ' + err.message);

			return result;
		}

		for (let i = 0; thisPaths[i] !==  undefined; i ++) {
			try {
				const	subStat	= that.fs.statSync(thisPath + '/' + thisPaths[i]);

				if (subStat.isDirectory()) {
					if (thisPaths[i] !== target && pathsToIgnore.indexOf(thisPaths[i]) === - 1) {
						// If we've found a target dir, we do not wish to scan it
						result	= result.concat(searchPathsRec(thisPath + '/' + thisPaths[i], pathsToIgnore));
					}
				}
			} catch (err) {
				that.log.error(subLogPrefix + 'Could not read "' + thisPaths[i] + '": ' + err.message);
			}
		}

		return result;
	}
573696
def search_on_web(self, *args):
        
        # TODO KEYBINDINGS ONLY
        current_term = self.get_notebook().get_current_terminal()

        if current_term.get_has_selection():
            current_term.copy_clipboard()
            guake_clipboard = Gtk.Clipboard.get_default(self.window.get_display())
            search_query = guake_clipboard.wait_for_text()
            search_query = quote_plus(search_query)
            if search_query:
                # TODO search provider should be selectable (someone might
                # prefer bing.com, the internet is a strange place ¯\_(ツ)_/¯ )
                search_url = "https://www.google.com/#q={!s}&safe=off".format(search_query, )
                Gtk.show_uri(self.window.get_screen(), search_url, get_server_time(self.window))
        return True
813634
def run_cmsearch(fastas, threads, cm):
    
    out = []
    for fasta in fastas:
        cmsearch = '%s.23S.cmsearch' % (fasta.name.rsplit('.', 1)[0])
        if os.path.exists(cmsearch) is False:
            p = Popen('\
                    cmsearch --cpu %s --hmmonly --acc --noali -T -1 --tblout %s %s %s >> cmsearch.log' \
                    % (threads, cmsearch, cm, fasta.name), shell = True)
            p.communicate()
        else:
            print('# cmsearch output found: %s' % (cmsearch), file=sys.stderr)
        out.append(open(cmsearch))
    return out
1367857
def _pip_search(stdout, stderr):
        """"""
        result = {}
        lines = to_text_string(stdout).split('\n')
        while '' in lines:
            lines.remove('')

        for line in lines:
            if ' - ' in line:
                parts = line.split(' - ')
                name = parts[0].strip()
                description = parts[1].strip()
                result[name] = description

        return result
672865
def grep_file(query, item):
    """"""
    return ['%s: %s' % (item, line) for line in open(item)
            if re.search(query, line)]
1260952
def do_find(lookup, term):
    """"""

    space = defaultdict(list)

    for name in lookup.keys():
        space[name].append(name)

    try:
        iter_lookup = lookup.iteritems()  # Python 2
    except AttributeError:
        iter_lookup = lookup.items()  # Python 3

    for name, definition in iter_lookup:
        for keyword in definition['keywords']:
            space[keyword].append(name)
        space[definition['category']].append(name)

    matches = fnmatch.filter(space.keys(), term)

    results = set()
    for match in matches:
        results.update(space[match])

    return [(r, translate(lookup, r)) for r in results]
294496
function execute(req, res) {
  var scanner = new Scanner(
    req.db.getKeys(), req.info.cursor, req.info.pattern, req.info.count);
  scanner.scan(req, res);
}
1113071
def search(context, keywords, module, raw, kind):
    
    logging.info(_('Entering search mode'))
    sense = context.obj['sense']
    func = sense.query_names if module else sense.query_info
    none = True
    for keyword in keywords:
        output = func(keyword, raw, kind)
        if output:
            none = False
            print(output)
        else:
            logging.warning(_('No results: %s'), keyword)
    sys.exit(1 if none else 0)
409902
def search(self, start_ts, end_ts):
        
        return self._stream_search(
            index=self.meta_index_name,
            body={"query": {"range": {"_ts": {"gte": start_ts, "lte": end_ts}}}},
        )