<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vispy: gallery 2
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

"""
3D brain mesh viewer.
"""

from timeit import default_timer
import numpy as np

from vispy import gloo
from vispy import app
from vispy.util.transforms import perspective, translate, rotate
from vispy.util import get_data_file

brain = np.load(get_data_file('brain/brain.npz'))
data = brain['vertex_buffer']
faces = brain['index_buffer']

VERT_SHADER = """
#version 120
uniform mat4 u_model;
uniform mat4 u_view;
uniform mat4 u_projection;
uniform vec4 u_color;

attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec4 a_color;

varying vec3 v_position;
varying vec3 v_normal;
varying vec4 v_color;

void main()
{
    v_normal = a_normal;
    v_position = a_position;
    v_color = a_color * u_color;
    gl_Position = u_projection * u_view * u_model * vec4(a_position,1.0);
}
"""

FRAG_SHADER = """
#version 120
uniform mat4 u_model;
uniform mat4 u_view;
uniform mat4 u_normal;

uniform vec3 u_light_intensity;
uniform vec3 u_light_position;

varying vec3 v_position;
varying vec3 v_normal;
varying vec4 v_color;

void main()
{
    // Calculate normal in world coordinates
    vec3 normal = normalize(u_normal * vec4(v_normal,1.0)).xyz;

    // Calculate the location of this fragment (pixel) in world coordinates
    vec3 position = vec3(u_view*u_model * vec4(v_position, 1));

    // Calculate the vector from this pixels surface to the light source
    vec3 surfaceToLight = u_light_position - position;

    // Calculate the cosine of the angle of incidence (brightness)
    float brightness = dot(normal, surfaceToLight) /
                      (length(surfaceToLight) * length(normal));
    brightness = max(min(brightness,1.0),0.0);

    // Calculate final color of the pixel, based on:
    // 1. The angle of incidence: brightness
    // 2. The color/intensities of the light: light.intensities
    // 3. The texture and texture coord: texture(tex, fragTexCoord)

    // Specular lighting.
    vec3 surfaceToCamera = vec3(0.0, 0.0, 1.0) - position;
    vec3 K = normalize(normalize(surfaceToLight) + normalize(surfaceToCamera));
    float specular = clamp(pow(abs(dot(normal, K)), 40.), 0.0, 1.0);

    gl_FragColor = v_color * brightness * vec4(u_light_intensity, 1) +
                   specular * vec4(1.0, 1.0, 1.0, 1.0);
}
"""

class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, close_keys='escape')
        self.size = 800, 600

        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)

        self.theta, self.phi = -80, 180
        self.translate = 3

        self.faces = gloo.IndexBuffer(faces)
        self.program.bind(gloo.VertexBuffer(data))

        self.program['u_color'] = 1, 1, 1, 1
        self.program['u_light_position'] = (1., 1., 1.)
        self.program['u_light_intensity'] = (1., 1., 1.)

        self._t0 = default_timer()
        self._timer = app.Timer(1. / 60)
        self._timer.connect(self.on_timer)
        self._timer.start()

        self.update_matrices()

    def update_matrices(self):
        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        rotate(self.model, self.theta, 1, 0, 0)
        rotate(self.model, self.phi, 0, 1, 0)

        translate(self.view, 0, 0, -self.translate)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.program['u_normal'] = np.array(np.matrix(np.dot(self.view,
                                                             self.model)).I.T)

    def on_initialize(self, event):
        gloo.set_state(blend=False, depth_test=True, polygon_offset_fill=True)

    def on_timer(self, event):
        elapsed = default_timer() - self._t0
        self.phi = 180 + elapsed * 50.
        self.update_matrices()
        self.update()

    def on_resize(self, event):
        width, height = event.size
        gloo.set_viewport(0, 0, width, height)
        self.projection = perspective(45.0, width / float(height), 1.0, 20.0)
        self.program['u_projection'] = self.projection

    def on_mouse_wheel(self, event):
        self.translate += -event.delta[1]/5.
        self.translate = max(2, self.translate)
        self.update_matrices()
        self.update()

    def on_draw(self, event):
        gloo.clear()
        self.program.draw('triangles', indices=self.faces)

if __name__ == '__main__':
    c = Canvas()
    c.show()
    app.run()
<commit_msg>Removed buggy specular lighting in brain example.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vispy: gallery 2
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

"""
3D brain mesh viewer.
"""

from timeit import default_timer
import numpy as np

from vispy import gloo
from vispy import app
from vispy.util.transforms import perspective, translate, rotate
from vispy.util import get_data_file

brain = np.load(get_data_file('brain/brain.npz'))
data = brain['vertex_buffer']
faces = brain['index_buffer']

VERT_SHADER = """
#version 120
uniform mat4 u_model;
uniform mat4 u_view;
uniform mat4 u_projection;
uniform vec4 u_color;

attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec4 a_color;

varying vec3 v_position;
varying vec3 v_normal;
varying vec4 v_color;

void main()
{
    v_normal = a_normal;
    v_position = a_position;
    v_color = a_color * u_color;
    gl_Position = u_projection * u_view * u_model * vec4(a_position,1.0);
}
"""

FRAG_SHADER = """
#version 120
uniform mat4 u_model;
uniform mat4 u_view;
uniform mat4 u_normal;

uniform vec3 u_light_intensity;
uniform vec3 u_light_position;

varying vec3 v_position;
varying vec3 v_normal;
varying vec4 v_color;

void main()
{
    // Calculate normal in world coordinates
    vec3 normal = normalize(u_normal * vec4(v_normal,1.0)).xyz;

    // Calculate the location of this fragment (pixel) in world coordinates
    vec3 position = vec3(u_view*u_model * vec4(v_position, 1));

    // Calculate the vector from this pixels surface to the light source
    vec3 surfaceToLight = u_light_position - position;

    // Calculate the cosine of the angle of incidence (brightness)
    float brightness = dot(normal, surfaceToLight) /
                      (length(surfaceToLight) * length(normal));
    brightness = max(min(brightness,1.0),0.0);

    // Calculate final color of the pixel, based on:
    // 1. The angle of incidence: brightness
    // 2. The color/intensities of the light: light.intensities
    // 3. The texture and texture coord: texture(tex, fragTexCoord)

    // Specular lighting.
    vec3 surfaceToCamera = vec3(0.0, 0.0, 1.0) - position;
    vec3 K = normalize(normalize(surfaceToLight) + normalize(surfaceToCamera));
    float specular = clamp(pow(abs(dot(normal, K)), 40.), 0.0, 1.0);

    gl_FragColor = v_color * brightness * vec4(u_light_intensity, 1);
}
"""

class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, close_keys='escape')
        self.size = 800, 600

        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)

        self.theta, self.phi = -80, 180
        self.translate = 3

        self.faces = gloo.IndexBuffer(faces)
        self.program.bind(gloo.VertexBuffer(data))

        self.program['u_color'] = 1, 1, 1, 1
        self.program['u_light_position'] = (1., 1., 1.)
        self.program['u_light_intensity'] = (1., 1., 1.)

        self._t0 = default_timer()
        self._timer = app.Timer(1. / 60)
        self._timer.connect(self.on_timer)
        self._timer.start()

        self.update_matrices()

    def update_matrices(self):
        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        rotate(self.model, self.theta, 1, 0, 0)
        rotate(self.model, self.phi, 0, 1, 0)

        translate(self.view, 0, 0, -self.translate)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.program['u_normal'] = np.array(np.matrix(np.dot(self.view,
                                                             self.model)).I.T)

    def on_initialize(self, event):
        gloo.set_state(blend=False, depth_test=True, polygon_offset_fill=True)

    def on_timer(self, event):
        elapsed = default_timer() - self._t0
        self.phi = 180 + elapsed * 50.
        self.update_matrices()
        self.update()

    def on_resize(self, event):
        width, height = event.size
        gloo.set_viewport(0, 0, width, height)
        self.projection = perspective(45.0, width / float(height), 1.0, 20.0)
        self.program['u_projection'] = self.projection

    def on_mouse_wheel(self, event):
        self.translate += -event.delta[1]/5.
        self.translate = max(2, self.translate)
        self.update_matrices()
        self.update()

    def on_draw(self, event):
        gloo.clear()
        self.program.draw('triangles', indices=self.faces)

if __name__ == '__main__':
    c = Canvas()
    c.show()
    app.run()
<|endoftext|>


<commit_before>
# --------------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <alexvandermey@gmail.com> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return -Alexander van der Mey
# --------------------------------------------------------------------------------

import os
import sys
import gtk
import gconf

WELCOME = """\\documentclass{article}
\\begin{document}

\\noindent\huge{Welcome to Gummi} \\\\
\\\\
\\large	{You are using the svn version.\\\\
	I welcome your suggestions at:\\\\
	http://code.google.com/p/gummi\\\\

\\end{document}"""

