<commit_before># Create your views here.
from django.shortcuts import get_object_or_404,render_to_response
from django.template import RequestContext
from django.conf import settings

from survey.models import Item, User

import uuid

def has_voted(request):
    if ( request.COOKIES.has_key('usercode') ):
        if ( settings.DEBUG and request.GET and request.GET['ignorecookie'] ):
            return False
        return True
    return False

def get_user_from_cookie(request):
    u = User.objects.get(code=request.COOKIES['usercode'])
    return u

def survey(request):
    if ( has_voted(request) ):
        u = get_user_from_cookie(request)

        if u:
            return render_to_response('already_completed.html', {}, context_instance=RequestContext(request))

    if ( request.GET.has_key('site') ):
        request.session['site'] = request.GET['site']

    return render_to_response('survey.html', {}, context_instance=RequestContext(request))

def record(request):
    if ( has_voted(request) ):
        u = get_user_from_cookie(request)
    else:
        u = User(code=uuid.uuid4())
        u.save()

    site = 'unknown'
    if ( request.session.has_key('site') ):
        site = request.session['site']

    for v in request.POST:
        if v == 'csrfmiddlewaretoken':
            continue
        #TODO: this is almost certainly not the best way but enough for proof of concept
        val = request.POST.getlist(v)
        if len(val) > 1:
            val = ','.join(val)
        else:
            val = request.POST[v]

        r = Item(user_id=u.id, key=v, value=val, site=site, batch=1)
        r.save()

    one_year = 60 * 60 * 24 * 365

    response = render_to_response('thanks.html', {}, context_instance=RequestContext(request))
    response.set_cookie('usercode', value=u.code, max_age=one_year)

    return response
<commit_msg>comment to explain why we're not using django sessions for usercode<commit_after># Create your views here.
from django.shortcuts import get_object_or_404,render_to_response
from django.template import RequestContext
from django.conf import settings

from survey.models import Item, User

import uuid

def has_voted(request):
    if ( request.COOKIES.has_key('usercode') ):
        if ( settings.DEBUG and request.GET and request.GET['ignorecookie'] ):
            return False
        return True
    return False

def get_user_from_cookie(request):
    u = User.objects.get(code=request.COOKIES['usercode'])
    return u

def survey(request):
    if ( has_voted(request) ):
        u = get_user_from_cookie(request)

        if u:
            return render_to_response('already_completed.html', {}, context_instance=RequestContext(request))

    if ( request.GET.has_key('site') ):
        request.session['site'] = request.GET['site']

    return render_to_response('survey.html', {}, context_instance=RequestContext(request))

def record(request):
    if ( has_voted(request) ):
        u = get_user_from_cookie(request)
    else:
        u = User(code=uuid.uuid4())
        u.save()

    site = 'unknown'
    if ( request.session.has_key('site') ):
        site = request.session['site']

    for v in request.POST:
        if v == 'csrfmiddlewaretoken':
            continue
        #TODO: this is almost certainly not the best way but enough for proof of concept
        val = request.POST.getlist(v)
        if len(val) > 1:
            val = ','.join(val)
        else:
            val = request.POST[v]

        r = Item(user_id=u.id, key=v, value=val, site=site, batch=1)
        r.save()

    """
    We don't use django's session handling as we want to save the cookie for a long
    time and we also use the built in session things for actual session data
    """
    one_year = 60 * 60 * 24 * 365

    response = render_to_response('thanks.html', {}, context_instance=RequestContext(request))
    response.set_cookie('usercode', value=u.code, max_age=one_year)

    return response
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
__docformat__ = "restructuredtext en"

__copyright__ = """
Copyright (C) 2008-2013 Hendrikx-ITC B.V.

Distributed under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option) any later
version.  The full license is in the file COPYING, distributed as part of
this software.
"""

from setuptools import setup

setup(
    name="minerva",
    author="Hendrikx ITC",
    author_email="info@hendrikx-itc.nl",
    version="4.1.0",
    license="GPL",
    install_requires=["pytz", "psycopg2>=2.2.1", "DBUtils", "PyYAML",
                      "configobj", "python-dateutil", "pyparsing"],
    test_suite="nose.collector",
    packages=[
        "minerva",
        "minerva.util",
        "minerva.test",
        "minerva.db",
        "minerva.system",
        "minerva.directory",
        "minerva.storage",
        "minerva.storage.trend",
        "minerva.storage.trend.test",
        "minerva.storage.attribute",
        "minerva.storage.notification",
        "minerva.storage.geospatial",
        "minerva.xmldochandler",
        "minerva.xmldochandler.xmlschema",
        "minerva.xmlschemaparser",
        "minerva.schemacontextbuilder",
        "minerva.instance"],
    package_dir={"": "src"},
    package_data={
        "minerva": ["defaults/*"]
    },
    scripts=[
        "scripts/create-relations",
        "scripts/load-tags",
        "scripts/link-entity-tags",
        "scripts/link-trend-tags",
        "scripts/link-attribute-tags",
        "scripts/create-network",
        "scripts/create-virtual-entities",
        "scripts/create-csv",
        "scripts/create-aliases",
        "scripts/job",
        "scripts/load-data",
        "scripts/load-datapackage",
        "scripts/query-entities",
        "scripts/load-elements",
        "scripts/populate-gis",
        "scripts/cleanup-trend-data",
        "scripts/materialize-attribute-curr"]
)
<commit_msg>Add compact-attribute script to setup.py for installation.<commit_after># -*- coding: utf-8 -*-
__docformat__ = "restructuredtext en"

__copyright__ = """
Copyright (C) 2008-2013 Hendrikx-ITC B.V.

Distributed under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option) any later
version.  The full license is in the file COPYING, distributed as part of
this software.
"""

from setuptools import setup

setup(
    name="minerva",
    author="Hendrikx ITC",
    author_email="info@hendrikx-itc.nl",
    version="4.1.0",
    license="GPL",
    install_requires=["pytz", "psycopg2>=2.2.1", "DBUtils", "PyYAML",
                      "configobj", "python-dateutil", "pyparsing"],
    test_suite="nose.collector",
    packages=[
        "minerva",
        "minerva.util",
        "minerva.test",
        "minerva.db",
        "minerva.system",
        "minerva.directory",
        "minerva.storage",
        "minerva.storage.trend",
        "minerva.storage.trend.test",
        "minerva.storage.attribute",
        "minerva.storage.notification",
        "minerva.storage.geospatial",
        "minerva.xmldochandler",
        "minerva.xmldochandler.xmlschema",
        "minerva.xmlschemaparser",
        "minerva.schemacontextbuilder",
        "minerva.instance"],
    package_dir={"": "src"},
    package_data={
        "minerva": ["defaults/*"]
    },
    scripts=[
        "scripts/create-relations",
        "scripts/load-tags",
        "scripts/link-entity-tags",
        "scripts/link-trend-tags",
        "scripts/link-attribute-tags",
        "scripts/create-network",
        "scripts/create-virtual-entities",
        "scripts/create-csv",
        "scripts/create-aliases",
        "scripts/job",
        "scripts/load-data",
        "scripts/load-datapackage",
        "scripts/query-entities",
        "scripts/load-elements",
        "scripts/populate-gis",
        "scripts/cleanup-trend-data",
        "scripts/materialize-attribute-curr",
        "scripts/compact-attribute"]
)
<|endoftext|>


