text:
import re
from copy import copy
from datetime import datetime
from typing import Union, Dict, Optional, Any, List

from qutils.models import AttrRef, ItemRef

from .errors import InvalidQuery, UnrecognizedExprType, UnrecognizedJsonableClass

JsonObjectType = Dict[str, Any]
JsonValueType = Union[int, float, str]
JsonType = Union[JsonValueType, JsonObjectType]

class ClassWithSubclassDictMeta(type):
    def __init__(cls, what, bases=None, dict=None):
        super().__init__(what, bases, dict)
        if dict is None:
            return
        is_base = dict.get('base', False)
        if is_base:
            cls.subclasses = {}
        cls.base = is_base
        cls_key = dict.get('key')
        if cls_key is not None:
            if is_base:
                all_cls_subclasses = (getattr(bcl, 'subclasses', None) for bcl in bases)
            else:
                all_cls_subclasses = [getattr(cls, 'subclasses', None)]
            all_cls_subclasses = [c for c in all_cls_subclasses if c is not None]
            if not all_cls_subclasses:
                raise KeyError('class "{}" has key ("{}") but no base class is found'
                               .format(cls.__name__, cls_key))
            for cls_subclasses in all_cls_subclasses:
                cls_existing_subcls = cls_subclasses.get(cls_key)
                if cls_existing_subcls is not None:
                    raise KeyError('key "{}" of class "{}" conflicts with class "{}"'
                                   .format(cls_key, cls.__name__, cls_existing_subcls.__name__))
                cls_subclasses[cls_key] = cls

    def __getitem__(cls, cls_key):
        cls_subclasses = getattr(cls, 'subclasses', None)
        if cls_subclasses is None:
            raise KeyError('no base class is found for class "{}"'.format(cls.__name__))
        subcls = cls_subclasses.get(cls_key)
        if subcls is None:
            raise KeyError('no class has key "{}"'.format(cls_key))
        return subcls

class ClassFromJsonWithSubclassDictMeta(ClassWithSubclassDictMeta):
    def __init__(cls, what, bases=None, dict=None):
        super().__init__(what, bases, dict)
        for bcl in bases:
            if getattr(bcl, 'final', False):
                raise TypeError('class "{}" cannot subclass from "{}" which has been marked as final'
                                .format(cls.__name__, bcl.__name__))
        is_final = dict.get('final', False)
        cls.final = is_final

    def new_from_json(cls, json: JsonType):
        for key in cls.cls_keys_from_json(json):
            try:
                subcls = cls[key]
                if subcls.final:
                    kwargs = subcls.init_args_from_json(json)
                    if kwargs is not None:
                        return subcls(**kwargs)
                    else:
                        raise UnrecognizedJsonableClass('class "{}" is marked final but no init args are defined'
                                                        .format(subcls.__name__))
                elif subcls.new_from_json is cls.new_from_json:
                    raise UnrecognizedJsonableClass('class "{}" constructs an object from json "{!r}" '
                                                    'by calling itself recursively, '
                                                    'no subclass\' construct method can be found'
                                                    .format(subcls.__name__, json))
                else:
                    return subcls.new_from_json(json)
            except (KeyError, UnrecognizedExprType):
                pass
        raise UnrecognizedJsonableClass('cannot recognize class from "{}"'.format(json))

    def cls_keys_from_json(cls, json: JsonType):
        return; yield

    def init_args_from_json(cls, json) -> Optional[JsonObjectType]:
        pass

class Query:
    def to_query(self, type: str):
        method = getattr(self, 'to_query_' + type, None)
        if method is None:
            raise NotImplementedError('generating {} from {!r} is not supported'.format(type, self))
        return method()

    def to_query_json(self) -> str:
        raise NotImplementedError('generating json from {!r} is not implemented'.format(self))

    def to_query_influx(self) -> str:
        raise NotImplementedError('generating InfluxQL from {!r} is not implemented'.format(self))

    def to_query_mysql(self) -> str:
        raise NotImplementedError('generating MySQL from {!r} is not implemented'.format(self))

    def to_query_mongo(self) -> JsonType:
        raise NotImplementedError('generating MongoDB query from {!r} is not implemented'.format(self))

    def to_query_pandas(self) -> str:
        raise NotImplementedError('generating pandas query from {!r} is not implemented.'.format(self))

    def to_query_pluto(self) -> str:
        raise NotImplementedError('generating pluto conditions from {!r} is not implemented.'.format(self))

class Expr(Query, metaclass=ClassFromJsonWithSubclassDictMeta):
    base = True

    def __init__(self):
        self.parent = None

    @classmethod
    def from_json(cls, json: Union['Expr', JsonType]) -> 'Expr':
        expr = cls._from_json(json)

        def add_parent(expr):
            for sub_expr_ref in expr.iter_sub_expr_ref():
                sub_expr_ref.v.parent = expr
                add_parent(sub_expr_ref.v)

        add_parent(expr)
        return expr

    @classmethod
    def _from_json(cls, json: Union['Expr', JsonType]) -> 'Expr':
        if isinstance(json, cls):
            expr = json
        else:
            try:
                expr = cls.new_from_json(json)
            except UnrecognizedJsonableClass as err:
                expr = err
        if not isinstance(expr, cls):
            raise InvalidQuery('Unexpected expression type for json {!r}. Expected "{}", but got "{}({})".'
                               .format(json, cls.__name__, type(expr).__name__, expr))
        return expr

    def __iter__(self):
        return self.iter_expr()

    def transform(self, transform_fn=lambda e: e):
        """
        Expr.transform will traverse recursively starting from expr as the root node, and apply transform_fn on each
        expr node.
        If transform_fn returns the input node itself, nothing happens and the recursion continues.
        If transform_fn returns nothing or None, the node will be eliminated entirely. If an expr subtree is
        syntactically invalid due to elimination of a node in the tree, the entire subtree will be eliminated as well.
        If transform_fn returns a new node, the returned node will replace the original one, and the recursion starting
        from this original node will be discarded.
        Regardless of what transform_fn returns, Expr.transform is guaranteed to return a full new copy of the tree.
        """
        transformed_self = transform_fn(self)
        if transformed_self is None:
            return And([])
        if transformed_self is self:
            transformed_self = copy(self)
            for sub_expr_ref in transformed_self.iter_sub_expr_ref():
                sub_expr = sub_expr_ref.v
                transformed_sub_expr = sub_expr.transform(transform_fn)
                if isinstance(transformed_sub_expr, And) and len(transformed_sub_expr) == 0:
                    if not isinstance(sub_expr, And):
                        return And([])
                sub_expr_ref.v = transformed_sub_expr
        return transformed_self

    @classmethod
    def cls_keys_from_json(cls, json: JsonType):
        if isinstance(json, dict):
            yield 'operator_expr'
        else:
            yield 'literal'

    def iter_expr(self):
        yield self
        for sub_expr_ref in self.iter_sub_expr_ref():
            yield from sub_expr_ref.v.iter_expr()

    def ancestors(self):
        expr = self
        while expr is not None:
            yield expr
            expr = expr.parent

    def iter_sub_expr_ref(self):
        return; yield

class LiteralExpr(Expr):
    base = True
    key = 'literal'

    def __init__(self, literal):
        super().__init__()
        if not self.validate_literal(literal):
            raise InvalidQuery('Invalid type of literal "{}". Expected "{}", but got "{}"'
                               .format(literal, self.key.__name__, type(literal).__name__))
        self.literal = literal

    def __copy__(self):
        return type(self)(self.literal)

    def validate_literal(self, literal):
        return isinstance(self.key, type) and isinstance(literal, self.key)

    @classmethod
    def cls_keys_from_json(cls, json):
        yield type(json)

    @classmethod
    def init_args_from_json(cls, json):
        return {'literal': json}

    def __repr__(self, *args, **kwargs):
        return '{}({!r})'.format(type(self).__name__, self.literal)

class StringLiteral(LiteralExpr):
    final = True
    key = str

    def to_query_json(self) -> JsonType:
        return self.literal

    def to_query_influx(self) -> str:
        return "'{}'".format(self.literal)

    def to_query_mysql(self) -> str:
        return "'{}'".format(self.literal)

    def to_query_mongo(self) -> JsonType:
        return self.literal

    def to_query_pandas(self) -> str:
        return "'{}'".format(self.literal)

    def to_query_pluto(self) -> str:
        return "\"{}\"".format(self.literal)

class BooleanLiteral(LiteralExpr):
    final = True
    key = bool

    def to_query_json(self) -> JsonType:
        return self.literal

    def to_query_influx(self) -> str:
        return repr(self.literal)

    def to_query_mysql(self) -> str:
        return repr(self.literal)

    def to_query_mongo(self) -> JsonType:
        return self.literal

    def to_query_pandas(self) -> str:
        return repr(self.literal)

