<commit_before>from .onmanager import ONProcess
from xml.etree import cElementTree

NS = ""

#
class OneNote():

    def __init__(self):
        self.process = ONProcess()
        global NS
        NS = self.process.NS
        self.object_tree = cElementTree.fromstring(self.process.GetHierarchy("",4))
        self.hierarchy = Hierarchy()
        self.hierarchy.deserialize_from_xml(self.object_tree)

    def get_page_content(self, page_id):
        page_content_xml = cElementTree.fromstring(self.process.GetPageContent(page_id))
        return PageContent(page_content_xml)

#
#  HIERARCHY
#

class Hierarchy():

    def __init__(self):
        self._children = []

    def deserialize_from_xml(self, xml):
        self._children = [Notebook(n) for n in xml]

    def __iter__(self):
        for c in self._children:
            yield c

#
# HIERARCHY NODE
#

class HierarchyNode():

    def _init_(self, parent=None):
        self.name = ""
        self.path = ""
        self.id = ""
        self.last_modified_time = ""
        self.synchronized = ""

    def deserialize_from_xml(self, xml):
        self.name = xml.get("name")
        self.path = xml.get("path")
        self.id = xml.get("ID")
        self.last_modified_time = xml.get("lastModifiedTime")

#
#   NOTEBOOK CLASS
#

class Notebook(HierarchyNode):

    def __init__ (self, xml=None):
        HierarchyNode.__init__(self)
        self.nickname = ""
        self.color = ""
        self.is_currently_viewed = ""
        self.recycleBin = None
        self._children = []
        if (xml != None):
            self.deserialize_from_xml(xml)

    def deserialize_from_xml(self, xml):
        HierarchyNode.deserialize_from_xml(self, xml)
        self.nickname = xml.get("nickname")
        self.color = xml.get("color")
        self.is_currently_viewed = xml.get("isCurrentlyViewed")
        self.recycleBin = None
        for node in xml:
            if (node.tag == NS + "Section"):
                self._children.append(Section(node, self))

            elif (node.tag == NS + "SectionGroup"):
                if(node.get("isRecycleBin")):
                    self.recycleBin = SectionGroup(node, self)
                else:
                    self._children.append(SectionGroup(node, self))

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

#
# SECTION GROUP CLASS
#

class SectionGroup(HierarchyNode):

    def __init__ (self, xml=None, parent_node=None):
        HierarchyNode.__init__(self)
        self.is_recycle_Bin = False
        self._children = []
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

    def deserialize_from_xml(self, xml):
        HierarchyNode.deserialize_from_xml(self, xml)
        self.is_recycle_Bin = xml.get("isRecycleBin")
        for node in xml:
            if (node.tag == NS + "SectionGroup"):
                self._children.append(SectionGroup(node, self))
            if (node.tag == NS + "Section"):
                self._children.append(Section(node, self))

#
# SECTION CLASS
#

class Section(HierarchyNode):

    def __init__ (self, xml=None, parent_node=None):
        HierarchyNode.__init__(self)
        self.color = ""
        self.read_only = False
        self.is_currently_viewed = False
        self._children = []
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

    def deserialize_from_xml(self, xml):
        HierarchyNode.deserialize_from_xml(self, xml)
        self.color = xml.get("color")
        try:
            self.read_only = xml.get("readOnly")
        except:
            self.read_only = False
        try:
            self.is_currently_viewed = xml.get("isCurrentlyViewed")
        except:
            self.is_currently_viewed = False

        self._children = [Page(node, self) for node in xml]

#
#  PAGE CLASS
#

class Page():

    def __init__ (self, xml=None, parent_node=None):
        self.name = ""
        self.id = ""
        self.date_time = ""
        self.last_modified_time = ""
        self.page_level = ""
        self.is_currently_viewed = ""
        self._children = []
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

    # Get / Set Meta

    def deserialize_from_xml (self, xml):
        self.name = xml.get("name")
        self.id = xml.get("ID")
        self.date_time = xml.get("dateTime")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.page_level = xml.get("pageLevel")
        self.is_currently_viewed = xml.get("isCurrentlyViewed")
        self._children = [Meta(node) for node in xml]

#
# META CLASS
#

class Meta():

    def __init__ (self, xml = None):
        self.name = ""
        self.content = ""
        if (xml!=None):
            self.deserialize_from_xml(xml)

    def __str__(self):
        return self.name

    def deserialize_from_xml (self, xml):
        self.name = xml.get("name")
        self.id = xml.get("content")

#
# PAGE CONTENT CLASS
#

class PageContent():

    def __init__ (self, xml=None):
        self.name = ""
        self.id = ""
        self.date_time = ""
        self.last_modified_time = ""
        self.page_level = ""
        self.lang = ""
        self.is_currently_viewed = ""
        self._children= []
        self.files = []
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

    def deserialize_from_xml(self, xml):
            self.name = xml.get("name")
            self.id = xml.get("ID")
            self.date_time = xml.get("dateTime")
            self.last_modified_time = xml.get("lastModifiedTime")
            self.page_level = xml.get("pageLevel")
            self.lang = xml.get("lang")
            self.is_currently_viewed = xml.get("isCurrentlyViewed")
            for node in xml:
                if (node.tag == NS + "Outline"):
                   self._children.append(Outline(node))
                elif (node.tag == NS + "Ink"):
                    self.files.append(Ink(node))
                elif (node.tag == NS + "Image"):
                    self.files.append(Image(node))
                elif (node.tag == NS + "InsertedFile"):
                    self.files.append(InsertedFile(node))
                elif (node.tag == NS + "Title"):
                    self._children.append(Title(node))

#
# TITLE CLASS
#

class Title():

    def __init__ (self, xml=None):
        self.style = ""
        self.lang = ""
        self._children = []

    def __str__ (self):
        return "Page Title"

    def __iter__ (self):
        for c in self._children:
            yield c

    def deserialize_from_xml(self, xml):
        self.style = xml.get("style")
        self.lang = xml.get("lang")
        for node in xml:
            if (node.tag == NS + "OE"):
                self._children.append(OE(node, self))

#
# OUTLINE CLASS
#

