<commit_before>import subprocess
import unittest

import git_gate

class TestParseArgs(unittest.TestCase):

    def test_project_only(self):
        args = git_gate.parse_args(["--project", "git.testing/project"])
        self.assertEqual(args.project, "git.testing/project")

    def test_project_and_ref(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project",
             "--project-ref", "v1"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.project_ref, "v1")

    def test_merging_other(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project",
             "--merge-url", "git.testing/proposed"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.merge_url, "git.testing/proposed")
        self.assertEqual(args.merge_ref, "HEAD")

    def test_merging_other_ref(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project",
             "--merge-url", "git.testing/proposed", "--merge-ref", "feature"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.merge_url, "git.testing/proposed")
        self.assertEqual(args.merge_ref, "feature")

    def test_project_with_deps(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project",
             "--dependencies", "git.testing/a", "git.testing/b"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.dependencies, ["git.testing/a", "git.testing/b"])
        self.assertEqual(args.go_get_all, False)

    def test_project_with_go_deps(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project", "--go-get-all"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.dependencies, None)
        self.assertEqual(args.go_get_all, True)

class TestSubcommandError(unittest.TestCase):

    def test_subcommand_error(self):
        proc_error = subprocess.CalledProcessError(1, ["git"])
        err = git_gate.SubcommandError("git", "clone", proc_error)
        self.assertEqual(str(err), "Subprocess git clone failed with code 1")
<commit_msg>Fix git gate arg tests given added restriction<commit_after>import subprocess
import unittest

import git_gate

class TestParseArgs(unittest.TestCase):

    def test_project_and_url(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project",
             "--project-url", "https://git.testing/project"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.project_url, "https://git.testing/project")

    def test_project_and_ref(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project", "--go-get-all",
             "--project-ref", "v1"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.project_ref, "v1")

    def test_merging_other(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project", "--go-get-all",
             "--merge-url", "git.testing/proposed"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.merge_url, "git.testing/proposed")
        self.assertEqual(args.merge_ref, "HEAD")

    def test_merging_other_ref(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project", "--go-get-all",
             "--merge-url", "git.testing/proposed", "--merge-ref", "feature"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.merge_url, "git.testing/proposed")
        self.assertEqual(args.merge_ref, "feature")

    def test_project_with_deps(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project",
             "--project-url", "https://git.testing/project",
             "--dependencies", "git.testing/a", "git.testing/b"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.project_url, "https://git.testing/project")
        self.assertEqual(args.dependencies, ["git.testing/a", "git.testing/b"])
        self.assertEqual(args.go_get_all, False)

    def test_project_with_go_deps(self):
        args = git_gate.parse_args(
            ["--project", "git.testing/project", "--go-get-all"])
        self.assertEqual(args.project, "git.testing/project")
        self.assertEqual(args.dependencies, None)
        self.assertEqual(args.go_get_all, True)

class TestSubcommandError(unittest.TestCase):

    def test_subcommand_error(self):
        proc_error = subprocess.CalledProcessError(1, ["git"])
        err = git_gate.SubcommandError("git", "clone", proc_error)
        self.assertEqual(str(err), "Subprocess git clone failed with code 1")
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'RideRiders'
        db.create_table('rides_riders', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('ride', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['rides.Ride'])),
            ('signup_date', self.gf('django.db.models.fields.DateTimeField')()),
            ('pending', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('paid', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal('rides', ['RideRiders'])

        # Removing M2M table for field riders on 'Ride'
        db.delete_table(db.shorten_name('rides_riders'))

    def backwards(self, orm):
        # Deleting model 'RideRiders'
        db.delete_table('rides_riders')

        # Adding M2M table for field riders on 'Ride'
        m2m_table_name = db.shorten_name('rides_riders')
        db.create_table(m2m_table_name, (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('ride', models.ForeignKey(orm['rides.ride'], null=False)),
            ('user', models.ForeignKey(orm[u'auth.user'], null=False))
        ))
        db.create_unique(m2m_table_name, ['ride_id', 'user_id'])

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'chapters.chapter': {
            'Meta': {'object_name': 'Chapter', 'db_table': "'chapters'"},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': "'255'"})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'rides.ride': {
            'Meta': {'object_name': 'Ride', 'db_table': "'rides'"},
            'chapter': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['chapters.Chapter']", 'null': 'True', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'end_location': ('django.db.models.fields.CharField', [], {'max_length': "'255'"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': "'255'"}),
            'price': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'rider_capacity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'riders': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['auth.User']", 'null': 'True', 'through': "orm['rides.RideRiders']", 'blank': 'True'}),
            'slug': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': "'255'"}),
            'start_date': ('django.db.models.fields.DateField', [], {}),
            'start_location': ('django.db.models.fields.CharField', [], {'max_length': "'255'"})
        },
        'rides.rideriders': {
            'Meta': {'object_name': 'RideRiders', 'db_table': "'rides_riders'"},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'paid': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'pending': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'ride': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rides.Ride']"}),
            'signup_date': ('django.db.models.fields.DateTimeField', [], {}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
        }
    }

    complete_apps = ['rides']<commit_msg>Annoying bug with South migration around the rides_riders table.<commit_after># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Removing M2M table for field riders on 'Ride'
        db.delete_table(db.shorten_name('rides_riders'))

        # Adding model 'RideRiders'
        db.create_table('rides_riders', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('ride', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['rides.Ride'])),
            ('signup_date', self.gf('django.db.models.fields.DateTimeField')()),
            ('pending', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('paid', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal('rides', ['RideRiders'])

    def backwards(self, orm):
        # Deleting model 'RideRiders'
        db.delete_table('rides_riders')

        # Adding M2M table for field riders on 'Ride'
        m2m_table_name = db.shorten_name('rides_riders')
        db.create_table(m2m_table_name, (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('ride', models.ForeignKey(orm['rides.ride'], null=False)),
            ('user', models.ForeignKey(orm[u'auth.user'], null=False))
        ))
        db.create_unique(m2m_table_name, ['ride_id', 'user_id'])

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'chapters.chapter': {
            'Meta': {'object_name': 'Chapter', 'db_table': "'chapters'"},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': "'255'"})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'rides.ride': {
            'Meta': {'object_name': 'Ride', 'db_table': "'rides'"},
            'chapter': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['chapters.Chapter']", 'null': 'True', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'end_location': ('django.db.models.fields.CharField', [], {'max_length': "'255'"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': "'255'"}),
            'price': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'rider_capacity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'riders': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['auth.User']", 'null': 'True', 'through': "orm['rides.RideRiders']", 'blank': 'True'}),
            'slug': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': "'255'"}),
            'start_date': ('django.db.models.fields.DateField', [], {}),
            'start_location': ('django.db.models.fields.CharField', [], {'max_length': "'255'"})
        },
        'rides.rideriders': {
            'Meta': {'object_name': 'RideRiders', 'db_table': "'rides_riders'"},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'paid': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'pending': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'ride': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rides.Ride']"}),
            'signup_date': ('django.db.models.fields.DateTimeField', [], {}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
        }
    }

    complete_apps = ['rides']<|endoftext|>


<commit_before>#!/usr/bin/env python
#
# 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.

"""Javelin makes resources that should survive an upgrade.

Javelin is a tool for creating, verifying, and deleting a small set of
resources in a declarative way.

"""

import logging
import os
import sys
import unittest
import yaml

import argparse

import tempest.auth
from tempest import exceptions
from tempest.services.compute.json import flavors_client
from tempest.services.compute.json import servers_client
from tempest.services.identity.json import identity_client
from tempest.services.image.v2.json import image_client
from tempest.services.object_storage import container_client
from tempest.services.object_storage import object_client
from tempest.services.volume.json import volumes_client

OPTS = {}
USERS = {}
RES = {}

LOG = None

class OSClient(object):
    _creds = None
    identity = None
    servers = None

    def __init__(self, user, pw, tenant):
        _creds = tempest.auth.KeystoneV2Credentials(
            username=user,
            password=pw,
            tenant_name=tenant)
        _auth = tempest.auth.KeystoneV2AuthProvider(_creds)
        self.identity = identity_client.IdentityClientJSON(_auth)
        self.servers = servers_client.ServersClientJSON(_auth)
        self.objects = object_client.ObjectClient(_auth)
        self.containers = container_client.ContainerClient(_auth)
        self.images = image_client.ImageClientV2JSON(_auth)
        self.flavors = flavors_client.FlavorsClientJSON(_auth)
        self.volumes = volumes_client.VolumesClientJSON(_auth)

def load_resources(fname):
    """Load the expected resources from a yaml flie."""
    return yaml.load(open(fname, 'r'))

def keystone_admin():
    return OSClient(OPTS.os_username, OPTS.os_password, OPTS.os_tenant_name)

def client_for_user(name):
    LOG.debug("Entering client_for_user")
    if name in USERS:
        user = USERS[name]
        LOG.debug("Created client for user %s" % user)
        return OSClient(user['name'], user['pass'], user['tenant'])
    else:
        LOG.error("%s not found in USERS: %s" % (name, USERS))

###################
#
# TENANTS
#
###################

def create_tenants(tenants):
    """Create tenants from resource definition.

    Don't create the tenants if they already exist.
    """
    admin = keystone_admin()
    _, body = admin.identity.list_tenants()
    existing = [x['name'] for x in body]
    for tenant in tenants:
        if tenant not in existing:
            admin.identity.create_tenant(tenant)
        else:
            LOG.warn("Tenant '%s' already exists in this environment" % tenant)

##############
#
# USERS
#
##############

def _users_for_tenant(users, tenant):
    u_for_t = []
    for user in users:
        for n in user:
            if user[n]['tenant'] == tenant:
                u_for_t.append(user[n])
    return u_for_t

def _tenants_from_users(users):
    tenants = set()
    for user in users:
        for n in user:
            tenants.add(user[n]['tenant'])
    return tenants

def _assign_swift_role(user):
    admin = keystone_admin()
    resp, roles = admin.identity.list_roles()
    role = next(r for r in roles if r['name'] == 'Member')
    LOG.debug(USERS[user])
    try:
        admin.identity.assign_user_role(
            USERS[user]['tenant_id'],
            USERS[user]['id'],
            role['id'])
    except exceptions.Conflict:
        # don't care if it's already assigned
        pass

def create_users(users):
    """Create tenants from resource definition.

    Don't create the tenants if they already exist.
    """
    global USERS
    LOG.info("Creating users")
    admin = keystone_admin()
    for u in users:
        try:
            tenant = admin.identity.get_tenant_by_name(u['tenant'])
        except exceptions.NotFound:
            LOG.error("Tenant: %s - not found" % u['tenant'])
            continue
        try:
            admin.identity.get_user_by_username(tenant['id'], u['name'])
            LOG.warn("User '%s' already exists in this environment"
                     % u['name'])
        except exceptions.NotFound:
            admin.identity.create_user(
                u['name'], u['pass'], tenant['id'],
                "%s@%s" % (u['name'], tenant['id']),
                enabled=True)

def collect_users(users):
    global USERS
    LOG.info("Creating users")
    admin = keystone_admin()
    for u in users:
        tenant = admin.identity.get_tenant_by_name(u['tenant'])
        u['tenant_id'] = tenant['id']
        USERS[u['name']] = u
        body = admin.identity.get_user_by_username(tenant['id'], u['name'])
        USERS[u['name']]['id'] = body['id']

class JavelinCheck(unittest.TestCase):
    def __init__(self, users, resources):
        super(JavelinCheck, self).__init__()
        self.users = users
        self.res = resources

    def runTest(self, *args):
        pass

    def check(self):
        self.check_users()
        self.check_objects()
        self.check_servers()
        # TODO(sdague): Volumes not yet working, bring it back once the
        # code is self testing.
        # self.check_volumes()

    def check_users(self):
        """Check that the users we expect to exist, do.

        We don't use the resource list for this because we need to validate
        that things like tenantId didn't drift across versions.
        """
        for name, user in self.users.iteritems():
            client = keystone_admin()
            _, found = client.identity.get_user(user['id'])
            self.assertEqual(found['name'], user['name'])
            self.assertEqual(found['tenantId'], user['tenant_id'])

            # also ensure we can auth with that user, and do something
            # on the cloud. We don't care about the results except that it
            # remains authorized.
            client = client_for_user(user['name'])
            resp, body = client.servers.list_servers()
            self.assertEqual(resp['status'], '200')

    def check_objects(self):
        """Check that the objects created are still there."""
        for obj in self.res['objects']:
            client = client_for_user(obj['owner'])
            r, contents = client.objects.get_object(
                obj['container'], obj['name'])
            source = _file_contents(obj['file'])
            self.assertEqual(contents, source)

    def check_servers(self):
        """Check that the servers are still up and running."""
        for server in self.res['servers']:
            client = client_for_user(server['owner'])
            found = _get_server_by_name(client, server['name'])
            self.assertIsNotNone(
                found,
                "Couldn't find expected server %s" % server['name'])

            r, found = client.servers.get_server(found['id'])
            # get the ipv4 address
            addr = found['addresses']['private'][0]['addr']
            self.assertEqual(os.system("ping -c 1 " + addr), 0,
                             "Server %s is not pingable at %s" % (
                                 server['name'], addr))

    def check_volumes(self):
        """Check that the volumes are still there and attached."""
        for volume in self.res['volumes']:
            client = client_for_user(volume['owner'])
            found = _get_volume_by_name(client, volume['name'])
            self.assertIsNotNone(
                found,
                "Couldn't find expected volume %s" % volume['name'])

            # Verify that a volume's attachment retrieved
            server_id = _get_server_by_name(client, volume['server'])['id']
            attachment = self.client.get_attachment_from_volume(volume)
            self.assertEqual(volume['id'], attachment['volume_id'])
            self.assertEqual(server_id, attachment['server_id'])

#######################
#
# OBJECTS
#
#######################

def _file_contents(fname):
    with open(fname, 'r') as f:
        return f.read()

def create_objects(objects):
    LOG.info("Creating objects")
    for obj in objects:
        LOG.debug("Object %s" % obj)
        _assign_swift_role(obj['owner'])
        client = client_for_user(obj['owner'])
        client.containers.create_container(obj['container'])
        client.objects.create_object(
            obj['container'], obj['name'],
            _file_contents(obj['file']))

#######################
#
# IMAGES
#
#######################

def _resolve_image(image, imgtype):
    name = image[imgtype]
    fname = os.path.join(OPTS.devstack_base, image['imgdir'], name)
    return name, fname

def create_images(images):
    for image in images:
        client = client_for_user(image['owner'])

        # only upload a new image if the name isn't there
        r, body = client.images.image_list()
        names = [x['name'] for x in body]
        if image['name'] in names:
            continue

        # special handling for 3 part image
        extras = {}
        if image['format'] == 'ami':
            name, fname = _resolve_image(image, 'aki')
            r, aki = client.images.create_image(
                'javelin_' + name, 'aki', 'aki')
            client.images.store_image(aki.get('id'), open(fname, 'r'))
            extras['kernel_id'] = aki.get('id')

            name, fname = _resolve_image(image, 'ari')
            r, ari = client.images.create_image(
                'javelin_' + name, 'ari', 'ari')
            client.images.store_image(ari.get('id'), open(fname, 'r'))
            extras['ramdisk_id'] = ari.get('id')

        _, fname = _resolve_image(image, 'file')
        r, body = client.images.create_image(
            image['name'], image['format'], image['format'], **extras)
        image_id = body.get('id')
        client.images.store_image(image_id, open(fname, 'r'))

#######################
#
# SERVERS
#
#######################

def _get_server_by_name(client, name):
    r, body = client.servers.list_servers()
    for server in body['servers']:
        if name == server['name']:
            return server
    return None

def _get_image_by_name(client, name):
    r, body = client.images.image_list()
    for image in body:
        if name == image['name']:
            return image
    return None

def _get_flavor_by_name(client, name):
    r, body = client.flavors.list_flavors()
    for flavor in body:
        if name == flavor['name']:
            return flavor
    return None

def create_servers(servers):
    for server in servers:
        client = client_for_user(server['owner'])

        if _get_server_by_name(client, server['name']):
            continue

        image_id = _get_image_by_name(client, server['image'])['id']
        flavor_id = _get_flavor_by_name(client, server['flavor'])['id']
        client.servers.create_server(server['name'], image_id, flavor_id)

#######################
#
# VOLUMES
#
#######################

def _get_volume_by_name(client, name):
    r, body = client.volumes.list_volumes()
    for volume in body['volumes']:
        if name == volume['name']:
            return volume
    return None

def create_volumes(volumes):
    for volume in volumes:
        client = client_for_user(volume['owner'])

        # only create a volume if the name isn't here
        r, body = client.volumes.list_volumes()
        if any(item['name'] == volume['name'] for item in body):
            continue

        client.volumes.create_volume(volume['name'], volume['size'])

def attach_volumes(volumes):
    for volume in volumes:
        client = client_for_user(volume['owner'])

        server_id = _get_server_by_name(client, volume['server'])['id']
        client.volumes.attach_volume(volume['name'], server_id)

#######################
#
# MAIN LOGIC
#
#######################

def create_resources():
    LOG.info("Creating Resources")
    # first create keystone level resources, and we need to be admin
    # for those.
    create_tenants(RES['tenants'])
    create_users(RES['users'])
    collect_users(RES['users'])

    # next create resources in a well known order
    create_objects(RES['objects'])
    create_images(RES['images'])
    create_servers(RES['servers'])
    # TODO(sdague): volumes definition doesn't work yet, bring it
    # back once we're actually executing the code
    # create_volumes(RES['volumes'])
    # attach_volumes(RES['volumes'])

def get_options():
    global OPTS
    parser = argparse.ArgumentParser(
        description='Create and validate a fixed set of OpenStack resources')
    parser.add_argument('-m', '--mode',
                        metavar='<create|check|destroy>',
                        required=True,
                        help=('One of (create, check, destroy)'))
    parser.add_argument('-r', '--resources',
                        required=True,
                        metavar='resourcefile.yaml',
                        help='Resources definition yaml file')
    parser.add_argument(
        '-d', '--devstack-base',
        required=True,
        metavar='/opt/stack/old',
        help='Devstack base directory for retrieving artifacts')
    # auth bits, letting us also just source the devstack openrc
    parser.add_argument('--os-username',
                        metavar='<auth-user-name>',
                        default=os.environ.get('OS_USERNAME'),
                        help=('Defaults to env[OS_USERNAME].'))
    parser.add_argument('--os-password',
                        metavar='<auth-password>',
                        default=os.environ.get('OS_PASSWORD'),
                        help=('Defaults to env[OS_PASSWORD].'))
    parser.add_argument('--os-tenant-name',
                        metavar='<auth-tenant-name>',
                        default=os.environ.get('OS_TENANT_NAME'),
                        help=('Defaults to env[OS_TENANT_NAME].'))

    OPTS = parser.parse_args()
    if OPTS.mode not in ('create', 'check', 'destroy'):
        print("ERROR: Unknown mode -m %s\n" % OPTS.mode)
        parser.print_help()
        sys.exit(1)

def setup_logging(debug=True):
    global LOG
    LOG = logging.getLogger(__name__)
    if debug:
        LOG.setLevel(logging.DEBUG)
    else:
        LOG.setLevel(logging.INFO)

    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        datefmt='%Y-%m-%d %H:%M:%S',
        fmt='%(asctime)s.%(msecs).03d - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    LOG.addHandler(ch)

def main():
    global RES
    get_options()
    setup_logging()
    RES = load_resources(OPTS.resources)

    if OPTS.mode == 'create':
        create_resources()
    elif OPTS.mode == 'check':
        collect_users(RES['users'])
        checker = JavelinCheck(USERS, RES)
        checker.check()
    elif OPTS.mode == 'destroy':
        LOG.warn("Destroy mode not yet implemented")
    else:
        LOG.error('Unknown mode %s' % OPTS.mode)
        return 1
    return 0

if __name__ == "__main__":
    sys.exit(main())
<commit_msg>Make javelin check logging a bit better<commit_after>#!/usr/bin/env python
#
# 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.

"""Javelin makes resources that should survive an upgrade.

Javelin is a tool for creating, verifying, and deleting a small set of
resources in a declarative way.

"""

import logging
import os
import sys
import unittest
import yaml

import argparse

import tempest.auth
from tempest import exceptions
from tempest.services.compute.json import flavors_client
from tempest.services.compute.json import servers_client
from tempest.services.identity.json import identity_client
from tempest.services.image.v2.json import image_client
from tempest.services.object_storage import container_client
from tempest.services.object_storage import object_client
from tempest.services.volume.json import volumes_client

OPTS = {}
USERS = {}
RES = {}

LOG = None

class OSClient(object):
    _creds = None
    identity = None
    servers = None

    def __init__(self, user, pw, tenant):
        _creds = tempest.auth.KeystoneV2Credentials(
            username=user,
            password=pw,
            tenant_name=tenant)
        _auth = tempest.auth.KeystoneV2AuthProvider(_creds)
        self.identity = identity_client.IdentityClientJSON(_auth)
        self.servers = servers_client.ServersClientJSON(_auth)
        self.objects = object_client.ObjectClient(_auth)
        self.containers = container_client.ContainerClient(_auth)
        self.images = image_client.ImageClientV2JSON(_auth)
        self.flavors = flavors_client.FlavorsClientJSON(_auth)
        self.volumes = volumes_client.VolumesClientJSON(_auth)

def load_resources(fname):
    """Load the expected resources from a yaml flie."""
    return yaml.load(open(fname, 'r'))

def keystone_admin():
    return OSClient(OPTS.os_username, OPTS.os_password, OPTS.os_tenant_name)

def client_for_user(name):
    LOG.debug("Entering client_for_user")
    if name in USERS:
        user = USERS[name]
        LOG.debug("Created client for user %s" % user)
        return OSClient(user['name'], user['pass'], user['tenant'])
    else:
        LOG.error("%s not found in USERS: %s" % (name, USERS))

###################
#
# TENANTS
#
###################

def create_tenants(tenants):
    """Create tenants from resource definition.

    Don't create the tenants if they already exist.
    """
    admin = keystone_admin()
    _, body = admin.identity.list_tenants()
    existing = [x['name'] for x in body]
    for tenant in tenants:
        if tenant not in existing:
            admin.identity.create_tenant(tenant)
        else:
            LOG.warn("Tenant '%s' already exists in this environment" % tenant)

##############
#
# USERS
#
##############

def _users_for_tenant(users, tenant):
    u_for_t = []
    for user in users:
        for n in user:
            if user[n]['tenant'] == tenant:
                u_for_t.append(user[n])
    return u_for_t

def _tenants_from_users(users):
    tenants = set()
    for user in users:
        for n in user:
            tenants.add(user[n]['tenant'])
    return tenants

def _assign_swift_role(user):
    admin = keystone_admin()
    resp, roles = admin.identity.list_roles()
    role = next(r for r in roles if r['name'] == 'Member')
    LOG.debug(USERS[user])
    try:
        admin.identity.assign_user_role(
            USERS[user]['tenant_id'],
            USERS[user]['id'],
            role['id'])
    except exceptions.Conflict:
        # don't care if it's already assigned
        pass

def create_users(users):
    """Create tenants from resource definition.

    Don't create the tenants if they already exist.
    """
    global USERS
    LOG.info("Creating users")
    admin = keystone_admin()
    for u in users:
        try:
            tenant = admin.identity.get_tenant_by_name(u['tenant'])
        except exceptions.NotFound:
            LOG.error("Tenant: %s - not found" % u['tenant'])
            continue
        try:
            admin.identity.get_user_by_username(tenant['id'], u['name'])
            LOG.warn("User '%s' already exists in this environment"
                     % u['name'])
        except exceptions.NotFound:
            admin.identity.create_user(
                u['name'], u['pass'], tenant['id'],
                "%s@%s" % (u['name'], tenant['id']),
                enabled=True)

def collect_users(users):
    global USERS
    LOG.info("Collecting users")
    admin = keystone_admin()
    for u in users:
        tenant = admin.identity.get_tenant_by_name(u['tenant'])
        u['tenant_id'] = tenant['id']
        USERS[u['name']] = u
        body = admin.identity.get_user_by_username(tenant['id'], u['name'])
        USERS[u['name']]['id'] = body['id']

class JavelinCheck(unittest.TestCase):
    def __init__(self, users, resources):
        super(JavelinCheck, self).__init__()
        self.users = users
        self.res = resources

    def runTest(self, *args):
        pass

    def check(self):
        self.check_users()
        self.check_objects()
        self.check_servers()
        # TODO(sdague): Volumes not yet working, bring it back once the
        # code is self testing.
        # self.check_volumes()

    def check_users(self):
        """Check that the users we expect to exist, do.

        We don't use the resource list for this because we need to validate
        that things like tenantId didn't drift across versions.
        """
        LOG.info("checking users")
        for name, user in self.users.iteritems():
            client = keystone_admin()
            _, found = client.identity.get_user(user['id'])
            self.assertEqual(found['name'], user['name'])
            self.assertEqual(found['tenantId'], user['tenant_id'])

            # also ensure we can auth with that user, and do something
            # on the cloud. We don't care about the results except that it
            # remains authorized.
            client = client_for_user(user['name'])
            resp, body = client.servers.list_servers()
            self.assertEqual(resp['status'], '200')

    def check_objects(self):
        """Check that the objects created are still there."""
        LOG.info("checking objects")
        for obj in self.res['objects']:
            client = client_for_user(obj['owner'])
            r, contents = client.objects.get_object(
                obj['container'], obj['name'])
            source = _file_contents(obj['file'])
            self.assertEqual(contents, source)

    def check_servers(self):
        """Check that the servers are still up and running."""
        LOG.info("checking servers")
        for server in self.res['servers']:
            client = client_for_user(server['owner'])
            found = _get_server_by_name(client, server['name'])
            self.assertIsNotNone(
                found,
                "Couldn't find expected server %s" % server['name'])

            r, found = client.servers.get_server(found['id'])
            # get the ipv4 address
            addr = found['addresses']['private'][0]['addr']
            self.assertEqual(os.system("ping -c 1 " + addr), 0,
                             "Server %s is not pingable at %s" % (
                                 server['name'], addr))

    def check_volumes(self):
        """Check that the volumes are still there and attached."""
        LOG.info("checking volumes")
        for volume in self.res['volumes']:
            client = client_for_user(volume['owner'])
            found = _get_volume_by_name(client, volume['name'])
            self.assertIsNotNone(
                found,
                "Couldn't find expected volume %s" % volume['name'])

            # Verify that a volume's attachment retrieved
            server_id = _get_server_by_name(client, volume['server'])['id']
            attachment = self.client.get_attachment_from_volume(volume)
            self.assertEqual(volume['id'], attachment['volume_id'])
            self.assertEqual(server_id, attachment['server_id'])

#######################
#
# OBJECTS
#
#######################

def _file_contents(fname):
    with open(fname, 'r') as f:
        return f.read()

def create_objects(objects):
    LOG.info("Creating objects")
    for obj in objects:
        LOG.debug("Object %s" % obj)
        _assign_swift_role(obj['owner'])
        client = client_for_user(obj['owner'])
        client.containers.create_container(obj['container'])
        client.objects.create_object(
            obj['container'], obj['name'],
            _file_contents(obj['file']))

#######################
#
# IMAGES
#
#######################

def _resolve_image(image, imgtype):
    name = image[imgtype]
    fname = os.path.join(OPTS.devstack_base, image['imgdir'], name)
    return name, fname

def create_images(images):
    for image in images:
        client = client_for_user(image['owner'])

        # only upload a new image if the name isn't there
        r, body = client.images.image_list()
        names = [x['name'] for x in body]
        if image['name'] in names:
            continue

        # special handling for 3 part image
        extras = {}
        if image['format'] == 'ami':
            name, fname = _resolve_image(image, 'aki')
            r, aki = client.images.create_image(
                'javelin_' + name, 'aki', 'aki')
            client.images.store_image(aki.get('id'), open(fname, 'r'))
            extras['kernel_id'] = aki.get('id')

            name, fname = _resolve_image(image, 'ari')
            r, ari = client.images.create_image(
                'javelin_' + name, 'ari', 'ari')
            client.images.store_image(ari.get('id'), open(fname, 'r'))
            extras['ramdisk_id'] = ari.get('id')

        _, fname = _resolve_image(image, 'file')
        r, body = client.images.create_image(
            image['name'], image['format'], image['format'], **extras)
        image_id = body.get('id')
        client.images.store_image(image_id, open(fname, 'r'))

#######################
#
# SERVERS
#
#######################

def _get_server_by_name(client, name):
    r, body = client.servers.list_servers()
    for server in body['servers']:
        if name == server['name']:
            return server
    return None

def _get_image_by_name(client, name):
    r, body = client.images.image_list()
    for image in body:
        if name == image['name']:
            return image
    return None

def _get_flavor_by_name(client, name):
    r, body = client.flavors.list_flavors()
    for flavor in body:
        if name == flavor['name']:
            return flavor
    return None

def create_servers(servers):
    for server in servers:
        client = client_for_user(server['owner'])

        if _get_server_by_name(client, server['name']):
            continue

        image_id = _get_image_by_name(client, server['image'])['id']
        flavor_id = _get_flavor_by_name(client, server['flavor'])['id']
        client.servers.create_server(server['name'], image_id, flavor_id)

#######################
#
# VOLUMES
#
#######################

def _get_volume_by_name(client, name):
    r, body = client.volumes.list_volumes()
    for volume in body['volumes']:
        if name == volume['name']:
            return volume
    return None

def create_volumes(volumes):
    for volume in volumes:
        client = client_for_user(volume['owner'])

        # only create a volume if the name isn't here
        r, body = client.volumes.list_volumes()
        if any(item['name'] == volume['name'] for item in body):
            continue

        client.volumes.create_volume(volume['name'], volume['size'])

def attach_volumes(volumes):
    for volume in volumes:
        client = client_for_user(volume['owner'])

        server_id = _get_server_by_name(client, volume['server'])['id']
        client.volumes.attach_volume(volume['name'], server_id)

#######################
#
# MAIN LOGIC
#
#######################

def create_resources():
    LOG.info("Creating Resources")
    # first create keystone level resources, and we need to be admin
    # for those.
    create_tenants(RES['tenants'])
    create_users(RES['users'])
    collect_users(RES['users'])

    # next create resources in a well known order
    create_objects(RES['objects'])
    create_images(RES['images'])
    create_servers(RES['servers'])
    # TODO(sdague): volumes definition doesn't work yet, bring it
    # back once we're actually executing the code
    # create_volumes(RES['volumes'])
    # attach_volumes(RES['volumes'])

def get_options():
    global OPTS
    parser = argparse.ArgumentParser(
        description='Create and validate a fixed set of OpenStack resources')
    parser.add_argument('-m', '--mode',
                        metavar='<create|check|destroy>',
                        required=True,
                        help=('One of (create, check, destroy)'))
    parser.add_argument('-r', '--resources',
                        required=True,
                        metavar='resourcefile.yaml',
                        help='Resources definition yaml file')
    parser.add_argument(
        '-d', '--devstack-base',
        required=True,
        metavar='/opt/stack/old',
        help='Devstack base directory for retrieving artifacts')
    # auth bits, letting us also just source the devstack openrc
    parser.add_argument('--os-username',
                        metavar='<auth-user-name>',
                        default=os.environ.get('OS_USERNAME'),
                        help=('Defaults to env[OS_USERNAME].'))
    parser.add_argument('--os-password',
                        metavar='<auth-password>',
                        default=os.environ.get('OS_PASSWORD'),
                        help=('Defaults to env[OS_PASSWORD].'))
    parser.add_argument('--os-tenant-name',
                        metavar='<auth-tenant-name>',
                        default=os.environ.get('OS_TENANT_NAME'),
                        help=('Defaults to env[OS_TENANT_NAME].'))

    OPTS = parser.parse_args()
    if OPTS.mode not in ('create', 'check', 'destroy'):
        print("ERROR: Unknown mode -m %s\n" % OPTS.mode)
        parser.print_help()
        sys.exit(1)

def setup_logging(debug=True):
    global LOG
    LOG = logging.getLogger(__name__)
    if debug:
        LOG.setLevel(logging.DEBUG)
    else:
        LOG.setLevel(logging.INFO)

    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        datefmt='%Y-%m-%d %H:%M:%S',
        fmt='%(asctime)s.%(msecs).03d - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    LOG.addHandler(ch)

def main():
    global RES
    get_options()
    setup_logging()
    RES = load_resources(OPTS.resources)

    if OPTS.mode == 'create':
        create_resources()
    elif OPTS.mode == 'check':
        collect_users(RES['users'])
        checker = JavelinCheck(USERS, RES)
        checker.check()
    elif OPTS.mode == 'destroy':
        LOG.warn("Destroy mode not yet implemented")
    else:
        LOG.error('Unknown mode %s' % OPTS.mode)
        return 1
    return 0

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


<commit_before>
VERSION = '0.27.2.2'

<commit_msg>version bump for 0.27.2.3.<commit_after>
VERSION = '0.27.2.3'

<|endoftext|>


<commit_before># Copyright 2020 Google LLC
#
# 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
#
#     https://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.
"""Provides a workspace macro to load dependent repositories."""

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@tf_runtime//third_party:repo.bzl", "tfrt_http_archive")
load("@tf_runtime//third_party/cuda:dependencies.bzl", "cuda_dependencies")

def tfrt_dependencies():
    """Loads TFRT external dependencies into WORKSPACE."""

    # Bazel rules to build CUDA targets.
    # TODO(csigg): move this to some public repo.
    maybe(
        name = "rules_cuda",
        repo_rule = native.local_repository,
        path = "third_party/rules_cuda",
    )

    cuda_dependencies()

    # LLVM and MLIR from llvm-project.
    LLVM_COMMIT = "f4c8b80318005ca61bfed9b40ee9e6039194159b"
    LLVM_SHA256 = "4d5a12f6fb6c839cee8c9a5ebd537f818427e856d1b70d53de2c4b02221fa59e"
    LLVM_URLS = [
        "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
    ]
    maybe(
        name = "llvm-project",
        repo_rule = tfrt_http_archive,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = LLVM_URLS,
        additional_build_files = {
            "@tf_runtime//third_party/llvm:llvm.autogenerated.BUILD": "llvm/BUILD",
            "@tf_runtime//third_party/mlir:BUILD": "mlir/BUILD",
            "@tf_runtime//third_party/mlir:test.BUILD": "mlir/test/BUILD",
        },
    )

    # https://github.com/bazelbuild/bazel-skylib/releases
    maybe(
        name = "bazel_skylib",
        repo_rule = http_archive,
        sha256 = "97e70364e9249702246c0e9444bccdc4b847bed1eb03c5a3ece4f83dfe6abc44",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz",
            "https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz",
        ],
    )

    # Eigen3
    maybe(
        name = "eigen_archive",
        repo_rule = http_archive,
        build_file = "@tf_runtime//third_party:eigen/BUILD",
        sha256 = "924c7f85d5e2e40beb663489bf3f6908bb4c328dc81ab845c27bb6ce199b8698",  # SHARED_EIGEN_SHA
        strip_prefix = "eigen-3c02fefec53f21d9fad537ff0d62d8dcc8162466",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/gitlab.com/libeigen/eigen/-/archive/3c02fefec53f21d9fad537ff0d62d8dcc8162466/eigen-3c02fefec53f21d9fad537ff0d62d8dcc8162466.tar.gz",
            "https://gitlab.com/libeigen/eigen/-/archive/3c02fefec53f21d9fad537ff0d62d8dcc8162466/eigen-3c02fefec53f21d9fad537ff0d62d8dcc8162466.tar.gz",
        ],
    )

    maybe(
        name = "mkl_dnn",
        repo_rule = http_archive,
        build_file = "@tf_runtime//third_party/mkl_dnn:BUILD.mkl_dnn",
        sha256 = "ed56652dd237deb86ee9bf102c18de5f2625c059e5ab1d7512c8dc01e316b694",
        strip_prefix = "mkl-dnn-0.21.2",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/intel/mkl-dnn/archive/v0.21.2.tar.gz",
            "https://github.com/intel/mkl-dnn/archive/v0.21.2.tar.gz",
        ],
    )

    maybe(
        name = "com_google_googletest",
        repo_rule = tfrt_http_archive,
        sha256 = "ff7a82736e158c077e76188232eac77913a15dac0b22508c390ab3f88e6d6d86",
        strip_prefix = "googletest-b6cd405286ed8635ece71c72f118e659f4ade3fb",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/google/googletest/archive/b6cd405286ed8635ece71c72f118e659f4ade3fb.zip",
            "https://github.com/google/googletest/archive/b6cd405286ed8635ece71c72f118e659f4ade3fb.zip",
        ],
    )

    maybe(
        name = "com_github_google_benchmark",
        repo_rule = http_archive,
        strip_prefix = "benchmark-16703ff83c1ae6d53e5155df3bb3ab0bc96083be",
        sha256 = "59f918c8ccd4d74b6ac43484467b500f1d64b40cc1010daa055375b322a43ba3",
        urls = ["https://github.com/google/benchmark/archive/16703ff83c1ae6d53e5155df3bb3ab0bc96083be.zip"],
    )

    maybe(
        name = "com_google_protobuf",
        repo_rule = tfrt_http_archive,
        patch_file = "//third_party/protobuf:protobuf.patch",
        sha256 = "cfcba2df10feec52a84208693937c17a4b5df7775e1635c1e3baffc487b24c9b",
        strip_prefix = "protobuf-3.9.2",
        system_build_file = "//third_party/systemlibs:protobuf.BUILD",
        system_link_files = {
            "//third_party/systemlibs:protobuf.bzl": "protobuf.bzl",
        },
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/protocolbuffers/protobuf/archive/v3.9.2.zip",
            "https://github.com/protocolbuffers/protobuf/archive/v3.9.2.zip",
        ],
    )

    maybe(
        name = "cub_archive",
        repo_rule = tfrt_http_archive,
        build_file = "//third_party:cub/BUILD",
        patch_file = "//third_party:cub/pr170.patch",
        sha256 = "6bfa06ab52a650ae7ee6963143a0bbc667d6504822cbd9670369b598f18c58c3",
        strip_prefix = "cub-1.8.0",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/NVlabs/cub/archive/1.8.0.zip",
            "https://github.com/NVlabs/cub/archive/1.8.0.zip",
        ],
    )

    maybe(
        name = "zlib",
        repo_rule = tfrt_http_archive,
        build_file = "//third_party:zlib.BUILD",
        sha256 = "c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1",
        strip_prefix = "zlib-1.2.11",
        system_build_file = "//third_party/systemlibs:zlib.BUILD",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/zlib.net/zlib-1.2.11.tar.gz",
            "https://zlib.net/zlib-1.2.11.tar.gz",
        ],
    )

    maybe(
        name = "py-cpuinfo",
        repo_rule = tfrt_http_archive,
        strip_prefix = "py-cpuinfo-0.2.3",
        sha256 = "f6a016fdbc4e7fadf2d519090fcb4fa9d0831bad4e85245d938e5c2fe7623ca6",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/pypi.python.org/packages/source/p/py-cpuinfo/py-cpuinfo-0.2.3.tar.gz",
            "https://pypi.python.org/packages/source/p/py-cpuinfo/py-cpuinfo-0.2.3.tar.gz",
        ],
        build_file = "//third_party:py-cpuinfo.BUILD",
    )
