<commit_before>import twiddle.check_almconnections as almconnections
from nose_parameterized import parameterized
from nose.tools import raises
from urllib2 import URLError

@parameterized.expand([
    ('', ''),
    (None, None),
    ('', None),
    (None, ''),
    (None, 0),
])
@raises(ValueError)
def test_get_database_connection_maximum_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_maximum(invalid_hostname, invalid_port)

@parameterized.expand([
    ('nonexistant.hostname', '80'),
])
@raises(URLError)
def test_get_database_connection_maximum_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_maximum(invalid_hostname, invalid_port)

@parameterized.expand([
    ('qd-app-01.rally.prod', '7001'),
])
def test_get_database_connection_maximum_returns_a_non_empty_string(host, port):
    return_val = almconnections.get_database_connection_maximum(host, port)
    assert isinstance(return_val, str), 'Expected that almconnections.get_database_connection_maximum(%s, %s) to return an integer, not %s=%s' %(host, port, type(return_val), return_val)
    assert return_val != '', 'Expected that almconnections.get_database_connection_maximum(%s, %s) to return a none empty string' %(host, port)

@parameterized.expand([
    ('', ''),
    (None, None),
    ('', None),
    (None, ''),
    (None, 0),
])
@raises(ValueError)
def test_get_database_connection_minimum_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_minimum(invalid_hostname, invalid_port)

@parameterized.expand([
    ('nonexistant.hostname', '80'),
])
@raises(URLError)
def test_get_database_connection_minimum_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_minimum(invalid_hostname, invalid_port)

@parameterized.expand([
    ('qd-app-01.rally.prod', '7001'),
])
def test_get_database_connection_minimum_returns_a_non_empty_string(host, port):
    return_val = almconnections.get_database_connection_minimum(host, port)
    assert isinstance(return_val, str), 'Expected that almconnections.get_database_connection_minimum(%s, %s) to return an integer, not %s=%s' %(host, port, type(return_val), return_val)
    assert return_val != '', 'Expected that almconnections.get_database_connection_minimum(%s, %s) to return a none empty string' %(host, port)

@parameterized.expand([
    ('', ''),
    (None, None),
    ('', None),
    (None, ''),
    (None, 0),
])
@raises(ValueError)
def test_get_database_connection_current_used_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_current_used(invalid_hostname, invalid_port)

@parameterized.expand([
    ('nonexistant.hostname', '80'),
])
@raises(URLError)
def test_get_database_connection_current_used_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_current_used(invalid_hostname, invalid_port)

@parameterized.expand([
    ('qd-app-01.rally.prod', '7001'),
])
def test_get_database_connection_current_used_returns_a_non_empty_string(host, port):
    return_val = almconnections.get_database_connection_current_used(host, port)
    assert isinstance(return_val, str), 'Expected that almconnections.get_database_connection_current_used(%s, %s) to return an integer, not %s=%s' %(host, port, type(return_val), return_val)
    assert return_val != '', 'Expected that almconnections.get_database_connection_current_used(%s, %s) to return a none empty string' %(host, port)

@parameterized.expand([
    ('', ''),
    (None, None),
    ('', None),
    (None, ''),
    (None, 0),
])
@raises(ValueError)
def test_get_database_connection_current_idle_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_current_idle(invalid_hostname, invalid_port)

@parameterized.expand([
    ('nonexistant.hostname', '80'),
])
@raises(URLError)
def test_get_database_connection_current_idle_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_current_idle(invalid_hostname, invalid_port)

@parameterized.expand([
    ('qd-app-01.rally.prod', '7001'),
])
def test_get_database_connection_current_idle_returns_a_non_empty_string(host, port):
    return_val = almconnections.get_database_connection_current_idle(host, port)
    assert isinstance(return_val, str), 'Expected that almconnections.get_database_connection_idle(%s, %s) to return an integer, not %s=%s' %(host, port, type(return_val), return_val)
    assert return_val != '', 'Expected that almconnections.get_database_connection_idle(%s, %s) to return a none empty string' %(host, port)
<commit_msg>fixing hostname in integration tests<commit_after>import twiddle.check_almconnections as almconnections
from nose_parameterized import parameterized
from nose.tools import raises
from urllib2 import URLError

@parameterized.expand([
    ('', ''),
    (None, None),
    ('', None),
    (None, ''),
    (None, 0),
])
@raises(ValueError)
def test_get_database_connection_maximum_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_maximum(invalid_hostname, invalid_port)

@parameterized.expand([
    ('nonexistant.hostname', '80'),
])
@raises(URLError)
def test_get_database_connection_maximum_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_maximum(invalid_hostname, invalid_port)

@parameterized.expand([
    ('mytesthost.com', '7001'),
])
def test_get_database_connection_maximum_returns_a_non_empty_string(host, port):
    return_val = almconnections.get_database_connection_maximum(host, port)
    assert isinstance(return_val, str), 'Expected that almconnections.get_database_connection_maximum(%s, %s) to return an integer, not %s=%s' %(host, port, type(return_val), return_val)
    assert return_val != '', 'Expected that almconnections.get_database_connection_maximum(%s, %s) to return a none empty string' %(host, port)

@parameterized.expand([
    ('', ''),
    (None, None),
    ('', None),
    (None, ''),
    (None, 0),
])
@raises(ValueError)
def test_get_database_connection_minimum_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_minimum(invalid_hostname, invalid_port)

@parameterized.expand([
    ('nonexistant.hostname', '80'),
])
@raises(URLError)
def test_get_database_connection_minimum_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_minimum(invalid_hostname, invalid_port)

@parameterized.expand([
    ('mytesthost.com', '7001'),
])
def test_get_database_connection_minimum_returns_a_non_empty_string(host, port):
    return_val = almconnections.get_database_connection_minimum(host, port)
    assert isinstance(return_val, str), 'Expected that almconnections.get_database_connection_minimum(%s, %s) to return an integer, not %s=%s' %(host, port, type(return_val), return_val)
    assert return_val != '', 'Expected that almconnections.get_database_connection_minimum(%s, %s) to return a none empty string' %(host, port)

@parameterized.expand([
    ('', ''),
    (None, None),
    ('', None),
    (None, ''),
    (None, 0),
])
@raises(ValueError)
def test_get_database_connection_current_used_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_current_used(invalid_hostname, invalid_port)

@parameterized.expand([
    ('nonexistant.hostname', '80'),
])
@raises(URLError)
def test_get_database_connection_current_used_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_current_used(invalid_hostname, invalid_port)

@parameterized.expand([
    ('mytesthost.com', '7001'),
])
def test_get_database_connection_current_used_returns_a_non_empty_string(host, port):
    return_val = almconnections.get_database_connection_current_used(host, port)
    assert isinstance(return_val, str), 'Expected that almconnections.get_database_connection_current_used(%s, %s) to return an integer, not %s=%s' %(host, port, type(return_val), return_val)
    assert return_val != '', 'Expected that almconnections.get_database_connection_current_used(%s, %s) to return a none empty string' %(host, port)

@parameterized.expand([
    ('', ''),
    (None, None),
    ('', None),
    (None, ''),
    (None, 0),
])
@raises(ValueError)
def test_get_database_connection_current_idle_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_current_idle(invalid_hostname, invalid_port)

@parameterized.expand([
    ('nonexistant.hostname', '80'),
])
@raises(URLError)
def test_get_database_connection_current_idle_raises_ValueError_when_arguments_are_invalid(invalid_hostname, invalid_port):
    almconnections.get_database_connection_current_idle(invalid_hostname, invalid_port)

@parameterized.expand([
    ('mytesthost.com', '7001'),
])
def test_get_database_connection_current_idle_returns_a_non_empty_string(host, port):
    return_val = almconnections.get_database_connection_current_idle(host, port)
    assert isinstance(return_val, str), 'Expected that almconnections.get_database_connection_idle(%s, %s) to return an integer, not %s=%s' %(host, port, type(return_val), return_val)
    assert return_val != '', 'Expected that almconnections.get_database_connection_idle(%s, %s) to return a none empty string' %(host, port)
<|endoftext|>


<commit_before># from tabulate import tabulate
from terminaltables import AsciiTable

def output_ascii_table(table_title=None,
                       table_data=None,
                       inner_heading_row_border=False,
                       inner_row_border=False):
    table = AsciiTable(table_data)
    table.inner_heading_row_border = inner_heading_row_border
    table.inner_row_border = inner_row_border
    table.title = table_title
    print(table.table)

def get_ec2_instance_name_tag(ec2_instance=None,
                              max_length=40):
    instance_name = ec2_instance.tags.get('Name', '-')
    if len(instance_name) > max_length:
        return "{0}...".format(instance_name[:max_length-3])
    else:
        return instance_name

def output_ec2_list(output_media=None, instances=None):
    if output_media == 'console':
        td = [['id', 'name', 'state', 'type', 'image',
                'public ip', 'private ip', 'profile']]
        for instance in instances:
            instance_id = instance[0].id
            instance_state = instance[0].state
            instance_type = instance[0].instance_type
            image_id = instance[0].image_id
            public_ip = instance[0].ip_address
            private_ip = instance[0].private_ip_address
            instance_profile = instance[0].instance_profile
            instance_profile_out = '-'
            instance_name = get_ec2_instance_name_tag(ec2_instance=instance[0])
            if instance_profile:
                instance_profile_out = short_instance_profile(instance_profile)
            td.append([instance_id,
                       instance_name,
                       instance_state,
                       instance_type,
                       image_id,
                       public_ip if public_ip else '-',
                       private_ip if private_ip else '-',
                       instance_profile_out])
        output_ascii_table(table_title="EC2 Instances",
                           table_data=td,
                           inner_heading_row_border=True)

def dash_if_none(item=None):
    return item if item else '-'

def short_instance_profile(instance_profile):
    if instance_profile:
        return instance_profile.get('arn').split('/')[-1]

def get_sec_group_names(groups=None):
    sec_group_names = [x.name for x in groups]
    return ",".join(sec_group_names)

def get_interface_ids(interfaces=None):
    interface_ids = [x.id for x in interfaces]
    return ",".join(interface_ids)

def output_elb_instances(instances=None):
    instance_ids = [x.id for x in instances]
    return ",".join(instance_ids)

def output_tags(tags):
    tag_list = []
    for tag_name, tag_value in tags.iteritems():
        tag_list.append("{0}:{1}".format(tag_name, tag_value))
    if tag_list:
        return ", ".join(tag_list)
    return "-"