class IntLiteral(LiteralExpr):
    final = True
    key = int

    def to_query_json(self) -> JsonType:
        return self.literal

    def to_query_influx(self) -> str:
        return repr(self.literal)

    def to_query_mysql(self) -> str:
        return repr(self.literal)

    def to_query_mongo(self) -> JsonType:
        return self.literal

    def to_query_pandas(self) -> str:
        return repr(self.literal)

    def to_query_pluto(self) -> str:
        return repr(self.literal)

class FloatLiteral(LiteralExpr):
    final = True
    key = float

    def to_query_json(self) -> JsonType:
        return self.literal

    def to_query_influx(self) -> str:
        return repr(self.literal)

    def to_query_mysql(self) -> str:
        return repr(self.literal)

    def to_query_mongo(self) -> JsonType:
        return self.literal

    def to_query_pandas(self) -> str:
        return repr(self.literal)

    def to_query_pluto(self) -> str:
        return repr(self.literal)

class DateTimeLiteral(LiteralExpr):
    final = True
    key = datetime

    def to_query_json(self) -> JsonType:
        return self.literal

    def to_query_influx(self) -> str:
        return "'{:%Y-%m-%dT%H:%M:%SZ}'".format(self.literal)

    def to_query_mysql(self) -> str:
        return "'{:%Y-%m-%d %H:%M:%S}'".format(self.literal)

    def to_query_mongo(self) -> JsonType:
        return self.literal

class RegexLiteral(LiteralExpr):
    final = True
    key = 'regex'

    def validate_literal(self, literal):
        return isinstance(literal, str)

    @classmethod
    def cls_keys_from_json(cls, json):
        yield 'regex'

    def to_query_json(self) -> JsonType:
        return self.literal

    def to_query_influx(self) -> str:
        return '/{}/'.format(self.literal)

    def to_query_mysql(self) -> str:
        return "'{}'".format(self.literal)

    def to_query_mongo(self):
        return re.compile(self.literal)

    def to_query_pluto(self) -> str:
        return "\"{}\"".format(self.literal)

class SchemaLiteral(LiteralExpr):
    final = True
    key = 'schema'

    def validate_literal(self, literal):
        return isinstance(literal, str)

    @classmethod
    def cls_keys_from_json(cls, json):
        yield 'schema'

    def to_query_json(self) -> JsonType:
        return self.literal

    def to_query_influx(self) -> str:
        return '"{}"'.format(self.literal)

    def to_query_mysql(self) -> str:
        return self.literal

    def to_query_mongo(self) -> JsonType:
        return self.literal

    def to_query_pandas(self) -> str:
        return self.literal

    def to_query_pluto(self) -> str:
        return self.literal

# Operator Expr
class OperatorExpr(Expr):
    base = True
    key = 'operator_expr'

    operator_influx = None
    operator_mysql = None
    operator_mongo = None
    operator_pandas = None
    operator_pluto = None

    @classmethod
    def normalize_eval_expr_dict(cls, filter: dict) -> dict:
        exprs = []
        for tag, tag_filter in sorted(filter.items()):
            if isinstance(tag_filter, str):
                if tag_filter.startswith('/') and tag_filter.endswith('/'):
                    exprs.append({tag: {MatchRegex.key: tag_filter[1:-1]}})
                else:
                    exprs.append({tag: {EqualValue.key: tag_filter}})
            elif isinstance(tag_filter, (int, float)):
                exprs.append({tag: {EqualValue.key: tag_filter}})
            elif isinstance(tag_filter, list):
                if tag == And.key:
                    exprs.extend(tag_filter)
                elif tag == All.key:
                    exprs.append({All.key: tag_filter})
                elif tag == Or.key:
                    exprs.append({Or.key: tag_filter})
                elif tag == Any.key:
                    exprs.append({Any.key: tag_filter})
                else:
                    exprs.append({tag: {In.key: tag_filter}})
            elif isinstance(tag_filter, dict):
                if tag == Not.key:
                    exprs.append({Not.key: tag_filter})
                else:
                    for op, condition in sorted(tag_filter.items()):
                        if isinstance(condition, (str, int, float, datetime)):
                            exprs.append({tag: {op: condition}})
                        elif isinstance(condition, list):
                            if op in (In.key, NotIn.key):
                                exprs.append({tag: {op: condition}})
                            else:
                                raise InvalidQuery('"{}" operator cannot be applied on a list.'
                                                   .format(op))
                        else:
                            raise InvalidQuery('Query condition is unrecognized: {!r}'
                                               .format(condition))
            else:
                raise InvalidQuery('Invalid query "{{ {}: {} }}". '
                                   'A tag\' filter must be of one of the following types: '
                                   'regex / string / numerical / list / a dict {{ operator: operand }}.'
                                   .format(tag, tag_filter))
        if len(exprs) == 1:
            return exprs[0]
        else:
            return {And.key: exprs}

    @classmethod
    def new_from_json(cls, json: dict):
        """
        :param json:
        :return:
        :raise: UnrecognizedExprType
        """
        json = cls.normalize_eval_expr_dict(json)
        return type(cls).new_from_json(cls, json)

    @classmethod
    def cls_keys_from_json(cls, json):
        k, v = next(iter(json.items()))
        yield k
        if isinstance(v, dict) and v:
            yield next(iter(v))

# Boolean Expr
class BooleanExpr(OperatorExpr):
    pass

class UnaryBooleanExpr(BooleanExpr):
    def __init__(self, operand: Union[Expr, JsonObjectType]):
        super().__init__()
        self.operand = BooleanExpr._from_json(operand)

    def __copy__(self):
        return type(self)(self.operand)

    @classmethod
    def init_args_from_json(cls, json):
        try:
            _, operand = next(iter(json.items()))
            return {'operand': operand}
        except StopIteration:
            pass

    def iter_sub_expr_ref(self):
        yield AttrRef(self, 'operand')

    def __repr__(self):
        return '{}(operand={})'.format(type(self).__name__, self.operand)

class Not(UnaryBooleanExpr):
    final = True
    key = '__not__'
    # operator_influx = '<not>'
    operator_mysql = 'NOT'
    operator_mongo = '$not'
    operator_pandas = '~'
    operator_pluto = 'it is not true that'

    def to_query_json(self) -> JsonType:
        return {self.key: self.operand.to_query_json()}

    # def to_query_influx(self):
    #     return '{} {}'.format(self.operator_influx, self.operand.to_query_influx())

    def to_query_mysql(self) -> str:
        return '{} ({})'.format(self.operator_mysql, self.operand.to_query_mysql())

    def to_query_mongo(self) -> JsonType:
        tmp_mongo_query = self.operand.to_query_mongo()
        k, v = next(iter(tmp_mongo_query.items()))
        return {k: {self.operator_mongo: v}}

    def to_query_pandas(self) -> str:
        return '{}({})'.format(self.operator_pandas, self.operand.to_query_pandas())

    def to_query_pluto(self) -> str:
        return '{} {}'.format(self.operator_pluto, self.operand.to_query_pluto())

class BinaryBooleanExpr(BooleanExpr):
    def __init__(self, left, right):
        super().__init__()
        self.left = SchemaLiteral._from_json(left)
        self.right = right

    def __copy__(self):
        return type(self)(self.left, self.right)

    @classmethod
    def init_args_from_json(cls, json):
        try:
            left, right_expr = next(iter(json.items()))
            op, right = next(iter(right_expr.items()))
            return {'left': left, 'right': right}
        except StopIteration:
            pass

    def __repr__(self):
        return '{}(left={}, right={})'.format(type(self).__name__, self.left, self.right)

class BinaryComparisonExpr(BinaryBooleanExpr):
    def iter_sub_expr_ref(self):
        yield AttrRef(self, 'left')
        yield AttrRef(self, 'right')

    def to_query_json(self) -> JsonType:
        if self.key is None:
            raise NotImplementedError('generating json from operator "{}" is not implemented'.format(self.key))
        return {self.left.to_query_json(): {self.key: self.right.to_query_json()}}

    def to_query_influx(self):
        if self.operator_influx is None:
            raise NotImplementedError('generating InfluxQL from operator "{}" is not implemented'.format(self.key))
        return '{} {} {}'.format(self.left.to_query_influx(), self.operator_influx, self.right.to_query_influx())

    def to_query_mysql(self) -> str:
        if self.operator_mysql is None:
            raise NotImplementedError('generating MySQL from operator "{}" is not implemented'.format(self.key))
        return '{} {} {}'.format(self.left.to_query_mysql(), self.operator_mysql, self.right.to_query_mysql())

    def to_query_mongo(self) -> JsonType:
        if self.operator_mongo is None:
            raise NotImplementedError('generating MongoDB query from operator "{}" is not implemented'.format(self.key))
        return {self.left.to_query_mongo(): {self.operator_mongo: self.right.to_query_mongo()}}

    def to_query_pandas(self) -> str:
        if self.operator_pandas is None:
            raise NotImplementedError('generating pandas query from operator "{}" is not implemented'.format(self.key))
        return '{} {} {}'.format(self.left.to_query_pandas(), self.operator_pandas, self.right.to_query_pandas())

    def to_query_pluto(self) -> str:
        if self.operator_pluto is None:
            raise NotImplementedError('generating pluto conditions from operator "{}" is not implemented'.format(self.key))
        return '{} {} {}'.format(self.left.to_query_pluto(), self.operator_pluto, self.right.to_query_pluto())