class prefs:

	def __init__(self, parent):
		self.parent = parent
		self.gconf_client = gconf.client_get_default()
		self.check_for_defaults()

	def create_gui(self):
		builder = gtk.Builder()
		builder.add_from_file(self.parent.installdir + "/gui/prefs.xml")

		self.prefwindow = builder.get_object("prefwindow")
		self.box = builder.get_object("hbox1")
		self.notebook = builder.get_object("notebook1")
		self.textwrap_char = builder.get_object("textwrap_char")
		self.textwrap_word = builder.get_object("textwrap_word")
		self.textlines_display = builder.get_object("textlines_display")
		self.textlines_highlight = builder.get_object("textlines_highlight")
		self.box.pack_start(self.notebook, expand=False)

		self.textwrap_char.connect("toggled", self.run_wrapping_char, "textwrap char")
		self.textwrap_word.connect("toggled", self.run_wrapping_word, "textwrap word")
		self.textlines_display.connect("toggled", self.run_lines, "textlines display")
		self.textlines_highlight.connect("toggled", self.run_highlight, "textlines highlight")

		self.get_current_status()

		builder.connect_signals(self)
		self.prefwindow.show_all()

	def get_current_status(self):
		self.textwrap_char.set_active(1)
		if self.get_config_value("text_wrapping") == "char":
			self.textwrap_char.set_active(1)
		if self.get_config_value("text_wrapping") == "word":
			self.textwrap_char.set_active(1)
			self.textwrap_word.set_active(1)
		if self.get_config_value("text_lines") == "True":
			self.textlines_display.set_active(1)
		if self.get_config_value("text_highlight") == "True":
			self.textlines_highlight.set_active(1)

	def run_wrapping_char(self, widget, data=None):
		if widget.get_active() == False:
			self.textwrap_word.set_active(0)
			self.parent.editorpane.set_wrapping("None")
		else:
			self.parent.editorpane.set_wrapping("char")

	def run_wrapping_word(self, widget, data=None):
		if widget.get_active() == False:
			self.parent.editorpane.set_wrapping("char")
		if widget.get_active() == True:
			self.parent.editorpane.set_wrapping("word")

	def run_lines(self, widget, data=None):
		if widget.get_active() == False:
			self.parent.editorpane.editorview.set_show_line_numbers(False)
			self.gconf_client.set_string("/apps/gummi/text_lines", "False")
		else:
			self.parent.editorpane.editorview.set_show_line_numbers(True)
			self.gconf_client.set_string("/apps/gummi/text_lines", "True")

	def run_highlight(self, widget, data=None):
		if widget.get_active() == False:
			self.parent.editorpane.editorview.set_highlight_current_line(False)
			self.gconf_client.set_string("/apps/gummi/text_highlight", "False")
		else:
			self.parent.editorpane.editorview.set_highlight_current_line(True)
			self.gconf_client.set_string("/apps/gummi/text_highlight", "True")

	def get_config_value(self, type, item):
		if type == "string":
			configitem = self.gconf_client.get_string("/apps/gummi/" + item)
			return configitem
		if type == "list":
			configitem = self.gconf_client.get_string("/apps/gummi/" + item)
			return configitem

	def get_config_status(self, item):
		if self.gconf_client.get_string("/apps/gummi/" + item) == "True":
			return 1
		else:
			return 0

	def check_for_defaults(self):
		textwrapping = self.gconf_client.get_string("/apps/gummi/text_wrapping")
		if textwrapping is None:
			self.gconf_client.set_string("/apps/gummi/text_wrapping", "word")
		textlines = self.gconf_client.get_string("/apps/gummi/text_lines")
		if textlines is None:
			self.gconf_client.set_string("/apps/gummi/text_lines", "True")
		texthighlight = self.gconf_client.get_string("/apps/gummi/text_highlight")
		if texthighlight is None:
			self.gconf_client.set_string("/apps/gummi/text_highlight", "True")
		default = self.gconf_client.get_string("/apps/gummi/default-text")
		if default is None:
			self.gconf_client.set_string("/apps/gummi/default-text", WELCOME)

<commit_msg>fixed bug that prevented prefs gui from building<commit_after>
# --------------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <alexvandermey@gmail.com> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return -Alexander van der Mey
# --------------------------------------------------------------------------------

import os
import sys
import gtk
import gconf

WELCOME = """\\documentclass{article}
\\begin{document}

\\noindent\huge{Welcome to Gummi} \\\\
\\\\
\\large	{You are using the svn version.\\\\
	I welcome your suggestions at:\\\\
	http://code.google.com/p/gummi\\\\

\\end{document}"""

class prefs:

	def __init__(self, parent):
		self.parent = parent
		self.gconf_client = gconf.client_get_default()
		self.check_for_defaults()

	def create_gui(self):
		builder = gtk.Builder()
		builder.add_from_file(self.parent.installdir + "/gui/prefs.xml")

		self.prefwindow = builder.get_object("prefwindow")
		self.box = builder.get_object("hbox1")
		self.notebook = builder.get_object("notebook1")
		self.textwrap_char = builder.get_object("textwrap_char")
		self.textwrap_word = builder.get_object("textwrap_word")
		self.textlines_display = builder.get_object("textlines_display")
		self.textlines_highlight = builder.get_object("textlines_highlight")
		self.box.pack_start(self.notebook, expand=False)

		self.textwrap_char.connect("toggled", self.run_wrapping_char, "textwrap char")
		self.textwrap_word.connect("toggled", self.run_wrapping_word, "textwrap word")
		self.textlines_display.connect("toggled", self.run_lines, "textlines display")
		self.textlines_highlight.connect("toggled", self.run_highlight, "textlines highlight")

		self.get_current_status()

		builder.connect_signals(self)
		self.prefwindow.show_all()

	def get_current_status(self):
		self.textwrap_char.set_active(1)
		if self.get_config_value("string", "text_wrapping") == "char":
			self.textwrap_char.set_active(1)
		if self.get_config_value("string", "text_wrapping") == "word":
			self.textwrap_char.set_active(1)
			self.textwrap_word.set_active(1)
		if self.get_config_value("string", "text_lines") == "True":
			self.textlines_display.set_active(1)
		if self.get_config_value("string", "text_highlight") == "True":
			self.textlines_highlight.set_active(1)

	def run_wrapping_char(self, widget, data=None):
		if widget.get_active() == False:
			self.textwrap_word.set_active(0)
			self.parent.editorpane.set_wrapping("None")
		else:
			self.parent.editorpane.set_wrapping("char")

	def run_wrapping_word(self, widget, data=None):
		if widget.get_active() == False:
			self.parent.editorpane.set_wrapping("char")
		if widget.get_active() == True:
			self.parent.editorpane.set_wrapping("word")

	def run_lines(self, widget, data=None):
		if widget.get_active() == False:
			self.parent.editorpane.editorview.set_show_line_numbers(False)
			self.gconf_client.set_string("/apps/gummi/text_lines", "False")
		else:
			self.parent.editorpane.editorview.set_show_line_numbers(True)
			self.gconf_client.set_string("/apps/gummi/text_lines", "True")

	def run_highlight(self, widget, data=None):
		if widget.get_active() == False:
			self.parent.editorpane.editorview.set_highlight_current_line(False)
			self.gconf_client.set_string("/apps/gummi/text_highlight", "False")
		else:
			self.parent.editorpane.editorview.set_highlight_current_line(True)
			self.gconf_client.set_string("/apps/gummi/text_highlight", "True")

	def get_config_value(self, type, item):
		if type == "string":
			configitem = self.gconf_client.get_string("/apps/gummi/" + item)
			return configitem
		if type == "list":
			configitem = self.gconf_client.get_string("/apps/gummi/" + item)
			return configitem

	def get_config_status(self, item):
		if self.gconf_client.get_string("/apps/gummi/" + item) == "True":
			return 1
		else:
			return 0

	def check_for_defaults(self):
		textwrapping = self.gconf_client.get_string("/apps/gummi/text_wrapping")
		if textwrapping is None:
			self.gconf_client.set_string("/apps/gummi/text_wrapping", "word")
		textlines = self.gconf_client.get_string("/apps/gummi/text_lines")
		if textlines is None:
			self.gconf_client.set_string("/apps/gummi/text_lines", "True")
		texthighlight = self.gconf_client.get_string("/apps/gummi/text_highlight")
		if texthighlight is None:
			self.gconf_client.set_string("/apps/gummi/text_highlight", "True")
		default = self.gconf_client.get_string("/apps/gummi/default-text")
		if default is None:
			self.gconf_client.set_string("/apps/gummi/default-text", WELCOME)

<|endoftext|>


<commit_before>import stripe

from ..conf import settings
from .. import utils
from .. import proxies

def sync_plans():
    for plan in stripe.Plan.all().data:
        defaults = dict(
            amount=utils.convert_amount_for_db(plan.amount, plan.currency),
            currency=plan.currency or "",
            interval=plan.interval,
            interval_count=plan.interval_count,
            name=plan.name,
            statement_descriptor=plan.statement_descriptor or "",
            trial_period_days=plan.trial_period_days
        )
        obj, created = proxies.PlanProxy.objects.get_or_create(
            stripe_id=plan.id,
            defaults=defaults
        )
        if not created:
            for key in defaults:
                setattr(obj, key, defaults[key])
            obj.save()

def sync_payment_source_from_stripe_data(customer, source):
    if source["id"].startswith("card_"):
        defaults = dict(
            customer=customer,
            name=source["name"] or "",
            address_line_1=source["address_line1"] or "",
            address_line_1_check=source["address_line1_check"] or "",
            address_line_2=source["address_line2"] or "",
            address_city=source["address_city"] or "",
            address_state=source["address_state"] or "",
            address_country=source["address_country"] or "",
            address_zip=source["address_zip"] or "",
            address_zip_check=source["address_zip_check"] or "",
            brand=source["brand"],
            country=source["country"],
            cvc_check=source["cvc_check"],
            dynamic_last4=source["dynamic_last4"] or "",
            exp_month=source["exp_month"],
            exp_year=source["exp_year"],
            funding=source["funding"] or "",
            last4=source["last4"] or "",
            fingerprint=source["fingerprint"] or ""
        )
        card, created = proxies.CardProxy.objects.get_or_create(
            stripe_id=source["id"],
            defaults=defaults
        )
        if not created:
            for key in defaults:
                setattr(card, key, defaults[key])
            card.save()
    else:
        defaults = dict(
            customer=customer,
            active=source["active"],
            amount=utils.conver_amount_for_db(source["amount"], source.currency),
            amount_received=utils.convert_amount_for_db(source["amount_received"], source.currency),
            bitcoin_amount=source["bitcoin_amount"],
            bitcoin_amount_received=source["bitcoin_amount_received"],
            bitcoin_uri=source["bitcoin_uri"],
            currency=source["currency"],
            description=source["description"],
            email=source["email"],
            filled=source["filled"],
            inbound_address=source["inbound_address"],
            payment=source["payment"],
            refund_address=source["refund_address"],
            uncaptured_funds=source["uncaptured_funds"],
            used_for_payment=source["used_for_payment"]
        )
        receiver, created = proxies.BitcoinRecieverProxy.objects.get_or_create(
            stripe_id=source["id"],
            defaults=defaults
        )
        if not created:
            for key in defaults:
                setattr(receiver, key, defaults[key])
            receiver.save()

def sync_subscription_from_stripe_data(customer, subscription):
    defaults = dict(
        customer=customer,
        application_fee_percent=subscription.application_fee_percent,
        cancel_at_period_end=subscription.cancel_at_period_end,
        canceled_at=utils.convert_tstamp(subscription.canceled_at),
        current_period_start=utils.convert_tstamp(subscription.current_period_start),
        current_period_end=utils.convert_tstamp(subscription.current_period_end),
        ended_at=utils.convert_tstamp(subscription.ended_at),
        plan=proxies.PlanProxy.objects.get(stripe_id=subscription.plan.id),
        quantity=subscription.quantity,
        start=utils.convert_tstamp(subscription.start),
        status=subscription.status,
        trial_start=utils.convert_tstamp(subscription.trial_start) if subscription.trial_start else None,
        trial_end=utils.convert_tstamp(subscription.trial_end) if subscription.trial_end else None
    )
    sub, created = proxies.SubscriptionProxy.objects.get_or_create(
        stripe_id=subscription.id,
        defaults=defaults
    )
    if not created:
        for key in defaults:
            setattr(sub, key, defaults[key])
        sub.save()
    return sub

