<commit_before># Copyright 2014, Oliver Nagy <olitheolix@gmail.com>
#
# This file is part of Azrael (https://github.com/olitheolix/azrael)
#
# Azrael is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Azrael is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Azrael. If not, see <http://www.gnu.org/licenses/>.

"""
Define the State Variables structure and its cencoding.

The state variables are encapsulated by the named tuple ``BulletData``. This
module contains the necessary conversions to/from binary, as well as a
conversion to NumPy. The NumPy conversion was necessary for the Cython
wrapper to Bullet. This has become redundant and will be cleaned up at some
point.
"""

import sys
import logging
import IPython
import numpy as np
import azrael.util
import azrael.config as config

from collections import namedtuple
from azrael.typecheck import typecheck
from azrael.protocol_json import loads, dumps

ipshell = IPython.embed

# All relevant physics data.
_BulletData = namedtuple('BulletData',
                         'scale imass restitution orientation '
                         'position velocityLin velocityRot cshape '
                         'axesLockLin axesLockRot checksumGeometry')

class BulletData(_BulletData):
    """
    Return a ``BulletData`` object.

    Without any arguments this function will return a valid ``BulletData``
    specimen with sensible defaults.
    """
    @typecheck
    def __new__(cls,
                scale: (int, float)=1,
                imass: (int, float)=1,
                restitution: (int, float)=0.9,
                orientation: (list, np.ndarray)=[0, 0, 0, 1],
                position: (list, np.ndarray)=[0, 0, 0],
                velocityLin: (list, np.ndarray)=[0, 0, 0],
                velocityRot: (list, np.ndarray)=[0, 0, 0],
                cshape: (list, np.ndarray)=[0, 1, 1, 1],
                axesLockLin: (list, np.ndarray)=[1, 1, 1],
                axesLockRot: (list, np.ndarray)=[1, 1, 1],
                checksumGeometry: int=0,
                ):

        # Convert arguments to NumPy types where necessary.
        position = np.array(position, np.float64)
        orientation = np.array(orientation, np.float64)
        velocityLin = np.array(velocityLin, np.float64)
        velocityRot = np.array(velocityRot, np.float64)
        cshape = np.array(cshape, np.float64)
        axesLockLin = np.array(axesLockLin, np.float64)
        axesLockRot = np.array(axesLockRot, np.float64)

        # Sanity checks.
        try:
            assert len(axesLockLin) == len(axesLockRot) == 3
            assert len(orientation) == len(cshape) == 4
            assert len(position) == len(velocityLin) == len(velocityRot) == 3
            assert checksumGeometry >= 0
        except (AssertionError, TypeError) as err:
            return None

        # Build the actual named tuple.
        return super().__new__(
            cls,
            scale=scale,
            imass=imass,
            restitution=restitution,
            orientation=orientation,
            position=position,
            velocityLin=velocityLin,
            velocityRot=velocityRot,
            cshape=cshape,
            axesLockLin=axesLockLin,
            axesLockRot=axesLockRot,
            checksumGeometry=checksumGeometry)

    def __eq__(self, ref):
        """
        Two ``BulletData`` instances are considered equal their content matches
        well.

        Small rounding errors are possible, especially when Bullet is involved
        since it uses 32Bit data types internally.
        """
        # Sanity check.
        if not isinstance(ref, type(self)):
            return False

        # Test all fields except cshape.
        for f in self._fields:
            if f == 'cshape':
                continue
            if not np.allclose(getattr(self, f), getattr(ref, f), atol=1E-9):
                return False
        return True

    def __ne__(self, ref):
        return not self.__eq__(ref)

    def toJsonDict(self):
        """
        Convert ``BulletData`` to JSON encodeable dictionary.
        """
        # fixme: use list comprehension
        d = {}
        for f in self._fields:
            d[f] = getattr(self, f)

        # The dictionary 'd' is alreay what we want. However, it still contains
        # some NumPy arrays which JSON cannot serialise. To avoid manually
        # converting all of them to lists we simply use our own JSON encoder
        # which does that automatically, and then decode it again. The result
        # is the same.
        return loads(dumps(d))

class BulletDataOverride(_BulletData):
    """
    Create a ``_BulletData`` named tuple.

    The only difference between this class and ``bullet_data.BulletData`` is
    that this class permits *None* values.
    """
    @typecheck
    def __new__(cls, *args, **kwargs):
        """
        This method merely uses a default value of *None* for every unspecified
        field in the named tuple.
        """
        # Convert all positional- and keyword arguments that are not None to a
        # dictionary of keyword arguments. Step 1: convert the positional
        # arguments to a dictionary...
        kwargs_tmp = dict(zip(_BulletData._fields, args))

        # ... Step 2: Remove all keys where the value is None...
        kwargs_tmp = {k: v for (k, v) in kwargs_tmp.items() if v is not None}

        # ... Step 3: add the original keyword arguments that are not None.
        for key, value in kwargs.items():
            if value is not None:
                kwargs_tmp[key] = value
        kwargs = kwargs_tmp
        del args, kwargs_tmp

        # Create a BulletData instance. Return an error if this fails.
        try:
            sv = BulletData(**kwargs)
        except TypeError:
            sv = None
        if sv is None:
            return None

        # Create keyword arguments for all fields and populate them all
        # with *None*.
        kwargs_all = {f: None for f in BulletData._fields}

        # Overwrite those keys for which we actually have a value. Note that we
        # will not use the valued supplied to this function directly but use
        # the ones from the temporary BulletData object because this ensures
        # the data types were correctly converted (mosty lists to NumPy
        # arrays).
        for key in kwargs:
            kwargs_all[key] = getattr(sv, key)

        # Create the ``_BulletData`` named tuple.
        return super().__new__(cls, **kwargs_all)

@typecheck
def fromJsonDict(data):
    """
    Unpack the JSON encoded ``BulletData`` in ``data``.
    """
    args = [data[_] for _ in BulletData._fields]
    return BulletData(*args)
<commit_msg>TLC in 'BulletData'.<commit_after># Copyright 2014, Oliver Nagy <olitheolix@gmail.com>
#
# This file is part of Azrael (https://github.com/olitheolix/azrael)
#
# Azrael is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Azrael is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Azrael. If not, see <http://www.gnu.org/licenses/>.

"""
Define the State Variables structure and its cencoding.

The state variables are encapsulated by the named tuple ``BulletData``. This
module contains the necessary conversions to/from binary, as well as a
conversion to NumPy. The NumPy conversion was necessary for the Cython
wrapper to Bullet. This has become redundant and will be cleaned up at some
point.
"""

import sys
import logging
import IPython
import numpy as np
import azrael.util
import azrael.config as config

from collections import namedtuple
from azrael.typecheck import typecheck
from azrael.protocol_json import loads, dumps

ipshell = IPython.embed

# All relevant physics data.
_BulletData = namedtuple('BulletData',
                         'scale imass restitution orientation '
                         'position velocityLin velocityRot cshape '
                         'axesLockLin axesLockRot checksumGeometry')

class BulletData(_BulletData):
    """
    Return a ``BulletData`` object.

    Without any arguments this function will return a valid ``BulletData``
    specimen with sensible defaults.
    """
    @typecheck
    def __new__(cls,
                scale: (int, float)=1,
                imass: (int, float)=1,
                restitution: (int, float)=0.9,
                orientation: (list, np.ndarray)=[0, 0, 0, 1],
                position: (list, np.ndarray)=[0, 0, 0],
                velocityLin: (list, np.ndarray)=[0, 0, 0],
                velocityRot: (list, np.ndarray)=[0, 0, 0],
                cshape: (list, np.ndarray)=[0, 1, 1, 1],
                axesLockLin: (list, np.ndarray)=[1, 1, 1],
                axesLockRot: (list, np.ndarray)=[1, 1, 1],
                checksumGeometry: int=0,
                ):

        # Convert arguments to NumPy types where necessary.
        position = np.array(position, np.float64)
        orientation = np.array(orientation, np.float64)
        velocityLin = np.array(velocityLin, np.float64)
        velocityRot = np.array(velocityRot, np.float64)
        cshape = np.array(cshape, np.float64)
        axesLockLin = np.array(axesLockLin, np.float64)
        axesLockRot = np.array(axesLockRot, np.float64)

        # Sanity checks.
        try:
            assert len(axesLockLin) == len(axesLockRot) == 3
            assert len(orientation) == len(cshape) == 4
            assert len(position) == len(velocityLin) == len(velocityRot) == 3
            assert checksumGeometry >= 0
        except (AssertionError, TypeError) as err:
            return None

        # Build the actual named tuple.
        return super().__new__(
            cls,
            scale=scale,
            imass=imass,
            restitution=restitution,
            orientation=orientation,
            position=position,
            velocityLin=velocityLin,
            velocityRot=velocityRot,
            cshape=cshape,
            axesLockLin=axesLockLin,
            axesLockRot=axesLockRot,
            checksumGeometry=checksumGeometry)

    def __eq__(self, ref):
        """
        Two ``BulletData`` instances are considered equal their content matches
        well.

        Small rounding errors are possible, especially when Bullet is involved
        since it uses 32Bit data types internally.
        """
        # Sanity check.
        if not isinstance(ref, type(self)):
            return False

        # Test all fields except cshape.
        for f in self._fields:
            if f == 'cshape':
                continue
            if not np.allclose(getattr(self, f), getattr(ref, f), atol=1E-9):
                return False
        return True

    def __ne__(self, ref):
        return not self.__eq__(ref)

    def toJsonDict(self):
        """
        Convert content of ``BulletData`` instance to JSON dictionary.
        """
        # NamedTuple --> Dictionary.
        d = {field: getattr(self, field) for field in self._fields}

        # The dictionary 'd' is alreay what we want. However, it still contains
        # some NumPy arrays which JSON cannot serialise. To avoid manually
        # converting all of them to lists we simply use our own JSON encoder
        # which does that automatically, and then decode it again. The result
        # is the same.
        return loads(dumps(d))

class BulletDataOverride(_BulletData):
    """
    Create a ``_BulletData`` named tuple.

    The only difference between this class and ``bullet_data.BulletData`` is
    that this class permits *None* values.
    """
    @typecheck
    def __new__(cls, *args, **kwargs):
        """
        This method merely uses a default value of *None* for every unspecified
        field in the named tuple.
        """
        # Convert all positional- and keyword arguments that are not None to a
        # dictionary of keyword arguments. Step 1: convert the positional
        # arguments to a dictionary...
        kwargs_tmp = dict(zip(_BulletData._fields, args))

        # ... Step 2: Remove all keys where the value is None...
        kwargs_tmp = {k: v for (k, v) in kwargs_tmp.items() if v is not None}

        # ... Step 3: add the original keyword arguments that are not None.
        for key, value in kwargs.items():
            if value is not None:
                kwargs_tmp[key] = value
        kwargs = kwargs_tmp
        del args, kwargs_tmp

        # Create a BulletData instance. Return an error if this fails.
        try:
            sv = BulletData(**kwargs)
        except TypeError:
            sv = None
        if sv is None:
            return None

        # Create keyword arguments for all fields and populate them all
        # with *None*.
        kwargs_all = {f: None for f in BulletData._fields}

        # Overwrite those keys for which we actually have a value. Note that we
        # will not use the valued supplied to this function directly but use
        # the ones from the temporary BulletData object because this ensures
        # the data types were correctly converted (mosty lists to NumPy
        # arrays).
        for key in kwargs:
            kwargs_all[key] = getattr(sv, key)

        # Create the ``_BulletData`` named tuple.
        return super().__new__(cls, **kwargs_all)

