<commit_before>from io import StringIO
from unittest.mock import patch
import datetime
import pytest

from dataactvalidator.scripts import load_program_activity
from dataactcore.models.domainModels import ProgramActivity, ExternalDataType

@patch('dataactvalidator.scripts.load_program_activity.io.BytesIO')
@patch('dataactvalidator.scripts.load_program_activity.boto3')
def test_get_program_activity_file_aws(boto3, bytesio, monkeypatch):
    """ Test retrieving the program activity file from AWS """

    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': True, 'aws_region': 'region'})

    bytesio.return_value = None

    load_program_activity.get_program_activity_file('some path')

    boto3.resource('s3').Object(
            load_program_activity.PA_BUCKET, load_program_activity.PA_SUB_KEY+load_program_activity.PA_FILE_NAME
            ).get.assert_called_with(load_program_activity.PA_SUB_KEY+load_program_activity.PA_FILE_NAME)

def test_get_program_activity_file_local(monkeypatch):
    """ Test obtaining the local file based on its path """

    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False})

    pa_file = load_program_activity.get_program_activity_file('local_path')

    assert pa_file == 'local_path/DATA Act Program Activity List for Treas.csv'

def test_set_get_pa_last_upload_existing(monkeypatch, database):
    """ Test the last upload date/time retrieval """

    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False})
    sess = database.session
    pa_data_type = ExternalDataType(external_data_type_id=2, name="program_activity_upload", description="lorem ipsum")
    sess.add(pa_data_type)
    sess.commit()

    # test epoch timing
    stored_date = load_program_activity.get_stored_pa_last_upload()
    expected_date = datetime.datetime(1970, 1, 1, 0, 0, 0)
    assert stored_date == expected_date

    load_program_activity.set_stored_pa_last_upload(datetime.datetime(2017, 12, 31, 0, 0, 0))

    stored_date = load_program_activity.get_stored_pa_last_upload()
    expected_date = datetime.datetime(2017, 12, 31, 0, 0, 0)
    assert stored_date == expected_date

    # repeat this, because the first time, there is no stored object, but now test with one that already exists.
    load_program_activity.set_stored_pa_last_upload(datetime.datetime(2016, 12, 31, 0, 0, 0))

    stored_date = load_program_activity.get_stored_pa_last_upload()
    expected_date = datetime.datetime(2016, 12, 31, 0, 0, 0)
    assert stored_date == expected_date

@patch('dataactvalidator.scripts.load_program_activity.set_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_date_of_current_pa_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_program_activity_file')
def test_load_program_activity_data(mocked_get_pa_file, mocked_get_current_date, mocked_get_stored_date,
                                    mocked_set_stored_date, database, monkeypatch):
    """ Test actually loading the program activity data """
    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False})

    mocked_get_pa_file.return_value = StringIO(
        """AGENCY_CODE,ALLOCATION_ID,ACCOUNT_CODE,PA_CODE,PA_TITLE,FYQ\n2000,000,111,0000,1111,Test Name,FY2015Q1"""
    )

    mocked_get_current_date.return_value = datetime.datetime(2017, 12, 31, 0, 0, 0)
    mocked_get_stored_date.return_value = datetime.datetime(2016, 12, 31, 0, 0, 0)
    mocked_set_stored_date.return_value = None

    sess = database.session

    load_program_activity.load_program_activity_data('some_path')

    pa = sess.query(ProgramActivity).one_or_none()

    assert pa.fiscal_year_quarter == 'FY2015Q1'
    assert pa.agency_id == '000'
    assert pa.allocation_transfer_id == '111'
    assert pa.account_number == '0000'
    assert pa.program_activity_code == '1111'
    assert pa.program_activity_name == 'test name'

@patch('dataactvalidator.scripts.load_program_activity.set_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_date_of_current_pa_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_program_activity_file')
def test_load_program_activity_data_only_header(mocked_get_pa_file, mocked_get_current_date, mocked_get_stored_date,
                                                mocked_set_stored_date, monkeypatch):
    """ Test actually loading the program activity data """
    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False, "local": False})

    mocked_get_pa_file.return_value = StringIO(
        """AGENCY_CODE,ALLOCATION_ID,ACCOUNT_CODE,PA_CODE,PA_TITLE,FYQ"""
    )

    mocked_get_current_date.return_value = datetime.datetime(2017, 12, 31, 0, 0, 0)
    mocked_get_stored_date.return_value = datetime.datetime(2016, 12, 31, 0, 0, 0)
    mocked_set_stored_date.return_value = None

    with pytest.raises(SystemExit) as se:
        load_program_activity.load_program_activity_data('some_path')

    assert se.value.code == 4

@patch('dataactvalidator.scripts.load_program_activity.set_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_date_of_current_pa_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_program_activity_file')
def test_load_program_activity_data_no_header(mocked_get_pa_file, mocked_get_current_date, mocked_get_stored_date,
                                              mocked_set_stored_date, monkeypatch):
    """ Test actually loading the program activity data """
    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False, 'local':False})

    mocked_get_pa_file.return_value = StringIO(
        """2000,000,111,0000,1111,Test Name,FY2015Q1"""
    )

    mocked_get_current_date.return_value = datetime.datetime(2017, 12, 31, 0, 0, 0)
    mocked_get_stored_date.return_value = datetime.datetime(2016, 12, 31, 0, 0, 0)
    mocked_set_stored_date.return_value = None

    with pytest.raises(SystemExit) as se:
        load_program_activity.load_program_activity_data('some_path')

    assert se.value.code == 4

@patch('dataactvalidator.scripts.load_program_activity.set_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_date_of_current_pa_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_program_activity_file')
def test_load_program_activity_data_empty_file(mocked_get_pa_file, mocked_get_current_date, mocked_get_stored_date,
                                               mocked_set_stored_date, monkeypatch):
    """ Test actually loading the program activity data """
    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False, 'local':False})

    mocked_get_pa_file.return_value = StringIO("")

    mocked_get_current_date.return_value = datetime.datetime(2017, 12, 31, 0, 0, 0)
    mocked_get_stored_date.return_value = datetime.datetime(2016, 12, 31, 0, 0, 0)
    mocked_set_stored_date.return_value = None

    with pytest.raises(SystemExit) as se:
        load_program_activity.load_program_activity_data('some_path')

    assert se.value.code == 4
<commit_msg>deflaking again<commit_after>from io import StringIO
from unittest.mock import patch
import datetime
import pytest

from dataactvalidator.scripts import load_program_activity
from dataactcore.models.domainModels import ProgramActivity, ExternalDataType

@patch('dataactvalidator.scripts.load_program_activity.io.BytesIO')
@patch('dataactvalidator.scripts.load_program_activity.boto3')
def test_get_program_activity_file_aws(boto3, bytesio, monkeypatch):
    """ Test retrieving the program activity file from AWS """

    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': True, 'aws_region': 'region'})

    bytesio.return_value = None

    load_program_activity.get_program_activity_file('some path')

    boto3.resource('s3').Object(
            load_program_activity.PA_BUCKET, load_program_activity.PA_SUB_KEY+load_program_activity.PA_FILE_NAME
            ).get.assert_called_with(load_program_activity.PA_SUB_KEY+load_program_activity.PA_FILE_NAME)

def test_get_program_activity_file_local(monkeypatch):
    """ Test obtaining the local file based on its path """

    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False})

    pa_file = load_program_activity.get_program_activity_file('local_path')

    assert pa_file == 'local_path/DATA Act Program Activity List for Treas.csv'

def test_set_get_pa_last_upload_existing(monkeypatch, database):
    """ Test the last upload date/time retrieval """

    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False})
    sess = database.session
    pa_data_type = ExternalDataType(external_data_type_id=2, name="program_activity_upload", description="lorem ipsum")
    sess.add(pa_data_type)
    sess.commit()

    # test epoch timing
    stored_date = load_program_activity.get_stored_pa_last_upload()
    expected_date = datetime.datetime(1970, 1, 1, 0, 0, 0)
    assert stored_date == expected_date

    load_program_activity.set_stored_pa_last_upload(datetime.datetime(2017, 12, 31, 0, 0, 0))

    stored_date = load_program_activity.get_stored_pa_last_upload()
    expected_date = datetime.datetime(2017, 12, 31, 0, 0, 0)
    assert stored_date == expected_date

    # repeat this, because the first time, there is no stored object, but now test with one that already exists.
    load_program_activity.set_stored_pa_last_upload(datetime.datetime(2016, 12, 31, 0, 0, 0))

    stored_date = load_program_activity.get_stored_pa_last_upload()
    expected_date = datetime.datetime(2016, 12, 31, 0, 0, 0)
    assert stored_date == expected_date

@patch('dataactvalidator.scripts.load_program_activity.set_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_date_of_current_pa_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_program_activity_file')
def test_load_program_activity_data(mocked_get_pa_file, mocked_get_current_date, mocked_get_stored_date,
                                    mocked_set_stored_date, database, monkeypatch):
    """ Test actually loading the program activity data """
    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False})

    mocked_get_pa_file.return_value = StringIO(
        """AGENCY_CODE,ALLOCATION_ID,ACCOUNT_CODE,PA_CODE,PA_TITLE,FYQ\n2000,000,111,0000,1111,Test Name,FY2015Q1"""
    )

    mocked_get_current_date.return_value = datetime.datetime(2017, 12, 31, 0, 0, 0)
    mocked_get_stored_date.return_value = datetime.datetime(2016, 12, 31, 0, 0, 0)
    mocked_set_stored_date.return_value = None

    sess = database.session

    load_program_activity.load_program_activity_data('some_path')

    pa = sess.query(ProgramActivity).one_or_none()

    assert pa.fiscal_year_quarter == 'FY2015Q1'
    assert pa.agency_id == '000'
    assert pa.allocation_transfer_id == '111'
    assert pa.account_number == '0000'
    assert pa.program_activity_code == '1111'
    assert pa.program_activity_name == 'test name'

@patch('dataactvalidator.scripts.load_program_activity.set_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_date_of_current_pa_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_program_activity_file')
def test_load_program_activity_data_only_header(mocked_get_pa_file, mocked_get_current_date, mocked_get_stored_date,
                                                mocked_set_stored_date, monkeypatch):
    """ Test actually loading the program activity data """
    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False, "local": False})

    mocked_get_pa_file.return_value = StringIO(
        """AGENCY_CODE,ALLOCATION_ID,ACCOUNT_CODE,PA_CODE,PA_TITLE,FYQ"""
    )

    mocked_get_current_date.return_value = datetime.datetime(2017, 12, 31, 0, 0, 0)
    mocked_get_stored_date.return_value = datetime.datetime(2016, 12, 31, 0, 0, 0)
    mocked_set_stored_date.return_value = None

    with pytest.raises(SystemExit) as se:
        load_program_activity.load_program_activity_data('some_path')

    assert se.value.code == 4

