<commit_before>"""
conway.py
Author: Dimitri
Credit: Morgan
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life
"""
"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle, MouseEvent

black = Color(0x000000, 1)
nostroke = LineStyle(0, black)
alivecells = {}
makecells = []
surcells = []
killcells = {}
xdiff = 0
ydiff = 0

def create():
    for celle in makecells[:]:
        Cell((celle[0], celle[1]))
        makecells.remove(celle)

def getcoor(xx, yy):
    return([[xx - 10, yy - 10], [xx - 10, yy], [xx - 10, yy + 10], [xx, yy - 10], [xx, yy + 10], [xx + 10, yy - 10], [xx + 10, yy], [xx + 10, yy + 10]])

def check():
    for celle in surcells[:]:
        if find(celle[0], celle[1]) == 3:
            makecells.append(celle)
        surcells.remove(celle)

def checking(xx, yy):
    dei = getcoor(xx, yy)
    for deadcell in dei:
        if alivecells.get((deadcell[0], deadcell[1]), False) == False:
            if deadcell in surcells:
                at = 1
            else:
                surcells.append(deadcell)

def find(xx, yy):
    neighbors = getcoor(xx, yy)
    neighborcount = 0
    for posi in neighbors:
        if alivecells.get((posi[0], posi[1]), False) == True:
            neighborcount += 1
    return(neighborcount)

class Cell(Sprite):
    pix = RectangleAsset(10, 10, nostroke, black)

    def __init__(self, position):
        super().__init__(Cell.pix, position)
        self.ogposx = self.x
        self.ogposy = self.y
        alivecells[(self.ogposx, self.ogposy)] = True
        self.x += xdiff
        self.y += ydiff
        self.day = 0
        self.changed = False

    def step(self):
        if alivecells.get((self.ogposx, self.ogposy)) == True:
            self.day += 1
            if self.day > 1 and self.changed == False:
                self.color = colortwo
                self.changed = True
            n = find(self.ogposx, self.ogposy)
            if n < 2 or n > 3:
                killcells[(self.ogposx, self.ogposy)] = True
            checking(self.ogposx, self.ogposy)
        else:
            self.visible = False

    def kill(self):
        if killcells.get((self.ogposx, self.ogposy), False) == True:
            alivecells[(self.ogposx, self.ogposy)] = False
            killcells[(self.ogposx, self.ogposy)] = False

    def mover(self, direction):
        if direction == "r":
            self.x += 20
        elif direction == "l":
            self.x -= 20
        elif direction == "u":
            self.y -= 20
        elif direction == "d":
            self.y += 20

    def checktokill(self, px, py):
        if px == self.ogposx and py == self.ogposy:
            self.visible = False
            killcells[(self.ogposx, self.ogposy)] = True
            self.kill()

