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

import random
import datetime

from sampledatahelper.helper import SampleDataHelper

from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils.timezone import now

from django.contrib.webdesign import lorem_ipsum

from greenmine.base.users.models import *
from greenmine.projects.models import *
from greenmine.projects.milestones.models import *
from greenmine.projects.userstories.models import *
from greenmine.projects.tasks.models import *
from greenmine.projects.issues.models import *
#from greenmine.projects.questions.models import *
#from greenmine.projects.documents.models import *
from greenmine.projects.wiki.models import *

SUBJECT_CHOICES = [
    "Create the user model",
    "Implement the form",
    "Create the html template",
    "Fixing templates for Django 1.6.",
    "get_actions() does not check for 'delete_selected' in actions",
    "Experimental: modular file types",
    "Add setting to allow regular users to create folders at the root level.",
    "Add tests for bulk operations",
    "Create testsuite with matrix builds",
    "Lighttpd support",
    "Lighttpd x-sendfile support",
    "Added file copying and processing of images (resizing)",
    "Exception is thrown if trying to add a folder with existing name",
    "Feature/improved image admin",
    "Support for bulk actions",
    "Migrate to Python 3 and milk a beautiful cow"
]

class Command(BaseCommand):
    sd = SampleDataHelper(seed=12345678901)

    @transaction.commit_on_success
    def handle(self, *args, **options):
        self.users = [User.objects.get(is_superuser=True)]
        for x in range(10):
            self.users.append(self.create_user(x))

        # projects
        for x in range(4):
            project = self.create_project(x)

            for user in self.users:
                Membership.objects.create(
                        project=project,
                        role=self.sd.db_object_from_queryset(Role.objects.all()),
                        user=user)

            start_date = now() - datetime.timedelta(55)

            # create random milestones
            for y in range(self.sd.int(1, 5)):
                end_date = start_date + datetime.timedelta(15)
                milestone = self.create_milestone(project, start_date, end_date)

                # create uss asociated to milestones
                for z in range(self.sd.int(3, 7)):
                    us = self.create_us(project, milestone)

                    rang = (1, 4) if start_date <= now() and end_date <= now() else (0, 6)
                    for w in range(self.sd.int(*rang)):
                        if start_date <= now() and end_date <= now():
                            task = self.create_task(project, milestone, us, start_date, end_date, closed=True)
                        elif start_date <= now() and end_date >= now():
                            task = self.create_task(project, milestone, us, start_date, now())
                        else:
                            # No task on not initiated milestones
                            pass

                start_date = end_date

            # created unassociated uss.
            for y in range(self.sd.int(8,15)):
                us = self.create_us(project)

            # create bugs.
            for y in range(self.sd.int(15,25)):
                bug = self.create_bug(project)

            # create questions.
            #for y in range(self.sd.int(15,25)):
            #    question = self.create_question(project)

    #def create_question(self, project):
    #    question = Question.objects.create(
    #        project=project,
    #        subject=self.sd.choice(SUBJECT_CHOICES),
    #        content=self.sd.paragraph(),
    #        owner=project.owner,
    #        status=self.sd.db_object_from_queryset(project.question_status.all()),
    #        tags=self.sd.words(1,5).split(" "),
    #    )

    #    return question

    def create_bug(self, project):
        bug = Issue.objects.create(
            project=project,
            subject=self.sd.choice(SUBJECT_CHOICES),
            description=self.sd.paragraph(),
            owner=project.owner,
            severity=self.sd.db_object_from_queryset(Severity.objects.filter(project=project)),
            status=self.sd.db_object_from_queryset(IssueStatus.objects.filter(project=project)),
            priority=self.sd.db_object_from_queryset(Priority.objects.filter(project=project)),
            type=self.sd.db_object_from_queryset(IssueType.objects.filter(project=project)),
            tags=self.sd.words(1, 5).split(" "),
        )

        return bug

    def create_task(self, project, milestone, us, min_date, max_date, closed=False):
        task = Task(
            subject=self.sd.choice(SUBJECT_CHOICES),
            description=self.sd.paragraph(),
            project=project,
            owner=self.sd.choice(self.users),
            milestone=milestone,
            user_story=us,
            finished_date=None,
        )
        if closed:
            task.status = project.task_statuses.get(order=4)
        else:
            task.status = self.sd.db_object_from_queryset(project.task_statuses.all())

        if task.status.is_closed:
            task.finished_date = self.sd.datetime_between(min_date, max_date)

        task.save()
        return task

    def create_us(self, project, milestone=None):
        us = UserStory.objects.create(
            subject=self.sd.choice(SUBJECT_CHOICES),
            project=project,
            owner=self.sd.choice(self.users),
            description=self.sd.paragraph(),
            milestone=milestone,
            status=self.sd.db_object_from_queryset(project.us_statuses.filter(is_closed=False)),
            tags=self.sd.words(1, 3).split(" ")
        )

        for role_points in us.role_points.all():
            if milestone:
                role_points.points = self.sd.db_object_from_queryset(
                               us.project.points.exclude(value=None))
            else:
                role_points.points = self.sd.db_object_from_queryset(
                                            us.project.points.all())

            role_points.save()

        return us

    def create_milestone(self, project, start_date, end_date):
        milestone = Milestone.objects.create(
            project=project,
            name='Sprint {0}-{1}-{2}'.format(start_date.year,
                                             start_date.month,
                                             start_date.day),
            owner=project.owner,
            created_date=start_date,
            modified_date=start_date,
            estimated_start=start_date,
            estimated_finish=end_date,
            order=10
        )
        return milestone

    def create_project(self, counter):
        # create project
        project = Project.objects.create(
            name='Project Example {0}'.format(counter),
            description='Project example {0} description'.format(counter),
            owner=random.choice(self.users),
            public=True,
            total_story_points=self.sd.int(100, 150),
            total_milestones=self.sd.int(5,10)
        )

        return project

    def create_user(self, counter):
        user = User.objects.create(
            username='user-{0}'.format(counter),
            first_name=self.sd.name('es'),
            last_name=self.sd.surname('es'),
            email=self.sd.email(),
            token=''.join(random.sample('abcdef0123456789', 10)),
        )

        user.set_password('user{0}'.format(counter))
        user.save()
        return user
<commit_msg>Added color to the users and assigned to a project<commit_after># -*- coding: utf-8 -*-

import random
import datetime

from sampledatahelper.helper import SampleDataHelper

from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils.timezone import now

from django.contrib.webdesign import lorem_ipsum

from greenmine.base.users.models import *
from greenmine.projects.models import *
from greenmine.projects.milestones.models import *
from greenmine.projects.userstories.models import *
from greenmine.projects.tasks.models import *
from greenmine.projects.issues.models import *
#from greenmine.projects.questions.models import *
#from greenmine.projects.documents.models import *
from greenmine.projects.wiki.models import *

COLOR_CHOICES = [
    "#FC8EAC",
    "#A5694F",
    "#002e33",
    "#67CF00",
    "#71A6D2",
    "#FFF8E7",
    "#4B0082",
    "#007000",
    "#40826D",
    "#708090",
    "#761CEC",
    "#0F0F0F",
    "#D70A53",
    "#CC0000",
    "#FFCC00",
    "#FFFF00",
    "#C0FF33",
    "#B6DA55",
    "#2099DB",
]

SUBJECT_CHOICES = [
    "Create the user model",
    "Implement the form",
    "Create the html template",
    "Fixing templates for Django 1.6.",
    "get_actions() does not check for 'delete_selected' in actions",
    "Experimental: modular file types",
    "Add setting to allow regular users to create folders at the root level.",
    "Add tests for bulk operations",
    "Create testsuite with matrix builds",
    "Lighttpd support",
    "Lighttpd x-sendfile support",
    "Added file copying and processing of images (resizing)",
    "Exception is thrown if trying to add a folder with existing name",
    "Feature/improved image admin",
    "Support for bulk actions",
    "Migrate to Python 3 and milk a beautiful cow"
]