@patch('dataactvalidator.scripts.load_program_activity.set_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_date_of_current_pa_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_program_activity_file')
def test_load_program_activity_data_no_header(mocked_get_pa_file, mocked_get_current_date, mocked_get_stored_date,
                                              mocked_set_stored_date, monkeypatch):
    """ Test actually loading the program activity data """
    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False, 'local': False})

    mocked_get_pa_file.return_value = StringIO(
        """2000,000,111,0000,1111,Test Name,FY2015Q1"""
    )

    mocked_get_current_date.return_value = datetime.datetime(2017, 12, 31, 0, 0, 0)
    mocked_get_stored_date.return_value = datetime.datetime(2016, 12, 31, 0, 0, 0)
    mocked_set_stored_date.return_value = None

    with pytest.raises(SystemExit) as se:
        load_program_activity.load_program_activity_data('some_path')

    assert se.value.code == 4

@patch('dataactvalidator.scripts.load_program_activity.set_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_stored_pa_last_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_date_of_current_pa_upload')
@patch('dataactvalidator.scripts.load_program_activity.get_program_activity_file')
def test_load_program_activity_data_empty_file(mocked_get_pa_file, mocked_get_current_date, mocked_get_stored_date,
                                               mocked_set_stored_date, monkeypatch):
    """ Test actually loading the program activity data """
    monkeypatch.setattr(load_program_activity, 'CONFIG_BROKER', {'use_aws': False, 'local': False})

    mocked_get_pa_file.return_value = StringIO("")

    mocked_get_current_date.return_value = datetime.datetime(2017, 12, 31, 0, 0, 0)
    mocked_get_stored_date.return_value = datetime.datetime(2016, 12, 31, 0, 0, 0)
    mocked_set_stored_date.return_value = None

    with pytest.raises(SystemExit) as se:
        load_program_activity.load_program_activity_data('some_path')

    assert se.value.code == 4
<|endoftext|>


<commit_before>from common_fixtures import *  # NOQA
import re

def pytest_configure(config):
    cleanup()

def cleanup():
    logger.info('Running cleanup')
    sc = super_client(accounts())
    instance_name_format = re.compile('Test')
    # For cleaning up environment and instances that get disassociated
    # from services where deleted
    env_name_format = re.compile('Test')
    # instance_name_format_for_services =
    # re.compile('test[0-9]{1,6}_test[0-9]{1,6}_[0-9]*')

    to_delete_env = []
    for i in sc.list_environment(state='active'):
        try:
            if env_name_format.match(i.name):
                to_delete_env.append(i)
        except AttributeError:
            pass
    delete_all(sc, to_delete_env)
    logger.info("Environments Deleted")

    to_delete_lb = []
    for i in sc.list_loadBalancer(state='active'):
        try:
            if instance_name_format.match(i.name):
                to_delete_lb.append(i)
        except AttributeError:
            pass
    delete_all(sc, to_delete_lb)
    logger.info("LBs Deleted")

    to_delete_lb_config = []
    for i in sc.list_loadBalancerConfig(state='active'):
        try:
            if instance_name_format.match(i.name):
                to_delete_lb_config.append(i)
        except AttributeError:
            pass
    delete_all(sc, to_delete_lb_config)
    logger.info("LB Configs deleted")

    to_delete_lb_listener = []
    for i in sc.list_loadBalancerListener(state='active'):
        try:
            if instance_name_format.match(i.name):
                to_delete_lb_listener.append(i)
        except AttributeError:
            pass
    delete_all(sc, to_delete_lb_listener)
    logger.info("LB listeners deleted")

    to_delete = []
    for i in sc.list_instance(state='running'):
        try:
            if instance_name_format.match(i.name) or \
                    i.name.startswith("socat-test") or \
                    i.name.startswith("native-test") or \
                    i.name.startswith("target-native-test-") or \
                    i.name.startswith("rancher-compose"):
                to_delete.append(i)
        except AttributeError:
            pass

    delete_all(sc, to_delete)
    logger.info("Running Instances deleted")

    to_delete = []
    for i in sc.list_instance(state='stopped'):
        try:
            if i.name is not None:
                if instance_name_format.match(i.name) or \
                        i.name.startswith("native-test") or \
                        i.name.startswith("target-native-test-"):
                    to_delete.append(i)
        except AttributeError:
            pass

    delete_all(sc, to_delete)
    logger.info("Stopped instances deleted")
<commit_msg>Fixed conftest<commit_after>from common_fixtures import *  # NOQA
import re

def pytest_configure(config):
    cleanup()

def cleanup():
    logger.info('Running cleanup')
    sc = super_client(accounts())
    instance_name_format = re.compile('Test')
    # For cleaning up environment and instances that get disassociated
    # from services where deleted
    env_name_format = re.compile('Test')
    # instance_name_format_for_services =
    # re.compile('test[0-9]{1,6}_test[0-9]{1,6}_[0-9]*')

    to_delete_env = []
    for i in sc.list_environment(state='active'):
        try:
            if env_name_format.match(i.name):
                to_delete_env.append(i)
        except AttributeError:
            pass
    delete_all(sc, to_delete_env)

    to_delete = []
    for i in sc.list_instance(state='running'):
        try:
            if i.name is not None:
                if instance_name_format.match(i.name) or \
                        i.name.startswith("socat-test") or \
                        i.name.startswith("host-test") or \
                        i.name.startswith("native-test") or \
                        i.name.startswith("target-native-test-") or \
                        i.name.startswith("lb-test-client") or \
                        i.name.startswith("rancher-compose"):
                    to_delete.append(i)
        except AttributeError:
            pass

    delete_all(sc, to_delete)

    to_delete = []
    for i in sc.list_instance(state='stopped'):
        try:
            if i.name is not None:
                if instance_name_format.match(i.name) or \
                        i.name.startswith("native-test") or \
                        i.name.startswith("host-test") or \
                        i.name.startswith("target-native-test-"):
                    to_delete.append(i)
        except AttributeError:
            pass

    delete_all(sc, to_delete)

    # Delete all apiKeys created by test runs
    account = sc.list_project(uuid="adminProject")[0]
    for cred in account.credentials():
        if cred.kind == 'apiKey' and \
                instance_name_format.match(cred.publicValue) \
                and cred.state == "active":
            print cred.id
            cred = sc.wait_success(cred.deactivate())
            sc.delete(cred)<|endoftext|>


<commit_before>#!/usr/bin/python3

import logging
logging.basicConfig(level=logging.DEBUG)

from binascii import a2b_hex, b2a_hex
import bitcoin.txn
import bitcoin.varlen
import jsonrpc
import jsonrpcserver
import merkletree
from struct import pack
import sys
from time import time
from util import RejectedShare

pool = jsonrpc.ServiceProxy(sys.argv[1])

worklog = {}
currentwork = [None, 0, 0]

def makeMRD():
	mp = pool.getmemorypool()
	coinbase = a2b_hex(mp['coinbasetxn'])
	cbtxn = bitcoin.txn.Txn(coinbase)
	cbtxn.disassemble()
	cbtxn.originalCB = cbtxn.getCoinbase()
	txnlist = [cbtxn,] + list(map(bitcoin.txn.Txn, map(a2b_hex, mp['transactions'])))
	merkleTree = merkletree.MerkleTree(txnlist)
	merkleRoot = None
	prevBlock = a2b_hex(mp['previousblockhash'])[::-1]
	bits = a2b_hex(mp['bits'])[::-1]
	rollPrevBlk = False
	MRD = (merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk)
	if 'coinbase/append' in mp.get('mutable', ()):
		currentwork[:] = (MRD, time(), 0)
	else:
		currentwork[2] = 0
	return MRD

def getMRD():
	now = time()
	if currentwork[1] < now - 45:
		MRD = makeMRD()
	else:
		MRD = currentwork[0]
		currentwork[2] += 1

	(merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk) = MRD
	cbtxn = merkleTree.data[0]
	coinbase = cbtxn.originalCB + pack('>Q', currentwork[2]).lstrip(b'\0')
	if len(coinbase) > 100:
		if len(cbtxn.originalCB) > 100:
			raise RuntimeError('Pool gave us a coinbase that is too long!')
		currentwork[1] = 0
		return getMRD()
	cbtxn.setCoinbase(coinbase)
	cbtxn.assemble()
	merkleRoot = merkleTree.merkleRoot()
	MRD = (merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk)
	return MRD

def MakeWork(username):
	MRD = getMRD()
	(merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk) = MRD
	timestamp = pack('<L', int(time()))
	hdr = b'\1\0\0\0' + prevBlock + merkleRoot + timestamp + bits + b'ppmg'
	worklog[hdr[4:68]] = (MRD, time())
	return hdr

def SubmitShare(share):
	hdr = share['data'][:80]
	k = hdr[4:68]
	if k not in worklog:
		raise RejectedShare('LOCAL unknown-work')
	(MRD, issueT) = worklog[k]
	(merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk) = MRD
	cbtxn = merkleTree.data[0]
	cbtxn.setCoinbase(coinbase)
	cbtxn.assemble()
	blkdata = bitcoin.varlen.varlenEncode(len(merkleTree.data))
	for txn in merkleTree.data:
		blkdata += txn.data
	data = b2a_hex(hdr + blkdata).decode('utf8')
	if not pool.submitblock(data):
		currentwork[1] = 0
		raise RejectedShare('pool-rejected')

server = jsonrpcserver.JSONRPCServer()
server.getBlockHeader = MakeWork
server.receiveShare = SubmitShare
jsonrpcserver.JSONRPCListener(server, ('::ffff:127.0.0.1', 9332))

server.serve_forever()
<commit_msg>Add a "workid" key to getmemorypool, just in case it might be needed<commit_after>#!/usr/bin/python3

import logging
logging.basicConfig(level=logging.DEBUG)

from binascii import a2b_hex, b2a_hex
import bitcoin.txn
import bitcoin.varlen
import jsonrpc
import jsonrpcserver
import merkletree
from struct import pack
import sys
from time import time
from util import RejectedShare

pool = jsonrpc.ServiceProxy(sys.argv[1])

worklog = {}
currentwork = [None, 0, 0]

def makeMRD():
	mp = pool.getmemorypool()
	coinbase = a2b_hex(mp['coinbasetxn'])
	cbtxn = bitcoin.txn.Txn(coinbase)
	cbtxn.disassemble()
	cbtxn.originalCB = cbtxn.getCoinbase()
	txnlist = [cbtxn,] + list(map(bitcoin.txn.Txn, map(a2b_hex, mp['transactions'])))
	merkleTree = merkletree.MerkleTree(txnlist)
	merkleRoot = None
	prevBlock = a2b_hex(mp['previousblockhash'])[::-1]
	bits = a2b_hex(mp['bits'])[::-1]
	rollPrevBlk = False
	MRD = (merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk, mp)
	if 'coinbase/append' in mp.get('mutable', ()):
		currentwork[:] = (MRD, time(), 0)
	else:
		currentwork[2] = 0
	return MRD

