<commit_before>import textwrap

import capa.main
import capa.rules
import capa.engine
import capa.features
import capa.features.extractors.viv
from fixtures import *
from capa.engine import *

def test_main(sample_9324d1a8ae37a36ae560c37448c9705a):
    # tests rules can be loaded successfully and all output modes
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path, "-vv"]) == 0
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path, "-v"]) == 0
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path, "-j"]) == 0
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path]) == 0

def test_main_single_rule(sample_9324d1a8ae37a36ae560c37448c9705a, tmpdir):
    # tests a single rule can be loaded successfully
    RULE_CONTENT = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
                scope: file
            features:
              - string: test
        """
    )
    rule_file = tmpdir.mkdir("capa").join("rule.yml")
    rule_file.write(RULE_CONTENT)
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path, "-v", "-r", rule_file.strpath,]) == 0

def test_main_shellcode(sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32):
    assert capa.main.main([sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32.path, "-vv", "-f", "sc32"]) == 0
    assert capa.main.main([sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32.path, "-v", "-f", "sc32"]) == 0
    assert capa.main.main([sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32.path, "-j", "-f", "sc32"]) == 0
    assert capa.main.main([sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32.path, "-f", "sc32"]) == 0

def test_ruleset():
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: file rule
                            scope: file
                        features:
                          - characteristic: embedded pe
                    """
                )
            ),
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: function rule
                            scope: function
                        features:
                          - characteristic: switch
                    """
                )
            ),
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: basic block rule
                            scope: basic block
                        features:
                          - characteristic: nzxor
                    """
                )
            ),
        ]
    )
    assert len(rules.file_rules) == 1
    assert len(rules.function_rules) == 1
    assert len(rules.basic_block_rules) == 1

def test_match_across_scopes_file_function(sample_9324d1a8ae37a36ae560c37448c9705a):
    rules = capa.rules.RuleSet(
        [
            # this rule should match on a function (0x4073F0)
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: install service
                            scope: function
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a:0x4073F0
                        features:
                            - and:
                                - api: advapi32.OpenSCManagerA
                                - api: advapi32.CreateServiceA
                                - api: advapi32.StartServiceA
                    """
                )
            ),
            # this rule should match on a file feature
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: .text section
                            scope: file
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a
                        features:
                            - section: .text
                    """
                )
            ),
            # this rule should match on earlier rule matches:
            #  - install service, with function scope
            #  - .text section, with file scope
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: .text section and install service
                            scope: file
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a
                        features:
                            - and:
                              - match: install service
                              - match: .text section
                    """
                )
            ),
        ]
    )
    extractor = capa.features.extractors.viv.VivisectFeatureExtractor(
        sample_9324d1a8ae37a36ae560c37448c9705a.vw, sample_9324d1a8ae37a36ae560c37448c9705a.path,
    )
    capabilities = capa.main.find_capabilities(rules, extractor)
    assert "install service" in capabilities
    assert ".text section" in capabilities
    assert ".text section and install service" in capabilities

def test_match_across_scopes(sample_9324d1a8ae37a36ae560c37448c9705a):
    rules = capa.rules.RuleSet(
        [
            # this rule should match on a basic block (including at least 0x403685)
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: tight loop
                            scope: basic block
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a:0x403685
                        features:
                          - characteristic: tight loop
                    """
                )
            ),
            # this rule should match on a function (0x403660)
            # based on API, as well as prior basic block rule match
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: kill thread loop
                            scope: function
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a:0x403660
                        features:
                          - and:
                            - api: kernel32.TerminateThread
                            - api: kernel32.CloseHandle
                            - match: tight loop
                    """
                )
            ),
            # this rule should match on a file feature and a prior function rule match
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: kill thread program
                            scope: file
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a
                        features:
                          - and:
                            - section: .text
                            - match: kill thread loop
                    """
                )
            ),
        ]
    )
    extractor = capa.features.extractors.viv.VivisectFeatureExtractor(
        sample_9324d1a8ae37a36ae560c37448c9705a.vw, sample_9324d1a8ae37a36ae560c37448c9705a.path
    )
    capabilities = capa.main.find_capabilities(rules, extractor)
    assert "tight loop" in capabilities
    assert "kill thread loop" in capabilities
    assert "kill thread program" in capabilities

def test_subscope_bb_rules(sample_9324d1a8ae37a36ae560c37448c9705a):
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: test rule
                            scope: function
                        features:
                            - and:
                                - basic block:
                                    - characteristic: tight loop
                    """
                )
            )
        ]
    )
    # tight loop at 0x403685
    extractor = capa.features.extractors.viv.VivisectFeatureExtractor(
        sample_9324d1a8ae37a36ae560c37448c9705a.vw, sample_9324d1a8ae37a36ae560c37448c9705a.path,
    )
    capabilities = capa.main.find_capabilities(rules, extractor)
    assert "test rule" in capabilities

def test_byte_matching(sample_9324d1a8ae37a36ae560c37448c9705a):
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: byte match test
                            scope: function
                        features:
                            - and:
                                - bytes: ED 24 9E F4 52 A9 07 47 55 8E E1 AB 30 8E 23 61
                    """
                )
            )
        ]
    )

    extractor = capa.features.extractors.viv.VivisectFeatureExtractor(
        sample_9324d1a8ae37a36ae560c37448c9705a.vw, sample_9324d1a8ae37a36ae560c37448c9705a.path,
    )
    capabilities = capa.main.find_capabilities(rules, extractor)
    assert "byte match test" in capabilities
<commit_msg>add test for #78<commit_after>import textwrap

import capa.main
import capa.rules
import capa.engine
import capa.features
import capa.features.extractors.viv
from fixtures import *
from capa.engine import *

def test_main(sample_9324d1a8ae37a36ae560c37448c9705a):
    # tests rules can be loaded successfully and all output modes
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path, "-vv"]) == 0
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path, "-v"]) == 0
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path, "-j"]) == 0
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path]) == 0

def test_main_single_rule(sample_9324d1a8ae37a36ae560c37448c9705a, tmpdir):
    # tests a single rule can be loaded successfully
    RULE_CONTENT = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
                scope: file
            features:
              - string: test
        """
    )
    rule_file = tmpdir.mkdir("capa").join("rule.yml")
    rule_file.write(RULE_CONTENT)
    assert capa.main.main([sample_9324d1a8ae37a36ae560c37448c9705a.path, "-v", "-r", rule_file.strpath,]) == 0

def test_main_shellcode(sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32):
    assert capa.main.main([sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32.path, "-vv", "-f", "sc32"]) == 0
    assert capa.main.main([sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32.path, "-v", "-f", "sc32"]) == 0
    assert capa.main.main([sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32.path, "-j", "-f", "sc32"]) == 0
    assert capa.main.main([sample_499c2a85f6e8142c3f48d4251c9c7cd6_raw32.path, "-f", "sc32"]) == 0

def test_ruleset():
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: file rule
                            scope: file
                        features:
                          - characteristic: embedded pe
                    """
                )
            ),
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: function rule
                            scope: function
                        features:
                          - characteristic: switch
                    """
                )
            ),
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: basic block rule
                            scope: basic block
                        features:
                          - characteristic: nzxor
                    """
                )
            ),
        ]
    )
    assert len(rules.file_rules) == 1
    assert len(rules.function_rules) == 1
    assert len(rules.basic_block_rules) == 1

def test_match_across_scopes_file_function(sample_9324d1a8ae37a36ae560c37448c9705a):
    rules = capa.rules.RuleSet(
        [
            # this rule should match on a function (0x4073F0)
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: install service
                            scope: function
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a:0x4073F0
                        features:
                            - and:
                                - api: advapi32.OpenSCManagerA
                                - api: advapi32.CreateServiceA
                                - api: advapi32.StartServiceA
                    """
                )
            ),
            # this rule should match on a file feature
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: .text section
                            scope: file
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a
                        features:
                            - section: .text
                    """
                )
            ),
            # this rule should match on earlier rule matches:
            #  - install service, with function scope
            #  - .text section, with file scope
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: .text section and install service
                            scope: file
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a
                        features:
                            - and:
                              - match: install service
                              - match: .text section
                    """
                )
            ),
        ]
    )
    extractor = capa.features.extractors.viv.VivisectFeatureExtractor(
        sample_9324d1a8ae37a36ae560c37448c9705a.vw, sample_9324d1a8ae37a36ae560c37448c9705a.path,
    )
    capabilities = capa.main.find_capabilities(rules, extractor)
    assert "install service" in capabilities
    assert ".text section" in capabilities
    assert ".text section and install service" in capabilities

def test_match_across_scopes(sample_9324d1a8ae37a36ae560c37448c9705a):
    rules = capa.rules.RuleSet(
        [
            # this rule should match on a basic block (including at least 0x403685)
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: tight loop
                            scope: basic block
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a:0x403685
                        features:
                          - characteristic: tight loop
                    """
                )
            ),
            # this rule should match on a function (0x403660)
            # based on API, as well as prior basic block rule match
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: kill thread loop
                            scope: function
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a:0x403660
                        features:
                          - and:
                            - api: kernel32.TerminateThread
                            - api: kernel32.CloseHandle
                            - match: tight loop
                    """
                )
            ),
            # this rule should match on a file feature and a prior function rule match
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: kill thread program
                            scope: file
                            examples:
                              - 9324d1a8ae37a36ae560c37448c9705a
                        features:
                          - and:
                            - section: .text
                            - match: kill thread loop
                    """
                )
            ),
        ]
    )
    extractor = capa.features.extractors.viv.VivisectFeatureExtractor(
        sample_9324d1a8ae37a36ae560c37448c9705a.vw, sample_9324d1a8ae37a36ae560c37448c9705a.path
    )
    capabilities = capa.main.find_capabilities(rules, extractor)
    assert "tight loop" in capabilities
    assert "kill thread loop" in capabilities
    assert "kill thread program" in capabilities

