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

import datetime
import jargparse
from intermine.webservice import Service
from lxml import etree

# MAIN
parser = jargparse.ArgParser('Generate a sitemap for an InterMine installation.')
parser.add_argument(
    'mineUrl', help="InterMine URL.  For example, http://www.synbiomine.org/synbiomine")
args = parser.parse_args()

service = Service(args.mineUrl + '/service')

# Get a new query on the class (table) you will be querying:
query = service.new_query("Gene")

# The view specifies the output columns
query.add_view("primaryIdentifier")

# Uncomment and edit the line below (the default) to select a custom sort order:
# query.add_sort_order("Pathway.primaryIdentifier", "ASC")

# You can edit the constraint values below
# query.add_constraint("primaryIdentifier", "IS NOT NULL", code = "A")
query.add_constraint("primaryIdentifier", "IS NOT NULL", code="A")
# query.add_constraint("organism.shortName", "=", "H. sapiens", code = "B")

# Uncomment and edit the code below to specify your own custom logic:
# query.set_logic("A")

sitemapCount = 0

prefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
prefix += "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n"
prefix += "  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
prefix += "  xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9" \
    + " http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n"

postfix = "</urlset>"

rowCount = 0

f = open('sitemap' + str(sitemapCount) + '.xml', 'w')

f.write(prefix)

for row in query.rows():
    f.write(
        '<url><loc>'
        + args.mineUrl + '/portal.do?class=Gene&externalids=' + row["primaryIdentifier"]
        + "</loc></url>\n")

    rowCount = rowCount + 1

    if rowCount >= 50000:
        f.write(postfix)
        f.close()
        sitemapCount = sitemapCount + 1
        f = open('sitemap' + str(sitemapCount) + '.xml', 'w')
        f.write(prefix)
        rowCount = 1

f.write(postfix)
f.close()

dateString = datetime.datetime.now().strftime('%Y-%m-%d')

# Write main sitemap file
nsMap = {None: 'http://www.sitemaps.org/schemas/sitemap/0.9', 'xsi': 'http://www.w3.org/1999/xlink'}
rootElem = etree.Element('urlset', nsmap=nsMap)
rootElem.attrib['{http://www.w3.org/1999/xlink}schemaLocation'] \
    = 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'

for i in range(0, sitemapCount + 1):
    sitemapElem = etree.SubElement(rootElem, 'sitemap')
    locElem = etree.SubElement(sitemapElem, 'loc')
    locElem.text = '%s/sitemap%d.xml' % (args.mineUrl, i)
    lastmodElem = etree.SubElement(sitemapElem, 'lastmod')
    lastmodElem.text = dateString

print(etree.tostring(rootElem, pretty_print=True))

etree.ElementTree(rootElem).write('sitemap.xml', pretty_print=True, xml_declaration=True, encoding='utf-8')
<commit_msg>Fix sitemap index generation - I was generating <urlset> again instead of <sitemapindex>!<commit_after>#!/usr/bin/env python3

import datetime
import jargparse
from intermine.webservice import Service
from lxml import etree

# MAIN
parser = jargparse.ArgParser('Generate a sitemap for an InterMine installation.')
parser.add_argument(
    'mineUrl', help="InterMine URL.  For example, http://www.synbiomine.org/synbiomine")
args = parser.parse_args()

service = Service(args.mineUrl + '/service')

# Get a new query on the class (table) you will be querying:
query = service.new_query("Gene")

# The view specifies the output columns
query.add_view("primaryIdentifier")

# Uncomment and edit the line below (the default) to select a custom sort order:
# query.add_sort_order("Pathway.primaryIdentifier", "ASC")

# You can edit the constraint values below
# query.add_constraint("primaryIdentifier", "IS NOT NULL", code = "A")
query.add_constraint("primaryIdentifier", "IS NOT NULL", code="A")
# query.add_constraint("organism.shortName", "=", "H. sapiens", code = "B")

# Uncomment and edit the code below to specify your own custom logic:
# query.set_logic("A")

sitemapCount = 0

prefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
prefix += "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n"
prefix += "  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
prefix += "  xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9" \
    + " http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n"

postfix = "</urlset>"

rowCount = 0

f = open('sitemap' + str(sitemapCount) + '.xml', 'w')

f.write(prefix)

for row in query.rows():
    f.write(
        '<url><loc>'
        + args.mineUrl + '/portal.do?class=Gene&externalids=' + row["primaryIdentifier"]
        + "</loc></url>\n")

    rowCount = rowCount + 1

    if rowCount >= 50000:
        f.write(postfix)
        f.close()
        sitemapCount = sitemapCount + 1
        f = open('sitemap' + str(sitemapCount) + '.xml', 'w')
        f.write(prefix)
        rowCount = 1

f.write(postfix)
f.close()

dateString = datetime.datetime.now().strftime('%Y-%m-%d')

# Write main sitemap index file
nsMap = {None: 'http://www.sitemaps.org/schemas/sitemap/0.9'}
rootElem = etree.Element('sitemapindex', nsmap=nsMap)

for i in range(0, sitemapCount + 1):
    sitemapElem = etree.SubElement(rootElem, 'sitemap')
    locElem = etree.SubElement(sitemapElem, 'loc')
    locElem.text = '%s/sitemap%d.xml' % (args.mineUrl, i)
    lastmodElem = etree.SubElement(sitemapElem, 'lastmod')
    lastmodElem.text = dateString

# Sitemap writing code which we'll use to replace hand-printed at some point
"""
nsMap = {None: 'http://www.sitemaps.org/schemas/sitemap/0.9', 'xsi': 'http://www.w3.org/1999/xlink'}
rootElem = etree.Element('urlset', nsmap=nsMap)
rootElem.attrib['{http://www.w3.org/1999/xlink}schemaLocation'] \
    = 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'

for i in range(0, sitemapCount + 1):
    sitemapElem = etree.SubElement(rootElem, 'sitemap')
    locElem = etree.SubElement(sitemapElem, 'loc')
    locElem.text = '%s/sitemap%d.xml' % (args.mineUrl, i)
    lastmodElem = etree.SubElement(sitemapElem, 'lastmod')
    lastmodElem.text = dateString
"""

# print(etree.tostring(rootElem, pretty_print=True))

etree.ElementTree(rootElem).write('sitemap.xml', pretty_print=True, xml_declaration=True, encoding='utf-8')
<|endoftext|>


<commit_before># Sendfile "streaming" backend
# This is based on sendfiles builtin "simple" backend but uses a StreamingHttpResponse

from __future__ import absolute_import, unicode_literals

import os
import re
import stat
from wsgiref.util import FileWrapper

from django.http import HttpResponseNotModified, StreamingHttpResponse
from django.utils.http import http_date

try:
    from email.utils import parsedate_tz, mktime_tz
except ImportError:
    from email.Utils import parsedate_tz, mktime_tz

def sendfile(request, filename, **kwargs):
    # Respect the If-Modified-Since header.
    statobj = os.stat(filename)

    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
        return HttpResponseNotModified()

    response = StreamingHttpResponse(FileWrapper(open(filename, 'rb')))

    response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
    return response

def was_modified_since(header=None, mtime=0, size=0):
    """
    Was something modified since the user last downloaded it?

    header
      This is the value of the If-Modified-Since header.  If this is None,
      I'll just return True.

    mtime
      This is the modification time of the item we're talking about.

    size
      This is the size of the item we're talking about.
    """
    try:
        if header is None:
            raise ValueError
        matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
                           re.IGNORECASE)
        header_date = parsedate_tz(matches.group(1))
        if header_date is None:
            raise ValueError
        header_mtime = mktime_tz(header_date)
        header_len = matches.group(3)
        if header_len and int(header_len) != size:
            raise ValueError
        if mtime > header_mtime:
            raise ValueError
    except (AttributeError, ValueError, OverflowError):
        return True
    return False
<commit_msg>Removed Python 2.6 email.utils import fallback<commit_after># Sendfile "streaming" backend
# This is based on sendfiles builtin "simple" backend but uses a StreamingHttpResponse

from __future__ import absolute_import, unicode_literals

import os
import re
import stat
from email.utils import mktime_tz, parsedate_tz
from wsgiref.util import FileWrapper

from django.http import HttpResponseNotModified, StreamingHttpResponse
from django.utils.http import http_date

def sendfile(request, filename, **kwargs):
    # Respect the If-Modified-Since header.
    statobj = os.stat(filename)

    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
        return HttpResponseNotModified()

    response = StreamingHttpResponse(FileWrapper(open(filename, 'rb')))

    response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
    return response

