text:
'''
WrapperPhylip.py -
======================================================

:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python

Code
----

'''
import os
import sys
import re
import tempfile
import subprocess
import shutil

from types import *
from CGAT import Experiment as Experiment
from CGAT import TreeTools as TreeTools
from CGAT import MatlabTools as MatlabTools

class Error(Exception):

    """Base class for exceptions in this module."""
    pass

    def __str__(self):
        return str(self.message)

class ParsingError(Error):

    """Exception raised for errors while parsing

    Attributes:
        message -- explanation of the error
    """

    def __init__(self, message, line):
        self.message = message + " at line " + line

class UsageError(Error):

    """Exception raised for errors while starting

    Attributes:
        message -- explanation of the error
    """

    def __init__(self, message):
        self.message = message

class PhylipResult:

    def __init__(self):
        self.mNexus = None
        self.mOutfile = None
        self.mMatrix = None

    def parseContrasts(self, infile):
        """parse results from contrasts run."""
        # remove empty lines and strip

        lines = filter(
            lambda x: x, map(lambda x: x.strip(), infile.readlines()))

        sections = filter(
            lambda x: lines[x + 1][:3] == "---", range(0, len(lines) - 1))
        sections.append(len(lines))

        def readTable(lines):
            data = []
            for line in lines:
                data.append(map(float, re.split("\s+", line[:-1])))
            return data

        for s in range(len(sections) - 1):
            start = sections[s]
            end = sections[s + 1]

            header = lines[start]
            if header[:len("Contrasts")] == "Contrasts":
                self.mContrasts = readTable(lines[start + 2:end])
            elif header[:len("Covariance")] == "Covariance":
                self.mCovariance = readTable(lines[start + 2:end])
            elif header[:len("Correlations")] == "Correlations":
                self.mCorrelations = readTable(lines[start + 2:end])
            elif header[:len("Regressions")] == "Regressions":
                self.mRegressions = readTable(lines[start + 2:end])

class Phylip:

    def __init__(self):

        self.mMapInput2Phylip = {}
        self.mMapPhylip2Input = {}

        self.mTempdir = None

        self.mInputTree = None
        self.mInputTrees = None
        self.mInputData = None
        self.mInputMatrix = None
        self.mInputMali = None

        self.mOutputTree = "-"

        self.mOptions = ""

        self.mOutputStdout = None
        self.mOutputStderr = None

        self.mPruneTree = False

        self.mLogLevel = 0

    def __del__(self):

        if self.mTempdir and self.mTempdir != "tmp" and self.mLogLevel == 0:
            os.system("rm -rf %s" % self.mTempdir)

    def setLogLevel(self, loglevel):
        self.mLogLevel = loglevel

    def setProgram(self, program):
        self.mProgram = program

    def setOptions(self, options):
        self.mOptions = options

    def setTree(self, tree):
        self.mInputTree = tree

    def setTrees(self, trees):
        self.mInputTrees = trees

    def setData(self, data):
        """set input data. This is a matrix with row headers."""
        self.mInputData = data

    def setMatrix(self, matrix):
        self.mInputMatrix = matrix

    def setMali(self, mali):
        self.mInputMali = mali

    def setPruneTree(self, flag=True):
        self.mPruneTree = flag

    def updateMaps(self, taxa):
        """update maps."""
        for taxon in taxa:
            if taxon not in self.mMapInput2Phylip:
                key = "t_%05i" % (len(self.mMapInput2Phylip))
                self.mMapInput2Phylip[taxon] = key
                self.mMapPhylip2Input[key] = taxon

    def __reset(self):
        """clear internal state variables."""
        self.mMapInput2Phylip = {}
        self.mMapPhylip2Input = {}

        self.mTempdir = None

    def prepareRun(self):

        self.__reset()

        self.mTempdir = tempfile.mkdtemp()
        # self.mTempdir = "tmp"
        if not os.path.exists(self.mTempdir):
            os.mkdir(self.mTempdir)

        if self.mInputMatrix and self.mInputData:
            raise ValueError(
                "please specify either input matrix or input data, but not both.")

        # prepare input matrix. Should already be in phylip like
        # format, but long identifiers are shortened and tabs are
        # replaced by spaces.
        if self.mInputMatrix:

            outfile = open(self.mTempdir + "/infile", "w")

            identifiers = map(
                lambda x: re.split("\s+", x[:-1])[0], self.mInputMatrix[1:])
            self.updateMaps(identifiers)

            outfile.write(self.mInputMatrix[0])
            for line in self.mInputMatrix[1:]:
                data = re.split("\s+", line[:-1])
                new_line = self.mMapInput2Phylip[
                    data[0]] + "       " + "  ".join(data[1:])
                outfile.write(new_line + "\n")

            outfile.close()

            if self.mLogLevel >= 1:
                print "# written input matrix with %i taxa to %s" % (len(identifiers), self.mTempdir + "/infile")
                os.system("cat %s" % self.mTempdir + "/infile")

        elif self.mInputData:

            outfile = open(self.mTempdir + "/infile", "w")
            outfile.write("%i %i\n" %
                          (len(self.mInputData), len(self.mInputData[0]) - 1))
            identifiers = map(lambda x: x[0], self.mInputData)
            self.updateMaps(identifiers)

            for x in range(len(identifiers)):
                outfile.write(
                    "%-10s %s\n" % (self.mMapInput2Phylip[identifiers[x]], " ".join(self.mInputData[x][1:])))

            outfile.close()

            if self.mLogLevel >= 1:
                print "# written input matrix with %i taxa to %s" % (len(identifiers), self.mTempdir + "/infile")
                os.system("cat %s" % self.mTempdir + "/infile")

        # prepare input tree or trees
        self.mNInputTrees = 0
        if self.mInputTree or self.mInputTrees:

            outfile = open(self.mTempdir + "/intree", "w")

            if self.mInputTree and self.mInputTrees:
                raise UsageError(
                    "please supply either one or mupltiple trees, but not both.")

            if self.mInputTree:
                trees = [self.mInputTree]
            else:
                trees = self.mInputTrees

            for tree in trees:
                if self.mPruneTree:
                    taxa = self.mMapInput2Phylip.keys()
                    TreeTools.PruneTree(tree, taxa)

                taxa = TreeTools.GetTaxa(tree)
                self.updateMaps(taxa)
                TreeTools.MapTaxa(tree, self.mMapInput2Phylip)

                # check if taxa are unique
                taxa = tree.get_taxa()
                staxa = set()

                skip = False
                for t in taxa:
                    if t in staxa:
                        if self.mLogLevel >= 1:
                            print "# skipping tree %s because of duplicate taxa." % (tree.name)
                        skip = True
                    staxa.add(t)

                if skip:
                    continue

                outfile.write(TreeTools.Tree2Newick(tree) + "\n")
                self.mNInputTrees += 1

                if self.mLogLevel >= 1:
                    print "# written input tree with %i taxa to %s" % (len(TreeTools.GetTaxa(tree)), self.mTempdir + "/intree")
                    print "#", TreeTools.Tree2Newick(tree)

            outfile.close()

        # prepare input multiple alignment
        if self.mInputMali:

            if self.mInputMatrix:
                raise "both mali and matrix supplied - infile conflict."

            outfile = open(self.mTempdir + "/infile", "w")

            identifiers = self.mInputMali.getIdentifiers()
            self.updateMaps(identifiers)
            self.mInputMali.mapIdentifiers(self.mMapInput2Phylip)
            self.mInputMali.writeToFile(outfile, format="phylip")

            outfile.close()

            if self.mLogLevel >= 1:
                print "# written input multiple alignments with %i taxa and with %i to %s" %\
                      (self.mInputMali.getLength(),
                       self.mInputMali.getWidth(), self.mTempdir + "/intree")

    def run(self):

        self.prepareRun()

        if not self.mProgram:
            raise UsageError("no program specified.")

        s = subprocess.Popen("%s" % (self.mProgram),
                             shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             cwd=self.mTempdir,
                             close_fds=True)

        (out, err) = s.communicate("\n".join(self.mOptions) + "\n")

        if s.returncode != 0:
            raise UsageError, "Error in running phylip.\n%s\n%s\nTemporary directory was %s" % (
                out, err, self.mTempdir)

        # Parse output files that might have been created:
        result = PhylipResult()

        # parse tree file
        if os.path.exists("%s/outtree" % self.mTempdir):

            nexus = TreeTools.Newick2Nexus(
                open("%s/outtree" % self.mTempdir, "r"))
            for tree in nexus.trees:
                TreeTools.MapTaxa(tree, self.mMapPhylip2Input)
            result.mNexus = nexus
            if self.mLogLevel >= 1:
                print "# received tree with %i taxa" % (len(TreeTools.GetTaxa(nexus.trees[0])))

        elif os.path.exists("%s/outfile" % self.mTempdir):

            if self.mProgram in ("dnadist", "protdist"):
                infile = open("%s/outfile" % self.mTempdir, "r")
                result.mMatrix, row_headers, col_headers = MatlabTools.readMatrix(
                    infile, format="phylip")
                result.mRowHeaders = []
                for x in row_headers:
                    result.mRowHeaders.append(self.mMapPhylip2Input[x])
                result.mColHeaders = result.mRowHeaders
            elif self.mProgram == "contrast":

                infile = open("%s/outfile" % self.mTempdir, "r")
                result.parseContrasts(infile)
                infile.close()

        else:
            raise "other return types not implemented"

        if self.mLogLevel >= 2:
            print out

        if self.mLogLevel == 0:
            shutil.rmtree(self.mTempdir)

        return result

