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

import os
import sys
import json
from textwrap import dedent
from polls.models import Question, Choice
from django.test import Client, TestCase
from django.test.utils import override_settings
import pyexcel as pe
import pyexcel.ext.xls  # noqa
import pyexcel.ext.xlsx  # noqa
import pyexcel.ext.ods3  # noqa
from django_excel._compact import urllib_quote

PY2 = sys.version_info[0] == 2
if sys.version_info[0] == 2 and sys.version_info[1] < 7:
    from ordereddict import OrderedDict
else:
    from collections import OrderedDict

_XLSX_MIME = (
    "application/" +
    "vnd.openxmlformats-officedocument.spreadsheetml.sheet")

FILE_TYPE_MIME_TABLE = {
    "csv": "text/csv",
    "tsv": "text/tab-separated-values",
    "csvz": "application/zip",
    "tsvz": "application/zip",
    "ods": "application/vnd.oasis.opendocument.spreadsheet",
    "xls": "application/vnd.ms-excel",
    "xlsx": _XLSX_MIME,
    "xlsm": "application/vnd.ms-excel.sheet.macroenabled.12"
}

class ExcelResponseTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.data = [
            [1, 2, 3],
            [4, 5, 6]
        ]
        self.single_sheet = [
            ['X', 'Y', 'Z'],
            [1, 2, 3],
            [4, 5, 6]
        ]
        self.book_content = OrderedDict()
        self.book_content.update({
            "Sheet1": [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]})
        self.book_content.update({
            "Sheet2": [[4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6]]})
        self.book_content.update({
            "Sheet3": [[u'X', u'Y', u'Z'], [1, 4, 7], [2, 5, 8], [3, 6, 9]]})

    def test_download(self):
        for file_type in FILE_TYPE_MIME_TABLE.keys():
            response = self.client.get("/polls/download/"+file_type)
            assert response['Content-Type'] == FILE_TYPE_MIME_TABLE[file_type]
            sheet = pe.get_sheet(file_type=file_type,
                                 file_content=response.content)
            sheet.format(int)
            array = sheet.to_array()
            assert array == self.data

    def test_download_attachment_with_ascii_name(self):
        test_file_name = "test"
        self._download_and_verify_file_name(test_file_name)

    def test_download_attachment_with_unicode_name(self):
        test_file_name = u'中文文件名'
        self._download_and_verify_file_name(test_file_name.encode('utf-8'))

    def test_download_attachment_with_unicode_name_as_string(self):
        test_file_name = '中文文件名'
        self._download_and_verify_file_name(test_file_name)

    def _download_and_verify_file_name(self, file_name):
        for file_type in FILE_TYPE_MIME_TABLE.keys():
            url_encoded_file_name = urllib_quote(file_name)
            response = self.client.get(
                ("/polls/download_attachment/%s/%s" % (
                    file_type, url_encoded_file_name)))
            assert response['Content-Type'] == FILE_TYPE_MIME_TABLE[file_type]
            assert response['Content-Disposition'] == (
                "attachment; filename=%s.%s;filename*=utf-8''%s.%s"
                % (url_encoded_file_name, file_type,
                   url_encoded_file_name, file_type))
            sheet = pe.get_sheet(file_type=file_type,
                                 file_content=response.content)
            sheet.format(int)
            array = sheet.to_array()
            assert array == self.data

    def test_parse_single_sheet(self):
        test_sample = {
            "array": {
                u'result': [[u'X', u'Y', u'Z'],
                            [1.0, 2.0, 3.0],
                            [4.0, 5.0, 6.0]]},
            "dict": {
                u'Y': [2.0, 5.0],
                u'X': [1.0, 4.0],
                u'Z': [3.0, 6.0]},
            "records": {
                u'result': [{u'Y': 2.0, u'X': 1.0, u'Z': 3.0},
                            {u'Y': 5.0, u'X': 4.0, u'Z': 6.0}]}
        }
        for data_struct_type in test_sample.keys():
            sheet = pe.Sheet(self.single_sheet)
            tmp_filename = "test.file.xls"
            sheet.save_as(tmp_filename)
            with open(tmp_filename, "rb") as fp:
                response = self.client.post(
                    '/polls/parse/'+data_struct_type,
                    data={"file": fp})
                self.assertEqual(json.loads(response.content.decode('utf-8')),
                                 test_sample[data_struct_type])
            os.unlink(tmp_filename)

    def test_parse_book(self):
        test_sample = [
            "book",
            "book_dict"
        ]
        expected_dict = {
            u'Sheet1': [[1.0, 1.0, 1.0, 1.0],
                        [2.0, 2.0, 2.0, 2.0],
                        [3.0, 3.0, 3.0, 3.0]],
            u'Sheet3': [[u'X', u'Y', u'Z'],
                        [1.0, 4.0, 7.0],
                        [2.0, 5.0, 8.0],
                        [3.0, 6.0, 9.0]],
            u'Sheet2': [[4.0, 4.0, 4.0, 4.0],
                        [5.0, 5.0, 5.0, 5.0],
                        [6.0, 6.0, 6.0, 6.0]]}
        for data_struct_type in test_sample:
            sheet = pe.Book(self.book_content)
            tmp_filename = "test.xls"
            sheet.save_as(tmp_filename)
            with open(tmp_filename, "rb") as fp:
                response = self.client.post(
                    '/polls/parse/'+data_struct_type,
                    data={"file": fp})
                self.assertEqual(json.loads(response.content.decode('utf-8')),
                                 expected_dict)
            os.unlink(tmp_filename)

    def test_exchange(self):
        for in_file_type in FILE_TYPE_MIME_TABLE.keys():
            sheet = pe.Sheet(self.data)
            tmp_filename = "test.%s" % in_file_type
            sheet.save_as(tmp_filename)
            for file_type in FILE_TYPE_MIME_TABLE.keys():
                print("Post %s -> Respond %s" % (in_file_type, file_type))
                with open(tmp_filename, "rb") as fp:
                    response = self.client.post(
                        '/polls/exchange/'+file_type,
                        data={"file": fp})
                    self.assertEqual(response['Content-Type'],
                                     FILE_TYPE_MIME_TABLE[file_type])
                    sheet = pe.get_sheet(file_type=file_type,
                                         file_content=response.content)
                    sheet.format(int)
                    array = sheet.to_array()
                    assert array == self.data
            os.unlink(tmp_filename)

class DatabaseOperationsTestCase(TestCase):
    def setUp(self):
        self.testfile = "sample-data.xls"
        Question.objects.all().delete()
        Choice.objects.all().delete()

    def testBook(self):
        fp = open(self.testfile, "rb")
        response = self.client.post('/polls/import/', data={"file": fp})
        assert response.status_code == 200
        response2 = self.client.get('/polls/export/book')
        assert response2.status_code == 200
        book = pe.get_book(file_type='xls', file_content=response2.content)
        content = dedent("""
        question:
        +----+---------------------------+----------------------------------------------+----------+
        | id | pub_date                  | question_text                                | slug     |
        +----+---------------------------+----------------------------------------------+----------+
        | 1  | 2015-01-28T00:00:00+00:00 | What is your favourite programming language? | language |
        +----+---------------------------+----------------------------------------------+----------+
        | 2  | 2015-01-29T00:00:00+00:00 | What is your favourite IDE?                  | ide      |
        +----+---------------------------+----------------------------------------------+----------+
        choice:
        +---------------+----+-------------+-------+
        | choice_text   | id | question_id | votes |
        +---------------+----+-------------+-------+
        | Java          | 1  | 1           | 0     |
        +---------------+----+-------------+-------+
        | C++           | 2  | 1           | 0     |
        +---------------+----+-------------+-------+
        | C             | 3  | 1           | 0     |
        +---------------+----+-------------+-------+
        | Eclipse       | 4  | 2           | 0     |
        +---------------+----+-------------+-------+
        | Visual Studio | 5  | 2           | 0     |
        +---------------+----+-------------+-------+
        | PyCharm       | 6  | 2           | 0     |
        +---------------+----+-------------+-------+
        | IntelliJ      | 7  | 2           | 0     |
        +---------------+----+-------------+-------+""").strip('\n')  # noqa
        self.assertEqual(str(book), content)

    def testSheet(self):
        fp = open(self.testfile, "rb")
        response = self.client.post('/polls/import/', data={"file": fp})
        assert response.status_code == 200
        response2 = self.client.get('/polls/export/sheet')
        assert response2.status_code == 200
        sheet = pe.get_sheet(file_type='xls', file_content=response2.content)
        content = dedent("""
        question:
        +----+---------------------------+----------------------------------------------+----------+
        | id | pub_date                  | question_text                                | slug     |
        +----+---------------------------+----------------------------------------------+----------+
        | 1  | 2015-01-28T00:00:00+00:00 | What is your favourite programming language? | language |
        +----+---------------------------+----------------------------------------------+----------+
        | 2  | 2015-01-29T00:00:00+00:00 | What is your favourite IDE?                  | ide      |
        +----+---------------------------+----------------------------------------------+----------+""").strip('\n')  # noqa
        assert str(sheet) == content

    def testImportSheet(self):
        fp = open("sample-sheet.xls", "rb")
        response = self.client.post('/polls/import_sheet/', data={"file": fp})
        assert response.status_code == 200
        response2 = self.client.get('/polls/export/sheet')
        assert response2.status_code == 200
        sheet = pe.get_sheet(file_type='xls', file_content=response2.content)
        content = dedent("""
        question:
        +----+---------------------------+----------------------------------------------+----------+
        | id | pub_date                  | question_text                                | slug     |
        +----+---------------------------+----------------------------------------------+----------+
        | 1  | 2015-01-28T00:00:00+00:00 | What is your favourite programming language? | language |
        +----+---------------------------+----------------------------------------------+----------+
        | 2  | 2015-01-29T00:00:00+00:00 | What is your favourite IDE?                  | ide      |
        +----+---------------------------+----------------------------------------------+----------+""").strip('\n')  # noqa
        self.assertEqual(str(sheet), content)

    def testCustomExport(self):
        fp = open(self.testfile, "rb")
        response = self.client.post('/polls/import/', data={"file": fp})
        assert response.status_code == 200
        response2 = self.client.get('/polls/export/custom')
        assert response2.status_code == 200
        sheet = pe.get_sheet(file_type='xls', file_content=response2.content)
        content = dedent("""
        pyexcel_sheet1:
        +---------------+----+-------+
        | choice_text   | id | votes |
        +---------------+----+-------+
        | Eclipse       | 4  | 0     |
        +---------------+----+-------+
        | Visual Studio | 5  | 0     |
        +---------------+----+-------+
        | PyCharm       | 6  | 0     |
        +---------------+----+-------+
        | IntelliJ      | 7  | 0     |
        +---------------+----+-------+""").strip('\n')
        self.assertEqual(str(sheet), content)