def output_name_tag(tags):
    for tag_name, tag_value in tags.iteritems():
        if tag_name == 'Name':
            return tag_value
    return "-"

def output_ec2_info(output_media=None, instance=None):
    if output_media == 'console':
        td = [['id', instance.id]]
        td.append(['name', instance.tags.get('Name', '-')])
        td.append(['groups', get_sec_group_names(instance.groups)])
        td.append(['public ip', dash_if_none(instance.ip_address)])
        td.append(['public dns name', dash_if_none(instance.public_dns_name)])
        td.append(['private ip', dash_if_none(instance.private_ip_address)])
        td.append(['private dns name', dash_if_none(instance.private_dns_name)])
        td.append(['state', dash_if_none(instance.state)])
        td.append(['previous state', dash_if_none(instance.previous_state)])
        td.append(['key name', dash_if_none(instance.key_name)])
        td.append(['instance type', dash_if_none(instance.instance_type)])
        td.append(['launch time', dash_if_none(instance.launch_time)])
        td.append(['image id', dash_if_none(instance.image_id)])
        td.append(['placement', dash_if_none(instance.placement)])
        td.append(['monitored', dash_if_none(str(instance.monitored))])
        td.append(['subnet id', dash_if_none(instance.subnet_id)])
        td.append(['vpc id', dash_if_none(instance.vpc_id)])
        td.append(['root device type', dash_if_none(instance.root_device_type)])
        td.append(['state reason', dash_if_none(instance.state_reason)])
        td.append(['interfaces', dash_if_none(get_interface_ids(instance.interfaces))])
        td.append(['ebs optimized', dash_if_none(instance.ebs_optimized)])
        td.append(['instance profile', dash_if_none(short_instance_profile(instance.instance_profile))])
        td.append(['tags', output_tags(instance.tags)])
        output_ascii_table(table_title="Instance Info",
                           table_data=td)
        return True

def output_elbs(output_media=None, elbs=None):
    if output_media == 'console':
        td = [['name', 'instances', 'dns_name']]
        for elb in elbs:
            td.append([elb.name, str(len(elb.instances)), elb.dns_name])
        output_ascii_table(table_title="ELBs",
                           table_data=td,
                           inner_heading_row_border=True)

def output_elb_info(output_media=None, elb=None):
    if output_media == 'console':
        td = [['name', elb[0].name]]
        td.append(['dns name', elb[0].dns_name])
        td.append(['listeners', str(elb[0].listeners)])
        td.append(['canonical hosted zone name', dash_if_none(elb[0].canonical_hosted_zone_name)])
        td.append(['canonical hosted zone name id', dash_if_none(elb[0].canonical_hosted_zone_name_id)])
        td.append(['connection', str(elb[0].connection)])
        td.append(['policies', str(elb[0].policies)])
        td.append(['health check', str(elb[0].health_check)])
        td.append(['created time', dash_if_none(elb[0].created_time)])
        td.append(['instances', output_elb_instances(elb[0].instances)])
        td.append(['availability zones', ",".join(elb[0].availability_zones)])
        td.append(['source security group', dash_if_none(elb[0].source_security_group.name)])
        td.append(['security groups', ",".join(elb[0].security_groups)])
        td.append(['subnets', ",".join(elb[0].subnets)])
        td.append(['vpc id', dash_if_none(elb[0].vpc_id)])
        output_ascii_table(table_title="ELB Info",
                           table_data=td)

def output_amis(output_media=None, amis=None):
    if output_media == 'console':
        td = [['id', 'name', 'created']]
        for ami in amis:
            td.append([ami.id, ami.name, ami.creationDate])
        output_ascii_table(table_title="AMIs",
                           inner_heading_row_border=True,
                           table_data=td)

def output_ami_info(output_media=None, ami=None):
    if output_media == 'console':
        td = [['id', ami.id]]
        td.append(['name', ami.name])
        td.append(['creationDate', dash_if_none(ami.creationDate)])
        td.append(['description', dash_if_none(ami.description)])
        td.append(['block_device_mapping', dash_if_none(str(ami.block_device_mapping))])
        td.append(['get_launch permissions', dash_if_none(ami.id)])
        td.append(['get_ramdisk', dash_if_none(ami.id)])
        td.append(['hypervisor', dash_if_none(ami.id)])
        td.append(['is_public', dash_if_none(ami.id)])
        td.append(['kernel_id', dash_if_none(ami.id)])
        td.append(['location', dash_if_none(ami.id)])
        td.append(['owner_id', dash_if_none(ami.id)])
        td.append(['owner_alias', dash_if_none(ami.id)])
        td.append(['platform', dash_if_none(ami.id)])
        td.append(['product_codes', dash_if_none(ami.id)])
        td.append(['ramdisk_id', dash_if_none(ami.id)])
        td.append(['region', dash_if_none(ami.id)])
        td.append(['root_device_name', dash_if_none(ami.id)])
        td.append(['root_device_type', dash_if_none(ami.id)])
        td.append(['sriov_net_support', dash_if_none(ami.id)])
        td.append(['state', dash_if_none(ami.id)])
        td.append(['type', dash_if_none(ami.id)])
        td.append(['virtualization_type', dash_if_none(ami.id)])
        output_ascii_table(table_title="AMI Info",
                           table_data=td)
<commit_msg>output ami and block device mapping.<commit_after># from tabulate import tabulate
from terminaltables import AsciiTable

def output_ascii_table(table_title=None,
                       table_data=None,
                       inner_heading_row_border=False,
                       inner_row_border=False):
    table = AsciiTable(table_data)
    table.inner_heading_row_border = inner_heading_row_border
    table.inner_row_border = inner_row_border
    table.title = table_title
    print(table.table)

def get_ec2_instance_name_tag(ec2_instance=None,
                              max_length=40):
    instance_name = ec2_instance.tags.get('Name', '-')
    if len(instance_name) > max_length:
        return "{0}...".format(instance_name[:max_length-3])
    else:
        return instance_name

def output_ec2_list(output_media=None, instances=None):
    if output_media == 'console':
        td = [['id', 'name', 'state', 'type', 'image',
                'public ip', 'private ip', 'profile']]
        for instance in instances:
            instance_id = instance[0].id
            instance_state = instance[0].state
            instance_type = instance[0].instance_type
            image_id = instance[0].image_id
            public_ip = instance[0].ip_address
            private_ip = instance[0].private_ip_address
            instance_profile = instance[0].instance_profile
            instance_profile_out = '-'
            instance_name = get_ec2_instance_name_tag(ec2_instance=instance[0])
            if instance_profile:
                instance_profile_out = short_instance_profile(instance_profile)
            td.append([instance_id,
                       instance_name,
                       instance_state,
                       instance_type,
                       image_id,
                       public_ip if public_ip else '-',
                       private_ip if private_ip else '-',
                       instance_profile_out])
        output_ascii_table(table_title="EC2 Instances",
                           table_data=td,
                           inner_heading_row_border=True)

def dash_if_none(item=None):
    return item if item else '-'

def short_instance_profile(instance_profile):
    if instance_profile:
        return instance_profile.get('arn').split('/')[-1]

def get_sec_group_names(groups=None):
    sec_group_names = [x.name for x in groups]
    return ",".join(sec_group_names)

def get_interface_ids(interfaces=None):
    interface_ids = [x.id for x in interfaces]
    return ",".join(interface_ids)

def output_elb_instances(instances=None):
    instance_ids = [x.id for x in instances]
    return ",".join(instance_ids)

def output_tags(tags):
    tag_list = []
    for tag_name, tag_value in tags.iteritems():
        tag_list.append("{0}:{1}".format(tag_name, tag_value))
    if tag_list:
        return ", ".join(tag_list)
    return "-"

def output_name_tag(tags):
    for tag_name, tag_value in tags.iteritems():
        if tag_name == 'Name':
            return tag_value
    return "-"

def output_ec2_info(output_media=None, instance=None):
    if output_media == 'console':
        td = [['id', instance.id]]
        td.append(['name', instance.tags.get('Name', '-')])
        td.append(['groups', get_sec_group_names(instance.groups)])
        td.append(['public ip', dash_if_none(instance.ip_address)])
        td.append(['public dns name', dash_if_none(instance.public_dns_name)])
        td.append(['private ip', dash_if_none(instance.private_ip_address)])
        td.append(['private dns name', dash_if_none(instance.private_dns_name)])
        td.append(['state', dash_if_none(instance.state)])
        td.append(['previous state', dash_if_none(instance.previous_state)])
        td.append(['key name', dash_if_none(instance.key_name)])
        td.append(['instance type', dash_if_none(instance.instance_type)])
        td.append(['launch time', dash_if_none(instance.launch_time)])
        td.append(['image id', dash_if_none(instance.image_id)])
        td.append(['placement', dash_if_none(instance.placement)])
        td.append(['monitored', dash_if_none(str(instance.monitored))])
        td.append(['subnet id', dash_if_none(instance.subnet_id)])
        td.append(['vpc id', dash_if_none(instance.vpc_id)])
        td.append(['root device type', dash_if_none(instance.root_device_type)])
        td.append(['state reason', dash_if_none(instance.state_reason)])
        td.append(['interfaces', dash_if_none(get_interface_ids(instance.interfaces))])
        td.append(['ebs optimized', dash_if_none(instance.ebs_optimized)])
        td.append(['instance profile', dash_if_none(short_instance_profile(instance.instance_profile))])
        td.append(['tags', output_tags(instance.tags)])
        output_ascii_table(table_title="Instance Info",
                           table_data=td)
        return True

def output_elbs(output_media=None, elbs=None):
    if output_media == 'console':
        td = [['name', 'instances', 'dns_name']]
        for elb in elbs:
            td.append([elb.name, str(len(elb.instances)), elb.dns_name])
        output_ascii_table(table_title="ELBs",
                           table_data=td,
                           inner_heading_row_border=True)

def output_elb_info(output_media=None, elb=None):
    if output_media == 'console':
        td = [['name', elb[0].name]]
        td.append(['dns name', elb[0].dns_name])
        td.append(['listeners', str(elb[0].listeners)])
        td.append(['canonical hosted zone name', dash_if_none(elb[0].canonical_hosted_zone_name)])
        td.append(['canonical hosted zone name id', dash_if_none(elb[0].canonical_hosted_zone_name_id)])
        td.append(['connection', str(elb[0].connection)])
        td.append(['policies', str(elb[0].policies)])
        td.append(['health check', str(elb[0].health_check)])
        td.append(['created time', dash_if_none(elb[0].created_time)])
        td.append(['instances', output_elb_instances(elb[0].instances)])
        td.append(['availability zones', ",".join(elb[0].availability_zones)])
        td.append(['source security group', dash_if_none(elb[0].source_security_group.name)])
        td.append(['security groups', ",".join(elb[0].security_groups)])
        td.append(['subnets', ",".join(elb[0].subnets)])
        td.append(['vpc id', dash_if_none(elb[0].vpc_id)])
        output_ascii_table(table_title="ELB Info",
                           table_data=td)

