for field in self.choices:<EOL><INDENT>if isinstance(field, ModelTypeValidator):<EOL><INDENT>try:<EOL><INDENT>return field.check_type(value, attr, data)<EOL><DEDENT>except ValidationError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>raise self._not_expected_type(<EOL>value, [field.__class__ for field in self.choices],<EOL>fields=[self], field_names=attr, data=data)<EOL>

Check if at least one of the possible choices validates the value.

        Possible choices are assumed to be ``ModelTypeValidator`` fields.


def check_type(self, value, attr, data):

<EOL>root_value = super(InstructionParameter, self).check_type(<EOL>value, attr, data)<EOL>if is_collection(value):<EOL><INDENT>_ = [super(InstructionParameter, self).check_type(item, attr, data)<EOL>for item in value]<EOL><DEDENT>return root_value<EOL>

Customize check_type for handling containers.


def __init__(self, valid_value_types, **kwargs):

<EOL>super(DictParameters, self).__init__(**kwargs)<EOL>self.valid_value_types = valid_value_types<EOL>

Create new model.

        Args:
            valid_value_types (tuple): valid types as values.


if self.many and not is_collection(value):<EOL><INDENT>raise self._not_expected_type(<EOL>value, Iterable, fields=[self], field_names=attr, data=data)<EOL><DEDENT>_check_type = super().check_type<EOL>errors = []<EOL>values = value if self.many else [value]<EOL>for idx, v in enumerate(values):<EOL><INDENT>try:<EOL><INDENT>_check_type(v, idx, values)<EOL><DEDENT>except ValidationError as err:<EOL><INDENT>errors.append(err.messages)<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>errors = errors if self.many else errors[<NUM_LIT:0>]<EOL>raise ValidationError(errors)<EOL><DEDENT>return value<EOL>

Validate if the value is of the type of the schema's model.

        Assumes the nested schema is a ``BaseSchema``.


super().check_type(value, attr, data)<EOL>errors = []<EOL>for idx, v in enumerate(value):<EOL><INDENT>try:<EOL><INDENT>self.container.check_type(v, idx, value)<EOL><DEDENT>except ValidationError as err:<EOL><INDENT>errors.append(err.messages)<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>raise ValidationError(errors)<EOL><DEDENT>return value<EOL>

Validate if it's a list of valid item-field values.

        Check if each element in the list can be validated by the item-field
        passed during construction.


return _SchemaBinder(schema)<EOL>

Class decorator for adding schema validation to its instances.

    Instances of the decorated class are automatically validated after
    instantiation and they are augmented to allow further validations with the
    private method ``_validate()``.

    The decorator also adds the class attribute ``schema`` with the schema used
    for validation, along with a class attribute ``shallow_schema`` used for
    validation during instantiation.

    It also allows using the ``to_dict`` and ``from_dict`` in the model class,
    with perform serialization/deserialization to/from simple Python objects
    respectively.

    The same schema cannot be bound more than once. If you need to reuse a
    schema for a different class, create a new schema subclassing the one you
    want to reuse and leave the new empty::

        class MySchema(BaseSchema):
            title = String()

        class AnotherSchema(MySchema):
            pass

        @bind_schema(MySchema):
        class MyModel(BaseModel):
            pass

        @bind_schema(AnotherSchema):
        class AnotherModel(BaseModel):
            pass

    Raises:
        ValueError: when trying to bind the same schema more than once.

    Return:
        type: the same class with validation capabilities.


return cls(**kwargs)<EOL>

Helper for BaseModel.__reduce__, expanding kwargs.


expected_types = self._expected_types()<EOL>if not isinstance(value, expected_types):<EOL><INDENT>raise self._not_expected_type(<EOL>value, expected_types, fields=[self], field_names=attr, data=data)<EOL><DEDENT>return value<EOL>

Validates a value against the correct type of the field.

        It calls ``_expected_types`` to get a list of valid types.

        Subclasses can do one of the following:

            1. They can override the ``valid_types`` property with a tuple with
            the expected types for this field.

            2. They can override the ``_expected_types`` method to return a
            tuple of expected types for the field.

            3. They can change ``check_type`` completely to customize
            validation.

        This method or the overrides must return the ``value`` parameter
        untouched.


@post_dump(pass_original=True, pass_many=True)<EOL><INDENT>def dump_additional_data(self, valid_data, many, original_data):<DEDENT>

if many:<EOL><INDENT>for i, _ in enumerate(valid_data):<EOL><INDENT>additional_keys = set(original_data[i].__dict__) - set(valid_data[i])<EOL>for key in additional_keys:<EOL><INDENT>valid_data[i][key] = getattr(original_data[i], key)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>additional_keys = set(original_data.__dict__) - set(valid_data)<EOL>for key in additional_keys:<EOL><INDENT>valid_data[key] = getattr(original_data, key)<EOL><DEDENT><DEDENT>return valid_data<EOL>

Include unknown fields after dumping.

        Unknown fields are added with no processing at all.

        Args:
            valid_data (dict or list): data collected and returned by ``dump()``.
            many (bool): if True, data and original_data are a list.
            original_data (object or list): object passed to ``dump()`` in the
                first place.

        Returns:
            dict: the same ``valid_data`` extended with the unknown attributes.

        Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.


@post_load(pass_original=True, pass_many=True)<EOL><INDENT>def load_additional_data(self, valid_data, many, original_data):<DEDENT>

if many:<EOL><INDENT>for i, _ in enumerate(valid_data):<EOL><INDENT>additional_keys = set(original_data[i]) - set(valid_data[i])<EOL>for key in additional_keys:<EOL><INDENT>valid_data[i][key] = original_data[i][key]<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>additional_keys = set(original_data) - set(valid_data)<EOL>for key in additional_keys:<EOL><INDENT>valid_data[key] = original_data[key]<EOL><DEDENT><DEDENT>return valid_data<EOL>

Include unknown fields after load.

        Unknown fields are added with no processing at all.

        Args:
            valid_data (dict or list): validated data returned by ``load()``.
            many (bool): if True, data and original_data are a list.
            original_data (dict or list): data passed to ``load()`` in the
                first place.

        Returns:
            dict: the same ``valid_data`` extended with the unknown attributes.

        Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.


return self.model_cls(**data)<EOL>

Make ``load`` return a ``model_cls`` instance instead of a dict.


self._schema_cls = schema_cls<EOL>


<EOL>if self._schema_cls.__dict__.get('<STR_LIT>', None) is not None:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(self._schema_cls, self._schema_cls.model_cls))<EOL><DEDENT>self._schema_cls.model_cls = model_cls<EOL>model_cls.schema = self._schema_cls()<EOL>model_cls._validate = self._validate<EOL>model_cls.__init__ = self._validate_after_init(model_cls.__init__)<EOL>model_cls.shallow_schema = self._create_validation_schema(self._schema_cls)<EOL>return model_cls<EOL>

Augment the model class with the validation API.

        See the docs for ``bind_schema`` for further information.


validation_schema = schema_cls()<EOL>for _, field in validation_schema.fields.items():<EOL><INDENT>if isinstance(field, ModelTypeValidator):<EOL><INDENT>validate_function = field.__class__.check_type<EOL>field._deserialize = MethodType(validate_function, field)<EOL><DEDENT><DEDENT>return validation_schema<EOL>

Create a patched Schema for validating models.

        Model validation is not part of Marshmallow. Schemas have a ``validate``
        method but this delegates execution on ``load`` and discards the result.
        Similarly, ``load`` will call ``_deserialize`` on every field in the
        schema.

        This function patches the ``_deserialize`` instance method of each
        field to make it call a custom defined method ``check_type``
        provided by Qiskit in the different fields at
        ``qiskit.validation.fields``.

        Returns:
            BaseSchema: a copy of the original Schema, overriding the
                ``_deserialize()`` call of its fields.


try:<EOL><INDENT>_ = instance.schema.validate(instance.to_dict())<EOL><DEDENT>except ValidationError as ex:<EOL><INDENT>raise ModelValidationError(<EOL>ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs)<EOL><DEDENT>

Validate the internal representation of the instance.