class FieldCompareValueExpr(BinaryComparisonExpr):
    def __init__(self, left: Union[SchemaLiteral, str], right):
        super().__init__(left, right)
        self.right = LiteralExpr._from_json(right)

class FieldCompareFieldExpr(BinaryComparisonExpr):
    def __init__(self, left: Union[SchemaLiteral, str], right: Union[SchemaLiteral, str]):
        super().__init__(left, right)
        if not isinstance(self.right, (SchemaLiteral, str)):
            raise InvalidQuery('The operand of "{}" must be of string type referring to a field name.'.format(self.key))
        self.right = SchemaLiteral._from_json(right)

class FieldAssertionExpr(BinaryComparisonExpr):
    def __init__(self, left: Union[SchemaLiteral, str], right: Union[BooleanLiteral, bool]):
        super().__init__(left, right)
        if not isinstance(self.right, (BooleanLiteral, bool)):
            raise InvalidQuery('The operand of "{}" must be either true or false.'.format(self.key))
        self.right = BooleanLiteral._from_json(right)

class Equal:
    operator_influx = '='
    operator_mysql = '='
    operator_pandas = '=='
    operator_pluto = 'equals'

# Inheritance order matters! WHY??
class EqualValue(Equal, FieldCompareValueExpr):
    final = True
    key = '__eq__'

    operator_mongo = '$eq'

class EqualField(Equal, FieldCompareFieldExpr):
    final = True
    key = '__eqf__'

class NotEqual:
    operator_influx = '!='
    operator_mysql = '<>'
    operator_pandas = '!='
    operator_pluto = 'does not equal'

class NotEqualValue(NotEqual, FieldCompareValueExpr):
    final = True
    key = '__neq__'

    operator_mongo = '$ne'

class NotEqualField(NotEqual, FieldCompareFieldExpr):
    final = True
    key = '__neqf__'

class GreaterThan:
    operator_influx = '>'
    operator_mysql = '>'
    operator_pandas = '>'
    operator_pluto = 'is more than'

class GreaterThanValue(GreaterThan, FieldCompareValueExpr):
    final = True
    key = '__gt__'

    operator_mongo = '$gt'

class GreaterThanField(GreaterThan, FieldCompareFieldExpr):
    final = True
    key = '__gtf__'

class GreaterThanOrEqual:
    operator_influx = '>='
    operator_mysql = '>='
    operator_pandas = '>='
    operator_pluto = 'is at least'

class GreaterThanOrEqualValue(GreaterThanOrEqual, FieldCompareValueExpr):
    final = True
    key = '__gte__'

    operator_mongo = '$gte'

class GreaterThanOrEqualField(GreaterThanOrEqual, FieldCompareFieldExpr):
    final = True
    key = '__gtef__'

class LessThan:
    operator_influx = '<'
    operator_mysql = '<'
    operator_pandas = '<'
    operator_pluto = 'is less than'

class LessThanValue(LessThan, FieldCompareValueExpr):
    final = True
    key = '__lt__'

    operator_mongo = '$lt'

class LessThanField(LessThan, FieldCompareFieldExpr):
    final = True
    key = '__ltf__'

class LessThanOrEqual:
    operator_influx = '<='
    operator_mysql = '<='
    operator_pandas = '<='
    operator_pluto = 'is at most'

class LessThanOrEqualValue(LessThanOrEqual, FieldCompareValueExpr):
    final = True
    key = '__lte__'

    operator_mongo = '$lte'

class LessThanOrEqualField(LessThanOrEqual, FieldCompareFieldExpr):
    final = True
    key = '__ltef__'

class MatchRegex(FieldCompareValueExpr):
    final = True
    key = '__regex__'
    operator_influx = '=~'
    operator_mysql = 'REGEXP'

    def __init__(self, left, right):
        super().__init__(left, right)
        self.right = RegexLiteral._from_json(right)

    def to_query_mongo(self) -> JsonType:
        return {self.left.to_query_mongo(): self.right.to_query_mongo()}

class InverseMatchRegex(FieldCompareValueExpr):
    final = True
    key = '__iregex__'
    operator_influx = '!~'
    operator_mysql = 'NOT REGEXP'

    def __init__(self, left, right):
        super().__init__(left, right)
        self.right = RegexLiteral._from_json(right)

    def to_query_mongo(self) -> JsonType:
        return {self.left.to_query_mongo(): {'$not': self.right.to_query_mongo()}}

class Null(FieldAssertionExpr):
    final = True
    key = '__null__'

    def to_query_mysql(self) -> str:
        return '{} {}'.format(self.left.to_query_mysql(), 'is NULL' if self.right.literal else 'is NOT NULL')

    def to_query_mongo(self) -> JsonType:
        return {self.left.to_query_mongo(): {'$eq' if self.right.literal else '$ne': None}}

    def to_query_pandas(self) -> str:
        return '{}pandas.isnull({})'.format('' if self.right.literal else '~', self.left.to_query_pandas())

    def to_query_pluto(self) -> str:
        return '{} {}'.format(self.left.to_query_pluto(), 'is null' if self.right.literal else 'is not null')

class Missing(FieldAssertionExpr):
    final = True
    key = '__missing__'

    def to_query_mongo(self) -> JsonType:
        return {self.left.to_query_mongo(): {'$exists': not self.right.literal}}

class FieldCompareListExpr(BinaryBooleanExpr):
    def __init__(self, left: Union[SchemaLiteral, str], right: List[Union[LiteralExpr, JsonValueType]]):
        super().__init__(left, right)
        if not isinstance(self.right, list):
            raise InvalidQuery('The operand of "{}" must be a list.'.format(self.key))
        self.right = [LiteralExpr._from_json(e) for e in right]

    def __copy__(self):
        return type(self)(self.left, list(self.right))

    def iter_sub_expr_ref(self):
        yield AttrRef(self, 'left')
        for i, expr in enumerate(self.right):
            yield ItemRef(self.right, i)

    def to_query_json(self) -> JsonType:
        return {self.left.to_query_json(): {self.key: [e.to_query_json() for e in self.right]}}

    def to_query_influx(self) -> str:
        return self.equivalent_fallback_expr().to_query_influx()

    def to_query_mysql(self) -> str:
        return '{} {} ({})'.format(self.left.to_query_mysql(), self.operator_mysql,
                                   ', '.join(e.to_query_mysql() for e in self.right))

    def to_query_mongo(self) -> JsonType:
        return {self.left.to_query_mongo(): {self.operator_mongo: [e.to_query_mongo() for e in self.right]}}

    def to_query_pandas(self):
        return self.equivalent_fallback_expr().to_query_pandas()

    def to_query_pluto(self) -> str:
        return self.equivalent_fallback_expr().to_query_pluto()

    def equivalent_fallback_expr(self):
        raise NotImplementedError('No fallback equivalent exprs for {}'.format(self))

class In(FieldCompareListExpr):
    final = True
    key = '__in__'

    operator_mysql = 'IN'
    operator_mongo = '$in'

    def equivalent_fallback_expr(self):
        return Or([EqualValue(self.left, e) for e in self.right])

class NotIn(FieldCompareListExpr):
    final = True
    key = '__nin__'

    operator_mysql = 'NOT IN'
    operator_mongo = '$nin'

    def equivalent_fallback_expr(self):
        return And([NotEqualValue(self.left, e) for e in self.right])