def output_amis(output_media=None, amis=None):
    if output_media == 'console':
        td = [['id', 'name', 'created']]
        for ami in amis:
            td.append([ami.id, ami.name, ami.creationDate])
        output_ascii_table(table_title="AMIs",
                           inner_heading_row_border=True,
                           table_data=td)

def output_block_device_mapping(bdm=None):
    out = ""
    for i, (key, value) in enumerate(bdm.iteritems()):
        out += "{0},{1},{2}".format(key, value.volume_type, value.size)
        if i < len(bdm)-1:
            out += "\n"
    return out

def output_ami_permissions(perms=None):
    out = ""
    for i, (key, value) in enumerate(perms.iteritems()):
        out += "{0},{1}".format(key, str(value))
        if i < len(perms)-1:
            out += "\n"
    return out

def output_ami_info(output_media=None, ami=None):
    if output_media == 'console':
        td = [['id', ami.id]]
        td.append(['name', ami.name])
        td.append(['creationDate', dash_if_none(ami.creationDate)])
        td.append(['description', dash_if_none(ami.description)])
        td.append(['block_device_mapping', output_block_device_mapping(bdm=ami.block_device_mapping)])
        td.append(['get launch permissions', output_ami_permissions(ami.get_launch_permissions())])
        td.append(['get ramdisk', dash_if_none(str(ami.get_ramdisk()))])
        td.append(['hypervisor', dash_if_none(ami.hypervisor)])
        td.append(['is_public', dash_if_none(str(ami.is_public))])
        td.append(['kernel_id', dash_if_none(ami.kernel_id)])
        td.append(['location', dash_if_none(ami.location)])
        td.append(['owner_id', dash_if_none(ami.owner_id)])
        td.append(['owner_alias', dash_if_none(ami.owner_alias)])
        td.append(['platform', dash_if_none(ami.platform)])
        td.append(['product codes', ",".join(ami.product_codes)])
        td.append(['ramdisk_id', dash_if_none(ami.ramdisk_id)])
        td.append(['region', dash_if_none(str(ami.region.name))])
        td.append(['root_device_name', dash_if_none(ami.root_device_name)])
        td.append(['root_device_type', dash_if_none(ami.root_device_type)])
        td.append(['sriov_net_support', dash_if_none(ami.sriov_net_support)])
        td.append(['state', dash_if_none(ami.state)])
        td.append(['type', dash_if_none(ami.type)])
        td.append(['virtualization_type', dash_if_none(ami.virtualization_type)])
        output_ascii_table(table_title="AMI Info",
                           table_data=td)
<|endoftext|>


<commit_before>import importlib
import urllib2
from datetime import datetime
from xml.etree import ElementTree

from django.core.management.base import BaseCommand, CommandError

from bixi.models import City, Station, Update

def timestampToDateTime(timestamp):
    if timestamp:
        return datetime.fromtimestamp(int(timestamp) / 1e3)
    return None

class StationListParser:
    def get_install_date(self, station):
        return timestampToDateTime(self.find(station, 'installDate'))

    def get_last_communication_time_with_server(self, station):
        raise NotImplementedError

    def get_latest_update_time(self, station):
        raise NotImplementedError

    def get_latitude(self, station):
        return float(self.find(station, 'lat'))

    def get_longitude(self, station):
        return float(self.find(station, 'long'))

    def get_number_available_bikes(self, station):
        return int(self.find(station, 'nbBikes'))

    def get_number_empty_docks(self, station):
        return int(self.find(station, 'nbEmptyDocks'))

    def get_public_id(self, station):
        return int(self.find(station, 'id'))

    def get_removal_date(self, station):
        return timestampToDateTime(self.find(station, 'removalDate'))

    def get_station_name(self, station):
        return self.find(station, 'name')

    def get_terminal_name(self, station):
        return self.find(station, 'terminalName')

    def is_locked(self, station):
        return self.find(station, 'locked') == 'true'

    def is_installed(self, station):
        return self.find(station, 'installed') == 'true'

    def is_public(self, station):
        raise NotImplementedError

    def is_temporary(self, station):
        return self.find(station, 'temporary') == 'true'

class XmlParser:
    def __init__(self, data, *args, **kwargs):
        tree = ElementTree.parse(data)
        self.root = tree.getroot()

    def find(self, element, field_name):
        return element.find(field_name).text

    def get_last_update_time(self):
        return timestampToDateTime(self.root.attrib['lastUpdate'])

    def get_stations(self):
        return self.root.findall('station')

class StationListParserTypeA(XmlParser, StationListParser):
    def get_last_communication_time_with_server(self, station):
        return timestampToDateTime(self.find(station, 'lastCommWithServer'))

    def get_latest_update_time(self, station):
        return timestampToDateTime(self.find(station, 'latestUpdateTime'))

    def is_public(self, station):
        return self.find(station, 'public') == 'true'

class StationListParserTypeB(XmlParser, StationListParser):
    def get_last_communication_time_with_server(self, station):
        return None

    def get_latest_update_time(self, station):
        return None

    def is_public(self, station):
        return None

class Command(BaseCommand):
    args = '<city_code city_code ...>'
    help = 'Updates the current bike and dock counts for a given list of cities.'

    def __init__(self):
        self.created = 0
        self.status_quo = 0
        self.updated = 0
        return super(Command, self).__init__()

    def _increase_created_count(self):
        self.created = self.created + 1
        self.progress('c')

    def _increase_status_quo_count(self):
        self.status_quo = self.status_quo + 1
        self.progress('.')

    def _increase_updated_count(self):
        self.updated = self.updated + 1
        self.progress('u')

    def handle(self, *args, **options):
        city_codes = args or map(lambda x: x[0], City.available.all().values_list('code'))
        parsers_module = importlib.import_module(self.__class__.__module__)

        for city_code in city_codes:
            try:
                city = City.objects.get(code=city_code)
            except City.DoesNotExist:
                raise CommandError("City '%s' does not exist." % city_code)

            xml = urllib2.urlopen(city.url)

            parsers = {City.parser_code_to_value(value): getattr(parsers_module, 'StationListParserType' + value) for value in City.PARSER_TYPES_VALUES}
            try:
                parser = parsers[city.parser_type](xml)
            except IndexError:
                raise NotImplementedError("The parser for '%s' hasn't been implemented yet." % (city.name,))

            for s in parser.get_stations():
                attrs = dict()
                public_id = parser.get_public_id(s)
                last_comm_with_server = parser.get_last_communication_time_with_server(s)
                try:
                    station = Station.objects.get(city=city, public_id=public_id)
                    # Skip if we have a timestamp to compare against
                    if last_comm_with_server and station.last_comm_with_server == last_comm_with_server:
                        self._update_status_quo()
                        continue
                    # Else, update the station
                except Station.DoesNotExist:
                    station = Station()
                    attrs.update({
                        'city_id': city.pk,
                        'name': parser.get_station_name(s),
                        'public_id': public_id,
                        'terminal_name': parser.get_terminal_name(s),
                    })
                    self._increase_created_count()
                    self.progress('c')

                attrs.update({
                    'install_date': parser.get_install_date(s),
                    'installed': parser.is_installed(s),
                    'last_comm_with_server': parser.get_last_communication_time_with_server(s),
                    'lat': parser.get_latitude(s),
                    'locked': parser.is_locked(s),
                    'long': parser.get_longitude(s),
                    'public': parser.is_public(s),
                    'removal_date': parser.get_removal_date(s),
                    'temporary': parser.is_temporary(s),
                })

                if not station.last_comm_with_server:
                    skip_station = True
                    for (attr, value,) in attrs.items():
                        if not getattr(station, attr) == value:
                            # Skip the station altogether
                            skip_station = False
                            continue
                    if skip_station:
                        self._increase_status_quo_count()
                        continue

                self._increase_updated_count()

                for (k, v) in attrs.items():
                    assert k in station.__dict__, "The attribute '%s' must be an existing model field." % (k,)
                    setattr(station, k, v)
                station.save()

                latest_update_time = parser.get_latest_update_time(s)
                if Update.objects.filter(station=station,
                    latest_update_time=latest_update_time).exists():
                    continue

                nb_bikes = parser.get_number_available_bikes(s)
                nb_empty_docks = parser.get_number_empty_docks(s)
                Update.objects.create(station=station, nb_bikes=nb_bikes,
                    nb_empty_docks=nb_empty_docks,
                    latest_update_time=latest_update_time)

            last_update = parser.get_last_update_time()
            city.last_update = last_update
            city.save()

            self.stdout.write("\nSuccessfully updated bike and dock counts for " +
                "'%s'." % city.name)
            self.stdout.write('Created: %s' % self.created)
            self.stdout.write('Updated: %s' % self.updated)
            self.stdout.write('Status quo: %s' % self.status_quo)

    def progress(self, str):
        self.stdout.write(str, ending='')

<commit_msg>Fixed oversight from previous refactorings.<commit_after>import importlib
import urllib2
from datetime import datetime
from xml.etree import ElementTree

from django.core.management.base import BaseCommand, CommandError

from bixi.models import City, Station, Update

def timestampToDateTime(timestamp):
    if timestamp:
        return datetime.fromtimestamp(int(timestamp) / 1e3)
    return None

class StationListParser:
    def get_install_date(self, station):
        return timestampToDateTime(self.find(station, 'installDate'))

    def get_last_communication_time_with_server(self, station):
        raise NotImplementedError

    def get_latest_update_time(self, station):
        raise NotImplementedError

    def get_latitude(self, station):
        return float(self.find(station, 'lat'))

    def get_longitude(self, station):
        return float(self.find(station, 'long'))

    def get_number_available_bikes(self, station):
        return int(self.find(station, 'nbBikes'))

    def get_number_empty_docks(self, station):
        return int(self.find(station, 'nbEmptyDocks'))

    def get_public_id(self, station):
        return int(self.find(station, 'id'))

    def get_removal_date(self, station):
        return timestampToDateTime(self.find(station, 'removalDate'))

    def get_station_name(self, station):
        return self.find(station, 'name')

    def get_terminal_name(self, station):
        return self.find(station, 'terminalName')

    def is_locked(self, station):
        return self.find(station, 'locked') == 'true'

    def is_installed(self, station):
        return self.find(station, 'installed') == 'true'

    def is_public(self, station):
        raise NotImplementedError

    def is_temporary(self, station):
        return self.find(station, 'temporary') == 'true'