def getMRD():
	now = time()
	if currentwork[1] < now - 45:
		MRD = makeMRD()
	else:
		MRD = currentwork[0]
		currentwork[2] += 1

	(merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk, mp) = MRD
	cbtxn = merkleTree.data[0]
	coinbase = cbtxn.originalCB + pack('>Q', currentwork[2]).lstrip(b'\0')
	if len(coinbase) > 100:
		if len(cbtxn.originalCB) > 100:
			raise RuntimeError('Pool gave us a coinbase that is too long!')
		currentwork[1] = 0
		return getMRD()
	cbtxn.setCoinbase(coinbase)
	cbtxn.assemble()
	merkleRoot = merkleTree.merkleRoot()
	MRD = (merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk, mp)
	return MRD

def MakeWork(username):
	MRD = getMRD()
	(merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk, mp) = MRD
	timestamp = pack('<L', int(time()))
	hdr = b'\1\0\0\0' + prevBlock + merkleRoot + timestamp + bits + b'ppmg'
	worklog[hdr[4:68]] = (MRD, time())
	return hdr

def SubmitShare(share):
	hdr = share['data'][:80]
	k = hdr[4:68]
	if k not in worklog:
		raise RejectedShare('LOCAL unknown-work')
	(MRD, issueT) = worklog[k]
	(merkleRoot, merkleTree, coinbase, prevBlock, bits, rollPrevBlk, mp) = MRD
	cbtxn = merkleTree.data[0]
	cbtxn.setCoinbase(coinbase)
	cbtxn.assemble()
	blkdata = bitcoin.varlen.varlenEncode(len(merkleTree.data))
	for txn in merkleTree.data:
		blkdata += txn.data
	data = b2a_hex(hdr + blkdata).decode('utf8')
	a = [data]
	if 'workid' in mp:
		a.append({'workid': mp['workid']})
	if not pool.submitblock(*a):
		currentwork[1] = 0
		raise RejectedShare('pool-rejected')

server = jsonrpcserver.JSONRPCServer()
server.getBlockHeader = MakeWork
server.receiveShare = SubmitShare
jsonrpcserver.JSONRPCListener(server, ('::ffff:127.0.0.1', 9332))

server.serve_forever()
<|endoftext|>


<commit_before>"""
Utilities and common tasks for wrapping the GMT modules.
"""
import textwrap
import functools

GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest'

COMMON_OPTIONS = {
    'R': '''\
        R : str or list
            *Required if this is the first plot command*.
            ``'xmin/xmax/ymin/ymax[+r][+uunit]'``.
            Specify the region of interest.''',
    'J': '''\
        J : str
            *Required if this is the first plot command*.
            Select map projection.''',
    'B': '''\
        B : str
            Set map boundary frame and axes attributes.''',
    'P': '''\
        P : bool
            Select “Portrait” plot orientation.''',
    'U': '''\
        U : bool or str
            Draw GMT time stamp logo on plot.''',
    'CPT': '''\
        C : str
           File name of a CPT file or ``C='color1,color2[,color3,...]'`` to
           build a linear continuous CPT from those colors automatically.''',
    'G': '''\
        G : str
            Select color or pattern for filling of symbols or polygons. Default
            is no fill.''',
}

def fmt_docstring(module_func):
    """
    Decorator to insert common text into module docstrings.

    Should be the last decorator (at the top).

    Use any of these placeholders in your docstring to have them substituted:

    * ``{gmt_module_docs}``: link to the GMT docs for that module. Assumes that
      the name of the GMT module is the same as the function name.
    * ``{aliases}``: Insert a section listing the parameter aliases defined by
      decorator ``use_alias``.

    The following are places for common parameter descriptions:

    * ``{R}``: R (region) option with 4 bounds
    * ``{J}``: J (projection)
    * ``{B}``: B (frame)
    * ``{P}``: P (portrait)
    * ``{U}``: U (insert time stamp)
    * ``{CPT}``: CPT (the color palette table)
    * ``{G}``: G (color)

    Parameters
    ----------
    module_func : function
        The module function.

    Returns
    -------
    module_func
        The same *module_func* but with the docstring formatted.

    Examples
    --------

    >>> @fmt_docstring
    ... @use_alias(R='region', J='projection')
    ... def gmtinfo(**kwargs):
    ...     '''
    ...     My nice module.
    ...
    ...     {gmt_module_docs}
    ...
    ...     Parameters
    ...     ----------
    ...     {R}
    ...     {J}
    ...
    ...     {aliases}
    ...     '''
    ...     pass
    >>> print(gmtinfo.__doc__)
    <BLANKLINE>
    My nice module.
    <BLANKLINE>
    Full option list at http://gmt.soest.hawaii.edu/doc/latest/gmtinfo.html
    <BLANKLINE>
    Parameters
    ----------
    R : str or list
        *Required if this is the first plot command*.
        ``'xmin/xmax/ymin/ymax[+r][+uunit]'``.
        Specify the region of interest.
    J : str
        *Required if this is the first plot command*.
        Select map projection.
    <BLANKLINE>
    **Aliases:**
    <BLANKLINE>
    - J = projection
    - R = region
    <BLANKLINE>

    """
    filler_text = {}

    url = "{}/{}.html".format(GMT_DOCS, module_func.__name__)
    text = "Full option list at"
    filler_text['gmt_module_docs'] = ' '.join([text, url])

    if hasattr(module_func, '_aliases'):
        aliases = ['**Aliases:**\n']
        for arg in sorted(module_func._aliases):
            alias = module_func._aliases[arg]
            aliases.append('- {} = {}'.format(arg, alias))
        filler_text['aliases'] = '\n'.join(aliases)

    for marker, text in COMMON_OPTIONS.items():
        # Remove the identation from the multiline strings so that it doesn't
        # mess up the original docstring
        filler_text[marker] = textwrap.dedent(text)

    # Dedent the docstring to make it all match the option text.
    docstring = textwrap.dedent(module_func.__doc__)

    module_func.__doc__ = docstring.format(**filler_text)

    return module_func

def kwargs2string(kwargs):
    """
    Transform keyword arguments into a GMT argument string.

    Parameters
    ----------
    kwargs : dict
        Parsed keyword arguments. Doesn't do any fancy conversions. Make sure
        all arguments can be cast to a string and inserted as is into the
        GMT argument string (that means no bools, lists, or arrays).

    Returns
    -------
    args : str
        The space-delimited argument string with '-' inserted before each
        keyword. The arguments are sorted alphabetically.

    Examples
    --------

    >>> print(kwargs2string(dict(R='1/2/3/4', J="X4i", P='', E=200)))
    -E200 -JX4i -P -R1/2/3/4

    """
    sorted_args = (
        '-{}{}'.format(key, kwargs[key])
        for key in sorted(kwargs)
    )
    arg_str = ' '.join(sorted_args)
    return arg_str

def use_alias(**aliases):
    """
    Decorator to add aliases to keyword arguments of a function.

    Use this decorator above the argument parsing decorators, usually only
    below ``fmt_docstring``.

    Replaces the aliases with their desired names before passing them along to
    the module function.

    Keywords passed to this decorator are the desired argument name and their
    value is the alias.

    Adds a dictionary attribute to the function with the aliases. Use in
    conjunction with ``fmt_docstring`` to insert a list of valid aliases in
    your docstring.

    Examples
    --------

    >>> @use_alias(R='region', J='projection')
    ... def my_module(**kwargs):
    ...     print('R =', kwargs['R'], 'J =', kwargs['J'])
    >>> my_module(R='bla', J='meh')
    R = bla J = meh
    >>> my_module(region='bla', J='meh')
    R = bla J = meh
    >>> my_module(R='bla', projection='meh')
    R = bla J = meh
    >>> my_module(region='bla', projection='meh')
    R = bla J = meh

    """

    def alias_decorator(module_func):
        """
        Decorator that replaces the aliases for arguments.
        """

        @functools.wraps(module_func)
        def new_module(*args, **kwargs):
            """
            New module that parses and replaces the registered aliases.
            """
            for arg, alias in aliases.items():
                if alias in kwargs:
                    kwargs[arg] = kwargs.pop(alias)
            return module_func(*args, **kwargs)

        new_module._aliases = aliases

        return new_module

    return alias_decorator

def parse_bools(module_func):
    """
    Parse boolean arguments and transform them into option strings.

    Decorator function transforms ``kwargs['P']`` from ``True`` into ``''``. If
    ``False``, remove the argument from ``kwargs``.

    Parameters
    ----------
    module_func : function
        The module function.

    Returns
    -------
    new_func
        A modified module that parses bools into strings before doing any work.

    Examples
    --------

    >>> @parse_bools
    ... def my_module(*args, **kwargs):
    ...     'My docstring'
    ...     print('{', end='')
    ...     print(', '.join(
    ...         "'{}': '{}'".format(k, kwargs[k]) for k in sorted(kwargs)),
    ...         end='')
    ...     print('}')
    >>> print(my_module.__doc__)
    My docstring
    >>> my_module(P=True)
    {'P': ''}
    >>> my_module(P=False)
    {}
    >>> my_module(A='something', P=True)
    {'A': 'something', 'P': ''}
    >>> my_module(A='something', P=False)
    {'A': 'something'}

    """

    @functools.wraps(module_func)
    def new_func(*args, **kwargs):
        "New function that parses bools before executing the module"
        new_kwargs = {}
        for arg, value in kwargs.items():
            if isinstance(value, bool):
                if value:
                    new_kwargs[arg] = ''
            else:
                new_kwargs[arg] = value
        return module_func(*args, **new_kwargs)

    return new_func

def parse_region(module_func):
    """
    Parse the region argument (R) before handing it off to the function.

    Decorator function that replaces R in the arguments dictionary with a
    string version that the C API will accept.

    Parameters
    ----------
    module_func : function
        The module function.

    Returns
    -------
    new_func
        A modified module that parses R into a string before doing any work.

    Examples
    --------

    >>> @parse_region
    ... def my_module(*args, **kwargs):
    ...     '''
    ...     My GMT module.
    ...     '''
    ...     print(kwargs)
    >>> my_module(R='1/2/3/4')
    {'R': '1/2/3/4'}
    >>> my_module(R=[1, 2, 3, 4])
    {'R': '1/2/3/4'}

    """

    @functools.wraps(module_func)
    def new_module(*args, **kwargs):
        """
        New function that parses R before executing the module.
        """
        if 'R' in kwargs:
            value = kwargs['R']
            if is_nonstr_iter(value):
                kwargs['R'] = '/'.join('{}'.format(item) for item in value)
        return module_func(*args, **kwargs)

    return new_module