<commit_msg>Integrate LLVM at llvm/llvm-project@511cfe944195<commit_after># Copyright 2020 Google LLC
#
# 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
#
#     https://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.
"""Provides a workspace macro to load dependent repositories."""

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@tf_runtime//third_party:repo.bzl", "tfrt_http_archive")
load("@tf_runtime//third_party/cuda:dependencies.bzl", "cuda_dependencies")

def tfrt_dependencies():
    """Loads TFRT external dependencies into WORKSPACE."""

    # Bazel rules to build CUDA targets.
    # TODO(csigg): move this to some public repo.
    maybe(
        name = "rules_cuda",
        repo_rule = native.local_repository,
        path = "third_party/rules_cuda",
    )

    cuda_dependencies()

    # LLVM and MLIR from llvm-project.
    LLVM_COMMIT = "511cfe9441955f20a8b93573fb9b62433b053550"
    LLVM_SHA256 = "57626cf2eb850c717b712e43774cad308f19cd9161db9ed286844ba8f42abd70"
    LLVM_URLS = [
        "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
    ]
    maybe(
        name = "llvm-project",
        repo_rule = tfrt_http_archive,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = LLVM_URLS,
        additional_build_files = {
            "@tf_runtime//third_party/llvm:llvm.autogenerated.BUILD": "llvm/BUILD",
            "@tf_runtime//third_party/mlir:BUILD": "mlir/BUILD",
            "@tf_runtime//third_party/mlir:test.BUILD": "mlir/test/BUILD",
        },
    )

    # https://github.com/bazelbuild/bazel-skylib/releases
    maybe(
        name = "bazel_skylib",
        repo_rule = http_archive,
        sha256 = "97e70364e9249702246c0e9444bccdc4b847bed1eb03c5a3ece4f83dfe6abc44",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz",
            "https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz",
        ],
    )

    # Eigen3
    maybe(
        name = "eigen_archive",
        repo_rule = http_archive,
        build_file = "@tf_runtime//third_party:eigen/BUILD",
        sha256 = "924c7f85d5e2e40beb663489bf3f6908bb4c328dc81ab845c27bb6ce199b8698",  # SHARED_EIGEN_SHA
        strip_prefix = "eigen-3c02fefec53f21d9fad537ff0d62d8dcc8162466",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/gitlab.com/libeigen/eigen/-/archive/3c02fefec53f21d9fad537ff0d62d8dcc8162466/eigen-3c02fefec53f21d9fad537ff0d62d8dcc8162466.tar.gz",
            "https://gitlab.com/libeigen/eigen/-/archive/3c02fefec53f21d9fad537ff0d62d8dcc8162466/eigen-3c02fefec53f21d9fad537ff0d62d8dcc8162466.tar.gz",
        ],
    )

    maybe(
        name = "mkl_dnn",
        repo_rule = http_archive,
        build_file = "@tf_runtime//third_party/mkl_dnn:BUILD.mkl_dnn",
        sha256 = "ed56652dd237deb86ee9bf102c18de5f2625c059e5ab1d7512c8dc01e316b694",
        strip_prefix = "mkl-dnn-0.21.2",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/intel/mkl-dnn/archive/v0.21.2.tar.gz",
            "https://github.com/intel/mkl-dnn/archive/v0.21.2.tar.gz",
        ],
    )

    maybe(
        name = "com_google_googletest",
        repo_rule = tfrt_http_archive,
        sha256 = "ff7a82736e158c077e76188232eac77913a15dac0b22508c390ab3f88e6d6d86",
        strip_prefix = "googletest-b6cd405286ed8635ece71c72f118e659f4ade3fb",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/google/googletest/archive/b6cd405286ed8635ece71c72f118e659f4ade3fb.zip",
            "https://github.com/google/googletest/archive/b6cd405286ed8635ece71c72f118e659f4ade3fb.zip",
        ],
    )

    maybe(
        name = "com_github_google_benchmark",
        repo_rule = http_archive,
        strip_prefix = "benchmark-16703ff83c1ae6d53e5155df3bb3ab0bc96083be",
        sha256 = "59f918c8ccd4d74b6ac43484467b500f1d64b40cc1010daa055375b322a43ba3",
        urls = ["https://github.com/google/benchmark/archive/16703ff83c1ae6d53e5155df3bb3ab0bc96083be.zip"],
    )

    maybe(
        name = "com_google_protobuf",
        repo_rule = tfrt_http_archive,
        patch_file = "//third_party/protobuf:protobuf.patch",
        sha256 = "cfcba2df10feec52a84208693937c17a4b5df7775e1635c1e3baffc487b24c9b",
        strip_prefix = "protobuf-3.9.2",
        system_build_file = "//third_party/systemlibs:protobuf.BUILD",
        system_link_files = {
            "//third_party/systemlibs:protobuf.bzl": "protobuf.bzl",
        },
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/protocolbuffers/protobuf/archive/v3.9.2.zip",
            "https://github.com/protocolbuffers/protobuf/archive/v3.9.2.zip",
        ],
    )

    maybe(
        name = "cub_archive",
        repo_rule = tfrt_http_archive,
        build_file = "//third_party:cub/BUILD",
        patch_file = "//third_party:cub/pr170.patch",
        sha256 = "6bfa06ab52a650ae7ee6963143a0bbc667d6504822cbd9670369b598f18c58c3",
        strip_prefix = "cub-1.8.0",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/NVlabs/cub/archive/1.8.0.zip",
            "https://github.com/NVlabs/cub/archive/1.8.0.zip",
        ],
    )

    maybe(
        name = "zlib",
        repo_rule = tfrt_http_archive,
        build_file = "//third_party:zlib.BUILD",
        sha256 = "c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1",
        strip_prefix = "zlib-1.2.11",
        system_build_file = "//third_party/systemlibs:zlib.BUILD",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/zlib.net/zlib-1.2.11.tar.gz",
            "https://zlib.net/zlib-1.2.11.tar.gz",
        ],
    )

    maybe(
        name = "py-cpuinfo",
        repo_rule = tfrt_http_archive,
        strip_prefix = "py-cpuinfo-0.2.3",
        sha256 = "f6a016fdbc4e7fadf2d519090fcb4fa9d0831bad4e85245d938e5c2fe7623ca6",
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/pypi.python.org/packages/source/p/py-cpuinfo/py-cpuinfo-0.2.3.tar.gz",
            "https://pypi.python.org/packages/source/p/py-cpuinfo/py-cpuinfo-0.2.3.tar.gz",
        ],
        build_file = "//third_party:py-cpuinfo.BUILD",
    )
