<commit_before># -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License

"""Class for reading and writing Mir files."""
import numpy as np

from .uvdata import UVData
from . import mir_parser
from .. import utils as uvutils

# from pyuvdata import utils

__all__ = ["Mir"]

class Mir(UVData):
    """
    A class for Mir file objects.

    This class defines an Mir-specific subclass of UVData for reading and
    writing Mir files. This class should not be interacted with directly,
    instead use the read_mir and write_mir methods on the UVData class.
    """

    def read_mir(self, filepath, isource=None, irec=None, isb=None, corrchunk=None):
        """
        Read in data from an SMA MIR file, and map to the UVData model.

        Note that with the exception of filename, the reset of the parameters are
        used to sub-select a range of data that matches the limitations of the current
        instantiation of pyuvdata  -- namely 1 spectral window, 1 source. These could
        be dropped in the future, as pyuvdata capabilities grow.

        Parameters
        ----------
        filepath : str
             The file path to the MIR folder to read from.
        isource : int
            Source code for MIR dataset
        irec : int
            Receiver code for MIR dataset
        isb : int
            Sideband code for MIR dataset
        corrchunk : int
            Correlator chunk code for MIR dataset
        """
        sma_lat = 0.3459976585365961
        sma_lon = -2.713594675620429
        sma_alt = 4080.0

        # Use the mir_parser to read in metadata, which can be used to select data.
        mir_data = mir_parser.MirParser(filepath)

        # Select out data that we want to work with.
        if isource is None:
            isource = mir_data.in_read["isource"][0]
        if irec is None:
            irec = mir_data.bl_read["irec"][0]
        if isb is None:
            isb = mir_data.bl_read["isb"][0]
        if corrchunk is None:
            corrchunk = mir_data.sp_read["corrchunk"][0]

        mir_data.use_in = mir_data.in_read["isource"] == isource
        mir_data.use_bl = np.logical_and(
            np.logical_and(
                mir_data.bl_read["isb"] == isb, mir_data.bl_read["ipol"] == 0
            ),
            mir_data.bl_read["irec"] == irec,
        )
        mir_data.use_sp = mir_data.sp_read["corrchunk"] == corrchunk

        # Load up the visibilities into the MirParser object. This will also update the
        # filters, and will make sure we're looking at the right metadata.
        mir_data._update_filter()
        if len(mir_data.in_data) == 0:
            raise IndexError("No valid records matching those selections!")

        mir_data.load_data(load_vis=True, load_raw=True)

        # Create a simple array/list for broadcasting values stored on a
        # per-intergration basis in MIR into the (tasty) per-blt records in UVDATA.
        bl_in_maparr = [mir_data.inhid_dict[idx] for idx in mir_data.bl_data["inhid"]]

        # Derive Nants_data this value from baselines.
        self.Nants_data = len(
            np.unique(
                np.concatenate((mir_data.bl_data["iant1"], mir_data.bl_data["iant2"]))
            )
        )

        self.Nants_telescope = 8
        self.Nbls = int(self.Nants_data * (self.Nants_data - 1) / 2)
        self.Nblts = len(mir_data.bl_data)
        self.Nfreqs = int(mir_data.sp_data["nch"][0])
        self.Npols = 1  # todo: We will need to go back and expand this.
        self.Nspws = 1  # todo: We will need to go back and expand this.
        self.Ntimes = len(mir_data.in_data)
        self.ant_1_array = mir_data.bl_data["iant1"] - 1
        self.ant_2_array = mir_data.bl_data["iant2"] - 1
        self.antenna_names = [
            "Ant 1",
            "Ant 2",
            "Ant 3",
            "Ant 4",
            "Ant 5",
            "Ant 6",
            "Ant 7",
            "Ant 8",
        ]
        self.antenna_numbers = np.arange(8)

        # Prepare the XYZ coordinates of the antenna positions.
        antXYZ = np.zeros([self.Nants_telescope, 3])
        for idx in range(self.Nants_telescope):
            if (idx + 1) in mir_data.antpos_data["antenna"]:
                antXYZ[idx] = mir_data.antpos_data["xyz_pos"][
                    mir_data.antpos_data["antenna"] == (idx + 1)
                ]

        self.antenna_positions = uvutils.ECEF_from_rotECEF(antXYZ, sma_lon)
        self.baseline_array = (
            2048 * (self.ant_1_array + 1) + (self.ant_2_array + 1) + (2 ** 16)
        )

        # todo: This may need to be reshaped.
        fsky = mir_data.sp_data["fsky"][0] * 1e9
        fres = mir_data.sp_data["fres"][0] * 1e6
        nch = mir_data.sp_data["nch"][0]

        self.channel_width = fres
        self.freq_array = fsky + fres * (np.arange(nch) - (nch / 2 - 0.5))
        self.freq_array = np.reshape(self.freq_array, (1, -1))
        self.history = "Raw Data"
        self.instrument = "SWARM"

        # todo: This won't work when we have multiple spectral windows.
        self.integration_time = mir_data.sp_data["integ"]

        # todo: Using MIR V3 convention, will need to be V2 compatible eventually.
        self.lst_array = mir_data.in_data["lst"][bl_in_maparr].astype(float)

        # todo: We change between xx yy and rr ll, so we will need to update this.
        self.polarization_array = np.asarray([-5])

        self.spw_array = np.asarray([0])
        self.telescope_location_lat_lon_alt = (sma_lat, sma_lon, sma_alt)
        self.telescope_name = "SMA"
        time_array_mjd = mir_data.in_read["mjd"][bl_in_maparr]
        self.time_array = time_array_mjd + 2400000.5
        self.uvw_array = np.transpose(
            np.vstack(
                (mir_data.bl_data["u"], mir_data.bl_data["v"], mir_data.bl_data["w"])
            )
        )

        # todo: Raw data is in correlation coefficients, we may want to convert to Jy.
        self.vis_units = "uncalib"

        self._set_phased()

        sou_list = mir_data.codes_data[mir_data.codes_data["v_name"] == b"source"]

        self.object_name = sou_list[sou_list["icode"] == isource]["code"][0].decode(
            "utf-8"
        )

        self.phase_center_ra = mir_data.in_data["rar"][0]
        self.phase_center_dec = mir_data.in_data["decr"][0]
        self.phase_center_epoch = mir_data.in_data["epoch"][0]

        self.phase_center_epoch = float(self.phase_center_epoch)
        self.antenna_diameters = np.zeros(self.Nants_telescope) + 6
        self.blt_order = ("time", "baseline")
        self.data_array = np.reshape(
            np.array(mir_data.vis_data),
            (self.Nblts, self.Nspws, self.Nfreqs, self.Npols),
        )
        # Don't need the data anymore, so drop it
        mir_data.unload_data()
        self.flag_array = np.zeros(self.data_array.shape, dtype=bool)
        self.nsample_array = np.ones(self.data_array.shape, dtype=np.single)

    def write_mir(self, filename):
        """
        Write out the SMA MIR files.

        Parameters
        ----------
        filename : str
            The path to the folder on disk to write data to.
        """
        raise NotImplementedError
<commit_msg>Updated copyright to 2020, now getting lat,lon,alt from telescopes.py, and fixed an indent.<commit_after># -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2020 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License

"""Class for reading and writing Mir files."""
import numpy as np

from .uvdata import UVData
from . import mir_parser
from .. import utils as uvutils
from .. import get_telescope

__all__ = ["Mir"]

