text:
"""Module for implementing the Coordinate search."""

import os
from string import Template
import sys
from search.common import exceptions
from search.common import geconstants
from search.common import utils
from search.plugin import coordinate_transform

class CoordinateSearch(object):
  """Class for performing the Coordinate search.

  Coordinate search supports the following formats:
  1. Decimal Degrees (DD)
  2. Degrees Minutes Seconds (DMS)
  3. Degrees Decimal Minutes (DDM)
  4. Military Grid Reference System (MGRS)
  5. Universal Transverse Mercator (UTM)

  Coordinate search transforms coordinates from DMS, DDM, UTM, MGRS formats to
  DD, validates the coordinates and sends the response back to the client.
  Depending on the client type, KML or JSONP formats are supported.
  """

  NUM_OF_COORDS_IN_LAT_LNG_FORMAT = 2
  NUM_OF_COORDS_IN_MGRS_FORMAT = 1

  def __init__(self):
    """Inits CoordinateSearch.

    Initializes the logger "ge_search".
    Initializes templates for kml, placemark templates for KML/JSONP outputs.
    """

    self.utils = utils.SearchUtils()
    self._transform = coordinate_transform.CoordinateTransform()

    configs = self.utils.GetConfigs(
        os.path.join(geconstants.SEARCH_CONFIGS_DIR, "CoordinateSearch.conf"))

    self._jsonp_call = self.utils.jsonp_functioncall

    self._geom = """
             <name>%s</name>
             <styleUrl>%s</styleUrl>
             <Point>
               <coordinates>%s,%s</coordinates>
             </Point>\
    """
    self._json_geom = """
       {
         "Point": {
                "coordinates": "%s,%s"
          }
       }
    """
    self._kml = """

    <kml xmlns="http://www.opengis.net/kml/2.2"
         xmlns:gx="http://www.google.com/kml/ext/2.2"
         xmlns:kml="http://www.opengis.net/kml/2.2"
         xmlns:atom="http://www.w3.org/2005/Atom">
       <Folder>
         <name>Coordinate Search Results</name>
         <open>1</open>
         <Style id="placemark_label">\
            ${style}
         </Style>\
         ${placemark}
        </Folder>
    </kml>

    """
    self._kml_template = Template(self._kml)

    self._placemark_template = self.utils.placemark_template

    self._json_template = self.utils.json_template
    self._json_placemark_template = self.utils.json_placemark_template
    style_template = self.utils.style_template
    self.coordinates_in_lat_lng_format_ = ["DD", "DMS", "DDM"]

    self.logger = self.utils.logger

    self._style = style_template.substitute(
        balloonBgColor=configs.get("balloonstyle.bgcolor"),
        balloonTextColor=configs.get("balloonstyle.textcolor"),
        balloonText=configs.get("balloonstyle.text"),
        iconStyleScale=configs.get("iconstyle.scale"),
        iconStyleHref=configs.get("iconstyle.href"),
        lineStyleColor=configs.get("linestyle.color"),
        lineStyleWidth=configs.get("linestyle.width"),
        polyStyleColor=configs.get("polystyle.color"),
        polyStyleColorMode=configs.get("polystyle.colormode"),
        polyStyleFill=configs.get("polystyle.fill"),
        polyStyleOutline=configs.get("polystyle.outline"),
        listStyleHref=configs.get("iconstyle.href"))

  def HandleSearchRequest(self, environ):
    """Fetches the search tokens from form and performs the coordinate search.

    Args:
     environ: A list of environment variables as supplied by the
      WSGI interface to the coordinate search application interface.
    Returns:
     search_results: A KML/JSONP formatted string which contains search results.
    Raises:
     BadQueryException: if the search query is invalid.
    """
    search_results = ""

    # Fetch all the attributes provided by the user.
    parameters = self.utils.GetParameters(environ)
    response_type = self.utils.GetResponseType(environ)

    # Retrieve the function call back name for JSONP response.
    self.f_callback = self.utils.GetCallback(parameters)

    original_query = self.utils.GetValue(parameters, "q")

    if not original_query:
      msg = "Empty search query received."
      self.logger.error(msg)
      raise exceptions.BadQueryException(msg)

    search_status, search_results = self.DoSearch(original_query, response_type)

    if not search_status:
      folder_name = "Search returned no results."
      search_results = self.utils.NoSearchResults(
          folder_name, self._style, response_type, self.f_callback)

    return (search_results, response_type)

  def DoSearch(self, search_query, response_type):
    """Performs the coordinate search.

    Args:
     search_query: A string containing the search coordinates as
      entered by the user.
     response_type: Response type can be KML or JSONP, depending on the client.
    Returns:
     search_results: A KML/JSONP formatted string which contains search results.
    Raises:
     BadQueryException: if the search query is invalid.
    """
    coordinate_type = ""
    search_results = ""

    input_coordinates = []
    decimal_degrees_coordinates = []

    search_tokens = self.utils.SearchTokensFromString(search_query)
    self.logger.debug("coordinates: %s", ",".join(search_tokens))
    input_coordinates = self._transform.GetInputCoordinates(
        ",".join(search_tokens))
    number_of_coordinates = len(input_coordinates)

    if number_of_coordinates == 0:
      msg = "Incomplete search query %s submitted" % search_query
      self.logger.error(msg)
      raise exceptions.BadQueryException(msg)

    coordinate_type = self._transform.GetInputType(input_coordinates)

    self.logger.debug("Coordinate type is %s.", coordinate_type)

    if coordinate_type in self.coordinates_in_lat_lng_format_:
      reqd_num_of_coordinates = CoordinateSearch.NUM_OF_COORDS_IN_LAT_LNG_FORMAT
    else:
      reqd_num_of_coordinates = CoordinateSearch.NUM_OF_COORDS_IN_MGRS_FORMAT

    if number_of_coordinates > reqd_num_of_coordinates:
      self.logger.warning(
          "extra search parameters ignored: %s", ",".join(
              input_coordinates[reqd_num_of_coordinates:]))
      input_coordinates = input_coordinates[:reqd_num_of_coordinates]
    elif number_of_coordinates < reqd_num_of_coordinates:
      msg = "Incomplete search query %s submitted" % search_query
      self.logger.error(msg)
      raise exceptions.BadQueryException(msg)

    decimal_degrees_coordinates = self._transform.TransformToDecimalDegrees(
        coordinate_type, input_coordinates)

    search_results = self.ConstructResponse(
        response_type, decimal_degrees_coordinates)

    search_status = True if search_results else False

    return search_status, search_results

  def ConstructKMLResponse(self, latitude, longitude):
    """Prepares KML response.

    KML response has the below format:
      <kml>
       <Folder>
       <name/>
       <StyleURL>
             ---
       </StyleURL>
       <Point>
              <coordinates/>
       </Point>
       </Folder>
      </kml>

    Args:
     latitude: latitude in Decimal Degress format.
     longitude: longitude in Decimal Degress format.
    Returns:
     kml_response: KML formatted response.
    """

    placemark = ""
    kml_response = ""

    name = "%s, %s" % (latitude, longitude)
    style_url = "#placemark_label"
    geom = self._geom % (name, style_url, str(longitude), str(latitude))
    placemark = self._placemark_template.substitute(geom=geom)
    kml_response = self._kml_template.substitute(
        style=self._style, placemark=placemark)

    self.logger.info("KML response successfully formatted")

    return kml_response

  def ConstructJSONPResponse(self, latitude, longitude):
    """Prepares JSONP response.

      {
               "Folder": {
                 "name": "X,Y",
                 "Style": {
                     "IconStyle": {"scale": "1" },
                   "LineStyle": {
                       "color": "7fffff00",
                       "width": "5" },
                   "PolyStyle": {
                       "color": "7f66ffff",
                       "fill": "1",
                       "outline": "1" } },
                 "Placemark": {
                    "Point": {
                      "coordinates": "X,Y" } }
                 }
       }
    Args:
     latitude: latitude in Decimal Degress format.
     longitude: longitude in Decimal Degress format.
    Returns:
     jsonp_response: JSONP formatted response.
    """
    placemark = ""
    json_response = ""
    jsonp_response = ""

    folder_name = "%s, %s" % (latitude, longitude)
    json_geom = self._json_geom % (latitude, longitude)

    placemark = self._json_placemark_template.substitute(
        geom=json_geom)
    json_response = self._json_template.substitute(
        foldername=folder_name, json_placemark=placemark)

    # Escape single quotes from json_response.
    json_response = json_response.replace("'", "\\'")

    jsonp_response = self._jsonp_call % (self.f_callback, json_response)

    self.logger.info("JSONP response successfully formatted")

    return jsonp_response

  def ConstructResponse(self, response_type, decimal_degrees_coordinates):
    """Construct the response based on response_type.

    Args:
     response_type: Response type can be KML or JSONP, depending on the client.
     decimal_degrees_coordinates: List of coordinates in DD(Decimal Degrees)
      format.
    Returns:
     search_results: A KML/JSONP formatted string which contains search results.
    """
    search_results = ""

    assert response_type in self.utils.output_formats, (
        self.logger.error("Invalid response type %s", response_type))

    if response_type == "KML":
      search_results = self.ConstructKMLResponse(
          decimal_degrees_coordinates[0], decimal_degrees_coordinates[1])
    elif response_type == "JSONP":
      search_results = self.ConstructJSONPResponse(
          decimal_degrees_coordinates[0], decimal_degrees_coordinates[1])

    return search_results

def main(coords, response_type):
  gepobj = CoordinateSearch()
  gepobj.DoSearch(coords, response_type)

if __name__ == "__main__":
  main(sys.argv[1], sys.argv[2])


text:
@echo off
NuGet Pack YoulessNet.nuspec
Copy /B *.nupkg YoulessNet.nuspec.nupkg
NuGet Push YoulessNet.nuspec.nupkg
Erase *.nupkg
Pause

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<merger version="3"><dataSet config="main"><source path="D:\Android\workspace\QR_CodeScan\app\src\androidTest\assets"/></dataSet></merger>


text:
"""
============
R Dataframes
============

:Author:
    Moritz Emanuel Beber
:Date:
    2010-11-29
:Copyright:
    Copyright(c) 2010 Jacobs University of Bremen. All rights reserved.
:File:
    dataframes.py
"""

import numpy
import rpy2.robjects as r_objects
import rpy2.rinterface as ri
import rpy2.robjects.numpy2ri # automatic shared memory between numpy and R
r_objects.conversion.py2ri = rpy2.robjects.numpy2ri.numpy2ri
r_objects.conversion.ri2numpy = rpy2.robjects.numpy2ri.ri2numpy

from collections import defaultdict

def one_dimensional(observables):
    """
    Parameters
    ----------
    observables : Can be one of the following types of containers
        1. An iterable of shape len(observables) x 1.
        2. A dictionary, in which case keys are taken as labels for the data
           and values are as in 1.
        3. A ``dict`` of ``dict``, allowing for combinations of labels to form
           a 2D facet grid, values are as in 1.

    Returns
    -------
    An rpy2.robjects.DataFrame with one column ``xpos``. Additional columns
    ``label`` and ``label_2`` may be present.
    """
    # collect the observables into a table
    data = defaultdict(list)
    if isinstance(observables, dict):
        for (label, content) in observables.iteritems():
            if isinstance(content, dict):
                for (label_2, real_data) in content.iteritems():
                    data["label"].extend([label] * len(real_data))
                    data["label_2"].extend([label_2] * len(real_data))
                    data["xpos"].extend(real_data)
            else:
                data["label"].extend([label] * len(content))
                data["xpos"].extend(content)
    elif isinstance(observables, list):
        data["xpos"] = observables
    elif isinstance(observables, numpy.array):
        assert observables.shape == (len(observables),)
        data["xpos"] = observables
        return r_objects.DataFrame(data)
    else:
        raise(ValueError("Wrong data container type!"))
    # convert to R-compatible data containers
    if data.has_key("label_2"):
        data["label_2"] = r_objects.FactorVector(data["label_2"])
    if data.has_key("label"):
        data["label"] = r_objects.FactorVector(data["label"])
    data["xpos"] = numpy.array(data["xpos"])
    return r_objects.DataFrame(data)