class XmlParser:
    def __init__(self, data, *args, **kwargs):
        tree = ElementTree.parse(data)
        self.root = tree.getroot()

    def find(self, element, field_name):
        return element.find(field_name).text

    def get_last_update_time(self):
        return timestampToDateTime(self.root.attrib['lastUpdate'])

    def get_stations(self):
        return self.root.findall('station')

class StationListParserTypeA(XmlParser, StationListParser):
    def get_last_communication_time_with_server(self, station):
        return timestampToDateTime(self.find(station, 'lastCommWithServer'))

    def get_latest_update_time(self, station):
        return timestampToDateTime(self.find(station, 'latestUpdateTime'))

    def is_public(self, station):
        return self.find(station, 'public') == 'true'

class StationListParserTypeB(XmlParser, StationListParser):
    def get_last_communication_time_with_server(self, station):
        return None

    def get_latest_update_time(self, station):
        return None

    def is_public(self, station):
        return None

class Command(BaseCommand):
    args = '<city_code city_code ...>'
    help = 'Updates the current bike and dock counts for a given list of cities.'

    def __init__(self):
        self.created = 0
        self.status_quo = 0
        self.updated = 0
        return super(Command, self).__init__()

    def _increase_created_count(self):
        self.created = self.created + 1
        self.progress('c')

    def _increase_status_quo_count(self):
        self.status_quo = self.status_quo + 1
        self.progress('.')

    def _increase_updated_count(self):
        self.updated = self.updated + 1
        self.progress('u')

    def handle(self, *args, **options):
        city_codes = args or map(lambda x: x[0], City.available.all().values_list('code'))
        parsers_module = importlib.import_module(self.__class__.__module__)

        for city_code in city_codes:
            try:
                city = City.objects.get(code=city_code)
            except City.DoesNotExist:
                raise CommandError("City '%s' does not exist." % city_code)

            xml = urllib2.urlopen(city.url)

            parsers = {City.parser_code_to_value(value): getattr(parsers_module, 'StationListParserType' + value) for value in City.PARSER_TYPES_VALUES}
            try:
                parser = parsers[city.parser_type](xml)
            except IndexError:
                raise NotImplementedError("The parser for '%s' hasn't been implemented yet." % (city.name,))

            for s in parser.get_stations():
                attrs = dict()
                public_id = parser.get_public_id(s)
                last_comm_with_server = parser.get_last_communication_time_with_server(s)
                try:
                    station = Station.objects.get(city=city, public_id=public_id)
                    # Skip if we have a timestamp to compare against
                    if last_comm_with_server and station.last_comm_with_server == last_comm_with_server:
                        self._increase_status_quo_count()
                        continue
                    # Else, update the station
                except Station.DoesNotExist:
                    station = Station()
                    attrs.update({
                        'city_id': city.pk,
                        'name': parser.get_station_name(s),
                        'public_id': public_id,
                        'terminal_name': parser.get_terminal_name(s),
                    })
                    self._increase_created_count()
                    self.progress('c')

                attrs.update({
                    'install_date': parser.get_install_date(s),
                    'installed': parser.is_installed(s),
                    'last_comm_with_server': parser.get_last_communication_time_with_server(s),
                    'lat': parser.get_latitude(s),
                    'locked': parser.is_locked(s),
                    'long': parser.get_longitude(s),
                    'public': parser.is_public(s),
                    'removal_date': parser.get_removal_date(s),
                    'temporary': parser.is_temporary(s),
                })

                if not station.last_comm_with_server:
                    skip_station = True
                    for (attr, value,) in attrs.items():
                        if not getattr(station, attr) == value:
                            # Skip the station altogether
                            skip_station = False
                            continue
                    if skip_station:
                        self._increase_status_quo_count()
                        continue

                self._increase_updated_count()

                for (k, v) in attrs.items():
                    assert k in station.__dict__, "The attribute '%s' must be an existing model field." % (k,)
                    setattr(station, k, v)
                station.save()

                latest_update_time = parser.get_latest_update_time(s)
                if Update.objects.filter(station=station,
                    latest_update_time=latest_update_time).exists():
                    continue

                nb_bikes = parser.get_number_available_bikes(s)
                nb_empty_docks = parser.get_number_empty_docks(s)
                Update.objects.create(station=station, nb_bikes=nb_bikes,
                    nb_empty_docks=nb_empty_docks,
                    latest_update_time=latest_update_time)

            last_update = parser.get_last_update_time()
            city.last_update = last_update
            city.save()

            self.stdout.write("\nSuccessfully updated bike and dock counts for " +
                "'%s'." % city.name)
            self.stdout.write('Created: %s' % self.created)
            self.stdout.write('Updated: %s' % self.updated)
            self.stdout.write('Status quo: %s' % self.status_quo)

    def progress(self, str):
        self.stdout.write(str, ending='')

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('cms', '0004_auto_20150411_1827'),
        ('blog', '0002_blogplugin'),
    ]

    operations = [
        migrations.CreateModel(
            name='BlogListPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(primary_key=True, auto_created=True, parent_link=True, serialize=False, to='cms.CMSPlugin')),
            ],
            options={
                'abstract': False,
            },
            bases=('cms.cmsplugin',),
        ),
        migrations.CreateModel(
            name='PostListPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(primary_key=True, auto_created=True, parent_link=True, serialize=False, to='cms.CMSPlugin')),
                ('blog', models.ForeignKey(to='blog.Blog')),
            ],
            options={
                'abstract': False,
            },
            bases=('cms.cmsplugin',),
        ),
        migrations.RemoveField(
            model_name='blogplugin',
            name='blog',
        ),
        migrations.RemoveField(
            model_name='blogplugin',
            name='cmsplugin_ptr',
        ),
        migrations.DeleteModel(
            name='BlogPlugin',
        ),
        migrations.AddField(
            model_name='post',
            name='body_en',
            field=models.TextField(null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='post',
            name='body_fi',
            field=models.TextField(null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='post',
            name='title_en',
            field=models.CharField(null=True, max_length=255),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='post',
            name='title_fi',
            field=models.CharField(null=True, max_length=255),
            preserve_default=True,
        ),
    ]
<commit_msg>Fix blog migration dependancy<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('cms', '0003_auto_20140926_2347'),
        ('blog', '0002_blogplugin'),
    ]

    operations = [
        migrations.CreateModel(
            name='BlogListPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(primary_key=True, auto_created=True, parent_link=True, serialize=False, to='cms.CMSPlugin')),
            ],
            options={
                'abstract': False,
            },
            bases=('cms.cmsplugin',),
        ),
        migrations.CreateModel(
            name='PostListPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(primary_key=True, auto_created=True, parent_link=True, serialize=False, to='cms.CMSPlugin')),
                ('blog', models.ForeignKey(to='blog.Blog')),
            ],
            options={
                'abstract': False,
            },
            bases=('cms.cmsplugin',),
        ),
        migrations.RemoveField(
            model_name='blogplugin',
            name='blog',
        ),
        migrations.RemoveField(
            model_name='blogplugin',
            name='cmsplugin_ptr',
        ),
        migrations.DeleteModel(
            name='BlogPlugin',
        ),
        migrations.AddField(
            model_name='post',
            name='body_en',
            field=models.TextField(null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='post',
            name='body_fi',
            field=models.TextField(null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='post',
            name='title_en',
            field=models.CharField(null=True, max_length=255),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='post',
            name='title_fi',
            field=models.CharField(null=True, max_length=255),
            preserve_default=True,
        ),
    ]
<|endoftext|>


<commit_before>#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import unittest
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import Embedding
import paddle.fluid.framework as framework
from paddle.fluid.optimizer import SGDOptimizer
from paddle.fluid.dygraph.base import to_variable
from test_imperative_base import new_program_scope
import numpy as np
import six
from paddle.fluid.backward import append_backward

class SimpleLSTMRNN(fluid.dygraph.Layer):
    def __init__(self,
                 name_scope,
                 hidden_size,
                 num_steps,
                 num_layers=2,
                 init_scale=0.1,
                 dropout=None):
        super(SimpleLSTMRNN, self).__init__(name_scope)
        self._hidden_size = hidden_size
        self._num_layers = num_layers
        self._init_scale = init_scale
        self._dropout = dropout
        self._input = None
        self._num_steps = num_steps
        self.cell_array = []
        self.hidden_array = []

    def _build_once(self, input_embedding, init_hidden=None, init_cell=None):
        self.weight_1_arr = []
        self.weight_2_arr = []
        self.bias_arr = []
        self.mask_array = []

        for i in range(self._num_layers):
            weight_1 = self.create_parameter(
                attr=fluid.ParamAttr(
                    initializer=fluid.initializer.UniformInitializer(
                        low=-self._init_scale, high=self._init_scale)),
                shape=[self._hidden_size * 2, self._hidden_size * 4],
                dtype="float32",
                default_initializer=fluid.initializer.UniformInitializer(
                    low=-self._init_scale, high=self._init_scale))
            self.weight_1_arr.append(self.add_parameter('w_%d' % i, weight_1))
            bias_1 = self.create_parameter(
                attr=fluid.ParamAttr(
                    initializer=fluid.initializer.UniformInitializer(
                        low=-self._init_scale, high=self._init_scale)),
                shape=[self._hidden_size * 4],
                dtype="float32",
                default_initializer=fluid.initializer.Constant(0.0))
            self.bias_arr.append(self.add_parameter('b_%d' % i, bias_1))

    def forward(self, input_embedding, init_hidden=None, init_cell=None):
        self.cell_array = []
        self.hidden_array = []

        for i in range(self._num_layers):
            pre_hidden = fluid.layers.slice(
                init_hidden, axes=[0], starts=[i], ends=[i + 1])
            pre_cell = fluid.layers.slice(
                init_cell, axes=[0], starts=[i], ends=[i + 1])
            pre_hidden = fluid.layers.reshape(
                pre_hidden, shape=[-1, self._hidden_size])
            pre_cell = fluid.layers.reshape(
                pre_cell, shape=[-1, self._hidden_size])
            self.hidden_array.append(pre_hidden)
            self.cell_array.append(pre_cell)

        res = []
        for index in range(self._num_steps):
            self._input = fluid.layers.slice(
                input_embedding, axes=[1], starts=[index], ends=[index + 1])
            self._input = fluid.layers.reshape(
                self._input, shape=[-1, self._hidden_size])
            for k in range(self._num_layers):
                pre_hidden = self.hidden_array[k]
                pre_cell = self.cell_array[k]
                weight_1 = self.weight_1_arr[k]
                bias = self.bias_arr[k]

                nn = fluid.layers.concat([self._input, pre_hidden], 1)
                gate_input = fluid.layers.matmul(x=nn, y=weight_1)

                gate_input = fluid.layers.elementwise_add(gate_input, bias)
                i, j, f, o = fluid.layers.split(
                    gate_input, num_or_sections=4, dim=-1)
                c = pre_cell * fluid.layers.sigmoid(f) + fluid.layers.sigmoid(
                    i) * fluid.layers.tanh(j)
                m = fluid.layers.tanh(c) * fluid.layers.sigmoid(o)
                self.hidden_array[k] = m
                self.cell_array[k] = c
                self._input = m

                if self._dropout is not None and self._dropout > 0.0:
                    self._input = fluid.layers.dropout(
                        self._input,
                        dropout_prob=self._dropout,
                        dropout_implementation='upscale_in_train')
            res.append(
                fluid.layers.reshape(
                    self._input, shape=[1, -1, self._hidden_size]))
        real_res = fluid.layers.concat(res, 0)
        real_res = fluid.layers.transpose(x=real_res, perm=[1, 0, 2])
        last_hidden = fluid.layers.concat(self.hidden_array, 1)
        last_hidden = fluid.layers.reshape(
            last_hidden, shape=[-1, self._num_layers, self._hidden_size])
        last_hidden = fluid.layers.transpose(x=last_hidden, perm=[1, 0, 2])
        last_cell = fluid.layers.concat(self.cell_array, 1)
        last_cell = fluid.layers.reshape(
            last_cell, shape=[-1, self._num_layers, self._hidden_size])
        last_cell = fluid.layers.transpose(x=last_cell, perm=[1, 0, 2])
        return real_res, last_hidden, last_cell

class PtbModel(fluid.dygraph.Layer):
    def __init__(self,
                 name_scope,
                 hidden_size,
                 vocab_size,
                 num_layers=2,
                 num_steps=20,
                 init_scale=0.1,
                 dropout=None):
        super(PtbModel, self).__init__(name_scope)
        self.hidden_size = hidden_size
        self.vocab_size = vocab_size
        self.init_scale = init_scale
        self.num_layers = num_layers
        self.num_steps = num_steps
        self.dropout = dropout
        self.simple_lstm_rnn = SimpleLSTMRNN(
            self.full_name(),
            hidden_size,
            num_steps,
            num_layers=num_layers,
            init_scale=init_scale,
            dropout=dropout)
        self.embedding = Embedding(
            self.full_name(),
            size=[vocab_size, hidden_size],
            dtype='float32',
            is_sparse=False,
            param_attr=fluid.ParamAttr(
                name='embedding_para',
                initializer=fluid.initializer.UniformInitializer(
                    low=-init_scale, high=init_scale)))
        self.softmax_weight = self.create_parameter(
            attr=fluid.ParamAttr(),
            shape=[self.hidden_size, self.vocab_size],
            dtype="float32",
            default_initializer=fluid.initializer.UniformInitializer(
                low=-self.init_scale, high=self.init_scale))
        self.softmax_bias = self.create_parameter(
            attr=fluid.ParamAttr(),
            shape=[self.vocab_size],
            dtype="float32",
            default_initializer=fluid.initializer.UniformInitializer(
                low=-self.init_scale, high=self.init_scale))

    def _build_once(self, input, label, init_hidden, init_cell):
        pass

    def forward(self, input, label, init_hidden, init_cell):
        init_h = fluid.layers.reshape(
            init_hidden, shape=[self.num_layers, -1, self.hidden_size])

        init_c = fluid.layers.reshape(
            init_cell, shape=[self.num_layers, -1, self.hidden_size])

        x_emb = self.embedding(input)
        x_emb = fluid.layers.reshape(
            x_emb, shape=[-1, self.num_steps, self.hidden_size])
        if self.dropout is not None and self.dropout > 0.0:
            x_emb = fluid.layers.dropout(
                x_emb,
                dropout_prob=self.drop_out,
                dropout_implementation='upscale_in_train')
        rnn_out, last_hidden, last_cell = self.simple_lstm_rnn(x_emb, init_h,
                                                               init_c)
        rnn_out = fluid.layers.reshape(
            rnn_out, shape=[-1, self.num_steps, self.hidden_size])
        projection = fluid.layers.matmul(rnn_out, self.softmax_weight)
        projection = fluid.layers.elementwise_add(projection, self.softmax_bias)
        projection = fluid.layers.reshape(
            projection, shape=[-1, self.vocab_size])
        projection = fluid.layers.reshape(
            projection, shape=[-1, self.vocab_size])
        loss = fluid.layers.softmax_with_cross_entropy(
            logits=projection, label=label, soft_label=False)
        loss = fluid.layers.reshape(loss, shape=[-1, self.num_steps])
        loss = fluid.layers.reduce_mean(loss, dim=[0])
        loss = fluid.layers.reduce_sum(loss)
        loss.permissions = True

        return loss, last_hidden, last_cell

class TestDygraphPtbRnn(unittest.TestCase):
    def test_ptb_rnn_cpu_float32(self):
        seed = 90
        hidden_size = 10
        vocab_size = 1000
        num_layers = 1
        num_steps = 3
        init_scale = 0.1
        batch_size = 4

        with fluid.dygraph.guard():
            fluid.default_startup_program().random_seed = seed
            fluid.default_main_program().random_seed = seed
            # TODO: marsyang1993 Change seed to
            ptb_model = PtbModel(
                "ptb_model",
                hidden_size=hidden_size,
                vocab_size=vocab_size,
                num_layers=num_layers,
                num_steps=num_steps,
                init_scale=init_scale)

            sgd = SGDOptimizer(learning_rate=1e-3)
            dy_param_updated = dict()
            dy_param_init = dict()
            dy_loss = None
            last_hidden = None
            last_cell = None
            batch_num = 200

            for i in range(batch_num):
                x_data = np.arange(12).reshape(4, 3).astype('int64')
                y_data = np.arange(1, 13).reshape(4, 3).astype('int64')
                x_data = x_data.reshape((-1, num_steps, 1))
                y_data = y_data.reshape((-1, 1))
                init_hidden_data = np.zeros(
                    (num_layers, batch_size, hidden_size), dtype='float32')
                init_cell_data = np.zeros(
                    (num_layers, batch_size, hidden_size), dtype='float32')
                x = to_variable(x_data)
                y = to_variable(y_data)
                init_hidden = to_variable(init_hidden_data)
                init_cell = to_variable(init_cell_data)
                dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden,
                                                            init_cell)
                if i == 0:
                    for param in ptb_model.parameters():
                        dy_param_init[param.name] = param._numpy()
                dy_loss._backward()
                sgd.minimize(dy_loss)
                ptb_model.clear_gradients()
                if i == batch_num - 1:
                    for param in ptb_model.parameters():
                        dy_param_updated[param.name] = param._numpy()

        with new_program_scope():
            fluid.default_startup_program().random_seed = seed
            fluid.default_main_program().random_seed = seed
            ptb_model = PtbModel(
                "ptb_model",
                hidden_size=hidden_size,
                vocab_size=vocab_size,
                num_layers=num_layers,
                num_steps=num_steps,
                init_scale=init_scale)

            exe = fluid.Executor(fluid.CPUPlace())
            sgd = SGDOptimizer(learning_rate=1e-3)
            x = fluid.layers.data(name="x", shape=[-1, 3, 1], dtype='int64')
            y = fluid.layers.data(name="y", shape=[-1, 1], dtype='float32')
            init_hidden = fluid.layers.data(
                name="init_hidden", shape=[1], dtype='float32')
            init_cell = fluid.layers.data(
                name="init_cell", shape=[1], dtype='float32')

            static_loss, static_last_hidden, static_last_cell = ptb_model(
                x, y, init_hidden, init_cell)
            sgd.minimize(static_loss)
            static_param_updated = dict()
            static_param_init = dict()
            static_param_name_list = list()
            for param in ptb_model.parameters():
                static_param_name_list.append(param.name)

            out = exe.run(framework.default_startup_program(),
                          fetch_list=static_param_name_list)
            for i in range(len(static_param_name_list)):
                static_param_init[static_param_name_list[i]] = out[i]
            static_loss_value = None
            static_last_cell_value = None
            static_last_hidden_value = None
            for i in range(batch_num):
                x_data = np.arange(12).reshape(4, 3).astype('int64')
                y_data = np.arange(1, 13).reshape(4, 3).astype('int64')
                x_data = x_data.reshape((-1, num_steps, 1))
                y_data = y_data.reshape((-1, 1))
                init_hidden_data = np.zeros(
                    (num_layers, batch_size, hidden_size), dtype='float32')
                init_cell_data = np.zeros(
                    (num_layers, batch_size, hidden_size), dtype='float32')
                fetch_list = [static_loss, static_last_hidden, static_last_cell]
                fetch_list.extend(static_param_name_list)
                out = exe.run(fluid.default_main_program(),
                              feed={
                                  "x": x_data,
                                  "y": y_data,
                                  "init_hidden": init_hidden_data,
                                  "init_cell": init_cell_data
                              },
                              fetch_list=fetch_list)
                static_loss_value = out[0]
                static_last_hidden_value = out[1]
                static_last_cell_value = out[2]

                if i == batch_num - 1:
                    for k in range(3, len(out)):
                        static_param_updated[static_param_name_list[k -
                                                                    3]] = out[k]

        self.assertTrue(np.allclose(static_loss_value, dy_loss._numpy()))
        self.assertTrue(np.allclose(static_last_cell_value, last_cell._numpy()))
        self.assertTrue(
            np.allclose(static_last_hidden_value, last_hidden._numpy()))
        for key, value in six.iteritems(static_param_init):
            # print("static_init name: {}, value {}".format(key, value))
            # print("dy_init name: {}, value {}".format(key, dy_param_init[key]))
            self.assertTrue(np.allclose(value, dy_param_init[key], atol=1e-5))
        for key, value in six.iteritems(static_param_updated):
            # print("static name: {}, value {}".format(key, value))
            # print("dy name: {}, value {}".format(key, dy_param_updated[key]))
            self.assertTrue(
                np.allclose(
                    value, dy_param_updated[key], atol=1e-5))