def was_modified_since(header=None, mtime=0, size=0):
    """
    Was something modified since the user last downloaded it?

    header
      This is the value of the If-Modified-Since header.  If this is None,
      I'll just return True.

    mtime
      This is the modification time of the item we're talking about.

    size
      This is the size of the item we're talking about.
    """
    try:
        if header is None:
            raise ValueError
        matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
                           re.IGNORECASE)
        header_date = parsedate_tz(matches.group(1))
        if header_date is None:
            raise ValueError
        header_mtime = mktime_tz(header_date)
        header_len = matches.group(3)
        if header_len and int(header_len) != size:
            raise ValueError
        if mtime > header_mtime:
            raise ValueError
    except (AttributeError, ValueError, OverflowError):
        return True
    return False
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
    'name':     'Argentina - Nombre y títulos de personas físicas o no.',
    'version':  '2.1',
    'author':   'OpenERP - Team de Localización Argentina',
    'category': 'Localization/Argentina',
    'website':  'https://launchpad.net/~openerp-l10n-ar-localization',
    'license':  'AGPL-3',
    'description': """
Módulo de nombres y títulos para personas físicas y no físicas.

Incluye:

 - Denominación de clientes, proveedores y contactos.

""",
    'depends': [
        'base',
    ],
    'init_xml': [],
    'demo_xml': [],
    'update_xml': [
        'data/res_partner_title.xml',
    ],
    'active': False,
    'installable': True,
}
<commit_msg>[VERSION] 2.7.155<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
    'name':     'Argentina - Nombre y títulos de personas físicas o no.',
    'version':  '2.7.155',
    'author':   'OpenERP - Team de Localización Argentina',
    'category': 'Localization/Argentina',
    'website':  'https://launchpad.net/~openerp-l10n-ar-localization',
    'license':  'AGPL-3',
    'description': """
Módulo de nombres y títulos para personas físicas y no físicas.

Incluye:

 - Denominación de clientes, proveedores y contactos.

""",
    'depends': [
        'base',
    ],
    'init_xml': [],
    'demo_xml': [],
    'update_xml': [
        'data/res_partner_title.xml',
    ],
    'active': False,
    'installable': True,
}
<|endoftext|>


<commit_before>#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4

from rapidsms.webui.utils import render_to_response
from django.http import HttpResponse
from django.template.loader import render_to_string
from xformmanager.models import Case
from datetime import datetime, date, timedelta

'''Define custom reports in this file.  The rules are one module per
   domain and the module name must match _lowercase_ the domain name.
   Each function in the module will then be listed as a custom report
   that should return html formatted text that will be displayed
   as the report. The doc string of the method is what will be
   displayed in the UI (self documentation!).'''
   # This is still a bit of a work in progress.

def monitoring(request):
    '''Safe Pregnancy Monitoring Report'''
    context = { }
    # use the cases we've put together for this
    safe_preg_case_name = "MVP Safe Pregnancies"
    try:
        case = Case.objects.get(name=safe_preg_case_name)
    except Case.DoesNotExist:
        return '''Sorry, it doesn't look like the forms that this report
                  depends on have been uploaded.'''

    data_maps = case.get_all_data_maps()

    # allow a list of usernames whose submissions don't show up
    # in the report.
    blacklist = ["teddy", "admin", "demo_user"]
    blacklist_columns = ["meta_username_1","meta_username_2",
                         "meta_username_3","meta_username_4",
                         "meta_username_5"]

    all_moms = []
    healthy_moms = []
    very_pregnant_moms = []
    moms_needing_followup = []
    moms_with_open_referrals = []
    for id, map in data_maps.items():
        # check blacklist
        if _is_blacklisted(map, blacklist, blacklist_columns):
            continue
        mom = Mother(id, map)
        if not mom.chw:
            # don't include submissions from non-users
            continue
        all_moms.append(mom)
        prev_list_size = len(moms_needing_followup) +\
                         len(very_pregnant_moms) +\
                         len(moms_with_open_referrals)
        if mom.needs_followup:
            moms_needing_followup.append(mom)
        if mom.months_pregnant >= 7:
            very_pregnant_moms.append(mom)
        if mom.has_open_referral:
            moms_with_open_referrals.append(mom)
        new_list_size = len(moms_needing_followup) +\
                        len(very_pregnant_moms) +\
                        len(moms_with_open_referrals)
        if new_list_size == prev_list_size:
            # we didn't add her to any lists so put her in
            # healthy moms
            healthy_moms.append(mom)

    context["all_moms"] = all_moms
    context["healthy_moms"] = healthy_moms
    context["open_referrals"] = moms_with_open_referrals
    context["very_pregnant"] = very_pregnant_moms
    context["need_followup"] = moms_needing_followup
    context["empty_data_holder"] = "???"
    return render_to_string("reports/mvp/monitoring.html", context)

def _is_blacklisted(data, blacklist, blacklist_columns):
    '''Checks a set of columns and values, and if any of the
       columns contains one of the values, returns true'''
    for column in blacklist_columns:
        if data[column] in blacklist:
            return True
    return False

class Mother(object):

    def __init__(self, id, data_map):
        self.id = id
        self.data_map = data_map
        # calculate some properties and set them for easy access
        # these are totally hard coded to the forms.
        # most of these depend on registration and will not display
        # very well if there is no registration

        # czue - i don't like that the sequence ids are hard-coded, but using the form
        # ids would just be way too long.  we could key these again by form, but
        # leaving that as an open-ended possibility.  a triple dictionary might
        # be a bit too much to deal with.

        # check against the old registration form
        reg_seq = "1"
        if not data_map["meta_timestart_1"] and data_map["meta_timestart_5"]:
            # we found an old reg and no new reg
            reg_seq = "5"

        self.mother_name = data_map["sampledata_mother_name_%s" % reg_seq]
        chw_cols = ["meta_username_1","meta_username_2","meta_username_3",
                    "meta_username_4", "meta_username_5"]

        self.chw = None
        for item in chw_cols:
            self.chw = data_map[item]
            if self.chw:
                break

        self.date_of_reg = data_map["meta_timestart_%s" % reg_seq]
        self.months_preg_at_reg = data_map["sampledata_months_pregnant_%s" % reg_seq]
        if self.date_of_reg and self.months_preg_at_reg:
            days_pregnant_at_reg = self.months_preg_at_reg * 30
            self.months_pregnant = ((datetime.now() - self.date_of_reg) +
                                    timedelta(days=days_pregnant_at_reg)).days / 30
        else:
            self.months_pregnant = None

        # Women Needing Followup
        # > 1 month since last Followup if 1-6 Months,
        # > 15 days since last Followup if 7-10 Months
        self.date_of_last_followup = data_map["meta_timestart_2"]
        if self.date_of_last_followup:
            self.days_since_followup = (datetime.now() - self.date_of_last_followup).days
        # this is yucky but we don't want to include folks with no followups
        # and no new reg, since we're not checkign the old followups
        elif self.date_of_reg and reg_seq == "1":
            self.days_since_followup = (datetime.now() - self.date_of_reg).days
        else:
            # no reg or follow-ups.  leave them out for now
            self.days_since_followup = None
            self.needs_followup = False
        if self.days_since_followup is not None:
            if self.days_since_followup > 30:
                self.needs_followup = True
            elif self.days_since_followup > 15 and\
                 self.months_pregnant and self.months_pregnant >= 7:
                self.needs_followup = True
            else:
                self.needs_followup = False

        # high risk factors
        hi_risk_cols = ["sampledata_hi_risk_info_old_%s" % reg_seq,
                        "sampledata_hi_risk_info_young_%s" % reg_seq,
                        "sampledata_hi_risk_info_education_%s" % reg_seq,
                        "sampledata_hi_risk_info_small_%s" % reg_seq,
                        "sampledata_hi_risk_info_10_years_%s" % reg_seq,
                        "sampledata_hi_risk_info_complications_%s" % reg_seq,
                        "sampledata_hi_risk_info_many_%s" % reg_seq,
                        "sampledata_hi_risk_info_health_%s" % reg_seq,
                        "sampledata_hi_risk_info_hiv_%s" % reg_seq,
                        "sampledata_hi_risk_info_syphilis_%s" % reg_seq]
        hi_risk_values = []
        for col in hi_risk_cols:
            if data_map[col]:
                risk_factor = self._clean(col, "sampledata_hi_risk_info_", "_%s" % reg_seq)
                hi_risk_values.append(risk_factor)
        self.high_risk_factors = ",".join(hi_risk_values)

        # referral
        self.date_referred = datetime.min
        self.most_recent_referral_id = None
        self.has_referral = False
        if data_map["safe_pregnancy_referred_2"] and\
           data_map["safe_pregnancy_referred_2"] == "yes":
            self.has_referral = True
            self.date_referred = self.date_of_last_followup
            self.most_recent_referral_id = data_map["safe_pregnancy_referral_id_2"]
        if data_map["safe_pregnancy_referred_3"] and\
           data_map["safe_pregnancy_referred_3"] == "yes":
            self.has_referral = True
            self.date_of_closure = data_map["meta_timestart_3"]
            self.date_referred = max([self.date_referred,
                                      self.date_of_closure])
            if self.date_of_closure == self.date_referred:
                self.most_recent_referral_id = data_map["safe_pregnancy_referral_id_2"]

        if data_map["meta_timestart_4"]:
            # we found a referral
            self.date_of_referral = data_map["meta_timestart_4"]
            if data_map["safe_pregnancy_why_not_4"] == "feeling_better" or\
               data_map["safe_pregnancy_treatment_4"] == "yes":
                # the referral is open no matter what if the referral
                # is present but not completed
                self.has_open_referral = True
            elif self.date_of_referral > self.date_referred:
                # they completed it.
                self.has_open_referral = False
            else:
                # they closed a referral but have a more recent one
                # that's still open
                self.has_open_referral = True
        else:
            # no information about a referral.  if there was one it's open
            self.has_open_referral = self.has_referral

        # danger signs
        # Followup form is referred:
        # if(/safe_pregnancy/feeling='not_well'
        # or /safe_pregnancy/pain_from_vagina='yes'
        # or /safe_pregnancy/headache_or_b_vision='yes'
        # or /safe_pregnancy/dark_urine='yes'
        # or /safe_pregnancy/swelling='yes'
        # or /safe_pregnancy/unusual_pain='yes'
        # or /safe_pregnancy/burn_urinate='yes'
        # or /safe_pregnancy/baby_not_moving='yes'
        # or /safe_pregnancy/fever='yes'
        # or /safe_pregnancy/other_illness='yes')
        followup_warnings = {"safe_pregnancy_feeling_2" : "not_well",
                             "safe_pregnancy_pain_from_vagina_2": "yes",
                             "safe_pregnancy_headache_or_b_vision_2": "yes",
                             "safe_pregnancy_dark_urine_2": "yes",
                             "safe_pregnancy_swelling_2": "yes",
                             "safe_pregnancy_unusual_pain_2": "yes",
                             "safe_pregnancy_burn_urinate_2": "yes",
                             "safe_pregnancy_baby_not_moving_2": "yes",
                             "safe_pregnancy_fever_2": "yes",
                             "safe_pregnancy_other_illness_2" : "yes"}

        danger_signs = []
        for key, value in followup_warnings.items():
             if data_map[key] == value:
                 danger_signs.append("%s: %s" % (self._clean(key, "safe_pregnancy_", "_2"),
                                                 self._clean(value, "", "")))

        # Close form is referred:
        # if(/safe_pregnancy/mother_survived='yes' and
        # (( /safe_pregnancy/why_not='skeptical_clinic'
        #    or /safe_pregnancy/why_not='busy'
        #    or /safe_pregnancy/why_not='transport'
        #    or /safe_pregnancy/why_not='other')
        #    or (/safe_pregnancy/treatment_why_not='no_medicine'
        #    or /safe_pregnancy/treatment_why_not='too_many_patients'
        #    or /safe_pregnancy/treatment_why_not='no_doctor'
        #    or /safe_pregnancy/treatment_why_not='no_health_workers'
        #    or /safe_pregnancy/treatment_why_not='other')))

        if data_map["safe_pregnancy_mother_survived_3"] == "yes":
            closure_warnings = {
                                "safe_pregnancy_why_not_3" : 'skeptical_clinic',
                                "safe_pregnancy_why_not_3" : 'busy',
                                "safe_pregnancy_why_not_3" : 'transport',
                                "safe_pregnancy_why_not_3" : 'other',
                                "safe_pregnancy_treatment_why_not_3" : 'no_medicine',
                                "safe_pregnancy_treatment_why_not_3" : 'too_many_patients',
                                "safe_pregnancy_treatment_why_not_3" : 'no_doctor',
                                "safe_pregnancy_treatment_why_not_3" : 'no_health_workers',
                                "safe_pregnancy_treatment_why_not_3" : 'other'
                                }
            for key, value in closure_warnings.items():
                 if data_map[key] == value:
                     danger_signs.append("%s: %s" % (self._clean(key, "safe_pregnancy_", "_3"),
                                                     self._clean(value, "", "")))

        self.danger_signs = ", ".join(danger_signs)

        # checklist
        checklist_items = ["safe_pregnancy_preg_actions_iron_folic_2",
                           "safe_pregnancy_preg_actions_start_tt_2",
                           "safe_pregnancy_preg_actions_finish_tt_2",
                           "safe_pregnancy_preg_actions_start_ipt_2",
                           "safe_pregnancy_preg_actions_finish_ipt_2",
                           "safe_pregnancy_preg_actions_deworm_2",
                           "safe_pregnancy_preg_actions_birth_plan_2",
                           "safe_pregnancy_preg_actions_test_hiv_2",
                           "safe_pregnancy_preg_actions_test_syphilis_2",
                           "safe_pregnancy_preg_actions_test_bp_2",
                           "safe_pregnancy_preg_actions_test_hb_2"]

        incomplete_checklist_items = []
        for item in checklist_items:
            if data_map[item] != 1:
                incomplete_checklist_items.append(self._clean(item, "safe_pregnancy_preg_actions_", "_2"))

        self.incomplete_checklist_items = ", ".join(incomplete_checklist_items)

    def _clean(self, column, prefix, suffix):
        '''Cleans a column by removing a prefix and suffix, if they
           are present, and converting underscores to spaces.'''
        if column.startswith(prefix):
            column = column[len(prefix):]
        if column.endswith(suffix):
            column = column[0:len(column) - len(suffix)]
        return column.replace("_", " ")<commit_msg>Fix open referral logic, which was backwards.<commit_after>#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4

