phantomscript = os.path.join(os.path.dirname(__file__),<EOL>'<STR_LIT>')<EOL>directory = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>image_name = kwargs.get('<STR_LIT>', None) or _image_name_from_url(url)<EOL>ext = kwargs.get('<STR_LIT>', '<STR_LIT>').lower()<EOL>save_path = os.path.join(directory, image_name) + '<STR_LIT:.>' + ext<EOL>crop_to_visible = kwargs.get('<STR_LIT>', False)<EOL>cmd_args = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>phantomscript,<EOL>url,<EOL>'<STR_LIT>',<EOL>str(kwargs['<STR_LIT:width>']),<EOL>'<STR_LIT>',<EOL>str(kwargs['<STR_LIT>']),<EOL>'<STR_LIT>',<EOL>str(kwargs['<STR_LIT>']),<EOL>'<STR_LIT>',<EOL>directory,<EOL>'<STR_LIT>',<EOL>ext,<EOL>'<STR_LIT>',<EOL>str(image_name),<EOL>]<EOL>if crop_to_visible:<EOL><INDENT>cmd_args.append('<STR_LIT>')<EOL><DEDENT>output = subprocess.Popen(cmd_args,<EOL>stdout=subprocess.PIPE).communicate()[<NUM_LIT:0>]<EOL>return Screenshot(save_path, directory, image_name + '<STR_LIT:.>' + ext, ext)<EOL>

Call PhantomJS with the specified flags and options.


find = r'<STR_LIT>'<EOL>replace = '<STR_LIT:_>'<EOL>return re.sub(find, replace, url).strip('<STR_LIT:_>')<EOL>


png('<STR_LIT>', device="<STR_LIT>")<EOL>

Debug function - runs if heimdall called directly.


self.accounts = self.accounts or []<EOL>idx = <NUM_LIT:0><EOL>for _acc in self._backend.accounts():<EOL><INDENT>_acc.wallet = self<EOL>try:<EOL><INDENT>if self.accounts[idx]:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>self.accounts.append(_acc)<EOL>idx += <NUM_LIT:1><EOL><DEDENT>

Reloads the wallet and its accounts. By default, this method is called only once,
on :class:`Wallet` initialization. When the wallet is accessed by multiple clients or
exists in multiple instances, calling `refresh()` will be necessary to update
the list of accounts.


return self._backend.height()<EOL>

Returns the height of the wallet.

:rtype: int


key = self._backend.spend_key()<EOL>if key == numbers.EMPTY_KEY:<EOL><INDENT>return None<EOL><DEDENT>return key<EOL>

Returns private spend key. None if wallet is view-only.

:rtype: str or None


return self._backend.view_key()<EOL>


return self._backend.seed()<EOL>


acc, addr = self._backend.new_account(label=label)<EOL>assert acc.index == len(self.accounts)<EOL>self.accounts.append(acc)<EOL>return acc<EOL>

Creates new account, appends it to the :class:`Wallet`'s account list and returns it.

:param label: account label as `str`
:rtype: :class:`Account`


if isinstance(txn_or_pmt, Payment):<EOL><INDENT>txn = txn_or_pmt.transaction<EOL><DEDENT>else:<EOL><INDENT>txn = txn_or_pmt<EOL><DEDENT>try:<EOL><INDENT>return max(<NUM_LIT:0>, self.height() - txn.height)<EOL><DEDENT>except TypeError:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>

Returns the number of confirmations for given
:class:`Transaction <monero.transaction.Transaction>` or
:class:`Payment <monero.transaction.Payment>` object.

:rtype: int


return self._backend.export_outputs()<EOL>

Exports outputs in hexadecimal format.

:rtype: str


return self._backend.import_outputs(outputs_hex)<EOL>

Imports outputs in hexadecimal format. Returns number of imported outputs.

:rtype: int


return self._backend.export_key_images()<EOL>

Exports signed key images as a list of dicts.

:rtype: [dict, dict, ...]


return self._backend.import_key_images(key_images_hex)<EOL>

Imports key images from a list of dicts. Returns tuple of (height, spent, unspent).

:rtype: (int, Decimal, Decimal)


return self.accounts[<NUM_LIT:0>].balances()<EOL>

Returns a tuple of balance and unlocked balance.

:rtype: (Decimal, Decimal)


return self.accounts[<NUM_LIT:0>].balance(unlocked=unlocked)<EOL>

Returns specified balance.

:param unlocked: if `True`, return the unlocked balance, otherwise return total balance
:rtype: Decimal


return self.accounts[<NUM_LIT:0>].addresses()[<NUM_LIT:0>]<EOL>

Returns wallet's master address.

:rtype: :class:`Address <monero.address.Address>`


return self.accounts[<NUM_LIT:0>].addresses()<EOL>

Returns all addresses of the default account.

:rtype: list of :class:`Address <monero.address.Address>` and
        :class:`SubAddress <monero.address.SubAddress>`


return self.accounts[<NUM_LIT:0>].new_address(label=label)<EOL>

Creates a new address in the default account.

:rtype: :class:`SubAddress <monero.address.SubAddress>`


<EOL>if major < <NUM_LIT:0> or major >= <NUM_LIT:2>**<NUM_LIT:32>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(major))<EOL><DEDENT>if minor < <NUM_LIT:0> or minor >= <NUM_LIT:2>**<NUM_LIT:32>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(minor))<EOL><DEDENT>master_address = self.address()<EOL>if major == minor == <NUM_LIT:0>:<EOL><INDENT>return master_address<EOL><DEDENT>master_svk = unhexlify(self.view_key())<EOL>master_psk = unhexlify(self.address().spend_key())<EOL>hsdata = b'<STR_LIT>'.join([<EOL>b'<STR_LIT>', master_svk,<EOL>struct.pack('<STR_LIT>', major), struct.pack('<STR_LIT>', minor)])<EOL>m = keccak_256(hsdata).digest()<EOL>D = ed25519.add_compressed(<EOL>ed25519.decodepoint(master_psk),<EOL>ed25519.scalarmult(ed25519.B, ed25519.decodeint(m)))<EOL>C = ed25519.scalarmult(D, ed25519.decodeint(master_svk))<EOL>netbyte = bytearray([<EOL><NUM_LIT> if master_address.is_mainnet() else<NUM_LIT> if master_address.is_testnet() else <NUM_LIT>])<EOL>data = netbyte + ed25519.encodepoint(D) + ed25519.encodepoint(C)<EOL>checksum = keccak_256(data).digest()[:<NUM_LIT:4>]<EOL>return address.SubAddress(base58.encode(hexlify(data + checksum)))<EOL>

Calculates sub-address for account index (`major`) and address index within
the account (`minor`).

:rtype: :class:`BaseAddress <monero.address.BaseAddress>`


def transfer(self, address, amount,<EOL>priority=prio.NORMAL, payment_id=None, unlock_time=<NUM_LIT:0>,<EOL>relay=True):

return self.accounts[<NUM_LIT:0>].transfer(<EOL>address,<EOL>amount,<EOL>priority=priority,<EOL>payment_id=payment_id,<EOL>unlock_time=unlock_time,<EOL>relay=relay)<EOL>

Sends a transfer from the default account. Returns a list of resulting transactions.

:param address: destination :class:`Address <monero.address.Address>` or subtype
:param amount: amount to send
:param priority: transaction priority, implies fee. The priority can be a number
            from 1 to 4 (unimportant, normal, elevated, priority) or a constant
            from `monero.prio`.
:param payment_id: ID for the payment (must be None if
                :class:`IntegratedAddress <monero.address.IntegratedAddress>`
                is used as the destination)
:param unlock_time: the extra unlock delay
:param relay: if `True`, the wallet will relay the transaction(s) to the network
                immediately; when `False`, it will only return the transaction(s)
                so they might be broadcasted later
:rtype: list of :class:`Transaction <monero.transaction.Transaction>`


def transfer_multiple(self, destinations,<EOL>priority=prio.NORMAL, payment_id=None, unlock_time=<NUM_LIT:0>,<EOL>relay=True):

return self.accounts[<NUM_LIT:0>].transfer_multiple(<EOL>destinations,<EOL>priority=priority,<EOL>payment_id=payment_id,<EOL>unlock_time=unlock_time,<EOL>relay=relay)<EOL>

Sends a batch of transfers from the default account. Returns a list of resulting
transactions.

:param destinations: a list of destination and amount pairs: [(address, amount), ...]
:param priority: transaction priority, implies fee. The priority can be a number
            from 1 to 4 (unimportant, normal, elevated, priority) or a constant
            from `monero.prio`.
:param payment_id: ID for the payment (must be None if
                :class:`IntegratedAddress <monero.address.IntegratedAddress>`
                is used as a destination)
:param unlock_time: the extra unlock delay
:param relay: if `True`, the wallet will relay the transaction(s) to the network
                immediately; when `False`, it will only return the transaction(s)
                so they might be broadcasted later
:rtype: list of :class:`Transaction <monero.transaction.Transaction>`


data = _hexToBin(hex)<EOL>l_data = len(data)<EOL>if l_data == <NUM_LIT:0>:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>full_block_count = l_data // __fullBlockSize<EOL>last_block_size = l_data % __fullBlockSize<EOL>res_size = full_block_count * __fullEncodedBlockSize + __encodedBlockSizes[last_block_size]<EOL>res = bytearray([__alphabet[<NUM_LIT:0>]] * res_size)<EOL>for i in range(full_block_count):<EOL><INDENT>res = encode_block(data[(i*__fullBlockSize):(i*__fullBlockSize+__fullBlockSize)], res, i * __fullEncodedBlockSize)<EOL><DEDENT>if last_block_size > <NUM_LIT:0>:<EOL><INDENT>res = encode_block(data[(full_block_count*__fullBlockSize):(full_block_count*__fullBlockSize+last_block_size)], res, full_block_count * __fullEncodedBlockSize)<EOL><DEDENT>return bytes(res).decode('<STR_LIT:ascii>')<EOL>

Encode hexadecimal string as base58 (ex: encoding a Monero address).


enc = bytearray(enc, encoding='<STR_LIT:ascii>')<EOL>l_enc = len(enc)<EOL>if l_enc == <NUM_LIT:0>:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>full_block_count = l_enc // __fullEncodedBlockSize<EOL>last_block_size = l_enc % __fullEncodedBlockSize<EOL>try:<EOL><INDENT>last_block_decoded_size = __encodedBlockSizes.index(last_block_size)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>" % l_enc)<EOL><DEDENT>data_size = full_block_count * __fullBlockSize + last_block_decoded_size<EOL>data = bytearray(data_size)<EOL>for i in range(full_block_count):<EOL><INDENT>data = decode_block(enc[(i*__fullEncodedBlockSize):(i*__fullEncodedBlockSize+__fullEncodedBlockSize)], data, i * __fullBlockSize)<EOL><DEDENT>if last_block_size > <NUM_LIT:0>:<EOL><INDENT>data = decode_block(enc[(full_block_count*__fullEncodedBlockSize):(full_block_count*__fullEncodedBlockSize+last_block_size)], data, full_block_count * __fullBlockSize)<EOL><DEDENT>return _binToHex(data)<EOL>

Decode a base58 string (ex: a Monero address) into hexidecimal form.


return self._backend.balances(account=self.index)<EOL>


return self._backend.balances(account=self.index)[<NUM_LIT:1> if unlocked else <NUM_LIT:0>]<EOL>


return self._backend.addresses(account=self.index)[<NUM_LIT:0>]<EOL>

Return account's main address.

:rtype: :class:`SubAddress <monero.address.SubAddress>`


return self._backend.addresses(account=self.index)<EOL>

Returns all addresses of the account.

:rtype: list


return self._backend.new_address(account=self.index, label=label)<EOL>

Creates a new address.

:param label: address label as `str`
:rtype: :class:`SubAddress <monero.address.SubAddress>`


return self._backend.transfer(<EOL>[(address, amount)],<EOL>priority,<EOL>payment_id,<EOL>unlock_time,<EOL>account=self.index,<EOL>relay=relay)<EOL>

Sends a transfer. Returns a list of resulting transactions.

:param address: destination :class:`Address <monero.address.Address>` or subtype
:param amount: amount to send
:param priority: transaction priority, implies fee. The priority can be a number
            from 1 to 4 (unimportant, normal, elevated, priority) or a constant
            from `monero.prio`.
:param payment_id: ID for the payment (must be None if
                :class:`IntegratedAddress <monero.address.IntegratedAddress>`
                is used as the destination)
:param unlock_time: the extra unlock delay
:param relay: if `True`, the wallet will relay the transaction(s) to the network
                immediately; when `False`, it will only return the transaction(s)
                so they might be broadcasted later
:rtype: list of :class:`Transaction <monero.transaction.Transaction>`


return self._backend.transfer(<EOL>destinations,<EOL>priority,<EOL>payment_id,<EOL>unlock_time,<EOL>account=self.index,<EOL>relay=relay)<EOL>

Sends a batch of transfers. Returns a list of resulting transactions.

:param destinations: a list of destination and amount pairs:
            [(:class:`Address <monero.address.Address>`, `Decimal`), ...]
:param priority: transaction priority, implies fee. The priority can be a number
            from 1 to 4 (unimportant, normal, elevated, priority) or a constant
            from `monero.prio`.
:param payment_id: ID for the payment (must be None if
                :class:`IntegratedAddress <monero.address.IntegratedAddress>`
                is used as the destination)
:param unlock_time: the extra unlock delay
:param relay: if `True`, the wallet will relay the transaction(s) to the network
                immediately; when `False`, it will only return the transaction(s)
                so they might be broadcasted later
:rtype: list of :class:`Transaction <monero.transaction.Transaction>`


