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

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

from __future__ import print_function

import pdb

import re as mod_re
import logging as mod_logging
import datetime as mod_datetime
import xml.dom.minidom as mod_minidom

try:
    import lxml.etree as mod_etree
except:
    mod_etree = None
    pass # LXML not available

from . import gpx as mod_gpx
from . import utils as mod_utils
from . import gpxfield as mod_gpxfield

class XMLParser:
    """
    Used when lxml is not available. Uses standard minidom.
    """

    def __init__(self, xml):
        self.xml = xml
        self.dom = mod_minidom.parseString(xml)

    def get_first_child(self, node=None, name=None):
        # TODO: Remove find_first_node from utils!
        if not node:
            node = self.dom

        children = node.childNodes
        if not children:
            return None

        if not name:
            return children[0]

        for tmp_node in children:
            if tmp_node.nodeName == name:
                return tmp_node

        return None

    def get_node_name(self, node):
        if not node:
            return None
        return node.nodeName

    def get_children(self, node=None):
        if not node:
            node = self.dom

        return node.childNodes

    def get_node_data(self, node):
        if node is None:
            return None

        child_nodes = self.get_children(node)
        if not child_nodes or len(child_nodes) == 0:
            return None

        return child_nodes[0].nodeValue

    def get_node_attribute(self, node, attribute):
        if (not hasattr(node, 'attributes')) or (not node.attributes):
            return None
        if attribute in node.attributes.keys():
            return node.attributes[attribute].nodeValue
        return None

class LXMLParser:
    """
    Used when lxml is available.
    """

    def __init__(self, xml):
        assert mod_etree

        if mod_utils.PYTHON_VERSION[0] == '3':
            # In python 3 all strings are unicode and for some reason lxml
            # don't like unicode strings with XMLs declared as UTF-8:
            self.xml = xml.encode('utf-8')
        else:
            self.xml = xml

        self.dom = mod_etree.XML(self.xml)
        # get the namespace
        self.ns = self.dom.nsmap.get(None)

    def get_first_child(self, node=None, name=None):
        if node is None:
            if name:
                if self.get_node_name(self.dom) == name:
                    return self.dom
            return self.dom

        children = node.getchildren()

        if not children:
            return None

        if name:
            for node in children:
                if self.get_node_name(node) == name:
                    return node
            return None

        return children[0]

    def get_node_name(self, node):
        if '}' in node.tag:
            return node.tag.split('}')[1]
        return node.tag

    def get_children(self, node=None):
        if node is None:
            node = self.dom
        return node.getchildren()

    def get_node_data(self, node):
        if node is None:
            return None

        return node.text

    def get_node_attribute(self, node, attribute):
        return node.attrib.get(attribute)

class GPXParser:
    def __init__(self, xml_or_file=None, parser=None):
        """
        Parser may be lxml of minidom. If you set to None then lxml will be used if installed
        otherwise minidom.
        """
        self.init(xml_or_file)
        self.gpx = mod_gpx.GPX()
        self.xml_parser_type = parser
        self.xml_parser = None

    def init(self, xml_or_file):
        text = xml_or_file.read() if hasattr(xml_or_file, 'read') else xml_or_file
        self.xml = mod_utils.make_str(text)
        self.gpx = mod_gpx.GPX()

    def parse(self):
        """
        Parses the XML file and returns a GPX object.

        It will throw GPXXMLSyntaxException if the XML file is invalid or
        GPXException if the XML file is valid but something is wrong with the
        GPX data.
        """
        try:
            if self.xml_parser_type is None:
                if mod_etree:
                    self.xml_parser = LXMLParser(self.xml)
                else:
                    self.xml_parser = XMLParser(self.xml)
            elif self.xml_parser_type == 'lxml':
                self.xml_parser = LXMLParser(self.xml)
            elif self.xml_parser_type == 'minidom':
                self.xml_parser = XMLParser(self.xml)
            else:
                raise mod_gpx.GPXException('Invalid parser type: %s' % self.xml_parser_type)

            self.__parse_dom()

            return self.gpx
        except Exception as e:
            # The exception here can be a lxml or minidom exception.
            mod_logging.debug('Error in:\n%s\n-----------\n' % self.xml)
            mod_logging.exception(e)

            # The library should work in the same way regardless of the
            # underlying XML parser that's why the exception thrown
            # here is GPXXMLSyntaxException (instead of simply throwing the
            # original minidom or lxml exception e).
            #
            # But, if the user need the original exception (lxml or minidom)
            # it is available with GPXXMLSyntaxException.original_exception:
            raise mod_gpx.GPXXMLSyntaxException('Error parsing XML: %s' % str(e), e)

    def __parse_dom(self):
        node = self.xml_parser.get_first_child(name='gpx')

        if node is None:
            raise mod_gpx.GPXException('Document must have a `gpx` root node.')

        version = self.xml_parser.get_node_attribute(node, 'version')

        print(version)

        mod_gpxfield.gpx_fields_from_xml(self.gpx, self.xml_parser, node, version)
<commit_msg>NPE fix<commit_after># -*- coding: utf-8 -*-

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

from __future__ import print_function

import pdb

import re as mod_re
import logging as mod_logging
import datetime as mod_datetime
import xml.dom.minidom as mod_minidom

try:
    import lxml.etree as mod_etree
except:
    mod_etree = None
    pass # LXML not available

from . import gpx as mod_gpx
from . import utils as mod_utils
from . import gpxfield as mod_gpxfield

class XMLParser:
    """
    Used when lxml is not available. Uses standard minidom.
    """

    def __init__(self, xml):
        self.xml = xml
        self.dom = mod_minidom.parseString(xml)

    def get_first_child(self, node=None, name=None):
        # TODO: Remove find_first_node from utils!
        if not node:
            node = self.dom

        children = node.childNodes
        if not children:
            return None

        if not name:
            return children[0]

        for tmp_node in children:
            if tmp_node.nodeName == name:
                return tmp_node

        return None

    def get_node_name(self, node):
        if not node:
            return None
        return node.nodeName

    def get_children(self, node=None):
        if not node:
            node = self.dom

        return node.childNodes

    def get_node_data(self, node):
        if node is None:
            return None

        child_nodes = self.get_children(node)
        if not child_nodes or len(child_nodes) == 0:
            return None

        return child_nodes[0].nodeValue

    def get_node_attribute(self, node, attribute):
        if (not hasattr(node, 'attributes')) or (not node.attributes):
            return None
        if attribute in node.attributes.keys():
            return node.attributes[attribute].nodeValue
        return None

class LXMLParser:
    """
    Used when lxml is available.
    """

    def __init__(self, xml):
        assert mod_etree

        if mod_utils.PYTHON_VERSION[0] == '3':
            # In python 3 all strings are unicode and for some reason lxml
            # don't like unicode strings with XMLs declared as UTF-8:
            self.xml = xml.encode('utf-8')
        else:
            self.xml = xml

        self.dom = mod_etree.XML(self.xml)
        # get the namespace
        self.ns = self.dom.nsmap.get(None)

    def get_first_child(self, node=None, name=None):
        if node is None:
            if name:
                if self.get_node_name(self.dom) == name:
                    return self.dom
            return self.dom

        children = node.getchildren()

        if not children:
            return None

        if name:
            for node in children:
                if self.get_node_name(node) == name:
                    return node
            return None

        return children[0]

    def get_node_name(self, node):
        if '}' in node.tag:
            return node.tag.split('}')[1]
        return node.tag

    def get_children(self, node=None):
        if node is None:
            node = self.dom
        return node.getchildren()

    def get_node_data(self, node):
        if node is None:
            return None

        return node.text

    def get_node_attribute(self, node, attribute):
        if node is None:
            return None
        return node.attrib.get(attribute)

class GPXParser:
    def __init__(self, xml_or_file=None, parser=None):
        """
        Parser may be lxml of minidom. If you set to None then lxml will be used if installed
        otherwise minidom.
        """
        self.init(xml_or_file)
        self.gpx = mod_gpx.GPX()
        self.xml_parser_type = parser
        self.xml_parser = None

    def init(self, xml_or_file):
        text = xml_or_file.read() if hasattr(xml_or_file, 'read') else xml_or_file
        self.xml = mod_utils.make_str(text)
        self.gpx = mod_gpx.GPX()

    def parse(self):
        """
        Parses the XML file and returns a GPX object.

        It will throw GPXXMLSyntaxException if the XML file is invalid or
        GPXException if the XML file is valid but something is wrong with the
        GPX data.
        """
        try:
            if self.xml_parser_type is None:
                if mod_etree:
                    self.xml_parser = LXMLParser(self.xml)
                else:
                    self.xml_parser = XMLParser(self.xml)
            elif self.xml_parser_type == 'lxml':
                self.xml_parser = LXMLParser(self.xml)
            elif self.xml_parser_type == 'minidom':
                self.xml_parser = XMLParser(self.xml)
            else:
                raise mod_gpx.GPXException('Invalid parser type: %s' % self.xml_parser_type)

            self.__parse_dom()

            return self.gpx
        except Exception as e:
            # The exception here can be a lxml or minidom exception.
            mod_logging.debug('Error in:\n%s\n-----------\n' % self.xml)
            mod_logging.exception(e)

            # The library should work in the same way regardless of the
            # underlying XML parser that's why the exception thrown
            # here is GPXXMLSyntaxException (instead of simply throwing the
            # original minidom or lxml exception e).
            #
            # But, if the user need the original exception (lxml or minidom)
            # it is available with GPXXMLSyntaxException.original_exception:
            raise mod_gpx.GPXXMLSyntaxException('Error parsing XML: %s' % str(e), e)

    def __parse_dom(self):
        node = self.xml_parser.get_first_child(name='gpx')

        if node is None:
            raise mod_gpx.GPXException('Document must have a `gpx` root node.')

        version = self.xml_parser.get_node_attribute(node, 'version')

        print(version)

        mod_gpxfield.gpx_fields_from_xml(self.gpx, self.xml_parser, node, version)
<|endoftext|>


<commit_before><commit_msg>Cleaning<commit_after><|endoftext|>