class Command(BaseCommand):
    sd = SampleDataHelper(seed=12345678901)

    @transaction.commit_on_success
    def handle(self, *args, **options):
        self.users = [User.objects.get(is_superuser=True)]
        for x in range(10):
            self.users.append(self.create_user(x))

        # projects
        for x in range(4):
            project = self.create_project(x)

            for user in self.users:
                Membership.objects.create(
                        project=project,
                        role=self.sd.db_object_from_queryset(Role.objects.all()),
                        user=user)

            start_date = now() - datetime.timedelta(55)

            # create random milestones
            for y in range(self.sd.int(1, 5)):
                end_date = start_date + datetime.timedelta(15)
                milestone = self.create_milestone(project, start_date, end_date)

                # create uss asociated to milestones
                for z in range(self.sd.int(3, 7)):
                    us = self.create_us(project, milestone)

                    rang = (1, 4) if start_date <= now() and end_date <= now() else (0, 6)
                    for w in range(self.sd.int(*rang)):
                        if start_date <= now() and end_date <= now():
                            task = self.create_task(project, milestone, us, start_date, end_date, closed=True)
                        elif start_date <= now() and end_date >= now():
                            task = self.create_task(project, milestone, us, start_date, now())
                        else:
                            # No task on not initiated milestones
                            pass

                start_date = end_date

            # created unassociated uss.
            for y in range(self.sd.int(8,15)):
                us = self.create_us(project)

            # create bugs.
            for y in range(self.sd.int(15,25)):
                bug = self.create_bug(project)

            # create questions.
            #for y in range(self.sd.int(15,25)):
            #    question = self.create_question(project)

    #def create_question(self, project):
    #    question = Question.objects.create(
    #        project=project,
    #        subject=self.sd.choice(SUBJECT_CHOICES),
    #        content=self.sd.paragraph(),
    #        owner=project.owner,
    #        status=self.sd.db_object_from_queryset(project.question_status.all()),
    #        tags=self.sd.words(1,5).split(" "),
    #    )

    #    return question

    def create_bug(self, project):
        bug = Issue.objects.create(
            project=project,
            subject=self.sd.choice(SUBJECT_CHOICES),
            description=self.sd.paragraph(),
            owner=project.owner,
            severity=self.sd.db_object_from_queryset(Severity.objects.filter(project=project)),
            status=self.sd.db_object_from_queryset(IssueStatus.objects.filter(project=project)),
            priority=self.sd.db_object_from_queryset(Priority.objects.filter(project=project)),
            type=self.sd.db_object_from_queryset(IssueType.objects.filter(project=project)),
            tags=self.sd.words(1, 5).split(" "),
        )

        return bug

    def create_task(self, project, milestone, us, min_date, max_date, closed=False):
        task = Task(
            subject=self.sd.choice(SUBJECT_CHOICES),
            description=self.sd.paragraph(),
            project=project,
            owner=self.sd.choice(self.users),
            milestone=milestone,
            user_story=us,
            finished_date=None,
            assigned_to = self.sd.db_object_from_queryset(
                                   project.memberships.all()).user
        )
        if closed:
            task.status = project.task_statuses.get(order=4)
        else:
            task.status = self.sd.db_object_from_queryset(project.task_statuses.all())

        if task.status.is_closed:
            task.finished_date = self.sd.datetime_between(min_date, max_date)

        task.save()
        return task

    def create_us(self, project, milestone=None):
        us = UserStory.objects.create(
            subject=self.sd.choice(SUBJECT_CHOICES),
            project=project,
            owner=self.sd.choice(self.users),
            description=self.sd.paragraph(),
            milestone=milestone,
            status=self.sd.db_object_from_queryset(project.us_statuses.filter(is_closed=False)),
            tags=self.sd.words(1, 3).split(" ")
        )

        for role_points in us.role_points.all():
            if milestone:
                role_points.points = self.sd.db_object_from_queryset(
                               us.project.points.exclude(value=None))
            else:
                role_points.points = self.sd.db_object_from_queryset(
                                            us.project.points.all())

            role_points.save()

        return us

    def create_milestone(self, project, start_date, end_date):
        milestone = Milestone.objects.create(
            project=project,
            name='Sprint {0}-{1}-{2}'.format(start_date.year,
                                             start_date.month,
                                             start_date.day),
            owner=project.owner,
            created_date=start_date,
            modified_date=start_date,
            estimated_start=start_date,
            estimated_finish=end_date,
            order=10
        )
        return milestone

    def create_project(self, counter):
        # create project
        project = Project.objects.create(
            name='Project Example {0}'.format(counter),
            description='Project example {0} description'.format(counter),
            owner=random.choice(self.users),
            public=True,
            total_story_points=self.sd.int(100, 150),
            total_milestones=self.sd.int(5,10)
        )

        return project

    def create_user(self, counter):
        user = User.objects.create(
            username='user-{0}'.format(counter),
            first_name=self.sd.name('es'),
            last_name=self.sd.surname('es'),
            email=self.sd.email(),
            token=''.join(random.sample('abcdef0123456789', 10)),
            color=self.sd.choice(COLOR_CHOICES)
        )

        user.set_password('user{0}'.format(counter))
        user.save()
        return user
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = r'''
---
module: bigip_policy_rule
short_description: Manage LTM policy rules on a BIG-IP
description:
  - This module will manage LTM policy rules on a BIG-IP.
version_added: 2.5
options:
  actions:
    description:
      - The actions that you want the policy rule to perform.
      - The available attributes vary by the action, however, each action requires that
        a C(type) be specified.
      - Available C(type) values are C(forward).
  append:
    description:
      - When C(yes), will append all C(conditions) and C(actions) to the
        given rule if they do not already exist.
      - When C(actions), will only append the specified actions. If C(conditions)
        are also provided, the existing conditions will be overwritten with the
        new list in the C(conditions) parameter.
      - When C(conditions), will only append the specified conditions. If C(actions)
        are also provided, the existing actions will be overwritten with the
        new list in the C(actions) parameter.
    choices:
      - yes
      - no
      - actions
      - conditions
    default: no
  policy:
    description:
      - The name of the policy that you want to associate this rule with.
    required: True
  name:
    description:
      - The name of the rule.
    required: True
  conditions:
    description:
      - A list of attributes that describe the condition.
      - See suboptions for details on how to construct each list entry.
      - The ordering of this list is important, the module will ensure the order is
        kept when modifying the task.
      - The suboption options listed below are not required for all condition types,
        read the description for more details.
    suboptions:
      type:
        description:
          - The condition type. This value controls what below options are required.
        required: true
        choices: [ http_uri ]
  state:
    description:
      - When C(present), ensures that the key is uploaded to the device. When
        C(absent), ensures that the key is removed from the device. If the key
        is currently in use, the module will not be able to remove the key.
    default: present
    choices:
      - present
      - absent
  partition:
    description:
      - Device partition to manage resources on.
    default: Common
notes:
  - Requires the f5-sdk Python package on the host. This is as easy as pip
    install f5-sdk.
extends_documentation_fragment: f5
requirements:
  - f5-sdk >= 3.0.0
  - BIG-IP >= v12.1.0
author:
  - Tim Rupp (@caphrim007)
'''

EXAMPLES = r'''
vars:
  policy_rules:
    - name: rule1
      actions:
    - type: forward
      pool: pool-svrs
  conditions:
    - type: http_uri
      path_starts_with: /euro
    - name: rule2
      actions:
    - type: forward
      pool: pool-svrs
  conditions:
    - type: http_uri
      path_starts_with: /HomePage/

- name: Create policies
  bigip_policy:
    name: Policy-Foo
    state: present
  delegate_to: localhost

- name: Add a rule to the new policy
  bigip_policy_rule:
    policy: Policy-Foo
    name: rule3
    conditions:
      - type: http_uri
        path_starts_with: /ABC
    actions:
      - type: forward
        pool: pool-svrs

- name: Add multiple rules to the new policy
  bigip_policy_rule:
    policy: Policy-Foo
    name: "{{ item.name }}"
    conditions: "{{ item.conditions }}"
    actions: "{{ item.actions }}"
  with_items:
    - policy_rules
'''

RETURN = r'''

'''

from ansible.module_utils.f5_utils import AnsibleF5Client
from ansible.module_utils.f5_utils import AnsibleF5Parameters
from ansible.module_utils.f5_utils import HAS_F5SDK
from ansible.module_utils.f5_utils import F5ModuleError
from ansible.module_utils.parsing.convert_bool import BOOLEANS
from ansible.module_utils.six import iteritems
from collections import defaultdict

try:
    # Test related
    from module_utils.f5networks.common import Noop
    from module_utils.f5networks.common import fqdn_name
    import q
except ImportError:
    pass

try:
    from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError
except ImportError:
    HAS_F5SDK = False

class Parameters(object):
    api_attributes = [
        'description'
    ]

    def __init__(self, *args, **kwargs):
        self._values = defaultdict(lambda: None)
        self._values['__warnings'] = []
        params = kwargs.get('params', None)
        q.q(params)
        if params:
            self.update(params)

    def update(self, params):
        self._values.update(params)

    @property
    def name(self):
        return self._values.get('name', None)

    @property
    def description(self):
        return self._values.get('description', None)

    @property
    def partition(self):
        return self._values.get('partition', 'Common')

    @property
    def strategy(self):
        value = self._values.get('strategy', None)
        if value is None:
            return None
        result = fqdn_name(self.partition, value)
        return result

    @property
    def policy(self):
        value = self._values.get('policy', None)
        if value is None:
            return None
        result = fqdn_name(self.partition, value)
        return result

class ApiParameters(Parameters):
    @staticmethod
    def to_params(self, changes):
        result = {}
        for api_attribute in self.api_attributes:
            if self.api_map is not None and api_attribute in self.api_map:
                result[api_attribute] = getattr(self, self.api_map[api_attribute])
            else:
                result[api_attribute] = getattr(self, api_attribute)
        result = self._filter_params(result)
        return result

class ModuleParameters(Parameters):
    @property
    def actions(self):
        pass

    @property
    def conditions(self):

class Changes(Parameters):
    returnables = []

    def to_return(self):
        result = {}
        try:
            for returnable in self.returnables:
                result[returnable] = getattr(self, returnable)
            result = self._filter_params(result)
        except Exception:
            pass
        return result