@override_settings(FILE_UPLOAD_MAX_MEMORY_SIZE=1)
class ExcelResponseUsingFileTestCase(ExcelResponseTestCase):
    pass

@override_settings(FILE_UPLOAD_MAX_MEMORY_SIZE=1)
class DatabaseOperationsUsingFileTestCase(DatabaseOperationsTestCase):
    pass
<commit_msg>update test cases<commit_after># -*- coding: utf-8 -*-

import os
import sys
import json
from textwrap import dedent
from polls.models import Question, Choice
from django.test import Client, TestCase
from django.test.utils import override_settings
import pyexcel as pe
import pyexcel.ext.xls  # noqa
import pyexcel.ext.xlsx  # noqa
import pyexcel.ext.ods3  # noqa
from django_excel._compact import urllib_quote
from nose.tools import eq_

PY2 = sys.version_info[0] == 2
if sys.version_info[0] == 2 and sys.version_info[1] < 7:
    from ordereddict import OrderedDict
else:
    from collections import OrderedDict

_XLSX_MIME = (
    "application/" +
    "vnd.openxmlformats-officedocument.spreadsheetml.sheet")

FILE_TYPE_MIME_TABLE = {
    "csv": "text/csv",
    "tsv": "text/tab-separated-values",
    "csvz": "application/zip",
    "tsvz": "application/zip",
    "ods": "application/vnd.oasis.opendocument.spreadsheet",
    "xls": "application/vnd.ms-excel",
    "xlsx": _XLSX_MIME,
    "xlsm": "application/vnd.ms-excel.sheet.macroenabled.12"
}

class ExcelResponseTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.data = [
            [1, 2, 3],
            [4, 5, 6]
        ]
        self.single_sheet = [
            ['X', 'Y', 'Z'],
            [1, 2, 3],
            [4, 5, 6]
        ]
        self.book_content = OrderedDict()
        self.book_content.update({
            "Sheet1": [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]})
        self.book_content.update({
            "Sheet2": [[4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6]]})
        self.book_content.update({
            "Sheet3": [[u'X', u'Y', u'Z'], [1, 4, 7], [2, 5, 8], [3, 6, 9]]})

    def test_download(self):
        for file_type in FILE_TYPE_MIME_TABLE.keys():
            response = self.client.get("/polls/download/"+file_type)
            assert response['Content-Type'] == FILE_TYPE_MIME_TABLE[file_type]
            sheet = pe.get_sheet(file_type=file_type,
                                 file_content=response.content)
            sheet.format(int)
            array = sheet.to_array()
            assert array == self.data

    def test_download_attachment_with_ascii_name(self):
        test_file_name = "test"
        self._download_and_verify_file_name(test_file_name)

    def test_download_attachment_with_unicode_name(self):
        test_file_name = u'中文文件名'
        self._download_and_verify_file_name(test_file_name.encode('utf-8'))

    def test_download_attachment_with_unicode_name_as_string(self):
        test_file_name = '中文文件名'
        self._download_and_verify_file_name(test_file_name)

    def _download_and_verify_file_name(self, file_name):
        for file_type in FILE_TYPE_MIME_TABLE.keys():
            url_encoded_file_name = urllib_quote(file_name)
            response = self.client.get(
                ("/polls/download_attachment/%s/%s" % (
                    file_type, url_encoded_file_name)))
            assert response['Content-Type'] == FILE_TYPE_MIME_TABLE[file_type]
            assert response['Content-Disposition'] == (
                "attachment; filename=%s.%s;filename*=utf-8''%s.%s"
                % (url_encoded_file_name, file_type,
                   url_encoded_file_name, file_type))
            sheet = pe.get_sheet(file_type=file_type,
                                 file_content=response.content)
            sheet.format(int)
            array = sheet.to_array()
            assert array == self.data

    def test_parse_single_sheet(self):
        test_sample = {
            "array": {
                u'result': [[u'X', u'Y', u'Z'],
                            [1.0, 2.0, 3.0],
                            [4.0, 5.0, 6.0]]},
            "dict": {
                u'Y': [2.0, 5.0],
                u'X': [1.0, 4.0],
                u'Z': [3.0, 6.0]},
            "records": {
                u'result': [{u'Y': 2.0, u'X': 1.0, u'Z': 3.0},
                            {u'Y': 5.0, u'X': 4.0, u'Z': 6.0}]}
        }
        for data_struct_type in test_sample.keys():
            sheet = pe.Sheet(self.single_sheet)
            tmp_filename = "test.file.xls"
            sheet.save_as(tmp_filename)
            with open(tmp_filename, "rb") as fp:
                response = self.client.post(
                    '/polls/parse/'+data_struct_type,
                    data={"file": fp})
                self.assertEqual(json.loads(response.content.decode('utf-8')),
                                 test_sample[data_struct_type])
            os.unlink(tmp_filename)

    def test_parse_book(self):
        test_sample = [
            "book",
            "book_dict"
        ]
        expected_dict = {
            u'Sheet1': [[1.0, 1.0, 1.0, 1.0],
                        [2.0, 2.0, 2.0, 2.0],
                        [3.0, 3.0, 3.0, 3.0]],
            u'Sheet3': [[u'X', u'Y', u'Z'],
                        [1.0, 4.0, 7.0],
                        [2.0, 5.0, 8.0],
                        [3.0, 6.0, 9.0]],
            u'Sheet2': [[4.0, 4.0, 4.0, 4.0],
                        [5.0, 5.0, 5.0, 5.0],
                        [6.0, 6.0, 6.0, 6.0]]}
        for data_struct_type in test_sample:
            sheet = pe.Book(self.book_content)
            tmp_filename = "test.xls"
            sheet.save_as(tmp_filename)
            with open(tmp_filename, "rb") as fp:
                response = self.client.post(
                    '/polls/parse/'+data_struct_type,
                    data={"file": fp})
                self.assertEqual(json.loads(response.content.decode('utf-8')),
                                 expected_dict)
            os.unlink(tmp_filename)

    def test_exchange(self):
        for in_file_type in FILE_TYPE_MIME_TABLE.keys():
            sheet = pe.Sheet(self.data)
            tmp_filename = "test.%s" % in_file_type
            sheet.save_as(tmp_filename)
            for file_type in FILE_TYPE_MIME_TABLE.keys():
                print("Post %s -> Respond %s" % (in_file_type, file_type))
                with open(tmp_filename, "rb") as fp:
                    response = self.client.post(
                        '/polls/exchange/'+file_type,
                        data={"file": fp})
                    self.assertEqual(response['Content-Type'],
                                     FILE_TYPE_MIME_TABLE[file_type])
                    sheet = pe.get_sheet(file_type=file_type,
                                         file_content=response.content)
                    sheet.format(int)
                    array = sheet.to_array()
                    assert array == self.data
            os.unlink(tmp_filename)

class DatabaseOperationsTestCase(TestCase):
    def setUp(self):
        self.testfile = "sample-data.xls"
        Question.objects.all().delete()
        Choice.objects.all().delete()

    def testBook(self):
        fp = open(self.testfile, "rb")
        response = self.client.post('/polls/import/', data={"file": fp})
        eq_(response.status_code, 302)
        response2 = self.client.get('/polls/export/book')
        assert response2.status_code == 200
        book = pe.get_book(file_type='xls', file_content=response2.content)
        content = dedent("""
        question:
        +----+---------------------------+----------------------------------------------+----------+
        | id | pub_date                  | question_text                                | slug     |
        +----+---------------------------+----------------------------------------------+----------+
        | 1  | 2015-01-28T00:00:00+00:00 | What is your favourite programming language? | language |
        +----+---------------------------+----------------------------------------------+----------+
        | 2  | 2015-01-29T00:00:00+00:00 | What is your favourite IDE?                  | ide      |
        +----+---------------------------+----------------------------------------------+----------+
        choice:
        +---------------+----+-------------+-------+
        | choice_text   | id | question_id | votes |
        +---------------+----+-------------+-------+
        | Java          | 1  | 1           | 0     |
        +---------------+----+-------------+-------+
        | C++           | 2  | 1           | 0     |
        +---------------+----+-------------+-------+
        | C             | 3  | 1           | 0     |
        +---------------+----+-------------+-------+
        | Eclipse       | 4  | 2           | 0     |
        +---------------+----+-------------+-------+
        | Visual Studio | 5  | 2           | 0     |
        +---------------+----+-------------+-------+
        | PyCharm       | 6  | 2           | 0     |
        +---------------+----+-------------+-------+
        | IntelliJ      | 7  | 2           | 0     |
        +---------------+----+-------------+-------+""").strip('\n')  # noqa
        self.assertEqual(str(book), content)

    def testSheet(self):
        fp = open(self.testfile, "rb")
        response = self.client.post('/polls/import/', data={"file": fp})
        eq_(response.status_code, 302)
        response2 = self.client.get('/polls/export/sheet')
        assert response2.status_code == 200
        sheet = pe.get_sheet(file_type='xls', file_content=response2.content)
        content = dedent("""
        question:
        +----+---------------------------+----------------------------------------------+----------+
        | id | pub_date                  | question_text                                | slug     |
        +----+---------------------------+----------------------------------------------+----------+
        | 1  | 2015-01-28T00:00:00+00:00 | What is your favourite programming language? | language |
        +----+---------------------------+----------------------------------------------+----------+
        | 2  | 2015-01-29T00:00:00+00:00 | What is your favourite IDE?                  | ide      |
        +----+---------------------------+----------------------------------------------+----------+""").strip('\n')  # noqa
        assert str(sheet) == content

    def testImportSheet(self):
        fp = open("sample-sheet.xls", "rb")
        response = self.client.post('/polls/import_sheet/', data={"file": fp})
        eq_(response.status_code, 200)
        response2 = self.client.get('/polls/export/sheet')
        eq_(response2.status_code, 200)
        sheet = pe.get_sheet(file_type='xls', file_content=response2.content)
        content = dedent("""
        question:
        +----+---------------------------+----------------------------------------------+----------+
        | id | pub_date                  | question_text                                | slug     |
        +----+---------------------------+----------------------------------------------+----------+
        | 1  | 2015-01-28T00:00:00+00:00 | What is your favourite programming language? | language |
        +----+---------------------------+----------------------------------------------+----------+
        | 2  | 2015-01-29T00:00:00+00:00 | What is your favourite IDE?                  | ide      |
        +----+---------------------------+----------------------------------------------+----------+""").strip('\n')  # noqa
        self.assertEqual(str(sheet), content)

    def testCustomExport(self):
        fp = open(self.testfile, "rb")
        response = self.client.post('/polls/import/', data={"file": fp})
        eq_(response.status_code, 302)
        response2 = self.client.get('/polls/export/custom')
        eq_(response2.status_code, 200)
        sheet = pe.get_sheet(file_type='xls', file_content=response2.content)
        content = dedent("""
        pyexcel_sheet1:
        +---------------+----+-------+
        | choice_text   | id | votes |
        +---------------+----+-------+
        | Eclipse       | 4  | 0     |
        +---------------+----+-------+
        | Visual Studio | 5  | 0     |
        +---------------+----+-------+
        | PyCharm       | 6  | 0     |
        +---------------+----+-------+
        | IntelliJ      | 7  | 0     |
        +---------------+----+-------+""").strip('\n')
        self.assertEqual(str(sheet), content)