<commit_before># Copyright 2014, Tresys Technology, LLC
#
# This file is part of SETools.
#
# SETools is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 2.1 of
# the License, or (at your option) any later version.
#
# SETools is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with SETools.  If not, see
# <http://www.gnu.org/licenses/>.
#
# Create a Python representation of the policy.
# The idea is that this is module provides convenient
# abstractions and methods for accessing the policy
# structures.
from itertools import chain

from . import qpol

# The libqpol SWIG class is not quite natural for
# Python the policy is repeatedly referenced in the
# function calls, which makes sense for C code
# but not for python code, so each object keeps
# a reference to the policy for internal use.
# This also makes sense since an object would only
# be valid for the policy it comes from.

# Components
from . import objclass
from . import typeattr
from . import boolcond
from . import role
from . import user
from . import mls
from . import polcap

# Rules
from . import terule
from . import rbacrule
from . import mlsrule

# Constraints
from . import constraint

# In-policy Labeling
from . import initsid
from . import fscontext
from . import netcontext

class SELinuxPolicy(object):

    """The complete SELinux policy."""

    def __init__(self, policyfile):
        """
        Parameter:
        policyfile  Path to a policy to open.
        """

        try:
            self.policy = qpol.qpol_policy_t(policyfile, 0)
        except OSError as err:
            raise OSError(
                "Error opening policy file \"{0}\": {1}".format(policyfile, err))

    #
    # Policy properties
    #

    @property
    def handle_unknown(self):
        """The handle unknown permissions setting (allow,deny,reject)"""
        return self.policy.handle_unknown()

    @property
    def mls(self):
        """(T/F) The policy has MLS enabled."""
        return bool(self.policy.capability(qpol.QPOL_CAP_MLS))

    @property
    def version(self):
        """The policy database version (e.g. v29)"""
        return self.policy.version()

    #
    # Policy statistics
    #

    @property
    def allow_count(self):
        """The number of (type) allow rules."""
        return self.policy.avrule_allow_count()

    @property
    def attribute_count(self):
        """The number of (type) attributes."""
        return sum(1 for _ in self.attributes())

    @property
    def auditallow_count(self):
        """The number of auditallow rules."""
        return self.policy.avrule_auditallow_count()

    @property
    def boolean_count(self):
        """The number of Booleans."""
        return self.policy.bool_count()

    @property
    def category_count(self):
        """The number of categories."""
        return self.policy.cat_count()

    @property
    def class_count(self):
        """The number of object classes."""
        return self.policy.class_count()

    @property
    def common_count(self):
        """The number of common permission sets."""
        return self.policy.common_count()

    @property
    def conditional_count(self):
        """The number of conditionals."""
        return self.policy.cond_count()

    @property
    def constraint_count(self):
        """The number of standard constraints."""
        return sum(1 for _ in self.constraints())

    @property
    def dontaudit_count(self):
        """The number of dontaudit rules."""
        return self.policy.avrule_dontaudit_count()

    @property
    def fs_use_count(self):
        """fs_use_* statements."""
        return self.policy.fs_use_count()

    @property
    def genfscon_count(self):
        """The number of genfscon statements."""
        return self.policy.genfscon_count()

    @property
    def initialsids_count(self):
        """The number of initial sid statements."""
        return self.policy.isid_count()

    @property
    def level_count(self):
        """The number of levels."""
        return self.policy.level_count()

    @property
    def mlsconstraint_count(self):
        """The number of MLS constraints."""
        return sum(1 for _ in self.mlsconstraints())

    @property
    def mlsvalidatetrans_count(self):
        """The number of MLS validatetrans."""
        return sum(1 for _ in self.mlsvalidatetrans())

    @property
    def netifcon_count(self):
        """The number of netifcon statements."""
        return self.policy.netifcon_count()

    @property
    def neverallow_count(self):
        """The number of neverallow rules."""
        return self.policy.avrule_neverallow_count()

    @property
    def nodecon_count(self):
        """The number of nodecon statements."""
        return self.policy.nodecon_count()

    @property
    def permission_count(self):
        """The number of permissions."""
        return sum(len(c.perms) for c in chain(self.commons(), self.classes()))

    @property
    def permissives_count(self):
        """The number of permissive types."""
        return self.policy.permissive_count()

    @property
    def polcap_count(self):
        """The number of policy capabilities."""
        return self.policy.polcap_count()

    @property
    def portcon_count(self):
        """The number of portcon statements."""
        return self.policy.portcon_count()

    @property
    def range_transition_count(self):
        """The number of range_transition rules."""
        return self.policy.range_trans_count()

    @property
    def role_count(self):
        """The number of roles."""
        return self.policy.role_count()

    @property
    def role_allow_count(self):
        """The number of (role) allow rules."""
        return self.policy.role_allow_count()

    @property
    def role_transition_count(self):
        """The number of role_transition rules."""
        return self.policy.role_trans_count()

    @property
    def type_count(self):
        """The number of types."""
        return sum(1 for _ in self.types())

    @property
    def type_change_count(self):
        """The number of type_change rules."""
        return self.policy.terule_change_count()

    @property
    def type_member_count(self):
        """The number of type_member rules."""
        return self.policy.terule_member_count()

    @property
    def type_transition_count(self):
        """The number of type_transition rules."""
        return self.policy.terule_trans_count() + self.policy.filename_trans_count()

    @property
    def user_count(self):
        """The number of users."""
        return self.policy.user_count()

    @property
    def validatetrans_count(self):
        """The number of validatetrans."""
        return sum(1 for _ in self.validatetrans())

    #
    # Policy components lookup functions
    #

    def lookup_role(self, name):
        """Look up a role by name."""
        return role.role_factory(self.policy, name)

    def lookup_type(self, name):
        """Look up a type by name."""
        return typeattr.typeattr_factory(self.policy, name)

    def lookup_user(self, name):
        """Look up a user by name."""
        return user.user_factory(self.policy, name)

    #
    # Policy components generators
    #

    def attributes(self):
        """Generator which yields all (type) attributes."""

        # libqpol unfortunately iterates over attributes and aliases
        for type_ in self.policy.type_iter():
            t = typeattr.TypeAttr(self.policy, type_)
            if t.isattr:
                yield t

    def classes(self):
        """Generator which yields all object classes."""

        for class_ in self.policy.class_iter():
            yield objclass.ObjClass(self.policy, class_)

    def commons(self):
        """Generator which yields all commons."""

        for common in self.policy.common_iter():
            yield objclass.Common(self.policy, common)

    def types(self):
        """Generator which yields all types."""

        # libqpol unfortunately iterates over attributes and aliases
        for type_ in self.policy.type_iter():
            t = typeattr.TypeAttr(self.policy, type_)
            if not t.isattr and not t.isalias:
                yield t

    def roles(self):
        """Generator which yields all roles."""

        for role_ in self.policy.role_iter():
            yield role.Role(self.policy, role_)

    def users(self):
        """Generator which yields all users."""

        for user_ in self.policy.user_iter():
            yield user.User(self.policy, user_)

    def bools(self):
        """Generator which yields all Booleans."""

        for bool_ in self.policy.bool_iter():
            yield boolcond.Boolean(self.policy, bool_)

    def polcaps(self):
        """Generator which yields all policy capabilities."""

        for cap in self.policy.polcap_iter():
            yield polcap.PolicyCapability(self.policy, cap)

    def permissives(self):
        """Generator which yields all permissive types."""

        for type_ in self.policy.permissive_iter():
            yield typeattr.TypeAttr(self.policy, type_)

    #
    # Policy rules generators
    #
    def terules(self):
        """Generator which yields all type enforcement rules."""

        for rule in self.policy.avrule_iter():
            yield terule.TERule(self.policy, rule)

        for rule in self.policy.terule_iter():
            yield terule.TERule(self.policy, rule)

        for rule in self.policy.filename_trans_iter():
            yield terule.TERule(self.policy, rule)

    def rbacrules(self):
        """Generator which yields all RBAC rules."""

        for rule in self.policy.role_allow_iter():
            yield rbacrule.RBACRule(self.policy, rule)

        for rule in self.policy.role_trans_iter():
            yield rbacrule.RBACRule(self.policy, rule)

    def mlsrules(self):
        """Generator which yields all MLS rules."""

        for rule in self.policy.range_trans_iter():
            yield mlsrule.MLSRule(self.policy, rule)

    #
    # Constraints generators
    #

    def constraints(self):
        """Generator which yields all constraints."""

        for constraint_ in self.policy.constraint_iter():
            c = constraint.Constraint(self.policy, constraint_)
            if not c.ismls:
                yield c

    def mlsconstraints(self):
        """Generator which yields all MLS constraints."""

        for constraint_ in self.policy.constraint_iter():
            c = constraint.Constraint(self.policy, constraint_)
            if c.ismls:
                yield c

    def mlsvalidatetrans(self):
        """Generator which yields all mlsvalidatetrans."""

        for validatetrans in self.policy.validatetrans_iter():
            v = constraint.ValidateTrans(self.policy, validatetrans)
            if v.ismls:
                yield v

    def validatetrans(self):
        """Generator which yields all validatetrans."""

        for validatetrans in self.policy.validatetrans_iter():
            v = constraint.ValidateTrans(self.policy, validatetrans)
            if not v.ismls:
                yield v

    #
    # In-policy Labeling statement generators
    #
    def initialsids(self):
        """Generator which yields all initial SID statements."""

        for sid in self.policy.isid_iter():
            yield initsid.InitialSID(self.policy, sid)

    def fs_uses(self):
        """Generator which yields all fs_use_* statements."""

        for fs_use in self.policy.fs_use_iter():
            yield fscontext.FSUse(self.policy, fs_use)

    def genfscons(self):
        """Generator which yields all genfscon statements."""

        for fscon in self.policy.genfscon_iter():
            yield fscontext.Genfscon(self.policy, fscon)

    def netifcons(self):
        """Generator which yields all netifcon statements."""

        for ifcon in self.policy.netifcon_iter():
            yield netcontext.Netifcon(self.policy, ifcon)

    def nodecons(self):
        """Generator which yields all nodecon statements."""

        for node in self.policy.nodecon_iter():
            yield netcontext.Nodecon(self.policy, node)

    def portcons(self):
        """Generator which yields all portcon statements."""

        for port in self.policy.portcon_iter():
            yield netcontext.Portcon(self.policy, port)