<|endoftext|>


<commit_before>import ptypes
from ptypes import *
#http://doxygen.reactos.org/dc/d27/cppexcept_8h_source.html

class codeptr_t(pint.uint32_t): pass
class vtable_ptr(codeptr_t): pass
class type_info(pstruct.type):
    _fields_ = [
        (dyn.pointer(vtable_ptr), 'vtable'),
        (dyn.pointer(pstr.szstring), 'name'),
        (dyn.clone(pstr.string, length=32), 'mangled'),
    ]

class exception(pstruct.type):
    _fields_ = [
        (dyn.pointer(vtable_ptr), 'vtable'),
        (dyn.pointer(pstr.szstring), 'name'),
        (pint.int32_t, 'do_free'),
    ]

class cxx_exception_frame(pstruct.type):
    _fields_ = [
        (dyn.pointer(ptype.undefined), 'frame'), # XXX
        (pint.int32_t, 'trylevel'),
        (pint.uint32_t, 'ebp'),
    ]

class catchblock_info(pstruct.type):
    _fields_ = [
        (pint.uint32_t, 'flags'),
        (dyn.pointer(type_info), 'type_info'),
        (pint.int32_t, 'offset'),
        (codeptr_t, 'handler'),
    ]

class tryblock_info(pstruct.type):
    _fields_ = [
        (pint.int32_t, 'start_level'),
        (pint.int32_t, 'end_level'),
        (pint.int32_t, 'catch_level'),
        (pint.int32_t, 'catchblock_count'),
        (dyn.pointer(catchblock_info), 'catchblock'),
    ]