if __name__ == '__main__':
    unittest.main()
<commit_msg>test=develop, ptb_rnn fix op (#16573)<commit_after>#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import unittest
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import Embedding
import paddle.fluid.framework as framework
from paddle.fluid.optimizer import SGDOptimizer
from paddle.fluid.dygraph.base import to_variable
from test_imperative_base import new_program_scope
import numpy as np
import six
from paddle.fluid.backward import append_backward

class SimpleLSTMRNN(fluid.dygraph.Layer):
    def __init__(self,
                 name_scope,
                 hidden_size,
                 num_steps,
                 num_layers=2,
                 init_scale=0.1,
                 dropout=None):
        super(SimpleLSTMRNN, self).__init__(name_scope)
        self._hidden_size = hidden_size
        self._num_layers = num_layers
        self._init_scale = init_scale
        self._dropout = dropout
        self._input = None
        self._num_steps = num_steps
        self.cell_array = []
        self.hidden_array = []

    def _build_once(self, input_embedding, init_hidden=None, init_cell=None):
        self.weight_1_arr = []
        self.weight_2_arr = []
        self.bias_arr = []
        self.mask_array = []

        for i in range(self._num_layers):
            weight_1 = self.create_parameter(
                attr=fluid.ParamAttr(
                    initializer=fluid.initializer.UniformInitializer(
                        low=-self._init_scale, high=self._init_scale)),
                shape=[self._hidden_size * 2, self._hidden_size * 4],
                dtype="float32",
                default_initializer=fluid.initializer.UniformInitializer(
                    low=-self._init_scale, high=self._init_scale))
            self.weight_1_arr.append(self.add_parameter('w_%d' % i, weight_1))
            bias_1 = self.create_parameter(
                attr=fluid.ParamAttr(
                    initializer=fluid.initializer.UniformInitializer(
                        low=-self._init_scale, high=self._init_scale)),
                shape=[self._hidden_size * 4],
                dtype="float32",
                default_initializer=fluid.initializer.Constant(0.0))
            self.bias_arr.append(self.add_parameter('b_%d' % i, bias_1))

    def forward(self, input_embedding, init_hidden=None, init_cell=None):
        self.cell_array = []
        self.hidden_array = []

        for i in range(self._num_layers):
            pre_hidden = fluid.layers.slice(
                init_hidden, axes=[0], starts=[i], ends=[i + 1])
            pre_cell = fluid.layers.slice(
                init_cell, axes=[0], starts=[i], ends=[i + 1])
            pre_hidden = fluid.layers.reshape(
                pre_hidden, shape=[-1, self._hidden_size])
            pre_cell = fluid.layers.reshape(
                pre_cell, shape=[-1, self._hidden_size])
            self.hidden_array.append(pre_hidden)
            self.cell_array.append(pre_cell)

        res = []
        for index in range(self._num_steps):
            self._input = fluid.layers.slice(
                input_embedding, axes=[1], starts=[index], ends=[index + 1])
            self._input = fluid.layers.reshape(
                self._input, shape=[-1, self._hidden_size])
            for k in range(self._num_layers):
                pre_hidden = self.hidden_array[k]
                pre_cell = self.cell_array[k]
                weight_1 = self.weight_1_arr[k]
                bias = self.bias_arr[k]

                nn = fluid.layers.concat([self._input, pre_hidden], 1)
                gate_input = fluid.layers.matmul(x=nn, y=weight_1)

                gate_input = fluid.layers.elementwise_add(gate_input, bias)
                i, j, f, o = fluid.layers.split(
                    gate_input, num_or_sections=4, dim=-1)
                c = pre_cell * fluid.layers.sigmoid(f) + fluid.layers.sigmoid(
                    i) * fluid.layers.tanh(j)
                m = fluid.layers.tanh(c) * fluid.layers.sigmoid(o)
                self.hidden_array[k] = m
                self.cell_array[k] = c
                self._input = m

                if self._dropout is not None and self._dropout > 0.0:
                    self._input = fluid.layers.dropout(
                        self._input,
                        dropout_prob=self._dropout,
                        dropout_implementation='upscale_in_train')
            res.append(
                fluid.layers.reshape(
                    self._input, shape=[1, -1, self._hidden_size]))
        real_res = fluid.layers.concat(res, 0)
        real_res = fluid.layers.transpose(x=real_res, perm=[1, 0, 2])
        last_hidden = fluid.layers.concat(self.hidden_array, 1)
        last_hidden = fluid.layers.reshape(
            last_hidden, shape=[-1, self._num_layers, self._hidden_size])
        last_hidden = fluid.layers.transpose(x=last_hidden, perm=[1, 0, 2])
        last_cell = fluid.layers.concat(self.cell_array, 1)
        last_cell = fluid.layers.reshape(
            last_cell, shape=[-1, self._num_layers, self._hidden_size])
        last_cell = fluid.layers.transpose(x=last_cell, perm=[1, 0, 2])
        return real_res, last_hidden, last_cell

class PtbModel(fluid.dygraph.Layer):
    def __init__(self,
                 name_scope,
                 hidden_size,
                 vocab_size,
                 num_layers=2,
                 num_steps=20,
                 init_scale=0.1,
                 dropout=None):
        super(PtbModel, self).__init__(name_scope)
        self.hidden_size = hidden_size
        self.vocab_size = vocab_size
        self.init_scale = init_scale
        self.num_layers = num_layers
        self.num_steps = num_steps
        self.dropout = dropout
        self.simple_lstm_rnn = SimpleLSTMRNN(
            self.full_name(),
            hidden_size,
            num_steps,
            num_layers=num_layers,
            init_scale=init_scale,
            dropout=dropout)
        self.embedding = Embedding(
            self.full_name(),
            size=[vocab_size, hidden_size],
            dtype='float32',
            is_sparse=False,
            param_attr=fluid.ParamAttr(
                name='embedding_para',
                initializer=fluid.initializer.UniformInitializer(
                    low=-init_scale, high=init_scale)))
        self.softmax_weight = self.create_parameter(
            attr=fluid.ParamAttr(),
            shape=[self.hidden_size, self.vocab_size],
            dtype="float32",
            default_initializer=fluid.initializer.UniformInitializer(
                low=-self.init_scale, high=self.init_scale))
        self.softmax_bias = self.create_parameter(
            attr=fluid.ParamAttr(),
            shape=[self.vocab_size],
            dtype="float32",
            default_initializer=fluid.initializer.UniformInitializer(
                low=-self.init_scale, high=self.init_scale))

    def _build_once(self, input, label, init_hidden, init_cell):
        pass

    def forward(self, input, label, init_hidden, init_cell):
        init_h = fluid.layers.reshape(
            init_hidden, shape=[self.num_layers, -1, self.hidden_size])

        init_c = fluid.layers.reshape(
            init_cell, shape=[self.num_layers, -1, self.hidden_size])

        x_emb = self.embedding(input)
        x_emb = fluid.layers.reshape(
            x_emb, shape=[-1, self.num_steps, self.hidden_size])
        if self.dropout is not None and self.dropout > 0.0:
            x_emb = fluid.layers.dropout(
                x_emb,
                dropout_prob=self.drop_out,
                dropout_implementation='upscale_in_train')
        rnn_out, last_hidden, last_cell = self.simple_lstm_rnn(x_emb, init_h,
                                                               init_c)
        rnn_out = fluid.layers.reshape(
            rnn_out, shape=[-1, self.num_steps, self.hidden_size])
        projection = fluid.layers.matmul(rnn_out, self.softmax_weight)
        projection = fluid.layers.elementwise_add(projection, self.softmax_bias)
        projection = fluid.layers.reshape(
            projection, shape=[-1, self.vocab_size])
        loss = fluid.layers.softmax_with_cross_entropy(
            logits=projection, label=label, soft_label=False)
        loss = fluid.layers.reshape(loss, shape=[-1, self.num_steps])
        loss = fluid.layers.reduce_mean(loss, dim=[0])
        loss = fluid.layers.reduce_sum(loss)
        loss.permissions = True

        return loss, last_hidden, last_cell

class TestDygraphPtbRnn(unittest.TestCase):
    def test_ptb_rnn_cpu_float32(self):
        seed = 90
        hidden_size = 10
        vocab_size = 1000
        num_layers = 1
        num_steps = 3
        init_scale = 0.1
        batch_size = 4
        batch_num = 200

        with fluid.dygraph.guard():
            fluid.default_startup_program().random_seed = seed
            fluid.default_main_program().random_seed = seed
            # TODO: marsyang1993 Change seed to
            ptb_model = PtbModel(
                "ptb_model",
                hidden_size=hidden_size,
                vocab_size=vocab_size,
                num_layers=num_layers,
                num_steps=num_steps,
                init_scale=init_scale)

            sgd = SGDOptimizer(learning_rate=1e-3)
            dy_param_updated = dict()
            dy_param_init = dict()
            dy_loss = None
            last_hidden = None
            last_cell = None

            for i in range(batch_num):
                x_data = np.arange(12).reshape(4, 3).astype('int64')
                y_data = np.arange(1, 13).reshape(4, 3).astype('int64')
                x_data = x_data.reshape((-1, num_steps, 1))
                y_data = y_data.reshape((-1, 1))
                init_hidden_data = np.zeros(
                    (num_layers, batch_size, hidden_size), dtype='float32')
                init_cell_data = np.zeros(
                    (num_layers, batch_size, hidden_size), dtype='float32')
                x = to_variable(x_data)
                y = to_variable(y_data)
                init_hidden = to_variable(init_hidden_data)
                init_cell = to_variable(init_cell_data)
                dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden,
                                                            init_cell)
                if i == 0:
                    for param in ptb_model.parameters():
                        dy_param_init[param.name] = param._numpy()
                dy_loss._backward()
                sgd.minimize(dy_loss)
                ptb_model.clear_gradients()
                if i == batch_num - 1:
                    for param in ptb_model.parameters():
                        dy_param_updated[param.name] = param._numpy()

        with new_program_scope():
            fluid.default_startup_program().random_seed = seed
            fluid.default_main_program().random_seed = seed
            ptb_model = PtbModel(
                "ptb_model",
                hidden_size=hidden_size,
                vocab_size=vocab_size,
                num_layers=num_layers,
                num_steps=num_steps,
                init_scale=init_scale)

            exe = fluid.Executor(fluid.CPUPlace())
            sgd = SGDOptimizer(learning_rate=1e-3)
            x = fluid.layers.data(
                name="x", shape=[-1, num_steps, 1], dtype='int64')
            y = fluid.layers.data(name="y", shape=[-1, 1], dtype='float32')
            init_hidden = fluid.layers.data(
                name="init_hidden", shape=[1], dtype='float32')
            init_cell = fluid.layers.data(
                name="init_cell", shape=[1], dtype='float32')

            static_loss, static_last_hidden, static_last_cell = ptb_model(
                x, y, init_hidden, init_cell)
            sgd.minimize(static_loss)
            static_param_updated = dict()
            static_param_init = dict()
            static_param_name_list = list()
            for param in ptb_model.parameters():
                static_param_name_list.append(param.name)

            out = exe.run(framework.default_startup_program(),
                          fetch_list=static_param_name_list)
            for i in range(len(static_param_name_list)):
                static_param_init[static_param_name_list[i]] = out[i]
            static_loss_value = None
            static_last_cell_value = None
            static_last_hidden_value = None
            for i in range(batch_num):
                x_data = np.arange(12).reshape(4, 3).astype('int64')
                y_data = np.arange(1, 13).reshape(4, 3).astype('int64')
                x_data = x_data.reshape((-1, num_steps, 1))
                y_data = y_data.reshape((-1, 1))
                init_hidden_data = np.zeros(
                    (num_layers, batch_size, hidden_size), dtype='float32')
                init_cell_data = np.zeros(
                    (num_layers, batch_size, hidden_size), dtype='float32')
                fetch_list = [static_loss, static_last_hidden, static_last_cell]
                fetch_list.extend(static_param_name_list)
                out = exe.run(fluid.default_main_program(),
                              feed={
                                  "x": x_data,
                                  "y": y_data,
                                  "init_hidden": init_hidden_data,
                                  "init_cell": init_cell_data
                              },
                              fetch_list=fetch_list)
                static_loss_value = out[0]
                static_last_hidden_value = out[1]
                static_last_cell_value = out[2]

                if i == batch_num - 1:
                    for k in range(3, len(out)):
                        static_param_updated[static_param_name_list[k -
                                                                    3]] = out[k]
        self.assertTrue(np.allclose(static_loss_value, dy_loss._numpy()))
        self.assertTrue(np.allclose(static_last_cell_value, last_cell._numpy()))
        self.assertTrue(
            np.allclose(static_last_hidden_value, last_hidden._numpy()))
        for key, value in six.iteritems(static_param_init):
            # print("static_init name: {}, value {}".format(key, value))
            # print("dy_init name: {}, value {}".format(key, dy_param_init[key]))
            self.assertTrue(np.allclose(value, dy_param_init[key]))
        for key, value in six.iteritems(static_param_updated):
            # print("static name: {}, value {}".format(key, value))
            # print("dy name: {}, value {}".format(key, dy_param_updated[key]))
            self.assertTrue(np.allclose(value, dy_param_updated[key]))

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