if __name__ == "__main__":

    phylip = Phylip()

    parser = E.OptionParser(
        version="%prog version: $Id: WrapperPhylip.py 2784 2009-09-10 11:41:14Z andreas $")

    parser.add_option("-t", "--filename-input-tree", dest="filename_input_tree", type="string",
                      help="filename with tree information.")
    parser.add_option("-T", "--filename-output-tree", dest="filename_output_tree", type="string",
                      help="output filename with tree information.")
    parser.add_option("-p", "--program", dest="program", type="string",
                      help="program to use.")
    parser.add_option("-o", "--options", dest="options", type="string",
                      help="input options.")

    parser.set_defaults(
        filename_input_tree=None,
        filename_output_tree=None,
        program=None,
        options="",
    )

    (options, args) = Experiment.Start(parser)

    if options.filename_input_tree != "-":
        phylip.setTree(open(options.filename_input_tree, "r").readlines())
    elif options.filename_input_tree == "-":
        phylip.setTree(sys.stdin.readlines())

    phylip.setOptions(options.options)

    phylip.setProgram(options.program)

    phylip.run()

    Experiment.Stop()


text:
from datetime import datetime

from django.template.defaultfilters import slugify

from taggit.models import Tag

from kitsune.sumo.tests import with_save

@with_save
def tag(**kwargs):
    """Model Maker for Tags."""
    defaults = {'name': str(datetime.now())}
    defaults.update(kwargs)
    if 'slug' not in kwargs:
        defaults['slug'] = slugify(defaults['title'])
    return Tag(**defaults)

redpajama_set_name: RedPajamaGithub


text:
package org.optaplanner.core.impl.domain.variable.inverserelation;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

import org.junit.jupiter.api.Test;
import org.optaplanner.core.api.score.director.ScoreDirector;
import org.optaplanner.core.impl.score.director.InnerScoreDirector;
import org.optaplanner.core.impl.testdata.domain.list.TestdataListEntity;
import org.optaplanner.core.impl.testdata.domain.list.TestdataListSolution;
import org.optaplanner.core.impl.testdata.domain.list.TestdataListValue;

class SingletonListInverseVariableListenerTest {

    private final ScoreDirector<TestdataListSolution> scoreDirector = mock(InnerScoreDirector.class);

    private final SingletonListInverseVariableListener<TestdataListSolution> inverseVariableListener =
            new SingletonListInverseVariableListener<>(
                    TestdataListValue.buildVariableDescriptorForEntity(),
                    TestdataListEntity.buildVariableDescriptorForValueList());

    @Test
    void inverseRelation() {
        TestdataListValue v1 = new TestdataListValue("1");
        TestdataListValue v2 = new TestdataListValue("2");
        TestdataListValue v3 = new TestdataListValue("3");
        TestdataListValue v4 = new TestdataListValue("4");
        TestdataListEntity e1 = new TestdataListEntity("a", v1, v2);
        TestdataListEntity e2 = new TestdataListEntity("b", v3);

        assertThat(v1.getEntity()).isNull();
        assertThat(v2.getEntity()).isNull();
        assertThat(v3.getEntity()).isNull();

        inverseVariableListener.beforeEntityAdded(scoreDirector, e1);
        inverseVariableListener.afterEntityAdded(scoreDirector, e1);
        inverseVariableListener.beforeEntityAdded(scoreDirector, e2);
        inverseVariableListener.afterEntityAdded(scoreDirector, e2);

        assertInverseEntity(v1, e1);
        assertInverseEntity(v2, e1);
        assertInverseEntity(v3, e2);

        // Move v1 from e1 to e2.
        inverseVariableListener.beforeListVariableChanged(scoreDirector, e1, 0, 1);
        e1.getValueList().remove(v1);
        inverseVariableListener.afterListVariableChanged(scoreDirector, e1, 0, 0);
        inverseVariableListener.beforeListVariableChanged(scoreDirector, e2, 1, 1);
        e2.getValueList().add(v1);
        inverseVariableListener.afterListVariableChanged(scoreDirector, e2, 1, 2);

        assertInverseEntity(v1, e2);

        // Assign v4 to e2[0].
        inverseVariableListener.beforeListVariableChanged(scoreDirector, e2, 0, 0);
        e2.getValueList().add(0, v4);
        inverseVariableListener.afterListVariableChanged(scoreDirector, e2, 0, 1);

        assertInverseEntity(v4, e2);

        // Unassign v2 from e1.
        inverseVariableListener.beforeListVariableChanged(scoreDirector, e1, 0, 1);
        e1.getValueList().remove(0);
        inverseVariableListener.afterListVariableElementUnassigned(scoreDirector, v2);
        inverseVariableListener.afterListVariableChanged(scoreDirector, e1, 0, 0);

        assertInverseEntity(v2, null);
    }

    @Test
    void removeEntity() {
        TestdataListValue v1 = new TestdataListValue("1");
        TestdataListValue v2 = new TestdataListValue("2");
        TestdataListValue v3 = new TestdataListValue("3");
        TestdataListEntity e1 = TestdataListEntity.createWithValues("a", v1, v2);
        TestdataListEntity e2 = TestdataListEntity.createWithValues("b", v3);

        assertThat(v1.getEntity()).isEqualTo(e1);
        assertThat(v2.getEntity()).isEqualTo(e1);
        assertThat(v3.getEntity()).isEqualTo(e2);

        inverseVariableListener.beforeEntityRemoved(scoreDirector, e1);
        inverseVariableListener.afterEntityRemoved(scoreDirector, e1);

        assertInverseEntity(v1, null);
        assertInverseEntity(v2, null);
        assertInverseEntity(v3, e2);
    }

    void assertInverseEntity(TestdataListValue element, Object entity) {
        assertThat(element.getEntity()).isEqualTo(entity);
        assertThat(inverseVariableListener.getInverseSingleton(element)).isEqualTo(entity);
    }
}