def sync_customer(customer, cu=None):
    if cu is None:
        cu = customer.stripe_customer
    customer.account_balance = utils.convert_amount_for_db(cu.account_balance, cu.currency)
    customer.currency = cu.currency or ""
    customer.delinquent = cu.delinquent
    customer.default_source = cu.default_source or ""
    customer.save()
    for source in cu.sources.data:
        sync_payment_source_from_stripe_data(customer, source)
    for subscription in cu.subscriptions.data:
        sync_subscription_from_stripe_data(customer, subscription)

def sync_invoices_for_customer(customer):
    for invoice in customer.stripe_customer.invoices().data:
        sync_invoice_from_stripe_data(invoice, send_receipt=False)

def sync_charges_for_customer(customer):
    for charge in customer.stripe_customer.charges().data:
        sync_charge_from_stripe_data(charge)

def sync_charge_from_stripe_data(data):
    customer = proxies.CustomerProxy.objects.get(stripe_id=data["customer"])
    obj, _ = proxies.ChargeProxy.objects.get_or_create(
        customer=customer,
        stripe_id=data["id"]
    )
    obj.source = data["source"]["id"]
    obj.currency = data["currency"]
    obj.invoice = next(iter(proxies.InvoiceProxy.objects.filter(stripe_id=data["invoice"])), None)
    obj.amount = utils.convert_amount_for_db(data["amount"], obj.currency)
    obj.paid = data["paid"]
    obj.refunded = data["refunded"]
    obj.captured = data["captured"]
    obj.disputed = data["dispute"] is not None
    obj.charge_created = utils.convert_tstamp(data, "created")
    if data.get("description"):
        obj.description = data["description"]
    if data.get("amount_refunded"):
        obj.amount_refunded = utils.convert_amount_for_db(data["amount_refunded"], obj.currency)
    if data["refunded"]:
        obj.amount_refunded = obj.amount
    obj.save()
    return obj

def fetch_and_sync_invoice(stripe_id, send_receipt=settings.PINAX_STRIPE_SEND_EMAIL_RECEIPTS):
    sync_invoice_from_stripe_data(stripe.Invoice.retrieve(stripe_id))

def sync_invoice_from_stripe_data(stripe_invoice, send_receipt=settings.PINAX_STRIPE_SEND_EMAIL_RECEIPTS):
    c = proxies.CustomerProxy.objects.get(stripe_id=stripe_invoice["customer"])
    period_end = utils.convert_tstamp(stripe_invoice, "period_end")
    period_start = utils.convert_tstamp(stripe_invoice, "period_start")
    date = utils.convert_tstamp(stripe_invoice, "date")
    sub_id = stripe_invoice.get("subscription")

    if stripe_invoice.get("charge"):
        charge = sync_charge_from_stripe_data(stripe.Charge.retrieve(stripe_invoice["charge"]))
        charge.save()
        if send_receipt:
            charge.send_receipt()
    else:
        charge = None

    subscription = sync_subscription_from_stripe_data(c, c.stripe_customer.subscriptions.retrieve(sub_id)) if sub_id else None

    defaults = dict(
        customer=c,
        attempted=stripe_invoice["attempted"],
        attempt_count=stripe_invoice["attempt_count"],
        amount_due=utils.convert_amount_for_db(stripe_invoice["amount_due"], stripe_invoice["currency"]),
        closed=stripe_invoice["closed"],
        paid=stripe_invoice["paid"],
        period_end=period_end,
        period_start=period_start,
        subtotal=utils.convert_amount_for_db(stripe_invoice["subtotal"], stripe_invoice["currency"]),
        total=utils.convert_amount_for_db(stripe_invoice["total"], stripe_invoice["currency"]),
        currency=stripe_invoice["currency"],
        date=date,
        charge=charge,
        subscription=subscription
    )
    invoice, created = proxies.InvoiceProxy.objects.get_or_create(
        stripe_id=stripe_invoice["id"],
        defaults=defaults
    )
    if charge is not None:
        charge.invoice = invoice
        charge.save()
    if not created:
        for key in defaults:
            setattr(invoice, key, defaults[key])
        invoice.save()

    for item in stripe_invoice["lines"].get("data", []):
        period_end = utils.convert_tstamp(item["period"], "end")
        period_start = utils.convert_tstamp(item["period"], "start")

        if item.get("plan"):
            plan = proxies.PlanProxy.objects.get(stripe_id=item["plan"]["id"])
        else:
            plan = None

        defaults = dict(
            amount=utils.convert_amount_for_db(item["amount"], item["currency"]),
            currency=item["currency"],
            proration=item["proration"],
            description=item.get("description") or "",
            line_type=item["type"],
            plan=plan,
            period_start=period_start,
            period_end=period_end,
            quantity=item.get("quantity")
        )
        inv_item, inv_item_created = invoice.items.get_or_create(
            stripe_id=item["id"],
            defaults=defaults
        )
        if not inv_item_created:
            for key in defaults:
                setattr(inv_item, key, defaults[key])
            inv_item.save()
    return invoice
<commit_msg>Pass the send_receipt argument through<commit_after>import stripe

from ..conf import settings
from .. import utils
from .. import proxies

def sync_plans():
    for plan in stripe.Plan.all().data:
        defaults = dict(
            amount=utils.convert_amount_for_db(plan.amount, plan.currency),
            currency=plan.currency or "",
            interval=plan.interval,
            interval_count=plan.interval_count,
            name=plan.name,
            statement_descriptor=plan.statement_descriptor or "",
            trial_period_days=plan.trial_period_days
        )
        obj, created = proxies.PlanProxy.objects.get_or_create(
            stripe_id=plan.id,
            defaults=defaults
        )
        if not created:
            for key in defaults:
                setattr(obj, key, defaults[key])
            obj.save()

def sync_payment_source_from_stripe_data(customer, source):
    if source["id"].startswith("card_"):
        defaults = dict(
            customer=customer,
            name=source["name"] or "",
            address_line_1=source["address_line1"] or "",
            address_line_1_check=source["address_line1_check"] or "",
            address_line_2=source["address_line2"] or "",
            address_city=source["address_city"] or "",
            address_state=source["address_state"] or "",
            address_country=source["address_country"] or "",
            address_zip=source["address_zip"] or "",
            address_zip_check=source["address_zip_check"] or "",
            brand=source["brand"],
            country=source["country"],
            cvc_check=source["cvc_check"],
            dynamic_last4=source["dynamic_last4"] or "",
            exp_month=source["exp_month"],
            exp_year=source["exp_year"],
            funding=source["funding"] or "",
            last4=source["last4"] or "",
            fingerprint=source["fingerprint"] or ""
        )
        card, created = proxies.CardProxy.objects.get_or_create(
            stripe_id=source["id"],
            defaults=defaults
        )
        if not created:
            for key in defaults:
                setattr(card, key, defaults[key])
            card.save()
    else:
        defaults = dict(
            customer=customer,
            active=source["active"],
            amount=utils.conver_amount_for_db(source["amount"], source.currency),
            amount_received=utils.convert_amount_for_db(source["amount_received"], source.currency),
            bitcoin_amount=source["bitcoin_amount"],
            bitcoin_amount_received=source["bitcoin_amount_received"],
            bitcoin_uri=source["bitcoin_uri"],
            currency=source["currency"],
            description=source["description"],
            email=source["email"],
            filled=source["filled"],
            inbound_address=source["inbound_address"],
            payment=source["payment"],
            refund_address=source["refund_address"],
            uncaptured_funds=source["uncaptured_funds"],
            used_for_payment=source["used_for_payment"]
        )
        receiver, created = proxies.BitcoinRecieverProxy.objects.get_or_create(
            stripe_id=source["id"],
            defaults=defaults
        )
        if not created:
            for key in defaults:
                setattr(receiver, key, defaults[key])
            receiver.save()

def sync_subscription_from_stripe_data(customer, subscription):
    defaults = dict(
        customer=customer,
        application_fee_percent=subscription.application_fee_percent,
        cancel_at_period_end=subscription.cancel_at_period_end,
        canceled_at=utils.convert_tstamp(subscription.canceled_at),
        current_period_start=utils.convert_tstamp(subscription.current_period_start),
        current_period_end=utils.convert_tstamp(subscription.current_period_end),
        ended_at=utils.convert_tstamp(subscription.ended_at),
        plan=proxies.PlanProxy.objects.get(stripe_id=subscription.plan.id),
        quantity=subscription.quantity,
        start=utils.convert_tstamp(subscription.start),
        status=subscription.status,
        trial_start=utils.convert_tstamp(subscription.trial_start) if subscription.trial_start else None,
        trial_end=utils.convert_tstamp(subscription.trial_end) if subscription.trial_end else None
    )
    sub, created = proxies.SubscriptionProxy.objects.get_or_create(
        stripe_id=subscription.id,
        defaults=defaults
    )
    if not created:
        for key in defaults:
            setattr(sub, key, defaults[key])
        sub.save()
    return sub

def sync_customer(customer, cu=None):
    if cu is None:
        cu = customer.stripe_customer
    customer.account_balance = utils.convert_amount_for_db(cu.account_balance, cu.currency)
    customer.currency = cu.currency or ""
    customer.delinquent = cu.delinquent
    customer.default_source = cu.default_source or ""
    customer.save()
    for source in cu.sources.data:
        sync_payment_source_from_stripe_data(customer, source)
    for subscription in cu.subscriptions.data:
        sync_subscription_from_stripe_data(customer, subscription)

def sync_invoices_for_customer(customer):
    for invoice in customer.stripe_customer.invoices().data:
        sync_invoice_from_stripe_data(invoice, send_receipt=False)

def sync_charges_for_customer(customer):
    for charge in customer.stripe_customer.charges().data:
        sync_charge_from_stripe_data(charge)