class unwind_info(pstruct.type):
    _fields_ = [
        (pint.int32_t, 'prev'),
        (codeptr_t, 'handler'),
    ]

class cxx_function_descr(pstruct.type):
    _fields_ = [
        (pint.uint32_t, 'magic'),
        (pint.uint32_t, 'unwind_count'),
        (lambda s: dyn.pointer(dyn.array(unwind_info, s['unwind_count'].li.int())), 'unwind_table'),
        (pint.uint32_t, 'tryblock_count'),
        (lambda s: dyn.pointer(dyn.array(tryblock_info, s['unwind_count'].li.int())), 'tryblock'),
        (pint.uint32_t, 'ipmap_count'),
        (dyn.pointer(ptype.undefined), 'ipmap'),       # XXX
        (dyn.pointer(ptype.undefined), 'expect_list'),     # XXX
        (pint.uint32_t, 'flags'),
    ]

class cxx_copy_ctor(codeptr_t): pass

class this_ptr_offsets(pstruct.type):
    _fields_ = [
        (pint.int32_t, 'this_offset'),
        (pint.int32_t, 'vbase_descr'),
        (pint.int32_t, 'vbase_offset'),
    ]

class cxx_type_info(pstruct.type):
    _fields_ = [
        (pint.uint32_t, 'flags'),
        (dyn.pointer(type_info), 'type_info'),
        (this_ptr_offsets, 'offsets'),
        (pint.uint32_t, 'size'),
        (cxx_copy_ctor, 'copy_ctor'),
    ]