from rapidsms.webui.utils import render_to_response
from django.http import HttpResponse
from django.template.loader import render_to_string
from xformmanager.models import Case
from datetime import datetime, date, timedelta

'''Define custom reports in this file.  The rules are one module per
   domain and the module name must match _lowercase_ the domain name.
   Each function in the module will then be listed as a custom report
   that should return html formatted text that will be displayed
   as the report. The doc string of the method is what will be
   displayed in the UI (self documentation!).'''
   # This is still a bit of a work in progress.

def monitoring(request):
    '''Safe Pregnancy Monitoring Report'''
    context = { }
    # use the cases we've put together for this
    safe_preg_case_name = "MVP Safe Pregnancies"
    try:
        case = Case.objects.get(name=safe_preg_case_name)
    except Case.DoesNotExist:
        return '''Sorry, it doesn't look like the forms that this report
                  depends on have been uploaded.'''

    data_maps = case.get_all_data_maps()

    # allow a list of usernames whose submissions don't show up
    # in the report.
    blacklist = ["teddy", "admin", "demo_user"]
    blacklist_columns = ["meta_username_1","meta_username_2",
                         "meta_username_3","meta_username_4",
                         "meta_username_5"]

    all_moms = []
    healthy_moms = []
    very_pregnant_moms = []
    moms_needing_followup = []
    moms_with_open_referrals = []
    for id, map in data_maps.items():
        # check blacklist
        if _is_blacklisted(map, blacklist, blacklist_columns):
            continue
        mom = Mother(id, map)
        if not mom.chw:
            # don't include submissions from non-users
            continue
        all_moms.append(mom)
        prev_list_size = len(moms_needing_followup) +\
                         len(very_pregnant_moms) +\
                         len(moms_with_open_referrals)
        if mom.needs_followup:
            moms_needing_followup.append(mom)
        if mom.months_pregnant >= 7:
            very_pregnant_moms.append(mom)
        if mom.has_open_referral:
            moms_with_open_referrals.append(mom)
        new_list_size = len(moms_needing_followup) +\
                        len(very_pregnant_moms) +\
                        len(moms_with_open_referrals)
        if new_list_size == prev_list_size:
            # we didn't add her to any lists so put her in
            # healthy moms
            healthy_moms.append(mom)

    context["all_moms"] = all_moms
    context["healthy_moms"] = healthy_moms
    context["open_referrals"] = moms_with_open_referrals
    context["very_pregnant"] = very_pregnant_moms
    context["need_followup"] = moms_needing_followup
    context["empty_data_holder"] = "???"
    return render_to_string("reports/mvp/monitoring.html", context)

def _is_blacklisted(data, blacklist, blacklist_columns):
    '''Checks a set of columns and values, and if any of the
       columns contains one of the values, returns true'''
    for column in blacklist_columns:
        if data[column] in blacklist:
            return True
    return False