<commit_before>from taggit.models import Tag, TaggedItem
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization, DjangoAuthorization
from tastypie import fields
from django.conf.urls import url
from tastypie.utils import dict_strip_unicode_keys, trailing_slash
from django.contrib.contenttypes.models import ContentType
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from django.http.response import HttpResponse
from tastypie import http
from django.utils.text import slugify
import json
from django.db.models import Count

class TagResource(ModelResource):
    name = fields.CharField(attribute='name')
    slug = fields.CharField(attribute='slug')

    class Meta:
        # queryset = Tag.objects.all()
        queryset = Tag.objects.annotate(Count('taggit_taggeditem_items')).order_by('-taggit_taggeditem_items__count')
        resource_name = 'tag'
        filtering = {
            "name": ["exact",],
            "slug": ["exact",]
        }
        allowed_methods = ['get']
        always_return_data = True
        authentication = AnonymousApiKeyAuthentication()
        authorization = DjangoAuthorization()

    def dehydrate(self, bundle):
        try:
            bundle.data["weight"] = bundle.obj.taggit_taggeditem_items__count
        except Exception, e:
            # taggit_taggeditem_items__count may unfortunately not be found ... don't know why
            pass

        return bundle

class TaggedItemResource(ModelResource):
    tag = fields.ToOneField(TagResource, 'tag', full=True)

    class Meta:
        queryset = TaggedItem.objects.all()
        resource_name = 'taggeditem'
        authentication = AnonymousApiKeyAuthentication()
        authorization = DjangoAuthorization()
        default_format = "application/json"
        filtering = {
            "tag" : ALL_WITH_RELATIONS,
            "object_id" : ['exact', ]
        }
        always_return_data = True

    def prepend_urls(self):
        return [
           url(r"^(?P<resource_name>%s)/(?P<content_type>\w+?)/(?P<object_id>\d+?)%s$" % (self._meta.resource_name, trailing_slash()),
               self.wrap_view('dispatch_list'),
               name="api_dispatch_list"),
            url(r"^(?P<resource_name>%s)/(?P<content_type>\w+?)/(?P<object_id>\d+?)/similars%s$" % (self._meta.resource_name, trailing_slash()),
               self.wrap_view('get_similars'),
               name="api_get_similars"),
        ]

    def get_similars(self, request, **kwargs):
        obj = ContentType.objects.get(model=kwargs.pop('content_type')).get_object_for_this_type(id=kwargs["object_id"])
        return HttpResponse(json.dumps([{'id' : o.id, 'type' : ContentType.objects.get_for_model(o).model} for o in obj.tags.similar_objects()]))

    def dispatch_list(self, request, **kwargs):
        self.method_check(request, allowed=['get', 'post'])
        self.is_authenticated(request)
        self.throttle_check(request)

        if 'content_type' in kwargs and 'object_id' in kwargs and request.method=="POST":
            data = json.loads(request.body)
            if 'tag' in data:
                tag_obj, created = Tag.objects.get_or_create(name=data['tag'], slug=slugify(data['tag']))

                params = kwargs.copy()
                del params['resource_name']
                del params['api_name']
                params['tag'] = tag_obj
                params['content_type'] = ContentType.objects.get(model=kwargs['content_type'])

                tagged_item, created = self._meta.queryset.model.objects.get_or_create(**params)

                bundle = self.build_bundle(obj=tagged_item, request=request)
                bundle = self.full_dehydrate(bundle)
                bundle = self.alter_detail_data_to_serialize(request, bundle)

                return self.create_response(request,
                                            bundle,
                                            response_class=http.HttpCreated,
                                            location=self.get_resource_uri(bundle))

        return ModelResource.dispatch_list(self, request, **kwargs)

    def dehydrate(self, bundle):
        bundle.data["object_type_name"] = bundle.obj.content_type.model
        return bundle
<commit_msg>added custom filter on tag resource to get tags for specified content_type<commit_after>from taggit.models import Tag, TaggedItem
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization, DjangoAuthorization
from tastypie import fields
from django.conf.urls import url
from tastypie.utils import dict_strip_unicode_keys, trailing_slash
from django.contrib.contenttypes.models import ContentType
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from django.http.response import HttpResponse
from tastypie import http
from django.utils.text import slugify
import json
from django.db.models import Count

class TagResource(ModelResource):
    name = fields.CharField(attribute='name')
    slug = fields.CharField(attribute='slug')

    class Meta:
        # queryset = Tag.objects.all()
        queryset = Tag.objects.annotate(Count('taggit_taggeditem_items')).order_by('-taggit_taggeditem_items__count')
        resource_name = 'tag'
        filtering = {
            "name": ["exact",],
            "slug": ["exact",]
        }
        allowed_methods = ['get']
        always_return_data = True
        authentication = AnonymousApiKeyAuthentication()
        authorization = DjangoAuthorization()

    def build_filters(self, filters=None):
        if filters is None:
            filters = {}

        orm_filters = super(TagResource, self).build_filters(filters)

        if "content_type" in filters:
            qs = Tag.objects.filter(taggit_taggeditem_items__content_type__model=filters['content_type'])

            orm_filters["pk__in"] = [i.pk for i in qs]

        return orm_filters

    def dehydrate(self, bundle):
        try:
            bundle.data["weight"] = bundle.obj.taggit_taggeditem_items__count
        except Exception, e:
            # taggit_taggeditem_items__count may unfortunately not be found ... don't know why
            pass

        return bundle

class TaggedItemResource(ModelResource):
    tag = fields.ToOneField(TagResource, 'tag', full=True)

    class Meta:
        queryset = TaggedItem.objects.all()
        resource_name = 'taggeditem'
        authentication = AnonymousApiKeyAuthentication()
        authorization = DjangoAuthorization()
        default_format = "application/json"
        filtering = {
            "tag" : ALL_WITH_RELATIONS,
            "object_id" : ['exact', ]
        }
        always_return_data = True

    def prepend_urls(self):
        return [
           url(r"^(?P<resource_name>%s)/(?P<content_type>\w+?)/(?P<object_id>\d+?)%s$" % (self._meta.resource_name, trailing_slash()),
               self.wrap_view('dispatch_list'),
               name="api_dispatch_list"),
            url(r"^(?P<resource_name>%s)/(?P<content_type>\w+?)/(?P<object_id>\d+?)/similars%s$" % (self._meta.resource_name, trailing_slash()),
               self.wrap_view('get_similars'),
               name="api_get_similars"),
        ]

    def get_similars(self, request, **kwargs):
        obj = ContentType.objects.get(model=kwargs.pop('content_type')).get_object_for_this_type(id=kwargs["object_id"])
        return HttpResponse(json.dumps([{'id' : o.id, 'type' : ContentType.objects.get_for_model(o).model} for o in obj.tags.similar_objects()]))

    def dispatch_list(self, request, **kwargs):
        self.method_check(request, allowed=['get', 'post'])
        self.is_authenticated(request)
        self.throttle_check(request)

        if 'content_type' in kwargs and 'object_id' in kwargs and request.method=="POST":
            data = json.loads(request.body)
            if 'tag' in data:
                tag_obj, created = Tag.objects.get_or_create(name=data['tag'], slug=slugify(data['tag']))

                params = kwargs.copy()
                del params['resource_name']
                del params['api_name']
                params['tag'] = tag_obj
                params['content_type'] = ContentType.objects.get(model=kwargs['content_type'])

                tagged_item, created = self._meta.queryset.model.objects.get_or_create(**params)

                bundle = self.build_bundle(obj=tagged_item, request=request)
                bundle = self.full_dehydrate(bundle)
                bundle = self.alter_detail_data_to_serialize(request, bundle)

                return self.create_response(request,
                                            bundle,
                                            response_class=http.HttpCreated,
                                            location=self.get_resource_uri(bundle))

        return ModelResource.dispatch_list(self, request, **kwargs)

    def dehydrate(self, bundle):
        bundle.data["object_type_name"] = bundle.obj.content_type.model
        return bundle
<|endoftext|>


<commit_before>from trakt.objects.core.helpers import update_attributes

class Person(object):
    def __init__(self, client, keys=None, index=None):
        self._client = client

        self.keys = keys
        """
        :type: :class:`~python:list` of :class:`~python:tuple`

        Keys (for imdb, tvdb, etc..), defined as:

        ..code-block::

            [
                (<service>, <id>)
            ]

        """

        self.index = index
        """
        :type: :class:`~python:int`

        Playlist item index
        """

        self.name = None
        """
        :type: :class:`~python:str`

        Name
        """

    @property
    def pk(self):
        """Primary Key (unique identifier for the item)

        Provides the following identifiers (by media type):
         - **movie:** imdb
         - **show:** tvdb
         - **season:** tvdb
         - **episode:** tvdb
         - **custom_list:** trakt
         - **person:** tmdb

        :return: :code:`(<service>, <value>)` or :code:`None` if no primary key is available
        :rtype: :class:`~python:tuple`
        """
        if not self.keys:
            return None

        return self.keys[0]

    def _update(self, info=None, **kwargs):
        if not info:
            return

        update_attributes(self, info, [
            'name'
        ])

    @classmethod
    def _construct(cls, client, keys, info=None, index=None, **kwargs):
        person = cls(client, keys, index=index)
        person._update(info, **kwargs)

        return person

    def __getstate__(self):
        state = self.__dict__

        if hasattr(self, '_client'):
            del state['_client']

        return state

    def __repr__(self):
        if self.name:
            return '<Person %r>' % self.name

        return '<Person>'

    def __str__(self):
        return self.__repr__()
<commit_msg>Added the `Person.listed_at` property<commit_after>from trakt.core.helpers import from_iso8601
from trakt.objects.core.helpers import update_attributes