@override_settings(FILE_UPLOAD_MAX_MEMORY_SIZE=1)
class ExcelResponseUsingFileTestCase(ExcelResponseTestCase):
    pass

@override_settings(FILE_UPLOAD_MAX_MEMORY_SIZE=1)
class DatabaseOperationsUsingFileTestCase(DatabaseOperationsTestCase):
    pass
<|endoftext|>


<commit_before>"""
COMAOPtriathlon.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random

"""
sl=int(input("Length of swim (in kilometers)"))
bl=int(input("Length of bike (in kilometers)"))
rl=int(input("Length of run (in kilometers)"))
fprostart=int(input("Time female pros start (in minutes after male pro start)"))
mprestart=int(input("Time male premiere start (in minutes after male pro start)"))
fprestart=int(input("Time female premiere start (in minutes after male pro start)"))
mopenstart=int(input("Time male open start (in minutes after male pro start)"))
fopenstart=int(input("Time female open start (in minutes after male pro start)"))
clystart=int(input("Time Clydsedale start (in minutes after male pro start)"))
athstart=int(input("Time Athena start (in minutes after male pro start)"))
"""
#average swim speeds
mpros=0
fpros=0
mpres=0
fpres=0
mos=0
fos=0
cyls=0
aths=0
#average t1 times
mprot1=0
fprot1=0
mpret1=0
fpret1=0
mot1=0
fot1=0
cylt1=0
atht1=0
#average bike speeds
mprob=0
fprob=0
mpreb=0
fpreb=0
mob=0
fob=0
cylb=0
athb=0
#average t2 times
mprot2=0
fprot2=0
mpret2=0
fpret2=0
mot2=0
fot2=0
cylt2=0
atht2=0
#average run speeds
mpror=0
fpror=0
mprer=0
fprer=0
mor=0
for1=0
cylr=0
athr=0

# colors
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class start(Sprite):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,60,50), 1, 'veritcal')
    def __init__(self, position):
        super().__init__(start.asset, position)
        self.vx=0
        self.vy=0

class finish(Sprite):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,10,10), 1, 'veritcal')
    def __init__(self, position):
        super().__init__(finish.asset, position)
        self.vx=0
        self.vy=0

class mpro(Sprite):
    asset = RectangleAsset(1,1,thicklineb,black)
    def __init__(self, position):
        super().__init__(mpro.asset, position)
        self.vx=0
        self.vy=0
    def step(self):
        self.x += 0
        self.y += 0

class fpro(Sprite):
    asset = RectangleAsset(1,1,thickliner,black)
    def __init__(self, position):
        super().__init__(fpro.asset, position)
        self.vx=0
        self.vy=0
    def step(self):
        self.x += 0
        self.y += 0

class triathlon(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        mpro((0,0))
        fpro((0,0))
        start((100,0))
        finish((500,0))
    def step(self):
        for mp in self.getSpritesbyClass(mpro):
            mp.step()
        for fp in self.getSpritesbyClass(fpro):
            fp.step()

myapp = triathlon(1000,750)
myapp.run()
<commit_msg>Updated from Brython Server: 11/10/2016 9:18:02 AM<commit_after>"""
COMAOPtriathlon.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random

"""
sl=int(input("Length of swim (in kilometers)"))
bl=int(input("Length of bike (in kilometers)"))
rl=int(input("Length of run (in kilometers)"))
fprostart=int(input("Time female pros start (in minutes after male pro start)"))
mprestart=int(input("Time male premiere start (in minutes after male pro start)"))
fprestart=int(input("Time female premiere start (in minutes after male pro start)"))
mopenstart=int(input("Time male open start (in minutes after male pro start)"))
fopenstart=int(input("Time female open start (in minutes after male pro start)"))
clystart=int(input("Time Clydsedale start (in minutes after male pro start)"))
athstart=int(input("Time Athena start (in minutes after male pro start)"))
"""
#average swim speeds
mpros=0
fpros=0
mpres=0
fpres=0
mos=0
fos=0
cyls=0
aths=0
#average t1 times
mprot1=0
fprot1=0
mpret1=0
fpret1=0
mot1=0
fot1=0
cylt1=0
atht1=0
#average bike speeds
mprob=0
fprob=0
mpreb=0
fpreb=0
mob=0
fob=0
cylb=0
athb=0
#average t2 times
mprot2=0
fprot2=0
mpret2=0
fpret2=0
mot2=0
fot2=0
cylt2=0
atht2=0
#average run speeds
mpror=0
fpror=0
mprer=0
fprer=0
mor=0
for1=0
cylr=0
athr=0

# colors
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class start(Sprite):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,55,50), 1, 'veritcal')
    def __init__(self, position):
        super().__init__(start.asset, position)
        self.vx=0
        self.vy=0

class finish(Sprite):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,10,10), 1, 'veritcal')
    def __init__(self, position):
        super().__init__(finish.asset, position)
        self.vx=0
        self.vy=0

class mpro(Sprite):
    asset = RectangleAsset(1,1,thicklineb,black)
    def __init__(self, position):
        super().__init__(mpro.asset, position)
        self.vx=0
        self.vy=0
    def step(self):
        self.x += 0
        self.y += 0

class fpro(Sprite):
    asset = RectangleAsset(1,1,thickliner,black)
    def __init__(self, position):
        super().__init__(fpro.asset, position)
        self.vx=0
        self.vy=0
    def step(self):
        self.x += 0
        self.y += 0