class Difference(object):
    updatables = [
        'actions', 'conditions', 'description'
    ]

    def __init__(self, *args, **kwargs):
        self.want = kwargs.get('want', None)
        self.have = kwargs.get('have', None)
        if self.want is None or self.have.have is None:
            raise F5ModuleError(
                "Calculating a difference requires 'want' and 'have' params."
            )

    def compare(self):
        result = dict()
        for param in self.updatables:
            try:
                change = getattr(self, param)
            except AttributeError:
                change = self.__default(param)
            if isinstance(change, dict):
                result.update(change)
            else:
                result[param] = change
        return result

    def __default(self, param):
        want = getattr(self.want, param)
        try:
            have = getattr(self.have, param)
            if want != have:
                return want
        except AttributeError:
            return want

    @property
    def actions(self):
        pass

    @property
    def conditions(self):
        pass

class ModuleManager(object):
    def __init__(self, client):
        self.client = client
        self.want = ModuleParameters(params=self.client.module.params)
        self.changes = Changes()

    def _update_changed_options(self):
        """Compares what you want with what you have.

        Returns:
            bool: True when changes are present. False otherwise.
        """
        diff = Difference(self.want, self.have)
        comparison = diff.compare()
        result = [r for r in comparison if not isistance(r[1], Noop)]
        if result:
            self.changes = Changes(params=result)
            return True
        return False

    def should_update(self):
        result = self._update_changed_options()
        if result:
            return True
        return False

    def exec_module(self):
        changed = False
        result = dict()
        state = self.want.state

        try:
            if state == "present":
                changed = self.present()
            elif state == "absent":
                changed = self.absent()
        except iControlUnexpectedHTTPError as e:
            raise F5ModuleError(str(e))

        changes = self.changes.to_return()
        result.update(**changes)
        result.update(dict(changed=changed))
        self._announce_deprecations(result)
        return result

    def _announce_deprecations(self, result):
        warnings = result.pop('__warnings', [])
        for warning in warnings:
            self.client.module.deprecate(
                msg=warning['msg'],
                version=warning['version']
            )

    def present(self):
        if self.exists():
            return self.update()
        else:
            return self.create()

    def exists(self):
        policy = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition
        )
        result = policy.rules_s.rules.exists(
            name=self.want.name
        )
        return result

    def update(self):
        self.have = self.read_current_from_device()
        if not self.should_update():
            return False
        if self.client.check_mode:
            return True
        self.update_on_device()
        return True

    def remove(self):
        if self.client.check_mode:
            return True
        self.remove_from_device()
        if self.exists():
            raise F5ModuleError("Failed to delete the resource.")
        return True

    def create(self):
        self.have = ApiParameters()
        self.should_update()
        if self.client.check_mode:
            return True
        self.create_on_device()
        return True

    def create_on_device(self):
        params = self.want.api_params()
        policy = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition
        )
        policy.rules_s.rules.create(
            name=self.want.name,
            **params
        )

    def update_on_device(self):
        params = self.want.api_params()
        policy = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition
        )
        resource = policy.rules_s.rules.load(
            name=self.want.name
        )
        resource.modify(**params)

    def absent(self):
        if self.exists():
            return self.remove()
        return False

    def remove_from_device(self):
        policy = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition
        )
        resource = policy.rules_s.rules.load(
            name=self.want.name
        )
        if resource:
            resource.delete()

    def read_current_from_device(self):
        resource = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition,
            requests_params=dict(
                params='expandSubcollections=true'
            )
        )
        return ApiParameters(params=resource.attrs)

class ArgumentSpec(object):
    def __init__(self):
        self.supports_check_mode = True
        conditions_suboption_spec = dict(
            type=dict(
                choices=[
                    'http_uri'
                ]
            )
        )
        actions_suboption_spec = dict(
            type=dict(
                choices=[
                    'forward'
                ]
            )
        )
        self.argument_spec = dict(
            append=dict(
                choices=['actions', 'conditions'] + BOOLEANS)
            ,
            actions=dict(
                type='list',
                options=actions_suboption_spec
            ),
            conditions=dict(
                type='list',
                options=conditions_suboption_spec
            ),
            name=dict(required=True),
            partition=dict(default='Common'),
            policy=dict(required=True),
        )
        self.f5_product_name = 'bigip'

def main():
    if not HAS_F5SDK:
        raise F5ModuleError("The python f5-sdk module is required")

    spec = ArgumentSpec()

    client = AnsibleF5Client(
        argument_spec=spec.argument_spec,
        supports_check_mode=spec.supports_check_mode,
        f5_product_name=spec.f5_product_name
    )

    try:
        mm = ModuleManager(client)
        results = mm.exec_module()
        client.module.exit_json(**results)
    except F5ModuleError as e:
        client.module.fail_json(msg=str(e))

if __name__ == '__main__':
    main()
<commit_msg>minor fixes<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = r'''
---
module: bigip_policy_rule
short_description: Manage LTM policy rules on a BIG-IP
description:
  - This module will manage LTM policy rules on a BIG-IP.
version_added: 2.5
options:
  actions:
    description:
      - The actions that you want the policy rule to perform.
      - The available attributes vary by the action, however, each action requires that
        a C(type) be specified.
      - Available C(type) values are C(forward).
  append:
    description:
      - When C(yes), will append all C(conditions) and C(actions) to the
        given rule if they do not already exist.
      - When C(actions), will only append the specified actions. If C(conditions)
        are also provided, the existing conditions will be overwritten with the
        new list in the C(conditions) parameter.
      - When C(conditions), will only append the specified conditions. If C(actions)
        are also provided, the existing actions will be overwritten with the
        new list in the C(actions) parameter.
    choices:
      - yes
      - no
      - actions
      - conditions
    default: no
  policy:
    description:
      - The name of the policy that you want to associate this rule with.
    required: True
  name:
    description:
      - The name of the rule.
    required: True
  conditions:
    description:
      - A list of attributes that describe the condition.
      - See suboptions for details on how to construct each list entry.
      - The ordering of this list is important, the module will ensure the order is
        kept when modifying the task.
      - The suboption options listed below are not required for all condition types,
        read the description for more details.
    suboptions:
      type:
        description:
          - The condition type. This value controls what below options are required.
        required: true
        choices: [ http_uri ]
  state:
    description:
      - When C(present), ensures that the key is uploaded to the device. When
        C(absent), ensures that the key is removed from the device. If the key
        is currently in use, the module will not be able to remove the key.
    default: present
    choices:
      - present
      - absent
  partition:
    description:
      - Device partition to manage resources on.
    default: Common
notes:
  - Requires the f5-sdk Python package on the host. This is as easy as pip
    install f5-sdk.
extends_documentation_fragment: f5
requirements:
  - f5-sdk >= 3.0.0
  - BIG-IP >= v12.1.0
author:
  - Tim Rupp (@caphrim007)
'''

EXAMPLES = r'''
vars:
  policy_rules:
    - name: rule1
      actions:
    - type: forward
      pool: pool-svrs
  conditions:
    - type: http_uri
      path_starts_with: /euro
    - name: rule2
      actions:
    - type: forward
      pool: pool-svrs
  conditions:
    - type: http_uri
      path_starts_with: /HomePage/

- name: Create policies
  bigip_policy:
    name: Policy-Foo
    state: present
  delegate_to: localhost

- name: Add a rule to the new policy
  bigip_policy_rule:
    policy: Policy-Foo
    name: rule3
    conditions:
      - type: http_uri
        path_starts_with: /ABC
    actions:
      - type: forward
        pool: pool-svrs

- name: Add multiple rules to the new policy
  bigip_policy_rule:
    policy: Policy-Foo
    name: "{{ item.name }}"
    conditions: "{{ item.conditions }}"
    actions: "{{ item.actions }}"
  with_items:
    - policy_rules
'''

RETURN = r'''

'''

from ansible.module_utils.f5_utils import AnsibleF5Client
from ansible.module_utils.f5_utils import AnsibleF5Parameters
from ansible.module_utils.f5_utils import HAS_F5SDK
from ansible.module_utils.f5_utils import F5ModuleError
from ansible.module_utils.parsing.convert_bool import BOOLEANS
from ansible.module_utils.six import iteritems
from collections import defaultdict

try:
    # Test related
    from module_utils.f5networks.common import Noop
    from module_utils.f5networks.common import fqdn_name
    import q
except ImportError:
    pass

try:
    from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError
except ImportError:
    HAS_F5SDK = False

class Parameters(object):
    api_attributes = [
        'description'
    ]

    def __init__(self, *args, **kwargs):
        self._values = defaultdict(lambda: None)
        self._values['__warnings'] = []
        params = kwargs.get('params', None)
        q.q(params)
        if params:
            self.update(params)

    def update(self, params):
        self._values.update(params)

    @property
    def name(self):
        return self._values.get('name', None)

    @property
    def description(self):
        return self._values.get('description', None)

    @property
    def partition(self):
        return self._values.get('partition', 'Common')

    @property
    def strategy(self):
        value = self._values.get('strategy', None)
        if value is None:
            return None
        result = fqdn_name(self.partition, value)
        return result

    @property
    def policy(self):
        value = self._values.get('policy', None)
        if value is None:
            return None
        result = fqdn_name(self.partition, value)
        return result

