Generate dictionary of results from query.

    Decodes the large dict recturned from the AWS query.

    Args:
        qry_results (dict): results from awsc.get_inst_info
    Returns:
        i_info (dict): information on instances and details.
354361
def process_results(qry_results):
    
    i_info = {}
    for i, j in enumerate(qry_results['Reservations']):
        i_info[i] = {'id': j['Instances'][0]['InstanceId']}
        i_info[i]['state'] = j['Instances'][0]['State']['Name']
        i_info[i]['ami'] = j['Instances'][0]['ImageId']
        i_info[i]['ssh_key'] = j['Instances'][0]['KeyName']
        i_info[i]['pub_dns_name'] = j['Instances'][0]['PublicDnsName']
        try:
            i_info[i]['tag'] = process_tags(j['Instances'][0]['Tags'])
        except KeyError:
            i_info[i]['tag'] = {"Name": ""}
    debg.dprint("numInstances: ", len(i_info))
    debg.dprintx("Details except AMI-name")
    debg.dprintx(i_info, True)
    return i_info
324720
def get_metrics_data(self, query):
        
        if self.es_url.startswith("http"):
            url = self.es_url
        else:
            url = 'http://' + self.es_url
        es = Elasticsearch(url)
        s = Search(using=es, index=self.es_index)
        s = s.update_from_dict(query)
        try:
            response = s.execute()
            return response.to_dict()
        except Exception as e:
            print()
            print("In get_metrics_data: Failed to fetch data.\n Query: {}, \n Error Info: {}"
                  .format(query, e.info))
            raise
538159
def getResult(self, queue, uid, suid=None):
        
        if suid:
            r = self._get_client().get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
        else:
            r = self._get_client().get('rhumba.q.%s.%s' % (queue, uid))

        if r:
            return json.loads(r)
        else:
            return None
515312
def get_response(self, results):
        
        if results is None:
            return None
        for result in itertools.chain.from_iterable(results):
            if isinstance(result, BaseResponse):
                return result
1062046
def result_to_dict(res):
    
    keys = res.keys()
    return [dict(itertools.izip(keys, row)) for row in res]
420512
def search(self, q):
        
        results = self._api.search(q=q)

        return results
572337
def _build_dictionary(self, results):
        
        foreign = self._first_key

        dictionary = {}

        for result in results:
            key = getattr(result, foreign)
            if key not in dictionary:
                dictionary[key] = []

            dictionary[key].append(result)

        return dictionary
542961
def dict2query(dictionary):
    
    query = []
    encoders = {dict: _dictionary_encoder}
    for k, v in dictionary.iteritems():
        if v.__class__ in encoders:
            nested_query = encoders[v.__class__](k, v)
            query += nested_query
        else:
            key = to_utf8(k)
            value = to_utf8(v)
            query.append('{}={}'.format(key, value))

    return '&'.join(query)
145204
def decode_search_index(self, index):
        
        result = {}
        result['name'] = bytes_to_str(index.name)
        if index.HasField('schema'):
            result['schema'] = bytes_to_str(index.schema)
        if index.HasField('n_val'):
            result['n_val'] = index.n_val
        return result
777392
def compile_query(query: dict) -> PyQuery:
    

    def _pair_to_dict(pair):
        if isinstance(pair, dict):
            return pair
        return {pair[0]: pair[1]}

    def _reduce(pair):
        try:
            return {'and': (_pair_to_dict(pair[0]), _pair_to_dict(pair[1]))}
        except (KeyError, IndexError):
            return _pair_to_dict(pair)

    def _get_first_pair(d: dict):
        return list(query.items())[0]

    if len(query) < 2:
        return compile_single_item(*_get_first_pair(query))
    try:
        reduced = reduce(lambda x, y: _reduce((x, y)), query.items())
    except KeyError:
        print(query)
        reduced = query
        raise
    return compile_single_item(*_get_first_pair(reduced))