class Mir(UVData):
    """
    A class for Mir file objects.

    This class defines an Mir-specific subclass of UVData for reading and
    writing Mir files. This class should not be interacted with directly,
    instead use the read_mir and write_mir methods on the UVData class.
    """

    def read_mir(self, filepath, isource=None, irec=None, isb=None, corrchunk=None):
        """
        Read in data from an SMA MIR file, and map to the UVData model.

        Note that with the exception of filename, the rest of the parameters are
        used to sub-select a range of data that matches the limitations of the current
        instantiation of pyuvdata  -- namely 1 spectral window, 1 source. These could
        be dropped in the future, as pyuvdata capabilities grow.

        Parameters
        ----------
        filepath : str
            The file path to the MIR folder to read from.
        isource : int
            Source code for MIR dataset
        irec : int
            Receiver code for MIR dataset
        isb : int
            Sideband code for MIR dataset
        corrchunk : int
            Correlator chunk code for MIR dataset
        """
        # Use the mir_parser to read in metadata, which can be used to select data.
        mir_data = mir_parser.MirParser(filepath)

        # Select out data that we want to work with.
        if isource is None:
            isource = mir_data.in_read["isource"][0]
        if irec is None:
            irec = mir_data.bl_read["irec"][0]
        if isb is None:
            isb = mir_data.bl_read["isb"][0]
        if corrchunk is None:
            corrchunk = mir_data.sp_read["corrchunk"][0]

        mir_data.use_in = mir_data.in_read["isource"] == isource
        mir_data.use_bl = np.logical_and(
            np.logical_and(
                mir_data.bl_read["isb"] == isb, mir_data.bl_read["ipol"] == 0
            ),
            mir_data.bl_read["irec"] == irec,
        )
        mir_data.use_sp = mir_data.sp_read["corrchunk"] == corrchunk

        # Load up the visibilities into the MirParser object. This will also update the
        # filters, and will make sure we're looking at the right metadata.
        mir_data._update_filter()
        if len(mir_data.in_data) == 0:
            raise IndexError("No valid records matching those selections!")

        mir_data.load_data(load_vis=True, load_raw=True)

        # Create a simple array/list for broadcasting values stored on a
        # per-intergration basis in MIR into the (tasty) per-blt records in UVDATA.
        bl_in_maparr = [mir_data.inhid_dict[idx] for idx in mir_data.bl_data["inhid"]]

        # Derive Nants_data this value from baselines.
        self.Nants_data = len(
            np.unique(
                np.concatenate((mir_data.bl_data["iant1"], mir_data.bl_data["iant2"]))
            )
        )

        self.Nants_telescope = 8
        self.Nbls = int(self.Nants_data * (self.Nants_data - 1) / 2)
        self.Nblts = len(mir_data.bl_data)
        self.Nfreqs = int(mir_data.sp_data["nch"][0])
        self.Npols = 1  # todo: We will need to go back and expand this.
        self.Nspws = 1  # todo: We will need to go back and expand this.
        self.Ntimes = len(mir_data.in_data)
        self.ant_1_array = mir_data.bl_data["iant1"] - 1
        self.ant_2_array = mir_data.bl_data["iant2"] - 1
        self.antenna_names = [
            "Ant 1",
            "Ant 2",
            "Ant 3",
            "Ant 4",
            "Ant 5",
            "Ant 6",
            "Ant 7",
            "Ant 8",
        ]
        self.antenna_numbers = np.arange(8)

        # Prepare the XYZ coordinates of the antenna positions.
        antXYZ = np.zeros([self.Nants_telescope, 3])
        for idx in range(self.Nants_telescope):
            if (idx + 1) in mir_data.antpos_data["antenna"]:
                antXYZ[idx] = mir_data.antpos_data["xyz_pos"][
                    mir_data.antpos_data["antenna"] == (idx + 1)
                ]

        # Get the coordinates from the entry in telescope.py
        lat, lon, alt = get_telescope("SMA")._telescope_location.lat_lon_alt()
        self.telescope_location_lat_lon_alt = (lat, lon, alt)

        self.antenna_positions = uvutils.ECEF_from_rotECEF(antXYZ, lon)
        self.baseline_array = (
            2048 * (self.ant_1_array + 1) + (self.ant_2_array + 1) + (2 ** 16)
        )

        # todo: This may need to be reshaped.
        fsky = mir_data.sp_data["fsky"][0] * 1e9
        fres = mir_data.sp_data["fres"][0] * 1e6
        nch = mir_data.sp_data["nch"][0]

        self.channel_width = fres
        self.freq_array = fsky + fres * (np.arange(nch) - (nch / 2 - 0.5))
        self.freq_array = np.reshape(self.freq_array, (1, -1))
        self.history = "Raw Data"
        self.instrument = "SWARM"

        # todo: This won't work when we have multiple spectral windows.
        self.integration_time = mir_data.sp_data["integ"]

        # todo: Using MIR V3 convention, will need to be V2 compatible eventually.
        self.lst_array = mir_data.in_data["lst"][bl_in_maparr].astype(float)

        # todo: We change between xx yy and rr ll, so we will need to update this.
        self.polarization_array = np.asarray([-5])

        self.spw_array = np.asarray([0])

        self.telescope_name = "SMA"
        time_array_mjd = mir_data.in_read["mjd"][bl_in_maparr]
        self.time_array = time_array_mjd + 2400000.5
        self.uvw_array = np.transpose(
            np.vstack(
                (mir_data.bl_data["u"], mir_data.bl_data["v"], mir_data.bl_data["w"])
            )
        )

        # todo: Raw data is in correlation coefficients, we may want to convert to Jy.
        self.vis_units = "uncalib"

        self._set_phased()

        sou_list = mir_data.codes_data[mir_data.codes_data["v_name"] == b"source"]

        self.object_name = sou_list[sou_list["icode"] == isource]["code"][0].decode(
            "utf-8"
        )

        self.phase_center_ra = mir_data.in_data["rar"][0]
        self.phase_center_dec = mir_data.in_data["decr"][0]
        self.phase_center_epoch = mir_data.in_data["epoch"][0]

        self.phase_center_epoch = float(self.phase_center_epoch)
        self.antenna_diameters = np.zeros(self.Nants_telescope) + 6
        self.blt_order = ("time", "baseline")
        self.data_array = np.reshape(
            np.array(mir_data.vis_data),
            (self.Nblts, self.Nspws, self.Nfreqs, self.Npols),
        )
        # Don't need the data anymore, so drop it
        mir_data.unload_data()
        self.flag_array = np.zeros(self.data_array.shape, dtype=bool)
        self.nsample_array = np.ones(self.data_array.shape, dtype=np.single)

    def write_mir(self, filename):
        """
        Write out the SMA MIR files.

        Parameters
        ----------
        filename : str
            The path to the folder on disk to write data to.
        """
        raise NotImplementedError
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import logging
from datetime import datetime, timedelta

from .base import View

from pyramid.httpexceptions import HTTPFound
from pyramid.url import route_url

from pyvac.models import Request, VacationType, User
# from pyvac.helpers.i18n import trans as _
from pyvac.helpers.calendar import delFromCal

import yaml
try:
    from yaml import CSafeLoader as YAMLLoader
except ImportError:
    from yaml import SafeLoader as YAMLLoader

log = logging.getLogger(__name__)

def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days + 1)):
        yield start_date + timedelta(n)

class Send(View):

    def render(self):
        try:
            form_date_from = self.request.params.get('date_from')
            if ' - ' not in form_date_from:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            dates = self.request.params.get('date_from').split(' - ')
            date_from = datetime.strptime(dates[0], '%d/%m/%Y')
            date_to = datetime.strptime(dates[1], '%d/%m/%Y')

            days = float(len([d for d in daterange(date_from, date_to)
                              if d.isoweekday() not in [6, 7]]))

            days_diff = (date_to - date_from).days
            if days_diff < 0:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if (date_to == date_from) and days > 1:
                # same day, asking only for one or less day duration
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if days <= 0:
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            vac_type = VacationType.by_id(self.session,
                                          int(self.request.params.get('type')))

            # label field is used when requesting half day
            label = u''
            breakdown = self.request.params.get('breakdown')
            if breakdown != 'FULL':
                # handle half day
                if (days > 1):
                    msg = ('AM/PM option must be used only when requesting a '
                           'single day.')
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                else:
                    days = 0.5
                    label = unicode(breakdown)

            # check RTT usage
            if vac_type.name == u'RTT':
                rtt_data = self.user.get_rtt_usage(self.session)
                if rtt_data is not None and rtt_data['left'] <= 0:
                    msg = 'No RTT left to take.'
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                # check that we have enough RTT to take
                if rtt_data is not None and days > rtt_data['left']:
                    msg = 'You only have %s RTT to use.' % rtt_data['left']
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            # create the request
            # default values
            target_status = u'PENDING'
            target_user = self.user
            target_notified = False

            sudo_use = False
            if self.user.is_admin:
                sudo_user_id = int(self.request.params.get('sudo_user'))
                if sudo_user_id != -1:
                    user = User.by_id(self.session, sudo_user_id)
                    if user:
                        sudo_use = True
                        target_user = user
                        target_status = u'APPROVED_ADMIN'
                        target_notified = True

            request = Request(date_from=date_from,
                              date_to=date_to,
                              days=days,
                              vacation_type=vac_type,
                              status=target_status,
                              user=target_user,
                              notified=target_notified,
                              label=label,
                              )
            self.session.add(request)
            self.session.flush()

            if request and not sudo_use:
                msg = 'Request sent to your manager.'
                self.request.session.flash('info;%s' % msg)
                # call celery task directly, do not wait for polling
                from celery.registry import tasks
                from celery.task import subtask
                req_task = tasks['worker_pending']
                data = {'req_id': request.id}
                subtask(req_task).delay(data=data)

        except Exception as exc:
            log.error(exc)
            msg = ('An error has occured while processing this request: %r'
                   % exc)
            self.request.session.flash('error;%s' % msg)

        return HTTPFound(location=route_url('home', self.request))