def sync_charge_from_stripe_data(data):
    customer = proxies.CustomerProxy.objects.get(stripe_id=data["customer"])
    obj, _ = proxies.ChargeProxy.objects.get_or_create(
        customer=customer,
        stripe_id=data["id"]
    )
    obj.source = data["source"]["id"]
    obj.currency = data["currency"]
    obj.invoice = next(iter(proxies.InvoiceProxy.objects.filter(stripe_id=data["invoice"])), None)
    obj.amount = utils.convert_amount_for_db(data["amount"], obj.currency)
    obj.paid = data["paid"]
    obj.refunded = data["refunded"]
    obj.captured = data["captured"]
    obj.disputed = data["dispute"] is not None
    obj.charge_created = utils.convert_tstamp(data, "created")
    if data.get("description"):
        obj.description = data["description"]
    if data.get("amount_refunded"):
        obj.amount_refunded = utils.convert_amount_for_db(data["amount_refunded"], obj.currency)
    if data["refunded"]:
        obj.amount_refunded = obj.amount
    obj.save()
    return obj

def fetch_and_sync_invoice(stripe_id, send_receipt=settings.PINAX_STRIPE_SEND_EMAIL_RECEIPTS):
    sync_invoice_from_stripe_data(stripe.Invoice.retrieve(stripe_id), send_receipt=send_receipt)

def sync_invoice_from_stripe_data(stripe_invoice, send_receipt=settings.PINAX_STRIPE_SEND_EMAIL_RECEIPTS):
    c = proxies.CustomerProxy.objects.get(stripe_id=stripe_invoice["customer"])
    period_end = utils.convert_tstamp(stripe_invoice, "period_end")
    period_start = utils.convert_tstamp(stripe_invoice, "period_start")
    date = utils.convert_tstamp(stripe_invoice, "date")
    sub_id = stripe_invoice.get("subscription")

    if stripe_invoice.get("charge"):
        charge = sync_charge_from_stripe_data(stripe.Charge.retrieve(stripe_invoice["charge"]))
        charge.save()
        if send_receipt:
            charge.send_receipt()
    else:
        charge = None

    subscription = sync_subscription_from_stripe_data(c, c.stripe_customer.subscriptions.retrieve(sub_id)) if sub_id else None

    defaults = dict(
        customer=c,
        attempted=stripe_invoice["attempted"],
        attempt_count=stripe_invoice["attempt_count"],
        amount_due=utils.convert_amount_for_db(stripe_invoice["amount_due"], stripe_invoice["currency"]),
        closed=stripe_invoice["closed"],
        paid=stripe_invoice["paid"],
        period_end=period_end,
        period_start=period_start,
        subtotal=utils.convert_amount_for_db(stripe_invoice["subtotal"], stripe_invoice["currency"]),
        total=utils.convert_amount_for_db(stripe_invoice["total"], stripe_invoice["currency"]),
        currency=stripe_invoice["currency"],
        date=date,
        charge=charge,
        subscription=subscription
    )
    invoice, created = proxies.InvoiceProxy.objects.get_or_create(
        stripe_id=stripe_invoice["id"],
        defaults=defaults
    )
    if charge is not None:
        charge.invoice = invoice
        charge.save()
    if not created:
        for key in defaults:
            setattr(invoice, key, defaults[key])
        invoice.save()

    for item in stripe_invoice["lines"].get("data", []):
        period_end = utils.convert_tstamp(item["period"], "end")
        period_start = utils.convert_tstamp(item["period"], "start")

        if item.get("plan"):
            plan = proxies.PlanProxy.objects.get(stripe_id=item["plan"]["id"])
        else:
            plan = None

        defaults = dict(
            amount=utils.convert_amount_for_db(item["amount"], item["currency"]),
            currency=item["currency"],
            proration=item["proration"],
            description=item.get("description") or "",
            line_type=item["type"],
            plan=plan,
            period_start=period_start,
            period_end=period_end,
            quantity=item.get("quantity")
        )
        inv_item, inv_item_created = invoice.items.get_or_create(
            stripe_id=item["id"],
            defaults=defaults
        )
        if not inv_item_created:
            for key in defaults:
                setattr(inv_item, key, defaults[key])
            inv_item.save()
    return invoice
<|endoftext|>


<commit_before>import json
from decimal import Decimal

from shapely.geometry import mapping

from c3nav.mapdata.utils.geometry import assert_multipolygon

def polygon_scad(polygon, height):
    results = [_polygon_scad(polygon, height=height) for polygon in assert_multipolygon(polygon)]
    if not results:
        raise ValueError
    if len(results) == 1:
        return results[0]
    return 'union() {\n'+add_indent(''.join(results))+'}\n'

def _polygon_scad(polygon, height):
    coords = mapping(polygon.simplify(0.001))['coordinates']

    interior = coords[0]
    exteriors = coords[1:]
    result = 'linear_extrude(height=%.2f, center=false, convexity=20) ' % height
    result += _ring_scad(interior)
    if exteriors:
        result = 'difference() {\n'+add_indent(result)
        result += '    translate([0, 0, -0.01]) {\n'
        for ring in exteriors:
            result += '        linear_extrude(height=%.2f, center=false, convexity=20) ' % (height+Decimal('0.02'))
            result += _ring_scad(ring)
        result += '    }\n'
        result += '}\n'
    return result

def _ring_scad(coords):
    return 'polygon(points='+json.dumps(coords[:-1], separators=(',', ':'))+', convexity=20);\n'

def add_indent(text):
    return '    '+text.replace('\n', '\n    ')[:(-4 if text.endswith('\n') else None)]
<commit_msg>exterior/interior<commit_after>import json
from decimal import Decimal

from shapely.geometry import mapping

from c3nav.mapdata.utils.geometry import assert_multipolygon

def polygon_scad(polygon, height):
    results = [_polygon_scad(polygon, height=height) for polygon in assert_multipolygon(polygon)]
    if not results:
        raise ValueError
    if len(results) == 1:
        return results[0]
    return 'union() {\n'+add_indent(''.join(results))+'}\n'

def _polygon_scad(polygon, height):
    coords = mapping(polygon.simplify(0.001))['coordinates']

    exterior = coords[0]
    interiors = coords[1:]
    result = 'linear_extrude(height=%.2f, center=false, convexity=20) ' % height
    result += _ring_scad(exterior)
    if interiors:
        result = 'difference() {\n'+add_indent(result)
        result += '    translate([0, 0, -0.01]) {\n'
        for ring in interiors:
            result += '        linear_extrude(height=%.2f, center=false, convexity=20) ' % (height+Decimal('0.02'))
            result += _ring_scad(ring)
        result += '    }\n'
        result += '}\n'
    return result

def _ring_scad(coords):
    return 'polygon(points='+json.dumps(coords[:-1], separators=(',', ':'))+', convexity=20);\n'

def add_indent(text):
    return '    '+text.replace('\n', '\n    ')[:(-4 if text.endswith('\n') else None)]
<|endoftext|>


<commit_before><commit_msg>updated comments<commit_after><|endoftext|>


<commit_before>import itertools
import unittest

from chainlet import ChainLink, genlet, funclet
from chainlet.dataflow import joinlet, forklet, NoOp
from chainlet.protolink import printlet
import chainlet._debug

from chainlet_unittests.utility import Adder, produce, abort_return, abort_swallow, AbortEvery, ReturnEvery

class Decorators(unittest.TestCase):
    def test_chainlink(self):
        """Decorate: class Join(ChainLink) ..."""
        @joinlet
        class Join(ChainLink):
            def chainlet_send(self, value=None):
                return sum(value)

        @forklet
        class Fork(ChainLink):
            def chainlet_send(self, value=None):
                return [value]

        self._test_flow(join_type=Join, fork_type=Fork)

    def test_genlet(self):
        """Decorate: @genlet ..."""
        @joinlet
        @genlet
        def join():
            value = yield
            while True:
                value = yield sum(value)

        @forklet
        @genlet
        def fork():
            value = yield
            while True:
                value = yield [value]

        self._test_flow(join_type=join, fork_type=fork)

    def test_funclet(self):
        """Decorate: @funclet ..."""
        @joinlet
        @funclet
        def join(value):
            return sum(value)

        @forklet
        @funclet
        def fork(value):
            return [value]

        self._test_flow(join_type=join, fork_type=fork)

    def _test_flow(self, join_type, fork_type):
        join_chain = (produce([1, 1, 1]), produce([2, 2, 2])) >> join_type()
        self.assertEqual(list(join_chain), [3, 3, 3])
        fork_chain = produce([1, 1, 1]) >> fork_type()
        self.assertEqual(list(fork_chain), [[1], [1], [1]])
        fork_join_chain = produce([1, 1, 1]) >> fork_type() >> join_type()
        self.assertEqual(list(fork_join_chain), [1, 1, 1])
<commit_msg>removed debug code from unittests<commit_after>import unittest

from chainlet import ChainLink, genlet, funclet
from chainlet.dataflow import joinlet, forklet

from chainlet_unittests.utility import produce

class Decorators(unittest.TestCase):
    def test_chainlink(self):
        """Decorate: class Join(ChainLink) ..."""
        @joinlet
        class Join(ChainLink):
            def chainlet_send(self, value=None):
                return sum(value)

        @forklet
        class Fork(ChainLink):
            def chainlet_send(self, value=None):
                return [value]

        self._test_flow(join_type=Join, fork_type=Fork)

    def test_genlet(self):
        """Decorate: @genlet ..."""
        @joinlet
        @genlet
        def join():
            value = yield
            while True:
                value = yield sum(value)

        @forklet
        @genlet
        def fork():
            value = yield
            while True:
                value = yield [value]

        self._test_flow(join_type=join, fork_type=fork)

    def test_funclet(self):
        """Decorate: @funclet ..."""
        @joinlet
        @funclet
        def join(value):
            return sum(value)

        @forklet
        @funclet
        def fork(value):
            return [value]

        self._test_flow(join_type=join, fork_type=fork)

    def _test_flow(self, join_type, fork_type):
        join_chain = (produce([1, 1, 1]), produce([2, 2, 2])) >> join_type()
        self.assertEqual(list(join_chain), [3, 3, 3])
        fork_chain = produce([1, 1, 1]) >> fork_type()
        self.assertEqual(list(fork_chain), [[1], [1], [1]])
        fork_join_chain = produce([1, 1, 1]) >> fork_type() >> join_type()
        self.assertEqual(list(fork_join_chain), [1, 1, 1])
<|endoftext|>


<commit_before>import itertools
import uuid
from collections import namedtuple
from xml.etree import cElementTree as ElementTree

from django.core.cache import cache

from casexml.apps.case.mock import CaseBlock
from dimagi.utils.couch import CriticalSection