<commit_before>from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _

from mooch.base import BaseMoocher, require_POST_m
from mooch.signals import post_charge

class BankTransferMoocher(BaseMoocher):
    identifier = 'banktransfer'
    title = _('Pay by bank transfer')

    def get_urls(self):
        return [
            url('^confirm/$', self.confirm_view, name='banktransfer_confirm'),
        ]

    def payment_form(self, request, payment):
        return render_to_string('mooch/banktransfer_payment_form.html', {
            'payment': payment,
            'moocher': self,
        }, request=request)

    @require_POST_m
    def confirm_view(self, request):
        instance = get_object_or_404(self.model, id=request.POST.get('id'))
        instance.payment_service_provider = self.identifier
        instance.transaction = repr(request.META.copy())
        instance.save()

        post_charge.send(
            sender=self.__class__,
            payment=instance,
            request=request,
        )

        return http.HttpResponseRedirect('/')  # TODO
<commit_msg>Set charged_at when confirming a bank transfer<commit_after>from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from mooch.base import BaseMoocher, require_POST_m
from mooch.signals import post_charge

class BankTransferMoocher(BaseMoocher):
    identifier = 'banktransfer'
    title = _('Pay by bank transfer')

    def get_urls(self):
        return [
            url('^confirm/$', self.confirm_view, name='banktransfer_confirm'),
        ]

    def payment_form(self, request, payment):
        return render_to_string('mooch/banktransfer_payment_form.html', {
            'payment': payment,
            'moocher': self,
        }, request=request)

    @require_POST_m
    def confirm_view(self, request):
        instance = get_object_or_404(self.model, id=request.POST.get('id'))
        instance.payment_service_provider = self.identifier
        instance.charged_at = timezone.now()
        instance.transaction = repr(request.META.copy())
        instance.save()

        post_charge.send(
            sender=self.__class__,
            payment=instance,
            request=request,
        )

        return http.HttpResponseRedirect('/')  # TODO