class triathlon(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        mpro((0,0))
        fpro((0,0))
        start((100,0))
        finish((500,0))
    def step(self):
        for mp in self.getSpritesbyClass(mpro):
            mp.step()
        for fp in self.getSpritesbyClass(fpro):
            fp.step()

myapp = triathlon(1000,750)
myapp.run()
<|endoftext|>


<commit_before>import datetime
import logging
import mail_settings
import xlsxwriter
import StringIO

from flask import Flask
from flask import jsonify
from flask import request

from google.appengine.api import mail
from google.appengine.ext import ndb

import model
import report_generator

app = Flask(__name__)
app.config['DEBUG'] = True

REQUIRED_ANSWER_JSON_KEYS = ['username', 'csrf_token', 'test_flavor']

class Badness(Exception):
  def __init__(self, message):
    logging.error('raising error: %s', message)
    self.message = message

class BadJsonPost(Badness):
  pass

class NoTestInProgress(Badness):
  def __init__(self):
    Badness.__init__(self, 'No test currently in progress')

@app.errorhandler(Badness)
def handle_invalid_data(error):
  response = jsonify({'error': error.message})
  response.status_code = 400
  return response

@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.', 404

@app.route('/test/start', methods=['POST'])
def start():
  user, posted_json = validate_json(['test_flavor'])
  flavor = posted_json['test_flavor']
  key = ndb.Key(model.TestResult, flavor, parent=user.key)
  test_result = key.get()
  if not test_result:
    model.TestResult(id=flavor, parent=user.key, flavor=flavor).put()
  else:
    # TODO: should this be an error? Support resuming a test?
    logging.error('Started a test that already existed? %d', posted_json)
  return jsonify(message='ok')

def GetTestResult(user_key):
  test_results = model.TestResult.query(ancestor=user_key).fetch()
  for test_result in test_results:
    return test_result
  raise NoTestInProgress()

@app.route('/test/finish', methods=['POST'])
def finish():
  user, posted_json = validate_json(['test_flavor'])
  flavor = posted_json['test_flavor']
  key = ndb.Key(model.TestResult, flavor, parent=user.key)
  test_result = key.get()

  if not test_result:
    error = 'No test currently in progress'
    logging.error(error)
    response = jsonify({'error': error})
    response.status_code = 400
    return response

  test_result.time_finished = datetime.datetime.now()
  test_result.put()
  MailTestResult(user, test_result)
  return jsonify(message='ok')

def MailTestResult(user, test_result):
  src = mail_settings.EMAIL_SOURCE
  dest = mail_settings.EMAIL_DESTINATION
  subject = mail_settings.SUBJECT + ' ' + str(user.name) + ' test ' + test_result.flavor
  #xls_title, xls_attachment = GenerateExcelFile(test_result)
  mail.send_mail(
      sender=src, to=dest, subject=subject,
      body='Only HTML is supported, sorry.',
      html=report_generator.GetUserReport(user, [test_result]))
  #    attachments=[(xls_title, xls_attachment)])

def GenerateExcelFile(test_result):
  title = 'papt.xlsx'
  output = StringIO.StringIO()
  workbook = xlsxwriter.Workbook(output)
  worksheet = workbook.add_worksheet()
  workbook.close()

  output.seek(0)
  return (title, output.read())

@app.route('/test/answer', methods=['POST'])
def answer():
  user, posted_json = validate_json(['expected', 'answer', 'test_flavor'])
  flavor = posted_json['test_flavor']

  key = ndb.Key(model.TestResult, flavor, parent=user.key)
  test_result = key.get()
  if not test_result:
    raise NoTestInProgress()

  answer = model.TestAnswer(
      user=user.key,
      expected=posted_json['expected'],
      got=posted_json['answer'],
      test_flavor=flavor)
  logging.info('Saving answer %(answer)s (flavor=%(test_flavor)s)', posted_json)

  test_result.answers.append(answer)
  test_result.put()
  return jsonify(message='ok', done=test_result.AllWordsAnswered())

def validate_json(extra_required_keys=None):
  posted_json = request.get_json()
  if not posted_json:
    raise BadJsonPost('no json sent')

  for key in REQUIRED_ANSWER_JSON_KEYS + (extra_required_keys or []):
    if key not in posted_json:
      raise BadJsonPost('bad json post: "%s" not present in %s' % (key, posted_json))

  user = model.User.get_by_id(posted_json['username'])
  if not user:
    raise BadJsonPost('unknown user %s' % posted_json['username'])
  if user.csrf_token.token != posted_json['csrf_token']:
    # TODO: check the csrf token generation date
    raise BadJsonPost('bad csrf token for user %s' % posted_json['username'])
  return user, posted_json
<commit_msg>send to admins<commit_after>import datetime
import logging
import mail_settings
import xlsxwriter
import StringIO

from flask import Flask
from flask import jsonify
from flask import request

from google.appengine.api import mail
from google.appengine.ext import ndb

import model
import report_generator

app = Flask(__name__)
app.config['DEBUG'] = True

REQUIRED_ANSWER_JSON_KEYS = ['username', 'csrf_token', 'test_flavor']

class Badness(Exception):
  def __init__(self, message):
    logging.error('raising error: %s', message)
    self.message = message

class BadJsonPost(Badness):
  pass

class NoTestInProgress(Badness):
  def __init__(self):
    Badness.__init__(self, 'No test currently in progress')

@app.errorhandler(Badness)
def handle_invalid_data(error):
  response = jsonify({'error': error.message})
  response.status_code = 400
  return response

@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.', 404

@app.route('/test/start', methods=['POST'])
def start():
  user, posted_json = validate_json(['test_flavor'])
  flavor = posted_json['test_flavor']
  key = ndb.Key(model.TestResult, flavor, parent=user.key)
  test_result = key.get()
  if not test_result:
    model.TestResult(id=flavor, parent=user.key, flavor=flavor).put()
  else:
    # TODO: should this be an error? Support resuming a test?
    logging.error('Started a test that already existed? %d', posted_json)
  return jsonify(message='ok')

def GetTestResult(user_key):
  test_results = model.TestResult.query(ancestor=user_key).fetch()
  for test_result in test_results:
    return test_result
  raise NoTestInProgress()

@app.route('/test/finish', methods=['POST'])
def finish():
  user, posted_json = validate_json(['test_flavor'])
  flavor = posted_json['test_flavor']
  key = ndb.Key(model.TestResult, flavor, parent=user.key)
  test_result = key.get()

  if not test_result:
    error = 'No test currently in progress'
    logging.error(error)
    response = jsonify({'error': error})
    response.status_code = 400
    return response

  test_result.time_finished = datetime.datetime.now()
  test_result.put()
  MailTestResult(user, test_result)
  return jsonify(message='ok')

def MailTestResult(user, test_result):
  src = mail_settings.EMAIL_SOURCE
  subject = mail_settings.SUBJECT + ' ' + str(user.name) + ' test ' + test_result.flavor
  #xls_title, xls_attachment = GenerateExcelFile(test_result)
  mail.send_mail_to_admins(
      sender=src, subject=subject,
      body='Only HTML is supported, sorry.',
      html=report_generator.GetUserReport(user, [test_result]))
  #    attachments=[(xls_title, xls_attachment)])

def GenerateExcelFile(test_result):
  title = 'papt.xlsx'
  output = StringIO.StringIO()
  workbook = xlsxwriter.Workbook(output)
  worksheet = workbook.add_worksheet()
  workbook.close()

  output.seek(0)
  return (title, output.read())

@app.route('/test/answer', methods=['POST'])
def answer():
  user, posted_json = validate_json(['expected', 'answer', 'test_flavor'])
  flavor = posted_json['test_flavor']

  key = ndb.Key(model.TestResult, flavor, parent=user.key)
  test_result = key.get()
  if not test_result:
    raise NoTestInProgress()

  answer = model.TestAnswer(
      user=user.key,
      expected=posted_json['expected'],
      got=posted_json['answer'],
      test_flavor=flavor)
  logging.info('Saving answer %(answer)s (flavor=%(test_flavor)s)', posted_json)

  test_result.answers.append(answer)
  test_result.put()
  return jsonify(message='ok', done=test_result.AllWordsAnswered())

def validate_json(extra_required_keys=None):
  posted_json = request.get_json()
  if not posted_json:
    raise BadJsonPost('no json sent')

  for key in REQUIRED_ANSWER_JSON_KEYS + (extra_required_keys or []):
    if key not in posted_json:
      raise BadJsonPost('bad json post: "%s" not present in %s' % (key, posted_json))

  user = model.User.get_by_id(posted_json['username'])
  if not user:
    raise BadJsonPost('unknown user %s' % posted_json['username'])
  if user.csrf_token.token != posted_json['csrf_token']:
    # TODO: check the csrf token generation date
    raise BadJsonPost('bad csrf token for user %s' % posted_json['username'])
  return user, posted_json
<|endoftext|>


<commit_before>"""
COMAOPtriathlon.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random

"""
sl=int(input("Length of swim (in kilometers)"))
bl=int(input("Length of bike (in kilometers)"))
rl=int(input("Length of run (in kilometers)"))
fprostart=int(input("Time female pros start (in minutes after male pro start)"))
mprestart=int(input("Time male premiere start (in minutes after male pro start)"))
fprestart=int(input("Time female premiere start (in minutes after male pro start)"))
mopenstart=int(input("Time male open start (in minutes after male pro start)"))
fopenstart=int(input("Time female open start (in minutes after male pro start)"))
clystart=int(input("Time Clydsedale start (in minutes after male pro start)"))
athstart=int(input("Time Athena start (in minutes after male pro start)"))
"""
#average swim speeds
mpros=0.114213198
fpros=0.1156812339
mpres=0.09
fpres=0.08806262231
mops=0.06517016655
fops=0.06603081438
cyls=0.05851755527
aths=0.0640569395
#average t1 times
mprot1=3.266666667
fprot1=3.633333333
mpret1=4.4
fpret1=4.95
mopt1=8.033333333
fopt1=10.33333333
cylt1=8.05
atht1=11.63333333
#average bike speeds
mprob=0.6434316354
fprob=0.591424347
mpreb=0.582807188
fpreb=0.5244755245
mopb=0.4643064423
fopb=0.4010025063
cylb=0.4531722054
athb=0.3670285976
#average t2 times
mprot2=0.85
fprot2=0.9166666667
mpret2=1.25
fpret2=1.433333333
mopt2=3.116666667
fopt2=3.816666667
cylt2=3.466666667
atht2=4.516666667
#average run speeds
mpror=0.2830188679
fpror=0.2609830361
mprer=0.251572327
fprer=0.2265861027
mopr=0.1635322976
fopr=0.124403898
cylr=0.1401541696
athr=0.1291433491

# colors
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class start(Sprite):
    asset = RectangleAsset(.5,500,thinline,black)
    def __init__(self, position):
        super().__init__(start.asset, position)
        self.vx=0

class finish(Sprite):
    asset = RectangleAsset(.5,500,thinline,black)
    def __init__(self, position):
        super().__init__(finish.asset, position)
        self.vx=0

class mpro(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(0)
        self.p=1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p == 1:
            self.x += mpros
            if self.x >= 55+(945/51.5)*1.5:
                self.p = 0
        if self.p == 2:
            self.x += mprob
            if self.x >= 55 + (945/51.5) + (945/51.5)*41.5:
                self. p = 0
        if self.p == 4:
            self.x += mpror
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        elif self.p == 0 and self.a == 2:
            self.x += 0
            self.a = 3
            self.t= time.time()
        if time.time() >= self.t + mprot1 and self.p == 0 and self.a == 1:
                self.p = 2
                self.a = 2
        if time.time() >= self.t + mprot2 and self.p == 0 and self.a == 3:
                self.p = 4
                self.a = 4

class fpro(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(1)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p == 1:
            self.x += fpros
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0:
            self.x += 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + fprot1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += fprob

class mpre(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(2)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p == 1:
            self.x += mpres
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0:
            self.x += 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + mpret1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += mpreb

class fpre(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(3)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += fpres
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + fpret1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += fpreb

class mop(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(4)
        self.p = 1
        self.t= time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += mops
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + mopt1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += mopb

class fop(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(5)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += fops
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + fopt1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += fopb

class cyl(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(6)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += cyls
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + cylt1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += cylb

class ath(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(7)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += aths
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + atht1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += athb

class triathlon(App):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,55,50), 8, 'horizontal')
    def __init__(self, width, height):
        super().__init__(width, height)
        mpro((0,0))
        fpro((0,50))
        mpre((0,100))
        fpre((0,150))
        mop((0,200))
        fop((0,250))
        cyl((0,300))
        ath((0,350))
        start((55,0))
        finish((999,0))
    def step(self):
        for mp in self.getSpritesbyClass(mpro):
            mp.step()
        for fp in self.getSpritesbyClass(fpro):
            fp.step()
        for mpr in self.getSpritesbyClass(mpre):
            mpr.step()
        for fpr in self.getSpritesbyClass(fpre):
            fpr.step()
        for mo in self.getSpritesbyClass(mop):
            mo.step()
        for fo in self.getSpritesbyClass(fop):
            fo.step()
        for c in self.getSpritesbyClass(cyl):
            c.step()
        for a in self.getSpritesbyClass(ath):
            a.step()
myapp = triathlon(1000,1000)
myapp.run()
<commit_msg>Updated from Brython Server: 11/10/2016 11:42:39 AM<commit_after>"""
COMAOPtriathlon.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random

"""
sl=int(input("Length of swim (in kilometers)"))
bl=int(input("Length of bike (in kilometers)"))
rl=int(input("Length of run (in kilometers)"))
fprostart=int(input("Time female pros start (in minutes after male pro start)"))
mprestart=int(input("Time male premiere start (in minutes after male pro start)"))
fprestart=int(input("Time female premiere start (in minutes after male pro start)"))
mopenstart=int(input("Time male open start (in minutes after male pro start)"))
fopenstart=int(input("Time female open start (in minutes after male pro start)"))
clystart=int(input("Time Clydsedale start (in minutes after male pro start)"))
athstart=int(input("Time Athena start (in minutes after male pro start)"))
"""
#average swim speeds
mpros=0.114213198
fpros=0.1156812339
mpres=0.09
fpres=0.08806262231
mops=0.06517016655
fops=0.06603081438
cyls=0.05851755527
aths=0.0640569395
#average t1 times
mprot1=3.266666667
fprot1=3.633333333
mpret1=4.4
fpret1=4.95
mopt1=8.033333333
fopt1=10.33333333
cylt1=8.05
atht1=11.63333333
#average bike speeds
mprob=0.6434316354
fprob=0.591424347
mpreb=0.582807188
fpreb=0.5244755245
mopb=0.4643064423
fopb=0.4010025063
cylb=0.4531722054
athb=0.3670285976
#average t2 times
mprot2=0.85
fprot2=0.9166666667
mpret2=1.25
fpret2=1.433333333
mopt2=3.116666667
fopt2=3.816666667
cylt2=3.466666667
atht2=4.516666667
#average run speeds
mpror=0.2830188679
fpror=0.2609830361
mprer=0.251572327
fprer=0.2265861027
mopr=0.1635322976
fopr=0.124403898
cylr=0.1401541696
athr=0.1291433491

# colors
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class start(Sprite):
    asset = RectangleAsset(.5,500,thinline,black)
    def __init__(self, position):
        super().__init__(start.asset, position)
        self.vx=0

class finish(Sprite):
    asset = RectangleAsset(.5,500,thinline,black)
    def __init__(self, position):
        super().__init__(finish.asset, position)
        self.vx=0

class mpro(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(0)
        self.p=1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p == 1:
            self.x += mpros
            if self.x >= 55+(945/51.5)*1.5:
                self.p = 0
        if self.p == 2:
            self.x += mprob
            if self.x >= 55 + (945/51.5) + (945/51.5)*41.5:
                self. p = 0
        if self.p == 4:
            self.x += mpror
            if self.x >= 55 + (945/51.1)*51.5:
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        elif self.p == 0 and self.a == 2:
            self.x += 0
            self.a = 3
            self.t= time.time()
        elif self.p == 0 and self.a = 4:
            self.x += 0
        if time.time() >= self.t + mprot1 and self.p == 0 and self.a == 1:
                self.p = 2
                self.a = 2
        if time.time() >= self.t + mprot2 and self.p == 0 and self.a == 3:
                self.p = 4
                self.a = 4

class fpro(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(1)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p == 1:
            self.x += fpros
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0:
            self.x += 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + fprot1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += fprob

class mpre(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(2)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p == 1:
            self.x += mpres
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0:
            self.x += 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + mpret1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += mpreb

class fpre(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(3)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += fpres
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + fpret1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += fpreb

class mop(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(4)
        self.p = 1
        self.t= time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += mops
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + mopt1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += mopb

class fop(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(5)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += fops
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + fopt1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += fopb

class cyl(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(6)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += cyls
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + cylt1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += cylb

class ath(Sprite):
    def __init__(self, position):
        super().__init__(triathlon.asset, position)
        self.setImage(7)
        self.p = 1
        self.t = time.time()
        self.a = 0
    def step(self):
        if self.p==1:
            self.x += aths
            if self.x >= 55+(945/51.5):
                self.p = 0
        if self.p == 0 and self.a == 0:
            self.x += 0
            self.a = 1
            self.t = time.time()
        if time.time() >= self.t + atht1 and self.p == 0 and self.a == 1:
                self.p = 2
        if self.p == 2:
            self.x += athb

class triathlon(App):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,55,50), 8, 'horizontal')
    def __init__(self, width, height):
        super().__init__(width, height)
        mpro((0,0))
        fpro((0,50))
        mpre((0,100))
        fpre((0,150))
        mop((0,200))
        fop((0,250))
        cyl((0,300))
        ath((0,350))
        start((55,0))
        finish((999,0))
    def step(self):
        for mp in self.getSpritesbyClass(mpro):
            mp.step()
        for fp in self.getSpritesbyClass(fpro):
            fp.step()
        for mpr in self.getSpritesbyClass(mpre):
            mpr.step()
        for fpr in self.getSpritesbyClass(fpre):
            fpr.step()
        for mo in self.getSpritesbyClass(mop):
            mo.step()
        for fo in self.getSpritesbyClass(fop):
            fo.step()
        for c in self.getSpritesbyClass(cyl):
            c.step()
        for a in self.getSpritesbyClass(ath):
            a.step()
myapp = triathlon(1000,1000)
myapp.run()
<|endoftext|>


<commit_before>## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
## Use of this source code is governed by a BSD-style license that can be
## found in the COPYING file.

"""
  This is a simple python script to test the autogenerated module

"""
import os
import sys
import time

path = `os.environ.get("AL_DIR")`
home = `os.environ.get("HOME")`

#Checking AL_DIR
if path == "None":
        print "the environnement variable AL_DIR is not set, aborting..."
        sys.exit(1)
else:
        alPath = path + "/extern/python/aldebaran"
        alPath = alPath.replace("~", home)
        alPath = alPath.replace("'", "")
        sys.path.append(alPath)
# import NaoQi lib

        import naoqi
        from naoqi import ALBroker
        from naoqi import ALModule
        from naoqi import ALProxy
        from naoqi import ALBehavior

# Put here IP and Port of a broker containg ALLaser
IP="127.0.0.1"
PORT=9559

#________________________________
# Generic Proxy creation
#________________________________
def main():
    print '        START TESTING ALLaser MODULE'
    try:
        ALLaser_Proxy = ALProxy("ALLaser",IP,PORT)
    except Exception,e:
        print "Error when creating ALLaser  proxy:"
        print str(e)
        return(1)
    #________________________________
    # Remote procedure call
    #________________________________
    inParam = ["test", 1, 45, [123, 456, "789"]]

    try:
        ret = ALLaser_Proxy.DummyFunction( "hello, world", inParam )
    except Exception,e:
        print "ALLaser test Failed"
        return(1)

    print 'Returned Value : '
    print(ret)
    if (ret == inParam):
        print 'Success, the return value is correct'
        print '            ALLaser MODULE TESTED'
        print ''
        return(0)
    else:
        print 'Failed, the return value is incorrect'
        print '            ALLaser MODULE TESTED'
        print ''
        return(1)

if __name__ == "__main__":
  exit (main())

<commit_msg>Remove unused python test<commit_after><|endoftext|>


<commit_before>import unittest

from flatten_json import flatten, unflatten, unflatten_list
from util import check_if_numbers_are_consecutive

class UnitTests(unittest.TestCase):
    def test_numbers_consecutive(self):
        """Checks if all numbers in a list are consecutive integers"""
        list_ = [1, 2, 3, 4, 5]
        actual = check_if_numbers_are_consecutive(list_)
        self.assertTrue(actual)

        list_ = [0, 1, 5]
        actual = check_if_numbers_are_consecutive(list_)
        self.assertFalse(actual)

        list_ = [1.0, 2.0, 3.0]
        actual = check_if_numbers_are_consecutive(list_)
        self.assertTrue(actual)

        list_ = range(10)
        actual = check_if_numbers_are_consecutive(list_)
        self.assertTrue(actual)

        list_ = range(10, 0, -1)
        actual = check_if_numbers_are_consecutive(list_)
        self.assertFalse(actual)

    def test_no_flatten(self):
        dic = {'a': '1', 'b': '2', 'c': 3}
        expected = dic
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_one_flatten(self):
        dic = {'a': '1',
               'b': '2',
               'c': {'c1': '3', 'c2': '4'}
               }
        expected = {'a': '1', 'b': '2', 'c_c1': '3', 'c_c2': '4'}
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_custom_separator(self):
        dic = {'a': '1',
               'b': '2',
               'c': {'c1': '3', 'c2': '4'}
               }
        expected = {'a': '1', 'b': '2', 'c*c1': '3', 'c*c2': '4'}
        actual = flatten(dic, '*')
        self.assertEqual(actual, expected)

    def test_list(self):
        dic = {
            'a': 1,
            'b': [{'c': [2, 3]}]
        }
        expected = {'a': 1, 'b_0_c_0': 2, 'b_0_c_1': 3}
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_list_and_dict(self):
        dic = {
            'a': 1,
            'b': 2,
            'c': [{'d': [2, 3, 4], 'e': [{'f': 1, 'g': 2}]}]
        }
        expected = {'a': 1, 'b': 2, 'c_0_d_0': 2, 'c_0_d_1': 3, 'c_0_d_2': 4, 'c_0_e_0_f': 1, 'c_0_e_0_g': 2}
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_blog_example(self):
        dic = {
            "a": 1,
            "b": 2,
            "c": [{"d": ['2', 3, 4], "e": [{"f": 1, "g": 2}]}]
        }
        expected = {'a': 1, 'b': 2, 'c_0_d_0': '2', 'c_0_d_1': 3, 'c_0_d_2': 4, 'c_0_e_0_f': 1,
                    'c_0_e_0_g': 2}
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_unflatten_no_list(self):
        dic = {
            'a': 1,
            'b_a': 2,
            'b_b': 3,
            'c_a_b': 5
        }
        expected = {
            'a': 1,
            'b': {'a': 2, 'b': 3},
            'c': {'a': {'b': 5}}
        }
        actual = unflatten(dic)
        self.assertEqual(actual, expected)

    def test_unflatten_with_list(self):
        """Dictionary with lists"""
        dic = {
            'a': 1,
            'b_0': 1,
            'b_1': 2,
            'c_a': 'a',
            'c_b_0': 1,
            'c_b_1': 2,
            'c_b_2': 3
        }
        expected = {
            'a': 1,
            'b': [1, 2],
            'c': {'a': 'a', 'b': [1, 2, 3]}
        }
        actual = unflatten_list(dic)
        self.assertEqual(actual, expected)

        dic = {'a': 1, 'b_0': 5}
        expected = {'a': 1, 'b': [5]}
        actual = unflatten_list(dic)
        self.assertEqual(actual, expected)

        dic = {'a': 1, 'b:0': 5}
        expected = {'a': 1, 'b': [5]}
        actual = unflatten_list(dic, ':')
        self.assertEqual(actual, expected)

    def test_unflatten_with_list_custom_separator(self):
        """Complex dictionary with lists"""
        self.maxDiff = None
        dic = {
            'a:b': 'str0',
            'c:0:d:0:e': 'str1',
            'c:1:d:0:e': 'str4',
            'c:1:f': 'str5',
            'c:0:f': 'str2',
            'c:1:g': 'str6',
            'c:0:g': 'str3',
            'h:d:0:e': 'str7',
            'h:i:0:f': 'str8',
            'h:i:0:g': 'str9'
        }
        expected = {
            'a': {'b': 'str0'},
            'c': [
                {
                    'd': [{'e': 'str1'}],
                    'f': 'str2',
                    'g': 'str3'
                }, {
                    'd': [{'e': 'str4'}],
                    'f': 'str5',
                    'g': 'str6'
                }
            ],
            'h': {
                'd': [{'e': 'str7'}],
                'i': [{'f': 'str8', 'g': 'str9'}]
            }
        }
        actual = unflatten_list(dic, ':')
        self.assertEqual(actual, expected)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Removed maxDiff from the test case<commit_after>import unittest

from flatten_json import flatten, unflatten, unflatten_list
from util import check_if_numbers_are_consecutive

class UnitTests(unittest.TestCase):
    def test_numbers_consecutive(self):
        """Checks if all numbers in a list are consecutive integers"""
        list_ = [1, 2, 3, 4, 5]
        actual = check_if_numbers_are_consecutive(list_)
        self.assertTrue(actual)

        list_ = [0, 1, 5]
        actual = check_if_numbers_are_consecutive(list_)
        self.assertFalse(actual)

        list_ = [1.0, 2.0, 3.0]
        actual = check_if_numbers_are_consecutive(list_)
        self.assertTrue(actual)

        list_ = range(10)
        actual = check_if_numbers_are_consecutive(list_)
        self.assertTrue(actual)

        list_ = range(10, 0, -1)
        actual = check_if_numbers_are_consecutive(list_)
        self.assertFalse(actual)

    def test_no_flatten(self):
        dic = {'a': '1', 'b': '2', 'c': 3}
        expected = dic
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_one_flatten(self):
        dic = {'a': '1',
               'b': '2',
               'c': {'c1': '3', 'c2': '4'}
               }
        expected = {'a': '1', 'b': '2', 'c_c1': '3', 'c_c2': '4'}
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_custom_separator(self):
        dic = {'a': '1',
               'b': '2',
               'c': {'c1': '3', 'c2': '4'}
               }
        expected = {'a': '1', 'b': '2', 'c*c1': '3', 'c*c2': '4'}
        actual = flatten(dic, '*')
        self.assertEqual(actual, expected)

    def test_list(self):
        dic = {
            'a': 1,
            'b': [{'c': [2, 3]}]
        }
        expected = {'a': 1, 'b_0_c_0': 2, 'b_0_c_1': 3}
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_list_and_dict(self):
        dic = {
            'a': 1,
            'b': 2,
            'c': [{'d': [2, 3, 4], 'e': [{'f': 1, 'g': 2}]}]
        }
        expected = {'a': 1, 'b': 2, 'c_0_d_0': 2, 'c_0_d_1': 3, 'c_0_d_2': 4, 'c_0_e_0_f': 1, 'c_0_e_0_g': 2}
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_blog_example(self):
        dic = {
            "a": 1,
            "b": 2,
            "c": [{"d": ['2', 3, 4], "e": [{"f": 1, "g": 2}]}]
        }
        expected = {'a': 1, 'b': 2, 'c_0_d_0': '2', 'c_0_d_1': 3, 'c_0_d_2': 4, 'c_0_e_0_f': 1,
                    'c_0_e_0_g': 2}
        actual = flatten(dic)
        self.assertEqual(actual, expected)

    def test_unflatten_no_list(self):
        dic = {
            'a': 1,
            'b_a': 2,
            'b_b': 3,
            'c_a_b': 5
        }
        expected = {
            'a': 1,
            'b': {'a': 2, 'b': 3},
            'c': {'a': {'b': 5}}
        }
        actual = unflatten(dic)
        self.assertEqual(actual, expected)

    def test_unflatten_with_list(self):
        """Dictionary with lists"""
        dic = {
            'a': 1,
            'b_0': 1,
            'b_1': 2,
            'c_a': 'a',
            'c_b_0': 1,
            'c_b_1': 2,
            'c_b_2': 3
        }
        expected = {
            'a': 1,
            'b': [1, 2],
            'c': {'a': 'a', 'b': [1, 2, 3]}
        }
        actual = unflatten_list(dic)
        self.assertEqual(actual, expected)

        dic = {'a': 1, 'b_0': 5}
        expected = {'a': 1, 'b': [5]}
        actual = unflatten_list(dic)
        self.assertEqual(actual, expected)

        dic = {'a': 1, 'b:0': 5}
        expected = {'a': 1, 'b': [5]}
        actual = unflatten_list(dic, ':')
        self.assertEqual(actual, expected)

    def test_unflatten_with_list_custom_separator(self):
        """Complex dictionary with lists"""
        dic = {
            'a:b': 'str0',
            'c:0:d:0:e': 'str1',
            'c:1:d:0:e': 'str4',
            'c:1:f': 'str5',
            'c:0:f': 'str2',
            'c:1:g': 'str6',
            'c:0:g': 'str3',
            'h:d:0:e': 'str7',
            'h:i:0:f': 'str8',
            'h:i:0:g': 'str9'
        }
        expected = {
            'a': {'b': 'str0'},
            'c': [
                {
                    'd': [{'e': 'str1'}],
                    'f': 'str2',
                    'g': 'str3'
                }, {
                    'd': [{'e': 'str4'}],
                    'f': 'str5',
                    'g': 'str6'
                }
            ],
            'h': {
                'd': [{'e': 'str7'}],
                'i': [{'f': 'str8', 'g': 'str9'}]
            }
        }
        actual = unflatten_list(dic, ':')
        self.assertEqual(actual, expected)

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


<commit_before>import copy
import logging
import unittest

import httpretty

from fulcrum import Fulcrum
from fulcrum.api import APIConfig
from fulcrum.exceptions import NotFoundException, InvalidAPIVersionException, InvalidObjectException, InternalServerErrorException

key = 'super_secret_key'
api_root = 'https://api.fulcrumapp.com/api/v2'
valid_form = {
    'form': {
        'name': 'whatever',
        'elements': [
            {
                'key': 'abc',
                'label': 'Name',
                'data_name': 'name'
            },
            {
                'key': '123',
                'label': 'Description',
                'data_name': 'description'
            }
        ]
    }
}

class APIConfigTest(unittest.TestCase):
    def test_invalid_version(self):
        try:
            APIConfig(key='foo', version=99)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidAPIVersionException)

class FormTest(unittest.TestCase):
    def setUp(self):
        self.fulcrum_api = Fulcrum(key=key)

    @httpretty.activate
    def test_all(self):
        httpretty.register_uri(httpretty.GET, api_root + '/forms',
            body='{"forms": [{"id": 1},{"id": 2}], "total_count": 2, "current_page": 1, "total_pages": 1, "per_page": 20000}',
            status=200)

        forms = self.fulcrum_api.form.all()
        self.assertIsInstance(forms, dict)
        self.assertEqual(len(forms['forms']), 2)

    @httpretty.activate
    def test_find(self):
        httpretty.register_uri(httpretty.GET, api_root + '/forms/5b656cd8-f3ef-43e9-8d22-84d015052778',
            body='{"record_count": 4, "description": "Food Carts and Trucks in Denver", "id": "5b656cd8-f3ef-43e9-8d22-84d015052778"}',
            status=200)
        form = self.fulcrum_api.form.find('5b656cd8-f3ef-43e9-8d22-84d015052778')
        self.assertIsInstance(form, dict)
        self.assertEqual(form['id'], '5b656cd8-f3ef-43e9-8d22-84d015052778')

    @httpretty.activate
    def test_find_not_found(self):
        httpretty.register_uri(httpretty.GET, api_root + '/forms/lobster', status=404)
        try:
            self.fulcrum_api.form.find('lobster')
        except Exception as exc:
            self.assertIsInstance(exc, NotFoundException)

    @httpretty.activate
    def test_delete(self):
        httpretty.register_uri(httpretty.DELETE, api_root + '/forms/5b656cd8-f3ef-43e9-8d22-84d015052778', status=200)
        self.fulcrum_api.form.delete('5b656cd8-f3ef-43e9-8d22-84d015052778')

    @httpretty.activate
    def test_create_500(self):
        httpretty.register_uri(httpretty.POST, api_root + '/forms', status=500)
        try:
            self.fulcrum_api.form.create(valid_form)
        except Exception as exc:
            self.assertIsInstance(exc, InternalServerErrorException)

    def test_create_no_form(self):
        try:
            self.fulcrum_api.form.create({'cats': True})
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'form must exist and not be empty.')

    def test_create_invalid_name(self):
        a_form = copy.deepcopy(valid_form)
        a_form['form']['name'] = ''
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'form name must exist and not be empty.')

    def test_create_invalid_elements(self):
        try:
            self.fulcrum_api.form.create({'form': {'name': 'cats', 'elements': []}})
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'form elements must exist and not be empty.')

    def test_create_no_name_no_elements(self):
        a_form = copy.deepcopy(valid_form)
        del a_form['form']['name']
        del a_form['form']['elements']
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertTrue(str(exc) == 'form elements must exist and not be empty. form name must exist and not be empty.' or str(exc) == 'form name must exist and not be empty. form elements must exist and not be empty.')

    def test_create_bad_element(self):
        a_form = copy.deepcopy(valid_form)
        a_form['form']['elements'][0] = {}
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertTrue(str(exc) == 'elements element must be of type dict and not be empty.')

    def test_element_no_key(self):
        a_form = copy.deepcopy(valid_form)
        del a_form['form']['elements'][0]['key']
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'element key must exist and not be empty.')

    def test_element_duplicate_key(self):
        a_form = copy.deepcopy(valid_form)
        a_form['form']['elements'][1]['key'] = a_form['form']['elements'][0]['key']
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'abc key must be unique.')

    @httpretty.activate
    def test_create_valid(self):
        httpretty.register_uri(httpretty.POST, api_root + '/forms',
            body='{"form": {"id": 1}}',
            status=200)
        form = self.fulcrum_api.form.create(valid_form)
        self.assertIsInstance(form, dict)
        self.assertTrue(form['form']['id'] == 1)

    @httpretty.activate
    def test_update(self):
        httpretty.register_uri(httpretty.PUT, api_root + '/forms/abc-123',
            body='{"form": {"id": "abc-123"}}',
            status=200)
        form = self.fulcrum_api.form.update('abc-123', valid_form)
        self.assertIsInstance(form, dict)
        self.assertTrue(form['form']['id'] == 'abc-123')

    def test_update_no_name(self):
        a_form = copy.deepcopy(valid_form)
        del a_form['form']['name']
        a_form['form']['id'] = 'abc-123'
        try:
            self.fulcrum_api.form.update('abc-123', a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'form name must exist and not be empty.')