def is_nonstr_iter(value):
    """
    Check if the value is not a string but is iterable (list, tuple, array)

    Parameters
    ----------
    value
        What you want to check.

    Returns
    -------
    is_iterable : bool
        Whether it is a non-string iterable or not.

    Examples
    --------

    >>> is_nonstr_iter('abc')
    False
    >>> is_nonstr_iter(10)
    False
    >>> is_nonstr_iter([1, 2, 3])
    True
    >>> is_nonstr_iter((1, 2, 3))
    True

    """
    try:
        [item for item in value]  # pylint: disable=pointless-statement
        is_iterable = True
    except TypeError:
        is_iterable = False
    return bool(not isinstance(value, str) and is_iterable)
<commit_msg>Linter failure corrections<commit_after>"""
Utilities and common tasks for wrapping the GMT modules.
"""
import textwrap
import functools

GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest'

COMMON_OPTIONS = {
    'R': '''\
        R : str or list
            *Required if this is the first plot command*.
            ``'xmin/xmax/ymin/ymax[+r][+uunit]'``.
            Specify the region of interest.''',
    'J': '''\
        J : str
            *Required if this is the first plot command*.
            Select map projection.''',
    'B': '''\
        B : str
            Set map boundary frame and axes attributes.''',
    'P': '''\
        P : bool
            Select “Portrait” plot orientation.''',
    'U': '''\
        U : bool or str
            Draw GMT time stamp logo on plot.''',
    'CPT': '''\
        C : str
           File name of a CPT file or ``C='color1,color2[,color3,...]'`` to
           build a linear continuous CPT from those colors automatically.''',
    'G': '''\
        G : str
            Select color or pattern for filling of symbols or polygons. Default
            is no fill.''',
}

def fmt_docstring(module_func):
    """
    Decorator to insert common text into module docstrings.

    Should be the last decorator (at the top).

    Use any of these placeholders in your docstring to have them substituted:

    * ``{gmt_module_docs}``: link to the GMT docs for that module. Assumes that
      the name of the GMT module is the same as the function name.
    * ``{aliases}``: Insert a section listing the parameter aliases defined by
      decorator ``use_alias``.

    The following are places for common parameter descriptions:

    * ``{R}``: R (region) option with 4 bounds
    * ``{J}``: J (projection)
    * ``{B}``: B (frame)
    * ``{P}``: P (portrait)
    * ``{U}``: U (insert time stamp)
    * ``{CPT}``: CPT (the color palette table)
    * ``{G}``: G (color)

    Parameters
    ----------
    module_func : function
        The module function.

    Returns
    -------
    module_func
        The same *module_func* but with the docstring formatted.

    Examples
    --------

    >>> @fmt_docstring
    ... @use_alias(R='region', J='projection')
    ... def gmtinfo(**kwargs):
    ...     '''
    ...     My nice module.
    ...
    ...     {gmt_module_docs}
    ...
    ...     Parameters
    ...     ----------
    ...     {R}
    ...     {J}
    ...
    ...     {aliases}
    ...     '''
    ...     pass
    >>> print(gmtinfo.__doc__)
    <BLANKLINE>
    My nice module.
    <BLANKLINE>
    Full option list at http://gmt.soest.hawaii.edu/doc/latest/gmtinfo.html
    <BLANKLINE>
    Parameters
    ----------
    R : str or list
        *Required if this is the first plot command*.
        ``'xmin/xmax/ymin/ymax[+r][+uunit]'``.
        Specify the region of interest.
    J : str
        *Required if this is the first plot command*.
        Select map projection.
    <BLANKLINE>
    **Aliases:**
    <BLANKLINE>
    - J = projection
    - R = region
    <BLANKLINE>

    """
    filler_text = {}

    url = "{}/{}.html".format(GMT_DOCS, module_func.__name__)
    text = "Full option list at"
    filler_text['gmt_module_docs'] = ' '.join([text, url])

    if hasattr(module_func, 'aliases'):
        aliases = ['**Aliases:**\n']
        for arg in sorted(module_func.aliases):
            alias = module_func.aliases[arg]
            aliases.append('- {} = {}'.format(arg, alias))
        filler_text['aliases'] = '\n'.join(aliases)

    for marker, text in COMMON_OPTIONS.items():
        # Remove the identation from the multiline strings so that it doesn't
        # mess up the original docstring
        filler_text[marker] = textwrap.dedent(text)

    # Dedent the docstring to make it all match the option text.
    docstring = textwrap.dedent(module_func.__doc__)

    module_func.__doc__ = docstring.format(**filler_text)

    return module_func

def kwargs2string(kwargs):
    """
    Transform keyword arguments into a GMT argument string.

    Parameters
    ----------
    kwargs : dict
        Parsed keyword arguments. Doesn't do any fancy conversions. Make sure
        all arguments can be cast to a string and inserted as is into the
        GMT argument string (that means no bools, lists, or arrays).

    Returns
    -------
    args : str
        The space-delimited argument string with '-' inserted before each
        keyword. The arguments are sorted alphabetically.

    Examples
    --------

    >>> print(kwargs2string(dict(R='1/2/3/4', J="X4i", P='', E=200)))
    -E200 -JX4i -P -R1/2/3/4

    """
    sorted_args = (
        '-{}{}'.format(key, kwargs[key])
        for key in sorted(kwargs)
    )
    arg_str = ' '.join(sorted_args)
    return arg_str

def use_alias(**aliases):
    """
    Decorator to add aliases to keyword arguments of a function.

    Use this decorator above the argument parsing decorators, usually only
    below ``fmt_docstring``.

    Replaces the aliases with their desired names before passing them along to
    the module function.

    Keywords passed to this decorator are the desired argument name and their
    value is the alias.

    Adds a dictionary attribute to the function with the aliases. Use in
    conjunction with ``fmt_docstring`` to insert a list of valid aliases in
    your docstring.

    Examples
    --------

    >>> @use_alias(R='region', J='projection')
    ... def my_module(**kwargs):
    ...     print('R =', kwargs['R'], 'J =', kwargs['J'])
    >>> my_module(R='bla', J='meh')
    R = bla J = meh
    >>> my_module(region='bla', J='meh')
    R = bla J = meh
    >>> my_module(R='bla', projection='meh')
    R = bla J = meh
    >>> my_module(region='bla', projection='meh')
    R = bla J = meh

    """

    def alias_decorator(module_func):
        """
        Decorator that replaces the aliases for arguments.
        """

        @functools.wraps(module_func)
        def new_module(*args, **kwargs):
            """
            New module that parses and replaces the registered aliases.
            """
            for arg, alias in aliases.items():
                if alias in kwargs:
                    kwargs[arg] = kwargs.pop(alias)
            return module_func(*args, **kwargs)

        new_module.aliases = aliases

        return new_module

    return alias_decorator

def parse_bools(module_func):
    """
    Parse boolean arguments and transform them into option strings.

    Decorator function transforms ``kwargs['P']`` from ``True`` into ``''``. If
    ``False``, remove the argument from ``kwargs``.

    Parameters
    ----------
    module_func : function
        The module function.

    Returns
    -------
    new_func
        A modified module that parses bools into strings before doing any work.

    Examples
    --------

    >>> @parse_bools
    ... def my_module(*args, **kwargs):
    ...     'My docstring'
    ...     print('{', end='')
    ...     print(', '.join(
    ...         "'{}': '{}'".format(k, kwargs[k]) for k in sorted(kwargs)),
    ...         end='')
    ...     print('}')
    >>> print(my_module.__doc__)
    My docstring
    >>> my_module(P=True)
    {'P': ''}
    >>> my_module(P=False)
    {}
    >>> my_module(A='something', P=True)
    {'A': 'something', 'P': ''}
    >>> my_module(A='something', P=False)
    {'A': 'something'}

    """

    @functools.wraps(module_func)
    def new_func(*args, **kwargs):
        "New function that parses bools before executing the module"
        new_kwargs = {}
        for arg, value in kwargs.items():
            if isinstance(value, bool):
                if value:
                    new_kwargs[arg] = ''
            else:
                new_kwargs[arg] = value
        return module_func(*args, **new_kwargs)

    return new_func

def parse_region(module_func):
    """
    Parse the region argument (R) before handing it off to the function.

    Decorator function that replaces R in the arguments dictionary with a
    string version that the C API will accept.

    Parameters
    ----------
    module_func : function
        The module function.

    Returns
    -------
    new_func
        A modified module that parses R into a string before doing any work.

    Examples
    --------

    >>> @parse_region
    ... def my_module(*args, **kwargs):
    ...     '''
    ...     My GMT module.
    ...     '''
    ...     print(kwargs)
    >>> my_module(R='1/2/3/4')
    {'R': '1/2/3/4'}
    >>> my_module(R=[1, 2, 3, 4])
    {'R': '1/2/3/4'}

    """

    @functools.wraps(module_func)
    def new_module(*args, **kwargs):
        """
        New function that parses R before executing the module.
        """
        if 'R' in kwargs:
            value = kwargs['R']
            if is_nonstr_iter(value):
                kwargs['R'] = '/'.join('{}'.format(item) for item in value)
        return module_func(*args, **kwargs)

    return new_module

def is_nonstr_iter(value):
    """
    Check if the value is not a string but is iterable (list, tuple, array)

    Parameters
    ----------
    value
        What you want to check.

    Returns
    -------
    is_iterable : bool
        Whether it is a non-string iterable or not.

    Examples
    --------

    >>> is_nonstr_iter('abc')
    False
    >>> is_nonstr_iter(10)
    False
    >>> is_nonstr_iter([1, 2, 3])
    True
    >>> is_nonstr_iter((1, 2, 3))
    True

    """
    try:
        [item for item in value]  # pylint: disable=pointless-statement
        is_iterable = True
    except TypeError:
        is_iterable = False
    return bool(not isinstance(value, str) and is_iterable)
<|endoftext|>


<commit_before>import flask

# from flask.ext import openid

from steam_friends import ext, models

blueprint = flask.Blueprint('auth', __name__)

@ext.oid.after_login
def after_login(resp):
    flask.session['openid'] = resp.identity_url
    steamid = models.SteamUser.id_from_openid(resp.identity_url)
    flask.g.steamid = steamid
    flask.g.steam_user = u = models.SteamUser.get_user(steamid)
    flask.flash('Welcome, {}!'.format(u), 'info')
    return flask.redirect(ext.oid.get_next_url())

@blueprint.route('/login', methods=['GET', 'POST'])
@ext.oid.loginhandler
def login():
    if flask.g.steam_user is not None:
        return flask.redirect(ext.oid.get_next_url())
    if flask.request.method == 'POST':
        url = openid.COMMON_PROVIDERS['steam']  # 'https://steamcommunity.com/openid'
        return ext.oid.try_login(url)  # 'http://steamcommunity.com/openid')
    return flask.render_template(
        'login.html',
        next=ext.oid.get_next_url(),
        error=ext.oid.fetch_error(),
    )