<commit_msg>Switch SELinuxPolicy terules and rbacrules generators to use chain().<commit_after># Copyright 2014, Tresys Technology, LLC
#
# This file is part of SETools.
#
# SETools is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 2.1 of
# the License, or (at your option) any later version.
#
# SETools is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with SETools.  If not, see
# <http://www.gnu.org/licenses/>.
#
# Create a Python representation of the policy.
# The idea is that this is module provides convenient
# abstractions and methods for accessing the policy
# structures.
from itertools import chain

from . import qpol

# The libqpol SWIG class is not quite natural for
# Python the policy is repeatedly referenced in the
# function calls, which makes sense for C code
# but not for python code, so each object keeps
# a reference to the policy for internal use.
# This also makes sense since an object would only
# be valid for the policy it comes from.

# Components
from . import objclass
from . import typeattr
from . import boolcond
from . import role
from . import user
from . import mls
from . import polcap

# Rules
from . import terule
from . import rbacrule
from . import mlsrule

# Constraints
from . import constraint

# In-policy Labeling
from . import initsid
from . import fscontext
from . import netcontext

class SELinuxPolicy(object):

    """The complete SELinux policy."""

    def __init__(self, policyfile):
        """
        Parameter:
        policyfile  Path to a policy to open.
        """

        try:
            self.policy = qpol.qpol_policy_t(policyfile, 0)
        except OSError as err:
            raise OSError(
                "Error opening policy file \"{0}\": {1}".format(policyfile, err))

    #
    # Policy properties
    #

    @property
    def handle_unknown(self):
        """The handle unknown permissions setting (allow,deny,reject)"""
        return self.policy.handle_unknown()

    @property
    def mls(self):
        """(T/F) The policy has MLS enabled."""
        return bool(self.policy.capability(qpol.QPOL_CAP_MLS))

    @property
    def version(self):
        """The policy database version (e.g. v29)"""
        return self.policy.version()

    #
    # Policy statistics
    #

    @property
    def allow_count(self):
        """The number of (type) allow rules."""
        return self.policy.avrule_allow_count()

    @property
    def attribute_count(self):
        """The number of (type) attributes."""
        return sum(1 for _ in self.attributes())

    @property
    def auditallow_count(self):
        """The number of auditallow rules."""
        return self.policy.avrule_auditallow_count()

    @property
    def boolean_count(self):
        """The number of Booleans."""
        return self.policy.bool_count()

    @property
    def category_count(self):
        """The number of categories."""
        return self.policy.cat_count()

    @property
    def class_count(self):
        """The number of object classes."""
        return self.policy.class_count()

    @property
    def common_count(self):
        """The number of common permission sets."""
        return self.policy.common_count()

    @property
    def conditional_count(self):
        """The number of conditionals."""
        return self.policy.cond_count()

    @property
    def constraint_count(self):
        """The number of standard constraints."""
        return sum(1 for _ in self.constraints())

    @property
    def dontaudit_count(self):
        """The number of dontaudit rules."""
        return self.policy.avrule_dontaudit_count()

    @property
    def fs_use_count(self):
        """fs_use_* statements."""
        return self.policy.fs_use_count()

    @property
    def genfscon_count(self):
        """The number of genfscon statements."""
        return self.policy.genfscon_count()

    @property
    def initialsids_count(self):
        """The number of initial sid statements."""
        return self.policy.isid_count()

    @property
    def level_count(self):
        """The number of levels."""
        return self.policy.level_count()

    @property
    def mlsconstraint_count(self):
        """The number of MLS constraints."""
        return sum(1 for _ in self.mlsconstraints())

    @property
    def mlsvalidatetrans_count(self):
        """The number of MLS validatetrans."""
        return sum(1 for _ in self.mlsvalidatetrans())

    @property
    def netifcon_count(self):
        """The number of netifcon statements."""
        return self.policy.netifcon_count()

    @property
    def neverallow_count(self):
        """The number of neverallow rules."""
        return self.policy.avrule_neverallow_count()

    @property
    def nodecon_count(self):
        """The number of nodecon statements."""
        return self.policy.nodecon_count()

    @property
    def permission_count(self):
        """The number of permissions."""
        return sum(len(c.perms) for c in chain(self.commons(), self.classes()))

    @property
    def permissives_count(self):
        """The number of permissive types."""
        return self.policy.permissive_count()

    @property
    def polcap_count(self):
        """The number of policy capabilities."""
        return self.policy.polcap_count()

    @property
    def portcon_count(self):
        """The number of portcon statements."""
        return self.policy.portcon_count()

    @property
    def range_transition_count(self):
        """The number of range_transition rules."""
        return self.policy.range_trans_count()

    @property
    def role_count(self):
        """The number of roles."""
        return self.policy.role_count()

    @property
    def role_allow_count(self):
        """The number of (role) allow rules."""
        return self.policy.role_allow_count()

    @property
    def role_transition_count(self):
        """The number of role_transition rules."""
        return self.policy.role_trans_count()

    @property
    def type_count(self):
        """The number of types."""
        return sum(1 for _ in self.types())

    @property
    def type_change_count(self):
        """The number of type_change rules."""
        return self.policy.terule_change_count()

    @property
    def type_member_count(self):
        """The number of type_member rules."""
        return self.policy.terule_member_count()

    @property
    def type_transition_count(self):
        """The number of type_transition rules."""
        return self.policy.terule_trans_count() + self.policy.filename_trans_count()

    @property
    def user_count(self):
        """The number of users."""
        return self.policy.user_count()

    @property
    def validatetrans_count(self):
        """The number of validatetrans."""
        return sum(1 for _ in self.validatetrans())

    #
    # Policy components lookup functions
    #

    def lookup_role(self, name):
        """Look up a role by name."""
        return role.role_factory(self.policy, name)

    def lookup_type(self, name):
        """Look up a type by name."""
        return typeattr.typeattr_factory(self.policy, name)

    def lookup_user(self, name):
        """Look up a user by name."""
        return user.user_factory(self.policy, name)

    #
    # Policy components generators
    #

    def attributes(self):
        """Generator which yields all (type) attributes."""

        # libqpol unfortunately iterates over attributes and aliases
        for type_ in self.policy.type_iter():
            t = typeattr.TypeAttr(self.policy, type_)
            if t.isattr:
                yield t

    def classes(self):
        """Generator which yields all object classes."""

        for class_ in self.policy.class_iter():
            yield objclass.ObjClass(self.policy, class_)

    def commons(self):
        """Generator which yields all commons."""

        for common in self.policy.common_iter():
            yield objclass.Common(self.policy, common)

    def types(self):
        """Generator which yields all types."""

        # libqpol unfortunately iterates over attributes and aliases
        for type_ in self.policy.type_iter():
            t = typeattr.TypeAttr(self.policy, type_)
            if not t.isattr and not t.isalias:
                yield t

    def roles(self):
        """Generator which yields all roles."""

        for role_ in self.policy.role_iter():
            yield role.Role(self.policy, role_)

    def users(self):
        """Generator which yields all users."""

        for user_ in self.policy.user_iter():
            yield user.User(self.policy, user_)

    def bools(self):
        """Generator which yields all Booleans."""

        for bool_ in self.policy.bool_iter():
            yield boolcond.Boolean(self.policy, bool_)

    def polcaps(self):
        """Generator which yields all policy capabilities."""

        for cap in self.policy.polcap_iter():
            yield polcap.PolicyCapability(self.policy, cap)

    def permissives(self):
        """Generator which yields all permissive types."""

        for type_ in self.policy.permissive_iter():
            yield typeattr.TypeAttr(self.policy, type_)

    #
    # Policy rules generators
    #
    def terules(self):
        """Generator which yields all type enforcement rules."""

        for rule in chain(self.policy.avrule_iter(), self.policy.terule_iter(), self.policy.filename_trans_iter()):
            yield terule.TERule(self.policy, rule)

    def rbacrules(self):
        """Generator which yields all RBAC rules."""

        for rule in chain(self.policy.role_allow_iter(), self.policy.role_trans_iter()):
            yield rbacrule.RBACRule(self.policy, rule)

    def mlsrules(self):
        """Generator which yields all MLS rules."""

        for rule in self.policy.range_trans_iter():
            yield mlsrule.MLSRule(self.policy, rule)

    #
    # Constraints generators
    #

    def constraints(self):
        """Generator which yields all constraints."""

        for constraint_ in self.policy.constraint_iter():
            c = constraint.Constraint(self.policy, constraint_)
            if not c.ismls:
                yield c

    def mlsconstraints(self):
        """Generator which yields all MLS constraints."""

        for constraint_ in self.policy.constraint_iter():
            c = constraint.Constraint(self.policy, constraint_)
            if c.ismls:
                yield c

    def mlsvalidatetrans(self):
        """Generator which yields all mlsvalidatetrans."""

        for validatetrans in self.policy.validatetrans_iter():
            v = constraint.ValidateTrans(self.policy, validatetrans)
            if v.ismls:
                yield v

    def validatetrans(self):
        """Generator which yields all validatetrans."""

        for validatetrans in self.policy.validatetrans_iter():
            v = constraint.ValidateTrans(self.policy, validatetrans)
            if not v.ismls:
                yield v

    #
    # In-policy Labeling statement generators
    #
    def initialsids(self):
        """Generator which yields all initial SID statements."""

        for sid in self.policy.isid_iter():
            yield initsid.InitialSID(self.policy, sid)

    def fs_uses(self):
        """Generator which yields all fs_use_* statements."""

        for fs_use in self.policy.fs_use_iter():
            yield fscontext.FSUse(self.policy, fs_use)

    def genfscons(self):
        """Generator which yields all genfscon statements."""

        for fscon in self.policy.genfscon_iter():
            yield fscontext.Genfscon(self.policy, fscon)

    def netifcons(self):
        """Generator which yields all netifcon statements."""

        for ifcon in self.policy.netifcon_iter():
            yield netcontext.Netifcon(self.policy, ifcon)

    def nodecons(self):
        """Generator which yields all nodecon statements."""

        for node in self.policy.nodecon_iter():
            yield netcontext.Nodecon(self.policy, node)

    def portcons(self):
        """Generator which yields all portcon statements."""

        for port in self.policy.portcon_iter():
            yield netcontext.Portcon(self.policy, port)