@typecheck
def fromJsonDict(data):
    """
    Unpack the JSON encoded ``BulletData`` in ``data``.
    """
    args = [data[_] for _ in BulletData._fields]
    return BulletData(*args)
<|endoftext|>


<commit_before>#!/usr/bin/env python3
from botocore.exceptions import ClientError

TABLE_DEFINITION = {"hash_key": "composite_doi",
                    "range_key": "score",
                    "rec_attribute": "rec_dois"}
REC_TYPES = set(('classic', 'expert'))
DATASETS = ['wos']

class Table(object):
    """
    Wrapping a DynamoDB table for use.

    Arguments:
        connection: A dynamodb resource object, likely created via boto3.resource("dynamodb")
        table_name: The name of the table to operate on.

    """
    def __init__(self, connection, table_name):
        self.table_name = table_name
        self.hash_key = TABLE_DEFINITION["hash_key"]
        self.range_key = TABLE_DEFINITION["range_key"]
        self.rec_attribute = TABLE_DEFINITION["rec_attribute"]
        self.rec_types = REC_TYPES
        self.connection = connection
        self.table = None

    def get_table(self):
        if not self.table:
            self.table = self.connection.Table(self.table_name)
        return self.table

    def create(self, read=5, write=5):
        self.table = self.connection.create_table(
            TableName=self.table_name,
            KeySchema=[
                {"AttributeName": self.hash_key,
                 "KeyType": "HASH"},
                {"AttributeName": self.range_key,
                 "KeyType": "RANGE"}],
            AttributeDefinitions=[
                {"AttributeName": self.hash_key,
                 "AttributeType": "S"},
                {"AttributeName": self.range_key,
                 "AttributeType": "N"},
                #{"AttributeName": self.rec_attribute,
                # "AttributeType": "SS"}
                ],
            ProvisionedThroughput={
                "ReadCapacityUnits": read,
                "WriteCapacityUnits": write})
        self.table.meta.client.get_waiter('table_exists').wait(TableName=self.table_name)

    def delete(self):
        try:
            self.get_table().delete()
            self.get_table().meta.client.get_waiter('table_not_exists').wait(TableName=self.table_name)
            self.table = None
        except ClientError:
            pass

    def get_batch_put_context(self):
        """
        Returns the context manager to use for batched put requests.

        See https://boto3.readthedocs.org/en/latest/guide/dynamodb.html for details
        """
        return self.get_table().batch_writer()

    def put_entry(self, entry):
        return self.get_table().put_item(entry)

    def update_throughput(self, read=5, write=5):
        return self.connection.meta.client.update_table(ProvisionedThroughput={'ReadCapacityUnits': read,
                                                                               'WriteCapacityUnits': write},
                                                        TableName=self.table_name)

<commit_msg>made aminer tweak<commit_after>#!/usr/bin/env python3
from botocore.exceptions import ClientError

TABLE_DEFINITION = {"hash_key": "composite_doi",
                    "range_key": "score",
                    "rec_attribute": "rec_dois"}
REC_TYPES = set(('classic', 'expert'))
DATASETS = ['wos', 'aminer']

class Table(object):
    """
    Wrapping a DynamoDB table for use.

    Arguments:
        connection: A dynamodb resource object, likely created via boto3.resource("dynamodb")
        table_name: The name of the table to operate on.

    """
    def __init__(self, connection, table_name):
        self.table_name = table_name
        self.hash_key = TABLE_DEFINITION["hash_key"]
        self.range_key = TABLE_DEFINITION["range_key"]
        self.rec_attribute = TABLE_DEFINITION["rec_attribute"]
        self.rec_types = REC_TYPES
        self.connection = connection
        self.table = None

    def get_table(self):
        if not self.table:
            self.table = self.connection.Table(self.table_name)
        return self.table

    def create(self, read=5, write=5):
        self.table = self.connection.create_table(
            TableName=self.table_name,
            KeySchema=[
                {"AttributeName": self.hash_key,
                 "KeyType": "HASH"},
                {"AttributeName": self.range_key,
                 "KeyType": "RANGE"}],
            AttributeDefinitions=[
                {"AttributeName": self.hash_key,
                 "AttributeType": "S"},
                {"AttributeName": self.range_key,
                 "AttributeType": "N"},
                #{"AttributeName": self.rec_attribute,
                # "AttributeType": "SS"}
                ],
            ProvisionedThroughput={
                "ReadCapacityUnits": read,
                "WriteCapacityUnits": write})
        self.table.meta.client.get_waiter('table_exists').wait(TableName=self.table_name)

    def delete(self):
        try:
            self.get_table().delete()
            self.get_table().meta.client.get_waiter('table_not_exists').wait(TableName=self.table_name)
            self.table = None
        except ClientError:
            pass

    def get_batch_put_context(self):
        """
        Returns the context manager to use for batched put requests.

        See https://boto3.readthedocs.org/en/latest/guide/dynamodb.html for details
        """
        return self.get_table().batch_writer()

    def put_entry(self, entry):
        return self.get_table().put_item(entry)

    def update_throughput(self, read=5, write=5):
        return self.connection.meta.client.update_table(ProvisionedThroughput={'ReadCapacityUnits': read,
                                                                               'WriteCapacityUnits': write},
                                                        TableName=self.table_name)

<|endoftext|>


<commit_before>import sublime
import sublime_plugin
import threading
from xml.etree import ElementTree
from .lib.requests import requests
from .src.stations import stations, abbreviations
from .src.Route import Route
from .src.PluginUtils import get_pref, set_settings

bsa_url = 'http://api.bart.gov/api/bsa.aspx'
sched_url = 'http://api.bart.gov/api/sched.aspx'
api_key = 'MW9S-E7SL-26DU-VV8V'

class ScheduleCommand(sublime_plugin.WindowCommand):

    def run(self):
        self.origin = None
        self.destination = None
        self.choose_station(self.on_origin_choosen)
        self.routes = []

    def on_origin_choosen(self, index):
        if index is -1:
            return None

        self.origin = abbreviations[index]
        sublime.set_timeout(
            lambda: self.choose_station(self.on_destination_choosen), 10
        )

    def on_destination_choosen(self, index):
        if index is -1:
            return None

        self.destination = abbreviations[index]
        planner = RoutePlanner(self.window, self.origin, self.destination)
        threading.Thread(target=planner.get_route_plan).start()

    def choose_station(self, callback):
        self.window.show_quick_panel(stations, callback)

class GoHomeCommand(sublime_plugin.WindowCommand):

    def run(self):
        home = get_pref('home')
        work = get_pref('work')
        planner = RoutePlanner(self.window, work, home)
        threading.Thread(target=planner.get_route_plan).start()

class GoToWorkCommand(sublime_plugin.WindowCommand):

    def run(self):
        home = get_pref('home')
        work = get_pref('work')
        planner = RoutePlanner(self.window, home, work)
        threading.Thread(target=planner.get_route_plan).start()

class RoutePlanner():

    def __init__(self, window, origin, destination):
        self.routes = []
        self.window = window
        self.origin = origin
        self.destination = destination

    def get_route_plan(self):
        params = self.get_params_with_key({
            'cmd': 'depart',
            'orig': self.origin,
            'dest': self.destination
        })
        res = requests.get(sched_url, params=params)
        self.handle_route_plan_response(res.text)

    def handle_route_plan_response(self, response):
        root = ElementTree.fromstring(response)
        schedule = root.find('schedule')
        trips = schedule.find('request').findall('trip')
        routes = []
        for trip in trips:
            routes.append(Route(trip.attrib, trip.findall('leg')))

        self.routes = routes
        sublime.set_timeout(
            lambda: self.show_routes(), 10
        )

    def show_routes(self):
        route_descriptions = list(map(
            lambda route: route.short_description(), self.routes
        ))
        self.window.show_quick_panel(route_descriptions, self.on_route_choosen)

    def get_params_with_key(self, params):
        params['key'] = 'MW9S-E7SL-26DU-VV8V'
        return params

    def on_route_choosen(self, index):
        if index is -1:
            return
        route = self.routes[index]
        if route.has_transfer():
            legs = route.long_description()
            sublime.set_timeout(
                lambda: self.window.show_quick_panel(legs, noop)
            )

class ChangeSettingsCommand(sublime_plugin.WindowCommand):

    def run(self, key):
        self.key = key
        self.choose_station(self.on_station_choosen)

    def on_station_choosen(self, index):
        if index >= 0:
            set_settings(self.key, abbreviations[index])

    def choose_station(self, callback):
        self.window.show_quick_panel(stations, callback)

def noop(self, index):
    return
<commit_msg>Add docstring comments<commit_after>import sublime
import sublime_plugin
import threading
from xml.etree import ElementTree
from .lib.requests import requests
from .src.stations import stations, abbreviations
from .src.Route import Route
from .src.PluginUtils import get_pref, set_settings

bsa_url = 'http://api.bart.gov/api/bsa.aspx'
sched_url = 'http://api.bart.gov/api/sched.aspx'
api_key = 'MW9S-E7SL-26DU-VV8V'

class ScheduleCommand(sublime_plugin.WindowCommand):
    """Sublime Window Command which prompts the user for an
    origin and destination BART station, requests real
    time departure and arrival information from the BART API
    and displays it to the user"""

    def run(self):
        """Called when the command is executed.  Runs the command"""
        self.origin = None
        self.destination = None
        self.choose_station(self.on_origin_choosen)
        self.routes = []

    def on_origin_choosen(self, index):
        """Callback for when the originating station is choosen.
        Sets self.origin and prompts the user for the destination
        station"""

        if index is -1:
            return None

        self.origin = abbreviations[index]
        sublime.set_timeout(
            lambda: self.choose_station(self.on_destination_choosen), 10
        )

    def on_destination_choosen(self, index):
        """Callback for when the destination station is choosen.
        Sets self.destination and makes the BART API request on
        a new thread"""

        if index is -1:
            return None

        self.destination = abbreviations[index]
        planner = RoutePlanner(self.window, self.origin, self.destination)
        threading.Thread(target=planner.get_route_plan).start()

    def choose_station(self, callback):
        """Propmts the user for a BART station"""
        self.window.show_quick_panel(stations, callback)