class List(View):
    """
    List all user requests
    """
    def render(self):

        req_list = {'requests': [], 'conflicts': {}}
        requests = []
        if self.user.is_admin:
            country = self.user.country
            requests = Request.all_for_admin_per_country(self.session,
                                                         country)
            # check if admin user is also a manager, in this case merge all
            # requests
            requests_manager = Request.by_manager(self.session, self.user)
            # avoid duplicate entries
            req_to_add = [req for req in requests_manager
                          if req not in requests]
            requests.extend(req_to_add)
        elif self.user.is_super:
            requests = Request.by_manager(self.session, self.user)

        if requests:
            conflicts = {}
            for req in requests:
                req.conflict = [req2.summary for req2 in
                                Request.in_conflict(self.session, req)]
                if req.conflict:
                    conflicts[req.id] = '\n'.join(req.conflict)
            req_list['requests'] = requests
            req_list['conflicts'] = conflicts

        # always add our requests
        for req in Request.by_user(self.session, self.user):
            if req not in req_list['requests']:
                req_list['requests'].append(req)

        return req_list

class Accept(View):
    """
    Accept a request
    """

    def render(self):

        req_id = self.request.params.get('request_id')
        req = Request.by_id(self.session, req_id)
        if not req:
            return ''

        data = {'req_id': req.id}

        only_manager = False
        # we should handle the case where the admin is also a user manager
        if (self.user.ldap_user and (req.user.manager_dn == self.user.dn)
                and (req.status == 'PENDING')):
            only_manager = True

        if self.user.is_admin and not only_manager:
            req.update_status('APPROVED_ADMIN')
            # save who performed this action
            req.last_action_user_id = self.user.id

            task_name = 'worker_approved'
            settings = self.request.registry.settings
            with open(settings['pyvac.celery.yaml']) as fdesc:
                Conf = yaml.load(fdesc, YAMLLoader)
            data['caldav.url'] = Conf.get('caldav').get('url')
        else:
            req.update_status('ACCEPTED_MANAGER')
            # save who performed this action
            req.last_action_user_id = self.user.id
            task_name = 'worker_accepted'

        self.session.flush()

        # call celery task directly, do not wait for polling
        from celery.registry import tasks
        from celery.task import subtask
        req_task = tasks[task_name]

        subtask(req_task).delay(data=data)

        return req.status

class Refuse(View):
    """
    Refuse a request
    """

    def render(self):

        req_id = self.request.params.get('request_id')
        req = Request.by_id(self.session, req_id)
        if not req:
            return ''
        reason = self.request.params.get('reason')

        req.reason = reason
        req.update_status('DENIED')
        # save who performed this action
        req.last_action_user_id = self.user.id
        self.session.flush()

        # call celery task directly, do not wait for polling
        from celery.registry import tasks
        from celery.task import subtask
        req_task = tasks['worker_denied']
        data = {'req_id': req.id}
        subtask(req_task).delay(data=data)

        return req.status

class Cancel(View):
    """
    Cancel a request and remove entry from calendar if needed.
    """

    def render(self):

        req_id = self.request.params.get('request_id')
        req = Request.by_id(self.session, req_id)
        if not req:
            return ''

        # check if request have already been consumed
        if not self.user.is_admin:
            today = datetime.now()
            if req.date_from <= today:
                log.error('User %s tried to CANCEL consumed request %d.' %
                          (self.user.login, req.id))
                return req.status

        # delete from calendar
        if req.status == 'APPROVED_ADMIN' and req.ics_url:
            settings = self.request.registry.settings
            with open(settings['pyvac.celery.yaml']) as fdesc:
                Conf = yaml.load(fdesc, YAMLLoader)
            caldav_url = Conf.get('caldav').get('url')
            delFromCal(caldav_url, req.ics_url)

        req.update_status('CANCELED')
        # save who performed this action
        req.last_action_user_id = self.user.id

        self.session.flush()
        return req.status

class Export(View):
    """
    Display form to export requests
    """
    def render(self):
        from datetime import datetime
        start = datetime(2014, 5, 1)
        today = datetime.now()
        entries = []
        for year in reversed(range(start.year, today.year + 1)):
            for month in reversed(range(1, 13)):
                temp = datetime(year, month, 1)
                if start <= temp <= today:
                    entries.append(('%d/%d' % (month, year),
                                   temp.strftime('%B %Y')))

        return {'months': entries,
                'current_month': '%d/%d' % (today.month, today.year)}

class Exported(View):
    """
    Export all requests of a month to csv
    """
    def render(self):

        exported = {}
        if self.user.is_admin:
            country = self.user.country
            month, year = self.request.params.get('month').split('/')
            requests = Request.get_by_month(self.session, country,
                                            int(month), int(year))
            data = []
            header = '%s,%s,%s,%s,%s,%s,%s' % ('#', 'lastname', 'firstname',
                                               'from', 'to', 'number', 'type')
            data.append(header)
            for idx, req in enumerate(requests, start=1):
                data.append('%d,%s' % (idx, req.summarycsv))
            exported = '\n'.join(data)
        return {u'exported': exported}
<commit_msg>Update Request list view to now display conflicts based on unit and not on manager<commit_after># -*- coding: utf-8 -*-
import logging
from datetime import datetime, timedelta

from .base import View

from pyramid.httpexceptions import HTTPFound
from pyramid.url import route_url

from pyvac.models import Request, VacationType, User
# from pyvac.helpers.i18n import trans as _
from pyvac.helpers.calendar import delFromCal

import yaml
try:
    from yaml import CSafeLoader as YAMLLoader
except ImportError:
    from yaml import SafeLoader as YAMLLoader

log = logging.getLogger(__name__)

def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days + 1)):
        yield start_date + timedelta(n)

class Send(View):

    def render(self):
        try:
            form_date_from = self.request.params.get('date_from')
            if ' - ' not in form_date_from:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            dates = self.request.params.get('date_from').split(' - ')
            date_from = datetime.strptime(dates[0], '%d/%m/%Y')
            date_to = datetime.strptime(dates[1], '%d/%m/%Y')

            days = float(len([d for d in daterange(date_from, date_to)
                              if d.isoweekday() not in [6, 7]]))

            days_diff = (date_to - date_from).days
            if days_diff < 0:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if (date_to == date_from) and days > 1:
                # same day, asking only for one or less day duration
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if days <= 0:
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            vac_type = VacationType.by_id(self.session,
                                          int(self.request.params.get('type')))

            # label field is used when requesting half day
            label = u''
            breakdown = self.request.params.get('breakdown')
            if breakdown != 'FULL':
                # handle half day
                if (days > 1):
                    msg = ('AM/PM option must be used only when requesting a '
                           'single day.')
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                else:
                    days = 0.5
                    label = unicode(breakdown)

            # check RTT usage
            if vac_type.name == u'RTT':
                rtt_data = self.user.get_rtt_usage(self.session)
                if rtt_data is not None and rtt_data['left'] <= 0:
                    msg = 'No RTT left to take.'
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                # check that we have enough RTT to take
                if rtt_data is not None and days > rtt_data['left']:
                    msg = 'You only have %s RTT to use.' % rtt_data['left']
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            # create the request
            # default values
            target_status = u'PENDING'
            target_user = self.user
            target_notified = False

            sudo_use = False
            if self.user.is_admin:
                sudo_user_id = int(self.request.params.get('sudo_user'))
                if sudo_user_id != -1:
                    user = User.by_id(self.session, sudo_user_id)
                    if user:
                        sudo_use = True
                        target_user = user
                        target_status = u'APPROVED_ADMIN'
                        target_notified = True

            request = Request(date_from=date_from,
                              date_to=date_to,
                              days=days,
                              vacation_type=vac_type,
                              status=target_status,
                              user=target_user,
                              notified=target_notified,
                              label=label,
                              )
            self.session.add(request)
            self.session.flush()

            if request and not sudo_use:
                msg = 'Request sent to your manager.'
                self.request.session.flash('info;%s' % msg)
                # call celery task directly, do not wait for polling
                from celery.registry import tasks
                from celery.task import subtask
                req_task = tasks['worker_pending']
                data = {'req_id': request.id}
                subtask(req_task).delay(data=data)

        except Exception as exc:
            log.error(exc)
            msg = ('An error has occured while processing this request: %r'
                   % exc)
            self.request.session.flash('error;%s' % msg)

        return HTTPFound(location=route_url('home', self.request))

class List(View):
    """
    List all user requests
    """
    def render(self):

        req_list = {'requests': [], 'conflicts': {}}
        requests = []
        if self.user.is_admin:
            country = self.user.country
            requests = Request.all_for_admin_per_country(self.session,
                                                         country)
            # check if admin user is also a manager, in this case merge all
            # requests
            requests_manager = Request.by_manager(self.session, self.user)
            # avoid duplicate entries
            req_to_add = [req for req in requests_manager
                          if req not in requests]
            requests.extend(req_to_add)
        elif self.user.is_super:
            requests = Request.by_manager(self.session, self.user)

        if requests:
            conflicts = {}
            for req in requests:
                req.conflict = [req2.summary for req2 in
                                Request.in_conflict_ou(self.session, req)]
                if req.conflict:
                    conflicts[req.id] = '\n'.join(req.conflict)
            req_list['requests'] = requests
            req_list['conflicts'] = conflicts

        # always add our requests
        for req in Request.by_user(self.session, self.user):
            if req not in req_list['requests']:
                req_list['requests'].append(req)

        return req_list