<|endoftext|>


<commit_before># coding: utf-8

from qingcloud.cli.misc.json_tool import json_load
from qingcloud.cli.iaas_client.actions.base import BaseAction

class AddRouterStaticsAction(BaseAction):

    action = 'AddRouterStatics'
    command = 'add-router-statics'
    usage = '%(prog) -r <router_id> -v <vxnet_id> -s <statics> [-f <conf_file>]'

    @classmethod
    def add_ext_arguments(cls, parser):
        parser.add_argument('-r', '--router', dest='router',
                action='store', type=str, default='',
                help='The ID of router whose statics you want to add. ')

        parser.add_argument('-s', '--statics', dest='statics',
                action='store', type=str, default='',
                help='''
                JSON string of rules list. e.g.
                '[{"static_type":0,"val1":"i-12345678","val2":"192.168.99.2","val3":"52:54:29:5c:de:a5","vxnet":"vxnet-1234567"},
                {"static_type":1,"val1":"80","val2":"192.168.99.2","val3":"8000"}]'
                ''')

    @classmethod
    def build_directive(cls, options):
        required_params = {
                'router': options.router,
                'statics': options.statics,
                }
        for param in required_params:
            if required_params[param] is None or required_params[param] == '':
                print 'param [%s] should be specified' % param
                return None

        return {
                'router': options.router,
                'statics': json_load(options.statics),
                }
<commit_msg>Update help msg<commit_after># coding: utf-8

from qingcloud.cli.misc.json_tool import json_load
from qingcloud.cli.iaas_client.actions.base import BaseAction

class AddRouterStaticsAction(BaseAction):

    action = 'AddRouterStatics'
    command = 'add-router-statics'
    usage = '%(prog) -r <router_id> -v <vxnet_id> -s <statics> [-f <conf_file>]'

    @classmethod
    def add_ext_arguments(cls, parser):
        parser.add_argument('-r', '--router', dest='router',
                action='store', type=str, default='',
                help='The ID of router you want to add statics to.')

        parser.add_argument('-s', '--statics', dest='statics',
                action='store', type=str, default='',
                help='''
                JSON string of static list. e.g.
                '[{"static_type":0,"val1":"i-12345678","val2":"192.168.99.2","val3":"52:54:29:5c:de:a5","vxnet":"vxnet-1234567"},
                {"static_type":1,"val1":"80","val2":"192.168.99.2","val3":"8000"}]'
                ''')

    @classmethod
    def build_directive(cls, options):
        required_params = {
                'router': options.router,
                'statics': options.statics,
                }
        for param in required_params:
            if required_params[param] is None or required_params[param] == '':
                print 'param [%s] should be specified' % param
                return None

        return {
                'router': options.router,
                'statics': json_load(options.statics),
                }
<|endoftext|>


<commit_before>import re
import pathlib
import itertools
import json
from .math_utils import mean_confidence, jain_fairness
from collections import OrderedDict

def iostat_cpu(directory, settings_hash):
    with directory.joinpath(settings_hash + '.cpu').open() as file_handler:
        keys = ('user', 'nice', 'system', 'iowait', 'steal', 'idle')
        values_list = [[], [], [], [], [], []]
        skip_line = False
        for line in file_handler:
            if skip_line or line.startswith('avg-cpu:'):
                skip_line = not skip_line  # if there's avg-cpu, we skip two lines
                continue
            row = map(float, line.split())
            for i, v in enumerate(row):
                values_list[i].append(v)
        cpu = {keys[i]: mean_confidence(values) for i, values in enumerate(values_list)}
        return cpu

def iperf(directory, settings_hash, settings):
    with directory.joinpath(settings_hash + '.throughput').open() as file_handler:
        values = [int(line.rstrip()) for line in file_handler]
    return {'throughput': mean_confidence(values)}

def read_jsons(file_handler):
    # read all from file_handler, splitting
    json_strings = []
    current_json = ''
    for line in file_handler:
        if line.startswith('{'):
            if len(current_json):
                json_strings.append(current_json)
            current_json = line
        else:
            current_json += line
    json_strings.append(current_json)  # the last one, don't forget this poor guy!
    # do the actual conversion from json to Python dict
    json_dicts = []
    for json_str in json_strings:
        json_dicts.append(json.loads(json_str))
    return json_dicts

def iperf3(directory, settings_hash, settings):
    with directory.joinpath(settings_hash + '.iperf3').open() as file_handler:
        json_dicts = read_jsons(file_handler)
    throughputs = []
    cpu_utilizations = []
    fairnesses = []
    for json_dict in json_dicts:
        json_end = json_dict['end']
        throughputs.append(json_end['sum_received']['bytes'] / json_end['sum_received']['seconds'] * 8)
        cpu_utilizations.append((json_end['cpu_utilization_percent']['host_total'], json_end['cpu_utilization_percent']['remote_total']))
        bytes_streams = [stream['receiver']['bytes'] for stream in json_end['streams']]
        fairnesses.append(jain_fairness(bytes_streams))
    return {
        'throughput': mean_confidence(throughputs),
        'cpu': {'host': mean_confidence([x[0] for x in cpu_utilizations]), 'remote': mean_confidence([x[1] for x in cpu_utilizations])},
        'fairness': mean_confidence(fairnesses),
    }

def iperf3m(directory, settings_hash, settings):
    json_dicts = [None] * settings['parallelism']
    for i in range(settings['parallelism']):
        with directory.joinpath('{}.iperf3.{}'.format(settings_hash, i + 1)).open() as file_handler:
            json_dicts[i] = read_jsons(file_handler)
            if i > 0 and len(json_dicts[i - 1]) != len(json_dicts[i]):
                raise ValueError('Something went wrong on {}: I expected to have the same number of tests on all the threads.'.format(settings_hash))
    tests_count = len(json_dicts[i])
    throughputs = []
    fairnesses = []
    for test_num in range(tests_count):
        throughput = 0
        bytes_streams = []
        for thread_id in range(settings['parallelism']):
            json_end = json_dicts[thread_id][test_num]['end']
            throughput += json_end['sum_received']['bytes'] / json_end['sum_received']['seconds'] * 8
            bytes_streams.append(json_end['sum_received']['bytes'])
        throughputs.append(throughput)
        fairnesses.append(jain_fairness(bytes_streams))
    return {
        'throughput': mean_confidence(throughputs),
        #'cpu': not clear: how should I interpret the results from iperf3?
        'fairness': mean_confidence(fairnesses),
    }