class GoHomeCommand(sublime_plugin.WindowCommand):
    """Sublime Window Command which requests real time arrival
    and departure information from the BART API for the saved home
    and work stations and displays it to the user"""

    def run(self):
        """Called when the command is executed. Runs the command"""
        home = get_pref('home')
        work = get_pref('work')
        planner = RoutePlanner(self.window, work, home)
        threading.Thread(target=planner.get_route_plan).start()

class GoToWorkCommand(sublime_plugin.WindowCommand):
    """Same as GoHomeCommand but with origin and destination switched"""

    def run(self):
        """Called when the command is executed. Runs the command"""
        home = get_pref('home')
        work = get_pref('work')
        planner = RoutePlanner(self.window, home, work)
        threading.Thread(target=planner.get_route_plan).start()

class RoutePlanner():
    """Helper class for planning routes. Handles requesting the BART API
    based on an origin and destination station. Additionally parses the
    resulting xml response."""

    def __init__(self, window, origin, destination):
        self.routes = []
        self.window = window
        self.origin = origin
        self.destination = destination

    def get_route_plan(self):
        params = self.get_params_with_key({
            'cmd': 'depart',
            'orig': self.origin,
            'dest': self.destination
        })
        res = requests.get(sched_url, params=params)
        self.handle_route_plan_response(res.text)

    def handle_route_plan_response(self, response):
        root = ElementTree.fromstring(response)
        schedule = root.find('schedule')
        trips = schedule.find('request').findall('trip')
        routes = []
        for trip in trips:
            routes.append(Route(trip.attrib, trip.findall('leg')))

        self.routes = routes
        sublime.set_timeout(
            lambda: self.show_routes(), 10
        )

    def show_routes(self):
        route_descriptions = list(map(
            lambda route: route.short_description(), self.routes
        ))
        self.window.show_quick_panel(route_descriptions, self.on_route_choosen)

    def get_params_with_key(self, params):
        params['key'] = 'MW9S-E7SL-26DU-VV8V'
        return params

    def on_route_choosen(self, index):
        if index is -1:
            return
        route = self.routes[index]
        if route.has_transfer():
            legs = route.long_description()
            sublime.set_timeout(
                lambda: self.window.show_quick_panel(legs, noop)
            )

class ChangeSettingsCommand(sublime_plugin.WindowCommand):
    """Sublime Window Command for setting the default home
    and work stations."""

    def run(self, key):
        self.key = key
        self.choose_station(self.on_station_choosen)

    def on_station_choosen(self, index):
        if index >= 0:
            set_settings(self.key, abbreviations[index])

    def choose_station(self, callback):
        self.window.show_quick_panel(stations, callback)

def noop(self, index):
    return
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json, csv<commit_msg>varios<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json, csv
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from opps.core.tests.models.channel import *
from opps.core.tests.models.source import *
<commit_msg>fix models did not validate, Accessor for field CommandError: One or more models did not validate: core.channel: Accessor for field 'user' clashes with related field 'User.channel_set'. Add a related_name argument to the definition for 'user'. core.channel: Accessor for field 'site' clashes with related field 'Site.channel_set'. Add a related_name argument to the definition for 'site'. channel.channel: Accessor for field 'user' clashes with related field 'User.channel_set'. Add a related_name argument to the definition for 'user'. channel.channel: Accessor for field 'site' clashes with related field 'Site.channel_set'. Add a related_name argument to the definition for 'site'.<commit_after># -*- coding: utf-8 -*-
from opps.core.tests.models.source import *
<|endoftext|>


<commit_before># coding=utf8
"""
search.py - Willie Web Search Module
Copyright 2008-9, Sean B. Palmer, inamidst.com
Copyright 2012, Edward Powell, embolalia.net
Licensed under the Eiffel Forum License 2.

http://willie.dftba.net
"""
from __future__ import unicode_literals

import re
from willie import web
from willie.module import commands, example
import json
import sys
import time

def formatnumber(n):
    """Format a number with beautiful commas."""
    parts = list(str(n))
    for i in range((len(parts) - 3), 0, -3):
        parts.insert(i, ',')
    return ''.join(parts)