class ApiParameters(Parameters):
    @staticmethod
    def to_params(self, changes):
        result = {}
        for api_attribute in self.api_attributes:
            if self.api_map is not None and api_attribute in self.api_map:
                result[api_attribute] = getattr(self, self.api_map[api_attribute])
            else:
                result[api_attribute] = getattr(self, api_attribute)
        result = self._filter_params(result)
        return result

class ModuleParameters(Parameters):
    @property
    def actions(self):
        pass

    @property
    def conditions(self):
        pass

class Changes(Parameters):
    returnables = []

    def to_return(self):
        result = {}
        try:
            for returnable in self.returnables:
                result[returnable] = getattr(self, returnable)
            result = self._filter_params(result)
        except Exception:
            pass
        return result

class Difference(object):
    updatables = [
        'actions', 'conditions', 'description'
    ]

    def __init__(self, *args, **kwargs):
        self.want = kwargs.get('want', None)
        self.have = kwargs.get('have', None)
        if self.want is None or self.have.have is None:
            raise F5ModuleError(
                "Calculating a difference requires 'want' and 'have' params."
            )

    def compare(self):
        result = dict()
        for param in self.updatables:
            try:
                change = getattr(self, param)
            except AttributeError:
                change = self.__default(param)
            if isinstance(change, dict):
                result.update(change)
            else:
                result[param] = change
        return result

    def __default(self, param):
        want = getattr(self.want, param)
        try:
            have = getattr(self.have, param)
            if want != have:
                return want
        except AttributeError:
            return want

    @property
    def actions(self):
        pass

    @property
    def conditions(self):
        pass

class ModuleManager(object):
    def __init__(self, client):
        self.client = client
        self.want = ModuleParameters(params=self.client.module.params)
        self.changes = Changes()

    def _update_changed_options(self):
        """Compares what you want with what you have.

        Returns:
            bool: True when changes are present. False otherwise.
        """
        diff = Difference(self.want, self.have)
        comparison = diff.compare()
        result = [r for r in comparison if not isistance(r[1], Noop)]
        if result:
            self.changes = Changes(params=result)
            return True
        return False

    def should_update(self):
        result = self._update_changed_options()
        if result:
            return True
        return False

    def exec_module(self):
        changed = False
        result = dict()
        state = self.want.state

        try:
            if state == "present":
                changed = self.present()
            elif state == "absent":
                changed = self.absent()
        except iControlUnexpectedHTTPError as e:
            raise F5ModuleError(str(e))

        changes = self.changes.to_return()
        result.update(**changes)
        result.update(dict(changed=changed))
        self._announce_deprecations(result)
        return result

    def _announce_deprecations(self, result):
        warnings = result.pop('__warnings', [])
        for warning in warnings:
            self.client.module.deprecate(
                msg=warning['msg'],
                version=warning['version']
            )

    def present(self):
        if self.exists():
            return self.update()
        else:
            return self.create()

    def exists(self):
        policy = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition
        )
        result = policy.rules_s.rules.exists(
            name=self.want.name
        )
        return result

    def update(self):
        self.have = self.read_current_from_device()
        if not self.should_update():
            return False
        if self.client.check_mode:
            return True
        self.update_on_device()
        return True

    def remove(self):
        if self.client.check_mode:
            return True
        self.remove_from_device()
        if self.exists():
            raise F5ModuleError("Failed to delete the resource.")
        return True

    def create(self):
        self.have = ApiParameters()
        self.should_update()
        if self.client.check_mode:
            return True
        self.create_on_device()
        return True

    def create_on_device(self):
        params = self.want.api_params()
        policy = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition
        )
        policy.rules_s.rules.create(
            name=self.want.name,
            **params
        )

    def update_on_device(self):
        params = self.want.api_params()
        policy = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition
        )
        resource = policy.rules_s.rules.load(
            name=self.want.name
        )
        resource.modify(**params)

    def absent(self):
        if self.exists():
            return self.remove()
        return False

    def remove_from_device(self):
        policy = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition
        )
        resource = policy.rules_s.rules.load(
            name=self.want.name
        )
        if resource:
            resource.delete()

    def read_current_from_device(self):
        resource = self.client.api.tm.ltm.policys.policy.load(
            name=self.want.policy,
            partition=self.want.partition,
            requests_params=dict(
                params='expandSubcollections=true'
            )
        )
        return ApiParameters(params=resource.attrs)

class ArgumentSpec(object):
    def __init__(self):
        self.supports_check_mode = True
        conditions_suboption_spec = dict(
            type=dict(
                choices=[
                    'http_uri'
                ]
            )
        )
        actions_suboption_spec = dict(
            type=dict(
                choices=[
                    'forward',
                    'enable'
                ]
            )
        )
        self.argument_spec = dict(
            append=dict(
                choices=['actions', 'conditions'] + list(BOOLEANS)
            ),
            actions=dict(
                type='list',
                options=actions_suboption_spec
            ),
            conditions=dict(
                type='list',
                options=conditions_suboption_spec
            ),
            name=dict(required=True),
            partition=dict(default='Common'),
            policy=dict(required=True),
        )
        self.f5_product_name = 'bigip'

def main():
    if not HAS_F5SDK:
        raise F5ModuleError("The python f5-sdk module is required")

    spec = ArgumentSpec()

    client = AnsibleF5Client(
        argument_spec=spec.argument_spec,
        supports_check_mode=spec.supports_check_mode,
        f5_product_name=spec.f5_product_name
    )

    try:
        mm = ModuleManager(client)
        results = mm.exec_module()
        client.module.exit_json(**results)
    except F5ModuleError as e:
        client.module.fail_json(msg=str(e))

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


<commit_before># from django.test import TestCase
from django.test.utils import override_settings

from .testcase import DatatableViewTestCase
from .test_app import models
from .. import utils

@override_settings(INSTALLED_APPS=['datatableview.tests.test_app'])
class UtilsTests(DatatableViewTestCase):
    def test_get_first_orm_bit(self):
        """  """
        self.assertEqual(utils.get_first_orm_bit('field'), 'field')
        self.assertEqual(utils.get_first_orm_bit('field__otherfield'), 'field')
        self.assertEqual(utils.get_first_orm_bit(["Pretty Name", 'field']), 'field')
        self.assertEqual(utils.get_first_orm_bit(["Pretty Name", 'field', "callback"]), 'field')
        self.assertEqual(utils.get_first_orm_bit(["Pretty Name", 'field__otherfield']), 'field')
        self.assertEqual(utils.get_first_orm_bit(["Pretty Name", 'field__otherfield', "callback"]), 'field')

    def test_resolve_orm_path_local(self):
        """ Verifies that references to a local field on a model are returned. """
        field = utils.resolve_orm_path(models.ExampleModel, 'name')
        self.assertEqual(field, models.ExampleModel._meta.get_field_by_name('name')[0])

    def test_resolve_orm_path_fk(self):
        """ Verify that ExampleModel->RelatedModel.name == RelatedModel.name """
        remote_field = utils.resolve_orm_path(models.ExampleModel, 'related__name')
        self.assertEqual(remote_field, models.RelatedModel._meta.get_field_by_name('name')[0])

    def test_resolve_orm_path_reverse_fk(self):
        """ Verify that ExampleModel->>>ReverseRelatedModel.name == ReverseRelatedModel.name """
        remote_field = utils.resolve_orm_path(models.ExampleModel, 'reverserelatedmodel__name')
        self.assertEqual(remote_field, models.ReverseRelatedModel._meta.get_field_by_name('name')[0])

    def test_resolve_orm_path_m2m(self):
        """ Verify that ExampleModel->>>RelatedM2MModel.name == RelatedM2MModel.name """
        remote_field = utils.resolve_orm_path(models.ExampleModel, 'relateds__name')
        self.assertEqual(remote_field, models.RelatedM2MModel._meta.get_field_by_name('name')[0])

    def test_split_real_fields(self):
        """ Verifies that the first non-real field causes a break in the field list. """
        model = models.ExampleModel

        # All-real fields
        real, fake = utils.split_real_fields(model, ['name', 'date_created'])
        self.assertEqual(real, ['name', 'date_created'])
        self.assertEqual(fake, [])

        # No real fields
        real, fake = utils.split_real_fields(model, ['fake1', 'fake2'])
        self.assertEqual(real, [])
        self.assertEqual(fake, ['fake1', 'fake2'])

        # Real first, fake last
        real, fake = utils.split_real_fields(model, ['name', 'fake'])
        self.assertEqual(real, ['name'])
        self.assertEqual(fake, ['fake'])

        # Fake first, real last
        real, fake = utils.split_real_fields(model, ['fake', 'name'])
        self.assertEqual(real, [])
        self.assertEqual(fake, ['fake', 'name'])

    def test_filter_real_fields(self):
        model = models.ExampleModel
        fields = [
            'name',
            ('name',),
            ("Pretty Name", 'name'),
            ("Pretty Name", 'name', 'callback'),
        ]
        fakes = [
            'fake',
            ("Pretty Name", 'fake'),
            ("Pretty Name", 'fake', 'callback'),
            None,
            ("Pretty Name", None),
            ("Pretty Name", None, 'callback'),
        ]
        db_fields, virtual_fields = utils.filter_real_fields(model, fields + fakes,
                                                             key=utils.get_first_orm_bit)

        self.assertEqual(db_fields, fields)
        self.assertEqual(virtual_fields, fakes)