class Accept(View):
    """
    Accept a request
    """

    def render(self):

        req_id = self.request.params.get('request_id')
        req = Request.by_id(self.session, req_id)
        if not req:
            return ''

        data = {'req_id': req.id}

        only_manager = False
        # we should handle the case where the admin is also a user manager
        if (self.user.ldap_user and (req.user.manager_dn == self.user.dn)
                and (req.status == 'PENDING')):
            only_manager = True

        if self.user.is_admin and not only_manager:
            req.update_status('APPROVED_ADMIN')
            # save who performed this action
            req.last_action_user_id = self.user.id

            task_name = 'worker_approved'
            settings = self.request.registry.settings
            with open(settings['pyvac.celery.yaml']) as fdesc:
                Conf = yaml.load(fdesc, YAMLLoader)
            data['caldav.url'] = Conf.get('caldav').get('url')
        else:
            req.update_status('ACCEPTED_MANAGER')
            # save who performed this action
            req.last_action_user_id = self.user.id
            task_name = 'worker_accepted'

        self.session.flush()

        # call celery task directly, do not wait for polling
        from celery.registry import tasks
        from celery.task import subtask
        req_task = tasks[task_name]

        subtask(req_task).delay(data=data)

        return req.status

class Refuse(View):
    """
    Refuse a request
    """

    def render(self):

        req_id = self.request.params.get('request_id')
        req = Request.by_id(self.session, req_id)
        if not req:
            return ''
        reason = self.request.params.get('reason')

        req.reason = reason
        req.update_status('DENIED')
        # save who performed this action
        req.last_action_user_id = self.user.id
        self.session.flush()

        # call celery task directly, do not wait for polling
        from celery.registry import tasks
        from celery.task import subtask
        req_task = tasks['worker_denied']
        data = {'req_id': req.id}
        subtask(req_task).delay(data=data)

        return req.status

class Cancel(View):
    """
    Cancel a request and remove entry from calendar if needed.
    """

    def render(self):

        req_id = self.request.params.get('request_id')
        req = Request.by_id(self.session, req_id)
        if not req:
            return ''

        # check if request have already been consumed
        if not self.user.is_admin:
            today = datetime.now()
            if req.date_from <= today:
                log.error('User %s tried to CANCEL consumed request %d.' %
                          (self.user.login, req.id))
                return req.status

        # delete from calendar
        if req.status == 'APPROVED_ADMIN' and req.ics_url:
            settings = self.request.registry.settings
            with open(settings['pyvac.celery.yaml']) as fdesc:
                Conf = yaml.load(fdesc, YAMLLoader)
            caldav_url = Conf.get('caldav').get('url')
            delFromCal(caldav_url, req.ics_url)

        req.update_status('CANCELED')
        # save who performed this action
        req.last_action_user_id = self.user.id

        self.session.flush()
        return req.status

class Export(View):
    """
    Display form to export requests
    """
    def render(self):
        from datetime import datetime
        start = datetime(2014, 5, 1)
        today = datetime.now()
        entries = []
        for year in reversed(range(start.year, today.year + 1)):
            for month in reversed(range(1, 13)):
                temp = datetime(year, month, 1)
                if start <= temp <= today:
                    entries.append(('%d/%d' % (month, year),
                                   temp.strftime('%B %Y')))

        return {'months': entries,
                'current_month': '%d/%d' % (today.month, today.year)}

class Exported(View):
    """
    Export all requests of a month to csv
    """
    def render(self):

        exported = {}
        if self.user.is_admin:
            country = self.user.country
            month, year = self.request.params.get('month').split('/')
            requests = Request.get_by_month(self.session, country,
                                            int(month), int(year))
            data = []
            header = '%s,%s,%s,%s,%s,%s,%s' % ('#', 'lastname', 'firstname',
                                               'from', 'to', 'number', 'type')
            data.append(header)
            for idx, req in enumerate(requests, start=1):
                data.append('%d,%s' % (idx, req.summarycsv))
            exported = '\n'.join(data)
        return {u'exported': exported}
<|endoftext|>


<commit_before># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license

import requests
import traceback

import xml.etree.ElementTree as ET
from superdesk.io.feeding_services.http_service import HTTPFeedingService
from superdesk.io.registry import register_feeding_service
from superdesk.errors import IngestApiError
from superdesk.logging import logger
from superdesk.utc import utcnow

class AAPSportsHTTPFeedingService(HTTPFeedingService):
    label = 'AAP Sports Results Feed'
    NAME = 'aap_sports_http'
    ERRORS = [IngestApiError.apiTimeoutError().get_error_description(),
              IngestApiError.apiRedirectError().get_error_description(),
              IngestApiError.apiRequestError().get_error_description(),
              IngestApiError.apiUnicodeError().get_error_description(),
              IngestApiError.apiParseError().get_error_description(),
              IngestApiError.apiGeneralError().get_error_description()]

    """
    Defines the collection service to be used with this ingest feeding service.
    """
    service = 'events'

    def _update(self, provider, update):
        self.provider = provider
        parser = self.get_feed_parser(provider)

        # <Response Status_Code="OK" Status_Message="" Status_Session="ae86c219-fef6-45d5-92cd-bdc67123f408"/>
        year = int(utcnow().year) % 100
        config = provider.get('config', {})
        content = self._request(config.get('login_url').format(config.get('username'), config.get('password')))
        xml = ET.fromstring(content)
        if xml.attrib['Status_Code'] == 'OK':
            session = xml.attrib['Status_Session']
            content = self._request(config.get('fixtures_url').format(session, '', '', ''))
            xml = ET.fromstring(content)
            for s in xml.findall('.//Sports/Sport'):
                sport_id = s.attrib['SportID']
                sport_name = s.attrib['SportName']
                content = self._request(config.get('fixtures_url').format(session, sport_id, '', ''))
                sport_xml = ET.fromstring(content)
                for c in sport_xml.findall('.//Competition'):
                    comp_id = c.attrib.get('Comp_ID')
                    comp_name = c.attrib.get('Comp_Name')
                    content = self._request(config.get('fixtures_url').format(session, sport_id, comp_id, ''))
                    comp_xml = ET.fromstring(content)
                    for season in comp_xml.findall('.//Season'):
                        season_id = season.attrib.get('SeasonID')
                        if str(year) in season_id or str(year + 1) in season_id:
                            content = self._request(
                                config.get('fixtures_url').format(session, sport_id, comp_id, season_id))
                            fixture_xml = ET.fromstring(content)
                            logger.info('Parsing {}/{} {}/{}'.format(sport_id, sport_name, comp_id, comp_name))
                            items = parser.parse({'fixture_xml': fixture_xml, 'sport_id': sport_id,
                                                  'sport_name': sport_name, 'comp_name': comp_name, 'comp_id': comp_id},
                                                 provider)
                            if len(items) > 0:
                                yield items

    def _request(self, url):
        try:
            response = requests.get(url, params={}, timeout=120)
        except requests.exceptions.Timeout as ex:
            # Maybe set up for a retry, or continue in a retry loop
            raise IngestApiError.apiTimeoutError(ex, self.provider)
        except requests.exceptions.TooManyRedirects as ex:
            # Tell the user their URL was bad and try a different one
            raise IngestApiError.apiRedirectError(ex, self.provider)
        except requests.exceptions.RequestException as ex:
            # catastrophic error. bail.
            raise IngestApiError.apiRequestError(ex, self.provider)
        except Exception as error:
            traceback.print_exc()
            raise IngestApiError.apiGeneralError(error, self.provider)

        if response.status_code == 404:
            raise LookupError('Not found')

        return response.content

register_feeding_service(AAPSportsHTTPFeedingService.NAME, AAPSportsHTTPFeedingService(),
                         AAPSportsHTTPFeedingService.ERRORS)
<commit_msg>Adds sport filtering to sports planning ingest<commit_after># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license

import requests
import traceback

import xml.etree.ElementTree as ET
from superdesk.io.feeding_services.http_service import HTTPFeedingService
from superdesk.io.registry import register_feeding_service
from superdesk.errors import IngestApiError
from superdesk.logging import logger
from superdesk.utc import utcnow