class LogicalExpr(BooleanExpr):
    def __init__(self, exprs: List[Union[BooleanExpr, JsonObjectType]]):
        super().__init__()
        if not isinstance(exprs, list):
            raise InvalidQuery('The "{}" operator is not applied on a list.'.format(self.key))
        exprs = (BooleanExpr._from_json(e) for e in exprs)
        self.exprs = [e for e in exprs if isinstance(e, LogicalExpr) and len(e) > 0 or not isinstance(e, LogicalExpr)]

    def __copy__(self):
        return type(self)(list(self.exprs))

    def to_query_json(self) -> JsonType:
        if self.key is None:
            raise NotImplementedError('generating json from operator "{}" is not implemented'.format(self.key))
        return {self.key: [e.to_query_json() for e in self.exprs]}

    def to_query_influx(self):
        if self.operator_influx is None:
            raise NotImplementedError('generating InfluxQL from operator "{}" is not implemented'.format(self.key))
        return ' {} '.format(self.operator_influx).join('(' + e.to_query_influx() + ')' for e in self.exprs)

    def to_query_mysql(self):
        if self.operator_mysql is None:
            raise NotImplementedError('generating MySQL from operator "{}" is not implemented'.format(self.key))
        return ' {} '.format(self.operator_mysql).join('(' + e.to_query_mysql() + ')' for e in self.exprs)

    def to_query_mongo(self) -> JsonType:
        if self.operator_mongo is None:
            raise NotImplementedError('generating MongoDB query from operator "{}" is not implemented'.format(self.key))
        return {self.operator_mongo: [e.to_query_mongo() for e in self.exprs]}

    def to_query_pandas(self) -> str:
        if self.operator_pandas is None:
            raise NotImplementedError('generating pandas query from operator "{}" is not implemented'.format(self.key))
        return ' {} '.format(self.operator_pandas).join('(' + e.to_query_pandas() + ')' for e in self.exprs)

    def to_query_pluto(self) -> str:
        if self.operator_pluto is None:
            raise NotImplementedError('generating pluto conditions from operator "{}" is not implemented'.format(self.key))
        return ' {} '.format(self.operator_pluto).join('(' + e.to_query_pluto() + ')' for e in self.exprs)

    def __repr__(self):
        return '{}({!r})'.format(type(self).__name__, self.exprs)

    def __len__(self):
        return len(self.exprs)

    def transform(self, transform_fn=lambda e: e):
        transformed_self = transform_fn(self)
        if transformed_self is None:
            return And([])
        if transformed_self is self:
            transformed_sub_exprs = (e.transform(transform_fn) for e in self.exprs)
            transformed_sub_exprs = [e for e in transformed_sub_exprs if not (isinstance(e, And) and len(e) == 0)]
            transformed_self = type(self)(transformed_sub_exprs)
        return transformed_self

    @classmethod
    def init_args_from_json(cls, json):
        try:
            exprs = next(iter(json.values()))
            return {'exprs': exprs}
        except StopIteration:
            pass

    def iter_sub_expr_ref(self):
        for i, expr in enumerate(self.exprs):
            yield ItemRef(self.exprs, i)

class And_(LogicalExpr):
    operator_influx = 'AND'
    operator_mysql = 'AND'
    operator_mongo = '$and'
    operator_pandas = '&'
    operator_pluto = 'and'

class And(And_):
    final = True
    key = '__and__'

class All(And_):
    final = True
    key = '__all__'

    def to_query_pluto(self):
        return 'all of the following conditions are true :\n' + \
               '\n'.join(sorted('      - (' + e.to_query_pluto() + ')' for e in self.exprs))

class Or_(LogicalExpr):
    operator_influx = 'OR'
    operator_mysql = 'OR'
    operator_mongo = '$or'
    operator_pandas = '|'
    operator_pluto = 'or'

class Or(Or_):
    final = True
    key = '__or__'

class Any(Or_):
    final = True
    key = '__any__'

    def to_query_pluto(self):
        return 'any of the following conditions is true :\n' + \
               '\n'.join(sorted('      - (' + e.to_query_pluto() + ')' for e in self.exprs))

# Statement
class Stmt(Query):
    pass

class Select(Stmt):
    def __init__(self, table: Union[SchemaLiteral, str],
                 retention_policy: Optional[Union[SchemaLiteral, str]] = None,
                 db: Optional[Union[SchemaLiteral, str]] = None,
                 columns: Optional[List[Union[SchemaLiteral, str]]] = None,
                 where: Optional[Union[BooleanExpr, JsonObjectType]] = None):
        super().__init__()
        self.table = SchemaLiteral._from_json(table)
        self.retention_policy = retention_policy and SchemaLiteral._from_json(retention_policy)
        self.db = db and SchemaLiteral._from_json(db)
        self.columns = columns and [SchemaLiteral._from_json(c) for c in columns]
        self.where = where and BooleanExpr._from_json(where)

    def __copy__(self):
        return type(self)(self.table, self.retention_policy, self.db, self.columns, self.where)

    def to_query_influx(self):
        if self.columns:
            ql_select = 'SELECT ' + ','.join(c.to_query_influx() for c in self.columns)
        else:
            ql_select = 'SELECT *'

        if self.db:
            if self.retention_policy:
                ql_db = self.db.to_query_influx() + '.' + self.retention_policy.to_query_influx() + '.' + self.table.to_query_influx()
            else:
                ql_db = self.db.to_query_influx() + '..' + self.table.to_query_influx()
        elif self.retention_policy:
            ql_db = self.retention_policy.to_query_influx() + '.' + self.table.to_query_influx()
        else:
            ql_db = self.table.to_query_influx()
        ql_from = ' FROM ' + ql_db

        if self.where:
            ql_where = self.where.to_query_influx()
            if ql_where:
                ql_where = ' WHERE ' + ql_where
        else:
            ql_where = ''

        return ql_select + ql_from + ql_where

    def to_query_mysql(self):
        if self.columns:
            ql_select = 'SELECT ' + ','.join(c.to_query_mysql() for c in self.columns)
        else:
            ql_select = 'SELECT *'

        if self.db:
            ql_db = self.db.to_query_mysql() + '.' + self.table.to_query_mysql()
        else:
            ql_db = self.table.to_query_mysql()
        ql_from = ' FROM ' + ql_db

        if self.where:
            ql_where = self.where.to_query_mysql()
            if ql_where:
                ql_where = ' WHERE ' + ql_where
        else:
            ql_where = ''

        return ql_select + ql_from + ql_where

class ShowTagKeys(Stmt):
    def __init__(self, measurement: Optional[Union[SchemaLiteral, str]] = None,
                 retention_policy: Optional[Union[SchemaLiteral, str]] = None,
                 db: Optional[Union[SchemaLiteral, str]] = None,
                 where: Optional[Union[BooleanExpr, JsonObjectType]] = None):
        super().__init__()
        self.measurement = measurement and SchemaLiteral._from_json(measurement)
        self.retention_policy = retention_policy and SchemaLiteral._from_json(retention_policy)
        self.db = db and SchemaLiteral._from_json(db)
        self.where = where and BooleanExpr._from_json(where)

    def __copy__(self):
        return type(self)(self.measurement, self.retention_policy, self.db, self.where)

    def to_query_influx(self):
        if self.db:
            ql_on = ' ON ' + self.db.to_query_influx()
        else:
            ql_on = ''

        if self.measurement:
            if self.retention_policy:
                ql_from = ' FROM ' + self.retention_policy.to_query_influx() + '.' + self.measurement.to_query_influx()
            else:
                ql_from = ' FROM ' + self.measurement.to_query_influx()
        else:
            ql_from = ''

        if self.where:
            ql_where = self.where.to_query_influx()
            if ql_where:
                ql_where = ' WHERE ' + ql_where
        else:
            ql_where = ''

        return 'SHOW TAG KEYS' + ql_on + ql_from + ql_where

class ShowColumns(Stmt):
    def __init__(self, table: Union[SchemaLiteral, str], db: Optional[Union[SchemaLiteral, str]] = None):
        super().__init__()
        self.table = SchemaLiteral._from_json(table)
        self.db = db and SchemaLiteral._from_json(db)

    def __copy__(self):
        return type(self)(self.table, self.db)

    def to_query_influx(self):
        if self.db:
            ql_on = ' ON ' + self.db.to_query_influx()
        else:
            ql_on = ''

        ql_from = ' FROM ' + self.table.to_query_influx()

        return 'SHOW TAG KEYS' + ql_on + ql_from

    def to_query_mysql(self):
        if self.db:
            ql_from = ' FROM ' + self.db.to_query_mysql() + '.' + self.table.to_query_mysql()
        else:
            ql_from = ' FROM ' + self.table.to_query_mysql()

        return 'SHOW COLUMNS' + ql_from


text:
interface IThroughTransform<T> {
    (chunk: T, encoding: string, callback: () => void): any;
}

interface IThrough2 {
    <T>(transform: IThroughTransform<T>): any;
    obj<T>(transform: IThroughTransform<T>): any;
}

declare var __IThrough2: IThrough2;
declare module "through2" {
    export = __IThrough2;
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>EnqueteWeb</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/business-casual.css" rel="stylesheet">

    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">

EnqueteWeb

Engenharia de Software - 2015.2 - UFRJ

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                Business Casual

                        Home

                        Informações

                        Contato

Engenharia de Software -
                        UFRJ

Período:

2015.2

Professores:

Guilherme Horta Travassos

Breno França

Emails:

name@example.com

name@example.com

name@example.com

UFRJ - Engenharia de Software 2015.2