class Mother(object):

    def __init__(self, id, data_map):
        self.id = id
        self.data_map = data_map
        # calculate some properties and set them for easy access
        # these are totally hard coded to the forms.
        # most of these depend on registration and will not display
        # very well if there is no registration

        # czue - i don't like that the sequence ids are hard-coded, but using the form
        # ids would just be way too long.  we could key these again by form, but
        # leaving that as an open-ended possibility.  a triple dictionary might
        # be a bit too much to deal with.

        # check against the old registration form
        reg_seq = "1"
        if not data_map["meta_timestart_1"] and data_map["meta_timestart_5"]:
            # we found an old reg and no new reg
            reg_seq = "5"

        self.mother_name = data_map["sampledata_mother_name_%s" % reg_seq]
        chw_cols = ["meta_username_1","meta_username_2","meta_username_3",
                    "meta_username_4", "meta_username_5"]

        self.chw = None
        for item in chw_cols:
            self.chw = data_map[item]
            if self.chw:
                break

        self.date_of_reg = data_map["meta_timestart_%s" % reg_seq]
        self.months_preg_at_reg = data_map["sampledata_months_pregnant_%s" % reg_seq]
        if self.date_of_reg and self.months_preg_at_reg:
            days_pregnant_at_reg = self.months_preg_at_reg * 30
            self.months_pregnant = ((datetime.now() - self.date_of_reg) +
                                    timedelta(days=days_pregnant_at_reg)).days / 30
        else:
            self.months_pregnant = None

        # Women Needing Followup
        # > 1 month since last Followup if 1-6 Months,
        # > 15 days since last Followup if 7-10 Months
        self.date_of_last_followup = data_map["meta_timestart_2"]
        if self.date_of_last_followup:
            self.days_since_followup = (datetime.now() - self.date_of_last_followup).days
        # this is yucky but we don't want to include folks with no followups
        # and no new reg, since we're not checkign the old followups
        elif self.date_of_reg and reg_seq == "1":
            self.days_since_followup = (datetime.now() - self.date_of_reg).days
        else:
            # no reg or follow-ups.  leave them out for now
            self.days_since_followup = None
            self.needs_followup = False
        if self.days_since_followup is not None:
            if self.days_since_followup > 30:
                self.needs_followup = True
            elif self.days_since_followup > 15 and\
                 self.months_pregnant and self.months_pregnant >= 7:
                self.needs_followup = True
            else:
                self.needs_followup = False

        # high risk factors
        hi_risk_cols = ["sampledata_hi_risk_info_old_%s" % reg_seq,
                        "sampledata_hi_risk_info_young_%s" % reg_seq,
                        "sampledata_hi_risk_info_education_%s" % reg_seq,
                        "sampledata_hi_risk_info_small_%s" % reg_seq,
                        "sampledata_hi_risk_info_10_years_%s" % reg_seq,
                        "sampledata_hi_risk_info_complications_%s" % reg_seq,
                        "sampledata_hi_risk_info_many_%s" % reg_seq,
                        "sampledata_hi_risk_info_health_%s" % reg_seq,
                        "sampledata_hi_risk_info_hiv_%s" % reg_seq,
                        "sampledata_hi_risk_info_syphilis_%s" % reg_seq]
        hi_risk_values = []
        for col in hi_risk_cols:
            if data_map[col]:
                risk_factor = self._clean(col, "sampledata_hi_risk_info_", "_%s" % reg_seq)
                hi_risk_values.append(risk_factor)
        self.high_risk_factors = ",".join(hi_risk_values)

        # referral
        self.date_referred = datetime.min
        self.most_recent_referral_id = None
        self.has_referral = False
        if data_map["safe_pregnancy_referred_2"] and\
           data_map["safe_pregnancy_referred_2"] == "yes":
            self.has_referral = True
            self.date_referred = self.date_of_last_followup
            self.most_recent_referral_id = data_map["safe_pregnancy_referral_id_2"]
        if data_map["safe_pregnancy_referred_3"] and\
           data_map["safe_pregnancy_referred_3"] == "yes":
            self.has_referral = True
            self.date_of_closure = data_map["meta_timestart_3"]
            self.date_referred = max([self.date_referred,
                                      self.date_of_closure])
            if self.date_of_closure == self.date_referred:
                self.most_recent_referral_id = data_map["safe_pregnancy_referral_id_2"]

        if data_map["meta_timestart_4"]:
            # we found a referral
            self.date_of_referral = data_map["meta_timestart_4"]
            if data_map["safe_pregnancy_why_not_4"] != "feeling_better" and\
               data_map["safe_pregnancy_treatment_4"] != "yes":
                # the referral is open no matter what if the referral
                # is present but not completed
                self.has_open_referral = True
            elif self.date_of_referral > self.date_referred:
                # they completed it.
                self.has_open_referral = False
            else:
                # they closed a referral but have a more recent one
                # that's still open
                self.has_open_referral = True
        else:
            # no information about a referral.  if there was one it's open
            self.has_open_referral = self.has_referral

        # danger signs
        # Followup form is referred:
        # if(/safe_pregnancy/feeling='not_well'
        # or /safe_pregnancy/pain_from_vagina='yes'
        # or /safe_pregnancy/headache_or_b_vision='yes'
        # or /safe_pregnancy/dark_urine='yes'
        # or /safe_pregnancy/swelling='yes'
        # or /safe_pregnancy/unusual_pain='yes'
        # or /safe_pregnancy/burn_urinate='yes'
        # or /safe_pregnancy/baby_not_moving='yes'
        # or /safe_pregnancy/fever='yes'
        # or /safe_pregnancy/other_illness='yes')
        followup_warnings = {"safe_pregnancy_feeling_2" : "not_well",
                             "safe_pregnancy_pain_from_vagina_2": "yes",
                             "safe_pregnancy_headache_or_b_vision_2": "yes",
                             "safe_pregnancy_dark_urine_2": "yes",
                             "safe_pregnancy_swelling_2": "yes",
                             "safe_pregnancy_unusual_pain_2": "yes",
                             "safe_pregnancy_burn_urinate_2": "yes",
                             "safe_pregnancy_baby_not_moving_2": "yes",
                             "safe_pregnancy_fever_2": "yes",
                             "safe_pregnancy_other_illness_2" : "yes"}

        danger_signs = []
        for key, value in followup_warnings.items():
             if data_map[key] == value:
                 danger_signs.append("%s: %s" % (self._clean(key, "safe_pregnancy_", "_2"),
                                                 self._clean(value, "", "")))

        # Close form is referred:
        # if(/safe_pregnancy/mother_survived='yes' and
        # (( /safe_pregnancy/why_not='skeptical_clinic'
        #    or /safe_pregnancy/why_not='busy'
        #    or /safe_pregnancy/why_not='transport'
        #    or /safe_pregnancy/why_not='other')
        #    or (/safe_pregnancy/treatment_why_not='no_medicine'
        #    or /safe_pregnancy/treatment_why_not='too_many_patients'
        #    or /safe_pregnancy/treatment_why_not='no_doctor'
        #    or /safe_pregnancy/treatment_why_not='no_health_workers'
        #    or /safe_pregnancy/treatment_why_not='other')))

        if data_map["safe_pregnancy_mother_survived_3"] == "yes":
            closure_warnings = {
                                "safe_pregnancy_why_not_3" : 'skeptical_clinic',
                                "safe_pregnancy_why_not_3" : 'busy',
                                "safe_pregnancy_why_not_3" : 'transport',
                                "safe_pregnancy_why_not_3" : 'other',
                                "safe_pregnancy_treatment_why_not_3" : 'no_medicine',
                                "safe_pregnancy_treatment_why_not_3" : 'too_many_patients',
                                "safe_pregnancy_treatment_why_not_3" : 'no_doctor',
                                "safe_pregnancy_treatment_why_not_3" : 'no_health_workers',
                                "safe_pregnancy_treatment_why_not_3" : 'other'
                                }
            for key, value in closure_warnings.items():
                 if data_map[key] == value:
                     danger_signs.append("%s: %s" % (self._clean(key, "safe_pregnancy_", "_3"),
                                                     self._clean(value, "", "")))

        self.danger_signs = ", ".join(danger_signs)

        # checklist
        checklist_items = ["safe_pregnancy_preg_actions_iron_folic_2",
                           "safe_pregnancy_preg_actions_start_tt_2",
                           "safe_pregnancy_preg_actions_finish_tt_2",
                           "safe_pregnancy_preg_actions_start_ipt_2",
                           "safe_pregnancy_preg_actions_finish_ipt_2",
                           "safe_pregnancy_preg_actions_deworm_2",
                           "safe_pregnancy_preg_actions_birth_plan_2",
                           "safe_pregnancy_preg_actions_test_hiv_2",
                           "safe_pregnancy_preg_actions_test_syphilis_2",
                           "safe_pregnancy_preg_actions_test_bp_2",
                           "safe_pregnancy_preg_actions_test_hb_2"]

        incomplete_checklist_items = []
        for item in checklist_items:
            if data_map[item] != 1:
                incomplete_checklist_items.append(self._clean(item, "safe_pregnancy_preg_actions_", "_2"))

        self.incomplete_checklist_items = ", ".join(incomplete_checklist_items)

    def _clean(self, column, prefix, suffix):
        '''Cleans a column by removing a prefix and suffix, if they
           are present, and converting underscores to spaces.'''
        if column.startswith(prefix):
            column = column[len(prefix):]
        if column.endswith(suffix):
            column = column[0:len(column) - len(suffix)]
        return column.replace("_", " ")<|endoftext|>


<commit_before>
class BaseVisitor:

    def visit(self, node):
        "method is really overridden by compiler.visitor.ASTVisitor"
        raise NotImplemented

    def visitChildren(self, n):
        for c in n.getChildNodes():
            self.visit(c)