text:
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;

[CanEditMultipleObjects]
[CustomEditor(typeof(SgtCloudsphereDepth))]
public class SgtCloudsphereDepth_Editor : SgtEditor<SgtCloudsphereDepth>
{
	protected override void OnInspector()
	{
		var updateTexture = false;
		var updateApply   = false;

		DrawDefault("Cloudsphere", ref updateApply);
		BeginError(Any(t => t.Width < 1));
			DrawDefault("Width", ref updateTexture);
		EndError();
		DrawDefault("Format", ref updateTexture);

		Separator();

		DrawDefault("RimEase", ref updateTexture);
		DrawDefault("RimColor", ref updateTexture);
		BeginError(Any(t => t.RimPower < 1.0f));
			DrawDefault("RimPower", ref updateTexture);
		EndError();

		Separator();

		BeginError(Any(t => t.AlphaDensity < 1.0f));
			DrawDefault("AlphaDensity", ref updateTexture);
		EndError();
		BeginError(Any(t => t.AlphaFade < 1.0f));
			DrawDefault("AlphaFade", ref updateTexture);
		EndError();

		if (updateTexture == true) DirtyEach(t => t.UpdateTexture());
		if (updateApply   == true) DirtyEach(t => t.UpdateApply  ());
	}
}
#endif