class RecordTest(unittest.TestCase):
    valid_record = {
        'record': {
            'latitude': 40.678,
            'longitude': -100.567,
            'form_id': 'abc-123',
            'form_values': {
                'height': 34,
                'bathrooms': 2.5,
            }
        }
    }

    def setUp(self):
        self.fulcrum_api = Fulcrum(key=key)

    def test_record_missing_record(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record must exist and not be empty.')

    def test_missing_latitude(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']['latitude']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record latitude must exist and be of type int or float.')

    def test_missing_longitude(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']['longitude']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record longitude must exist and be of type int or float.')

    def test_missing_form_id(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']['form_id']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record form_id must exist and be of type str.')

    def test_missing_form_values(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']['form_values']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record form_values must exist and be of type dict.')

    def test_missing_form_values_empty_dict(self):
        a_record = copy.deepcopy(self.valid_record)
        a_record['record']['form_values'] = {}
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record form_values must exist and be of type dict and not be empty.')

    @httpretty.activate
    def test_records_from_form_via_url_params(self):
        httpretty.register_uri(httpretty.GET, api_root + '/records?form_id=abc-123',
            body='{"records": [{"id": 1},{"id": 2}], "total_count": 2, "current_page": 1, "total_pages": 1, "per_page": 20000}',
            status=200)

        records = self.fulcrum_api.record.all(params={'form_id': 'abc-123'})
        self.assertIsInstance(records, dict)
        self.assertEqual(len(records['records']), 2)
<commit_msg>Cover missing data_name<commit_after>import copy
import logging
import unittest

import httpretty

from fulcrum import Fulcrum
from fulcrum.api import APIConfig
from fulcrum.exceptions import NotFoundException, InvalidAPIVersionException, InvalidObjectException, InternalServerErrorException

key = 'super_secret_key'
api_root = 'https://api.fulcrumapp.com/api/v2'
valid_form = {
    'form': {
        'name': 'whatever',
        'elements': [
            {
                'key': 'abc',
                'label': 'Name',
                'data_name': 'name'
            },
            {
                'key': '123',
                'label': 'Description',
                'data_name': 'description'
            }
        ]
    }
}

class APIConfigTest(unittest.TestCase):
    def test_invalid_version(self):
        try:
            APIConfig(key='foo', version=99)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidAPIVersionException)