<|endoftext|>


<commit_before><commit_msg>L2L2 – email<commit_after><|endoftext|>


<commit_before>from bottle import route, run, template, static_file, redirect
import time
import urllib2
import numpy as np
import matplotlib as mpl
# we are running headless, use "Agg" as backend for matplotlib
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from datetime import datetime
from RPIO import PWM

# setup PWM hardware
PWM.set_loglevel(PWM.LOG_LEVEL_ERRORS)
##PWM.setup(pulse_incr_us=10, delay_hw=1)
PWM.setup(pulse_incr_us=10, delay_hw=0)

# servo pins
servo_x=25
servo_y=24
mlx_url="http://localhost:8080/mlx"

@route('/')
def send_root():
  redirect("/html/index.html")

@route('/images/<filename:path>')
def send_image(filename):
  return static_file(filename, root='/root/thermo/scripts/images', mimetype='image/png')

@route('/html/<filename:path>')
def send_static(filename):
  return static_file(filename, root='/root/thermo/scripts/html')

# default mode redirection
@route('/do')
def redirect_it():
  redirect("/do/default")

# different resolutions, "default", "small", "big"
# Load paramaters for each resolution
@route('/do/<resolution>')
def do_it(resolution):

# default parameters
# set start, end (this is hardware dependent) and number of steps
  start_pos=1200
  end_pos=1800
  step_count=32
  pause=.1
  pause_line=1

  if resolution == 'small':
    start_pos=1200
    end_pos=1800
    step_count=10
    pause=.15
    pause_line=.3

  if resolution == 'big':
    start_pos=1200
    end_pos=1800
    step_count=48
    pause=.1
    pause_line=.3