def get_chain_analysis(db_query, row_info_fn, grouping_fn=lambda row_element: (0,)):
    columns = sorted(list(set((r['chain_len'] for r in db_query))))
    rows = {}  # key => {label => label of the serie, color => color, row => [db record, ...]}
    for r in db_query:
        key, label, color = row_info_fn(r)
        if key not in rows:
            rows[key] = {'label': label, 'color': color, 'row': [None] * len(columns)}
        col_index = columns.index(r['chain_len'])
        if rows[key]['row'][col_index] is not None:
            raise ValueError("Multiple values for serie '{}' at chain_len '{}'.\nHere's the two we have now:\n{}\nand\n{}".format(label, r['chain_len'], r, rows[key]['row'][col_index]))
        rows[key]['row'][col_index] = r

    rows_sorted = OrderedDict()  # label => {label => label of the serie, color => color, row => [db record, ...]}
    rows_grouped = {}  # group_id => OrderedDict(*as above*)
    for k in sorted(rows.keys()):
        row = rows[k]
        rows_sorted[row['label']] = row
        first_obj = [c for c in row['row'] if c is not None][0]
        for group_id in grouping_fn(first_obj):
            if group_id not in rows_grouped:
                rows_grouped[group_id] = OrderedDict()
            rows_grouped[group_id][row['label']] = row
    rows_grouped_sorted = OrderedDict([(i, rows_grouped[i]) for i in sorted(rows_grouped.keys())])

    return columns, rows_sorted, rows_grouped_sorted
<commit_msg>float throughput for iperf3<commit_after>import re
import pathlib
import itertools
import json
from .math_utils import mean_confidence, jain_fairness
from collections import OrderedDict

def iostat_cpu(directory, settings_hash):
    with directory.joinpath(settings_hash + '.cpu').open() as file_handler:
        keys = ('user', 'nice', 'system', 'iowait', 'steal', 'idle')
        values_list = [[], [], [], [], [], []]
        skip_line = False
        for line in file_handler:
            if skip_line or line.startswith('avg-cpu:'):
                skip_line = not skip_line  # if there's avg-cpu, we skip two lines
                continue
            row = map(float, line.split())
            for i, v in enumerate(row):
                values_list[i].append(v)
        cpu = {keys[i]: mean_confidence(values) for i, values in enumerate(values_list)}
        return cpu

def iperf(directory, settings_hash, settings):
    with directory.joinpath(settings_hash + '.throughput').open() as file_handler:
        values = [int(line.rstrip()) for line in file_handler]
    return {'throughput': mean_confidence(values)}

def read_jsons(file_handler):
    # read all from file_handler, splitting
    json_strings = []
    current_json = ''
    for line in file_handler:
        if line.startswith('{'):
            if len(current_json):
                json_strings.append(current_json)
            current_json = line
        else:
            current_json += line
    json_strings.append(current_json)  # the last one, don't forget this poor guy!
    # do the actual conversion from json to Python dict
    json_dicts = []
    for json_str in json_strings:
        json_dicts.append(json.loads(json_str))
    return json_dicts

def iperf3(directory, settings_hash, settings):
    with directory.joinpath(settings_hash + '.iperf3').open() as file_handler:
        json_dicts = read_jsons(file_handler)
    throughputs = []
    cpu_utilizations = []
    fairnesses = []
    for json_dict in json_dicts:
        json_end = json_dict['end']
        throughputs.append(8.0 * json_end['sum_received']['bytes'] / json_end['sum_received']['seconds'])
        cpu_utilizations.append((json_end['cpu_utilization_percent']['host_total'], json_end['cpu_utilization_percent']['remote_total']))
        bytes_streams = [stream['receiver']['bytes'] for stream in json_end['streams']]
        fairnesses.append(jain_fairness(bytes_streams))
    return {
        'throughput': mean_confidence(throughputs),
        'cpu': {'host': mean_confidence([x[0] for x in cpu_utilizations]), 'remote': mean_confidence([x[1] for x in cpu_utilizations])},
        'fairness': mean_confidence(fairnesses),
    }

def iperf3m(directory, settings_hash, settings):
    json_dicts = [None] * settings['parallelism']
    for i in range(settings['parallelism']):
        with directory.joinpath('{}.iperf3.{}'.format(settings_hash, i + 1)).open() as file_handler:
            json_dicts[i] = read_jsons(file_handler)
            if i > 0 and len(json_dicts[i - 1]) != len(json_dicts[i]):
                raise ValueError('Something went wrong on {}: I expected to have the same number of tests on all the threads.'.format(settings_hash))
    tests_count = len(json_dicts[i])
    throughputs = []
    fairnesses = []
    for test_num in range(tests_count):
        throughput = 0
        bytes_streams = []
        for thread_id in range(settings['parallelism']):
            json_end = json_dicts[thread_id][test_num]['end']
            throughput += 8.0 * json_end['sum_received']['bytes'] / json_end['sum_received']['seconds']
            bytes_streams.append(json_end['sum_received']['bytes'])
        throughputs.append(throughput)
        fairnesses.append(jain_fairness(bytes_streams))
    return {
        'throughput': mean_confidence(throughputs),
        #'cpu': not clear: how should I interpret the results from iperf3?
        'fairness': mean_confidence(fairnesses),
    }

def get_chain_analysis(db_query, row_info_fn, grouping_fn=lambda row_element: (0,)):
    columns = sorted(list(set((r['chain_len'] for r in db_query))))
    rows = {}  # key => {label => label of the serie, color => color, row => [db record, ...]}
    for r in db_query:
        key, label, color = row_info_fn(r)
        if key not in rows:
            rows[key] = {'label': label, 'color': color, 'row': [None] * len(columns)}
        col_index = columns.index(r['chain_len'])
        if rows[key]['row'][col_index] is not None:
            raise ValueError("Multiple values for serie '{}' at chain_len '{}'.\nHere's the two we have now:\n{}\nand\n{}".format(label, r['chain_len'], r, rows[key]['row'][col_index]))
        rows[key]['row'][col_index] = r

    rows_sorted = OrderedDict()  # label => {label => label of the serie, color => color, row => [db record, ...]}
    rows_grouped = {}  # group_id => OrderedDict(*as above*)
    for k in sorted(rows.keys()):
        row = rows[k]
        rows_sorted[row['label']] = row
        first_obj = [c for c in row['row'] if c is not None][0]
        for group_id in grouping_fn(first_obj):
            if group_id not in rows_grouped:
                rows_grouped[group_id] = OrderedDict()
            rows_grouped[group_id][row['label']] = row
    rows_grouped_sorted = OrderedDict([(i, rows_grouped[i]) for i in sorted(rows_grouped.keys())])

    return columns, rows_sorted, rows_grouped_sorted
<|endoftext|>


<commit_before>from __future__ import unicode_literals

import pygst
pygst.require('0.10')
import gst

def calculate_duration(num_samples, sample_rate):
    """Determine duration of samples using GStreamer helper for precise math."""
    return gst.util_uint64_scale(num_samples, gst.SECOND, sample_rate)

def create_buffer(data, capabilites=None, timestamp=None, duration=None):
    """Create a new GStreamer buffer based on provided data.

    Mainly intended to keep gst imports out of non-audio modules.
    """
    buffer_ = gst.Buffer(data)
    if capabilites:
        if isinstance(capabilites, basestring):
            capabilites = gst.caps_from_string(capabilites)
        buffer_.set_caps(capabilites)
    if timestamp:
        buffer_.timestamp = timestamp
    if duration:
        buffer_.duration = duration
    return buffer_

def millisecond_to_clocktime(value):
    """Convert a millisecond time to internal gstreamer time."""
    return value * gst.MSECOND

def supported_uri_schemes(uri_schemes):
    """Determine which URIs we can actually support from provided whitelist.

    :param uri_schemes: list/set of URIs to check support for.
    :type uri_schemes: list or set or URI schemes as strings.
    :rtype: set of URI schemes we can support via this GStreamer install.
    """
    supported_schemes = set()
    registry = gst.registry_get_default()

    for factory in registry.get_feature_list(gst.TYPE_ELEMENT_FACTORY):
        for uri in factory.get_uri_protocols():
            if uri in uri_schemes:
                supported_schemes.add(uri)

    return supported_schemes
<commit_msg>audio: Add clocktime_to_millisecond util function<commit_after>from __future__ import unicode_literals

import pygst
pygst.require('0.10')
import gst

def calculate_duration(num_samples, sample_rate):
    """Determine duration of samples using GStreamer helper for precise
    math."""
    return gst.util_uint64_scale(num_samples, gst.SECOND, sample_rate)

def create_buffer(data, capabilites=None, timestamp=None, duration=None):
    """Create a new GStreamer buffer based on provided data.

    Mainly intended to keep gst imports out of non-audio modules.
    """
    buffer_ = gst.Buffer(data)
    if capabilites:
        if isinstance(capabilites, basestring):
            capabilites = gst.caps_from_string(capabilites)
        buffer_.set_caps(capabilites)
    if timestamp:
        buffer_.timestamp = timestamp
    if duration:
        buffer_.duration = duration
    return buffer_

def millisecond_to_clocktime(value):
    """Convert a millisecond time to internal GStreamer time."""
    return value * gst.MSECOND

def clocktime_to_millisecond(value):
    """Convert a millisecond time to internal GStreamer time."""
    return value // gst.MSECOND

def supported_uri_schemes(uri_schemes):
    """Determine which URIs we can actually support from provided whitelist.

    :param uri_schemes: list/set of URIs to check support for.
    :type uri_schemes: list or set or URI schemes as strings.
    :rtype: set of URI schemes we can support via this GStreamer install.
    """
    supported_schemes = set()
    registry = gst.registry_get_default()

    for factory in registry.get_feature_list(gst.TYPE_ELEMENT_FACTORY):
        for uri in factory.get_uri_protocols():
            if uri in uri_schemes:
                supported_schemes.add(uri)

    return supported_schemes
<|endoftext|>