class AAPSportsHTTPFeedingService(HTTPFeedingService):
    label = 'AAP Sports Results Feed'
    NAME = 'aap_sports_http'
    ERRORS = [IngestApiError.apiTimeoutError().get_error_description(),
              IngestApiError.apiRedirectError().get_error_description(),
              IngestApiError.apiRequestError().get_error_description(),
              IngestApiError.apiUnicodeError().get_error_description(),
              IngestApiError.apiParseError().get_error_description(),
              IngestApiError.apiGeneralError().get_error_description()]

    """
    Defines the collection service to be used with this ingest feeding service.
    """
    service = 'events'

    def _update(self, provider, update):
        self.provider = provider
        parser = self.get_feed_parser(provider)

        # get the current year, it is used to filter fixtures for this year and next
        year = int(utcnow().year) % 100
        config = provider.get('config', {})
        content = self._request(config.get('login_url').format(config.get('username'), config.get('password')))
        # get the configured sports
        configured_sports = config.get('sports').split(',')
        xml = ET.fromstring(content)
        if xml.attrib['Status_Code'] == 'OK':
            session = xml.attrib['Status_Session']
            content = self._request(config.get('fixtures_url').format(session, '', '', ''))
            xml = ET.fromstring(content)
            for s in xml.findall('.//Sports/Sport'):
                sport_id = s.attrib['SportID']
                if sport_id not in configured_sports:
                    continue
                sport_name = s.attrib['SportName']
                content = self._request(config.get('fixtures_url').format(session, sport_id, '', ''))
                sport_xml = ET.fromstring(content)
                for c in sport_xml.findall('.//Competition'):
                    comp_id = c.attrib.get('Comp_ID')
                    comp_name = c.attrib.get('Comp_Name')
                    content = self._request(config.get('fixtures_url').format(session, sport_id, comp_id, ''))
                    comp_xml = ET.fromstring(content)
                    for season in comp_xml.findall('.//Season'):
                        season_id = season.attrib.get('SeasonID')
                        if str(year) in season_id or str(year + 1) in season_id:
                            content = self._request(
                                config.get('fixtures_url').format(session, sport_id, comp_id, season_id))
                            fixture_xml = ET.fromstring(content)
                            logger.info('Parsing {}/{} {}/{}'.format(sport_id, sport_name, comp_id, comp_name))
                            items = parser.parse({'fixture_xml': fixture_xml, 'sport_id': sport_id,
                                                  'sport_name': sport_name, 'comp_name': comp_name, 'comp_id': comp_id},
                                                 provider)
                            if len(items) > 0:
                                yield items

    def _request(self, url):
        try:
            response = requests.get(url, params={}, timeout=120)
        except requests.exceptions.Timeout as ex:
            # Maybe set up for a retry, or continue in a retry loop
            raise IngestApiError.apiTimeoutError(ex, self.provider)
        except requests.exceptions.TooManyRedirects as ex:
            # Tell the user their URL was bad and try a different one
            raise IngestApiError.apiRedirectError(ex, self.provider)
        except requests.exceptions.RequestException as ex:
            # catastrophic error. bail.
            raise IngestApiError.apiRequestError(ex, self.provider)
        except Exception as error:
            traceback.print_exc()
            raise IngestApiError.apiGeneralError(error, self.provider)

        if response.status_code == 404:
            raise LookupError('Not found')

        return response.content

register_feeding_service(AAPSportsHTTPFeedingService.NAME, AAPSportsHTTPFeedingService(),
                         AAPSportsHTTPFeedingService.ERRORS)
<|endoftext|>


<commit_before>"""
Import hooks; when installed with the install() function, these hooks
allow importing .pyx files as if they were Python modules.

If you want the hook installed every time you run Python
you can add it to your Python version by adding these lines to
sitecustomize.py (which you can create from scratch in site-packages
if it doesn't exist there or somewhere else on your python path)::

    import pyximport
    pyximport.install()

For instance on the Mac with a non-system Python 2.3, you could create
sitecustomize.py with only those two lines at
/usr/local/lib/python2.3/site-packages/sitecustomize.py .

A custom distutils.core.Extension instance and setup() args
(Distribution) for for the build can be defined by a <modulename>.pyxbld
file like:

# examplemod.pyxbdl
def make_ext(modname, pyxfilename):
    from distutils.extension import Extension
    return Extension(name = modname,
                     sources=[pyxfilename, 'hello.c'],
                     include_dirs=['/myinclude'] )
def make_setup_args():
    return dict(script_args=["--compiler=mingw32"])

Extra dependencies can be defined by a <modulename>.pyxdep .
See README.

Since Cython 0.11, the :mod:`pyximport` module also has experimental
compilation support for normal Python modules.  This allows you to
automatically run Cython on every .pyx and .py module that Python
imports, including parts of the standard library and installed
packages.  Cython will still fail to compile a lot of Python modules,
in which case the import mechanism will fall back to loading the
Python source modules instead.  The .py import mechanism is installed
like this::

    pyximport.install(pyimport = True)

Running this module as a top-level script will run a test and then print
the documentation.

This code is based on the Py2.3+ import protocol as described in PEP 302.
"""

import sys
import os
import glob
import imp

mod_name = "pyximport"

assert sys.hexversion >= 0x2030000, "need Python 2.3 or later"

PYX_EXT = ".pyx"
PYXDEP_EXT = ".pyxdep"
PYXBLD_EXT = ".pyxbld"

DEBUG_IMPORT = False

# Performance problem: for every PYX file that is imported, we will
# invoke the whole distutils infrastructure even if the module is
# already built. It might be more efficient to only do it when the
# mod time of the .pyx is newer than the mod time of the .so but
# the question is how to get distutils to tell me the name of the .so
# before it builds it. Maybe it is easy...but maybe the peformance
# issue isn't real.
def _load_pyrex(name, filename):
    "Load a pyrex file given a name and filename."

def get_distutils_extension(modname, pyxfilename):
#    try:
#        import hashlib
#    except ImportError:
#        import md5 as hashlib
#    extra = "_" + hashlib.md5(open(pyxfilename).read()).hexdigest()
#    modname = modname + extra
    extension_mod,setup_args = handle_special_build(modname, pyxfilename)
    if not extension_mod:
        from distutils.extension import Extension
        extension_mod = Extension(name = modname, sources=[pyxfilename])
    return extension_mod,setup_args

def handle_special_build(modname, pyxfilename):
    special_build = os.path.splitext(pyxfilename)[0] + PYXBLD_EXT
    ext = None
    setup_args={}
    if os.path.exists(special_build):
        # globls = {}
        # locs = {}
        # execfile(special_build, globls, locs)
        # ext = locs["make_ext"](modname, pyxfilename)
        mod = imp.load_source("XXXX", special_build, open(special_build))
        make_ext = getattr(mod,'make_ext',None)
        if make_ext:
            ext = make_ext(modname, pyxfilename)
            assert ext and ext.sources, ("make_ext in %s did not return Extension"
                                         % special_build)
        make_setup_args = getattr(mod,'make_setup_args',None)
        if make_setup_args:
            setup_args = make_setup_args()
            assert isinstance(setup_args,dict), ("make_setup_args in %s did not return a dict"
                                         % special_build)
        assert set or setup_args, ("neither make_ext nor make_setup_args %s"
                                         % special_build)
        ext.sources = [os.path.join(os.path.dirname(special_build), source)
                       for source in ext.sources]
    return ext, setup_args

def handle_dependencies(pyxfilename):
    testing = '_test_files' in globals()
    dependfile = os.path.splitext(pyxfilename)[0] + PYXDEP_EXT

    # by default let distutils decide whether to rebuild on its own
    # (it has a better idea of what the output file will be)

    # but we know more about dependencies so force a rebuild if
    # some of the dependencies are newer than the pyxfile.
    if os.path.exists(dependfile):
        depends = open(dependfile).readlines()
        depends = [depend.strip() for depend in depends]

        # gather dependencies in the "files" variable
        # the dependency file is itself a dependency
        files = [dependfile]
        for depend in depends:
            fullpath = os.path.join(os.path.dirname(dependfile),
                                    depend)
            files.extend(glob.glob(fullpath))

        # only for unit testing to see we did the right thing
        if testing:
            _test_files[:] = []  #$pycheck_no

        # if any file that the pyxfile depends upon is newer than
        # the pyx file, 'touch' the pyx file so that distutils will
        # be tricked into rebuilding it.
        for file in files:
            from distutils.dep_util import newer
            if newer(file, pyxfilename):
                print("Rebuilding because of ", file)
                filetime = os.path.getmtime(file)
                os.utime(pyxfilename, (filetime, filetime))
                if testing:
                    _test_files.append(file)

def build_module(name, pyxfilename, pyxbuild_dir=None):
    assert os.path.exists(pyxfilename), (
        "Path does not exist: %s" % pyxfilename)
    handle_dependencies(pyxfilename)

    extension_mod,setup_args = get_distutils_extension(name, pyxfilename)
    build_in_temp=pyxargs.build_in_temp
    sargs=pyxargs.setup_args.copy()
    sargs.update(setup_args)
    build_in_temp=sargs.pop('build_in_temp',build_in_temp)

    import pyxbuild
    so_path = pyxbuild.pyx_to_dll(pyxfilename, extension_mod,
                                  build_in_temp=build_in_temp,
                                  pyxbuild_dir=pyxbuild_dir,
                                  setup_args=sargs,
                                  reload_support=pyxargs.reload_support)
    assert os.path.exists(so_path), "Cannot find: %s" % so_path

    junkpath = os.path.join(os.path.dirname(so_path), name+"_*") #very dangerous with --inplace ?
    junkstuff = glob.glob(junkpath)
    for path in junkstuff:
        if path!=so_path:
            try:
                os.remove(path)
            except IOError:
                print("Couldn't remove ", path)

    return so_path