class Conway(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        self.stopped = True
        Cell((100, 50))
        Cell((110, 60))
        Cell((110, 70))
        Cell((100, 70))
        Cell((90, 70))
        self.listenKeyEvent("keydown", "right arrow", self.moveright)
        self.listenKeyEvent("keydown", "left arrow", self.moveleft)
        self.listenKeyEvent("keydown", "up arrow", self.moveup)
        self.listenKeyEvent("keydown", "down arrow", self.movedown)
        self.listenKeyEvent("keydown", "space", self.toggle)
        self.listenMouseEvent('click', self.create)

    def moveright(self, event):
        xdiff += 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("r")
    def moveleft(self, event):
        xdiff -= 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("l")
    def moveup(self, event):
        ydiff -= 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("u")
    def movedown(self, event):
        ydiff += 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("d")
    def toggle(self, event):
        if self.stopped == True:
            self.stopped = False
        else:
            self.stopped = True

    def create(self, event):
        diffx = event.x % 10
        diffy = event.y % 10
        finx = event.x - diffx - 10 - xdiff
        finy = event.y - diffy - 10 - ydiff
        if alivecells.get((finx, finy), False) == True:
            for cell in self.getSpritesbyClass(Cell):
                cell.checktokill(finx, finy)
        else:
            Cell((finx, finy))

    def step(self):
        if self.stopped == False:
            create()
            for cell in self.getSpritesbyClass(Cell):
                cell.kill()
            for cell in self.getSpritesbyClass(Cell):
                cell.step()
            check()

myapp = Conway(640, 480)
myapp.run()
"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle, MouseEvent

black = Color(0, 1)
white = Color(0xffffff, 1)
noline = LineStyle(0, white)
livecells = []
deadcells = []
addcells = []
surcells = []
mortalcells = []

def neighborlist(x1, y1):
    return([[x1-10, y1-10], [x1-10, y1], [x1-10, y1+10], [x1, y1-10], [x1, y1+10], [x1+10, y1-10], [x1+10, y1], [x1+10, y1+10]])

def getneighborssur():
    for pos in surcells:
        if newneighbors(pos[0], pos[1]) == 3:
            print("new")
            addcells.append(pos)
            surcells.remove(pos)

def newneighbors(x1, y1):
    neighbors = neighborlist(x1, y1)
    counted = 0
    for outsidecells in neighbors:
        if [outsidecells[0], outsidecells[1]] in livecells:
            counted += 1
    return(counted)

def getneighbors(x1, y1):
    neighbors = neighborlist(x1, y1)
    counted = 0
    for outsidecells in neighbors:
        if [outsidecells[0], outsidecells[1]] in livecells:
            counted += 1
        else:
            surcells.append(outsidecells)
    return(counted)

def createcells():
    for newcells in addcells:
        #print(newcells[0], newcells[1])
        Cell((newcells[0], newcells[1]))
        addcells.remove(newcells)

def revive():
    for nextcells in surcells:
        #print(getneighborssur(nextcells[0], nextcells[1]))
        if getneighborssur(nextcells[0], nextcells[1]) == 3:
            addcells.append(nextcells)
        surcells.remove(nextcells)

def kill():
    for thecell in mortalcells:
        deadcells.append(thecell)
        livecells.remove(thecell)
        mortalcells.remove(thecell)

class Cell(Sprite):
    asset = RectangleAsset(10, 10, noline, black)

    def __init__(self, position):
        super().__init__(Cell.asset, position)
        livecells.append([self.x, self.y])
        generation = 0

    def step(self):
        if [self.x, self.y] in livecells:
            neighbor = getneighbors(self.x, self.y)
            print(neighbor)
            if neighbor < 2 or neighbor > 3:
                self.visible = False
                mortalcells.append([self.x, self.y])
                print("dead")
            elif [self.x, self.y] in mortalcells:
                mortalcells.remove([self.x, self.y])
        else:
            if neighbors == 3 and [self.x, self.y] in deadcells:
                self.visible = True
                deadcells.pop(deadcells.index([self.x, self.y]))
                livecells.append([self.x, self.y])

class Conways(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        #self.stopped = True
        Cell((100, 100))
        Cell((100, 90))
        Cell((100, 80))

    def step(self):
        print(livecells, "b", deadcells, "b", addcells, "b", surcells, "b", mortalcells)
        kill()
        countir = 0
        for cell in self.getSpritesbyClass(Cell):
            countir += 1
            cell.step()
            print("hi")
        getneighborssur()
        createcells()
        print(countir)

myapp = Conways(640, 480)
myapp.run()
<commit_msg>Updated from Brython Server: January 15, 2016 8:41:22 PM EST<commit_after>"""
conway.py
Author: Dimitri
Credit: Morgan
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life
"""
"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle, MouseEvent

black = Color(0x000000, 1)
nostroke = LineStyle(0, black)
alivecells = {}
makecells = []
surcells = []
killcells = {}
xdiff = 0
ydiff = 0

def create():
    for celle in makecells[:]:
        Cell((celle[0], celle[1]))
        makecells.remove(celle)

def getcoor(xx, yy):
    return([[xx - 10, yy - 10], [xx - 10, yy], [xx - 10, yy + 10], [xx, yy - 10], [xx, yy + 10], [xx + 10, yy - 10], [xx + 10, yy], [xx + 10, yy + 10]])

def check():
    for celle in surcells[:]:
        if find(celle[0], celle[1]) == 3:
            makecells.append(celle)
        surcells.remove(celle)

def checking(xx, yy):
    dei = getcoor(xx, yy)
    for deadcell in dei:
        if alivecells.get((deadcell[0], deadcell[1]), False) == False:
            if deadcell in surcells:
                at = 1
            else:
                surcells.append(deadcell)

def find(xx, yy):
    neighbors = getcoor(xx, yy)
    neighborcount = 0
    for posi in neighbors:
        if alivecells.get((posi[0], posi[1]), False) == True:
            neighborcount += 1
    return(neighborcount)

class Cell(Sprite):
    pix = RectangleAsset(10, 10, nostroke, black)

    def __init__(self, position):
        super().__init__(Cell.pix, position)
        self.ogposx = self.x
        self.ogposy = self.y
        alivecells[(self.ogposx, self.ogposy)] = True
        self.x += xdiff
        self.y += ydiff
        self.day = 0
        self.changed = False

    def step(self):
        if alivecells.get((self.ogposx, self.ogposy)) == True:
            self.day += 1
            if self.day > 1 and self.changed == False:
                self.color = colortwo
                self.changed = True
            n = find(self.ogposx, self.ogposy)
            if n < 2 or n > 3:
                killcells[(self.ogposx, self.ogposy)] = True
            checking(self.ogposx, self.ogposy)
        else:
            self.visible = False

    def kill(self):
        if killcells.get((self.ogposx, self.ogposy), False) == True:
            alivecells[(self.ogposx, self.ogposy)] = False
            killcells[(self.ogposx, self.ogposy)] = False

    def mover(self, direction):
        if direction == "r":
            self.x += 20
        elif direction == "l":
            self.x -= 20
        elif direction == "u":
            self.y -= 20
        elif direction == "d":
            self.y += 20

    def checktokill(self, px, py):
        if px == self.ogposx and py == self.ogposy:
            self.visible = False
            killcells[(self.ogposx, self.ogposy)] = True
            self.kill()

class Conway(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        self.stopped = True
        Cell((100, 50))
        Cell((110, 60))
        Cell((110, 70))
        Cell((100, 70))
        Cell((90, 70))
        self.listenKeyEvent("keydown", "right arrow", self.moveright)
        self.listenKeyEvent("keydown", "left arrow", self.moveleft)
        self.listenKeyEvent("keydown", "up arrow", self.moveup)
        self.listenKeyEvent("keydown", "down arrow", self.movedown)
        self.listenKeyEvent("keydown", "space", self.toggle)
        self.listenMouseEvent('click', self.create)

    def moveright(self, event):
        xdiff += 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("r")
    def moveleft(self, event):
        xdiff -= 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("l")
    def moveup(self, event):
        ydiff -= 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("u")
    def movedown(self, event):
        ydiff += 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("d")
    def toggle(self, event):
        if self.stopped == True:
            self.stopped = False
        else:
            self.stopped = True

    def create(self, event):
        diffx = event.x % 10
        diffy = event.y % 10
        finx = event.x - diffx - 10 - xdiff
        finy = event.y - diffy - 10 - ydiff
        if alivecells.get((finx, finy), False) == True:
            for cell in self.getSpritesbyClass(Cell):
                cell.checktokill(finx, finy)
        else:
            Cell((finx, finy))

    def step(self):
        if self.stopped == False:
            create()
            for cell in self.getSpritesbyClass(Cell):
                cell.kill()
            for cell in self.getSpritesbyClass(Cell):
                cell.step()
            check()

myapp = Conway(640, 480)
myapp.run()
"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle, MouseEvent

black = Color(0, 1)
white = Color(0xffffff, 1)
noline = LineStyle(0, white)
livecells = []
deadcells = []
addcells = []
surcells = []
mortalcells = []

def neighborlist(x1, y1):
    return([[x1-10, y1-10], [x1-10, y1], [x1-10, y1+10], [x1, y1-10], [x1, y1+10], [x1+10, y1-10], [x1+10, y1], [x1+10, y1+10]])

def getneighborssur():
    for pos in surcells:
        if newneighbors(pos[0], pos[1]) == 3:
            addcells.append(pos)

def newneighbors(x1, y1):
    neighbors2 = neighborlist(x1, y1)
    #print(neighbors2)
    counted2 = 0
    for outsidecells2 in neighbors2:
        if [outsidecells2[0], outsidecells2[1]] in livecells:
            counted2 += 1
    return(counted2)

def getneighbors(x1, y1):
    neighbors = neighborlist(x1, y1)
    counted = 0
    for outsidecells in neighbors:
        if [outsidecells[0], outsidecells[1]] in livecells:
            counted += 1
        else:
            surcells.append(outsidecells)
    return(counted)

def createcells():
    for newcells in addcells:
        #print(newcells[0], newcells[1])
        Cell((newcells[0], newcells[1]))

def kill():
    for thecell in mortalcells:
        deadcells.append(thecell)
        livecells.remove(thecell)

class Cell(Sprite):
    asset = RectangleAsset(10, 10, noline, black)

    def __init__(self, position):
        super().__init__(Cell.asset, position)
        livecells.append([self.x, self.y])
        generation = 0

    def step(self):
        if [self.x, self.y] in livecells:
            neighbor = getneighbors(self.x, self.y)
            print(neighbor)
            if neighbor < 2 or neighbor > 3:
                self.visible = False
                mortalcells.append([self.x, self.y])
                print("dead")
           # elif [self.x, self.y] in mortalcells:
               # mortalcells.remove([self.x, self.y])
        """else:
            if neighbors == 3 and [self.x, self.y] in deadcells:
                self.visible = True
                deadcells.pop(deadcells.index([self.x, self.y]))
                livecells.append([self.x, self.y])"""

class Conways(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        #self.stopped = True
        Cell((100, 100))
        Cell((100, 90))
        Cell((100, 80))

    def step(self):
        #print(addcells)
        countir = 0
        for cell in self.getSpritesbyClass(Cell):
            countir += 1
            cell.step()
            print("hi")
        #print(surcells)
        getneighborssur()
        surcells = []
        createcells()
        addcells = []
        kill()
        mortalcells = []
        print(countir)

myapp = Conways(640, 480)
myapp.run()
<|endoftext|>


<commit_before>###
# Test script for new WikiPathways webservice API
# author: msk (mkutmon@gmail.com)
###

import requests
from lxml import etree as ET

# define namespaces
namespaces = {'ns1':'http://www.wso2.org/php/xs','ns2':'http://www.wikipathways.org/webservice'}

# list organisms
r = requests.get('http://test2.wikipathways.org/wpi/webservicetest/?method=listOrganisms&format=xml')
dom = ET.fromstring(r.text)

# print each organism
for node in dom:
	print node.text
<commit_msg>updated list organism file<commit_after>###
# Test script for new WikiPathways webservice API
# author: msk (mkutmon@gmail.com)
###

import httplib2
from lxml import etree as ET

# define namespaces
namespaces = {'ns1':'http://www.wso2.org/php/xs','ns2':'http://www.wikipathways.org/webservice'}

# list organisms
h = httplib2.Http()
(resp_headers, content) = h.request("http://test2.wikipathways.org/wpi/webservicetest/webservice.php/listOrganisms", "GET")

dom = ET.fromstring(content)

# print each organism
for node in dom:
	print node.text

<|endoftext|>


<commit_before>##########################################################################
#
#  Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
#     * Neither the name of Image Engine Design nor the names of any
#       other contributors to this software may be used to endorse or
#       promote products derived from this software without specific prior
#       written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
#  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
#  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################

"""Unit test for CompoundData binding"""

import os
import math
import unittest
import IECore

class CompoundDataTest(unittest.TestCase):

	def testConstructors(self):
		"""Test constructors"""
		v1 = IECore.CompoundData()
		a = dict()
		a["1"] = IECore.IntData(1)
		v3 = IECore.CompoundData(a)
		self.assertEqual(v3.size(), 1)

	def testResize(self):
		"""Test resizing"""
		v = IECore.CompoundData()
		v["0"] = IECore.FloatData(2)
		self.assertEqual(v["0"], IECore.FloatData(2))
		v["1"] = IECore.FloatData(0)
		v["2"] = IECore.FloatData(3)
		v["3"] = IECore.FloatData(2)
		v["4"] = IECore.FloatData(5)
		self.assertEqual(v["4"], IECore.FloatData(5))
		self.assertEqual(len(v), 5)
		del(v["0"])
		self.assertEqual(len(v), 4)
		self.assert_(v.has_key("0") == False)
		v.clear()
		self.assertEqual(len(v), 0)

	def testAssignment(self):
		"""Test assignment"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v2 = v1.copy()
		v3 = v1
		v4 = v1.copy()
		self.assertEqual(len(v1), 2)
		self.assertEqual(len(v1), len(v2))
		self.assertEqual(v1["0"], v2["0"])
		self.assertEqual(v1["1"], v2["1"])
		self.assertEqual(v1["0"], v4["0"])
		self.assertEqual(v1["1"], v4["1"])

	def testCopyOnWrite(self):
		"""Test copy-on-write behavior"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v2 = v1.copy()
		v3 = v1.copy()
		v3["0"] = IECore.UIntData(5)
		self.assert_(v3["0"] == IECore.UIntData(5))
		self.assert_(v2["0"] == IECore.FloatData(1.2))
		v1["2"] = IECore.FloatData(5);
		self.assertEqual(len(v1), 3)
		self.assertEqual(len(v2), 2)

	def testSearch(self):
		"""Test search functions"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		self.assert_("0" in v1)
		self.assert_("3" not in v1)
		self.assert_(v1.has_key("1"))
		self.assert_(not v1.has_key("3"))
		self.assert_(v1.get("0") == IECore.FloatData(1.2))
		self.assert_(v1.get("0", IECore.IntData(10)) == IECore.FloatData(1.2))
		self.assert_(v1.get("xx", IECore.IntData(10)) == IECore.IntData(10))
		self.assertEqual(len(v1), 3)

	def testUpdate(self):
		"""Test update function"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v2 = IECore.CompoundData()
		v2["0"] = IECore.UIntData(5)
		v2["3"] = IECore.UIntData(6)
		v2.update(v1)
		self.assertEqual(len(v2), 4)
		self.assert_(v2["0"] == IECore.FloatData(1.2))
		self.assert_(v2["3"] == IECore.UIntData(6))
		v3 = dict()
		v3["1"] = IECore.CharData("a")
		v3["4"] = IECore.UCharData(9)
		v2.update(v3)
		self.assertEqual(len(v2), 5)
		self.assert_(v2["1"] == IECore.CharData("a"))
		self.assert_(v2["4"] == IECore.UCharData(9))

	def testSetDefault(self):
		"""Test setdefault function"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v2 = v1.copy()
		self.assertEqual(len(v1), 3)
		self.assert_(v1.setdefault("2", IECore.UIntData(10)) == IECore.FloatData(3))
		self.assertEqual(len(v1), 3)
		self.assert_(v1.setdefault("x", IECore.UIntData(10)) == IECore.UIntData(10))
		self.assertEqual(len(v1), 4)

	def testPop(self):
		"""Test pop functions"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v1["3"] = IECore.FloatData(4)
		self.assertEqual(len(v1), 4)
		prev = v1.popitem()
		self.assertEqual(len(v1), 3)
		self.assert_(prev == ('0', IECore.FloatData(1.2)))
		self.assert_(v1.pop("x", IECore.UIntData(10)) == IECore.UIntData(10))
		self.assert_(v1.pop("3", IECore.UIntData(10)) == IECore.FloatData(4))
		self.assertEqual(len(v1), 2)

	def testKeyValues(self):
		"""Test keys/values listing"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		self.assert_(v1.keys() == ['0', '1', '2'])
		vals = v1.values()
		self.assert_(vals == [IECore.FloatData(1.2), IECore.FloatData(2.3), IECore.FloatData(3)])
		items = v1.items()
		self.assert_(items == [('0', IECore.FloatData(1.2)), ('1', IECore.FloatData(2.3)), ('2', IECore.FloatData(3))])

	def testEquality(self):
		"""Test equality function"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v2 = IECore.CompoundData()
		v2["0"] = IECore.FloatData(1.2)
		v2["1"] = IECore.FloatData(2.3)
		v2["2"] = IECore.FloatData(3)
		v3 = v2.copy()
		del v3["2"]
		self.assert_(v1 == v2)
		self.assert_(not v1 != v2)
		self.assert_(not v1 == v3)
		self.assert_(not v2 == v3)
		v2["-1"] = IECore.FloatData(6)
		self.assert_(v1 != v2)
		self.assert_(not v1 == v2)
		del(v1["2"])
		self.assert_(v1 == v3)

	def testByValueItem(self):
		"""Test by value return type"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		self.assert_(v1["0"] == IECore.FloatData(1.2))
		a = v1["0"]
		a = IECore.UIntData(255)
		self.assert_(v1["0"] == IECore.FloatData(1.2))
		self.assert_(a == IECore.UIntData(255))

	def testLoadSave(self):
		"""Test load/save"""

		iface = IECore.IndexedIOInterface.create( "test/CompoundData.fio", "/", IECore.IndexedIOOpenMode.Write )

		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v1["some:data"] = IECore.FloatData(3)
		self.assert_(v1["0"] == IECore.FloatData(1.2))

		v1.save( iface, "test" )

		v2 = IECore.Object.load( iface, "test" )
		self.assertEqual( v1, v2 )

	def testRepr(self):
		"""Test repr"""

		v1 = IECore.CompoundData()

		r1 = repr(v1)

		self.assertEqual( eval(repr(v1)), v1 )

		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)

		self.assertEqual( eval(repr(v1)), v1 )

		v1 = IECore.CompoundData()
		v1["0"] = IECore.StringData( "test" )
		v1["1"] = IECore.CompoundData(
			{ "0" : IECore.StringData( "test" ),
			  "1" : IECore.M33fData()
			}
		)
		v1["someMoreData"] = IECore.V3fVectorData()
		v1["A"] = IECore.Color4fVectorData()

		self.assertEqual( eval(repr(v1)), v1 )

	def tearDown(self):

		if os.path.isfile("./test/CompoundData.fio") :
			os.remove("./test/CompoundData.fio")

if __name__ == "__main__":
    unittest.main()

<commit_msg>Test now accounts for the fact that CompoundData is unsorted<commit_after>##########################################################################
#
#  Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
#     * Neither the name of Image Engine Design nor the names of any
#       other contributors to this software may be used to endorse or
#       promote products derived from this software without specific prior
#       written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
#  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
#  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################

"""Unit test for CompoundData binding"""

import os
import math
import unittest
import IECore

class CompoundDataTest(unittest.TestCase):

	def testConstructors(self):
		"""Test constructors"""
		v1 = IECore.CompoundData()
		a = dict()
		a["1"] = IECore.IntData(1)
		v3 = IECore.CompoundData(a)
		self.assertEqual(v3.size(), 1)

	def testResize(self):
		"""Test resizing"""
		v = IECore.CompoundData()
		v["0"] = IECore.FloatData(2)
		self.assertEqual(v["0"], IECore.FloatData(2))
		v["1"] = IECore.FloatData(0)
		v["2"] = IECore.FloatData(3)
		v["3"] = IECore.FloatData(2)
		v["4"] = IECore.FloatData(5)
		self.assertEqual(v["4"], IECore.FloatData(5))
		self.assertEqual(len(v), 5)
		del(v["0"])
		self.assertEqual(len(v), 4)
		self.assert_(v.has_key("0") == False)
		v.clear()
		self.assertEqual(len(v), 0)

	def testAssignment(self):
		"""Test assignment"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v2 = v1.copy()
		v3 = v1
		v4 = v1.copy()
		self.assertEqual(len(v1), 2)
		self.assertEqual(len(v1), len(v2))
		self.assertEqual(v1["0"], v2["0"])
		self.assertEqual(v1["1"], v2["1"])
		self.assertEqual(v1["0"], v4["0"])
		self.assertEqual(v1["1"], v4["1"])

	def testCopyOnWrite(self):
		"""Test copy-on-write behavior"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v2 = v1.copy()
		v3 = v1.copy()
		v3["0"] = IECore.UIntData(5)
		self.assert_(v3["0"] == IECore.UIntData(5))
		self.assert_(v2["0"] == IECore.FloatData(1.2))
		v1["2"] = IECore.FloatData(5);
		self.assertEqual(len(v1), 3)
		self.assertEqual(len(v2), 2)

	def testSearch(self):
		"""Test search functions"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		self.assert_("0" in v1)
		self.assert_("3" not in v1)
		self.assert_(v1.has_key("1"))
		self.assert_(not v1.has_key("3"))
		self.assert_(v1.get("0") == IECore.FloatData(1.2))
		self.assert_(v1.get("0", IECore.IntData(10)) == IECore.FloatData(1.2))
		self.assert_(v1.get("xx", IECore.IntData(10)) == IECore.IntData(10))
		self.assertEqual(len(v1), 3)

	def testUpdate(self):
		"""Test update function"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v2 = IECore.CompoundData()
		v2["0"] = IECore.UIntData(5)
		v2["3"] = IECore.UIntData(6)
		v2.update(v1)
		self.assertEqual(len(v2), 4)
		self.assert_(v2["0"] == IECore.FloatData(1.2))
		self.assert_(v2["3"] == IECore.UIntData(6))
		v3 = dict()
		v3["1"] = IECore.CharData("a")
		v3["4"] = IECore.UCharData(9)
		v2.update(v3)
		self.assertEqual(len(v2), 5)
		self.assert_(v2["1"] == IECore.CharData("a"))
		self.assert_(v2["4"] == IECore.UCharData(9))

	def testSetDefault(self):
		"""Test setdefault function"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v2 = v1.copy()
		self.assertEqual(len(v1), 3)
		self.assert_(v1.setdefault("2", IECore.UIntData(10)) == IECore.FloatData(3))
		self.assertEqual(len(v1), 3)
		self.assert_(v1.setdefault("x", IECore.UIntData(10)) == IECore.UIntData(10))
		self.assertEqual(len(v1), 4)

	def testPop(self):
		"""Test pop functions"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v1["3"] = IECore.FloatData(4)
		self.assertEqual(len(v1), 4)
		prev = v1.popitem()
		self.assertEqual(len(v1), 3)

		self.assert_(v1.pop("x", IECore.UIntData(10)) == IECore.UIntData(10))
		self.assert_(v1.pop("3", IECore.UIntData(10)) == IECore.FloatData(4))
		self.assertEqual(len(v1), 2)

	def testKeyValues(self):
		"""Test keys/values listing"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1)
		v1["1"] = IECore.FloatData(2)
		v1["2"] = IECore.FloatData(3)
		self.assertEqual( set( v1.keys() ), set( ['0', '1', '2'] ) )
		vals = v1.values()
		self.assertEqual( set( [ x.value for x in vals ] ), set( [ 1, 2, 3 ] ) )
		items = v1.items()
		self.assertEqual( set( [ ( x[0], x[1].value ) for x in items ] ), set( [ ( "0", 1 ), ( "1", 2 ), ( "2", 3 ) ] ) )

	def testEquality(self):
		"""Test equality function"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v2 = IECore.CompoundData()
		v2["0"] = IECore.FloatData(1.2)
		v2["1"] = IECore.FloatData(2.3)
		v2["2"] = IECore.FloatData(3)
		v3 = v2.copy()
		del v3["2"]
		self.assert_(v1 == v2)
		self.assert_(not v1 != v2)
		self.assert_(not v1 == v3)
		self.assert_(not v2 == v3)
		v2["-1"] = IECore.FloatData(6)
		self.assert_(v1 != v2)
		self.assert_(not v1 == v2)
		del(v1["2"])
		self.assert_(v1 == v3)

	def testByValueItem(self):
		"""Test by value return type"""
		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		self.assert_(v1["0"] == IECore.FloatData(1.2))
		a = v1["0"]
		a = IECore.UIntData(255)
		self.assert_(v1["0"] == IECore.FloatData(1.2))
		self.assert_(a == IECore.UIntData(255))

	def testLoadSave(self):
		"""Test load/save"""

		iface = IECore.IndexedIOInterface.create( "test/CompoundData.fio", "/", IECore.IndexedIOOpenMode.Write )

		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)
		v1["some:data"] = IECore.FloatData(3)
		self.assert_(v1["0"] == IECore.FloatData(1.2))

		v1.save( iface, "test" )

		v2 = IECore.Object.load( iface, "test" )
		self.assertEqual( v1, v2 )

	def testRepr(self):
		"""Test repr"""

		v1 = IECore.CompoundData()

		r1 = repr(v1)

		self.assertEqual( eval(repr(v1)), v1 )

		v1 = IECore.CompoundData()
		v1["0"] = IECore.FloatData(1.2)
		v1["1"] = IECore.FloatData(2.3)
		v1["2"] = IECore.FloatData(3)

		self.assertEqual( eval(repr(v1)), v1 )

		v1 = IECore.CompoundData()
		v1["0"] = IECore.StringData( "test" )
		v1["1"] = IECore.CompoundData(
			{ "0" : IECore.StringData( "test" ),
			  "1" : IECore.M33fData()
			}
		)
		v1["someMoreData"] = IECore.V3fVectorData()
		v1["A"] = IECore.Color4fVectorData()

		self.assertEqual( eval(repr(v1)), v1 )

	def tearDown(self):

		if os.path.isfile("./test/CompoundData.fio") :
			os.remove("./test/CompoundData.fio")

if __name__ == "__main__":
    unittest.main()

<|endoftext|>


<commit_before>import os
import shutil
import subprocess

import docker
import pytest

IMAGE_NAME=os.environ["IMAGE_NAME"]

@pytest.mark.generic
def test_by_compiling(tmpdir):
    # Travis CI tests are running using user 2000, in container we have user 1000
    # we need to ensure that we can write into the tmp file
    # yes, this is insecure
    print(subprocess.call(["sudo", "chmod", "0777", str(tmpdir)]))
    tests_dir = os.path.dirname(os.path.abspath(__file__))
    helper_files_dir = os.path.join(tests_dir, "files", "compilation")
    rust_source_file = os.path.join(helper_files_dir, "main.rs")
    shutil.copy2(rust_source_file, str(tmpdir))

    d = docker.APIClient(version="auto")
    container = d.create_container(
        IMAGE_NAME,
        command="rustc ./main.rs",
        volumes=['/src'],
        host_config=d.create_host_config(
            binds={
                str(tmpdir): {
                    'bind': '/src',
                    'mode': 'rw'
                }
            }
        )
    )
    d.start(container)
    d.wait(container)
    print(d.logs(container))
    output = subprocess.check_output([os.path.join(str(tmpdir), "main")]).decode("utf-8")
    expected_output = "works\n"
    assert output == expected_output

@pytest.mark.generic
def test_cargo(tmpdir):
    # Travis CI tests are running using user 2000, in container we have user 1000
    # we need to ensure that we can write into the tmp file
    # yes, this is insecure
    print(subprocess.call(["sudo", "chmod", "0777", str(tmpdir)]))
    d = docker.APIClient(version="auto")
    container = d.create_container(
        IMAGE_NAME,
        command="sleep 99999",
        volumes=['/src'],
        host_config=d.create_host_config(
            binds={
                str(tmpdir): {
                    'bind': '/src',
                    'mode': 'rw'
                }
            }
        )
    )
    d.start(container)
    try:
        # TODO: create --bin project and run it
        exec_cargo_new = d.exec_create(container, "cargo init")
        output = d.exec_start(exec_cargo_new).decode("utf-8")
        assert "Created library project" in output
        exec_inspect = d.exec_inspect(exec_cargo_new)
        assert exec_inspect["ExitCode"] == 0

        exec_add_libc_dep = d.exec_create(container, 'bash -c \'echo libc = \\\"*\\\" >>Cargo.toml\'')
        output = d.exec_start(exec_add_libc_dep).decode("utf-8")
        exec_inspect = d.exec_inspect(exec_add_libc_dep)
        assert exec_inspect["ExitCode"] == 0

        exec_cargo_build = d.exec_create(container, "cargo build")
        output = d.exec_start(exec_cargo_build).decode("utf-8")
        assert "Finished dev [unoptimized + debuginfo] target(s) in" in output
        assert "Compiling libc" in output
        exec_inspect = d.exec_inspect(exec_cargo_build)
        assert exec_inspect["ExitCode"] == 0
    finally:
        d.kill(container)

@pytest.mark.clippy
def test_clippy(tmpdir):
    # Travis CI tests are running using user 2000, in container we have user 1000
    # we need to ensure that we can write into the tmp file
    # yes, this is insecure
    print(subprocess.call(["sudo", "chmod", "0777", str(tmpdir)]))
    tests_dir = os.path.dirname(os.path.abspath(__file__))
    helper_files_dir = os.path.join(tests_dir, "files", "clippy")
    target_dir = os.path.join(str(tmpdir), "project")
    shutil.copytree(helper_files_dir, target_dir)

    d = docker.APIClient(version="auto")
    container = d.create_container(
        IMAGE_NAME,
        command="cargo clippy",
        volumes=['/src'],
        host_config=d.create_host_config(
            binds={
                target_dir: {
                    'bind': '/src',
                    'mode': 'rw'
                }
            }
        )
    )
    d.start(container)
    d.wait(container)
    logs = d.logs(container).decode('utf-8')
    print(repr(logs))
    expected_output = (
        "   Compiling clippy-test v0.0.1 (file:///src)\n"
        "warning: you seem to be trying to use match for destructuring a single pattern. Consider using `if let`\n"
        " --> src/main.rs:3:5\n"
        "  |\n"
        "3 | /     match x {\n"
        "4 | |         Some(y) => println!(\"{:?}\", y),\n"
        "5 | |         _ => ()\n"
        "6 | |     }\n"
        "  | |_____^ help: try this `if let Some(y) = x { $ crate :: io :: _print ( format_args ! ( $ ( $ arg ) * ) ) }`\n"
        "  |\n"
        "  = note: #[warn(single_match)] on by default\n"
        "  = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#single_match"
    )
    print(repr(expected_output))
    assert expected_output in logs
    # no need to compile again
    # binary_path = os.path.join(target_dir, "target", "debug", "clippy-test")
    # output = subprocess.check_output([binary_path]).decode("utf-8")
    # expected_output = "1\n"
    # assert output == expected_output
<commit_msg>fix clippy test<commit_after>import os
import shutil
import subprocess

import docker
import pytest

IMAGE_NAME=os.environ["IMAGE_NAME"]

@pytest.mark.generic
def test_by_compiling(tmpdir):
    # Travis CI tests are running using user 2000, in container we have user 1000
    # we need to ensure that we can write into the tmp file
    # yes, this is insecure
    print(subprocess.call(["sudo", "chmod", "0777", str(tmpdir)]))
    tests_dir = os.path.dirname(os.path.abspath(__file__))
    helper_files_dir = os.path.join(tests_dir, "files", "compilation")
    rust_source_file = os.path.join(helper_files_dir, "main.rs")
    shutil.copy2(rust_source_file, str(tmpdir))

    d = docker.APIClient(version="auto")
    container = d.create_container(
        IMAGE_NAME,
        command="rustc ./main.rs",
        volumes=['/src'],
        host_config=d.create_host_config(
            binds={
                str(tmpdir): {
                    'bind': '/src',
                    'mode': 'rw'
                }
            }
        )
    )
    d.start(container)
    d.wait(container)
    print(d.logs(container))
    output = subprocess.check_output([os.path.join(str(tmpdir), "main")]).decode("utf-8")
    expected_output = "works\n"
    assert output == expected_output

@pytest.mark.generic
def test_cargo(tmpdir):
    # Travis CI tests are running using user 2000, in container we have user 1000
    # we need to ensure that we can write into the tmp file
    # yes, this is insecure
    print(subprocess.call(["sudo", "chmod", "0777", str(tmpdir)]))
    d = docker.APIClient(version="auto")
    container = d.create_container(
        IMAGE_NAME,
        command="sleep 99999",
        volumes=['/src'],
        host_config=d.create_host_config(
            binds={
                str(tmpdir): {
                    'bind': '/src',
                    'mode': 'rw'
                }
            }
        )
    )
    d.start(container)
    try:
        # TODO: create --bin project and run it
        exec_cargo_new = d.exec_create(container, "cargo init")
        output = d.exec_start(exec_cargo_new).decode("utf-8")
        assert "Created library project" in output
        exec_inspect = d.exec_inspect(exec_cargo_new)
        assert exec_inspect["ExitCode"] == 0

        exec_add_libc_dep = d.exec_create(container, 'bash -c \'echo libc = \\\"*\\\" >>Cargo.toml\'')
        output = d.exec_start(exec_add_libc_dep).decode("utf-8")
        exec_inspect = d.exec_inspect(exec_add_libc_dep)
        assert exec_inspect["ExitCode"] == 0

        exec_cargo_build = d.exec_create(container, "cargo build")
        output = d.exec_start(exec_cargo_build).decode("utf-8")
        assert "Finished dev [unoptimized + debuginfo] target(s) in" in output
        assert "Compiling libc" in output
        exec_inspect = d.exec_inspect(exec_cargo_build)
        assert exec_inspect["ExitCode"] == 0
    finally:
        d.kill(container)

@pytest.mark.clippy
def test_clippy(tmpdir):
    # Travis CI tests are running using user 2000, in container we have user 1000
    # we need to ensure that we can write into the tmp file
    # yes, this is insecure
    tests_dir = os.path.dirname(os.path.abspath(__file__))
    helper_files_dir = os.path.join(tests_dir, "files", "clippy")
    target_dir = os.path.join(str(tmpdir), "project")
    print(subprocess.call(["sudo", "chmod", "0777", target_dir]))
    shutil.copytree(helper_files_dir, target_dir)

    d = docker.APIClient(version="auto")
    container = d.create_container(
        IMAGE_NAME,
        command="cargo clippy",
        volumes=['/src'],
        host_config=d.create_host_config(
            binds={
                target_dir: {
                    'bind': '/src',
                    'mode': 'rw'
                }
            }
        )
    )
    d.start(container)
    d.wait(container)
    logs = d.logs(container).decode('utf-8')
    print(repr(logs))
    expected_output = (
        "   Compiling clippy-test v0.0.1 (file:///src)\n"
        "warning: you seem to be trying to use match for destructuring a single pattern. Consider using `if let`\n"
        " --> src/main.rs:3:5\n"
        "  |\n"
        "3 | /     match x {\n"
        "4 | |         Some(y) => println!(\"{:?}\", y),\n"
        "5 | |         _ => ()\n"
        "6 | |     }\n"
        "  | |_____^ help: try this `if let Some(y) = x { $ crate :: io :: _print ( format_args ! ( $ ( $ arg ) * ) ) }`\n"
        "  |\n"
        "  = note: #[warn(single_match)] on by default\n"
        "  = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#single_match"
    )
    print(repr(expected_output))
    assert expected_output in logs
    # no need to compile again
    # binary_path = os.path.join(target_dir, "target", "debug", "clippy-test")
    # output = subprocess.check_output([binary_path]).decode("utf-8")
    # expected_output = "1\n"
    # assert output == expected_output
<|endoftext|>


<commit_before>"""Koji builder plugin extends Koji to build containers

Acts as a wrapper between Koji and OpenShift builsystem via osbs for building
containers."""

# Copyright (C) 2015  Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
# USA

# Authors:
#       Pavol Babincak <pbabinca@redhat.com>
import os

import koji
from koji.daemon import SCM
from koji.tasks import ServerExit, BaseTaskHandler
from osbs.api import OSBS
from osbs.conf import Configuration

# We need kojid module which isn't proper python module and not even in
# site-package path.
kojid_exe_path = '/usr/sbin/kojid'
fo = file(kojid_exe_path, 'U')
try:
    kojid = imp.load_module('kojid', fo, fo.name, ('.py', 'U', 1))
finally:
    fo.close()

class ContainerError(koji.GenericError):
    """Raised when container creation fails"""
    faultCode = 2001

class CreateContainerTask(BaseTaskHandler):
    Methods = ['createContainer']
    _taskWeight = 2.0

    def __init__(self, id, method, params, session, options, workdir=None):
        BaseTaskHandler.__init__(self, id, method, params, session, options,
                                 workdir)
        self._osbs = None

    def _download_logs(self, osbs_build_id):
        build_log = os.path.join(self.workdir, 'build.log')
        self.logger.debug("Getting logs from OSBS")
        build_log_contents = self.osbs().get_build_logs(osbs_build_id)
        self.logger.debug("Logs from OSBS retrieved")
        outfile = open(build_log, 'w')
        outfile.write(build_log_contents)
        outfile.close()
        self.logger.debug("Logs written to: %s" % build_log)
        return ['build.log']

    def osbs(self):
        """Handler of OSBS object"""
        if not self._osbs:
            os_conf = Configuration()
            build_conf = Configuration()
            self._osbs = OSBS(os_conf, build_conf)
            assert self._osbs
        return self._osbs

    def _rpm_package_info(self, parts):
        if len(parts) < 8:
            self.logger.error("Too few number of fields in the list"
                              " of rpms: %r", parts)
            return
        rpm = {
            'name': parts[0],
            'version': parts[1],
            'release': parts[2],
            'arch': parts[3],
            'size': int(parts[5]),
            'sigmd5': parts[6],
            'buildtime': int(parts[7])
        }

        if parts[4] == '(none)':
            rpm['epoch'] = None
        else:
            rpm['epoch'] = int(parts[4])
        return rpm

    def handler(self, src, target_info, build_tag, arch, scratch=False):
        this_task = self.session.getTaskInfo(self.id)
        self.logger.debug("This task: %r", this_task)
        owner_info = self.session.getUser(this_task['owner'])
        self.logger.debug("Started by %s", owner_info['name'])

        scm = SCM(src)
        scm.assert_allowed(self.options.allowed_scms)

        # stolen from koji.daemon
        scheme = scm.scheme
        if '+' in scheme:
            scheme = scheme.split('+')[1]
        git_uri = '%s%s%s' % (scheme, scm.host, scm.repository)
        component = os.path.basename(scm.repository)
        if scm.repository.endswith('.git'):
            # If we're referring to a bare repository for the main module,
            # assume we need to do the same for the common module
            component = os.path.basename(scm.repository[:-4])
        # /stolen from koji.daemon

        build = self.osbs().create_build(
            git_uri=git_uri,
            git_ref=scm.revision,
            user=owner_info['name'],
            component=component,
            target=target_info['name'],
            architecture=arch,
        )
        self.logger.debug("OSBS build id: %s", build.build_id)

        self.logger.info("Waiting for osbs build_id: %s to finish.",
                         build.build_id)
        build_json = self.osbs().wait_for_build_to_finish(build.build_id)
        self.logger.debug("OSBS build finished. Build json response: %s.",
                          build_json)
        logs = self._download_logs(build.build_id)

        rpmlist = []
        try:
            rpm_packages = build_json['metadata']['annotations']['rpm-packages']
        except (KeyError, TypeError), error:
            self.logger.error("Build response miss rpm-package: %s" % error)
            rpm_packages = ''
        for package in rpm_packages.split('\n'):
            parts = package.split(',')
            rpm_info = self._rpm_package_info(parts)
            if not rpm_info:
                continue
            rpmlist.append(rpm_info)

        repo_info = self.session.getRepo(target_info['build_tag'])
        # TODO: copied from image build
        # TODO: hack to make this work for now, need to refactor
        if scratch:
            br = kojid.BuildRoot(self.session, self.options, build_tag, arch,
                                 self.id, repo_id=repo_info['id'])
            br.markExternalRPMs(rpmlist)
            # TODO: I'm not sure if this is ok
            br.expire()

        containerdata = {
            'arch': arch,
            'task_id': self.id,
            'logs': logs,
            'osbs_build_id': build.build_id,
            'rpmlist': rpmlist,
        }

        # upload the build output
        for filename in containerdata['logs']:
            build_log = os.path.join(self.workdir, filename)
            self.uploadFile(build_log)

        return containerdata

class BuildContainerTask(BaseTaskHandler):

    Methods = ['buildContainer']
    # We mostly just wait on other tasks. Same value as for regular 'build'
    # method.
    _taskWeight = 0.2

    def __init__(self, id, method, params, session, options, workdir=None):
        BaseTaskHandler.__init__(self, id, method, params, session, options,
                                 workdir)
        self._osbs = None

    def osbs(self):
        """Handler of OSBS object"""
        if not self._osbs:
            os_conf = Configuration()
            build_conf = Configuration()
            self._osbs = OSBS(os_conf, build_conf)
            assert self._osbs
        return self._osbs

    def initContainerBuild(self, name, version, release, target_info, opts):
        """create a build object for this container build"""
        pkg_cfg = self.session.getPackageConfig(target_info['dest_tag_name'],
                                                name)
        self.logger.debug("%r" % pkg_cfg)
        if not opts.get('skip_tag') and not opts.get('scratch'):
            # Make sure package is on the list for this tag
            if pkg_cfg is None:
                raise koji.BuildError("package (container) %s not in list for tag %s" % (name, target_info['dest_tag_name']))
            elif pkg_cfg['blocked']:
                raise koji.BuildError("package (container)  %s is blocked for tag %s" % (name, target_info['dest_tag_name']))
        return self.session.host.initContainerBuild(self.id,
                                                    dict(name=name,
                                                         version=version,
                                                         release=release,
                                                         epoch=0))

    def runBuilds(self, src, target_info, build_tag, arches, scratch=False):
        subtasks = {}
        for arch in arches:
            subtasks[arch] = self.session.host.subtask(method='createContainer',
                                                       arglist=[src,
                                                                target_info,
                                                                build_tag,
                                                                arch,
                                                                scratch],
                                                       label='container',
                                                       parent=self.id)
        self.logger.debug("Got image subtasks: %r", (subtasks))
        self.logger.debug("Waiting on image subtasks...")
        results = self.wait(subtasks.values(), all=True, failany=True)

        self.logger.debug("Results: %r", results)
        return results

    def getArchList(self, build_tag, extra=None):
        """Copied from build task"""
        # get list of arches to build for
        buildconfig = self.session.getBuildConfig(build_tag, event=self.event_id)
        arches = buildconfig['arches']
        if not arches:
            #XXX - need to handle this better
            raise koji.BuildError, "No arches for tag %(name)s [%(id)s]" % buildconfig
        tag_archlist = [koji.canonArch(a) for a in arches.split()]
        self.logger.debug('arches: %s', arches)
        if extra:
            self.logger.debug('Got extra arches: %s', extra)
            arches = "%s %s" % (arches, extra)
        archlist = arches.split()
        self.logger.debug('base archlist: %r' % archlist)

        override = self.opts.get('arch_override')
        if self.opts.get('scratch') and override:
            # only honor override for scratch builds
            self.logger.debug('arch override: %s', override)
            archlist = override.split()
        archdict = {}
        for a in archlist:
            # Filter based on canonical arches for tag
            # This prevents building for an arch that we can't handle
            if a == 'noarch' or koji.canonArch(a) in tag_archlist:
                archdict[a] = 1
        if not archdict:
            raise koji.BuildError("No matching arches were found")
        return archdict.keys()

    def getRelease(self, name, ver):
        """return the next available release number for an N-V"""
        return self.session.getNextRelease(dict(name=name, version=ver))

    def handler(self, src, target, opts=None):
        if not opts:
            opts = {}
        self.opts = opts
        data = {}

        self.event_id = self.session.getLastEvent()['id']
        target_info = self.session.getBuildTarget(target, event=self.event_id)
        build_tag = target_info['build_tag']
        archlist = self.getArchList(build_tag)
        data['task_id'] = self.id

        if not self.opts.get('scratch'):
            # scratch builds do not get imported
            #raise NotImplementedError("Non-scratch container builds support isn't finished yet")

            name = opts.get('name')
            version = opts.get('version')
            release = opts.get('release')

            if not name:
                raise koji.BuildError('Name needs to be specified for non-scratch container builds')
            if not version:
                raise koji.BuildError('Version needs to be specified for non-scratch container builds')
            if not release:
                release = self.getRelease(name, version)
                if not release:
                    raise koji.BuildError('Release was not specified and failed to get one')

            bld_info = self.initContainerBuild(name, version, release,
                                               target_info, opts)

        try:
            self.extra_information = {"src": src, "data": data,
                                      "target": target}
            if not SCM.is_scm_url(src):
                raise koji.BuildError('Invalid source specification: %s' % src)
            results = self.runBuilds(src, target_info, build_tag, archlist,
                                     opts.get('scratch', False))
            results_xmlrpc = {}
            for task_id, result in results.items():
                # get around an xmlrpc limitation, use arches for keys instead
                results_xmlrpc[str(task_id)] = result
            for result in results.values():
                self._raise_if_image_failed(result['osbs_build_id'])
            if opts.get('scratch'):
                # scratch builds do not get imported
                self.session.host.moveContainerToScratch(self.id,
                                                         results_xmlrpc)
            else:
                self.session.host.completeContainerBuild(self.id,
                                                         bld_info['id'],
                                                         results_xmlrpc)
        except (SystemExit, ServerExit, KeyboardInterrupt):
            # we do not trap these
            raise
        except:
            if not self.opts.get('scratch'):
                # scratch builds do not get imported
                if bld_info:
                    self.session.host.failBuild(self.id, bld_info['id'])
            # reraise the exception
            raise

    def _raise_if_image_failed(self, osbs_build_id):
        build = self.osbs().get_build(osbs_build_id)
        if build.is_failed():
            raise ContainerError('Image build failed')
<commit_msg>Improve rpm_packages listings<commit_after>"""Koji builder plugin extends Koji to build containers

Acts as a wrapper between Koji and OpenShift builsystem via osbs for building
containers."""

# Copyright (C) 2015  Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
# USA

# Authors:
#       Pavol Babincak <pbabinca@redhat.com>
import os

import koji
from koji.daemon import SCM
from koji.tasks import ServerExit, BaseTaskHandler
from osbs.api import OSBS
from osbs.conf import Configuration

# We need kojid module which isn't proper python module and not even in
# site-package path.
kojid_exe_path = '/usr/sbin/kojid'
fo = file(kojid_exe_path, 'U')
try:
    kojid = imp.load_module('kojid', fo, fo.name, ('.py', 'U', 1))
finally:
    fo.close()

class ContainerError(koji.GenericError):
    """Raised when container creation fails"""
    faultCode = 2001

class CreateContainerTask(BaseTaskHandler):
    Methods = ['createContainer']
    _taskWeight = 2.0

    def __init__(self, id, method, params, session, options, workdir=None):
        BaseTaskHandler.__init__(self, id, method, params, session, options,
                                 workdir)
        self._osbs = None

    def _download_logs(self, osbs_build_id):
        build_log = os.path.join(self.workdir, 'build.log')
        self.logger.debug("Getting logs from OSBS")
        build_log_contents = self.osbs().get_build_logs(osbs_build_id)
        self.logger.debug("Logs from OSBS retrieved")
        outfile = open(build_log, 'w')
        outfile.write(build_log_contents)
        outfile.close()
        self.logger.debug("Logs written to: %s" % build_log)
        return ['build.log']

    def osbs(self):
        """Handler of OSBS object"""
        if not self._osbs:
            os_conf = Configuration()
            build_conf = Configuration()
            self._osbs = OSBS(os_conf, build_conf)
            assert self._osbs
        return self._osbs

    def _rpm_package_info(self, parts):
        if len(parts) < 8:
            self.logger.error("Too few number of fields in the list"
                              " of rpms: %r", parts)
            return
        rpm = {
            'name': parts[0],
            'version': parts[1],
            'release': parts[2],
            'arch': parts[3],
            'size': int(parts[5]),
            'sigmd5': parts[6],
            'buildtime': int(parts[7])
        }

        if parts[4] == '(none)':
            rpm['epoch'] = None
        else:
            rpm['epoch'] = int(parts[4])
        return rpm

    def handler(self, src, target_info, build_tag, arch, scratch=False):
        this_task = self.session.getTaskInfo(self.id)
        self.logger.debug("This task: %r", this_task)
        owner_info = self.session.getUser(this_task['owner'])
        self.logger.debug("Started by %s", owner_info['name'])

        scm = SCM(src)
        scm.assert_allowed(self.options.allowed_scms)

        # stolen from koji.daemon
        scheme = scm.scheme
        if '+' in scheme:
            scheme = scheme.split('+')[1]
        git_uri = '%s%s%s' % (scheme, scm.host, scm.repository)
        component = os.path.basename(scm.repository)
        if scm.repository.endswith('.git'):
            # If we're referring to a bare repository for the main module,
            # assume we need to do the same for the common module
            component = os.path.basename(scm.repository[:-4])
        # /stolen from koji.daemon

        build = self.osbs().create_build(
            git_uri=git_uri,
            git_ref=scm.revision,
            user=owner_info['name'],
            component=component,
            target=target_info['name'],
            architecture=arch,
        )
        self.logger.debug("OSBS build id: %s", build.build_id)

        self.logger.info("Waiting for osbs build_id: %s to finish.",
                         build.build_id)
        build_json = self.osbs().wait_for_build_to_finish(build.build_id)
        self.logger.debug("OSBS build finished. Build json response: %s.",
                          build_json)
        logs = self._download_logs(build.build_id)

        rpmlist = []
        try:
            rpm_packages = response.get_rpm_packages()
        except (KeyError, TypeError), error:
            self.logger.error("Build response miss rpm-package: %s" % error)
            rpm_packages = ''
        if rpm_packages is None:
            rpm_packages = ''
        for package in rpm_packages.split('\n'):
            if len(package.strip()) == 0:
                continue
            parts = package.split(',')
            rpm_info = self._rpm_package_info(parts)
            if not rpm_info:
                continue
            rpmlist.append(rpm_info)

        repo_info = self.session.getRepo(target_info['build_tag'])
        # TODO: copied from image build
        # TODO: hack to make this work for now, need to refactor
        if scratch:
            br = kojid.BuildRoot(self.session, self.options, build_tag, arch,
                                 self.id, repo_id=repo_info['id'])
            br.markExternalRPMs(rpmlist)
            # TODO: I'm not sure if this is ok
            br.expire()

        containerdata = {
            'arch': arch,
            'task_id': self.id,
            'logs': logs,
            'osbs_build_id': build.build_id,
            'rpmlist': rpmlist,
        }

        # upload the build output
        for filename in containerdata['logs']:
            build_log = os.path.join(self.workdir, filename)
            self.uploadFile(build_log)

        return containerdata

class BuildContainerTask(BaseTaskHandler):

    Methods = ['buildContainer']
    # We mostly just wait on other tasks. Same value as for regular 'build'
    # method.
    _taskWeight = 0.2

    def __init__(self, id, method, params, session, options, workdir=None):
        BaseTaskHandler.__init__(self, id, method, params, session, options,
                                 workdir)
        self._osbs = None

    def osbs(self):
        """Handler of OSBS object"""
        if not self._osbs:
            os_conf = Configuration()
            build_conf = Configuration()
            self._osbs = OSBS(os_conf, build_conf)
            assert self._osbs
        return self._osbs

    def initContainerBuild(self, name, version, release, target_info, opts):
        """create a build object for this container build"""
        pkg_cfg = self.session.getPackageConfig(target_info['dest_tag_name'],
                                                name)
        self.logger.debug("%r" % pkg_cfg)
        if not opts.get('skip_tag') and not opts.get('scratch'):
            # Make sure package is on the list for this tag
            if pkg_cfg is None:
                raise koji.BuildError("package (container) %s not in list for tag %s" % (name, target_info['dest_tag_name']))
            elif pkg_cfg['blocked']:
                raise koji.BuildError("package (container)  %s is blocked for tag %s" % (name, target_info['dest_tag_name']))
        return self.session.host.initContainerBuild(self.id,
                                                    dict(name=name,
                                                         version=version,
                                                         release=release,
                                                         epoch=0))

    def runBuilds(self, src, target_info, build_tag, arches, scratch=False):
        subtasks = {}
        for arch in arches:
            subtasks[arch] = self.session.host.subtask(method='createContainer',
                                                       arglist=[src,
                                                                target_info,
                                                                build_tag,
                                                                arch,
                                                                scratch],
                                                       label='container',
                                                       parent=self.id)
        self.logger.debug("Got image subtasks: %r", (subtasks))
        self.logger.debug("Waiting on image subtasks...")
        results = self.wait(subtasks.values(), all=True, failany=True)

        self.logger.debug("Results: %r", results)
        return results

    def getArchList(self, build_tag, extra=None):
        """Copied from build task"""
        # get list of arches to build for
        buildconfig = self.session.getBuildConfig(build_tag, event=self.event_id)
        arches = buildconfig['arches']
        if not arches:
            #XXX - need to handle this better
            raise koji.BuildError, "No arches for tag %(name)s [%(id)s]" % buildconfig
        tag_archlist = [koji.canonArch(a) for a in arches.split()]
        self.logger.debug('arches: %s', arches)
        if extra:
            self.logger.debug('Got extra arches: %s', extra)
            arches = "%s %s" % (arches, extra)
        archlist = arches.split()
        self.logger.debug('base archlist: %r' % archlist)

        override = self.opts.get('arch_override')
        if self.opts.get('scratch') and override:
            # only honor override for scratch builds
            self.logger.debug('arch override: %s', override)
            archlist = override.split()
        archdict = {}
        for a in archlist:
            # Filter based on canonical arches for tag
            # This prevents building for an arch that we can't handle
            if a == 'noarch' or koji.canonArch(a) in tag_archlist:
                archdict[a] = 1
        if not archdict:
            raise koji.BuildError("No matching arches were found")
        return archdict.keys()

    def getRelease(self, name, ver):
        """return the next available release number for an N-V"""
        return self.session.getNextRelease(dict(name=name, version=ver))

    def handler(self, src, target, opts=None):
        if not opts:
            opts = {}
        self.opts = opts
        data = {}

        self.event_id = self.session.getLastEvent()['id']
        target_info = self.session.getBuildTarget(target, event=self.event_id)
        build_tag = target_info['build_tag']
        archlist = self.getArchList(build_tag)
        data['task_id'] = self.id

        if not self.opts.get('scratch'):
            # scratch builds do not get imported
            #raise NotImplementedError("Non-scratch container builds support isn't finished yet")

            name = opts.get('name')
            version = opts.get('version')
            release = opts.get('release')

            if not name:
                raise koji.BuildError('Name needs to be specified for non-scratch container builds')
            if not version:
                raise koji.BuildError('Version needs to be specified for non-scratch container builds')
            if not release:
                release = self.getRelease(name, version)
                if not release:
                    raise koji.BuildError('Release was not specified and failed to get one')

            bld_info = self.initContainerBuild(name, version, release,
                                               target_info, opts)

        try:
            self.extra_information = {"src": src, "data": data,
                                      "target": target}
            if not SCM.is_scm_url(src):
                raise koji.BuildError('Invalid source specification: %s' % src)
            results = self.runBuilds(src, target_info, build_tag, archlist,
                                     opts.get('scratch', False))
            results_xmlrpc = {}
            for task_id, result in results.items():
                # get around an xmlrpc limitation, use arches for keys instead
                results_xmlrpc[str(task_id)] = result
            for result in results.values():
                self._raise_if_image_failed(result['osbs_build_id'])
            if opts.get('scratch'):
                # scratch builds do not get imported
                self.session.host.moveContainerToScratch(self.id,
                                                         results_xmlrpc)
            else:
                self.session.host.completeContainerBuild(self.id,
                                                         bld_info['id'],
                                                         results_xmlrpc)
        except (SystemExit, ServerExit, KeyboardInterrupt):
            # we do not trap these
            raise
        except:
            if not self.opts.get('scratch'):
                # scratch builds do not get imported
                if bld_info:
                    self.session.host.failBuild(self.id, bld_info['id'])
            # reraise the exception
            raise

    def _raise_if_image_failed(self, osbs_build_id):
        build = self.osbs().get_build(osbs_build_id)
        if build.is_failed():
            raise ContainerError('Image build failed')
<|endoftext|>


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

import LabJackPython
import u3

def setup(dev):
    # configure inputs
    dev.getDIState(u3.FIO3)  # /reset
    dev.getDIState(u3.FIO6)  # ready
    dev.getDIState(u3.FIO7)  # dirc

    # configure timers
    # fio4: timer 0 (frequency out)
    # fio5: timer 1 (timer stop)
    # connect /strobe to fio4 and fio5
    dev.configIO(TimerCounterPinOffset=4,
                 NumberOfTimersEnabled=2)

    # use 48 MHz timer clock
    cmd = dev.configTimerClock(LabJackPython.LJ_tc48MHZ_DIV, 1)
    dev.getFeedback(cmd)

def strobe(dev):
    # set timer 1 mode as timer stop.  this will stop timer 0 after a
    # single pulse (Value=1).  this must be done before starting timer 0
    # or else it will be too late to stop the pulses.
    cmd = u3.Timer1Config(TimerMode=LabJackPython.LJ_tmTIMERSTOP, Value=1)
    dev.getFeedback(cmd)

    # set timer 0 mode as frequency out.  this will start immediately after
    # the command is sent.  it should output one pulse (the line is normally
    # high and will be pulled low temporarily) and then be stopped by timer 1.
    cmd = u3.Timer0Config(TimerMode=LabJackPython.LJ_tmFREQOUT, Value=0)
    dev.getFeedback(cmd)

def is_drive_ready(dev):
    return dev.getDIState(u3.FIO6) == 1

def is_host_to_drive(dev):
    return dev.getDIState(u3.FIO7) == 1

if __name__ == "__main__":
    dev = u3.U3()
    setup(dev)

    for i in range(100):
        while not(is_drive_ready(dev)):
          pass
        print("drive is ready")

        while not(is_host_to_drive(dev)):
          pass
        print("direction is host-to-drive")

        strobe(dev)
        print("strobe")

        while not(is_drive_ready(dev)):
          pass
        print("drive is ready")

        while is_host_to_drive(dev):
          pass
        print("direction is drive-to-host")

        strobe(dev)
        print("strobe")
<commit_msg>Add data bus read/write<commit_after>#!/usr/bin/env python

import LabJackPython
import u3

def setup(dev):
    # configure inputs
    dev.getDIState(u3.FIO3)  # /reset
    dev.getDIState(u3.FIO6)  # ready
    dev.getDIState(u3.FIO7)  # dirc

    # configure outputs
    dev.setDOState(u3.FIO0, 1)  # 74hct245 /oe for corvus data bus

    # configure timers
    # fio4: timer 0 (frequency out)
    # fio5: timer 1 (timer stop)
    # connect /strobe to fio4 and fio5
    dev.configIO(TimerCounterPinOffset=4,
                 NumberOfTimersEnabled=2)

    # use 48 MHz timer clock
    cmd = dev.configTimerClock(LabJackPython.LJ_tc48MHZ_DIV, 1)
    dev.getFeedback(cmd)

def strobe(dev):
    # set timer 1 mode as timer stop.  this will stop timer 0 after a
    # single pulse (Value=1).  this must be done before starting timer 0
    # or else it will be too late to stop the pulses.
    cmd = u3.Timer1Config(TimerMode=LabJackPython.LJ_tmTIMERSTOP, Value=1)
    dev.getFeedback(cmd)

    # set timer 0 mode as frequency out.  this will start immediately after
    # the command is sent.  it should output one pulse (the line is normally
    # high and will be pulled low temporarily) and then be stopped by timer 1.
    cmd = u3.Timer0Config(TimerMode=LabJackPython.LJ_tmFREQOUT, Value=0)
    dev.getFeedback(cmd)

def is_drive_ready(dev):
    return dev.getDIState(u3.FIO6) == 1

def is_host_to_drive(dev):
    return dev.getDIState(u3.FIO7) == 1

DATA_LINES = (u3.EIO0, u3.EIO1, u3.EIO2, u3.EIO3,
              u3.EIO4, u3.EIO5, u3.EIO6, u3.EIO7)

def connect_data_bus(dev):
    # set pins as input
    for line in DATA_LINES:
        dev.getDIState(line)

    # set /oe on 74hct245 to low to connect
    dev.setDOState(u3.FIO0, 0)

def disconnect_data_bus(dev):
    # set /oe on 74hct245 to high to disconnect
    dev.setDOState(u3.FIO0, 1)

    # set pins as input
    for line in DATA_LINES:
        dev.getDIState(line)

def read_data(dev):
    # lines must already be configured as input
    # read each line to build the byte
    value = 0
    for bit, line in enumerate(DATA_LINES):
        if dev.getDIState(line) == 1:
            value |= 2**bit
    return value

def write_data(dev, value):
    # set pins as output low
    for line in DATA_LINES:
        dev.setDOState(line, 0)

    # turn on lines for bits that are high
    for bit, line in enumerate(DATA_LINES):
        if (value & 2**bit) != 0:
            dev.setDOState(line, 1)

if __name__ == "__main__":
    dev = u3.U3()
    setup(dev)

    for i in range(100):
        while not(is_drive_ready(dev)):
          pass
        print("drive is ready")

        while not(is_host_to_drive(dev)):
          pass
        print("direction is host-to-drive")

        connect_data_bus(dev)
        value = 0xff # 0xff is an invalid command
        write_data(dev, value)
        print("wrote %02x" % value)
        strobe(dev)
        print("strobe")
        disconnect_data_bus(dev)

        while not(is_drive_ready(dev)):
          pass
        print("drive is ready")

        while is_host_to_drive(dev):
          pass
        print("direction is drive-to-host")

        connect_data_bus(dev)
        value = read_data(dev) # should return 0x8f (invalid command)
        print("read %02x" % value)
        strobe(dev)
        print("strobe")
        disconnect_data_bus(dev)
<|endoftext|>


<commit_before>'''
Manage PHP pecl extensions.
'''

# Import python libs
import re

__opts__ = {}
__pillar__ = {}

def _pecl(command):
    cmdline = 'pecl {0}'.format(command)

    ret = __salt__['cmd.run_all'](cmdline)

    if ret['retcode'] == 0:
        return ret['stdout']
    else:
        return False

def install(pecls):
    '''
    Installs one or several pecl extensions.

    pecls
        The pecl extensions to install.
    '''
    return _pecl('install {0}'.format(pecls))

def uninstall(pecls):
    '''
    Uninstall one or several pecl extensions.

    pecls
        The pecl extensions to uninstall.
    '''
    return _pecl('uninstall {0}'.format(pecls))

def update(pecls):
    '''
    Update one or several pecl exntesions.

    pecls
        The pecl extensions to update.
    '''
    return _pecl('install -U {0}'.format(pecls))

def list():
    '''
    List installed pecl extensions.
    '''

    lines = _pecl('list').splitlines()
    lines.pop(0)
    lines.pop(0)
    lines.pop(0)
    lines.pop(0)

    pecls = {}
    for line in lines:
        m = re.match('^([^ ]+)[ ]+([^ ]+)[ ]+([^ ]+)', line)
        if m:
            pecls[m.group(1)] = [m.group(2), m.group(3)]

    return pecls

<commit_msg>Update salt/modules/pecl.py<commit_after>'''
Manage PHP pecl extensions.
'''

# Import python libs
import re

__opts__ = {}
__pillar__ = {}

def _pecl(command):
    cmdline = 'pecl {0}'.format(command)

    ret = __salt__['cmd.run_all'](cmdline)

    if ret['retcode'] == 0:
        return ret['stdout']
    else:
        return False

def install(pecls):
    '''
    Installs one or several pecl extensions.

    pecls
        The pecl extensions to install.
    '''
    return _pecl('install {0}'.format(pecls))

def uninstall(pecls):
    '''
    Uninstall one or several pecl extensions.

    pecls
        The pecl extensions to uninstall.
    '''
    return _pecl('uninstall {0}'.format(pecls))

def update(pecls):
    '''
    Update one or several pecl exntesions.

    pecls
        The pecl extensions to update.
    '''
    return _pecl('install -U {0}'.format(pecls))

def list():
    '''
    List installed pecl extensions.
    '''

    lines = _pecl('list').splitlines()
    lines.pop(0)
    lines.pop(0)
    lines.pop(0)

    pecls = {}
    for line in lines:
        m = re.match('^([^ ]+)[ ]+([^ ]+)[ ]+([^ ]+)', line)
        if m:
            pecls[m.group(1)] = [m.group(2), m.group(3)]

    return pecls

<|endoftext|>