from corehq.apps.app_manager.const import USERCASE_TYPE
from corehq.apps.callcenter.const import CALLCENTER_USER
from corehq.apps.export.tasks import add_inferred_export_properties
from corehq.apps.hqcase.utils import submit_case_blocks
from corehq.apps.locations.models import SQLLocation
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors

class _UserCaseHelper(object):

    CASE_SOURCE_ID = __name__ + "._UserCaseHelper."

    def __init__(self, domain, owner_id):
        self.domain = domain
        self.owner_id = owner_id
        self._case_block_to_submit = None
        self._tasks_to_trigger = []

    def commit(self):
        with CriticalSection(get_sync_lock_key(self.owner_id)):
            if self._case_block_to_submit:
                submit_case_blocks(
                    self._case_block_to_submit.as_text(), self.domain, device_id=self.CASE_SOURCE_ID)
            for task, task_args in self._tasks_to_trigger:
                task.delay((task_args))

    @staticmethod
    def commit_multiple(helpers):
        case_blocks = itertools.chain(
            [h._case_block_to_submit for h in helpers if h and h._case_block_to_submit])
        submit_case_blocks(case_blocks, helpers[0].domain, device_id="sync_user_case")
        for helper in helpers:
            for task, task_args in helper._tasks_to_trigger:
                task.delay((task_args))

    @staticmethod
    def re_open_case(case):
        transactions = case.get_closing_transactions()
        for transaction in transactions:
            transaction.form.archive()

    def create_user_case(self, commcare_user, fields):
        self._case_block_to_submit = CaseBlock(
            create=True,
            case_id=uuid.uuid4().hex,
            owner_id=fields.pop('owner_id'),
            user_id=CALLCENTER_USER,
            case_type=fields.pop('case_type'),
            case_name=fields.pop('name', None),
            update=fields
        )
        self._user_case_changed(fields)

    def update_user_case(self, case, fields, close):
        self._case_block_to_submit = CaseBlock(
            create=False,
            case_id=case.case_id,
            owner_id=fields.pop('owner_id', CaseBlock.undefined),
            case_type=fields.pop('case_type', CaseBlock.undefined),
            case_name=fields.pop('name', CaseBlock.undefined),
            close=close,
            update=fields
        )
        self._user_case_changed(fields)

    def _user_case_changed(self, fields):
        field_names = list(fields)
        if _domain_has_new_fields(self.domain, field_names):
            self._tasks_to_trigger = (add_inferred_export_properties, (
                'UserSave',
                self.domain,
                USERCASE_TYPE,
                field_names,
            ))

def _domain_has_new_fields(domain, field_names):
    cache_key = 'user_case_fields_{}'.format(domain)
    cached_fields = cache.get(cache_key)
    new_field_set = set(field_names)
    if cached_fields != new_field_set:
        cache.set(cache_key, new_field_set)
        return True

    return False

def _get_sync_user_case_helper(commcare_user, case_type, owner_id, case=None):
    domain = commcare_user.domain
    fields = _get_user_case_fields(commcare_user, case_type, owner_id)
    case = case or CaseAccessors(domain).get_case_by_domain_hq_user_id(commcare_user._id, case_type)
    close = commcare_user.to_be_deleted() or not commcare_user.is_active
    user_case_helper = _UserCaseHelper(domain, owner_id)

    def case_should_be_reopened(case, user_case_should_be_closed):
        return case and case.closed and not user_case_should_be_closed

    if not case:
        user_case_helper.create_user_case(commcare_user, fields)
    else:
        if case_should_be_reopened(case, close):
            user_case_helper.re_open_case(case)
        changed_fields = _get_changed_fields(case, fields)
        close_case = close and not case.closed
        if changed_fields or close_case:
            user_case_helper.update_user_case(case, changed_fields, close_case)
    return user_case_helper

def _get_user_case_fields(commcare_user, case_type, owner_id):

    def valid_element_name(name):
        try:
            ElementTree.fromstring('<{}/>'.format(name))
            return True
        except ElementTree.ParseError:
            return False

    # remove any keys that aren't valid XML element names
    fields = {k: v for k, v in commcare_user.user_data.items() if
              valid_element_name(k)}
    # language or phone_number can be null and will break
    # case submission
    fields.update({
        'name': commcare_user.name or commcare_user.raw_username,
        'username': commcare_user.raw_username,
        'email': commcare_user.email,
        'language': commcare_user.language or '',
        'phone_number': commcare_user.phone_number or '',
        'last_device_id_used': commcare_user.devices[0].device_id if commcare_user.devices else '',
        'owner_id': owner_id,
        'case_type': case_type,
        'hq_user_id': commcare_user.get_id,
        'first_name': commcare_user.first_name or '',
        'last_name': commcare_user.last_name or '',
    })

    return fields

def _get_changed_fields(case, fields):
    def _to_unicode(val):
        if isinstance(val, bytes):
            return val.decode('utf8')
        elif not isinstance(val, str):
            return str(val)
        return val

    def _not_same(val1, val2):
        return _to_unicode(val1) != _to_unicode(val2)

    hq_fields = {
        'name': 'name',
        'case_type': 'type',
        'owner_id': 'owner_id'
    }
    changed_fields = {}
    props = case.dynamic_case_properties()
    for field, value in fields.items():
        if field not in hq_fields and _not_same(props.get(field), value):
            changed_fields[field] = value

    for field, attrib in hq_fields.items():
        if _not_same(getattr(case, attrib), fields[field]):
            changed_fields[field] = fields[field]

    return changed_fields

def get_sync_lock_key(user_id):
    return ["sync_user_case_for_%s" % user_id]

def sync_call_center_user_case(user):
    helper = get_call_center_case_helper(user)
    if helper:
        helper.commit()

def get_call_center_case_helper(user):
    config = user.project.call_center_config
    if config.enabled and config.config_is_valid():
        case, owner_id = _get_call_center_case_and_owner(user)
        helper = _get_sync_user_case_helper(user, config.case_type, owner_id, case)
        return helper

CallCenterCaseAndOwner = namedtuple('CallCenterCaseAndOwner', 'case owner_id')

def _get_call_center_case_and_owner(user):
    """
    Return the appropriate owner id for the given users call center case.
    """
    config = user.project.call_center_config
    case = CaseAccessors(user.domain).get_case_by_domain_hq_user_id(
        user._id, config.case_type
    )
    if config.use_user_location_as_owner:
        owner_id = _call_center_location_owner(user, config.user_location_ancestor_level)
    elif case and case.owner_id:
        owner_id = case.owner_id
    else:
        owner_id = config.case_owner_id
    return CallCenterCaseAndOwner(case, owner_id)

def _call_center_location_owner(user, ancestor_level):
    if user.location_id is None:
        return ""
    if ancestor_level == 0:
        owner_id = user.location_id
    else:
        location = SQLLocation.objects.get(location_id=user.location_id)
        ancestors = location.get_ancestors(ascending=True, include_self=True).only("location_id")
        try:
            owner_id = ancestors[ancestor_level].location_id
        except IndexError:
            owner_id = ancestors.last().location_id
    return owner_id

def sync_usercase(user):
    helper = get_sync_usercase_helper()
    if helper:
        helper.commit()

def get_sync_usercase_helper(user):
    if user.project.usercase_enabled:
        return _get_sync_user_case_helper(
            user,
            USERCASE_TYPE,
            user.get_id
        )

def sync_user_cases(user):
    """
    Each time a CommCareUser is saved this method gets called and creates or updates
    a case associated with the user with the user's details.

    This is also called to create user cases when the usercase is used for the
    first time.
    """
    with CriticalSection(get_sync_lock_key(user._id)):
        helpers = [get_sync_usercase_helper(), get_call_center_case_helper()]
        _UserCaseHelper.commit_multiple(helpers)
<commit_msg>As text<commit_after>import itertools
import uuid
from collections import namedtuple
from xml.etree import cElementTree as ElementTree

from django.core.cache import cache

from casexml.apps.case.mock import CaseBlock
from dimagi.utils.couch import CriticalSection

from corehq.apps.app_manager.const import USERCASE_TYPE
from corehq.apps.callcenter.const import CALLCENTER_USER
from corehq.apps.export.tasks import add_inferred_export_properties
from corehq.apps.hqcase.utils import submit_case_blocks
from corehq.apps.locations.models import SQLLocation
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors

class _UserCaseHelper(object):

    CASE_SOURCE_ID = __name__ + "._UserCaseHelper."

    def __init__(self, domain, owner_id):
        self.domain = domain
        self.owner_id = owner_id
        self._case_block_to_submit = None
        self._tasks_to_trigger = []

    def commit(self):
        with CriticalSection(get_sync_lock_key(self.owner_id)):
            if self._case_block_to_submit:
                submit_case_blocks(
                    self._case_block_to_submit.as_text(), self.domain, device_id=self.CASE_SOURCE_ID)
            for task, task_args in self._tasks_to_trigger:
                task.delay((task_args))

    @staticmethod
    def commit_multiple(helpers):
        case_blocks = itertools.chain(
            [h._case_block_to_submit.as_text() for h in helpers if h and h._case_block_to_submit])
        submit_case_blocks(case_blocks, helpers[0].domain, device_id="sync_user_case")
        for helper in helpers:
            for task, task_args in helper._tasks_to_trigger:
                task.delay((task_args))

    @staticmethod
    def re_open_case(case):
        transactions = case.get_closing_transactions()
        for transaction in transactions:
            transaction.form.archive()

    def create_user_case(self, commcare_user, fields):
        self._case_block_to_submit = CaseBlock(
            create=True,
            case_id=uuid.uuid4().hex,
            owner_id=fields.pop('owner_id'),
            user_id=CALLCENTER_USER,
            case_type=fields.pop('case_type'),
            case_name=fields.pop('name', None),
            update=fields
        )
        self._user_case_changed(fields)

    def update_user_case(self, case, fields, close):
        self._case_block_to_submit = CaseBlock(
            create=False,
            case_id=case.case_id,
            owner_id=fields.pop('owner_id', CaseBlock.undefined),
            case_type=fields.pop('case_type', CaseBlock.undefined),
            case_name=fields.pop('name', CaseBlock.undefined),
            close=close,
            update=fields
        )
        self._user_case_changed(fields)

    def _user_case_changed(self, fields):
        field_names = list(fields)
        if _domain_has_new_fields(self.domain, field_names):
            self._tasks_to_trigger = (add_inferred_export_properties, (
                'UserSave',
                self.domain,
                USERCASE_TYPE,
                field_names,
            ))