def load_module(name, pyxfilename, pyxbuild_dir=None):
    try:
        so_path = build_module(name, pyxfilename, pyxbuild_dir)
        mod = imp.load_dynamic(name, so_path)
        assert mod.__file__ == so_path, (mod.__file__, so_path)
    except Exception, e:
        import traceback
        raise ImportError("Building module failed: %s" %
                          traceback.format_exception_only(*sys.exc_info()[:2])),None,sys.exc_info()[2]
    return mod

# import hooks

class PyxImporter(object):
    """A meta-path importer for .pyx files.
    """
    def __init__(self, extension=PYX_EXT, pyxbuild_dir=None):
        self.extension = extension
        self.pyxbuild_dir = pyxbuild_dir

    def find_module(self, fullname, package_path=None):
        if fullname in sys.modules  and  not pyxargs.reload_support:
            return None  # only here when reload()
        try:
            fp, pathname, (ext,mode,ty) = imp.find_module(fullname,package_path)
            if fp: fp.close()  # Python should offer a Default-Loader to avoid this double find/open!
            if pathname.endswith(self.extension):
                return PyxLoader(fullname, pathname,
                                 pyxbuild_dir=self.pyxbuild_dir)
            if ty != imp.C_EXTENSION: # only when an extension, check if we have a .pyx next!
                return None

            # find .pyx fast, when .so/.pyd exist --inplace
            pyxpath = os.path.splitext(pathname)[0]+self.extension
            if os.path.isfile(pyxpath):
                return PyxLoader(fullname, pyxpath,
                                 pyxbuild_dir=self.pyxbuild_dir)

            # .so/.pyd's on PATH should not be remote from .pyx's
            # think no need to implement PyxArgs.importer_search_remote here?

        except ImportError:
            pass

        # searching sys.path ...

        #if DEBUG_IMPORT:  print "SEARCHING", fullname, package_path
        if '.' in fullname: # only when package_path anyway?
            mod_parts = fullname.split('.')
            module_name = mod_parts[-1]
        else:
            module_name = fullname
        pyx_module_name = module_name + self.extension
        # this may work, but it returns the file content, not its path
        #import pkgutil
        #pyx_source = pkgutil.get_data(package, pyx_module_name)

        if package_path:
            paths = package_path
        else:
            paths = sys.path
        join_path = os.path.join
        is_file = os.path.isfile
        #is_dir = os.path.isdir
        sep = os.path.sep
        for path in paths:
            if not path:
                path = os.getcwd()
            if is_file(path+sep+pyx_module_name):
                return PyxLoader(fullname, join_path(path, pyx_module_name),
                                 pyxbuild_dir=self.pyxbuild_dir)

        # not found, normal package, not a .pyx file, none of our business
        return None

class PyImporter(PyxImporter):
    """A meta-path importer for normal .py files.
    """
    def __init__(self, pyxbuild_dir=None):
        self.super = super(PyImporter, self)
        self.super.__init__(extension='.py', pyxbuild_dir=pyxbuild_dir)
        self.uncompilable_modules = {}
        self.blocked_modules = ['Cython']

    def find_module(self, fullname, package_path=None):
        if fullname in sys.modules:
            return None
        if fullname.startswith('Cython.'):
            return None
        if fullname in self.blocked_modules:
            # prevent infinite recursion
            return None
        if DEBUG_IMPORT:
            print("trying import of module '%s'" % fullname)
        if fullname in self.uncompilable_modules:
            path, last_modified = self.uncompilable_modules[fullname]
            try:
                new_last_modified = os.stat(path).st_mtime
                if new_last_modified > last_modified:
                    # import would fail again
                    return None
            except OSError:
                # module is no longer where we found it, retry the import
                pass

        self.blocked_modules.append(fullname)
        try:
            importer = self.super.find_module(fullname, package_path)
            if importer is not None:
                if DEBUG_IMPORT:
                    print("importer found")
                try:
                    if importer.init_path:
                        path = importer.init_path
                    else:
                        path = importer.path
                    build_module(fullname, path,
                                 pyxbuild_dir=self.pyxbuild_dir)
                except Exception, e:
                    if DEBUG_IMPORT:
                        import traceback
                        traceback.print_exc()
                    # build failed, not a compilable Python module
                    try:
                        last_modified = os.stat(path).st_mtime
                    except OSError:
                        last_modified = 0
                    self.uncompilable_modules[fullname] = (path, last_modified)
                    importer = None
        finally:
            self.blocked_modules.pop()
        return importer

class PyxLoader(object):
    def __init__(self, fullname, path, init_path=None, pyxbuild_dir=None):
        self.fullname = fullname
        self.path, self.init_path = path, init_path
        self.pyxbuild_dir = pyxbuild_dir

    def load_module(self, fullname):
        assert self.fullname == fullname, (
            "invalid module, expected %s, got %s" % (
            self.fullname, fullname))
        if self.init_path:
            # package
            #print "PACKAGE", fullname
            module = load_module(fullname, self.init_path,
                                 self.pyxbuild_dir)
            module.__path__ = [self.path]
        else:
            #print "MODULE", fullname
            module = load_module(fullname, self.path,
                                 self.pyxbuild_dir)
        return module

#install args
class PyxArgs(object):
    build_dir=True
    build_in_temp=True
    setup_args={}   #None

##pyxargs=None

def install(pyximport=True, pyimport=False, build_dir=None, build_in_temp=True,
            setup_args={}, reload_support=False ):
    """Main entry point. Call this to install the .pyx import hook in
    your meta-path for a single Python process.  If you want it to be
    installed whenever you use Python, add it to your sitecustomize
    (as described above).

    You can pass ``pyimport=True`` to also install the .py import hook
    in your meta-path.  Note, however, that it is highly experimental,
    will not work for most .py files, and will therefore only slow
    down your imports.  Use at your own risk.

    By default, compiled modules will end up in a ``.pyxbld``
    directory in the user's home directory.  Passing a different path
    as ``build_dir`` will override this.

    ``build_in_temp=False`` will produce the C files locally. Working
    with complex dependencies and debugging becomes more easy. This
    can principally interfere with existing files of the same name.
    build_in_temp can be overriden by <modulename>.pyxbld/make_setup_args()
    by a dict item of 'build_in_temp'

    ``setup_args``: dict of arguments for Distribution - see
    distutils.core.setup() . They are extended/overriden by those of
    <modulename>.pyxbld/make_setup_args()

    ``reload_support``:  Enables support for dynamic
    reload(<pyxmodulename>), e.g. after a change in the Cython code.
    Additional files <so_path>.reloadNN may arise on that account, when
    the previously loaded module file cannot be overwritten.
    """
    if not build_dir:
        build_dir = os.path.expanduser('~/.pyxbld')

    global pyxargs
    pyxargs = PyxArgs()  #$pycheck_no
    pyxargs.build_dir = build_dir
    pyxargs.build_in_temp = build_in_temp
    pyxargs.setup_args = (setup_args or {}).copy()
    pyxargs.reload_support = reload_support

    has_py_importer = False
    has_pyx_importer = False
    for importer in sys.meta_path:
        if isinstance(importer, PyxImporter):
            if isinstance(importer, PyImporter):
                has_py_importer = True
            else:
                has_pyx_importer = True

    if pyimport and not has_py_importer:
        importer = PyImporter(pyxbuild_dir=build_dir)
        sys.meta_path.insert(0, importer)

    if pyximport and not has_pyx_importer:
        importer = PyxImporter(pyxbuild_dir=build_dir)
        sys.meta_path.append(importer)

# MAIN

def show_docs():
    import __main__
    __main__.__name__ = mod_name
    for name in dir(__main__):
        item = getattr(__main__, name)
        try:
            setattr(item, "__module__", mod_name)
        except (AttributeError, TypeError):
            pass
    help(__main__)

if __name__ == '__main__':
    show_docs()
<commit_msg>blacklist distutils.extension in pyximport<commit_after>"""
Import hooks; when installed with the install() function, these hooks
allow importing .pyx files as if they were Python modules.

If you want the hook installed every time you run Python
you can add it to your Python version by adding these lines to
sitecustomize.py (which you can create from scratch in site-packages
if it doesn't exist there or somewhere else on your python path)::

    import pyximport
    pyximport.install()

For instance on the Mac with a non-system Python 2.3, you could create
sitecustomize.py with only those two lines at
/usr/local/lib/python2.3/site-packages/sitecustomize.py .

A custom distutils.core.Extension instance and setup() args
(Distribution) for for the build can be defined by a <modulename>.pyxbld
file like:

# examplemod.pyxbdl
def make_ext(modname, pyxfilename):
    from distutils.extension import Extension
    return Extension(name = modname,
                     sources=[pyxfilename, 'hello.c'],
                     include_dirs=['/myinclude'] )
def make_setup_args():
    return dict(script_args=["--compiler=mingw32"])

Extra dependencies can be defined by a <modulename>.pyxdep .
See README.

Since Cython 0.11, the :mod:`pyximport` module also has experimental
compilation support for normal Python modules.  This allows you to
automatically run Cython on every .pyx and .py module that Python
imports, including parts of the standard library and installed
packages.  Cython will still fail to compile a lot of Python modules,
in which case the import mechanism will fall back to loading the
Python source modules instead.  The .py import mechanism is installed
like this::

    pyximport.install(pyimport = True)

Running this module as a top-level script will run a test and then print
the documentation.

This code is based on the Py2.3+ import protocol as described in PEP 302.
"""