#
  step_size=round(((end_pos-start_pos)/(step_count-1)/10))*10
  x=0
  y=0

  data=np.zeros((step_count, step_count))

  servo = PWM.Servo()
##  servo.__init__(0,6000,10)
  servo.set_servo(servo_x, start_pos)
  servo.set_servo(servo_y, start_pos)

# Sweep thru one frame
  for x in range(step_count):
    servo.set_servo(servo_x, start_pos + x * step_size)
    servo.set_servo(servo_y, start_pos)
    time.sleep(pause_line)
    for y in range(step_count):
      servo.set_servo(servo_y, start_pos + y * step_size)
      time.sleep(pause)
      response=urllib2.urlopen(mlx_url)
      temperature=response.read()
      data[x,y]=temperature

# flip array to get correct orientation
  data = np.flipud(data)
##data = np.fliplr(data)
# Generate heatmap from data array
  cmap = cm.get_cmap('jet')
  plt.clf()
  plt.imshow(data, interpolation="nearest", cmap=cmap)
  plt.axis('off')
# add temp colorbar
  cb = plt.colorbar()
  cb.set_label('Temp (in C)')
  plt.savefig('/root/thermo/scripts/images/heatmap.png')

# save again with datecoded filename
  date_string = datetime.now().strftime("%Y-%m-%d--%H-%M")
  plt.savefig('/root/thermo/scripts/images/heatmap' + date_string + '.png')

  redirect("/html/index.html")

run(host='0.0.0.0', port=80)
#run(host='192.168.1.1', port=80)
<commit_msg>put date/time into image<commit_after>from bottle import route, run, template, static_file, redirect
import time
import urllib2
import numpy as np
import matplotlib as mpl

# we are running headless, use "Agg" as backend for matplotlib
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from datetime import datetime
from RPIO import PWM

# setup PWM hardware
PWM.set_loglevel(PWM.LOG_LEVEL_ERRORS)
##PWM.setup(pulse_incr_us=10, delay_hw=1)
PWM.setup(pulse_incr_us=10, delay_hw=0)

# servo pins
servo_x=25
servo_y=24
mlx_url="http://localhost:8080/mlx"

@route('/')
def send_root():
  redirect("/html/index.html")

@route('/images/<filename:path>')
def send_image(filename):
  return static_file(filename, root='/root/thermo/scripts/images', mimetype='image/png')

@route('/html/<filename:path>')
def send_static(filename):
  return static_file(filename, root='/root/thermo/scripts/html')

# default mode redirection
@route('/do')
def redirect_it():
  redirect("/do/default")

# different resolutions, "default", "small", "big"
# Load paramaters for each resolution
@route('/do/<resolution>')
def do_it(resolution):

# default parameters
# set start, end (this is hardware dependent) and number of steps
  start_pos=1200
  end_pos=1800
  step_count=32
  pause=.1
  pause_line=1

  if resolution == 'small':
    start_pos=1200
    end_pos=1800
    step_count=10
    pause=.15
    pause_line=.3

  if resolution == 'big':
    start_pos=1200
    end_pos=1800
    step_count=48
    pause=.1
    pause_line=.3

#
  step_size=round(((end_pos-start_pos)/(step_count-1)/10))*10
  x=0
  y=0

  data=np.zeros((step_count, step_count))

  servo = PWM.Servo()
##  servo.__init__(0,6000,10)
  servo.set_servo(servo_x, start_pos)
  servo.set_servo(servo_y, start_pos)

# Sweep thru one frame
  for x in range(step_count):
    servo.set_servo(servo_x, start_pos + x * step_size)
    servo.set_servo(servo_y, start_pos)
    time.sleep(pause_line)
    for y in range(step_count):
      servo.set_servo(servo_y, start_pos + y * step_size)
      time.sleep(pause)
      response=urllib2.urlopen(mlx_url)
      temperature=response.read()
      data[x,y]=temperature

# flip array to get correct orientation
##  data = np.flipud(data)
##data = np.fliplr(data)
# Generate heatmap from data array
  cmap = cm.get_cmap('jet')
  plt.clf()
  plt.imshow(data, interpolation="nearest", cmap=cmap)
  plt.axis('off')
# add temp colorbar
  cb = plt.colorbar()
  date_disp = datetime.now().strftime("%Y-%m-%d  %H:%M")
  cb.set_label('Temp (in C)  ' + date_disp)
  plt.savefig('/root/thermo/scripts/images/heatmap.png')

# save again with datecoded filename
  date_string = datetime.now().strftime("%Y-%m-%d--%H-%M")
  plt.savefig('/root/thermo/scripts/images/heatmap' + date_string + '.png')

  redirect("/html/index.html")

run(host='0.0.0.0', port=80)
<|endoftext|>


<commit_before>import os
import re
import subprocess
import tempfile

from reviewboard.scmtools.core import SCMError, FileNotFoundError, \
                                      SCMTool, HEAD, PRE_CREATION
from reviewboard.diffviewer.parser import DiffParser, DiffParserError

class CVSTool(SCMTool):
    regex_rev = re.compile(r'^.*?(\d+(\.\d+)+)\r?$')
    regex_repopath = re.compile(r'^(?P<hostname>.*):(?P<port>\d+)?(?P<path>.*)')

    def __init__(self, repository):
        SCMTool.__init__(self, repository)

        self.cvsroot, self.repopath = self.build_cvsroot()
        self.client = CVSClient(self.cvsroot, self.repopath)

    def build_cvsroot(self):
        # NOTE: According to cvs, the following formats are valid.
        #
        #  :(gserver|kserver|pserver):[[user][:password]@]host[:[port]]/path
        #  [:(ext|server):][[user]@]host[:]/path
        #  :local:e:\path
        #  :fork:/path

        if not self.repository.path.startswith(":"):
            # The user has a path or something. We'll want to parse out the
            # server name, port (if specified) and path and build a :pserver:
            # CVSROOT.
            m = self.regex_repopath.match(self.repository.path)

            if m:
                path = m.group("path")
                cvsroot = ":pserver:"

                if self.repository.username:
                    if self.repository.password:
                        cvsroot += '%s:%s@' % (self.repository.username,
                                               self.repository.password)
                    else:
                        cvsroot += '%s@' % (self.repository.username)

                cvsroot += "%s:%s%s" % (m.group("hostname"),
                                        m.group("port") or "",
                                        path)
                return cvsroot, path

        # We couldn't parse this as a hostname:port/path. Assume it's a local
        # path or a full CVSROOT and let CVS handle it.
        return self.repository.path, self.repository.path

    def get_file(self, path, revision=HEAD):
        if not path:
            raise FileNotFoundError(path, revision)

        return self.client.cat_file(path, revision)

    def parse_diff_revision(self, file_str, revision_str):
        if revision_str == "PRE-CREATION":
            return file_str, PRE_CREATION

        m = self.regex_rev.match(revision_str)
        if not m:
            raise SCMError("Unable to parse diff revision header '%s'" %
                           revision_str)
        return file_str, m.group(1)

    def get_diffs_use_absolute_paths(self):
        return True

    def get_fields(self):
        return ['diff_path']

    def get_parser(self, data):
        return CVSDiffParser(data, self.repopath)