@blueprint.route('/logout')
def logout():
    flask.session.pop('openid', None)
    flask.flash(u'You were signed out', 'info')
    return flask.redirect(ext.oid.get_next_url())

@blueprint.before_app_request
def lookup_current_user():
    flask.g.steam_user = None
    if 'openid' in flask.session:
        steamid = models.SteamUser.id_from_openid(flask.session['openid'])
        flask.g.steamid = steamid
        flask.g.steam_user = models.SteamUser.get_user(steamid)

@ext.oid.errorhandler
def on_error(message):
    flask.flash(u'Login Error: ' + message, 'warning')
<commit_msg>uncomment openid<commit_after>import flask

from flask.ext import openid

from steam_friends import ext, models

blueprint = flask.Blueprint('auth', __name__)

@ext.oid.after_login
def after_login(resp):
    flask.session['openid'] = resp.identity_url
    steamid = models.SteamUser.id_from_openid(resp.identity_url)
    flask.g.steamid = steamid
    flask.g.steam_user = u = models.SteamUser.get_user(steamid)
    flask.flash('Welcome, {}!'.format(u), 'info')
    return flask.redirect(ext.oid.get_next_url())

@blueprint.route('/login', methods=['GET', 'POST'])
@ext.oid.loginhandler
def login():
    if flask.g.steam_user is not None:
        return flask.redirect(ext.oid.get_next_url())
    if flask.request.method == 'POST':
        url = openid.COMMON_PROVIDERS['steam']  # 'https://steamcommunity.com/openid'
        return ext.oid.try_login(url)  # 'http://steamcommunity.com/openid')
    return flask.render_template(
        'login.html',
        next=ext.oid.get_next_url(),
        error=ext.oid.fetch_error(),
    )

@blueprint.route('/logout')
def logout():
    flask.session.pop('openid', None)
    flask.flash(u'You were signed out', 'info')
    return flask.redirect(ext.oid.get_next_url())

@blueprint.before_app_request
def lookup_current_user():
    flask.g.steam_user = None
    if 'openid' in flask.session:
        steamid = models.SteamUser.id_from_openid(flask.session['openid'])
        flask.g.steamid = steamid
        flask.g.steam_user = models.SteamUser.get_user(steamid)

@ext.oid.errorhandler
def on_error(message):
    flask.flash(u'Login Error: ' + message, 'warning')
<|endoftext|>


<commit_before>#!/usr/bin/python3
import string
import random
from random import randint

def generate(fragmentsDir, genomeDir, id):
	def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
	    return ''.join(random.choice(chars) for _ in range(size))

	# Gera sequência
	genome = id_generator(1000, "ACTG")

	# Escreve sequência
	file = open(genomeDir + str(id) + ".txt", "w")
	file.write(genome)
	file.close()

	file = open(fragmentsDir + str(id) + ".txt", "w")
	collection = [genome, genome, genome]

	print("Tamanho Sequência Original:", len(genome))

	added = []

	for i in collection:
	  x = 0
	  while (x < len(i)):
	    t = randint(25,40)
	    fragment = i[x:x+t]
	    x=x+t

	    if fragment not in added:
		    file.write(fragment + "\n")
		    added.append(fragment)
	file.close()
<commit_msg>Usando seed no gerador aleatorio de sequencias, para controlar os resultados<commit_after>#!/usr/bin/python3
import string
import random
from random import randint

def generate(fragmentsDir, genomeDir, id):

    random.seed(1234 * id);

    def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))

    # Gera sequência
    genome = id_generator(1000, "ACTG")

    # Escreve sequência
    file = open(genomeDir + str(id) + ".txt", "w")
    file.write(genome)
    file.close()

    file = open(fragmentsDir + str(id) + ".txt", "w")
    collection = [genome, genome, genome]

    print("Tamanho Sequência Original:", len(genome))

    added = []

    for i in collection:
        x = 0
        while (x < len(i)):
            t = randint(25,40)
            fragment = i[x:x+t]
            x=x+t

        if fragment not in added:
            file.write(fragment + "\n")
            added.append(fragment)
    file.close()
<|endoftext|>


<commit_before>__version__ = '0.9.0a3'
<commit_msg>prepare release<commit_after>__version__ = '0.9.0'
<|endoftext|>


<commit_before># coding: utf-8

import base64

from .memo import HashMemo, IdMemo, NoneMemo, RetHashMemo, TextMemo
from .operation import (
    CreateAccount, ManageOffer, AccountMerge, AllowTrust, ChangeTrust,
    CreatePassiveOffer, Inflation, ManageData, PathPayment, Payment,
    SetOptions)
from .stellarxdr import Xdr
from .utils import account_xdr_object, decode_check, encode_check

# TODO: Consider making a part of the Transaction object?
FEE = 100

class Transaction(object):
    """The :class:`Transaction` object, which represents a transaction
    on Stellar's network.

    A transaction contains a list of operations (see :class:`Operation
    <stellar_base.operation.Operation>`),
    which are all executed in order as one ACID transaction, along with an
    associated source account, fee, account sequence number, list of
    signatures, both an optional memo and an optional timebound. Typically a
    :class:`Transaction` is placed in a :class:`TransactionEnvelope
    <stellar_base.transaction_envelope.TransactionEnvelope>` which is
    then signed before being sent over the network.

    For more information on Transactions in Stellar, see `Stellar's guide
    on transactions`_.

    .. _Stellar's guide on transactions:
        https://www.stellar.org/developers/guides/concepts/transactions.html

    :param str source: A strkey encoded account ID (public key) of the source
        account for the transaction.
    :param dict opts: A dict that contains the primary components of the
        transaction. The following keys are searched from the dict:

        * opts.sequence - The current sequence number of the source account.
          The sequence number is incremented by 1 automatically, as is
          necessary for a new transaction for a given source account.
        * opts.time_bounds - A list of two Unix timestamps representing the
          lower and upper bound of when a given transaction will be valid.
          NOTE: This should likely be an object containing a minTime and
          maxTime attribute instead, and the implementation may change.
        * opts.memo - The memo being sent with the transaction, being
          represented as one of the subclasses of the
          :class:`Memo <stellar_base.memo.Memo>` object.
          Defaults to :class:`NoneMemo <stellar_base.memo.NoneMemo>`.
        * opts.fee - The fee amount for the transaction, which should equal
          BASE_FEE (currently 100 stroops) multiplied by the number of
          operations in the transaction. See `Stellar's latest documentation
          on fees
          <https://www.stellar.org/developers/guides/concepts/fees.html#transaction-fee>`_
          for more information.
        * opts.operations: A list of :class:`Operation
          <stellar_base.operation.Operation>` objects (typically its
          subclasses as defined in :mod:`stellar_base.operation` to be
          included in the transaction. By default this is an empty list.

    """
    # TODO: Why is this passed in as a dictionary (outside of conforming to the
    # JavaScript SDK)? Wouldn't it make more sense to use optional arguments?
    # Several of the components in opts are also required. Especially because
    # they're just being shoved into typed attributes anyways?
    def __init__(self, source, opts):
        # TODO: Remove these assert statements and throw more appropriate
        # exceptions.
        assert source is not None
        assert decode_check('account', source)
        assert type(opts) is dict
        assert opts.get('sequence') is not None

        self.source = source
        self.sequence = int(opts.get('sequence')) + 1
        # FIXME: Shouldn't timebounds be an object that contains minTime and
        # maxTime fields?
        self.time_bounds = opts.get('timeBounds', [])
        self.memo = opts.get('memo', NoneMemo())
        self.fee = int(opts['fee']) if 'fee' in opts else FEE
        self.operations = opts.get('operations', [])

    def add_operation(self, operation):
        """Add an :class:`Operation <stellar_base.operation.Operation>` to
        this transaction.

        This method will only add an operation if it is not already in the
        transaction's list of operations, i.e. every operation in the
        transaction should be unique.

        :param Operation operation: The operation to add to this transaction.

        """
        if operation not in self.operations:
            self.operations.append(operation)

    def to_xdr_object(self):
        """Creates an XDR Transaction object that represents this
        :class:`Transaction`.

        """
        source_account = account_xdr_object(self.source)
        memo = self.memo.to_xdr_object()
        operations = [o.to_xdr_object() for o in self.operations]
        ext = Xdr.nullclass()
        ext.v = 0
        return Xdr.types.Transaction(
            source_account, self.fee, self.sequence, self.time_bounds, memo,
            operations, ext)

    def xdr(self):
        """Packs and base64 encodes this :class:`Transaction` as an XDR
        string.

        """
        tx = Xdr.StellarXDRPacker()
        tx.pack_Transaction(self.to_xdr_object())
        return base64.b64encode(tx.get_buffer())

    @classmethod
    def from_xdr_object(cls, tx_xdr_object):
        """Create a :class:`Transaction` object from a Transaction XDR
        object.

        """
        source = encode_check('account', tx_xdr_object.sourceAccount.ed25519)
        sequence = tx_xdr_object.seqNum - 1
        time_bounds = tx_xdr_object.timeBounds  # TODO test

        memo_type = tx_xdr_object.memo.type
        memo_switch = tx_xdr_object.memo.switch
        if memo_type == Xdr.const.MEMO_TEXT:
            memo = TextMemo(memo_switch)
        elif memo_type == Xdr.const.MEMO_ID:
            memo = IdMemo(memo_switch)
        elif memo_type == Xdr.const.MEMO_HASH:
            memo = HashMemo(memo_switch)
        elif memo_type == Xdr.const.MEMO_RETURN:
            memo = RetHashMemo(memo_switch)
        else:
            memo = NoneMemo()

        fee = tx_xdr_object.fee

        operations = []
        ops = tx_xdr_object.operations
        for op in ops:
            if op.type == Xdr.const.CREATE_ACCOUNT:
                operations.append(CreateAccount.from_xdr_object(op))
            elif op.type == Xdr.const.PAYMENT:
                operations.append(Payment.from_xdr_object(op))
            elif op.type == Xdr.const.PATH_PAYMENT:
                operations.append(PathPayment.from_xdr_object(op))
            elif op.type == Xdr.const.CHANGE_TRUST:
                operations.append(ChangeTrust.from_xdr_object(op))
            elif op.type == Xdr.const.ALLOW_TRUST:
                operations.append(AllowTrust.from_xdr_object(op))
            elif op.type == Xdr.const.SET_OPTIONS:
                operations.append(SetOptions.from_xdr_object(op))
            elif op.type == Xdr.const.MANAGE_OFFER:
                operations.append(ManageOffer.from_xdr_object(op))
            elif op.type == Xdr.const.CREATE_PASSIVE_OFFER:
                operations.append(CreatePassiveOffer.from_xdr_object(op))
            elif op.type == Xdr.const.ACCOUNT_MERGE:
                operations.append(AccountMerge.from_xdr_object(op))
            elif op.type == Xdr.const.INFLATION:
                operations.append(Inflation.from_xdr_object(op))
            elif op.type == Xdr.const.MANAGE_DATA:
                operations.append(ManageData.from_xdr_object(op))

        return cls(
            source, {
                'sequence': sequence,
                'timeBounds': time_bounds,
                'memo': memo,
                'fee': fee,
                'operations': operations
            })