return "<STR_LIT>".join([word[i:i+<NUM_LIT:2>] for i in [<NUM_LIT:6>, <NUM_LIT:4>, <NUM_LIT:2>, <NUM_LIT:0>]])<EOL>

Given any string, swap bits and return the result.

    :rtype: str


out = []<EOL>for i in range(len(hex) // <NUM_LIT:8>):<EOL><INDENT>word = endian_swap(hex[<NUM_LIT:8>*i:<NUM_LIT:8>*i+<NUM_LIT:8>])<EOL>x = int(word, <NUM_LIT:16>)<EOL>w1 = x % cls.n<EOL>w2 = (x // cls.n + w1) % cls.n<EOL>w3 = (x // cls.n // cls.n + w2) % cls.n<EOL>out += [cls.word_list[w1], cls.word_list[w2], cls.word_list[w3]]<EOL><DEDENT>checksum = cls.get_checksum("<STR_LIT:U+0020>".join(out))<EOL>out.append(checksum)<EOL>return "<STR_LIT:U+0020>".join(out)<EOL>

Convert hexadecimal string to mnemonic word representation with checksum.


phrase = phrase.split("<STR_LIT:U+0020>")<EOL>out = "<STR_LIT>"<EOL>for i in range(len(phrase) // <NUM_LIT:3>):<EOL><INDENT>word1, word2, word3 = phrase[<NUM_LIT:3>*i:<NUM_LIT:3>*i+<NUM_LIT:3>]<EOL>w1 = cls.word_list.index(word1)<EOL>w2 = cls.word_list.index(word2) % cls.n<EOL>w3 = cls.word_list.index(word3) % cls.n<EOL>x = w1 + cls.n *((w2 - w1) % cls.n) + cls.n * cls.n * ((w3 - w2) % cls.n)<EOL>out += endian_swap("<STR_LIT>" % x)<EOL><DEDENT>return out<EOL>

Calculate hexadecimal representation of the phrase.


phrase_split = phrase.split("<STR_LIT:U+0020>")<EOL>if len(phrase_split) < <NUM_LIT:12>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(phrase_split) > <NUM_LIT>:<EOL><INDENT>phrase = phrase_split[:<NUM_LIT>]<EOL><DEDENT>else:<EOL><INDENT>phrase = phrase_split[:<NUM_LIT:12>]<EOL><DEDENT>wstr = "<STR_LIT>".join(word[:cls.unique_prefix_length] for word in phrase)<EOL>wstr = bytearray(wstr.encode('<STR_LIT:utf-8>'))<EOL>z = ((crc32(wstr) & <NUM_LIT>) ^ <NUM_LIT> ) >> <NUM_LIT:0><EOL>z2 = ((z ^ <NUM_LIT>) >> <NUM_LIT:0>) % len(phrase)<EOL>return phrase_split[z2]<EOL>

Given a mnemonic word string, return a string of the computed checksum.

        :rtype: str


return self._backend.info()<EOL>

Returns basic information about the daemon.

:rtype: dict


return self._backend.info()['<STR_LIT>']<EOL>

Return daemon's chain height.

:rtype: int


def send_transaction(self, tx, relay=True):

return self._backend.send_transaction(tx.blob, relay=relay)<EOL>

Sends a transaction generated by a :class:`Wallet <monero.wallet.Wallet>`.

:param tx: :class:`Transaction <monero.transaction.Transaction>`
:param relay: whether to relay the transaction to peers. If `False`, the daemon will have
        to mine the transaction itself in order to have it included in the blockchain.


return self._backend.mempool()<EOL>

Returns current mempool contents.

:rtype: list of :class:`Transaction <monero.transaction.Transaction>`


addr = str(addr)<EOL>if _ADDR_REGEX.match(addr):<EOL><INDENT>netbyte = bytearray(unhexlify(base58.decode(addr)))[<NUM_LIT:0>]<EOL>if netbyte in Address._valid_netbytes:<EOL><INDENT>return Address(addr, label=label)<EOL><DEDENT>elif netbyte in SubAddress._valid_netbytes:<EOL><INDENT>return SubAddress(addr, label=label)<EOL><DEDENT>raise ValueError("<STR_LIT>".format(<EOL>nb=netbyte,<EOL>allowed="<STR_LIT:U+002CU+0020>".join(map(<EOL>lambda b: '<STR_LIT>' % b,<EOL>sorted(Address._valid_netbytes + SubAddress._valid_netbytes)))))<EOL><DEDENT>elif _IADDR_REGEX.match(addr):<EOL><INDENT>return IntegratedAddress(addr)<EOL><DEDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(addr=addr, len=len(addr)))<EOL>

Discover the proper class and return instance for a given Monero address.

    :param addr: the address as a string-like object
    :param label: a label for the address (defaults to `None`)

    :rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress`


return self._decoded[<NUM_LIT:0>] == self._valid_netbytes[<NUM_LIT:0>]<EOL>

Returns `True` if the address belongs to mainnet.

        :rtype: bool


return self._decoded[<NUM_LIT:0>] == self._valid_netbytes[<NUM_LIT:2>]<EOL>

Returns `True` if the address belongs to stagenet.

        :rtype: bool


return hexlify(self._decoded[<NUM_LIT>:<NUM_LIT>]).decode()<EOL>

Returns public view key.

        :rtype: str


return hexlify(self._decoded[<NUM_LIT:1>:<NUM_LIT>]).decode()<EOL>

Returns public spend key.

        :rtype: str


return ed25519.public_from_secret_hex(key) == self.view_key()<EOL>

Checks if private view key matches this address.

        :rtype: bool


return ed25519.public_from_secret_hex(key) == self.spend_key()<EOL>

Checks if private spend key matches this address.

        :rtype: bool


payment_id = numbers.PaymentID(payment_id)<EOL>if not payment_id.is_short():<EOL><INDENT>raise TypeError("<STR_LIT>".format(payment_id))<EOL><DEDENT>prefix = <NUM_LIT> if self.is_testnet() else <NUM_LIT> if self.is_stagenet() else <NUM_LIT><EOL>data = bytearray([prefix]) + self._decoded[<NUM_LIT:1>:<NUM_LIT>] + struct.pack('<STR_LIT>', int(payment_id))<EOL>checksum = bytearray(keccak_256(data).digest()[:<NUM_LIT:4>])<EOL>return IntegratedAddress(base58.encode(hexlify(data + checksum)))<EOL>

Integrates payment id into the address.

        :param payment_id: int, hexadecimal string or :class:`PaymentID <monero.numbers.PaymentID>`
                    (max 64-bit long)

        :rtype: `IntegratedAddress`
        :raises: `TypeError` if the payment id is too long


return numbers.PaymentID(hexlify(self._decoded[<NUM_LIT>:-<NUM_LIT:4>]).decode())<EOL>

Returns the integrated payment id.

        :rtype: :class:`PaymentID <monero.numbers.PaymentID>`


prefix = <NUM_LIT> if self.is_testnet() else <NUM_LIT> if self.is_stagenet() else <NUM_LIT><EOL>data = bytearray([prefix]) + self._decoded[<NUM_LIT:1>:<NUM_LIT>]<EOL>checksum = keccak_256(data).digest()[:<NUM_LIT:4>]<EOL>return Address(base58.encode(hexlify(data + checksum)))<EOL>

Returns the base address without payment id.
        :rtype: :class:`Address`


h = hexlify(urandom(n_bytes))<EOL>return "<STR_LIT>".join(h.decode("<STR_LIT:utf-8>"))<EOL>

Generate a secure and random hexadecimal string. 32 bytes by default, but arguments can override.

    :rtype: str


def __init__(self, phrase_or_hex="<STR_LIT>", wordlist="<STR_LIT>"):

self.phrase = "<STR_LIT>" <EOL>self.hex = "<STR_LIT>" <EOL>self.word_list = wordlists.get_wordlist(wordlist)<EOL>self._ed_pub_spend_key = None<EOL>self._ed_pub_view_key = None<EOL>if phrase_or_hex:<EOL><INDENT>seed_split = phrase_or_hex.split("<STR_LIT:U+0020>")<EOL>if len(seed_split) >= <NUM_LIT>:<EOL><INDENT>self.phrase = phrase_or_hex<EOL>if len(seed_split) == <NUM_LIT>:<EOL><INDENT>self._validate_checksum()<EOL><DEDENT>self._decode_seed()<EOL><DEDENT>elif len(seed_split) >= <NUM_LIT:12>:<EOL><INDENT>self.phrase = phrase_or_hex<EOL>if len(seed_split) == <NUM_LIT>:<EOL><INDENT>self._validate_checksum()<EOL><DEDENT>self._decode_seed()<EOL><DEDENT>elif len(seed_split) == <NUM_LIT:1>:<EOL><INDENT>if not len(phrase_or_hex) % <NUM_LIT:8> == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>".format(hex=phrase_or_hex))<EOL><DEDENT>self.hex = phrase_or_hex<EOL>self._encode_seed()<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(arg=phrase_or_hex))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.hex = generate_hex()<EOL>self._encode_seed()<EOL><DEDENT>

If user supplied a seed string to the class, break it down and determine
        if it's hexadecimal or mnemonic word string. Gather the values and store them.
        If no seed is passed, automatically generate a new one from local system randomness.

        :rtype: :class:`Seed <monero.seed.Seed>`


return len(self.hex) == <NUM_LIT:32><EOL>

Returns True if the seed is MyMonero-style (12/13-word).


self.phrase = self.word_list.encode(self.hex)<EOL>

Convert hexadecimal string to mnemonic word representation with checksum.


self.hex = self.word_list.decode(self.phrase)<EOL>

Calculate hexadecimal representation of the phrase.


phrase = self.phrase.split("<STR_LIT:U+0020>")<EOL>if self.word_list.get_checksum(self.phrase) == phrase[-<NUM_LIT:1>]:<EOL><INDENT>return True<EOL><DEDENT>raise ValueError("<STR_LIT>")<EOL>

Given a mnemonic word string, confirm seed checksum (last word) matches the computed checksum.

        :rtype: bool


if net not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>netbyte = <NUM_LIT> if net == '<STR_LIT>' else <NUM_LIT> if net == '<STR_LIT>' else <NUM_LIT><EOL>data = "<STR_LIT>".format(netbyte, self.public_spend_key(), self.public_view_key())<EOL>h = keccak_256()<EOL>h.update(unhexlify(data))<EOL>checksum = h.hexdigest()<EOL>return address(base58.encode(data + checksum[<NUM_LIT:0>:<NUM_LIT:8>]))<EOL>

Returns the master :class:`Address <monero.address.Address>` represented by the seed.

        :param net: the network, one of 'mainnet', 'testnet', 'stagenet'. Default is 'mainnet'.

        :rtype: :class:`Address <monero.address.Address>`


if not isinstance(amount, (Decimal, float) + _integer_types):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return int(amount * <NUM_LIT:10>**<NUM_LIT:12>)<EOL>

Convert Monero decimal to atomic integer of piconero.


return (Decimal(amount) * PICONERO).quantize(PICONERO)<EOL>

Convert atomic integer of piconero to Monero decimal.


return Decimal(amount).quantize(PICONERO)<EOL>

Return the amount rounded to maximal Monero precision.


return self._payment_id.bit_length() <= <NUM_LIT:64><EOL>

Returns True if payment ID is short enough to be included
        in :class:`IntegratedAddress <monero.address.IntegratedAddress>`.


with codecs.open(os.path.join(here, *parts), '<STR_LIT:r>', errors='<STR_LIT:ignore>') as fp:<EOL><INDENT>version_file = fp.read()<EOL><DEDENT>version_match = re.search(r"<STR_LIT>",<EOL>version_file, re.M)<EOL>if version_match:<EOL><INDENT>return version_match.group(<NUM_LIT:1>)<EOL><DEDENT>raise RuntimeError("<STR_LIT>")<EOL>

Figure out version number without importing the package.
https://packaging.python.org/guides/single-sourcing-package-version/


<EOL>import xmlsec<EOL>from saml.schema.base import _element_registry<EOL>element = _element_registry.get(xml.tag)<EOL>signature_node = xmlsec.template.create(<EOL>xml,<EOL>xmlsec.Transform.EXCL_C14N,<EOL>xmlsec.Transform.RSA_SHA1)<EOL>xml.insert(element.meta.signature_index, signature_node)<EOL>ref = xmlsec.template.add_reference(<EOL>signature_node, xmlsec.Transform.SHA1)<EOL>xmlsec.template.add_transform(ref, xmlsec.Transform.ENVELOPED)<EOL>ctx = xmlsec.SignatureContext()<EOL>key = xmlsec.Key.from_memory(stream, xmlsec.KeyFormat.PEM, password)<EOL>ctx.key = key<EOL>ctx.sign(signature_node)<EOL>

Sign an XML document with the given private key file. This will add a
<Signature> element to the document.

:param lxml.etree._Element xml: The document to sign
:param file stream: The private key to sign the document with
:param str password: The password used to access the private key

:rtype: None

Example usage:
::
    from saml import schema
    from lxml import etree

    document = schema.AuthenticationRequest()
    xml_document = document.serialize()
    with open('my_key_file.pem', 'r+') as stream:
        sign(xml_document, stream)

    print etree.tostring(xml_document)

Produces the following XML document:

.. code-block:: xml

    <samlp:AuthnRequest
        xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
        xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
        Version="2.0" ID="_6087de0b111b44349a70ff40191a4c0c"
        IssueInstant="2015-03-16T21:06:39Z">
        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
            <SignedInfo>
                <CanonicalizationMethod
                    Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                    <SignatureMethod
                        Algorithm="http://www.w3.org/2000/
                        09/xmldsig#rsa-sha1"/>
                        <Reference>
                            <Transforms>
                                <Transform
                                    Algorithm="http://www.w3.org/2000/
                                    09/xmldsig#enveloped-signature"/>
                            </Transforms>
                            <DigestMethod
                                Algorithm="http://www.w3.org/2000/
                                09/xmldsig#sha1"/>
                                <DigestValue>
                                    94O1FOjRE4JQYVDqStkYzne9StQ=
                                </DigestValue>
                        </Reference>
            </SignedInfo>
            <SignatureValue>
                aFYRRjtB3bDyLLJzLZmsn0K4SXmOpFYJ+8R8D31VojgiF37FOElbE56UFbm8BAjn
                l2AixrUGXP4djxoxxnfBD/reYw5yVuIVXlMxKec784nF2V4GyrfwJOKaNmlVPkq5
                c8SI+EkKJ02mwiail0Zvjb9FzwvlYD+osMSXvJXVqnGHQDVFlhwbBRRVB6t44/M3
                TzC4mLSVhuvcpsm4GTQSpGkHP7HvweKN/OTc0aTy8Kh/YUrImwnUCii+J0EW4nGg
                71eZyq/IiSPnTD09WDHsWe3g29kpicZXqrQCWeLE2zfVKtyxxs7PyEmodH19jXyz
                wh9hQ8t6PFO47Ros5aV0bw==
            </SignatureValue>
        </Signature>
    </samlp:AuthnRequest>


<EOL>import xmlsec<EOL>signature_node = xmlsec.tree.find_node(xml, xmlsec.Node.SIGNATURE)<EOL>if signature_node is None:<EOL><INDENT>return False<EOL><DEDENT>ctx = xmlsec.SignatureContext()<EOL>ctx.register_id(xml)<EOL>for assertion in xml.xpath("<STR_LIT>"):<EOL><INDENT>ctx.register_id(assertion)<EOL><DEDENT>key = None<EOL>for fmt in [<EOL>xmlsec.KeyFormat.PEM,<EOL>xmlsec.KeyFormat.CERT_PEM]:<EOL><INDENT>stream.seek(<NUM_LIT:0>)<EOL>try:<EOL><INDENT>key = xmlsec.Key.from_memory(stream, fmt)<EOL>break<EOL><DEDENT>except ValueError:  <EOL><INDENT>pass<EOL><DEDENT><DEDENT>ctx.key = key<EOL>try:<EOL><INDENT>ctx.verify(signature_node)<EOL>return True<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>

Verify the signaure of an XML document with the given certificate.
Returns `True` if the document is signed with a valid signature.
Returns `False` if the document is not signed or if the signature is
invalid.

:param lxml.etree._Element xml: The document to sign
:param file stream: The private key to sign the document with

:rtype: Boolean


def __init__(self, meta, name, data, bases):

<EOL>self.name = meta.get('<STR_LIT:name>')<EOL>if self.name is None:<EOL><INDENT>self.name = pascalize(name)<EOL><DEDENT>self.namespace = meta.get('<STR_LIT>')<EOL>self.signature_index = meta.get('<STR_LIT>', <NUM_LIT:1>)<EOL>

Initializes the options object and defaults configuration not
specified.


<EOL>attributes, elements = OrderedDict(), []<EOL>nsmap = dict([self.meta.namespace])<EOL>for name, item in self._items.items():<EOL><INDENT>if isinstance(item, Attribute):<EOL><INDENT>attributes[name] = item.prepare(self)<EOL><DEDENT>elif isinstance(item, Element):<EOL><INDENT>nsmap.update([item.namespace])<EOL>elements.append(item)<EOL><DEDENT><DEDENT>return attributes, elements, nsmap<EOL>

Prepare the date in the instance state for serialization.


<EOL>return self._serialize_item(self)<EOL>

Serializes the data in the instance state as an
XML representation.


return codecs.lookup(name).name<EOL>


if PY3:<EOL><INDENT>bytes_ = map(lambda i: bytes([i]), range(<NUM_LIT:0>, <NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>bytes_ = map(chr, range(<NUM_LIT:0>, <NUM_LIT>))<EOL><DEDENT>for byte in bytes_:<EOL><INDENT>try:<EOL><INDENT>byte.decode(encoding)<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

Whether the encoding can decode all byte values (e.g. latin1)


try:<EOL><INDENT>return os.fspath(p)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return p<EOL><DEDENT>


<EOL>ascii_char = characters(min_codepoint=<NUM_LIT>, max_codepoint=<NUM_LIT>)<EOL>if os.name == '<STR_LIT>':  <EOL><INDENT>surrogate = characters(<EOL>min_codepoint=<NUM_LIT>, max_codepoint=<NUM_LIT>)<EOL>uni_char = characters(min_codepoint=<NUM_LIT>)<EOL>text_strategy = text(<EOL>alphabet=one_of(uni_char, surrogate, ascii_char))<EOL>def text_to_bytes(path):<EOL><INDENT>fs_enc = sys.getfilesystemencoding()<EOL>try:<EOL><INDENT>return path.encode(fs_enc, '<STR_LIT>')<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>return path.encode(fs_enc, '<STR_LIT:replace>')<EOL><DEDENT><DEDENT>bytes_strategy = text_strategy.map(text_to_bytes)<EOL><DEDENT>else:<EOL><INDENT>latin_char = characters(min_codepoint=<NUM_LIT>, max_codepoint=<NUM_LIT>)<EOL>bytes_strategy = text(alphabet=one_of(latin_char, ascii_char)).map(<EOL>lambda t: t.encode('<STR_LIT>'))<EOL>unix_path_text = bytes_strategy.map(<EOL>lambda b: b.decode(<EOL>sys.getfilesystemencoding(),<EOL>'<STR_LIT>' if PY3 else '<STR_LIT:ignore>'))<EOL>text_strategy = permutations(draw(unix_path_text)).map(u"<STR_LIT>".join)<EOL><DEDENT>if result_type is None:<EOL><INDENT>return draw(one_of(bytes_strategy, text_strategy))<EOL><DEDENT>elif result_type is bytes:<EOL><INDENT>return draw(bytes_strategy)<EOL><DEDENT>else:<EOL><INDENT>return draw(text_strategy)<EOL><DEDENT>

Generate a path value of type result_type.

    result_type can either be bytes or text_type


assert isinstance(s, str)<EOL>if isinstance(s, bytes) and result_type is text_type:<EOL><INDENT>return s.decode('<STR_LIT:ascii>')<EOL><DEDENT>elif isinstance(s, text_type) and result_type is bytes:<EOL><INDENT>return s.encode('<STR_LIT:ascii>')<EOL><DEDENT>return s<EOL>

Given an ASCII str, returns a path of the given type.


<EOL>def tp(s='<STR_LIT>'):<EOL><INDENT>return _str_to_path(s, result_type)<EOL><DEDENT>if os.name != '<STR_LIT>':<EOL><INDENT>return tp(os.sep)<EOL><DEDENT>sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp)<EOL>name = _filename(result_type)<EOL>char = characters(min_codepoint=ord("<STR_LIT:A>"), max_codepoint=ord("<STR_LIT:z>")).map(<EOL>lambda c: tp(str(c)))<EOL>relative = sep<EOL>drive = builds(lambda *x: tp().join(x), char, just(tp('<STR_LIT::>')), sep)<EOL>extended = builds(<EOL>lambda *x: tp().join(x), sep, sep, just(tp('<STR_LIT:?>')), sep, drive)<EOL>network = one_of([<EOL>builds(lambda *x: tp().join(x), sep, sep, name, sep, name, sep),<EOL>builds(lambda *x: tp().join(x),<EOL>sep, sep, just(tp('<STR_LIT:?>')), sep, name, sep, name, sep),<EOL>builds(lambda *x: tp().join(x),<EOL>sep, sep, just(tp('<STR_LIT:?>')), sep, just(tp('<STR_LIT>')), sep, name, sep,<EOL>name, sep),<EOL>builds(lambda *x: tp().join(x),<EOL>sep, sep, just(tp('<STR_LIT:.>')), sep, name, sep),<EOL>])<EOL>final = one_of(relative, drive, extended, network)<EOL>return draw(final)<EOL>


has_pathlike = hasattr(os, '<STR_LIT>')<EOL>if allow_pathlike is None:<EOL><INDENT>allow_pathlike = has_pathlike<EOL><DEDENT>if allow_pathlike and not has_pathlike:<EOL><INDENT>raise InvalidArgument(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>result_type = draw(sampled_from([bytes, text_type]))<EOL>def tp(s='<STR_LIT>'):<EOL><INDENT>return _str_to_path(s, result_type)<EOL><DEDENT>special_component = sampled_from([tp(os.curdir), tp(os.pardir)])<EOL>normal_component = _filename(result_type)<EOL>path_component = one_of(normal_component, special_component)<EOL>extension = normal_component.map(lambda f: tp(os.extsep) + f)<EOL>root = _path_root(result_type)<EOL>def optional(st):<EOL><INDENT>return one_of(st, just(result_type()))<EOL><DEDENT>sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp)<EOL>path_part = builds(lambda s, l: s.join(l), sep, lists(path_component))<EOL>main_strategy = builds(lambda *x: tp().join(x),<EOL>optional(root), path_part, optional(extension))<EOL>if allow_pathlike and hasattr(os, '<STR_LIT>'):<EOL><INDENT>pathlike_strategy = main_strategy.map(lambda p: _PathLike(p))<EOL>main_strategy = one_of(main_strategy, pathlike_strategy)<EOL><DEDENT>return draw(main_strategy)<EOL>

A strategy which generates filesystem path values.

    The generated values include everything which the builtin
    :func:`python:open` function accepts i.e. which won't lead to
    :exc:`ValueError` or :exc:`TypeError` being raised.

    Note that the range of the returned values depends on the operating
    system, the Python version, and the filesystem encoding as returned by
    :func:`sys.getfilesystemencoding`.

    :param allow_pathlike:
        If :obj:`python:None` makes the strategy include objects implementing
        the :class:`python:os.PathLike` interface when Python >= 3.6 is used.
        If :obj:`python:False` no pathlike objects will be generated. If
        :obj:`python:True` pathlike will be generated (Python >= 3.6 required)

    :type allow_pathlike: :obj:`python:bool` or :obj:`python:None`

    .. versionadded:: 3.15


if not hasattr(theclass, '<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>for name, value in list(theclass.CORRELATE.__dict__.items()):<EOL><INDENT>if not isfunction(value):<EOL><INDENT>continue<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>name = '<STR_LIT>'<EOL><DEDENT>elif name.startswith('<STR_LIT:_>'):<EOL><INDENT>continue<EOL><DEDENT>testname = re.sub(r'<STR_LIT>',  uppercase, name)<EOL>testname = re.sub(r'<STR_LIT>', uppercase, testname)<EOL>testname = '<STR_LIT:test>' + re.sub(r'<STR_LIT>', uppercase, testname)<EOL>testmethod = theclass.__name__ + '<STR_LIT:.>' + testname<EOL>method = theclass.CORRELATE.__name__ + '<STR_LIT:.>' + name<EOL>both = testmethod + '<STR_LIT>' + method + '<STR_LIT:)>'<EOL>if testname in dir(theclass):<EOL><INDENT>continue<EOL><DEDENT>if ismodule(theclass.CORRELATE) andvalue.__module__ != theclass.CORRELATE.__name__:<EOL><INDENT>continue  <EOL><DEDENT>if both in correlated:<EOL><INDENT>continue<EOL><DEDENT>correlated[both] = True<EOL>if ismodule(theclass.CORRELATE):<EOL><INDENT>sys.stderr.write('<STR_LIT>' + both + '<STR_LIT:\n>')<EOL><DEDENT>elif isclass(theclass.CORRELATE):<EOL><INDENT>sys.stderr.write('<STR_LIT>' + both + '<STR_LIT:\n>')<EOL><DEDENT><DEDENT>

Checks the given testcase for missing test methods.


for name, item in list(module.__dict__.items()):<EOL><INDENT>if isclass(item):<EOL><INDENT>correlate_class(item)<EOL><DEDENT><DEDENT>

Checks all testcases in the module for missing test methods.


def __init__(self, workflow_spec, deserializing=False, **kwargs):

assert workflow_spec is not None<EOL>LOG.debug("<STR_LIT>" % self.__str__())<EOL>self.spec = workflow_spec<EOL>self.data = {}<EOL>self.outer_workflow = kwargs.get('<STR_LIT>', self)<EOL>self.locks = {}<EOL>self.last_task = None<EOL>if deserializing:<EOL><INDENT>assert '<STR_LIT>' in workflow_spec.task_specs<EOL>root = workflow_spec.task_specs['<STR_LIT>']  <EOL><DEDENT>else:<EOL><INDENT>if '<STR_LIT>' in workflow_spec.task_specs:<EOL><INDENT>root = workflow_spec.task_specs['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>root = specs.Simple(workflow_spec, '<STR_LIT>')<EOL><DEDENT><DEDENT>self.task_tree = Task(self, root)<EOL>self.success = True<EOL>self.debug = False<EOL>self.completed_event = Event()<EOL>self.task_tree.state = Task.COMPLETED<EOL>start = self.task_tree._add_child(self.spec.start, state=Task.FUTURE)<EOL>self.spec.start._predict(start)<EOL>if '<STR_LIT>' not in kwargs:<EOL><INDENT>start.task_spec._update(start)<EOL><DEDENT>

Constructor.

:type workflow_spec: specs.WorkflowSpec
:param workflow_spec: The workflow specification.
:type deserializing: bool
:param deserializing: set to true when deserializing to avoid
  generating tasks twice (and associated problems with multiple
  hierarchies of tasks)


mask = Task.NOT_FINISHED_MASK<EOL>iter = Task.Iterator(self.task_tree, mask)<EOL>try:<EOL><INDENT>next(iter)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Returns True if the entire Workflow is completed, False otherwise.

:rtype: bool
:return: Whether the workflow is completed.


return self.data.get(name, default)<EOL>

Returns the value of the data field with the given name, or the given
default value if the data field does not exist.

:type  name: str
:param name: A data field name.
:type  default: obj
:param default: Return this value if the data field does not exist.
:rtype:  obj
:returns: The value of the data field.


self.success = success<EOL>cancel = []<EOL>mask = Task.NOT_FINISHED_MASK<EOL>for task in Task.Iterator(self.task_tree, mask):<EOL><INDENT>cancel.append(task)<EOL><DEDENT>for task in cancel:<EOL><INDENT>task.cancel()<EOL><DEDENT>

Cancels all open tasks in the workflow.

:type  success: bool
:param success: Whether the Workflow should be marked as successfully
                completed.


return self.spec.get_task_spec_from_name(name)<EOL>

Returns the task spec with the given name.

:type  name: str
:param name: The name of the task.
:rtype:  TaskSpec
:returns: The task spec with the given name.


tasks = [task for task in self.get_tasks() if task.id == id]<EOL>return tasks[<NUM_LIT:0>] if len(tasks) == <NUM_LIT:1> else None<EOL>

Returns the task with the given id.

:type id:integer
:param id: The id of a task.
:rtype: Task
:returns: The task with the given id.


return [task for task in self.get_tasks()<EOL>if task.task_spec.name == name]<EOL>

Returns all tasks whose spec has the given name.

:type name: str
:param name: The name of a task spec.
:rtype: Task
:return: The task that relates to the spec with the given name.


return [t for t in Task.Iterator(self.task_tree, state)]<EOL>

Returns a list of Task objects with the given state.

:type  state: integer
:param state: A bitmask of states.
:rtype:  list[Task]
:returns: A list of tasks.


if task_id is None:<EOL><INDENT>raise WorkflowException(self.spec, '<STR_LIT>')<EOL><DEDENT>for task in self.task_tree:<EOL><INDENT>if task.id == task_id:<EOL><INDENT>return task.complete()<EOL><DEDENT><DEDENT>msg = '<STR_LIT>' % task_id<EOL>raise WorkflowException(self.spec, msg)<EOL>

Runs the task with the given id.

:type  task_id: integer
:param task_id: The id of the Task object.


def complete_next(self, pick_up=True, halt_on_manual=True):

<EOL>blacklist = []<EOL>if pick_up and self.last_task is not None:<EOL><INDENT>try:<EOL><INDENT>iter = Task.Iterator(self.last_task, Task.READY)<EOL>task = next(iter)<EOL><DEDENT>except StopIteration:<EOL><INDENT>task = None<EOL><DEDENT>self.last_task = None<EOL>if task is not None:<EOL><INDENT>if not (halt_on_manual and task.task_spec.manual):<EOL><INDENT>if task.complete():<EOL><INDENT>self.last_task = task<EOL>return True<EOL><DEDENT><DEDENT>blacklist.append(task)<EOL><DEDENT><DEDENT>for task in Task.Iterator(self.task_tree, Task.READY):<EOL><INDENT>for blacklisted_task in blacklist:<EOL><INDENT>if task._is_descendant_of(blacklisted_task):<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if not (halt_on_manual and task.task_spec.manual):<EOL><INDENT>if task.complete():<EOL><INDENT>self.last_task = task<EOL>return True<EOL><DEDENT><DEDENT>blacklist.append(task)<EOL><DEDENT>for task in Task.Iterator(self.task_tree, Task.WAITING):<EOL><INDENT>task.task_spec._update(task)<EOL>if not task._has_state(Task.WAITING):<EOL><INDENT>self.last_task = task<EOL>return True<EOL><DEDENT><DEDENT>return False<EOL>

Runs the next task.
Returns True if completed, False otherwise.

:type  pick_up: bool
:param pick_up: When True, this method attempts to choose the next
                task not by searching beginning at the root, but by
                searching from the position at which the last call
                of complete_next() left off.
:type  halt_on_manual: bool
:param halt_on_manual: When True, this method will not attempt to
                complete any tasks that have manual=True.
                See :meth:`SpiffWorkflow.specs.TaskSpec.__init__`
:rtype:  bool
:returns: True if all tasks were completed, False otherwise.


def complete_all(self, pick_up=True, halt_on_manual=True):

while self.complete_next(pick_up, halt_on_manual):<EOL><INDENT>pass<EOL><DEDENT>

Runs all branches until completion. This is a convenience wrapper
around :meth:`complete_next`, and the pick_up argument is passed
along.

:type  pick_up: bool
:param pick_up: Passed on to each call of complete_next().
:type  halt_on_manual: bool
:param halt_on_manual: When True, this method will not attempt to
                complete any tasks that have manual=True.
                See :meth:`SpiffWorkflow.specs.TaskSpec.__init__`


return self.task_tree.get_dump()<EOL>

Returns a complete dump of the current internal task tree for
debugging.

:rtype:  str
:returns: The debug information.


Like :meth:`get_dump`, but prints the output to the terminal instead
of returning it.


def serialize(self, serializer, **kwargs):

return serializer.serialize_workflow(self, **kwargs)<EOL>

Serializes a Workflow instance using the provided serializer.

:type  serializer: :class:`SpiffWorkflow.serializer.base.Serializer`
:param serializer: The serializer to use.
:type  kwargs: dict
:param kwargs: Passed to the serializer.
:rtype:  object
:returns: The serialized workflow.


@classmethod<EOL><INDENT>def deserialize(cls, serializer, s_state, **kwargs):<DEDENT>

return serializer.deserialize_workflow(s_state, **kwargs)<EOL>

Deserializes a Workflow instance using the provided serializer.

:type  serializer: :class:`SpiffWorkflow.serializer.base.Serializer`
:param serializer: The serializer to use.
:type  s_state: object
:param s_state: The serialized workflow.
:type  kwargs: dict
:param kwargs: Passed to the serializer.
:rtype:  Workflow
:returns: The workflow instance.


def __init__(self, workflow_spec, name=None, script_engine=None,<EOL>read_only=False, **kwargs):

super(BpmnWorkflow, self).__init__(workflow_spec, **kwargs)<EOL>self.name = name or workflow_spec.name<EOL>self.script_engine = script_engine or BpmnScriptEngine()<EOL>self._busy_with_restore = False<EOL>self.read_only = read_only<EOL>

Constructor.

:param script_engine: set to an instance of BpmnScriptEngine if you
need a specialised version. Defaults to a new BpmnScriptEngine
instance.

:param read_only: If this parameter is set then the workflow state
cannot change. It can only be queried to find out about the current
state. This is used in conjunction with the CompactWorkflowSerializer
to provide read only access to a previously saved workflow.


assert not self.read_only<EOL>self.refresh_waiting_tasks()<EOL>self.do_engine_steps()<EOL>for my_task in Task.Iterator(self.task_tree, Task.WAITING):<EOL><INDENT>my_task.task_spec.accept_message(my_task, message)<EOL><DEDENT>

Indicate to the workflow that a message has been received. The message
will be processed by any waiting Intermediate or Boundary Message
Events, that are waiting for the message.


assert not self.read_only<EOL>engine_steps = list(<EOL>[t for t in self.get_tasks(Task.READY)<EOL>if self._is_engine_task(t.task_spec)])<EOL>while engine_steps:<EOL><INDENT>for task in engine_steps:<EOL><INDENT>task.complete()<EOL><DEDENT>engine_steps = list(<EOL>[t for t in self.get_tasks(Task.READY)<EOL>if self._is_engine_task(t.task_spec)])<EOL><DEDENT>

Execute any READY tasks that are engine specific (for example, gateways
or script tasks). This is done in a loop, so it will keep completing
those tasks until there are only READY User tasks, or WAITING tasks
left.


assert not self.read_only<EOL>for my_task in self.get_tasks(Task.WAITING):<EOL><INDENT>my_task.task_spec._update(my_task)<EOL><DEDENT>

Refresh the state of all WAITING tasks. This will, for example, update
Catching Timer Events whose waiting time has passed.


return [t for t in self.get_tasks(Task.READY)<EOL>if not self._is_engine_task(t.task_spec)]<EOL>

Returns a list of User Tasks that are READY for user action


return self.get_tasks(Task.WAITING)<EOL>


def deserialize_workflow_spec(self, s_state, filename=None):

if isinstance(s_state, (str, bytes)):<EOL><INDENT>s_state = BytesIO(s_state)<EOL><DEDENT>package_zip = zipfile.ZipFile(<EOL>s_state, "<STR_LIT:r>", compression=zipfile.ZIP_DEFLATED)<EOL>config = configparser.ConfigParser()<EOL>ini_fp = TextIOWrapper(<EOL>package_zip.open(Packager.METADATA_FILE), encoding="<STR_LIT>")<EOL>try:<EOL><INDENT>config.read_file(ini_fp)<EOL><DEDENT>finally:<EOL><INDENT>ini_fp.close()<EOL><DEDENT>parser_class = BpmnParser<EOL>try:<EOL><INDENT>parser_class_module = config.get(<EOL>'<STR_LIT>', '<STR_LIT>', fallback=None)<EOL><DEDENT>except TypeError:<EOL><INDENT>parser_class_module = config.get(<EOL>'<STR_LIT>', '<STR_LIT>', None)<EOL><DEDENT>if parser_class_module:<EOL><INDENT>mod = __import__(parser_class_module, fromlist=[<EOL>config.get('<STR_LIT>', '<STR_LIT>')])<EOL>parser_class = getattr(mod, config.get('<STR_LIT>', '<STR_LIT>'))<EOL><DEDENT>parser = parser_class()<EOL>for info in package_zip.infolist():<EOL><INDENT>parts = os.path.split(info.filename)<EOL>if (len(parts) == <NUM_LIT:2> and<EOL>not parts[<NUM_LIT:0>] and parts[<NUM_LIT:1>].lower().endswith('<STR_LIT>')):<EOL><INDENT>try:<EOL><INDENT>svg = package_zip.read(info.filename[:-<NUM_LIT:5>] + '<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>svg = None<EOL><DEDENT>bpmn_fp = package_zip.open(info)<EOL>try:<EOL><INDENT>bpmn = ET.parse(bpmn_fp)<EOL><DEDENT>finally:<EOL><INDENT>bpmn_fp.close()<EOL><DEDENT>parser.add_bpmn_xml(<EOL>bpmn, svg=svg,<EOL>filename='<STR_LIT>' % (filename, info.filename))<EOL><DEDENT><DEDENT>return parser.get_spec(config.get('<STR_LIT>', '<STR_LIT>'))<EOL>

:param s_state: a byte-string with the contents of the packaged
workflow archive, or a file-like object.

:param filename: the name of the package file.


if not packager_class:<EOL><INDENT>packager_class = Packager<EOL><DEDENT>packager_class.main()<EOL>

:param packager_class: The Packager class to use. Default: Packager.


def __init__(self, package_file, entry_point_process, meta_data=None,<EOL>editor=None):

self.package_file = package_file<EOL>self.entry_point_process = entry_point_process<EOL>self.parser = self.PARSER_CLASS()<EOL>self.meta_data = meta_data or []<EOL>self.input_files = []<EOL>self.input_path_prefix = None<EOL>self.editor = editor<EOL>self.manifest = {}<EOL>

Constructor.

:param package_file: a file-like object where the contents of the
package must be written to

:param entry_point_process: the name or ID of the entry point process

:param meta_data: A list of meta-data tuples to include in the
metadata.ini file (in addition to the standard ones)

:param editor: The name of the editor used to create the source BPMN /
SVG files. This activates additional hook method calls. (optional)


Add the given BPMN filename to the packager's set.


Add all filenames matching the provided pattern (e.g. *.bpmn) to the
packager's set.


self.input_files += filenames<EOL>

Add all filenames in the given list to the packager's set.


<EOL>self.input_path_prefix = None<EOL>for filename in self.input_files:<EOL><INDENT>if not os.path.isfile(filename):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' % filename)<EOL><DEDENT>if self.input_path_prefix:<EOL><INDENT>full = os.path.abspath(os.path.dirname(filename))<EOL>while not (full.startswith(self.input_path_prefix) and<EOL>self.input_path_prefix):<EOL><INDENT>self.input_path_prefix = self.input_path_prefix[:-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.input_path_prefix = os.path.abspath(<EOL>os.path.dirname(filename))<EOL><DEDENT><DEDENT>self.bpmn = {}<EOL>for filename in self.input_files:<EOL><INDENT>bpmn = ET.parse(filename)<EOL>self.bpmn[os.path.abspath(filename)] = bpmn<EOL><DEDENT>for filename, bpmn in list(self.bpmn.items()):<EOL><INDENT>bpmn = self.pre_parse_and_validate(bpmn, filename)<EOL>self.bpmn[os.path.abspath(filename)] = bpmn<EOL><DEDENT>for filename, bpmn in list(self.bpmn.items()):<EOL><INDENT>self.parser.add_bpmn_xml(bpmn, filename=filename)<EOL><DEDENT>self.wf_spec = self.parser.get_spec(self.entry_point_process)<EOL>self.package_zip = zipfile.ZipFile(<EOL>self.package_file, "<STR_LIT:w>", compression=zipfile.ZIP_DEFLATED)<EOL>done_files = set()<EOL>for spec in self.wf_spec.get_specs_depth_first():<EOL><INDENT>filename = spec.file<EOL>if filename not in done_files:<EOL><INDENT>done_files.add(filename)<EOL>bpmn = self.bpmn[os.path.abspath(filename)]<EOL>self.write_to_package_zip(<EOL>"<STR_LIT>" % spec.name, ET.tostring(bpmn.getroot()))<EOL>self.write_file_to_package_zip(<EOL>"<STR_LIT>" + self._get_zip_path(filename), filename)<EOL>self._call_editor_hook('<STR_LIT>', spec, filename)<EOL><DEDENT><DEDENT>self.write_meta_data()<EOL>self.write_manifest()<EOL>self.package_zip.close()<EOL>

Creates the package, writing the data out to the provided file-like
object.


def write_file_to_package_zip(self, filename, src_filename):

f = open(src_filename)<EOL>with f:<EOL><INDENT>data = f.read()<EOL><DEDENT>self.manifest[filename] = md5hash(data)<EOL>self.package_zip.write(src_filename, filename)<EOL>

Writes a local file in to the zip file and adds it to the manifest
dictionary

:param filename: The zip file name

:param src_filename: the local file name


def write_to_package_zip(self, filename, data):

self.manifest[filename] = md5hash(data)<EOL>self.package_zip.writestr(filename, data)<EOL>

Writes data to the zip file and adds it to the manifest dictionary

:param filename: The zip file name

:param data: the data


config = configparser.ConfigParser()<EOL>config.add_section('<STR_LIT>')<EOL>for f in sorted(self.manifest.keys()):<EOL><INDENT>config.set('<STR_LIT>', f.replace(<EOL>'<STR_LIT:\\>', '<STR_LIT:/>').lower(), self.manifest[f])<EOL><DEDENT>ini = StringIO()<EOL>config.write(ini)<EOL>self.manifest_data = ini.getvalue()<EOL>self.package_zip.writestr(self.MANIFEST_FILE, self.manifest_data)<EOL>

Write the manifest content to the zip file. It must be a predictable
order.


def pre_parse_and_validate(self, bpmn, filename):

bpmn = self._call_editor_hook(<EOL>'<STR_LIT>', bpmn, filename) or bpmn<EOL>return bpmn<EOL>

A subclass can override this method to provide additional parseing or
validation. It should call the parent method first.

:param bpmn: an lxml tree of the bpmn content

:param filename: the source file name

This must return the updated bpmn object (or a replacement)


def pre_parse_and_validate_signavio(self, bpmn, filename):

self._check_for_disconnected_boundary_events_signavio(bpmn, filename)<EOL>self._fix_call_activities_signavio(bpmn, filename)<EOL>return bpmn<EOL>

This is the Signavio specific editor hook for pre-parsing and
validation.

A subclass can override this method to provide additional parseing or
validation. It should call the parent method first.

:param bpmn: an lxml tree of the bpmn content

:param filename: the source file name

This must return the updated bpmn object (or a replacement)


def _fix_call_activities_signavio(self, bpmn, filename):

for node in xpath_eval(bpmn)("<STR_LIT>"):<EOL><INDENT>calledElement = node.get('<STR_LIT>', None)<EOL>if not calledElement:<EOL><INDENT>signavioMetaData = xpath_eval(node, extra_ns={<EOL>'<STR_LIT>': SIGNAVIO_NS})(<EOL>'<STR_LIT>')<EOL>if not signavioMetaData:<EOL><INDENT>raise ValidationException(<EOL>'<STR_LIT>',<EOL>node=node, filename=filename)<EOL><DEDENT>subprocess_reference = one(signavioMetaData).get('<STR_LIT>')<EOL>matches = []<EOL>for b in list(self.bpmn.values()):<EOL><INDENT>for p in xpath_eval(b)("<STR_LIT>"):<EOL><INDENT>if (p.get('<STR_LIT:name>', p.get('<STR_LIT:id>', None)) ==<EOL>subprocess_reference):<EOL><INDENT>matches.append(p)<EOL><DEDENT><DEDENT><DEDENT>if not matches:<EOL><INDENT>raise ValidationException(<EOL>"<STR_LIT>" %<EOL>subprocess_reference, node=node, filename=filename)<EOL><DEDENT>if len(matches) != <NUM_LIT:1>:<EOL><INDENT>raise ValidationException(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % subprocess_reference, node=node,<EOL>filename=filename)<EOL><DEDENT>node.set('<STR_LIT>', matches[<NUM_LIT:0>].get('<STR_LIT:id>'))<EOL><DEDENT><DEDENT>

Signavio produces slightly invalid BPMN for call activity nodes... It
is supposed to put a reference to the id of the called process in to
the calledElement attribute. Instead it stores a string (which is the
name of the process - not its ID, in our interpretation) in an
extension tag.

This code gets the name of the 'subprocess reference', finds a process
with a matching name, and sets the calledElement attribute to the id of
the process.


def package_for_editor_signavio(self, spec, filename):

signavio_file = filename[:-len('<STR_LIT>')] + '<STR_LIT>'<EOL>if os.path.exists(signavio_file):<EOL><INDENT>self.write_file_to_package_zip(<EOL>"<STR_LIT>" + self._get_zip_path(signavio_file), signavio_file)<EOL>f = open(signavio_file, '<STR_LIT:r>')<EOL>try:<EOL><INDENT>signavio_tree = ET.parse(f)<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT>svg_node = one(signavio_tree.findall('<STR_LIT>'))<EOL>self.write_to_package_zip("<STR_LIT>" % spec.name, svg_node.text)<EOL><DEDENT>

Adds the SVG files to the archive for this BPMN file.


config = configparser.ConfigParser()<EOL>config.add_section('<STR_LIT>')<EOL>config.set('<STR_LIT>', '<STR_LIT>', self.wf_spec.name)<EOL>if self.editor:<EOL><INDENT>config.set('<STR_LIT>', '<STR_LIT>', self.editor)<EOL><DEDENT>for k, v in self.meta_data:<EOL><INDENT>config.set('<STR_LIT>', k, v)<EOL><DEDENT>if not self.PARSER_CLASS == BpmnParser:<EOL><INDENT>config.set('<STR_LIT>', '<STR_LIT>',<EOL>inspect.getmodule(self.PARSER_CLASS).__name__)<EOL>config.set('<STR_LIT>', '<STR_LIT>', self.PARSER_CLASS.__name__)<EOL><DEDENT>ini = StringIO()<EOL>config.write(ini)<EOL>self.write_to_package_zip(self.METADATA_FILE, ini.getvalue())<EOL>

Writes the metadata.ini file to the archive.


return OptionParser(<EOL>usage=("<STR_LIT>"<EOL>"<STR_LIT>"),<EOL>version="<STR_LIT>" % (cls.get_version()))<EOL>


parser.add_option("<STR_LIT>", "<STR_LIT>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_option("<STR_LIT>", "<STR_LIT>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_option("<STR_LIT:-c>", "<STR_LIT>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store_true>",<EOL>dest="<STR_LIT>", default=False,<EOL>help="<STR_LIT>")<EOL>group = OptionGroup(parser, "<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>group.add_option("<STR_LIT>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_option_group(group)<EOL>


group = OptionGroup(parser, "<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>group.add_option("<STR_LIT>", "<STR_LIT>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>group.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_option_group(group)<EOL>


@classmethod<EOL><INDENT>def check_args(cls, config, options, args, parser, package_file=None):<DEDENT>

if not args:<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>if not (package_file or options.package_file):<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>if not options.entry_point_process:<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>


@classmethod<EOL><INDENT>def merge_options_and_config(cls, config, options, args):<DEDENT>

if args:<EOL><INDENT>config.set(CONFIG_SECTION_NAME, '<STR_LIT>', '<STR_LIT:U+002C>'.join(args))<EOL><DEDENT>elif config.has_option(CONFIG_SECTION_NAME, '<STR_LIT>'):<EOL><INDENT>for i in config.get(CONFIG_SECTION_NAME, '<STR_LIT>').split('<STR_LIT:U+002C>'):<EOL><INDENT>if not os.path.isabs(i):<EOL><INDENT>i = os.path.abspath(<EOL>os.path.join(os.path.dirname(options.config_file), i))<EOL><DEDENT>args.append(i)<EOL><DEDENT><DEDENT>cls.merge_option_and_config_str('<STR_LIT>', config, options)<EOL>cls.merge_option_and_config_str('<STR_LIT>', config, options)<EOL>cls.merge_option_and_config_str('<STR_LIT>', config, options)<EOL>cls.merge_option_and_config_str(<EOL>'<STR_LIT>', config, options)<EOL>cls.merge_option_and_config_str('<STR_LIT>', config, options)<EOL>


@classmethod<EOL><INDENT>def merge_option_and_config_str(cls, option_name, config, options):<DEDENT>

opt = getattr(options, option_name, None)<EOL>if opt:<EOL><INDENT>config.set(CONFIG_SECTION_NAME, option_name, opt)<EOL><DEDENT>elif config.has_option(CONFIG_SECTION_NAME, option_name):<EOL><INDENT>setattr(options, option_name, config.get(<EOL>CONFIG_SECTION_NAME, option_name))<EOL><DEDENT>

Utility method to merge an option and config, with the option taking "
precedence


@classmethod<EOL><INDENT>def create_meta_data(cls, options, args, parser):<DEDENT>

meta_data = []<EOL>meta_data.append(('<STR_LIT>', cls.get_version()))<EOL>if options.target_engine:<EOL><INDENT>meta_data.append(('<STR_LIT>', options.target_engine))<EOL><DEDENT>if options.target_engine:<EOL><INDENT>meta_data.append(<EOL>('<STR_LIT>', options.target_engine_version))<EOL><DEDENT>return meta_data<EOL>


def serialize_workflow(self, workflow, include_spec=False, **kwargs):

if include_spec:<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return self._get_workflow_state(workflow)<EOL>

:param workflow: the workflow instance to serialize

:param include_spec: Always set to False (The CompactWorkflowSerializer
only supports workflow serialization)


def deserialize_workflow(self, s_state, workflow_spec=None,<EOL>read_only=False, **kwargs):

if workflow_spec is None:<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>workflow = self.new_workflow(<EOL>workflow_spec, read_only=read_only, **kwargs)<EOL>self._restore_workflow_state(workflow, s_state)<EOL>return workflow<EOL>

:param s_state: the state of the workflow as returned by
serialize_workflow

:param workflow_spec: the Workflow Spec of the workflow
(CompactWorkflowSerializer only supports workflow serialization)

:param read_only: (Optional) True if the workflow should be restored in
READ ONLY mode

NB: Additional kwargs passed to the deserialize_workflow method will be
passed to the new_workflow method.


def new_workflow(self, workflow_spec, read_only=False, **kwargs):

return BpmnWorkflow(workflow_spec, read_only=read_only, **kwargs)<EOL>

Create a new workflow instance from the given spec and arguments.

:param workflow_spec: the workflow spec to use

:param read_only: this should be in read only mode

:param kwargs: Any extra kwargs passed to the deserialize_workflow
method will be passed through here


def __init__(self, id, name, documentation, target_task_spec):

self.id = id<EOL>self.name = name.strip() if name else name<EOL>self.documentation = documentation<EOL>self.target_task_spec = target_task_spec<EOL>


def __init__(self, wf_spec, name, lane=None, **kwargs):

super(BpmnSpecMixin, self).__init__(wf_spec, name, **kwargs)<EOL>self.outgoing_sequence_flows = {}<EOL>self.outgoing_sequence_flows_by_id = {}<EOL>self.lane = lane<EOL>self.documentation = None<EOL>

Constructor.

:param lane: Indicates the name of the lane that this task belongs to
(optional).


def connect_outgoing(self, taskspec, sequence_flow_id, sequence_flow_name,<EOL>documentation):

self.connect(taskspec)<EOL>s = SequenceFlow(<EOL>sequence_flow_id, sequence_flow_name, documentation, taskspec)<EOL>self.outgoing_sequence_flows[taskspec.name] = s<EOL>self.outgoing_sequence_flows_by_id[sequence_flow_id] = s<EOL>

Connect this task spec to the indicated child.

:param sequence_flow_id: The ID of the connecting sequenceFlow node.

:param sequence_flow_name: The name of the connecting sequenceFlow
node.


def connect_outgoing_if(self, condition, taskspec, sequence_flow_id,<EOL>sequence_flow_name, documentation):

self.connect_if(_BpmnCondition(condition), taskspec)<EOL>s = SequenceFlow(<EOL>sequence_flow_id, sequence_flow_name, documentation, taskspec)<EOL>self.outgoing_sequence_flows[taskspec.name] = s<EOL>self.outgoing_sequence_flows_by_id[sequence_flow_id] = s<EOL>

Connect this task spec to the indicated child, if the condition
evaluates to true. This should only be called if the task has a
connect_if method (e.g. ExclusiveGateway).

:param sequence_flow_id: The ID of the connecting sequenceFlow node.

:param sequence_flow_name: The name of the connecting sequenceFlow
node.


return self.outgoing_sequence_flows[task_spec.name]<EOL>

Returns the outgoing SequenceFlow targeting the specified task_spec.


return self.outgoing_sequence_flows_by_id[id]<EOL>

Returns the outgoing SequenceFlow with the specified ID.


return id in self.outgoing_sequence_flows_by_id<EOL>

Returns true if the SequenceFlow with the specified ID is leaving this
task.


return sorted([s.name for s in<EOL>list(self.outgoing_sequence_flows_by_id.values())])<EOL>

Returns a list of the names of outgoing sequences. Some may be None.


return iter(list(self.outgoing_sequence_flows_by_id.values()))<EOL>

Returns a list of outgoing sequences. Some may be None.


def accept_message(self, my_task, message):

return False<EOL>

A subclass should override this method if they want to be notified of
the receipt of a message when in a WAITING state.

Returns True if the task did process the message.


pass<EOL>

Called when a task enters the WAITING state.

A subclass may override this method to do work when this happens.


pass<EOL>

Called when a task enters the READY state.

A subclass may override this method to do work when this happens.


pass<EOL>

Called when a task enters the COMPLETE state.

A subclass may override this method to do work when this happens.


pass<EOL>

Called when a task enters the CANCELLED state.

A subclass may override this method to do work when this happens.


def __init__(self, wf_spec, name, event_definition=None, **kwargs):

super(IntermediateCatchEvent, self).__init__(wf_spec, name, **kwargs)<EOL>self.event_definition = event_definition<EOL>

Constructor.

:param event_definition: the EventDefinition that we must wait for.


def __init__(self, wf_spec, name, cancel_activity=None,<EOL>event_definition=None, **kwargs):

super(BoundaryEvent, self).__init__(<EOL>wf_spec, name, event_definition=event_definition, **kwargs)<EOL>self._cancel_activity = cancel_activity<EOL>

Constructor.

:param cancel_activity: True if this is a Cancelling boundary event.


return my_task._get_internal_data('<STR_LIT>', False)<EOL>

This should return True if the event has occurred (i.e. the task may
move from WAITING to READY). This will be called multiple times.


self.message = message<EOL>

Constructor.

:param message: The message to wait for.


Returns true if the message was received while the task was in a
WAITING state.


self.label = label<EOL>self.dateTime = dateTime<EOL>

Constructor.

:param label: The label of the event. Used for the description.

:param dateTime: The dateTime expression for the expiry time. This is
passed to the Script Engine and must evaluate to a datetime.datetime
instance.


dt = my_task.workflow.script_engine.evaluate(my_task, self.dateTime)<EOL>if dt is None:<EOL><INDENT>return False<EOL><DEDENT>if dt.tzinfo:<EOL><INDENT>tz = dt.tzinfo<EOL>now = tz.fromutc(datetime.datetime.utcnow().replace(tzinfo=tz))<EOL><DEDENT>else:<EOL><INDENT>now = datetime.datetime.now()<EOL><DEDENT>return now > dt<EOL>

The Timer is considered to have fired if the evaluated dateTime
expression is before datetime.datetime.now()


def __init__(self, wf_spec, name, script, **kwargs):

super(ScriptTask, self).__init__(wf_spec, name, **kwargs)<EOL>self.script = script<EOL>

Constructor.

:param script: the script that must be executed by the script engine.


def __init__(self, wf_spec, name, bpmn_wf_spec=None, bpmn_wf_class=None,<EOL>**kwargs):

super(CallActivity, self).__init__(wf_spec, name, None, **kwargs)<EOL>self.spec = bpmn_wf_spec<EOL>self.wf_class = bpmn_wf_class<EOL>

Constructor.

:param bpmn_wf_spec: the BpmnProcessSpec for the sub process.
:param bpmn_wf_class: the BpmnWorkflow class to instantiate


return self.wf_class<EOL>

Returns the workflow class to instantiate for the sub workflow


def __init__(self, wf_spec, name, is_terminate_event=False, **kwargs):

super(EndEvent, self).__init__(wf_spec, name, **kwargs)<EOL>self.is_terminate_event = is_terminate_event<EOL>

Constructor.

:param is_terminate_event: True if this is a terminating end event


def __init__(self, name=None, description=None, filename=None, svg=None):

super(BpmnProcessSpec, self).__init__(name=name, filename=filename)<EOL>self.end = _EndJoin(self, '<STR_LIT>' % (self.name))<EOL>end = Simple(self, '<STR_LIT>')<EOL>end.follow(self.end)<EOL>self.svg = svg<EOL>self.description = description<EOL>

Constructor.

:param svg: This provides the SVG representation of the workflow as an
LXML node. (optional)


done = set()<EOL>lanes = set()<EOL>def recursive_find(task_spec):<EOL><INDENT>if task_spec in done:<EOL><INDENT>return<EOL><DEDENT>done.add(task_spec)<EOL>if hasattr(task_spec, '<STR_LIT>') and task_spec.lane:<EOL><INDENT>lanes.add(task_spec.lane)<EOL><DEDENT>if hasattr(task_spec, '<STR_LIT>'):<EOL><INDENT>recursive_find(task_spec.spec.start)<EOL><DEDENT>for t in task_spec.outputs:<EOL><INDENT>recursive_find(t)<EOL><DEDENT><DEDENT>recursive_find(self.start)<EOL>return lanes<EOL>

Returns a set of the distinct lane names used in the process (including
called activities)


done = set()<EOL>specs = [self]<EOL>def recursive_find(task_spec):<EOL><INDENT>if task_spec in done:<EOL><INDENT>return<EOL><DEDENT>done.add(task_spec)<EOL>if hasattr(task_spec, '<STR_LIT>'):<EOL><INDENT>specs.append(task_spec.spec)<EOL>recursive_find(task_spec.spec.start)<EOL><DEDENT>for t in task_spec.outputs:<EOL><INDENT>recursive_find(t)<EOL><DEDENT><DEDENT>recursive_find(self.start)<EOL>return specs<EOL>

Get the specs for all processes (including called ones), in depth first
order.


html = ET.Element('<STR_LIT:html>')<EOL>head = ET.SubElement(html, '<STR_LIT>')<EOL>title = ET.SubElement(head, '<STR_LIT:title>')<EOL>title.text = self.description<EOL>body = ET.SubElement(html, '<STR_LIT:body>')<EOL>h1 = ET.SubElement(body, '<STR_LIT>')<EOL>h1.text = self.description<EOL>span = ET.SubElement(body, '<STR_LIT>')<EOL>span.text = '<STR_LIT>'<EOL>html_text = ET.tostring(html)<EOL>svg_content = '<STR_LIT>'<EOL>svg_done = set()<EOL>for spec in self.get_specs_depth_first():<EOL><INDENT>if spec.svg and spec.svg not in svg_done:<EOL><INDENT>svg_content += '<STR_LIT>' + spec.svg + "<STR_LIT>"<EOL>svg_done.add(spec.svg)<EOL><DEDENT><DEDENT>return html_text.replace('<STR_LIT>', svg_content)<EOL>

Returns an etree HTML node with a document describing the process. This
is only supported if the editor provided an SVG representation.


if isinstance(expression, Operator):<EOL><INDENT>return expression._matches(task)<EOL><DEDENT>else:<EOL><INDENT>return self._eval(task, expression, **task.data)<EOL><DEDENT>

Evaluate the given expression, within the context of the given task and
return the result.


def execute(self, task, script, **kwargs):

locals().update(kwargs)<EOL>exec(script)<EOL>

Execute the script, within the context of the specified task


return False<EOL>

At the moment I haven't implemented support for diverging inclusive
gateways


return one(self.xpath('<STR_LIT>')).text<EOL>

Gets the script content from the node. A subclass can override this
method, if the script needs to be pre-parsed. The result of this call
will be passed to the Script Engine for execution.


messageEventDefinition = first(<EOL>self.xpath('<STR_LIT>'))<EOL>if messageEventDefinition is not None:<EOL><INDENT>return self.get_message_event_definition(messageEventDefinition)<EOL><DEDENT>timerEventDefinition = first(<EOL>self.xpath('<STR_LIT>'))<EOL>if timerEventDefinition is not None:<EOL><INDENT>return self.get_timer_event_definition(timerEventDefinition)<EOL><DEDENT>raise NotImplementedError(<EOL>'<STR_LIT>', ET.tostring(self.node))<EOL>

Parse the event definition node, and return an instance of Event


messageRef = first(self.xpath('<STR_LIT>'))<EOL>message = messageRef.get(<EOL>'<STR_LIT:name>') if messageRef is not None else self.node.get('<STR_LIT:name>')<EOL>return MessageEventDefinition(message)<EOL>

Parse the messageEventDefinition node and return an instance of
MessageEventDefinition


timeDate = first(self.xpath('<STR_LIT>'))<EOL>return TimerEventDefinition(<EOL>self.node.get('<STR_LIT:name>', timeDate.text),<EOL>self.parser.parse_condition(<EOL>timeDate.text, None, None, None, None, self))<EOL>

Parse the timerEventDefinition node and return an instance of
TimerEventDefinition

This currently only supports the timeDate node for specifying an expiry
time for the timer.


self.process_parsers = {}<EOL>self.process_parsers_by_name = {}<EOL>


if process_id_or_name in self.process_parsers_by_name:<EOL><INDENT>return self.process_parsers_by_name[process_id_or_name]<EOL><DEDENT>else:<EOL><INDENT>return self.process_parsers[process_id_or_name]<EOL><DEDENT>

Returns the ProcessParser for the given process ID or name. It matches
by name first.


Add the given BPMN filename to the parser's set.


Add all filenames matching the provided pattern (e.g. *.bpmn) to the
parser's set.


for filename in filenames:<EOL><INDENT>f = open(filename, '<STR_LIT:r>')<EOL>try:<EOL><INDENT>self.add_bpmn_xml(ET.parse(f), filename=filename)<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT><DEDENT>

Add all filenames in the given list to the parser's set.


def add_bpmn_xml(self, bpmn, svg=None, filename=None):

xpath = xpath_eval(bpmn)<EOL>processes = xpath('<STR_LIT>')<EOL>for process in processes:<EOL><INDENT>process_parser = self.PROCESS_PARSER_CLASS(<EOL>self, process, svg, filename=filename, doc_xpath=xpath)<EOL>if process_parser.get_id() in self.process_parsers:<EOL><INDENT>raise ValidationException(<EOL>'<STR_LIT>', node=process, filename=filename)<EOL><DEDENT>if process_parser.get_name() in self.process_parsers_by_name:<EOL><INDENT>raise ValidationException(<EOL>'<STR_LIT>', node=process, filename=filename)<EOL><DEDENT>self.process_parsers[process_parser.get_id()] = process_parser<EOL>self.process_parsers_by_name[<EOL>process_parser.get_name()] = process_parser<EOL><DEDENT>

Add the given lxml representation of the BPMN file to the parser's set.

:param svg: Optionally, provide the text data for the SVG of the BPMN
  file
:param filename: Optionally, provide the source filename.


def parse_condition(self, condition_expression, outgoing_task,<EOL>outgoing_task_node, sequence_flow_node,<EOL>condition_expression_node, task_parser):

return condition_expression<EOL>

Pre-parse the given condition expression, and return the parsed
version. The returned version will be passed to the Script Engine for
evaluation.


def parse_documentation(self, documentation_node, node, node_xpath,<EOL>task_parser=None):

return None if documentation_node is None else documentation_node.text<EOL>

Pre-parse the documentation node for the given node and return the
text.


return self.get_process_parser(process_id_or_name).get_spec()<EOL>

Parses the required subset of the BPMN files, in order to provide an
instance of BpmnProcessSpec (i.e. WorkflowSpec)
for the given process ID or name. The Name is matched first.


if not nodes and or_none:<EOL><INDENT>return None<EOL><DEDENT>assert len(<EOL>nodes) == <NUM_LIT:1>, '<STR_LIT>' % (len(nodes))<EOL>return nodes[<NUM_LIT:0>]<EOL>

Assert that there is exactly one node in the give list, and return it.


if len(nodes) >= <NUM_LIT:1>:<EOL><INDENT>return nodes[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Return the first node in the given list, or None, if the list is empty.


namespaces = {'<STR_LIT>': BPMN_MODEL_NS}<EOL>if extra_ns:<EOL><INDENT>namespaces.update(extra_ns)<EOL><DEDENT>return lambda path: node.findall(path, namespaces)<EOL>

Returns an XPathEvaluator, with namespace prefixes 'bpmn' for
http://www.omg.org/spec/BPMN/20100524/MODEL, and additional specified ones


return '<STR_LIT>' % (BPMN_MODEL_NS, tag)<EOL>

Return the full tag name including namespace for the given BPMN tag. In
other words, the name with namespace
http://www.omg.org/spec/BPMN/20100524/MODEL


def __init__(self, p, node, svg=None, filename=None, doc_xpath=None):

self.parser = p<EOL>self.node = node<EOL>self.doc_xpath = doc_xpath<EOL>self.xpath = xpath_eval(node)<EOL>self.spec = BpmnProcessSpec(<EOL>name=self.get_id(), description=self.get_name(), svg=svg,<EOL>filename=filename)<EOL>self.parsing_started = False<EOL>self.is_parsed = False<EOL>self.parsed_nodes = {}<EOL>self.svg = svg<EOL>self.filename = filename<EOL>self.id_to_lane_lookup = None<EOL>self._init_lane_lookup()<EOL>

Constructor.

:param p: the owning BpmnParser instance
:param node: the XML node for the process
:param svg: the SVG representation of this process as a string
  (optional)
:param filename: the source BPMN filename (optional)


return self.node.get('<STR_LIT:id>')<EOL>


return self.node.get('<STR_LIT:name>', default=self.get_id())<EOL>

Returns the process name (or ID, if no name is included in the file)


if node.get('<STR_LIT:id>') in self.parsed_nodes:<EOL><INDENT>return self.parsed_nodes[node.get('<STR_LIT:id>')]<EOL><DEDENT>(node_parser, spec_class) = self.parser._get_parser_class(node.tag)<EOL>if not node_parser or not spec_class:<EOL><INDENT>raise ValidationException(<EOL>"<STR_LIT>",<EOL>node=node, filename=self.filename)<EOL><DEDENT>np = node_parser(self, spec_class, node)<EOL>task_spec = np.parse_node()<EOL>return task_spec<EOL>

Parses the specified child task node, and returns the task spec. This
can be called by a TaskParser instance, that is owned by this
ProcessParser.


return self.id_to_lane_lookup.get(id, None)<EOL>

Return the name of the lane that contains the specified task


if self.is_parsed:<EOL><INDENT>return self.spec<EOL><DEDENT>if self.parsing_started:<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>')<EOL><DEDENT>self._parse()<EOL>return self.get_spec()<EOL>

Parse this process (if it has not already been parsed), and return the
workflow spec.


def __init__(self, process_parser, spec_class, node):

self.parser = process_parser.parser<EOL>self.process_parser = process_parser<EOL>self.spec_class = spec_class<EOL>self.process_xpath = self.process_parser.xpath<EOL>self.spec = self.process_parser.spec<EOL>self.node = node<EOL>self.xpath = xpath_eval(node)<EOL>

Constructor.

:param process_parser: the owning process parser instance
:param spec_class: the type of spec that should be created. This allows
  a subclass of BpmnParser to provide a specialised spec class, without
  extending the TaskParser.
:param node: the XML node for this task


try:<EOL><INDENT>self.task = self.create_task()<EOL>self.task.documentation = self.parser._parse_documentation(<EOL>self.node, xpath=self.xpath, task_parser=self)<EOL>boundary_event_nodes = self.process_xpath(<EOL>'<STR_LIT>' % self.get_id())<EOL>if boundary_event_nodes:<EOL><INDENT>parent_task = _BoundaryEventParent(<EOL>self.spec, '<STR_LIT>' % self.get_id(),<EOL>self.task, lane=self.task.lane)<EOL>self.process_parser.parsed_nodes[<EOL>self.node.get('<STR_LIT:id>')] = parent_task<EOL>parent_task.connect_outgoing(<EOL>self.task, '<STR_LIT>' % self.get_id(),<EOL>None, None)<EOL>for boundary_event in boundary_event_nodes:<EOL><INDENT>b = self.process_parser.parse_node(boundary_event)<EOL>parent_task.connect_outgoing(<EOL>b,<EOL>'<STR_LIT>' % boundary_event.get(<EOL>'<STR_LIT:id>'),<EOL>None, None)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.process_parser.parsed_nodes[<EOL>self.node.get('<STR_LIT:id>')] = self.task<EOL><DEDENT>children = []<EOL>outgoing = self.process_xpath(<EOL>'<STR_LIT>' % self.get_id())<EOL>if len(outgoing) > <NUM_LIT:1> and not self.handles_multiple_outgoing():<EOL><INDENT>raise ValidationException(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>node=self.node,<EOL>filename=self.process_parser.filename)<EOL><DEDENT>for sequence_flow in outgoing:<EOL><INDENT>target_ref = sequence_flow.get('<STR_LIT>')<EOL>target_node = one(<EOL>self.process_xpath('<STR_LIT>' % target_ref))<EOL>c = self.process_parser.parse_node(target_node)<EOL>children.append((c, target_node, sequence_flow))<EOL><DEDENT>if children:<EOL><INDENT>default_outgoing = self.node.get('<STR_LIT:default>')<EOL>if not default_outgoing:<EOL><INDENT>(c, target_node, sequence_flow) = children[<NUM_LIT:0>]<EOL>default_outgoing = sequence_flow.get('<STR_LIT:id>')<EOL><DEDENT>for (c, target_node, sequence_flow) in children:<EOL><INDENT>self.connect_outgoing(<EOL>c, target_node, sequence_flow,<EOL>sequence_flow.get('<STR_LIT:id>') == default_outgoing)<EOL><DEDENT><DEDENT>return parent_task if boundary_event_nodes else self.task<EOL><DEDENT>except ValidationException:<EOL><INDENT>raise<EOL><DEDENT>except Exception as ex:<EOL><INDENT>exc_info = sys.exc_info()<EOL>tb = "<STR_LIT>".join(traceback.format_exception(<EOL>exc_info[<NUM_LIT:0>], exc_info[<NUM_LIT:1>], exc_info[<NUM_LIT:2>]))<EOL>LOG.error("<STR_LIT>", ex, tb)<EOL>raise ValidationException(<EOL>"<STR_LIT>" % (ex), node=self.node,<EOL>filename=self.process_parser.filename)<EOL><DEDENT>

Parse this node, and all children, returning the connected task spec.


return self.process_parser.get_lane(self.get_id())<EOL>

Return the name of the lane that contains this task


return target_ref or self.get_id()<EOL>

Returns a unique task spec name for this task (or the targeted one)


return self.spec_class(self.spec, self.get_task_spec_name(),<EOL>lane=self.get_lane(),<EOL>description=self.node.get('<STR_LIT:name>', None))<EOL>

Create an instance of the task appropriately. A subclass can override
this method to get extra information from the node.


def connect_outgoing(self, outgoing_task, outgoing_task_node,<EOL>sequence_flow_node, is_default):

Connects this task to the indicating outgoing task, with the details in
the sequence flow. A subclass can override this method to get extra
information from the node.


return False<EOL>

A subclass should override this method if the task supports multiple
outgoing sequence flows.


def __init__(self, workflow, task_spec, parent=None, state=MAYBE):

assert workflow is not None<EOL>assert task_spec is not None<EOL>self.workflow = workflow<EOL>self.parent = parent<EOL>self.children = []<EOL>self._state = state<EOL>self.triggered = False<EOL>self.state_history = [state]<EOL>self.log = []<EOL>self.task_spec = task_spec<EOL>self.id = uuid4()<EOL>self.thread_id = self.__class__.thread_id_pool<EOL>self.last_state_change = time.time()<EOL>self.data = {}<EOL>self.internal_data = {}<EOL>if parent is not None:<EOL><INDENT>self.parent._child_added_notify(self)<EOL><DEDENT>


def _setstate(self, value, force=False):

if self._state == value:<EOL><INDENT>return<EOL><DEDENT>if value < self._state and not force:<EOL><INDENT>raise WorkflowException(self.task_spec,<EOL>'<STR_LIT>' % (<EOL>self.get_state_name(),<EOL>self.state_names[value]))<EOL><DEDENT>if __debug__:<EOL><INDENT>old = self.get_state_name()<EOL><DEDENT>self._state = value<EOL>if __debug__:<EOL><INDENT>self.log.append("<STR_LIT>" % (<EOL>self.get_name(),<EOL>old, self.get_state_name()))<EOL><DEDENT>self.state_history.append(value)<EOL>LOG.debug("<STR_LIT>" % (<EOL>self.get_name(),<EOL>self.task_spec.name, old, self.get_state_name()))<EOL>

Setting force to True allows for changing a state after it
COMPLETED. This would otherwise be invalid.


if self.parent is None:<EOL><INDENT>return self<EOL><DEDENT>return self.parent._get_root()<EOL>


assert child is not None<EOL>self.children.append(child)<EOL>

Called by another Task to let us know that a child was added.


def _set_state(self, state, force=True):

self._setstate(state, True)<EOL>self.last_state_change = time.time()<EOL>


return (self.state & state) != <NUM_LIT:0><EOL>

Returns True if the Task has the given state flag set.


def _add_child(self, task_spec, state=MAYBE):

if task_spec is None:<EOL><INDENT>raise ValueError(self, '<STR_LIT>')<EOL><DEDENT>if self._is_predicted() and state & self.PREDICTED_MASK == <NUM_LIT:0>:<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise WorkflowException(self.task_spec, msg)<EOL><DEDENT>task = Task(self.workflow, task_spec, self, state=state)<EOL>task.thread_id = self.thread_id<EOL>if state == self.READY:<EOL><INDENT>task._ready()<EOL><DEDENT>return task<EOL>

Adds a new child and assigns the given TaskSpec to it.

:type  task_spec: TaskSpec
:param task_spec: The task spec that is assigned to the new child.
:type  state: integer
:param state: The bitmask of states for the new child.
:rtype:  Task
:returns: The new child task.


self.__class__.thread_id_pool += <NUM_LIT:1><EOL>self.thread_id = self.__class__.thread_id_pool<EOL>if not recursive:<EOL><INDENT>return self.thread_id<EOL><DEDENT>for child in self:<EOL><INDENT>child.thread_id = self.thread_id<EOL><DEDENT>return self.thread_id<EOL>

Assigns a new thread id to the task.

:type  recursive: bool
:param recursive: Whether to assign the id to children recursively.
:rtype:  bool
:returns: The new thread id.


def _sync_children(self, task_specs, state=MAYBE):

LOG.debug("<STR_LIT>" % self.get_name())<EOL>if task_specs is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>add = task_specs[:]<EOL>remove = []<EOL>for child in self.children:<EOL><INDENT>if child.triggered:<EOL><INDENT>continue<EOL><DEDENT>if child.task_spec in add:<EOL><INDENT>add.remove(child.task_spec)<EOL>continue<EOL><DEDENT>if child._is_definite():<EOL><INDENT>raise WorkflowException(self.task_spec,<EOL>'<STR_LIT>' %<EOL>repr(child))<EOL><DEDENT>remove.append(child)<EOL><DEDENT>for child in remove:<EOL><INDENT>self.children.remove(child)<EOL><DEDENT>for task_spec in add:<EOL><INDENT>self._add_child(task_spec, state)<EOL><DEDENT>

This method syncs up the task's children with the given list of task
specs. In other words::

    - Add one child for each given TaskSpec, unless that child already
      exists.
    - Remove all children for which there is no spec in the given list,
      unless it is a "triggered" task.

.. note::

   It is an error if the task has a non-predicted child that is
   not given in the TaskSpecs.

:type  task_specs: list(TaskSpec)
:param task_specs: The list of task specs that may become children.
:type  state: integer
:param state: The bitmask of states for the new children.


if self.parent is None:<EOL><INDENT>return False<EOL><DEDENT>if self.parent == parent:<EOL><INDENT>return True<EOL><DEDENT>return self.parent._is_descendant_of(parent)<EOL>

Returns True if parent is in the list of ancestors, returns False
otherwise.

:type  parent: Task
:param parent: The parent that is searched in the ancestors.
:rtype:  bool
:returns: Whether the parent was found.


if self.parent is None:<EOL><INDENT>return self<EOL><DEDENT>if self.parent.task_spec == parent_task_spec:<EOL><INDENT>return self<EOL><DEDENT>return self.parent._find_child_of(parent_task_spec)<EOL>

Returns the ancestor that has a task with the given task spec
as a parent.
If no such ancestor was found, the root task is returned.

:type  parent_task_spec: TaskSpec
:param parent_task_spec: The wanted ancestor.
:rtype:  Task
:returns: The child of the given ancestor.


tasks = []<EOL>if self.task_spec == task_spec:<EOL><INDENT>tasks.append(self)<EOL><DEDENT>for child in self:<EOL><INDENT>if child.task_spec != task_spec:<EOL><INDENT>continue<EOL><DEDENT>tasks.append(child)<EOL><DEDENT>return tasks<EOL>

Returns any descendants that have the given task spec assigned.

:type  task_spec: TaskSpec
:param task_spec: The wanted task spec.
:rtype:  list(Task)
:returns: The tasks objects that are attached to the given task spec.


if self.parent is None:<EOL><INDENT>return self<EOL><DEDENT>if self.parent.task_spec == task_spec:<EOL><INDENT>return self.parent<EOL><DEDENT>return self.parent._find_ancestor(task_spec)<EOL>

Returns the ancestor that has the given task spec assigned.
If no such ancestor was found, the root task is returned.

:type  task_spec: TaskSpec
:param task_spec: The wanted task spec.
:rtype:  Task
:returns: The ancestor.


if self.parent is None:<EOL><INDENT>return None<EOL><DEDENT>if self.parent.get_name() == name:<EOL><INDENT>return self.parent<EOL><DEDENT>return self.parent._find_ancestor_from_name(name)<EOL>

Returns the ancestor that has a task with the given name assigned.
Returns None if no such ancestor was found.

:type  name: str
:param name: The name of the wanted task.
:rtype:  Task
:returns: The ancestor.


if self._has_state(self.COMPLETED) or self._has_state(self.CANCELLED):<EOL><INDENT>return<EOL><DEDENT>self._set_state(self.READY)<EOL>self.task_spec._on_ready(self)<EOL>


return self.state<EOL>


state_name = []<EOL>for state, name in list(self.state_names.items()):<EOL><INDENT>if self._has_state(state):<EOL><INDENT>state_name.append(name)<EOL><DEDENT><DEDENT>return '<STR_LIT:|>'.join(state_name)<EOL>

Returns a textual representation of this Task's state.


def get_spec_data(self, name=None, default=None):

return self.task_spec.get_data(name, default)<EOL>

Returns the value of the spec data with the given name, or the given
default value if the spec data does not exist.

:type  name: str
:param name: The name of the spec data field.
:type  default: obj
:param default: Return this value if the spec data does not exist.
:rtype:  obj
:returns: The value of the spec data.


Defines the given attribute/value pairs.


self.data.update(kwargs)<EOL>


LOG.debug("<STR_LIT>" % (self.get_name(),<EOL>self.parent.get_name()),<EOL>extra=dict(data=self.parent.data))<EOL>self.set_data(**self.parent.data)<EOL>


return self.data.get(name, default)<EOL>

Returns the value of the data field with the given name, or the given
default value if the data field does not exist.

:type  name: str
:param name: A data field name.
:type  default: obj
:param default: Return this value if the data field does not exist.
:rtype:  obj
:returns: The value of the data field


if self._is_finished():<EOL><INDENT>for child in self.children:<EOL><INDENT>child.cancel()<EOL><DEDENT>return<EOL><DEDENT>self._set_state(self.CANCELLED)<EOL>self._drop_children()<EOL>self.task_spec._on_cancel(self)<EOL>

Cancels the item if it was not yet completed, and removes
any children that are LIKELY.


self._set_state(self.COMPLETED)<EOL>return self.task_spec._on_complete(self)<EOL>

Called by the associated task to let us know that its state
has changed (e.g. from FUTURE to COMPLETED.)


self.task_spec._on_trigger(self, *args)<EOL>

If recursive is True, the state is applied to the tree recursively.


def get_dump(self, indent=<NUM_LIT:0>, recursive=True):

dbg = ('<STR_LIT:U+0020>' * indent * <NUM_LIT:2>)<EOL>dbg += '<STR_LIT>' % self.id<EOL>dbg += '<STR_LIT>' % self.thread_id<EOL>dbg += '<STR_LIT>' % self.get_name()<EOL>if self.task_spec.description:<EOL><INDENT>dbg += '<STR_LIT>' % self.get_description()<EOL><DEDENT>dbg += '<STR_LIT>' % self.get_state_name()<EOL>dbg += '<STR_LIT>' % len(self.children)<EOL>if recursive:<EOL><INDENT>for child in self.children:<EOL><INDENT>dbg += '<STR_LIT:\n>' + child.get_dump(indent + <NUM_LIT:1>)<EOL><DEDENT><DEDENT>return dbg<EOL>

Returns the subtree as a string for debugging.

:rtype:  str
:returns: The debug information.


Prints the subtree as a string for debugging.


return serializer.serialize_attrib(self)<EOL>

Serializes the instance using the provided serializer.

:type  serializer: :class:`SpiffWorkflow.serializer.base.Serializer`
:param serializer: The serializer to use.
:rtype:  object
:returns: The serialized object.


@classmethod<EOL><INDENT>def deserialize(cls, serializer, s_state):<DEDENT>

return serializer.deserialize_attrib(s_state)<EOL>


return serializer.serialize_pathattrib(self)<EOL>


return serializer.deserialize_pathattrib(s_state)<EOL>


if not right_attribute and not right:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>assert left_attribute is not None<EOL>self.left_attribute = left_attribute<EOL>self.right_attribute = right_attribute<EOL>self.right = right<EOL>

Constructor.

:type  left_attribute: str
:param left_attribute: The name of the attribute to which the value
                       is assigned.
:type  right: object
:param right: A static value that, when given, is assigned to
              left_attribute.
:type  right_attribute: str
:param right_attribute: When given, the attribute with the given
                        name is used as the source (instead of the
                        static value).
:type  kwargs: dict
:param kwargs: See :class:`SpiffWorkflow.specs.TaskSpec`.


return serializer.serialize_assign(self)<EOL>


return serializer.deserialize_assign(s_state)<EOL>


if len(args) == <NUM_LIT:0>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.args = args<EOL>


return serializer.serialize_operator(self)<EOL>


return serializer.deserialize_operator(s_state)<EOL>


Operator.__init__(self, left, right)<EOL>


Operator.__init__(self, *args)<EOL>self.regex = re.compile(regex)<EOL>


stack = [(dst, src)]<EOL>while stack:<EOL><INDENT>current_dst, current_src = stack.pop()<EOL>for key in current_src:<EOL><INDENT>source = current_src[key]<EOL>if key not in current_dst:<EOL><INDENT>current_dst[key] = source<EOL><DEDENT>else:<EOL><INDENT>dest = current_dst[key]<EOL>if isinstance(source, dict) and isinstance(dest, dict):<EOL><INDENT>stack.append((dest, source))<EOL><DEDENT>elif isinstance(source, list) and isinstance(dest, list):<EOL><INDENT>r = dest[:]<EOL>s = source[:]<EOL>if len(dest) > len(source):<EOL><INDENT>s.append([None for i in range(len(dest) -<EOL>len(source))])<EOL><DEDENT>elif len(dest) < len(source):<EOL><INDENT>r.append([None for i in range(len(source) -<EOL>len(dest))])<EOL><DEDENT>for index, value in enumerate(r):<EOL><INDENT>if (not value) and s[index]:<EOL><INDENT>r[index] = s[index]<EOL><DEDENT>elif isinstance(value, dict) andisinstance(s[index], dict):<EOL><INDENT>stack.append((dest[index], source[index]))<EOL><DEDENT>else:<EOL><INDENT>dest[index] = s[index]<EOL><DEDENT><DEDENT>current_dst[key] = r<EOL><DEDENT>else:<EOL><INDENT>current_dst[key] = source<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return dst<EOL>

Recursive merge two dicts (vs .update which overwrites the hashes at the
    root level)

    Note: This updates dst.
    Copied from checkmate.utils


try:<EOL><INDENT>function.__func__<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _WeakMethodFree(function, callback)<EOL><DEDENT>return _WeakMethodBound(function, callback)<EOL>

Returns a weak reference to the given method or function.
If the callback argument is not None, it is called as soon
as the referenced function is garbage deleted.

:type  function: callable
:param function: The function to reference.
:type  callback: callable
:param callback: Called when the function dies.


self.name = name<EOL>self.callback = callback<EOL>

Constructor. Do not use directly, use :class:`ref()` instead.


raise NotImplementedError()<EOL>

Returns the referenced method/function if it is still alive.
Returns None otherwise.

:rtype:  callable|None
:returns: The referenced function if it is still alive.


return self.get_function() is not None<EOL>

Returns True if the referenced function is still alive, False
otherwise.

:rtype:  bool
:returns: Whether the referenced function is still alive.


method = self.get_function()<EOL>if method is None:<EOL><INDENT>raise DeadMethodCalled('<STR_LIT>' + self.name)<EOL><DEDENT>method(*args, **kwargs)<EOL>

Proxied to the underlying function or method. Raises
:class:`DeadMethodCalled` if the referenced function is dead.

:rtype:  object :returns: Whatever the referenced function returned.


<EOL>self.lock = None<EOL>self.weak_subscribers = None<EOL>self.hard_subscribers = None<EOL>


return self.emit(*args, **kwargs)<EOL>


def connect(self, callback, *args, **kwargs):

if self.is_connected(callback):<EOL><INDENT>raise AttributeError('<STR_LIT>')<EOL><DEDENT>if self.hard_subscribers is None:<EOL><INDENT>self.hard_subscribers = []<EOL><DEDENT>self.hard_subscribers.append((callback, args, kwargs))<EOL>

Connects the event with the given callback.
When the signal is emitted, the callback is invoked.

.. note::

    The signal handler is stored with a hard reference, so you
    need to make sure to call :class:`disconnect()` if you want the
    handler
    to be garbage collected.

:type  callback: object
:param callback: The callback function.
:type  args: tuple
:param args: Optional arguments passed to the callback.
:type  kwargs: dict
:param kwargs: Optional keyword arguments passed to the callback.


def listen(self, callback, *args, **kwargs):

if self.lock is None:<EOL><INDENT>self.lock = Lock()<EOL><DEDENT>with self.lock:<EOL><INDENT>if self.is_connected(callback):<EOL><INDENT>raise AttributeError('<STR_LIT>')<EOL><DEDENT>if self.weak_subscribers is None:<EOL><INDENT>self.weak_subscribers = []<EOL><DEDENT>ref = weakmethod.ref(callback, self._try_disconnect)<EOL>self.weak_subscribers.append((ref, args, kwargs))<EOL><DEDENT>return ref<EOL>

Like :class:`connect()`, but uses a weak reference instead of a
normal reference.
The signal is automatically disconnected as soon as the handler
is garbage collected.

.. note::

    Storing signal handlers as weak references means that if
    your handler is a local function, it may be garbage collected. To
    prevent this, use :class:`connect()` instead.

:type  callback: object
:param callback: The callback function.
:type  args: tuple
:param args: Optional arguments passed to the callback.
:type  kwargs: dict
:param kwargs: Optional keyword arguments passed to the callback.
:rtype:  :class:`Exscript.util.weakmethod.WeakMethod`
:returns: The newly created weak reference to the callback.


hard = self.hard_subscribers and len(self.hard_subscribers) or <NUM_LIT:0><EOL>weak = self.weak_subscribers and len(self.weak_subscribers) or <NUM_LIT:0><EOL>return hard + weak<EOL>

Returns the number of connected subscribers.

:rtype:  int
:returns: The number of subscribers.


index = self._weakly_connected_index(callback)<EOL>if index is not None:<EOL><INDENT>return True<EOL><DEDENT>if self.hard_subscribers is None:<EOL><INDENT>return False<EOL><DEDENT>return callback in self._hard_callbacks()<EOL>

Returns True if the event is connected to the given function.

:type  callback: object
:param callback: The callback function.
:rtype:  bool
:returns: Whether the signal is connected to the given function.


if self.hard_subscribers is not None:<EOL><INDENT>for callback, user_args, user_kwargs in self.hard_subscribers:<EOL><INDENT>kwargs.update(user_kwargs)<EOL>result = callback(*args + user_args, **kwargs)<EOL>if result is not None:<EOL><INDENT>return result<EOL><DEDENT><DEDENT><DEDENT>if self.weak_subscribers is not None:<EOL><INDENT>for callback, user_args, user_kwargs in self.weak_subscribers:<EOL><INDENT>kwargs.update(user_kwargs)<EOL>function = callback.get_function()<EOL>if function is None:<EOL><INDENT>continue<EOL><DEDENT>result = function(*args + user_args, **kwargs)<EOL>if result is not None:<EOL><INDENT>return result<EOL><DEDENT><DEDENT><DEDENT>

Emits the signal, passing the given arguments to the callbacks.
If one of the callbacks returns a value other than None, no further
callbacks are invoked and the return value of the callback is
returned to the caller of emit().

:type  args: tuple
:param args: Optional arguments passed to the callbacks.
:type  kwargs: dict
:param kwargs: Optional keyword arguments passed to the callbacks.
:rtype:  object
:returns: Returns None if all callbacks returned None. Returns
         the return value of the last invoked callback otherwise.


with self.lock:<EOL><INDENT>weak = [s[<NUM_LIT:0>] for s in self.weak_subscribers]<EOL>try:<EOL><INDENT>index = weak.index(ref)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.weak_subscribers.pop(index)<EOL><DEDENT><DEDENT>

Called by the weak reference when its target dies.
In other words, we can assert that self.weak_subscribers is not
None at this time.


if self.weak_subscribers is not None:<EOL><INDENT>with self.lock:<EOL><INDENT>index = self._weakly_connected_index(callback)<EOL>if index is not None:<EOL><INDENT>self.weak_subscribers.pop(index)[<NUM_LIT:0>]<EOL><DEDENT><DEDENT><DEDENT>if self.hard_subscribers is not None:<EOL><INDENT>try:<EOL><INDENT>index = self._hard_callbacks().index(callback)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.hard_subscribers.pop(index)<EOL><DEDENT><DEDENT>

Disconnects the signal from the given function.

:type  callback: object
:param callback: The callback function.


self.hard_subscribers = None<EOL>self.weak_subscribers = None<EOL>

Disconnects all connected functions from all signals.


elem = etree.Element('<STR_LIT>')<EOL>elem.text = op.name<EOL>return elem<EOL>

Serializer for :meth:`SpiffWorkflow.operators.Attrib`.

Example::

    <attribute>foobar</attribute>


elem = etree.Element('<STR_LIT:path>')<EOL>elem.text = op.path<EOL>return elem<EOL>

Serializer for :meth:`SpiffWorkflow.operators.PathAttrib`.

Example::

    <path>foobar</path>


elem = etree.Element('<STR_LIT>')<EOL>self.serialize_value(SubElement(elem, '<STR_LIT:name>'), op.left_attribute)<EOL>if op.right:<EOL><INDENT>self.serialize_value(SubElement(elem, '<STR_LIT:value>'), op.right)<EOL><DEDENT>if op.right_attribute:<EOL><INDENT>self.serialize_value(<EOL>SubElement(elem, '<STR_LIT>'), op.right_attribute)<EOL><DEDENT>return elem<EOL>

Serializer for :meth:`SpiffWorkflow.operators.Assign`.

Example::

    <assign>
        <name>foobar</name>
        <value>doodle</value>
    </assign>


def serialize_value(self, parent_elem, value):

if isinstance(value, (str, int)) or type(value).__name__ == '<STR_LIT:str>':<EOL><INDENT>parent_elem.text = str(value)<EOL><DEDENT>elif value is None:<EOL><INDENT>parent_elem.text = None<EOL><DEDENT>else:<EOL><INDENT>parent_elem.append(value.serialize(self))<EOL><DEDENT>

Serializes str, Attrib, or PathAttrib objects.

Example::

    <attribute>foobar</attribute>


def serialize_value_map(self, map_elem, thedict):

for key, value in sorted((str(k), v) for (k, v) in thedict.items()):<EOL><INDENT>var_elem = SubElement(map_elem, '<STR_LIT>')<EOL>SubElement(var_elem, '<STR_LIT:name>').text = str(key)<EOL>value_elem = SubElement(var_elem, '<STR_LIT:value>')<EOL>self.serialize_value(value_elem, value)<EOL><DEDENT>return map_elem<EOL>

Serializes a dictionary of key/value pairs, where the values are
either strings, or Attrib, or PathAttrib objects.

Example::

    <variable>
        <name>foo</name>
        <value>text</value>
    </variable>
    <variable>
        <name>foo2</name>
        <value><attribute>foobar</attribute></value>
    </variable>


def serialize_value_list(self, list_elem, thelist):

for value in thelist:<EOL><INDENT>value_elem = SubElement(list_elem, '<STR_LIT:value>')<EOL>self.serialize_value(value_elem, value)<EOL><DEDENT>return list_elem<EOL>

Serializes a list, where the values are objects of type
str, Attrib, or PathAttrib.

Example::

    <value>text</value>
    <value><attribute>foobar</attribute></value>
    <value><path>foobar</path></value>


elem = etree.Element('<STR_LIT>')<EOL>return self.serialize_value_list(elem, op.args)<EOL>

Serializer for :meth:`SpiffWorkflow.operators.Equal`.

Example::

    <equals>
        <value>text</value>
        <value><attribute>foobar</attribute></value>
        <value><path>foobar</path></value>
    </equals>


Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.

Example::

    <not-equals>
        <value>text</value>
        <value><attribute>foobar</attribute></value>
        <value><path>foobar</path></value>
    </not-equals>