<commit_msg>Add DatatableStructure tests<commit_after># from django.test import TestCase
from django.test.utils import override_settings

from .testcase import DatatableViewTestCase
from .test_app import models
from .. import utils

def get_structure(columns, opts):
    return utils.get_datatable_structure('/', models.ExampleModel, dict(opts, columns=columns))

@override_settings(INSTALLED_APPS=['datatableview.tests.test_app'])
class UtilsTests(DatatableViewTestCase):
    def test_get_first_orm_bit(self):
        """  """
        self.assertEqual(utils.get_first_orm_bit('field'), 'field')
        self.assertEqual(utils.get_first_orm_bit('field__otherfield'), 'field')
        self.assertEqual(utils.get_first_orm_bit(["Pretty Name", 'field']), 'field')
        self.assertEqual(utils.get_first_orm_bit(["Pretty Name", 'field', "callback"]), 'field')
        self.assertEqual(utils.get_first_orm_bit(["Pretty Name", 'field__otherfield']), 'field')
        self.assertEqual(utils.get_first_orm_bit(["Pretty Name", 'field__otherfield', "callback"]), 'field')

    def test_resolve_orm_path_local(self):
        """ Verifies that references to a local field on a model are returned. """
        field = utils.resolve_orm_path(models.ExampleModel, 'name')
        self.assertEqual(field, models.ExampleModel._meta.get_field_by_name('name')[0])

    def test_resolve_orm_path_fk(self):
        """ Verify that ExampleModel->RelatedModel.name == RelatedModel.name """
        remote_field = utils.resolve_orm_path(models.ExampleModel, 'related__name')
        self.assertEqual(remote_field, models.RelatedModel._meta.get_field_by_name('name')[0])

    def test_resolve_orm_path_reverse_fk(self):
        """ Verify that ExampleModel->>>ReverseRelatedModel.name == ReverseRelatedModel.name """
        remote_field = utils.resolve_orm_path(models.ExampleModel, 'reverserelatedmodel__name')
        self.assertEqual(remote_field, models.ReverseRelatedModel._meta.get_field_by_name('name')[0])

    def test_resolve_orm_path_m2m(self):
        """ Verify that ExampleModel->>>RelatedM2MModel.name == RelatedM2MModel.name """
        remote_field = utils.resolve_orm_path(models.ExampleModel, 'relateds__name')
        self.assertEqual(remote_field, models.RelatedM2MModel._meta.get_field_by_name('name')[0])

    def test_split_real_fields(self):
        """ Verifies that the first non-real field causes a break in the field list. """
        model = models.ExampleModel

        # All-real fields
        real, fake = utils.split_real_fields(model, ['name', 'date_created'])
        self.assertEqual(real, ['name', 'date_created'])
        self.assertEqual(fake, [])

        # No real fields
        real, fake = utils.split_real_fields(model, ['fake1', 'fake2'])
        self.assertEqual(real, [])
        self.assertEqual(fake, ['fake1', 'fake2'])

        # Real first, fake last
        real, fake = utils.split_real_fields(model, ['name', 'fake'])
        self.assertEqual(real, ['name'])
        self.assertEqual(fake, ['fake'])

        # Fake first, real last
        real, fake = utils.split_real_fields(model, ['fake', 'name'])
        self.assertEqual(real, [])
        self.assertEqual(fake, ['fake', 'name'])

    def test_filter_real_fields(self):
        model = models.ExampleModel
        fields = [
            'name',
            ('name',),
            ("Pretty Name", 'name'),
            ("Pretty Name", 'name', 'callback'),
        ]
        fakes = [
            'fake',
            ("Pretty Name", 'fake'),
            ("Pretty Name", 'fake', 'callback'),
            None,
            ("Pretty Name", None),
            ("Pretty Name", None, 'callback'),
        ]
        db_fields, virtual_fields = utils.filter_real_fields(model, fields + fakes,
                                                             key=utils.get_first_orm_bit)

        self.assertEqual(db_fields, fields)
        self.assertEqual(virtual_fields, fakes)

    def test_structure_ordering(self):
        """ Verifies that the structural object correctly maps configuration values. """
        # Verify basic ordering
        columns = [
            'name',
        ]
        structure = get_structure(columns, { 'ordering': ['name'] })
        self.assertEqual(structure.ordering['name'].direction, 'asc')
        structure = get_structure(columns, { 'ordering': ['+name'] })
        self.assertEqual(structure.ordering['name'].direction, 'asc')
        structure = get_structure(columns, { 'ordering': ['-name'] })
        self.assertEqual(structure.ordering['name'].direction, 'desc')

        # Verify compound ordering is preserved
        columns = [
            'pk',
            'name',
        ]
        structure = get_structure(columns, { 'ordering': ['name', 'pk'] })
        self.assertEqual(structure.ordering['name'].order, 0)
        self.assertEqual(structure.ordering['pk'].order, 1)

        # Verify non-real field ordering is recognized when column is defined
        columns = [
            'fake',
        ]
        structure = get_structure(columns, { 'ordering': ['fake'] })
        self.assertEqual(structure.ordering['fake'].direction, 'asc')
        structure = get_structure(columns, { 'ordering': ['+fake'] })
        self.assertEqual(structure.ordering['fake'].direction, 'asc')
        structure = get_structure(columns, { 'ordering': ['-fake'] })
        self.assertEqual(structure.ordering['fake'].direction, 'desc')

        # Verify invalid ordering names are not included
        columns = [
            'name',
        ]
        structure = get_structure(columns, { 'ordering': ['fake', 'name'] })
        self.assertIn('name', structure.ordering)
        self.assertNotIn('fake', structure.ordering)

    def test_structure_data_api(self):
        """
        Verifies that unsortable_columns, hidden_columns, and ordering all add expected data-* API
        attributes
        """
        columns = [
            'pk',
            'name',
        ]
        structure = get_structure(columns, {})
        self.assertEqual(structure.get_column_attributes('name')['data-visible'], 'true')
        self.assertEqual(structure.get_column_attributes('name')['data-sortable'], 'true')
        structure = get_structure(columns, { 'hidden_columns': ['name'] })
        self.assertEqual(structure.get_column_attributes('name')['data-visible'], 'false')
        self.assertEqual(structure.get_column_attributes('name')['data-sortable'], 'true')
        structure = get_structure(columns, { 'unsortable_columns': ['name'] })
        self.assertEqual(structure.get_column_attributes('name')['data-visible'], 'true')
        self.assertEqual(structure.get_column_attributes('name')['data-sortable'], 'false')
        structure = get_structure(columns, { 'hidden_columns': ['name'], 'unsortable_columns': ['name'] })
        self.assertEqual(structure.get_column_attributes('name')['data-visible'], 'false')
        self.assertEqual(structure.get_column_attributes('name')['data-sortable'], 'false')
        structure = get_structure(columns, { 'ordering': ['-name', 'pk'] })
        self.assertEqual(structure.get_column_attributes('pk')['data-sorting'], '1,0,asc')
        self.assertEqual(structure.get_column_attributes('name')['data-sorting'], '0,1,desc')

    def test_structure_automatic_pretty_names(self):
        """ Verify columns missing Pretty Names receive one based on their field name. """
        columns = [
            ('Primary Key', 'pk'),
            'name',
        ]
        structure = get_structure(columns, {})
        column_info = structure.get_column_info()
        self.assertEqual(column_info[0].pretty_name, "Primary Key")
        self.assertEqual(column_info[1].pretty_name, "Name")

    def test_structure_is_iterable(self):
        columns = [
            'pk',
            'name',
            'fake',
        ]
        structure = get_structure(columns, {})
        self.assertEqual(len(list(structure)), len(columns))
<|endoftext|>


<commit_before>import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils

DATA_LIB="data/11-0.txt"
if __name__=="__main__":
	#load the raw ascii text
	filename = DATA_LIB
	raw_text = open(filename).read()
	raw_text = raw_text.lower()

	chars = sorted(list(set(raw_text)))
	print chars
	char_to_int = dict((c,i) for i,c in enumerate(chars))

	n_chars = len(raw_text)
	n_vocab = len(chars)
	print "Total Characters:", n_chars
	print "Total Vocab:", n_vocab

	seq_length = 100
	dataX = []
	dataY = []

	for i in range(0,n_chars - seq_length, 1):
		#selection
		seq_in = raw_text[i:i + seq_length]
		seq_out = raw_text[i + seq_length]
		#select data form, to make this more readable i should encapsulate it in methods
		dataX.append([char_to_int[char] for char in seq_in])
		dataY.append(char_to_int[seq_out])

	n_patterns = len(dataX)
	print "Total Patterns:", n_patterns

	X = numpy.reshape(dataX,(n_patterns,seq_length,1))
	X = X/float(n_vocab) #seems like a normalization of the vector weights?

	y = np_utils.to_categorical(dataY)

	#print X
	#print y
	model = Sequential()
	model.add(LSTM(256,input_shape=(X.shape[1],X.shape[2])))
	model.add(Dropout(0.2))
	model.add(Dense(y.shape[1],activation='softmax'))
	model.compile(loss='categorical_crossentropy',optimizer='adam')

	filepath="weights-improvement-{epoch:02d}-{loss:.4f}.hdf5"
	checkpoint = ModelCheckpoint(filepath,monitor='loss',verbose=1,save_best_only=True,mode='min')
	callback_list = [checkpoint]
	#fit the model
	model.fit(X,y,epochs=20, batch_size=128,callbacks=callback_list)
<commit_msg>Delete alice_in_wonderland.py<commit_after><|endoftext|>


<commit_before># multiAgents.py
# --------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to
# http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

from util import manhattanDistance
from game import Directions
import random, util

from game import Agent

class ReflexAgent(Agent):
    """
      A reflex agent chooses an action at each choice point by examining
      its alternatives via a state evaluation function.

      The code below is provided as a guide.  You are welcome to change
      it in any way you see fit, so long as you don't touch our method
      headers.
    """

    def getAction(self, gameState):
        """
        You do not need to change this method, but you're welcome to.

        getAction chooses among the best options according to the evaluation function.

        Just like in the previous project, getAction takes a GameState and returns
        some Directions.X for some X in the set {North, South, West, East, Stop}
        """
        # Collect legal moves and successor states
        legalMoves = gameState.getLegalActions()

        # Choose one of the best actions
        scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
        bestScore = max(scores)
        bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
        chosenIndex = random.choice(bestIndices) # Pick randomly among the best

        "Add more of your code here if you want to"

        return legalMoves[chosenIndex]

    def evaluationFunction(self, currentGameState, action):
        """
        Design a better evaluation function here.

        The evaluation function takes in the current and proposed successor
        GameStates (pacman.py) and returns a number, where higher numbers are better.

        The code below extracts some useful information from the state, like the
        remaining food (newFood) and Pacman position after moving (newPos).
        newScaredTimes holds the number of moves that each ghost will remain
        scared because of Pacman having eaten a power pellet.

        Print out these variables to see what you're getting, then combine them
        to create a masterful evaluation function.
        """
        # Useful information you can extract from a GameState (pacman.py)
        successorGameState = currentGameState.generatePacmanSuccessor(action)
        newPos = successorGameState.getPacmanPosition()
        newFood = successorGameState.getFood()
        newGhostStates = successorGameState.getGhostStates()
        newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]

        food_left = sum(int(j) for i in newFood for j in i)

        if food_left > 0:
            food_distances = [manhattanDistance(newPos, (x, y))
                              for x, row in enumerate(newFood)
                              for y, food in enumerate(row)
                              if food]
            shortest_food = min(food_distances)
        else:
            shortest_food = 0

        if newGhostStates:
            ghost_distances = [manhattanDistance(ghost.getPosition(), newPos)
                               for ghost in newGhostStates]
            shortest_ghost = min(ghost_distances)

            if shortest_ghost == 0:
                shortest_ghost = -2000
            else:
                shortest_ghost = -5 / shortest_ghost
        else:
            shortest_ghost = 0

        return -2 * shortest_food + shortest_ghost - 40 * food_left

def scoreEvaluationFunction(currentGameState):
    """
      This default evaluation function just returns the score of the state.
      The score is the same one displayed in the Pacman GUI.

      This evaluation function is meant for use with adversarial search agents
      (not reflex agents).
    """
    return currentGameState.getScore()

class MultiAgentSearchAgent(Agent):
    """
      This class provides some common elements to all of your
      multi-agent searchers.  Any methods defined here will be available
      to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.

      You *do not* need to make any changes here, but you can if you want to
      add functionality to all your adversarial search agents.  Please do not
      remove anything, however.

      Note: this is an abstract class: one that should not be instantiated.  It's
      only partially specified, and designed to be extended.  Agent (game.py)
      is another abstract class.
    """

    def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):
        self.index = 0 # Pacman is always agent index 0
        self.evaluationFunction = util.lookup(evalFn, globals())
        self.depth = int(depth)

class MinimaxAgent(MultiAgentSearchAgent):
    """
      Your minimax agent (question 2)
    """

    def getAction(self, gameState):
        """
          Returns the minimax action from the current gameState using self.depth
          and self.evaluationFunction.

          Here are some method calls that might be useful when implementing minimax.

          gameState.getLegalActions(agentIndex):
            Returns a list of legal actions for an agent
            agentIndex=0 means Pacman, ghosts are >= 1

          gameState.generateSuccessor(agentIndex, action):
            Returns the successor game state after an agent takes an action

          gameState.getNumAgents():
            Returns the total number of agents in the game
        """

        def _search_depth(state, depth, agent):
            if agent == state.getNumAgents():
                if depth == self.depth:
                    return self.evaluationFunction(state)
                else:
                    return _search_depth(state, depth + 1, 0)
            else:
                actions = state.getLegalActions(agent)

                if len(actions) == 0:
                    return self.evaluationFunction(state)

                next_states = (
                    _search_depth(state.generateSuccessor(agent, action),
                    depth, agent + 1)
                    for action in actions
                    )

                return (max if agent == 0 else min)(next_states)

        return max(
            gameState.getLegalActions(0),
            key = lambda x: _search_depth(gameState.generateSuccessor(0, x), 1, 1)
            )

class AlphaBetaAgent(MultiAgentSearchAgent):
    """
      Your minimax agent with alpha-beta pruning (question 3)
    """

    def getAction(self, gameState):
        """
          Returns the minimax action using self.depth and self.evaluationFunction
        """
        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()

class ExpectimaxAgent(MultiAgentSearchAgent):
    """
      Your expectimax agent (question 4)
    """

    def getAction(self, gameState):
        """
          Returns the expectimax action using self.depth and self.evaluationFunction

          All ghosts should be modeled as choosing uniformly at random from their
          legal moves.
        """
        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()

def betterEvaluationFunction(currentGameState):
    """
      Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
      evaluation function (question 5).

      DESCRIPTION: <write something here so we know what you did>
    """
    "*** YOUR CODE HERE ***"
    util.raiseNotDefined()

# Abbreviation
better = betterEvaluationFunction

class ContestAgent(MultiAgentSearchAgent):
    """
      Your agent for the mini-contest
    """

    def getAction(self, gameState):
        """
          Returns an action.  You can use any method you want and search to any depth you want.
          Just remember that the mini-contest is timed, so you have to trade off speed and computation.

          Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually
          just make a beeline straight towards Pacman (or away from him if they're scared!)
        """
        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()
<commit_msg>A partial solution to q3<commit_after># multiAgents.py
# --------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to
# http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

from util import manhattanDistance
from game import Directions
import random, util

from game import Agent

class ReflexAgent(Agent):
    """
      A reflex agent chooses an action at each choice point by examining
      its alternatives via a state evaluation function.

      The code below is provided as a guide.  You are welcome to change
      it in any way you see fit, so long as you don't touch our method
      headers.
    """

    def getAction(self, gameState):
        """
        You do not need to change this method, but you're welcome to.

        getAction chooses among the best options according to the evaluation function.

        Just like in the previous project, getAction takes a GameState and returns
        some Directions.X for some X in the set {North, South, West, East, Stop}
        """
        # Collect legal moves and successor states
        legalMoves = gameState.getLegalActions()

        # Choose one of the best actions
        scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
        bestScore = max(scores)
        bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
        chosenIndex = random.choice(bestIndices) # Pick randomly among the best

        "Add more of your code here if you want to"

        return legalMoves[chosenIndex]

    def evaluationFunction(self, currentGameState, action):
        """
        Design a better evaluation function here.

        The evaluation function takes in the current and proposed successor
        GameStates (pacman.py) and returns a number, where higher numbers are better.

        The code below extracts some useful information from the state, like the
        remaining food (newFood) and Pacman position after moving (newPos).
        newScaredTimes holds the number of moves that each ghost will remain
        scared because of Pacman having eaten a power pellet.

        Print out these variables to see what you're getting, then combine them
        to create a masterful evaluation function.
        """
        # Useful information you can extract from a GameState (pacman.py)
        successorGameState = currentGameState.generatePacmanSuccessor(action)
        newPos = successorGameState.getPacmanPosition()
        newFood = successorGameState.getFood()
        newGhostStates = successorGameState.getGhostStates()
        newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]

        food_left = sum(int(j) for i in newFood for j in i)

        if food_left > 0:
            food_distances = [manhattanDistance(newPos, (x, y))
                              for x, row in enumerate(newFood)
                              for y, food in enumerate(row)
                              if food]
            shortest_food = min(food_distances)
        else:
            shortest_food = 0

        if newGhostStates:
            ghost_distances = [manhattanDistance(ghost.getPosition(), newPos)
                               for ghost in newGhostStates]
            shortest_ghost = min(ghost_distances)

            if shortest_ghost == 0:
                shortest_ghost = -2000
            else:
                shortest_ghost = -5 / shortest_ghost
        else:
            shortest_ghost = 0

        return -2 * shortest_food + shortest_ghost - 40 * food_left