class FormTest(unittest.TestCase):
    def setUp(self):
        self.fulcrum_api = Fulcrum(key=key)

    @httpretty.activate
    def test_all(self):
        httpretty.register_uri(httpretty.GET, api_root + '/forms',
            body='{"forms": [{"id": 1},{"id": 2}], "total_count": 2, "current_page": 1, "total_pages": 1, "per_page": 20000}',
            status=200)

        forms = self.fulcrum_api.form.all()
        self.assertIsInstance(forms, dict)
        self.assertEqual(len(forms['forms']), 2)

    @httpretty.activate
    def test_find(self):
        httpretty.register_uri(httpretty.GET, api_root + '/forms/5b656cd8-f3ef-43e9-8d22-84d015052778',
            body='{"record_count": 4, "description": "Food Carts and Trucks in Denver", "id": "5b656cd8-f3ef-43e9-8d22-84d015052778"}',
            status=200)
        form = self.fulcrum_api.form.find('5b656cd8-f3ef-43e9-8d22-84d015052778')
        self.assertIsInstance(form, dict)
        self.assertEqual(form['id'], '5b656cd8-f3ef-43e9-8d22-84d015052778')

    @httpretty.activate
    def test_find_not_found(self):
        httpretty.register_uri(httpretty.GET, api_root + '/forms/lobster', status=404)
        try:
            self.fulcrum_api.form.find('lobster')
        except Exception as exc:
            self.assertIsInstance(exc, NotFoundException)

    @httpretty.activate
    def test_delete(self):
        httpretty.register_uri(httpretty.DELETE, api_root + '/forms/5b656cd8-f3ef-43e9-8d22-84d015052778', status=200)
        self.fulcrum_api.form.delete('5b656cd8-f3ef-43e9-8d22-84d015052778')

    @httpretty.activate
    def test_create_500(self):
        httpretty.register_uri(httpretty.POST, api_root + '/forms', status=500)
        try:
            self.fulcrum_api.form.create(valid_form)
        except Exception as exc:
            self.assertIsInstance(exc, InternalServerErrorException)

    def test_create_no_form(self):
        try:
            self.fulcrum_api.form.create({'cats': True})
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'form must exist and not be empty.')

    def test_create_invalid_name(self):
        a_form = copy.deepcopy(valid_form)
        a_form['form']['name'] = ''
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'form name must exist and not be empty.')

    def test_create_invalid_elements(self):
        try:
            self.fulcrum_api.form.create({'form': {'name': 'cats', 'elements': []}})
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'form elements must exist and not be empty.')

    def test_create_no_name_no_elements(self):
        a_form = copy.deepcopy(valid_form)
        del a_form['form']['name']
        del a_form['form']['elements']
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertTrue(str(exc) == 'form elements must exist and not be empty. form name must exist and not be empty.' or str(exc) == 'form name must exist and not be empty. form elements must exist and not be empty.')

    def test_create_bad_element(self):
        a_form = copy.deepcopy(valid_form)
        a_form['form']['elements'][0] = {}
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertTrue(str(exc) == 'elements element must be of type dict and not be empty.')

    def test_create_element_missing_data_name(self):
        a_form = copy.deepcopy(valid_form)
        del a_form['form']['elements'][0]['data_name']
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertTrue(str(exc) == 'abc data_name is required.')

    def test_element_no_key(self):
        a_form = copy.deepcopy(valid_form)
        del a_form['form']['elements'][0]['key']
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'element key must exist and not be empty.')

    def test_element_duplicate_key(self):
        a_form = copy.deepcopy(valid_form)
        a_form['form']['elements'][1]['key'] = a_form['form']['elements'][0]['key']
        try:
            self.fulcrum_api.form.create(a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'abc key must be unique.')

    @httpretty.activate
    def test_create_valid(self):
        httpretty.register_uri(httpretty.POST, api_root + '/forms',
            body='{"form": {"id": 1}}',
            status=200)
        form = self.fulcrum_api.form.create(valid_form)
        self.assertIsInstance(form, dict)
        self.assertTrue(form['form']['id'] == 1)

    @httpretty.activate
    def test_update(self):
        httpretty.register_uri(httpretty.PUT, api_root + '/forms/abc-123',
            body='{"form": {"id": "abc-123"}}',
            status=200)
        form = self.fulcrum_api.form.update('abc-123', valid_form)
        self.assertIsInstance(form, dict)
        self.assertTrue(form['form']['id'] == 'abc-123')

    def test_update_no_name(self):
        a_form = copy.deepcopy(valid_form)
        del a_form['form']['name']
        a_form['form']['id'] = 'abc-123'
        try:
            self.fulcrum_api.form.update('abc-123', a_form)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'form name must exist and not be empty.')