297801
def parse_json_qry(qry_str):
    

    def param_analyzer(param_list):
        rtn_list = []
        for param in param_list:
            parts = param.strip().split("=")
            try:
                rtn_list.append(\
                        JsonQryProcessor[parts[0].strip().lower()](parts[1]))
            except IndexError:
                rtn_list.append(\
                        JsonQryProcessor[parts[0].strip().lower()]())
        return rtn_list

    def part_analyzer(part, idx):
        nonlocal dallor, asterick, question_mark
        if part == "$":
            dallor = idx
            return part
        elif part == "*":
            asterick = idx
            return part
        elif part == "?":
            question_mark = idx
            return part
        elif part.startswith("="):
            return part
        return cssparse(part)[0]
    # pdb.set_trace()
    main_parts = qry_str.split("|")
    or_parts = main_parts.pop(0).strip()
    params = param_analyzer(main_parts)
    rtn_list = []
    for or_part in [item.strip()
                    for item in or_parts.split(",")
                    if item.strip()]:
        dallor, asterick, question_mark = None, None, None
        dot_parts = or_part.split(".")
        rtn_list.append(([part_analyzer(part, i) \
                            for i, part in enumerate(dot_parts)],
                          dallor,
                          asterick,
                          question_mark))
    return {"qry_parts": rtn_list, "params": params}
747461
def is_get_query_with_results(results):
        
        return results and EsConst.FOUND in results and results[EsConst.FOUND] and EsConst.FIELDS in results
462885
def results(query)
      return [] unless doc = fetch_data(query)
      return doc["results"][0]['locations'] if doc['info']['statuscode'] == 0 # A successful geocode call

      messages = doc['info']['messages'].join

      case doc['info']['statuscode']
      when 400 # Error with input
        raise_error(Geocoder::InvalidRequest, messages) ||
          Geocoder.log(:warn, "Mapquest Geocoding API error: #{messages}")
      when 403 # Key related error
        raise_error(Geocoder::InvalidApiKey, messages) ||
          Geocoder.log(:warn, "Mapquest Geocoding API error: #{messages}")
      when 500 # Unknown error
        raise_error(Geocoder::Error, messages) ||
          Geocoder.log(:warn, "Mapquest Geocoding API error: #{messages}")
      end
      []
    end
476534
def from_dict(cls, info_dict):
        '''
        '''
        return WebBrowserInteractionInfo(
            visit_url=info_dict.get('VisitURL'),
            wait_token_url=info_dict.get('WaitTokenURL'))
460016
def results(self, dataset_name, index_by, timeframe):
        
        url = "{0}/{1}/results".format(self._cached_datasets_url, dataset_name)

        index_by = index_by if isinstance(index_by, str) else json.dumps(index_by)
        timeframe = timeframe if isinstance(timeframe, str) else json.dumps(timeframe)

        query_params = {
            "index_by": index_by,
            "timeframe": timeframe
        }

        return self._get_json(
            HTTPMethods.GET, url, self._get_read_key(), params=query_params
        )
442200
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'matching_results' in _dict:
            args['matching_results'] = _dict.get('matching_results')
        if 'results' in _dict:
            args['results'] = [
                QueryNoticesResult._from_dict(x) for x in (_dict.get('results'))
            ]
        if 'aggregations' in _dict:
            args['aggregations'] = [
                QueryAggregation._from_dict(x)
                for x in (_dict.get('aggregations'))
            ]
        if 'passages' in _dict:
            args['passages'] = [
                QueryPassages._from_dict(x) for x in (_dict.get('passages'))
            ]
        if 'duplicates_removed' in _dict:
            args['duplicates_removed'] = _dict.get('duplicates_removed')
        return cls(**args)
394754
def __parse_results(self,results):
        
        reslist = []
        cursor = 0
        match  = RE_RESULTS.search(results,cursor)
        while match:
            doc = {}
            doc['bibcode'] = match.group('bibcode')
            doc['confidence'] = self.__get_confidence_level(match.group('confidence'))
            doc['refstring'] = match.group('refstring')
            reslist.append(doc)
            cursor = match.end()
            match  = RE_RESULTS.search(results,cursor)
        return reslist