<commit_msg>NotImplemented -> NotImplementedError<commit_after>
class BaseVisitor:

    def visit(self, node):
        "method is really overridden by compiler.visitor.ASTVisitor"
        raise NotImplementedError("Unreachable")

    def visitChildren(self, n):
        for c in n.getChildNodes():
            self.visit(c)

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
    'name':     'Banks of Argentina',
    'version':  '2.1',
    'author':   'OpenERP - Team de Localización Argentina',
    'category': 'Localization/Argentina',
    'website':  'https://launchpad.net/~openerp-l10n-ar-localization',
    'license':  'AGPL-3',
    'description': """\
Part of localization Model for Argentina - Banks of Argentina

--------------------------
(SPANISH)

Listado de entidades financieras habilitadas por el BCRA.

Este módulo le permite tener a disposición el listado actualizado de
las entidades bancarias de la República Argentina.

Incluye:
 - Entidades financieras (http://www.bcra.gov.ar/)
 - Asistente de actualización de bancos.

Requiere:
	BeautifulSoup
	geopy

Para que el asistente funcione debe tener instalada ambos módulos de python.

Instalación de los requerimientos:

	$ pip install BeautifulSoup
	$ pip install geopy

ejecutar desde la linea de comandos.

--------------------------
(ENGLISH)

Includes:
 - Financial Entities (http://www.bcra.gov.ar/)
 - A wizard online updater.

Requires:
	BeautifulSoup
	geopy

Attention, to run the wizard you need to have installed two libraries in python.
Without these two libraries the wizard will fail and will not update the information.

Install them using:

	$ pip install BeautifulSoup
	$ pip install geopy

from the CLI.

""",
    'depends': [
		  'base',
		  'l10n_ar_states',
		],
    'init_xml': [],
    'demo_xml': [],
    'update_xml': [
		      'data/res_bank.xml',
		      'l10n_ar_bank.xml',
		      'l10n_ar_bank_menu.xml',
		      'wizard/wiz_l10n_ar_bank.xml',
		  ],
    'test': [
        'test/l10n_ar_banks_wizard.yml',
    ],
    'active': False,
    'installable': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>[REF] Changes for v7.0<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
    'name':     'Banks of Argentina',
    'version':  '2.1',
    'author':   'OpenERP - Team de Localización Argentina',
    'category': 'Localization/Argentina',
    'website':  'https://launchpad.net/~openerp-l10n-ar-localization',
    'license':  'AGPL-3',
    'description': """\
Part of localization Model for Argentina - Banks of Argentina

--------------------------
(SPANISH)

Listado de entidades financieras habilitadas por el BCRA.

Este módulo le permite tener a disposición el listado actualizado de
las entidades bancarias de la República Argentina.

Incluye:
 - Entidades financieras (http://www.bcra.gov.ar/)
 - Asistente de actualización de bancos.

Requiere:
	BeautifulSoup
	geopy

Para que el asistente funcione debe tener instalada ambos módulos de python.

Instalación de los requerimientos:

	$ pip install BeautifulSoup
	$ pip install geopy

ejecutar desde la linea de comandos.

--------------------------
(ENGLISH)

Includes:
 - Financial Entities (http://www.bcra.gov.ar/)
 - A wizard online updater.

Requires:
	BeautifulSoup
	geopy

Attention, to run the wizard you need to have installed two libraries in python.
Without these two libraries the wizard will fail and will not update the information.

Install them using:

	$ pip install BeautifulSoup
	$ pip install geopy

from the CLI.

""",
    'depends': [
		  'base',
		  'l10n_ar_states',
		],
    'init_xml': [],
    'demo_xml': [],
    'update_xml': [
		      'data/res_bank.xml',
		      'l10n_ar_bank.xml',
		      'l10n_ar_bank_menu.xml',
		      'wizard/wiz_l10n_ar_bank.xml',
		  ],
    'test': [
        'test/l10n_ar_banks_wizard.yml',
    ],
    'external_dependencies': {
        'python': [ 'BeautifulSoup', 'geopy' ],
    },
    'active': False,
    'installable': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before>import matplotlib.pyplot as plt
import numpy as np
from astropy import units as u
from ipywidgets import fixed, interact

interpolators = ['none', 'nearest', 'bilinear', 'bicubic',
                 'spline16', 'spline36', 'hanning', 'hamming',
                 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian',
                 'bessel', 'mitchell', 'sinc', 'lanczos']

def lookup_rcparam(rcParams, pattern):
    """Look up a pattern in the matplotlib rcParams dict.

    Just a little helper to get to the right MPL settings faster.
    """
    return [i for i in rcParams.keys() if pattern in i]

def myimshow(img, vmin, vmax, i, cmap='gray'):
    _, ax = plt.subplots(nrows=2, figsize=(10, 10))
    ax, ax2 = ax
    ax.imshow(img, vmin=vmin, vmax=vmax, aspect='auto',
              interpolation=interpolators[i],
              cmap=cmap)
    ax.set_title('vmin: {:.2f}, vmax: {:.2f}, interpolator:{}'
                 .format(vmin, vmax, interpolators[i]))
    tohist = img[~np.isnan(img)]
    p1, p99 = np.percentile(tohist, (0.5, 99.5))
    ax2.hist(img[~np.isnan(img)], 100, range=(p1, p99))
    plt.show()

def myinteract(img):
    min_ = round(np.nanmin(img), 4)
    max_ = round(np.nanmax(img), 4)
    p30, p70 = np.percentile(img[~np.isnan(img)], (30, 70))
    delta = round((p30-min_)/50, 5)
    interact(myimshow, img=fixed(img), vmin=(min_, p30, delta),
             vmax=(p70, max_, delta), i=(0, len(interpolators)-1))

def imshowlowhigh(data, low=10, high=90):
    fig, ax = plt.subplots()
    plow, phigh = np.percentile(data[~np.isnan(data)], (low, high))
    ax.imshow(data, vmin=plow, vmax=phigh, cmap='gray', interpolation='sinc')
    return fig

def add_ticks_to_x(ax, newticks, newnames):
    """Add new ticks to an axis.

    I use this for the right-hand plotting of resonance names in my plots.
    """
    ticks = list(ax.get_xticks())
    ticks.extend(newticks)
    ax.set_xticks(ticks)

    names = list(ax.get_xticklabels())
    names.extend(newnames)
    ax.set_xticklabels(names)

def soliton_plot(cube, solitons, ax=None, solitoncolor='red', resonances=None,
                 draw_prediction=True, soliton_controls_radius=False,
                 saveroot=None):
    if ax is None:
        fig, ax = plt.subplots(figsize=(12, 9), nrows=2)
    else:
        fig = ax.get_figure()

    # set resonances to True to get all (warning: in A ring too many to be useful)
    if resonances is None:
        # setting some reasonable defaults here:
        resonances = ['janus', 'prometheus', 'epimetheus']

    cube.imshow(show_resonances=resonances, ax=ax[0], fig=fig,
                set_extent=True, plow=35)

    ticks = []
    names = []
    if draw_prediction:
        for k, v in solitons.items():
            ax[0].axhline(y=v.value/1000, alpha=1, color=solitoncolor, linestyle='dashdot',
                          lw=4, xmin=0.25, xmax=0.5)
            ticks.append(v.value)
            names.append(k)

    ax2 = ax[0].twinx()

    # soliton name and value, only using first found soliton
    # TODO: create function that deals with more than one soliton
    res_name, res_radius = next(iter(solitons.items()))

    if soliton_controls_radius:
        xlow = (res_radius - 20*u.km).to(u.Mm)
        xhigh = xlow + 0.2 * u.Mm
        ax[0].set_ybound(xlow.value, xhigh.value)
        ax2.set_ybound(xlow.value, xhigh.value)
    else:
        ax2.set_ybound(cube.minrad.value, cube.maxrad.value)

    ax2.ticklabel_format(useOffset=False)
    ax2.set_yticks(np.array(ticks)/1000)
    ax2.set_yticklabels(names)

    ax[1].plot(np.linspace(*cube.extent[2:], cube.img.shape[0]),
               np.nanmedian(cube.img, axis=1),
               color='white', lw=1)

    ticks = []
    names = []
    if draw_prediction:
        for k, v in solitons.items():
            ax[1].axvline(x=v.value/1000, alpha=1, color=solitoncolor, linestyle='dashdot',
                          lw=4)
            ticks.append(v.value)
            names.append(k)

    ax[1].set_axis_bgcolor('black')
    ax[1].set_title('Longitude-median profile over radius')
    ax[1].set_xlabel('Radius [Mm]')
    ax[1].set_ylabel('I/F')
    if soliton_controls_radius:
        ax[1].set_xlim(xlow.value, xhigh.value)
    else:
        ax[1].set_xlim(cube.minrad.value, cube.maxrad.value)
    ax3 = ax[1].twiny()
    ax3.ticklabel_format(useOffset=False)
    ax3.set_xticks(np.array(ticks)/1000)
    ax3.set_xticklabels(names)
    # add_ticks_to_x(ax[1], ticks, names)
    fig.tight_layout()
    savepath = "{}_{}.png".format(cube.pm.img_id, res_name)
    if saveroot is not None:
        savepath = Path(saveroot) / savepath
    fig.savefig(savepath, dpi=100)
<commit_msg>fix missing Path import<commit_after>import matplotlib.pyplot as plt
import numpy as np
from astropy import units as u
from ipywidgets import fixed, interact
from pathlib import Path

interpolators = ['none', 'nearest', 'bilinear', 'bicubic',
                 'spline16', 'spline36', 'hanning', 'hamming',
                 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian',
                 'bessel', 'mitchell', 'sinc', 'lanczos']

def lookup_rcparam(rcParams, pattern):
    """Look up a pattern in the matplotlib rcParams dict.

    Just a little helper to get to the right MPL settings faster.
    """
    return [i for i in rcParams.keys() if pattern in i]

def myimshow(img, vmin, vmax, i, cmap='gray'):
    _, ax = plt.subplots(nrows=2, figsize=(10, 10))
    ax, ax2 = ax
    ax.imshow(img, vmin=vmin, vmax=vmax, aspect='auto',
              interpolation=interpolators[i],
              cmap=cmap)
    ax.set_title('vmin: {:.2f}, vmax: {:.2f}, interpolator:{}'
                 .format(vmin, vmax, interpolators[i]))
    tohist = img[~np.isnan(img)]
    p1, p99 = np.percentile(tohist, (0.5, 99.5))
    ax2.hist(img[~np.isnan(img)], 100, range=(p1, p99))
    plt.show()

def myinteract(img):
    min_ = round(np.nanmin(img), 4)
    max_ = round(np.nanmax(img), 4)
    p30, p70 = np.percentile(img[~np.isnan(img)], (30, 70))
    delta = round((p30-min_)/50, 5)
    interact(myimshow, img=fixed(img), vmin=(min_, p30, delta),
             vmax=(p70, max_, delta), i=(0, len(interpolators)-1))