def two_dimensional(observables):
    """
    Parameters
    ----------
    observables : Can be one of the following types of containers:
        1. An iterable of shape len(observables) x 2.
        2. A dictionary, in which case keys are taken as labels for the data
           and values are as in 1.
        3. A ``dict`` of ``dict``, allowing for combinations of labels to form
           a 2D facet grid, values are as in 1.

    Returns
    -------
    An rpy2.robjects.DataFrame with two columns ``xpos`` and ``ypos``. Additional
    columns ``label`` and ``label_2`` may be present.
    """
    # collect the observables into a table
    data = defaultdict(list)
    if isinstance(observables, dict):
        for (label, content) in observables.iteritems():
            if isinstance(content, dict):
                for (label_2, real_data) in content.iteritems():
                    data["label"].extend([label] * len(real_data))
                    data["label_2"].extend([label_2] * len(real_data))
                    data["xpos"].extend([pair[0] for pair in real_data])
                    data["ypos"].extend([pair[1] for pair in real_data])
            else:
                data["label"].extend([label] * len(content))
                data["xpos"].extend([pair[0] for pair in content])
                data["ypos"].extend([pair[1] for pair in content])
    elif isinstance(observables, list):
        data["xpos"].extend([pair[0] for pair in observables])
        data["ypos"].extend([pair[1] for pair in observables])
    elif isinstance(observables, numpy.array):
        assert observables.shape == (len(observables), 2)
        data["xpos"] = observables[:, 0]
        data["ypos"] = observables[:, 1]
        return r_objects.DataFrame(data)
    else:
        raise(ValueError("Wrong data container type!"))
    # convert to R-compatible data containers
    if data.has_key("label_2"):
        data["label_2"] = r_objects.FactorVector(data["label_2"])
    if data.has_key("label"):
        data["label"] = r_objects.FactorVector(data["label"])
    data["xpos"] = numpy.array(data["xpos"])
    data["ypos"] = numpy.array(data["ypos"])
    return r_objects.DataFrame(data)

def two_dimensional_with_label(observables):
    """
    Parameters
    ----------
    observables : iterable
        An iterable of three tuples.

    Returns
    -------
    An rpy2.robjects.DataFrame with three columns ``xpos``, ``ypos``, and
    ``label``.
    """
    # collect the observables into a table
    data = defaultdict(list)
    if isinstance(observables, list):
        data["xpos"].extend([triple[0] for triple in observables])
        data["ypos"].extend([triple[1] for triple in observables])
        data["label"].extend([triple[2] for triple in observables])
    else:
        raise(ValueError("Wrong data container type!"))
    # convert to R-compatible data containers
    if data.has_key("label"):
        data["label"] = r_objects.FactorVector(data["label"])
    data["xpos"] = numpy.array(data["xpos"])
    data["ypos"] = numpy.array(data["ypos"])
    return r_objects.DataFrame(data)

def two_dimensional_y_uncertainty(observables):
    """
    Parameters
    ----------
    observables : Can be one of the following types of containers:
        1. An iterable of shape len(observables) x 3.
        2. A dictionary, in which case keys are taken as labels for the data
           and values are as in 1.
        3. A ``dict`` of ``dict``, allowing for combinations of labels to form
           a 2D facet grid, values are as in 1.

    Returns
    -------
    An rpy2.robjects.DataFrame with four columns ``xpos``, ``ypos``, ``ymin``,
    and ``ymax``. Additional columns ``label`` and ``label_2`` may be present.
    """
    # collect the observables into a table
    data = defaultdict(list)
    if isinstance(observables, dict):
        for (label, content) in observables.iteritems():
            if isinstance(content, dict):
                for (label_2, real_data) in content.iteritems():
                    data["label"].extend([label] * len(real_data))
                    data["label_2"].extend([label_2] * len(real_data))
                    data["xpos"].extend([triple[0] for triple in real_data])
                    data["ypos"].extend([triple[1] for triple in real_data])
                    data["ymin"].extend([(triple[1] - triple[2])\
                            for triple in real_data])
                    data["ymax"].extend([(triple[1] + triple[2])\
                            for triple in real_data])
            else:
                data["label"].extend([label] * len(content))
                data["xpos"].extend([triple[0] for triple in content])
                data["ypos"].extend([triple[1] for triple in content])
                data["ymin"].extend([(triple[1] - triple[2])\
                        for triple in content])
                data["ymax"].extend([(triple[1] + triple[2])\
                        for triple in content])
    elif isinstance(observables, list):
        data["xpos"].extend([triple[0] for triple in observables])
        data["ypos"].extend([triple[1] for triple in observables])
        data["ymin"].extend([(triple[1] - triple[2])\
                for triple in observables])
        data["ymax"].extend([(triple[1] + triple[2])\
                for triple in observables])
    elif isinstance(observables, numpy.array):
        assert observables.shape == (len(observables), 3)
        data["xpos"] = observables[:, 0]
        data["ypos"] = observables[:, 1]
        data["ymin"] = observables[:, 1] - observables[:, 2]
        data["ymax"] = observables[:, 1] + observables[:, 2]
        return r_objects.DataFrame(data)
    else:
        raise(ValueError("Wrong data container type!"))
    # convert to R-compatible data containers
    if data.has_key("label_2"):
        data["label_2"] = r_objects.FactorVector(data["label_2"])
    if data.has_key("label"):
        data["label"] = r_objects.FactorVector(data["label"])
    data["xpos"] = numpy.array(data["xpos"])
    data["ypos"] = numpy.array(data["ypos"])
    data["ymin"] = numpy.array(data["ymin"])
    data["ymax"] = numpy.array(data["ymax"])
    return r_objects.DataFrame(data)

def three_dimensional(observables):
    """
    Parameters
    ----------
    observables : Can be one of the following types of containers:
        1. An iterable of shape len(observables) x 3.
        2. A dictionary, in which case keys are taken as labels for the data
           and values are as in 1.
        3. A ``dict`` of ``dict``, allowing for combinations of labels to form
           a 2D facet grid, values are as in 1.

    Returns
    -------
    An rpy2.robjects.DataFrame with three columns ``xpos``, ``ypos``, and
    ``zpos``. Additional columns ``label`` and ``label_2`` may be present.
    """
    # collect the observables into a table
    data = defaultdict(list)
    if isinstance(observables, dict):
        for (label, content) in observables.iteritems():
            if isinstance(content, dict):
                for (label_2, real_data) in content.iteritems():
                    data["label"].extend([label] * len(real_data))
                    data["label_2"].extend([label_2] * len(real_data))
                    data["xpos"].extend([triple[0] for triple in real_data])
                    data["ypos"].extend([triple[1] for triple in real_data])
                    data["zpos"].extend([triple[2] for triple in real_data])
            else:
                data["label"].extend([label] * len(content))
                data["xpos"].extend([triple[0] for triple in content])
                data["ypos"].extend([triple[1] for triple in content])
                data["zpos"].extend([triple[2] for triple in content])
    elif isinstance(observables, list):
        data["xpos"].extend([triple[0] for triple in observables])
        data["ypos"].extend([triple[1] for triple in observables])
        data["zpos"].extend([triple[2] for triple in observables])
    elif isinstance(observables, numpy.array):
        assert observables.shape == (len(observables), 3)
        data["xpos"] = observables[:, 0]
        data["ypos"] = observables[:, 1]
        data["zpos"] = observables[:, 2]
        return r_objects.DataFrame(data)
    else:
        raise(ValueError("Wrong data container type!"))
    # convert to R-compatible data containers
    if data.has_key("label_2"):
        data["label_2"] = r_objects.FactorVector(data["label_2"])
    if data.has_key("label"):
        data["label"] = r_objects.FactorVector(data["label"])
    data["xpos"] = numpy.array(data["xpos"])
    data["ypos"] = numpy.array(data["ypos"])
    data["zpos"] = numpy.array(data["zpos"])
    return r_objects.DataFrame(data)

def three_dimensional_with_label(observables):
    """
    Parameters
    ----------
    observables : iterable
        An iterable of four tuples.

    Returns
    -------
    An rpy2.robjects.DataFrame with three columns ``xpos``, ``ypos``, ``zpos``,
    and ``label``.
    """
    # collect the observables into a table
    data = defaultdict(list)
    if isinstance(observables, list):
        data["xpos"].extend([triple[0] for triple in observables])
        data["ypos"].extend([triple[1] for triple in observables])
        data["zpos"].extend([triple[2] for triple in observables])
        data["label"].extend([triple[3] for triple in observables])
    else:
        raise(ValueError("Wrong data container type!"))
    # convert to R-compatible data containers
    if data.has_key("label"):
        data["label"] = r_objects.FactorVector(data["label"])
    data["xpos"] = numpy.array(data["xpos"])
    data["ypos"] = numpy.array(data["ypos"])
    data["zpos"] = numpy.array(data["zpos"])
    return r_objects.DataFrame(data)

def three_dimensional_y_uncertainty(observables):
    """
    Parameters
    ----------
    observables : Can be one of the following types of containers:
        1. An iterable of shape len(observables) x 4. The expected format is
           x, y, std(y), z.
        2. A dictionary, in which case keys are taken as labels for the data
           and values are as in 1.
        3. A ``dict`` of ``dict``, allowing for combinations of labels to form
           a 2D facet grid, values are as in 1.

    Returns
    -------
    An rpy2.robjects.DataFrame with five columns ``xpos``, ``ypos``, ''ymin'',
    ''ymax'', and ``zpos``. Additional columns ``label`` and ``label_2`` may be
    present.
    """
    # collect the observables into a table
    data = defaultdict(list)
    if isinstance(observables, dict):
        for (label, content) in observables.iteritems():
            if isinstance(content, dict):
                for (label_2, real_data) in content.iteritems():
                    data["label"].extend([label] * len(real_data))
                    data["label_2"].extend([label_2] * len(real_data))
                    data["xpos"].extend([triple[0] for triple in real_data])
                    data["ypos"].extend([triple[1] for triple in real_data])
                    data["ymin"].extend([(triple[1] - triple[2])\
                            for triple in real_data])
                    data["ymax"].extend([(triple[1] + triple[2])\
                            for triple in real_data])
                    data["zpos"].extend([triple[3] for triple in real_data])
            else:
                data["label"].extend([label] * len(content))
                data["xpos"].extend([triple[0] for triple in content])
                data["ypos"].extend([triple[1] for triple in content])
                data["ymin"].extend([(triple[1] - triple[2])\
                        for triple in content])
                data["ymax"].extend([(triple[1] + triple[2])\
                        for triple in content])
                data["zpos"].extend([triple[3] for triple in content])
    elif isinstance(observables, list):
        data["xpos"].extend([triple[0] for triple in observables])
        data["ypos"].extend([triple[1] for triple in observables])
        data["ymin"].extend([(triple[1] - triple[2])\
                for triple in observables])
        data["ymax"].extend([(triple[1] + triple[2])\
                for triple in observables])
        data["zpos"].extend([triple[3] for triple in observables])
    elif isinstance(observables, numpy.array):
        assert observables.shape == (len(observables), 4)
        data["xpos"] = observables[:, 0]
        data["ypos"] = observables[:, 1]
        data["ymin"] = observables[:, 1] - observables[:, 2]
        data["ymax"] = observables[:, 1] + observables[:, 2]
        data["zpos"] = observables[:, 3]
        return r_objects.DataFrame(data)
    else:
        raise(ValueError("Wrong data container type!"))
    # convert to R-compatible data containers
    if data.has_key("label_2"):
        data["label_2"] = r_objects.FactorVector(data["label_2"])
    if data.has_key("label"):
        data["label"] = r_objects.FactorVector(data["label"])
    data["xpos"] = numpy.array(data["xpos"])
    data["ypos"] = numpy.array(data["ypos"])
    data["ymin"] = numpy.array(data["ymin"])
    data["ymax"] = numpy.array(data["ymax"])
    data["zpos"] = numpy.array(data["zpos"])
    return r_objects.DataFrame(data)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>Dollar 0.4.5195 Reference Package dollar.internal.runtime.script</title>
		<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="style" />

        	dollar.internal.runtime.script