class Outline():

    def __init__ (self, xml=None):
        self.author = ""
        self.author_initials = ""
        self.last_modified_by = ""
        self.last_modified_by_initials = ""
        self.last_modified_time = ""
        self.id = ""
        self._children = []
        if(xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return "Outline"

    def deserialize_from_xml (self, xml):
        self.author = xml.get("author")
        self.author_initials = xml.get("authorInitials")
        self.last_modified_by = xml.get("lastModifiedBy")
        self.last_modified_by_initials = xml.get("lastModifiedByInitials")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.id = xml.get("objectID")
        append = self._children.append
        for node in xml:
            if (node.tag == NS + "OEChildren"):
                for childNode in node:
                    if (childNode.tag == NS + "OE"):
                        append(OE(childNode, self))

#
# POSITION CLASS
#

class Position():

    def __init__ (self, xml=None, parent_node=None):
        self.x = ""
        self.y = ""
        self.z = ""
        self.parent = parent_node
        if (xml!=None):
            self.deserialize_from_xml(xml)

    def deserialize_from_xml(self, xml):
        self.x = xml.get("x")
        self.y = xml.get("y")
        self.z = xml.get("z")

#
# SIZE CLASS
#

class Size():

    def __init__ (self, xml=None, parent_node=None):
        self.width = ""
        self.height = ""
        self.parent = parent_node
        if (xml!=None):
            self.deserialize_from_xml(xml)

    def deserialize_from_xml(self, xml):
        self.width = xml.get("width")
        self.height = xml.get("height")

#
# OE CLASS
#

class OE():

    def __init__ (self, xml=None, parent_node=None):

        self.creation_time = ""
        self.last_modified_time = ""
        self.last_modified_by = ""
        self.id = ""
        self.alignment = ""
        self.quick_style_index = ""
        self.style = ""
        self.text = ""
        self._children = []
        self.parent = parent_node
        self.files = []
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        try:
            return self.text
        except AttributeError:
            return "Empty OE"

    def deserialize_from_xml(self, xml):
        self.creation_time = xml.get("creationTime")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.last_modified_by = xml.get("lastModifiedBy")
        self.id = xml.get("objectID")
        self.alignment = xml.get("alignment")
        self.quick_style_index = xml.get("quickStyleIndex")
        self.style = xml.get("style")

        for node in xml:
            if (node.tag == NS + "T"):
                if (node.text != None):
                    self.text = node.text
                else:
                    self.text = "NO TEXT"

            elif (node.tag == NS + "OEChildren"):
                for childNode in node:
                    if (childNode.tag == NS + "OE"):
                        self._children.append(OE(childNode, self))

            elif (node.tag == NS + "Image"):
                self.files.append(Image(node, self))

            elif (node.tag == NS + "InkWord"):
                self.files.append(Ink(node, self))

            elif (node.tag == NS + "InsertedFile"):
                self.files.append(InsertedFile(node, self))

#
# INSERTED FILE CLASS
#

class InsertedFile():

    # need to add position data to this class

    def __init__ (self, xml=None, parent_node=None):
        self.path_cache = ""
        self.path_source = ""
        self.preferred_name = ""
        self.last_modified_time = ""
        self.last_modified_by = ""
        self.id = ""
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def _iter_ (self):
        yield None

    def __str__(self):
        try:
            return self.preferredName
        except AttributeError:
            return "Unnamed File"

    def deserialize_from_xml(self, xml):
        self.path_cache = xml.get("pathCache")
        self.path_source = xml.get("pathSource")
        self.preferred_name = xml.get("preferredName")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.last_modified_by = xml.get("lastModifiedBy")
        self.id = xml.get("objectID")

#
# INK CLASS
#

class Ink():

    # need to add position data to this class

    def __init__ (self, xml=None, parent_node=None):
        self.recognized_text = ""
        self.x = ""
        self.y = ""
        self.ink_origin_x = ""
        self.ink_origin_y = ""
        self.width = ""
        self.height = ""
        self.data = ""
        self.callback_id = ""
        self.parent = parent_node

        if (xml != None):
            self.deserialize_from_xml(xml)

    def _iter_ (self):
        yield None

    def __str__(self):
        try:
            return self.recognizedText
        except AttributeError:
            return "Unrecognized Ink"

    def deserialize_from_xml(self, xml):
        self.recognized_text = xml.get("recognizedText")
        self.x = xml.get("x")
        self.y = xml.get("y")
        self.ink_origin_x = xml.get("inkOriginX")
        self.ink_origin_y = xml.get("inkOriginY")
        self.width = xml.get("width")
        self.height = xml.get("height")

        for node in xml:
            if (node.tag == NS + "CallbackID"):
                self.callback_id = node.get("callbackID")
            elif (node.tag == NS + "Data"):
                self.data = node.text

#
#  IMAGE CLASS
#

class Image():

    def __init__ (self, xml=None, parent_node=None):
        self.format = ""
        self.original_page_number = ""
        self.last_modified_time = ""
        self.id = ""
        self.callback_id = None
        self.data = ""
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def _iter_ (self):
        yield None

    def __str__(self):
        return self.format + " Image"

    def deserialize_from_xml(self, xml):
        self.format = xml.get("format")
        self.original_page_number = xml.get("originalPageNumber")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.id = xml.get("objectID")
        for node in xml:
            if (node.tag == NS + "CallbackID"):
                self.callback_id = node.get("callbackID")
            elif (node.tag == NS + "Data"):
                if (node.text != None):
                    self.data = node.text
                <commit_msg>Removed unnecessary comments from onepy.py<commit_after>from .onmanager import ONProcess
from xml.etree import cElementTree

NS = ""

class OneNote():

    def __init__(self):
        self.process = ONProcess()
        global NS
        NS = self.process.NS
        self.object_tree = cElementTree.fromstring(self.process.GetHierarchy("",4))
        self.hierarchy = Hierarchy()
        self.hierarchy.deserialize_from_xml(self.object_tree)

    def get_page_content(self, page_id):
        page_content_xml = cElementTree.fromstring(self.process.GetPageContent(page_id))
        return PageContent(page_content_xml)

class Hierarchy():

    def __init__(self):
        self._children = []

    def deserialize_from_xml(self, xml):
        self._children = [Notebook(n) for n in xml]

    def __iter__(self):
        for c in self._children:
            yield c

class HierarchyNode():

    def _init_(self, parent=None):
        self.name = ""
        self.path = ""
        self.id = ""
        self.last_modified_time = ""
        self.synchronized = ""

    def deserialize_from_xml(self, xml):
        self.name = xml.get("name")
        self.path = xml.get("path")
        self.id = xml.get("ID")
        self.last_modified_time = xml.get("lastModifiedTime")

class Notebook(HierarchyNode):

    def __init__ (self, xml=None):
        HierarchyNode.__init__(self)
        self.nickname = ""
        self.color = ""
        self.is_currently_viewed = ""
        self.recycleBin = None
        self._children = []
        if (xml != None):
            self.deserialize_from_xml(xml)

    def deserialize_from_xml(self, xml):
        HierarchyNode.deserialize_from_xml(self, xml)
        self.nickname = xml.get("nickname")
        self.color = xml.get("color")
        self.is_currently_viewed = xml.get("isCurrentlyViewed")
        self.recycleBin = None
        for node in xml:
            if (node.tag == NS + "Section"):
                self._children.append(Section(node, self))

            elif (node.tag == NS + "SectionGroup"):
                if(node.get("isRecycleBin")):
                    self.recycleBin = SectionGroup(node, self)
                else:
                    self._children.append(SectionGroup(node, self))

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

class SectionGroup(HierarchyNode):

    def __init__ (self, xml=None, parent_node=None):
        HierarchyNode.__init__(self)
        self.is_recycle_Bin = False
        self._children = []
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

    def deserialize_from_xml(self, xml):
        HierarchyNode.deserialize_from_xml(self, xml)
        self.is_recycle_Bin = xml.get("isRecycleBin")
        for node in xml:
            if (node.tag == NS + "SectionGroup"):
                self._children.append(SectionGroup(node, self))
            if (node.tag == NS + "Section"):
                self._children.append(Section(node, self))

class Section(HierarchyNode):

    def __init__ (self, xml=None, parent_node=None):
        HierarchyNode.__init__(self)
        self.color = ""
        self.read_only = False
        self.is_currently_viewed = False
        self._children = []
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

    def deserialize_from_xml(self, xml):
        HierarchyNode.deserialize_from_xml(self, xml)
        self.color = xml.get("color")
        try:
            self.read_only = xml.get("readOnly")
        except:
            self.read_only = False
        try:
            self.is_currently_viewed = xml.get("isCurrentlyViewed")
        except:
            self.is_currently_viewed = False

        self._children = [Page(node, self) for node in xml]

class Page():

    def __init__ (self, xml=None, parent_node=None):
        self.name = ""
        self.id = ""
        self.date_time = ""
        self.last_modified_time = ""
        self.page_level = ""
        self.is_currently_viewed = ""
        self._children = []
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

    # Get / Set Meta

    def deserialize_from_xml (self, xml):
        self.name = xml.get("name")
        self.id = xml.get("ID")
        self.date_time = xml.get("dateTime")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.page_level = xml.get("pageLevel")
        self.is_currently_viewed = xml.get("isCurrentlyViewed")
        self._children = [Meta(node) for node in xml]

class Meta():

    def __init__ (self, xml = None):
        self.name = ""
        self.content = ""
        if (xml!=None):
            self.deserialize_from_xml(xml)

    def __str__(self):
        return self.name

    def deserialize_from_xml (self, xml):
        self.name = xml.get("name")
        self.id = xml.get("content")

class PageContent():

    def __init__ (self, xml=None):
        self.name = ""
        self.id = ""
        self.date_time = ""
        self.last_modified_time = ""
        self.page_level = ""
        self.lang = ""
        self.is_currently_viewed = ""
        self._children= []
        self.files = []
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return self.name

    def deserialize_from_xml(self, xml):
            self.name = xml.get("name")
            self.id = xml.get("ID")
            self.date_time = xml.get("dateTime")
            self.last_modified_time = xml.get("lastModifiedTime")
            self.page_level = xml.get("pageLevel")
            self.lang = xml.get("lang")
            self.is_currently_viewed = xml.get("isCurrentlyViewed")
            for node in xml:
                if (node.tag == NS + "Outline"):
                   self._children.append(Outline(node))
                elif (node.tag == NS + "Ink"):
                    self.files.append(Ink(node))
                elif (node.tag == NS + "Image"):
                    self.files.append(Image(node))
                elif (node.tag == NS + "InsertedFile"):
                    self.files.append(InsertedFile(node))
                elif (node.tag == NS + "Title"):
                    self._children.append(Title(node))

class Title():

    def __init__ (self, xml=None):
        self.style = ""
        self.lang = ""
        self._children = []

    def __str__ (self):
        return "Page Title"

    def __iter__ (self):
        for c in self._children:
            yield c

    def deserialize_from_xml(self, xml):
        self.style = xml.get("style")
        self.lang = xml.get("lang")
        for node in xml:
            if (node.tag == NS + "OE"):
                self._children.append(OE(node, self))

class Outline():

    def __init__ (self, xml=None):
        self.author = ""
        self.author_initials = ""
        self.last_modified_by = ""
        self.last_modified_by_initials = ""
        self.last_modified_time = ""
        self.id = ""
        self._children = []
        if(xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        return "Outline"

    def deserialize_from_xml (self, xml):
        self.author = xml.get("author")
        self.author_initials = xml.get("authorInitials")
        self.last_modified_by = xml.get("lastModifiedBy")
        self.last_modified_by_initials = xml.get("lastModifiedByInitials")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.id = xml.get("objectID")
        append = self._children.append
        for node in xml:
            if (node.tag == NS + "OEChildren"):
                for childNode in node:
                    if (childNode.tag == NS + "OE"):
                        append(OE(childNode, self))

class Position():

    def __init__ (self, xml=None, parent_node=None):
        self.x = ""
        self.y = ""
        self.z = ""
        self.parent = parent_node
        if (xml!=None):
            self.deserialize_from_xml(xml)

    def deserialize_from_xml(self, xml):
        self.x = xml.get("x")
        self.y = xml.get("y")
        self.z = xml.get("z")

class Size():

    def __init__ (self, xml=None, parent_node=None):
        self.width = ""
        self.height = ""
        self.parent = parent_node
        if (xml!=None):
            self.deserialize_from_xml(xml)

    def deserialize_from_xml(self, xml):
        self.width = xml.get("width")
        self.height = xml.get("height")

class OE():

    def __init__ (self, xml=None, parent_node=None):

        self.creation_time = ""
        self.last_modified_time = ""
        self.last_modified_by = ""
        self.id = ""
        self.alignment = ""
        self.quick_style_index = ""
        self.style = ""
        self.text = ""
        self._children = []
        self.parent = parent_node
        self.files = []
        if (xml != None):
            self.deserialize_from_xml(xml)

    def __iter__(self):
        for c in self._children:
            yield c

    def __str__(self):
        try:
            return self.text
        except AttributeError:
            return "Empty OE"

    def deserialize_from_xml(self, xml):
        self.creation_time = xml.get("creationTime")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.last_modified_by = xml.get("lastModifiedBy")
        self.id = xml.get("objectID")
        self.alignment = xml.get("alignment")
        self.quick_style_index = xml.get("quickStyleIndex")
        self.style = xml.get("style")

        for node in xml:
            if (node.tag == NS + "T"):
                if (node.text != None):
                    self.text = node.text
                else:
                    self.text = "NO TEXT"

            elif (node.tag == NS + "OEChildren"):
                for childNode in node:
                    if (childNode.tag == NS + "OE"):
                        self._children.append(OE(childNode, self))

            elif (node.tag == NS + "Image"):
                self.files.append(Image(node, self))

            elif (node.tag == NS + "InkWord"):
                self.files.append(Ink(node, self))

            elif (node.tag == NS + "InsertedFile"):
                self.files.append(InsertedFile(node, self))

class InsertedFile():

    # need to add position data to this class

    def __init__ (self, xml=None, parent_node=None):
        self.path_cache = ""
        self.path_source = ""
        self.preferred_name = ""
        self.last_modified_time = ""
        self.last_modified_by = ""
        self.id = ""
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def _iter_ (self):
        yield None

    def __str__(self):
        try:
            return self.preferredName
        except AttributeError:
            return "Unnamed File"

    def deserialize_from_xml(self, xml):
        self.path_cache = xml.get("pathCache")
        self.path_source = xml.get("pathSource")
        self.preferred_name = xml.get("preferredName")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.last_modified_by = xml.get("lastModifiedBy")
        self.id = xml.get("objectID")

class Ink():

    # need to add position data to this class

    def __init__ (self, xml=None, parent_node=None):
        self.recognized_text = ""
        self.x = ""
        self.y = ""
        self.ink_origin_x = ""
        self.ink_origin_y = ""
        self.width = ""
        self.height = ""
        self.data = ""
        self.callback_id = ""
        self.parent = parent_node

        if (xml != None):
            self.deserialize_from_xml(xml)

    def _iter_ (self):
        yield None

    def __str__(self):
        try:
            return self.recognizedText
        except AttributeError:
            return "Unrecognized Ink"

    def deserialize_from_xml(self, xml):
        self.recognized_text = xml.get("recognizedText")
        self.x = xml.get("x")
        self.y = xml.get("y")
        self.ink_origin_x = xml.get("inkOriginX")
        self.ink_origin_y = xml.get("inkOriginY")
        self.width = xml.get("width")
        self.height = xml.get("height")

        for node in xml:
            if (node.tag == NS + "CallbackID"):
                self.callback_id = node.get("callbackID")
            elif (node.tag == NS + "Data"):
                self.data = node.text

class Image():

    def __init__ (self, xml=None, parent_node=None):
        self.format = ""
        self.original_page_number = ""
        self.last_modified_time = ""
        self.id = ""
        self.callback_id = None
        self.data = ""
        self.parent = parent_node
        if (xml != None):
            self.deserialize_from_xml(xml)

    def _iter_ (self):
        yield None

    def __str__(self):
        return self.format + " Image"

    def deserialize_from_xml(self, xml):
        self.format = xml.get("format")
        self.original_page_number = xml.get("originalPageNumber")
        self.last_modified_time = xml.get("lastModifiedTime")
        self.id = xml.get("objectID")
        for node in xml:
            if (node.tag == NS + "CallbackID"):
                self.callback_id = node.get("callbackID")
            elif (node.tag == NS + "Data"):
                if (node.text != None):
                    self.data = node.text

<|endoftext|>


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

import psycopg2
import psycopg2.extras
import psycopg2.extensions

from   env       import *

## Exportable classes

class OADao(object):
    """Wrapper around psycopg2 with additional functionality
    for logging, connection management and sql execution"""
    def __init__(self, schema):
        """Schema refers to the api entity we're referring
        to: auth, trading etc"""
        self.schema = schema
        self.__dbinfo = getenv().dbinfo
        self.dbinfo = self.__dbinfo
        self.__enter__()

    def __enter__(self):
        self.dbconn = psycopg2.connect(dbname=self.__dbinfo['dbname'],
                                       user=self.__dbinfo['user'],
                                       host=self.__dbinfo['host'],
                                       port=self.__dbinfo['port'])
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def commit(self):
        """Proxy method for committing dbconnection actions"""
        self.dbconn.commit()

    def close(self):
        """Proxy method for closing dbconnection"""
        self.dbconn.close()

    def rollback(self):
        """Proxy method for rolling back any existing action"""
        self.dbconn.rollback()

    @property
    def cur(self):
        cursor = self.dbconn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cursor.execute("SET search_path TO %s", [self.schema])
        return cursor

    @property
    def isolation(self):
        return self._isolation_level
    @isolation.setter
    def isolation(self, value):
        self.dbconn.set_isolation_level(value)

    class Isolation(object):
        READCMT = psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED
        READRPT = psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ
        SERIAL  = psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE

<commit_msg>Provide option to use normal psycopg2 cursor behavior<commit_after>#!/usr/bin/env python2.7

import psycopg2
import psycopg2.extras
import psycopg2.extensions

from   env       import *

## Exportable classes

class OADao(object):
    """Wrapper around psycopg2 with additional functionality
    for logging, connection management and sql execution"""
    def __init__(self, schema, cdict=True):
        """Schema refers to the api entity we're referring
        to: auth, trading etc"""
        self.cdict  = cdict
        self.schema = schema
        self.__dbinfo = getenv().dbinfo
        self.dbinfo = self.__dbinfo
        self.__enter__()

    def __enter__(self):
        self.dbconn = psycopg2.connect(dbname=self.__dbinfo['dbname'],
                                       user=self.__dbinfo['user'],
                                       host=self.__dbinfo['host'],
                                       port=self.__dbinfo['port'])
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def commit(self):
        """Proxy method for committing dbconnection actions"""
        self.dbconn.commit()

    def close(self):
        """Proxy method for closing dbconnection"""
        self.dbconn.close()

    def rollback(self):
        """Proxy method for rolling back any existing action"""
        self.dbconn.rollback()

    @property
    def cur(self):
        if self.cdict:
            cursor = self.dbconn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        else:
            cursor = self.dbconn.cursor()
        cursor.execute("SET search_path TO %s", [self.schema])
        return cursor

    @property
    def isolation(self):
        return self._isolation_level
    @isolation.setter
    def isolation(self, value):
        self.dbconn.set_isolation_level(value)

    class Isolation(object):
        READCMT = psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED
        READRPT = psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ
        SERIAL  = psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE

<|endoftext|>


<commit_before>import json
import sys
import csv
import math

def read_csv(csv_path):
    """
    Read flat csv file, first row are headers
    Return file contents as json {1:{header1:value1,...},2:}
    """

    print('Reading file %s\n' % csv_path)
    with open(csv_path,'r') as csv_file:
        reader = csv.reader(csv_file, delimiter=',', quotechar='"')
        row_num=0
        out={}
        for row in reader:
            if row_num == 0:
                head=row;
            else:
                out[row_num]={}
                for header, value in zip (head, row):
                     out[row_num][header]=value
            row_num = row_num + 1

        return(out)

def json2kml(s,kml_path):

    with open(kml_path,'w') as kml:
        with open('src/vis/partial1.kml','r') as part:
            for line in part:
               kml.write(line)

        kml.write('<Folder>\n')
        kml.write('<name>Detection squares</name>\n')

        r = 6378   # Earth radius
        km_lat = 180/(math.pi*r)  # 1km in degrees latitude
        sq_size_km = 1.0   # square size

        for p in s:
            latitude=s[p]['latitude']
            longitude=s[p]['longitude']
            acq_date=s[p]['acq_date']
            acq_time=s[p]['acq_time']
            satellite=s[p].get('satellite','Not available')
            instrument=s[p].get('instrument','Not available')
            confidence=s[p].get('confidence','Not available')
            frp=s[p].get('frp','Not available')

            latitude=float(latitude)
            longitude=float(longitude)
            confidence=float(confidence)
            frp=float(frp)
            timestamp=acq_date + 'T' + acq_time[0:2] + ':' + acq_time[2:4] + 'Z'
            timedescr=acq_date + ' ' + acq_time[0:2] + ':' + acq_time[2:4] + ' UTC'

            print([longitude,latitude,acq_date,acq_time,satellite,instrument,confidence,frp])

            kml.write('<Placemark>\n<name>Fire detection square</name>\n')
            kml.write('<description>\nlongitude:  %s\n' % longitude
                                  +  'latitude:   %s\n' % latitude
                                  +  'time:       %s\n' % timedescr
                                  +  'satellite:  %s\n' % satellite
                                  +  'instrument: %s\n' % instrument
                                  +  'confidence: %s\n' % confidence
                                  +  'FRP:        %s\n' % frp
                    + '</description>\n')
            kml.write('<TimeStamp>%s</TimeStamp>\n' % timestamp)
            if confidence < 30:
                kml.write('<styleUrl> modis_conf_low </styleUrl>\n')
            elif confidence < 80:
                kml.write('<styleUrl> modis_conf_med </styleUrl>\n')
            else:
                kml.write('<styleUrl> modis_conf_high </styleUrl>\n')
            kml.write('<Polygon>\n<outerBoundaryIs>\n<LinearRing>\n<coordinates>\n')

	    km_lon=km_lat/math.cos(latitude*math.pi/180)  # 1 km in longitude
            sq2_lat=km_lat * sq_size_km/2;
            sq2_lon=km_lon * sq_size_km/2;
            kml.write('%s,%s,0\n' % (longitude - sq2_lon, latitude-sq2_lat))
            kml.write('%s,%s,0\n' % (longitude - sq2_lon, latitude+sq2_lat))
            kml.write('%s,%s,0\n' % (longitude + sq2_lon, latitude+sq2_lat))
            kml.write('%s,%s,0\n' % (longitude + sq2_lon, latitude-sq2_lat))
            kml.write('%s,%s,0\n' % (longitude - sq2_lon, latitude-sq2_lat))

            kml.write('</coordinates>\n</LinearRing>\n</outerBoundaryIs>\n</Polygon>\n</Placemark>\n')

        kml.write('</Folder>\n')
        kml.write('</Document>\n</kml>\n')

    print('Created file %s\n' % kml_path)

if __name__ == '__main__':

    if len(sys.argv) < 3 or not sys.argv[2]:
        print('usage: csv2kml.sh csv_file_path kml_file_path')
        #print('usage: python csv2kml.py csv_file_path kml_file_path')
        sys.exit(1)

    csv_file_path=sys.argv[1]
    kml_file_path=sys.argv[2]

    s = read_csv(csv_file_path)
    json2kml(s,kml_file_path)

    exit(0)
<commit_msg>open csv with universal newline mode<commit_after>import json
import sys
import csv
import math

def read_csv(csv_path):
    """
    Read flat csv file, first row are headers
    Return file contents as json {1:{header1:value1,...},2:}
    """

    print('Reading file %s\n' % csv_path)
    with open(csv_path,'rU') as csv_file:
        reader = csv.reader(csv_file, delimiter=',', quotechar='"')
        row_num=0
        out={}
        for row in reader:
            if row_num == 0:
                head=row;
            else:
                out[row_num]={}
                for header, value in zip (head, row):
                     out[row_num][header]=value
            row_num = row_num + 1

        return(out)

def json2kml(s,kml_path):

    with open(kml_path,'w') as kml:
        with open('src/vis/partial1.kml','r') as part:
            for line in part:
               kml.write(line)

        kml.write('<Folder>\n')
        kml.write('<name>Detection squares</name>\n')

        r = 6378   # Earth radius
        km_lat = 180/(math.pi*r)  # 1km in degrees latitude
        sq_size_km = 1.0   # square size

        for p in s:
            latitude=s[p]['latitude']
            longitude=s[p]['longitude']
            acq_date=s[p]['acq_date']
            acq_time=s[p]['acq_time']
            satellite=s[p].get('satellite','Not available')
            instrument=s[p].get('instrument','Not available')
            confidence=s[p].get('confidence','Not available')
            frp=s[p].get('frp','Not available')

            latitude=float(latitude)
            longitude=float(longitude)
            confidence=float(confidence)
            frp=float(frp)
            timestamp=acq_date + 'T' + acq_time[0:2] + ':' + acq_time[2:4] + 'Z'
            timedescr=acq_date + ' ' + acq_time[0:2] + ':' + acq_time[2:4] + ' UTC'

            print([longitude,latitude,acq_date,acq_time,satellite,instrument,confidence,frp])

            kml.write('<Placemark>\n<name>Fire detection square</name>\n')
            kml.write('<description>\nlongitude:  %s\n' % longitude
                                  +  'latitude:   %s\n' % latitude
                                  +  'time:       %s\n' % timedescr
                                  +  'satellite:  %s\n' % satellite
                                  +  'instrument: %s\n' % instrument
                                  +  'confidence: %s\n' % confidence
                                  +  'FRP:        %s\n' % frp
                    + '</description>\n')
            kml.write('<TimeStamp>%s</TimeStamp>\n' % timestamp)
            if confidence < 30:
                kml.write('<styleUrl> modis_conf_low </styleUrl>\n')
            elif confidence < 80:
                kml.write('<styleUrl> modis_conf_med </styleUrl>\n')
            else:
                kml.write('<styleUrl> modis_conf_high </styleUrl>\n')
            kml.write('<Polygon>\n<outerBoundaryIs>\n<LinearRing>\n<coordinates>\n')

	    km_lon=km_lat/math.cos(latitude*math.pi/180)  # 1 km in longitude
            sq2_lat=km_lat * sq_size_km/2;
            sq2_lon=km_lon * sq_size_km/2;
            kml.write('%s,%s,0\n' % (longitude - sq2_lon, latitude-sq2_lat))
            kml.write('%s,%s,0\n' % (longitude - sq2_lon, latitude+sq2_lat))
            kml.write('%s,%s,0\n' % (longitude + sq2_lon, latitude+sq2_lat))
            kml.write('%s,%s,0\n' % (longitude + sq2_lon, latitude-sq2_lat))
            kml.write('%s,%s,0\n' % (longitude - sq2_lon, latitude-sq2_lat))

            kml.write('</coordinates>\n</LinearRing>\n</outerBoundaryIs>\n</Polygon>\n</Placemark>\n')

        kml.write('</Folder>\n')
        kml.write('</Document>\n</kml>\n')

    print('Created file %s\n' % kml_path)

if __name__ == '__main__':

    if len(sys.argv) < 3 or not sys.argv[2]:
        print('usage: csv2kml.sh csv_file_path kml_file_path')
        #print('usage: python csv2kml.py csv_file_path kml_file_path')
        sys.exit(1)

    csv_file_path=sys.argv[1]
    kml_file_path=sys.argv[2]

    s = read_csv(csv_file_path)
    json2kml(s,kml_file_path)

    exit(0)
<|endoftext|>


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

"""
Miscellaneous utility functions and classes.
"""

from functools import wraps
from heapq import heappush, heapreplace

from whoosh.support.bitvector import BitVector

# Functions

_fib_cache = {}
def fib(n):
    """Returns the nth value in the Fibonacci sequence."""

    if n <= 2: return n
    if n in _fib_cache: return _fib_cache[n]
    result = fib(n - 1) + fib(n - 2)
    _fib_cache[n] = result
    return result

def permute(ls):
    """Yields all permutations of a list."""

    if len(ls) == 1:
        yield ls
    else:
        for i in range(len(ls)):
            this = ls[i]
            rest = ls[:i] + ls[i+1:]
            for p in permute(rest):
                yield [this] + p

def first_diff(a, b):
    """Returns the position of the first differing character in the strings
    a and b. For example, first_diff('render', 'rending') == 4. This
    function limits the return value to 255 so the difference can be encoded
    in a single byte.
    """

    i = -1
    for i in xrange(0, len(a)):
        if a[i] != b[1]:
            return i
        if i == 255: return i
    return i + 1

def prefix_encode(a, b):
    """Compresses string b as an integer (encoded in a byte) representing
    the prefix it shares with a, followed by the suffix encoded as UTF-8.
    """
    i = first_diff(a, b)
    return chr(i) + b[i:].encode("utf8")

def prefix_encode_all(ls):
    """Compresses the given list of (unicode) strings by storing each string
    (except the first one) as an integer (encoded in a byte) representing
    the prefix it shares with its predecessor, followed by the suffix encoded
    as UTF-8.
    """

    last = u''
    for w in ls:
        i = first_diff(last, w)
        yield chr(i) + w[i:].encode("utf8")
        last = w

def prefix_decode_all(ls):
    """Decompresses a list of strings compressed by prefix_encode().
    """

    last = u''
    for w in ls:
        i = ord(w[0])
        decoded = last[:i] + w[1:].decode("utf8")
        yield decoded
        last = decoded

# Classes

class TopDocs(object):
    """This is like a list that only remembers the top N values that are added
    to it. This increases efficiency when you only want the top N values, since
    you don't have to sort most of the values (once the object reaches capacity
    and the next item to consider has a lower score than the lowest item in the
    collection, you can just throw it away).

    The reason we use this instead of heapq.nlargest is this object keeps
    track of all docnums that were added, even if they're not in the "top N".
    """

    def __init__(self, capacity, max_doc, docvector = None):
        self.capacity = capacity
        self.docs = docvector or BitVector(max_doc)
        self.heap = []
        self._total = 0

    def __len__(self):
        return len(self.sorted)

    def add_all(self, sequence):
        heap = self.heap
        docs = self.docs
        capacity = self.capacity

        subtotal = 0
        for docnum, score in sequence:
            docs.set(docnum)
            subtotal += 1

            if len(heap) >= capacity:
                if score <= heap[0][0]:
                    continue
                else:
                    heapreplace(heap, (score, docnum))
            else:
                heappush(heap, (score, docnum))

        self._total += subtotal

    def total(self):
        return self._total

    def best(self):
        """
        Returns the "top N" items. Note that this call
        involves sorting and reversing the internal queue, so you may
        want to cache the results rather than calling this method
        multiple times.
        """

        # Throw away the score and just return a list of items
        return [(item, score) for score, item in reversed(sorted(self.heap))]

# Mix-in for objects with a close() method that allows them to be
# used as a context manager.

class ClosableMixin(object):
    """Mix-in for classes with a close() method to allow them to be
    used as a context manager.
    """

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        self.close()

def protected(func):
    """Decorator for storage-access methods. This decorator
    (a) checks if the object has already been closed, and
    (b) synchronizes on a threading lock. The parent object must
    have 'is_closed' and '_sync_lock' attributes.
    """

    @wraps(func)
    def wrapper(self, *args, **kwargs):
        if self.is_closed:
            raise Exception("This object has been closed")
        if self._sync_lock.acquire(False):
            try:
                return func(self, *args, **kwargs)
            finally:
                self._sync_lock.release()
        else:
            raise Exception("Could not acquire sync lock")

    return wrapper

<commit_msg>Changed to make "This is closed" exception message include the repr of the closed object.<commit_after>#===============================================================================
# Copyright 2007 Matt Chaput
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#===============================================================================

"""
Miscellaneous utility functions and classes.
"""

from functools import wraps
from heapq import heappush, heapreplace

from whoosh.support.bitvector import BitVector

# Functions

_fib_cache = {}
def fib(n):
    """Returns the nth value in the Fibonacci sequence."""

    if n <= 2: return n
    if n in _fib_cache: return _fib_cache[n]
    result = fib(n - 1) + fib(n - 2)
    _fib_cache[n] = result
    return result

def permute(ls):
    """Yields all permutations of a list."""

    if len(ls) == 1:
        yield ls
    else:
        for i in range(len(ls)):
            this = ls[i]
            rest = ls[:i] + ls[i+1:]
            for p in permute(rest):
                yield [this] + p

def first_diff(a, b):
    """Returns the position of the first differing character in the strings
    a and b. For example, first_diff('render', 'rending') == 4. This
    function limits the return value to 255 so the difference can be encoded
    in a single byte.
    """

    i = -1
    for i in xrange(0, len(a)):
        if a[i] != b[1]:
            return i
        if i == 255: return i
    return i + 1

def prefix_encode(a, b):
    """Compresses string b as an integer (encoded in a byte) representing
    the prefix it shares with a, followed by the suffix encoded as UTF-8.
    """
    i = first_diff(a, b)
    return chr(i) + b[i:].encode("utf8")

def prefix_encode_all(ls):
    """Compresses the given list of (unicode) strings by storing each string
    (except the first one) as an integer (encoded in a byte) representing
    the prefix it shares with its predecessor, followed by the suffix encoded
    as UTF-8.
    """

    last = u''
    for w in ls:
        i = first_diff(last, w)
        yield chr(i) + w[i:].encode("utf8")
        last = w

def prefix_decode_all(ls):
    """Decompresses a list of strings compressed by prefix_encode().
    """

    last = u''
    for w in ls:
        i = ord(w[0])
        decoded = last[:i] + w[1:].decode("utf8")
        yield decoded
        last = decoded

# Classes

class TopDocs(object):
    """This is like a list that only remembers the top N values that are added
    to it. This increases efficiency when you only want the top N values, since
    you don't have to sort most of the values (once the object reaches capacity
    and the next item to consider has a lower score than the lowest item in the
    collection, you can just throw it away).

    The reason we use this instead of heapq.nlargest is this object keeps
    track of all docnums that were added, even if they're not in the "top N".
    """

    def __init__(self, capacity, max_doc, docvector = None):
        self.capacity = capacity
        self.docs = docvector or BitVector(max_doc)
        self.heap = []
        self._total = 0

    def __len__(self):
        return len(self.sorted)

    def add_all(self, sequence):
        heap = self.heap
        docs = self.docs
        capacity = self.capacity

        subtotal = 0
        for docnum, score in sequence:
            docs.set(docnum)
            subtotal += 1

            if len(heap) >= capacity:
                if score <= heap[0][0]:
                    continue
                else:
                    heapreplace(heap, (score, docnum))
            else:
                heappush(heap, (score, docnum))

        self._total += subtotal

    def total(self):
        return self._total

    def best(self):
        """
        Returns the "top N" items. Note that this call
        involves sorting and reversing the internal queue, so you may
        want to cache the results rather than calling this method
        multiple times.
        """

        # Throw away the score and just return a list of items
        return [(item, score) for score, item in reversed(sorted(self.heap))]

# Mix-in for objects with a close() method that allows them to be
# used as a context manager.

class ClosableMixin(object):
    """Mix-in for classes with a close() method to allow them to be
    used as a context manager.
    """

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        self.close()

def protected(func):
    """Decorator for storage-access methods. This decorator
    (a) checks if the object has already been closed, and
    (b) synchronizes on a threading lock. The parent object must
    have 'is_closed' and '_sync_lock' attributes.
    """

    @wraps(func)
    def wrapper(self, *args, **kwargs):
        if self.is_closed:
            raise Exception("%r has been closed" % self)
        if self._sync_lock.acquire(False):
            try:
                return func(self, *args, **kwargs)
            finally:
                self._sync_lock.release()
        else:
            raise Exception("Could not acquire sync lock")

    return wrapper

<|endoftext|>


<commit_before>#
# Copyright (c) 2004-2005 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/cpl.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#

import sqlite3

class InstanceTable:
    """
    Generic table for assigning id's to a 3-tuple of IDs.
    """
    def __init__(self, db):
        self.db = db

        cu = self.db.cursor()
        cu.execute("""SELECT tbl_name FROM sqlite_master
                      WHERE type='table' or type='view' """)
        tables = [ x[0] for x in cu ]
        if "Instances" not in tables:
            cu.execute("""
            CREATE TABLE Instances(
                instanceId      INTEGER PRIMARY KEY,
                itemId          INTEGER,
                versionId       INTEGER,
                flavorId        INTEGER,
                isRedirect      INTEGER,
                isPresent       INTEGER,
                CONSTRAINT Instances_itemId_fk
                    FOREIGN KEY (itemId) REFERENCES Items(itemId)
                    ON DELETE CASCADE ON UPDATE CASCADE,
                CONSTRAINT Instances_versionId_fk
                    FOREIGN KEY (versionId) REFERENCES Versions(versionId)
                    ON DELETE CASCADE ON UPDATE CASCADE,
                CONSTRAINT Instances_flavorId_fk
                    FOREIGN KEY (flavorId) REFERENCES Flavors(flavorId)
                    ON DELETE RESTRICT ON UPDATE CASCADE,
                CONSTRAINT Instances_item_version_flavor_uq
                    UNIQUE (itemId, versionId, flavorId)
            )""")
            cu.execute("""CREATE UNIQUE INDEX InstancesIdx ON
		               Instances(itemId, versionId, flavorId)""")
        if "InstancesView" not in tables:
            cu.execute("""
            CREATE VIEW
                InstancesView AS
            SELECT
                Instances.instanceId as instanceId,
                Items.item as item,
                Versions.version as version,
                Flavors.flavor as flavor
            FROM
                Instances
            JOIN Items on Instances.itemId = Items.itemId
            JOIN Versions on Instances.versionId = Versions.versionId
            JOIN Flavors on Instances.flavorId = Flavors.flavorId
            """)

    def addId(self, itemId, versionId, flavorId, isRedirect, isPresent = True):
	if isPresent:
	    isPresent = 1
	else:
	    isPresent = 0

	if isRedirect:
	    isRedirect = 1
	else:
	    isRedirect = 0

        cu = self.db.cursor()
        cu.execute("INSERT INTO Instances VALUES (NULL, ?, ?, ?, ?, ?)",
                   (itemId, versionId, flavorId, isRedirect, isPresent))
	return cu.lastrowid

    def getId(self, theId):
        cu = self.db.cursor()
        cu.execute("SELECT itemId, versionId, flavorId, isPresent "
		   "FROM Instances WHERE instanceId=?", theId)
	try:
	    return cu.next()
	except StopIteration:
            raise KeyError, theId

    def isPresent(self, item):
        cu = self.db.cursor()
        cu.execute("SELECT isPresent FROM Instances WHERE "
			"itemId=? AND versionId=? AND flavorId=?", item)

	val = cu.fetchone()
	if not val:
	    return 0

	return val[0]

    def setPresent(self, theId, val):
        cu = self.db.cursor()
	cu.execute("UPDATE Instances SET isPresent=? WHERE instanceId=?",
                   (val, theId))

    def has_key(self, item):
        cu = self.db.cursor()
        cu.execute("SELECT instanceId FROM Instances WHERE "
			"itemId=? AND versionId=? AND flavorId=?", item)
	return not(cu.fetchone() == None)

    def __getitem__(self, item):
        cu = self.db.cursor()
        cu.execute("SELECT instanceId FROM Instances WHERE "
			"itemId=? AND versionId=? AND flavorId=?", item)
	try:
	    return cu.next()[0]
	except StopIteration:
            raise KeyError, item

    def get(self, item, defValue):
        cu = self.db.cursor()
        cu.execute("SELECT instanceId FROM Instances WHERE "
			"itemId=? AND versionId=? AND flavorId=?", item)
	item = cu.fetchone()
	if not item:
	    return defValue
	return item[0]

class FileStreams:
    def __init__(self, db):
        self.db = db
        cu = self.db.cursor()
        cu.execute("SELECT tbl_name FROM sqlite_master WHERE type='table'")
        tables = [ x[0] for x in cu ]
        if 'FileStreams' not in tables:
            cu.execute("""
            CREATE TABLE FileStreams(
                streamId INTEGER PRIMARY KEY,
                fileId BINARY,
                stream BINARY
            )""")
	    # in sqlite 2.8.15, a unique here seems to cause problems
	    # (as the versionId isn't unique, apparently)
	    cu.execute("""CREATE INDEX FileStreamsIdx ON FileStreams(fileId)""")
<commit_msg>add more constraints (not null default 0) on the isPresent and isRedirect columns<commit_after>#
# Copyright (c) 2004-2005 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/cpl.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#

import sqlite3

class InstanceTable:
    """
    Generic table for assigning id's to a 3-tuple of IDs.
    """
    def __init__(self, db):
        self.db = db

        cu = self.db.cursor()
        cu.execute("""SELECT tbl_name FROM sqlite_master
                      WHERE type='table' or type='view' """)
        tables = [ x[0] for x in cu ]
        if "Instances" not in tables:
            cu.execute("""
            CREATE TABLE Instances(
                instanceId      INTEGER PRIMARY KEY,
                itemId          INTEGER,
                versionId       INTEGER,
                flavorId        INTEGER,
                isRedirect      INTEGER NOT NULL DEFAULT 0,
                isPresent       INTEGER NOT NULL DEFAULT 0,
                CONSTRAINT Instances_itemId_fk
                    FOREIGN KEY (itemId) REFERENCES Items(itemId)
                    ON DELETE CASCADE ON UPDATE CASCADE,
                CONSTRAINT Instances_versionId_fk
                    FOREIGN KEY (versionId) REFERENCES Versions(versionId)
                    ON DELETE CASCADE ON UPDATE CASCADE,
                CONSTRAINT Instances_flavorId_fk
                    FOREIGN KEY (flavorId) REFERENCES Flavors(flavorId)
                    ON DELETE RESTRICT ON UPDATE CASCADE
            )""")
            cu.execute(" CREATE UNIQUE INDEX InstancesIdx ON "
                       " Instances(itemId, versionId, flavorId) ")
        if "InstancesView" not in tables:
            cu.execute("""
            CREATE VIEW
                InstancesView AS
            SELECT
                Instances.instanceId as instanceId,
                Items.item as item,
                Versions.version as version,
                Flavors.flavor as flavor
            FROM
                Instances
            JOIN Items on Instances.itemId = Items.itemId
            JOIN Versions on Instances.versionId = Versions.versionId
            JOIN Flavors on Instances.flavorId = Flavors.flavorId
            """)

    def addId(self, itemId, versionId, flavorId, isRedirect, isPresent = True):
	if isPresent:
	    isPresent = 1
	else:
	    isPresent = 0

	if isRedirect:
	    isRedirect = 1
	else:
	    isRedirect = 0

        cu = self.db.cursor()
        cu.execute("INSERT INTO Instances VALUES (NULL, ?, ?, ?, ?, ?)",
                   (itemId, versionId, flavorId, isRedirect, isPresent))
        # XXX: sqlite-ism
	return cu.lastrowid

    def getId(self, theId):
        cu = self.db.cursor()
        cu.execute(" SELECT itemId, versionId, flavorId, isPresent "
		   " FROM Instances WHERE instanceId=? ", theId)
	try:
	    return cu.next()
	except StopIteration:
            raise KeyError, theId

    def isPresent(self, item):
        cu = self.db.cursor()
        cu.execute(" SELECT isPresent FROM Instances WHERE "
                   " itemId=? AND versionId=? AND flavorId=?", item)
	val = cu.fetchone()
	if not val:
	    return 0
	return val[0]

    def setPresent(self, theId, val):
        cu = self.db.cursor()
	cu.execute("UPDATE Instances SET isPresent=? WHERE instanceId=?",
                   (val, theId))

    def has_key(self, item):
        cu = self.db.cursor()
        cu.execute("SELECT instanceId FROM Instances WHERE "
			"itemId=? AND versionId=? AND flavorId=?", item)
	return not(cu.fetchone() == None)

    def __getitem__(self, item):
        cu = self.db.cursor()
        cu.execute("SELECT instanceId FROM Instances WHERE "
			"itemId=? AND versionId=? AND flavorId=?", item)
	try:
	    return cu.next()[0]
	except StopIteration:
            raise KeyError, item

    def get(self, item, defValue):
        cu = self.db.cursor()
        cu.execute("SELECT instanceId FROM Instances WHERE "
			"itemId=? AND versionId=? AND flavorId=?", item)
	item = cu.fetchone()
	if not item:
	    return defValue
	return item[0]

class FileStreams:
    def __init__(self, db):
        self.db = db
        cu = self.db.cursor()
        cu.execute("SELECT tbl_name FROM sqlite_master WHERE type='table'")
        tables = [ x[0] for x in cu ]
        if 'FileStreams' not in tables:
            cu.execute("""
            CREATE TABLE FileStreams(
                streamId INTEGER PRIMARY KEY,
                fileId BINARY,
                stream BINARY
            )""")
	    # in sqlite 2.8.15, a unique here seems to cause problems
	    # (as the versionId isn't unique, apparently)
	    cu.execute("""CREATE INDEX FileStreamsIdx ON FileStreams(fileId)""")
<|endoftext|>


<commit_before>'''
Richards
'''

# based on a Java version:
#  Based on original version written in BCPL by Dr Martin Richards
#  in 1981 at Cambridge University Computer Laboratory, England
#  and a C++ version derived from a Smalltalk version written by
#  L Peter Deutsch.
#  Java version:  Copyright (C) 1995 Sun Microsystems, Inc.
#  Translation from C++, Mario Wolczko
#  Outer loop added by Alex Jacoby

from time import clock

# Task IDs
I_IDLE = 1
I_WORK = 2
I_HANDLERA = 3
I_HANDLERB = 4
I_DEVA = 5
I_DEVB = 6

# Packet types
K_DEV = 1000
K_WORK = 1001

# Packet

BUFSIZE = 4

BUFSIZE_RANGE = range(BUFSIZE)

class Packet(object):

	def __init__(self,link:Packet, ident:int, kind:int):
		self.link = l
		self.ident = i
		self.kind = k
		self.datum = 0
		self.data = []int()
		for x in range(BUFSIZE):
			self.data.append( 0 )

	def append_to(self, lst:Packet) ->Packet:
		self.link = None
		if lst is None:
			return self
		else:
			p = lst
			next = p.link
			while next is not None:
				p = next
				next = p.link
			p.link = self
			return lst

# Task Records

class TaskRec(object):
	pass

class DeviceTaskRec(TaskRec):
	def __init__(self):
		let self.pending : Packet = None

class IdleTaskRec(TaskRec):
	def __init__(self):
		self.control = 1
		self.count = 10000

class HandlerTaskRec(TaskRec):
	def __init__(self):
		let self.work_in   : Packet = None
		let self.device_in : Packet = None

	def workInAdd(self, p:Packet) ->Packet:
		self.work_in = p.append_to(self.work_in)
		return self.work_in

	def deviceInAdd(self, p:Packet) ->Packet:
		self.device_in = p.append_to(self.device_in)
		return self.device_in

class WorkerTaskRec(TaskRec):
	def __init__(self):
		let self.destination : int = I_HANDLERA
		let self.count       : int = 0

# Task

class TaskState(object):
	def __init__(self):
		self.packet_pending = True
		self.task_waiting = False
		self.task_holding = False

	def packetPending(self) -> self:
		self.packet_pending = True
		self.task_waiting = False
		self.task_holding = False
		return self

	def waiting(self) -> self:
		self.packet_pending = False
		self.task_waiting = True
		self.task_holding = False
		return self

	def running(self) -> self:
		self.packet_pending = False
		self.task_waiting = False
		self.task_holding = False
		return self

	def waitingWithPacket(self) -> self:
		self.packet_pending = True
		self.task_waiting = True
		self.task_holding = False
		return self

	def isPacketPending(self) -> bool:
		return self.packet_pending

	def isTaskWaiting(self) -> bool:
		return self.task_waiting

	def isTaskHolding(self) -> bool:
		return self.task_holding

	def isTaskHoldingOrWaiting(self) -> bool:
		return self.task_holding or (not self.packet_pending and self.task_waiting)

	def isWaitingWithPacket(self) -> bool:
		return self.packet_pending and self.task_waiting and not self.task_holding

tracing = False
layout = 0

def trace(a:string):
	global layout
	layout -= 1
	if layout <= 0:
		print()
		layout = 50
	print(a)

class Task(TaskState):

	# note: r:TaskRec is the super class, TODO cast to its subclass.
	def __init__(self,i:int, p:int, w:Packet, initialState:TaskState, r:TaskRec):
		let self.link     : Task = taskWorkArea.task
		let self.ident    : int = i
		let self.priority : int = p
		let self.input    : Packet = w

		let self.packet_pending : bool = initialState.isPacketPending()
		let self.task_waiting   : bool = initialState.isTaskWaiting()
		let self.task_holding   : bool = initialState.isTaskHolding()

		self.handle = r  ## generic - some subclass

		#taskWorkArea.taskList = self
		#taskWorkArea.taskTab[i] = self
		taskWorkArea.set_task(self, i)

	def fn(self, pkt:Packet, r:TaskRec) -> self:
		#raise NotImplementedError  ## could make function abstract in c++ TODO
		print('NotImplementedError')
		print(r)
		return self

	def addPacket(self,p:Packet, old:Task) -> self:
		if self.input is None:
			self.input = p
			self.packet_pending = True
			if self.priority > old.priority:
				return self
		else:
			p.append_to(self.input)
		return old

	def runTask(self) -> self:
		let msg : Packet = None
		if self.isWaitingWithPacket():
			msg = self.input
			self.input = msg.link
			if self.input is None:
				self.running()
			else:
				self.packetPending()

		return self.fn(msg,self.handle)
		#return self.run_fn( msg, self.handle )
		#return self.fn(msg, go.type_assert(self.handle, TaskRec))  ## self.handle is generic (interface{})

	def waitTask(self) -> self:
		self.task_waiting = True
		return self

	def hold(self) -> Task:
		taskWorkArea.holdCount += 1
		self.task_holding = True
		return self.link

	def release(self,i:int) -> self:
		t = self.findtcb(i)
		t.task_holding = False
		if t.priority > self.priority:
			return go.type_assert(t, self)
		else:
			return self

	def qpkt(self, pkt:Packet) -> self:
		t = self.findtcb(pkt.ident)
		taskWorkArea.qpktCount += 1
		pkt.link = None
		pkt.ident = self.ident
		return t.addPacket(pkt,self)

	def findtcb(self,id:int) -> Task:
		t = taskWorkArea.taskTab[id]
		if t is None:
			print('Exception in findtcb')
		return t

# DeviceTask

class DeviceTask(Task):
	def __init__(self,i:int, p:int, w:Packet, s:TaskState, r:TaskRec):
		Task.__init__(self,i,p,w,s,r)

	#######def fn(self,pkt:*Packet, d:TaskRec) -> self:
	def fn(self,pkt:Packet, d:DeviceTaskRec) -> self:
		if pkt is None:
			pkt = d.pending
			if pkt is None:
				return self.waitTask()
			else:
				d.pending = None
				return self.qpkt(pkt)
		else:
			d.pending = pkt
			return self.hold()

class HandlerTask(Task):
	def __init__(self,i:int, p:int, w:Packet, s:TaskState, r:TaskRec):
		Task.__init__(self,i,p,w,s,r)

	def fn(self, pkt:Packet, h:HandlerTaskRec) -> self:
		if pkt is not None:
			if pkt.kind == K_WORK:
				h.workInAdd(pkt)
			else:
				h.deviceInAdd(pkt)
		work = h.work_in
		if work is None:
			return self.waitTask()
		count = work.datum
		if count >= BUFSIZE:
			h.work_in = work.link
			return self.qpkt(work)

		dev = h.device_in
		if dev is None:
			return self.waitTask()

		h.device_in = dev.link
		dev.datum = work.data[count]
		work.datum = count + 1
		return self.qpkt(dev)

# IdleTask

class IdleTask(Task):
	def __init__(self,i:int, p:int, w:Packet, s:TaskState, r:TaskRec):
		Task.__init__(self,i,0,None,s,r)

	def fn(self,pkt:Packet, i:TaskRec) -> self:
		i.count -= 1
		if i.count == 0:
			return self.hold()
		elif i.control & 1 == 0:
			i.control //= 2
			return self.release(I_DEVA)
		else:
			i.control = i.control//2 ^ 0xd008
			return self.release(I_DEVB)

# WorkTask

A = ord('A')

class WorkTask(Task):
	def __init__(self,i:int, p:int, w:Packet, s:TaskState, r:TaskRec):
		Task.__init__(self,i,p,w,s,r)

	def fn(self,pkt:Packet, w:TaskRec) -> self:
		if pkt is None:
			return self.waitTask()

		dest = 0
		if w.destination == I_HANDLERA:
			dest = I_HANDLERB
		else:
			dest = I_HANDLERA

		w.destination = dest
		pkt.ident = dest
		pkt.datum = 0

		for i in BUFSIZE_RANGE: # xrange(BUFSIZE)
			w.count += 1
			if w.count > 26:
				w.count = 1
			pkt.data[i] = A + w.count - 1

		return self.qpkt(pkt)

class TaskWorkArea(object):
	def __init__(self, taskTab:[]Task ):
		let self.task    : Task = None
		self.taskTab   = taskTab
		self.holdCount = 0
		self.qpktCount = 0

	def set_task(self, c:Task, i:int):
		self.task = c
		self.taskTab[i] = c

#global_tasks = []Task(None for i in range(10))
#global_tasks = []Task()
let global_tasks: [10]Task

taskWorkArea = TaskWorkArea(global_tasks)

def schedule():
	t = taskWorkArea.task
	while t is not None:
		#pkt = None
		#if tracing:
		#	print("tcb =",t.ident)

		if t.isTaskHoldingOrWaiting():
			t = t.link
		else:
			###########if tracing: trace(chr(ord("0")+t.ident))
			t = t.runTask()

class Richards(object):

	def run(self, iterations:int) ->bool:
		for i in range(iterations):
			taskWorkArea.holdCount = 0
			taskWorkArea.qpktCount = 0

			#IdleTask(I_IDLE, 1, 10000, TaskState().running(), IdleTaskRec())  ##??
			IdleTask(I_IDLE, 1, None, TaskState().running(), IdleTaskRec())

			wkq = Packet(None, 0, K_WORK)
			wkq = Packet(wkq , 0, K_WORK)
			WorkTask(I_WORK, 1000, wkq, TaskState().waitingWithPacket(), WorkerTaskRec())

			wkq = Packet(None, I_DEVA, K_DEV)
			wkq = Packet(wkq , I_DEVA, K_DEV)
			wkq = Packet(wkq , I_DEVA, K_DEV)
			HandlerTask(I_HANDLERA, 2000, wkq, TaskState().waitingWithPacket(), HandlerTaskRec())

			wkq = Packet(None, I_DEVB, K_DEV)
			wkq = Packet(wkq , I_DEVB, K_DEV)
			wkq = Packet(wkq , I_DEVB, K_DEV)
			HandlerTask(I_HANDLERB, 3000, wkq, TaskState().waitingWithPacket(), HandlerTaskRec())

			wkq = None;
			DeviceTask(I_DEVA, 4000, wkq, TaskState().waiting(), DeviceTaskRec());
			DeviceTask(I_DEVB, 5000, wkq, TaskState().waiting(), DeviceTaskRec());

			schedule()

			if taskWorkArea.holdCount == 9297 and taskWorkArea.qpktCount == 23246:
				pass
			else:
				return False

		return True

def entry_point(iterations:int) ->float64:
	r = Richards()
	startTime = clock()
	result = r.run(iterations)
	if not result:
		print('#ERROR incorrect results!')
	return clock() - startTime

def main():
	iterations=10
	#print("#Richards benchmark (Python) starting. iterations="+str(iterations))
	total_s = entry_point(iterations)
	#print("#Total time for %s iterations: %s secs" %(iterations,total_s))
	s = total_s / float64(iterations)
	#print("#Average seconds per iteration:", s)
	print(s)
<commit_msg>fixing richards benchmark typed version<commit_after>'''
Richards
'''

# based on a Java version:
#  Based on original version written in BCPL by Dr Martin Richards
#  in 1981 at Cambridge University Computer Laboratory, England
#  and a C++ version derived from a Smalltalk version written by
#  L Peter Deutsch.
#  Java version:  Copyright (C) 1995 Sun Microsystems, Inc.
#  Translation from C++, Mario Wolczko
#  Outer loop added by Alex Jacoby

from time import clock

# Task IDs
I_IDLE = 1
I_WORK = 2
I_HANDLERA = 3
I_HANDLERB = 4
I_DEVA = 5
I_DEVB = 6

# Packet types
K_DEV = 1000
K_WORK = 1001

# Packet

macro('#define BUFSIZE 4')

BUFSIZE_RANGE = range(BUFSIZE)

class Packet(object):

	def __init__(self,link:Packet, ident:int, kind:int):
		self.link = link
		self.ident = ident
		self.kind = kind
		let self.datum:int = 0
		let self.data : [BUFSIZE]int

	def append_to(self, lst:Packet) ->Packet:
		self.link = None
		if lst is None:
			return self
		else:
			p = lst
			next = p.link
			while next is not None:
				p = next
				next = p.link
			p.link = self
			return lst

# Task Records

class TaskRec(object):
	pass

class DeviceTaskRec(TaskRec):
	def __init__(self):
		let self.pending : Packet = None

class IdleTaskRec(TaskRec):
	def __init__(self):
		self.control = 1
		self.count = 10000

class HandlerTaskRec(TaskRec):
	def __init__(self):
		let self.work_in   : Packet = None
		let self.device_in : Packet = None

	def workInAdd(self, p:Packet) ->Packet:
		self.work_in = p.append_to(self.work_in)
		return self.work_in

	def deviceInAdd(self, p:Packet) ->Packet:
		self.device_in = p.append_to(self.device_in)
		return self.device_in

class WorkerTaskRec(TaskRec):
	def __init__(self):
		let self.destination : int = I_HANDLERA
		let self.count       : int = 0

# Task

class TaskState(object):
	def __init__(self):
		let self.packet_pending:bool = True
		let self.task_waiting:bool   = False
		let self.task_holding:bool   = False

	def packetPending(self) -> self:
		self.packet_pending = True
		self.task_waiting = False
		self.task_holding = False
		return self

	def waiting(self) -> self:
		self.packet_pending = False
		self.task_waiting = True
		self.task_holding = False
		return self

	def running(self) -> self:
		self.packet_pending = False
		self.task_waiting = False
		self.task_holding = False
		return self

	def waitingWithPacket(self) -> self:
		self.packet_pending = True
		self.task_waiting = True
		self.task_holding = False
		return self

	def isPacketPending(self) -> bool:
		return self.packet_pending

	def isTaskWaiting(self) -> bool:
		return self.task_waiting

	def isTaskHolding(self) -> bool:
		return self.task_holding

	def isTaskHoldingOrWaiting(self) -> bool:
		return self.task_holding or (not self.packet_pending and self.task_waiting)

	def isWaitingWithPacket(self) -> bool:
		return self.packet_pending and self.task_waiting and not self.task_holding

tracing = False
layout = 0

def trace(a:string):
	global layout
	layout -= 1
	if layout <= 0:
		print()
		layout = 50
	print(a)

class Task(TaskState):

	# note: r:TaskRec is the super class, TODO cast to its subclass.
	def __init__(self,i:int, p:int, w:Packet, initialState:TaskState, r:TaskRec):
		let self.link     : Task = taskWorkArea.task
		let self.ident    : int = i
		let self.priority : int = p
		let self.input    : Packet = w

		let self.packet_pending : bool = initialState.isPacketPending()
		let self.task_waiting   : bool = initialState.isTaskWaiting()
		let self.task_holding   : bool = initialState.isTaskHolding()

		self.handle = r  ## generic - some subclass

		#taskWorkArea.taskList = self
		#taskWorkArea.taskTab[i] = self
		taskWorkArea.set_task(self, i)

	def fn(self, pkt:Packet, r:TaskRec) -> self:
		#raise NotImplementedError  ## could make function abstract in c++ TODO
		print('NotImplementedError')
		print(r)
		return self

	def addPacket(self,p:Packet, old:Task) -> self:
		if self.input is None:
			self.input = p
			self.packet_pending = True
			if self.priority > old.priority:
				return self
		else:
			p.append_to(self.input)
		return old

	def runTask(self) -> self:
		let msg : Packet = None
		if self.isWaitingWithPacket():
			msg = self.input
			self.input = msg.link
			if self.input is None:
				self.running()
			else:
				self.packetPending()

		return self.fn(msg,self.handle)
		#return self.run_fn( msg, self.handle )
		#return self.fn(msg, go.type_assert(self.handle, TaskRec))  ## self.handle is generic (interface{})

	def waitTask(self) -> self:
		self.task_waiting = True
		return self

	def hold(self) -> Task:
		taskWorkArea.holdCount += 1
		self.task_holding = True
		return self.link

	def release(self,i:int) -> self:
		t = self.findtcb(i)
		t.task_holding = False
		if t.priority > self.priority:
			return t
		else:
			return self

	def qpkt(self, pkt:Packet) -> self:
		t = self.findtcb(pkt.ident)
		taskWorkArea.qpktCount += 1
		pkt.link = None
		pkt.ident = self.ident
		return t.addPacket(pkt,self)

	def findtcb(self,id:int) -> Task:
		t = taskWorkArea.taskTab[id]
		if t is None:
			print('Exception in findtcb')
		return t

# DeviceTask

class DeviceTask(Task):
	def __init__(self,i:int, p:int, w:Packet, s:TaskState, r:TaskRec):
		Task.__init__(self,i,p,w,s,r)

	#######def fn(self,pkt:*Packet, d:TaskRec) -> self:
	def fn(self,pkt:Packet, d:DeviceTaskRec) -> self:
		if pkt is None:
			pkt = d.pending
			if pkt is None:
				return self.waitTask()
			else:
				d.pending = None
				return self.qpkt(pkt)
		else:
			d.pending = pkt
			return self.hold()

class HandlerTask(Task):
	def __init__(self,i:int, p:int, w:Packet, s:TaskState, r:TaskRec):
		Task.__init__(self,i,p,w,s,r)

	def fn(self, pkt:Packet, h:HandlerTaskRec) -> self:
		if pkt is not None:
			if pkt.kind == K_WORK:
				h.workInAdd(pkt)
			else:
				h.deviceInAdd(pkt)
		work = h.work_in
		if work is None:
			return self.waitTask()
		count = work.datum
		if count >= BUFSIZE:
			h.work_in = work.link
			return self.qpkt(work)

		dev = h.device_in
		if dev is None:
			return self.waitTask()

		h.device_in = dev.link
		dev.datum = work.data[count]
		work.datum = count + 1
		return self.qpkt(dev)

# IdleTask

class IdleTask(Task):
	def __init__(self,i:int, p:int, w:Packet, s:TaskState, r:TaskRec):
		Task.__init__(self,i,0,None,s,r)

	def fn(self,pkt:Packet, i:TaskRec) -> self:
		i.count -= 1
		if i.count == 0:
			return self.hold()
		elif i.control & 1 == 0:
			i.control //= 2
			return self.release(I_DEVA)
		else:
			i.control = i.control//2 ^ 0xd008
			return self.release(I_DEVB)

# WorkTask

A = ord('A')

class WorkTask(Task):
	def __init__(self,i:int, p:int, w:Packet, s:TaskState, r:TaskRec):
		Task.__init__(self,i,p,w,s,r)

	def fn(self,pkt:Packet, w:TaskRec) -> self:
		if pkt is None:
			return self.waitTask()

		dest = 0
		if w.destination == I_HANDLERA:
			dest = I_HANDLERB
		else:
			dest = I_HANDLERA

		w.destination = dest
		pkt.ident = dest
		pkt.datum = 0

		for i in BUFSIZE_RANGE: # xrange(BUFSIZE)
			w.count += 1
			if w.count > 26:
				w.count = 1
			pkt.data[i] = A + w.count - 1

		return self.qpkt(pkt)

class TaskWorkArea(object):
	def __init__(self, taskTab:[]Task ):
		let self.task    : Task = None
		self.taskTab   = taskTab
		let self.holdCount:int = 0
		let self.qpktCount:int = 0

	def set_task(self, c:Task, i:int):
		self.task = c
		self.taskTab[i] = c

#global_tasks = []Task(None for i in range(10))
#global_tasks = []Task()
let global_tasks: [10]Task

taskWorkArea = TaskWorkArea(global_tasks)

def schedule():
	t = taskWorkArea.task
	while t is not None:
		#pkt = None
		#if tracing:
		#	print("tcb =",t.ident)

		if t.isTaskHoldingOrWaiting():
			t = t.link
		else:
			###########if tracing: trace(chr(ord("0")+t.ident))
			t = t.runTask()

class Richards(object):

	def run(self, iterations:int) ->bool:
		for i in range(iterations):
			taskWorkArea.holdCount = 0
			taskWorkArea.qpktCount = 0

			#IdleTask(I_IDLE, 1, 10000, TaskState().running(), IdleTaskRec())  ##??
			IdleTask(I_IDLE, 1, None, TaskState().running(), IdleTaskRec())

			wkq = Packet(None, 0, K_WORK)
			wkq = Packet(wkq , 0, K_WORK)
			WorkTask(I_WORK, 1000, wkq, TaskState().waitingWithPacket(), WorkerTaskRec())

			wkq = Packet(None, I_DEVA, K_DEV)
			wkq = Packet(wkq , I_DEVA, K_DEV)
			wkq = Packet(wkq , I_DEVA, K_DEV)
			HandlerTask(I_HANDLERA, 2000, wkq, TaskState().waitingWithPacket(), HandlerTaskRec())

			wkq = Packet(None, I_DEVB, K_DEV)
			wkq = Packet(wkq , I_DEVB, K_DEV)
			wkq = Packet(wkq , I_DEVB, K_DEV)
			HandlerTask(I_HANDLERB, 3000, wkq, TaskState().waitingWithPacket(), HandlerTaskRec())

			wkq = None;
			DeviceTask(I_DEVA, 4000, wkq, TaskState().waiting(), DeviceTaskRec());
			DeviceTask(I_DEVB, 5000, wkq, TaskState().waiting(), DeviceTaskRec());

			schedule()

			if taskWorkArea.holdCount == 9297 and taskWorkArea.qpktCount == 23246:
				pass
			else:
				return False

		return True

def entry_point(iterations:int) ->double:
	r = Richards()
	startTime = clock()
	result = r.run(iterations)
	if not result:
		print('#ERROR incorrect results!')
	return clock() - startTime

def main():
	iterations=10
	#print("#Richards benchmark (Python) starting. iterations="+str(iterations))
	total_s = entry_point(iterations)
	#print("#Total time for %s iterations: %s secs" %(iterations,total_s))
	s = total_s / iterations
	#print("#Average seconds per iteration:", s)
	print(s)
<|endoftext|>