                     Grupo I : Diego Cruz, Patrícia Kovaleski, Victor Cardoso e Vinícius Campos


text:
database/hbase
================


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Folio {

  /// Holder for reflection information generated from folio/reservation_folio_summary.proto
  public static partial class ReservationFolioSummaryReflection {

    #region Descriptor
    /// File descriptor for folio/reservation_folio_summary.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static ReservationFolioSummaryReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "CiVmb2xpby9yZXNlcnZhdGlvbl9mb2xpb19zdW1tYXJ5LnByb3RvEhFob2xt",
            "cy50eXBlcy5mb2xpbxouYm9va2luZy9pbmRpY2F0b3JzL3Jlc2VydmF0aW9u",
            "X2luZGljYXRvci5wcm90bxozZm9saW8vZ3VhcmFudGVlcy9yZXNlcnZhdGlv",
            "bl9ndWFyYW50ZWVfc3RhdHVzLnByb3RvGhtmb2xpby9mb2xpb19pbmRpY2F0",
            "b3IucHJvdG8aH2ZvbGlvL21hc3Rlcl9mb2xpb19zdGF0dXMucHJvdG8aMnRl",
            "bmFuY3lfY29uZmlnL2luZGljYXRvcnMvcHJvcGVydHlfaW5kaWNhdG9yLnBy",
            "b3RvGh1wcmltaXRpdmUvcGJfbG9jYWxfZGF0ZS5wcm90bxosYm9va2luZy9y",
            "ZXNlcnZhdGlvbnMvcmVzZXJ2YXRpb25fc3RhdGUucHJvdG8aKnByaW1pdGl2",
            "ZS9wYl9pbmNsdXNpdmVfb3BzZGF0ZV9yYW5nZS5wcm90byL4BQoXUmVzZXJ2",
            "YXRpb25Gb2xpb1N1bW1hcnkSTAoOcmVzZXJ2YXRpb25faWQYASABKAsyNC5o",
            "b2xtcy50eXBlcy5ib29raW5nLmluZGljYXRvcnMuUmVzZXJ2YXRpb25JbmRp",
            "Y2F0b3ISQQoTbWFzdGVyX2ZvbGlvX3N0YXR1cxgCIAEoDjIkLmhvbG1zLnR5",
            "cGVzLmZvbGlvLk1hc3RlckZvbGlvU3RhdHVzEjcKDG1hc3Rlcl9mb2xpbxgD",
            "IAEoCzIhLmhvbG1zLnR5cGVzLmZvbGlvLkZvbGlvSW5kaWNhdG9yEjgKDWNs",
            "aWVudF9mb2xpb3MYBSADKAsyIS5ob2xtcy50eXBlcy5mb2xpby5Gb2xpb0lu",
            "ZGljYXRvchJWChBndWFyYW50ZWVfc3RhdHVzGAYgASgOMjwuaG9sbXMudHlw",
            "ZXMuYm9va2luZy5yZXNlcnZhdGlvbnMuUmVzZXJ2YXRpb25HdWFyYW50ZWVT",
            "dGF0dXMSPAoQZ3VhcmFudGVlX2R1ZV9vbhgHIAEoCzIiLmhvbG1zLnR5cGVz",
            "LnByaW1pdGl2ZS5QYkxvY2FsRGF0ZRJPCg1ob3N0X3Byb3BlcnR5GAggASgL",
            "MjguaG9sbXMudHlwZXMudGVuYW5jeV9jb25maWcuaW5kaWNhdG9ycy5Qcm9w",
            "ZXJ0eUluZGljYXRvchJOChJtYXN0ZXJfZm9saW9fc3RhdGUYCSABKA4yMi5o",
            "b2xtcy50eXBlcy5ib29raW5nLnJlc2VydmF0aW9ucy5SZXNlcnZhdGlvblN0",
            "YXRlElcKGWNsaWVudF9mb2xpb19yZXNlcnZhdGlvbnMYCiADKAsyNC5ob2xt",
            "cy50eXBlcy5ib29raW5nLmluZGljYXRvcnMuUmVzZXJ2YXRpb25JbmRpY2F0",
            "b3ISSQoRbWFzdGVyX2RhdGVfcmFuZ2UYCyABKAsyLi5ob2xtcy50eXBlcy5w",
            "cmltaXRpdmUuUGJJbmNsdXNpdmVPcHNkYXRlUmFuZ2VCFKoCEUhPTE1TLlR5",
            "cGVzLkZvbGlvYgZwcm90bzM="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Folio.Guarantees.ReservationGuaranteeStatusReflection.Descriptor, global::HOLMS.Types.Folio.FolioIndicatorReflection.Descriptor, global::HOLMS.Types.Folio.MasterFolioStatusReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.ReservationStateReflection.Descriptor, global::HOLMS.Types.Primitive.PbInclusiveOpsdateRangeReflection.Descriptor, },
          new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Folio.ReservationFolioSummary), global::HOLMS.Types.Folio.ReservationFolioSummary.Parser, new[]{ "ReservationId", "MasterFolioStatus", "MasterFolio", "ClientFolios", "GuaranteeStatus", "GuaranteeDueOn", "HostProperty", "MasterFolioState", "ClientFolioReservations", "MasterDateRange" }, null, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  public sealed partial class ReservationFolioSummary : pb::IMessage<ReservationFolioSummary> {
    private static readonly pb::MessageParser<ReservationFolioSummary> _parser = new pb::MessageParser<ReservationFolioSummary>(() => new ReservationFolioSummary());
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public static pb::MessageParser<ReservationFolioSummary> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::HOLMS.Types.Folio.ReservationFolioSummaryReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public ReservationFolioSummary() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public ReservationFolioSummary(ReservationFolioSummary other) : this() {
      ReservationId = other.reservationId_ != null ? other.ReservationId.Clone() : null;
      masterFolioStatus_ = other.masterFolioStatus_;
      MasterFolio = other.masterFolio_ != null ? other.MasterFolio.Clone() : null;
      clientFolios_ = other.clientFolios_.Clone();
      guaranteeStatus_ = other.guaranteeStatus_;
      GuaranteeDueOn = other.guaranteeDueOn_ != null ? other.GuaranteeDueOn.Clone() : null;
      HostProperty = other.hostProperty_ != null ? other.HostProperty.Clone() : null;
      masterFolioState_ = other.masterFolioState_;
      clientFolioReservations_ = other.clientFolioReservations_.Clone();
      MasterDateRange = other.masterDateRange_ != null ? other.MasterDateRange.Clone() : null;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public ReservationFolioSummary Clone() {
      return new ReservationFolioSummary(this);
    }

    /// Field number for the "reservation_id" field.
    public const int ReservationIdFieldNumber = 1;
    private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservationId_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Booking.Indicators.ReservationIndicator ReservationId {
      get { return reservationId_; }
      set {
        reservationId_ = value;
      }
    }

    /// Field number for the "master_folio_status" field.
    public const int MasterFolioStatusFieldNumber = 2;
    private global::HOLMS.Types.Folio.MasterFolioStatus masterFolioStatus_ = 0;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Folio.MasterFolioStatus MasterFolioStatus {
      get { return masterFolioStatus_; }
      set {
        masterFolioStatus_ = value;
      }
    }

    /// Field number for the "master_folio" field.
    public const int MasterFolioFieldNumber = 3;
    private global::HOLMS.Types.Folio.FolioIndicator masterFolio_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Folio.FolioIndicator MasterFolio {
      get { return masterFolio_; }
      set {
        masterFolio_ = value;
      }
    }

    /// Field number for the "client_folios" field.
    public const int ClientFoliosFieldNumber = 5;
    private static readonly pb::FieldCodec<global::HOLMS.Types.Folio.FolioIndicator> _repeated_clientFolios_codec
        = pb::FieldCodec.ForMessage(42, global::HOLMS.Types.Folio.FolioIndicator.Parser);
    private readonly pbc::RepeatedField<global::HOLMS.Types.Folio.FolioIndicator> clientFolios_ = new pbc::RepeatedField<global::HOLMS.Types.Folio.FolioIndicator>();
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public pbc::RepeatedField<global::HOLMS.Types.Folio.FolioIndicator> ClientFolios {
      get { return clientFolios_; }
    }

    /// Field number for the "guarantee_status" field.
    public const int GuaranteeStatusFieldNumber = 6;
    private global::HOLMS.Types.Folio.Guarantees.ReservationGuaranteeStatus guaranteeStatus_ = 0;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Folio.Guarantees.ReservationGuaranteeStatus GuaranteeStatus {
      get { return guaranteeStatus_; }
      set {
        guaranteeStatus_ = value;
      }
    }

    /// Field number for the "guarantee_due_on" field.
    public const int GuaranteeDueOnFieldNumber = 7;
    private global::HOLMS.Types.Primitive.PbLocalDate guaranteeDueOn_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Primitive.PbLocalDate GuaranteeDueOn {
      get { return guaranteeDueOn_; }
      set {
        guaranteeDueOn_ = value;
      }
    }

    /// Field number for the "host_property" field.
    public const int HostPropertyFieldNumber = 8;
    private global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator hostProperty_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator HostProperty {
      get { return hostProperty_; }
      set {
        hostProperty_ = value;
      }
    }

    /// Field number for the "master_folio_state" field.
    public const int MasterFolioStateFieldNumber = 9;
    private global::HOLMS.Types.Booking.Reservations.ReservationState masterFolioState_ = 0;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Booking.Reservations.ReservationState MasterFolioState {
      get { return masterFolioState_; }
      set {
        masterFolioState_ = value;
      }
    }

    /// Field number for the "client_folio_reservations" field.
    public const int ClientFolioReservationsFieldNumber = 10;
    private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> _repeated_clientFolioReservations_codec
        = pb::FieldCodec.ForMessage(82, global::HOLMS.Types.Booking.Indicators.ReservationIndicator.Parser);
    private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> clientFolioReservations_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Indicators.ReservationIndicator>();
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public pbc::RepeatedField<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> ClientFolioReservations {
      get { return clientFolioReservations_; }
    }

    /// Field number for the "master_date_range" field.
    public const int MasterDateRangeFieldNumber = 11;
    private global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange masterDateRange_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange MasterDateRange {
      get { return masterDateRange_; }
      set {
        masterDateRange_ = value;
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override bool Equals(object other) {
      return Equals(other as ReservationFolioSummary);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public bool Equals(ReservationFolioSummary other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (!object.Equals(ReservationId, other.ReservationId)) return false;
      if (MasterFolioStatus != other.MasterFolioStatus) return false;
      if (!object.Equals(MasterFolio, other.MasterFolio)) return false;
      if(!clientFolios_.Equals(other.clientFolios_)) return false;
      if (GuaranteeStatus != other.GuaranteeStatus) return false;
      if (!object.Equals(GuaranteeDueOn, other.GuaranteeDueOn)) return false;
      if (!object.Equals(HostProperty, other.HostProperty)) return false;
      if (MasterFolioState != other.MasterFolioState) return false;
      if(!clientFolioReservations_.Equals(other.clientFolioReservations_)) return false;
      if (!object.Equals(MasterDateRange, other.MasterDateRange)) return false;
      return true;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override int GetHashCode() {
      int hash = 1;
      if (reservationId_ != null) hash ^= ReservationId.GetHashCode();
      if (MasterFolioStatus != 0) hash ^= MasterFolioStatus.GetHashCode();
      if (masterFolio_ != null) hash ^= MasterFolio.GetHashCode();
      hash ^= clientFolios_.GetHashCode();
      if (GuaranteeStatus != 0) hash ^= GuaranteeStatus.GetHashCode();
      if (guaranteeDueOn_ != null) hash ^= GuaranteeDueOn.GetHashCode();
      if (hostProperty_ != null) hash ^= HostProperty.GetHashCode();
      if (MasterFolioState != 0) hash ^= MasterFolioState.GetHashCode();
      hash ^= clientFolioReservations_.GetHashCode();
      if (masterDateRange_ != null) hash ^= MasterDateRange.GetHashCode();
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void WriteTo(pb::CodedOutputStream output) {
      if (reservationId_ != null) {
        output.WriteRawTag(10);
        output.WriteMessage(ReservationId);
      }
      if (MasterFolioStatus != 0) {
        output.WriteRawTag(16);
        output.WriteEnum((int) MasterFolioStatus);
      }
      if (masterFolio_ != null) {
        output.WriteRawTag(26);
        output.WriteMessage(MasterFolio);
      }
      clientFolios_.WriteTo(output, _repeated_clientFolios_codec);
      if (GuaranteeStatus != 0) {
        output.WriteRawTag(48);
        output.WriteEnum((int) GuaranteeStatus);
      }
      if (guaranteeDueOn_ != null) {
        output.WriteRawTag(58);
        output.WriteMessage(GuaranteeDueOn);
      }
      if (hostProperty_ != null) {
        output.WriteRawTag(66);
        output.WriteMessage(HostProperty);
      }
      if (MasterFolioState != 0) {
        output.WriteRawTag(72);
        output.WriteEnum((int) MasterFolioState);
      }
      clientFolioReservations_.WriteTo(output, _repeated_clientFolioReservations_codec);
      if (masterDateRange_ != null) {
        output.WriteRawTag(90);
        output.WriteMessage(MasterDateRange);
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public int CalculateSize() {
      int size = 0;
      if (reservationId_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReservationId);
      }
      if (MasterFolioStatus != 0) {
        size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) MasterFolioStatus);
      }
      if (masterFolio_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(MasterFolio);
      }
      size += clientFolios_.CalculateSize(_repeated_clientFolios_codec);
      if (GuaranteeStatus != 0) {
        size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) GuaranteeStatus);
      }
      if (guaranteeDueOn_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(GuaranteeDueOn);
      }
      if (hostProperty_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(HostProperty);
      }
      if (MasterFolioState != 0) {
        size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) MasterFolioState);
      }
      size += clientFolioReservations_.CalculateSize(_repeated_clientFolioReservations_codec);
      if (masterDateRange_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(MasterDateRange);
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void MergeFrom(ReservationFolioSummary other) {
      if (other == null) {
        return;
      }
      if (other.reservationId_ != null) {
        if (reservationId_ == null) {
          reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
        }
        ReservationId.MergeFrom(other.ReservationId);
      }
      if (other.MasterFolioStatus != 0) {
        MasterFolioStatus = other.MasterFolioStatus;
      }
      if (other.masterFolio_ != null) {
        if (masterFolio_ == null) {
          masterFolio_ = new global::HOLMS.Types.Folio.FolioIndicator();
        }
        MasterFolio.MergeFrom(other.MasterFolio);
      }
      clientFolios_.Add(other.clientFolios_);
      if (other.GuaranteeStatus != 0) {
        GuaranteeStatus = other.GuaranteeStatus;
      }
      if (other.guaranteeDueOn_ != null) {
        if (guaranteeDueOn_ == null) {
          guaranteeDueOn_ = new global::HOLMS.Types.Primitive.PbLocalDate();
        }
        GuaranteeDueOn.MergeFrom(other.GuaranteeDueOn);
      }
      if (other.hostProperty_ != null) {
        if (hostProperty_ == null) {
          hostProperty_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator();
        }
        HostProperty.MergeFrom(other.HostProperty);
      }
      if (other.MasterFolioState != 0) {
        MasterFolioState = other.MasterFolioState;
      }
      clientFolioReservations_.Add(other.clientFolioReservations_);
      if (other.masterDateRange_ != null) {
        if (masterDateRange_ == null) {
          masterDateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
        }
        MasterDateRange.MergeFrom(other.MasterDateRange);
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 10: {
            if (reservationId_ == null) {
              reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
            }
            input.ReadMessage(reservationId_);
            break;
          }
          case 16: {
            masterFolioStatus_ = (global::HOLMS.Types.Folio.MasterFolioStatus) input.ReadEnum();
            break;
          }
          case 26: {
            if (masterFolio_ == null) {
              masterFolio_ = new global::HOLMS.Types.Folio.FolioIndicator();
            }
            input.ReadMessage(masterFolio_);
            break;
          }
          case 42: {
            clientFolios_.AddEntriesFrom(input, _repeated_clientFolios_codec);
            break;
          }
          case 48: {
            guaranteeStatus_ = (global::HOLMS.Types.Folio.Guarantees.ReservationGuaranteeStatus) input.ReadEnum();
            break;
          }
          case 58: {
            if (guaranteeDueOn_ == null) {
              guaranteeDueOn_ = new global::HOLMS.Types.Primitive.PbLocalDate();
            }
            input.ReadMessage(guaranteeDueOn_);
            break;
          }
          case 66: {
            if (hostProperty_ == null) {
              hostProperty_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator();
            }
            input.ReadMessage(hostProperty_);
            break;
          }
          case 72: {
            masterFolioState_ = (global::HOLMS.Types.Booking.Reservations.ReservationState) input.ReadEnum();
            break;
          }
          case 82: {
            clientFolioReservations_.AddEntriesFrom(input, _repeated_clientFolioReservations_codec);
            break;
          }
          case 90: {
            if (masterDateRange_ == null) {
              masterDateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
            }
            input.ReadMessage(masterDateRange_);
            break;
          }
        }
      }
    }

  }

  #endregion

}

#endregion Designer generated code


text:
package org.jboss.resteasy.test.xxe;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.test.xxe.resource.XxeSecureProcessingFavoriteMovieXmlRootElement;
import org.jboss.resteasy.test.xxe.resource.XxeSecureProcessingMovieResource;
import org.jboss.resteasy.utils.PortProviderUtil;
import org.jboss.resteasy.utils.TestUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;

/**
 * @tpSubChapter XXE
 * @tpChapter Integration tests
 * @tpTestCaseDetails Regression test for RESTEASY-869
 * @tpSince RESTEasy 3.0.16
 */
@RunWith(Arquillian.class)
@RunAsClient
public class XxeSecureProcessingTest {

    private ResteasyClient client;
    public final Logger logger = LogManager.getLogger(XxeSecureProcessingTest.class.getName());

    String doctype =
            "<!DOCTYPE foodocument [" +
                    "<!ENTITY foo 'foo'>" +
                    "<!ENTITY foo1 '&foo;&foo;&foo;&foo;&foo;&foo;&foo;&foo;&foo;&foo;'>" +
                    "<!ENTITY foo2 '&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;'>" +
                    "<!ENTITY foo3 '&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;'>" +
                    "<!ENTITY foo4 '&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;'>" +
                    "<!ENTITY foo5 '&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;'>" +
                    "<!ENTITY foo6 '&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;'>" +
                    "<!ENTITY foo7 '&foo6;&foo6;&foo6;&foo6;&foo6;&foo6;&foo6;&foo6;&foo6;&foo6;'>" +
                    "<!ENTITY foo8 '&foo7;&foo7;&foo7;&foo7;&foo7;&foo7;&foo7;&foo7;&foo7;&foo7;'>" +
                    "<!ENTITY foo9 '&foo8;&foo8;&foo8;&foo8;&foo8;&foo8;&foo8;&foo8;&foo8;&foo8;'>" +
                    "]>";

    String small = doctype + "<xxeSecureProcessingFavoriteMovieXmlRootElement><title>&foo4;</title></xxeSecureProcessingFavoriteMovieXmlRootElement>";
    String big = doctype + "<xxeSecureProcessingFavoriteMovieXmlRootElement><title>&foo5;</title></xxeSecureProcessingFavoriteMovieXmlRootElement>";

    private static final String T_DEFAULT = "default";
    private static final String T_TRUE = "true";
    private static final String T_FALSE = "false";

    public static Archive<?> deploy(String expandEntityReferences) {
        WebArchive war = TestUtil.prepareArchive(expandEntityReferences);
        Map<String, String> contextParam = new HashMap<>();
        contextParam.put("resteasy.document.secure.disableDTDs", "false");
        if (expandEntityReferences != null) {
            contextParam.put("resteasy.document.expand.entity.references", expandEntityReferences);
        }
        war.addClass(XxeSecureProcessingFavoriteMovieXmlRootElement.class);
        return TestUtil.finishContainerPrepare(war, contextParam, XxeSecureProcessingMovieResource.class);
    }

    @Before
    public void init() {
        client = new ResteasyClientBuilder().build();
    }

    @After
    public void after() throws Exception {
        client.close();
    }

    @Deployment(name = T_DEFAULT)
    public static Archive<?> deployDefault() {
        return deploy(null);
    }

    @Deployment(name = T_TRUE)
    public static Archive<?> deployTrue() {
        return deploy("true");
    }

    @Deployment(name = T_FALSE)
    public static Archive<?> deployFalse() {
        return deploy("false");
    }

    /**
     * @tpTestDetails Small request in XML root element. "resteasy.document.expand.entity.references" property is not set.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testXmlRootElementDefaultSmall() throws Exception {
        Response response = client.target(PortProviderUtil.generateURL("/xmlRootElement", null)).request().post(Entity.entity(small, "application/xml"));
        Assert.assertEquals(200, response.getStatus());
        String entity = response.readEntity(String.class);
        logger.debug("Result: " + entity.substring(0, 30));
        Assert.assertEquals(10000, countFoos(entity));
        response.close();
    }

    /**
     * @tpTestDetails Big request in XML root element. "resteasy.document.expand.entity.references" property is not set.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testXmlRootElementDefaultBig() throws Exception {
        Response response = client.target(PortProviderUtil.generateURL("/xmlRootElement", null)).request().post(Entity.entity(big, "application/xml"));
        Assert.assertEquals(400, response.getStatus());
        String entity = response.readEntity(String.class);
        logger.debug("Result: " + entity);
        Assert.assertTrue(entity.contains("javax.xml.bind.UnmarshalException"));
        response.close();
    }

    /**
     * @tpTestDetails Small request in XML root element. "resteasy.document.expand.entity.references" property is set to false.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testXmlRootElementWithoutExternalExpansionSmall() throws Exception {
        Response response = client.target(PortProviderUtil.generateURL("/xmlRootElement", T_FALSE)).request()
                .post(Entity.entity(small, "application/xml"));
        Assert.assertEquals(200, response.getStatus());
        String entity = response.readEntity(String.class);
        logger.debug("Result: " + entity.substring(0, 30));
        Assert.assertEquals(10000, countFoos(entity));
        response.close();
    }

    /**
     * @tpTestDetails Big request in XML root element. "resteasy.document.expand.entity.references" property is set to false.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testXmlRootElementWithoutExternalExpansionBig() throws Exception {
        Response response = client.target(PortProviderUtil.generateURL("/xmlRootElement", T_FALSE)).request()
                .post(Entity.entity(big, "application/xml"));
        Assert.assertEquals(400, response.getStatus());
        String entity = response.readEntity(String.class);
        logger.debug("Result: " + entity);
        Assert.assertTrue(entity.contains("javax.xml.bind.UnmarshalException"));
        response.close();
    }

    /**
     * @tpTestDetails Small request in XML root element. "resteasy.document.expand.entity.references" property is set to true.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testXmlRootElementWithExternalExpansionSmall() throws Exception {
        Response response = client.target(PortProviderUtil.generateURL("/xmlRootElement", T_TRUE)).request()
                .post(Entity.entity(small, "application/xml"));
        Assert.assertEquals(200, response.getStatus());
        String entity = response.readEntity(String.class);
        logger.debug("Result: " + entity.substring(0, 30));
        Assert.assertEquals(10000, countFoos(entity));
        response.close();
    }

    /**
     * @tpTestDetails Big request in XML root element. "resteasy.document.expand.entity.references" property is set to true.
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testXmlRootElementWithExternalExpansionBig() throws Exception {
        Response response = client.target(PortProviderUtil.generateURL("/xmlRootElement", T_TRUE)).request()
                .post(Entity.entity(big, "application/xml"));
        Assert.assertEquals(400, response.getStatus());
        String entity = response.readEntity(String.class);
        logger.debug("Result: " + entity);
        Assert.assertTrue(entity.contains("javax.xml.bind.UnmarshalException"));
        response.close();
    }

    private int countFoos(String s) {
        int count = 0;
        int pos = 0;

        while (pos >= 0) {
            pos = s.indexOf("foo", pos);
            if (pos >= 0) {
                count++;
                pos += 3;
            }
        }
        return count;
    }
}


text:
#include "WxColumnFrame.h"
#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/charts/wxcharts.h>

WxColumnFrame::WxColumnFrame(const wxString& title)
    : wxFrame(NULL, wxID_ANY, title)
{
    // Create a top-level panel to hold all the contents of the frame
    wxPanel* panel = new wxPanel(this, wxID_ANY);

    // Create the data for the bar chart widget
    wxVector<wxString> labels;
    labels.push_back("January");
    labels.push_back("February");
    labels.push_back("March");
    labels.push_back("April");
    labels.push_back("May");
    labels.push_back("June");
    labels.push_back("July");
    wxChartsCategoricalData::ptr chartData = wxChartsCategoricalData::make_shared(labels);

    // Add the first dataset
    wxVector<wxDouble> points1;
    points1.push_back(3);
    points1.push_back(2.5);
    points1.push_back(1.2);
    points1.push_back(3);
    points1.push_back(6);
    points1.push_back(5);
    points1.push_back(1);
    wxChartsDoubleDataset::ptr dataset1(
        new wxChartsDoubleDataset(
            wxColor(220, 220, 220, 0x7F),
            wxColor(220, 220, 220, 0xCC),
            points1)
        );
    chartData->AddDataset(dataset1);

    // Add the second dataset
    wxVector<wxDouble> points2;
    points2.push_back(1);
    points2.push_back(1.33);
    points2.push_back(2.5);
    points2.push_back(2);
    points2.push_back(3);
    points2.push_back(1.8);
    points2.push_back(0.4);
    wxChartsDoubleDataset::ptr dataset2(new wxChartsDoubleDataset(
        wxColor(151, 187, 205, 0x7F),
        wxColor(151, 187, 205, 0xFF),
        points2));
    chartData->AddDataset(dataset2);

    // Create the column chart widget
    wxColumnChartCtrl* columnChartCtrl = new wxColumnChartCtrl(panel, wxID_ANY, chartData);

    // Set up the sizer for the panel
    wxBoxSizer* panelSizer = new wxBoxSizer(wxHORIZONTAL);
    panelSizer->Add(columnChartCtrl, 1, wxEXPAND);
    panel->SetSizer(panelSizer);

    // Set up the sizer for the frame
    wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL);
    topSizer->Add(panel, 1, wxEXPAND);
    SetSizerAndFit(topSizer);
}


text:
/**
 * @file
 * @brief ARCv2 public kernel find-first-set interface
 *
 * ARC-specific kernel ffs interface. Included by arc/arch.h.
 */

#ifndef ZEPHYR_INCLUDE_ARCH_ARC_V2_FFS_H_
#define ZEPHYR_INCLUDE_ARCH_ARC_V2_FFS_H_

#ifdef __cplusplus
extern "C" {
#endif

#ifndef _ASMLANGUAGE

#include <zephyr/types.h>

/**
 *
 * @brief find most significant bit set in a 32-bit word
 *
 * This routine finds the first bit set starting from the most significant bit
 * in the argument passed in and returns the index of that bit.  Bits are
 * numbered starting at 1 from the least significant bit.  A return value of
 * zero indicates that the value passed is zero.
 *
 * @return most significant bit set, 0 if @a op is 0
 */

#if defined(__GNUC__)
static ALWAYS_INLINE unsigned int find_msb_set(u32_t op)
{
	unsigned int bit;

	__asm__ volatile(

		/* see explanation in ffs.S */
		"fls.f %0, %1;\n\t"
		"add.nz %0, %0, 1;\n\t"
		: "=r"(bit)
		: "r"(op));

	return bit;
}
#endif

/**
 *
 * @brief find least significant bit set in a 32-bit word
 *
 * This routine finds the first bit set starting from the least significant bit
 * in the argument passed in and returns the index of that bit.  Bits are
 * numbered starting at 1 from the least significant bit.  A return value of
 * zero indicates that the value passed is zero.
 *
 * @return least significant bit set, 0 if @a op is 0
 */

#if defined(__GNUC__)
static ALWAYS_INLINE unsigned int find_lsb_set(u32_t op)
{
	unsigned int bit;

	__asm__ volatile(

		/* see explanation in ffs.S */
		"ffs.f %0, %1;\n\t"
		"add.nz %0, %0, 1;\n\t"
		"mov.z %0, 0;\n\t"
		: "=&r"(bit)
		: "r"(op));

	return bit;
}
#endif

#endif /* _ASMLANGUAGE */

#ifdef __cplusplus
}
#endif

#endif /* ZEPHYR_INCLUDE_ARCH_ARC_V2_FFS_H_ */


text:
#ifndef _STIM_SIMULATORS_MATCHED_ERROR_H
#define _STIM_SIMULATORS_MATCHED_ERROR_H

#include "stim/circuit/gate_target.h"
#include "stim/dem/detector_error_model.h"

namespace stim {

/// Describes the location of an instruction being executed within a
/// circuit or loop, distinguishing between separate loop iterations.
///
/// The full location is a stack of these frames, drilling down from
/// the top level circuit to the inner-most loop that the instruction
/// is within.
struct CircuitErrorLocationStackFrame {
    /// The index of the instruction in the circuit (or block).
    uint64_t instruction_offset;
    /// If inside a loop, the number of iterations of the loop that completed
    /// before the moment that we are trying to refer to.
    /// If not in a loop, set to 0.
    uint64_t iteration_index;
    /// If the instruction is a REPEAT block, this is how many times it repeats.
    /// If not, set to 0.
    uint64_t instruction_repetitions_arg;

    bool operator<(const CircuitErrorLocationStackFrame &other) const;

    /// Standard methods for easy testing.
    bool operator==(const CircuitErrorLocationStackFrame &other) const;
    bool operator!=(const CircuitErrorLocationStackFrame &other) const;
    std::string str() const;
};

/// A gate target with qubit coordinate metadata attached to it.
struct GateTargetWithCoords {
    GateTarget gate_target;
    std::vector<double> coords;

    bool operator<(const GateTargetWithCoords &other) const;

    /// Standard methods for easy testing.
    bool operator==(const GateTargetWithCoords &other) const;
    bool operator!=(const GateTargetWithCoords &other) const;
    std::string str() const;
};

/// A dem target with detector coordinate metadata attached to it.
struct DemTargetWithCoords {
    DemTarget dem_target;
    std::vector<double> coords;

    bool operator<(const DemTargetWithCoords &other) const;

    /// Standard methods for easy testing.
    bool operator==(const DemTargetWithCoords &other) const;
    bool operator!=(const DemTargetWithCoords &other) const;
    std::string str() const;
};

/// Stores additional details about measurement errors.
struct FlippedMeasurement {
    /// Which output bit this measurement corresponds to.
    /// UINT64_MAX means "no measurement error occurred".
    uint64_t measurement_record_index;
    /// Which observable this measurement was responsible for measuring.
    std::vector<GateTargetWithCoords> measured_observable;

    bool operator<(const FlippedMeasurement &other) const;

    /// Standard methods for easy testing.
    bool operator==(const FlippedMeasurement &other) const;
    bool operator!=(const FlippedMeasurement &other) const;
    std::string str() const;
};

/// Describes a specific range of targets within a parameterized instruction.
struct CircuitTargetsInsideInstruction {
    /// The instruction type.
    const Gate *gate;

    /// The parens arguments for the instruction.
    std::vector<double> args;

    /// The range of targets within the instruction that were executing.
    size_t target_range_start;
    size_t target_range_end;
    std::vector<GateTargetWithCoords> targets_in_range;

    void fill_args_and_targets_in_range(
        const OperationData &actual_op, const std::map<uint64_t, std::vector<double>> &qubit_coords);

    bool operator<(const CircuitTargetsInsideInstruction &other) const;

    /// Standard methods for easy testing.
    bool operator==(const CircuitTargetsInsideInstruction &other) const;
    bool operator!=(const CircuitTargetsInsideInstruction &other) const;
    std::string str() const;
};

/// Describes the location of an error within a circuit, with as much extra information
/// as possible in order to make it easier for users to grok the location.
struct CircuitErrorLocation {
    /// The number of ticks that have been executed by this point.
    uint64_t tick_offset;

    /// The pauli terms corresponding to the circuit error.
    /// For non-measurement errors, this is the actual pauli error that triggers the problem.
    /// For measurement errors, this is the observable that was being measured.
    std::vector<GateTargetWithCoords> flipped_pauli_product;

    /// Determines if the circuit error was a measurement error.
    /// UINT64_MAX means NOT a measurement error.
    /// Other values refer to a specific measurement index in the measurement record.
    FlippedMeasurement flipped_measurement;

    /// These two values identify a specific range of targets within the executing instruction.
    CircuitTargetsInsideInstruction instruction_targets;

    // Stack trace within the circuit and nested loop blocks.
    std::vector<CircuitErrorLocationStackFrame> stack_frames;

    void canonicalize();
    bool operator<(const CircuitErrorLocation &other) const;
    bool is_simpler_than(const CircuitErrorLocation &other) const;

    /// Standard methods for easy testing.
    bool operator==(const CircuitErrorLocation &other) const;
    bool operator!=(const CircuitErrorLocation &other) const;
    std::string str() const;
};

/// Explains how an error from a detector error model matches error(s) from a circuit.
struct ExplainedError {
    /// A sorted list of detector and observable targets flipped by the error.
    /// This list should never contain target separators.
    std::vector<DemTargetWithCoords> dem_error_terms;

    /// Locations of matching errors in the circuit.
    std::vector<CircuitErrorLocation> circuit_error_locations;

    void fill_in_dem_targets(
        ConstPointerRange<DemTarget> targets, const std::map<uint64_t, std::vector<double>> &dem_coords);

    void canonicalize();

    /// Standard methods for easy testing.
    std::string str() const;
    bool operator==(const ExplainedError &other) const;
    bool operator!=(const ExplainedError &other) const;
};

std::ostream &operator<<(std::ostream &out, const CircuitErrorLocation &e);
std::ostream &operator<<(std::ostream &out, const CircuitErrorLocationStackFrame &e);
std::ostream &operator<<(std::ostream &out, const CircuitTargetsInsideInstruction &e);
std::ostream &operator<<(std::ostream &out, const DemTargetWithCoords &e);
std::ostream &operator<<(std::ostream &out, const FlippedMeasurement &e);
std::ostream &operator<<(std::ostream &out, const GateTargetWithCoords &e);
std::ostream &operator<<(std::ostream &out, const ExplainedError &e);

}  // namespace stim

#endif


text:
ActionController::Base.session = {
  :key         => '_bestprice_session',
  :secret      => 'fd43bcdf06dbd6151d4c1485a07841d4453e697e3662a0171002dcd99cdf4c5c4e86a358c072f7641ecc0cba38ea69a74dc54996dafdcc48f4b74bf3777e7a1c'
}

# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# ActionController::Base.session_store = :active_record_store