Classes

            	ParserMainTest

            	ParserQuickTest

            	ParserSlowTest


text:
<?php

namespace Sonata\AdminBundle\Admin;

use Knp\Menu\ItemInterface;

/**
 * Stateless breadcrumbs builder (each method needs an Admin object).
 *
 * @author Grégoire Paris <postmaster@greg0ire.fr>
 */
final class BreadcrumbsBuilder implements BreadcrumbsBuilderInterface
{
    /**
     * {@inheritdoc}
     */
    public function getBreadcrumbs(AdminInterface $admin, $action)
    {
        $breadcrumbs = array();
        if ($admin->isChild()) {
            return $this->getBreadcrumbs($admin->getParent(), $action);
        }

        $menu = $this->buildBreadcrumbs($admin, $action);

        do {
            $breadcrumbs[] = $menu;
        } while ($menu = $menu->getParent());

        $breadcrumbs = array_reverse($breadcrumbs);
        array_shift($breadcrumbs);

        return $breadcrumbs;
    }

    /**
     * {@inheritdoc}
     * NEXT_MAJOR : make this method private.
     */
    public function buildBreadcrumbs(AdminInterface $admin, $action, ItemInterface $menu = null)
    {
        if (!$menu) {
            $menu = $admin->getMenuFactory()->createItem('root');

            $menu = $this->createMenuItem(
                $admin,
                $menu,
                'dashboard',
                'SonataAdminBundle',
                array('uri' => $admin->getRouteGenerator()->generate(
                    'sonata_admin_dashboard'
                ))
            );
        }

        $menu = $this->createMenuItem(
            $admin,
            $menu,
            sprintf('%s_list', $admin->getClassnameLabel()),
            null,
            array(
                'uri' => $admin->hasRoute('list') && $admin->isGranted('LIST') ?
                $admin->generateUrl('list') :
                null,
            )
        );

        $childAdmin = $admin->getCurrentChildAdmin();

        if ($childAdmin) {
            $id = $admin->getRequest()->get($admin->getIdParameter());

            $menu = $menu->addChild(
                $admin->toString($admin->getSubject()),
                array(
                    'uri' => $admin->hasRoute('edit') && $admin->isGranted('EDIT') ?
                    $admin->generateUrl('edit', array('id' => $id)) :
                    null,
                )
            );

            return $this->buildBreadcrumbs($childAdmin, $action, $menu);
        }

        if ('list' === $action && $admin->isChild()) {
            $menu->setUri(false);
        } elseif ('create' !== $action && $admin->hasSubject()) {
            $menu = $menu->addChild($admin->toString($admin->getSubject()));
        } else {
            $menu = $this->createMenuItem(
                $admin,
                $menu,
                sprintf('%s_%s', $admin->getClassnameLabel(), $action)
            );
        }

        return $menu;
    }