def test_subscope_bb_rules(sample_9324d1a8ae37a36ae560c37448c9705a):
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: test rule
                            scope: function
                        features:
                            - and:
                                - basic block:
                                    - characteristic: tight loop
                    """
                )
            )
        ]
    )
    # tight loop at 0x403685
    extractor = capa.features.extractors.viv.VivisectFeatureExtractor(
        sample_9324d1a8ae37a36ae560c37448c9705a.vw, sample_9324d1a8ae37a36ae560c37448c9705a.path,
    )
    capabilities = capa.main.find_capabilities(rules, extractor)
    assert "test rule" in capabilities

def test_byte_matching(sample_9324d1a8ae37a36ae560c37448c9705a):
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: byte match test
                            scope: function
                        features:
                            - and:
                                - bytes: ED 24 9E F4 52 A9 07 47 55 8E E1 AB 30 8E 23 61
                    """
                )
            )
        ]
    )

    extractor = capa.features.extractors.viv.VivisectFeatureExtractor(
        sample_9324d1a8ae37a36ae560c37448c9705a.vw, sample_9324d1a8ae37a36ae560c37448c9705a.path,
    )
    capabilities = capa.main.find_capabilities(rules, extractor)
    assert "byte match test" in capabilities

def test_count_bb(sample_9324d1a8ae37a36ae560c37448c9705a):
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                      meta:
                        name: count bb
                        namespace: test
                        scope: function
                      features:
                        - and:
                          - count(basic blocks): 1 or more
                    """
                )
            )
        ]
    )

    extractor = capa.features.extractors.viv.VivisectFeatureExtractor(
        sample_9324d1a8ae37a36ae560c37448c9705a.vw, sample_9324d1a8ae37a36ae560c37448c9705a.path,
    )
    capabilities = capa.main.find_capabilities(rules, extractor)
    assert "count bb" in capabilities

<|endoftext|>


<commit_before>#!/usr/bin/env python3
# Copyright (c) 2014-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test descendant package tracking carve-out allowing one final transaction in
   an otherwise-full package as long as it has only one parent and is <= 10k in
   size.
"""

from decimal import Decimal

from test_framework.blocktools import COINBASE_MATURITY
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
    assert_equal,
    assert_raises_rpc_error,
    chain_transaction,
)

MAX_ANCESTORS = 25
MAX_DESCENDANTS = 25

class MempoolPackagesTest(BitcoinTestFramework):
    def set_test_params(self):
        self.num_nodes = 1
        self.extra_args = [["-maxorphantx=1000"]]

    def skip_test_if_missing_module(self):
        self.skip_if_no_wallet()

    def run_test(self):
        # Mine some blocks and have them mature.
        self.generate(self.nodes[0], COINBASE_MATURITY + 1)
        utxo = self.nodes[0].listunspent(10)
        txid = utxo[0]['txid']
        vout = utxo[0]['vout']
        value = utxo[0]['amount']

        fee = Decimal("0.0002")
        # MAX_ANCESTORS transactions off a confirmed tx should be fine
        chain = []
        for _ in range(4):
            (txid, sent_value) = chain_transaction(self.nodes[0], [txid], [vout], value, fee, 2)
            vout = 0
            value = sent_value
            chain.append([txid, value])
        for _ in range(MAX_ANCESTORS - 4):
            (txid, sent_value) = chain_transaction(self.nodes[0], [txid], [0], value, fee, 1)
            value = sent_value
            chain.append([txid, value])
        (second_chain, second_chain_value) = chain_transaction(self.nodes[0], [utxo[1]['txid']], [utxo[1]['vout']], utxo[1]['amount'], fee, 1)

        # Check mempool has MAX_ANCESTORS + 1 transactions in it
        assert_equal(len(self.nodes[0].getrawmempool()), MAX_ANCESTORS + 1)

        # Adding one more transaction on to the chain should fail.
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many unconfirmed ancestors [limit: 25]", chain_transaction, self.nodes[0], [txid], [0], value, fee, 1)
        # ...even if it chains on from some point in the middle of the chain.
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many descendants", chain_transaction, self.nodes[0], [chain[2][0]], [1], chain[2][1], fee, 1)
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many descendants", chain_transaction, self.nodes[0], [chain[1][0]], [1], chain[1][1], fee, 1)
        # ...even if it chains on to two parent transactions with one in the chain.
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many descendants", chain_transaction, self.nodes[0], [chain[0][0], second_chain], [1, 0], chain[0][1] + second_chain_value, fee, 1)
        # ...especially if its > 40k weight
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many descendants", chain_transaction, self.nodes[0], [chain[0][0]], [1], chain[0][1], fee, 350)
        # But not if it chains directly off the first transaction
        (replacable_txid, replacable_orig_value) = chain_transaction(self.nodes[0], [chain[0][0]], [1], chain[0][1], fee, 1)
        # and the second chain should work just fine
        chain_transaction(self.nodes[0], [second_chain], [0], second_chain_value, fee, 1)

        # Make sure we can RBF the chain which used our carve-out rule
        second_tx_outputs = {self.nodes[0].getrawtransaction(replacable_txid, True)["vout"][0]['scriptPubKey']['address']: replacable_orig_value - (Decimal(1) / Decimal(100))}
        second_tx = self.nodes[0].createrawtransaction([{'txid': chain[0][0], 'vout': 1}], second_tx_outputs)
        signed_second_tx = self.nodes[0].signrawtransactionwithwallet(second_tx)
        self.nodes[0].sendrawtransaction(signed_second_tx['hex'])

        # Finally, check that we added two transactions
        assert_equal(len(self.nodes[0].getrawmempool()), MAX_ANCESTORS + 3)

if __name__ == '__main__':
    MempoolPackagesTest().main()
<commit_msg>test: use MiniWallet for mempool_package_onemore.py<commit_after>#!/usr/bin/env python3
# Copyright (c) 2014-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test descendant package tracking carve-out allowing one final transaction in
   an otherwise-full package as long as it has only one parent and is <= 10k in
   size.