@wraps(init_method)<EOL>def _decorated(self, **kwargs):<EOL><INDENT>try:<EOL><INDENT>_ = self.shallow_schema.validate(kwargs)<EOL><DEDENT>except ValidationError as ex:<EOL><INDENT>raise ModelValidationError(<EOL>ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None<EOL><DEDENT>init_method(self, **kwargs)<EOL><DEDENT>return _decorated<EOL>


return _base_model_from_kwargs, (self.__class__, self.__dict__)<EOL>

Custom __reduce__ for allowing pickling and unpickling.

        Customize the reduction in order to allow serialization, as the
        BaseModels need to be pickled during the use of futures by the backends.
        Instead of returning the class, a helper is used in order to pass the
        arguments as **kwargs, as it is needed by SimpleNamespace and the
        standard __reduce__ only allows passing args as a tuple.


return item in self.__dict__<EOL>

Custom implementation of membership test.

        Implement the ``__contains__`` method for catering to the common case
        of finding out if a model contains a certain key (``key in model``).


try:<EOL><INDENT>data, _ = self.schema.dump(self)<EOL><DEDENT>except ValidationError as ex:<EOL><INDENT>raise ModelValidationError(<EOL>ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None<EOL><DEDENT>return data<EOL>

Serialize the model into a Python dict of simple types.

        Note that this method requires that the model is bound with
        ``@bind_schema``.


try:<EOL><INDENT>data, _ = cls.schema.load(dict_)<EOL><DEDENT>except ValidationError as ex:<EOL><INDENT>raise ModelValidationError(<EOL>ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None<EOL><DEDENT>return data<EOL>

Deserialize a dict of simple types into an instance of this class.

        Note that this method requires that the model is bound with
        ``@bind_schema``.


return self.to_dict()<EOL>

Serialize the model into a Python dict of simple types.


self.validators = validators<EOL>

Args:
    validators (list[Validator]): list of Validators.


self.pattern_properties = pattern_properties<EOL>

Args:
    pattern_properties (dict[Validator: Field]): dictionary of the
        valid mappings.


if name is None:<EOL><INDENT>name = os.path.splitext(os.path.basename(file_path))[<NUM_LIT:0>]<EOL><DEDENT>if name not in _SCHEMAS:<EOL><INDENT>with open(file_path, '<STR_LIT:r>') as schema_file:<EOL><INDENT>_SCHEMAS[name] = json.load(schema_file)<EOL><DEDENT><DEDENT>return _SCHEMAS[name]<EOL>

Loads the QObj schema for use in future validations.

   Caches schema in _SCHEMAS module attribute.

   Args:
        file_path(str): Path to schema.
        name(str): Given name for schema. Defaults to file_path filename
            without schema.
   Return:
        schema(dict): Loaded schema.


def _get_validator(name, schema=None, check_schema=True,<EOL>validator_class=None, **validator_kwargs):

if schema is None:<EOL><INDENT>try:<EOL><INDENT>schema = _SCHEMAS[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise SchemaValidationError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>if name not in _VALIDATORS:<EOL><INDENT>if validator_class is None:<EOL><INDENT>validator_class = jsonschema.validators.validator_for(schema)<EOL><DEDENT>_VALIDATORS[name] = validator_class(schema, **validator_kwargs)<EOL><DEDENT>validator = _VALIDATORS[name]<EOL>if check_schema:<EOL><INDENT>validator.check_schema(schema)<EOL><DEDENT>return validator<EOL>

Generate validator for JSON schema.

    Args:
        name (str): Name for validator. Will be validator key in
            `_VALIDATORS` dict.
        schema (dict): JSON schema `dict`. If not provided searches for schema
            in `_SCHEMAS`.
        check_schema (bool): Verify schema is valid.
        validator_class (jsonschema.IValidator): jsonschema IValidator instance.
            Default behavior is to determine this from the schema `$schema`
            field.
        **validator_kwargs (dict): Additional keyword arguments for validator.

    Return:
        jsonschema.IValidator: Validator for JSON schema.

    Raises:
        SchemaValidationError: Raised if validation fails.


schema_base_path = os.path.join(os.path.dirname(__file__), '<STR_LIT>')<EOL>for name, path in _DEFAULT_SCHEMA_PATHS.items():<EOL><INDENT>_load_schema(os.path.join(schema_base_path, path), name)<EOL>_get_validator(name)<EOL><DEDENT>

Load all default schemas into `_SCHEMAS`.


try:<EOL><INDENT>if isinstance(schema, str):<EOL><INDENT>schema_name = schema<EOL>schema = _SCHEMAS[schema_name]<EOL>validator = _get_validator(schema_name)<EOL>validator.validate(json_dict)<EOL><DEDENT>else:<EOL><INDENT>jsonschema.validate(json_dict, schema)<EOL><DEDENT><DEDENT>except jsonschema.ValidationError as err:<EOL><INDENT>if err_msg is None:<EOL><INDENT>err_msg = "<STR_LIT>""<STR_LIT>"<EOL><DEDENT>newerr = SchemaValidationError(err_msg)<EOL>newerr.__cause__ = _SummaryValidationError(err)<EOL>logger.debug('<STR_LIT:%s>', _format_causes(err))<EOL>raise newerr<EOL><DEDENT>

Validates JSON dict against a schema.

    Args:
        json_dict (dict): JSON to be validated.
        schema (dict or str): JSON schema dictionary or the name of one of the
            standards schemas in Qiskit to validate against it. The list of
            standard schemas is: ``backend_configuration``,
            ``backend_properties``, ``backend_status``,
            ``default_pulse_configuration``, ``job_status``, ``qobj``,
            ``result``.
        err_msg (str): Optional error message.

    Raises:
        SchemaValidationError: Raised if validation fails.


lines = []<EOL>def _print(string, offset=<NUM_LIT:0>):<EOL><INDENT>lines.append(_pad(string, offset=offset))<EOL><DEDENT>def _pad(string, offset=<NUM_LIT:0>):<EOL><INDENT>padding = '<STR_LIT:U+0020>' * (level + offset)<EOL>padded_lines = [padding + line for line in string.split('<STR_LIT:\n>')]<EOL>return '<STR_LIT:\n>'.join(padded_lines)<EOL><DEDENT>def _format_path(path):<EOL><INDENT>def _format(item):<EOL><INDENT>if isinstance(item, str):<EOL><INDENT>return '<STR_LIT>'.format(item)<EOL><DEDENT>return '<STR_LIT>'.format(item)<EOL><DEDENT>return '<STR_LIT>'.join(['<STR_LIT>'] + list(map(_format, path)))<EOL><DEDENT>_print('<STR_LIT>'.format(<EOL>err.validator, _format_path(err.absolute_path)))<EOL>if not err.context:<EOL><INDENT>_print(str(err.message), offset=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>for suberr in err.context:<EOL><INDENT>lines.append(_format_causes(suberr, level+<NUM_LIT:1>))<EOL><DEDENT><DEDENT>return '<STR_LIT:\n>'.join(lines)<EOL>

Return a cascading explanation of the validation error.

    Returns a cascading explanation of the validation error in the form of::

        <validator> failed @ <subfield_path> because of:
            <validator> failed @ <subfield_path> because of:
                ...
            <validator> failed @ <subfield_path> because of:
                ...
            ...

    For example::

        'oneOf' failed @ '<root>' because of:
            'required' failed @ '<root>.config' because of:
                'meas_level' is a required property

    Meaning the validator 'oneOf' failed while validating the whole object
    because of the validator 'required' failing while validating the property
    'config' because its 'meas_level' field is missing.

    The cascade repeats the format "<validator> failed @ <path> because of"
    until there are no deeper causes. In this case, the string representation
    of the error is shown.

    Args:
        err (jsonschema.ValidationError): the instance to explain.
        level (int): starting level of indentation for the cascade of
            explanations.

    Return:
        str: a formatted string with the explanation of the error.


if filename is None:<EOL><INDENT>filename = "<STR_LIT>"<EOL><DEDENT>self.lexer = QasmLexer(filename)<EOL>self.tokens = self.lexer.tokens<EOL>self.parse_dir = tempfile.mkdtemp(prefix='<STR_LIT>')<EOL>self.precedence = (<EOL>('<STR_LIT:left>', '<STR_LIT:+>', '<STR_LIT:->'),<EOL>('<STR_LIT:left>', '<STR_LIT:*>', '<STR_LIT:/>'),<EOL>('<STR_LIT:left>', '<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT:right>', '<STR_LIT>'))<EOL>self.parser = yacc.yacc(module=self, debug=False,<EOL>outputdir=self.parse_dir)<EOL>self.qasm = None<EOL>self.parse_deb = False<EOL>self.global_symtab = {}                          <EOL>self.current_symtab = self.global_symtab         <EOL>self.symbols = []                                <EOL>self.external_functions = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>


if obj.name in self.current_symtab:<EOL><INDENT>prev = self.current_symtab[obj.name]<EOL>raise QasmError("<STR_LIT>", obj.type + "<STR_LIT>"<EOL>+ obj.name + "<STR_LIT>", str(obj.line)<EOL>+ '<STR_LIT>', obj.file<EOL>+ '<STR_LIT>',<EOL>str(prev.line) + '<STR_LIT>', prev.file)<EOL><DEDENT>self.current_symtab[obj.name] = obj<EOL>

Update a node in the symbol table.

        Everything in the symtab must be a node with these attributes:
        name - the string name of the object
        type - the string type of the object
        line - the source line where the type was first found
        file - the source file where the type was first found


<EOL>if obj.name not in self.current_symtab:<EOL><INDENT>raise QasmError("<STR_LIT>" + obj.name<EOL>+ "<STR_LIT>",<EOL>str(obj.line), '<STR_LIT:file>', obj.file)<EOL><DEDENT>sym = self.current_symtab[obj.name]<EOL>if not (sym.type == '<STR_LIT:id>' and sym.is_bit):<EOL><INDENT>raise QasmError("<STR_LIT>", obj.name,<EOL>'<STR_LIT>')<EOL><DEDENT>

Verify a qubit id against the gate prototype.


<EOL>for children in obj.children:<EOL><INDENT>self.verify_declared_bit(children)<EOL><DEDENT>


<EOL>if obj.children is not None:<EOL><INDENT>for children in obj.children:<EOL><INDENT>if isinstance(children, node.Id):<EOL><INDENT>if children.name in self.external_functions:<EOL><INDENT>continue<EOL><DEDENT>if children.name not in self.current_symtab:<EOL><INDENT>raise QasmError("<STR_LIT>" + children.name<EOL>+ "<STR_LIT>"<EOL>+ "<STR_LIT>", str(children.line),<EOL>"<STR_LIT:file>", children.file)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if hasattr(children, "<STR_LIT>"):<EOL><INDENT>self.verify_exp_list(children)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>


def verify_as_gate(self, obj, bitlist, arglist=None):

if obj.name not in self.global_symtab:<EOL><INDENT>raise QasmError("<STR_LIT>" + obj.name<EOL>+ "<STR_LIT>", str(obj.line), '<STR_LIT:file>', obj.file)<EOL><DEDENT>g_sym = self.global_symtab[obj.name]<EOL>if not (g_sym.type == '<STR_LIT>' or g_sym.type == '<STR_LIT>'):<EOL><INDENT>raise QasmError("<STR_LIT:'>" + obj.name + "<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>+ "<STR_LIT>" + g_sym.type + "<STR_LIT>",<EOL>str(obj.line), '<STR_LIT:file>', obj.file)<EOL><DEDENT>if g_sym.n_bits() != bitlist.size():<EOL><INDENT>raise QasmError("<STR_LIT>" + obj.name<EOL>+ "<STR_LIT>", str(bitlist.size()),<EOL>"<STR_LIT>",<EOL>str(g_sym.n_bits()), "<STR_LIT>", "<STR_LIT>",<EOL>str(obj.line), '<STR_LIT:file>', obj.file)<EOL><DEDENT>if arglist:<EOL><INDENT>if g_sym.n_args() != arglist.size():<EOL><INDENT>raise QasmError("<STR_LIT>" + obj.name<EOL>+ "<STR_LIT>", str(arglist.size()),<EOL>"<STR_LIT>",<EOL>str(g_sym.n_args()), "<STR_LIT>", "<STR_LIT>",<EOL>str(obj.line), '<STR_LIT:file>', obj.file)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if g_sym.n_args() > <NUM_LIT:0>:<EOL><INDENT>raise QasmError("<STR_LIT>" + obj.name<EOL>+ "<STR_LIT>",<EOL>str(g_sym.n_args()), "<STR_LIT>", "<STR_LIT>",<EOL>str(obj.line), '<STR_LIT:file>', obj.file)<EOL><DEDENT><DEDENT>


<EOL>if obj.name not in self.global_symtab:<EOL><INDENT>raise QasmError('<STR_LIT>', object_type, "<STR_LIT:'>"<EOL>+ obj.name + "<STR_LIT:'>", '<STR_LIT>', str(obj.line),<EOL>'<STR_LIT:file>', obj.file)<EOL><DEDENT>g_sym = self.global_symtab[obj.name]<EOL>if g_sym.type != object_type:<EOL><INDENT>raise QasmError("<STR_LIT>" + g_sym.name + "<STR_LIT>"<EOL>+ object_type + "<STR_LIT>"<EOL>+ g_sym.type + "<STR_LIT:'>", "<STR_LIT>", str(obj.line),<EOL>"<STR_LIT:file>", obj.file)<EOL><DEDENT>if obj.type == '<STR_LIT>':<EOL><INDENT>bound = g_sym.index<EOL>ndx = obj.index<EOL>if ndx < <NUM_LIT:0> or ndx >= bound:<EOL><INDENT>raise QasmError("<STR_LIT>" + g_sym.name<EOL>+ "<STR_LIT>", str(ndx),<EOL>"<STR_LIT>", str(bound),<EOL>"<STR_LIT>", str(obj.line), "<STR_LIT:file>", obj.file)<EOL><DEDENT><DEDENT>


def verify_reg_list(self, obj, object_type):

<EOL>for children in obj.children:<EOL><INDENT>self.verify_reg(children, object_type)<EOL><DEDENT>


if id_node.type != "<STR_LIT:id>":<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>bit_list = []<EOL>try:<EOL><INDENT>g_sym = self.current_symtab[id_node.name]<EOL><DEDENT>except KeyError:<EOL><INDENT>g_sym = self.global_symtab[id_node.name]<EOL><DEDENT>if g_sym.type == "<STR_LIT>" or g_sym.type == "<STR_LIT>":<EOL><INDENT>for idx in range(g_sym.index):<EOL><INDENT>bit_list.append((id_node.name, idx))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>bit_list.append((id_node.name, -<NUM_LIT:1>))<EOL><DEDENT>return bit_list<EOL>

Return a list of (name, index) tuples for this id node.


bit_list = []<EOL>line_number = -<NUM_LIT:1><EOL>filename = "<STR_LIT>"<EOL>for node_ in list_of_nodes:<EOL><INDENT>if node_.type == "<STR_LIT:id>":<EOL><INDENT>bit_list.extend(self.id_tuple_list(node_))<EOL>line_number = node_.line<EOL>filename = node_.file<EOL><DEDENT>elif node_.type == "<STR_LIT>":<EOL><INDENT>bit_list.append((node_.name, node_.index))<EOL>line_number = node_.line<EOL>filename = node_.file<EOL><DEDENT>elif node_.type == "<STR_LIT>":<EOL><INDENT>for child in node_.children:<EOL><INDENT>if child.type == "<STR_LIT:id>":<EOL><INDENT>bit_list.extend(self.id_tuple_list(child))<EOL><DEDENT>else:<EOL><INDENT>bit_list.append((child.name, child.index))<EOL><DEDENT>line_number = child.line<EOL>filename = child.file<EOL><DEDENT><DEDENT>elif node_.type == "<STR_LIT>":<EOL><INDENT>for child in node_.children:<EOL><INDENT>bit_list.extend(self.id_tuple_list(child))<EOL>line_number = child.line<EOL>filename = child.file<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT><DEDENT>if len(bit_list) != len(set(bit_list)):<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>% (line_number, filename))<EOL><DEDENT>

Check that objects in list_of_nodes represent distinct (qu)bits.

        list_of_nodes is a list containing nodes of type id, indexed_id,
        primary_list, or id_list. We assume these are all the same type
        'qreg' or 'creg'.
        This method raises an exception if list_of_nodes refers to the
        same object more than once.


self.current_symtab = self.symbols.pop()<EOL>


self.symbols.append(self.current_symtab)<EOL>self.current_symtab = {}<EOL>


self.qasm = program[<NUM_LIT:1>]<EOL>


program[<NUM_LIT:0>] = node.Program([program[<NUM_LIT:1>]])<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>program[<NUM_LIT:0>].add_child(program[<NUM_LIT:2>])<EOL>


if len(program) > <NUM_LIT:2>:<EOL><INDENT>if program[<NUM_LIT:2>] != '<STR_LIT:;>':<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>", str(program[<NUM_LIT:2>].value))<EOL><DEDENT><DEDENT>program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>

statement : decl
          | quantum_op ';'
          | format ';'
          | ignore
          | quantum_op error
          | format error


program[<NUM_LIT:0>] = node.Format(program[<NUM_LIT:1>])<EOL>


version = "<STR_LIT>"<EOL>raise QasmError("<STR_LIT>" + version<EOL>+ "<STR_LIT>")<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>


raise QasmError("<STR_LIT>"<EOL>+ str(program[<NUM_LIT:1>].value) + "<STR_LIT:'>")<EOL>


if len(program) == <NUM_LIT:4>:<EOL><INDENT>raise QasmError("<STR_LIT>",<EOL>str(program[<NUM_LIT:3>].value))<EOL><DEDENT>if program[<NUM_LIT:4>] != '<STR_LIT:]>':<EOL><INDENT>raise QasmError("<STR_LIT>",<EOL>str(program[<NUM_LIT:4>].value))<EOL><DEDENT>program[<NUM_LIT:0>] = node.IndexedId([program[<NUM_LIT:1>], node.Int(program[<NUM_LIT:3>])])<EOL>

indexed_id : id '[' NNINTEGER ']'
           | id '[' NNINTEGER error
           | id '[' error


program[<NUM_LIT:0>] = node.IdList([program[<NUM_LIT:1>]])<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>program[<NUM_LIT:0>].add_child(program[<NUM_LIT:3>])<EOL>


program[<NUM_LIT:0>] = node.IdList([program[<NUM_LIT:1>]])<EOL>self.update_symtab(program[<NUM_LIT:1>])<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>program[<NUM_LIT:0>].add_child(program[<NUM_LIT:3>])<EOL>self.update_symtab(program[<NUM_LIT:3>])<EOL>


program[<NUM_LIT:0>] = node.IdList([program[<NUM_LIT:1>]])<EOL>program[<NUM_LIT:1>].is_bit = True<EOL>self.update_symtab(program[<NUM_LIT:1>])<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>program[<NUM_LIT:0>].add_child(program[<NUM_LIT:3>])<EOL>program[<NUM_LIT:3>].is_bit = True<EOL>self.update_symtab(program[<NUM_LIT:3>])<EOL>


program[<NUM_LIT:0>] = node.PrimaryList([program[<NUM_LIT:1>]])<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>program[<NUM_LIT:1>].add_child(program[<NUM_LIT:3>])<EOL>


if len(program) > <NUM_LIT:2>:<EOL><INDENT>if program[<NUM_LIT:2>] != '<STR_LIT:;>':<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>"<STR_LIT>" + program[<NUM_LIT:2>].value + "<STR_LIT:'>")<EOL><DEDENT><DEDENT>program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>

decl : qreg_decl ';'
     | creg_decl ';'
     | qreg_decl error
     | creg_decl error
     | gate_decl


program[<NUM_LIT:0>] = node.Qreg([program[<NUM_LIT:2>]])<EOL>if program[<NUM_LIT:2>].name in self.external_functions:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>" + program[<NUM_LIT:2>].name + "<STR_LIT:'>")<EOL><DEDENT>if program[<NUM_LIT:2>].index == <NUM_LIT:0>:<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>self.update_symtab(program[<NUM_LIT:0>])<EOL>


raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>", program[<NUM_LIT:2>].value)<EOL>


program[<NUM_LIT:0>] = node.Creg([program[<NUM_LIT:2>]])<EOL>if program[<NUM_LIT:2>].name in self.external_functions:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>" + program[<NUM_LIT:2>].name + "<STR_LIT:'>")<EOL><DEDENT>if program[<NUM_LIT:2>].index == <NUM_LIT:0>:<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>self.update_symtab(program[<NUM_LIT:0>])<EOL>


program[<NUM_LIT:0>] = node.Gate([program[<NUM_LIT:2>], program[<NUM_LIT:4>], program[<NUM_LIT:5>]])<EOL>if program[<NUM_LIT:2>].name in self.external_functions:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>" + program[<NUM_LIT:2>].name + "<STR_LIT:'>")<EOL><DEDENT>self.pop_scope()<EOL>self.update_symtab(program[<NUM_LIT:0>])<EOL>

gate_decl : GATE id gate_scope bit_list gate_body


program[<NUM_LIT:0>] = node.Gate([program[<NUM_LIT:2>], program[<NUM_LIT:6>], program[<NUM_LIT:7>]])<EOL>if program[<NUM_LIT:2>].name in self.external_functions:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>" + program[<NUM_LIT:2>].name + "<STR_LIT:'>")<EOL><DEDENT>self.pop_scope()<EOL>self.update_symtab(program[<NUM_LIT:0>])<EOL>

gate_decl : GATE id gate_scope '(' ')' bit_list gate_body


program[<NUM_LIT:0>] = node.Gate(<EOL>[program[<NUM_LIT:2>], program[<NUM_LIT:5>], program[<NUM_LIT:7>], program[<NUM_LIT:8>]])<EOL>if program[<NUM_LIT:2>].name in self.external_functions:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>" + program[<NUM_LIT:2>].name + "<STR_LIT:'>")<EOL><DEDENT>self.pop_scope()<EOL>self.update_symtab(program[<NUM_LIT:0>])<EOL>

gate_decl : GATE id gate_scope '(' gate_id_list ')' bit_list gate_body


if program[<NUM_LIT:2>] != '<STR_LIT:}>':<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ str(program[<NUM_LIT:2>].value) + "<STR_LIT:'>")<EOL><DEDENT>program[<NUM_LIT:0>] = node.GateBody(None)<EOL>


program[<NUM_LIT:0>] = node.GateBody(program[<NUM_LIT:2>])<EOL>


program[<NUM_LIT:0>] = [program[<NUM_LIT:1>]]<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>program[<NUM_LIT:0>].append(program[<NUM_LIT:2>])<EOL>


program[<NUM_LIT:0>] = node.UniversalUnitary([program[<NUM_LIT:3>], program[<NUM_LIT:5>]])<EOL>self.verify_reg(program[<NUM_LIT:5>], '<STR_LIT>')<EOL>self.verify_exp_list(program[<NUM_LIT:3>])<EOL>


program[<NUM_LIT:0>] = node.Cnot([program[<NUM_LIT:2>], program[<NUM_LIT:4>]])<EOL>self.verify_reg(program[<NUM_LIT:2>], '<STR_LIT>')<EOL>self.verify_reg(program[<NUM_LIT:4>], '<STR_LIT>')<EOL>self.verify_distinct([program[<NUM_LIT:2>], program[<NUM_LIT:4>]])<EOL>


program[<NUM_LIT:0>] = node.CustomUnitary([program[<NUM_LIT:1>], program[<NUM_LIT:2>]])<EOL>self.verify_as_gate(program[<NUM_LIT:1>], program[<NUM_LIT:2>])<EOL>self.verify_reg_list(program[<NUM_LIT:2>], '<STR_LIT>')<EOL>self.verify_distinct([program[<NUM_LIT:2>]])<EOL>


program[<NUM_LIT:0>] = node.CustomUnitary([program[<NUM_LIT:1>], program[<NUM_LIT:4>]])<EOL>self.verify_as_gate(program[<NUM_LIT:1>], program[<NUM_LIT:4>])<EOL>self.verify_reg_list(program[<NUM_LIT:4>], '<STR_LIT>')<EOL>self.verify_distinct([program[<NUM_LIT:4>]])<EOL>


program[<NUM_LIT:0>] = node.CustomUnitary([program[<NUM_LIT:1>], program[<NUM_LIT:3>], program[<NUM_LIT:5>]])<EOL>self.verify_as_gate(program[<NUM_LIT:1>], program[<NUM_LIT:5>], arglist=program[<NUM_LIT:3>])<EOL>self.verify_reg_list(program[<NUM_LIT:5>], '<STR_LIT>')<EOL>self.verify_exp_list(program[<NUM_LIT:3>])<EOL>self.verify_distinct([program[<NUM_LIT:5>]])<EOL>

unitary_op : id '(' exp_list ')' primary_list


program[<NUM_LIT:0>] = node.UniversalUnitary([program[<NUM_LIT:3>], program[<NUM_LIT:5>]])<EOL>self.verify_declared_bit(program[<NUM_LIT:5>])<EOL>self.verify_exp_list(program[<NUM_LIT:3>])<EOL>


raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>")<EOL>


raise QasmError("<STR_LIT>")<EOL>


raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>+ str(program[<NUM_LIT:2>].value) + "<STR_LIT:'>")<EOL>


raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>+ str(program[<NUM_LIT:4>].value) + "<STR_LIT:'>")<EOL>


program[<NUM_LIT:0>] = node.CustomUnitary([program[<NUM_LIT:1>], program[<NUM_LIT:3>], program[<NUM_LIT:5>]])<EOL>self.verify_as_gate(program[<NUM_LIT:1>], program[<NUM_LIT:5>], arglist=program[<NUM_LIT:3>])<EOL>self.verify_bit_list(program[<NUM_LIT:5>])<EOL>self.verify_exp_list(program[<NUM_LIT:3>])<EOL>self.verify_distinct([program[<NUM_LIT:5>]])<EOL>

gate_op : id '(' exp_list ')' id_list ';'


program[<NUM_LIT:0>] = node.Barrier([program[<NUM_LIT:2>]])<EOL>self.verify_bit_list(program[<NUM_LIT:2>])<EOL>self.verify_distinct([program[<NUM_LIT:2>]])<EOL>


<EOL>program[<NUM_LIT:0>] = node.Opaque([program[<NUM_LIT:2>], program[<NUM_LIT:4>]])<EOL>if program[<NUM_LIT:2>].name in self.external_functions:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>" + program[<NUM_LIT:2>].name + "<STR_LIT:'>")<EOL><DEDENT>self.pop_scope()<EOL>self.update_symtab(program[<NUM_LIT:0>])<EOL>


program[<NUM_LIT:0>] = node.Opaque([program[<NUM_LIT:2>], program[<NUM_LIT:6>]])<EOL>self.pop_scope()<EOL>self.update_symtab(program[<NUM_LIT:0>])<EOL>

opaque : OPAQUE id gate_scope '(' ')' bit_list


program[<NUM_LIT:0>] = node.Opaque([program[<NUM_LIT:2>], program[<NUM_LIT:5>], program[<NUM_LIT:7>]])<EOL>if program[<NUM_LIT:2>].name in self.external_functions:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>" + program[<NUM_LIT:2>].name + "<STR_LIT:'>")<EOL><DEDENT>self.pop_scope()<EOL>self.update_symtab(program[<NUM_LIT:0>])<EOL>

opaque : OPAQUE id gate_scope '(' gate_id_list ')' bit_list


program[<NUM_LIT:0>] = node.Measure([program[<NUM_LIT:2>], program[<NUM_LIT:4>]])<EOL>self.verify_reg(program[<NUM_LIT:2>], '<STR_LIT>')<EOL>self.verify_reg(program[<NUM_LIT:4>], '<STR_LIT>')<EOL>

measure : MEASURE primary ASSIGN primary


raise QasmError("<STR_LIT>" +<EOL>str(program[<NUM_LIT:3>].value))<EOL>


program[<NUM_LIT:0>] = node.Barrier([program[<NUM_LIT:2>]])<EOL>self.verify_reg_list(program[<NUM_LIT:2>], '<STR_LIT>')<EOL>self.verify_distinct([program[<NUM_LIT:2>]])<EOL>


program[<NUM_LIT:0>] = node.Reset([program[<NUM_LIT:2>]])<EOL>self.verify_reg(program[<NUM_LIT:2>], '<STR_LIT>')<EOL>


if len(program) == <NUM_LIT:3>:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>")<EOL><DEDENT>if len(program) == <NUM_LIT:5>:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>" + str(program[<NUM_LIT:4>].value))<EOL><DEDENT>if len(program) == <NUM_LIT:6>:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>" + str(program[<NUM_LIT:5>].value))<EOL><DEDENT>if len(program) == <NUM_LIT:7>:<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>if program[<NUM_LIT:7>].type == '<STR_LIT>':<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>if program[<NUM_LIT:7>].type == '<STR_LIT>':<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>program[<NUM_LIT:0>] = node.If([program[<NUM_LIT:3>], node.Int(program[<NUM_LIT:5>]), program[<NUM_LIT:7>]])<EOL>