    /**
     * Creates a new menu item from a simple name. The name is normalized and
     * translated with the specified translation domain.
     *
     * @param AdminInterface $admin             used for translation
     * @param ItemInterface  $menu              will be modified and returned
     * @param string         $name              the source of the final label
     * @param string         $translationDomain for label translation
     * @param array          $options           menu item options
     *
     * @return ItemInterface
     */
    private function createMenuItem(
        AdminInterface $admin,
        ItemInterface $menu,
        $name,
        $translationDomain = null,
        $options = array()
    ) {
        return $menu->addChild(
            $admin->trans(
                $admin->getLabelTranslatorStrategy()->getLabel(
                    $name,
                    'breadcrumb',
                    'link'
                ),
                array(),
                $translationDomain
            ),
            $options
        );
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Struct LeastSquares
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Struct LeastSquares
   ">
    <meta name="generator" content="docfx 2.48.0.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Struct LeastSquares

Represents the result of a LeastSquares calculation of the form y = mX + b

Implements

IFormattable

IEquatable<LeastSquares>

Inherited Members

      Object.Equals(Object, Object)

      Object.ReferenceEquals(Object, Object)

      Object.GetType()

Namespace: LinqStatistics

Assembly: LinqStatistics.dll

Syntax

public struct LeastSquares : IFormattable, IEquatable<LeastSquares>

Constructors

    |
    Improve this Doc

    View Source

LeastSquares(Double, Double)

Declaration

public LeastSquares(double m, double b)

Parameters

        Type
        Name
        Description

        Double
        m

The slope

        Double
        b

The intercept

    |
    Improve this Doc

    View Source

LeastSquares(Double, Double, Double)

Declaration

public LeastSquares(double m, double b, double r2)

Parameters

        Type
        Name
        Description

        Double
        m

The slope

        Double
        b

The intercept

        Double
        r2

The R Squared correlation coefficient

Fields

    |
    Improve this Doc

    View Source

Empty

Empty instance - returned when EnumerableStats.LeastSquares is passed a singular matrix.
All members are zero.

Declaration

public static readonly LeastSquares Empty

Field Value

        Type
        Description

        LeastSquares

Properties

    |
    Improve this Doc

    View Source

B

B Coefficient for y = Mx + B
(i.e. y intercept)

Declaration

public double B { get; }

Property Value

        Type
        Description

        Double

    |
    Improve this Doc

    View Source

M

M Coefficient for y = Mx + B
(i.e. slope)

Declaration

public double M { get; }

Property Value

        Type
        Description

        Double

    |
    Improve this Doc

    View Source

RSquared

The R Squared correlation coefficient

Declaration

public double RSquared { get; }

Property Value

        Type
        Description

        Double

Methods

    |
    Improve this Doc

    View Source

Equals(LeastSquares)

Equals(T)

Declaration

public bool Equals(LeastSquares other)

Parameters

        Type
        Name
        Description

        LeastSquares
        other

Returns

        Type
        Description

        Boolean

True if other has equal m and b values

    |
    Improve this Doc

    View Source

Equals(Object)

Equals(Object)

Declaration

public override bool Equals(object obj)

Parameters

        Type
        Name
        Description

        Object
        obj

The object to compare to

Returns

        Type
        Description

        Boolean

True if obj is a LeastSquares and has equal m and b values

Overrides

ValueType.Equals(Object)

    |
    Improve this Doc

    View Source

GetHashCode()

GetHashCode()

Declaration

public override int GetHashCode()

Returns

        Type
        Description

        Int32

Hascode of the instance

Overrides

ValueType.GetHashCode()

    |
    Improve this Doc

    View Source

IsNaN(LeastSquares)

Determines if the LeastSquares argument has Not a Number elements

Declaration

public static bool IsNaN(LeastSquares ls)

Parameters

        Type
        Name
        Description

        LeastSquares
        ls

Returns

        Type
        Description

        Boolean

True if either M, B or RSquared is NaN

    |
    Improve this Doc

    View Source

Solve(Double)

Uses the calculated coefficients to solve Y for inputted X

Declaration

public double Solve(double x)

Parameters

        Type
        Name
        Description

        Double
        x

X value to solve for

Returns

        Type
        Description

        Double

Y value (y = Mx + B)

    |
    Improve this Doc

    View Source

SolveForX(Double)

Uses the calculated coefficients to solve X for inputted Y

Declaration

public double SolveForX(double y)

Parameters

        Type
        Name
        Description

        Double
        y

Y value to solve for

Returns

        Type
        Description

        Double

X value (x = (y - b) / m)

    |
    Improve this Doc

    View Source

ToFunc(LeastSquares)

Casts a LeastSqaures to a Function Solve(Double)

Declaration

public static Func<double, double> ToFunc(LeastSquares ls)

Parameters

        Type
        Name
        Description

        LeastSquares
        ls

The LeastSquares instance

Returns

        Type
        Description

        Func<Double, Double>

    |
    Improve this Doc

    View Source

ToString()

ToString()

Declaration

public override string ToString()

Returns

        Type
        Description

        String

Overrides

ValueType.ToString()

    |
    Improve this Doc

    View Source

ToString(IFormatProvider)

Declaration

public string ToString(IFormatProvider provider)

Parameters

        Type
        Name
        Description

        IFormatProvider
        provider

Returns

        Type
        Description

        String

    |
    Improve this Doc

    View Source

ToString(String)

Declaration

public string ToString(string format)

Parameters

        Type
        Name
        Description

        String
        format

Returns

        Type
        Description

        String

    |
    Improve this Doc

    View Source

ToString(String, IFormatProvider)

Declaration

public string ToString(string format, IFormatProvider provider)

Parameters

        Type
        Name
        Description

        String
        format

        IFormatProvider
        provider

Returns

        Type
        Description

        String

Operators

    |
    Improve this Doc

    View Source

Equality(LeastSquares, LeastSquares)

Equality operator (M, B and RSquared must be equal)

Declaration

public static bool operator ==(LeastSquares lhs, LeastSquares rhs)

Parameters

        Type
        Name
        Description

        LeastSquares
        lhs

        LeastSquares
        rhs

Returns

        Type
        Description

        Boolean

    |
    <a href="https://github.com/dkackman/LinqStatistics/new/master/apiSpec/new?filename=LinqStatistics_LeastSquares_op_Implicit_LinqStatistics_LeastSquares__System_Func_System_Double_System_Double_.md&value=---%0Auid%3A%20LinqStatistics.LeastSquares.op_Implicit(LinqStatistics.LeastSquares)~System.Func%7BSystem.Double%2CSystem.Double%7D%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

Implicit(LeastSquares to Func<Double, Double>)

Casts a LeastSqaures to a Function Solve(Double)

Declaration

public static implicit operator Func<double, double>(LeastSquares ls)

Parameters

        Type
        Name
        Description

        LeastSquares
        ls

The LeastSquares instance

Returns

        Type
        Description

        Func<Double, Double>

    |
    Improve this Doc

    View Source

Inequality(LeastSquares, LeastSquares)

Inequality operatory

Declaration

public static bool operator !=(LeastSquares lhs, LeastSquares rhs)

Parameters

        Type
        Name
        Description

        LeastSquares
        lhs

        LeastSquares
        rhs

Returns

        Type
        Description

        Boolean

Implements

      IFormattable

      IEquatable<T>

                    Improve this Doc

                    View Source

              Back to top

            Generated by DocFX


text:
"""
PyCOMPSs API - COMMONS - ERROR MESSAGES
=======================================
    This file defines the public PyCOMPSs error messages displayed
    by the api.
"""

def not_in_pycompss(decorator_name):
    """
    Retrieves the "not in PyCOMPSs scope" error message.

    :param decorator_name: Decorator name which requires the message.
    :return: String - Not in PyCOMPSs error message.
    """
    return "The " + decorator_name + \
           " decorator only works within PyCOMPSs framework."

def cast_env_to_int_error(what):
    """
    Retrieves the "can not cast from environment variable to integer" error
    message.

    :param what: Environment variable name.
    :return: String - Can not cast from environment variable to integer.
    """
    return "ERROR: " + what + " value cannot be cast from ENV variable to int"

def cast_string_to_int_error(what):
    """
    Retrieves the "can not cast from string to integer" error message.

    :param what: Environment variable name.
    :return: String - Can not cast from string to integer.
    """
    return "ERROR: " + what + " value cannot be cast from string to int"

def wrong_value(value_name, decorator_name):
    """
    Retrieves the "wrong value at decorator" error message.

    :param value_name: Wrong value's name
    :param decorator_name: Decorator name which requires the message.
    :return: String - Wrong value at decorator message.
    """
    return "ERROR: Wrong " + value_name + \
           " value at " + decorator_name + \
           " decorator."


text:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package mapviz
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

0.0.4 (2016-01-06)
------------------
* Show full path when recording screenshots/movies.
* Fixes a bug in plug-in sorting.
* Sorts topic, plug-in, and frame lists in selection dialogs.
* Fixes mapviz launch file frame parameter
* Marks single argument constructors explicit.
* Contributors: Edward Venator, Elliot Johnson, Marc Alban, Vincent Rousseau

0.0.3 (2015-09-28)
------------------
* Fixing casting issues that prevented compilation on 32-bit systems.
* Contributors: P. J. Reed

0.0.2 (2015-09-27)
------------------
* Adds missing qt4_opengl dependency

0.0.1 (2015-09-27)
------------------
* Renames all marti_common packages that were renamed.
  (See http://github.com/swri-robotics/marti_common/issues/231)
* Adds missing dependencies in mapviz package.xml.
* Fixes catkin_lint problems that could prevent installation.
* Formats package files
* Cleans up dependencies
* Adds required rosdeps
* Saving/loading config files to the ROS_WORKSPACE directory.
* fixes lint issues
* Makes mapviz show a warning dialog instead of crash when it fails to load a plugin.
* includes yaml_util header in mapviz plug-in base class
* Handles loading old config files that still reference "mutlires_image".
* Adds an RQT plugin version of Mapviz.
* updates cmake version to squash the CMP0003 warning
* uses correct operator when combining quaternions
* adds option for rotating camera 90 degrees
* throttles log msgs
* removes dependencies on build_tools
* uses format 2 package definition
* allows plug-in selection with double-clicks
* displays file name in window title
* displays preview icon next to plug-in names
* fixes issue with coordinates displayed on status bar
* fixes missing organization in license text
* Adds tooltips describing the various mapviz widgets
* fixes GLEW/GL include order
* catkinizes mapviz
* changes license to BSD
* adds license and readme files
* Contributors: Ed Venator, Edward Venator, Jerry Towler, Marc Alban, P. J. Reed


text:
import React from 'react';
import Paper from 'material-ui/Paper';

const style = {
  height: 100,
  width: 100,
  margin: 20,
  textAlign: 'center',
  display: 'inline-block',
};

const PaperExampleCircle = () => (
  <div>
    <Paper style={style} zDepth={1} circle={true} />
    <Paper style={style} zDepth={2} circle={true} />
    <Paper style={style} zDepth={3} circle={true} />
    <Paper style={style} zDepth={4} circle={true} />
    <Paper style={style} zDepth={5} circle={true} />
  </div>
);

export default PaperExampleCircle;


text:
class Furniture < ActiveRecord::Base
	belongs_to :user
	has_many :comments

	mount_uploader :image, ImageUploader
end


text:
use strict;
use warnings;
use ReseqTrack::DBSQL::DBAdaptor;
use Getopt::Long;
use ReseqTrack::Tools::Exception;
use Data::Dumper;
use Array::Utils qw(:all);

my ( $dbhost, $dbuser, $dbpass, $dbport, $dbname,$type_merge );

&GetOptions(
    'dbhost=s'                  => \$dbhost,
    'dbname=s'                  => \$dbname,
    'dbuser=s'                  => \$dbuser,
    'dbpass=s'                  => \$dbpass,
    'dbport=s'                  => \$dbport,
    'type=s'                    => \$type_merge
);

# dba + adaptors
my $db = ReseqTrack::DBSQL::DBAdaptor->new(
    -host   => $dbhost,
    -user   => $dbuser,
    -port   => $dbport,
    -dbname => $dbname,
    -pass   => $dbpass,
);
throw("Could not create db adaptor") if ( !$db );

$db->dbc->disconnect_when_inactive(1);
my $ca   = $db->get_CollectionAdaptor;
my $rm   = $db->get_RunMetaInfoAdaptor;

my %hash;

die ("[ERROR] Invalid --type: $type_merge") if $type_merge ne 'DNASE_MERGE_RUN_BAM' && $type_merge ne 'CHIP_MERGE_RUN_BAM';

my $cs = $ca->fetch_by_type( $type_merge);

foreach my $c ( @{$cs} ){
    throw("Collection $type_merge does not contain files") unless ( $c->table_name eq 'file' );

    my $experiment_name=$c->name;
    my $other_ids=$c->other_ids;
    foreach my $other_id (@$other_ids) {
	my $collectionArrays=$ca->fetch_by_other_id_and_type($other_id,'CHIP_RUN_BAM');
	foreach my $collection (@$collectionArrays) {
	    $hash{$experiment_name}{'merged'}{$collection->name}=0;
	}
    }
}

foreach my $ex (keys %hash) {
    my $run_meta_info_array=$rm->fetch_by_experiment_id($ex);
    foreach my $rminfo (@$run_meta_info_array) {
	my $runid=$rminfo->run_id;
	#get run ids
	my $collection=$ca->fetch_by_name_and_type($runid,'CHIP_RUN_BAM');
	next if !$collection;
	$hash{$ex}{'new'}{$collection->name}=0;
    }
}

my $update_required=0;
foreach my $ex (keys %hash) {
    my @merged=keys %{$hash{$ex}{'merged'}};
    my @new=keys %{$hash{$ex}{'new'}};
    if ( array_diff(@merged, @new) ) {
	print "[HEY!] For experiment $ex: runs_merged:@merged total_runs:@new\n";
	$update_required=1;
    }
}

print "[INFO] Everything is up-to-date\n" if !$update_required;


text:
const os = require('os');

const maxThreadsFraction = parseFloat(
  process.env.WEBDEV_INFRA_MAX_THREADS || '0.9'
);

/**
 * Determines the number of available CPUs and uses a configured
 * fraction (defaulting to 90%) to calculate the maximum number
 * of threads that should be used for parallel work
 * @returns The number of usable threads as an integer
 */
module.exports = function getMaxThreads() {
  return Math.round(maxThreadsFraction * os.cpus().length);
};


text:
<!DOCTYPE html>

[
Heading
]


text:
//
//  SKNavigationWindow.m
//  Skim
//
//  Created by Christiaan Hofman on 12/19/06.

#import "SKNavigationWindow.h"
#import <Quartz/Quartz.h>
#import "NSBezierPath_SKExtensions.h"
#import "SKPDFView.h"
#import "NSParagraphStyle_SKExtensions.h"
#import "NSGeometry_SKExtensions.h"

#define BUTTON_WIDTH 50.0
#define BUTTON_HEIGHT 50.0
#define SLIDER_WIDTH 100.0
#define SEP_WIDTH 21.0
#define BUTTON_MARGIN 7.0
#define WINDOW_OFFSET 20.0
#define LABEL_OFFSET 10.0
#define LABEL_TEXT_MARGIN 2.0

static inline NSBezierPath *nextButtonPath(NSSize size);
static inline NSBezierPath *previousButtonPath(NSSize size);
static inline NSBezierPath *zoomButtonPath(NSSize size);
static inline NSBezierPath *alternateZoomButtonPath(NSSize size);
static inline NSBezierPath *closeButtonPath(NSSize size);

@implementation SKNavigationWindow

- (id)initWithPDFView:(SKPDFView *)pdfView hasSlider:(BOOL)hasSlider {
    NSScreen *screen = [[pdfView window] screen] ?: [NSScreen mainScreen];
    CGFloat width = 4 * BUTTON_WIDTH + 2 * SEP_WIDTH + 2 * BUTTON_MARGIN;
    if (hasSlider)
        width += SLIDER_WIDTH;
    NSRect contentRect = NSMakeRect(NSMidX([screen frame]) - 0.5 * width, NSMinY([screen frame]) + WINDOW_OFFSET, width, BUTTON_HEIGHT + 2 * BUTTON_MARGIN);
    if (self = [super initWithContentRect:contentRect]) {

        [self setDisplaysWhenScreenProfileChanges:YES];
        [self setLevel:[[pdfView window] level]];
        [self setMovableByWindowBackground:YES];

        [self setContentView:[[[SKNavigationContentView alloc] init] autorelease]];

        NSRect rect = NSMakeRect(BUTTON_MARGIN, BUTTON_MARGIN, BUTTON_WIDTH, BUTTON_HEIGHT);
        previousButton = [[SKNavigationButton alloc] initWithFrame:rect];
        [previousButton setTarget:pdfView];
        [previousButton setAction:@selector(goToPreviousPage:)];
        [previousButton setToolTip:NSLocalizedString(@"Previous", @"Tool tip message")];
        [previousButton setPath:previousButtonPath(rect.size)];
        [previousButton setEnabled:[pdfView canGoToPreviousPage]];
        [[self contentView] addSubview:previousButton];

        rect.origin.x = NSMaxX(rect);
        nextButton = [[SKNavigationButton alloc] initWithFrame:rect];
        [nextButton setTarget:pdfView];
        [nextButton setAction:@selector(goToNextPage:)];
        [nextButton setToolTip:NSLocalizedString(@"Next", @"Tool tip message")];
        [nextButton setPath:nextButtonPath(rect.size)];
        [nextButton setEnabled:[pdfView canGoToNextPage]];
        [[self contentView] addSubview:nextButton];

        rect.origin.x = NSMaxX(rect);
        rect.size.width = SEP_WIDTH;
        [[self contentView] addSubview:[[[SKNavigationSeparator alloc] initWithFrame:rect] autorelease]];

        if (hasSlider) {
            rect.origin.x = NSMaxX(rect);
            rect.size.width = SLIDER_WIDTH;
            zoomSlider = [[SKNavigationSlider alloc] initWithFrame:rect];
            [zoomSlider setTarget:pdfView];
            [zoomSlider setAction:@selector(zoomLog:)];
            [zoomSlider setToolTip:NSLocalizedString(@"Zoom", @"Tool tip message")];
            [zoomSlider setMinValue:log(0.1)];
            [zoomSlider setMaxValue:log(10.0)];
            [zoomSlider setDoubleValue:log([pdfView scaleFactor])];
            [[self contentView] addSubview:zoomSlider];
        }

        rect.origin.x = NSMaxX(rect);
        rect.size.width = BUTTON_WIDTH;
        zoomButton = [[SKNavigationButton alloc] initWithFrame:rect];
        [zoomButton setTarget:pdfView];
        [zoomButton setAction:@selector(toggleAutoActualSize:)];
        [zoomButton setToolTip:NSLocalizedString(@"Fit to Screen", @"Tool tip message")];
        [zoomButton setAlternateToolTip:NSLocalizedString(@"Actual Size", @"Tool tip message")];
        [zoomButton setPath:zoomButtonPath(rect.size)];
        [zoomButton setAlternatePath:alternateZoomButtonPath(rect.size)];
        [zoomButton setState:[pdfView autoScales]];
        [zoomButton setButtonType:NSPushOnPushOffButton];
        [[self contentView] addSubview:zoomButton];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleScaleChangedNotification:)
                                                     name:PDFViewScaleChangedNotification object:pdfView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePageChangedNotification:)
                                                     name:PDFViewPageChangedNotification object:pdfView];

        rect.origin.x = NSMaxX(rect);
        rect.size.width = SEP_WIDTH;
        [[self contentView] addSubview:[[[SKNavigationSeparator alloc] initWithFrame:rect] autorelease]];

        rect.origin.x = NSMaxX(rect);
        rect.size.width = BUTTON_WIDTH;
        closeButton = [[SKNavigationButton alloc] initWithFrame:rect];
        [closeButton setTarget:pdfView];
        [closeButton setAction:@selector(exitFullScreen:)];
        [closeButton setToolTip:NSLocalizedString(@"Close", @"Tool tip message")];
        [closeButton setPath:closeButtonPath(rect.size)];
        [[self contentView] addSubview:closeButton];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        previousButton = [[decoder decodeObjectForKey:@"previousButton"] retain];
        nextButton = [[decoder decodeObjectForKey:@"nextButton"] retain];
        zoomButton = [[decoder decodeObjectForKey:@"zoomButton"] retain];
        zoomSlider = [[decoder decodeObjectForKey:@"zoomSlider"] retain];
        closeButton = [[decoder decodeObjectForKey:@"closeButton"] retain];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [super encodeWithCoder:coder];
    [coder encodeConditionalObject:previousButton forKey:@"previousButton"];
    [coder encodeConditionalObject:nextButton forKey:@"nextButton"];
    [coder encodeConditionalObject:zoomButton forKey:@"zoomButton"];
    [coder encodeConditionalObject:zoomSlider forKey:@"zoomSlider"];
    [coder encodeConditionalObject:closeButton forKey:@"closeButton"];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    SKDESTROY(previousButton);
    SKDESTROY(nextButton);
    SKDESTROY(zoomButton);
    SKDESTROY(zoomSlider);
    SKDESTROY(closeButton);
    [super dealloc];
}

- (void)remove {
    [[self parentWindow] removeChildWindow:self];
    [super remove];
}

- (void)orderOut:(id)sender {
    [[SKNavigationToolTipWindow sharedToolTipWindow] orderOut:nil];
    [super orderOut:sender];
}

- (void)handleScaleChangedNotification:(NSNotification *)notification {
    [zoomButton setState:[[notification object] autoScales] ? NSOnState : NSOffState];
    [zoomSlider setDoubleValue:log([[notification object] scaleFactor])];
}

- (void)handlePageChangedNotification:(NSNotification *)notification {
    [previousButton setEnabled:[[notification object] canGoToPreviousPage]];
    [nextButton setEnabled:[[notification object] canGoToNextPage]];
}

@end

#pragma mark -

@implementation SKNavigationContentView

- (void)drawRect:(NSRect)rect {
    [[NSGraphicsContext currentContext] saveGraphicsState];
    rect = NSInsetRect([self bounds], 1.0, 1.0);
    [[NSColor colorWithDeviceWhite:0.0 alpha:0.5] set];
    [[NSBezierPath bezierPathWithRoundedRect:rect xRadius:10.0 yRadius:10.0] fill];
    rect = NSInsetRect([self bounds], 0.5, 0.5);
    [[NSColor colorWithDeviceWhite:1.0 alpha:0.2] set];
    [NSBezierPath setDefaultLineWidth:1.0];
    [[NSBezierPath bezierPathWithRoundedRect:rect xRadius:10.0 yRadius:10.0] stroke];
    [[NSGraphicsContext currentContext] restoreGraphicsState];
}

@end

#pragma mark -

@implementation SKNavigationToolTipWindow

@synthesize view;

+ (id)sharedToolTipWindow {
    static SKNavigationToolTipWindow *sharedToolTipWindow = nil;
    if (sharedToolTipWindow == nil)
        sharedToolTipWindow = [[self alloc] init];
    return sharedToolTipWindow;
}

- (id)init {
    if (self = [super initWithContentRect:NSZeroRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES]) {
		[self setBackgroundColor:[NSColor clearColor]];
		[self setOpaque:NO];
        [self setDisplaysWhenScreenProfileChanges:YES];
        [self setReleasedWhenClosed:NO];
        [self setHidesOnDeactivate:NO];

        [self setContentView:[[[SKNavigationToolTipView alloc] init] autorelease]];
    }
    return self;
}

- (BOOL)canBecomeKeyWindow { return NO; }

- (BOOL)canBecomeMainWindow { return NO; }

- (void)showToolTip:(NSString *)toolTip forView:(NSView *)aView {
    [view release];
    view = [aView retain];
    [[self contentView] setStringValue:toolTip];
    NSRect newFrame = NSZeroRect;
    NSRect viewRect = [view convertRect:[view bounds] toView:nil];
    viewRect.origin = [[view window] convertBaseToScreen:viewRect.origin];
    newFrame.size = [[self contentView] fitSize];
    newFrame.origin = NSMakePoint(ceil(NSMidX(viewRect) - 0.5 * NSWidth(newFrame)), NSMaxY(viewRect) + LABEL_OFFSET);
    [self setFrame:newFrame display:YES];
    [self setLevel:[[view window] level]];
    if ([self parentWindow] != [view window])
        [[self parentWindow] removeChildWindow:self];
    if ([self parentWindow] == nil)
        [[view window] addChildWindow:self ordered:NSWindowAbove];
    [self orderFront:self];
}

- (void)orderOut:(id)sender {
    [[self parentWindow] removeChildWindow:self];
    [super orderOut:sender];
    SKDESTROY(view);
}

- (BOOL)accessibilityIsIgnored {
    return YES;
}

@end

#pragma mark -

@implementation SKNavigationToolTipView

@synthesize stringValue;
@dynamic attributedStringValue;

- (id)initWithFrame:(NSRect)frameRect {
    if (self = [super initWithFrame:frameRect]) {
        stringValue = nil;
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        stringValue = [[decoder decodeObjectForKey:@"stringValue"] retain];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [super encodeWithCoder:coder];
    [coder encodeObject:stringValue forKey:@"stringValue"];
}

- (void)dealloc {
    SKDESTROY(stringValue);
    [super dealloc];
}

- (NSAttributedString *)attributedStringValue {
    if (stringValue == nil)
        return nil;
    NSShadow *aShadow = [[NSShadow alloc] init];
    [aShadow setShadowColor:[NSColor blackColor]];
    [aShadow setShadowBlurRadius:3.0];
    [aShadow setShadowOffset:NSMakeSize(0.0, -1.0)];
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSFont boldSystemFontOfSize:15.0], NSFontAttributeName,
        [NSColor whiteColor], NSForegroundColorAttributeName,
        [NSParagraphStyle defaultClippingParagraphStyle], NSParagraphStyleAttributeName,
        aShadow, NSShadowAttributeName, nil];
    [aShadow release];
    return [[[NSAttributedString alloc] initWithString:stringValue attributes:attrs] autorelease];
}