def scoreEvaluationFunction(currentGameState):
    """
      This default evaluation function just returns the score of the state.
      The score is the same one displayed in the Pacman GUI.

      This evaluation function is meant for use with adversarial search agents
      (not reflex agents).
    """
    return currentGameState.getScore()

class MultiAgentSearchAgent(Agent):
    """
      This class provides some common elements to all of your
      multi-agent searchers.  Any methods defined here will be available
      to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.

      You *do not* need to make any changes here, but you can if you want to
      add functionality to all your adversarial search agents.  Please do not
      remove anything, however.

      Note: this is an abstract class: one that should not be instantiated.  It's
      only partially specified, and designed to be extended.  Agent (game.py)
      is another abstract class.
    """

    def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):
        self.index = 0 # Pacman is always agent index 0
        self.evaluationFunction = util.lookup(evalFn, globals())
        self.depth = int(depth)

class MinimaxAgent(MultiAgentSearchAgent):
    """
      Your minimax agent (question 2)
    """

    def getAction(self, gameState):
        """
          Returns the minimax action from the current gameState using self.depth
          and self.evaluationFunction.

          Here are some method calls that might be useful when implementing minimax.

          gameState.getLegalActions(agentIndex):
            Returns a list of legal actions for an agent
            agentIndex=0 means Pacman, ghosts are >= 1

          gameState.generateSuccessor(agentIndex, action):
            Returns the successor game state after an agent takes an action

          gameState.getNumAgents():
            Returns the total number of agents in the game
        """

        def _search_depth(state, depth, agent):
            if agent == state.getNumAgents():
                if depth == self.depth:
                    return self.evaluationFunction(state)
                else:
                    return _search_depth(state, depth + 1, 0)
            else:
                actions = state.getLegalActions(agent)

                if len(actions) == 0:
                    return self.evaluationFunction(state)

                next_states = (
                    _search_depth(state.generateSuccessor(agent, action),
                    depth, agent + 1)
                    for action in actions
                    )

                return (max if agent == 0 else min)(next_states)

        return max(
            gameState.getLegalActions(0),
            key = lambda x: _search_depth(gameState.generateSuccessor(0, x), 1, 1)
            )

class AlphaBetaAgent(MultiAgentSearchAgent):
    """
      Your minimax agent with alpha-beta pruning (question 3)
    """

    def _can_prune(agent, alpha, beta, val):
        return False

    def getAction(self, gameState):
        """
          Returns the minimax action using self.depth and self.evaluationFunction
        """
        def min_val(state, depth, agent, alpha, beta):
            if agent == state.getNumAgents():
                return max_val(state, depth + 1, 0, alpha, beta)

            val = None
            for action in state.getLegalActions(agent):
                successor = min_val(state.generateSuccessor(agent, action), depth, agent + 1, alpha, beta)

                if val is None:
                    val = successor
                else:
                    val = min(val, successor)

                if val <= alpha:
                    return val
                beta = min(beta, val)

            if val is None:
                return self.evaluationFunction(state)

            return val

        def max_val(state, depth, agent, alpha, beta):
            assert agent == 0

            if depth == self.depth:
                return self.evaluationFunction(state)

            val = None
            for action in state.getLegalActions(agent):
                successor = min_val(state.generateSuccessor(agent, action), depth, agent + 1, alpha, beta)

                if val is None:
                    val = successor
                else:
                    val = max(val, successor)

                if val >= beta:
                    return val
                alpha = max(alpha, val)

            if val is None:
                return self.evaluationFunction(state)

            return val

        val, alpha, beta, best = None, None, None, None
        for action in gameState.getLegalActions(0):
            val = max(val, min_val(gameState.generateSuccessor(0, action), 1, 1, alpha, beta))
            # if val >= beta: return action
            if alpha is None:
                alpha, best = val, action
            else:
                alpha, best = max(val, alpha), action if val > alpha else best

        return best

class ExpectimaxAgent(MultiAgentSearchAgent):
    """
      Your expectimax agent (question 4)
    """

    def getAction(self, gameState):
        """
          Returns the expectimax action using self.depth and self.evaluationFunction

          All ghosts should be modeled as choosing uniformly at random from their
          legal moves.
        """
        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()

def betterEvaluationFunction(currentGameState):
    """
      Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
      evaluation function (question 5).

      DESCRIPTION: <write something here so we know what you did>
    """
    "*** YOUR CODE HERE ***"
    util.raiseNotDefined()

# Abbreviation
better = betterEvaluationFunction

class ContestAgent(MultiAgentSearchAgent):
    """
      Your agent for the mini-contest
    """

    def getAction(self, gameState):
        """
          Returns an action.  You can use any method you want and search to any depth you want.
          Just remember that the mini-contest is timed, so you have to trade off speed and computation.

          Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually
          just make a beeline straight towards Pacman (or away from him if they're scared!)
        """
        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()
<|endoftext|>


<commit_before>from django.shortcuts import render

# Create your views here.
<commit_msg>Removed old views.py<commit_after><|endoftext|>


<commit_before># Copyright 2018 Google Inc.
#
# 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.
"""Module for the manager of services."""
# TODO(xpconanfan: move the device errors to a more generic location so
# other device controllers like iOS can share it.
import collections
import contextlib
import inspect

from mobly import expects
from mobly.controllers.android_device_lib import errors
from mobly.controllers.android_device_lib.services import base_service

class Error(errors.DeviceError):
    """Root error type for this module."""

class ServiceManager(object):
    """Manager for services of AndroidDevice.

    A service is a long running process that involves an Android device, like
    adb logcat or Snippet.
    """

    def __init__(self, device):
        self._service_objects = collections.OrderedDict()
        self._device = device

    def has_service_by_name(self, name):
        """Checks if the manager has a service registered with a specific name.

        Args:
            name: string, the name to look for.

        Returns:
            True if a service is registered with the specified name, False
            otherwise.
        """
        return name in self._service_objects

    @property
    def is_any_alive(self):
        """True if any service is alive; False otherwise."""
        for service in self._service_objects.values():
            if service.is_alive:
                return True
        return False

    def register(self, alias, service_class, configs=None, start_service=True):
        """Registers a service.

        This will create a service instance, starts the service, and adds the
        instance to the mananger.

        Args:
            alias: string, the alias for this instance.
            service_class: class, the service class to instantiate.
            configs: (optional) config object to pass to the service class's
                constructor.
            start_service: bool, whether to start the service instance or not.
                Default is True.
        """
        if not inspect.isclass(service_class):
            raise Error(self._device, '"%s" is not a class!' % service_class)
        if not issubclass(service_class, base_service.BaseService):
            raise Error(
                self._device,
                'Class %s is not a subclass of BaseService!' % service_class)
        if alias in self._service_objects:
            raise Error(
                self._device,
                'A service is already registered with alias "%s".' % alias)
        service_obj = service_class(self._device, configs)
        service_obj.alias = alias
        if start_service:
            service_obj.start()
        self._service_objects[alias] = service_obj

    def unregister(self, alias):
        """Unregisters a service instance.

        Stops a service and removes it from the manager.

        Args:
            alias: string, the alias of the service instance to unregister.
        """
        if alias not in self._service_objects:
            raise Error(self._device,
                        'No service is registered with alias "%s".' % alias)
        service_obj = self._service_objects.pop(alias)
        if service_obj.is_alive:
            with expects.expect_no_raises(
                    'Failed to stop service instance "%s".' % alias):
                service_obj.stop()

    def for_each(self, func):
        """Executes a function with all registered services.

        Args:
            func: function, the function to execute. This function should take
                a service object as args.
        """
        aliases = list(self._service_objects.keys())
        for alias in aliases:
            with expects.expect_no_raises(
                    'Failed to execute "%s" for service "%s".' %
                (func.__name__, alias)):
                func(self._service_objects[alias])

    def list_live_services(self):
        """Lists the aliases of all the services that are alive.

        Order of this list is determined by the order the services are
        registered in.

        Returns:
            list of strings, the aliases of the services that are running.
        """
        aliases = []
        self.for_each(lambda service: aliases.append(service.alias)
                      if service.is_alive else None)
        return aliases

    def create_output_excerpts_all(self, test_info):
        """Creates output excerpts from all services.

        This calls `create_output_excerpts` on all registered services.

        Args:
            test_info: RuntimeTestInfo, the test info associated with the scope
                of the excerpts.

        Returns:
            Dict, keys are the names of the services, values are the paths to
                the excerpt files created by the corresponding services.
        """
        excerpt_paths = {}

        def create_output_excerpts_for_one(service):
            if not service.is_alive:
                return
            paths = service.create_output_excerpts(test_info)
            excerpt_paths[service.alias] = paths

        self.for_each(create_output_excerpts_for_one)
        return excerpt_paths

    def unregister_all(self):
        """Safely unregisters all active instances.

        Errors occurred here will be recorded but not raised.
        """
        aliases = list(self._service_objects.keys())
        for alias in aliases:
            self.unregister(alias)

    def start_all(self):
        """Starts all inactive service instances.

        Services will be started in the order they were registered.
        """
        for alias, service in self._service_objects.items():
            if not service.is_alive:
                with expects.expect_no_raises('Failed to start service "%s".' %
                                              alias):
                    service.start()

    def start_services(self, service_alises):
        """Starts the specified services.

        Services will be started in the order specified by the input list.
        No-op for services that are already running.

        Args:
            service_alises: list of strings, the aliases of services to start.
        """
        for name in service_alises:
            if name not in self._service_objects:
                raise Error(
                    self._device,
                    'No service is registered under the name "%s", cannot start.'
                    % name)
            service = self._service_objects[name]
            if not service.is_alive:
                service.start()

    def stop_all(self):
        """Stops all active service instances.

        Services will be stopped in the reverse order they were registered.
        """
        # OrdereDict#items does not return a sequence in Python 3.4, so we have
        # to do a list conversion here.
        for alias, service in reversed(list(self._service_objects.items())):
            if service.is_alive:
                with expects.expect_no_raises('Failed to stop service "%s".' %
                                              alias):
                    service.stop()

    def pause_all(self):
        """Pauses all service instances.

        Services will be paused in the reverse order they were registered.
        """
        # OrdereDict#items does not return a sequence in Python 3.4, so we have
        # to do a list conversion here.
        for alias, service in reversed(list(self._service_objects.items())):
            with expects.expect_no_raises('Failed to pause service "%s".' %
                                          alias):
                service.pause()

    def resume_all(self):
        """Resumes all service instances.

        Services will be resumed in the order they were registered.
        """
        for alias, service in self._service_objects.items():
            with expects.expect_no_raises('Failed to resume service "%s".' %
                                          alias):
                service.resume()

    def resume_services(self, service_alises):
        """Resumes the specified services.

        Services will be resumed in the order specified by the input list.
        No-op for services that are already running.

        Args:
            service_alises: list of strings, the names of services to start.
        """
        for name in service_alises:
            if name not in self._service_objects:
                raise Error(
                    self._device,
                    'No service is registered under the name "%s", cannot resume.'
                    % name)
            service = self._service_objects[name]
            if not service.is_alive:
                service.resume()

    def __getattr__(self, name):
        """Syntactic sugar to enable direct access of service objects by alias.

        Args:
            name: string, the alias a service object was registered under.
        """
        if self.has_service_by_name(name):
            return self._service_objects[name]
        return self.__getattribute__(name)