if : IF '(' id MATCHES NNINTEGER ')' quantum_op
if : IF '(' id error
if : IF '(' id MATCHES error
if : IF '(' id MATCHES NNINTEGER error
if : IF error


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>

quantum_op : unitary_op
           | opaque
           | measure
           | barrier
           | reset
           | if


program[<NUM_LIT:0>] = node.Int(program[<NUM_LIT:1>])<EOL>


program[<NUM_LIT:0>] = node.Real(sympy.Number(program[<NUM_LIT:1>]))<EOL>


program[<NUM_LIT:0>] = node.Real(sympy.pi)<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:2>]<EOL>


<EOL>if program[<NUM_LIT:1>].name not in self.external_functions:<EOL><INDENT>raise QasmError("<STR_LIT>",<EOL>str(program[<NUM_LIT:1>].name))<EOL><DEDENT>program[<NUM_LIT:0>] = node.External([program[<NUM_LIT:1>], program[<NUM_LIT:3>]])<EOL>


program[<NUM_LIT:0>] = node.Prefix([node.UnaryOperator(program[<NUM_LIT:1>]), program[<NUM_LIT:2>]])<EOL>

expression : '-' expression %prec negative
            | '+' expression %prec positive


program[<NUM_LIT:0>] = node.BinaryOp([node.BinaryOperator(program[<NUM_LIT:2>]),<EOL>program[<NUM_LIT:1>], program[<NUM_LIT:3>]])<EOL>

expression : expression '*' expression
            | expression '/' expression
            | expression '+' expression
            | expression '-' expression
            | expression '^' expression


program[<NUM_LIT:0>] = node.ExpressionList([program[<NUM_LIT:1>]])<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>program[<NUM_LIT:0>].add_child(program[<NUM_LIT:3>])<EOL>


<EOL>pass<EOL>


if token is None:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>last_cr = input_.rfind('<STR_LIT:\n>', <NUM_LIT:0>, token.lexpos)<EOL>if last_cr < <NUM_LIT:0>:<EOL><INDENT>last_cr = <NUM_LIT:0><EOL><DEDENT>column = (token.lexpos - last_cr) + <NUM_LIT:1><EOL>return column<EOL>

Compute the column.

        Input is the input text string.
        token is a token instance.


try:<EOL><INDENT>while True:<EOL><INDENT>token = self.lexer.token()<EOL>if not token:<EOL><INDENT>break<EOL><DEDENT>yield token<EOL><DEDENT><DEDENT>except QasmError as e:<EOL><INDENT>print('<STR_LIT>', e.msg)<EOL><DEDENT>


if val is True:<EOL><INDENT>self.parse_deb = True<EOL><DEDENT>elif val is False:<EOL><INDENT>self.parse_deb = False<EOL><DEDENT>else:<EOL><INDENT>raise QasmError("<STR_LIT>" + str(val)<EOL>+ "<STR_LIT>")<EOL><DEDENT>


self.parser.parse(data, lexer=self.lexer, debug=self.parse_deb)<EOL>if self.qasm is None:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>")<EOL><DEDENT>return self.qasm<EOL>


