Python operator.or_() Examples

The following are 30 code examples of operator.or_(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module operator , or try the search function .
Example #1
Source File: list.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def get_queryset(self):
        queryset = super(ListModelView, self).get_queryset()
        search = self.get_search_by()
        effective = self.get_filter_by()
        ordering = self.get_ordering()
        if search and 'actived' in effective.keys():
            del effective['actived']
        _all = self.apply_optimize_queryset().filter(**effective)
        if hasattr(
                self.model,
                'onidc_id') and not self.request.user.is_superuser:
            _shared = _all.filter(mark='shared')
            _private = _all.filter(onidc_id=self.onidc_id)
            queryset = (_shared | _private).order_by(*ordering)
        else:
            queryset = _all.order_by(*ordering)
        if search:
            lst = []
            for q in search:
                q = q.strip()
                str = [models.Q(**{k: q}) for k in self.allow_search_fields]
                lst.extend(str)
            query_str = reduce(operator.or_, lst)
            queryset = queryset.filter(query_str).order_by(*ordering)
        return queryset 
Example #2
Source File: managers.py    From prospector with GNU General Public License v3.0 6 votes vote down vote up
def get_ancestors(self, include_self=True):
        """
        Gets the MPTT ancestors of a queryset. Adapted from get_descendants()
        """

        filters = []
        for node in self.all():
            lft, rght = node.lft, node.rght

            if include_self:
                lft += 1
                rght -= 1

            filters.append(Q(tree_id=node.tree_id, lft__lt=lft, rght__gt=rght))

        q = functools.reduce(operator.or_, filters)

        return self.model.objects.filter(q) 
Example #3
Source File: managers.py    From prospector with GNU General Public License v3.0 6 votes vote down vote up
def get_descendants(self, include_self=True):
        """
        Gets a the MPTT descendants of a queryset
        Found and modified from
        http://stackoverflow.com/questions/5722767
        """
        filters = []
        for node in self.all():
            lft, rght = node.lft, node.rght
            if include_self:
                lft -= 1
                rght += 1

            filters.append(Q(tree_id=node.tree_id, lft__gt=lft, rght__lt=rght))

        q = functools.reduce(operator.or_, filters)

        return self.model.objects.filter(q) 
Example #4
Source File: logic.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def normalize(self, newvars=None):
        """Rename auto-generated unique variables"""
        def get_indiv_vars(e):
            if isinstance(e, IndividualVariableExpression):
                return set([e])
            elif isinstance(e, AbstractVariableExpression):
                return set()
            else:
                return e.visit(get_indiv_vars,
                               lambda parts: reduce(operator.or_, parts, set()))

        result = self
        for i,e in enumerate(sorted(get_indiv_vars(self), key=lambda e: e.variable)):
            if isinstance(e,EventVariableExpression):
                newVar = e.__class__(Variable('e0%s' % (i+1)))
            elif isinstance(e,IndividualVariableExpression):
                newVar = e.__class__(Variable('z%s' % (i+1)))
            else:
                newVar = e
            result = result.replace(e.variable, newVar, True)
        return result 
Example #5
Source File: test_differential_ops.py    From galgebra with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_multiply(self):
        coords = x, y, z = symbols('x y z', real=True)
        ga, ex, ey, ez = Ga.build('e*x|y|z', g=[1, 1, 1], coords=coords)

        p = Pdop(x)
        assert x * p == Sdop([(x, p)])
        assert ex * p == Sdop([(ex, p)])

        assert p * x == p(x) == S(1)
        assert p * ex == p(ex) == S(0)
        assert type(p(ex)) is Mv

        # These are not defined for consistency with Sdop
        for op in [operator.xor, operator.or_, operator.lt, operator.gt]:
            with pytest.raises(TypeError):
                op(ex, p)
            with pytest.raises(TypeError):
                op(p, ex) 
Example #6
Source File: test_differential_ops.py    From galgebra with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def chain_with_mv(self):
        coords = x, y, z = symbols('x y z', real=True)
        ga, ex, ey, ez = Ga.build('e*x|y|z', g=[1, 1, 1], coords=coords)
        s = Sdop([(x, Pdop(x)), (y, Pdop(y))])

        assert type(ex * s) is Sdop
        assert type(s * ex) is Mv

        # type should be preserved even when the result is 0
        assert type(ex * Sdop([])) is Sdop
        assert type(Sdop([]) * ex) is Mv

        # As discussed with brombo, these operations are not well defined - if
        # you need them, you should be using `Dop` not `Sdop`.
        for op in [operator.xor, operator.or_, operator.lt, operator.gt]:
            with pytest.raises(TypeError):
                op(ex, s)
            with pytest.raises(TypeError):
                op(s, ex) 
Example #7
Source File: export.py    From finam-export with Apache License 2.0 6 votes vote down vote up
def _apply_filter(self, col, val, comparator):
        """
        Builds a dataframe matching original dataframe with conditions passed

        The original dataframe is left intact
        """
        if not is_container(val):
            val = [val]

        if comparator == LookupComparator.EQUALS:
            # index must be sliced differently
            if col == 'id':
                expr = self._meta.index.isin(val)
            else:
                expr = self._meta[col].isin(val)
        else:
            if comparator == LookupComparator.STARTSWITH:
                op = 'startswith'
            else:
                op = 'contains'
            expr = self._combine_filters(
                map(getattr(self._meta[col].str, op), val), operator.or_)
        return expr 
Example #8
Source File: _constants.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _flagOp(op, left, right):
    """
    Implement a binary operator for a L{FlagConstant} instance.

    @param op: A two-argument callable implementing the binary operation.  For
        example, C{operator.or_}.

    @param left: The left-hand L{FlagConstant} instance.
    @param right: The right-hand L{FlagConstant} instance.

    @return: A new L{FlagConstant} instance representing the result of the
        operation.
    """
    value = op(left.value, right.value)
    names = op(left.names, right.names)
    result = FlagConstant()
    result._realize(left._container, names, value)
    return result 
Example #9
Source File: backend.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _normalize_group_dns(self, group_dns):
        """
        Converts one or more group DNs to an LDAPGroupQuery.

        group_dns may be a string, a non-empty list or tuple of strings, or an
        LDAPGroupQuery. The result will be an LDAPGroupQuery. A list or tuple
        will be joined with the | operator.

        """
        if isinstance(group_dns, LDAPGroupQuery):
            query = group_dns
        elif isinstance(group_dns, str):
            query = LDAPGroupQuery(group_dns)
        elif isinstance(group_dns, (list, tuple)) and len(group_dns) > 0:
            query = reduce(operator.or_, map(LDAPGroupQuery, group_dns))
        else:
            raise ValueError(group_dns)

        return query 
Example #10
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def index(request):
    person = get_person(request.user)

    # PERS, INST reminders for this person
    personal_reminders = Reminder.objects.filter(reminder_type__in=['PERS','INST'], person=person).select_related('course')

    # ROLE reminders for this person's current roles
    user_roles = Role.objects_fresh.filter(person=person)
    role_query = reduce(
        operator.or_,
        (Q(role=r.role) & Q(unit=r.unit) for r in user_roles)
        )
    role_reminders = Reminder.objects.filter(role_query, reminder_type='ROLE').select_related('unit')

    reminders = set(personal_reminders) | set(role_reminders)
    context = {
        'reminders': reminders,
    }
    return render(request, 'reminders/index.html', context) 
Example #11
Source File: formular.py    From gamification-engine with MIT License 6 votes vote down vote up
def _term_eval(term, column_variable, column_key):

    if term["type"].lower() == "conjunction":
        return and_(*((_term_eval(t, column_variable, column_key) for t in term["terms"])))
    elif term["type"].lower() == "disjunction":
        return or_(*((_term_eval(t, column_variable, column_key) for t in term["terms"])))
    elif term["type"].lower() == "literal":
        if "key" in term and term["key"]:
            key_operator = term.get("key_operator", "IN")
            if key_operator is None or key_operator == "IN":
                key_condition = column_key.in_(term["key"])
            elif key_operator=="ILIKE":
                key_condition = or_(*(column_key.ilike(pattern) for pattern in term["key"]))
            return and_(column_variable==term["variable"], key_condition)
        else:
            return column_variable==term["variable"] 
Example #12
Source File: views.py    From cornerwise with MIT License 5 votes vote down vote up
def _query(req):
    queries = req.GET.getlist("query")
    if queries:
        query = reduce(or_, (build_proposal_query(json.loads(q))
                             for q in queries), Q())
    else:
        query = build_proposal_query(req.GET)
    proposals = Proposal.objects.filter(query)
    if "include_projects" in req.GET:
        proposals = proposals.select_related("project")
    return proposals 
Example #13
Source File: test_operator.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_bitwise_or(self):
        self.assertRaises(TypeError, operator.or_)
        self.assertRaises(TypeError, operator.or_, None, None)
        self.assertTrue(operator.or_(0xa, 0x5) == 0xf) 
Example #14
Source File: api.py    From ibis with Apache License 2.0 5 votes vote down vote up
def _string_like(self, patterns):
    """
    Wildcard fuzzy matching function equivalent to the SQL LIKE directive. Use
    % as a multiple-character wildcard or _ (underscore) as a single-character
    wildcard.

    Use re_search or rlike for regex-based matching.

    Parameters
    ----------
    pattern : str or List[str]
        A pattern or list of patterns to match. If `pattern` is a list, then if
        **any** pattern matches the input then the corresponding row in the
        output is ``True``.

    Returns
    -------
    matched : ir.BooleanColumn
    """
    return functools.reduce(
        operator.or_,
        (
            ops.StringSQLLike(self, pattern).to_expr()
            for pattern in util.promote_list(patterns)
        ),
    ) 
Example #15
Source File: UserInt.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __ror__(self, other):
        return self._rop(other, operator.or_) 
Example #16
Source File: UserFloat.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __or__(self, other):
        return self._op(other, operator.or_) 
Example #17
Source File: UserFloat.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __ror__(self, other):
        return self._rop(other, operator.or_) 
Example #18
Source File: UserInt.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __or__(self, other):
        return self._op(other, operator.or_) 
Example #19
Source File: pkg_resources.py    From oss-ftp with MIT License 5 votes vote down vote up
def test(cls, nodelist):
        # MUST NOT short-circuit evaluation, or invalid syntax can be skipped!
        return functools.reduce(operator.or_, [cls.interpret(nodelist[i]) for i in range(1,len(nodelist),2)]) 
Example #20
Source File: validation.py    From PandasSchema with GNU General Public License v3.0 5 votes vote down vote up
def __or__(self, other: '_SeriesValidation'):
        """
        Returns a validation which is true if either this or the other validation is true
        """
        return _CombinedValidation(self, other, operator.or_) 
Example #21
Source File: dataset.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __or__(self, other):
        return self._bin_op(other, operator.or_) 
Example #22
Source File: pkg_resources.py    From oss-ftp with MIT License 5 votes vote down vote up
def test(cls, nodelist):
        # MUST NOT short-circuit evaluation, or invalid syntax can be skipped!
        items = [
            cls.interpret(nodelist[i])
            for i in range(1, len(nodelist), 2)
        ]
        return functools.reduce(operator.or_, items) 
Example #23
Source File: markers.py    From pdm with MIT License 5 votes vote down vote up
def _build_pyspec_from_marker(markers):
    def split_version(version):
        if "," in version:
            return [v.strip() for v in version.split(",")]
        return version.split()

    groups = [PySpecSet()]
    for marker in markers:
        if isinstance(marker, list):
            # It is a submarker
            groups[-1] = groups[-1] & _build_pyspec_from_marker(marker)
        elif isinstance(marker, tuple):
            key, op, version = [i.value for i in marker]
            if key == "python_version":
                if op == ">":
                    int_versions = [int(ver) for ver in version.split(".")]
                    int_versions[-1] += 1
                    version = ".".join(str(v) for v in int_versions)
                    op = ">="
                elif op in ("==", "!="):
                    if len(version.split(".")) < 3:
                        version += ".*"
                elif op in ("in", "not in"):
                    version = " ".join(v + ".*" for v in split_version(version))
            if op == "in":
                pyspec = reduce(
                    operator.or_, (PySpecSet(f"=={v}") for v in split_version(version))
                )
            elif op == "not in":
                pyspec = reduce(
                    operator.and_, (PySpecSet(f"!={v}") for v in split_version(version))
                )
            else:
                pyspec = PySpecSet(f"{op}{version}")
            groups[-1] = groups[-1] & pyspec
        else:
            assert marker in ("and", "or")
            if marker == "or":
                groups.append(PySpecSet())
    return reduce(operator.or_, groups) 
Example #24
Source File: asset_restrictions.py    From pylivetrader with Apache License 2.0 5 votes vote down vote up
def is_restricted(self, assets, dt):
        if isinstance(assets, Asset):
            return any(
                r.is_restricted(assets, dt) for r in self.sub_restrictions
            )

        return reduce(
            operator.or_,
            (r.is_restricted(assets, dt) for r in self.sub_restrictions)
        ) 
Example #25
Source File: test_operator.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_bitwise_or(self):
        self.assertRaises(TypeError, operator.or_)
        self.assertRaises(TypeError, operator.or_, None, None)
        self.assertTrue(operator.or_(0xa, 0x5) == 0xf) 
Example #26
Source File: utils.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_lemmas(text):
    word = Word(to_lemma(text))
    sets = map(set, [synset.lemma_names()
                     for synset in word.synsets])

    return map(from_lemma, reduce(operator.or_, sets)) 
Example #27
Source File: options.py    From bioforum with MIT License 5 votes vote down vote up
def get_search_results(self, request, queryset, search_term):
        """
        Return a tuple containing a queryset to implement the search
        and a boolean indicating if the results may contain duplicates.
        """
        # Apply keyword searches.
        def construct_search(field_name):
            if field_name.startswith('^'):
                return "%s__istartswith" % field_name[1:]
            elif field_name.startswith('='):
                return "%s__iexact" % field_name[1:]
            elif field_name.startswith('@'):
                return "%s__search" % field_name[1:]
            else:
                return "%s__icontains" % field_name

        use_distinct = False
        search_fields = self.get_search_fields(request)
        if search_fields and search_term:
            orm_lookups = [construct_search(str(search_field))
                           for search_field in search_fields]
            for bit in search_term.split():
                or_queries = [models.Q(**{orm_lookup: bit})
                              for orm_lookup in orm_lookups]
                queryset = queryset.filter(reduce(operator.or_, or_queries))
            if not use_distinct:
                for search_spec in orm_lookups:
                    if lookup_needs_distinct(self.opts, search_spec):
                        use_distinct = True
                        break

        return queryset, use_distinct 
Example #28
Source File: ops.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def ror_(left, right):
    return operator.or_(right, left) 
Example #29
Source File: test_Signal.py    From myhdl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def testOr(self):
        self.binaryCheck(operator.or_) 
Example #30
Source File: views.py    From djangoSIGE with MIT License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(EditarPermissoesUsuarioView,
                        self).get_context_data(**kwargs)
        user = User.objects.get(pk=self.kwargs['pk'])
        context['user'] = user
        condition = reduce(operator.or_, [Q(codename__icontains=s) for s in [
                           'add_', 'change_', 'view_', 'delete_']])
        context['default_permissions'] = Permission.objects.filter(
            condition, content_type__model__in=DEFAULT_PERMISSION_MODELS)
        context['custom_permissions'] = Permission.objects.filter(
            codename__in=CUSTOM_PERMISSIONS)
        return context