class cxx_type_info_table(pstruct.type):
    _fields_ = [
        (pint.uint32_t, 'count'),
        (dyn.array(cxx_type_info, 3), 'info'),
    ]

class cxx_exc_custom_handler(codeptr_t): pass

class cxx_exception_type(pstruct.type):
    _fields_ = [
        (pint.uint32_t, 'flags'),
        (codeptr_t, 'destructor'),
        (cxx_exc_custom_handler, 'custom_handler'),
        (dyn.pointer(cxx_type_info_table), 'type_info_table'),
    ]
<commit_msg>Imported the definitions for the language.vc template using the partial definitions from the swan project's runtime.<commit_after>import ptypes
from ptypes import *

# https://github.com/hvdieren/swan_runtime/blob/master/runtime/except-win32.h
# https://github.com/hvdieren/swan_runtime/blob/master/runtime/except-win64.h

# constants
EXCEPTION_MAXIMUM_PARAMETERS = 15

# native types
class char(pint.int8_t): pass
class int(pint.int32_t): pass
class long(pint.integer.lookup(ptypes.Config.integer.size)): pass
class DWORD(pint.uint32_t): pass
class ULONG(pint.uint32_t): pass
class ULONG64(pint.uint64_t): pass
class PVOID(ptype.pointer_t):
    _object_ = ptype.undefined