if self.qasm is not None:<EOL><INDENT>self.qasm.to_string(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>


ast = self.parser.parse(data, debug=True)<EOL>self.parser.parse(data, debug=True)<EOL>ast.to_string(<NUM_LIT:0>)<EOL>

Parser runner.

        To use this module stand-alone.


def __init__(self, filename=None, data=None):

if filename is None and data is None:<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>if filename is not None and data is not None:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self._filename = filename<EOL>self._data = data<EOL>


return self._filename<EOL>


if self._filename:<EOL><INDENT>with open(self._filename) as ifile:<EOL><INDENT>self._data = ifile.read()<EOL><DEDENT><DEDENT>with QasmParser(self._filename) as qasm_p:<EOL><INDENT>return qasm_p.get_tokens()<EOL><DEDENT>


if self._filename:<EOL><INDENT>with open(self._filename) as ifile:<EOL><INDENT>self._data = ifile.read()<EOL><DEDENT><DEDENT>with QasmParser(self._filename) as qasm_p:<EOL><INDENT>qasm_p.parse_debug(False)<EOL>return qasm_p.parse(self._data)<EOL><DEDENT>


super().__init__('<STR_LIT>', children, None)<EOL>


return "<STR_LIT>" + self.children[<NUM_LIT:0>].qasm(prec) + "<STR_LIT:U+002C>" +self.children[<NUM_LIT:1>].qasm(prec) + "<STR_LIT:;>"<EOL>

Return the corresponding OPENQASM string.


<EOL>super().__init__("<STR_LIT:int>", None, None)<EOL>self.value = id<EOL>


ind = indent * '<STR_LIT:U+0020>'<EOL>print(ind, '<STR_LIT:int>', self.value)<EOL>


<EOL>return "<STR_LIT>" % self.value<EOL>


def latex(self, prec=<NUM_LIT:15>, nested_scope=None):

Return the corresponding math mode latex string.


<EOL>return N(self.value)<EOL>


<EOL>return float(self.value)<EOL>

Return the correspond floating point number.


return "<STR_LIT:(>" + self.children[<NUM_LIT:1>].qasm(prec) + self.children[<NUM_LIT:0>].value +self.children[<NUM_LIT:2>].qasm(prec) + "<STR_LIT:)>"<EOL>


<EOL>return sympy.latex(self.sym(nested_scope))<EOL>


operation = self.children[<NUM_LIT:0>].operation()<EOL>lhs = self.children[<NUM_LIT:1>].real(nested_scope)<EOL>rhs = self.children[<NUM_LIT:2>].real(nested_scope)<EOL>return operation(lhs, rhs)<EOL>


operation = self.children[<NUM_LIT:0>].operation()<EOL>lhs = self.children[<NUM_LIT:1>].sym(nested_scope)<EOL>rhs = self.children[<NUM_LIT:2>].sym(nested_scope)<EOL>return operation(lhs, rhs)<EOL>


super().__init__('<STR_LIT>', None, None)<EOL>self.value = operation<EOL>


try:<EOL><INDENT>return VALID_OPERATORS[self.value]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise NodeException("<STR_LIT>" %<EOL>self.value)<EOL><DEDENT>

Return the operator as a function f(left, right).


<EOL>return self.value<EOL>


return self.children[<NUM_LIT:0>].qasm(prec) + "<STR_LIT:(>" +self.children[<NUM_LIT:1>].qasm(prec) + "<STR_LIT:)>"<EOL>


op = self.children[<NUM_LIT:0>].name<EOL>expr = self.children[<NUM_LIT:1>]<EOL>dispatch = {<EOL>'<STR_LIT>': sympy.sin,<EOL>'<STR_LIT>': sympy.cos,<EOL>'<STR_LIT>': sympy.tan,<EOL>'<STR_LIT>': sympy.asin,<EOL>'<STR_LIT>': sympy.acos,<EOL>'<STR_LIT>': sympy.atan,<EOL>'<STR_LIT>': sympy.exp,<EOL>'<STR_LIT>': sympy.log,<EOL>'<STR_LIT>': sympy.sqrt<EOL>}<EOL>if op in dispatch:<EOL><INDENT>arg = expr.real(nested_scope)<EOL>return dispatch[op](arg)<EOL><DEDENT>else:<EOL><INDENT>raise NodeException("<STR_LIT>")<EOL><DEDENT>


op = self.children[<NUM_LIT:0>].name<EOL>expr = self.children[<NUM_LIT:1>]<EOL>dispatch = {<EOL>'<STR_LIT>': sympy.sin,<EOL>'<STR_LIT>': sympy.cos,<EOL>'<STR_LIT>': sympy.tan,<EOL>'<STR_LIT>': sympy.asin,<EOL>'<STR_LIT>': sympy.acos,<EOL>'<STR_LIT>': sympy.atan,<EOL>'<STR_LIT>': sympy.exp,<EOL>'<STR_LIT>': sympy.log,<EOL>'<STR_LIT>': sympy.sqrt<EOL>}<EOL>if op in dispatch:<EOL><INDENT>arg = expr.sym(nested_scope)<EOL>return dispatch[op](arg)<EOL><DEDENT>else:<EOL><INDENT>raise NodeException("<STR_LIT>")<EOL><DEDENT>

Return the corresponding symbolic expression.


super().__init__('<STR_LIT>', children, None)<EOL>self.id = children[<NUM_LIT:0>]<EOL>self.name = self.id.name<EOL>self.line = self.id.line<EOL>self.file = self.id.file<EOL>if len(children) == <NUM_LIT:3>:<EOL><INDENT>self.arguments = children[<NUM_LIT:1>]<EOL>self.bitlist = children[<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>self.arguments = None<EOL>self.bitlist = children[<NUM_LIT:1>]<EOL><DEDENT>


if self.arguments:<EOL><INDENT>return self.arguments.size()<EOL><DEDENT>return <NUM_LIT:0><EOL>

Return the number of parameter expressions.


return self.bitlist.size()<EOL>


string = "<STR_LIT>" % self.name<EOL>if self.arguments is not None:<EOL><INDENT>string += "<STR_LIT:(>" + self.arguments.qasm(prec) + "<STR_LIT:)>"<EOL><DEDENT>string += "<STR_LIT:U+0020>" + self.bitlist.qasm(prec) + "<STR_LIT:;>"<EOL>return string<EOL>


super().__init__('<STR_LIT>', children, None)<EOL>


string = "<STR_LIT>"<EOL>for children in self.children:<EOL><INDENT>string += children.qasm(prec) + "<STR_LIT:\n>"<EOL><DEDENT>return string<EOL>


return self.children[<NUM_LIT:0>].value + "<STR_LIT:(>" + self.children[<NUM_LIT:1>].qasm(prec) + "<STR_LIT:)>"<EOL>


operation = self.children[<NUM_LIT:0>].operation()<EOL>expr = self.children[<NUM_LIT:1>].real(nested_scope)<EOL>return operation(expr)<EOL>


operation = self.children[<NUM_LIT:0>].operation()<EOL>expr = self.children[<NUM_LIT:1>].sym(nested_scope)<EOL>return operation(expr)<EOL>


return "<STR_LIT>" + self.children[<NUM_LIT:0>].qasm(prec) + "<STR_LIT:;>"<EOL>


return "<STR_LIT>" + self.children[<NUM_LIT:0>].qasm(prec) + "<STR_LIT>" +self.children[<NUM_LIT:1>].qasm(prec) + "<STR_LIT:;>"<EOL>


return len(self.children)<EOL>


return "<STR_LIT:U+002C>".join([self.children[j].qasm(prec)<EOL>for j in range(self.size())])<EOL>


return "<STR_LIT>" + self.children[<NUM_LIT:0>].qasm(prec) + "<STR_LIT>"+ str(self.children[<NUM_LIT:1>].value) + "<STR_LIT>" +self.children[<NUM_LIT:2>].qasm(prec)<EOL>


super().__init__('<STR_LIT>', children, None)<EOL>self.id = children[<NUM_LIT:0>]<EOL>self.name = self.id.name<EOL>if len(children) == <NUM_LIT:3>:<EOL><INDENT>self.arguments = children[<NUM_LIT:1>]<EOL>self.bitlist = children[<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>self.arguments = None<EOL>self.bitlist = children[<NUM_LIT:1>]<EOL><DEDENT>


string = self.name<EOL>if self.arguments is not None:<EOL><INDENT>string += "<STR_LIT:(>" + self.arguments.qasm(prec) + "<STR_LIT:)>"<EOL><DEDENT>string += "<STR_LIT:U+0020>" + self.bitlist.qasm(prec) + "<STR_LIT:;>"<EOL>return string<EOL>


<EOL>super().__init__("<STR_LIT:id>", None, None)<EOL>self.name = id<EOL>self.line = line<EOL>self.file = file<EOL>self.is_bit = False<EOL>


ind = indent * '<STR_LIT:U+0020>'<EOL>print(ind, '<STR_LIT:id>', self.name)<EOL>


<EOL>return self.name<EOL>


if not nested_scope:<EOL><INDENT>return "<STR_LIT>" + self.name + "<STR_LIT:}>"<EOL><DEDENT>else:<EOL><INDENT>if self.name not in nested_scope[-<NUM_LIT:1>]:<EOL><INDENT>raise NodeException("<STR_LIT>",<EOL>"<STR_LIT>" % self.name,<EOL>"<STR_LIT>" % self.line,<EOL>"<STR_LIT>" % self.file)<EOL><DEDENT>else:<EOL><INDENT>return nested_scope[-<NUM_LIT:1>][self.name].latex(prec,<EOL>nested_scope[<NUM_LIT:0>:-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>

Return the correspond math mode latex string.


if not nested_scope or self.name not in nested_scope[-<NUM_LIT:1>]:<EOL><INDENT>raise NodeException("<STR_LIT>",<EOL>"<STR_LIT>" % (<EOL>self.name, self.line, self.file))<EOL><DEDENT>else:<EOL><INDENT>return nested_scope[-<NUM_LIT:1>][self.name].sym(nested_scope[<NUM_LIT:0>:-<NUM_LIT:1>])<EOL><DEDENT>


if not nested_scope or self.name not in nested_scope[-<NUM_LIT:1>]:<EOL><INDENT>raise NodeException("<STR_LIT>",<EOL>"<STR_LIT>" % (<EOL>self.name, self.line, self.file))<EOL><DEDENT>else:<EOL><INDENT>return nested_scope[-<NUM_LIT:1>][self.name].real(nested_scope[<NUM_LIT:0>:-<NUM_LIT:1>])<EOL><DEDENT>


super().__init__("<STR_LIT>", None, None)<EOL>parts = re.match(r'<STR_LIT>', value)<EOL>self.language = parts.group(<NUM_LIT:1>)<EOL>self.majorversion = parts.group(<NUM_LIT:2>)<EOL>self.minorversion = parts.group(<NUM_LIT:3>)<EOL>


return "<STR_LIT>" % (self.majorversion, self.minorversion)<EOL>


<EOL>return "<STR_LIT>" % (self.language, self.version())<EOL>


super().__init__('<STR_LIT>', children, None)<EOL>


string = "<STR_LIT>"<EOL>for children in self.children:<EOL><INDENT>string += "<STR_LIT:U+0020>" + children.qasm(prec) + "<STR_LIT:\n>"<EOL><DEDENT>return string<EOL>


lst = []<EOL>for children in self.children:<EOL><INDENT>if children.type == "<STR_LIT>":<EOL><INDENT>lst.append(children.name)<EOL><DEDENT><DEDENT>return lst<EOL>

Return a list of custom gate names in this gate body.


super().__init__('<STR_LIT>', children, None)<EOL>self.id = children[<NUM_LIT:0>]<EOL>self.name = self.id.name<EOL>self.line = self.id.line<EOL>self.file = self.id.file<EOL>if len(children) == <NUM_LIT:3>:<EOL><INDENT>self.arguments = None<EOL>self.bitlist = children[<NUM_LIT:1>]<EOL>self.body = children[<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>self.arguments = children[<NUM_LIT:1>]<EOL>self.bitlist = children[<NUM_LIT:2>]<EOL>self.body = children[<NUM_LIT:3>]<EOL><DEDENT>


if self.arguments:<EOL><INDENT>return self.arguments.size()<EOL><DEDENT>return <NUM_LIT:0><EOL>


return self.bitlist.size()<EOL>


string = "<STR_LIT>" + self.name<EOL>if self.arguments is not None:<EOL><INDENT>string += "<STR_LIT:(>" + self.arguments.qasm(prec) + "<STR_LIT:)>"<EOL><DEDENT>string += "<STR_LIT:U+0020>" + self.bitlist.qasm(prec) + "<STR_LIT:\n>"<EOL>string += "<STR_LIT>" + self.body.qasm(prec) + "<STR_LIT:}>"<EOL>return string<EOL>


super().__init__('<STR_LIT>', children, None)<EOL>self.id = children[<NUM_LIT:0>]<EOL>self.name = self.id.name<EOL>self.line = self.id.line<EOL>self.file = self.id.file<EOL>self.index = self.id.index<EOL>


ind = indent * '<STR_LIT:U+0020>'<EOL>print(ind, '<STR_LIT>')<EOL>self.children[<NUM_LIT:0>].to_string(indent + <NUM_LIT:3>)<EOL>


return "<STR_LIT>" + self.id.qasm(prec) + "<STR_LIT:;>"<EOL>


return len(self.children)<EOL>


return "<STR_LIT:U+002C>".join([self.children[j].qasm(prec)<EOL>for j in range(self.size())])<EOL>


<EOL>super().__init__("<STR_LIT>", None, None)<EOL>self.value = id<EOL>


ind = indent * '<STR_LIT:U+0020>'<EOL>print(ind, '<STR_LIT>', self.value)<EOL>


if self.value == pi:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>return ccode(self.value, precision=prec)<EOL>


<EOL>return latex(self.value)<EOL>


<EOL>return self.value<EOL>


<EOL>return float(self.value.evalf())<EOL>


def __init__(self, type, children=None, root=None):

<EOL>self.type = type<EOL>if children:<EOL><INDENT>self.children = children<EOL><DEDENT>else:<EOL><INDENT>self.children = []<EOL><DEDENT>self.root = root<EOL>self.expression = False<EOL>


return self.expression<EOL>

Return True if this is an expression node.


self.children.append(node)<EOL>


ind = indent * '<STR_LIT:U+0020>'<EOL>if self.root:<EOL><INDENT>print(ind, self.type, '<STR_LIT>', self.root)<EOL><DEDENT>else:<EOL><INDENT>print(ind, self.type)<EOL><DEDENT>indent = indent + <NUM_LIT:3><EOL>ind = indent * '<STR_LIT:U+0020>'<EOL>for children in self.children:<EOL><INDENT>if children is None:<EOL><INDENT>print("<STR_LIT>", type(self))<EOL>print(self.children)<EOL><DEDENT>if isinstance(children, str):<EOL><INDENT>print(ind, children)<EOL><DEDENT>elif isinstance(children, int):<EOL><INDENT>print(ind, str(children))<EOL><DEDENT>elif isinstance(children, float):<EOL><INDENT>print(ind, str(children))<EOL><DEDENT>else:<EOL><INDENT>children.to_string(indent)<EOL><DEDENT><DEDENT>


super().__init__('<STR_LIT>', children, None)<EOL>self.id = children[<NUM_LIT:0>]<EOL>self.name = self.id.name<EOL>self.line = self.id.line<EOL>self.file = self.id.file<EOL>self.index = children[<NUM_LIT:1>].value<EOL>


ind = indent * '<STR_LIT:U+0020>'<EOL>print(ind, '<STR_LIT>', self.name, self.index)<EOL>


<EOL>return self.name + "<STR_LIT>" % self.index<EOL>


super().__init__(*msg)<EOL>self.msg = '<STR_LIT:U+0020>'.join(msg)<EOL>


return repr(self.msg)<EOL>


self.lexer = lex.lex(module=self, debug=False)<EOL>self.filename = filename<EOL>self.lineno = <NUM_LIT:1><EOL>if filename:<EOL><INDENT>with open(filename, '<STR_LIT:r>') as ifile:<EOL><INDENT>self.data = ifile.read()<EOL><DEDENT>self.lexer.input(self.data)<EOL><DEDENT>


self.__mklexer__(filename)<EOL>self.stack = []<EOL>


self.data = data<EOL>self.lexer.input(data)<EOL>


ret = self.lexer.token()<EOL>return ret<EOL>


self.lexer = self.stack.pop()<EOL>self.filename = self.lexer.qasm_file<EOL>self.lineno = self.lexer.qasm_line<EOL>


self.lexer.qasm_file = self.filename<EOL>self.lexer.qasm_line = self.lineno<EOL>self.stack.append(self.lexer)<EOL>self.__mklexer__(filename)<EOL>

Push a PLY lexer on the stack to parse filename.


t.value = Number(t.value)<EOL>return t<EOL>


t.value = int(t.value)<EOL>return t<EOL>


return t<EOL>


<EOL>next_token = self.lexer.token()<EOL>lineno = next_token.lineno<EOL>if isinstance(next_token.value, str):<EOL><INDENT>incfile = next_token.value.strip('<STR_LIT:">')<EOL><DEDENT>else:<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>if incfile in CORE_LIBS:<EOL><INDENT>incfile = os.path.join(CORE_LIBS_PATH, incfile)<EOL><DEDENT>next_token = self.lexer.token()<EOL>if next_token is None or next_token.value != '<STR_LIT:;>':<EOL><INDENT>raise QasmError('<STR_LIT>', str(lineno))<EOL><DEDENT>if not os.path.exists(incfile):<EOL><INDENT>raise QasmError(<EOL>'<STR_LIT>' %<EOL>(incfile, str(next_token.lineno), self.filename))<EOL><DEDENT>self.push(incfile)<EOL>return self.lexer.token()<EOL>


pass<EOL>


t.type = self.reserved.get(t.value, '<STR_LIT>')<EOL>if t.type == '<STR_LIT>':<EOL><INDENT>t.value = node.Id(t.value, self.lineno, self.filename)<EOL><DEDENT>return t<EOL>


self.lineno += len(t.value)<EOL>t.lexer.lineno = self.lineno<EOL>


self._bound_instructions = {}<EOL>

Acts as method registration decorator and tracker for instruction conversion methods.


<EOL>def _apply_converter(converter):<EOL><INDENT>"""<STR_LIT>"""<EOL>@functools.wraps(converter)<EOL>def _call_valid_converter(self, shift, instruction):<EOL><INDENT>"""<STR_LIT>"""<EOL>if isinstance(instruction, type_instruction):<EOL><INDENT>return converter(self, shift, instruction)<EOL><DEDENT>else:<EOL><INDENT>raise PulseError('<STR_LIT>'<EOL>'<STR_LIT>'.format(instruction, type_instruction))<EOL><DEDENT><DEDENT>self._bound_instructions[type_instruction] = _call_valid_converter<EOL>return _call_valid_converter<EOL><DEDENT>return _apply_converter<EOL>

Converter decorator method.

        Pulse instruction converter is defined for each instruction type,
        and this decorator binds converter function to valid instruction type.

        Args:
            type_instruction (Instruction): valid pulse instruction class to the converter.


try:<EOL><INDENT>return self._bound_instructions[type(instruction)]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise PulseError('<STR_LIT>' % instruction)<EOL><DEDENT>


def __init__(self, qobj_model, **run_config):

self._qobj_model = qobj_model<EOL>self._run_config = run_config<EOL>

Create new converter.

        Args:
             qobj_model (QobjInstruction): marshmallow model to serialize to object.
             run_config (dict): experimental configuration.


@bind_instruction(commands.AcquireInstruction)<EOL><INDENT>def convert_acquire(self, shift, instruction):<DEDENT>

meas_level = self._run_config.get('<STR_LIT>', <NUM_LIT:2>)<EOL>command_dict = {<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT>': shift+instruction.start_time,<EOL>'<STR_LIT>': instruction.duration,<EOL>'<STR_LIT>': [q.index for q in instruction.acquires],<EOL>'<STR_LIT>': [m.index for m in instruction.mem_slots]<EOL>}<EOL>if meas_level == <NUM_LIT:2>:<EOL><INDENT>if instruction.command.discriminator:<EOL><INDENT>command_dict.update({<EOL>'<STR_LIT>': [<EOL>QobjMeasurementOption(<EOL>name=instruction.command.discriminator.name,<EOL>params=instruction.command.discriminator.params)<EOL>]<EOL>})<EOL><DEDENT>command_dict.update({<EOL>'<STR_LIT>': [regs.index for regs in instruction.reg_slots]<EOL>})<EOL><DEDENT>if meas_level >= <NUM_LIT:1>:<EOL><INDENT>if instruction.command.kernel:<EOL><INDENT>command_dict.update({<EOL>'<STR_LIT>': [<EOL>QobjMeasurementOption(<EOL>name=instruction.command.kernel.name,<EOL>params=instruction.command.kernel.params)<EOL>]<EOL>})<EOL><DEDENT><DEDENT>return self._qobj_model(**command_dict)<EOL>

Return converted `AcquireInstruction`.

        Args:
            shift(int): Offset time.
            instruction (AcquireInstruction): acquire instruction.
        Returns:
            dict: Dictionary of required parameters.


command_dict = {<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT>': shift+instruction.start_time,<EOL>'<STR_LIT>': instruction.channels[<NUM_LIT:0>].name,<EOL>'<STR_LIT>': instruction.command.phase<EOL>}<EOL>return self._qobj_model(**command_dict)<EOL>

Return converted `FrameChangeInstruction`.

        Args:
            shift(int): Offset time.
            instruction (FrameChangeInstruction): frame change instruction.
        Returns:
            dict: Dictionary of required parameters.


command_dict = {<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT>': shift+instruction.start_time,<EOL>'<STR_LIT>': instruction.channels[<NUM_LIT:0>].name,<EOL>'<STR_LIT>': instruction.command.value<EOL>}<EOL>return self._qobj_model(**command_dict)<EOL>

Return converted `PersistentValueInstruction`.

        Args:
            shift(int): Offset time.
            instruction (PersistentValueInstruction): persistent value instruction.
        Returns:
            dict: Dictionary of required parameters.


@bind_instruction(commands.PulseInstruction)<EOL><INDENT>def convert_drive(self, shift, instruction):<DEDENT>

command_dict = {<EOL>'<STR_LIT:name>': instruction.command.name,<EOL>'<STR_LIT>': shift+instruction.start_time,<EOL>'<STR_LIT>': instruction.channels[<NUM_LIT:0>].name<EOL>}<EOL>return self._qobj_model(**command_dict)<EOL>

Return converted `PulseInstruction`.

        Args:
            shift(int): Offset time.
            instruction (PulseInstruction): drive instruction.
        Returns:
            dict: Dictionary of required parameters.


@bind_instruction(commands.Snapshot)<EOL><INDENT>def convert_snapshot(self, shift, instruction):<DEDENT>

command_dict = {<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT>': shift+instruction.start_time,<EOL>'<STR_LIT:label>': instruction.name,<EOL>'<STR_LIT:type>': instruction.type<EOL>}<EOL>return self._qobj_model(**command_dict)<EOL>

Return converted `Snapshot`.

        Args:
            shift(int): Offset time.
            instruction (Snapshot): snapshot instruction.
        Returns:
            dict: Dictionary of required parameters.


def __init__(self, qobj_model, default_qubit_los, default_meas_los, **run_config):

self.qobj_model = qobj_model<EOL>self.default_qubit_los = default_qubit_los<EOL>self.default_meas_los = default_meas_los<EOL>self.run_config = run_config<EOL>

Create new converter.

        Args:
            qobj_model (PulseQobjExperimentConfig): qobj model for experiment config.
            default_qubit_los (list): List of default qubit lo frequencies.
            default_meas_los (list): List of default meas lo frequencies.
            run_config (dict): experimental configuration.


lo_config = {}<EOL>q_los = self.get_qubit_los(user_lo_config)<EOL>if q_los:<EOL><INDENT>lo_config['<STR_LIT>'] = q_los<EOL><DEDENT>m_los = self.get_meas_los(user_lo_config)<EOL>if m_los:<EOL><INDENT>lo_config['<STR_LIT>'] = m_los<EOL><DEDENT>return self.qobj_model(**lo_config)<EOL>

Return PulseQobjExperimentConfig

        Args:
            user_lo_config (LoConfig): A dictionary of LOs to format.

        Returns:
            PulseQobjExperimentConfig: qobj.


try:<EOL><INDENT>_q_los = self.default_qubit_los.copy()<EOL><DEDENT>except KeyError:<EOL><INDENT>raise PulseError('<STR_LIT>')<EOL><DEDENT>for channel, lo_freq in user_lo_config.qubit_lo_dict().items():<EOL><INDENT>_q_los[channel.index] = lo_freq<EOL><DEDENT>if _q_los == self.default_qubit_los:<EOL><INDENT>return None<EOL><DEDENT>return _q_los<EOL>

Embed default qubit LO frequencies from backend and format them to list object.
        If configured lo frequency is the same as default, this method returns `None`.

        Args:
            user_lo_config (LoConfig): A dictionary of LOs to format.

        Returns:
            list: A list of qubit LOs.

        Raises:
            PulseError: when LO frequencies are missing.


try:<EOL><INDENT>_m_los = self.default_meas_los.copy()<EOL><DEDENT>except KeyError:<EOL><INDENT>raise PulseError('<STR_LIT>')<EOL><DEDENT>for channel, lo_freq in user_lo_config.meas_lo_dict().items():<EOL><INDENT>_m_los[channel.index] = lo_freq<EOL><DEDENT>if _m_los == self.default_meas_los:<EOL><INDENT>return None<EOL><DEDENT>return _m_los<EOL>

Embed default meas LO frequencies from backend and format them to list object.
        If configured lo frequency is the same as default, this method returns `None`.

        Args:
            user_lo_config (LoConfig): A dictionary of LOs to format.

        Returns:
            list: A list of meas LOs.

        Raises:
            PulseError: when LO frequencies are missing.


validate_json_against_schema(<EOL>qobj.as_dict(), '<STR_LIT>',<EOL>err_msg='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>

Validates a QObj against the .json schema.

    Args:
        qobj (Qobj): Qobj to be validated.


super().__init__('<STR_LIT:U+0020>'.join(message))<EOL>self.message = '<STR_LIT:U+0020>'.join(message)<EOL>


return repr(self.message)<EOL>


p.cx(c, b)<EOL>p.cx(c, a)<EOL>p.ccx(a, b, c)<EOL>


p.ccx(a, b, c)<EOL>p.cx(c, a)<EOL>p.cx(a, b)<EOL>


q = QuantumRegister(<NUM_LIT:2>)<EOL>c = ClassicalRegister(<NUM_LIT:2>)<EOL>qc = QuantumCircuit(q, c)<EOL>qc.h(q[<NUM_LIT:0>])<EOL>qc.cx(q[<NUM_LIT:0>], q[<NUM_LIT:1>])<EOL>qc.measure(q, c)<EOL>return qc<EOL>

Returns a circuit putting 2 qubits in the Bell state.


for j in range(n):<EOL><INDENT>circ.h(q[j])<EOL>circ.u1(math.pi/float(<NUM_LIT:2>**(j)), q[j]).inverse()<EOL><DEDENT>

n-qubit input state for QFT that produces output 1.


for j in range(n):<EOL><INDENT>for k in range(j):<EOL><INDENT>circ.cu1(math.pi/float(<NUM_LIT:2>**(j-k)), q[j], q[k])<EOL><DEDENT>circ.h(q[j])<EOL><DEDENT>


def assertEqualLedgerPosting(self, a, b, msg=None):

a1 = re.sub('<STR_LIT>', '<STR_LIT:U+0020>', a)<EOL>b1 = re.sub('<STR_LIT>', '<STR_LIT:U+0020>', b)<EOL>return self.assertEqual(a1, b1, msg=msg)<EOL>

Checks that two strings are the same posting. Collapses all space
        sequences > len(2).


if ledgerrcpath is None:<EOL><INDENT>ledgerrcpath = os.path.abspath(os.path.expanduser("<STR_LIT>"))<EOL><DEDENT>if "<STR_LIT>" in os.environ:<EOL><INDENT>return os.path.abspath(os.path.expanduser(os.environ["<STR_LIT>"]))<EOL><DEDENT>elif os.path.exists(ledgerrcpath):<EOL><INDENT>ledgerrc = open(ledgerrcpath)<EOL>for line in ledgerrc.readlines():<EOL><INDENT>md = re.match(r"<STR_LIT>", line)<EOL>if md is not None:<EOL><INDENT>return os.path.abspath(os.path.expanduser(md.group(<NUM_LIT:1>)))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Returns main ledger file path or raise exception if it cannot be \
found.


def print_results(converter, ofx, ledger, txns, args):

if args.initial:<EOL><INDENT>if (not(ledger.check_transaction_by_id<EOL>("<STR_LIT>", converter.mk_ofxid(AUTOSYNC_INITIAL))) and<EOL>not(ledger.check_transaction_by_id("<STR_LIT>", ALL_AUTOSYNC_INITIAL))):<EOL><INDENT>print(converter.format_initial_balance(ofx.account.statement))<EOL><DEDENT><DEDENT>for txn in txns:<EOL><INDENT>print(converter.convert(txn).format(args.indent))<EOL><DEDENT>if args.assertions:<EOL><INDENT>print(converter.format_balance(ofx.account.statement))<EOL><DEDENT>if hasattr(ofx.account.statement, '<STR_LIT>'):<EOL><INDENT>for pos in ofx.account.statement.positions:<EOL><INDENT>print(converter.format_position(pos))<EOL><DEDENT><DEDENT>

This function is the final common pathway of program:

Print initial balance if requested;
Print transactions surviving de-duplication filter;
Print balance assertions if requested;
Print commodity prices obtained from position statements


ofxid = self.mk_ofxid(txn.id)<EOL>metadata = {}<EOL>posting_metadata = {"<STR_LIT>": ofxid}<EOL>if isinstance(txn, OfxTransaction):<EOL><INDENT>posting = Posting(self.name,<EOL>Amount(txn.amount, self.currency),<EOL>metadata=posting_metadata)<EOL>return Transaction(<EOL>date=txn.date,<EOL>payee=self.format_payee(txn),<EOL>postings=[<EOL>posting,<EOL>posting.clone_inverted(<EOL>self.mk_dynamic_account(self.format_payee(txn),<EOL>exclude=self.name))])<EOL><DEDENT>elif isinstance(txn, InvestmentTransaction):<EOL><INDENT>acct1 = self.name<EOL>acct2 = self.name<EOL>posting1 = None<EOL>posting2 = None<EOL>security = self.maybe_get_ticker(txn.security)<EOL>if isinstance(txn.type, str):<EOL><INDENT>if re.match('<STR_LIT>', txn.type):<EOL><INDENT>acct2 = self.unknownaccount or '<STR_LIT>'<EOL><DEDENT>elif txn.type == '<STR_LIT>':<EOL><INDENT>acct2 = '<STR_LIT>'<EOL><DEDENT>elif txn.type == '<STR_LIT>':<EOL><INDENT>acct2 = '<STR_LIT>'<EOL><DEDENT>elif txn.type == '<STR_LIT>' and txn.income_type == '<STR_LIT>':<EOL><INDENT>metadata['<STR_LIT>'] = security<EOL>acct2 = '<STR_LIT>'<EOL>posting1 = Posting(acct1,<EOL>Amount(txn.total, self.currency),<EOL>metadata=posting_metadata)<EOL>posting2 = posting1.clone_inverted(acct2)<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if (txn.type in [<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:3>, <NUM_LIT:4>]):<EOL><INDENT>acct2 = self.unknownaccount or '<STR_LIT>'<EOL><DEDENT>elif (txn.type == <NUM_LIT:2>):<EOL><INDENT>acct2 = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>aux_date = None<EOL>if txn.settleDate is not None andtxn.settleDate != txn.tradeDate:<EOL><INDENT>aux_date = txn.settleDate<EOL><DEDENT>if posting1 is None and posting2 is None:<EOL><INDENT>posting1 = Posting(<EOL>acct1,<EOL>Amount(<EOL>txn.units,<EOL>security,<EOL>unlimited=True),<EOL>unit_price=Amount(<EOL>txn.unit_price,<EOL>self.currency,<EOL>unlimited=True),<EOL>metadata=posting_metadata)<EOL>posting2 = Posting(<EOL>acct2,<EOL>Amount(<EOL>txn.units *<EOL>txn.unit_price,<EOL>self.currency,<EOL>reverse=True))<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT>return Transaction(<EOL>date=txn.tradeDate,<EOL>aux_date=aux_date,<EOL>payee=self.format_payee(txn),<EOL>metadata=metadata,<EOL>postings=[posting1, posting2]<EOL>)<EOL><DEDENT>


<EOL>num_rows, partial = divmod(len(seq), num_columns)<EOL>if partial:<EOL><INDENT>num_rows += <NUM_LIT:1><EOL><DEDENT>try:<EOL><INDENT>result = more_itertools.grouper(seq, num_rows)<EOL><DEDENT>except TypeError:<EOL><INDENT>result = more_itertools.grouper(num_rows, seq)<EOL><DEDENT>return zip(*result)<EOL>


queues = GroupbySaved(seq, func)<EOL>return queues.get_first_n_queues(<NUM_LIT:2>)<EOL>

Split a sequence into two sequences:  the first is elements that
return False for func(element) and the second for True for
func(element).
By default, func is ``bool``, so uses the truth value of the object.

>>> is_odd = lambda n: n%2
>>> even, odd = bisect(range(5), is_odd)
>>> list(odd)
[1, 3]
>>> list(even)
[0, 2, 4]

>>> other, zeros = bisect(reversed(range(5)))
>>> list(zeros)
[0]
>>> list(other)
[4, 3, 2, 1]


res = more_itertools.chunked(iterable, n)<EOL>if isinstance(iterable, six.string_types):<EOL><INDENT>res = ('<STR_LIT>'.join(item) for item in res)<EOL><DEDENT>return res<EOL>

Take a sequence and break it up into chunks of the specified size.
The last chunk may be smaller than size.

This works very similar to grouper_nofill, except
it works with strings as well.

>>> tuple(grouper_nofill_str(3, 'foobarbaz'))
('foo', 'bar', 'baz')

You can still use it on non-strings too if you like.

>>> tuple(grouper_nofill_str(42, []))
()

>>> tuple(grouper_nofill_str(3, list(range(10))))
([0, 1, 2], [3, 4, 5], [6, 7, 8], [9])


return (f() for _ in itertools.repeat(None))<EOL>

Perpetually yield the result of calling function f.

>>> counter = itertools.count()
>>> get_next = functools.partial(next, counter)
>>> numbers = infinite_call(get_next)
>>> next(numbers)
0
>>> next(numbers)
1


return iter(tuple())<EOL>


try:<EOL><INDENT>next(iter(iterable))<EOL><DEDENT>except StopIteration:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Return whether the iterable is empty or not. Consumes at most one item
from the iterator to test.

>>> is_empty(iter(range(0)))
True
>>> is_empty(iter(range(1)))
False


items = iter(iterable)<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>yield next(items)<EOL>next(items)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return<EOL><DEDENT><DEDENT>

Yield every other item from the iterable

>>> ' '.join(every_other('abcdefg'))
'a c e g'


return itertools.chain.from_iterable(six.moves.map(<EOL>every_other, six.moves.map(<EOL>operator.itemgetter(<NUM_LIT:1>),<EOL>itertools.groupby(iterable, key)<EOL>)))<EOL>

Given an iterable with items that may come in as sequential duplicates,
remove those duplicates.

Unlike unique_justseen, this function does not remove triplicates.

>>> ' '.join(remove_duplicates('abcaabbccaaabbbcccbcbc'))
'a b c a b c a a b b c c b c b c'
>>> ' '.join(remove_duplicates('aaaabbbbb'))
'a a b b b'


return itertools.islice(iterable, <NUM_LIT:1>, None)<EOL>

Skip the first element of an iterable

>>> tuple(skip_first(range(10)))
(1, 2, 3, 4, 5, 6, 7, 8, 9)


peeker, original = itertools.tee(iterable)<EOL>return next(peeker), original<EOL>

Get the next value from an iterable, but also return an iterable
that will subsequently return that value and the rest of the
original iterable.

>>> l = iter([1,2,3])
>>> val, l = peek(l)
>>> val
1
>>> list(l)
[1, 2, 3]


while True:<EOL><INDENT>try:<EOL><INDENT>if not predicate(iterable.peek()):<EOL><INDENT>break<EOL><DEDENT>yield next(iterable)<EOL><DEDENT>except StopIteration:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

Like takewhile, but takes a peekable iterable and doesn't
consume the non-matching item.

>>> items = Peekable(range(10))
>>> is_small = lambda n: n < 4

>>> small_items = takewhile_peek(is_small, items)

>>> list(small_items)
[0, 1, 2, 3]

>>> list(items)
[4, 5, 6, 7, 8, 9]

>>> empty = takewhile_peek(is_small, Peekable([]))
>>> list(empty)
[]

>>> items = Peekable([3])
>>> small_items = takewhile_peek(is_small, items)
>>> list(small_items)
[3]
>>> list(items)
[]

>>> items = Peekable([4])
>>> small_items = takewhile_peek(is_small, items)
>>> list(small_items)
[]
>>> list(items)
[4]


iterable = iter(iterable)<EOL>return next(iterable, *args)<EOL>

Return the first item from the iterable.

>>> first(range(11))
0
>>> first([3,2,1])
3
>>> iter = range(11)
>>> first(iter)
0

Raises StopIteration if no value is present.

>>> first([])
Traceback (most recent call last):
...
StopIteration

Pass a default to be used when iterable is empty.

>>> first([], None)


for item in iterable:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return item<EOL><DEDENT>except NameError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Return the last item from the iterable, discarding the rest.

>>> last(range(20))
19
>>> last([])
Traceback (most recent call last):
...
ValueError: Iterable contains no items


result, = item<EOL>return result<EOL>

Return the first element from the iterable, but raise an exception
if elements remain in the iterable after the first.

>>> one(['val'])
'val'

>>> one(['val', 'other'])
Traceback (most recent call last):
...
ValueError: ...values to unpack...

>>> one([])
Traceback (most recent call last):
...
ValueError: ...values to unpack...

>>> numbers = itertools.count()
>>> one(numbers)
Traceback (most recent call last):
...
ValueError: ...values to unpack...
>>> next(numbers)
2


iterset = [iter]<EOL>while len(iterset) < n:<EOL><INDENT>iterset[-<NUM_LIT:1>:] = itertools.tee(iterset[-<NUM_LIT:1>])<EOL>next(iterset[-<NUM_LIT:1>], None)<EOL><DEDENT>return six.moves.zip(*iterset)<EOL>

Like pairwise, except returns n-tuples of adjacent items.
s -> (s0,s1,...,sn), (s1,s2,...,s(n+1)), ...


def window(iter, pre_size=<NUM_LIT:1>, post_size=<NUM_LIT:1>):

pre_iter, iter = itertools.tee(iter)<EOL>pre_iter = itertools.chain((None,) * pre_size, pre_iter)<EOL>pre_iter = nwise(pre_iter, pre_size)<EOL>post_iter, iter = itertools.tee(iter)<EOL>post_iter = itertools.chain(post_iter, (None,) * post_size)<EOL>post_iter = nwise(post_iter, post_size)<EOL>next(post_iter, None)<EOL>return six.moves.zip(pre_iter, iter, post_iter)<EOL>

Given an iterable, return a new iterable which yields triples of
(pre, item, post), where pre and post are the items preceeding and
following the item (or None if no such item is appropriate). pre
and post will always be pre_size and post_size in length.

>>> example = window(range(10), pre_size=2)
>>> pre, item, post = next(example)
>>> pre
(None, None)
>>> post
(1,)
>>> next(example)
((None, 0), 1, (2,))
>>> list(example)[-1]
((7, 8), 9, (None,))


num_bins = int(math.ceil(count / float(bin_size)))<EOL>bins = [<NUM_LIT:0>] * num_bins<EOL>for i in range(count):<EOL><INDENT>bins[i % num_bins] += <NUM_LIT:1><EOL><DEDENT>return bins<EOL>

Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.

So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.

>>> partition_items(11, 3)
[3, 3, 3, 2]

But if you only have ten items, you'll have two groups of three and
two of two.

>>> partition_items(10, 3)
[3, 3, 2, 2]


def balanced_rows(n, iterable, fillvalue=None):

iterable, iterable_copy = itertools.tee(iterable)<EOL>count = len(tuple(iterable_copy))<EOL>for allocation in partition_items(count, n):<EOL><INDENT>row = itertools.islice(iterable, allocation)<EOL>if allocation < n:<EOL><INDENT>row = itertools.chain(row, [fillvalue])<EOL><DEDENT>yield tuple(row)<EOL><DEDENT>

Like grouper, but balance the rows to minimize fill per row.
balanced_rows(3, 'ABCDEFG', 'x') --> ABC DEx FGx"


return list(map(list, map(reversed, lists)))<EOL>


base_types = six.text_type, bytes, collections.abc.Mapping<EOL>return more_itertools.always_iterable(item, base_type=base_types)<EOL>

Given an object, always return an iterable. If the item is not
already iterable, return a tuple containing only the item. If item is
None, an empty iterable is returned.

>>> always_iterable([1,2,3])
<list_iterator...>
>>> always_iterable('foo')
<tuple_iterator...>
>>> always_iterable(None)
<tuple_iterator...>
>>> always_iterable(range(10))
<range_iterator...>
>>> def _test_func(): yield "I'm iterable"
>>> print(next(always_iterable(_test_func())))
I'm iterable

Although mappings are iterable, treat each like a singleton, as
it's more like an object than a sequence.

>>> next(always_iterable(dict(a=1)))
{'a': 1}


if not exceptions:<EOL><INDENT>exceptions = Exception,<EOL><DEDENT>for callable in callables:<EOL><INDENT>try:<EOL><INDENT>yield callable()<EOL><DEDENT>except exceptions:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>

Call each callable in callables, suppressing any exceptions supplied. If
no exception classes are supplied, all Exceptions will be suppressed.

>>> import functools
>>> c1 = functools.partial(int, 'a')
>>> c2 = functools.partial(int, '10')
>>> list(suppress_exceptions((c1, c2)))
[10]
>>> list(suppress_exceptions((c1, c2), KeyError))
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'a'


for item in iterable:<EOL><INDENT>func(item)<EOL>yield item<EOL><DEDENT>

Like 'map', invoking func on each item in the iterable,
except return the original item and not the return
value from the function.

Useful when the side-effect of the func is what's desired.

>>> res = apply(print, range(1, 4))
>>> list(res)
1
2
3
[1, 2, 3]


warnings.warn("<STR_LIT>", DeprecationWarning, stacklevel=<NUM_LIT:2>)<EOL>return maybe_single(list(iterable))<EOL>

Given an iterable, return the items as a list. If the iterable contains
exactly one item, return that item. Correlary function to always_iterable.


try:<EOL><INDENT>single, = sequence<EOL><DEDENT>except ValueError:<EOL><INDENT>return sequence<EOL><DEDENT>return single<EOL>

Given a sequence, if it contains exactly one item,
return that item, otherwise return the sequence.
Correlary function to always_iterable.

>>> maybe_single(tuple('abcd'))
('a', 'b', 'c', 'd')
>>> maybe_single(['a'])
'a'


return itertools.product(*itertools.tee(iterable))<EOL>

Return the cross product of the iterable with itself.

>>> list(self_product([1, 2, 3]))
[(1, 1), (1, 2), ..., (3, 3)]


key = kwargs.pop('<STR_LIT:key>', lambda x: x)<EOL>assert not kwargs<EOL>zipped = more_itertools.collate(*iterables, key=key)<EOL>grouped = itertools.groupby(zipped, key=key)<EOL>groups = (<EOL>tuple(g)<EOL>for k, g in grouped<EOL>)<EOL>def has_dupes(group):<EOL><INDENT>return len(group) > <NUM_LIT:1><EOL><DEDENT>return filter(has_dupes, groups)<EOL>

Yield duplicate items from any number of sorted iterables of items

>>> items_a = [1, 2, 3]
>>> items_b = [0, 3, 4, 5, 6]
>>> list(duplicates(items_a, items_b))
[(3, 3)]

It won't behave as you expect if the iterables aren't ordered

>>> items_b.append(1)
>>> list(duplicates(items_a, items_b))
[(3, 3)]
>>> list(duplicates(items_a, sorted(items_b)))
[(1, 1), (3, 3)]

This function is most interesting when it's operating on a key
of more complex objects.

>>> items_a = [dict(email='joe@example.com', id=1)]
>>> items_b = [dict(email='joe@example.com', id=2), dict(email='other')]
>>> dupe, = duplicates(items_a, items_b, key=operator.itemgetter('email'))
>>> dupe[0]['email'] == dupe[1]['email'] == 'joe@example.com'
True
>>> dupe[0]['id']
1
>>> dupe[1]['id']
2


def assert_ordered(iterable, key=lambda x: x, comp=operator.le):

err_tmpl = (<EOL>"<STR_LIT>" if comp is operator.le else<EOL>"<STR_LIT>" if comp is operator.ge else<EOL>"<STR_LIT>"<EOL>)<EOL>for pair in more_itertools.pairwise(iterable):<EOL><INDENT>keyed = tuple(map(key, pair))<EOL>assert comp(*keyed), err_tmpl.format(**locals())<EOL>yield pair[<NUM_LIT:0>]<EOL><DEDENT>yield pair[<NUM_LIT:1>]<EOL>

Assert that for all items in the iterable, they're in order based on comp

>>> list(assert_ordered(range(5)))
[0, 1, 2, 3, 4]
>>> list(assert_ordered(range(5), comp=operator.ge))
Traceback (most recent call last):
...
AssertionError: 0 < 1
>>> list(assert_ordered(range(5, 0, -1), key=operator.neg))
[5, 4, 3, 2, 1]


def collate_revs(old, new, key=lambda x: x, merge=lambda old, new: new):

missing = object()<EOL>def maybe_merge(*items):<EOL><INDENT>"""<STR_LIT>"""<EOL>def not_missing(ob):<EOL><INDENT>return ob is not missing<EOL><DEDENT>return functools.reduce(merge, filter(not_missing, items))<EOL><DEDENT>new_items = collections.OrderedDict(<EOL>(key(el), el)<EOL>for el in new<EOL>)<EOL>old_items = collections.OrderedDict(<EOL>(key(el), el)<EOL>for el in old<EOL>)<EOL>for old_key, old_item in _mutable_iter(old_items):<EOL><INDENT>if old_key not in new_items:<EOL><INDENT>yield old_item<EOL>continue<EOL><DEDENT>before, match_new, new_items = _swap_on_miss(<EOL>partition_dict(new_items, old_key))<EOL>for new_key, new_item in before.items():<EOL><INDENT>yield maybe_merge(new_item, old_items.pop(new_key, missing))<EOL><DEDENT>yield merge(old_item, match_new)<EOL><DEDENT>for item in new_items.values():<EOL><INDENT>yield item<EOL><DEDENT>

Given revision sets old and new, each containing a series
of revisions of some set of objects, collate them based on
these rules:

- all items from each set are yielded in stable order
- items in old are yielded first
- items in new are yielded last
- items that match are yielded in the order in which they
appear, giving preference to new

Items match based on the 'key' parameter (identity by default).

Items are merged using the 'merge' function, which accepts the old
and new items to be merged (returning new by default).

This algorithm requires fully materializing both old and new in memory.

>>> rev1 = ['a', 'b', 'c']
>>> rev2 = ['a', 'd', 'c']
>>> result = list(collate_revs(rev1, rev2))

'd' must appear before 'c'
>>> result.index('d') < result.index('c')
True

'b' must appear before 'd' because it came chronologically
first.
>>> result.index('b') < result.index('d')
True

>>> result
['a', 'b', 'd', 'c']

>>> list(collate_revs(['a', 'b', 'c'], ['d']))
['a', 'b', 'c', 'd']

>>> list(collate_revs(['b', 'a'], ['a', 'b']))
['a', 'b']

>>> list(collate_revs(['a', 'c'], ['a', 'b', 'c']))
['a', 'b', 'c']

Given two sequences of things out of order, regardless
of which order in which the items are merged, all
keys should always be merged.

>>> from more_itertools import consume
>>> left_items = ['a', 'b', 'c']
>>> right_items = ['a', 'c', 'b']
>>> consume(collate_revs(left_items, right_items, merge=print))
a a
c c
b b
>>> consume(collate_revs(right_items, left_items, merge=print))
a a
b b
c c

The merge should not suppress non-True items:

>>> consume(collate_revs([0, 1, 2, None, ''], [0, None, ''], merge=print))
None None
<BLANKLINE>
0 0


while dict:<EOL><INDENT>prev_key = next(iter(dict))<EOL>yield prev_key, dict.pop(prev_key)<EOL><DEDENT>

Iterate over items in the dict, yielding the first one, but allowing
it to be mutated during the process.
>>> d = dict(a=1)
>>> it = _mutable_iter(d)
>>> next(it)
('a', 1)
>>> d
{}
>>> d.update(b=2)
>>> list(it)
[('b', 2)]


before, item, after = partition_result<EOL>return (before, item, after) if item else (after, item, before)<EOL>

Given a partition_dict result, if the partition missed, swap
the before and after.


def unmatched(pair):<EOL><INDENT>test_key, item, = pair<EOL>return test_key != key<EOL><DEDENT>items_iter = iter(items.items())<EOL>item = items.get(key)<EOL>left = collections.OrderedDict(itertools.takewhile(unmatched, items_iter))<EOL>right = collections.OrderedDict(items_iter)<EOL>return left, item, right<EOL>

Given an ordered dictionary of items and a key in that dict,
return an ordered dict of items before, the keyed item, and
an ordered dict of items after.

>>> od = collections.OrderedDict(zip(range(5), 'abcde'))
>>> before, item, after = partition_dict(od, 3)
>>> before
OrderedDict([(0, 'a'), (1, 'b'), (2, 'c')])
>>> item
'd'
>>> after
OrderedDict([(4, 'e')])

Like string.partition, if the key is not found in the items,
the before will contain all items, item will be None, and
after will be an empty iterable.

>>> before, item, after = partition_dict(od, -1)
>>> before
OrderedDict([(0, 'a'), ..., (4, 'e')])
>>> item
>>> list(after)
[]


item = next(self.sequence)<EOL>key = self.func(item)<EOL>queue = self.queues.setdefault(key, FetchingQueue(self.__fetch__))<EOL>queue.enqueue(item)<EOL>

get the next item from the sequence and queue it up


try:<EOL><INDENT>while key not in self.queues:<EOL><INDENT>self.__fetch__()<EOL><DEDENT>return self.queues[key]<EOL><DEDENT>except StopIteration:<EOL><INDENT>raise KeyError(key)<EOL><DEDENT>


try:<EOL><INDENT>while len(self.queues) < n:<EOL><INDENT>self.__fetch__()<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>pass<EOL><DEDENT>values = list(self.queues.values())<EOL>missing = n - len(values)<EOL>values.extend(iter([]) for n in range(missing))<EOL>return values<EOL>

Run through the sequence until n queues are created and return
them. If fewer are created, return those plus empty iterables to
compensate.


def __init__(self, ignore_classes=six.string_types + (six.binary_type,)):

warnings.warn(<EOL>"<STR_LIT>", DeprecationWarning, stacklevel=<NUM_LIT:2>)<EOL>assert set(six.string_types) <= set(ignore_classes), (<EOL>'<STR_LIT>')<EOL>self.ignore_classes = ignore_classes<EOL>

ignore_classes must include str, because if a string
        is iterable, so is a single character, and the routine runs
        into an infinite recursion


self.__iterator, self.__saved = itertools.tee(self.__saved)<EOL>

Resets the iterator to the start.

Any remaining values in the current iteration are discarded.


if '<STR_LIT:.>' in filename:<EOL><INDENT>main, ext = os.path.splitext(filename)<EOL>return main + ext.lower()<EOL><DEDENT>return filename<EOL>

This is a helper used by UploadSet.save to provide lowercase extensions for
all processed files, to compare with configured extensions in the same
case.

.. versionchanged:: 0.1.4
   Filenames without extensions are no longer lowercased, only the
   extension is returned in lowercase, if an extension exists.

:param filename: The filename to ensure has a lowercase extension.


def patch_request_class(app, size=<NUM_LIT:64> * <NUM_LIT> * <NUM_LIT>):

if size is None:<EOL><INDENT>if isinstance(app.request_class.__dict__['<STR_LIT>'],<EOL>property):<EOL><INDENT>return<EOL><DEDENT>size = app.config.get('<STR_LIT>')<EOL><DEDENT>reqclass = app.request_class<EOL>patched = type(reqclass.__name__, (reqclass,),<EOL>{'<STR_LIT>': size})<EOL>app.request_class = patched<EOL>

By default, Flask will accept uploads to an arbitrary size. While Werkzeug
switches uploads from memory to a temporary file when they hit 500 KiB,
it's still possible for someone to overload your disk space with a
gigantic file.

This patches the app's request class's
`~werkzeug.BaseRequest.max_content_length` attribute so that any upload
larger than the given size is rejected with an HTTP error.

.. note::

   In Flask 0.6, you can do this by setting the `MAX_CONTENT_LENGTH`
   setting, without patching the request class. To emulate this behavior,
   you can pass `None` as the size (you must pass it explicitly). That is
   the best way to call this function, as it won't break the Flask 0.6
   functionality if it exists.

.. versionchanged:: 0.1.1

:param app: The app to patch the request class of.
:param size: The maximum size to accept, in bytes. The default is 64 MiB.
             If it is `None`, the app's `MAX_CONTENT_LENGTH` configuration
             setting will be used to patch.


def config_for_set(uset, app, defaults=None):

config = app.config<EOL>prefix = '<STR_LIT>' % uset.name.upper()<EOL>using_defaults = False<EOL>if defaults is None:<EOL><INDENT>defaults = dict(dest=None, url=None)<EOL><DEDENT>allow_extns = tuple(config.get(prefix + '<STR_LIT>', ()))<EOL>deny_extns = tuple(config.get(prefix + '<STR_LIT>', ()))<EOL>destination = config.get(prefix + '<STR_LIT>')<EOL>base_url = config.get(prefix + '<STR_LIT>')<EOL>if destination is None:<EOL><INDENT>if uset.default_dest:<EOL><INDENT>destination = uset.default_dest(app)<EOL><DEDENT>if destination is None: <EOL><INDENT>if defaults['<STR_LIT>'] is not None:<EOL><INDENT>using_defaults = True<EOL>destination = os.path.join(defaults['<STR_LIT>'], uset.name)<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>" % uset.name)<EOL><DEDENT><DEDENT><DEDENT>if base_url is None and using_defaults and defaults['<STR_LIT:url>']:<EOL><INDENT>base_url = addslash(defaults['<STR_LIT:url>']) + uset.name + '<STR_LIT:/>'<EOL><DEDENT>return UploadConfiguration(destination, base_url, allow_extns, deny_extns)<EOL>

This is a helper function for `configure_uploads` that extracts the
configuration for a single set.

:param uset: The upload set.
:param app: The app to load the configuration from.
:param defaults: A dict with keys `url` and `dest` from the
                 `UPLOADS_DEFAULT_DEST` and `DEFAULT_UPLOADS_URL`
                 settings.


if isinstance(upload_sets, UploadSet):<EOL><INDENT>upload_sets = (upload_sets,)<EOL><DEDENT>if not hasattr(app, '<STR_LIT>'):<EOL><INDENT>app.upload_set_config = {}<EOL><DEDENT>set_config = app.upload_set_config<EOL>defaults = dict(dest=app.config.get('<STR_LIT>'),<EOL>url=app.config.get('<STR_LIT>'))<EOL>for uset in upload_sets:<EOL><INDENT>config = config_for_set(uset, app, defaults)<EOL>set_config[uset.name] = config<EOL><DEDENT>should_serve = any(s.base_url is None for s in set_config.values())<EOL>if '<STR_LIT>' not in app.blueprints and should_serve:<EOL><INDENT>app.register_blueprint(uploads_mod)<EOL><DEDENT>

Call this after the app has been configured. It will go through all the
upload sets, get their configuration, and store the configuration on the
app. It will also register the uploads module if it hasn't been set. This
can be called multiple times with different upload sets.

.. versionchanged:: 0.1.3
   The uploads module/blueprint will only be registered if it is needed
   to serve the upload sets.

:param app: The `~flask.Flask` instance to get the configuration from.
:param upload_sets: The `UploadSet` instances to configure.


if self._config is not None:<EOL><INDENT>return self._config<EOL><DEDENT>try:<EOL><INDENT>return current_app.upload_set_config[self.name]<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>

This gets the current configuration. By default, it looks up the
current application and gets the configuration from there. But if you
don't want to go to the full effort of setting an application, or it's
otherwise outside of a request context, set the `_config` attribute to
an `UploadConfiguration` instance, then set it back to `None` when
you're done.


base = self.config.base_url<EOL>if base is None:<EOL><INDENT>return url_for('<STR_LIT>', setname=self.name,<EOL>filename=filename, _external=True)<EOL><DEDENT>else:<EOL><INDENT>return base + filename<EOL><DEDENT>

This function gets the URL a file uploaded to this set would be
accessed at. It doesn't check whether said file exists.

:param filename: The filename to return the URL for.


if folder is not None:<EOL><INDENT>target_folder = os.path.join(self.config.destination, folder)<EOL><DEDENT>else:<EOL><INDENT>target_folder = self.config.destination<EOL><DEDENT>return os.path.join(target_folder, filename)<EOL>

This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.

:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
               to save to.


def file_allowed(self, storage, basename):

return self.extension_allowed(extension(basename))<EOL>

This tells whether a file is allowed. It should return `True` if the
given `werkzeug.FileStorage` object can be saved with the given
basename, and `False` if it can't. The default implementation just
checks the extension, so you can override this if you want.

:param storage: The `werkzeug.FileStorage` to check.
:param basename: The basename it will be saved under.


return ((ext in self.config.allow) or<EOL>(ext in self.extensions and ext not in self.config.deny))<EOL>

This determines whether a specific extension is allowed. It is called
by `file_allowed`, so if you override that but still want to check
extensions, call back into this.

:param ext: The extension to check, without the dot.


def save(self, storage, folder=None, name=None):

if not isinstance(storage, FileStorage):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if folder is None and name is not None and "<STR_LIT:/>" in name:<EOL><INDENT>folder, name = os.path.split(name)<EOL><DEDENT>basename = self.get_basename(storage.filename)<EOL>if name:<EOL><INDENT>if name.endswith('<STR_LIT:.>'):<EOL><INDENT>basename = name + extension(basename)<EOL><DEDENT>else:<EOL><INDENT>basename = name<EOL><DEDENT><DEDENT>if not self.file_allowed(storage, basename):<EOL><INDENT>raise UploadNotAllowed()<EOL><DEDENT>if folder:<EOL><INDENT>target_folder = os.path.join(self.config.destination, folder)<EOL><DEDENT>else:<EOL><INDENT>target_folder = self.config.destination<EOL><DEDENT>if not os.path.exists(target_folder):<EOL><INDENT>os.makedirs(target_folder)<EOL><DEDENT>if os.path.exists(os.path.join(target_folder, basename)):<EOL><INDENT>basename = self.resolve_conflict(target_folder, basename)<EOL><DEDENT>target = os.path.join(target_folder, basename)<EOL>storage.save(target)<EOL>if folder:<EOL><INDENT>return posixpath.join(folder, basename)<EOL><DEDENT>else:<EOL><INDENT>return basename<EOL><DEDENT>

This saves a `werkzeug.FileStorage` into this upload set. If the
upload is not allowed, an `UploadNotAllowed` error will be raised.
Otherwise, the file will be saved and its name (including the folder)
will be returned.

:param storage: The uploaded file to save.
:param folder: The subfolder within the upload set to save to.
:param name: The name to save the file as. If it ends with a dot, the
             file's extension will be appended to the end. (If you
             are using `name`, you can include the folder in the
             `name` instead of explicitly using `folder`, i.e.
             ``uset.save(file, name="someguy/photo_123.")``


def resolve_conflict(self, target_folder, basename):

name, ext = os.path.splitext(basename)<EOL>count = <NUM_LIT:0><EOL>while True:<EOL><INDENT>count = count + <NUM_LIT:1><EOL>newname = '<STR_LIT>' % (name, count, ext)<EOL>if not os.path.exists(os.path.join(target_folder, newname)):<EOL><INDENT>return newname<EOL><DEDENT><DEDENT>

If a file with the selected name already exists in the target folder,
this method is called to resolve the conflict. It should return a new
basename for the file.

The default implementation splits the name and extension and adds a
suffix to the name consisting of an underscore and a number, and tries
that until it finds one that doesn't exist.

:param target_folder: The absolute path to the target.
:param basename: The file's original basename.


def save(self, dst, buffer_size=<NUM_LIT>):

if isinstance(dst, string_types):<EOL><INDENT>self.saved = dst<EOL><DEDENT>else:<EOL><INDENT>self.saved = dst.name<EOL><DEDENT>

This marks the file as saved by setting the `saved` attribute to the
name of the file it was saved to.

:param dst: The file to save to.
:param buffer_size: Ignored.


for cutoff, units, multiplier in units_table:<EOL><INDENT>if seconds < cutoff:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return units, multiplier<EOL>

Given a duration in seconds, determines the best units and multiplier to
use to display the time. Return value is a 2-tuple of units and multiplier.


units, divider = get_time_units_and_multiplier(seconds)<EOL>seconds *= divider<EOL>return "<STR_LIT>" % (seconds, units)<EOL>

Formats a number of seconds using the best units.


pool = tuple(iterable)<EOL>n = len(pool)<EOL>if r is None:<EOL><INDENT>r = n<EOL><DEDENT>indices = list(range(n))<EOL>cycles = list(range(n - r + <NUM_LIT:1>, n + <NUM_LIT:1>))[::-<NUM_LIT:1>]<EOL>yield tuple(pool[i] for i in indices[:r])<EOL>while n:<EOL><INDENT>for i in reversed(range(r)):<EOL><INDENT>cycles[i] -= <NUM_LIT:1><EOL>if cycles[i] == <NUM_LIT:0>:<EOL><INDENT>indices[i:] = indices[i + <NUM_LIT:1>:] + indices[i:i + <NUM_LIT:1>]<EOL>cycles[i] = n - i<EOL><DEDENT>else:<EOL><INDENT>j = cycles[i]<EOL>indices[i], indices[-j] = indices[-j], indices[i]<EOL>yield tuple(pool[i] for i in indices[:r])<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT>


cols = range(queen_count)<EOL>for vec in permutations(cols):<EOL><INDENT>if (queen_count == len(set(vec[i] + i for i in cols))<EOL>== len(set(vec[i] - i for i in cols))):<EOL><INDENT>yield vec<EOL><DEDENT><DEDENT>

N-Queens solver.

    Args:
        queen_count: the number of queens to solve for. This is also the
            board size.

    Yields:
        Solutions to the problem. Each yielded value is looks like
        (3, 8, 2, 1, 4, ..., 6) where each number is the column position for the
        queen, and the index into the tuple indicates the row.


out = [<NUM_LIT:0>]<EOL>for o in ido:<EOL><INDENT>out.append(out[-<NUM_LIT:1>] + o)<EOL><DEDENT>return list(set(out))<EOL>

incremental direction offsets -> "coordinate offsets


se_nh = []<EOL>nh = [E, SW, SE]<EOL>for c in board:<EOL><INDENT>se_nh.append(frozenset([cti[c + o] for o in nh if (c + o) in cti]))<EOL><DEDENT>return se_nh<EOL>


def __init__(self, points, degree=<NUM_LIT:3>, knots=None):

if knots is None:<EOL><INDENT>self.knots = GetKnots(points, degree)<EOL><DEDENT>else:<EOL><INDENT>if len(points) > len(knots) - degree + <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif len(points) < len(knots) - degree + <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>last = knots[<NUM_LIT:0>]<EOL>for cur in knots[<NUM_LIT:1>:]:<EOL><INDENT>if cur < last:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>last = cur<EOL><DEDENT>self.knots = knots<EOL><DEDENT>self.points = points<EOL>self.degree = degree<EOL>

Creates a Spline. points is a list of GVector, degree is the
degree of the Spline.


return (self.knots[self.degree - <NUM_LIT:1>],<EOL>self.knots[len(self.knots) - self.degree])<EOL>


dom = self.GetDomain()<EOL>if u < dom[<NUM_LIT:0>] or u > dom[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if u == dom[<NUM_LIT:0>]:<EOL><INDENT>return self.points[<NUM_LIT:0>]<EOL><DEDENT>if u == dom[<NUM_LIT:1>]:<EOL><INDENT>return self.points[-<NUM_LIT:1>]<EOL><DEDENT>I = self.GetIndex(u)<EOL>d = [self.points[I - self.degree + <NUM_LIT:1> + ii]<EOL>for ii in range(self.degree + <NUM_LIT:1>)]<EOL>U = self.knots<EOL>for ik in range(<NUM_LIT:1>, self.degree + <NUM_LIT:1>):<EOL><INDENT>for ii in range(I - self.degree + ik + <NUM_LIT:1>, I + <NUM_LIT:2>):<EOL><INDENT>ua = U[ii + self.degree - ik]<EOL>ub = U[ii - <NUM_LIT:1>]<EOL>co1 = (ua - u) / (ua - ub)<EOL>co2 = (u - ub) / (ua - ub)<EOL>index = ii - I + self.degree - ik - <NUM_LIT:1><EOL>d[index] = d[index].linear_combination(d[index + <NUM_LIT:1>], co1, co2)<EOL><DEDENT><DEDENT>return d[<NUM_LIT:0>]<EOL>

Calculates a point of the B-Spline using de Boors Algorithm


color = board.color<EOL>node = self<EOL>path = [node]<EOL>while True:<EOL><INDENT>pos = node.select(board)<EOL>if pos == PASS:<EOL><INDENT>break<EOL><DEDENT>board.move(pos)<EOL>child = node.pos_child[pos]<EOL>if not child:<EOL><INDENT>child = node.pos_child[pos] = UCTNode()<EOL>child.unexplored = board.useful_moves()<EOL>child.pos = pos<EOL>child.parent = node<EOL>path.append(child)<EOL>break<EOL><DEDENT>path.append(child)<EOL>node = child<EOL><DEDENT>self.random_playout(board)<EOL>self.update_path(board, color, path)<EOL>


if self.unexplored:<EOL><INDENT>i = random.randrange(len(self.unexplored))<EOL>pos = self.unexplored[i]<EOL>self.unexplored[i] = self.unexplored[len(self.unexplored) - <NUM_LIT:1>]<EOL>self.unexplored.pop()<EOL>return pos<EOL><DEDENT>elif self.bestchild:<EOL><INDENT>return self.bestchild.pos<EOL><DEDENT>else:<EOL><INDENT>return PASS<EOL><DEDENT>

select move; unexplored children first, then according to uct value


for x in range(MAXMOVES):  <EOL><INDENT>if board.finished:<EOL><INDENT>break<EOL><DEDENT>board.move(board.random_move())<EOL><DEDENT>


def update_path(self, board, color, path):

wins = board.score(BLACK) >= board.score(WHITE)<EOL>for node in path:<EOL><INDENT>if color == BLACK:<EOL><INDENT>color = WHITE<EOL><DEDENT>else:<EOL><INDENT>color = BLACK<EOL><DEDENT>if wins == (color == BLACK):<EOL><INDENT>node.wins += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>node.losses += <NUM_LIT:1><EOL><DEDENT>if node.parent:<EOL><INDENT>node.parent.bestchild = node.parent.best_child()<EOL><DEDENT><DEDENT>


result = []<EOL>for x in xrange(len(l) - <NUM_LIT:1>):<EOL><INDENT>ls = l[x + <NUM_LIT:1>:]<EOL>for y in ls:<EOL><INDENT>result.append((l[x], y))<EOL><DEDENT><DEDENT>return result<EOL>

Pure-Python implementation of itertools.combinations(l, 2).


def filter_benchmarks(benchmarks, bench_funcs, base_ver):

for bm in list(benchmarks):<EOL><INDENT>func = bench_funcs[bm]<EOL>if getattr(func, '<STR_LIT>', False) and (<NUM_LIT:3>, <NUM_LIT:0>) <= base_ver:<EOL><INDENT>benchmarks.discard(bm)<EOL>logging.info("<STR_LIT>"<EOL>"<STR_LIT>" % (bm, base_ver))<EOL>continue<EOL><DEDENT><DEDENT>return benchmarks<EOL>

Filters out benchmarks not supported by both Pythons.

    Args:
        benchmarks: a set() of benchmark names
        bench_funcs: dict mapping benchmark names to functions
        python: the interpereter commands (as lists)

    Returns:
        The filtered set of benchmark names


expansion = bench_groups.get(bm_name)<EOL>if expansion:<EOL><INDENT>for name in expansion:<EOL><INDENT>for name in expand_benchmark_name(name, bench_groups):<EOL><INDENT>yield name<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>yield bm_name<EOL><DEDENT>

Recursively expand name benchmark names.

    Args:
        bm_name: string naming a benchmark or benchmark group.

    Yields:
        Names of actual benchmarks, with all group names fully expanded.


results = []<EOL>visited = set()<EOL>stack = [(node, <NUM_LIT:0>) for node in roots]<EOL>while stack:<EOL><INDENT>current, state = stack.pop()<EOL>if state == <NUM_LIT:0>:<EOL><INDENT>if current not in visited:<EOL><INDENT>visited.add(current)<EOL>stack.append((current, <NUM_LIT:1>))<EOL>stack.extend((parent, <NUM_LIT:0>) for parent in getParents(current))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>assert(current in visited)<EOL>results.append(current)<EOL><DEDENT><DEDENT>return results<EOL>

Return a topological sorting of nodes in a graph.

    roots - list of root nodes to search from
    getParents - function which returns the parents of a given node


strings = []<EOL>def append(s):<EOL><INDENT>if USE_BYTES_IN_PY3K:<EOL><INDENT>strings.append(s.encode('<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>strings.append(s)<EOL><DEDENT><DEDENT>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:P>' * n + '<STR_LIT>' + '<STR_LIT:P>' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:P>' * n + '<STR_LIT>' + '<STR_LIT:P>' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:P>' * n + '<STR_LIT>' + '<STR_LIT:P>' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:P>' * n + '<STR_LIT>' + '<STR_LIT:P>' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>append('<STR_LIT:->' * n + '<STR_LIT>' + '<STR_LIT:->' * n)<EOL>return strings<EOL>

Generates the list of strings that will be used in the benchmarks.

    All strings have repeated prefixes and suffices, and n specifies the
    number of repetitions.