class Person(object):
    def __init__(self, client, keys=None, index=None):
        self._client = client

        self.keys = keys
        """
        :type: :class:`~python:list` of :class:`~python:tuple`

        Keys (for imdb, tvdb, etc..), defined as:

        ..code-block::

            [
                (<service>, <id>)
            ]

        """

        self.index = index
        """
        :type: :class:`~python:int`

        Playlist item index
        """

        self.name = None
        """
        :type: :class:`~python:str`

        Name
        """

        # Timestamps
        self.listed_at = None
        """
        :type: :class:`~python:datetime.datetime`

        Timestamp of when this item was added to the list (or `None`)
        """

    @property
    def pk(self):
        """Primary Key (unique identifier for the item)

        Provides the following identifiers (by media type):
         - **movie:** imdb
         - **show:** tvdb
         - **season:** tvdb
         - **episode:** tvdb
         - **custom_list:** trakt
         - **person:** tmdb

        :return: :code:`(<service>, <value>)` or :code:`None` if no primary key is available
        :rtype: :class:`~python:tuple`
        """
        if not self.keys:
            return None

        return self.keys[0]

    def _update(self, info=None, **kwargs):
        if not info:
            return

        update_attributes(self, info, [
            'name'
        ])

        # Set timestamps
        if 'listed_at' in info:
            self.listed_at = from_iso8601(info.get('listed_at'))

    @classmethod
    def _construct(cls, client, keys, info=None, index=None, **kwargs):
        person = cls(client, keys, index=index)
        person._update(info, **kwargs)

        return person

    def __getstate__(self):
        state = self.__dict__

        if hasattr(self, '_client'):
            del state['_client']

        return state

    def __repr__(self):
        if self.name:
            return '<Person %r>' % self.name

        return '<Person>'

    def __str__(self):
        return self.__repr__()
<|endoftext|>


<commit_before>from pylab import *
import pandas, cv

logFilePath="/scratch/copterlogs/logs/2012-07-09 10-02 6.log"
startTime=datetime.datetime(2012,07,9)
def loadDataFromLog(logFilePath=logFilePath,dataType='all',startTime=startTime):
    logData={'timestamp':[],'motors_out':np.empty(dtype='int32', shape=(0,4))}
    logFile=open(logFilePath,'r')
    timestampIsCurrent=False
    for logLine in logFile:
        if dataType=='all':
            if logLine.startswith('GPS'):
                logLine=logLine.split(',')
                logData['timestamp'].append(datetime.timedelta(milliseconds=int(logLine[1]))+startTime)
                timestampIsCurrent=True
            elif logLine.startswith('MOT'):
                if timestampIsCurrent:
                    logData['motors_out']=vstack((logData['motors_out'],logLine.split(',')[1:]))
                    #Throw away data until we get another timestamp
                    timestampIsCurrent=False
    logData=pandas.DataFrame(logData['motors_out'],index=logData['timestamp'])
    return(logData)

loadDataFromLog()
<commit_msg>Got to the point where it outputs .pngs with a sliding bar.<commit_after>from pylab import *
import pandas, cv, os

logFilePath="/home/aaron/Mission Planner 1.1.96/logs/2012-07-09 10-02 6.log"
startTime=datetime.datetime(2012,07,9)
def loadDataFromLog(logFilePath=logFilePath,dataType='all',startTime=startTime):
    logData={'timestamp':[],'motors_out':np.empty(dtype='int32', shape=(0,4))}
    logFile=open(logFilePath,'r')
    timestampIsCurrent=False
    for logLine in logFile:
        if dataType=='all':
            if logLine.startswith('GPS'):
                logLine=logLine.split(',')
                logData['timestamp'].append(datetime.timedelta(milliseconds=int(logLine[1]))+startTime)
                timestampIsCurrent=True
            elif logLine.startswith('MOT'):
                if timestampIsCurrent:
                    logData['motors_out']=vstack((logData['motors_out'],logLine.split(',')[1:]))
                    #Throw away data until we get another timestamp
                    timestampIsCurrent=False
    logData=pandas.DataFrame(logData['motors_out'],index=logData['timestamp'],dtype='int32')
    return(logData)

def plotWithTimeBar(logData, timeBarLoc, outputDir='frame'):
    if not os.path.exists(outputDir):
        os.mkdir(outputDir)
    hold(True)
    figure(1,figsize=(800,200),dpi=100,bbox_inches=0)
    logData.plot(subplots=False)
    axvline(timeBarLoc)
    savefig(outputDir+'/'+str(timeBarLoc)+'.png',transparent=True)
    hold(False)

def plotAllFrames(logData):
    for timeStamp in logData.index:
        plotWithTimeBar(logData, timeStamp)

def basicStats(logFilePath=logFilePath):
    pass

<|endoftext|>


<commit_before>from __future__ import unicode_literals
from __future__ import print_function
from collections import OrderedDict
import logging
import multiprocessing
from multiprocessing.pool import Pool
import sys
import time
import traceback

from unittest.signals import registerResult
from unittest import TestCase
import warnings

from green.output import Colors, debug, GreenStream
from green.version import pretty_version
from green.loader import getTests

try: # pragma nocover
    import html
    escape = html.escape
except: # pragma nocover
    import cgi
    escape = cgi.escape

class ProtoTestResult():

    def __init__(self):
        self.shouldStop = False
        # Individual lists
        self.errors              = []
        self.expectedFailures    = []
        self.failures            = []
        self.passing             = []
        self.skipped             = []
        self.unexpectedSuccesses = []

    def spy(self, test_name):
        if sum([len(x) for x in [self.errors, self.expectedFailures, self.failures, self.passing, self.skipped, self.unexpectedSuccesses]]) == 0:
            fh = open('dmp', 'a')
            fh.write(test_name + '\n')
            fh.close()

    def __repr__(self):
        return (
                "errors" + str(self.errors) + ', ' +
                "expectedFailures" + str(self.expectedFailures) + ', ' +
                "failures" + str(self.failures) + ', ' +
                "passing" + str(self.passing) + ', ' +
                "skipped" + str(self.skipped) + ', ' +
                "unexpectedSuccesses" + str(self.unexpectedSuccesses))

    def startTest(self, test):
        "Called before each test runs"

    def stopTest(self, test):
        "Called after each test runs"

    def addSuccess(self, test):
        "Called when a test passed"
        self.passing.append(test)

    def addError(self, test, err):
        "Called when a test raises an exception"
        self.errors.append((test, traceback.format_exception(*err)))

    def addFailure(self, test, err):
        "Called when a test fails a unittest assertion"
        self.failures.append((test, traceback.format_exception(*err)))

    def addSkip(self, test, reason):
        "Called when a test is skipped"
        self.skipped.append((test, reason))

    def addExpectedFailure(self, test, err):
        "Called when a test fails, and we expeced the failure"
        self.expectedFailures.append((test, traceback.format_exception(*err)))

    def addUnexpectedSuccess(self, test):
        "Called when a test passed, but we expected a failure"
        self.unexpectedSuccesses.append(test)