class ULONG_PTR(ptype.pointer_t):
    _object_ = ptype.undefined

# structured types
class TypeDescriptor(pstruct.type):
    _fields_ = [
        (PVOID, 'pVFTable'),
        (PVOID, 'spare'),
        (dyn.array(char, 1), 'name'),
    ]

class _EXCEPTION_RECORD(pstruct.type):
    _fields_ = [
        (DWORD, 'ExceptionCode'),
        (DWORD, 'ExceptionFlags'),
        (dyn.pointer(lambda: _EXCEPTION_RECORD), 'ExceptionRecord'),
        (PVOID, 'ExceptionAddress'),
        (DWORD, 'NumberParameters'),
        (dyn.array(dyn.pointer(ULONG), EXCEPTION_MAXIMUM_PARAMETERS), 'ExceptionInformation'),
    ]
EXCEPTION_RECORD = _EXCEPTION_RECORD

class PMD(pstruct.type):
    _fields_ = [
        (int, 'mdisp'),
        (int, 'pdisp'),
        (int, 'vdisp'),
    ]

class win32_except_info(pint.enum):
    _values_ = [
        ('info_magic_number', 0),
        ('info_cpp_object', 1),
        ('info_throw_data', 2),
        ('info_image_base', 3),
    ]

class win64_except_info(pint.enum):
    _values_ = [
        ('info_magic_number', 0),
        ('info_cpp_object', 1),
        ('info_throw_data', 2),
        ('info_image_base', 3),
    ]

class UnwindMapEntry(pstruct.type):
    _fields_ = [
        (int, 'toState'),
        (DWORD, 'offWindFunclet'),
    ]

class HandlerType(pstruct.type):
    class _adjectives(pint.enum, DWORD):
        _values_ = [
            (1, 'const'),
            (2, 'volatile'),
            (8, 'reference'),
        ]
    _fields_ = [
        (_adjectives, 'adjectives'),
        (DWORD, 'offTypeDescriptor'),
        (int, 'dispCatchObj'),
        (DWORD, 'offHandlerCode'),
        (DWORD, 'unknown'),
    ]

class TryBlockMapEntry(pstruct.type):
    _fields_ = [
        (int, 'tryLow'),
        (int, 'tryHigh'),
        (int, 'catchHigh'),
        (int, 'nCatches'),
        (DWORD, 'offHandlerArray'),
    ]

class Ip2StateMapEntry(pstruct.type):
    _fields_ = [
        (DWORD, 'offIp'),
        (int, 'iTryLevel'),
    ]

class FuncInfo(pstruct.type):
    class _magicNumber(pbinary.struct):
        _fields_ = [
            (3, 'bbtFlags'),
            (29, 'number'),
        ]
    _fields_ = [
        (_magicNumber, 'magicNumber'),
        (int, 'maxState'),
        (DWORD, 'offUnwindMap'),
        (DWORD, 'nTryBlocks'),
        (DWORD, 'offTryBlockMap'),
        (DWORD, 'nIpMapEntries'),
        (DWORD, 'offIpToStateMap'),
        (int, 'EHFlags'),
    ]

class Win32CatchableType(pstruct.type):
    _fields_ = [
        (DWORD, 'properties'),
        (dyn.pointer(TypeDescriptor), 'pType'),
        (PMD, 'thisDisplacement'),
        (int, 'sizeOrOffset'),
        (PVOID, 'copyFunction'),
    ]

class Win64CatchableType(pstruct.type):
    _fields_ = [
        (DWORD, 'properties'),
        (DWORD, 'offTypeDescriptor'),
        (PMD, 'thisDisplacement'),
        (int, 'sizeOrOffset'),
        (DWORD, 'offCopyFunction'),
    ]

class Win32CatchableTypeInfo(pstruct.type):
    _fields_ = [
        (int, 'nCatchableTypes'),
        (dyn.array(dyn.pointer(Win32CatchableType), 1), 'arrayOfCatchableTypes'),
    ]

class Win64CatchableTypeInfo(pstruct.type):
    _fields_ = [
        (int, 'nCatchableTypes'),
        (DWORD, 'offArrayOfCatchableTypes'),
    ]

class Win32ThrowInfo(pstruct.type):
    _fields_ = [
        (DWORD, 'attributes'),
        (PVOID, 'pmfnUnwind'),
        (PVOID, 'pForwardCompat'),
        (dyn.pointer(Win32CatchableTypeInfo), 'pCatchableTypeArray'),
    ]

class Win64ThrowInfo(pstruct.type):
    _fields_ = [
        (DWORD, 'attributes'),
        (DWORD, 'offDtor'),
        (DWORD, 'pfnForwardCompat'),
        (DWORD, 'offCatchableTypeInfo'),
    ]

### this is all cilk-related
class cilk_fiber(ptype.undefined): pass
class cilkrts_worker(ptype.undefined): pass
class cilkrts_stack_frame(ptype.undefined): pass

class pending_exception_info32(pstruct.type):
    _fields_ = [
        (PVOID, 'rethrow_sp'),
        (dyn.pointer(cilk_fiber), 'fiber'),
        (dyn.pointer(cilkrts_worker), 'w'),
        (dyn.pointer(cilkrts_stack_frame), 'saved_sf'),
        (Win32ThrowInfo, 'fake_info'),
        (dyn.pointer(Win32ThrowInfo), 'real_info'),
        (DWORD, 'ExceptionCode'),
        (DWORD, 'ExceptionFlags'),
        (DWORD, 'NumberParameters'),
        (dyn.array(ULONG_PTR, EXCEPTION_MAXIMUM_PARAMETERS), 'ExceptionInformation'),
    ]

class pending_exception_info64(pstruct.type):
    _fields_ = [
        (dyn.pointer(lambda: pending_exception_info), 'nested_exception'),
        (ULONG64, 'rethrow_rip'),
        (ULONG64, 'exception_rbp'),
        (ULONG64, 'exception_rsp'),
        (ULONG64, 'sync_rbp'),
        (ULONG64, 'sync_rsp'),
        (dyn.pointer(cilk_fiber), 'exception_fiber'),
        (dyn.pointer(cilkrts_worker), 'w'),
        (dyn.pointer(cilkrts_stack_frame), 'saved_protected_tail'),
        (dyn.pointer(EXCEPTION_RECORD), 'pExceptRec'),
        (Win64ThrowInfo, 'copy_ThrowInfo'),
        (DWORD, 'offset_dtor'),
        (int, 'nested_exception_found'),
        (int, 'saved_protected_tail_worker_id'),
    ]

class exception_entry_t(pstruct.type):
    _fields_ = [
        (PVOID, 'exception_object'),
        (dyn.pointer(pending_exception_info32), 'pei'),
    ]

class pending_exceptions_t(pstruct.type):
    _fields_ = [
        (long, 'lock'),
        (int, 'max_pending_exceptions'),
        (dyn.pointer(exception_entry_t), 'entries'),
    ]
<|endoftext|>


<commit_before>#!/usr/bin/env python2

import pygame
import random
import os

from sprites.sun import Sun
from objects.button import Button
from question import Question
from fractions import Fraction

class Color:
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    SKYBLUE = (126, 192, 238)
    BROWN = (127, 96, 0)
    GREEN = (0, 255, 0)