<commit_msg>fix: import from xdr error(with text memo)<commit_after># coding: utf-8

import base64

from .memo import HashMemo, IdMemo, NoneMemo, RetHashMemo, TextMemo
from .operation import (
    CreateAccount, ManageOffer, AccountMerge, AllowTrust, ChangeTrust,
    CreatePassiveOffer, Inflation, ManageData, PathPayment, Payment,
    SetOptions)
from .stellarxdr import Xdr
from .utils import account_xdr_object, decode_check, encode_check

# TODO: Consider making a part of the Transaction object?
FEE = 100

class Transaction(object):
    """The :class:`Transaction` object, which represents a transaction
    on Stellar's network.

    A transaction contains a list of operations (see :class:`Operation
    <stellar_base.operation.Operation>`),
    which are all executed in order as one ACID transaction, along with an
    associated source account, fee, account sequence number, list of
    signatures, both an optional memo and an optional timebound. Typically a
    :class:`Transaction` is placed in a :class:`TransactionEnvelope
    <stellar_base.transaction_envelope.TransactionEnvelope>` which is
    then signed before being sent over the network.

    For more information on Transactions in Stellar, see `Stellar's guide
    on transactions`_.

    .. _Stellar's guide on transactions:
        https://www.stellar.org/developers/guides/concepts/transactions.html

    :param str source: A strkey encoded account ID (public key) of the source
        account for the transaction.
    :param dict opts: A dict that contains the primary components of the
        transaction. The following keys are searched from the dict:

        * opts.sequence - The current sequence number of the source account.
          The sequence number is incremented by 1 automatically, as is
          necessary for a new transaction for a given source account.
        * opts.time_bounds - A list of two Unix timestamps representing the
          lower and upper bound of when a given transaction will be valid.
          NOTE: This should likely be an object containing a minTime and
          maxTime attribute instead, and the implementation may change.
        * opts.memo - The memo being sent with the transaction, being
          represented as one of the subclasses of the
          :class:`Memo <stellar_base.memo.Memo>` object.
          Defaults to :class:`NoneMemo <stellar_base.memo.NoneMemo>`.
        * opts.fee - The fee amount for the transaction, which should equal
          BASE_FEE (currently 100 stroops) multiplied by the number of
          operations in the transaction. See `Stellar's latest documentation
          on fees
          <https://www.stellar.org/developers/guides/concepts/fees.html#transaction-fee>`_
          for more information.
        * opts.operations: A list of :class:`Operation
          <stellar_base.operation.Operation>` objects (typically its
          subclasses as defined in :mod:`stellar_base.operation` to be
          included in the transaction. By default this is an empty list.

    """
    # TODO: Why is this passed in as a dictionary (outside of conforming to the
    # JavaScript SDK)? Wouldn't it make more sense to use optional arguments?
    # Several of the components in opts are also required. Especially because
    # they're just being shoved into typed attributes anyways?
    def __init__(self, source, opts):
        # TODO: Remove these assert statements and throw more appropriate
        # exceptions.
        assert source is not None
        assert decode_check('account', source)
        assert type(opts) is dict
        assert opts.get('sequence') is not None

        self.source = source
        self.sequence = int(opts.get('sequence')) + 1
        # FIXME: Shouldn't timebounds be an object that contains minTime and
        # maxTime fields?
        self.time_bounds = opts.get('timeBounds', [])
        self.memo = opts.get('memo', NoneMemo())
        self.fee = int(opts['fee']) if 'fee' in opts else FEE
        self.operations = opts.get('operations', [])

    def add_operation(self, operation):
        """Add an :class:`Operation <stellar_base.operation.Operation>` to
        this transaction.

        This method will only add an operation if it is not already in the
        transaction's list of operations, i.e. every operation in the
        transaction should be unique.

        :param Operation operation: The operation to add to this transaction.

        """
        if operation not in self.operations:
            self.operations.append(operation)

    def to_xdr_object(self):
        """Creates an XDR Transaction object that represents this
        :class:`Transaction`.

        """
        source_account = account_xdr_object(self.source)
        memo = self.memo.to_xdr_object()
        operations = [o.to_xdr_object() for o in self.operations]
        ext = Xdr.nullclass()
        ext.v = 0
        return Xdr.types.Transaction(
            source_account, self.fee, self.sequence, self.time_bounds, memo,
            operations, ext)

    def xdr(self):
        """Packs and base64 encodes this :class:`Transaction` as an XDR
        string.

        """
        tx = Xdr.StellarXDRPacker()
        tx.pack_Transaction(self.to_xdr_object())
        return base64.b64encode(tx.get_buffer())

    @classmethod
    def from_xdr_object(cls, tx_xdr_object):
        """Create a :class:`Transaction` object from a Transaction XDR
        object.

        """
        source = encode_check('account', tx_xdr_object.sourceAccount.ed25519)
        sequence = tx_xdr_object.seqNum - 1
        time_bounds = tx_xdr_object.timeBounds  # TODO test

        memo_type = tx_xdr_object.memo.type
        memo_switch = tx_xdr_object.memo.switch
        if memo_type == Xdr.const.MEMO_TEXT:
            memo = TextMemo(memo_switch.decode())
        elif memo_type == Xdr.const.MEMO_ID:
            memo = IdMemo(memo_switch)
        elif memo_type == Xdr.const.MEMO_HASH:
            memo = HashMemo(memo_switch)
        elif memo_type == Xdr.const.MEMO_RETURN:
            memo = RetHashMemo(memo_switch)
        else:
            memo = NoneMemo()

        fee = tx_xdr_object.fee

        operations = []
        ops = tx_xdr_object.operations
        for op in ops:
            if op.type == Xdr.const.CREATE_ACCOUNT:
                operations.append(CreateAccount.from_xdr_object(op))
            elif op.type == Xdr.const.PAYMENT:
                operations.append(Payment.from_xdr_object(op))
            elif op.type == Xdr.const.PATH_PAYMENT:
                operations.append(PathPayment.from_xdr_object(op))
            elif op.type == Xdr.const.CHANGE_TRUST:
                operations.append(ChangeTrust.from_xdr_object(op))
            elif op.type == Xdr.const.ALLOW_TRUST:
                operations.append(AllowTrust.from_xdr_object(op))
            elif op.type == Xdr.const.SET_OPTIONS:
                operations.append(SetOptions.from_xdr_object(op))
            elif op.type == Xdr.const.MANAGE_OFFER:
                operations.append(ManageOffer.from_xdr_object(op))
            elif op.type == Xdr.const.CREATE_PASSIVE_OFFER:
                operations.append(CreatePassiveOffer.from_xdr_object(op))
            elif op.type == Xdr.const.ACCOUNT_MERGE:
                operations.append(AccountMerge.from_xdr_object(op))
            elif op.type == Xdr.const.INFLATION:
                operations.append(Inflation.from_xdr_object(op))
            elif op.type == Xdr.const.MANAGE_DATA:
                operations.append(ManageData.from_xdr_object(op))

        return cls(
            source, {
                'sequence': sequence,
                'timeBounds': time_bounds,
                'memo': memo,
                'fee': fee,
                'operations': operations
            })
<|endoftext|>


<commit_before>from . import kv
from os.path import dirname, normpath, splitext, isfile
import re
import sublime

_fn = re.compile(r'^(?P<fn>.+?)(?:[:](?P<line>[\d+]+)(?:[:](?P<column>[\d+]+))?)?\s*$')
_vfn_id = re.compile(r'gs\.view#(\d+)')

class V(object):
	def __init__(self, view, win=None):
		self.v = view
		self.w = win

	def temp(self):
		if self.v is None:
			return False

		return not self.perma()

	def perma(self):
		if self.v is None:
			return False

		win = self.v.window()
		if win is None:
			return False

		if self.v not in win.views():
			return False

		vs = self.v.settings()
		if vs.get('is_widget') or vs.get('9o'):
			return False

		return True

	def fn(self):
		if self.v is None:
			return ''

		return self.v.file_name() or ''

	def splitext(self):
		return splitext(self.fn())

	def ext(self):
		return splitext(self.fn())[1]

	def vfn(self):
		if self.v is None:
			return ''

		fn = self.fn()
		if fn:
			return fn

		fn = self.v.name()
		if fn:
			fn = fn.replace(' ', '_')
		else:
			fn = 'sublime.go'

		return 'gs.view#%s,%s' % (self.v.id(), fn)

	def dir(self):
		return dirname(normpath(self.fn()))

	def src(self):
		if self.v is None:
			return ''

		return self.v.substr(sublime.Region(0, self.v.size()))

	def size(self):
		return self.v.size() if self.v is not None else 0

	def is_empty(self):
		if self.v is None:
			return True

		return self.v.find(r'\S', 0) is not None

	def scope_name(self, pos=0):
		if self.v is None:
			return ''

		return self.v.scope_name(pos)

	def view(self):
		return self.v

	def window(self):
		if self.v is None:
			return self.w

		return self.v.window()

	def has_view(self):
		return self.v is not None

	def has_window(self):
		return self.window() is not None

	def sibling_views(self):
		win = self.window()
		if win is not None:
			return win.views()

		return []

	def setting(self, k, default=None):
		if self.v is not None:
			return self.v.settings().get(k, default)

		return default

	def folders(self):
		try:
			return self.window().folders()
		except Exception:
			return []

	def sel(self, i=0):
		return sel(self.v, i)

	def rowcol(self):
		return rowcol(self.v)

	def write(self, s, pt=-1, ctx='', interp=False, scope='', outlined=False):
		if not self.has_view():
			return False

		self.v.run_command('gs_write', {
			's': s,
			'pt': pt,
			'ctx': ctx,
			'interp': interp,
			'scope': scope,
			'outlined': outlined,
		})
		return True

	def focus(self, row=0, col=0, pat='^package ', cb=None):
		win = self.window()
		view = self.view()
		if None in (win, view):
			if cb:
				cb(False)
			return

		if self.v.is_loading():
			sublime.set_timeout(lambda: self.focus(row=row, col=col, pat=pat, cb=cb), 100)
			return

		win.focus_view(view)
		if row <= 0 and col <= 0 and pat:
			r = view.find(pat, 0)
			if r:
				row, col = view.rowcol(r.begin())

		view.run_command("gs_goto_row_col", { "row": row, "col": col })
		if cb:
			cb(True)