def _domain_has_new_fields(domain, field_names):
    cache_key = 'user_case_fields_{}'.format(domain)
    cached_fields = cache.get(cache_key)
    new_field_set = set(field_names)
    if cached_fields != new_field_set:
        cache.set(cache_key, new_field_set)
        return True

    return False

def _get_sync_user_case_helper(commcare_user, case_type, owner_id, case=None):
    domain = commcare_user.domain
    fields = _get_user_case_fields(commcare_user, case_type, owner_id)
    case = case or CaseAccessors(domain).get_case_by_domain_hq_user_id(commcare_user._id, case_type)
    close = commcare_user.to_be_deleted() or not commcare_user.is_active
    user_case_helper = _UserCaseHelper(domain, owner_id)

    def case_should_be_reopened(case, user_case_should_be_closed):
        return case and case.closed and not user_case_should_be_closed

    if not case:
        user_case_helper.create_user_case(commcare_user, fields)
    else:
        if case_should_be_reopened(case, close):
            user_case_helper.re_open_case(case)
        changed_fields = _get_changed_fields(case, fields)
        close_case = close and not case.closed
        if changed_fields or close_case:
            user_case_helper.update_user_case(case, changed_fields, close_case)
    return user_case_helper

def _get_user_case_fields(commcare_user, case_type, owner_id):

    def valid_element_name(name):
        try:
            ElementTree.fromstring('<{}/>'.format(name))
            return True
        except ElementTree.ParseError:
            return False

    # remove any keys that aren't valid XML element names
    fields = {k: v for k, v in commcare_user.user_data.items() if
              valid_element_name(k)}
    # language or phone_number can be null and will break
    # case submission
    fields.update({
        'name': commcare_user.name or commcare_user.raw_username,
        'username': commcare_user.raw_username,
        'email': commcare_user.email,
        'language': commcare_user.language or '',
        'phone_number': commcare_user.phone_number or '',
        'last_device_id_used': commcare_user.devices[0].device_id if commcare_user.devices else '',
        'owner_id': owner_id,
        'case_type': case_type,
        'hq_user_id': commcare_user.get_id,
        'first_name': commcare_user.first_name or '',
        'last_name': commcare_user.last_name or '',
    })

    return fields

def _get_changed_fields(case, fields):
    def _to_unicode(val):
        if isinstance(val, bytes):
            return val.decode('utf8')
        elif not isinstance(val, str):
            return str(val)
        return val

    def _not_same(val1, val2):
        return _to_unicode(val1) != _to_unicode(val2)

    hq_fields = {
        'name': 'name',
        'case_type': 'type',
        'owner_id': 'owner_id'
    }
    changed_fields = {}
    props = case.dynamic_case_properties()
    for field, value in fields.items():
        if field not in hq_fields and _not_same(props.get(field), value):
            changed_fields[field] = value

    for field, attrib in hq_fields.items():
        if _not_same(getattr(case, attrib), fields[field]):
            changed_fields[field] = fields[field]

    return changed_fields

def get_sync_lock_key(user_id):
    return ["sync_user_case_for_%s" % user_id]

def sync_call_center_user_case(user):
    helper = get_call_center_case_helper(user)
    if helper:
        helper.commit()

def get_call_center_case_helper(user):
    config = user.project.call_center_config
    if config.enabled and config.config_is_valid():
        case, owner_id = _get_call_center_case_and_owner(user)
        helper = _get_sync_user_case_helper(user, config.case_type, owner_id, case)
        return helper

CallCenterCaseAndOwner = namedtuple('CallCenterCaseAndOwner', 'case owner_id')

def _get_call_center_case_and_owner(user):
    """
    Return the appropriate owner id for the given users call center case.
    """
    config = user.project.call_center_config
    case = CaseAccessors(user.domain).get_case_by_domain_hq_user_id(
        user._id, config.case_type
    )
    if config.use_user_location_as_owner:
        owner_id = _call_center_location_owner(user, config.user_location_ancestor_level)
    elif case and case.owner_id:
        owner_id = case.owner_id
    else:
        owner_id = config.case_owner_id
    return CallCenterCaseAndOwner(case, owner_id)

def _call_center_location_owner(user, ancestor_level):
    if user.location_id is None:
        return ""
    if ancestor_level == 0:
        owner_id = user.location_id
    else:
        location = SQLLocation.objects.get(location_id=user.location_id)
        ancestors = location.get_ancestors(ascending=True, include_self=True).only("location_id")
        try:
            owner_id = ancestors[ancestor_level].location_id
        except IndexError:
            owner_id = ancestors.last().location_id
    return owner_id

def sync_usercase(user):
    helper = get_sync_usercase_helper()
    if helper:
        helper.commit()

def get_sync_usercase_helper(user):
    if user.project.usercase_enabled:
        return _get_sync_user_case_helper(
            user,
            USERCASE_TYPE,
            user.get_id
        )

def sync_user_cases(user):
    """
    Each time a CommCareUser is saved this method gets called and creates or updates
    a case associated with the user with the user's details.

    This is also called to create user cases when the usercase is used for the
    first time.
    """
    with CriticalSection(get_sync_lock_key(user._id)):
        helpers = [get_sync_usercase_helper(), get_call_center_case_helper()]
        _UserCaseHelper.commit_multiple(helpers)
<|endoftext|>


<commit_before>#04/24/2012;  EM:  added apogee vacuum, and ln2level;
# change font for title;

import RO.Wdg
import TUI.Models
import string
from datetime import datetime

class ScriptClass(object):
    def __init__(self, sr):
        # if True, run in debug-only mode
        # if False, real time run
        sr.debug = False
        sr.master.winfo_toplevel().wm_resizable(True, True)
        self.logWdg = RO.Wdg.LogWdg(
            master=sr.master,
            width=40,
            height =35,
        )
        self.logWdg.grid(row=0, column=0, sticky="news")
        sr.master.rowconfigure(0, weight=1)
        sr.master.columnconfigure(0, weight=1)

        self.blueWarn=RO.Constants.sevWarning
        self.redWarn=RO.Constants.sevError
        self.apogeeModel = TUI.Models.getModel("apogee")

    def run(self,sr):
      defstr='n/a'; defval=0

      ff=("Times", "17", "bold italic")
      fs="12"   # font size
      ft="Monaco" # "Courier"  #"Menlo"  # font type
      self.logWdg.text.tag_config("cur", font=(ft,fs,"bold"))

      print "-----status---"
      mcpModel = TUI.Models.getModel("mcp")
      guiderModel = TUI.Models.getModel("guider")
      bossModel = TUI.Models.getModel("boss")
      tccModel = TUI.Models.getModel("tcc")
      gcameraModel = TUI.Models.getModel("gcamera")
      apoModel = TUI.Models.getModel("apo")

      self.logWdg.addMsg("-- Status --  %s  " % (str(datetime.utcnow())), tags=["cur"])
   #   self.logWdg.addMsg(" ")

      yield sr.waitCmd(actor="apo", cmdStr="status",
                 keyVars=[apoModel.encl25m], checkFail=False)
      if sr.value.didFail: encl=-1
      else: encl=sr.value.getLastKeyVarData(apoModel.encl25m)[0]
      if encl > 0: enclM="open"
      elif encl == 0: enclM="closed"
      else : enclM="n/a"
      self.logWdg.addMsg("Enclosure = %s; " % (enclM))

  #    self.logWdg.addMsg(" ")
      mcpW=[0,0,0,0]
      for i in range(0,4):
           mcpW[i]=sr.getKeyVar(mcpModel.cwPositions, ind=i, defVal='n/a')
      mcpWs=str(mcpW[0])+","+str(mcpW[1])+","+str(mcpW[2])+","+str(mcpW[3])
      self.logWdg.addMsg("cwPositions =  %s  %s  %s  %s;  " %
          (str(mcpW[0]),str(mcpW[1]),str(mcpW[2]),str(mcpW[3])))

      mcpInst = sr.getKeyVar(mcpModel.instrumentNum, ind=0, defVal='n/a')
      self.logWdg.addMsg("MCP instr =  %s  (mounted);  "  % (str(mcpInst)))

      ctLoad=guiderModel.cartridgeLoaded
      gc = sr.getKeyVar(ctLoad, ind=0, defVal='n/a')
      gp = sr.getKeyVar(ctLoad, ind=1, defVal='n/a')
      gs = sr.getKeyVar(ctLoad, ind=2, defVal='n/a')
      ss="Guider cart= %s,  plate= %s,  side= %s (loaded)"  % (str(gc),str(gp),str(gs))
      if mcpInst != gc:  self.logWdg.addMsg("%s;  " % (ss), severity=self.redWarn)
      else: self.logWdg.addMsg("%s;  " % (ss), severity=0 )

      self.logWdg.addMsg(" ")
      motPos=[0,0,0,0,0,0]
      for i in range(0,6):
         motPos[i]=sr.getKeyVar(bossModel.motorPosition, ind=i, defVal=0)
      self.logWdg.addMsg("motorPosition")
      self.logWdg.addMsg("%s sp1:  %6i,  %6i,  %6i;  " % (" "*4, motPos[0],motPos[1],motPos[2]))
      self.logWdg.addMsg("%s sp2:  %6i,  %6i,  %6i;  " % (" "*4,motPos[3],motPos[4],motPos[5]))

      self.logWdg.addMsg(" ")
      yield sr.waitCmd(actor="boss", cmdStr="status",
                 keyVars=[bossModel.sp1Temp,bossModel.sp2Temp], checkFail=False)
      if sr.value.didFail:
          sp1T="n/a"; sp2T="n/a"
      else:
         sp1T=sr.value.getLastKeyVarData(bossModel.sp1Temp)[0]
         sp2T=sr.value.getLastKeyVarData(bossModel.sp2Temp)[0]
      self.logWdg.addMsg("Median spectrographs temperatures:")
      self.logWdg.addMsg("%s Tsp1= %s,  Tsp2= %s;  " % (" "*4,str(sp1T),str(sp2T)))
      airT=sr.getKeyVar(tccModel.airTemp, ind=0, defVal='n/a')
      self.logWdg.addMsg("%s Outside air temperature= %s;  " % (" "*4,str(airT)))

    #  primT=sr.getKeyVar(tccModel.primF_BFTemp, ind=0)
    #  secT=sr.getKeyVar(tccModel.secF_BFTemp, ind=0)
    #  self.logWdg.addMsg("Temp prim="+str(primT)+"C   sec="+str(secT)+"C")

  #    self.logWdg.addMsg(" ")
      self.logWdg.addMsg("%s" % ('-'*30))
      bossModel = TUI.Models.getModel("boss")
      sp1r0N=sr.getKeyVar(bossModel.SP1R0CCDTempNom, ind=0, defVal=0)
      sp1b2N=sr.getKeyVar(bossModel.SP1B2CCDTempNom, ind=0, defVal=0)
      sp2r0N=sr.getKeyVar(bossModel.SP2R0CCDTempNom, ind=0, defVal=0)
      sp2b2N=sr.getKeyVar(bossModel.SP2B2CCDTempNom, ind=0, defVal=0)
      sp1r0=sr.getKeyVar(bossModel.SP1R0CCDTempRead, ind=0, defVal=0)

      sp1b2=sr.getKeyVar(bossModel.SP1B2CCDTempRead, ind=0, defVal=0)
      sp2r0=sr.getKeyVar(bossModel.SP2R0CCDTempRead, ind=0, defVal=0)
      sp2b2=sr.getKeyVar(bossModel.SP2B2CCDTempRead, ind=0, defVal=0)
      def sevf(rr,nom,vv):
          if abs(rr-nom)>vv: sev=self.redWarn
          else: sev=0
          return sev
      self.logWdg.addMsg("Boss CCD Temp :")
      self.logWdg.addMsg("    sp1r0= %6.1f (%6.1f);  " % (sp1r0, sp1r0N), severity=sevf(sp1r0, sp1r0N,5))
      self.logWdg.addMsg("    sp1b2= %6.1f (%6.1f);  " % (sp1b2, sp1b2N), severity=sevf(sp1b2, sp1b2N,5))
      self.logWdg.addMsg("    sp2r0= %6.1f (%6.1f);  " % (sp2r0, sp2r0N), severity=sevf(sp2r0, sp2r0N,5))
      self.logWdg.addMsg("    sp2b2= %6.1f (%6.1f);  " % (sp2b2, sp2b2N), severity=sevf(sp2b2, sp2b2N,5))