- (NSSize)fitSize {
    NSSize stringSize = [[self attributedStringValue] size];
    return NSMakeSize(ceil(stringSize.width + 2 * LABEL_TEXT_MARGIN), ceil(stringSize.height + 2 * LABEL_TEXT_MARGIN));
}

- (void)drawRect:(NSRect)rect {
    NSRect textRect = NSInsetRect(rect, LABEL_TEXT_MARGIN, LABEL_TEXT_MARGIN);
    NSAttributedString *attrString = [self attributedStringValue];
    // draw it 3x to see some shadow
    [attrString drawInRect:textRect];
    [attrString drawInRect:textRect];
    [attrString drawInRect:textRect];
}

@end

#pragma mark -

@implementation SKNavigationButton

@dynamic path, alternatePath, toolTip, alternateToolTip;

+ (Class)cellClass { return [SKNavigationButtonCell class]; }

- (NSBezierPath *)path {
    return [(SKNavigationButtonCell *)[self cell] path];
}

- (void)setPath:(NSBezierPath *)newPath {
    [(SKNavigationButtonCell *)[self cell] setPath:newPath];
}

- (NSBezierPath *)alternatePath {
    return [(SKNavigationButtonCell *)[self cell] alternatePath];
}

- (void)setAlternatePath:(NSBezierPath *)newAlternatePath {
    [(SKNavigationButtonCell *)[self cell] setAlternatePath:newAlternatePath];
}

- (NSString *)toolTip {
    return [(SKNavigationButtonCell *)[self cell] toolTip];
}

// we don't use the superclass's ivar because we don't want the system toolTips
- (void)setToolTip:(NSString *)string {
    [(SKNavigationButtonCell *)[self cell] setToolTip:string];
    [self setShowsBorderOnlyWhileMouseInside:[string length] > 0];
}

- (NSString *)alternateToolTip {
    return [(SKNavigationButtonCell *)[self cell] alternateToolTip];
}

- (void)setAlternateToolTip:(NSString *)string {
    [(SKNavigationButtonCell *)[self cell] setAlternateToolTip:string];
}

@end

#pragma mark -

@implementation SKNavigationButtonCell

@synthesize path, alternatePath, toolTip, alternateToolTip;

- (id)initTextCell:(NSString *)aString {
    if (self = [super initTextCell:@""]) {
		[self setBezelStyle:NSShadowlessSquareBezelStyle]; // this is mainly to make it selectable
        [self setBordered:NO];
        [self setButtonType:NSMomentaryPushInButton];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        toolTip = [[decoder decodeObjectForKey:@"toolTip"] retain];
        alternateToolTip = [[decoder decodeObjectForKey:@"alternateToolTip"] retain];
        path = [[decoder decodeObjectForKey:@"path"] retain];
        alternatePath = [[decoder decodeObjectForKey:@"alternatePath"] retain];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [super encodeWithCoder:coder];
    [coder encodeObject:toolTip forKey:@"toolTip"];
    [coder encodeObject:alternateToolTip forKey:@"alternateToolTip"];
    [coder encodeObject:path forKey:@"path"];
    [coder encodeObject:alternatePath forKey:@"alternatePath"];
}

- (void)dealloc {
    SKDESTROY(toolTip);
    SKDESTROY(alternateToolTip);
    SKDESTROY(path);
    SKDESTROY(alternatePath);
    [super dealloc];
}

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
    [[NSColor colorWithDeviceWhite:1.0 alpha:[self isEnabled] == NO ? 0.3 : [self isHighlighted] ? 0.9 : 0.6] setFill];
    [([self state] == NSOnState && [self alternatePath] ? [self alternatePath] : [self path]) fill];
}