def ve_replace(view, edit, begin, end, s):
	view.replace(edit, sublime.Region(begin, end), s)

def ve_write(view, edit, s, pt=-1, ctx='', interp=False, scope='', outlined=False):
	if not s:
		return

	n = view.size()
	rl = view.get_regions(ctx) if ctx else []
	ep = int(pt)
	if ep < 0:
		ep = rl[-1].end() if rl else n

	# todo: maybe make this behave more like a real console and handle \b
	if interp and s.startswith('\r'):
		s = s[1:]
		lr = view.line(ep)
		r = sublime.Region(lr.begin(), min(lr.begin()+len(s), lr.end()))
		view.replace(edit, r, s)
	else:
		view.insert(edit, ep, s)

	if ctx:
		sp = rl[0].begin() if rl else ep
		ep += view.size() - n
		flags = sublime.DRAW_OUTLINED if outlined else sublime.HIDDEN
		view.add_regions(ctx, [sublime.Region(sp, ep)], scope, '', flags)

def active(win=None, view=None):
	if view is None:
		if win is None:
			win = sublime.active_window()

		if win is not None:
			view = win.active_view()

	return V(view)

def open(fn='', id=-1, view=None, win=None):
	vv, loc = find_loc(fn=fn, id=id, view=view, win=win)
	if not vv.has_view() and isfile(loc.fn):
		if win is None:
			win = sublime.active_window()
		vv = V(win.open_file(loc.fn), win=win)

	if vv.has_view():
		vv.focus(loc.row, loc.col)

	return vv

def find(fn='', id=-1, view=None, win=None):
	vv, _ = find_loc(fn=fn, id=id, view=view, win=win)
	return vv

def find_loc(fn='', id=-1, view=None, win=None):
	loc = mk_loc()
	if view is not None:
		return (V(view, win=win), loc)

	match = None
	if id >= 0:
		match = lambda v: v.id() == id
	else:
		loc = parse(fn)
		if loc.ok:
			if loc.id >= 0:
				match = lambda v: v.id() == loc.id
			else:
				match = lambda v: v.file_name() == loc.fn
		else:
			match = lambda v: v.file_name() == fn

	if win is None:
		win = sublime.active_window()

	for v in win.views():
		if match(v):
			return (V(v, win=win), loc)

	return (V(None, win=win), loc)

def sel(view, i=0):
	try:
		s = view.sel()
		if s is not None and i < len(s):
			return s[i]
	except Exception:
		pass

	return sublime.Region(0, 0)

def rowcol(view):
	try:
		return view.rowcol(sel(view).begin())
	except Exception:
		return (0, 0)

def mk_loc():
	return kv.O(
		ok=False,
		id=-1,
		fn='',
		row=0,
		col=0,
		pos=''
	)

def get_num(m, k):
	try:
		return int(m.get(k))
	except Exception:
		return 0

def parse(s):
	loc = mk_loc()
	m = _fn.search(s or '')
	if m:
		m = m.groupdict()
		loc.ok = True
		loc.id = get_num(m, 'id')
		loc.row = max(0, get_num(m, 'line')-1)
		loc.col = max(0, get_num(m, 'column')-1)
		loc.pos = '%s:%s' % (loc.row, loc.col)
		loc.fn = m.get('fn', '')

		vm = _vfn_id.search(loc.fn)
		if vm:
			loc.id = int(vm.group(1))
			loc.fn = ''

	return loc

def is_vfn(s):
	return 'gs.view#' in s

def gs_init(m={}):
	pass
<commit_msg>* revert the \r handling to replace the whole line.     there's no notion of a cursor position and treating it like a terminal     results garbage data if we ever get partial data<commit_after>from . import kv
from os.path import dirname, normpath, splitext, isfile
import re
import sublime

_fn = re.compile(r'^(?P<fn>.+?)(?:[:](?P<line>[\d+]+)(?:[:](?P<column>[\d+]+))?)?\s*$')
_vfn_id = re.compile(r'gs\.view#(\d+)')

class V(object):
	def __init__(self, view, win=None):
		self.v = view
		self.w = win

	def temp(self):
		if self.v is None:
			return False

		return not self.perma()

	def perma(self):
		if self.v is None:
			return False

		win = self.v.window()
		if win is None:
			return False

		if self.v not in win.views():
			return False

		vs = self.v.settings()
		if vs.get('is_widget') or vs.get('9o'):
			return False

		return True

	def fn(self):
		if self.v is None:
			return ''

		return self.v.file_name() or ''

	def splitext(self):
		return splitext(self.fn())

	def ext(self):
		return splitext(self.fn())[1]

	def vfn(self):
		if self.v is None:
			return ''

		fn = self.fn()
		if fn:
			return fn

		fn = self.v.name()
		if fn:
			fn = fn.replace(' ', '_')
		else:
			fn = 'sublime.go'

		return 'gs.view#%s,%s' % (self.v.id(), fn)

	def dir(self):
		return dirname(normpath(self.fn()))

	def src(self):
		if self.v is None:
			return ''

		return self.v.substr(sublime.Region(0, self.v.size()))

	def size(self):
		return self.v.size() if self.v is not None else 0

	def is_empty(self):
		if self.v is None:
			return True

		return self.v.find(r'\S', 0) is not None

	def scope_name(self, pos=0):
		if self.v is None:
			return ''

		return self.v.scope_name(pos)

	def view(self):
		return self.v

	def window(self):
		if self.v is None:
			return self.w

		return self.v.window()

	def has_view(self):
		return self.v is not None

	def has_window(self):
		return self.window() is not None

	def sibling_views(self):
		win = self.window()
		if win is not None:
			return win.views()

		return []

	def setting(self, k, default=None):
		if self.v is not None:
			return self.v.settings().get(k, default)

		return default

	def folders(self):
		try:
			return self.window().folders()
		except Exception:
			return []

	def sel(self, i=0):
		return sel(self.v, i)

	def rowcol(self):
		return rowcol(self.v)

	def write(self, s, pt=-1, ctx='', interp=False, scope='', outlined=False):
		if not self.has_view():
			return False

		self.v.run_command('gs_write', {
			's': s,
			'pt': pt,
			'ctx': ctx,
			'interp': interp,
			'scope': scope,
			'outlined': outlined,
		})
		return True

	def focus(self, row=0, col=0, pat='^package ', cb=None):
		win = self.window()
		view = self.view()
		if None in (win, view):
			if cb:
				cb(False)
			return

		if self.v.is_loading():
			sublime.set_timeout(lambda: self.focus(row=row, col=col, pat=pat, cb=cb), 100)
			return

		win.focus_view(view)
		if row <= 0 and col <= 0 and pat:
			r = view.find(pat, 0)
			if r:
				row, col = view.rowcol(r.begin())

		view.run_command("gs_goto_row_col", { "row": row, "col": col })
		if cb:
			cb(True)

def ve_replace(view, edit, begin, end, s):
	view.replace(edit, sublime.Region(begin, end), s)

def ve_write(view, edit, s, pt=-1, ctx='', interp=False, scope='', outlined=False):
	if not s:
		return

	n = view.size()
	rl = view.get_regions(ctx) if ctx else []
	ep = int(pt)
	if ep < 0:
		ep = rl[-1].end() if rl else n

	# todo: maybe make this behave more like a real console and handle \b
	if interp and s.startswith('\r'):
		view.replace(edit, view.line(ep), s[1:])
	else:
		view.insert(edit, ep, s)

	if ctx:
		sp = rl[0].begin() if rl else ep
		ep += view.size() - n
		flags = sublime.DRAW_OUTLINED if outlined else sublime.HIDDEN
		view.add_regions(ctx, [sublime.Region(sp, ep)], scope, '', flags)

def active(win=None, view=None):
	if view is None:
		if win is None:
			win = sublime.active_window()

		if win is not None:
			view = win.active_view()

	return V(view)

def open(fn='', id=-1, view=None, win=None):
	vv, loc = find_loc(fn=fn, id=id, view=view, win=win)
	if not vv.has_view() and isfile(loc.fn):
		if win is None:
			win = sublime.active_window()
		vv = V(win.open_file(loc.fn), win=win)

	if vv.has_view():
		vv.focus(loc.row, loc.col)

	return vv

def find(fn='', id=-1, view=None, win=None):
	vv, _ = find_loc(fn=fn, id=id, view=view, win=win)
	return vv

def find_loc(fn='', id=-1, view=None, win=None):
	loc = mk_loc()
	if view is not None:
		return (V(view, win=win), loc)

	match = None
	if id >= 0:
		match = lambda v: v.id() == id
	else:
		loc = parse(fn)
		if loc.ok:
			if loc.id >= 0:
				match = lambda v: v.id() == loc.id
			else:
				match = lambda v: v.file_name() == loc.fn
		else:
			match = lambda v: v.file_name() == fn

	if win is None:
		win = sublime.active_window()

	for v in win.views():
		if match(v):
			return (V(v, win=win), loc)

	return (V(None, win=win), loc)

def sel(view, i=0):
	try:
		s = view.sel()
		if s is not None and i < len(s):
			return s[i]
	except Exception:
		pass

	return sublime.Region(0, 0)

def rowcol(view):
	try:
		return view.rowcol(sel(view).begin())
	except Exception:
		return (0, 0)

def mk_loc():
	return kv.O(
		ok=False,
		id=-1,
		fn='',
		row=0,
		col=0,
		pos=''
	)

def get_num(m, k):
	try:
		return int(m.get(k))
	except Exception:
		return 0

def parse(s):
	loc = mk_loc()
	m = _fn.search(s or '')
	if m:
		m = m.groupdict()
		loc.ok = True
		loc.id = get_num(m, 'id')
		loc.row = max(0, get_num(m, 'line')-1)
		loc.col = max(0, get_num(m, 'column')-1)
		loc.pos = '%s:%s' % (loc.row, loc.col)
		loc.fn = m.get('fn', '')

		vm = _vfn_id.search(loc.fn)
		if vm:
			loc.id = int(vm.group(1))
			loc.fn = ''

	return loc

def is_vfn(s):
	return 'gs.view#' in s

def gs_init(m={}):
	pass
<|endoftext|>


<commit_before>import django

from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response

from django.contrib.auth import authenticate, login, logout
from django.contrib import messages

from ..models import Component
from ..models import Device

def add_test_view(request):
    return render(request, 'add_test.html', {})

def add_component_test_view(request):
    return render(request, 'add_test_component_form.html', {})

def add_device_test_view(request):
    return render(request, 'add_test_device_form.html', {})

def satisfy_component_test_requirements(data):
    means_for_failing = ""

    for element in data:
        if element == means_for_failing:
            return False

    return True