#      self.logWdg.addMsg(" ")
      SP1SecDewPress=sr.getKeyVar(bossModel.SP1SecondaryDewarPress, ind=0, defVal=defval)
      SP2SecDewPress=sr.getKeyVar(bossModel.SP2SecondaryDewarPress, ind=0, defVal=defval)
      self.logWdg.addMsg("%s sp1LN2: %4.1f;  " % (" "*8, SP1SecDewPress),severity=sevf(SP1SecDewPress,10,5))
      self.logWdg.addMsg("%s sp2LN2: %4.1f;  " % (" "*8, SP2SecDewPress), severity=sevf(SP1SecDewPress,10,5))
      self.logWdg.addMsg("%s" % ('-'*30))

   #   self.logWdg.addMsg(" ")
   #   gcamTempN=sr.getKeyVar(gcameraModel.cooler, ind=0)
      gcamTempN=-40.0
      gcamTemp=sr.getKeyVar(gcameraModel.cooler, ind=1, defVal=defval)
  #    self.logWdg.addMsg("gcameraTemp= %5.1f (%5.1f);  " % (gcamTemp, gcamTempN),
      self.logWdg.addMsg("gcameraTemp= %s (%s);  " % (gcamTemp, gcamTempN),
                severity=sevf(gcamTemp,gcamTempN,3))

      secFoc=sr.getKeyVar(tccModel.secFocus, ind=0, defVal=defstr)
      self.logWdg.addMsg("Rel. Focus =  %s;  " % (str(secFoc)))

      ra=sr.getKeyVar(tccModel.objArcOff, ind=0, defVal=[defstr,defstr,defstr,])
      dec=sr.getKeyVar(tccModel.objArcOff, ind=1, defVal=[defstr, defstr])
      def offStr (off):
          off1=str(off)
          off1=string.replace(off1,"PVT","")
          off1=string.replace(off1,"(","")
          off1=string.replace(off1,")","")
          off1=string.replace(off1,"[","")
          off1=string.replace(off1,"]","")
          off1=string.replace(off1,"'","")
          off2,off3=off1.split(None,1)
          off2=string.replace(off2,",","")
          return off2
      self.logWdg.addMsg("objArcOff = %s,  %s;  " % (offStr(ra),offStr(dec)))
      self.logWdg.addMsg("%s" % ('-'*30))
      def sevLevL(rr,lev1,lev2):
          if rr <= lev2: sev=self.redWarn
          elif lev2 < rr <lev1: sev=self.blueWarn
          elif rr >= lev1: sev=0
          else: pass
          return sev

      def sevLevU(rr,lev1,lev2):
          if rr > lev2: sev=self.redWarn
          elif lev1 < rr <lev2: sev=self.blueWarn
          elif rr<lev1: sev=0
          else: pass
          return sev

      vac = sr.getKeyVar(self.apogeeModel.vacuum, ind=0, defVal=defstr)
      ln2Lev =  sr.getKeyVar(self.apogeeModel.ln2Level, ind=0, defVal=defstr)
      if vac > 1.0e-6:  sev=self.redWarn
      else: sev=0
      self.logWdg.addMsg("Apogee: vacuum = %s" % (vac), severity=sev)
      self.logWdg.addMsg("Apogee: ln2Level = %s" %(ln2Lev),severity=sevLevL(ln2Lev,85,70))
      self.logWdg.addMsg("%s" % ('-'*30))

      humidPT=sr.getKeyVar(apoModel.humidPT, ind=0, defVal=defstr)
      self.logWdg.addMsg("humid25m =  %s;  " % (str(humidPT)), severity=sevLevU(humidPT,75,85))
      airTempPT=sr.getKeyVar(apoModel.airTempPT, ind=0, defVal=defstr)
      dpTempPT=sr.getKeyVar(apoModel.dpTempPT, ind=0, defVal=defstr)
      self.logWdg.addMsg("airTemp25m =  %sC,  dpTemp25m =  %sC;  " % (str(airTempPT), str(dpTempPT)))
      try:
          diff=airTempPT-dpTempPT
      except:
          diff=defstr
    #  self.logWdg.addMsg("airTemp25m =  %sC,  dpTemp25m =  %sC;  " % (str(airTempPT), str(dpTempPT)))
      self.logWdg.addMsg("      diff= %sC;  " % (str(diff)),severity=sevLevL(diff,5.0,2.5))

      if encl > 0:
          dir25m=sr.getKeyVar(apoModel.windd25m, ind=0, defVal=defstr)
          wind25m=sr.getKeyVar(apoModel.winds25m, ind=0, defVal=defstr)
          ww=str(wind25m); dd=str(dir25m)
          self.logWdg.addMsg("wind25m = %s mph,  direction = %s;  " %  (str(wind25m),str(dir25m)),
                           severity=sevLevU(wind25m,30,35))
      else:
          self.logWdg.addMsg("wind25m = %s,  direction = %s  "% (defstr, defstr) )

      self.logWdg.addMsg("%s" % ('-'*30))
      self.logWdg.addMsg(" ")

#      yield sr.waitCmd(actor="boss", cmdStr="status",
#                 keyVars=[bossModel.sp1Temp,bossModel.sp2Temp], checkFail=False)
#      if sr.value.didFail:
#          sp1T="failed"; sp2T="failed"
#      else:
#         sp1T=sr.value.getLastKeyVarData(bossModel.sp1Temp)[0]
#         sp2T=sr.value.getLastKeyVarData(bossModel.sp2Temp)[0]
<commit_msg>script Status update<commit_after>#04/24/2012;  EM:  added apogee vacuum, and ln2level;
# change font for title;
# added stui memory use, and mcp.semOwner  10/25/2012

import RO.Wdg
import TUI.Models
import string, os, time
#from datetime import datetime

