Match edges with the given dictionary as a sub-dictionary.

    :param query: The annotation query dict to match
970545
def _annotation_dict_all_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool:
    
    annotations = edge_data.get(ANNOTATIONS)

    if annotations is None:
        return False

    for key, values in query.items():
        ak = annotations.get(key)

        if ak is None:
            return False

        for value in values:
            if value not in ak:
                return False

    return True
422121
def _parse_query_dict(query_data, model):
        
        operator = 'iexact'
        if query_data['field'] == '_OR':
            query_data['operator'] = operator
            return query_data

        parts = query_data['field'].split('__')
        if len(parts) < 2:
            field = parts[0]
        else:
            if parts[-1] in dict(AdvancedFilterQueryForm.OPERATORS).keys():
                field = '__'.join(parts[:-1])
                operator = parts[-1]
            else:
                field = query_data['field']

        query_data['field'] = field
        mfield = get_fields_from_path(model, query_data['field'])
        if not mfield:
            raise Exception('Field path "%s" could not be followed to a field'
                            ' in model %s', query_data['field'], model)
        else:
            mfield = mfield[-1]  # get the field object

        if query_data['value'] is None:
            query_data['operator'] = "isnull"
        elif query_data['value'] is True:
            query_data['operator'] = "istrue"
        elif query_data['value'] is False:
            query_data['operator'] = "isfalse"
        else:
            if isinstance(mfield, DateField):
                # this is a date/datetime field
                query_data['operator'] = "range"  # default
            else:
                query_data['operator'] = operator  # default

        if isinstance(query_data.get('value'),
                      list) and query_data['operator'] == 'range':
            date_from = date_to_string(query_data.get('value_from'))
            date_to = date_to_string(query_data.get('value_to'))
            query_data['value'] = ','.join([date_from, date_to])

        return query_data
538029
def build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate:
    
    if not annotations:
        return keep_edge_permissive

    @edge_predicate
    def annotation_dict_any_filter(edge_data: EdgeData) -> bool:
        """Check if the any of the annotations in the enclosed query match."""
        return _annotation_dict_any_filter(edge_data, query=annotations)

    return annotation_dict_any_filter
765629
def match_as_dict(self, film_sl_vectors, substrate_sl_vectors, film_vectors, substrate_vectors, match_area):
        
        d = {}
        d["film_sl_vecs"] = np.asarray(film_sl_vectors)
        d["sub_sl_vecs"] = np.asarray(substrate_sl_vectors)
        d["match_area"] = match_area
        d["film_vecs"] = np.asarray(film_vectors)
        d["sub_vecs"] = np.asarray(substrate_vectors)

        return d
202745
def query_neighbors(self, nodes: List[Node]) -> List[Edge]:
        """"""
        return self.session.query(Edge).filter(self._edge_one_node(nodes)).all()
318828
def querydict_to_multidict(query_dict, wrap=None):
    
    wrap = wrap or (lambda val: val)
    return MultiDict(chain.from_iterable(
        six.moves.zip(repeat(key), (wrap(v) for v in vals))
        for key, vals in six.iterlists(query_dict)
    ))
1273061
def update_from_dict(self, d):
        
        d = d.copy()
        if 'query' in d:
            self.query._proxied = Q(d.pop('query'))
        if 'script' in d:
            self._script = d.pop('script')
        self._extra = d
        return self
652277
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'relations' in _dict:
            args['relations'] = [
                QueryRelationsRelationship._from_dict(x)
                for x in (_dict.get('relations'))
            ]
        return cls(**args)
1276858
def match(self, route):
        
        _resource = trim_resource(self.resource)
        self.method = self.method.lower()
        resource_match = route.resource_regex.search(_resource)
        if resource_match is None:
            return None

        # build params and querystring
        params = resource_match.groupdict()
        querystring = params.pop("querystring", "")
        setattr(self, "param", params)
        setattr(self, "query", parse_querystring(querystring))

        return copy.deepcopy(self)
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)
522245
def coords_from_query(query):
    """"""
    try:
        coords = json.loads(query)
    except ValueError:
        query = query.replace(',', ' ')
        vals = query.split()
        coords = [float(v) for v in vals]
    return tuple(coords[:2])
224805
def query(self, parents=None):
        
        # TODO: benchmark single-query strategy
        q = Select([])
        q = self.project(q, parent=True)
        q = self.filter(q, parents=parents)

        if self.parent is None:
            subq = Select([self.var])
            subq = self.filter(subq, parents=parents)
            subq = subq.offset(self.node.offset)
            subq = subq.limit(self.node.limit)
            subq = subq.distinct()
            # TODO: sorting.
            subq = subq.order_by(desc(self.var))
            q = q.where(subq)

        # if hasattr(self.context, 'identifier'):
        #     q._where = graph(self.context.identifier, q._where)
        log.debug("Compiled query: %r", q.compile())
        return q
163588
def extract(query_dict, prefix=""):
    

    strs = ['order_by']
    ints = ['per_page', 'page']

    extracted = { }

    for key in (strs + ints):
        if (prefix + key) in query_dict:
            val = query_dict.get(prefix + key)

            extracted[key] = (val
                if not key in ints
                else int(val))

    return extracted
1090394
def clean_query_Dict(cls, query_Dict):
    
    return {k: v for k, v in query_Dict.items() if v}
863131
def query_closest(self, query_item):
        

        if not isinstance(query_item, dict):
            raise TypeError("The query query_item isn't a dictionary")
        
        _type = query_item.get("type")
        _timestamp = query_item.get("timestamp")

        if _type is None:
            raise AttributeError("Please make sure to add a type to the query_item dict")

        if _timestamp is None:
            raise AttributeError("Timestamp doesn't exist. It's necessary to provide closest query")
        
        query_less = deepcopy(query_item)
        query_more = deepcopy(query_item)
        
        query_less["timestamp"] = {"$lte": _timestamp}
        query_more["timestamp"] = {"$gt": _timestamp}
        closestBelow = self._collection.find(query_less).sort(
            "timestamp", pymongo.DESCENDING).limit(1)
        closestAbove = self._collection.find(query_more).sort("timestamp", pymongo.ASCENDING).limit(1)
        
        combined = list(closestAbove) + list(closestBelow)
        for x in combined:
            del x['_id']
        
        # abs()
        if len(combined) >= 2: 
            if abs(combined[0]["timestamp"] - _timestamp) > abs(combined[1]["timestamp"] - _timestamp):
                return combined[1]
            else:
                return combined[0]
        elif combined == 1:
            return combined[0]
        else:
            return None
507487
def query(self, search, query):
        
        if query:
            if self.fields:
                return search.query('multi_match', fields=self.fields, query=query)
            else:
                return search.query('multi_match', query=query)
        return search
1334604
def _annotation_dict_any_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool:
    
    annotations = edge_data.get(ANNOTATIONS)

    if annotations is None:
        return False

    return any(
        key in annotations and value in annotations[key]
        for key, values in query.items()
        for value in values
    )