r_bing = re.compile(r'
')

def duck_search(query):
    query = query.replace('!', '')
    uri = 'http://duckduckgo.com/html/?q=%s&kl=uk-en' % query
    bytes = web.get(uri)
    if 'web-result"' in bytes:  # filter out the adds on top of the page
        bytes = bytes.split('web-result"')[1]
    m = r_duck.search(bytes)
    if m:
        return web.decode(m.group(1))

# Alias google_search to duck_search
google_search = duck_search

def duck_api(query):
    if '!bang' in query.lower():
        return 'https://duckduckgo.com/bang.html'

    uri = 'http://api.duckduckgo.com/?q=%s&format=json&no_html=1&no_redirect=1' % query
    results = json.loads(web.get(uri))
    if results['Redirect']:
        return results['Redirect']
    else:
        return None

@commands('duck', 'ddg', 'g')
@example('.duck privacy or .duck !mcwiki obsidian')
def duck(bot, trigger):
    """Queries Duck Duck Go for the specified input."""
    query = trigger.group(2)
    if not query:
        return bot.reply('.ddg what?')

    # If the API gives us something, say it and stop
    result = duck_api(query)
    if result:
        bot.reply(result)
        return

    # Otherwise, look it up on the HTMl version
    uri = duck_search(query)

    if uri:
        bot.reply(uri)
        if 'last_seen_url' in bot.memory:
            bot.memory['last_seen_url'][trigger.sender] = uri
    else:
        bot.reply("No results found for '%s'." % query)

@commands('search')
@example('.search nerdfighter')
def search(bot, trigger):
    """Searches Bing and Duck Duck Go."""
    if not trigger.group(2):
        return bot.reply('.search for what?')
    query = trigger.group(2)
    bu = bing_search(query) or '-'
    du = duck_search(query) or '-'

    if bu == du:
        result = '%s (b, d)' % gu
    else:
        if len(bu) > 150:
            bu = '(extremely long link)'
        if len(du) > 150:
            du = '(extremely long link)'
        result = '%s (b), %s (d)' % (bu, du)

    bot.reply(result)

@commands('suggest')
def suggest(bot, trigger):
    """Suggest terms starting with given input"""
    if not trigger.group(2):
        return bot.reply("No query term.")
    query = trigger.group(2)
    uri = 'http://websitedev.de/temp-bin/suggest.pl?q='
    answer = web.get(uri + query.replace('+', '%2B'))
    if answer:
        bot.say(answer)
    else:
        bot.reply('Sorry, no result.')
<commit_msg>search: remove useless imports<commit_after># coding=utf8
"""
search.py - Willie Web Search Module
Copyright 2008-9, Sean B. Palmer, inamidst.com
Copyright 2012, Edward Powell, embolalia.net
Licensed under the Eiffel Forum License 2.

http://willie.dftba.net
"""
from __future__ import unicode_literals

import re
from willie import web
from willie.module import commands, example
import json

def formatnumber(n):
    """Format a number with beautiful commas."""
    parts = list(str(n))
    for i in range((len(parts) - 3), 0, -3):
        parts.insert(i, ',')
    return ''.join(parts)

r_bing = re.compile(r'
')

def duck_search(query):
    query = query.replace('!', '')
    uri = 'http://duckduckgo.com/html/?q=%s&kl=uk-en' % query
    bytes = web.get(uri)
    if 'web-result"' in bytes:  # filter out the adds on top of the page
        bytes = bytes.split('web-result"')[1]
    m = r_duck.search(bytes)
    if m:
        return web.decode(m.group(1))

# Alias google_search to duck_search
google_search = duck_search

def duck_api(query):
    if '!bang' in query.lower():
        return 'https://duckduckgo.com/bang.html'

    uri = 'http://api.duckduckgo.com/?q=%s&format=json&no_html=1&no_redirect=1' % query
    results = json.loads(web.get(uri))
    if results['Redirect']:
        return results['Redirect']
    else:
        return None

@commands('duck', 'ddg', 'g')
@example('.duck privacy or .duck !mcwiki obsidian')
def duck(bot, trigger):
    """Queries Duck Duck Go for the specified input."""
    query = trigger.group(2)
    if not query:
        return bot.reply('.ddg what?')

    # If the API gives us something, say it and stop
    result = duck_api(query)
    if result:
        bot.reply(result)
        return

    # Otherwise, look it up on the HTMl version
    uri = duck_search(query)

    if uri:
        bot.reply(uri)
        if 'last_seen_url' in bot.memory:
            bot.memory['last_seen_url'][trigger.sender] = uri
    else:
        bot.reply("No results found for '%s'." % query)

@commands('search')
@example('.search nerdfighter')
def search(bot, trigger):
    """Searches Bing and Duck Duck Go."""
    if not trigger.group(2):
        return bot.reply('.search for what?')
    query = trigger.group(2)
    bu = bing_search(query) or '-'
    du = duck_search(query) or '-'

    if bu == du:
        result = '%s (b, d)' % gu
    else:
        if len(bu) > 150:
            bu = '(extremely long link)'
        if len(du) > 150:
            du = '(extremely long link)'
        result = '%s (b), %s (d)' % (bu, du)

    bot.reply(result)

@commands('suggest')
def suggest(bot, trigger):
    """Suggest terms starting with given input"""
    if not trigger.group(2):
        return bot.reply("No query term.")
    query = trigger.group(2)
    uri = 'http://websitedev.de/temp-bin/suggest.pl?q='
    answer = web.get(uri + query.replace('+', '%2B'))
    if answer:
        bot.say(answer)
    else:
        bot.reply('Sorry, no result.')
<|endoftext|>


<commit_before>#!/usr/bin/env python
import xlsxwriter as xl
import os

path = '.'

# Create a workbook and add a worksheet.
workbook = xl.Workbook('results_wmseg_dices.xlsx')
worksheet_36 = workbook.add_worksheet('36subjects')
worksheet_28 = workbook.add_worksheet('28subjects')
worksheet_20 = workbook.add_worksheet('20subjects')
worksheet_15 = workbook.add_worksheet('15subjects')
worksheet_10 = workbook.add_worksheet('10subjects')
worksheet_5 = workbook.add_worksheet('5subjects')
worksheet_2 = workbook.add_worksheet('2subjects')

bold = workbook.add_format({'bold': True})

worksheets = {'36subjects': [worksheet_36, 2, {}], '28subjects': [worksheet_28, 2, {}], '20subjects': [worksheet_20, 2, {}], '15subjects': [worksheet_15, 2, {}], '10subjects': [worksheet_10, 2, {}], '5subjects': [worksheet_5, 2, {}], '2subjects': [worksheet_2, 2, {}]}

for w in worksheets.values():
    w[0].write(1, 0, 'Subject', bold)
    w[0].write(1, 1, 'Slice #', bold)
    w[0].write(1, 2, 'Slice level', bold)

    for mod in range(8):
        w[0].write(1, 3+3*mod, 'Dice - gamma 1.2', bold)
        w[0].write(1, 3+3*mod+1, 'Dice - gamma 0', bold)
        w[0].write(1, 3+3*mod+2, 'Number of model slices', bold)
        w[0].merge_range(0, 3+3*mod, 0, 3+3*mod+2, str(mod), bold)

for loocv_dir in os.listdir(path):
    if os.path.isdir(path + '/' + loocv_dir):
        words = loocv_dir.split('_')
        n_sub = words[0]
        mod = int(words[1])
        gamma = words[-1]
        if gamma == '1.2':
            to_add_col = 0
        else:
            to_add_col = 1

        dice_file = open(path + '/' + loocv_dir + '/wm_dice_coeff.txt', 'r')
        dice_lines = dice_file.readlines()
        dice_file.close()

        dice_lines = [line.split(' ') for line in dice_lines]

        col = 0
        for line in dice_lines:
            line[2] = line[2][:-1]
            line[-1] = line[-1][:-1]
            line.pop(4)
            line.pop(4)
            slice_id = '_'.join(line[:2])
            if slice_id not in worksheets[n_sub][2].keys():
                worksheets[n_sub][2][slice_id] = worksheets[n_sub][1]
                for i, v in enumerate(line[:3]):
                    worksheets[n_sub][0].write(worksheets[n_sub][1], col+i, v)
                worksheets[n_sub][0].write(worksheets[n_sub][1], 3+3*mod+to_add_col, line[3])
                worksheets[n_sub][0].write(worksheets[n_sub][1], 3+3*mod+2, line[-1])
                worksheets[n_sub][1] += 1
            else:
                worksheets[n_sub][0].write(worksheets[n_sub][2][slice_id], 3+3*mod+to_add_col, line[3])
                worksheets[n_sub][0].write(worksheets[n_sub][2][slice_id], 3+3*mod+2, line[-1])

workbook.close()<commit_msg>OPT: extracting results from LOOCV<commit_after>#!/usr/bin/env python
import xlsxwriter as xl
import os

path = '.'

# ############################# MULTIPLE LOOCV FROM MAGMA #############################
# Create a workbook and add a worksheet.
workbook = xl.Workbook('results_wmseg_dices.xlsx')
worksheet_36 = workbook.add_worksheet('36subjects')
worksheet_28 = workbook.add_worksheet('28subjects')
worksheet_20 = workbook.add_worksheet('20subjects')
worksheet_15 = workbook.add_worksheet('15subjects')
worksheet_10 = workbook.add_worksheet('10subjects')
worksheet_5 = workbook.add_worksheet('5subjects')
worksheet_2 = workbook.add_worksheet('2subjects')

bold = workbook.add_format({'bold': True})

worksheets = {'36subjects': [worksheet_36, 2, {}], '28subjects': [worksheet_28, 2, {}], '20subjects': [worksheet_20, 2, {}], '15subjects': [worksheet_15, 2, {}], '10subjects': [worksheet_10, 2, {}], '5subjects': [worksheet_5, 2, {}], '2subjects': [worksheet_2, 2, {}]}

for w in worksheets.values():
    w[0].write(1, 0, 'Subject', bold)
    w[0].write(1, 1, 'Slice #', bold)
    w[0].write(1, 2, 'Slice level', bold)

    for mod in range(8):
        w[0].write(1, 3+3*mod, 'Dice - gamma 1.2', bold)
        w[0].write(1, 3+3*mod+1, 'Dice - gamma 0', bold)
        w[0].write(1, 3+3*mod+2, 'Number of model slices', bold)
        w[0].merge_range(0, 3+3*mod, 0, 3+3*mod+2, str(mod), bold)

for loocv_dir in os.listdir(path):
    if os.path.isdir(path + '/' + loocv_dir) and 'dictionary' not in loocv_dir:
        words = loocv_dir.split('_')
        n_sub = words[0]
        mod = int(words[1])
        gamma = words[-1]
        if gamma == '1.2':
            to_add_col = 0
        else:
            to_add_col = 1

        dice_file = open(path + '/' + loocv_dir + '/wm_dice_coeff.txt', 'r')
        dice_lines = dice_file.readlines()
        dice_file.close()

        dice_lines = [line.split(' ') for line in dice_lines]

        col = 0
        for line in dice_lines:
            line[2] = line[2][:-1]
            line[-1] = line[-1][:-1]
            line.pop(4)
            line.pop(4)
            slice_id = '_'.join(line[:2])
            if slice_id not in worksheets[n_sub][2].keys():
                worksheets[n_sub][2][slice_id] = worksheets[n_sub][1]
                for i, v in enumerate(line[:3]):
                    worksheets[n_sub][0].write(worksheets[n_sub][1], col+i, v)
                worksheets[n_sub][0].write(worksheets[n_sub][1], 3+3*mod+to_add_col, float(line[3]))
                worksheets[n_sub][0].write(worksheets[n_sub][1], 3+3*mod+2, float(line[-1]))
                worksheets[n_sub][1] += 1
            else:
                worksheets[n_sub][0].write(worksheets[n_sub][2][slice_id], 3+3*mod+to_add_col, float(line[3]))
                worksheets[n_sub][0].write(worksheets[n_sub][2][slice_id], 3+3*mod+2, float(line[-1]))

workbook.close()

"""
# ############################# CLASSICAL LOOCV #############################

workbook = xl.Workbook('results_loocv_subjects_resampled.xlsx')

worksheet_wm = workbook.add_worksheet('wm_dice')
worksheet_gm = workbook.add_worksheet('gm_dice')

worksheet_csa = workbook.add_worksheet('CSA')

bold = workbook.add_format({'bold': True, 'text_wrap': True})

init_col = 3
dic_worksheets = {worksheet_wm: init_col, worksheet_gm: init_col, worksheet_csa: init_col}

for w in dic_worksheets.keys():
    w.write(1, 0, 'Subject', bold)
    w.write(1, 1, 'Slice #', bold)
    w.write(1, 2, 'Slice level', bold)

len_gm_lines = 0
len_wm_lines = 0

for loocv_dir in os.listdir(path):
    if os.path.isdir(path + '/' + loocv_dir):
        words = loocv_dir.split('_')
        levels = words[0] + ' ' + words[1]
        gamma = words[2]
        reg = words[-1]
        info = levels + ' - ' + gamma + ' - ' + reg

        # GM DICE
        gm_dice = open(path + '/' + loocv_dir + '/gm_dice_coeff.txt')
        gm_dice_lines = gm_dice.readlines()
        gm_dice.close()

        gm_dice_lines = [line.split(' ') for line in gm_dice_lines]

        if dic_worksheets[worksheet_gm] == init_col:
            worksheet_gm.write(1, dic_worksheets[worksheet_gm], 'Number of slices in model', bold)
            dic_worksheets[worksheet_gm] += 1
            for i, line in enumerate(gm_dice_lines):
                worksheet_gm.write(i+2, 0, line[0])
                worksheet_gm.write(i+2, 1, line[1])
                worksheet_gm.write(i+2, 2, line[2][:-1])
                worksheet_gm.write(i+2, 3, int(line[-1][:-1]))
                res = float(line[3])
                worksheet_gm.write(i+2, dic_worksheets[worksheet_gm], res)  # RESULT
            len_gm_lines = len(gm_dice_lines)
        else:
            for i, line in enumerate(gm_dice_lines):
                res = float(line[3])
                worksheet_gm.write(i+2, dic_worksheets[worksheet_gm], res)  # RESULT
        worksheet_gm.write(0, dic_worksheets[worksheet_gm], info, bold)
        dic_worksheets[worksheet_gm] += 1

        # WM DICE
        wm_dice = open(path + '/' + loocv_dir + '/wm_dice_coeff.txt')
        wm_dice_lines = wm_dice.readlines()
        wm_dice.close()

        wm_dice_lines = [line.split(' ') for line in wm_dice_lines]

        if dic_worksheets[worksheet_wm] == init_col:
            worksheet_wm.write(1, dic_worksheets[worksheet_wm], 'Number of slices in model', bold)
            dic_worksheets[worksheet_wm] += 1
            for i, line in enumerate(wm_dice_lines[:-1]):
                worksheet_wm.write(i+2, 0, line[0])
                worksheet_wm.write(i+2, 1, line[1])
                worksheet_wm.write(i+2, 2, line[2][:-1])
                worksheet_wm.write(i+2, 3, int(line[-1][:-1]))
                if line[3] != '':
                    res = float(line[3])
                else:
                    res = 0
                worksheet_wm.write(i+2, dic_worksheets[worksheet_wm], res)  # RESULT
            len_wm_lines = len(wm_dice_lines)

        else:
            for i, line in enumerate(wm_dice_lines[:-1]):
                if line[3] != '':
                    res = float(line[3])
                else:
                    res = 0
                worksheet_wm.write(i+2, dic_worksheets[worksheet_wm], res)  # RESULT
        worksheet_wm.write(0, dic_worksheets[worksheet_wm], info, bold)
        dic_worksheets[worksheet_wm] += 1

        # CSA
        wm_csa = open(path + '/' + loocv_dir + '/wm_csa.txt')
        wm_csa_lines = wm_csa.readlines()
        wm_csa.close()
        wm_csa_lines = [line.split(' ') for line in wm_csa_lines]

        gm_csa = open(path + '/' + loocv_dir + '/gm_csa.txt')
        gm_csa_lines = gm_csa.readlines()
        gm_csa.close()
        gm_csa_lines = [line.split(' ') for line in gm_csa_lines]

        worksheet_csa.write(1, dic_worksheets[worksheet_csa], 'WM', bold)
        worksheet_csa.write(1, dic_worksheets[worksheet_csa]+1, 'GM', bold)

        if dic_worksheets[worksheet_csa] == init_col:
            for i, csa_lines in enumerate(zip(wm_csa_lines, gm_csa_lines)):
                wm_line, gm_line = csa_lines
                worksheet_csa.write(i+2, 0, wm_line[0])
                worksheet_csa.write(i+2, 1, wm_line[1])
                worksheet_csa.write(i+2, 2, wm_line[2][:-1])

                res_wm = float(wm_line[3])
                res_gm = float(gm_line[3])

                worksheet_csa.write(i+2, dic_worksheets[worksheet_csa], res_wm)
                worksheet_csa.write(i+2, dic_worksheets[worksheet_csa]+1, res_gm)
        else:
            for i, csa_lines in enumerate(zip(wm_csa_lines, gm_csa_lines)):
                wm_line, gm_line = csa_lines
                res_wm = float(wm_line[3])
                res_gm = float(gm_line[3])

                worksheet_csa.write(i+2, dic_worksheets[worksheet_csa], res_wm)
                worksheet_csa.write(i+2, dic_worksheets[worksheet_csa]+1, res_gm)

        worksheet_csa.merge_range(0,dic_worksheets[worksheet_csa], 0, dic_worksheets[worksheet_csa]+1, info, bold)
        dic_worksheets[worksheet_csa] += 2

# ##  CONDITIONAL FORMATTING  ##
good = workbook.add_format({'font_color': '#006600', 'bg_color': '#CCFFCC'})
med = workbook.add_format({'font_color': '#CC6600', 'bg_color': '#FDED83'})
bad = workbook.add_format({'font_color': '#990000', 'bg_color': '#FFCCCC'})

gm_lim = chr(dic_worksheets[worksheet_gm] + 64) + str(len_gm_lines)
worksheet_gm.conditional_format('E3:' + gm_lim, {'type':     'cell',
                                        'criteria': '>=',
                                        'value':    0.9,
                                        'format':   good})
worksheet_gm.conditional_format('E3:' + gm_lim, {'type':     'cell',
                                        'criteria': 'between',
                                        'minimum': 0.8,
                                        'maximum': 0.85,
                                        'format':   med})
worksheet_gm.conditional_format('E3:' + gm_lim, {'type':     'cell',
                                        'criteria': '<',
                                        'value':    0.8,
                                        'format':   bad})

wm_lim = chr(dic_worksheets[worksheet_wm] + 64) + str(len_wm_lines)
worksheet_wm.conditional_format('E3:' + wm_lim, {'type':     'cell',
                                        'criteria': '>=',
                                        'value':    0.9,
                                        'format':   good})
worksheet_wm.conditional_format('E3:' + wm_lim, {'type':     'cell',
                                        'criteria': 'between',
                                        'minimum': 0.8,
                                        'maximum': 0.85,
                                        'format':   med})
worksheet_wm.conditional_format('E3:' + wm_lim, {'type':     'cell',
                                        'criteria': '<',
                                        'value':    0.8,
                                        'format':   bad})

workbook.close()

"""
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import installer
import todo
import wizard

from osv import osv
import netsvc

class base_setup_config_choice(osv.osv_memory):
    """
    """
    _name = 'base.setup.config'
    logger = netsvc.Logger()

    def set_default_menu(self, cr, uid, menu, context=None):
        users = self.pool.get('res.users')
        users.write(cr, uid,
                    users.search(cr, uid,
                                 [('action_id','=','Setup')],
                                 context=context),
                    {'action_id': menu.id},
                    context=context)
        users.write(cr, uid,
                    users.search(cr, uid,
                                 [('menu_id','=','Setup')],
                                 context=context),
                    {'menu_id': menu.id},
                    context=context)

    def get_default_menu(self, cr, uid, context=None):
        actions = self.pool.get('ir.actions.act_window')

        current_menu_id = actions.search(cr, uid, [('name','=','Menu')],
                                         context=context)
        assert len(current_menu_id) == 1,\
               'A given user should only have menu item'
        return actions.browse(cr, uid, current_menu_id[0], context=context)

    def menu(self, cr, uid, ids, context=None):
        menu = self.get_default_menu(cr, uid, context=context)
        self.set_default_menu(cr, uid, menu, context=context)

        if menu.view_id.id:
            view_id = (menu.view_id.id, menu.view_id.name)
        else:
            view_id = False

        return {
            'name': menu.name,
            'type': menu.type,
            'view_id': view_id,
            'domain': menu.domain,
            'res_users': menu.res_model,
            'src_model': menu.src_model,
            'view_type': menu.view_type,
            'view_mode': menu.view_mode,
            'views': menu.views,
        }
    def config(self, cr, uid, ids, context=None):
        menu = self.get_default_menu(cr, uid, context=context)
        self.set_default_menu(cr, uid, menu, context=context)

        return self.pool.get('res.config').next(cr, uid, [], context=context)

base_setup_config_choice()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

<commit_msg>[fix] try to fix intermittent error where the user's action_id gets set to the wrong item<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import installer
import todo
import wizard

from osv import osv
import netsvc

class base_setup_config_choice(osv.osv_memory):
    """
    """
    _name = 'base.setup.config'
    logger = netsvc.Logger()

    def set_default_menu(self, cr, uid, menu, context=None):
        user = self.pool.get('res.users')\
                        .browse(cr, uid, uid, context=context)

        user.write({'action_id': menu.id,
                    'menu_id': menu.id})

    def get_default_menu(self, cr, uid, context=None):
        actions = self.pool.get('ir.actions.act_window')

        current_menu_id = actions.search(cr, uid, [('name','=','Menu')],
                                         context=context)
        assert len(current_menu_id) == 1,\
               'A given user should only have one menu item'
        return actions.browse(cr, uid, current_menu_id[0], context=context)

    def menu(self, cr, uid, ids, context=None):
        menu = self.get_default_menu(cr, uid, context=context)
        self.set_default_menu(cr, uid, menu, context=context)

        if menu.view_id.id:
            view_id = (menu.view_id.id, menu.view_id.name)
        else:
            view_id = False

        return {
            'name': menu.name,
            'type': menu.type,
            'view_id': view_id,
            'domain': menu.domain,
            'res_users': menu.res_model,
            'src_model': menu.src_model,
            'view_type': menu.view_type,
            'view_mode': menu.view_mode,
            'views': menu.views,
        }
    def config(self, cr, uid, ids, context=None):
        menu = self.get_default_menu(cr, uid, context=context)
        self.set_default_menu(cr, uid, menu, context=context)

        return self.pool.get('res.config').next(cr, uid, [], context=context)

base_setup_config_choice()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

<|endoftext|>


<commit_before>#! /usr/bin/env python
#
#  Non-terminal symbols of Python grammar (from "graminit.h")
#
#  This file is automatically generated; please don't muck it up!
#
#  To update the symbols in this file, 'cd' to the top directory of
#  the python source tree after building the interpreter and run:
#
#    PYTHONPATH=Lib:Modules ./python Lib/symbol.py
#
#  (this path allows the import of string.py, token.py, and regexmodule.so
#  for a site with no installation in place)

#--start constants--
single_input = 256
file_input = 257
eval_input = 258
funcdef = 259
parameters = 260
varargslist = 261
fpdef = 262
fplist = 263
stmt = 264
simple_stmt = 265
small_stmt = 266
expr_stmt = 267
print_stmt = 268
del_stmt = 269
pass_stmt = 270
flow_stmt = 271
break_stmt = 272
continue_stmt = 273
return_stmt = 274
raise_stmt = 275
import_stmt = 276
dotted_name = 277
global_stmt = 278
exec_stmt = 279
compound_stmt = 280
if_stmt = 281
while_stmt = 282
for_stmt = 283
try_stmt = 284
except_clause = 285
suite = 286
test = 287
and_test = 288
not_test = 289
comparison = 290
comp_op = 291
expr = 292
xor_expr = 293
and_expr = 294
shift_expr = 295
arith_expr = 296
term = 297
factor = 298
power = 299
atom = 300
lambdef = 301
trailer = 302
subscriptlist = 303
subscript = 304
sliceop = 305
exprlist = 306
testlist = 307
dictmaker = 308
classdef = 309
arglist = 310
argument = 311
#--end constants--

names = dir()
sym_name = {}
for name in names:
    number = eval(name)
    if type(number) is type(0):
	sym_name[number] = name

def main():
    import sys
    import token
    if len(sys.argv) == 1:
	sys.argv = sys.argv + ["Include/graminit.h", "Lib/symbol.py"]
    token.main()

if __name__ == "__main__":
    main()

#
#  end of file
<commit_msg>New symbols due to assert statement.<commit_after>#! /usr/bin/env python
#
#  Non-terminal symbols of Python grammar (from "graminit.h")
#
#  This file is automatically generated; please don't muck it up!
#
#  To update the symbols in this file, 'cd' to the top directory of
#  the python source tree after building the interpreter and run:
#
#    PYTHONPATH=Lib:Modules ./python Lib/symbol.py
#
#  (this path allows the import of string.py, token.py, and regexmodule.so
#  for a site with no installation in place)

#--start constants--
single_input = 256
file_input = 257
eval_input = 258
funcdef = 259
parameters = 260
varargslist = 261
fpdef = 262
fplist = 263
stmt = 264
simple_stmt = 265
small_stmt = 266
expr_stmt = 267
print_stmt = 268
del_stmt = 269
pass_stmt = 270
flow_stmt = 271
break_stmt = 272
continue_stmt = 273
return_stmt = 274
raise_stmt = 275
import_stmt = 276
dotted_name = 277
global_stmt = 278
exec_stmt = 279
assert_stmt = 280
compound_stmt = 281
if_stmt = 282
while_stmt = 283
for_stmt = 284
try_stmt = 285
except_clause = 286
suite = 287
test = 288
and_test = 289
not_test = 290
comparison = 291
comp_op = 292
expr = 293
xor_expr = 294
and_expr = 295
shift_expr = 296
arith_expr = 297
term = 298
factor = 299
power = 300
atom = 301
lambdef = 302
trailer = 303
subscriptlist = 304
subscript = 305
sliceop = 306
exprlist = 307
testlist = 308
dictmaker = 309
classdef = 310
arglist = 311
argument = 312
#--end constants--

names = dir()
sym_name = {}
for name in names:
    number = eval(name)
    if type(number) is type(0):
	sym_name[number] = name

def main():
    import sys
    import token
    if len(sys.argv) == 1:
	sys.argv = sys.argv + ["Include/graminit.h", "Lib/symbol.py"]
    token.main()

if __name__ == "__main__":
    main()

#
#  end of file
<|endoftext|>


<commit_before># Django imports
from django import forms
from django.contrib import messages
from django.utils import timezone
from django_cradmin import crapp
from django.utils.translation import ugettext_lazy as _, ugettext_lazy, pgettext_lazy

# Devilry/cradmin imports
from devilry.apps.core import models as core_models
from devilry.devilry_group.views import cradmin_feedbackfeed_base
from devilry.devilry_group import models
from devilry.devilry_group.views.cradmin_feedbackfeed_base import GroupCommentForm

# 3rd party imports
from crispy_forms import layout

class ExaminerBaseFeedbackFeedView(cradmin_feedbackfeed_base.FeedbackFeedBaseView):
    """
    Base view for examiner.
    """
    def _get_comments_for_group(self, group):
        """
        Filters the comments a examiner should have access to.
        A examiner is able to see all comment except comments from other examiners
        with :obj:`devilry.devilry_group.models.AbstractGroupComment.visibility` set to
        :obj:`devilry.devilry_group.models.AbstractGroupComment.VISIBILITY_PRIVATE`.

        :param group:
            The :class:`devilry.apps.core.models.AssignmentGroup` the user belongs to.

        Returns:
            List of :class:`devilry.devilry_group.models.GroupComment` objects.
        """
        return models.GroupComment.objects.filter(
            feedback_set__group=group
        ).exclude_private_comments_from_other_users(
            user=self.request.user
        )

    def get_context_data(self, **kwargs):
        context = super(ExaminerBaseFeedbackFeedView, self).get_context_data(**kwargs)
        context['devilry_ui_role'] = 'examiner'
        return context

    def get_buttons(self):
        return [
            layout.Submit('examiner_add_comment_for_examiners',
                _('Add comment for examiners'),
               css_class='btn btn-default'),
            layout.Submit('examiner_add_public_comment',
               _('Add public comment'),
               css_class='btn btn-primary'),
            layout.Submit('examiner_add_comment_to_feedback_draft',
                   _('Add to feedback'),
                   css_class='btn btn-default')
        ]

    def set_automatic_attributes(self, obj):
        super(ExaminerBaseFeedbackFeedView, self).set_automatic_attributes(obj)
        obj.user_role = 'examiner'

class AbstractFeedbackForm(GroupCommentForm):

    def get_grading_points(self):
        raise NotImplementedError()

class PassedFailedFeedbackForm(AbstractFeedbackForm):
    """
    Form for passed/failed grade plugin.
    """

    #: Set delivery as passed or failed.
    passed = forms.BooleanField(
        label=pgettext_lazy('grading', 'Passed?'),
        help_text=pgettext_lazy('grading', 'Check to provide a passing grade.'),
        initial=True,
        required=False)

    @classmethod
    def get_field_layout(cls):
        return ['passed']

    def get_grading_points(self):
        if self.cleaned_data['passed']:
            return self.group.assignment.max_points
        else:
            return 0

class PointsFeedbackForm(AbstractFeedbackForm):
    """
    Form for point-based grade plugin.
    """

    #: Set points that should be given to the delivery.
    points = forms.IntegerField(
            required=True,
            min_value=0,
            label=_('Points'))

    def __init__(self, *args, **kwargs):
        super(PointsFeedbackForm, self).__init__(*args, **kwargs)
        self.fields['points'].max_value = self.group.assignment.max_points
        self.fields['points'].help_text = pgettext_lazy('grading', 'Number between 0 and %(max_points)s.') % {
            'max_points': self.group.assignment.max_points
        }

    @classmethod
    def get_field_layout(cls):
        return ['points']

    def get_grading_points(self):
        return self.cleaned_data['points']

class ExaminerFeedbackView(ExaminerBaseFeedbackFeedView):
    """
    The examiner feedbackview.
    This is the view where examiner corrects the delivery made by a student
    and is only able to create drafted comments, or publish grading.
    """

    def get_form_class(self):
        """
        Get the correct form based on what grade plugin that is used.

        Returns:
            A :class:`devilry.devilry_group.views.cradmin_feedbackfeed_base.GroupCommentForm`

        """
        assignment = self.request.cradmin_role.assignment
        if assignment.grading_system_plugin_id == core_models.Assignment.GRADING_SYSTEM_PLUGIN_ID_PASSEDFAILED:
            return PassedFailedFeedbackForm
        elif assignment.grading_system_plugin_id == core_models.Assignment.GRADING_SYSTEM_PLUGIN_ID_POINTS:
            return PointsFeedbackForm
        else:
            raise ValueError('Unsupported grading_system_plugin_id: {}'.format(assignment.grading_system_plugin_id))

    def get_buttons(self):
        return [
            layout.Submit('examiner_add_comment_to_feedback_draft',
                   _('Add to feedback'),
                   css_class='btn btn-default'),
            layout.Submit('examiner_publish_feedback',
                   _('Publish feedback'),
                   css_class='btn btn-primary')
        ]

    def save_object(self, form, commit=True):
        obj = super(ExaminerFeedbackView, self).save_object(form=form)
        if obj.feedback_set.grading_published_datetime is not None:
            messages.warning(self.request, ugettext_lazy('Feedback is already published!'))
        else:
            if form.data.get('examiner_add_comment_to_feedback_draft'):
                obj.visibility = models.GroupComment.VISIBILITY_PRIVATE
                obj.part_of_grading = True
                obj = super(ExaminerFeedbackView, self).save_object(form=form, commit=True)
            elif form.data.get('examiner_publish_feedback'):
                result, error_msg = obj.feedback_set.publish(
                        published_by=obj.user,
                        grading_points=form.get_grading_points())
                if result is False:
                    messages.warning(self.request, ugettext_lazy(error_msg))
                elif len(obj.text) > 0:
                    obj.visibility = models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE
                    obj.part_of_grading = True
                    obj.published_datetime = obj.get_published_datetime()
                    obj = super(ExaminerFeedbackView, self).save_object(form=form, commit=True)
        return obj

    def get_form_invalid_message(self, form):
        return 'Cannot publish feedback until deadline has passed!'

class ExaminerDiscussView(ExaminerBaseFeedbackFeedView):
    """
    The examiner discussview.
    This is the view examiner uses for communicating with students and admins in the feedbackfeed.
    """

    def _get_comments_for_group(self, group):
        return models.GroupComment.objects.filter(
            feedback_set__group=group
        ).exclude_private_comments_from_other_users(
            user=self.request.user
        )

    def get_buttons(self):
        return [
            layout.Submit('examiner_add_comment_for_examiners',
                _('Add comment for examiners'),
               css_class='btn btn-default'),
            layout.Submit('examiner_add_public_comment',
               _('Add public comment'),
               css_class='btn btn-primary'),
        ]

    def save_object(self, form, commit=True):
        obj = super(ExaminerDiscussView, self).save_object(form)
        self._convert_temporary_files_to_comment_files(form, obj)
        if form.data.get('examiner_add_comment_for_examiners'):
            obj.visibility = models.GroupComment.VISIBILITY_VISIBLE_TO_EXAMINER_AND_ADMINS
            obj.published_datetime = timezone.now()
        elif form.data.get('examiner_add_public_comment'):
            obj.visibility = models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE
            obj.published_datetime = timezone.now()

        obj = super(ExaminerDiscussView, self).save_object(form, commit=True)
        return obj

    def get_success_url(self):
        return self.request.cradmin_app.reverse_appurl(viewname='discuss')

class App(crapp.App):
    appurls = [
        crapp.Url(
            r'^feedback$',
            ExaminerFeedbackView.as_view(),
            name=crapp.INDEXVIEW_NAME),
        crapp.Url(
            r'^discuss$',
            ExaminerDiscussView.as_view(),
            name='discuss'
        )
    ]
<commit_msg>devilry/devilry_group/feedbackfeed/feedbackfeed_examiner: More reusable implementation of get buttons for examiner view .<commit_after># Django imports
from django import forms
from django.contrib import messages
from django.utils import timezone
from django_cradmin import crapp
from django.utils.translation import ugettext_lazy as _, ugettext_lazy, pgettext_lazy

# Devilry/cradmin imports
from devilry.apps.core import models as core_models
from devilry.devilry_group.views import cradmin_feedbackfeed_base
from devilry.devilry_group import models
from devilry.devilry_group.views.cradmin_feedbackfeed_base import GroupCommentForm

# 3rd party imports
from crispy_forms import layout

class ExaminerBaseFeedbackFeedView(cradmin_feedbackfeed_base.FeedbackFeedBaseView):
    """
    Base view for examiner.
    """
    def _get_comments_for_group(self, group):
        """
        Filters the comments a examiner should have access to.
        A examiner is able to see all comment except comments from other examiners
        with :obj:`devilry.devilry_group.models.AbstractGroupComment.visibility` set to
        :obj:`devilry.devilry_group.models.AbstractGroupComment.VISIBILITY_PRIVATE`.

        :param group:
            The :class:`devilry.apps.core.models.AssignmentGroup` the user belongs to.

        Returns:
            List of :class:`devilry.devilry_group.models.GroupComment` objects.
        """
        return models.GroupComment.objects.filter(
            feedback_set__group=group
        ).exclude_private_comments_from_other_users(
            user=self.request.user
        )

    def get_context_data(self, **kwargs):
        context = super(ExaminerBaseFeedbackFeedView, self).get_context_data(**kwargs)
        context['devilry_ui_role'] = 'examiner'
        return context

    def get_buttons(self):
        return []

    def set_automatic_attributes(self, obj):
        super(ExaminerBaseFeedbackFeedView, self).set_automatic_attributes(obj)
        obj.user_role = 'examiner'

class AbstractFeedbackForm(GroupCommentForm):

    def get_grading_points(self):
        raise NotImplementedError()

class PassedFailedFeedbackForm(AbstractFeedbackForm):
    """
    Form for passed/failed grade plugin.
    """

    #: Set delivery as passed or failed.
    passed = forms.BooleanField(
        label=pgettext_lazy('grading', 'Passed?'),
        help_text=pgettext_lazy('grading', 'Check to provide a passing grade.'),
        initial=True,
        required=False)

    @classmethod
    def get_field_layout(cls):
        return ['passed']

    def get_grading_points(self):
        if self.cleaned_data['passed']:
            return self.group.assignment.max_points
        else:
            return 0

class PointsFeedbackForm(AbstractFeedbackForm):
    """
    Form for point-based grade plugin.
    """

    #: Set points that should be given to the delivery.
    points = forms.IntegerField(
            required=True,
            min_value=0,
            label=_('Points'))

    def __init__(self, *args, **kwargs):
        super(PointsFeedbackForm, self).__init__(*args, **kwargs)
        self.fields['points'].max_value = self.group.assignment.max_points
        self.fields['points'].help_text = pgettext_lazy('grading', 'Number between 0 and %(max_points)s.') % {
            'max_points': self.group.assignment.max_points
        }

    @classmethod
    def get_field_layout(cls):
        return ['points']

    def get_grading_points(self):
        return self.cleaned_data['points']

class ExaminerFeedbackView(ExaminerBaseFeedbackFeedView):
    """
    The examiner feedbackview.
    This is the view where examiner corrects the delivery made by a student
    and is only able to create drafted comments, or publish grading.
    """

    def get_form_class(self):
        """
        Get the correct form based on what grade plugin that is used.

        Returns:
            A :class:`devilry.devilry_group.views.cradmin_feedbackfeed_base.GroupCommentForm`

        """
        assignment = self.request.cradmin_role.assignment
        if assignment.grading_system_plugin_id == core_models.Assignment.GRADING_SYSTEM_PLUGIN_ID_PASSEDFAILED:
            return PassedFailedFeedbackForm
        elif assignment.grading_system_plugin_id == core_models.Assignment.GRADING_SYSTEM_PLUGIN_ID_POINTS:
            return PointsFeedbackForm
        else:
            raise ValueError('Unsupported grading_system_plugin_id: {}'.format(assignment.grading_system_plugin_id))

    def get_buttons(self):
        buttons = super(ExaminerFeedbackView, self).get_buttons()
        buttons.extend([
            layout.Submit('examiner_add_comment_to_feedback_draft',
                          _('Add to feedback'),
                          css_class='btn btn-default'),
            layout.Submit('examiner_publish_feedback',
                          _('Publish feedback'),
                          css_class='btn btn-primary')
        ])
        return buttons

    def save_object(self, form, commit=True):
        obj = super(ExaminerFeedbackView, self).save_object(form=form)
        if obj.feedback_set.grading_published_datetime is not None:
            messages.warning(self.request, ugettext_lazy('Feedback is already published!'))
        else:
            if form.data.get('examiner_add_comment_to_feedback_draft'):
                obj.visibility = models.GroupComment.VISIBILITY_PRIVATE
                obj.part_of_grading = True
                obj = super(ExaminerFeedbackView, self).save_object(form=form, commit=True)
            elif form.data.get('examiner_publish_feedback'):
                result, error_msg = obj.feedback_set.publish(
                        published_by=obj.user,
                        grading_points=form.get_grading_points())
                if result is False:
                    messages.warning(self.request, ugettext_lazy(error_msg))
                elif len(obj.text) > 0:
                    obj.visibility = models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE
                    obj.part_of_grading = True
                    obj.published_datetime = obj.get_published_datetime()
                    obj = super(ExaminerFeedbackView, self).save_object(form=form, commit=True)
        return obj

    def get_form_invalid_message(self, form):
        return 'Cannot publish feedback until deadline has passed!'

class ExaminerDiscussView(ExaminerBaseFeedbackFeedView):
    """
    The examiner discussview.
    This is the view examiner uses for communicating with students and admins in the feedbackfeed.
    """

    def _get_comments_for_group(self, group):
        return models.GroupComment.objects.filter(
            feedback_set__group=group
        ).exclude_private_comments_from_other_users(
            user=self.request.user
        )

    def get_buttons(self):
        buttons = super(ExaminerDiscussView, self).get_buttons()
        buttons.extend([
            layout.Submit('examiner_add_comment_for_examiners',
                          _('Add comment for examiners'),
                          css_class='btn btn-default'),
            layout.Submit('examiner_add_public_comment',
                          _('Add public comment'),
                          css_class='btn btn-primary'),
        ])
        return buttons

    def save_object(self, form, commit=True):
        obj = super(ExaminerDiscussView, self).save_object(form)
        self._convert_temporary_files_to_comment_files(form, obj)
        if form.data.get('examiner_add_comment_for_examiners'):
            obj.visibility = models.GroupComment.VISIBILITY_VISIBLE_TO_EXAMINER_AND_ADMINS
            obj.published_datetime = timezone.now()
        elif form.data.get('examiner_add_public_comment'):
            obj.visibility = models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE
            obj.published_datetime = timezone.now()

        obj = super(ExaminerDiscussView, self).save_object(form, commit=True)
        return obj

    def get_success_url(self):
        return self.request.cradmin_app.reverse_appurl(viewname='discuss')

class App(crapp.App):
    appurls = [
        crapp.Url(
            r'^feedback$',
            ExaminerFeedbackView.as_view(),
            name=crapp.INDEXVIEW_NAME),
        crapp.Url(
            r'^discuss$',
            ExaminerDiscussView.as_view(),
            name='discuss'
        )
    ]
<|endoftext|>


<commit_before>#-*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from datetime import datetime
from osv import fields,osv,orm
from tools.translate import _
import crm

AVAILABLE_STATES = [
    ('draft','New'),
    ('open','Open'),
    ('cancel', 'Lost'),
    ('done', 'Converted'),
    ('pending','Pending')
]

class crm_opportunity(osv.osv):
    """ Opportunity Cases """

    _name = "crm.opportunity"
    _description = "Opportunity Cases"
    _order = "id desc"
    _inherit = 'crm.case'

    def case_open(self, cr, uid, ids, *args):
        """
        @param self: The object pointer
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: List of case's Ids
        @param *args: Give Tuple Value
        """

        cases = self.browse(cr, uid, ids)
        for case in cases:
            data = {'state': 'open', 'active': True}
            if not case.user_id:
                data['user_id'] = uid
            data.update({'date_open': time.strftime('%Y-%m-%d %H:%M:%S')})
            self.write(cr, uid, ids, data)
        self._action(cr, uid, cases, 'open')
        return True

    def _compute_day(self, cr, uid, ids, fields, args, context={}):
        """
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: List of Openday’s IDs
        @return: difference between current date and log date
        @param context: A standard dictionary for contextual values
        """
        log_obj = self.pool.get('crm.case.log')
        model_obj = self.pool.get('ir.model')
        cal_obj = self.pool.get('resource.calendar')

        model_ids = model_obj.search(cr, uid, [('model', '=', self._name)])
        model_id = False
        if len(model_ids):
            model_id = model_ids[0]

        res = {}
        for opportunity in self.browse(cr, uid, ids , context):
            for field in fields:
                res[opportunity.id] = {}
                duration = 0
                if field == 'day_open':
                    if opportunity.date_open:
                        date_create = datetime.strptime(opportunity.create_date, "%Y-%m-%d %H:%M:%S")
                        date_open = datetime.strptime(opportunity.date_open, "%Y-%m-%d %H:%M:%S")

                        ans = date_open - date_create
                        duration =  float(ans.days) + (float(ans.seconds) / 86400)

                elif field == 'day_close':
                    if opportunity.date_closed:
                        date_create = datetime.strptime(opportunity.create_date, "%Y-%m-%d %H:%M:%S")
                        date_close = datetime.strptime(opportunity.date_closed, "%Y-%m-%d %H:%M:%S")

                        ans = date_close - date_create
                        duration =  float(ans.days) + (float(ans.seconds) / 86400)
                res[opportunity.id][field] = abs(int(duration))
        return res

    _columns = {
        'stage_id': fields.many2one ('crm.case.stage', 'Stage', \
                     domain="[('section_id','=',section_id),\
                    ('object_id.model', '=', 'crm.opportunity')]"),
        'categ_id': fields.many2one('crm.case.categ', 'Category', \
                     domain="[('section_id','=',section_id), \
                    ('object_id.model', '=', 'crm.opportunity')]"),
        'type_id': fields.many2one('crm.case.resource.type', 'Resource Type',\
                    domain="[('section_id','=',section_id),('object_id.model', '=', 'crm.opportunity')]"),
        'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
        'probability': fields.float('Probability (%)'),
        'planned_revenue': fields.float('Expected Revenue'),
        'ref': fields.reference('Reference', selection=crm._links_get, size=128),
        'ref2': fields.reference('Reference 2', selection=crm._links_get, size=128),
        'date_closed': fields.datetime('Closed', readonly=True),
        'user_id': fields.many2one('res.users', 'Salesman'),
        'phone': fields.char("Phone", size=64),
        'date_deadline': fields.date('Expected Closing'),
        'state': fields.selection(AVAILABLE_STATES, 'State', size=16, readonly=True,
                                  help='The state is set to \'Draft\', when a case is created.\
                                  \nIf the case is in progress the state is set to \'Open\'.\
                                  \nWhen the case is over, the state is set to \'Done\'.\
                                  \nIf the case needs to be reviewed then the state is set to \'Pending\'.'),

        'date_open': fields.datetime('Opened', readonly=True),
        'day_open': fields.function(_compute_day, string='Days to Open', \
                                method=True, multi='day_open', type="integer", store=True),
        'day_close': fields.function(_compute_day, string='Days to Close', \
                                method=True, multi='day_close', type="integer", store=True),
         }

    def onchange_stage_id(self, cr, uid, ids, stage_id, context={}):

        """ @param self: The object pointer
            @param cr: the current row, from the database cursor,
            @param uid: the current user’s ID for security checks,
            @param ids: List of stage’s IDs
            @stage_id: change state id on run time """

        if not stage_id:
            return {'value':{}}

        stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context)
        if not stage.on_change:
            return {'value':{}}
        return {'value':{'probability':stage.probability}}

    def stage_next(self, cr, uid, ids, context={}):

        """ @param self: The object pointer
            @param cr: the current row, from the database cursor,
            @param uid: the current user’s ID for security checks,
            @param ids: List of stage next’s IDs
            @param context: A standard dictionary for contextual values """

        res = super(crm_opportunity, self).stage_next(cr, uid, ids, context=context)
        for case in self.browse(cr, uid, ids, context):
            if case.stage_id and case.stage_id.on_change:
                self.write(cr, uid, [case.id], {'probability': case.stage_id.probability})
        return res

    def stage_previous(self, cr, uid, ids, context={}):

        """ @param self: The object pointer
            @param cr: the current row, from the database cursor,
            @param uid: the current user’s ID for security checks,
            @param ids: List of stage previous’s IDs
            @param context: A standard dictionary for contextual values """

        res = super(crm_opportunity, self).stage_previous(cr, uid, ids, context=context)
        for case in self.browse(cr, uid, ids, context):
            if case.stage_id and case.stage_id.on_change:
                self.write(cr, uid, [case.id], {'probability': case.stage_id.probability})
        return res

    _defaults = {
        'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.opportunity', context=c),
        'priority': lambda *a: crm.AVAILABLE_PRIORITIES[2][0],
    }

    def action_makeMeeting(self, cr, uid, ids, context=None):
        """
        This opens Meeting's calendar view to schedule meeting on current Opportunity
        @param self: The object pointer
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: List of Opportunity to Meeting IDs
        @param context: A standard dictionary for contextual values

        @return : Dictionary value for created Meeting view
        """
        value = {}
        for opp in self.browse(cr, uid, ids):
            data_obj = self.pool.get('ir.model.data')

            # Get meeting views
            result = data_obj._get_id(cr, uid, 'crm', 'view_crm_case_meetings_filter')
            res = data_obj.read(cr, uid, result, ['res_id'])
            id1 = data_obj._get_id(cr, uid, 'crm', 'crm_case_calendar_view_meet')
            id2 = data_obj._get_id(cr, uid, 'crm', 'crm_case_form_view_meet')
            id3 = data_obj._get_id(cr, uid, 'crm', 'crm_case_tree_view_meet')
            if id1:
                id1 = data_obj.browse(cr, uid, id1, context=context).res_id
            if id2:
                id2 = data_obj.browse(cr, uid, id2, context=context).res_id
            if id3:
                id3 = data_obj.browse(cr, uid, id3, context=context).res_id

            context = {
                'default_opportunity_id': opp.id,
                'default_partner_id': opp.partner_id and opp.partner_id.id or False,
                'default_section_id': opp.section_id and opp.section_id.id or False,
                'default_email_from': opp.email_from,
                'default_state': 'open',
                'default_name': opp.name
            }
            value = {
                'name': _('Meetings'),
                'domain': "[('user_id','=',%s)]" % (uid),
                'context': context,
                'view_type': 'form',
                'view_mode': 'calendar,form,tree',
                'res_model': 'crm.meeting',
                'view_id': False,
                'views': [(id1, 'calendar'), (id2, 'form'), (id3, 'tree')],
                'type': 'ir.actions.act_window',
                'search_view_id': res['res_id'],
                'nodestroy': True
            }

        return value