def create_test_view(request):
    if request.user.is_authenticated():
        try:
            component_name = request.POST['component_name']
            is_component = True
        except:
            is_component = False

        try:
            device_name = request.POST['device_name']
            is_device = True
        except:
            is_device = False

        author = request.user.username

        if is_component == True:
            rating = request.POST['component_rating']
            is_working = "Failed"
            notes = request.POST['component_test_notes']
            component_category = request.POST['component_category']
            manufacturer = request.POST['component_manufacturer']
            haiku_revision = request.POST['component_haiku_revision']
            haiku_architecture = request.POST['component_haiku_architecture']

            component_data = [
                component_category,
                manufacturer,
                haiku_revision,
                haiku_architecture
            ]

            if satisfy_component_test_requirements(component_data) == False:
                messages.error(request, 'Fields that were required were not filled out...please try again')

                return HttpResponseRedirect(reverse('index'))

            try:
                if str(request.POST['group1']) == "on":
                    is_working = "Passed"
            except:
                pass

            try:
                newComponent = Component(name = component_name,
                                         rating = rating,
                                         is_working = is_working,
                                         notes = notes,
                                         author = author,
                                         author_email = author_email,
                                         category = component_category,
                                         manufacturer = manufacturer,
                                         haiku_revision = haiku_revision,
                                         haiku_arch = haiku_architecture)
                newComponent.save()

                messages.success(request, 'Successfully created a new test')
            except:
                messages.error(request, 'Could not create a new test...please try again')

        if is_device == True:
            rating = request.POST['device_rating']
            is_working = "Failed"
            notes = request.POST['device_test_notes']

            device_cpu = request.POST['device_cpu']
            device_motherboard = request.POST['device_motherboard']
            device_hard_drive = request.POST['device_hard_drive']
            device_sound = request.POST['device_sound']
            is_sound_working = "Failed"
            device_display_name = request.POST['device_display_name']
            device_display_config = request.POST['device_display_config']
            is_display_working = "Failed"
            device_dedicated_graphics = request.POST['device_dedicated_graphics']
            is_dedicated_graphics_working = request.POST['device_dedicated_graphics']
            manufacturer = request.POST['device_manufacturer']
            category = request.POST['device_category']

            lan_chipset = request.POST['device_lan_network_chipset']
            wlan_chipset = request.POST['device_wlan_network_chipset']

            haiku_revision = request.POST['component_haiku_revision']
            haiku_architecture = request.POST['component_haiku_architecture']

            optical_drive_works = "Failed"
            card_reader_works = "Failed"

            usb2_works = "Failed"
            usb3_works = "Failed"

            try:
                if str(request.POST['group9']) == "on":
                    is_working = "Passed"
            except:
                pass

            try:
                if str(request.POST['group3']) == "on":
                    is_sound_working = "Passed"
            except:
                pass

            try:
                if str(request.POST['group5']) == "on":
                    is_display_working = "Passed"
            except:
                pass

            try:
                if str(request.POST['group7']) == "on":
                    is_dedicated_graphics_working = "Passed"
            except:
                pass

            try:
                if str(request.POST['device_usb2_pass']) == "on":
                    usb2_works = "Passed"
            except:
                pass

            try:
                if str(request.POST['device_usb3_pass']) == "on":
                    usb3_works = "Passed"
            except:
                pass

            try:
                if str(request.POST['device_optical_drive_pass']) == "on":
                    optical_drive_works = "Passed"
            except:
                pass

            try:
                if str(request.POST['device_card_reader_pass']) == "on":
                    card_reader_works = "Passed"
            except:
                pass

            try:
                newDevice = Device(name = device_name,
                                   rating = rating,
                                   is_working = is_working,
                                   notes = notes,
                                   author = author,
                                   author_email = author_email,
                                   cpu = device_cpu,
                                   motherboard = device_motherboard,
                                   hard_drive = device_hard_drive,
                                   sound = device_sound,
                                   is_sound_working = is_sound_working,
                                   display = device_display_name,
                                   display_configuration = device_display_config,
                                   is_display_working = is_display_working,
                                   graphics_card = device_dedicated_graphics,
                                   graphics_card_is_working = is_dedicated_graphics_working,
                                   manufacturer = manufacturer,
                                   does_usb2_work = usb2_works,
                                   does_usb3_work = usb3_works,
                                   lan_network_chipset = lan_chipset,
                                   wlan_network_chipset = wlan_chipset,
                                   does_optical_drive_work = optical_drive_works,
                                   does_card_reader_work = card_reader_works,
                                   haiku_revision = haiku_revision,
                                   haiku_architecture = haiku_architecture,
                                   category = category)
                newDevice.save()
                messages.success(request, 'Successfully created a new test')
            except:
                messages.error(request, 'Could not create a new test...please try again')

    return HttpResponseRedirect(reverse('index'))

def my_tests_view(request):
    all_components = Component.objects.all().filter(author=request.user.username)
    all_devices = Device.objects.all().filter(author=request.user.username)
    context = {
        'all_devices' : all_devices,
        'all_components' : all_components
    }

    return render(request, 'my_tests.html', context)
<commit_msg>Fix device form error & add part validation<commit_after>import django

from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response

from django.contrib.auth import authenticate, login, logout
from django.contrib import messages

from ..models import Component
from ..models import Device

def add_test_view(request):
    return render(request, 'add_test.html', {})

def add_component_test_view(request):
    return render(request, 'add_test_component_form.html', {})

def add_device_test_view(request):
    return render(request, 'add_test_device_form.html', {})

def satisfy_test_requirements(data):
    means_for_failing = ""

    for element in data:
        if element == means_for_failing:
            return False

    return True

def create_test_view(request):
    if request.user.is_authenticated():
        try:
            component_name = request.POST['component_name']
            is_component = True
        except:
            is_component = False

        try:
            device_name = request.POST['device_name']
            is_device = True
        except:
            is_device = False

        author = request.user.username

        if is_component == True:
            rating = request.POST['component_rating']
            is_working = "Failed"
            notes = request.POST['component_test_notes']
            component_category = request.POST['component_category']
            manufacturer = request.POST['component_manufacturer']
            haiku_revision = request.POST['component_haiku_revision']
            haiku_architecture = request.POST['component_haiku_architecture']

            component_data = [
                component_category,
                manufacturer,
                haiku_revision,
                haiku_architecture
            ]

            if satisfy_test_requirements(component_data) == False:
                messages.error(request, 'Fields that were required were not filled out...please try again')

                return HttpResponseRedirect(reverse('index'))

            try:
                if str(request.POST['group1']) == "on":
                    is_working = "Passed"
            except:
                pass

            try:
                newComponent = Component(name = component_name,
                                         rating = rating,
                                         is_working = is_working,
                                         notes = notes,
                                         author = author,
                                         author_email = author_email,
                                         category = component_category,
                                         manufacturer = manufacturer,
                                         haiku_revision = haiku_revision,
                                         haiku_arch = haiku_architecture)
                newComponent.save()

                messages.success(request, 'Successfully created a new test')
            except:
                messages.error(request, 'Could not create a new test...please try again')

        if is_device == True:
            rating = request.POST['device_rating']
            notes = request.POST['device_test_notes']

            device_cpu = request.POST['device_cpu']
            device_motherboard = request.POST['device_motherboard']
            device_hard_drive = request.POST['device_hard_drive']
            device_sound = request.POST['device_sound']
            device_display_name = request.POST['device_display_name']
            device_display_config = request.POST['device_display_config']
            device_dedicated_graphics = request.POST['device_dedicated_graphics']
            is_dedicated_graphics_working = request.POST['device_dedicated_graphics']
            manufacturer = request.POST['device_manufacturer']
            category = request.POST['device_category']
            lan_chipset = request.POST['device_lan_network_chipset']
            wlan_chipset = request.POST['device_wlan_network_chipset']
            haiku_revision = request.POST['device_haiku_revision']
            haiku_architecture = request.POST['device_haiku_architecture']

            device_data = [
                rating,
                haiku_revision,
                haiku_architecture,
                manufacturer,
                device_cpu,
                device_motherboard,
                device_hard_drive,
                category
            ]

            if satisfy_test_requirements(device_data) == False:
                messages.error(request, 'Fields that were required were not filled out...please try again')

                return HttpResponseRedirect(reverse('index'))

            try:
                if str(request.POST['group9']) == "on":
                    is_working = "Passed"
            except:
                is_working = ""

            try:
                if str(request.POST['group3']) == "on":
                    is_sound_working = "Passed"
            except:
                is_sound_working = ""

            try:
                if str(request.POST['group5']) == "on":
                    is_display_working = "Passed"
            except:
                is_display_working = ""

            try:
                if str(request.POST['group7']) == "on":
                    is_dedicated_graphics_working = "Passed"
            except:
                is_dedicated_graphics_working = ""

            try:
                if str(request.POST['device_usb2_pass']) == "on":
                    usb2_works = "Passed"
            except:
                usb2_works = ""

            try:
                if str(request.POST['device_usb3_pass']) == "on":
                    usb3_works = "Passed"
            except:
                usb3_works = ""

            try:
                if str(request.POST['device_optical_drive_pass']) == "on":
                    optical_drive_works = "Passed"
            except:
                optical_drive_works = ""

            try:
                if str(request.POST['device_card_reader_pass']) == "on":
                    card_reader_works = "Passed"
            except:
                card_reader_works = ""

            try:
                newDevice = Device(name = device_name,
                                   rating = rating,
                                   is_working = is_working,
                                   notes = notes,
                                   author = author,
                                   author_email = author_email,
                                   cpu = device_cpu,
                                   motherboard = device_motherboard,
                                   hard_drive = device_hard_drive,
                                   sound = device_sound,
                                   is_sound_working = is_sound_working,
                                   display = device_display_name,
                                   display_configuration = device_display_config,
                                   is_display_working = is_display_working,
                                   graphics_card = device_dedicated_graphics,
                                   graphics_card_is_working = is_dedicated_graphics_working,
                                   manufacturer = manufacturer,
                                   does_usb2_work = usb2_works,
                                   does_usb3_work = usb3_works,
                                   lan_network_chipset = lan_chipset,
                                   wlan_network_chipset = wlan_chipset,
                                   does_optical_drive_work = optical_drive_works,
                                   does_card_reader_work = card_reader_works,
                                   haiku_revision = haiku_revision,
                                   haiku_architecture = haiku_architecture,
                                   category = category)
                newDevice.save()
                messages.success(request, 'Successfully created a new test')
            except:
                messages.error(request, 'Could not create a new test...please try again')

    return HttpResponseRedirect(reverse('index'))

def my_tests_view(request):
    all_components = Component.objects.all().filter(author=request.user.username)
    all_devices = Device.objects.all().filter(author=request.user.username)
    context = {
        'all_devices' : all_devices,
        'all_components' : all_components
    }

    return render(request, 'my_tests.html', context)
<|endoftext|>