def imshowlowhigh(data, low=10, high=90):
    fig, ax = plt.subplots()
    plow, phigh = np.percentile(data[~np.isnan(data)], (low, high))
    ax.imshow(data, vmin=plow, vmax=phigh, cmap='gray', interpolation='sinc')
    return fig

def add_ticks_to_x(ax, newticks, newnames):
    """Add new ticks to an axis.

    I use this for the right-hand plotting of resonance names in my plots.
    """
    ticks = list(ax.get_xticks())
    ticks.extend(newticks)
    ax.set_xticks(ticks)

    names = list(ax.get_xticklabels())
    names.extend(newnames)
    ax.set_xticklabels(names)

def soliton_plot(cube, solitons, ax=None, solitoncolor='red', resonances=None,
                 draw_prediction=True, soliton_controls_radius=False,
                 saveroot=None):
    if ax is None:
        fig, ax = plt.subplots(figsize=(12, 9), nrows=2)
    else:
        fig = ax.get_figure()

    # set resonances to True to get all (warning: in A ring too many to be useful)
    if resonances is None:
        # setting some reasonable defaults here:
        resonances = ['janus', 'prometheus', 'epimetheus']

    cube.imshow(show_resonances=resonances, ax=ax[0], fig=fig,
                set_extent=True, plow=35)

    ticks = []
    names = []
    if draw_prediction:
        for k, v in solitons.items():
            ax[0].axhline(y=v.value/1000, alpha=1, color=solitoncolor, linestyle='dashdot',
                          lw=4, xmin=0.25, xmax=0.5)
            ticks.append(v.value)
            names.append(k)

    ax2 = ax[0].twinx()

    # soliton name and value, only using first found soliton
    # TODO: create function that deals with more than one soliton
    res_name, res_radius = next(iter(solitons.items()))

    if soliton_controls_radius:
        xlow = (res_radius - 20*u.km).to(u.Mm)
        xhigh = xlow + 0.2 * u.Mm
        ax[0].set_ybound(xlow.value, xhigh.value)
        ax2.set_ybound(xlow.value, xhigh.value)
    else:
        ax2.set_ybound(cube.minrad.value, cube.maxrad.value)

    ax2.ticklabel_format(useOffset=False)
    ax2.set_yticks(np.array(ticks)/1000)
    ax2.set_yticklabels(names)

    ax[1].plot(np.linspace(*cube.extent[2:], cube.img.shape[0]),
               np.nanmedian(cube.img, axis=1),
               color='white', lw=1)

    ticks = []
    names = []
    if draw_prediction:
        for k, v in solitons.items():
            ax[1].axvline(x=v.value/1000, alpha=1, color=solitoncolor, linestyle='dashdot',
                          lw=4)
            ticks.append(v.value)
            names.append(k)

    ax[1].set_axis_bgcolor('black')
    ax[1].set_title('Longitude-median profile over radius')
    ax[1].set_xlabel('Radius [Mm]')
    ax[1].set_ylabel('I/F')
    if soliton_controls_radius:
        ax[1].set_xlim(xlow.value, xhigh.value)
    else:
        ax[1].set_xlim(cube.minrad.value, cube.maxrad.value)
    ax3 = ax[1].twiny()
    ax3.ticklabel_format(useOffset=False)
    ax3.set_xticks(np.array(ticks)/1000)
    ax3.set_xticklabels(names)
    # add_ticks_to_x(ax[1], ticks, names)
    fig.tight_layout()
    savepath = "{}_{}.png".format(cube.pm.img_id, res_name)
    if saveroot is not None:
        root = Path(saveroot)
        root.mkdir(exist_ok=True)
        savepath = root / savepath
    fig.savefig(savepath, dpi=100)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
{
    "name": "Alternate Ledger",
    "version": "0.1",
    "author": "XCG Consulting",
    "category": 'Accounting',
    "description": """Enhancements to the account module to allow user to
                   exclude openning journal when generating trial balance.""",
    'website': 'http://www.openerp-experts.com',
    'init_xml': [],
    "depends": [
        'base',
        'account_accountant',
    ],
    "data": [
        'wizard/account_report_alternate_account_balance_view.xml',
        'views/account_view.xml',
        'views/ledger_type.xml',
        'security/ir.model.access.csv',
        'views/menu.xml',
    ],
    'js': [
        'static/src/js/account_move_line_alternate_quickadd.js',
    ],
    'qweb': [
        'static/src/xml/account_move_line_alternate_quickadd.xml',
    ],
    'installable': True,
    'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>Depend on account_streamline<commit_after># -*- coding: utf-8 -*-
{
    "name": "Alternate Ledger",
    "version": "0.1",
    "author": "XCG Consulting",
    "category": 'Accounting',
    "description": '''Allow the creation of new accounting ledgers that store
        separate transactions.''',
    'website': 'http://www.openerp-experts.com',
    'init_xml': [],
    "depends": [
        'base',
        'account_streamline',
    ],
    "data": [
        'wizard/account_report_alternate_account_balance_view.xml',
        'views/account_view.xml',
        'views/ledger_type.xml',
        'views/menu.xml',
#         'security/ir.model.access.csv',
    ],
    'js': [
        'static/src/js/account_move_line_alternate_quickadd.js',
    ],
    'qweb': [
        'static/src/xml/account_move_line_alternate_quickadd.xml',
    ],
    'installable': True,
    'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
##############################################################################
{
    "name": "Account Invoice Streamline",
    "version": "1.3",
    "author": "XCG Consulting",
    "category": 'Accounting',
    "description": """Enhancements to the account
    invoice module to streamline its usage.
    """,
    'website': 'http://www.openerp-experts.com',
    'init_xml': [],
    "depends": [
        'base',
        'account_streamline',
        'analytic_structure'],
    "data": [
        'views/account_invoice.xml',
    ],
    #'demo_xml': [],
    'test': [],
    'installable': True,
    'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>Bumped version to 1.4(stable)<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
##############################################################################
{
    "name": "Account Invoice Streamline",
    "version": "1.4",
    "author": "XCG Consulting",
    "category": 'Accounting',
    "description": """Enhancements to the account
    invoice module to streamline its usage.
    """,
    'website': 'http://www.openerp-experts.com',
    'init_xml': [],
    "depends": [
        'base',
        'account_streamline',
        'analytic_structure'],
    "data": [
        'views/account_invoice.xml',
    ],
    #'demo_xml': [],
    'test': [],
    'installable': True,
    'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


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

import sys
from rpython import conftest
class o:
    view = False
    viewloops = True
conftest.option = o
from rpython.jit.metainterp.test.test_ajit import LLJitMixin

import pytest
from pycket.test.test_larger import parse_file
from pycket.expand import expand, to_ast
from pycket.interpreter import *
from pycket.values import *

class TestLLtype(LLJitMixin):

    def test_countdown(self):
        ast = to_ast(expand("""
(letrec ([countdown (lambda (n) (if (< n 0) 1 (countdown (- n 1))))])
 (countdown 1000))
"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_countdown_nested(self):
        ast = to_ast(expand("""
(let ()
  (define (nested n)
    (let countdown ([n n]) (if (< n 0) 1 (countdown (- n 1))))
    (if (< n 0) 1 (nested (- n 1))))
  (nested 10))
"""))
        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_countdown_loop(self):
        ast = to_ast(expand("""
(let countdown ([n 1000]) (if (< n 0) 1 (countdown (- n 1))))
"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_bistable_loop(self):
        ast = to_ast(expand("""
(let ()
    (define (countdown n sub2?)
        (if (< n 0) 1
            (if sub2?
                (countdown (- n 2) #f)
                (countdown (- n 1) #t)
                )))
    (countdown 1000 #f)
)
"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_side_exit(self):
        ast = to_ast(expand("""
(let ()
    (define (count-positive l sum)
        (if (null? l) sum
            (if (> (car l) 0)
                (count-positive (cdr l) (+ (car l) sum))
                (count-positive (cdr l) sum)
                )))
    (count-positive (list -1 1 1 1 1 -1 2 3 -5 1 2 2 -5 6 4 3 -5) 0))

"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 27

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_setbang(self):

        ast = to_ast(expand("(let ([n 1000]) (letrec ([countdown (lambda () (if (< n 0) 1 (begin (set! n (- n 1)) (countdown))))]) (countdown)))"))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_puzzle(self):
        fname = "puzzle.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret_one(ast)
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_bubble(self):
        fname = "bubble.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret([ast])
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_bubble_unsafe(self):
        fname = "bubble-unsafe.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret([ast])
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_bubble_arg(self):
        fname = "bubble-arg.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret([ast])
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_pseudoknot(self):
        fname = "nucleic2.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret([ast])
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_minik(self):
        fname = "minikanren.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret_one(ast)
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_microk(self):
        fname = "microkanren.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret_one(ast)
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_append(self):
        ast = to_ast(expand("""
(let () (define (append a b)
  (if (null? a)
      b
      (cons (car a) (append (cdr a) b))))
 (append (list 1 2 3 5 6 6 7 7 8 3 4 5 3 5 4 3 5 3 5 3 3 5 4 3) (list 4 5 6)))
"""
))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Object)
            return 1

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_let_append(self):
        ast = to_ast(expand("""
(let ()
(define (let-append a b)
  (let ([tst (null? a)])
      (if tst
          b
          (cons (car a) (let-append (cdr a) b)))))
 (let-append (list 1 2 3 5 6 6 7 7 8 3 4 5 3 5 4 3 5 3 5 3 3 5 4 3) (list 4 5 6)))
"""
))

    def test_anormal_append(self):
        ast = to_ast(expand("""
(let ()
(define (append-anormal a b)
  (if (null? a)
      b
      (let* ([ca (car a)]
             [cd (cdr a)]
             [ap (append-anormal cd b)])
        (cons ca ap))))
 (append-anormal (list 1 2 3 5 6 6 7 7 8 3 4 5 3 5 4 3 5 3 5 3 3 5 4 3) (list 4 5 6)))
"""
))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Object)
            return 1

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_ycombinator(self):

        Y = """
      (lambda (f)
        ((lambda (x) (x x))
         (lambda (g)
           (f (lambda (z) ((g g) z))))))
    """
        countdown = """
        (lambda (f)
          (lambda (x)
            (if (< x 0)
                1
                (f (- x 1)))))
     """
        ast = to_ast(expand("((%s %s) 1000)"%(Y,countdown)))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return val.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_vector_get_set(self):
        ast = to_ast(expand("""
(letrec ([v (make-vector 1000 0)]
         [fill-square-vector (lambda (n)
                                (if (< n 0)
                                  (vector-ref v 999)
                                  (begin (vector-set! v n (* n n))
                                         (fill-square-vector (- n 1)))))]
         [sum-vector (lambda (n s)
                        (if (< n 0)
                            s
                            (sum-vector (- n 1) (+ s (vector-ref v n)))))])
 (begin (fill-square-vector 999) (sum-vector 999 0)))
"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return val.value

        assert interp_w() == sum(i ** 2 for i in range(1000))

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

<commit_msg>close over an outer var in example<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Test.
#

import sys
from rpython import conftest
class o:
    view = False
    viewloops = True
conftest.option = o
from rpython.jit.metainterp.test.test_ajit import LLJitMixin

import pytest
from pycket.test.test_larger import parse_file
from pycket.expand import expand, to_ast
from pycket.interpreter import *
from pycket.values import *

class TestLLtype(LLJitMixin):

    def test_countdown(self):
        ast = to_ast(expand("""
(letrec ([countdown (lambda (n) (if (< n 0) 1 (countdown (- n 1))))])
 (countdown 1000))
"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_countdown_nested(self):
        ast = to_ast(expand("""
(let ([sub 1])
  (define (nested n)
    (let countdown ([n n]) (if (< n 0) 1 (countdown (- n sub))))
    (if (< n 0) 1 (nested (- n sub))))
  (nested 10))
"""))
        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_countdown_loop(self):
        ast = to_ast(expand("""
(let countdown ([n 1000]) (if (< n 0) 1 (countdown (- n 1))))
"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_bistable_loop(self):
        ast = to_ast(expand("""
(let ()
    (define (countdown n sub2?)
        (if (< n 0) 1
            (if sub2?
                (countdown (- n 2) #f)
                (countdown (- n 1) #t)
                )))
    (countdown 1000 #f)
)
"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_side_exit(self):
        ast = to_ast(expand("""
(let ()
    (define (count-positive l sum)
        (if (null? l) sum
            (if (> (car l) 0)
                (count-positive (cdr l) (+ (car l) sum))
                (count-positive (cdr l) sum)
                )))
    (count-positive (list -1 1 1 1 1 -1 2 3 -5 1 2 2 -5 6 4 3 -5) 0))

"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 27

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_setbang(self):

        ast = to_ast(expand("(let ([n 1000]) (letrec ([countdown (lambda () (if (< n 0) 1 (begin (set! n (- n 1)) (countdown))))]) (countdown)))"))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return ov.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_puzzle(self):
        fname = "puzzle.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret_one(ast)
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_bubble(self):
        fname = "bubble.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret([ast])
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_bubble_unsafe(self):
        fname = "bubble-unsafe.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret([ast])
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_bubble_arg(self):
        fname = "bubble-arg.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret([ast])
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_pseudoknot(self):
        fname = "nucleic2.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret([ast])
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_minik(self):
        fname = "minikanren.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret_one(ast)
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_microk(self):
        fname = "microkanren.sch"
        ast = parse_file(fname)
        def interp_w():
            val = interpret_one(ast)
            return val

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_append(self):
        ast = to_ast(expand("""
(let () (define (append a b)
  (if (null? a)
      b
      (cons (car a) (append (cdr a) b))))
 (append (list 1 2 3 5 6 6 7 7 8 3 4 5 3 5 4 3 5 3 5 3 3 5 4 3) (list 4 5 6)))
"""
))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Object)
            return 1

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_let_append(self):
        ast = to_ast(expand("""
(let ()
(define (let-append a b)
  (let ([tst (null? a)])
      (if tst
          b
          (cons (car a) (let-append (cdr a) b)))))
 (let-append (list 1 2 3 5 6 6 7 7 8 3 4 5 3 5 4 3 5 3 5 3 3 5 4 3) (list 4 5 6)))
"""
))

    def test_anormal_append(self):
        ast = to_ast(expand("""
(let ()
(define (append-anormal a b)
  (if (null? a)
      b
      (let* ([ca (car a)]
             [cd (cdr a)]
             [ap (append-anormal cd b)])
        (cons ca ap))))
 (append-anormal (list 1 2 3 5 6 6 7 7 8 3 4 5 3 5 4 3 5 3 5 3 3 5 4 3) (list 4 5 6)))
"""
))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Object)
            return 1

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_ycombinator(self):

        Y = """
      (lambda (f)
        ((lambda (x) (x x))
         (lambda (g)
           (f (lambda (z) ((g g) z))))))
    """
        countdown = """
        (lambda (f)
          (lambda (x)
            (if (< x 0)
                1
                (f (- x 1)))))
     """
        ast = to_ast(expand("((%s %s) 1000)"%(Y,countdown)))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return val.value

        assert interp_w() == 1

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

    def test_vector_get_set(self):
        ast = to_ast(expand("""
(letrec ([v (make-vector 1000 0)]
         [fill-square-vector (lambda (n)
                                (if (< n 0)
                                  (vector-ref v 999)
                                  (begin (vector-set! v n (* n n))
                                         (fill-square-vector (- n 1)))))]
         [sum-vector (lambda (n s)
                        (if (< n 0)
                            s
                            (sum-vector (- n 1) (+ s (vector-ref v n)))))])
 (begin (fill-square-vector 999) (sum-vector 999 0)))
"""))

        def interp_w():
            val = interpret_one(ast)
            ov = check_one_val(val)
            assert isinstance(ov, W_Fixnum)
            return val.value

        assert interp_w() == sum(i ** 2 for i in range(1000))

        self.meta_interp(interp_w, [], listcomp=True, listops=True, backendopt=True)

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from openerp import _, api, fields, models, tools

class ProductTemplate(models.Model):
    _inherit = 'product.template'

    pricelist = fields.Boolean(
        string=_('Price list'),
        help=_('the product is displayed in the price list'),
    )
    note_pricelist = fields.Text(
        string=_('Note price list'),
    )
    length = fields.Integer(
        string=_('Length'),
        help=_('length in cm'),
    )
    width = fields.Integer(
        string=_('Width'),
        help=_('width in cm'),
    )
    height = fields.Integer(
        string=_('Height'),
        help=_('height in cm'),
    )
    isometric = fields.Binary(
        string=_("Isometric image"),
        attachment=True,
    )
    isometric_medium = fields.Binary(
        string=_("Medium-sized isometric image"),
        compute='_compute_isometric',
        inverse='_inverse_medium_isometric',
        store=True,
        attachment=True,
    )
    isometric_small = fields.Binary(
        string=_("Small-sized isometric image"),
        compute='_compute_isometric',
        inverse='_inverse_small_isometric',
        store=True,
        attachment=True,
    )

    @api.depends('isometric')
    def _compute_isometric(self):
        for rec in self:
            rec.isometric_medium = tools.image_resize_image_medium(
                rec.isometric,
                avoid_if_small=True)
            rec.isometric_small = tools.image_resize_image_small(rec.isometric)

    def _inverse_medium_isometric(self):
        for rec in self:
            rec.isometric = tools.image_resize_image_big(rec.isometric_medium)

    def _inverse_small_isometric(self):
        for rec in self:
            rec.isometric = tools.image_resize_image_big(rec.isometric_small)
<commit_msg>[FIX] product attribute target<commit_after># -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from openerp import _, api, fields, models, tools

class ProductTemplate(models.Model):
    _inherit = 'product.template'

    pricelist = fields.Boolean(
        string=_('Price list'),
        help=_('the product is displayed in the price list'),
    )
    note_pricelist = fields.Text(
        string=_('Note price list'),
    )
    length = fields.Integer(
        string=_('Length'),
        help=_('length in cm'),
    )
    width = fields.Integer(
        string=_('Width'),
        help=_('width in cm'),
    )
    height = fields.Integer(
        string=_('Height'),
        help=_('height in cm'),
    )
    isometric = fields.Binary(
        string=_("Isometric image"),
        attachment=True,
    )
    isometric_medium = fields.Binary(
        string=_("Medium-sized isometric image"),
        compute='_compute_isometric',
        inverse='_inverse_medium_isometric',
        store=True,
        attachment=True,
    )
    isometric_small = fields.Binary(
        string=_("Small-sized isometric image"),
        compute='_compute_isometric',
        inverse='_inverse_small_isometric',
        store=True,
        attachment=True,
    )

    @api.depends('isometric')
    def _compute_isometric(self):
        for rec in self:
            rec.isometric_medium = tools.image_resize_image_medium(
                rec.isometric,
                avoid_if_small=True)
            rec.isometric_small = tools.image_resize_image_small(rec.isometric)

    def _inverse_medium_isometric(self):
        for rec in self:
            rec.isometric = tools.image_resize_image_big(rec.isometric_medium)

    def _inverse_small_isometric(self):
        for rec in self:
            rec.isometric = tools.image_resize_image_big(rec.isometric_small)

class ProductAttributeLine(models.Model):
    _inherit = 'product.attribute.line'

    target_id = fields.Many2one('product.attribute.target',
                                ondelete='restrict',
                                string=_(u"Apply to"),
                                store=True)

class ProductAttributeTarget(models.Model):
    _name = 'product.attribute.target'

    target_code = fields.Char(
        string=_('Code'),)

    target_name = fields.Char(
        string=_('Name'),)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
{
    'name': 'Chilean VAT Ledger',
    'description': '''
Chilean VAT Ledger Management
=================================
Creates Sale and Purchase VAT report menus in
"accounting/period processing/VAT Ledger"
    ''',
    'version': '0.1',
    'author': u'Blanco Martín & Asociados',
    'website': 'http://blancomartin.cl',
    'depends': [
        'report_aeroo',
        'l10n_cl_invoice'
    ],
    'category': 'Reporting subsystems',
    'data': [
        'account_vat_report_view.xml',
        'report/account_vat_ledger_report.xml',
        'security/security.xml',
        'security/ir.model.access.csv',
    ],
    'installable': True,
    'active': False
}
<commit_msg>Set license to AGPL-3 in manifest<commit_after># -*- coding: utf-8 -*-
{
    'name': 'Chilean VAT Ledger',
    'license': 'AGPL-3',
    'description': '''
Chilean VAT Ledger Management
=================================
Creates Sale and Purchase VAT report menus in
"accounting/period processing/VAT Ledger"
    ''',
    'version': '0.1',
    'author': u'Blanco Martín & Asociados',
    'website': 'http://blancomartin.cl',
    'depends': [
        'report_aeroo',
        'l10n_cl_invoice'
    ],
    'category': 'Reporting subsystems',
    'data': [
        'account_vat_report_view.xml',
        'report/account_vat_ledger_report.xml',
        'security/security.xml',
        'security/ir.model.access.csv',
    ],
    'installable': True,
    'active': False
}
<|endoftext|>


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

#details how to set global SVN variables can be found in http://blogchuck.com/2009/09/adding-svn-headers-revisited/

"""
# Copyright (C) 2012-2013 Alexander Loew, alexander.loew@mpimet.mpg.de
# See COPYING file for copying and redistribution conditions.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# 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 General Public License for more details.
"""

__name__ = "pyCMBS"
"""The project name."""

__author__ = "$Author: $"
"""The primary author of pyCMBS."""

__institute__="Max-Planck-Institute for Meteorology (MPI-M)"

__copyright__ = "Copyright (c) 2011-2013 Alexander Loew"
"""The copyright holder of pyCMBS."""

__license__ = "GNU General Public License"
"""The license governing the use and distribution of pyCMBS."""

__url__ = "https://code.zmaw.de/projects/pycmbs"
"""The URL for pyCMBS's homepage."""

__version__ = "0.1.5"
"""Version number of pyCMBS."""

__revision__ = filter(str.isdigit, "$Revision$")
"""SVN repository number, set SVN using svn propset (see here: http://stackoverflow.com/questions/1449935/getting-svn-revision-number-into-a-program-automatically)"""

__date__ = "2013-06-14"
"""The release date of this version of pyCMBS."""

__docformat__ = "epytext en"
"""The epydoc documentation format for this file."""

__email__ = "alexander.loew@mpimet.mpg.de"

#------------------------------
#--- Import classes
#------------------------------

#- generic classes
import matplotlib
matplotlib.use('Agg')   #this is the first level import of Matplotlib. activate or deactivate here if you want to change the backend used
from matplotlib import pylab as pl
from netcdf import *

from scipy import stats

import numpy as np

from mpl_toolkits.basemap import Basemap,shiftgrid

import os

import sys

import logging

#- classes specific to pyCMBS
from statistic import *
from data   import *
from report import *
from region import *
from plots  import *
from diagnostic import *
from icon import *
from grid import *
from data4D import *

from taylor import *

from hov import *
from region import *

from netcdftime import *

from colormaps.colormaps import *

#------------------------------
#--- Global constants
#------------------------------
EarthRadius = 6371000. #default radius of the earth in m

#~ logger = logging.getLogger('pyCMBS_logger')
#~ hdlr = logging.FileHandler('pyCMBS.log')
#~ formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
#~ hdlr.setFormatter(formatter)
#~ logger.addHandler(hdlr)
#~ logger.setLevel(logging.WARNING) #logging.DEBUG
<commit_msg>[pycmbs/init] removed most of implicit import statements<commit_after># -*- coding: utf-8 -*-

#details how to set global SVN variables can be found in http://blogchuck.com/2009/09/adding-svn-headers-revisited/

"""
# Copyright (C) 2012-2013 Alexander Loew, alexander.loew@mpimet.mpg.de
# See COPYING file for copying and redistribution conditions.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# 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 General Public License for more details.
"""

__name__ = "pycmbs"
"""The project name."""

__author__ = "$Author: $"
"""The primary author of pyCMBS."""

__institute__="Max-Planck-Institute for Meteorology (MPI-M)"

__copyright__ = "Copyright (c) 2011-2013 Alexander Loew"
"""The copyright holder of pyCMBS."""

__license__ = "GNU General Public License"
"""The license governing the use and distribution of pyCMBS."""

__url__ = "https://code.zmaw.de/projects/pycmbs"
"""The URL for pyCMBS's homepage."""

__version__ = "0.1.5"
"""Version number of pyCMBS."""

__revision__ = filter(str.isdigit, "$Revision$")
"""SVN repository number, set SVN using svn propset (see here: http://stackoverflow.com/questions/1449935/getting-svn-revision-number-into-a-program-automatically)"""

__date__ = "2013-06-14"
"""The release date of this version of pyCMBS."""

__docformat__ = "epytext en"
"""The epydoc documentation format for this file."""

__email__ = "alexander.loew@mpimet.mpg.de"

#------------------------------
#--- Import classes
#------------------------------

#- generic classes
import matplotlib
matplotlib.use('Agg')   #this is the first level import of Matplotlib. activate or deactivate here if you want to change the backend used
# from matplotlib import pylab as pl
# from pycmbs import  netcdf
#
# from scipy import stats
#
# import numpy as np
#
# from mpl_toolkits.basemap import Basemap,shiftgrid
#
# import os
#
# import sys
#
# import logging
#
# #- classes specific to pyCMBS
# from pycmbs import statistic
# from data   import *
# from report import *
# from region import *
# from plots  import *
# from diagnostic import *
# from icon import *
# from grid import *
# from data4D import *
#
# from taylor import *
#
# from hov import *
# from region import *
#
# from netcdftime import *
#
# from colormaps.colormaps import *

#------------------------------
#--- Global constants
#------------------------------
EarthRadius = 6371000. #default radius of the earth in m

#~ logger = logging.getLogger('pyCMBS_logger')
#~ hdlr = logging.FileHandler('pyCMBS.log')
#~ formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
#~ hdlr.setFormatter(formatter)
#~ logger.addHandler(hdlr)
#~ logger.setLevel(logging.WARNING) #logging.DEBUG
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#   sale_payment_method for OpenERP
#   Copyright (C) 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>
#
#   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/>.
#
##############################################################################

{
    'name': 'Sale Payment Method',
    'version': '0.2.1',
    'category': 'Generic Modules/Others',
    'license': 'AGPL-3',
    'description': """
Sale Payment Method
===================

This module adds low-level features used for instance by modules:

- Sale Automatic Workflow
- Sale Quick Payment

It adds a payment method on the sales orders and allow to register
payments entries on sales orders.
""",
    'author': 'Akretion',
    'website': 'http://www.akretion.com/',
    'depends': ['sale',
                ],
    'data': ['sale_view.xml',
             'payment_method_view.xml',
             'security/ir.model.access.csv',
             'security/rules.xml',
             ],
    'demo': [],
    'installable': True,
}
<commit_msg>set the flag 'installable' to False on the modules<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#   sale_payment_method for OpenERP
#   Copyright (C) 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>
#
#   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/>.
#
##############################################################################

{
    'name': 'Sale Payment Method',
    'version': '0.2.1',
    'category': 'Generic Modules/Others',
    'license': 'AGPL-3',
    'description': """
Sale Payment Method
===================

This module adds low-level features used for instance by modules:

- Sale Automatic Workflow
- Sale Quick Payment

It adds a payment method on the sales orders and allow to register
payments entries on sales orders.
""",
    'author': 'Akretion',
    'website': 'http://www.akretion.com/',
    'depends': ['sale',
                ],
    'data': ['sale_view.xml',
             'payment_method_view.xml',
             'security/ir.model.access.csv',
             'security/rules.xml',
             ],
    'demo': [],
    'installable': False,
}
<|endoftext|>