class CVSDiffParser(DiffParser):
    """
        This class is able to parse diffs created with CVS.
    """

    regex_small = re.compile('^RCS file: (.+)$')

    def __init__(self, data, repo):
        DiffParser.__init__(self, data)
        self.regex_full = re.compile('^RCS file: %s/(.*),v$' % re.escape(repo))

    def parse_special_header(self, linenum, info):
        linenum = super(CVSDiffParser, self).parse_special_header(linenum, info)

        if 'index' not in info:
            # We didn't find an index, so the rest is probably bogus too.
            return linenum

        m = self.regex_full.match(self.lines[linenum])
        if not m:
            m = self.regex_small.match(self.lines[linenum])

        if m:
            info['filename'] = m.group(1)
            linenum += 1
        else:
            raise DiffParserError('Unable to find RCS line', linenum)

        while self.lines[linenum].startswith('retrieving '):
            linenum += 1

        if self.lines[linenum].startswith('diff '):
            linenum += 1

        return linenum

    def parse_diff_header(self, linenum, info):
        linenum = super(CVSDiffParser, self).parse_diff_header(linenum, info)

        if info.get('origFile') == '/dev/null':
            info['origFile'] = info['newFile']
            info['origInfo'] = 'PRE-CREATION'
        elif 'filename' in info:
            info['origFile'] = info['filename']

        return linenum

class CVSClient:
    def __init__(self, repository, path):
        self.tempdir = ""
        self.currentdir = os.getcwd()
        self.repository = repository
        self.path = path

    def cleanup(self):
        if self.currentdir != os.getcwd():
            # Restore current working directory
            os.chdir(self.currentdir)
            # Remove temporary directory
            if self.tempdir != "":
                os.rmdir(self.tempdir)

    def cat_file(self, filename, revision):
        # Somehow CVS sometimes seems to write .cvsignore files to current
        # working directory even though we force stdout with -p.
        self.tempdir = tempfile.mkdtemp()
        os.chdir(self.tempdir)

        # We strip the repo off of the fully qualified path as CVS does
        # not like to be given absolute paths.
        repos_path = self.path.split(":")[-1]
        if filename.startswith(repos_path + "/"):
            filename = filename[len(repos_path) + 1:]

        # Strip off the ",v" we sometimes get for CVS paths.
        if filename.endswith(",v"):
            filename = filename.rstrip(",v")

        p = subprocess.Popen(['cvs', '-d', self.repository, 'checkout',
                              '-r', str(revision), '-p', filename],
                             stderr=subprocess.PIPE, stdout=subprocess.PIPE,
                             close_fds=True)
        contents = p.stdout.read()
        errmsg = p.stderr.read()
        failure = p.wait()

        # Unfortunately, CVS is not consistent about exiting non-zero on
        # errors.  If the file is not found at all, then CVS will print an
        # error message on stderr, but it doesn't set an exit code with
        # pservers.  If the file is found but an invalid revision is requested,
        # then cvs exits zero and nothing is printed at all. (!)
        #
        # But, when it is successful, cvs will print a header on stderr like
        # so:
        #
        # ===================================================================
        # Checking out foobar
        # RCS: /path/to/repo/foobar,v
        # VERS: 1.1
        # ***************

        # So, if nothing is in errmsg, or errmsg has a specific recognized
        # message, call it FileNotFound.
        if not errmsg or \
           errmsg.startswith('cvs checkout: cannot find module') or \
           errmsg.startswith('cvs checkout: could not read RCS file'):
            self.cleanup()
            raise FileNotFoundError(filename, revision)

        # Otherwise, if there's an exit code, or errmsg doesn't look like
        # successful header, then call it a generic SCMError.
        #
        # If the .cvspass file doesn't exist, CVS will return an error message
        # stating this. This is safe to ignore.
        if (failure and not errmsg.startswith('==========')) and \
           not ".cvspass does not exist - creating new file" in errmsg:
            self.cleanup()
            raise SCMError(errmsg)

        self.cleanup()
        return contents
<commit_msg>Make CVSTool ignore .cvsrc<commit_after>import os
import re
import subprocess
import tempfile

from reviewboard.scmtools.core import SCMError, FileNotFoundError, \
                                      SCMTool, HEAD, PRE_CREATION
from reviewboard.diffviewer.parser import DiffParser, DiffParserError

class CVSTool(SCMTool):
    regex_rev = re.compile(r'^.*?(\d+(\.\d+)+)\r?$')
    regex_repopath = re.compile(r'^(?P<hostname>.*):(?P<port>\d+)?(?P<path>.*)')

    def __init__(self, repository):
        SCMTool.__init__(self, repository)

        self.cvsroot, self.repopath = self.build_cvsroot()
        self.client = CVSClient(self.cvsroot, self.repopath)

    def build_cvsroot(self):
        # NOTE: According to cvs, the following formats are valid.
        #
        #  :(gserver|kserver|pserver):[[user][:password]@]host[:[port]]/path
        #  [:(ext|server):][[user]@]host[:]/path
        #  :local:e:\path
        #  :fork:/path

        if not self.repository.path.startswith(":"):
            # The user has a path or something. We'll want to parse out the
            # server name, port (if specified) and path and build a :pserver:
            # CVSROOT.
            m = self.regex_repopath.match(self.repository.path)

            if m:
                path = m.group("path")
                cvsroot = ":pserver:"

                if self.repository.username:
                    if self.repository.password:
                        cvsroot += '%s:%s@' % (self.repository.username,
                                               self.repository.password)
                    else:
                        cvsroot += '%s@' % (self.repository.username)

                cvsroot += "%s:%s%s" % (m.group("hostname"),
                                        m.group("port") or "",
                                        path)
                return cvsroot, path

        # We couldn't parse this as a hostname:port/path. Assume it's a local
        # path or a full CVSROOT and let CVS handle it.
        return self.repository.path, self.repository.path

    def get_file(self, path, revision=HEAD):
        if not path:
            raise FileNotFoundError(path, revision)

        return self.client.cat_file(path, revision)

    def parse_diff_revision(self, file_str, revision_str):
        if revision_str == "PRE-CREATION":
            return file_str, PRE_CREATION

        m = self.regex_rev.match(revision_str)
        if not m:
            raise SCMError("Unable to parse diff revision header '%s'" %
                           revision_str)
        return file_str, m.group(1)

    def get_diffs_use_absolute_paths(self):
        return True

    def get_fields(self):
        return ['diff_path']

    def get_parser(self, data):
        return CVSDiffParser(data, self.repopath)