class ScriptClass(object):
    def __init__(self, sr):
        # if True, run in debug-only mode
        # if False, real time run
        sr.debug = False
        self.name="Status"
        sr.master.winfo_toplevel().wm_resizable(True, True)
        self.logWdg = RO.Wdg.LogWdg(
            master=sr.master,
            width=40,
            height =35,
        )
        self.logWdg.grid(row=0, column=0, sticky="news")
        sr.master.rowconfigure(0, weight=1)
        sr.master.columnconfigure(0, weight=1)

        self.blueWarn=RO.Constants.sevWarning
        self.redWarn=RO.Constants.sevError
        self.apogeeModel = TUI.Models.getModel("apogee")

    def getTAITimeStr(self,):
        return time.strftime("%H:%M:%S",
           time.gmtime(time.time() - RO.Astro.Tm.getUTCMinusTAI()))

    def run(self,sr):
      defstr='n/a'; defval=0

      ff=("Times", "17", "bold italic")
      fs="12"   # font size
      ft="Monaco" # "Courier"  #"Menlo"  # font type
      self.logWdg.text.tag_config("cur", font=(ft,fs,"bold"))

      mcpModel = TUI.Models.getModel("mcp")
      guiderModel = TUI.Models.getModel("guider")
      bossModel = TUI.Models.getModel("boss")
      tccModel = TUI.Models.getModel("tcc")
      gcameraModel = TUI.Models.getModel("gcamera")
      apoModel = TUI.Models.getModel("apo")

      tm = self.getTAITimeStr()
      self.logWdg.addMsg("-- Status  --  %s ---- " % (tm,), tags=["cur"])

      yield sr.waitCmd(actor="apo", cmdStr="status",
                 keyVars=[apoModel.encl25m], checkFail=False)
      if sr.value.didFail: encl=-1
      else: encl=sr.value.getLastKeyVarData(apoModel.encl25m)[0]
      if encl > 0: enclM="open"
      elif encl == 0: enclM="closed"
      else : enclM="n/a"
      self.logWdg.addMsg("Enclosure = %s; " % (enclM))

      mcpW=[0,0,0,0]
      for i in range(0,4):
           mcpW[i]=sr.getKeyVar(mcpModel.cwPositions, ind=i, defVal='n/a')
      mcpWs=str(mcpW[0])+","+str(mcpW[1])+","+str(mcpW[2])+","+str(mcpW[3])
      self.logWdg.addMsg("cwPositions =  %s  %s  %s  %s;  " %
          (str(mcpW[0]),str(mcpW[1]),str(mcpW[2]),str(mcpW[3])))

      mcpInst = sr.getKeyVar(mcpModel.instrumentNum, ind=0, defVal='n/a')
      self.logWdg.addMsg("MCP instr =  %s  (mounted);  "  % (str(mcpInst)))

      ctLoad=guiderModel.cartridgeLoaded
      gc = sr.getKeyVar(ctLoad, ind=0, defVal='n/a')
      gp = sr.getKeyVar(ctLoad, ind=1, defVal='n/a')
      gs = sr.getKeyVar(ctLoad, ind=2, defVal='n/a')
      ss="Guider cart= %s,  plate= %s,  side= %s (loaded)"  % (str(gc),str(gp),str(gs))
      if mcpInst != gc:  self.logWdg.addMsg("%s;  " % (ss), severity=self.redWarn)
      else: self.logWdg.addMsg("%s;  " % (ss), severity=0 )
      self.logWdg.addMsg("%s" % ('-'*30))

      motPos=[0,0,0,0,0,0]
      for i in range(0,6):
         motPos[i]=sr.getKeyVar(bossModel.motorPosition, ind=i, defVal=0)
      self.logWdg.addMsg("motorPosition")
      self.logWdg.addMsg("%s sp1:  %6i,  %6i,  %6i;  " % (" "*4, motPos[0],motPos[1],motPos[2]))
      self.logWdg.addMsg("%s sp2:  %6i,  %6i,  %6i;  " % (" "*4,motPos[3],motPos[4],motPos[5]))
      self.logWdg.addMsg("%s" % ('-'*30))

      yield sr.waitCmd(actor="boss", cmdStr="status",
                 keyVars=[bossModel.sp1Temp,bossModel.sp2Temp], checkFail=False)
      if sr.value.didFail:
          sp1T="n/a"; sp2T="n/a"
      else:
         sp1T=sr.value.getLastKeyVarData(bossModel.sp1Temp)[0]
         sp2T=sr.value.getLastKeyVarData(bossModel.sp2Temp)[0]
      self.logWdg.addMsg("Median spectrographs temperatures:")
      self.logWdg.addMsg("%s Tsp1= %s,  Tsp2= %s;  " % (" "*4,str(sp1T),str(sp2T)))
      airT=sr.getKeyVar(tccModel.airTemp, ind=0, defVal='n/a')
      self.logWdg.addMsg("%s Outside air temperature= %s;  " % (" "*4,str(airT)))

    #  primT=sr.getKeyVar(tccModel.primF_BFTemp, ind=0)
    #  secT=sr.getKeyVar(tccModel.secF_BFTemp, ind=0)
    #  self.logWdg.addMsg("Temp prim="+str(primT)+"C   sec="+str(secT)+"C")

      self.logWdg.addMsg("%s" % ('-'*30))
      bossModel = TUI.Models.getModel("boss")
      sp1r0N=sr.getKeyVar(bossModel.SP1R0CCDTempNom, ind=0, defVal=0)
      sp1b2N=sr.getKeyVar(bossModel.SP1B2CCDTempNom, ind=0, defVal=0)
      sp2r0N=sr.getKeyVar(bossModel.SP2R0CCDTempNom, ind=0, defVal=0)
      sp2b2N=sr.getKeyVar(bossModel.SP2B2CCDTempNom, ind=0, defVal=0)
      sp1r0=sr.getKeyVar(bossModel.SP1R0CCDTempRead, ind=0, defVal=0)

      sp1b2=sr.getKeyVar(bossModel.SP1B2CCDTempRead, ind=0, defVal=0)
      sp2r0=sr.getKeyVar(bossModel.SP2R0CCDTempRead, ind=0, defVal=0)
      sp2b2=sr.getKeyVar(bossModel.SP2B2CCDTempRead, ind=0, defVal=0)
      def sevf(rr,nom,vv):
          if abs(rr-nom)>vv: sev=self.redWarn
          else: sev=0
          return sev
      self.logWdg.addMsg("Boss CCD Temp :")
      self.logWdg.addMsg("    sp1r0= %6.1f (%6.1f);  " % (sp1r0, sp1r0N), severity=sevf(sp1r0, sp1r0N,5))
      self.logWdg.addMsg("    sp1b2= %6.1f (%6.1f);  " % (sp1b2, sp1b2N), severity=sevf(sp1b2, sp1b2N,5))
      self.logWdg.addMsg("    sp2r0= %6.1f (%6.1f);  " % (sp2r0, sp2r0N), severity=sevf(sp2r0, sp2r0N,5))
      self.logWdg.addMsg("    sp2b2= %6.1f (%6.1f);  " % (sp2b2, sp2b2N), severity=sevf(sp2b2, sp2b2N,5))

#      self.logWdg.addMsg(" ")
      SP1SecDewPress=sr.getKeyVar(bossModel.SP1SecondaryDewarPress, ind=0, defVal=defval)
      SP2SecDewPress=sr.getKeyVar(bossModel.SP2SecondaryDewarPress, ind=0, defVal=defval)
      self.logWdg.addMsg("%s sp1LN2: %4.1f;  " % (" "*8, SP1SecDewPress),severity=sevf(SP1SecDewPress,10,5))
      self.logWdg.addMsg("%s sp2LN2: %4.1f;  " % (" "*8, SP2SecDewPress), severity=sevf(SP1SecDewPress,10,5))
      self.logWdg.addMsg("%s" % ('-'*30))

   #   self.logWdg.addMsg(" ")
   #   gcamTempN=sr.getKeyVar(gcameraModel.cooler, ind=0)
      gcamTempN=-40.0
      gcamTemp=sr.getKeyVar(gcameraModel.cooler, ind=1, defVal=defval)
  #    self.logWdg.addMsg("gcameraTemp= %5.1f (%5.1f);  " % (gcamTemp, gcamTempN),
      self.logWdg.addMsg("gcameraTemp= %s (%s);  " % (gcamTemp, gcamTempN),
                severity=sevf(gcamTemp,gcamTempN,3))

      secFoc=sr.getKeyVar(tccModel.secFocus, ind=0, defVal=defstr)
      self.logWdg.addMsg("Rel. Focus =  %s;  " % (str(secFoc)))

      ra=sr.getKeyVar(tccModel.objArcOff, ind=0, defVal=[defstr,defstr,defstr,])
      dec=sr.getKeyVar(tccModel.objArcOff, ind=1, defVal=[defstr, defstr])
      def offStr (off):
          off1=str(off)
          off1=string.replace(off1,"PVT","")
          off1=string.replace(off1,"(","")
          off1=string.replace(off1,")","")
          off1=string.replace(off1,"[","")
          off1=string.replace(off1,"]","")
          off1=string.replace(off1,"'","")
          off2,off3=off1.split(None,1)
          off2=string.replace(off2,",","")
          return off2
      self.logWdg.addMsg("objArcOff = %s,  %s;  " % (offStr(ra),offStr(dec)))
      self.logWdg.addMsg("%s" % ('-'*30))
      def sevLevL(rr,lev1,lev2):
          if rr <= lev2: sev=self.redWarn
          elif lev2 < rr <lev1: sev=self.blueWarn
          elif rr >= lev1: sev=0
          else: pass
          return sev

      def sevLevU(rr,lev1,lev2):
          if rr > lev2: sev=self.redWarn
          elif lev1 < rr <lev2: sev=self.blueWarn
          elif rr<lev1: sev=0
          else: pass
          return sev

      vac = sr.getKeyVar(self.apogeeModel.vacuum, ind=0, defVal=defstr)
      ln2Lev =  sr.getKeyVar(self.apogeeModel.ln2Level, ind=0, defVal=defstr)
      if vac > 1.0e-6:  sev=self.redWarn
      else: sev=0
      self.logWdg.addMsg("Apogee: vacuum = %s (<1.0e-6 )" % (vac), severity=sev)
      self.logWdg.addMsg("Apogee: ln2Level = %s (<85 warn, <75 alert)" %(ln2Lev),severity=sevLevL(ln2Lev,85,70))
      self.logWdg.addMsg("%s" % ('-'*30))

      humidPT=sr.getKeyVar(apoModel.humidPT, ind=0, defVal=defstr)
      self.logWdg.addMsg("humid25m =  %s;  " % (str(humidPT)), severity=sevLevU(humidPT,75,85))
      airTempPT=sr.getKeyVar(apoModel.airTempPT, ind=0, defVal=defstr)
      dpTempPT=sr.getKeyVar(apoModel.dpTempPT, ind=0, defVal=defstr)
      self.logWdg.addMsg("airTemp25m =  %sC,  dpTemp25m =  %sC;  " % (str(airTempPT), str(dpTempPT)))
      try:
          diff=airTempPT-dpTempPT
      except:
          diff=defstr
    #  self.logWdg.addMsg("airTemp25m =  %sC,  dpTemp25m =  %sC;  " % (str(airTempPT), str(dpTempPT)))
      self.logWdg.addMsg("      diff= %sC;  " % (str(diff)),severity=sevLevL(diff,5.0,2.5))

      if encl > 0:
          dir25m=sr.getKeyVar(apoModel.windd25m, ind=0, defVal=defstr)
          wind25m=sr.getKeyVar(apoModel.winds25m, ind=0, defVal=defstr)
          ww=str(wind25m); dd=str(dir25m)
          self.logWdg.addMsg("wind25m = %s mph,  direction = %s;  " %  (str(wind25m),str(dir25m)),
                           severity=sevLevU(wind25m,30,35))
      else:
          self.logWdg.addMsg("wind25m = %s,  direction = %s  "% (defstr, defstr) )

      self.logWdg.addMsg("%s" % ('-'*30))

      self.semOwn = sr.getKeyVar(mcpModel.semaphoreOwner, ind=0, defVal=None)
      self.logWdg.addMsg("semOwner = %s"% (self.semOwn))

      tuiver=TUI.Version.VersionStr
      pid=os.getpid()
      sz="rss"
      mem=int(os.popen('ps -p %d -o %s | tail -1' % (pid, sz)).read())
      ss="%s, stuiVer=(%s),  pid = %s,  mem = %s MB" % (tm, tuiver, pid,  mem/1000)
      self.logWdg.addMsg("%s" % (ss))
      print self.name, ss

      self.logWdg.addMsg(" ")
      self.logWdg.addMsg(" ")

#      yield sr.waitCmd(actor="boss", cmdStr="status",
#                 keyVars=[bossModel.sp1Temp,bossModel.sp2Temp], checkFail=False)
#      if sr.value.didFail:
#          sp1T="failed"; sp2T="failed"
#      else:
#         sp1T=sr.value.getLastKeyVarData(bossModel.sp1Temp)[0]
#         sp2T=sr.value.getLastKeyVarData(bossModel.sp2Temp)[0]
<|endoftext|>