- (void)mouseEntered:(NSEvent *)theEvent {
    NSString *currentToolTip = [self state] == NSOnState && alternateToolTip ? alternateToolTip : toolTip;
    [[SKNavigationToolTipWindow sharedToolTipWindow] showToolTip:currentToolTip forView:[self controlView]];
    [super mouseEntered:theEvent];
}

- (void)mouseExited:(NSEvent *)theEvent {
    if ([[[SKNavigationToolTipWindow sharedToolTipWindow] view] isEqual:[self controlView]])
        [[SKNavigationToolTipWindow sharedToolTipWindow] orderOut:nil];
    [super mouseExited:theEvent];
}

- (void)setState:(NSInteger)state {
    NSInteger oldState = [self state];
    NSView *button = [self controlView];
    [super setState:state];
    if (oldState != state && [[button window] isVisible]) {
        if (alternatePath)
            [button setNeedsDisplay:YES];
        if (alternateToolTip && [[[SKNavigationToolTipWindow sharedToolTipWindow] view] isEqual:button]) {
            NSString *currentToolTip = [self state] == NSOnState && alternateToolTip ? alternateToolTip : toolTip;
            [[SKNavigationToolTipWindow sharedToolTipWindow] showToolTip:currentToolTip forView:button];
        }
    }
}

@end

#pragma mark -

@implementation SKNavigationSlider

@synthesize toolTip;

+ (Class)cellClass { return [SKNavigationSliderCell class]; }

- (id)initWithFrame:(NSRect)frameRect {
    if (self = [super initWithFrame:frameRect]) {
        trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options:NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect | NSTrackingActiveAlways owner:self userInfo:nil];
        [self addTrackingArea:trackingArea];
        toolTip = nil;
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        toolTip = [[decoder decodeObjectForKey:@"toolTip"] retain];
        trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options:NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect | NSTrackingActiveAlways owner:self userInfo:nil];
        [self addTrackingArea:trackingArea];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [super encodeWithCoder:coder];
    [coder encodeObject:toolTip forKey:@"toolTip"];
}

- (void)dealloc {
    SKDESTROY(trackingArea);
    SKDESTROY(toolTip);
    [super dealloc];
}

- (void)mouseEntered:(NSEvent *)theEvent {
    if ([[theEvent trackingArea] isEqual:trackingArea])
        [[SKNavigationToolTipWindow sharedToolTipWindow] showToolTip:toolTip forView:self];
    else
        [super mouseEntered:theEvent];
}

- (void)mouseExited:(NSEvent *)theEvent {
    if ([[theEvent trackingArea] isEqual:trackingArea]) {
        if ([[[SKNavigationToolTipWindow sharedToolTipWindow] view] isEqual:self])
            [[SKNavigationToolTipWindow sharedToolTipWindow] orderOut:nil];
    } else
        [super mouseExited:theEvent];
}

@end

#pragma mark -

@implementation SKNavigationSliderCell

- (void)drawBarInside:(NSRect)frame flipped:(BOOL)flipped {
    frame = NSInsetRect(frame, 2.5, 0.0);
    frame.origin.y = NSMidY(frame) - (flipped ? 2.0 : 3.0);
    frame.size.height = 5.0;

    CGFloat alpha = [self isEnabled] ? 0.6 : 0.3;
    [[NSColor colorWithDeviceWhite:0.3 alpha:alpha] setFill];
    [[NSColor colorWithDeviceWhite:1.0 alpha:alpha] setStroke];

	NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:frame xRadius:2.0 yRadius:2.0];
    [path fill];
    [path stroke];
}

- (void)drawKnob:(NSRect)frame {
	if ([self isEnabled]) {
        [[NSColor colorWithDeviceWhite:1.0 alpha:[self isHighlighted] ? 0.9 : 0.7] setFill];
        NSShadow *shade = [[NSShadow alloc] init];
        [shade setShadowColor:[NSColor blackColor]];
        [shade setShadowBlurRadius:2.0];
        [shade set];
        [shade release];
    } else {
        [[NSColor colorWithDeviceWhite:1.0 alpha:0.3] setFill];
    }

    [[NSBezierPath bezierPathWithOvalInRect:SKRectFromCenterAndSize(SKCenterPoint(frame), SKMakeSquareSize(15.0))] fill];
}

- (BOOL)_usesCustomTrackImage { return YES; }

@end

#pragma mark -

@implementation SKNavigationSeparator

- (void)drawRect:(NSRect)rect {
    NSRect bounds = [self bounds];
    [[NSColor colorWithDeviceWhite:1.0 alpha:0.6] setFill];
    [NSBezierPath fillRect:NSMakeRect(NSMidX(bounds) - 0.5, NSMinY(bounds), 1.0, NSHeight(bounds))];
}

@end

#pragma mark Button paths

static inline NSBezierPath *nextButtonPath(NSSize size) {
    NSRect bounds = {NSZeroPoint, size};
    NSRect rect = NSInsetRect(bounds, 10.0, 10.0);
    NSBezierPath *path = [NSBezierPath bezierPath];
    [path moveToPoint:NSMakePoint(NSMaxX(rect), NSMidY(rect))];
    [path lineToPoint:NSMakePoint(NSMinX(rect), NSMaxY(rect))];
    [path lineToPoint:NSMakePoint(NSMinX(rect), NSMinY(rect))];
    [path closePath];
    return path;
}

static inline NSBezierPath *previousButtonPath(NSSize size) {
    NSRect bounds = {NSZeroPoint, size};
    NSRect rect = NSInsetRect(bounds, 10.0, 10.0);
    NSBezierPath *path = [NSBezierPath bezierPath];
    [path moveToPoint:NSMakePoint(NSMinX(rect), NSMidY(rect))];
    [path lineToPoint:NSMakePoint(NSMaxX(rect), NSMaxY(rect))];
    [path lineToPoint:NSMakePoint(NSMaxX(rect), NSMinY(rect))];
    [path closePath];
    return path;
}

static inline NSBezierPath *zoomButtonPath(NSSize size) {
    NSRect bounds = {NSZeroPoint, size};
    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(bounds, 15.0, 15.0) xRadius:3.0 yRadius:3.0];
    CGFloat centerX = NSMidX(bounds), centerY = NSMidY(bounds);

    [path appendBezierPath:[NSBezierPath bezierPathWithRect:NSInsetRect(bounds, 19.0, 19.0)]];

    NSBezierPath *arrow = [NSBezierPath bezierPath];
    [arrow moveToPoint:NSMakePoint(centerX, NSMaxY(bounds) + 2.0)];
    [arrow relativeLineToPoint:NSMakePoint(-5.0, -5.0)];
    [arrow relativeLineToPoint:NSMakePoint(3.0, 0.0)];
    [arrow relativeLineToPoint:NSMakePoint(0.0, -5.0)];
    [arrow relativeLineToPoint:NSMakePoint(4.0, 0.0)];
    [arrow relativeLineToPoint:NSMakePoint(0.0, 5.0)];
    [arrow relativeLineToPoint:NSMakePoint(3.0, 0.0)];
    [arrow relativeLineToPoint:NSMakePoint(-5.0, 5.0)];

    NSAffineTransform *transform = [[[NSAffineTransform alloc] init] autorelease];
    [transform translateXBy:centerX yBy:centerY];
    [transform rotateByDegrees:45.0];
    [transform translateXBy:-centerX yBy:-centerY];
    [arrow transformUsingAffineTransform:transform];
    [transform translateXBy:centerX yBy:centerY];
    [transform rotateByDegrees:45.0];
    [transform translateXBy:-centerX yBy:-centerY];

    NSInteger i;
    for (i = 0; i < 4; i++) {
        [path appendBezierPath:arrow];
        [arrow transformUsingAffineTransform:transform];
    }

    [path setWindingRule:NSEvenOddWindingRule];

    return path;
}

static inline NSBezierPath *alternateZoomButtonPath(NSSize size) {
    NSRect bounds = {NSZeroPoint, size};
    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(bounds, 15.0, 15.0) xRadius:3.0 yRadius:3.0];
    CGFloat centerX = NSMidX(bounds), centerY = NSMidY(bounds);

    [path appendBezierPath:[NSBezierPath bezierPathWithRect:NSInsetRect(bounds, 19.0, 19.0)]];

    NSBezierPath *arrow = [NSBezierPath bezierPath];
    [arrow moveToPoint:NSMakePoint(centerX, NSMaxY(bounds) - 8.0)];
    [arrow relativeLineToPoint:NSMakePoint(-5.0, 5.0)];
    [arrow relativeLineToPoint:NSMakePoint(3.0, 0.0)];
    [arrow relativeLineToPoint:NSMakePoint(0.0, 5.0)];
    [arrow relativeLineToPoint:NSMakePoint(4.0, 0.0)];
    [arrow relativeLineToPoint:NSMakePoint(0.0, -5.0)];
    [arrow relativeLineToPoint:NSMakePoint(3.0, 0.0)];
    [arrow relativeLineToPoint:NSMakePoint(-5.0, -5.0)];

    NSAffineTransform *transform = [[[NSAffineTransform alloc] init] autorelease];
    [transform translateXBy:centerX yBy:centerY];
    [transform rotateByDegrees:45.0];
    [transform translateXBy:-centerX yBy:-centerY];
    [arrow transformUsingAffineTransform:transform];
    [transform translateXBy:centerX yBy:centerY];
    [transform rotateByDegrees:45.0];
    [transform translateXBy:-centerX yBy:-centerY];

    NSInteger i;
    for (i = 0; i < 4; i++) {
        [path appendBezierPath:arrow];
        [arrow transformUsingAffineTransform:transform];
    }

    [path setWindingRule:NSEvenOddWindingRule];

    return path;
}

static inline NSBezierPath *closeButtonPath(NSSize size) {
    NSRect bounds = {NSZeroPoint, size};
    NSBezierPath *path = [NSBezierPath bezierPath];
    CGFloat radius = 2.0, halfWidth = 0.5 * NSWidth(bounds) - 15.0, halfHeight = 0.5 * NSHeight(bounds) - 15.0;

    [path moveToPoint:NSMakePoint(radius, radius)];
    [path appendBezierPathWithArcWithCenter:NSMakePoint(halfWidth, 0.0) radius:radius startAngle:90.0 endAngle:-90.0 clockwise:YES];
    [path lineToPoint:NSMakePoint(radius, -radius)];
    [path appendBezierPathWithArcWithCenter:NSMakePoint(0.0, -halfHeight) radius:radius startAngle:360.0 endAngle:180.0 clockwise:YES];
    [path lineToPoint:NSMakePoint(-radius, -radius)];
    [path appendBezierPathWithArcWithCenter:NSMakePoint(-halfWidth, 0.0) radius:radius startAngle:270.0 endAngle:90.0 clockwise:YES];
    [path lineToPoint:NSMakePoint(-radius, radius)];
    [path appendBezierPathWithArcWithCenter:NSMakePoint(0.0, halfHeight) radius:radius startAngle:180.0 endAngle:0.0 clockwise:YES];
    [path closePath];

    NSAffineTransform *transform = [[[NSAffineTransform alloc] init] autorelease];
    [transform translateXBy:NSMidX(bounds) yBy:NSMidY(bounds)];
    [transform rotateByDegrees:45.0];
    [path transformUsingAffineTransform:transform];

    [path appendBezierPath:[NSBezierPath bezierPathWithOvalInRect:NSInsetRect(bounds, 8.0, 8.0)]];

    return path;
}