class MathHurdler:
    def __init__(self):
        # Set up a clock for managing the frame rate.
        self.clock = pygame.time.Clock()

        self.x = -100
        self.y = 100

        self.vx = 10
        self.vy = 0

        self.paused = False
        self.direction = -1

        self.circle_size = 150

        self.horse_change_semaphore = 3
        self.horse_change = 0

        self.font = pygame.font.SysFont('monospace', 36)
        self.lg_font = pygame.font.SysFont('monospace', 60)

        self.hurdle_number = 0

        self.points = 0

        self.question = Question()

        self.question_text_label = self.lg_font.render(
            str(self.question),
            1,
            Color.BLACK
        )

        self.question_label = self.font.render(
            'Hurdle #' + str(self.hurdle_number),
            1,
            Color.BLACK
        )

        self.score_label = self.lg_font.render(
            str(self.points),
            1,
            Color.BLACK
        )

        self.buttons = []

    def set_paused(self, paused):
        self.paused = paused

    def set_gameover(self, gameover):
        self.gameover = gameover

    def set_playing(self, playing):
        self.playing = playing
        self.set_paused(False)
        self.set_gameover(False)

    def get_asset_path(self, asset_name):
        return os.path.join('./assets/images', asset_name)

    # The main game loop.
    def run(self):
        self.running = True
        self.playing = False
        self.gameover = False
        self.paused = False
        self.last_answer = -1
        question_dirty = True

        self.score = 0

        display_info = pygame.display.Info()
        background_color = Color.SKYBLUE

        screen = pygame.display.get_surface()
        screen_size = screen.get_size()

        ground = pygame.Surface((screen_size[0], screen_size[1] / 3))
        ground = ground.convert()
        ground.fill(Color.BROWN)

        button_panel = pygame.Surface((screen_size[0]/3, screen_size[1] / 7))

        self.buttons = [
            Button(
                str(self.question.answers[i]),
                self.lg_font,
                Color.BLACK,
                button_panel.get_width() / 2,
                button_panel.get_height() / 2,
                Color.WHITE,
                Color.BLACK,
                -2
            ) for i in range(4)
        ]

        grass = pygame.draw.line(
            ground,
            Color.GREEN,
            (0, 0),
            (ground.get_width(), 0),
            ground.get_height() / 2
        )

        points_label = self.lg_font.render('POINTS', 1, Color.BLACK)

        horse = pygame.image.load(self.get_asset_path('color_unicorn.png'))
        horse = pygame.transform.scale(horse,(horse.get_width() / 3, horse.get_height() / 3))
        horse_jump = pygame.transform.rotate(horse,45)
        horse_gallop = pygame.transform.rotate(horse, -15)
        horse_dead = pygame.transform.rotate(horse,-90)

        active_horse = horse_gallop

        horse_x = display_info.current_h/3

        hurdle = pygame.image.load('./assets/images/hurdle.png')
        hurdle = pygame.transform.scale(hurdle,(hurdle.get_height()/3,hurdle.get_width()/3))

        hurdle_y = display_info.current_h - hurdle.get_height() - (2*ground.get_height()/3)

        question_board = pygame.Surface((screen_size[0]/3, screen_size[1] / 5))
        question_board = question_board.convert()
        question_board.fill(Color.WHITE)

        play_button = Button(
            'Play',
            self.lg_font,
            Color.BLACK,
            200,
            100,
            Color.WHITE,
            Color.BLACK,
            -2
        )

        pause_label = self.lg_font.render('PAUSED', 1, Color.BLACK)

        def reset():
            self.last_answer = -1
            question_dirty = True

            self.score = 0
            self.hurdle_number = 0

            self.x = -100
            self.y = 100

            self.vx = 10
            self.vy = 0

            self.direction = -1

            active_horse = horse

            horse_x = display_info.current_h/3

        def generate_question():
            self.question = Question()

            self.buttons[0].set_text(str(self.question.answers[0]))
            self.buttons[1].set_text(str(self.question.answers[1]))
            self.buttons[2].set_text(str(self.question.answers[2]))
            self.buttons[3].set_text(str(self.question.answers[3]))

            self.question_text_label = self.lg_font.render(str(self.question), 1, Color.BLACK)
            self.hurdle_number += 1
            self.score_label = self.lg_font.render(str(self.points),1,Color.BLACK)
            self.question_label = self.font.render("Hurdle #" + str(self.hurdle_number), 1, Color.BLACK)
            question_board.fill(Color.WHITE)

            self.score_label = self.lg_font.render(str(self.points), 1, Color.BLACK)

        def set_answer(answer):
            self.last_answer = Fraction(self.buttons[answer].text)

        def evaluate_answer(answer):
            if self.question.is_answer(answer):
                self.points += 100
                self.score_label = self.lg_font.render(str(self.points), 1, Color.BLACK)
            else:
                self.set_gameover(True)

        while self.running:
            if self.playing:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        return
                    elif event.type == pygame.VIDEORESIZE:
                        pygame.display.set_mode(event.size, pygame.RESIZABLE)
                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_p:
                            self.paused = not self.paused
                        elif event.key == pygame.K_r:
                            reset()
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        for i in range(0, 3):
                            self.buttons[i].mouse_click(
                                pygame.mouse.get_pos(),
                                set_answer,
                                i
                            )

                screen_size = screen.get_size()

                if not self.paused and not self.gameover:

                    self.x += self.vx * self.direction
                    if self.direction == 1 and self.x > screen.get_width() + 50:
                        self.x = -50
                    elif self.direction == -1 and self.x < -50:
                        self.x = screen.get_width() + 50
                    self.y = display_info.current_h - horse.get_height() - ground.get_height()

                    hurdle_rect = hurdle.get_rect(topleft=(self.x,hurdle_y))
                    horse_rect = horse.get_rect(topleft=(horse_x,self.y))

                    if (active_horse == horse_jump) and (not hurdle_rect.colliderect(horse_rect)):
                        active_horse = horse

                    if (self.horse_change == self.horse_change_semaphore):
                        if (active_horse == horse):
                            active_horse = horse_gallop
                        elif (active_horse == horse_gallop):
                            active_horse = horse
                        else:
                            active_horse = horse
                        self.horse_change = 0

                    self.horse_change += 1

                    # Check if hurdle and horse in same spot.
                    if hurdle_rect.colliderect(horse_rect):
                        #evaluate answer on first frame of hurdle collision
                        if not question_dirty:
                            evaluate_answer(self.last_answer)
                            question_dirty = True

                        #if not gameover, jump the hurdle
                        if not self.gameover:
                            active_horse = horse_jump
                            self.y -= 200

                    #if not colliding with hurdle and question still dirty, generate new question
                    elif question_dirty:
                        generate_question()
                        question_dirty = False
                        self.last_answer = -1

                if self.gameover:
                    #spin the horse
                    #active_horse = pygame.transform.rotate(horse_dead, pygame.time.get_ticks())
                    active_horse = horse_dead

                # Set the "sky" color to blue
                screen.fill(background_color)

                sun = Sun()
                sun.rect.x = screen_size[1] + sun.image.get_width()
                sun.rect.y = 0

                allsprites = pygame.sprite.RenderPlain((sun))
                allsprites.draw(screen)

                screen.blit(question_board, (screen_size[0] / 4, screen_size[1] / 5))
                question_board.blit(self.question_label, (10,10))
                question_board.blit(self.question_text_label, (10,self.question_label.get_height()+10))

                screen.blit(
                    self.score_label,
                    (
                        sun.rect.x + sun.image.get_width() / 4,
                        sun.rect.y + sun.image.get_height() / 3
                    )
                )

                screen.blit(
                    points_label,
                    (
                        sun.rect.x + sun.image.get_width() / 4,
                        sun.rect.y + sun.image.get_height() / 3 + self.score_label.get_height()
                    )
                )

                screen.blit(ground, (0, screen_size[1] - ground.get_height()))
                button_panel_x = ground.get_width()/4
                button_panel_y = screen_size[1] - ground.get_height() + ground.get_height() / 3 + 10
                screen.blit(button_panel, (button_panel_x, button_panel_y))

                self.buttons[0].rect.x = button_panel_x
                self.buttons[0].rect.y = button_panel_y
                self.buttons[0].draw(screen)

                self.buttons[1].rect.x = button_panel_x + self.buttons[0].image.get_width()
                self.buttons[1].rect.y = button_panel_y
                self.buttons[1].draw(screen)

                self.buttons[2].rect.x = button_panel_x
                self.buttons[2].rect.y = button_panel_y + self.buttons[0].image.get_height()
                self.buttons[2].draw(screen)

                self.buttons[3].rect.x = button_panel_x + self.buttons[2].image.get_width()
                self.buttons[3].rect.y = button_panel_y + self.buttons[2].image.get_height()
                self.buttons[3].draw(screen)

                screen.blit(active_horse, (horse_x, self.y))
                screen.blit(hurdle,(self.x,hurdle_y))

                # Draw the frame
                pygame.display.flip()

                # Try to stay at 30 FPS
                self.clock.tick(30)
            else:
                def start_game():
                    self.set_playing(True)

                #in the menu
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        return
                    elif event.type == pygame.VIDEORESIZE:
                        pygame.display.set_mode(event.size, pygame.RESIZABLE)
                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_p:
                            self.set_playing(True)
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        play_button.mouse_click(
                            pygame.mouse.get_pos(),
                            start_game
                        )

                screen_size = screen.get_size()

                screen.fill(background_color);

                play_button.rect.x = (screen_size[0] - play_button.rect.width) / 2
                play_button.rect.y = (screen_size[1] - play_button.rect.height) / 2
                play_button.draw(screen)

                pygame.display.flip()

                # Try to stay at 30 FPS
                self.clock.tick(30)

# This function is called when the game is run directly from the command line:
# ./TestGame.py
def main():
    pygame.init()
    pygame.display.set_mode((0, 0), pygame.RESIZABLE)
    game = MathHurdler()
    game.run()

if __name__ == '__main__':
    main()
<commit_msg>Added button selection logic to state controls.<commit_after>#!/usr/bin/env python2

import pygame
import random
import os

from sprites.sun import Sun
from objects.button import Button
from question import Question
from fractions import Fraction

class Color:
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    SKYBLUE = (126, 192, 238)
    BROWN = (127, 96, 0)
    GREEN = (0, 255, 0)