"""

from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
    assert_equal,
    assert_raises_rpc_error,
)
from test_framework.wallet import MiniWallet

MAX_ANCESTORS = 25
MAX_DESCENDANTS = 25

class MempoolPackagesTest(BitcoinTestFramework):
    def set_test_params(self):
        self.num_nodes = 1
        self.extra_args = [["-maxorphantx=1000"]]

    def chain_tx(self, utxos_to_spend, *, num_outputs=1):
        return self.wallet.send_self_transfer_multi(
            from_node=self.nodes[0],
            utxos_to_spend=utxos_to_spend,
            num_outputs=num_outputs)['new_utxos']

    def run_test(self):
        self.wallet = MiniWallet(self.nodes[0])
        self.wallet.rescan_utxos()

        # MAX_ANCESTORS transactions off a confirmed tx should be fine
        chain = []
        utxo = self.wallet.get_utxo()
        for _ in range(4):
            utxo, utxo2 = self.chain_tx([utxo], num_outputs=2)
            chain.append(utxo2)
        for _ in range(MAX_ANCESTORS - 4):
            utxo, = self.chain_tx([utxo])
            chain.append(utxo)
        second_chain, = self.chain_tx([self.wallet.get_utxo()])

        # Check mempool has MAX_ANCESTORS + 1 transactions in it
        assert_equal(len(self.nodes[0].getrawmempool()), MAX_ANCESTORS + 1)

        # Adding one more transaction on to the chain should fail.
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many unconfirmed ancestors [limit: 25]", self.chain_tx, [utxo])
        # ...even if it chains on from some point in the middle of the chain.
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many descendants", self.chain_tx, [chain[2]])
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many descendants", self.chain_tx, [chain[1]])
        # ...even if it chains on to two parent transactions with one in the chain.
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many descendants", self.chain_tx, [chain[0], second_chain])
        # ...especially if its > 40k weight
        assert_raises_rpc_error(-26, "too-long-mempool-chain, too many descendants", self.chain_tx, [chain[0]], num_outputs=350)
        # But not if it chains directly off the first transaction
        replacable_tx = self.wallet.send_self_transfer_multi(from_node=self.nodes[0], utxos_to_spend=[chain[0]])['tx']
        # and the second chain should work just fine
        self.chain_tx([second_chain])

        # Make sure we can RBF the chain which used our carve-out rule
        replacable_tx.vout[0].nValue -= 1000000
        self.nodes[0].sendrawtransaction(replacable_tx.serialize().hex())

        # Finally, check that we added two transactions
        assert_equal(len(self.nodes[0].getrawmempool()), MAX_ANCESTORS + 3)

if __name__ == '__main__':
    MempoolPackagesTest().main()
<|endoftext|>


<commit_before>import os
import unittest

from dataset_creator.dataset import Dataset

from data import test_data

MEGA_DATA_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'Mega')

class TestMega(unittest.TestCase):
    def setUp(self):
        self.maxDiff = None

    def test_dataset(self):
        dataset = Dataset(test_data, format='MEGA', partitioning='by gene')
        result = dataset.dataset_str
        expected = open(os.path.join(MEGA_DATA_PATH, 'dataset.meg')).read()
        self.assertEqual(expected, result)

    def test_dataset_as_aminoacids(self):
        dataset = Dataset(test_data, format='MEGA', partitioning='by gene',
                          aminoacids=True)
        result = dataset.dataset_str
        expected = open(os.path.join(MEGA_DATA_PATH, 'dataset_aa.meg')).read()
        self.assertEqual(expected, result)

    def test_dataset_as_degenerate(self):
        dataset = Dataset(test_data, format='MEGA', partitioning='by gene',
                          degenerate='S')
        result = dataset.dataset_str
        expected = open(os.path.join(MEGA_DATA_PATH, 'dataset_degenerate.meg')).read()
        self.assertEqual(expected, result)

    def test_dataset_as_degenerate_bad_partitioning_scheme(self):
        self.assertRaises(ValueError, Dataset, test_data, format='MEGA',
                          partitioning='1st-2nd, 3rd', degenerate='S')
<commit_msg>fix test_data import<commit_after>import os
import unittest

from dataset_creator.dataset import Dataset

from .data import test_data

MEGA_DATA_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'Mega')

class TestMega(unittest.TestCase):
    def setUp(self):
        self.maxDiff = None

    def test_dataset(self):
        dataset = Dataset(test_data, format='MEGA', partitioning='by gene')
        result = dataset.dataset_str
        expected = open(os.path.join(MEGA_DATA_PATH, 'dataset.meg')).read()
        self.assertEqual(expected, result)

    def test_dataset_as_aminoacids(self):
        dataset = Dataset(test_data, format='MEGA', partitioning='by gene',
                          aminoacids=True)
        result = dataset.dataset_str
        expected = open(os.path.join(MEGA_DATA_PATH, 'dataset_aa.meg')).read()
        self.assertEqual(expected, result)

    def test_dataset_as_degenerate(self):
        dataset = Dataset(test_data, format='MEGA', partitioning='by gene',
                          degenerate='S')
        result = dataset.dataset_str
        expected = open(os.path.join(MEGA_DATA_PATH, 'dataset_degenerate.meg')).read()
        self.assertEqual(expected, result)

    def test_dataset_as_degenerate_bad_partitioning_scheme(self):
        self.assertRaises(ValueError, Dataset, test_data, format='MEGA',
                          partitioning='1st-2nd, 3rd', degenerate='S')
<|endoftext|>


<commit_before># game.py
#
# This script initializes all the resources and sets up the game logic,
# to finally run the game.
#
# Carlos N. Abreu Takemura
# Andres A. Gonzalez Lagares
# License(s): CC By 3.0
#
# Python.org (PEP 8) Coding Style Suggestions

"""Initializes and runs the game."""

import sys
import time
import random
import pygame
import environment
import keyboard
import physics as helper
from managers import graphics_manager as picasso
from managers import sound_manager as dj
from gamestate import GameState
import logger

pygame.init()
#---MAIN------------------------------------------------

def main(log):
    global game_state
    while True:
        handle_input(log)

        if not game_state.paused:
            game_logic(log)
            draw(log)
            end_game(log)
        else:
            environment.DISPLAY_SURFACE.blit(environment.PAUSED_TEXT,(environment.WINDOW_WIDTH/2,environment.WINDOW_HEIGHT/2))
            pygame.display.update()
        #game_state.time += 1
        environment.CLOCK.tick(environment.FPS)
        #print "Score: " + str(game_state.score)

#---FUNCTIONS-------------------------------------------
#
#---PRIMARY-FUNCTIONS-----------------------------------

def handle_input(log, END_GAME = False):
    """
    Handles all external input,such as those  keyboard and mouse.
    """
    for event in pygame.event.get():

        keys = pygame.key.get_pressed()

        # Closing
        handle_quit(event)

        if keyboard.queue_prompt(event):
            game_state.next_wave()

        # Pausing game
        if keyboard.pause_prompt(keys):
            game_state.toggle_paused()

        # Hero's movement
        hero_dir = keyboard.movement(keys)
        game_state.hero.change_direction(hero_dir)

        #END_GAME
        global game_state
        handle_quit(event, END_GAME)
        if keyboard.restart(event, END_GAME):
            if game_state.mode == "FIXED":
                new_choice = "DYNAMIC"
            else:
                new_choice = "FIXED"
            game_state = GameState(new_choice)
            log.refresh(new_choice)
            log.first_row()

        # Sound Adjustment
        if keyboard.music_prompt(keys):
            dj.switch_background_music()
        if keyboard.increase_prompt(keys):
            dj.increase_volume()
        if keyboard.decrease_prompt(keys):
            dj.decrease_volume()

        # Shoot Laser
        if keyboard.laser_prompt(keys):
            if game_state.hero.laser_equipped:
                game_state.hero.is_firing_laser = True
                game_state.hero.fire_time = time.clock()

        # Shoot Pew
        if keyboard.pew_prompt(keys):
            if game_state.hero.ok_to_shoot():
                game_state.hero_fire()
                dj.play_pew()

def game_logic(log):
    """
    Handles all game logic,
    such as collisions, damage calculation, movement,etc.
    """
    #Hero
    location = helper.locate_in_boundary(game_state.hero, environment.BOUNDARY)
    helper.movement_manager(game_state.hero, location)
    game_state.hero.update_pos()
    game_state.hero.recharge()

    if game_state.hero.vulnerable:
        for enemy in game_state.enemy_list:
            if helper.check_collision(enemy, game_state.hero):
                game_state.hitcount += 1
                game_state.hero.get_hit_by_enemy(enemy)
                game_state.hero.knockback()
                game_state.hero.give_immunity()
                game_state.update_hero_bar()
                if game_state.hero.isdead():
                    game_state.game_over = True
                    print "GAME_OVER"  # GAME OVER - TODO
    else:
        if (time.clock() - game_state.hero.vulnerability_time) > 1.5:
            game_state.hero.take_immunity()

    # Hero - Laser
    if game_state.hero.is_firing_laser:
        if time.clock() - game_state.hero.fire_time < 6:
            game_state.hero.fire_laser()
        else:
            game_state.hero.stop_firing_laser()

    # Pews
    game_state.update_pews()

    # Rupees
    game_state.update_pickups()

    # Enemies and Waves
    game_state.update_enemies()

    hp_100 = game_state.hero.stats.current_hp / game_state.hero.stats.hp
    game_state.master.update(hp_100)

    log.add_row(game_state)

def draw(log):
    """
    Draws everything and updates the changes in the screen
    """
    screen = environment.DISPLAY_SURFACE

    picasso.draw_background(screen)

    picasso.draw_hero(screen, game_state.hero)

    for pewpew in game_state.projectile_list:
        if not pewpew.is_out_of_screen():
            picasso.draw_pewpew(screen, pewpew)

    for pickup in game_state.pickup_list:
        picasso.draw_pickup(screen, pickup)

    if game_state.hero.is_firing_laser:
        picasso.draw_laser(screen, game_state.hero.laser)

    for enemy in game_state.enemy_list:
        picasso.draw_enemy(screen, enemy)
        picasso.draw_bar(screen, enemy.bar)

    picasso.draw_bar(screen, game_state.hero_bar, hero_bar=True)

    picasso.draw_score(screen, game_state.score)

    pygame.display.update()

#End Game
def end_game(log):
    if game_state.game_over:
        surf = environment.DISPLAY_SURFACE

        picasso.draw_background(surf)
        surf.blit(environment.GAME_OVER_TEXT,(environment.WINDOW_WIDTH/4,environment.WINDOW_HEIGHT/2))
        surf.blit(environment.PROMPT_TEXT,(environment.WINDOW_WIDTH/4,environment.WINDOW_HEIGHT*(3.0/4.0)))
        pygame.display.update()

        while game_state.game_over:
            handle_input(log, game_state.game_over)

    if game_state.win:
        picasso.draw_background(surf)
        surf.blit(environment.WIN_TEXT,(environment.WINDOW_WIDTH/8,environment.WINDOW_HEIGHT/2))
        surf.blit(environment.PROMPT_TEXT,(environment.WINDOW_WIDTH/4,environment.WINDOW_HEIGHT*(3.0/4.0)))
        pygame.display.update()

        while game_state.win:
            handle_input(game_state.win)

def handle_quit(event, GAME_OVER = False):
    if keyboard.escape_prompt(event, GAME_OVER):
            pygame.quit()
            sys.exit()

#---BLACK-MAGIC---

if __name__ == '__main__':
    dj.loop_background_music()
    pygame.display.set_caption("BitCuisine Experiment")
    possibilities = ["FIXED", "DYNAMIC"]
    game_state = GameState(possibilities[random.randint(0, 1)])
    log = logger.Log("", game_state)
    log.first_row()
    main(log)

<commit_msg>Initializing fork for documented/refactored version<commit_after># game.py
#
# This script initializes all the resources and sets up the game logic,
# to finally run the game.
#
# Carlos N. Abreu Takemura
# Andres A. Gonzalez Lagares
# License(s): CC By 3.0
#
# Python.org (PEP 8) Coding Style Suggestions

"""Initializes and runs the game."""

import sys
import time
import random
import pygame
import environment
import keyboard
import physics as helper
from managers import graphics_manager as picasso
from managers import sound_manager as dj
from gamestate import GameState
import logger

pygame.init()
#---MAIN------------------------------------------------

def main(log):
    global game_state
    while True:
        handle_input(log)

        if not game_state.paused:
            game_logic(log)
            draw(log)
            end_game(log)
        else:
            environment.DISPLAY_SURFACE.blit(environment.PAUSED_TEXT,(environment.WINDOW_WIDTH/2,environment.WINDOW_HEIGHT/2))
            pygame.display.update()
        #game_state.time += 1
        environment.CLOCK.tick(environment.FPS)
        #print "Score: " + str(game_state.score)

#---FUNCTIONS-------------------------------------------
#
#---PRIMARY-FUNCTIONS-----------------------------------

def handle_input(log, END_GAME = False):
    """
    Handles all external input,such as those  keyboard and mouse.
    """
    for event in pygame.event.get():

        keys = pygame.key.get_pressed()

        # Closing
        handle_quit(event)

        if keyboard.queue_prompt(event):
            game_state.next_wave()

        # Pausing game
        if keyboard.pause_prompt(keys):
            game_state.toggle_paused()

        # Hero's movement
        hero_dir = keyboard.movement(keys)
        game_state.hero.change_direction(hero_dir)

        #END_GAME
        global game_state
        handle_quit(event, END_GAME)
        if keyboard.restart(event, END_GAME):
            if game_state.mode == "FIXED":
                new_choice = "DYNAMIC"
            else:
                new_choice = "FIXED"
            game_state = GameState(new_choice)
            log.refresh(new_choice)
            log.first_row()

        # Sound Adjustment
        if keyboard.music_prompt(keys):
            dj.switch_background_music()
        if keyboard.increase_prompt(keys):
            dj.increase_volume()
        if keyboard.decrease_prompt(keys):
            dj.decrease_volume()

        # Shoot Laser
        if keyboard.laser_prompt(keys):
            if game_state.hero.laser_equipped:
                game_state.hero.is_firing_laser = True
                game_state.hero.fire_time = time.clock()

        # Shoot Pew
        if keyboard.pew_prompt(keys):
            if game_state.hero.ok_to_shoot():
                game_state.hero_fire()
                dj.play_pew()

def game_logic(log):
    """
    Handles all game logic,
    such as collisions, damage calculation, movement,etc.
    """
    #Hero
    location = helper.locate_in_boundary(game_state.hero, environment.BOUNDARY)
    helper.movement_manager(game_state.hero, location)
    game_state.hero.update_pos()
    game_state.hero.recharge()

    if game_state.hero.vulnerable:
        for enemy in game_state.enemy_list:
            if helper.check_collision(enemy, game_state.hero):
                game_state.hitcount += 1
                game_state.hero.get_hit_by_enemy(enemy)
                game_state.hero.knockback()
                game_state.hero.give_immunity()
                game_state.update_hero_bar()
                if game_state.hero.isdead():
                    game_state.game_over = True
                    print "GAME_OVER"  # GAME OVER - TODO
    else:
        if (time.clock() - game_state.hero.vulnerability_time) > 1.5:
            game_state.hero.take_immunity()

    # Hero - Laser
    if game_state.hero.is_firing_laser:
        if time.clock() - game_state.hero.fire_time < 6:
            game_state.hero.fire_laser()
        else:
            game_state.hero.stop_firing_laser()

    # Pews
    game_state.update_pews()

    # Rupees
    game_state.update_pickups()

    # Enemies and Waves
    game_state.update_enemies()

    hp_100 = game_state.hero.stats.current_hp / game_state.hero.stats.hp
    game_state.master.update(hp_100)

    log.add_row(game_state)

def draw(log):
    """
    Draws everything and updates the changes in the screen
    """
    screen = environment.DISPLAY_SURFACE

    picasso.draw_background(screen)

    picasso.draw_hero(screen, game_state.hero)

    for pewpew in game_state.projectile_list:
        if not pewpew.is_out_of_screen():
            picasso.draw_pewpew(screen, pewpew)

    for pickup in game_state.pickup_list:
        picasso.draw_pickup(screen, pickup)

    if game_state.hero.is_firing_laser:
        picasso.draw_laser(screen, game_state.hero.laser)

    for enemy in game_state.enemy_list:
        picasso.draw_enemy(screen, enemy)
        picasso.draw_bar(screen, enemy.bar)

    picasso.draw_bar(screen, game_state.hero_bar, hero_bar=True)

    picasso.draw_score(screen, game_state.score)

    pygame.display.update()

#End Game
def end_game(log):
    if game_state.game_over:
        surf = environment.DISPLAY_SURFACE

        picasso.draw_background(surf)
        surf.blit(environment.GAME_OVER_TEXT,(environment.WINDOW_WIDTH/4,environment.WINDOW_HEIGHT/2))
        surf.blit(environment.PROMPT_TEXT,(environment.WINDOW_WIDTH/4,environment.WINDOW_HEIGHT*(3.0/4.0)))
        pygame.display.update()

        while game_state.game_over:
            handle_input(log, game_state.game_over)

    if game_state.win:
        picasso.draw_background(surf)
        surf.blit(environment.WIN_TEXT,(environment.WINDOW_WIDTH/8,environment.WINDOW_HEIGHT/2))
        surf.blit(environment.PROMPT_TEXT,(environment.WINDOW_WIDTH/4,environment.WINDOW_HEIGHT*(3.0/4.0)))
        pygame.display.update()

        while game_state.win:
            handle_input(game_state.win)

def handle_quit(event, GAME_OVER = False):
    if keyboard.escape_prompt(event, GAME_OVER):
            pygame.quit()
            sys.exit()

#---BLACK-MAGIC---

if __name__ == '__main__':
    dj.loop_background_music()
    pygame.display.set_caption("BitCuisine Experiment")
    possibilities = ["DYNAMIC", "FIXED"]
    game_state = GameState(possibilities[random.randint(0, 1)])
    log = logger.Log("danny", game_state)
    log.first_row()
    main(log)

#doc

<|endoftext|>


<commit_before>import pandas as pd
from collections import defaultdict

def generate_snp_acc_mapping(table_file):
    """
    Generates a mapping from SNP IDs from a platform to NCBI RS IDs. Based on one Affymetrix GEO dataset, may need
    further tweaking.

    :param table_file: Filename of table-sperated SNP info file
    :return: dictionary mapping platform IDs to RS IDs
    """
    with open(table_file) as snps:
        header = False
        snp_map = {}
        for snp in (l for l in snps if not l.startswith('#')):
            if not header:
                header = snp
            snp = snp.split('\t')
            snp_map[snp[0]] = snp[2] if snp[2].startswith('rs') else snp[1]
    return snp_map

def find_clinvar_groups(clinvar_summary, assembly='GRCh37'):
    """
    Seperated ClinVar variants into groups based on their associated phenotype given a genome assembly id.

    :param clinvar_summary: Filename of variant_summary.txt from ClinVar FTP.
    :param assembly: ID of assembly from which to use SNPs. Current GRCh37 or GRCh38
    :return: Dictionary containing keys of each MedGen phenotype ID mapping to lists of SNP RS IDs
    """
    variants = pd.read_table(clinvar_summary)
    groups = defaultdict(list)
    for i, var in variants[variants.Assembly==assembly].iterrows():
        pheno_ids = {xr.split(':')[0]: xr.split(':')[1] for xr in var.PhenotypeIDs.split(',') if ':' in xr}
        if 'MedGen' in pheno_ids:
            groups[pheno_ids['MedGen']].append(var['RS# (dbSNP)'])
        else:
            groups[None].append(var['RS# (dbSNP)'])
    return groups

def subset_wrap(table, groups, dependents):
    """table is a pandas DataFrame
       groups is a dictionary keys are group labels (phenotype for ex.), values are lists of column labels
       dependents is a list the length of the number of samples
       returns a dictionary keys(group labels): values(sub dataframes)
    """
    df = table
    levels = list(set(dependents.tolist()))
    df['dependent'] = [levels.index(d) for d in dependents] #This is the dependent variable

    # call generic_subset on each group
    sub_dfs = {}
    for group, col_id_list in groups.items():
        sub_dfs[group] = generic_subset(df, col_id_list)

    return sub_dfs

def generic_subset(table, col_list):
    """table is a pandas dataframe
       snplist is a list of ids"""
    col_list.append('dependent')

    avail_cols = set(col_list).intersection(table.columns)
    if len(avail_cols) == 1: #dependent column only
        return # There are no snps in your study for phenotype group x
    subset_table = table[list(avail_cols)]

    return subset_table #pandas dataframe

<commit_msg>Forced phenotype column to end of sub dataframes<commit_after>import pandas as pd
from collections import defaultdict

def generate_snp_acc_mapping(table_file):
    """
    Generates a mapping from SNP IDs from a platform to NCBI RS IDs. Based on one Affymetrix GEO dataset, may need
    further tweaking.

    :param table_file: Filename of table-sperated SNP info file
    :return: dictionary mapping platform IDs to RS IDs
    """
    with open(table_file) as snps:
        header = False
        snp_map = {}
        for snp in (l for l in snps if not l.startswith('#')):
            if not header:
                header = snp
            snp = snp.split('\t')
            snp_map[snp[0]] = snp[2] if snp[2].startswith('rs') else snp[1]
    return snp_map

def find_clinvar_groups(clinvar_summary, assembly='GRCh37'):
    """
    Seperated ClinVar variants into groups based on their associated phenotype given a genome assembly id.

    :param clinvar_summary: Filename of variant_summary.txt from ClinVar FTP.
    :param assembly: ID of assembly from which to use SNPs. Current GRCh37 or GRCh38
    :return: Dictionary containing keys of each MedGen phenotype ID mapping to lists of SNP RS IDs
    """
    variants = pd.read_table(clinvar_summary)
    groups = defaultdict(list)
    for i, var in variants[variants.Assembly==assembly].iterrows():
        pheno_ids = {xr.split(':')[0]: xr.split(':')[1] for xr in var.PhenotypeIDs.split(',') if ':' in xr}
        if 'MedGen' in pheno_ids:
            groups[pheno_ids['MedGen']].append(var['RS# (dbSNP)'])
        else:
            groups[None].append(var['RS# (dbSNP)'])
    return groups

def subset_wrap(table, groups, dependents):
    """table is a pandas DataFrame
       groups is a dictionary keys are group labels (phenotype for ex.), values are lists of column labels
       dependents is a list the length of the number of samples
       returns a dictionary keys(group labels): values(sub dataframes)
    """
    df = table
    levels = list(set(dependents.tolist()))
    df['dependent'] = [levels.index(d) for d in dependents] #This is the dependent variable

    # call generic_subset on each group
    sub_dfs = {}
    for group, col_id_list in groups.items():
        sub_dfs[group] = generic_subset(df, col_id_list)

    return sub_dfs

def generic_subset(table, col_list):
    """table is a pandas dataframe
       snplist is a list of ids"""
    avail_cols = set(col_list).intersection(table.columns)
    if len(avail_cols) == 1: #dependent column only
        return # There are no snps in your study for phenotype group x
    subset_table = table[list(avail_cols)]
    subset_table['dependent'] = table['dependent']

    return subset_table #pandas dataframe

<|endoftext|>


<commit_before>#-----------------------------------------------------------------------------
# Name:        miditest.py
# Purpose:     Unit testing harness for midiutil
#
# Author:      Mark Conway Wirt <emergentmusics) at (gmail . com>
#
# Created:     2008/04/17
# Copyright:   (c) 2009, Mark Conway Wirt
# License:     Please see License.txt for the terms under which this
#              software is distributed.
#-----------------------------------------------------------------------------

# Next few lines are necessary owing to limitations of the IDE and the
# directory structure of the project.

import sys,  struct
sys.path.append('..')

import unittest
from pyknon.MidiFile import MIDIFile, MIDIHeader, MIDITrack, writeVarLength,  \
    frequencyTransform,  returnFrequency
import sys

class TestMIDIUtils(unittest.TestCase):

    def testWriteVarLength(self):
        self.assertEquals(writeVarLength(0x70), [0x70])
        self.assertEquals(writeVarLength(0x80), [0x81, 0x00])
        self.assertEquals(writeVarLength(0x1FFFFF), [0xFF, 0xFF, 0x7F])
        self.assertEquals(writeVarLength(0x08000000), [0xC0, 0x80, 0x80, 0x00])

    def testAddNote(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(0, 0, 100,0,1,100)
        self.assertEquals(MyMIDI.tracks[0].eventList[0].type, "note")
        self.assertEquals(MyMIDI.tracks[0].eventList[0].pitch, 100)
        self.assertEquals(MyMIDI.tracks[0].eventList[0].time, 0)
        self.assertEquals(MyMIDI.tracks[0].eventList[0].duration, 1)
        self.assertEquals(MyMIDI.tracks[0].eventList[0].volume, 100)

    def testDeinterleaveNotes(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(0, 0, 100, 0, 2, 100)
        MyMIDI.addNote(0, 0, 100, 1, 2, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[2].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[2].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[3].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[3].time,  256)

    def testTimeShift(self):

        # With one track
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(0, 0, 100, 5, 1, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)

        # With two tracks
        MyMIDI = MIDIFile(2)
        MyMIDI.addNote(0, 0, 100, 5, 1, 100)
        MyMIDI.addNote(1, 0, 100, 6, 1, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].time,  128)
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].time,  128)

        # Negative Time
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(0, 0, 100, -5, 1, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)

        # Negative time, two tracks

        MyMIDI = MIDIFile(2)
        MyMIDI.addNote(0, 0, 100, -1, 1, 100)
        MyMIDI.addNote(1, 0, 100, 0, 1, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].time,  128)
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].time,  128)

    def testFrequency(self):
        freq = frequencyTransform(8.1758)
        self.assertEquals(freq[0],  0x00)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(8.66196) # 8.6620 in MIDI documentation
        self.assertEquals(freq[0],  0x01)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(440.00)
        self.assertEquals(freq[0],  0x45)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(440.0016)
        self.assertEquals(freq[0],  0x45)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x01)
        freq = frequencyTransform(439.9984)
        self.assertEquals(freq[0],  0x44)
        self.assertEquals(freq[1],  0x7f)
        self.assertEquals(freq[2],  0x7f)
        freq = frequencyTransform(8372.0190)
        self.assertEquals(freq[0],  0x78)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(8372.062) #8372.0630 in MIDI documentation
        self.assertEquals(freq[0],  0x78)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x01)
        freq = frequencyTransform(13289.7300)
        self.assertEquals(freq[0],  0x7F)
        self.assertEquals(freq[1],  0x7F)
        self.assertEquals(freq[2],  0x7E)
        freq = frequencyTransform(12543.8760)
        self.assertEquals(freq[0],  0x7F)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(8.2104) # Just plain wrong in documentation, as far as I can tell.
        #self.assertEquals(freq[0],  0x0)
        #self.assertEquals(freq[1],  0x0)
        #self.assertEquals(freq[2],  0x1)

        # Test the inverse
        testFreq = 15.0
        accuracy = 0.00001
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 200.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 400.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 440.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 1200.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 5000.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 12000.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)

    def testSysEx(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.addSysEx(0,0, 0, struct.pack('>B', 0x01))
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'SysEx')
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[0])[0], 0x00)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[1])[0], 0xf0)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[2])[0], 3)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[3])[0], 0x00)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[4])[0], 0x01)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[5])[0], 0xf7)

    def testUniversalSysEx(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.addUniversalSysEx(0,0, 1, 2, struct.pack('>B', 0x01))
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'UniversalSysEx')
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[0])[0], 0x00)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[1])[0], 0xf0)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[2])[0], 6)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[3])[0], 0x7E)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[4])[0], 0x7F)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[5])[0], 0x01)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[6])[0], 0x02)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[7])[0], 0x01)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[8])[0], 0xf7)

    def testTuning(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.changeNoteTuning(0, [(1, 440), (2, 880)])
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'UniversalSysEx')
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[0])[0], 0x00)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[1])[0], 0xf0)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[2])[0], 15)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[3])[0], 0x7E)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[4])[0], 0x7F)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[5])[0], 0x08)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[6])[0], 0x02)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[7])[0], 0x00)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[8])[0], 0x2)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[9])[0], 0x1)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[10])[0], 69)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[11])[0], 0)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[12])[0], 0)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[13])[0], 0x2)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[14])[0], 81)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[15])[0], 0)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[16])[0], 0)
        self.assertEquals(struct.unpack('>B', MyMIDI.tracks[0].MIDIdata[17])[0], 0xf7)

MIDISuite = unittest.TestLoader().loadTestsFromTestCase(TestMIDIUtils)

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=1).run(MIDISuite)

<commit_msg>struct.unpack needs a byte in python3<commit_after>#-----------------------------------------------------------------------------
# Name:        miditest.py
# Purpose:     Unit testing harness for midiutil
#
# Author:      Mark Conway Wirt <emergentmusics) at (gmail . com>
#
# Created:     2008/04/17
# Copyright:   (c) 2009, Mark Conway Wirt
# License:     Please see License.txt for the terms under which this
#              software is distributed.
#-----------------------------------------------------------------------------

# Next few lines are necessary owing to limitations of the IDE and the
# directory structure of the project.

import sys,  struct
sys.path.append('..')
PYTHON3 = True if sys.version_info[0] == 3 else False

import unittest

from pyknon.MidiFile import MIDIFile, MIDIHeader, MIDITrack, writeVarLength,  \
    frequencyTransform,  returnFrequency
import sys

def get_byte(midi, track, data):
    if PYTHON3:
        return struct.unpack('>B', bytes([midi.tracks[track].MIDIdata[data]]))[0]
    else:
        return struct.unpack('>B', midi.tracks[track].MIDIdata[data])[0]

class TestMIDIUtils(unittest.TestCase):
    def testWriteVarLength(self):
        self.assertEquals(writeVarLength(0x70), [0x70])
        self.assertEquals(writeVarLength(0x80), [0x81, 0x00])
        self.assertEquals(writeVarLength(0x1FFFFF), [0xFF, 0xFF, 0x7F])
        self.assertEquals(writeVarLength(0x08000000), [0xC0, 0x80, 0x80, 0x00])

    def testAddNote(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(0, 0, 100,0,1,100)
        self.assertEquals(MyMIDI.tracks[0].eventList[0].type, "note")
        self.assertEquals(MyMIDI.tracks[0].eventList[0].pitch, 100)
        self.assertEquals(MyMIDI.tracks[0].eventList[0].time, 0)
        self.assertEquals(MyMIDI.tracks[0].eventList[0].duration, 1)
        self.assertEquals(MyMIDI.tracks[0].eventList[0].volume, 100)

    def testDeinterleaveNotes(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(0, 0, 100, 0, 2, 100)
        MyMIDI.addNote(0, 0, 100, 1, 2, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[2].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[2].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[3].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[3].time,  256)

    def testTimeShift(self):

        # With one track
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(0, 0, 100, 5, 1, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)

        # With two tracks
        MyMIDI = MIDIFile(2)
        MyMIDI.addNote(0, 0, 100, 5, 1, 100)
        MyMIDI.addNote(1, 0, 100, 6, 1, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].time,  128)
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].time,  128)

        # Negative Time
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(0, 0, 100, -5, 1, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)

        # Negative time, two tracks

        MyMIDI = MIDIFile(2)
        MyMIDI.addNote(0, 0, 100, -1, 1, 100)
        MyMIDI.addNote(1, 0, 100, 0, 1, 100)
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time,  0)
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time,  128)
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].type, 'NoteOn')
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].time,  128)
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].type, 'NoteOff')
        self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].time,  128)

    def testFrequency(self):
        freq = frequencyTransform(8.1758)
        self.assertEquals(freq[0],  0x00)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(8.66196) # 8.6620 in MIDI documentation
        self.assertEquals(freq[0],  0x01)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(440.00)
        self.assertEquals(freq[0],  0x45)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(440.0016)
        self.assertEquals(freq[0],  0x45)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x01)
        freq = frequencyTransform(439.9984)
        self.assertEquals(freq[0],  0x44)
        self.assertEquals(freq[1],  0x7f)
        self.assertEquals(freq[2],  0x7f)
        freq = frequencyTransform(8372.0190)
        self.assertEquals(freq[0],  0x78)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(8372.062) #8372.0630 in MIDI documentation
        self.assertEquals(freq[0],  0x78)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x01)
        freq = frequencyTransform(13289.7300)
        self.assertEquals(freq[0],  0x7F)
        self.assertEquals(freq[1],  0x7F)
        self.assertEquals(freq[2],  0x7E)
        freq = frequencyTransform(12543.8760)
        self.assertEquals(freq[0],  0x7F)
        self.assertEquals(freq[1],  0x00)
        self.assertEquals(freq[2],  0x00)
        freq = frequencyTransform(8.2104) # Just plain wrong in documentation, as far as I can tell.
        #self.assertEquals(freq[0],  0x0)
        #self.assertEquals(freq[1],  0x0)
        #self.assertEquals(freq[2],  0x1)

        # Test the inverse
        testFreq = 15.0
        accuracy = 0.00001
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 200.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 400.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 440.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 1200.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 5000.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)
        testFreq = 12000.0
        x = returnFrequency(frequencyTransform(testFreq))
        delta = abs(testFreq - x)
        self.assertEquals(delta < (accuracy*testFreq), True)

    def testSysEx(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.addSysEx(0,0, 0, struct.pack('>B', 0x01))
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'SysEx')
        self.assertEquals(get_byte(MyMIDI, 0, 0), 0x00)
        self.assertEquals(get_byte(MyMIDI, 0, 1), 0xf0)
        self.assertEquals(get_byte(MyMIDI, 0, 2), 3)
        self.assertEquals(get_byte(MyMIDI, 0, 3), 0x00)
        self.assertEquals(get_byte(MyMIDI, 0, 4), 0x01)
        self.assertEquals(get_byte(MyMIDI, 0, 5), 0xf7)

    def testUniversalSysEx(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.addUniversalSysEx(0,0, 1, 2, struct.pack('>B', 0x01))
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'UniversalSysEx')
        self.assertEquals(get_byte(MyMIDI, 0, 0), 0x00)
        self.assertEquals(get_byte(MyMIDI, 0, 1), 0xf0)
        self.assertEquals(get_byte(MyMIDI, 0, 2), 6)
        self.assertEquals(get_byte(MyMIDI, 0, 3), 0x7E)
        self.assertEquals(get_byte(MyMIDI, 0, 4), 0x7F)
        self.assertEquals(get_byte(MyMIDI, 0, 5), 0x01)
        self.assertEquals(get_byte(MyMIDI, 0, 6), 0x02)
        self.assertEquals(get_byte(MyMIDI, 0, 7), 0x01)
        self.assertEquals(get_byte(MyMIDI, 0, 8), 0xf7)

    def testTuning(self):
        MyMIDI = MIDIFile(1)
        MyMIDI.changeNoteTuning(0, [(1, 440), (2, 880)])
        MyMIDI.close()
        self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'UniversalSysEx')
        self.assertEquals(get_byte(MyMIDI, 0, 0), 0x00)
        self.assertEquals(get_byte(MyMIDI, 0, 1), 0xf0)
        self.assertEquals(get_byte(MyMIDI, 0, 2), 15)
        self.assertEquals(get_byte(MyMIDI, 0, 3), 0x7E)
        self.assertEquals(get_byte(MyMIDI, 0, 4), 0x7F)
        self.assertEquals(get_byte(MyMIDI, 0, 5), 0x08)
        self.assertEquals(get_byte(MyMIDI, 0, 6), 0x02)
        self.assertEquals(get_byte(MyMIDI, 0, 7), 0x00)
        self.assertEquals(get_byte(MyMIDI, 0, 8), 0x2)
        self.assertEquals(get_byte(MyMIDI, 0, 9), 0x1)
        self.assertEquals(get_byte(MyMIDI, 0, 10), 69)
        self.assertEquals(get_byte(MyMIDI, 0, 11), 0)
        self.assertEquals(get_byte(MyMIDI, 0, 12), 0)
        self.assertEquals(get_byte(MyMIDI, 0, 13), 0x2)
        self.assertEquals(get_byte(MyMIDI, 0, 14), 81)
        self.assertEquals(get_byte(MyMIDI, 0, 15), 0)
        self.assertEquals(get_byte(MyMIDI, 0, 16), 0)
        self.assertEquals(get_byte(MyMIDI, 0, 17), 0xf7)

MIDISuite = unittest.TestLoader().loadTestsFromTestCase(TestMIDIUtils)

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=1).run(MIDISuite)

<|endoftext|>


<commit_before>import pygame
from pygame.locals import *

screen_size = (1600, 800)

class Game(object):
    def __init__(self):
        pygame.init()
        pygame.mixer.init()
        self.surface = pygame.display.set_mode(screen_size, pygame.HWSURFACE)
        self.gamestate = 1

    def main(self):
        while self.gamestate==1:
            for event in pygame.event.get():
                if event.type==QUIT or (event.type==KEYDOWN and event.key==K_ESCAPE):
                    self.gamestate=0

if __name__ == "__main__":
    Game().main()
<commit_msg>poprawki flake8 i mniejszcza rozdzielczość<commit_after>import pygame
from pygame.locals import *  # noqa

screen_size = (1024, 798)

class Game(object):
    def __init__(self):
        pygame.init()
        pygame.mixer.init()
        self.surface = pygame.display.set_mode(screen_size, pygame.HWSURFACE)
        self.gamestate = 1

    def main(self):
        while self.gamestate == 1:
            for event in pygame.event.get():
                if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                    self.gamestate = 0

if __name__ == "__main__":
    Game().main()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from random import random

WIDTH = 10
HEIGHT = 16
MAX_TMP = 20

class FailedException(BaseException):
    pass

tic_white = lambda *_:None

def tic_orange(self, family):
    self.tmp = self.tmp - 1
    if self.tmp == 0:
        self.color = block.WHITE
        if not self.is_bottom:
            block_down = family(*self.id_down)
            if block_down.is_cursor:
                raise FailedException
            else:
                block_down.color = block.ORANGE
                block_down.tmp   = MAX_TMP

tic_functions = [tic_white, tic_orange]
colors = [(128,128,128), (255,165,0)]

class block:
    WHITE = 0
    ORANGE = 1

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, value):
        self._color = value
        self.tic_function = tic_functions[value]

    def __init__(self):
        self.color = block.WHITE
        self.tmp   = 0
        self.is_cursor = False

    def tic(self, family):
        self.tic_function(self, family)

class base_game:

    def __init__(self):
        self.blocks = [[block() for x in range(1, WIDTH+1)] for y in range(HEIGHT+1)]
        self.family = lambda x, y: self.blocks[y][x-1]
        for y in range(HEIGHT+1):
            for x in range(1, WIDTH+1):
                b = self.family(x, y)
                b.is_far_left  = x == 1
                b.is_far_right = x == WIDTH
                b.is_bottom    = y == 0
                b.is_top       = y == HEIGHT

                b.id_left  = b.is_far_left  or (x-1, y)
                b.id_right = b.is_far_right or (x+1, y)
                b.id_up    = b.is_top       or (x, y+1)
                b.id_down  = b.is_bottom    or (x, y-1)
        self.cursor = (4, 0)
        self.family(*self.cursor).is_cursor = True
        self.time= 0

    def update(self):
        self.time = self.time + 1
        for s in self.blocks:
            for t in s:
                t.tic(self.family)
        if self.time % MAX_TMP == 0:
            for x in range(1, WIDTH+1):
                b = self.family(x, HEIGHT)
                if b.color == block.WHITE:
                    if random() < 1/7:
                        b.color = block.ORANGE
                        b.tmp = MAX_TMP

    def move_cursor_left(self):
        if not self.family(*self.cursor).is_far_left:
            self.family(*self.cursor).is_cursor = False
            x, y = self.cursor
            self.cursor = x-1, y
            self.family(*self.cursor).is_cursor = True

    def move_cursor_right(self):
        if not self.family(*self.cursor).is_far_right:
            self.family(*self.cursor).is_cursor = False
            x, y = self.cursor
            self.cursor = x+1, y
            self.family(*self.cursor).is_cursor = True

    def __repr__(self):
        """
        game.__repr__()
        This method is mainly designed for testing
        """
        s = "game object at time %d\n" % self.time
        s = s + '-'*61 + '\n'
        for y in range(HEIGHT+1):
            s = s + '| '
            for x in range(1, WIDTH+1):
                b = self.family(x, y)
                s = s + "%c%2d%c| "%("WO???"[b.color], b.tmp, " ^"[b.is_cursor])
            s = s + '\n'
        return s

<commit_msg>a working version<commit_after># -*- coding: utf-8 -*-

from random import random

WIDTH = 10
HEIGHT = 16
MAX_TMP = 40

class FailedException(BaseException):
    pass

tic_white = lambda *_:None

def tic_orange(self, family):
    self.tmp = self.tmp - 1
    if self.tmp == MAX_TMP//3*2:
        if not self.is_bottom:
            block_down = family(*self.id_down)
            if block_down.is_cursor:
                raise FailedException
            else:
                block_down.color = block.ORANGE
                block_down.tmp   = MAX_TMP
    elif self.tmp == 0:
        self.color = block.WHITE

tic_functions = [tic_white, tic_orange]
colors = [(128,128,128), (255,165,0)]

class block:
    WHITE = 0
    ORANGE = 1

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, value):
        self._color = value
        self.tic_function = tic_functions[value]

    def __init__(self):
        self.color = block.WHITE
        self.tmp   = 0
        self.is_cursor = False

    def tic(self, family):
        self.tic_function(self, family)

class base_game:

    def __init__(self):
        self.blocks = [[block() for x in range(1, WIDTH+1)] for y in range(HEIGHT+1)]
        self.family = lambda x, y: self.blocks[y][x-1]
        for y in range(HEIGHT+1):
            for x in range(1, WIDTH+1):
                b = self.family(x, y)
                b.is_far_left  = x == 1
                b.is_far_right = x == WIDTH
                b.is_bottom    = y == 0
                b.is_top       = y == HEIGHT

                b.id_left  = b.is_far_left  or (x-1, y)
                b.id_right = b.is_far_right or (x+1, y)
                b.id_up    = b.is_top       or (x, y+1)
                b.id_down  = b.is_bottom    or (x, y-1)
        self.cursor = (4, 0)
        self.family(*self.cursor).is_cursor = True
        self.time= 0

    def update(self):
        self.time = self.time + 1
        for s in self.blocks:
            for t in s:
                t.tic(self.family)
        if self.time % MAX_TMP == 0:
            for x in range(1, WIDTH+1):
                b = self.family(x, HEIGHT)
                if b.color == block.WHITE:
                    if random() < 1/7:
                        b.color = block.ORANGE
                        b.tmp = MAX_TMP

    def move_cursor_left(self):
        if not self.family(*self.cursor).is_far_left:
            self.family(*self.cursor).is_cursor = False
            x, y = self.cursor
            self.cursor = x-1, y
            self.family(*self.cursor).is_cursor = True

    def move_cursor_right(self):
        if not self.family(*self.cursor).is_far_right:
            self.family(*self.cursor).is_cursor = False
            x, y = self.cursor
            self.cursor = x+1, y
            self.family(*self.cursor).is_cursor = True

    def __repr__(self):
        """
        game.__repr__()
        This method is mainly designed for testing
        """
        s = "game object at time %d\n" % self.time
        s = s + '-'*61 + '\n'
        for y in range(HEIGHT+1):
            s = s + '| '
            for x in range(1, WIDTH+1):
                b = self.family(x, y)
                s = s + "%c%2d%c| "%("WO???"[b.color], b.tmp, " ^"[b.is_cursor])
            s = s + '\n'
        return s

<|endoftext|>


<commit_before>
import json
import random
from operator import itemgetter
import os

# Read questions file
_site_root = os.path.realpath(os.path.dirname(__file__))
_questions_path = os.path.join(_site_root, 'resources', 'questions.json')
with open(_questions_path, 'r') as f:
    _questions = json.load(f)

# TODO how long?
MAX_TIME = 6000

def get_question_header(question_id):
    q = _questions[question_id]
    return {
        'img': q['img'],
        'question': q['question']
    }

def get_question(question_id):
    q = _questions[question_id]
    answers = list(q['answers'])
    random.shuffle(answers)
    question_dict = {
        'img': q['img'],
        'question': q['question'],
        'answers': list(map(itemgetter('answer'), answers))
    }
    correct_answers = list(map(itemgetter('correct'), answers))
    return question_dict, correct_answers

def get_answer_score(t):
    if (t < 0 or t > MAX_TIME):
        raise ValueError('Invalid answer time')
    return 6000 - t

def get_question_id_list():
    return list(range(num_questions()))

def num_questions():
    return len(_questions)
<commit_msg>Added MAX_SCORE per question<commit_after>
import json
import random
from operator import itemgetter
import os

# Read questions file
_site_root = os.path.realpath(os.path.dirname(__file__))
_questions_path = os.path.join(_site_root, 'resources', 'questions.json')
with open(_questions_path, 'r') as f:
    _questions = json.load(f)

# TODO how long?
MAX_TIME = 6000
MAX_SCORE = 1000

def get_question_header(question_id):
    q = _questions[question_id]
    return {
        'img': q['img'],
        'question': q['question']
    }

def get_question(question_id):
    q = _questions[question_id]
    answers = list(q['answers'])
    random.shuffle(answers)
    question_dict = {
        'img': q['img'],
        'question': q['question'],
        'answers': list(map(itemgetter('answer'), answers))
    }
    correct_answers = list(map(itemgetter('correct'), answers))
    return question_dict, correct_answers

def get_answer_score(t):
    if (t < 0 or t > MAX_TIME):
        raise ValueError('Invalid answer time')
    return int(MAX_SCORE * (float(MAX_TIME - t) / MAX_TIME))

def get_question_id_list():
    return list(range(num_questions()))

def num_questions():
    return len(_questions)
<|endoftext|>


<commit_before>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 500

class Field(Sprite):
    field=ImageAsset("images/field.jpg")

    def __init__(self, position):
         super().__init__(Field.field, position)
         self.vx=1
         self.vy=1
         self.vr=0

class AOA():
    def __init__(self, r):
        self.rotation = r
    def anglex(self):
        return (-1 * math.cos(self.rotation))
    def angley(self):
        return (-1 * math.sin(self.rotation))

    a = AOA(3,4,2)
    vx=a.anglex()
    vy=a.angley()
    vx=AOA(3,4,2).anglex()

class Plane(Sprite):
    airplane = ImageAsset("images/28293b2fe5801e03f1f70ed61c8397f6_airplane-clipart-transparent-airplane-clipart-transparent-background_2400-1009.png")
    def __init__(self, position):
        super().__init__(Plane.airplane, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.scale = 0.1
        Game.listenKeyEvent("keydown", "d", self.Forward)
        Game.listenKeyEvent("keydown", "a", self.Slow)
        Game.listenKeyEvent("keydown", "left arrow", self.Up)
        Game.listenKeyEvent("keydown", "right arrow", self.Down)
        Game.listenKeyEvent("keyup", "right arrow", self.Stop)
        Game.listenKeyEvent("keyup", "left arrow", self.Stop)
        Game.listenKeyEvent("keydown", "e", self.Print)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        #while self.vx >= 0:
        #self.vx -= 0.4
        #while self.vy >= 0:
        #self.vy -= 0.4
        self.rotation += self.vr
        angle=AOA(self.rotation)
        self.vx=angle.anglex()
        self.vy=angle.angley()
        self.y += self.vy
        self.x += self.vx
        """
         if self.rotation > 90:
             self.vx = 0
             self.y -=
        """
    def Forward(self, event)
        self.vx += 0.6
    def Slow(self, event):
        self.vx -= 0.6
    def Up(self, event):
        self.vr += 0.1
    def Down(self, event):
        self.vr -= 0.1

    def Stop(self, event):
        self.vr=0
    def Print(self, event):
        print(self.rotation)

class Game(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        """
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, noline, black)
        bg = Sprite(bg_asset, (0,0))
        """
        Field((0,0))
        Plane((0,500))

    def step(self):
        for airplane in self.getSpritesbyClass(Plane):
            airplane.step()

myapp = Game(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<commit_msg>Updated from Brython Server: 5/2/2017 2:49:51 PM<commit_after>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 500

class Field(Sprite):
    field=ImageAsset("images/field.jpg")

    def __init__(self, position):
         super().__init__(Field.field, position)
         self.vx=1
         self.vy=1
         self.vr=0

class AOA():
    def __init__(self, r):
        self.rotation = r
    def anglex(self):
        return (-1 * math.cos(self.rotation))
    def angley(self):
        return (-1 * math.sin(self.rotation))

class Plane(Sprite):
    airplane = ImageAsset("images/28293b2fe5801e03f1f70ed61c8397f6_airplane-clipart-transparent-airplane-clipart-transparent-background_2400-1009.png")
    def __init__(self, position):
        super().__init__(Plane.airplane, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.scale = 0.1
        Game.listenKeyEvent("keydown", "d", self.Forward)
        Game.listenKeyEvent("keydown", "a", self.Slow)
        Game.listenKeyEvent("keydown", "left arrow", self.Up)
        Game.listenKeyEvent("keydown", "right arrow", self.Down)
        Game.listenKeyEvent("keyup", "right arrow", self.Stop)
        Game.listenKeyEvent("keyup", "left arrow", self.Stop)
        Game.listenKeyEvent("keydown", "e", self.Print)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        #while self.vx >= 0:
        #self.vx -= 0.4
        #while self.vy >= 0:
        #self.vy -= 0.4
        self.rotation += self.vr
        angle=AOA(self.rotation)
        self.vx=angle.anglex()
        self.vy=angle.angley()
        self.y += self.vy
        self.x += self.vx
        """
         if self.rotation > 90:
             self.vx = 0
             self.y -=
        """
    def Forward(self, event)
        self.vx += 0.6
    def Slow(self, event):
        self.vx -= 0.6
    def Up(self, event):
        self.vr += 0.1
    def Down(self, event):
        self.vr -= 0.1

    def Stop(self, event):
        self.vr=0
    def Print(self, event):
        print(self.rotation)

class Game(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        """
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, noline, black)
        bg = Sprite(bg_asset, (0,0))
        """
        Field((0,0))
        Plane((0,500))

    def step(self):
        for airplane in self.getSpritesbyClass(Plane):
            airplane.step()

myapp = Game(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<|endoftext|>


<commit_before>from __future__ import absolute_import

import json
import os
import tempfile
import unittest
from functools import partial

import pytest
from six import StringIO

import cwltool.pack
import cwltool.workflow
from cwltool import load_tool
from cwltool.load_tool import fetch_document, validate_document
from cwltool.main import main, make_relative, print_pack
from cwltool.pathmapper import adjustDirObjs, adjustFileObjs
from cwltool.resolver import tool_resolver

from .util import get_data, needs_docker

class TestPack(unittest.TestCase):
    maxDiff = None

    def test_pack(self):
        load_tool.loaders = {}

        document_loader, workflowobj, uri = fetch_document(
            get_data("tests/wf/revsort.cwl"))
        document_loader, avsc_names, processobj, metadata, uri = validate_document(
            document_loader, workflowobj, uri)
        packed = cwltool.pack.pack(document_loader, processobj, uri, metadata)
        with open(get_data("tests/wf/expect_packed.cwl")) as f:
            expect_packed = json.load(f)
        adjustFileObjs(packed, partial(make_relative,
            os.path.abspath(get_data("tests/wf"))))
        adjustDirObjs(packed, partial(make_relative,
            os.path.abspath(get_data("tests/wf"))))
        self.assertIn("$schemas", packed)
        del packed["$schemas"]
        del expect_packed["$schemas"]

        self.assertEqual(expect_packed, packed)

    def test_pack_rewrites(self):
        load_tool.loaders = {}

        document_loader, workflowobj, uri = fetch_document(get_data("tests/wf/default-wf5.cwl"))
        document_loader, avsc_names, processobj, metadata, uri = validate_document(
            document_loader, workflowobj, uri)
        rewrites = {}
        packed = cwltool.pack.pack(document_loader, processobj, uri, metadata, rewrite_out=rewrites)
        self.assertEqual(6, len(rewrites))

    def test_pack_missing_cwlVersion(self):
        """Test to ensure the generated pack output is not missing
        the `cwlVersion` in case of single tool workflow and single step workflow"""

        # Testing single tool workflow
        document_loader, workflowobj, uri = fetch_document(
            get_data("tests/wf/hello_single_tool.cwl"))
        document_loader, _, processobj, metadata, uri = validate_document(
            document_loader, workflowobj, uri)
        # generate pack output dict
        packed = json.loads(print_pack(document_loader, processobj, uri, metadata))

        self.assertEqual('v1.0', packed["cwlVersion"])

        # Testing single step workflow
        document_loader, workflowobj, uri = fetch_document(
            get_data("tests/wf/hello-workflow.cwl"))
        document_loader, _, processobj, metadata, uri = validate_document(
            document_loader, workflowobj, uri)
        # generate pack output dict
        packed = json.loads(print_pack(document_loader, processobj, uri, metadata))

        self.assertEqual('v1.0', packed["cwlVersion"])

    def test_pack_idempotence_tool(self):
        """Test to ensure that pack produces exactly the same document for
           an already packed document"""

        # Testing single tool
        self._pack_idempotently("tests/wf/hello_single_tool.cwl")

    def test_pack_idempotence_workflow(self):
        """Test to ensure that pack produces exactly the same document for
           an already packed document"""

        # Testing workflow
        self._pack_idempotently("tests/wf/count-lines1-wf.cwl")

    def _pack_idempotently(self, document):
        document_loader, workflowobj, uri = fetch_document(
            get_data(document))
        document_loader, avsc_names, processobj, metadata, uri = validate_document(
            document_loader, workflowobj, uri)
        # generate pack output dict
        packed = json.loads(print_pack(document_loader, processobj, uri, metadata))

        document_loader, workflowobj, uri2 = fetch_document(packed)
        document_loader, avsc_names, processobj, metadata, uri2 = validate_document(
            document_loader, workflowobj, uri)
        double_packed = json.loads(print_pack(document_loader, processobj, uri2, metadata))
        self.assertEqual(packed, double_packed)

    @needs_docker
    def test_packed_workflow_execution(self):
        load_tool.loaders = {}
        test_wf = "tests/wf/count-lines1-wf.cwl"
        test_wf_job = "tests/wf/wc-job.json"
        document_loader, workflowobj, uri = fetch_document(
            get_data(test_wf), resolver=tool_resolver)
        document_loader, avsc_names, processobj, metadata, uri = validate_document(
            document_loader, workflowobj, uri)
        packed = json.loads(print_pack(document_loader, processobj, uri, metadata))
        temp_packed_handle, temp_packed_path = tempfile.mkstemp()
        with open(temp_packed_path, 'w') as f:
            json.dump(packed, f)
        normal_output = StringIO()
        packed_output = StringIO()
        self.assertEquals(main(['--debug', get_data(temp_packed_path),
                                get_data(test_wf_job)],
                               stdout=packed_output), 0)
        self.assertEquals(main([get_data(test_wf),
                                get_data(test_wf_job)],
                               stdout=normal_output), 0)
        self.assertEquals(json.loads(packed_output.getvalue()), json.loads(normal_output.getvalue()))
        os.close(temp_packed_handle)
        os.remove(temp_packed_path)

    @needs_docker
    def test_preserving_namespaces(self):
        test_wf = "tests/wf/formattest.cwl"
        test_wf_job = "tests/wf/formattest-job.json"
        document_loader, workflowobj, uri = fetch_document(
            get_data(test_wf))
        document_loader, avsc_names, processobj, metadata, uri = validate_document(
            document_loader, workflowobj, uri)
        packed = json.loads(print_pack(document_loader, processobj, uri, metadata))
        assert "$namespaces" in packed
        temp_packed_handle, temp_packed_path = tempfile.mkstemp()
        with open(temp_packed_path, 'w') as f:
            json.dump(packed, f)
        normal_output = StringIO()
        packed_output = StringIO()
        self.assertEquals(main(['--debug', get_data(temp_packed_path),
                                get_data(test_wf_job)],
                               stdout=packed_output), 0)
        self.assertEquals(main([get_data(test_wf),
                                get_data(test_wf_job)],
                               stdout=normal_output), 0)
        self.assertEquals(json.loads(packed_output.getvalue()), json.loads(normal_output.getvalue()))
        os.close(temp_packed_handle)
        os.remove(temp_packed_path)
<commit_msg>maintenance: remove unittest from test_pack<commit_after>import json
import os
import tempfile
from functools import partial

from six import StringIO
import pytest

import cwltool.pack
import cwltool.workflow
from cwltool import load_tool
from cwltool.load_tool import fetch_document, validate_document
from cwltool.main import main, make_relative, print_pack
from cwltool.pathmapper import adjustDirObjs, adjustFileObjs
from cwltool.resolver import tool_resolver

from .util import get_data, needs_docker

def test_pack():
    load_tool.loaders = {}

    document_loader, workflowobj, uri = fetch_document(get_data("tests/wf/revsort.cwl"))
    document_loader, _, processobj, metadata, uri = validate_document(
        document_loader, workflowobj, uri)

    with open(get_data("tests/wf/expect_packed.cwl")) as packed_file:
        expect_packed = json.load(packed_file)

    packed = cwltool.pack.pack(document_loader, processobj, uri, metadata)
    adjustFileObjs(packed, partial(make_relative, os.path.abspath(get_data("tests/wf"))))
    adjustDirObjs(packed, partial(make_relative, os.path.abspath(get_data("tests/wf"))))

    assert "$schemas" in packed

    del packed["$schemas"]
    del expect_packed["$schemas"]

    assert packed == expect_packed

def test_pack_rewrites():
    load_tool.loaders = {}
    rewrites = {}

    document_loader, workflowobj, uri = fetch_document(get_data("tests/wf/default-wf5.cwl"))
    document_loader, _, processobj, metadata, uri = validate_document(
        document_loader, workflowobj, uri)

    cwltool.pack.pack(document_loader, processobj, uri, metadata, rewrite_out=rewrites)

    assert len(rewrites) == 6

cwl_missing_version_paths = [
    "tests/wf/hello_single_tool.cwl",
    "tests/wf/hello-workflow.cwl"
]

@pytest.mark.parametrize('cwl_path', cwl_missing_version_paths)
def test_pack_missing_cwlVersion(cwl_path):
    """Test to ensure the generated pack output is not missing
    the `cwlVersion` in case of single tool workflow and single step workflow"""

    # Testing single tool workflow
    document_loader, workflowobj, uri = fetch_document(get_data(cwl_path))
    document_loader, _, processobj, metadata, uri = validate_document(
        document_loader, workflowobj, uri)
    # generate pack output dict
    packed = json.loads(print_pack(document_loader, processobj, uri, metadata))

    assert packed["cwlVersion"] == 'v1.0'

def test_pack_idempotence_tool():
    """Test to ensure that pack produces exactly the same document for
       an already packed document"""

    # Testing single tool
    _pack_idempotently("tests/wf/hello_single_tool.cwl")

def test_pack_idempotence_workflow():
    """Test to ensure that pack produces exactly the same document for
       an already packed document"""

    # Testing workflow
    _pack_idempotently("tests/wf/count-lines1-wf.cwl")

def _pack_idempotently(document):
    document_loader, workflowobj, uri = fetch_document(
        get_data(document))
    document_loader, _, processobj, metadata, uri = validate_document(
        document_loader, workflowobj, uri)
    # generate pack output dict
    packed = json.loads(print_pack(document_loader, processobj, uri, metadata))

    document_loader, workflowobj, uri2 = fetch_document(packed)
    document_loader, _, processobj, metadata, uri2 = validate_document(
        document_loader, workflowobj, uri)
    double_packed = json.loads(print_pack(document_loader, processobj, uri2, metadata))
    assert packed == double_packed

cwl_to_run = [
    ("tests/wf/count-lines1-wf.cwl",
     "tests/wf/wc-job.json",
     False
     ),
    ("tests/wf/formattest.cwl",
     "tests/wf/formattest-job.json",
     True
     ),
]

@needs_docker
@pytest.mark.parametrize('wf_path,job_path,namespaced', cwl_to_run)
def test_packed_workflow_execution(wf_path, job_path, namespaced):
    load_tool.loaders = {}

    document_loader, workflowobj, uri = fetch_document(
        get_data(wf_path), resolver=tool_resolver)

    document_loader, _, processobj, metadata, uri = validate_document(
        document_loader, workflowobj, uri)

    packed = json.loads(print_pack(document_loader, processobj, uri, metadata))

    assert not namespaced or "$namespaces" in packed

    wf_packed_handle, wf_packed_path = tempfile.mkstemp()
    with open(wf_packed_path, 'w') as temp_file:
        json.dump(packed, temp_file)

    normal_output = StringIO()
    packed_output = StringIO()

    normal_params = [get_data(wf_path), get_data(job_path)]
    packed_params = ['--debug', get_data(wf_packed_path), get_data(job_path)]

    assert main(normal_params, stdout=normal_output) == 0
    assert main(packed_params, stdout=packed_output) == 0

    assert json.loads(packed_output.getvalue()) == json.loads(normal_output.getvalue())

    os.close(wf_packed_handle)
    os.remove(wf_packed_path)
<|endoftext|>