crm_opportunity()

<commit_msg>[IMP]: crm: Apply some changes<commit_after>#-*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from datetime import datetime
from osv import fields,osv,orm
from tools.translate import _
import crm
import time

AVAILABLE_STATES = [
    ('draft','New'),
    ('open','Open'),
    ('cancel', 'Lost'),
    ('done', 'Converted'),
    ('pending','Pending')
]

class crm_opportunity(osv.osv):
    """ Opportunity Cases """

    _name = "crm.opportunity"
    _description = "Opportunity Cases"
    _order = "id desc"
    _inherit = 'crm.case'

    def case_open(self, cr, uid, ids, *args):
        """
        @param self: The object pointer
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: List of case's Ids
        @param *args: Give Tuple Value
        """

        cases = self.browse(cr, uid, ids)
        for case in cases:
            data = {'state': 'open', 'active': True}
            if not case.user_id:
                data['user_id'] = uid
            data.update({'date_open': time.strftime('%Y-%m-%d %H:%M:%S')})
            self.write(cr, uid, ids, data)
        self._action(cr, uid, cases, 'open')
        return True

    def _compute_day(self, cr, uid, ids, fields, args, context={}):
        """
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: List of Openday’s IDs
        @return: difference between current date and log date
        @param context: A standard dictionary for contextual values
        """
        log_obj = self.pool.get('crm.case.log')
        model_obj = self.pool.get('ir.model')
        cal_obj = self.pool.get('resource.calendar')

        model_ids = model_obj.search(cr, uid, [('model', '=', self._name)])
        model_id = False
        if len(model_ids):
            model_id = model_ids[0]

        res = {}
        for opportunity in self.browse(cr, uid, ids , context):
            for field in fields:
                res[opportunity.id] = {}
                duration = 0
                if field == 'day_open':
                    if opportunity.date_open:
                        date_create = datetime.strptime(opportunity.create_date, "%Y-%m-%d %H:%M:%S")
                        date_open = datetime.strptime(opportunity.date_open, "%Y-%m-%d %H:%M:%S")

                        ans = date_open - date_create
                        duration =  float(ans.days) + (float(ans.seconds) / 86400)

                elif field == 'day_close':
                    if opportunity.date_closed:
                        date_create = datetime.strptime(opportunity.create_date, "%Y-%m-%d %H:%M:%S")
                        date_close = datetime.strptime(opportunity.date_closed, "%Y-%m-%d %H:%M:%S")

                        ans = date_close - date_create
                        duration =  float(ans.days) + (float(ans.seconds) / 86400)
                res[opportunity.id][field] = abs(int(duration))
        return res

    _columns = {
        'stage_id': fields.many2one ('crm.case.stage', 'Stage', \
                     domain="[('section_id','=',section_id),\
                    ('object_id.model', '=', 'crm.opportunity')]"),
        'categ_id': fields.many2one('crm.case.categ', 'Category', \
                     domain="[('section_id','=',section_id), \
                    ('object_id.model', '=', 'crm.opportunity')]"),
        'type_id': fields.many2one('crm.case.resource.type', 'Resource Type',\
                    domain="[('section_id','=',section_id),('object_id.model', '=', 'crm.opportunity')]"),
        'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
        'probability': fields.float('Probability (%)'),
        'planned_revenue': fields.float('Expected Revenue'),
        'ref': fields.reference('Reference', selection=crm._links_get, size=128),
        'ref2': fields.reference('Reference 2', selection=crm._links_get, size=128),
        'date_closed': fields.datetime('Closed', readonly=True),
        'user_id': fields.many2one('res.users', 'Salesman'),
        'phone': fields.char("Phone", size=64),
        'date_deadline': fields.date('Expected Closing'),
        'state': fields.selection(AVAILABLE_STATES, 'State', size=16, readonly=True,
                                  help='The state is set to \'Draft\', when a case is created.\
                                  \nIf the case is in progress the state is set to \'Open\'.\
                                  \nWhen the case is over, the state is set to \'Done\'.\
                                  \nIf the case needs to be reviewed then the state is set to \'Pending\'.'),

        'date_open': fields.datetime('Opened', readonly=True),
        'day_open': fields.function(_compute_day, string='Days to Open', \
                                method=True, multi='day_open', type="integer", store=True),
        'day_close': fields.function(_compute_day, string='Days to Close', \
                                method=True, multi='day_close', type="integer", store=True),
         }

    def onchange_stage_id(self, cr, uid, ids, stage_id, context={}):

        """ @param self: The object pointer
            @param cr: the current row, from the database cursor,
            @param uid: the current user’s ID for security checks,
            @param ids: List of stage’s IDs
            @stage_id: change state id on run time """

        if not stage_id:
            return {'value':{}}

        stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context)
        if not stage.on_change:
            return {'value':{}}
        return {'value':{'probability':stage.probability}}

    def stage_next(self, cr, uid, ids, context={}):

        """ @param self: The object pointer
            @param cr: the current row, from the database cursor,
            @param uid: the current user’s ID for security checks,
            @param ids: List of stage next’s IDs
            @param context: A standard dictionary for contextual values """

        res = super(crm_opportunity, self).stage_next(cr, uid, ids, context=context)
        for case in self.browse(cr, uid, ids, context):
            if case.stage_id and case.stage_id.on_change:
                self.write(cr, uid, [case.id], {'probability': case.stage_id.probability})
        return res

    def stage_previous(self, cr, uid, ids, context={}):

        """ @param self: The object pointer
            @param cr: the current row, from the database cursor,
            @param uid: the current user’s ID for security checks,
            @param ids: List of stage previous’s IDs
            @param context: A standard dictionary for contextual values """

        res = super(crm_opportunity, self).stage_previous(cr, uid, ids, context=context)
        for case in self.browse(cr, uid, ids, context):
            if case.stage_id and case.stage_id.on_change:
                self.write(cr, uid, [case.id], {'probability': case.stage_id.probability})
        return res

    _defaults = {
        'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.opportunity', context=c),
        'priority': lambda *a: crm.AVAILABLE_PRIORITIES[2][0],
    }

    def action_makeMeeting(self, cr, uid, ids, context=None):
        """
        This opens Meeting's calendar view to schedule meeting on current Opportunity
        @param self: The object pointer
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param ids: List of Opportunity to Meeting IDs
        @param context: A standard dictionary for contextual values

        @return : Dictionary value for created Meeting view
        """
        value = {}
        for opp in self.browse(cr, uid, ids):
            data_obj = self.pool.get('ir.model.data')

            # Get meeting views
            result = data_obj._get_id(cr, uid, 'crm', 'view_crm_case_meetings_filter')
            res = data_obj.read(cr, uid, result, ['res_id'])
            id1 = data_obj._get_id(cr, uid, 'crm', 'crm_case_calendar_view_meet')
            id2 = data_obj._get_id(cr, uid, 'crm', 'crm_case_form_view_meet')
            id3 = data_obj._get_id(cr, uid, 'crm', 'crm_case_tree_view_meet')
            if id1:
                id1 = data_obj.browse(cr, uid, id1, context=context).res_id
            if id2:
                id2 = data_obj.browse(cr, uid, id2, context=context).res_id
            if id3:
                id3 = data_obj.browse(cr, uid, id3, context=context).res_id

            context = {
                'default_opportunity_id': opp.id,
                'default_partner_id': opp.partner_id and opp.partner_id.id or False,
                'default_section_id': opp.section_id and opp.section_id.id or False,
                'default_email_from': opp.email_from,
                'default_state': 'open',
                'default_name': opp.name
            }
            value = {
                'name': _('Meetings'),
                'domain': "[('user_id','=',%s)]" % (uid),
                'context': context,
                'view_type': 'form',
                'view_mode': 'calendar,form,tree',
                'res_model': 'crm.meeting',
                'view_id': False,
                'views': [(id1, 'calendar'), (id2, 'form'), (id3, 'tree')],
                'type': 'ir.actions.act_window',
                'search_view_id': res['res_id'],
                'nodestroy': True
            }

        return value