text:
"""
34. Generic relations

Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.

The canonical example is tags (although this example implementation is *far*
from complete).
"""

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class TaggedItem(models.Model):
    """A tag on an item."""
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()

    content_object = generic.GenericForeignKey()

    class Meta:
        ordering = ["tag", "-object_id"]

    def __unicode__(self):
        return self.tag

class ValuableTaggedItem(TaggedItem):
    value = models.PositiveIntegerField()

class Comparison(models.Model):
    """
    A model that tests having multiple GenericForeignKeys
    """
    comparative = models.CharField(max_length=50)

    content_type1 = models.ForeignKey(ContentType, related_name="comparative1_set")
    object_id1 = models.PositiveIntegerField()

    content_type2 = models.ForeignKey(ContentType,  related_name="comparative2_set")
    object_id2 = models.PositiveIntegerField()

    first_obj = generic.GenericForeignKey(ct_field="content_type1", fk_field="object_id1")
    other_obj = generic.GenericForeignKey(ct_field="content_type2", fk_field="object_id2")

    def __unicode__(self):
        return u"%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj)

class Animal(models.Model):
    common_name = models.CharField(max_length=150)
    latin_name = models.CharField(max_length=150)

    tags = generic.GenericRelation(TaggedItem)
    comparisons = generic.GenericRelation(Comparison,
                                          object_id_field="object_id1",
                                          content_type_field="content_type1")

    def __unicode__(self):
        return self.common_name

class Vegetable(models.Model):
    name = models.CharField(max_length=150)
    is_yucky = models.BooleanField(default=True)

    tags = generic.GenericRelation(TaggedItem)

    def __unicode__(self):
        return self.name

class Mineral(models.Model):
    name = models.CharField(max_length=150)
    hardness = models.PositiveSmallIntegerField()

    # note the lack of an explicit GenericRelation here...

    def __unicode__(self):
        return self.name

__test__ = {'API_TESTS':"""
# Create the world in 7 lines of code...
>>> lion = Animal(common_name="Lion", latin_name="Panthera leo")
>>> platypus = Animal(common_name="Platypus", latin_name="Ornithorhynchus anatinus")
>>> eggplant = Vegetable(name="Eggplant", is_yucky=True)
>>> bacon = Vegetable(name="Bacon", is_yucky=False)
>>> quartz = Mineral(name="Quartz", hardness=7)
>>> for o in (platypus, lion, eggplant, bacon, quartz):
...     o.save()

# Objects with declared GenericRelations can be tagged directly -- the API
# mimics the many-to-many API.
>>> bacon.tags.create(tag="fatty")
<TaggedItem: fatty>
>>> bacon.tags.create(tag="salty")
<TaggedItem: salty>
>>> lion.tags.create(tag="yellow")
<TaggedItem: yellow>
>>> lion.tags.create(tag="hairy")
<TaggedItem: hairy>
>>> platypus.tags.create(tag="fatty")
<TaggedItem: fatty>

>>> lion.tags.all()
[<TaggedItem: hairy>, <TaggedItem: yellow>]
>>> bacon.tags.all()
[<TaggedItem: fatty>, <TaggedItem: salty>]

# You can easily access the content object like a foreign key.
>>> t = TaggedItem.objects.get(tag="salty")
>>> t.content_object
<Vegetable: Bacon>

# Recall that the Mineral class doesn't have an explicit GenericRelation
# defined. That's OK, because you can create TaggedItems explicitly.
>>> tag1 = TaggedItem(content_object=quartz, tag="shiny")
>>> tag2 = TaggedItem(content_object=quartz, tag="clearish")
>>> tag1.save()
>>> tag2.save()

# However, excluding GenericRelations means your lookups have to be a bit more
# explicit.
>>> from django.contrib.contenttypes.models import ContentType
>>> ctype = ContentType.objects.get_for_model(quartz)
>>> TaggedItem.objects.filter(content_type__pk=ctype.id, object_id=quartz.id)
[<TaggedItem: clearish>, <TaggedItem: shiny>]

# You can set a generic foreign key in the way you'd expect.
>>> tag1.content_object = platypus
>>> tag1.save()
>>> platypus.tags.all()
[<TaggedItem: fatty>, <TaggedItem: shiny>]
>>> TaggedItem.objects.filter(content_type__pk=ctype.id, object_id=quartz.id)
[<TaggedItem: clearish>]

# Queries across generic relations respect the content types. Even though there are two TaggedItems with a tag of "fatty", this query only pulls out the one with the content type related to Animals.
>>> Animal.objects.order_by('common_name')
[<Animal: Lion>, <Animal: Platypus>]
>>> Animal.objects.filter(tags__tag='fatty')
[<Animal: Platypus>]
>>> Animal.objects.exclude(tags__tag='fatty')
[<Animal: Lion>]

# If you delete an object with an explicit Generic relation, the related
# objects are deleted when the source object is deleted.
# Original list of tags:
>>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()]
[(u'clearish', <ContentType: mineral>, 1), (u'fatty', <ContentType: vegetable>, 2), (u'fatty', <ContentType: animal>, 1), (u'hairy', <ContentType: animal>, 2), (u'salty', <ContentType: vegetable>, 2), (u'shiny', <ContentType: animal>, 1), (u'yellow', <ContentType: animal>, 2)]

>>> lion.delete()
>>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()]
[(u'clearish', <ContentType: mineral>, 1), (u'fatty', <ContentType: vegetable>, 2), (u'fatty', <ContentType: animal>, 1), (u'salty', <ContentType: vegetable>, 2), (u'shiny', <ContentType: animal>, 1)]

# If Generic Relation is not explicitly defined, any related objects
# remain after deletion of the source object.
>>> quartz.delete()
>>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()]
[(u'clearish', <ContentType: mineral>, 1), (u'fatty', <ContentType: vegetable>, 2), (u'fatty', <ContentType: animal>, 1), (u'salty', <ContentType: vegetable>, 2), (u'shiny', <ContentType: animal>, 1)]

# If you delete a tag, the objects using the tag are unaffected
# (other than losing a tag)
>>> tag = TaggedItem.objects.get(id=1)
>>> tag.delete()
>>> bacon.tags.all()
[<TaggedItem: salty>]
>>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()]
[(u'clearish', <ContentType: mineral>, 1), (u'fatty', <ContentType: animal>, 1), (u'salty', <ContentType: vegetable>, 2), (u'shiny', <ContentType: animal>, 1)]

>>> TaggedItem.objects.filter(tag='fatty').delete()

>>> ctype = ContentType.objects.get_for_model(lion)
>>> Animal.objects.filter(tags__content_type=ctype)
[<Animal: Platypus>]

# Simple tests for multiple GenericForeignKeys
# only uses one model, since the above tests should be sufficient.
>>> tiger, cheetah, bear = Animal(common_name="tiger"), Animal(common_name="cheetah"), Animal(common_name="bear")
>>> for o in [tiger, cheetah, bear]: o.save()

# Create directly
>>> Comparison(first_obj=cheetah, other_obj=tiger, comparative="faster").save()
>>> Comparison(first_obj=tiger, other_obj=cheetah, comparative="cooler").save()

# Create using GenericRelation
>>> tiger.comparisons.create(other_obj=bear, comparative="cooler")
<Comparison: tiger is cooler than bear>
>>> tiger.comparisons.create(other_obj=cheetah, comparative="stronger")
<Comparison: tiger is stronger than cheetah>

>>> cheetah.comparisons.all()
[<Comparison: cheetah is faster than tiger>]

# Filtering works
>>> tiger.comparisons.filter(comparative="cooler")
[<Comparison: tiger is cooler than cheetah>, <Comparison: tiger is cooler than bear>]

# Filtering and deleting works
>>> subjective = ["cooler"]
>>> tiger.comparisons.filter(comparative__in=subjective).delete()
>>> Comparison.objects.all()
[<Comparison: cheetah is faster than tiger>, <Comparison: tiger is stronger than cheetah>]

# If we delete cheetah, Comparisons with cheetah as 'first_obj' will be deleted
# since Animal has an explicit GenericRelation to Comparison through first_obj.
# Comparisons with cheetah as 'other_obj' will not be deleted.
>>> cheetah.delete()
>>> Comparison.objects.all()
[<Comparison: tiger is stronger than None>]

# GenericForeignKey should work with subclasses (see #8309)
>>> quartz = Mineral.objects.create(name="Quartz", hardness=7)
>>> valuedtag = ValuableTaggedItem(content_object=quartz, tag="shiny", value=10)
>>> valuedtag.save()
>>> valuedtag.content_object
<Mineral: Quartz>

# GenericInlineFormSet tests ##################################################

>>> from django.contrib.contenttypes.generic import generic_inlineformset_factory

>>> GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1)
>>> formset = GenericFormSet()
>>> for form in formset.forms:
...     print form.as_p()

Tag: <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" />

Delete: <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" />

>>> formset = GenericFormSet(instance=Animal())
>>> for form in formset.forms:
...     print form.as_p()

Tag: <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" />

Delete: <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" />

>>> formset = GenericFormSet(instance=platypus)
>>> for form in formset.forms:
...     print form.as_p()

Tag: <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" value="shiny" maxlength="50" />

Delete: <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" value="..." id="id_generic_relations-taggeditem-content_type-object_id-0-id" />

Tag: <input id="id_generic_relations-taggeditem-content_type-object_id-1-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-1-tag" maxlength="50" />

Delete: <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-1-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-1-id" id="id_generic_relations-taggeditem-content_type-object_id-1-id" />

>>> formset = GenericFormSet(instance=lion, prefix='x')
>>> for form in formset.forms:
...     print form.as_p()

Tag: <input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50" />

Delete: <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE" /><input type="hidden" name="x-0-id" id="id_x-0-id" />

"""}


text:
include InfluxDB::Helpers

def initialize(new_resource, run_context)
  super
  @client    = InfluxDB::Helpers.client(new_resource.auth_username, new_resource.auth_password, run_context)
  @username  = new_resource.username
  @password  = new_resource.password
end

action :create do
  unless @password
    fail('You must provide a password for the :create' \
                     ' action on this resource!')
  end

  begin
    unless @client.list_cluster_admins.member?(@username)
      @client.create_cluster_admin(@username, @password)
    end
  rescue InfluxDB::AuthenticationError => e
    # Exception due to missing admin user
    # https://influxdb.com/docs/v0.9/administration/authentication.html
    # https://github.com/chrisduong/chef-influxdb/commit/fe730374b4164e872cbf208c06d2462c8a056a6a
    if e.to_s.include? 'create admin user'
      @client.create_cluster_admin(@username, @password)
    end
  end
end

action :update do
  unless @password
    fail('You must provide a password for the :update' \
                     ' action on this resource!')
  end
  @client.update_user_password(@username, @password)
end

action :delete do
  if @client.list_cluster_admins.member?(@username)
    @client.delete_user(@username)
  end
end


text:
package sort

import (
	"testing"
)

func TestMultikeyQuickSort(t *testing.T) {
	testSortArguments(t, MultikeyQuickSort)
	testSortRepeated(t, MultikeyQuickSort, largeDataSize)
	testSortRepeatedCycle(t, MultikeyQuickSort, largeDataSize)
	testSortRandom(t, MultikeyQuickSort, largeDataSize)
	testSortDictWords(t, MultikeyQuickSort, largeDataSize)
	testSortReversed(t, MultikeyQuickSort, largeDataSize)
	testSortNonUnique(t, MultikeyQuickSort, largeDataSize)
}


text:
package com.google.errorprone.bugpatterns.testdata;