[ExecuteInEditMode]
[AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Cloudsphere Depth")]
public class SgtCloudsphereDepth : MonoBehaviour
{
	[Tooltip("The cloudsphere this texture will be applied to")]
	public SgtCloudsphere Cloudsphere;

	[Tooltip("The resolution of the surface/space optical thickness transition in pixels")]
	public int Width = 256;

	[Tooltip("The format of this texture")]
	public TextureFormat Format = TextureFormat.ARGB32;

	[Tooltip("The rim transition style")]
	public SgtEase.Type RimEase = SgtEase.Type.Exponential;

	[Tooltip("The rim color")]
	public Color RimColor = new Color(1.0f, 0.0f, 0.0f, 0.25f);

	[Tooltip("The rim transition sharpness")]
	public float RimPower = 5.0f;

	[Tooltip("The density of the atmosphere")]
	public float AlphaDensity = 50.0f;

	[Tooltip("The strength of the density fading in the upper atmosphere")]
	public float AlphaFade = 2.0f;

	[System.NonSerialized]
	private Texture2D generatedTexture;

	[SerializeField]
	[HideInInspector]
	private bool startCalled;

	public Texture2D GeneratedTexture
	{
		get
		{
			return generatedTexture;
		}
	}

#if UNITY_EDITOR
	[ContextMenu("Export Texture")]
	public void ExportTexture()
	{
		var importer = SgtHelper.ExportTextureDialog(generatedTexture, "Cloudsphere Depth");

		if (importer != null)
		{
			importer.textureCompression  = TextureImporterCompression.Uncompressed;
			importer.alphaSource         = TextureImporterAlphaSource.FromInput;
			importer.wrapMode            = TextureWrapMode.Clamp;
			importer.filterMode          = FilterMode.Trilinear;
			importer.anisoLevel          = 16;
			importer.alphaIsTransparency = true;

			importer.SaveAndReimport();
		}
	}
#endif

	[ContextMenu("Update Texture")]
	public void UpdateTexture()
	{
		if (Width > 0)
		{
			// Destroy if invalid
			if (generatedTexture != null)
			{
				if (generatedTexture.width != Width || generatedTexture.height != 1 || generatedTexture.format != Format)
				{
					generatedTexture = SgtHelper.Destroy(generatedTexture);
				}
			}

			// Create?
			if (generatedTexture == null)
			{
				generatedTexture = SgtHelper.CreateTempTexture2D("Cloudsphere Depth (Generated)", Width, 1, Format);

				generatedTexture.wrapMode = TextureWrapMode.Clamp;

				UpdateApply();
			}

			var stepX = 1.0f / (Width - 1);

			for (var x = 0; x < Width; x++)
			{
				var v = x * stepX;

				WriteTexture(v, x);
			}

			generatedTexture.Apply();
		}
	}

	private void WriteTexture(float u, int x)
	{
		var rim   = SgtEase.Evaluate(RimEase, Mathf.Pow(1.0f - u, RimPower));
		var color = Color.Lerp(Color.white, RimColor, rim * RimColor.a);

		color.a = 1.0f - Mathf.Pow(1.0f - Mathf.Pow(u, AlphaFade), AlphaDensity);

		generatedTexture.SetPixel(x, 0, color);
	}

	[ContextMenu("Update Apply")]
	public void UpdateApply()
	{
		if (Cloudsphere != null)
		{
			if (generatedTexture != null)
			{
				if (Cloudsphere.DepthTex != generatedTexture)
				{
					Cloudsphere.DepthTex = generatedTexture;

					Cloudsphere.UpdateDeptchTex();
				}
			}
		}
	}

	protected virtual void OnEnable()
	{
		if (startCalled == true)
		{
			CheckUpdateCalls();
		}
	}

	protected virtual void Start()
	{
		if (startCalled == false)
		{
			startCalled = true;

			if (Cloudsphere == null)
			{
				Cloudsphere = GetComponent<SgtCloudsphere>();
			}

			CheckUpdateCalls();
		}
	}

	protected virtual void OnDestroy()
	{
		SgtHelper.Destroy(generatedTexture);
	}

	private void CheckUpdateCalls()
	{
		if (generatedTexture == null)
		{
			UpdateTexture();
		}

		UpdateApply();
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Uchen. Zap. Tartu. Gos. Univ. 9: 371 (1970)

#### Original name
Discina korfii Raitv.

### Remarks
null


text:
// -----------------------------------------------------------------------
// <copyright file="AddressLocation.cs" company="Spardo, LLC">
// Copyright (c) 2011 SPardo, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// -----------------------------------------------------------------------

namespace DotNet37Signals.Client.Highrise.Models
{
    using System.Runtime.Serialization;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    [DataContract(Name = "location", Namespace = "")]
    public enum AddressLocation
    {
        [EnumMember(Value = "Work")]
        Work,
        [EnumMember(Value = "Home")]
        Home,
        [EnumMember(Value = "Other")]
        Other
    }
}


text:
obj- := dummy.o

# List of programs to build
hostprogs-y := v4lgrab

# Tell kbuild to always build the programs
always := $(hostprogs-y)


text:
package org.ovirt.engine.ui.common.view.popup;

import java.util.ArrayList;
import java.util.List;

import org.ovirt.engine.ui.common.idhandler.HasElementId;
import org.ovirt.engine.ui.common.presenter.AbstractModelBoundPopupPresenterWidget;
import org.ovirt.engine.ui.common.utils.ElementIdUtils;
import org.ovirt.engine.ui.common.view.AbstractPopupView;
import org.ovirt.engine.ui.common.widget.AbstractUiCommandButton;
import org.ovirt.engine.ui.common.widget.HasUiCommandClickHandlers;
import org.ovirt.engine.ui.common.widget.IsProgressContentWidget;
import org.ovirt.engine.ui.common.widget.UiCommandButton;
import org.ovirt.engine.ui.common.widget.dialog.AbstractDialogPanel;
import org.ovirt.engine.ui.common.widget.dialog.PopupNativeKeyPressHandler;
import org.ovirt.engine.ui.common.widget.dialog.ProgressPopupContent;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * Base class for popup views bound to a UiCommon Window model.
 *
 * @param <T>
 *            Window model type.
 */
public abstract class AbstractModelBoundPopupView<T extends Model> extends AbstractPopupView<AbstractDialogPanel>
        implements AbstractModelBoundPopupPresenterWidget.ViewDef<T>, HasElementId, FocusableComponentsContainer {

    /**
     * Popup progress indicator widget
     */
    private final IsProgressContentWidget progressContent;

    /**
     * Actual popup content
     */
    private Widget popupContent;

    /**
     * Popup hash-name
     */
    private String hashName;

    private String elementId = DOM.createUniqueId();

    private final List<FocusableComponentsContainer> focusableButtons = new ArrayList<FocusableComponentsContainer>();

    public AbstractModelBoundPopupView(EventBus eventBus) {
        super(eventBus);
        this.progressContent = createProgressContentWidget();
    }

    @Override
    protected void initWidget(AbstractDialogPanel widget) {
        super.initWidget(widget);
        this.popupContent = widget.getContent();
    }

    protected AbstractUiCommandButton createCommandButton(String label, String uniqueId) {
        return new UiCommandButton(label);
    }

    protected IsProgressContentWidget createProgressContentWidget() {
        return new ProgressPopupContent();
    }

    /**
     * Hook bound to "Title" property change on given model.
     */
    @Override
    public void setTitle(String title) {
        asWidget().setHeader(new Label(title));
    }

    /**
     * Hook bound to "Message" property change on given model.
     */
    @Override
    public void setMessage(String message) {
        // No-op, override as necessary
    }

    /**
     * Hook bound to "Items" property change on given model.
     *

     * Called only if the model is a {@code ListModel}.
     */
    @Override
    public void setItems(Iterable<?> items) {
        // No-op, override as necessary
    }

    /**
     * Hook bound to "HashName" property change on given model.
     */
    @Override
    public void setHashName(String name) {
        this.hashName = name;
    }

    /**
     * Hook bound to "HelpTag" property change on given model.
     *

     * Called only if the model's {@linkplain Model#getOpenDocumentationCommand Open
     * Documentation command} (open context-sensitive help) is available, passing it
     * as a parameter.
     */
    @Override
    public void setHelpCommand(UICommand command) {
        asWidget().setHelpCommand(command);
    }

    @Override
    public HasUiCommandClickHandlers addFooterButton(String label, String uniqueId) {
        AbstractUiCommandButton button = createCommandButton(label, uniqueId);
        asWidget().addFooterButton(button);
        focusableButtons.add(0, button);

        // Set button element ID for better accessibility
        button.asWidget().getElement().setId(
                ElementIdUtils.createElementId(elementId, uniqueId));

        return button;
    }

    public void addStatusWidget(Widget widget) {
        asWidget().addStatusWidget(widget);
    }

    @Override
    public void removeButtons() {
        asWidget().removeFooterButtons();
        focusableButtons.clear();
    }

    @Override
    public void startProgress(String progressMessage) {
        // Set dialog content to the progress indicator widget
        progressContent.setProgressMessage(progressMessage);
        asWidget().setContent(progressContent.asWidget());

        // Hide dialog buttons when starting progress
        asWidget().setFooterPanelVisible(false);
    }

    @Override
    public void stopProgress() {
        // Set dialog content to the actual popup content widget
        asWidget().setContent(popupContent);

        // Show dialog buttons when stopping progress
        asWidget().setFooterPanelVisible(true);

        // Update tab index values
        updateTabIndexes();

        // Now that the panel is visible we can try to focus
        focusInput();
    }

    /**
     * Hook for setting initial focus when the View becomes visible.
     *

     * For example:
     *
     *

     *  userNameWidget.setFocus(true);
     *

     */
    @Override
    public void focusInput() {
        // No-op, override as necessary
    }

    @Override
    public HasClickHandlers getCloseButton() {
        return null;
    }

    @Override
    public HasClickHandlers getCloseIconButton() {
        return asWidget().getCloseIconButton();
    }

    @Override
    public void setPopupKeyPressHandler(PopupNativeKeyPressHandler handler) {
        asWidget().setKeyPressHandler(handler);
    }

    @Override
    public void setElementId(String elementId) {
        this.elementId = elementId;
    }

    protected String getHashName() {
        return hashName;
    }

    /**
     * Hook for assigning tab index to widgets contained in the View.
     *

     * For example:
     *
     *

     *  userNameWidget.setTabIndex(nextTabIndex++);
     *  passwordWidget.setTabIndex(nextTabIndex++);
     *  return nextTabIndex;
     *

     *
     * @param nextTabIndex
     *            Currently available tab index value.
     * @return Next available tab index value.
     */
    @Override
    public int setTabIndexes(int nextTabIndex) {
        // No-op, override as necessary
        return nextTabIndex;
    }

    @Override
    public void updateTabIndexes() {
        // Update tab indexes for popup view's content
        int nextTabIndex = setTabIndexes(0);

        // Update tab indexes for popup view's footer buttons
        for (FocusableComponentsContainer button : focusableButtons) {
            nextTabIndex = button.setTabIndexes(nextTabIndex);
        }
    }

    /**
     * Hook for initializing the View from given model.
     *

     * Called once per model instance, before the initial {@link #edit}
     * call that fills the View with model's current data.
     *

     * This is the right place for any model-specific (one-time) event
     * handler registration or initialization logic, for example:
     *
     *

     *  model.getFoo().getPropertyChangedEvent().addListener( ... );
     *  model.getBar().getEntityChangedEvent().addListener( ... );
     *

     *
     * @param model
     *            Model instance assigned to the View.
     */
    @Override
    public void init(T model) {
        // No-op, override as necessary
    }

}


text:
from __future__ import absolute_import

from mock import patch
import unittest
import pytest

from bokeh.plotting import figure
from bokeh.models import GlyphRenderer, Label, Range1d
from bokeh.models.tools import PanTool

class TestPlotSelect(unittest.TestCase):

    def setUp(self):
        self._plot = figure(tools='pan')
        self._plot.circle([1,2,3], [3,2,1], name='foo')

    @patch('bokeh.models.plots.find')
    def test_string_arg(self, mock_find):
        self._plot.select('foo')
        self.assertTrue(mock_find.called)
        self.assertEqual(mock_find.call_args[0][1], dict(name='foo'))

    @patch('bokeh.models.plots.find')
    def test_type_arg(self, mock_find):
        self._plot.select(PanTool)
        self.assertTrue(mock_find.called)
        self.assertEqual(mock_find.call_args[0][1], dict(type=PanTool))

    @patch('bokeh.models.plots.find')
    def test_kwargs(self, mock_find):
        kw = dict(name='foo', type=GlyphRenderer)
        self._plot.select(**kw)
        self.assertTrue(mock_find.called)
        self.assertEqual(mock_find.call_args[0][1], kw)

    def test_too_many_args(self):
        with self.assertRaises(TypeError) as cm:
            self._plot.select('foo', 'bar')
        self.assertEqual(
            'select accepts at most ONE positional argument.',
            str(cm.exception)
        )

    def test_no_input(self):
        with self.assertRaises(TypeError) as cm:
            self._plot.select()
        self.assertEqual(
            'select requires EITHER a positional argument, OR keyword arguments.',
            str(cm.exception)
        )

    def test_arg_and_kwarg(self):
        with self.assertRaises(TypeError) as cm:
            self._plot.select('foo', type=PanTool)
        self.assertEqual(
            'select accepts EITHER a positional argument, OR keyword arguments (not both).',
            str(cm.exception)
        )

def test_plot_add_annotation_method():
    plot = figure()

    with pytest.raises(ValueError):
        plot.add_annotation(Range1d())

    with pytest.raises(ValueError):
        plot.add_annotation(Label(plot=figure()))

    label = Label()
    plot.add_annotation(label)

    assert label in plot.renderers

def test_responsive_property_is_false_by_default():
    plot = figure()
    assert plot.responsive is False

if __name__ == '__main__':
    unittest.main()


text:
// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            Portions ©2008-2011 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================
/*globals sc_assert */

require("sproutcore-views/system/render_buffer");
var get = SC.get, set = SC.set, addObserver = SC.addObserver;
var getPath = SC.getPath, meta = SC.meta, fmt = SC.String.fmt;

/**
  @static

  Global hash of shared templates. This will automatically be populated
  by the build tools so that you can store your Handlebars templates in
  separate files that get loaded into JavaScript at buildtime.

  @type Hash
*/
SC.TEMPLATES = {};

/**
  @class
  @since SproutCore 2.0
  @extends SC.Object
*/
SC.View = SC.Object.extend(
/** @scope SC.View.prototype */ {

  /** @private */
  concatenatedProperties: ['classNames', 'classNameBindings', 'attributeBindings'],

  /**
    @type Boolean
    @default YES
    @constant
  */
  isView: YES,

  // ..........................................................
  // TEMPLATE SUPPORT
  //

  /**
    The name of the template to lookup if no template is provided.

    SC.View will look for a template with this name in this view's
    `templates` object. By default, this will be a global object
    shared in `SC.TEMPLATES`.

    @type String
    @default null
  */
  templateName: null,

  /**
    The hash in which to look for `templateName`.

    @type SC.Object
    @default SC.TEMPLATES
  */
  templates: SC.TEMPLATES,

  /**
    The template used to render the view. This should be a function that
    accepts an optional context parameter and returns a string of HTML that
    will be inserted into the DOM relative to its parent view.

    In general, you should set the `templateName` property instead of setting
    the template yourself.

    @field
    @type Function
  */
  template: function(key, value) {
    if (value !== undefined) { return value; }

    var templateName = get(this, 'templateName'), template;

    if (templateName) { template = get(get(this, 'templates'), templateName); }

    // If there is no template but a templateName has been specified,
    // try to lookup as a spade module
    if (!template && templateName) {
      if ('undefined' !== require && require.exists) {
        if (require.exists(templateName)) { template = require(templateName); }
      }

      if (!template) {
        throw new SC.Error('%@ - Unable to find template "%@".'.fmt(this, templateName));
      }
    }

    // return the template, or undefined if no template was found
    return template || get(this, 'defaultTemplate');
  }.property('templateName').cacheable(),

  /**
    The object from which templates should access properties.

    This object will be passed to the template function each time the render
    method is called, but it is up to the individual function to decide what
    to do with it.

    By default, this will be the view itself.

    @type Object
  */
  templateContext: function(key, value) {
    return value !== undefined ? value : this;
  }.property().cacheable(),

  /**
    If the view is currently inserted into the DOM of a parent view, this
    property will point to the parent of the view.

    @type SC.View
    @default null
  */
  parentView: null,

  /**
    If false, the view will appear hidden in DOM.

    @type Boolean
    @default true
  */
  isVisible: true,

  /**
    Array of child views. You should never edit this array directly.
    Instead, use appendChild and removeFromParent.

    @private
    @type Array
    @default []
  */
  childViews: [],

  /**
    Return the nearest ancestor that is an instance of the provided
    class.

    @param {Class} klass Subclass of SC.View (or SC.View itself)
    @returns SC.View
  */
  nearestInstanceOf: function(klass) {
    var view = this.parentView;

    while (view) {
      if(view instanceof klass) { return view; }
      view = view.parentView;
    }
  },

  /**
    Return the nearest ancestor that has a given property.

    @param {String} property A property name
    @returns SC.View
  */
  nearestWithProperty: function(property) {
    var view = this.parentView;

    while (view) {
      if (property in view) { return view; }
      view = view.parentView;
    }
  },

  /**
    Return the nearest ancestor that is a direct child of a
    view of.

    @param {Class} klass Subclass of SC.View (or SC.View itself)
    @returns SC.View
  */
  nearestChildOf: function(klass) {
    var view = this.parentView;

    while (view) {
      if(view.parentView instanceof klass) { return view; }
      view = view.parentView;
    }
  },

  /**
    Return the nearest ancestor that is an SC.CollectionView

    @returns SC.CollectionView
  */
  collectionView: function() {
    return this.nearestInstanceOf(SC.CollectionView);
  }.property().cacheable(),

  /**
    Return the nearest ancestor that is a direct child of
    an SC.CollectionView

    @returns SC.View
  */
  itemView: function() {
    return this.nearestChildOf(SC.CollectionView);
  }.property().cacheable(),

  /**
    Return the nearest ancestor that has the property
    `content`.

    @returns SC.View
  */
  contentView: function() {
    return this.nearestWithProperty('content');
  }.property().cacheable(),

  /**
    @private

    When the parent view changes, recursively invalidate
    collectionView, itemView, and contentView
  */
  _parentViewDidChange: function() {
    this.invokeRecursively(function(view) {
      view.propertyDidChange('collectionView');
      view.propertyDidChange('itemView');
      view.propertyDidChange('contentView');
    });
  }.observes('parentView'),

  /**
    Called on your view when it should push strings of HTML into a
    SC.RenderBuffer. Most users will want to override the `template`
    or `templateName` properties instead of this method.

    By default, SC.View will look for a function in the `template`
    property and invoke it with the value of `templateContext`. The value of
    `templateContext` will be the view itself unless you override it.

    @param {SC.RenderBuffer} buffer The render buffer
  */
  render: function(buffer) {
    var template = get(this, 'template');

    if (template) {
      var context = get(this, 'templateContext'),
          data = { view: this, buffer: buffer, isRenderData: true };

      // Invoke the template with the provided template context, which
      // is the view by default. A hash of data is also passed that provides
      // the template with access to the view and render buffer.

      // The template should write directly to the render buffer instead
      // of returning a string.
      var output = template(context, { data: data });

      // If the template returned a string instead of writing to the buffer,
      // push the string onto the buffer.
      if (output !== undefined) { buffer.push(output); }
    }
  },

  invokeForState: function(name) {
    var parent = this, states = parent.states;

    while (states) {
      var stateName = get(this, 'state'),
          state     = states[stateName];

      if (state) {
        var fn = state[name] || states["default"][name];

        if (fn) {
          var args = Array.prototype.slice.call(arguments, 1);
          args.unshift(this);

          return fn.apply(this, args);
        }
      }

      states = states.parent;
    }
  },

  /**
    Renders the view again. This will work regardless of whether the
    view is already in the DOM or not. If the view is in the DOM, the
    rendering process will be deferred to give bindings a chance
    to synchronize.

    If children were added during the rendering process using `appendChild`,
    `rerender` will remove them, because they will be added again
    if needed by the next `render`.

    In general, if the display of your view changes, you should modify
    the DOM element directly instead of manually calling `rerender`, which can
    be slow.
  */
  rerender: function() {
    return this.invokeForState('rerender');
  },

  clearRenderedChildren: function() {
    var viewMeta = meta(this)['SC.View'],
        lengthBefore = viewMeta.lengthBeforeRender,
        lengthAfter  = viewMeta.lengthAfterRender;

    // If there were child views created during the last call to render(),
    // remove them under the assumption that they will be re-created when
    // we re-render.

    // VIEW-TODO: Unit test this path.
    var childViews = get(this, 'childViews');
    for (var i=lengthAfter-1; i>=lengthBefore; i--) {
      childViews[i] && childViews[i].destroy();
    }
  },

  /**
    @private

    Iterates over the view's `classNameBindings` array, inserts the value
    of the specified property into the `classNames` array, then creates an
    observer to update the view's element if the bound property ever changes
    in the future.
  */
  _applyClassNameBindings: function() {
    var classBindings = get(this, 'classNameBindings'),
        classNames = get(this, 'classNames'),
        elem, newClass, dasherizedClass;

    if (!classBindings) { return; }

    // Loop through all of the configured bindings. These will be either
    // property names ('isUrgent') or property paths relative to the view
    // ('content.isUrgent')
    classBindings.forEach(function(binding) {

      // Variable in which the old class value is saved. The observer function
      // closes over this variable, so it knows which string to remove when
      // the property changes.
      var oldClass, property;

      // Set up an observer on the context. If the property changes, toggle the
      // class name.
      var observer = function() {
        // Get the current value of the property
        newClass = this._classStringForProperty(binding);
        elem = this.$();

        // If we had previously added a class to the element, remove it.
        if (oldClass) {
          elem.removeClass(oldClass);
        }

        // If necessary, add a new class. Make sure we keep track of it so
        // it can be removed in the future.
        if (newClass) {
          elem.addClass(newClass);
          oldClass = newClass;
        } else {
          oldClass = null;
        }
      };

      // Get the class name for the property at its current value
      dasherizedClass = this._classStringForProperty(binding);

      if (dasherizedClass) {
        // Ensure that it gets into the classNames array
        // so it is displayed when we render.
        classNames.push(dasherizedClass);

        // Save a reference to the class name so we can remove it
        // if the observer fires. Remember that this variable has
        // been closed over by the observer.
        oldClass = dasherizedClass;
      }

      // Extract just the property name from bindings like 'foo:bar'
      property = binding.split(':')[0];
      addObserver(this, property, observer);
    }, this);
  },

  /**
    Iterates through the view's attribute bindings, sets up observers for each,
    then applies the current value of the attributes to the passed render buffer.

    @param {SC.RenderBuffer} buffer
  */
  _applyAttributeBindings: function(buffer) {
    var attributeBindings = get(this, 'attributeBindings'),
        attributeValue, elem, type;

    if (!attributeBindings) { return; }

    attributeBindings.forEach(function(attribute) {
      // Create an observer to add/remove/change the attribute if the
      // JavaScript property changes.
      var observer = function() {
        elem = this.$();
        var currentValue = elem.attr(attribute);
        attributeValue = get(this, attribute);

        type = typeof attributeValue;

        if ((type === 'string' || type === 'number') && attributeValue !== currentValue) {
          elem.attr(attribute, attributeValue);
        } else if (attributeValue && type === 'boolean') {
          elem.attr(attribute, attribute);
        } else if (attributeValue === NO) {
          elem.removeAttr(attribute);
        }
      };

      addObserver(this, attribute, observer);

      // Determine the current value and add it to the render buffer
      // if necessary.
      attributeValue = get(this, attribute);
      type = typeof attributeValue;

      if (type === 'string' || type === 'number') {
        buffer.attr(attribute, attributeValue);
      } else if (attributeValue && type === 'boolean') {
        // Apply boolean attributes in the form attribute="attribute"
        buffer.attr(attribute, attribute);
      }
    }, this);
  },

  /**
    @private

    Given a property name, returns a dasherized version of that
    property name if the property evaluates to a non-falsy value.

    For example, if the view has property `isUrgent` that evaluates to true,
    passing `isUrgent` to this method will return `"is-urgent"`.
  */
  _classStringForProperty: function(property) {
    var split = property.split(':'), className = split[1];
    property = split[0];

    var val = SC.getPath(this, property);

    // If value is a Boolean and true, return the dasherized property
    // name.
    if (val === YES) {
      if (className) { return className; }

      // Normalize property path to be suitable for use
      // as a class name. For exaple, content.foo.barBaz
      // becomes bar-baz.
      return SC.String.dasherize(get(property.split('.'), 'lastObject'));

    // If the value is not NO, undefined, or null, return the current
    // value of the property.
    } else if (val !== NO && val !== undefined && val !== null) {
      return val;

    // Nothing to display. Return null so that the old class is removed
    // but no new class is added.
    } else {
      return null;
    }
  },

  // ..........................................................
  // ELEMENT SUPPORT
  //

  /**
    Returns the current DOM element for the view.

    @field
    @type DOMElement
  */
  element: function(key, value) {
    if (value !== undefined) {
      return this.invokeForState('setElement', value);
    } else {
      return this.invokeForState('getElement');
    }
  }.property('parentView', 'state').cacheable(),

  /**
    Returns a jQuery object for this view's element. If you pass in a selector
    string, this method will return a jQuery object, using the current element
    as its buffer.

    For example, calling `view.$('li')` will return a jQuery object containing
    all of the `li` elements inside the DOM element of this view.

    @param {String} [selector] a jQuery-compatible selector string
    @returns {SC.CoreQuery} the CoreQuery object for the DOM node
  */
  $: function(sel) {
    return this.invokeForState('$', sel);
  },

  /** @private */
  mutateChildViews: function(callback) {
    var childViews = get(this, 'childViews'),
        idx = get(childViews, 'length'),
        view;

    while(--idx >= 0) {
      view = childViews[idx];
      callback.call(this, view, idx);
    }

    return this;
  },

  /** @private */
  forEachChildView: function(callback) {
    var childViews = get(this, 'childViews'),
        len = get(childViews, 'length'),
        view, idx;

    for(idx = 0; idx < len; idx++) {
      view = childViews[idx];
      callback.call(this, view);
    }

    return this;
  },

  /**
    Appends the view's element to the specified parent element.

    If the view does not have an HTML representation yet, `createElement()`
    will be called automatically.

    Note that this method just schedules the view to be appended; the DOM
    element will not be appended to the given element until all bindings have
    finished synchronizing.

    @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object
    @returns {SC.View} receiver
  */
  appendTo: function(target) {
    // Schedule the DOM element to be created and appended to the given
    // element after bindings have synchronized.
    this._insertElementLater(function() {
      this.$().appendTo(target);
    });

    return this;
  },

  /**
    @private

    Schedules a DOM operation to occur during the next render phase. This
    ensures that all bindings have finished synchronizing before the view is
    rendered.

    To use, pass a function that performs a DOM operation..

    Before your function is called, this view and all child views will receive
    the `willInsertElement` event. After your function is invoked, this view
    and all of its child views will receive the `didInsertElement` event.

        view._insertElementLater(function() {
          this.createElement();
          this.$().appendTo('body');
        });

    @param {Function} fn the function that inserts the element into the DOM
  */
  _insertElementLater: function(fn) {
    SC.run.schedule('render', this, 'invokeForState', 'insertElement', fn);
  },

  /**
    Appends the view's element to the document body. If the view does
    not have an HTML representation yet, `createElement()` will be called
    automatically.

    Note that this method just schedules the view to be appended; the DOM
    element will not be appended to the document body until all bindings have
    finished synchronizing.

    @returns {SC.View} receiver
  */
  append: function() {
    return this.appendTo(document.body);
  },

  /**
    Removes the view's element from the element to which it is attached.

    @returns {SC.View} receiver
  */
  remove: function() {
    // What we should really do here is wait until the end of the run loop
    // to determine if the element has been re-appended to a different
    // element.
    // In the interim, we will just re-render if that happens. It is more
    // important than elements get garbage collected.
    this.destroyElement();
  },

  /**
    The ID to use when trying to locate the element in the DOM. If you do not
    set the elementId explicitly, then the view's GUID will be used instead.
    This ID must be set at the time the view is created.

    @type String
    @readOnly
  */
  elementId: function(key, value) {
    return value !== undefined ? value : SC.guidFor(this);
  }.property().cacheable(),

  /**
    Attempts to discover the element in the parent element. The default
    implementation looks for an element with an ID of elementId (or the view's
    guid if elementId is null). You can override this method to provide your
    own form of lookup. For example, if you want to discover your element
    using a CSS class name instead of an ID.

    @param {DOMElement} parentElement The parent's DOM element
    @returns {DOMElement} The discovered element
  */
  findElementInParentElement: function(parentElem) {
    var id = "#" + get(this, 'elementId');
    return jQuery(id)[0] || jQuery(id, parentElem)[0];
  },

  /**
    Creates a new renderBuffer with the passed tagName. You can override this
    method to provide further customization to the buffer if needed. Normally
    you will not need to call or override this method.

    @returns {SC.RenderBuffer}
  */
  renderBuffer: function(tagName) {
    return SC.RenderBuffer(tagName || get(this, 'tagName') || 'div');
  },

  /**
    Creates a DOM representation of the view and all of its
    child views by recursively calling the `render()` method.

    After the element has been created, `didCreateElement` will
    be called on this view and all of its child views.

    @returns {SC.View} receiver
  */
  createElement: function() {
    if (get(this, 'element')) { return this; }

    var buffer = this.renderToBuffer();
    set(this, 'element', buffer.element());

    return this;
  },

  /**
    Called when the element of the view is created but before it is inserted
    into the DOM.  Override this function to do any set up that requires an
    element.
  */
  willInsertElement: SC.K,

  /**
    Called when the element of the view has been inserted into the DOM.
    Override this function to do any set up that requires an element in the
    document body.
  */
  didInsertElement: SC.K,

  /**
    Run this callback on the current view and recursively on child views.

    @private
  */
  invokeRecursively: function(fn) {
    fn.call(this, this);

    this.forEachChildView(function(view) {
      view.invokeRecursively(fn);
    });
  },

  /**
    Invalidates the cache for a property on all child views.
  */
  invalidateRecursively: function(key) {
    this.forEachChildView(function(view) {
      view.propertyDidChange(key);
    });
  },

  /**
    @private

    Invokes the receiver's willInsertElement() method if it exists and then
    invokes the same on all child views.
  */
  _notifyWillInsertElement: function() {
    this.invokeRecursively(function(view) {
      view.willInsertElement();
    });
  },

  /**
    @private

    Invokes the receiver's didInsertElement() method if it exists and then
    invokes the same on all child views.
  */
  _notifyDidInsertElement: function() {
    this.invokeRecursively(function(view) {
      view.didInsertElement();
    });
  },

  /**
    Destroys any existing element along with the element for any child views
    as well. If the view does not currently have a element, then this method
    will do nothing.

    If you implement willDestroyElement() on your view, then this method will
    be invoked on your view before your element is destroyed to give you a
    chance to clean up any event handlers, etc.

    If you write a willDestroyElement() handler, you can assume that your
    didCreateElement() handler was called earlier for the same element.

    Normally you will not call or override this method yourself, but you may
    want to implement the above callbacks when it is run.

    @returns {SC.View} receiver
  */
  destroyElement: function() {
    return this.invokeForState('destroyElement');
  },

  /**
    Called when the element of the view is going to be destroyed. Override
    this function to do any teardown that requires an element, like removing
    event listeners.
  */
  willDestroyElement: function() {},

  /**
    @private

    Invokes the `willDestroyElement` callback on the view and child views.
  */
  _notifyWillDestroyElement: function() {
    this.invokeRecursively(function(view) {
      view.willDestroyElement();
    });
  },

  /** @private (nodoc) */
  _elementWillChange: function() {
    this.forEachChildView(function(view) {
      SC.propertyWillChange(view, 'element');
    });
  }.observesBefore('element'),

  /**
    @private

    If this view's element changes, we need to invalidate the caches of our
    child views so that we do not retain references to DOM elements that are
    no longer needed.

    @observes element
  */
  _elementDidChange: function() {
    this.forEachChildView(function(view) {
      SC.propertyDidChange(view, 'element');
    });
  }.observes('element'),

  /**
    Called when the parentView property has changed.

    @function
  */
  parentViewDidChange: SC.K,

  /**
    @private

    Invoked by the view system when this view needs to produce an HTML
    representation. This method will create a new render buffer, if needed,
    then apply any default attributes, such as class names and visibility.
    Finally, the `render()` method is invoked, which is responsible for
    doing the bulk of the rendering.

    You should not need to override this method; instead, implement the
    `template` property, or if you need more control, override the `render`
    method.

    @param {SC.RenderBuffer} buffer the render buffer. If no buffer is
      passed, a default buffer, using the current view's `tagName`, will
      be used.
  */
  renderToBuffer: function(parentBuffer, bufferOperation) {
    var viewMeta = meta(this)['SC.View'];
    var buffer;

    SC.run.sync();

    // Determine where in the parent buffer to start the new buffer.
    // By default, a new buffer will be appended to the parent buffer.
    // The buffer operation may be changed if the child views array is
    // mutated by SC.ContainerView.
    bufferOperation = bufferOperation || 'begin';

    // If this is the top-most view, start a new buffer. Otherwise,
    // create a new buffer relative to the original using the
    // provided buffer operation (for example, `insertAfter` will
    // insert a new buffer after the "parent buffer").
    if (parentBuffer) {
      buffer = parentBuffer[bufferOperation](get(this, 'tagName') || 'div');
    } else {
      buffer = this.renderBuffer();
    }

    viewMeta.buffer = buffer;
    this.transitionTo('inBuffer');

    viewMeta.lengthBeforeRender = getPath(this, 'childViews.length');

    this.applyAttributesToBuffer(buffer);
    this.render(buffer);

    viewMeta.lengthAfterRender = getPath(this, 'childViews.length');

    return buffer;
  },

  /**
    @private
  */
  applyAttributesToBuffer: function(buffer) {
    // Creates observers for all registered class name and attribute bindings,
    // then adds them to the element.
    this._applyClassNameBindings();

    // Pass the render buffer so the method can apply attributes directly.
    // This isn't needed for class name bindings because they use the
    // existing classNames infrastructure.
    this._applyAttributeBindings(buffer);

    buffer.addClass(get(this, 'classNames').join(' '));
    buffer.id(get(this, 'elementId'));

    var role = get(this, 'ariaRole');
    if (role) {
      buffer.attr('role', role);
    }

    if (!get(this, 'isVisible')) {
      buffer.style('display', 'none');
    }
  },

  // ..........................................................
  // STANDARD RENDER PROPERTIES
  //

  /**
    Tag name for the view's outer element. The tag name is only used when
    an element is first created. If you change the tagName for an element, you
    must destroy and recreate the view element.

    By default, the render buffer will use a `<div>` tag for views.

    @type String
    @default null
  */

  // We leave this null by default so we can tell the difference between
  // the default case and a user-specified tag.
  tagName: null,

  /**
    The WAI-ARIA role of the control represented by this view. For example, a
    button may have a role of type 'button', or a pane may have a role of
    type 'alertdialog'. This property is used by assistive software to help
    visually challenged users navigate rich web applications.

    The full list of valid WAI-ARIA roles is available at:
    http://www.w3.org/TR/wai-aria/roles#roles_categorization

    @type String
    @default null
  */
  ariaRole: null,

  /**
    Standard CSS class names to apply to the view's outer element. This
    property automatically inherits any class names defined by the view's
    superclasses as well.

    @type Array
    @default ['sc-view']
  */
  classNames: ['sc-view'],

  /**
    A list of properties of the view to apply as class names. If the property
    is a string value, the value of that string will be applied as a class
    name.

        // Applies the 'high' class to the view element
        SC.View.create({
          classNameBindings: ['priority']
          priority: 'high'
        });

    If the value of the property is a Boolean, the name of that property is
    added as a dasherized class name.

        // Applies the 'is-urgent' class to the view element
        SC.View.create({
          classNameBindings: ['isUrgent']
          isUrgent: true
        });

    If you would prefer to use a custom value instead of the dasherized
    property name, you can pass a binding like this:

        // Applies the 'urgent' class to the view element
        SC.View.create({
          classNameBindings: ['isUrgent:urgent']
          isUrgent: true
        });

    This list of properties is inherited from the view's superclasses as well.

    @type Array
    @default []
  */
  classNameBindings: [],

  /**
    A list of properties of the view to apply as attributes. If the property is
    a string value, the value of that string will be applied as the attribute.

        // Applies the type attribute to the element
        // with the value "button", like <div type="button">
        SC.View.create({
          attributeBindings: ['type'],
          type: 'button'
        });

    If the value of the property is a Boolean, the name of that property is
    added as an attribute.

        // Renders something like <div enabled="enabled">
        SC.View.create({
          attributeBindings: ['enabled'],
          enabled: true
        });
  */
  attributeBindings: [],

  // .......................................................
  // CORE DISPLAY METHODS
  //

  /**
    @private

    Setup a view, but do not finish waking it up.
    - configure childViews
    - register the view with the global views hash, which is used for event
      dispatch
  */
  init: function() {
    set(this, 'state', 'preRender');

    var parentView = get(this, 'parentView');

    this._super();

    // Register the view for event handling. This hash is used by
    // SC.RootResponder to dispatch incoming events.
    SC.View.views[get(this, 'elementId')] = this;

    var childViews = get(this, 'childViews').slice();
    // setup child views. be sure to clone the child views array first
    set(this, 'childViews', childViews);

    this.mutateChildViews(function(viewName, idx) {
      var view;

      if ('string' === typeof viewName) {
        view = get(this, viewName);
        view = this.createChildView(view);
        childViews[idx] = view;
        set(this, viewName, view);
      } else if (viewName.isClass) {
        view = this.createChildView(viewName);
        childViews[idx] = view;
      }
    });

    this.classNameBindings = get(this, 'classNameBindings').slice();
    this.classNames = get(this, 'classNames').slice();

    meta(this)["SC.View"] = {};
  },

  appendChild: function(view, options) {
    return this.invokeForState('appendChild', view, options);
  },

  /**
    Removes the child view from the parent view.

    @param {SC.View} view
    @returns {SC.View} receiver
  */
  removeChild: function(view) {
    // update parent node
    set(view, 'parentView', null);

    // remove view from childViews array.
    var childViews = get(this, 'childViews');
    childViews.removeObject(view);

    return this;
  },

  /**
    Removes all children from the parentView.

    @returns {SC.View} receiver
  */
  removeAllChildren: function() {
    return this.mutateChildViews(function(view) {
      this.removeChild(view);
    });
  },

  destroyAllChildren: function() {
    return this.mutateChildViews(function(view) {
      view.destroy();
    });
  },

  /**
    Removes the view from its parentView, if one is found. Otherwise
    does nothing.

    @returns {SC.View} receiver
  */
  removeFromParent: function() {
    var parent = get(this, 'parentView');

    // Remove DOM element from parent
    this.remove();

    if (parent) { parent.removeChild(this); }
    return this;
  },

  /**
    You must call this method on a view to destroy the view (and all of its
    child views). This will remove the view from any parent node, then make
    sure that the DOM element managed by the view can be released by the
    memory manager.
  */
  destroy: function() {
    if (get(this, 'isDestroyed')) { return; }

    // calling this._super() will nuke computed properties and observers,
    // so collect any information we need before calling super.
    var viewMeta   = meta(this)['SC.View'],
        childViews = get(this, 'childViews'),
        parent     = get(this, 'parentView'),
        elementId  = get(this, 'elementId'),
        childLen   = childViews.length;

    // destroy the element -- this will avoid each child view destroying
    // the element over and over again...
    this.destroyElement();

    // remove from parent if found. Don't call removeFromParent,
    // as removeFromParent will try to remove the element from
    // the DOM again.
    if (parent) { parent.removeChild(this); }
    SC.Descriptor.setup(this, 'state', 'destroyed');

    this._super();

    for (var i=childLen-1; i>=0; i--) {
      childViews[i].destroy();
    }

    // next remove view from global hash
    delete SC.View.views[get(this, 'elementId')];

    return this; // done with cleanup
  },

  /**
    Instantiates a view to be added to the childViews array during view
    initialization. You generally will not call this method directly unless
    you are overriding createChildViews(). Note that this method will
    automatically configure the correct settings on the new view instance to
    act as a child of the parent.

    @param {Class} viewClass
    @param {Hash} [attrs] Attributes to add
    @returns {SC.View} new instance
    @test in createChildViews
  */
  createChildView: function(view, attrs) {
    if (SC.View.detect(view)) {
      view = view.create(attrs || {}, { parentView: this });
    } else {
      sc_assert('must pass instance of View', view instanceof SC.View);
      set(view, 'parentView', this);
    }
    return view;
  },

  /**
    @private

    When the view's `isVisible` property changes, toggle the visibility
    element of the actual DOM element.
  */
  _isVisibleDidChange: function() {
    this.$().toggle(get(this, 'isVisible'));
  }.observes('isVisible'),

  clearBuffer: function() {
    this.invokeRecursively(function(view) {
      meta(view)['SC.View'].buffer = null;
    });
  },

  transitionTo: function(state, children) {
    set(this, 'state', state);

    if (children !== false) {
      this.forEachChildView(function(view) {
        view.transitionTo(state);
      });
    }
  }

});

/**
  Describe how the specified actions should behave in the various
  states that a view can exist in. Possible states:

  * preRender: when a view is first instantiated, and after its
    element was destroyed, it is in the preRender state
  * inBuffer: once a view has been rendered, but before it has
    been inserted into the DOM, it is in the inBuffer state
  * inDOM: once a view has been inserted into the DOM it is in
    the inDOM state. A view spends the vast majority of its
    existence in this state.
  * destroyed: once a view has been destroyed (using the destroy
    method), it is in this state. No further actions can be invoked
    on a destroyed view.
*/

  // in the destroyed state, everything is illegal

  // before rendering has begun, all legal manipulations are noops.

  // inside the buffer, legal manipulations are done on the buffer

  // once the view has been inserted into the DOM, legal manipulations
  // are done on the DOM element.

SC.View.reopen({
  states: SC.View.states
});

// Create a global view hash.
SC.View.views = {};


text:
@interface ImageTableViewController : UITableViewController

@property (nonatomic) NSString *city;

@end


text:
using System;
using Android.App;
using Android.Runtime;
using ReactiveUI;

namespace Gitter.Android
{
    [Application(Label = "Gitter", Theme = "@android:style/Theme.Holo.Light",
#if DEBUG
 Debuggable = true
#else
 Debuggable = false
#endif
)]
    public class AndroidApplication : Application
    {
        private AutoSuspendHelper autoSuspendHelper;

        public AndroidApplication(IntPtr handle, JniHandleOwnership transfer)
            : base(handle, transfer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();

            autoSuspendHelper = new AutoSuspendHelper(this);
            RxApp.SuspensionHost.CreateNewAppState = () => new AppBootstrapper();

            RxApp.SuspensionHost.SetupDefaultSuspendResume();
        }
    }
}


text:
title: Introduction
keywords: homepage
sidebar: overview_sidebar
permalink: index.html
toc: true
summary: A brief introduction to getting started with NHS Digital's implementation of OpenID Connect.
---

These pages provide an introduction to NHS Digital's implementation of the OpenID Connect specifications.

An introduction to OpenID Connect and a detailed description of the Authorization Code Flow which is the basis of NHS Digital's implementation can be found [here](explore_intro_to_oidc).

An introduction to the NHS Digital implentation of and a detailed description of its online and offline modes of operation can be found [here](develop_intro_to_nhs_impl).