import sys
import os
import glob
import imp

mod_name = "pyximport"

assert sys.hexversion >= 0x2030000, "need Python 2.3 or later"

PYX_EXT = ".pyx"
PYXDEP_EXT = ".pyxdep"
PYXBLD_EXT = ".pyxbld"

DEBUG_IMPORT = False

# Performance problem: for every PYX file that is imported, we will
# invoke the whole distutils infrastructure even if the module is
# already built. It might be more efficient to only do it when the
# mod time of the .pyx is newer than the mod time of the .so but
# the question is how to get distutils to tell me the name of the .so
# before it builds it. Maybe it is easy...but maybe the peformance
# issue isn't real.
def _load_pyrex(name, filename):
    "Load a pyrex file given a name and filename."

def get_distutils_extension(modname, pyxfilename):
#    try:
#        import hashlib
#    except ImportError:
#        import md5 as hashlib
#    extra = "_" + hashlib.md5(open(pyxfilename).read()).hexdigest()
#    modname = modname + extra
    extension_mod,setup_args = handle_special_build(modname, pyxfilename)
    if not extension_mod:
        from distutils.extension import Extension
        extension_mod = Extension(name = modname, sources=[pyxfilename])
    return extension_mod,setup_args

def handle_special_build(modname, pyxfilename):
    special_build = os.path.splitext(pyxfilename)[0] + PYXBLD_EXT
    ext = None
    setup_args={}
    if os.path.exists(special_build):
        # globls = {}
        # locs = {}
        # execfile(special_build, globls, locs)
        # ext = locs["make_ext"](modname, pyxfilename)
        mod = imp.load_source("XXXX", special_build, open(special_build))
        make_ext = getattr(mod,'make_ext',None)
        if make_ext:
            ext = make_ext(modname, pyxfilename)
            assert ext and ext.sources, ("make_ext in %s did not return Extension"
                                         % special_build)
        make_setup_args = getattr(mod,'make_setup_args',None)
        if make_setup_args:
            setup_args = make_setup_args()
            assert isinstance(setup_args,dict), ("make_setup_args in %s did not return a dict"
                                         % special_build)
        assert set or setup_args, ("neither make_ext nor make_setup_args %s"
                                         % special_build)
        ext.sources = [os.path.join(os.path.dirname(special_build), source)
                       for source in ext.sources]
    return ext, setup_args

def handle_dependencies(pyxfilename):
    testing = '_test_files' in globals()
    dependfile = os.path.splitext(pyxfilename)[0] + PYXDEP_EXT

    # by default let distutils decide whether to rebuild on its own
    # (it has a better idea of what the output file will be)

    # but we know more about dependencies so force a rebuild if
    # some of the dependencies are newer than the pyxfile.
    if os.path.exists(dependfile):
        depends = open(dependfile).readlines()
        depends = [depend.strip() for depend in depends]

        # gather dependencies in the "files" variable
        # the dependency file is itself a dependency
        files = [dependfile]
        for depend in depends:
            fullpath = os.path.join(os.path.dirname(dependfile),
                                    depend)
            files.extend(glob.glob(fullpath))

        # only for unit testing to see we did the right thing
        if testing:
            _test_files[:] = []  #$pycheck_no

        # if any file that the pyxfile depends upon is newer than
        # the pyx file, 'touch' the pyx file so that distutils will
        # be tricked into rebuilding it.
        for file in files:
            from distutils.dep_util import newer
            if newer(file, pyxfilename):
                print("Rebuilding because of ", file)
                filetime = os.path.getmtime(file)
                os.utime(pyxfilename, (filetime, filetime))
                if testing:
                    _test_files.append(file)

def build_module(name, pyxfilename, pyxbuild_dir=None):
    assert os.path.exists(pyxfilename), (
        "Path does not exist: %s" % pyxfilename)
    handle_dependencies(pyxfilename)

    extension_mod,setup_args = get_distutils_extension(name, pyxfilename)
    build_in_temp=pyxargs.build_in_temp
    sargs=pyxargs.setup_args.copy()
    sargs.update(setup_args)
    build_in_temp=sargs.pop('build_in_temp',build_in_temp)

    import pyxbuild
    so_path = pyxbuild.pyx_to_dll(pyxfilename, extension_mod,
                                  build_in_temp=build_in_temp,
                                  pyxbuild_dir=pyxbuild_dir,
                                  setup_args=sargs,
                                  reload_support=pyxargs.reload_support)
    assert os.path.exists(so_path), "Cannot find: %s" % so_path

    junkpath = os.path.join(os.path.dirname(so_path), name+"_*") #very dangerous with --inplace ?
    junkstuff = glob.glob(junkpath)
    for path in junkstuff:
        if path!=so_path:
            try:
                os.remove(path)
            except IOError:
                print("Couldn't remove ", path)

    return so_path

def load_module(name, pyxfilename, pyxbuild_dir=None):
    try:
        so_path = build_module(name, pyxfilename, pyxbuild_dir)
        mod = imp.load_dynamic(name, so_path)
        assert mod.__file__ == so_path, (mod.__file__, so_path)
    except Exception, e:
        import traceback
        raise ImportError("Building module failed: %s" %
                          traceback.format_exception_only(*sys.exc_info()[:2])),None,sys.exc_info()[2]
    return mod

# import hooks

class PyxImporter(object):
    """A meta-path importer for .pyx files.
    """
    def __init__(self, extension=PYX_EXT, pyxbuild_dir=None):
        self.extension = extension
        self.pyxbuild_dir = pyxbuild_dir

    def find_module(self, fullname, package_path=None):
        if fullname in sys.modules  and  not pyxargs.reload_support:
            return None  # only here when reload()
        try:
            fp, pathname, (ext,mode,ty) = imp.find_module(fullname,package_path)
            if fp: fp.close()  # Python should offer a Default-Loader to avoid this double find/open!
            if pathname.endswith(self.extension):
                return PyxLoader(fullname, pathname,
                                 pyxbuild_dir=self.pyxbuild_dir)
            if ty != imp.C_EXTENSION: # only when an extension, check if we have a .pyx next!
                return None

            # find .pyx fast, when .so/.pyd exist --inplace
            pyxpath = os.path.splitext(pathname)[0]+self.extension
            if os.path.isfile(pyxpath):
                return PyxLoader(fullname, pyxpath,
                                 pyxbuild_dir=self.pyxbuild_dir)

            # .so/.pyd's on PATH should not be remote from .pyx's
            # think no need to implement PyxArgs.importer_search_remote here?

        except ImportError:
            pass

        # searching sys.path ...

        #if DEBUG_IMPORT:  print "SEARCHING", fullname, package_path
        if '.' in fullname: # only when package_path anyway?
            mod_parts = fullname.split('.')
            module_name = mod_parts[-1]
        else:
            module_name = fullname
        pyx_module_name = module_name + self.extension
        # this may work, but it returns the file content, not its path
        #import pkgutil
        #pyx_source = pkgutil.get_data(package, pyx_module_name)

        if package_path:
            paths = package_path
        else:
            paths = sys.path
        join_path = os.path.join
        is_file = os.path.isfile
        #is_dir = os.path.isdir
        sep = os.path.sep
        for path in paths:
            if not path:
                path = os.getcwd()
            if is_file(path+sep+pyx_module_name):
                return PyxLoader(fullname, join_path(path, pyx_module_name),
                                 pyxbuild_dir=self.pyxbuild_dir)

        # not found, normal package, not a .pyx file, none of our business
        return None