class CVSDiffParser(DiffParser):
    """
        This class is able to parse diffs created with CVS.
    """

    regex_small = re.compile('^RCS file: (.+)$')

    def __init__(self, data, repo):
        DiffParser.__init__(self, data)
        self.regex_full = re.compile('^RCS file: %s/(.*),v$' % re.escape(repo))

    def parse_special_header(self, linenum, info):
        linenum = super(CVSDiffParser, self).parse_special_header(linenum, info)

        if 'index' not in info:
            # We didn't find an index, so the rest is probably bogus too.
            return linenum

        m = self.regex_full.match(self.lines[linenum])
        if not m:
            m = self.regex_small.match(self.lines[linenum])

        if m:
            info['filename'] = m.group(1)
            linenum += 1
        else:
            raise DiffParserError('Unable to find RCS line', linenum)

        while self.lines[linenum].startswith('retrieving '):
            linenum += 1

        if self.lines[linenum].startswith('diff '):
            linenum += 1

        return linenum

    def parse_diff_header(self, linenum, info):
        linenum = super(CVSDiffParser, self).parse_diff_header(linenum, info)

        if info.get('origFile') == '/dev/null':
            info['origFile'] = info['newFile']
            info['origInfo'] = 'PRE-CREATION'
        elif 'filename' in info:
            info['origFile'] = info['filename']

        return linenum

class CVSClient:
    def __init__(self, repository, path):
        self.tempdir = ""
        self.currentdir = os.getcwd()
        self.repository = repository
        self.path = path

    def cleanup(self):
        if self.currentdir != os.getcwd():
            # Restore current working directory
            os.chdir(self.currentdir)
            # Remove temporary directory
            if self.tempdir != "":
                os.rmdir(self.tempdir)

    def cat_file(self, filename, revision):
        # Somehow CVS sometimes seems to write .cvsignore files to current
        # working directory even though we force stdout with -p.
        self.tempdir = tempfile.mkdtemp()
        os.chdir(self.tempdir)

        # We strip the repo off of the fully qualified path as CVS does
        # not like to be given absolute paths.
        repos_path = self.path.split(":")[-1]
        if filename.startswith(repos_path + "/"):
            filename = filename[len(repos_path) + 1:]

        # Strip off the ",v" we sometimes get for CVS paths.
        if filename.endswith(",v"):
            filename = filename.rstrip(",v")

        p = subprocess.Popen(['cvs', '-f', '-d', self.repository, 'checkout',
                              '-r', str(revision), '-p', filename],
                             stderr=subprocess.PIPE, stdout=subprocess.PIPE,
                             close_fds=True)
        contents = p.stdout.read()
        errmsg = p.stderr.read()
        failure = p.wait()

        # Unfortunately, CVS is not consistent about exiting non-zero on
        # errors.  If the file is not found at all, then CVS will print an
        # error message on stderr, but it doesn't set an exit code with
        # pservers.  If the file is found but an invalid revision is requested,
        # then cvs exits zero and nothing is printed at all. (!)
        #
        # But, when it is successful, cvs will print a header on stderr like
        # so:
        #
        # ===================================================================
        # Checking out foobar
        # RCS: /path/to/repo/foobar,v
        # VERS: 1.1
        # ***************

        # So, if nothing is in errmsg, or errmsg has a specific recognized
        # message, call it FileNotFound.
        if not errmsg or \
           errmsg.startswith('cvs checkout: cannot find module') or \
           errmsg.startswith('cvs checkout: could not read RCS file'):
            self.cleanup()
            raise FileNotFoundError(filename, revision)

        # Otherwise, if there's an exit code, or errmsg doesn't look like
        # successful header, then call it a generic SCMError.
        #
        # If the .cvspass file doesn't exist, CVS will return an error message
        # stating this. This is safe to ignore.
        if (failure and not errmsg.startswith('==========')) and \
           not ".cvspass does not exist - creating new file" in errmsg:
            self.cleanup()
            raise SCMError(errmsg)

        self.cleanup()
        return contents
<|endoftext|>


<commit_before>from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
<commit_msg>attempting to fix deploy<commit_after>import os

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)
<|endoftext|>


<commit_before>from flask.ext.rq import get_connection, get_queue
from rq_scheduler import Scheduler

def get_scheduler(queue='default'):
    return Scheduler(get_queue(queue), connection=get_connection(queue))

def scheduled_job(func_or_queue=None):
    if callable(func_or_queue):
        func = func_or_queue
        queue = 'default'
    else:
        func = None
        queue = func_or_queue

    def wrapper(fn):
        def delay_at(scheduled_time, *args, **kwargs):
            s = get_scheduler(queue)
            return s.enqueue_at(scheduled_time, fn, *args, **kwargs)

        def delay_in(time_delta, *args, **kwargs):
            s = get_scheduler(queue)
            return s.enqueue_in(time_delta, fn, *args, **kwargs)

        def schedule(scheduled_time, args=None, kwargs=None, interval=None, repeat=None):
            s = get_scheduler(queue)
            return s.schedule(scheduled_time, fn, args, kwargs, interval, repeat)

        fn.delay_at = delay_at
        fn.delay_in = delay_in
        fn.schedule = schedule
        return fn

    if func is not None:
        return wrapper(func)

    return wrapper

class RQScheduler(object):
    def __init__(self, app=None):
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        pass
<commit_msg>Fixed queue name parameter<commit_after>from flask.ext.rq import get_connection, get_queue
from rq_scheduler import Scheduler

def get_scheduler(queue='default'):
    return Scheduler(queue, connection=get_connection(queue))

def scheduled_job(func_or_queue=None):
    if callable(func_or_queue):
        func = func_or_queue
        queue = 'default'
    else:
        func = None
        queue = func_or_queue

    def wrapper(fn):
        def delay_at(scheduled_time, *args, **kwargs):
            s = get_scheduler(queue)
            return s.enqueue_at(scheduled_time, fn, *args, **kwargs)

        def delay_in(time_delta, *args, **kwargs):
            s = get_scheduler(queue)
            return s.enqueue_in(time_delta, fn, *args, **kwargs)

        def schedule(scheduled_time, args=None, kwargs=None, interval=None, repeat=None):
            s = get_scheduler(queue)
            return s.schedule(scheduled_time, fn, args, kwargs, interval, repeat)

        fn.delay_at = delay_at
        fn.delay_in = delay_in
        fn.schedule = schedule
        return fn

    if func is not None:
        return wrapper(func)

    return wrapper

class RQScheduler(object):
    def __init__(self, app=None):
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        pass
<|endoftext|>


<commit_before>from Graph import Graph
class UndirectGraph( Graph ):

    def __init__( self ):
        super( UndirectGraph,self ).__init__()

    def connect( self, vertexA,vertexB,label = None ):
        if super().connect( vertexA,vertexB,label ) == False:
            return False
        self.graph[vertexB][vertexA] = label
        return True

    # verifica se o grafo é regular
    def isRegular( self ):
        lastValue = 0
        for v in self.graph:
            if lastValue == 0:
                lastValue = self.degree( v )
            elif lastValue != self.degree( v ):
                return False
        return True

    # verifica se o grafo é completo
    def isComplete( self ):
        totalVertex = len( self.graph )
        for v in self.graph:
            if self.degree( v ) != ( totalVertex -1 ):
                return False
        return True

    #verifica se o grafo é uma arvore
    def isTree( self ):
        anyVertex = self.anyVertex()
        return self.isConnected() and not( self._hasCycle( anyVertex,anyVertex,None,{} ) )

    #verifica se o grafo tem ciclos
    def _hasCycle( self,v,vCurrent,vPrevious,alreadyVisited ):

        if alreadyVisited.get( vCurrent,None ) != None:
            return vCurrent
        alreadyVisited[vCurrent] = {}
        for vertexRelated in self.related( v ):
            if vertexRelated != vPrevious:
                if self._hasCycle( v,vertexRelated,vCurrent,alreadyVisited ):
                    print('a')
                    print(v,vertexRelated,vCurrent,alreadyVisited)
                    return True
        del alreadyVisited[vCurrent]
        return False

    #verifica se o grafo é conexo TEM ERRO
    def isConnected( self ):
        for v in self.graph:
            if self.degree( v ) == 0:
                return False
        return True

    #retorna fecho transitivo de um vertice
    def transitiveClosure( self,vertex ):
        return self.isConnected() and self._findTransitiveClosure( vertex,{} )

    def _findTransitiveClosure( self, vertex, alreadyVisited ):
        alreadyVisited[vertex] = {}
        ft = alreadyVisited.copy()
        for vertexRelated in self.related( vertex ):
            if alreadyVisited.get( vertexRelated,None ) == None:
                ft.update( self._findTransitiveClosure( vertexRelated,alreadyVisited ) )
        return ft