class GreenTestResult():
    "Aggregates test results and outputs them to a stream."

    def __init__(self, stream, descriptions, verbosity, html=False,
            termcolor=None):
        """stream, descriptions, and verbosity are as in
        unittest.runner.TextTestRunner.
        """
        self.stream       = stream
        self.showAll      = verbosity > 1
        self.dots         = verbosity == 1
        self.verbosity    = verbosity
        self.descriptions = descriptions
        self.colors       = Colors(termcolor, html)
        self.last_module  = ''
        self.last_class   = ''
        self.shouldStop   = False
        self.testsRun     = 0
        # Individual lists
        self.errors              = []
        self.expectedFailures    = []
        self.failures            = []
        self.passing             = []
        self.skipped             = []
        self.unexpectedSuccesses = []
        # Combination of all errors and failures
        self.all_errors = []

    def addProto(self, proto):
        if getattr(proto, 'passing', None) == None:
            print(proto)
        else:
            for test, err in proto.errors:
                self.startTest(test)
                self.addError(test, err)
            for test, err in proto.expectedFailures:
                self.startTest(test)
                self.addExpectedFailure(test, err)
            for test, err in proto.failures:
                self.startTest(test)
                self.addFailure(test, err)
            for test in proto.passing:
                self.startTest(test)
                self.addSuccess(test)
            for test, reason in proto.skipped:
                self.startTest(test)
                self.addSkip(test, reason)
            for test in proto.unexpectedSuccesses:
                self.startTest(test)
                self.addUnexpectedSuccess(test)

    def startTestRun(self):
        "Called once before any tests run"
        self.startTime = time.time()
        # Really verbose information
        if self.colors.html:
            self.stream.write(
                    '
')
        if self.verbosity > 2:
            self.stream.writeln(self.colors.bold(pretty_version() + "\n"))

    def stopTestRun(self):
        "Called once after all tests have run"
        self.stopTime = time.time()
        self.timeTaken = self.stopTime - self.startTime
        self.printErrors()
        if self.testsRun:
            self.stream.writeln()
        self.stream.writeln("Ran %s test%s in %ss" %
            (self.colors.bold(str(self.testsRun)),
            self.testsRun != 1 and "s" or "",
            self.colors.bold("%.3f" % self.timeTaken)))
        self.stream.writeln()
        results = [
            (self.errors, 'errors', self.colors.error),
            (self.expectedFailures, 'expected_failures',
                self.colors.expectedFailure),
            (self.failures, 'failures', self.colors.failing),
            (self.passing, 'passes', self.colors.passing),
            (self.skipped, 'skips', self.colors.skipped),
            (self.unexpectedSuccesses, 'unexpected_successes',
                self.colors.unexpectedSuccess),
        ]
        stats = []
        for obj_list, name, color_func in results:
            if obj_list:
                stats.append("{}={}".format(name, color_func(str(len(obj_list)))))
        if not stats:
            self.stream.writeln(self.colors.passing("No Tests Found"))
        else:
            grade = self.colors.passing('OK')
            if self.errors or self.failures:
                grade = self.colors.failing('FAILED')
            self.stream.writeln("{} ({})".format(grade, ', '.join(stats)))
        if self.colors.html:
            self.stream.writeln('
')

    def startTest(self, test):
        "Called before the start of each test"
        self.testsRun += 1

        # Get our bearings
        current_module = test.__module__
        current_class  = test.__class__.__name__

        # Output
        if self.showAll:
            # Module...if it changed.
            if current_module != self.last_module:
                self.stream.writeln(self.colors.moduleName(current_module))
            # Class...if it changed.
            if current_class != self.last_class:
                self.stream.writeln(self.colors.className(
                    self.stream.formatText(current_class, indent=1)))
            # Test name or description
            self.test_output_line = self._testDescription(test)
            if not self.colors.html:
                # In the terminal, we will write a placeholder, and then
                # rewrite it in color after the test has run.
                self.stream.write(
                    self.colors.bold(
                        self.stream.formatLine(self.test_output_line, indent=2)))
            self.stream.flush()

        # Set state for next time
        if current_module != self.last_module:
            self.last_module = current_module
        if current_class != self.last_class:
            self.last_class = current_class

    def stopTest(self, test):
        "Called after the end of each test"

    def _testDescription(self, test):
        return test.shortDescription() or str(test).split()[0]

    def _reportOutcome(self, test, outcome_char, color_func, err=None,
            reason=''):
        if self.showAll:
            # Move the cursor back to the start of the line in terminal mode
            if not self.colors.html:
                self.stream.write('\r')
            # Escape the HTML that may be in the docstring
            if self.colors.html:
                self.test_output_line = escape(self.test_output_line)
            self.stream.write(
                color_func(
                    self.stream.formatLine(
                        self.test_output_line,
                        indent=2,
                        outcome_char=outcome_char)
                )
            )
            if reason:
                self.stream.write(color_func(' -- ' + reason))
            self.stream.writeln()
            self.stream.flush()
        elif self.dots:
            self.stream.write(color_func(outcome_char))
            self.stream.flush()

    def addSuccess(self, test):
        "Called when a test passed"
        self.passing.append(test)
        self._reportOutcome(test, '.', self.colors.passing)

    def addError(self, test, err):
        "Called when a test raises an exception"
        self.errors.append(test)
        self.all_errors.append((test, self.colors.error, 'Error', err))
        self._reportOutcome(test, 'E', self.colors.error, err)

    def addFailure(self, test, err):
        "Called when a test fails a unittest assertion"
        self.failures.append(test)
        self.all_errors.append((test, self.colors.error, 'Failure', err))
        self._reportOutcome(test, 'F', self.colors.failing, err)

    def addSkip(self, test, reason):
        "Called when a test is skipped"
        self.skipped.append(test)
        self._reportOutcome(
                test, 's', self.colors.skipped, reason=reason)

    def addExpectedFailure(self, test, err):
        "Called when a test fails, and we expeced the failure"
        self.expectedFailures.append(test)
        self._reportOutcome(test, 'x', self.colors.expectedFailure, err)

    def addUnexpectedSuccess(self, test):
        "Called when a test passed, but we expected a failure"
        self.unexpectedSuccesses.append(test)
        self._reportOutcome(test, 'u', self.colors.unexpectedSuccess)

    def printErrors(self):
        "Print a list of all tracebacks from errors and failures"
        if not self.all_errors:
            return
        if self.dots:
            self.stream.writeln()
        for (test, color_func, outcome, err) in self.all_errors:
            # Header Line
            self.stream.writeln(
                    '\n' + color_func(outcome) +
                    ' in ' + self.colors.bold(str(test).split()[0]) +
                    ' from ' + str(test).split()[1].strip('()'))

            # Frame Line
            relevant_frames = []
            if issubclass(type(err), Exception) or (type(err) == tuple):
                iterable = enumerate(traceback.format_exception(*err))
            else:
                iterable = enumerate(err)
            for i, frame in iterable:
                debug('\n' + '*' * 30 + "Frame {}:".format(i) + '*' * 30
                      + "\n{}".format(self.colors.yellow(frame)), level = 3)
                # Ignore useless frames
                if self.verbosity < 4:
                    if frame.strip() == "Traceback (most recent call last):":
                        continue
                reindented_lines = []
                # If we're in html, space-based indenting needs to be converted.
                if self.colors.html:
                    for line in frame.split('\n'):
                        frame_indent = 0
                        while line[:2] == '  ':
                            line = line[2:]
                            frame_indent += 1
                        line = self.stream.formatLine(line, indent=frame_indent)
                        reindented_lines.append(line)
                    frame = "\n".join(reindented_lines)
                # Done with this frame, capture it.
                relevant_frames.append(frame)
            self.stream.write(''.join(relevant_frames))

    def wasSuccessful(self):
        "Tells whether or not the overall run was successful"
        return len(self.all_errors) == 0

class LogExceptions(object):

    def __init__(self, callable):
        self.__callable = callable

    def __call__(self, *args, **kwargs):
        try:
            result = self.__callable(*args, **kwargs)
        except Exception:
            # Here we add some debugging help. If multiprocessing's
            # debugging is on, it will arrange to log the traceback
            logger = multiprocessing.get_logger()
            if not logger.handlers:
                logger.addHandler(logging.StreamHandler())
            logger.error(traceback.format_exc())
            logger.handlers[0].flush()
            # Re-raise the original exception so the Pool worker can
            # clean up
            raise

        # It was fine, give a normal answer
        return result

class LoggingPool(Pool):

    def apply_async(self, func, args=(), kwds={}, callback=None):
        return Pool.apply_async(self, LogExceptions(func), args, kwds, callback)

def pool_runner(test_name):
    result = ProtoTestResult()
    try:
        suite = getTests(test_name)
        suite.run(result)
    except:
        err = sys.exc_info()
        result.addError('a test', err)
    return result

def getSuiteDict(item, suite_dict=OrderedDict()):
    if issubclass(type(item), TestCase):
        class_part = item.__module__ + '.' + item.__class__.__name__
        test_part = str(item).split(' ')[0]
        full_test = class_part + '.' + test_part
        if class_part not in suite_dict.keys():
            suite_dict[class_part] = []
        suite_dict[class_part].append(full_test)
    else:
        for i in item:
            getSuiteDict(i, suite_dict)
        return suite_dict

class GreenTestRunner():
    "A test runner class that displays results in Green's clean style."

    def __init__(self, stream=None, descriptions=True, verbosity=1,
                 warnings=None, html=None, termcolor=None, subprocesses=0):
        """
        stream - Any stream passed in will be wrapped in a GreenStream
        """
        if stream is None:
            stream = sys.stderr
        if not issubclass(GreenStream, type(stream)):
            stream = GreenStream(stream)
        self.stream = stream
        self.descriptions = descriptions
        self.verbosity = verbosity
        self.warnings = warnings
        self.html = html
        self.termcolor = termcolor
        self.subprocesses = subprocesses or None

    def run(self, suite):
        "Run the given test case or test suite."
        result = GreenTestResult(
                self.stream, self.descriptions, self.verbosity, html=self.html,
                termcolor=self.termcolor)
        registerResult(result)
        with warnings.catch_warnings():
            if self.warnings:
                # if self.warnings is set, use it to filter all the warnings
                warnings.simplefilter(self.warnings)
                # if the filter is 'default' or 'always', special-case the
                # warnings from the deprecated unittest methods to show them
                # no more than once per module, because they can be fairly
                # noisy.  The -Wd and -Wa flags can be used to bypass this
                # only when self.warnings is None.
                if self.warnings in ['default', 'always']:
                    warnings.filterwarnings('module',
                            category=DeprecationWarning,
                            message='Please use assert\w+ instead.')
            result.startTestRun()

            if self.subprocesses == 1:
                suite.run(result)
            else:
                tests = getSuiteDict(suite)
                pool = LoggingPool(processes=self.subprocesses)
                if tests:
                    for group in tests:
                        for test in tests[group]:
                            pool.apply_async(
                                pool_runner, (test,), callback=result.addProto)
                    pool.close()
                    pool.join()

            result.stopTestRun()

        return result
<commit_msg>Removed unused debugging stuff.<commit_after>from __future__ import unicode_literals
from __future__ import print_function
from collections import OrderedDict
import logging
import multiprocessing
from multiprocessing.pool import Pool
import sys
import time
import traceback

from unittest.signals import registerResult
from unittest import TestCase
import warnings

from green.output import Colors, debug, GreenStream
from green.version import pretty_version
from green.loader import getTests

try: # pragma nocover
    import html
    escape = html.escape
except: # pragma nocover
    import cgi
    escape = cgi.escape

class ProtoTestResult():

    def __init__(self):
        self.shouldStop = False
        # Individual lists
        self.errors              = []
        self.expectedFailures    = []
        self.failures            = []
        self.passing             = []
        self.skipped             = []
        self.unexpectedSuccesses = []

    def __repr__(self): # pragma: no cover
        return (
                "errors" + str(self.errors) + ', ' +
                "expectedFailures" + str(self.expectedFailures) + ', ' +
                "failures" + str(self.failures) + ', ' +
                "passing" + str(self.passing) + ', ' +
                "skipped" + str(self.skipped) + ', ' +
                "unexpectedSuccesses" + str(self.unexpectedSuccesses))

    def startTest(self, test):
        "Called before each test runs"

    def stopTest(self, test):
        "Called after each test runs"

    def addSuccess(self, test):
        "Called when a test passed"
        self.passing.append(test)

    def addError(self, test, err):
        "Called when a test raises an exception"
        self.errors.append((test, traceback.format_exception(*err)))

    def addFailure(self, test, err):
        "Called when a test fails a unittest assertion"
        self.failures.append((test, traceback.format_exception(*err)))

    def addSkip(self, test, reason):
        "Called when a test is skipped"
        self.skipped.append((test, reason))

    def addExpectedFailure(self, test, err):
        "Called when a test fails, and we expeced the failure"
        self.expectedFailures.append((test, traceback.format_exception(*err)))

    def addUnexpectedSuccess(self, test):
        "Called when a test passed, but we expected a failure"
        self.unexpectedSuccesses.append(test)

class GreenTestResult():
    "Aggregates test results and outputs them to a stream."

    def __init__(self, stream, descriptions, verbosity, html=False,
            termcolor=None):
        """stream, descriptions, and verbosity are as in
        unittest.runner.TextTestRunner.
        """
        self.stream       = stream
        self.showAll      = verbosity > 1
        self.dots         = verbosity == 1
        self.verbosity    = verbosity
        self.descriptions = descriptions
        self.colors       = Colors(termcolor, html)
        self.last_module  = ''
        self.last_class   = ''
        self.shouldStop   = False
        self.testsRun     = 0
        # Individual lists
        self.errors              = []
        self.expectedFailures    = []
        self.failures            = []
        self.passing             = []
        self.skipped             = []
        self.unexpectedSuccesses = []
        # Combination of all errors and failures
        self.all_errors = []

    def addProto(self, proto):
        if getattr(proto, 'passing', None) == None:
            print(proto)
        else:
            for test, err in proto.errors:
                self.startTest(test)
                self.addError(test, err)
            for test, err in proto.expectedFailures:
                self.startTest(test)
                self.addExpectedFailure(test, err)
            for test, err in proto.failures:
                self.startTest(test)
                self.addFailure(test, err)
            for test in proto.passing:
                self.startTest(test)
                self.addSuccess(test)
            for test, reason in proto.skipped:
                self.startTest(test)
                self.addSkip(test, reason)
            for test in proto.unexpectedSuccesses:
                self.startTest(test)
                self.addUnexpectedSuccess(test)

    def startTestRun(self):
        "Called once before any tests run"
        self.startTime = time.time()
        # Really verbose information
        if self.colors.html:
            self.stream.write(
                    '
')
        if self.verbosity > 2:
            self.stream.writeln(self.colors.bold(pretty_version() + "\n"))

    def stopTestRun(self):
        "Called once after all tests have run"
        self.stopTime = time.time()
        self.timeTaken = self.stopTime - self.startTime
        self.printErrors()
        if self.testsRun:
            self.stream.writeln()
        self.stream.writeln("Ran %s test%s in %ss" %
            (self.colors.bold(str(self.testsRun)),
            self.testsRun != 1 and "s" or "",
            self.colors.bold("%.3f" % self.timeTaken)))
        self.stream.writeln()
        results = [
            (self.errors, 'errors', self.colors.error),
            (self.expectedFailures, 'expected_failures',
                self.colors.expectedFailure),
            (self.failures, 'failures', self.colors.failing),
            (self.passing, 'passes', self.colors.passing),
            (self.skipped, 'skips', self.colors.skipped),
            (self.unexpectedSuccesses, 'unexpected_successes',
                self.colors.unexpectedSuccess),
        ]
        stats = []
        for obj_list, name, color_func in results:
            if obj_list:
                stats.append("{}={}".format(name, color_func(str(len(obj_list)))))
        if not stats:
            self.stream.writeln(self.colors.passing("No Tests Found"))
        else:
            grade = self.colors.passing('OK')
            if self.errors or self.failures:
                grade = self.colors.failing('FAILED')
            self.stream.writeln("{} ({})".format(grade, ', '.join(stats)))
        if self.colors.html:
            self.stream.writeln('
')

    def startTest(self, test):
        "Called before the start of each test"
        self.testsRun += 1

        # Get our bearings
        current_module = test.__module__
        current_class  = test.__class__.__name__

        # Output
        if self.showAll:
            # Module...if it changed.
            if current_module != self.last_module:
                self.stream.writeln(self.colors.moduleName(current_module))
            # Class...if it changed.
            if current_class != self.last_class:
                self.stream.writeln(self.colors.className(
                    self.stream.formatText(current_class, indent=1)))
            # Test name or description
            self.test_output_line = self._testDescription(test)
            if not self.colors.html:
                # In the terminal, we will write a placeholder, and then
                # rewrite it in color after the test has run.
                self.stream.write(
                    self.colors.bold(
                        self.stream.formatLine(self.test_output_line, indent=2)))
            self.stream.flush()

        # Set state for next time
        if current_module != self.last_module:
            self.last_module = current_module
        if current_class != self.last_class:
            self.last_class = current_class

    def stopTest(self, test):
        "Called after the end of each test"

    def _testDescription(self, test):
        return test.shortDescription() or str(test).split()[0]

    def _reportOutcome(self, test, outcome_char, color_func, err=None,
            reason=''):
        if self.showAll:
            # Move the cursor back to the start of the line in terminal mode
            if not self.colors.html:
                self.stream.write('\r')
            # Escape the HTML that may be in the docstring
            if self.colors.html:
                self.test_output_line = escape(self.test_output_line)
            self.stream.write(
                color_func(
                    self.stream.formatLine(
                        self.test_output_line,
                        indent=2,
                        outcome_char=outcome_char)
                )
            )
            if reason:
                self.stream.write(color_func(' -- ' + reason))
            self.stream.writeln()
            self.stream.flush()
        elif self.dots:
            self.stream.write(color_func(outcome_char))
            self.stream.flush()

    def addSuccess(self, test):
        "Called when a test passed"
        self.passing.append(test)
        self._reportOutcome(test, '.', self.colors.passing)

    def addError(self, test, err):
        "Called when a test raises an exception"
        self.errors.append(test)
        self.all_errors.append((test, self.colors.error, 'Error', err))
        self._reportOutcome(test, 'E', self.colors.error, err)

    def addFailure(self, test, err):
        "Called when a test fails a unittest assertion"
        self.failures.append(test)
        self.all_errors.append((test, self.colors.error, 'Failure', err))
        self._reportOutcome(test, 'F', self.colors.failing, err)

    def addSkip(self, test, reason):
        "Called when a test is skipped"
        self.skipped.append(test)
        self._reportOutcome(
                test, 's', self.colors.skipped, reason=reason)

    def addExpectedFailure(self, test, err):
        "Called when a test fails, and we expeced the failure"
        self.expectedFailures.append(test)
        self._reportOutcome(test, 'x', self.colors.expectedFailure, err)

    def addUnexpectedSuccess(self, test):
        "Called when a test passed, but we expected a failure"
        self.unexpectedSuccesses.append(test)
        self._reportOutcome(test, 'u', self.colors.unexpectedSuccess)

    def printErrors(self):
        "Print a list of all tracebacks from errors and failures"
        if not self.all_errors:
            return
        if self.dots:
            self.stream.writeln()
        for (test, color_func, outcome, err) in self.all_errors:
            # Header Line
            self.stream.writeln(
                    '\n' + color_func(outcome) +
                    ' in ' + self.colors.bold(str(test).split()[0]) +
                    ' from ' + str(test).split()[1].strip('()'))

            # Frame Line
            relevant_frames = []
            if issubclass(type(err), Exception) or (type(err) == tuple):
                iterable = enumerate(traceback.format_exception(*err))
            else:
                iterable = enumerate(err)
            for i, frame in iterable:
                debug('\n' + '*' * 30 + "Frame {}:".format(i) + '*' * 30
                      + "\n{}".format(self.colors.yellow(frame)), level = 3)
                # Ignore useless frames
                if self.verbosity < 4:
                    if frame.strip() == "Traceback (most recent call last):":
                        continue
                reindented_lines = []
                # If we're in html, space-based indenting needs to be converted.
                if self.colors.html:
                    for line in frame.split('\n'):
                        frame_indent = 0
                        while line[:2] == '  ':
                            line = line[2:]
                            frame_indent += 1
                        line = self.stream.formatLine(line, indent=frame_indent)
                        reindented_lines.append(line)
                    frame = "\n".join(reindented_lines)
                # Done with this frame, capture it.
                relevant_frames.append(frame)
            self.stream.write(''.join(relevant_frames))

    def wasSuccessful(self):
        "Tells whether or not the overall run was successful"
        return len(self.all_errors) == 0

class LogExceptions(object):

    def __init__(self, callable):
        self.__callable = callable

    def __call__(self, *args, **kwargs):
        try:
            result = self.__callable(*args, **kwargs)
        except Exception:
            # Here we add some debugging help. If multiprocessing's
            # debugging is on, it will arrange to log the traceback
            logger = multiprocessing.get_logger()
            if not logger.handlers:
                logger.addHandler(logging.StreamHandler())
            logger.error(traceback.format_exc())
            logger.handlers[0].flush()
            # Re-raise the original exception so the Pool worker can
            # clean up
            raise

        # It was fine, give a normal answer
        return result

class LoggingPool(Pool):

    def apply_async(self, func, args=(), kwds={}, callback=None):
        return Pool.apply_async(self, LogExceptions(func), args, kwds, callback)

def pool_runner(test_name):
    result = ProtoTestResult()
    try:
        suite = getTests(test_name)
        suite.run(result)
    except:
        err = sys.exc_info()
        result.addError('a test', err)
    return result

def getSuiteDict(item, suite_dict=OrderedDict()):
    if issubclass(type(item), TestCase):
        class_part = item.__module__ + '.' + item.__class__.__name__
        test_part = str(item).split(' ')[0]
        full_test = class_part + '.' + test_part
        if class_part not in suite_dict.keys():
            suite_dict[class_part] = []
        suite_dict[class_part].append(full_test)
    else:
        for i in item:
            getSuiteDict(i, suite_dict)
        return suite_dict

class GreenTestRunner():
    "A test runner class that displays results in Green's clean style."

    def __init__(self, stream=None, descriptions=True, verbosity=1,
                 warnings=None, html=None, termcolor=None, subprocesses=0):
        """
        stream - Any stream passed in will be wrapped in a GreenStream
        """
        if stream is None:
            stream = sys.stderr
        if not issubclass(GreenStream, type(stream)):
            stream = GreenStream(stream)
        self.stream = stream
        self.descriptions = descriptions
        self.verbosity = verbosity
        self.warnings = warnings
        self.html = html
        self.termcolor = termcolor
        self.subprocesses = subprocesses or None

    def run(self, suite):
        "Run the given test case or test suite."
        result = GreenTestResult(
                self.stream, self.descriptions, self.verbosity, html=self.html,
                termcolor=self.termcolor)
        registerResult(result)
        with warnings.catch_warnings():
            if self.warnings:
                # if self.warnings is set, use it to filter all the warnings
                warnings.simplefilter(self.warnings)
                # if the filter is 'default' or 'always', special-case the
                # warnings from the deprecated unittest methods to show them
                # no more than once per module, because they can be fairly
                # noisy.  The -Wd and -Wa flags can be used to bypass this
                # only when self.warnings is None.
                if self.warnings in ['default', 'always']:
                    warnings.filterwarnings('module',
                            category=DeprecationWarning,
                            message='Please use assert\w+ instead.')
            result.startTestRun()

            if self.subprocesses == 1:
                suite.run(result)
            else:
                tests = getSuiteDict(suite)
                pool = LoggingPool(processes=self.subprocesses)
                if tests:
                    for group in tests:
                        for test in tests[group]:
                            pool.apply_async(
                                pool_runner, (test,), callback=result.addProto)
                    pool.close()
                    pool.join()

            result.stopTestRun()

        return result
<|endoftext|>


<commit_before>__version__ = "1.1.0"
<commit_msg>Bump version number to 1.2.0<commit_after>__version__ = "1.2.0"
<|endoftext|>


<commit_before>
import json

from keen.api import KeenApi, HTTPMethods
from keen import exceptions, utilities
from keen.utilities import KeenKeys, requires_key

class SavedQueriesInterface:

    def __init__(self, api):
        self.api = api
        self.saved_query_url = "{0}/{1}/projects/{2}/queries/saved".format(
            self.api.base_url, self.api.api_version, self.api.project_id
        )

    @requires_key(KeenKeys.MASTER)
    def all(self):
        """
        Gets all saved queries for a project from the Keen IO API.
        Master key must be set.
        """

        response = self._get_json(HTTPMethods.GET, self.saved_query_url, self._get_master_key())

        return response

    @requires_key(KeenKeys.MASTER)
    def get(self, query_name):
        """
        Gets a single saved query for a project from the Keen IO API given a
        query name.
        Master key must be set.
        """

        url = "{0}/{1}".format(self.saved_query_url, query_name)
        response = self._get_json(HTTPMethods.GET, url, self._get_master_key())

        return response

    @requires_key(KeenKeys.READ)
    def results(self, query_name):
        """
        Gets a single saved query with a 'result' object for a project from the
        Keen IO API given a query name.
        Read or Master key must be set.
        """

        url = "{0}/{1}/result".format(self.saved_query_url, query_name)
        response = self._get_json(HTTPMethods.GET, url, self._get_read_key())

        return response

    @requires_key(KeenKeys.MASTER)
    def create(self, query_name, saved_query):
        """
        Creates the saved query via a PUT request to Keen IO Saved Query endpoint.
        Master key must be set.
        """
        url = "{0}/{1}".format(self.saved_query_url, query_name)
        payload = saved_query

        # To support clients that may have already called dumps() to work around how this used to
        # work, make sure it's not a str. Hopefully it's some sort of mapping. When we actually
        # try to send the request, client code will get an InvalidJSONError if payload isn't
        # a json-formatted string.
        if not isinstance(payload, str):
            payload = json.dumps(saved_query)

        response = self._get_json(HTTPMethods.PUT, url, self._get_master_key(), data=payload)
        keen_api._error_handling(response)

        return response

    @requires_key(KeenKeys.MASTER)
    def update(self, query_name, saved_query):
        """
        Updates the saved query via a PUT request to Keen IO Saved Query
        endpoint.
        Master key must be set.
        """

        return self.create(query_name, saved_query)

    @requires_key(KeenKeys.MASTER)
    def delete(self, query_name):
        """
        Deletes a saved query from a project with a query name.
        Master key must be set.
        """

        url = "{0}/{1}".format(self.saved_query_url, query_name)
        response = self._get_json(HTTPMethods.DELETE, url, self._get_master_key())

        return True

    def _get_json(self, http_method, url, key, *args, **kwargs):
        response = self.api.fulfill(http_method, url, headers=utilities.headers(key), *args, **kwargs)
        self.api._error_handling(response)

        try:
            response = response.json()
        except ValueError:
            response = "No JSON available."

        return response

    def _get_read_key(self):
        return self.api.read_key

    def _get_master_key(self):
        return self.api.master_key
<commit_msg>Fix bad merge.<commit_after>
import json

from keen.api import KeenApi, HTTPMethods
from keen import exceptions, utilities
from keen.utilities import KeenKeys, requires_key

class SavedQueriesInterface:

    def __init__(self, api):
        self.api = api
        self.saved_query_url = "{0}/{1}/projects/{2}/queries/saved".format(
            self.api.base_url, self.api.api_version, self.api.project_id
        )

    @requires_key(KeenKeys.MASTER)
    def all(self):
        """
        Gets all saved queries for a project from the Keen IO API.
        Master key must be set.
        """

        response = self._get_json(HTTPMethods.GET, self.saved_query_url, self._get_master_key())

        return response

    @requires_key(KeenKeys.MASTER)
    def get(self, query_name):
        """
        Gets a single saved query for a project from the Keen IO API given a
        query name.
        Master key must be set.
        """

        url = "{0}/{1}".format(self.saved_query_url, query_name)
        response = self._get_json(HTTPMethods.GET, url, self._get_master_key())

        return response

    @requires_key(KeenKeys.READ)
    def results(self, query_name):
        """
        Gets a single saved query with a 'result' object for a project from the
        Keen IO API given a query name.
        Read or Master key must be set.
        """

        url = "{0}/{1}/result".format(self.saved_query_url, query_name)
        response = self._get_json(HTTPMethods.GET, url, self._get_read_key())

        return response

    @requires_key(KeenKeys.MASTER)
    def create(self, query_name, saved_query):
        """
        Creates the saved query via a PUT request to Keen IO Saved Query endpoint.
        Master key must be set.
        """
        url = "{0}/{1}".format(self.saved_query_url, query_name)
        payload = saved_query

        # To support clients that may have already called dumps() to work around how this used to
        # work, make sure it's not a str. Hopefully it's some sort of mapping. When we actually
        # try to send the request, client code will get an InvalidJSONError if payload isn't
        # a json-formatted string.
        if not isinstance(payload, str):
            payload = json.dumps(saved_query)

        response = self._get_json(HTTPMethods.PUT, url, self._get_master_key(), data=payload)

        return response

    @requires_key(KeenKeys.MASTER)
    def update(self, query_name, saved_query):
        """
        Updates the saved query via a PUT request to Keen IO Saved Query
        endpoint.
        Master key must be set.
        """

        return self.create(query_name, saved_query)

    @requires_key(KeenKeys.MASTER)
    def delete(self, query_name):
        """
        Deletes a saved query from a project with a query name.
        Master key must be set.
        """

        url = "{0}/{1}".format(self.saved_query_url, query_name)
        response = self._get_json(HTTPMethods.DELETE, url, self._get_master_key())

        return True

    def _get_json(self, http_method, url, key, *args, **kwargs):
        response = self.api.fulfill(http_method, url, headers=utilities.headers(key), *args, **kwargs)
        self.api._error_handling(response)

        try:
            response = response.json()
        except ValueError:
            response = "No JSON available."

        return response

    def _get_read_key(self):
        return self.api.read_key

    def _get_master_key(self):
        return self.api.master_key
<|endoftext|>


<commit_before># This file is part of Maker Keeper Framework.
#
# Copyright (C) 2017 reverendus
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import typing
from functools import total_ordering, reduce
from decimal import *

@total_ordering
class Wad:
    """Represents a number with 18 decimal places.

    `Wad` implements comparison, addition, subtraction, multiplication and division operators. Comparison, addition,
    subtraction and division only work with other instances of `Wad`. Multiplication works with instances
    of `Wad` and `Ray` and also with `int` numbers. The result of multiplication is always a `Wad`.

    `Wad`, along with `Ray`, are the two basic numeric types used by Maker contracts.

    Notes:
        The internal representation of `Wad` is an unbounded integer, the last 18 digits of it being treated
        as decimal places. It is similar to the representation used in Maker contracts (`uint128`).
    """

    def __init__(self, value):
        """Creates a new Wad number.

        Args:
            value: an instance of `Wad`, `Ray` or an integer. In case of an integer, the internal representation
                of Maker contracts is used which means that passing `1` will create an instance of `Wad`
                with a value of `0.000000000000000001'.
        """
        if isinstance(value, Wad):
            self.value = value.value
        elif isinstance(value, Ray):
            self.value = int((Decimal(value.value) / (Decimal(10)**Decimal(9))).quantize(1, rounding=ROUND_DOWN))
        elif isinstance(value, int):
            # assert(value >= 0)
            self.value = value
        else:
            raise ArithmeticError

    @classmethod
    def from_number(cls, number):
        # assert(number >= 0)
        pwr = Decimal(10) ** 18
        dec = Decimal(str(number)) * pwr
        return Wad(int(dec.quantize(1)))

    def __repr__(self):
        return "Wad(" + str(self.value) + ")"

    def __str__(self):
        tmp = str(self.value).zfill(19)
        return (tmp[0:len(tmp)-18] + "." + tmp[len(tmp)-18:len(tmp)]).replace("-.", "-0.")

    def __add__(self, other):
        if isinstance(other, Wad):
            return Wad(self.value + other.value)
        else:
            raise ArithmeticError

    def __sub__(self, other):
        if isinstance(other, Wad):
            return Wad(self.value - other.value)
        else:
            raise ArithmeticError

    # z = cast((uint256(x) * y + WAD / 2) / WAD);
    def __mul__(self, other):
        if isinstance(other, Wad):
            result = Decimal(self.value) * Decimal(other.value) / (Decimal(10) ** Decimal(18))
            return Wad(int(result.quantize(1, rounding=ROUND_DOWN)))
        elif isinstance(other, Ray):
            result = Decimal(self.value) * Decimal(other.value) / (Decimal(10) ** Decimal(27))
            return Wad(int(result.quantize(1, rounding=ROUND_DOWN)))
        elif isinstance(other, int):
            return Wad(int((Decimal(self.value) * Decimal(other)).quantize(1)))
        else:
            raise ArithmeticError

    def __truediv__(self, other):
        if isinstance(other, Wad):
            return Wad(int((Decimal(self.value) * (Decimal(10) ** Decimal(18)) / Decimal(other.value)).quantize(1, rounding=ROUND_DOWN)))
        else:
            raise ArithmeticError

    def __eq__(self, other):
        if isinstance(other, Wad):
            return self.value == other.value
        else:
            raise ArithmeticError

    def __hash__(self):
        return hash(self.value)

    def __lt__(self, other):
        if isinstance(other, Wad):
            return self.value < other.value
        else:
            raise ArithmeticError

    def __round__(self, ndigits: int = 0):
        return Wad(round(self.value, -18 + ndigits))

    @staticmethod
    def min(*args):
        """Returns the lower of the Wad values"""
        return reduce(lambda x, y: x if x < y else y, args[1:], args[0])

    @staticmethod
    def max(*args):
        """Returns the higher of the Wad values"""
        return reduce(lambda x, y: x if x > y else y, args[1:], args[0])

@total_ordering
class Ray:
    """Represents a number with 27 decimal places.

    `Ray` implements comparison, addition, subtraction, multiplication and division operators. Comparison, addition,
    subtraction and division only work with other instances of `Ray`. Multiplication works with instances
    of `Ray` and `And` and also with `int` numbers. The result of multiplication is always a `Ray`.

    `Ray`, along with `Wad`, are the two basic numeric types used by Maker contracts.

    Notes:
        The internal representation of `Ray` is an unbounded integer, the last 27 digits of it being treated
        as decimal places. It is similar to the representation used in Maker contracts (`uint128`).
    """

    def __init__(self, value):
        """Creates a new Ray number.

        Args:
            value: an instance of `Ray`, `Wad` or an integer. In case of an integer, the internal representation
                of Maker contracts is used which means that passing `1` will create an instance of `Ray`
                with a value of `0.000000000000000000000000001'.
        """
        if isinstance(value, Ray):
            self.value = value.value
        elif isinstance(value, Wad):
            self.value = int((Decimal(value.value) * (Decimal(10)**Decimal(9))).quantize(1))
        elif isinstance(value, int):
            # assert(value >= 0)
            self.value = value
        else:
            raise ArithmeticError

    @classmethod
    def from_number(cls, number):
        assert(number >= 0)
        pwr = Decimal(10) ** 27
        dec = Decimal(str(number)) * pwr
        return Ray(int(dec.quantize(1)))

    def __repr__(self):
        return "Ray(" + str(self.value) + ")"

    def __str__(self):
        tmp = str(self.value).zfill(28)
        return (tmp[0:len(tmp)-27] + "." + tmp[len(tmp)-27:len(tmp)]).replace("-.", "-0.")

    def __add__(self, other):
        if isinstance(other, Ray):
            return Ray(self.value + other.value)
        else:
            raise ArithmeticError

    def __sub__(self, other):
        if isinstance(other, Ray):
            return Ray(self.value - other.value)
        else:
            raise ArithmeticError

    def __mul__(self, other):
        if isinstance(other, Ray):
            result = Decimal(self.value) * Decimal(other.value) / (Decimal(10) ** Decimal(27))
            return Ray(int(result.quantize(1, rounding=ROUND_DOWN)))
        elif isinstance(other, Wad):
            result = Decimal(self.value) * Decimal(other.value) / (Decimal(10) ** Decimal(18))
            return Ray(int(result.quantize(1, rounding=ROUND_DOWN)))
        elif isinstance(other, int):
            return Ray(int((Decimal(self.value) * Decimal(other)).quantize(1)))
        else:
            raise ArithmeticError

    def __truediv__(self, other):
        if isinstance(other, Ray):
            return Ray(int((Decimal(self.value) * (Decimal(10) ** Decimal(27)) / Decimal(other.value)).quantize(1, rounding=ROUND_DOWN)))
        else:
            raise ArithmeticError

    def __eq__(self, other):
        if isinstance(other, Ray):
            return self.value == other.value
        else:
            raise ArithmeticError

    def __hash__(self):
        return hash(self.value)

    def __lt__(self, other):
        if isinstance(other, Ray):
            return self.value < other.value
        else:
            raise ArithmeticError

    def __round__(self, ndigits: int = 0):
        return Ray(round(self.value, -27 + ndigits))

    @staticmethod
    def min(*args):
        """Returns the lower of the Ray values"""
        return reduce(lambda x, y: x if x < y else y, args[1:], args[0])

    @staticmethod
    def max(*args):
        """Returns the higher of the Ray values"""
        return reduce(lambda x, y: x if x > y else y, args[1:], args[0])
<commit_msg>Allowed `Ray`s to be negative<commit_after># This file is part of Maker Keeper Framework.
#
# Copyright (C) 2017 reverendus
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import typing
from functools import total_ordering, reduce
from decimal import *

@total_ordering
class Wad:
    """Represents a number with 18 decimal places.

    `Wad` implements comparison, addition, subtraction, multiplication and division operators. Comparison, addition,
    subtraction and division only work with other instances of `Wad`. Multiplication works with instances
    of `Wad` and `Ray` and also with `int` numbers. The result of multiplication is always a `Wad`.

    `Wad`, along with `Ray`, are the two basic numeric types used by Maker contracts.

    Notes:
        The internal representation of `Wad` is an unbounded integer, the last 18 digits of it being treated
        as decimal places. It is similar to the representation used in Maker contracts (`uint128`).
    """

    def __init__(self, value):
        """Creates a new Wad number.

        Args:
            value: an instance of `Wad`, `Ray` or an integer. In case of an integer, the internal representation
                of Maker contracts is used which means that passing `1` will create an instance of `Wad`
                with a value of `0.000000000000000001'.
        """
        if isinstance(value, Wad):
            self.value = value.value
        elif isinstance(value, Ray):
            self.value = int((Decimal(value.value) / (Decimal(10)**Decimal(9))).quantize(1, rounding=ROUND_DOWN))
        elif isinstance(value, int):
            # assert(value >= 0)
            self.value = value
        else:
            raise ArithmeticError

    @classmethod
    def from_number(cls, number):
        # assert(number >= 0)
        pwr = Decimal(10) ** 18
        dec = Decimal(str(number)) * pwr
        return Wad(int(dec.quantize(1)))

    def __repr__(self):
        return "Wad(" + str(self.value) + ")"

    def __str__(self):
        tmp = str(self.value).zfill(19)
        return (tmp[0:len(tmp)-18] + "." + tmp[len(tmp)-18:len(tmp)]).replace("-.", "-0.")

    def __add__(self, other):
        if isinstance(other, Wad):
            return Wad(self.value + other.value)
        else:
            raise ArithmeticError

    def __sub__(self, other):
        if isinstance(other, Wad):
            return Wad(self.value - other.value)
        else:
            raise ArithmeticError

    # z = cast((uint256(x) * y + WAD / 2) / WAD);
    def __mul__(self, other):
        if isinstance(other, Wad):
            result = Decimal(self.value) * Decimal(other.value) / (Decimal(10) ** Decimal(18))
            return Wad(int(result.quantize(1, rounding=ROUND_DOWN)))
        elif isinstance(other, Ray):
            result = Decimal(self.value) * Decimal(other.value) / (Decimal(10) ** Decimal(27))
            return Wad(int(result.quantize(1, rounding=ROUND_DOWN)))
        elif isinstance(other, int):
            return Wad(int((Decimal(self.value) * Decimal(other)).quantize(1)))
        else:
            raise ArithmeticError

    def __truediv__(self, other):
        if isinstance(other, Wad):
            return Wad(int((Decimal(self.value) * (Decimal(10) ** Decimal(18)) / Decimal(other.value)).quantize(1, rounding=ROUND_DOWN)))
        else:
            raise ArithmeticError

    def __eq__(self, other):
        if isinstance(other, Wad):
            return self.value == other.value
        else:
            raise ArithmeticError

    def __hash__(self):
        return hash(self.value)

    def __lt__(self, other):
        if isinstance(other, Wad):
            return self.value < other.value
        else:
            raise ArithmeticError

    def __round__(self, ndigits: int = 0):
        return Wad(round(self.value, -18 + ndigits))

    @staticmethod
    def min(*args):
        """Returns the lower of the Wad values"""
        return reduce(lambda x, y: x if x < y else y, args[1:], args[0])

    @staticmethod
    def max(*args):
        """Returns the higher of the Wad values"""
        return reduce(lambda x, y: x if x > y else y, args[1:], args[0])

@total_ordering
class Ray:
    """Represents a number with 27 decimal places.

    `Ray` implements comparison, addition, subtraction, multiplication and division operators. Comparison, addition,
    subtraction and division only work with other instances of `Ray`. Multiplication works with instances
    of `Ray` and `And` and also with `int` numbers. The result of multiplication is always a `Ray`.

    `Ray`, along with `Wad`, are the two basic numeric types used by Maker contracts.

    Notes:
        The internal representation of `Ray` is an unbounded integer, the last 27 digits of it being treated
        as decimal places. It is similar to the representation used in Maker contracts (`uint128`).
    """

    def __init__(self, value):
        """Creates a new Ray number.

        Args:
            value: an instance of `Ray`, `Wad` or an integer. In case of an integer, the internal representation
                of Maker contracts is used which means that passing `1` will create an instance of `Ray`
                with a value of `0.000000000000000000000000001'.
        """
        if isinstance(value, Ray):
            self.value = value.value
        elif isinstance(value, Wad):
            self.value = int((Decimal(value.value) * (Decimal(10)**Decimal(9))).quantize(1))
        elif isinstance(value, int):
            # assert(value >= 0)
            self.value = value
        else:
            raise ArithmeticError

    @classmethod
    def from_number(cls, number):
        # assert(number >= 0)
        pwr = Decimal(10) ** 27
        dec = Decimal(str(number)) * pwr
        return Ray(int(dec.quantize(1)))

    def __repr__(self):
        return "Ray(" + str(self.value) + ")"

    def __str__(self):
        tmp = str(self.value).zfill(28)
        return (tmp[0:len(tmp)-27] + "." + tmp[len(tmp)-27:len(tmp)]).replace("-.", "-0.")

    def __add__(self, other):
        if isinstance(other, Ray):
            return Ray(self.value + other.value)
        else:
            raise ArithmeticError

    def __sub__(self, other):
        if isinstance(other, Ray):
            return Ray(self.value - other.value)
        else:
            raise ArithmeticError

    def __mul__(self, other):
        if isinstance(other, Ray):
            result = Decimal(self.value) * Decimal(other.value) / (Decimal(10) ** Decimal(27))
            return Ray(int(result.quantize(1, rounding=ROUND_DOWN)))
        elif isinstance(other, Wad):
            result = Decimal(self.value) * Decimal(other.value) / (Decimal(10) ** Decimal(18))
            return Ray(int(result.quantize(1, rounding=ROUND_DOWN)))
        elif isinstance(other, int):
            return Ray(int((Decimal(self.value) * Decimal(other)).quantize(1)))
        else:
            raise ArithmeticError

    def __truediv__(self, other):
        if isinstance(other, Ray):
            return Ray(int((Decimal(self.value) * (Decimal(10) ** Decimal(27)) / Decimal(other.value)).quantize(1, rounding=ROUND_DOWN)))
        else:
            raise ArithmeticError

    def __eq__(self, other):
        if isinstance(other, Ray):
            return self.value == other.value
        else:
            raise ArithmeticError

    def __hash__(self):
        return hash(self.value)

    def __lt__(self, other):
        if isinstance(other, Ray):
            return self.value < other.value
        else:
            raise ArithmeticError

    def __round__(self, ndigits: int = 0):
        return Ray(round(self.value, -27 + ndigits))

    @staticmethod
    def min(*args):
        """Returns the lower of the Ray values"""
        return reduce(lambda x, y: x if x < y else y, args[1:], args[0])

    @staticmethod
    def max(*args):
        """Returns the higher of the Ray values"""
        return reduce(lambda x, y: x if x > y else y, args[1:], args[0])
<|endoftext|>


<commit_before>from honeybadger import honeybadger
from honeybadger.contrib.aws_lambda import AWSLambdaPlugin
from honeybadger.plugins import default_plugin_manager

honeybadger.configure(api_key='your api key')

def lambda_handler(event, context):
    """
    A buggy lambda function that tries to perform a zero division
    """
    a = 1
    b = 0

    return (a/b)
<commit_msg>Removed Irrelevant imports from example lambda (#76)<commit_after>from honeybadger import honeybadger

honeybadger.configure(api_key='your api key')

def lambda_handler(event, context):
    """
    A buggy lambda function that tries to perform a zero division
    """
    a = 1
    b = 0

    return (a/b)
<|endoftext|>


<commit_before>import struct
from time import time as now
import atexit

event_bin_format = 'llHHI'

# Taken from include/linux/input.h
# https://www.kernel.org/doc/Documentation/input/event-codes.txt
EV_SYN = 0x00
EV_KEY = 0x01
EV_REL = 0x02
EV_ABS = 0x03
EV_MSC = 0x04

class EventDevice(object):
    def __init__(self, path):
        self.path = path
        self._input_file = None
        self._output_file = None

    @property
    def input_file(self):
        if self._input_file is None:
            self._input_file = open(self.path, 'rb')
            atexit.register(self._input_file.close)
        return self._input_file

    @property
    def output_file(self):
        if self._output_file is None:
            self._output_file = open(self.path, 'wb')
            atexit.register(self._output_file.close)
        return self._output_file

    def read_event(self):
        data = self.input_file.read(struct.calcsize(event_bin_format))
        seconds, microseconds, type, code, value = struct.unpack(event_bin_format, data)
        return (seconds + microseconds / 1e6, type, code, value)

    def write_event(self, type, code, value):
        integer, fraction = divmod(now(), 1)
        seconds = int(integer)
        microseconds = int(fraction * 1e6)
        data_event = struct.pack(event_bin_format, seconds, microseconds, type, code, value)

        # Send a sync event to ensure other programs update.
        sync_event = struct.pack(event_bin_format, seconds, microseconds, EV_SYN, 0, 0)

        self.output_file.write(data_event + sync_event)
        self.output_file.flush()<commit_msg>Better nix file handling<commit_after>import struct
from time import time as now
import atexit

event_bin_format = 'llHHI'

# Taken from include/linux/input.h
# https://www.kernel.org/doc/Documentation/input/event-codes.txt
EV_SYN = 0x00
EV_KEY = 0x01
EV_REL = 0x02
EV_ABS = 0x03
EV_MSC = 0x04

class EventDevice(object):
    def __init__(self, path):
        self.path = path
        self._input_file = None
        self._output_file = None

    @property
    def input_file(self):
        if self._input_file is None:
            try:
                self._input_file = open(self.path, 'rb')
            except IOError as e:
                if e.strerror == 'Permission denied':
                    print('Permission denied ({}). You must be sudo to access global events.'.format(self.path))
                    exit()

            def try_close():
                try:
                    self._input_file.close
                except:
                    pass
            atexit.register(try_close)
        return self._input_file

    @property
    def output_file(self):
        if self._output_file is None:
            self._output_file = open(self.path, 'wb')
            atexit.register(self._output_file.close)
        return self._output_file

    def read_event(self):
        data = self.input_file.read(struct.calcsize(event_bin_format))
        seconds, microseconds, type, code, value = struct.unpack(event_bin_format, data)
        return (seconds + microseconds / 1e6, type, code, value)

    def write_event(self, type, code, value):
        integer, fraction = divmod(now(), 1)
        seconds = int(integer)
        microseconds = int(fraction * 1e6)
        data_event = struct.pack(event_bin_format, seconds, microseconds, type, code, value)

        # Send a sync event to ensure other programs update.
        sync_event = struct.pack(event_bin_format, seconds, microseconds, EV_SYN, 0, 0)

        self.output_file.write(data_event + sync_event)
        self.output_file.flush()
<|endoftext|>


<commit_before>from pyramid.httpexceptions import HTTPNotFound
from pyramid.view import view_config

from ..models import Qso, Band, Mode, Profile, dbtools

def _check(dbsession, call, profile=None):
    call = dbtools.formatters.call_formatter(call)
    tmp = None
    req_type = None
    addrowlink = False
    name = ''
    if profile:
        req_type = Mode
        name = dbsession.query(Profile).get(profile).name
        tmp = dbsession.query(Qso.mode, Qso.band).group_by(Qso.mode, Qso.band).\
            filter_by(call=call, profile=profile).all()
    else:
        req_type = Profile
        addrowlink = True
        tmp = dbsession.query(Qso.profile, Qso.band).group_by(Qso.profile, Qso.band).filter_by(call=call).all()
    if not tmp:
        return {'message': 'Call %s is not in the log...' % call}
    col = {x[1] for x in tmp}
    col = col.union([5, 7, 8, 9, 10, 11, 12, 13])  #always show 80m-10m band
    col = sorted(col)
    row = {x[0] for x in tmp}
    row = sorted(row)
    res = {}
    for r, c in tmp:
        res[(r, c)] = True

    rowh = {id: dbsession.query(req_type).get(id).name for id in row}
    colh = [dbsession.query(Band).get(id).name for id in col]
    return {'call': call, 'name': name, 'res': res, 'col': col, 'row': row,
            'rowh': rowh, 'colh': colh, 'addrowlink': addrowlink}

@view_config(route_name='checkwp', renderer='check.jinja2')
def checkwp_view(request):
    profile = request.matchdict['profile']
    tmp = request.dbsession.query(Profile).get(profile)
    if not tmp:
        raise HTTPNotFound()
    if 'call' in request.params:
        call = request.params['call']
        return _check(request.dbsession, call, profile)
    return {}

@view_config(route_name='check', renderer='check.jinja2')
def check_view(request):
    if 'call' in request.params:
        call = request.params['call']
        if 'profile' in request.params:
            profile = request.params['profile']
            return _check(request.dbsession, call, profile)
        return _check(request.dbsession, call)
    return {}
<commit_msg>check name change<commit_after>from pyramid.httpexceptions import HTTPNotFound
from pyramid.view import view_config

from ..models import Qso, Band, Mode, Profile, dbtools

def _check(dbsession, call, profile=None):
    call = dbtools.formatters.call_formatter(call)
    tmp = None
    req_type = None
    addrowlink = False
    name = ''
    if profile:
        req_type = Mode
        name = "%s (%s)" % (dbsession.query(Profile).get(profile).call, dbsession.query(Profile).get(profile).gridsquare)
        tmp = dbsession.query(Qso.mode, Qso.band).group_by(Qso.mode, Qso.band).\
            filter_by(call=call, profile=profile).all()
    else:
        req_type = Profile
        addrowlink = True
        tmp = dbsession.query(Qso.profile, Qso.band).group_by(Qso.profile, Qso.band).filter_by(call=call).all()
    if not tmp:
        return {'message': 'Call %s is not in the log...' % call}
    col = {x[1] for x in tmp}
    col = col.union([5, 7, 8, 9, 10, 11, 12, 13])  #always show 80m-10m band
    col = sorted(col)
    row = {x[0] for x in tmp}
    row = sorted(row)
    res = {}
    for r, c in tmp:
        res[(r, c)] = True

    rowh = {id: dbsession.query(req_type).get(id).name for id in row}
    colh = [dbsession.query(Band).get(id).name for id in col]
    return {'call': call, 'name': name, 'res': res, 'col': col, 'row': row,
            'rowh': rowh, 'colh': colh, 'addrowlink': addrowlink}

@view_config(route_name='checkwp', renderer='check.jinja2')
def checkwp_view(request):
    profile = request.matchdict['profile']
    tmp = request.dbsession.query(Profile).get(profile)
    if not tmp:
        raise HTTPNotFound()
    if 'call' in request.params:
        call = request.params['call']
        return _check(request.dbsession, call, profile)
    return {}

@view_config(route_name='check', renderer='check.jinja2')
def check_view(request):
    if 'call' in request.params:
        call = request.params['call']
        if 'profile' in request.params:
            profile = request.params['profile']
            return _check(request.dbsession, call, profile)
        return _check(request.dbsession, call)
    return {}
<|endoftext|>