class PyImporter(PyxImporter):
    """A meta-path importer for normal .py files.
    """
    def __init__(self, pyxbuild_dir=None):
        self.super = super(PyImporter, self)
        self.super.__init__(extension='.py', pyxbuild_dir=pyxbuild_dir)
        self.uncompilable_modules = {}
        self.blocked_modules = ['Cython', 'distutils.extension']

    def find_module(self, fullname, package_path=None):
        if fullname in sys.modules:
            return None
        if fullname.startswith('Cython.'):
            return None
        if fullname in self.blocked_modules:
            # prevent infinite recursion
            return None
        if DEBUG_IMPORT:
            print("trying import of module '%s'" % fullname)
        if fullname in self.uncompilable_modules:
            path, last_modified = self.uncompilable_modules[fullname]
            try:
                new_last_modified = os.stat(path).st_mtime
                if new_last_modified > last_modified:
                    # import would fail again
                    return None
            except OSError:
                # module is no longer where we found it, retry the import
                pass

        self.blocked_modules.append(fullname)
        try:
            importer = self.super.find_module(fullname, package_path)
            if importer is not None:
                try:
                    if importer.init_path:
                        path = importer.init_path
                    else:
                        path = importer.path
                    if DEBUG_IMPORT:
                        print("importer found path %s" % path)
                    build_module(fullname, path,
                                 pyxbuild_dir=self.pyxbuild_dir)
                except Exception, e:
                    if DEBUG_IMPORT:
                        import traceback
                        traceback.print_exc()
                    # build failed, not a compilable Python module
                    try:
                        last_modified = os.stat(path).st_mtime
                    except OSError:
                        last_modified = 0
                    self.uncompilable_modules[fullname] = (path, last_modified)
                    importer = None
        finally:
            self.blocked_modules.pop()
        return importer

class PyxLoader(object):
    def __init__(self, fullname, path, init_path=None, pyxbuild_dir=None):
        self.fullname = fullname
        self.path, self.init_path = path, init_path
        self.pyxbuild_dir = pyxbuild_dir

    def load_module(self, fullname):
        assert self.fullname == fullname, (
            "invalid module, expected %s, got %s" % (
            self.fullname, fullname))
        if self.init_path:
            # package
            #print "PACKAGE", fullname
            module = load_module(fullname, self.init_path,
                                 self.pyxbuild_dir)
            module.__path__ = [self.path]
        else:
            #print "MODULE", fullname
            module = load_module(fullname, self.path,
                                 self.pyxbuild_dir)
        return module

#install args
class PyxArgs(object):
    build_dir=True
    build_in_temp=True
    setup_args={}   #None

##pyxargs=None

def install(pyximport=True, pyimport=False, build_dir=None, build_in_temp=True,
            setup_args={}, reload_support=False ):
    """Main entry point. Call this to install the .pyx import hook in
    your meta-path for a single Python process.  If you want it to be
    installed whenever you use Python, add it to your sitecustomize
    (as described above).

    You can pass ``pyimport=True`` to also install the .py import hook
    in your meta-path.  Note, however, that it is highly experimental,
    will not work for most .py files, and will therefore only slow
    down your imports.  Use at your own risk.

    By default, compiled modules will end up in a ``.pyxbld``
    directory in the user's home directory.  Passing a different path
    as ``build_dir`` will override this.

    ``build_in_temp=False`` will produce the C files locally. Working
    with complex dependencies and debugging becomes more easy. This
    can principally interfere with existing files of the same name.
    build_in_temp can be overriden by <modulename>.pyxbld/make_setup_args()
    by a dict item of 'build_in_temp'

    ``setup_args``: dict of arguments for Distribution - see
    distutils.core.setup() . They are extended/overriden by those of
    <modulename>.pyxbld/make_setup_args()

    ``reload_support``:  Enables support for dynamic
    reload(<pyxmodulename>), e.g. after a change in the Cython code.
    Additional files <so_path>.reloadNN may arise on that account, when
    the previously loaded module file cannot be overwritten.
    """
    if not build_dir:
        build_dir = os.path.expanduser('~/.pyxbld')

    global pyxargs
    pyxargs = PyxArgs()  #$pycheck_no
    pyxargs.build_dir = build_dir
    pyxargs.build_in_temp = build_in_temp
    pyxargs.setup_args = (setup_args or {}).copy()
    pyxargs.reload_support = reload_support

    has_py_importer = False
    has_pyx_importer = False
    for importer in sys.meta_path:
        if isinstance(importer, PyxImporter):
            if isinstance(importer, PyImporter):
                has_py_importer = True
            else:
                has_pyx_importer = True

    if pyimport and not has_py_importer:
        importer = PyImporter(pyxbuild_dir=build_dir)
        sys.meta_path.insert(0, importer)

    if pyximport and not has_pyx_importer:
        importer = PyxImporter(pyxbuild_dir=build_dir)
        sys.meta_path.append(importer)

# MAIN

def show_docs():
    import __main__
    __main__.__name__ = mod_name
    for name in dir(__main__):
        item = getattr(__main__, name)
        try:
            setattr(item, "__module__", mod_name)
        except (AttributeError, TypeError):
            pass
    help(__main__)

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


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

"""
Expansion of Python's `pathlib`.
"""

import os
import pathlib

class Path(pathlib.Path):

	__slots__ = ()

	def __eq__(self, rhs):
		"""
		Will now allow comparing to `str`s.
		"""
		if isinstance(rhs, str):
			rhs = Path(rhs)
		return super().__eq__(rhs)

	def is_subdir(self, *others):
		"""
		Determines if this `Path` is in the given path.  For example:
			>>> Path("/usr/bin/python3").is_subdir("/usr")
			True
			>>> Path("/usr/bin/python3").is_subdir("/usr/bin")
			True
			>>> Path("/usr/bin/python3").is_subdir("/usr/bin/python3")
			False
			>>> Path("/usr/bin").is_subdir("/usr/bin/python3")
			False
		"""
		try:
			p = super().relative_to(*others)
		except ValueError:
			return False
		return p != "."

	def is_supdir(self, *others):
		"""
		Determines if the given path is within this `Path`.  For example:
			>>> Path("/usr").is_superdir("/usr/bin/python3")
			True
			>>> Path("/usr/bin").is_superdir("/usr/bin/python3")
			True
			>>> Path("/usr/bin/python3").is_superdir("/usr/bin/python3")
			False
			>>> Path("/usr/bin/python3").is_superdir("/usr/bin")
			False
		"""
		return Path(*others).is_subdir(self)

	def __len__(self):
		"""Returns the `int` number of parts in the path."""
		return len(self.parts)

	def __new__(cls, *args, **kargs):
		#...because the dev forgot to support subclasses.
		cls = WindowsPath if os.name == 'nt' else PosixPath
		return pathlib.Path.__new__(cls, *args, **kargs)

	def relative_to(self, *others):
		"""
		Customized form that, rather than throwing a ValueError if the given
		path is not a parent directory, will simply return the relative form,
		including ".." elements if necessary and an absolute path if no relative
		path is available.
		"""
		#Move this behavior closer to `os.path.relpath`.
		try:
			return super().relative_to(*others)
		except ValueError:
			p = Path(*others)
			return Path(os.path.relpath(str(self), str(p)))

class PosixPath(Path, pathlib.PosixPath):
	__slots__ = ()

class WindowsPath(Path, pathlib.WindowsPath):
	__slots__ = ()
<commit_msg>Code style adjustment.<commit_after>#! /usr/bin/env python3.7

"""
Expansion of Python's `pathlib`.
"""

import os
import pathlib

class Path(pathlib.Path):

	__slots__ = ()

	def __eq__(self, rhs):
		"""
		Will now allow comparing to `str`s.
		"""
		if isinstance(rhs, str):
			rhs = Path(rhs)
		return super().__eq__(rhs)

	def is_subdir(self, *others):
		"""
		Determines if this `Path` is in the given path.  For example:
			>>> Path("/usr/bin/python3").is_subdir("/usr")
			True
			>>> Path("/usr/bin/python3").is_subdir("/usr/bin")
			True
			>>> Path("/usr/bin/python3").is_subdir("/usr/bin/python3")
			False
			>>> Path("/usr/bin").is_subdir("/usr/bin/python3")
			False
		"""
		try:
			p = super().relative_to(*others)
		except ValueError:
			return False
		return p != "."

	def is_supdir(self, *others):
		"""
		Determines if the given path is within this `Path`.  For example:
			>>> Path("/usr").is_superdir("/usr/bin/python3")
			True
			>>> Path("/usr/bin").is_superdir("/usr/bin/python3")
			True
			>>> Path("/usr/bin/python3").is_superdir("/usr/bin/python3")
			False
			>>> Path("/usr/bin/python3").is_superdir("/usr/bin")
			False
		"""
		return Path(*others).is_subdir(self)

	def __len__(self):
		"""Returns the `int` number of parts in the path."""
		return len(self.parts)

	def __new__(cls, *args, **kargs):
		#...because the dev forgot to support subclasses.
		cls = WindowsPath if os.name == 'nt' else PosixPath
		return pathlib.Path.__new__(cls, *args, **kargs)

	def relative_to(self, *others):
		"""
		Customized form that, rather than throwing a ValueError if the given
		path is not a parent directory, will simply return the relative form,
		including ".." elements if necessary and an absolute path if no relative
		path is available.
		"""
		#Move this behavior closer to `os.path.relpath`.
		try:
			return super().relative_to(*others)
		except ValueError:
			p = Path(*others)
			return Path(os.path.relpath(str(self), str(p)))

class PosixPath(Path, pathlib.PosixPath):
	__slots__ = ()

class WindowsPath(Path, pathlib.WindowsPath):
	__slots__ = ()
<|endoftext|>