class RecordTest(unittest.TestCase):
    valid_record = {
        'record': {
            'latitude': 40.678,
            'longitude': -100.567,
            'form_id': 'abc-123',
            'form_values': {
                'height': 34,
                'bathrooms': 2.5,
            }
        }
    }

    def setUp(self):
        self.fulcrum_api = Fulcrum(key=key)

    def test_record_missing_record(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record must exist and not be empty.')

    def test_missing_latitude(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']['latitude']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record latitude must exist and be of type int or float.')

    def test_missing_longitude(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']['longitude']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record longitude must exist and be of type int or float.')

    def test_missing_form_id(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']['form_id']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record form_id must exist and be of type str.')

    def test_missing_form_values(self):
        a_record = copy.deepcopy(self.valid_record)
        del a_record['record']['form_values']
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record form_values must exist and be of type dict.')

    def test_missing_form_values_empty_dict(self):
        a_record = copy.deepcopy(self.valid_record)
        a_record['record']['form_values'] = {}
        try:
            self.fulcrum_api.record.create(a_record)
        except Exception as exc:
            self.assertIsInstance(exc, InvalidObjectException)
            self.assertEqual(str(exc), 'record form_values must exist and be of type dict and not be empty.')

    @httpretty.activate
    def test_records_from_form_via_url_params(self):
        httpretty.register_uri(httpretty.GET, api_root + '/records?form_id=abc-123',
            body='{"records": [{"id": 1},{"id": 2}], "total_count": 2, "current_page": 1, "total_pages": 1, "per_page": 20000}',
            status=200)

        records = self.fulcrum_api.record.all(params={'form_id': 'abc-123'})
        self.assertIsInstance(records, dict)
        self.assertEqual(len(records['records']), 2)
<|endoftext|>


<commit_before>import logging

from rllab.envs.normalized_env import normalize
from rllab.misc.instrument import stub, run_experiment_lite
from rllab.algos.trpo import TRPO
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline
from rllab.policies.gaussian_mlp_policy import GaussianMLPPolicy

# from cistar.core.exp import SumoExperiment
from cistar.envs.loop_accel import SimpleAccelerationEnvironment
from cistar.scenarios.loop.loop_scenario import LoopScenario
from cistar.controllers.rlcontroller import RLController
from cistar.controllers.lane_change_controllers import *

logging.basicConfig(level=logging.INFO)

stub(globals())

sumo_params = {"port": 8877, "time_step":0.01}
sumo_binary = "sumo"

env_params = {"target_velocity": 20, "max-deacc": -3, "max-acc": 3, "fail-safe": 'instantaneous'}

net_params = {"length": 230, "lanes": 1, "speed_limit": 35, "resolution": 40,
              "net_path": "debug/rl/net/"}

cfg_params = {"start_time": 0, "end_time": 3000, "cfg_path": "debug/rl/cfg/"}

initial_config = {"shuffle": False}

num_cars = 1

exp_tag = str(num_cars) + '-car-rl'

type_params = {"rl":(num_cars, (RLController, {}), (StaticLaneChanger, {}), 0)}

scenario = LoopScenario(exp_tag, type_params, net_params, cfg_params, initial_config=initial_config)

env = SimpleAccelerationEnvironment(env_params, sumo_binary, sumo_params, scenario)

env = normalize(env)

for seed in [15]:
    policy = GaussianMLPPolicy(
        env_spec=env.spec,
        hidden_sizes=(16,)
    )

    baseline = LinearFeatureBaseline(env_spec=env.spec)

    algo = TRPO(
        env=env,
        policy=policy,
        baseline=baseline,
        batch_size=300,
        max_path_length=1500,
        n_itr=750,  # 1000
        # whole_paths=True,
        # discount=0.99,
        # step_size=0.01,
    )
    # algo.train()

    run_experiment_lite(
        algo.train(),
        # Number of parallel workers for sampling
        n_parallel=1,
        # Only keep the snapshot parameters for the last iteration
        snapshot_mode="all",
        # Specifies the seed for the experiment. If this is not provided, a random seed
        # will be used
        seed=seed,
        mode="local",
        #mode="ec2",
        exp_prefix=exp_tag
        # plot=True,
    )
<commit_msg>fixed batch size. Batch size over max_path_length is the number of rollout<commit_after>import logging

from rllab.envs.normalized_env import normalize
from rllab.misc.instrument import stub, run_experiment_lite
from rllab.algos.trpo import TRPO
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline
from rllab.policies.gaussian_mlp_policy import GaussianMLPPolicy

# from cistar.core.exp import SumoExperiment
from cistar.envs.loop_accel import SimpleAccelerationEnvironment
from cistar.scenarios.loop.loop_scenario import LoopScenario
from cistar.controllers.rlcontroller import RLController
from cistar.controllers.lane_change_controllers import *

logging.basicConfig(level=logging.INFO)

stub(globals())

sumo_params = {"port": 8820, "time_step":0.01}
sumo_binary = "sumo"

env_params = {"target_velocity": 20, "max-deacc": -3, "max-acc": 3, "fail-safe": 'instantaneous'}

net_params = {"length": 230, "lanes": 1, "speed_limit": 35, "resolution": 40,
              "net_path": "debug/rl/net/"}

cfg_params = {"start_time": 0, "end_time": 3000, "cfg_path": "debug/rl/cfg/"}

initial_config = {"shuffle": False}

num_cars = 1

exp_tag = str(num_cars) + '-car-rl-longrun16x16'

type_params = {"rl":(num_cars, (RLController, {}), (StaticLaneChanger, {}), 0)}

scenario = LoopScenario(exp_tag, type_params, net_params, cfg_params, initial_config=initial_config)

env = SimpleAccelerationEnvironment(env_params, sumo_binary, sumo_params, scenario)

env = normalize(env)

for seed in [15]:
    policy = GaussianMLPPolicy(
        env_spec=env.spec,
        hidden_sizes=(32,32)
    )

    baseline = LinearFeatureBaseline(env_spec=env.spec)

    algo = TRPO(
        env=env,
        policy=policy,
        baseline=baseline,
        batch_size=8000,
        max_path_length=1000,
        n_itr=40,  # 1000
        # whole_paths=True,
        discount=0.999,
        step_size=0.01,
    )
    # algo.train()

    run_experiment_lite(
        algo.train(),
        # Number of parallel workers for sampling
        n_parallel=1,
        # Only keep the snapshot parameters for the last iteration
        snapshot_mode="all",
        # Specifies the seed for the experiment. If this is not provided, a random seed
        # will be used
        seed=seed,
        mode="local",
        #mode="ec2",
        exp_prefix=exp_tag
        # plot=True,
    )
<|endoftext|>


<commit_before>"""
Unit or integration tests for gpustat
"""

import unittest
import gpustat

# mock output for test
def _mock_check_output(cmd, shell=True):
    if cmd.startswith('nvidia-smi --query-compute-apps'):
        return '''\
GPU-10fb0fbd-2696-43f3-467f-d280d906a107, 48448, 4000
GPU-10fb0fbd-2696-43f3-467f-d280d906a107, 153223, 4000
GPU-d1df4664-bb44-189c-7ad0-ab86c8cb30e2, 192453, 3000
GPU-d1df4664-bb44-189c-7ad0-ab86c8cb30e2, 194826, 6000
GPU-50205d95-57b6-f541-2bcb-86c09afed564, 38310, 4245
GPU-50205d95-57b6-f541-2bcb-86c09afed564, [Not Supported], [Not Supported]
'''
    elif cmd.startswith('nvidia-smi --query-gpu'):
        return '''\
0, GPU-10fb0fbd-2696-43f3-467f-d280d906a107, GeForce GTX TITAN X, 80, 76, 8000, 12287
1, GPU-d1df4664-bb44-189c-7ad0-ab86c8cb30e2, GeForce GTX TITAN X, 36, 0, 9000, 12287
2, GPU-50205d95-57b6-f541-2bcb-86c09afed564, GeForce GTX TITAN X, 71, [Not Supported], 8520, 12287
'''
    elif cmd.startswith('ps -o pid,user,comm -p'):
        return '''\
   PID USER  COMMAND
 48448 user1 python
154213 user1 caffe
 38310 user3 python
153223 user2 python
194826 user3 caffe
192453 user1 torch
'''
    else:
        raise ValueError(cmd)

# mocking (override subprocess.check_output)
gpustat.check_output = _mock_check_output

class TestGPUStat(unittest.TestCase):

    def test_new_query_mocked(self):
        gpustats = gpustat.new_query()
        gpustats.print_formatted(no_color=False, show_user=True, show_cmd=True, show_pid=True)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Fix failing tests, and improve the testcase<commit_after>"""
Unit or integration tests for gpustat
"""

from __future__ import print_function
import sys

import unittest
import gpustat
from cStringIO import StringIO

# mock output for test
def _mock_check_output(cmd, shell=True):
    if cmd.startswith('nvidia-smi --query-compute-apps'):
        return '''\
GPU-10fb0fbd-2696-43f3-467f-d280d906a107, 48448, 4000
GPU-10fb0fbd-2696-43f3-467f-d280d906a107, 153223, 4000
GPU-d1df4664-bb44-189c-7ad0-ab86c8cb30e2, 192453, 3000
GPU-d1df4664-bb44-189c-7ad0-ab86c8cb30e2, 194826, 6000
GPU-50205d95-57b6-f541-2bcb-86c09afed564, 38310, 4245
GPU-50205d95-57b6-f541-2bcb-86c09afed564, [Not Supported], [Not Supported]
'''
    elif cmd.startswith('nvidia-smi --query-gpu'):
        return '''\
0, GPU-10fb0fbd-2696-43f3-467f-d280d906a107, GeForce GTX TITAN X, 80, 76, 8000, 12287
1, GPU-d1df4664-bb44-189c-7ad0-ab86c8cb30e2, GeForce GTX TITAN X, 36, 0, 9000, 12287
2, GPU-50205d95-57b6-f541-2bcb-86c09afed564, GeForce GTX TITAN X, 71, [Not Supported], 8520, 12287
'''
    elif cmd.startswith('ps -o pid,user:16,comm -p'):
        return '''\
   PID USER  COMMAND
 48448 user1 python
154213 user1 caffe
 38310 user3 python
153223 user2 python
194826 user3 caffe
192453 user1 torch
'''
    else:
        raise ValueError(cmd)

# mocking (override subprocess.check_output)
gpustat.check_output = _mock_check_output

def remove_ansi_codes(s):
    import re
    ansi_escape = re.compile(r'\x1b[^m]*m')
    return ansi_escape.sub('', s)

class TestGPUStat(unittest.TestCase):

    def test_new_query_mocked(self):
        gpustats = gpustat.new_query()
        fp = StringIO()
        gpustats.print_formatted(fp=fp, no_color=False, show_user=True, show_cmd=True, show_pid=True)

        result = fp.getvalue()
        print(result)

        unescaped = remove_ansi_codes(result)
        self.assertEqual(unescaped,
"""\
[0] GeForce GTX TITAN X | 80'C,  76 % |  8000 / 12287 MB | user1:python/48448(4000M) user2:python/153223(4000M)
[1] GeForce GTX TITAN X | 36'C,   0 % |  9000 / 12287 MB | user1:torch/192453(3000M) user3:caffe/194826(6000M)
[2] GeForce GTX TITAN X | 71'C,  ?? % |  8520 / 12287 MB | user3:python/38310(4245M) --:--/--(?M)
""")
        #"""

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