<commit_msg>Do not check if a service is `alive` in `resume_services`. (#663)<commit_after># Copyright 2018 Google Inc.
#
# 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.
"""Module for the manager of services."""
# TODO(xpconanfan: move the device errors to a more generic location so
# other device controllers like iOS can share it.
import collections
import contextlib
import inspect

from mobly import expects
from mobly.controllers.android_device_lib import errors
from mobly.controllers.android_device_lib.services import base_service

class Error(errors.DeviceError):
    """Root error type for this module."""

class ServiceManager(object):
    """Manager for services of AndroidDevice.

    A service is a long running process that involves an Android device, like
    adb logcat or Snippet.
    """

    def __init__(self, device):
        self._service_objects = collections.OrderedDict()
        self._device = device

    def has_service_by_name(self, name):
        """Checks if the manager has a service registered with a specific name.

        Args:
            name: string, the name to look for.

        Returns:
            True if a service is registered with the specified name, False
            otherwise.
        """
        return name in self._service_objects

    @property
    def is_any_alive(self):
        """True if any service is alive; False otherwise."""
        for service in self._service_objects.values():
            if service.is_alive:
                return True
        return False

    def register(self, alias, service_class, configs=None, start_service=True):
        """Registers a service.

        This will create a service instance, starts the service, and adds the
        instance to the mananger.

        Args:
            alias: string, the alias for this instance.
            service_class: class, the service class to instantiate.
            configs: (optional) config object to pass to the service class's
                constructor.
            start_service: bool, whether to start the service instance or not.
                Default is True.
        """
        if not inspect.isclass(service_class):
            raise Error(self._device, '"%s" is not a class!' % service_class)
        if not issubclass(service_class, base_service.BaseService):
            raise Error(
                self._device,
                'Class %s is not a subclass of BaseService!' % service_class)
        if alias in self._service_objects:
            raise Error(
                self._device,
                'A service is already registered with alias "%s".' % alias)
        service_obj = service_class(self._device, configs)
        service_obj.alias = alias
        if start_service:
            service_obj.start()
        self._service_objects[alias] = service_obj

    def unregister(self, alias):
        """Unregisters a service instance.

        Stops a service and removes it from the manager.

        Args:
            alias: string, the alias of the service instance to unregister.
        """
        if alias not in self._service_objects:
            raise Error(self._device,
                        'No service is registered with alias "%s".' % alias)
        service_obj = self._service_objects.pop(alias)
        if service_obj.is_alive:
            with expects.expect_no_raises(
                    'Failed to stop service instance "%s".' % alias):
                service_obj.stop()

    def for_each(self, func):
        """Executes a function with all registered services.

        Args:
            func: function, the function to execute. This function should take
                a service object as args.
        """
        aliases = list(self._service_objects.keys())
        for alias in aliases:
            with expects.expect_no_raises(
                    'Failed to execute "%s" for service "%s".' %
                (func.__name__, alias)):
                func(self._service_objects[alias])

    def list_live_services(self):
        """Lists the aliases of all the services that are alive.

        Order of this list is determined by the order the services are
        registered in.

        Returns:
            list of strings, the aliases of the services that are running.
        """
        aliases = []
        self.for_each(lambda service: aliases.append(service.alias)
                      if service.is_alive else None)
        return aliases

    def create_output_excerpts_all(self, test_info):
        """Creates output excerpts from all services.

        This calls `create_output_excerpts` on all registered services.

        Args:
            test_info: RuntimeTestInfo, the test info associated with the scope
                of the excerpts.

        Returns:
            Dict, keys are the names of the services, values are the paths to
                the excerpt files created by the corresponding services.
        """
        excerpt_paths = {}

        def create_output_excerpts_for_one(service):
            if not service.is_alive:
                return
            paths = service.create_output_excerpts(test_info)
            excerpt_paths[service.alias] = paths

        self.for_each(create_output_excerpts_for_one)
        return excerpt_paths

    def unregister_all(self):
        """Safely unregisters all active instances.

        Errors occurred here will be recorded but not raised.
        """
        aliases = list(self._service_objects.keys())
        for alias in aliases:
            self.unregister(alias)

    def start_all(self):
        """Starts all inactive service instances.

        Services will be started in the order they were registered.
        """
        for alias, service in self._service_objects.items():
            if not service.is_alive:
                with expects.expect_no_raises('Failed to start service "%s".' %
                                              alias):
                    service.start()

    def start_services(self, service_alises):
        """Starts the specified services.

        Services will be started in the order specified by the input list.
        No-op for services that are already running.

        Args:
            service_alises: list of strings, the aliases of services to start.
        """
        for name in service_alises:
            if name not in self._service_objects:
                raise Error(
                    self._device,
                    'No service is registered under the name "%s", cannot start.'
                    % name)
            service = self._service_objects[name]
            if not service.is_alive:
                service.start()

    def stop_all(self):
        """Stops all active service instances.

        Services will be stopped in the reverse order they were registered.
        """
        # OrdereDict#items does not return a sequence in Python 3.4, so we have
        # to do a list conversion here.
        for alias, service in reversed(list(self._service_objects.items())):
            if service.is_alive:
                with expects.expect_no_raises('Failed to stop service "%s".' %
                                              alias):
                    service.stop()

    def pause_all(self):
        """Pauses all service instances.

        Services will be paused in the reverse order they were registered.
        """
        # OrdereDict#items does not return a sequence in Python 3.4, so we have
        # to do a list conversion here.
        for alias, service in reversed(list(self._service_objects.items())):
            with expects.expect_no_raises('Failed to pause service "%s".' %
                                          alias):
                service.pause()

    def resume_all(self):
        """Resumes all service instances.

        Services will be resumed in the order they were registered.
        """
        for alias, service in self._service_objects.items():
            with expects.expect_no_raises('Failed to resume service "%s".' %
                                          alias):
                service.resume()

    def resume_services(self, service_alises):
        """Resumes the specified services.

        Services will be resumed in the order specified by the input list.

        Args:
            service_alises: list of strings, the names of services to start.
        """
        for name in service_alises:
            if name not in self._service_objects:
                raise Error(
                    self._device,
                    'No service is registered under the name "%s", cannot resume.'
                    % name)
            service = self._service_objects[name]
            service.resume()

    def __getattr__(self, name):
        """Syntactic sugar to enable direct access of service objects by alias.

        Args:
            name: string, the alias a service object was registered under.
        """
        if self.has_service_by_name(name):
            return self._service_objects[name]
        return self.__getattribute__(name)
<|endoftext|>