<commit_msg>Correção no metodo que verifica se o Grafo é conexo<commit_after>from Graph import Graph
class UndirectGraph( Graph ):

    def __init__( self ):
        super( UndirectGraph,self ).__init__()

    def connect( self, vertexA,vertexB,label = None ):
        if super().connect( vertexA,vertexB,label ) == False:
            return False
        self.graph[vertexB][vertexA] = label
        return True

    # verifica se o grafo é regular
    def isRegular( self ):
        lastValue = 0
        for v in self.graph:
            if lastValue == 0:
                lastValue = self.degree( v )
            elif lastValue != self.degree( v ):
                return False
        return True

    # verifica se o grafo é completo
    def isComplete( self ):
        totalVertex = len( self.graph )
        for v in self.graph:
            if self.degree( v ) != ( totalVertex -1 ):
                return False
        return True

    #verifica se o grafo é uma arvore
    def isTree( self ):
        anyVertex = self.anyVertex()
        return self.isConnected() and not( self._hasCycle( anyVertex,anyVertex,None,{} ) )

    #verifica se o grafo tem ciclos
    def _hasCycle( self,v,vCurrent,vPrevious,alreadyVisited ):

        if alreadyVisited.get( vCurrent,None ) != None:
            return vCurrent
        alreadyVisited[vCurrent] = {}
        for vertexRelated in self.related( v ):
            if vertexRelated != vPrevious:
                if self._hasCycle( v,vertexRelated,vCurrent,alreadyVisited ):
                    return True
        del alreadyVisited[vCurrent]
        return False

    #verifica se o grafo é conexo
    def isConnected( self ):
        return self.getRelationVertex() == self._findTransitiveClosure( self.anyVertex(),{} ).keys()

    #retorna fecho transitivo de um vertice
    def transitiveClosure( self,vertex ):
        return self.isConnected() and self._findTransitiveClosure( vertex,{} )

    def _findTransitiveClosure( self, vertex, alreadyVisited ):
        alreadyVisited[vertex] = {}
        ft = alreadyVisited.copy()
        for vertexRelated in self.related( vertex ):
            if alreadyVisited.get( vertexRelated,None ) == None:
                ft.update( self._findTransitiveClosure( vertexRelated,alreadyVisited ) )
        return ft
<|endoftext|>


<commit_before>#!/usr/bin/env python
import sys
import logging
import traceback
from logging import config as logconfig

import servicemanager
import win32event
import win32service
import win32serviceutil
import click

from swak.config import select_and_parse
from swak.util import init_home, check_python_version
from swak.cli import main
from swak.version import VERSION

check_python_version()

def prog_name():
    if getattr(sys, 'frozen', False):
        return "swaksvc.exe"
    else:
        return "win_svc.py"

def show_usage():
    print("Swak version {}".format(VERSION))
    print("================== Swak Commands  ==================")
    ctx = click.Context(main, info_name="{} cli".format(prog_name()))
    print(ctx.get_help())
    print()
    sys.argv = [prog_name()]
    print("================= Service Commands =================")
    win32serviceutil.HandleCommandLine(None)

# Handle help / cli command beforehand (No need to parse config)
if len(sys.argv) > 2:
    cmd = sys.argv[1]
    if cmd == 'help':
        show_usage()
    elif cmd == 'cli':
        main(obj={}, prog_name="{} cli".format(prog_name()), args=sys.argv[2:])
        sys.exit()

home, cfg = select_and_parse(None)
# init required directories
init_home(home, cfg)
# init logger
logconfig.dictConfig(cfg['logger'])

class SwakService(win32serviceutil.ServiceFramework):
    _svc_name_ = cfg['svc_name']
    _svc_display_name_ = cfg['svc_dname']

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        servicemanager.LogInfoMsg("Service is stopping.")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        servicemanager.LogInfoMsg("Service is starting.")
        rc = None
        log_header()
        while rc != win32event.WAIT_OBJECT_0:
            try:
                pass
            except Exception:
                for l in traceback.format_exc().splitlines():
                    logging.error(l)
                break
            rc = win32event.WaitForSingleObject(self.hWaitStop, 0)
        log_footer()
        servicemanager.LogInfoMsg("Service is finished.")

def log_header():
    logging.critical("=============== Start service ===============")
    # cfg_path = get_cfg_path()

def log_footer():
    logging.critical("=============== Finish service ===============")

if __name__ == '__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(SwakService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(SwakService)
<commit_msg>fix help<commit_after>#!/usr/bin/env python
import sys
import logging
import traceback
from logging import config as logconfig

import servicemanager
import win32event
import win32service
import win32serviceutil
import click

from swak.config import select_and_parse
from swak.util import init_home, check_python_version
from swak.cli import main
from swak.version import VERSION

check_python_version()

def prog_name():
    if getattr(sys, 'frozen', False):
        return "swaksvc.exe"
    else:
        return "win_svc.py"

def show_usage():
    print("Swak version {}".format(VERSION))
    print("================== Swak Commands  ==================")
    ctx = click.Context(main, info_name="{} cli".format(prog_name()))
    print(ctx.get_help())
    print()
    sys.argv = [prog_name()]
    print("================= Service Commands =================")
    win32serviceutil.HandleCommandLine(None)

# Handle help / cli command beforehand (No need to parse config)
print(sys.argv)
if len(sys.argv) >= 2:
    cmd = sys.argv[1]
    if cmd == 'help':
        show_usage()
    elif cmd == 'cli':
        main(obj={}, prog_name="{} cli".format(prog_name()), args=sys.argv[2:])
        sys.exit()

home, cfg = select_and_parse(None)
# init required directories
init_home(home, cfg)
# init logger
logconfig.dictConfig(cfg['logger'])

class SwakService(win32serviceutil.ServiceFramework):
    _svc_name_ = cfg['svc_name']
    _svc_display_name_ = cfg['svc_dname']

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        servicemanager.LogInfoMsg("Service is stopping.")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        servicemanager.LogInfoMsg("Service is starting.")
        rc = None
        log_header()
        while rc != win32event.WAIT_OBJECT_0:
            try:
                pass
            except Exception:
                for l in traceback.format_exc().splitlines():
                    logging.error(l)
                break
            rc = win32event.WaitForSingleObject(self.hWaitStop, 0)
        log_footer()
        servicemanager.LogInfoMsg("Service is finished.")

def log_header():
    logging.critical("=============== Start service ===============")
    # cfg_path = get_cfg_path()

def log_footer():
    logging.critical("=============== Finish service ===============")

if __name__ == '__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(SwakService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(SwakService)
<|endoftext|>