import com.google.errorprone.annotations.MustBeClosed;
import java.util.stream.Stream;

class MustBeClosedCheckerPositiveCases {

  class DoesNotImplementAutoCloseable {
    @MustBeClosed
    // BUG: Diagnostic contains: MustBeClosed should only annotate constructors of AutoCloseables.
    DoesNotImplementAutoCloseable() {}

    @MustBeClosed
    // BUG: Diagnostic contains: MustBeClosed should only annotate methods that return an
    // AutoCloseable.
    void doesNotReturnAutoCloseable() {}
  }

  class Closeable implements AutoCloseable {

    @Override
    public void close() {}

    public int method() {
      return 1;
    }
  }

  class Foo {

    @MustBeClosed
    Closeable mustBeClosedAnnotatedMethod() {
      return new Closeable();
    }

    void sameClass() {
      // BUG: Diagnostic contains:
      mustBeClosedAnnotatedMethod();
    }
  }

  class MustBeClosedAnnotatedConstructor extends Closeable {

    @MustBeClosed
    MustBeClosedAnnotatedConstructor() {}

    void sameClass() {
      // BUG: Diagnostic contains:
      new MustBeClosedAnnotatedConstructor();
    }
  }

  interface Lambda {

    Closeable expression();
  }

  void positiveCase1() {
    // BUG: Diagnostic contains:
    new Foo().mustBeClosedAnnotatedMethod();
  }

  void positiveCase2() {
    // BUG: Diagnostic contains:
    Closeable closeable = new Foo().mustBeClosedAnnotatedMethod();
  }

  void positiveCase3() {
    try {
      // BUG: Diagnostic contains:
      new Foo().mustBeClosedAnnotatedMethod();
    } finally {
    }
  }

  void positiveCase4() {
    try (Closeable c = new Foo().mustBeClosedAnnotatedMethod()) {
      // BUG: Diagnostic contains:
      new Foo().mustBeClosedAnnotatedMethod();
    }
  }

  void positiveCase5() {
    // BUG: Diagnostic contains:
    new MustBeClosedAnnotatedConstructor();
  }

  Closeable positiveCase6() {
    // BUG: Diagnostic contains:
    return new MustBeClosedAnnotatedConstructor();
  }

  Closeable positiveCase7() {
    // BUG: Diagnostic contains:
    return new Foo().mustBeClosedAnnotatedMethod();
  }

  void positiveCase8() {
    Lambda expression =
        () -> {
          // BUG: Diagnostic contains:
          return new Foo().mustBeClosedAnnotatedMethod();
        };
  }

  void positiveCase9() {
    new Foo() {
      @Override
      public Closeable mustBeClosedAnnotatedMethod() {
        // BUG: Diagnostic contains:
        return new MustBeClosedAnnotatedConstructor();
      }
    };
  }

  int expressionDeclaredVariable() {
    // BUG: Diagnostic contains:
    int result = new Foo().mustBeClosedAnnotatedMethod().method();
    return result;
  }

  void tryWithResources_nonFinal() {
    Foo foo = new Foo();
    // BUG: Diagnostic contains:
    Closeable closeable = foo.mustBeClosedAnnotatedMethod();
    try {
      closeable = null;
    } finally {
      closeable.close();
    }
  }

  void tryWithResources_noClose() {
    Foo foo = new Foo();
    // BUG: Diagnostic contains:
    Closeable closeable = foo.mustBeClosedAnnotatedMethod();
    try {
    } finally {
    }
  }

  class CloseableFoo implements AutoCloseable {

    @MustBeClosed
    CloseableFoo() {}

    // Doesn't autoclose Foo on Stream close.
    Stream<String> stream() {
      return null;
    }

    @Override
    public void close() {}
  }

  void twrStream() {
    // BUG: Diagnostic contains:
    try (Stream<String> stream = new CloseableFoo().stream()) {}
  }

  void constructorsTransitivelyRequiredAnnotation() {
    abstract class Parent implements AutoCloseable {
      @MustBeClosed
      Parent() {}

      // BUG: Diagnostic contains: Invoked constructor is marked @MustBeClosed
      Parent(int i) {
        this();
      }
    }

    // BUG: Diagnostic contains: Implicitly invoked constructor is marked @MustBeClosed
    abstract class ChildDefaultConstructor extends Parent {}

    abstract class ChildExplicitConstructor extends Parent {
      // BUG: Diagnostic contains: Invoked constructor is marked @MustBeClosed
      ChildExplicitConstructor() {}

      // BUG: Diagnostic contains: Invoked constructor is marked @MustBeClosed
      ChildExplicitConstructor(int a) {
        super();
      }
    }
  }
}


text:
package org.apereo.cas.authentication.policy;

import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.exceptions.UniquePrincipalRequiredException;
import org.apereo.cas.config.CasCoreHttpConfiguration;
import org.apereo.cas.config.CasCoreNotificationsConfiguration;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreTicketCatalogConfiguration;
import org.apereo.cas.config.CasCoreTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.CasCoreTicketsConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.CasCoreWebConfiguration;
import org.apereo.cas.config.CasDefaultServiceTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration;
import org.apereo.cas.ticket.TicketGrantingTicketImpl;
import org.apereo.cas.ticket.expiration.NeverExpiresExpirationPolicy;
import org.apereo.cas.ticket.registry.TicketRegistry;
import org.apereo.cas.validation.Assertion;

import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.LinkedHashSet;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * This is {@link UniquePrincipalAuthenticationPolicyTests}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@SpringBootTest(classes = {
    RefreshAutoConfiguration.class,
    CasCoreTicketIdGeneratorsConfiguration.class,
    CasDefaultServiceTicketIdGeneratorsConfiguration.class,
    CasCoreTicketsConfiguration.class,
    CasCoreWebConfiguration.class,
    CasCoreUtilConfiguration.class,
    CasCoreNotificationsConfiguration.class,
    CasCoreHttpConfiguration.class,
    CasWebApplicationServiceFactoryConfiguration.class,
    CasCoreTicketCatalogConfiguration.class,
    CasCoreServicesConfiguration.class
})
@Tag("AuthenticationPolicy")
public class UniquePrincipalAuthenticationPolicyTests {
    @Autowired
    @Qualifier(TicketRegistry.BEAN_NAME)
    private TicketRegistry ticketRegistry;

    @Autowired
    private ConfigurableApplicationContext applicationContext;

    @Test
    public void verifyPolicyIsGoodUserNotFound() {
        this.ticketRegistry.deleteAll();
        val p = new UniquePrincipalAuthenticationPolicy(this.ticketRegistry);
        assertTrue(p.isSatisfiedBy(CoreAuthenticationTestUtils.getAuthentication("casuser"),
            new LinkedHashSet<>(), applicationContext, Optional.empty()).isSuccess());
    }

    @Test
    public void verifyPolicyWithAssertion() throws Exception {
        this.ticketRegistry.deleteAll();
        val p = new UniquePrincipalAuthenticationPolicy(this.ticketRegistry);
        assertTrue(p.isSatisfiedBy(CoreAuthenticationTestUtils.getAuthentication("casuser"),
            new LinkedHashSet<>(), applicationContext, Optional.of(mock(Assertion.class))).isSuccess());
    }

    @Test
    @SneakyThrows
    public void verifyPolicyFailsUserFoundOnce() {
        this.ticketRegistry.deleteAll();
        val ticket = new TicketGrantingTicketImpl("TGT-1",
            CoreAuthenticationTestUtils.getAuthentication("casuser"),
            NeverExpiresExpirationPolicy.INSTANCE);
        this.ticketRegistry.addTicket(ticket);
        val p = new UniquePrincipalAuthenticationPolicy(this.ticketRegistry);
        assertThrows(UniquePrincipalRequiredException.class,
            () -> p.isSatisfiedBy(CoreAuthenticationTestUtils.getAuthentication("casuser"),
                new LinkedHashSet<>(), applicationContext, Optional.empty()));
    }
}


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_UTIL_CONSTRAINTS_INTEGRAL_H_
#define _BLAZE_UTIL_CONSTRAINTS_INTEGRAL_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/util/constraints/ConstraintTest.h>
#include <blaze/util/Suffix.h>
#include <blaze/util/typetraits/IsIntegral.h>

namespace blaze {

//=================================================================================================
//
//  MUST_BE_INTEGRAL_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Compile time constraint.
// \ingroup constraints
//
// Helper template class for the compile time constraint enforcement. Based on the compile time
// constant expression used for the template instantiation, either the undefined basic template
// or the specialization is selected. If the undefined basic template is selected, a compilation
// error is created.
*/
template< bool > struct CONSTRAINT_MUST_BE_INTEGRAL_TYPE_FAILED;
template<> struct CONSTRAINT_MUST_BE_INTEGRAL_TYPE_FAILED<true> { enum { value = 1 }; };
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup constraints
//
// In case the given data type \a T is not an integral data type, a compilation error is created.
*/
#define BLAZE_CONSTRAINT_MUST_BE_INTEGRAL_TYPE(T) \
   typedef \
      ::blaze::CONSTRAINT_TEST< \
         ::blaze::CONSTRAINT_MUST_BE_INTEGRAL_TYPE_FAILED< ::blaze::IsIntegral<T>::value >::value > \
      BLAZE_JOIN( CONSTRAINT_MUST_BE_INTEGRAL_TYPE_TYPEDEF, __LINE__ )
//*************************************************************************************************

//=================================================================================================
//
//  MUST_NOT_BE_INTEGRAL_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Compile time constraint.
// \ingroup constraints
//
// Helper template class for the compile time constraint enforcement. Based on the compile time
// constant expression used for the template instantiation, either the undefined basic template
// or the specialization is selected. If the undefined basic template is selected, a compilation
// error is created.
*/
template< bool > struct CONSTRAINT_MUST_NOT_BE_INTEGRAL_TYPE_FAILED;
template<> struct CONSTRAINT_MUST_NOT_BE_INTEGRAL_TYPE_FAILED<true> { enum { value = 1 }; };
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup constraints
//
// In case the given data type \a T is an integral data type, a compilation error is created.
*/
#define BLAZE_CONSTRAINT_MUST_NOT_BE_INTEGRAL_TYPE(T) \
   typedef \
      ::blaze::CONSTRAINT_TEST< \
         ::blaze::CONSTRAINT_MUST_NOT_BE_INTEGRAL_TYPE_FAILED< !::blaze::IsIntegral<T>::value >::value > \
      BLAZE_JOIN( CONSTRAINT_MUST_NOT_BE_INTEGRAL_TYPE_TYPEDEF, __LINE__ )
//*************************************************************************************************

} // namespace blaze

#endif


text:
package com.dianping.zebra.group.config.system;

public class Constants {

   public static final String ATTR_ALLOW_PERCENT = "allow-percent";

   public static final String ATTR_APP = "app";

   public static final String ATTR_IP_PREFIX = "ip-prefix";

   public static final String ATTR_NAME = "name";

   public static final String ATTR_SQL_ID = "sql-id";

   public static final String ELEMENT_RETRY_TIMES = "retry-times";

   public static final String ENTITY_DATA_CENTER = "data-center";

   public static final String ENTITY_DATA_CENTERS = "data-centers";

   public static final String ENTITY_SQL_FLOW_CONTROL = "sql-flow-control";

   public static final String ENTITY_SQL_FLOW_CONTROLS = "sql-flow-controls";

   public static final String ENTITY_SYSTEM_CONFIG = "system-config";
}