class MathHurdler:
    def __init__(self):
        # Set up a clock for managing the frame rate.
        self.clock = pygame.time.Clock()

        self.x = -100
        self.y = 100

        self.vx = 10
        self.vy = 0

        self.paused = False
        self.direction = -1

        self.circle_size = 150

        self.horse_change_semaphore = 3
        self.horse_change = 0

        self.font = pygame.font.SysFont('monospace', 36)
        self.lg_font = pygame.font.SysFont('monospace', 60)

        self.hurdle_number = 0

        self.points = 0

        self.question = Question()

        self.question_text_label = self.lg_font.render(
            str(self.question),
            1,
            Color.BLACK
        )

        self.question_label = self.font.render(
            'Hurdle #' + str(self.hurdle_number),
            1,
            Color.BLACK
        )

        self.score_label = self.lg_font.render(
            str(self.points),
            1,
            Color.BLACK
        )

        self.buttons = []

    def set_paused(self, paused):
        self.paused = paused

    def set_gameover(self, gameover):
        self.gameover = gameover

    def set_playing(self, playing):
        self.playing = playing
        self.set_paused(False)
        self.set_gameover(False)

    def get_asset_path(self, asset_name):
        return os.path.join('./assets/images', asset_name)

    # The main game loop.
    def run(self):
        self.running = True
        self.playing = False
        self.gameover = False
        self.paused = False
        self.last_answer = -1
        self.last_answer_index = -1
        question_dirty = True

        self.score = 0

        display_info = pygame.display.Info()
        background_color = Color.SKYBLUE

        screen = pygame.display.get_surface()
        screen_size = screen.get_size()

        ground = pygame.Surface((screen_size[0], screen_size[1] / 3))
        ground = ground.convert()
        ground.fill(Color.BROWN)

        button_panel = pygame.Surface((screen_size[0]/3, screen_size[1] / 7))

        self.buttons = [
            Button(
                str(self.question.answers[i]),
                self.lg_font,
                Color.BLACK,
                button_panel.get_width() / 2,
                button_panel.get_height() / 2,
                Color.WHITE,
                Color.BLACK,
                -2
            ) for i in range(4)
        ]

        grass = pygame.draw.line(
            ground,
            Color.GREEN,
            (0, 0),
            (ground.get_width(), 0),
            ground.get_height() / 2
        )

        points_label = self.lg_font.render('POINTS', 1, Color.BLACK)

        horse = pygame.image.load(self.get_asset_path('color_unicorn.png'))
        horse = pygame.transform.scale(horse,(horse.get_width() / 3, horse.get_height() / 3))
        horse_jump = pygame.transform.rotate(horse,45)
        horse_gallop = pygame.transform.rotate(horse, -15)
        horse_dead = pygame.transform.rotate(horse,-90)

        active_horse = horse_gallop

        horse_x = display_info.current_h/3

        hurdle = pygame.image.load('./assets/images/hurdle.png')
        hurdle = pygame.transform.scale(hurdle,(hurdle.get_height()/3,hurdle.get_width()/3))

        hurdle_y = display_info.current_h - hurdle.get_height() - (2*ground.get_height()/3)

        question_board = pygame.Surface((screen_size[0]/3, screen_size[1] / 5))
        question_board = question_board.convert()
        question_board.fill(Color.WHITE)

        play_button = Button(
            'Play',
            self.lg_font,
            Color.BLACK,
            200,
            100,
            Color.WHITE,
            Color.BLACK,
            -2
        )

        pause_label = self.lg_font.render('PAUSED', 1, Color.BLACK)

        def reset():
            question_dirty = True

            self.score = 0
            self.hurdle_number = 0

            self.x = -100
            self.y = 100

            self.vx = 10
            self.vy = 0

            self.direction = -1

            active_horse = horse

            horse_x = display_info.current_h/3

            set_answer(-1)

        def generate_question():
            self.question = Question()

            self.buttons[0].set_text(str(self.question.answers[0]))
            self.buttons[1].set_text(str(self.question.answers[1]))
            self.buttons[2].set_text(str(self.question.answers[2]))
            self.buttons[3].set_text(str(self.question.answers[3]))

            self.question_text_label = self.lg_font.render(str(self.question), 1, Color.BLACK)
            self.hurdle_number += 1
            self.score_label = self.lg_font.render(str(self.points),1,Color.BLACK)
            self.question_label = self.font.render("Hurdle #" + str(self.hurdle_number), 1, Color.BLACK)
            question_board.fill(Color.WHITE)

            self.score_label = self.lg_font.render(str(self.points), 1, Color.BLACK)

        def set_answer(answer):
            #unselect the previous answer button
            if self.last_answer_index >= 0:
                self.buttons[self.last_answer_index].set_selected(False)

            if answer >= 0:
                self.last_answer = Fraction(self.buttons[answer].text)
                self.buttons[answer].set_selected(True)
                self.last_answer_index = answer
            else:
                self.last_answer = -1
                self.last_answer_index = -1

        def evaluate_answer(answer):
            if self.question.is_answer(answer):
                self.points += 100
                self.score_label = self.lg_font.render(str(self.points), 1, Color.BLACK)
            else:
                self.set_gameover(True)

        while self.running:
            if self.playing:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        return
                    elif event.type == pygame.VIDEORESIZE:
                        pygame.display.set_mode(event.size, pygame.RESIZABLE)
                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_p:
                            self.paused = not self.paused
                        elif event.key == pygame.K_r:
                            reset()
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        for i in range(0, 3):
                            self.buttons[i].mouse_click(
                                pygame.mouse.get_pos(),
                                set_answer,
                                i
                            )

                screen_size = screen.get_size()

                if not self.paused and not self.gameover:

                    self.x += self.vx * self.direction
                    if self.direction == 1 and self.x > screen.get_width() + 50:
                        self.x = -50
                    elif self.direction == -1 and self.x < -50:
                        self.x = screen.get_width() + 50
                    self.y = display_info.current_h - horse.get_height() - ground.get_height()

                    hurdle_rect = hurdle.get_rect(topleft=(self.x,hurdle_y))
                    horse_rect = horse.get_rect(topleft=(horse_x,self.y))

                    if (active_horse == horse_jump) and (not hurdle_rect.colliderect(horse_rect)):
                        active_horse = horse

                    if (self.horse_change == self.horse_change_semaphore):
                        if (active_horse == horse):
                            active_horse = horse_gallop
                        elif (active_horse == horse_gallop):
                            active_horse = horse
                        else:
                            active_horse = horse
                        self.horse_change = 0

                    self.horse_change += 1

                    # Check if hurdle and horse in same spot.
                    if hurdle_rect.colliderect(horse_rect):
                        #evaluate answer on first frame of hurdle collision
                        if not question_dirty:
                            evaluate_answer(self.last_answer)
                            question_dirty = True

                        #if not gameover, jump the hurdle
                        if not self.gameover:
                            active_horse = horse_jump
                            self.y -= 200

                    #if not colliding with hurdle and question still dirty, generate new question
                    elif question_dirty:
                        generate_question()
                        question_dirty = False
                        set_answer(-1)

                if self.gameover:
                    #spin the horse
                    #active_horse = pygame.transform.rotate(horse_dead, pygame.time.get_ticks())
                    active_horse = horse_dead

                # Set the "sky" color to blue
                screen.fill(background_color)

                sun = Sun()
                sun.rect.x = screen_size[1] + sun.image.get_width()
                sun.rect.y = 0

                allsprites = pygame.sprite.RenderPlain((sun))
                allsprites.draw(screen)

                screen.blit(question_board, (screen_size[0] / 4, screen_size[1] / 5))
                question_board.blit(self.question_label, (10,10))
                question_board.blit(self.question_text_label, (10,self.question_label.get_height()+10))

                screen.blit(
                    self.score_label,
                    (
                        sun.rect.x + sun.image.get_width() / 4,
                        sun.rect.y + sun.image.get_height() / 3
                    )
                )

                screen.blit(
                    points_label,
                    (
                        sun.rect.x + sun.image.get_width() / 4,
                        sun.rect.y + sun.image.get_height() / 3 + self.score_label.get_height()
                    )
                )

                screen.blit(ground, (0, screen_size[1] - ground.get_height()))
                button_panel_x = ground.get_width()/4
                button_panel_y = screen_size[1] - ground.get_height() + ground.get_height() / 3 + 10
                screen.blit(button_panel, (button_panel_x, button_panel_y))

                self.buttons[0].rect.x = button_panel_x
                self.buttons[0].rect.y = button_panel_y
                self.buttons[0].draw(screen)

                self.buttons[1].rect.x = button_panel_x + self.buttons[0].image.get_width()
                self.buttons[1].rect.y = button_panel_y
                self.buttons[1].draw(screen)

                self.buttons[2].rect.x = button_panel_x
                self.buttons[2].rect.y = button_panel_y + self.buttons[0].image.get_height()
                self.buttons[2].draw(screen)

                self.buttons[3].rect.x = button_panel_x + self.buttons[2].image.get_width()
                self.buttons[3].rect.y = button_panel_y + self.buttons[2].image.get_height()
                self.buttons[3].draw(screen)

                screen.blit(active_horse, (horse_x, self.y))
                screen.blit(hurdle,(self.x,hurdle_y))

                # Draw the frame
                pygame.display.flip()

                # Try to stay at 30 FPS
                self.clock.tick(30)
            else:
                def start_game():
                    self.set_playing(True)

                #in the menu
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        return
                    elif event.type == pygame.VIDEORESIZE:
                        pygame.display.set_mode(event.size, pygame.RESIZABLE)
                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_p:
                            self.set_playing(True)
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        play_button.mouse_click(
                            pygame.mouse.get_pos(),
                            start_game
                        )

                screen_size = screen.get_size()

                screen.fill(background_color);

                play_button.rect.x = (screen_size[0] - play_button.rect.width) / 2
                play_button.rect.y = (screen_size[1] - play_button.rect.height) / 2
                play_button.draw(screen)

                pygame.display.flip()

                # Try to stay at 30 FPS
                self.clock.tick(30)

# This function is called when the game is run directly from the command line:
# ./TestGame.py
def main():
    pygame.init()
    pygame.display.set_mode((0, 0), pygame.RESIZABLE)
    game = MathHurdler()
    game.run()

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