crm_opportunity()

<|endoftext|>


<commit_before>from sentinels import NOTHING

class ErrorContainer(object):

    def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING, is_failure=NOTHING):
        return self.client.api.call_function('add_error', {self._get_id_key(): self.id,
                                                           'message': message,
                                                           'exception_type': exception_type,
                                                           'traceback': traceback,
                                                           'is_failure': is_failure,
                                                           'timestamp': timestamp
                                                       })

    def add_failure(self, message, **kwargs):
        return self.add_error(message, is_failure=True, **kwargs)

    def _get_id_key(self):
        if type(self).__name__ == 'Test':
            return 'test_id'
        return 'session_id'
<commit_msg>Support streaming uploads of tracebacks (fix #25)<commit_after>import gzip
import json
import tempfile

from ._compat import TextIOWrapper

from sentinels import NOTHING

class ErrorContainer(object):

    def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING, is_failure=NOTHING):

        kwargs = {self._get_id_key(): self.id,
                  'message': message,
                  'exception_type': exception_type,
                  'is_failure': is_failure,
                  'timestamp': timestamp
                  }

        has_streaming_upload = self.client.api.info().endpoints.add_error.version >= 2

        if traceback is not NOTHING and not has_streaming_upload:
            kwargs['traceback'] = traceback

        returned = self.client.api.call_function('add_error', kwargs) # pylint: disable=no-member

        if has_streaming_upload and traceback is not NOTHING:
            traceback_url = returned.api_url.add_path('traceback')
            with tempfile.TemporaryFile(mode='w+b') as traceback_file:
                with gzip.GzipFile(fileobj=traceback_file, mode='w+b') as compressed_file_raw:
                    with TextIOWrapper(compressed_file_raw) as compressed_file:
                        json.dump(traceback, compressed_file)

                traceback_file.seek(0)
                resp = self.client.api.session.put(traceback_url, data=traceback_file) # pylint: disable=no-member
                resp.raise_for_status()
            returned.refresh()
        return returned

    def add_failure(self, message, **kwargs):
        return self.add_error(message, is_failure=True, **kwargs)

    def _get_id_key(self):
        if type(self).__name__ == 'Test':
            return 'test_id'
        return 'session_id'
<|endoftext|>