text:
package system.basic

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

import common.JsHelpers
import common.TestHelpers
import common.TestUtils
import common.Wsk
import common.WskProps
import common.WskTestHelpers
import spray.json._

@RunWith(classOf[JUnitRunner])
abstract class WskUnicodeTests
    extends TestHelpers
    with WskTestHelpers
    with JsHelpers {

    val actionKind:String
    val actionSource:String

    implicit val wskprops = WskProps()
    val wsk = new Wsk

    s"$actionKind action" should "Ensure that UTF-8 in supported in source files, input params, logs, and output results" in withAssetCleaner(wskprops) {
        (wp, assetHelper) =>
            val name = s"unicodeGalore.${actionKind.replace(":", "")}"

            assetHelper.withCleaner(wsk.action, name) {
                (action, _) =>
                    action.create(
                        name,
                        Some(TestUtils.getTestActionFilename(actionSource)),
                        main = if (actionKind == "java") Some("Unicode") else None,
                        kind = Some(actionKind))
            }

            withActivation(wsk.activation, wsk.action.invoke(name, parameters = Map("delimiter" -> JsString("❄")))) {
                activation =>
                    val response = activation.response
                    response.result.get.fields.get("error") shouldBe empty
                    response.result.get.fields.get("winter") should be(Some(JsString("❄ ☃ ❄")))

                    activation.logs.toList.flatten.mkString(" ") should include("❄ ☃ ❄")
            }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>petshop</artifactId>
        <groupId>be.kwakeroni.parameters.petshop</groupId>
        <version>0.1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>petshop-web</artifactId>
    <packaging>jar</packaging>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                    <executions>
                        <execution>
                            <id>copy webapp</id>
                            <goals>
                                <goal>copy-resources</goal>
                            </goals>
                            <phase>process-sources</phase>
                            <configuration>
                                <outputDirectory>${project.build.directory}/petshop-webapp-src</outputDirectory>
                                <resources>
                                    <resource>
                                        <directory>src/main/webapp</directory>
                                        <filtering>false</filtering>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>com.github.eirslett</groupId>
                    <artifactId>frontend-maven-plugin</artifactId>
                    <version>1.6</version>
                    <executions>
                        <execution>
                            <id>install node and npm</id>
                            <goals>
                                <goal>install-node-and-npm</goal>
                            </goals>
                            <phase>generate-resources</phase>
                            <configuration>
                                <nodeVersion>v8.6.0</nodeVersion>
                                <!--<npmVersion>2.15.9</npmVersion>-->
                                <!--<downloadRoot>http://myproxy.example.org/nodejs/</downloadRoot>-->
                            </configuration>
                        </execution>
                        <execution>
                            <id>npm install</id>
                            <goals>
                                <goal>npm</goal>
                            </goals>
                            <phase>generate-resources</phase>
                            <configuration>
                                <arguments>install</arguments>
                            </configuration>
                        </execution>
                        <execution>
                            <id>ng build</id>
                            <goals>
                                <goal>npm</goal>
                            </goals>
                            <phase>generate-resources</phase>
                            <configuration>
                                <arguments>run build -- --output-path ../classes/</arguments>
                            </configuration>
                        </execution>
                    </executions>
                    <configuration>
                        <workingDirectory>${project.build.directory}/petshop-webapp-src</workingDirectory>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>com.github.eirslett</groupId>
                <artifactId>frontend-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.devicefarm.model.transform;

import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;

import com.amazonaws.services.devicefarm.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DeviceMinutes JSON Unmarshaller
 */
public class DeviceMinutesJsonUnmarshaller implements
        Unmarshaller<DeviceMinutes, JsonUnmarshallerContext> {

    public DeviceMinutes unmarshall(JsonUnmarshallerContext context)
            throws Exception {
        DeviceMinutes deviceMinutes = new DeviceMinutes();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL)
            return null;

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("total", targetDepth)) {
                    context.nextToken();
                    deviceMinutes.setTotal(context
                            .getUnmarshaller(Double.class).unmarshall(context));
                }
                if (context.testExpression("metered", targetDepth)) {
                    context.nextToken();
                    deviceMinutes.setMetered(context.getUnmarshaller(
                            Double.class).unmarshall(context));
                }
                if (context.testExpression("unmetered", targetDepth)) {
                    context.nextToken();
                    deviceMinutes.setUnmetered(context.getUnmarshaller(
                            Double.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null
                        || context.getLastParsedParentElement().equals(
                                currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return deviceMinutes;
    }

    private static DeviceMinutesJsonUnmarshaller instance;

    public static DeviceMinutesJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new DeviceMinutesJsonUnmarshaller();
        return instance;
    }
}


text:
<!DOCTYPE html>

  <title>DOM manipulation with jQuery</title>

 Hello. Welcome to the jQuery DOM Manipulation Challenge!

 My DBC Mascot


text:
from abc import ABCMeta, abstractmethod, abstractproperty

from django.utils.translation import gettext_lazy as _

import sqlalchemy
from jsonobject.base_properties import DefaultProperty

from dimagi.ext import jsonobject

from corehq.apps.aggregate_ucrs.aggregations import AGG_WINDOW_START_PARAM
from corehq.apps.aggregate_ucrs.query_column_providers import (
    AggregationParamQueryColumnProvider,
    StandardQueryColumnProvider,
)
from corehq.apps.userreports import const
from corehq.apps.userreports.datatypes import (
    DATA_TYPE_DATE,
    DATA_TYPE_DECIMAL,
    DATA_TYPE_INTEGER,
    DATA_TYPE_SMALL_INTEGER,
    DATA_TYPE_STRING,
    DataTypeProperty,
)
from corehq.apps.userreports.indicators import Column
from corehq.apps.userreports.reports.specs import SQLAGG_COLUMN_MAP

class ColumnAdapater(metaclass=ABCMeta):
    """
    A column adapter represents everything needed to work with an aggregate column,
    including its config as well as its sqlalchemy information (via the ucr column spec).

    Column adapters handle both the querying side (via the to_sqlalchemy_query_column function)
    as well as the table creation/writing side.
    """
    # most subclasses will/should override this to provide a schema for how they are configured.
    config_spec = jsonobject.JsonObject

    def __init__(self, db_column):
        self._db_column = db_column
        self.column_id = db_column.column_id
        self.properties = self.config_spec.wrap(db_column.config_params)

    @abstractmethod
    def is_nullable(self):
        pass

    @abstractmethod
    def is_primary_key(self):
        pass

    @abstractmethod
    def create_index(self):
        pass

    def to_ucr_column_spec(self):
        """
        :return: a UCR-compatible `Column` object that can be used to be converted to sqlalchemy tables
        """
        return Column(
            id=self.column_id,
            datatype=self.get_datatype(),
            is_nullable=self.is_nullable(),
            is_primary_key=self.is_primary_key(),
            create_index=self.create_index(),
        )

    @abstractmethod
    def get_datatype(self):
        pass

    @abstractmethod
    def to_sqlalchemy_query_column(self, sqlalchemy_table, aggregation_params):
        pass

    @abstractmethod
    def is_groupable(self):
        """
        Whether the column should be included in the group by clause when doing aggregation queries
        """
        pass

PRIMARY_COLUMN_TYPE_REFERENCE = 'reference'
PRIMARY_COLUMN_TYPE_CONSTANT = 'constant'
PRIMARY_COLUMN_TYPE_SQL = 'sql_statement'
PRIMARY_COLUMN_TYPE_CHOICES = (
    (PRIMARY_COLUMN_TYPE_REFERENCE, _('Reference')),
    (PRIMARY_COLUMN_TYPE_CONSTANT, _('Constant')),
    (PRIMARY_COLUMN_TYPE_SQL, _('SQL Statement')),
)

class RawColumnAdapter(ColumnAdapater):
    """
    A ColumnAdapter that is composed of all the possible fields it can have.
    """

    def __init__(self, column_id, datatype, is_nullable, is_primary_key, create_index, query_column_provider):
        # short circuit super class call to avoid refences to db_column
        # todo: find a better way to do this that doesn't break constructor inheritance
        self.column_id = column_id
        self._datatype = datatype
        self._is_nullable = is_nullable
        self._is_primary_key = is_primary_key
        self._create_index = create_index
        self.query_column_provider = query_column_provider

    def is_nullable(self):
        return self._is_nullable

    def is_primary_key(self):
        return self._is_primary_key

    def create_index(self):
        return self._create_index

    def get_datatype(self):
        return self._datatype

    def to_sqlalchemy_query_column(self, sqlalchemy_table, aggregation_params):
        return self.query_column_provider.get_query_column(sqlalchemy_table, aggregation_params)

    def is_groupable(self):
        return self.query_column_provider.is_groupable()

def IdColumnAdapter():
    """shortcut/convenience method to instantiate id columns"""
    return RawColumnAdapter(
        column_id='doc_id',
        datatype=DATA_TYPE_STRING,
        is_nullable=False,
        is_primary_key=True,
        create_index=True,
        query_column_provider=StandardQueryColumnProvider('doc_id'),
    )

def MonthColumnAdapter():
    """shortcut/convenience method to instantiate month columns"""
    return RawColumnAdapter(
        column_id='month',
        datatype=DATA_TYPE_DATE,
        is_nullable=False,
        is_primary_key=True,
        create_index=True,
        query_column_provider=AggregationParamQueryColumnProvider(AGG_WINDOW_START_PARAM)
    )

def WeekColumnAdapter():
    """shortcut/convenience method to instantiate week columns"""
    return RawColumnAdapter(
        column_id='week',
        datatype=DATA_TYPE_DATE,
        is_nullable=False,
        is_primary_key=True,
        create_index=True,
        query_column_provider=AggregationParamQueryColumnProvider(AGG_WINDOW_START_PARAM)
    )

class PrimaryColumnAdapter(ColumnAdapater, metaclass=ABCMeta):
    """
    A base ColumnAdapter class for columns associated with the primary table.
    """

    def is_nullable(self):
        return True

    def is_primary_key(self):
        return False

    def create_index(self):
        return False

    @staticmethod
    def from_db_column(db_column):
        type_to_class_mapping = {
            PRIMARY_COLUMN_TYPE_REFERENCE: ReferenceColumnAdapter,
            PRIMARY_COLUMN_TYPE_CONSTANT: ConstantColumnAdapter,
            PRIMARY_COLUMN_TYPE_SQL: SqlColumnAdapter,
        }
        return type_to_class_mapping[db_column.column_type](db_column)

    def is_groupable(self):
        return True

class ConstantColumnProperties(jsonobject.JsonObject):
    constant = DefaultProperty(required=True)

class ConstantColumnAdapter(PrimaryColumnAdapter):
    """
    A PrimaryColumnAdapter class that allows populating a table with constant values.
    """

    config_spec = ConstantColumnProperties

    def get_datatype(self):
        # todo should be configurable
        return DATA_TYPE_INTEGER

    def to_sqlalchemy_query_column(self, sqlalchemy_table, aggregation_params):
        # https://stackoverflow.com/a/7546802/8207
        return sqlalchemy.bindparam(self.column_id, self.properties.constant)

    def is_groupable(self):
        return False

class ReferenceColumnProperties(jsonobject.JsonObject):
    referenced_column = jsonobject.StringProperty(required=True)

class ReferenceColumnAdapter(PrimaryColumnAdapter):
    """
    A PrimaryColumnAdapter class that allows populating a table with the value
    of a column in the primary table.
    """

    config_spec = ReferenceColumnProperties

    def get_datatype(self):
        return _get_datatype_from_referenced_column(self._db_column, self.properties.referenced_column)

    def to_sqlalchemy_query_column(self, sqlalchemy_table, aggregation_params):
        return sqlalchemy_table.c[self.properties.referenced_column]

class SqlColumnProperties(jsonobject.JsonObject):
    datatype = DataTypeProperty(required=True)
    statement = jsonobject.StringProperty(required=True)
    statement_params = jsonobject.DictProperty()

class SqlColumnAdapter(PrimaryColumnAdapter):
    """
    A PrimaryColumnAdapter class that allows populating a table with the value
    of a sql expression run on the primary table.
    """

    config_spec = SqlColumnProperties

    def get_datatype(self):
        return self.properties.datatype

    def to_sqlalchemy_query_column(self, sqlalchemy_table, aggregation_params):
        def _map_params(statement_params):
            mapped_params = {}
            for param_name, param_value in statement_params.items():
                mapped_value = param_value
                # transform anything starting with a ":" to the value passed in from aggregation_params
                if mapped_value.startswith(':'):
                    mapped_value = aggregation_params[mapped_value[1:]]
                mapped_params[param_name] = mapped_value
            return mapped_params

        mapped_params = _map_params(self.properties.statement_params)
        return sqlalchemy.text(self.properties.statement).bindparams(
            **mapped_params
        )

SECONDARY_COLUMN_TYPE_CHOICES = (
    (const.AGGGREGATION_TYPE_SUM, _('Sum')),
    (const.AGGGREGATION_TYPE_MIN, _('Min')),
    (const.AGGGREGATION_TYPE_MAX, _('Max')),
    (const.AGGGREGATION_TYPE_AVG, _('Average')),
    (const.AGGGREGATION_TYPE_COUNT, _('Count')),
    (const.AGGGREGATION_TYPE_COUNT_UNIQUE, _('Count Unique Values')),
    (const.AGGGREGATION_TYPE_NONZERO_SUM, _('Has a nonzero sum (1 if sum is nonzero else 0).')),
)

class SecondaryColumnAdapter(ColumnAdapater):
    """
    A base ColumnAdapter class for columns associated with secondary tables.
    """

    def is_nullable(self):
        return True

    def is_primary_key(self):
        return False

    def create_index(self):
        return False

    @staticmethod
    def from_db_column(db_column):
        assert db_column.aggregation_type in SQLAGG_COLUMN_MAP
        return SqlaggColumnAdapter(db_column)

    def is_groupable(self):
        return False

class SingleFieldColumnProperties(jsonobject.JsonObject):
    referenced_column = jsonobject.StringProperty(required=True)

class SimpleAggregationAdapater(SecondaryColumnAdapter, metaclass=ABCMeta):
    """
    Generic SecondaryColumnAdapter class that does a passed-in sqlalchemy aggregation.
    """
    config_spec = SingleFieldColumnProperties

    @abstractproperty
    def sqlalchemy_fn(self):
        pass

    def to_sqlalchemy_query_column(self, sqlalchemy_table, aggregation_params):
        return self.sqlalchemy_fn(sqlalchemy_table.c[self.properties.referenced_column])

class SqlaggColumnAdapter(SimpleAggregationAdapater):

    def _get_sqlagg_column(self):
        return SQLAGG_COLUMN_MAP[self._db_column.aggregation_type](self._db_column.column_id)

    @property
    def sqlalchemy_fn(self):
        return self._get_sqlagg_column().aggregate_fn

    def get_datatype(self):
        # special case some columns to allow to e.g. count unique values from a string column
        if self._db_column.aggregation_type in (
                const.AGGGREGATION_TYPE_COUNT,
                const.AGGGREGATION_TYPE_COUNT_UNIQUE
        ):
            return DATA_TYPE_INTEGER
        elif self._db_column.aggregation_type in (
                const.AGGGREGATION_TYPE_NONZERO_SUM
        ):
            return DATA_TYPE_SMALL_INTEGER
        elif self._db_column.aggregation_type in (
                const.AGGGREGATION_TYPE_AVG
        ):
            return DATA_TYPE_DECIMAL
        else:
            # default to using the same column type as the source
            return _get_datatype_from_referenced_column(self._db_column, self.properties.referenced_column)

def _get_datatype_from_referenced_column(db_column, referenced_column):
    return db_column.table_definition.data_source.get_column_by_id(referenced_column).datatype


text:
#pragma once

// Constants
//
#ifndef E_NOTFOUND
#define E_NOTFOUND HRESULT_FROM_WIN32(ERROR_NOT_FOUND)
#endif

#ifndef E_FILENOTFOUND
#define E_FILENOTFOUND HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
#endif

#ifndef E_NOTSUPPORTED
#define E_NOTSUPPORTED HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)
#endif

// Enumerations
//
/// <summary>
/// The state of an instance.
/// </summary>
enum InstanceState
{
    /// <summary>
    /// The instance state has not been determined.
    /// </summary>
    eNone = 0,

    /// <summary>
    /// The instance installation path exists.
    /// </summary>
    eLocal = 1,

    /// <summary>
    /// A product is registered to the instance.
    /// </summary>
    eRegistered = 2,

    /// <summary>
    /// No reboot is required for the instance.
    /// </summary>
    eNoRebootRequired = 4,

    /// <summary>
    /// No errors were reported for the instance.
    /// </summary>
    eNoErrors = 8,

    /// <summary>
    /// The instance represents a complete install.
    /// </summary>
    eComplete = MAXUINT,
};

// Forward interface declarations
//
#ifndef __ISetupInstance_FWD_DEFINED__
#define __ISetupInstance_FWD_DEFINED__
typedef struct ISetupInstance ISetupInstance;
#endif

#ifndef __ISetupInstance2_FWD_DEFINED__
#define __ISetupInstance2_FWD_DEFINED__
typedef struct ISetupInstance2 ISetupInstance2;
#endif

#ifndef __ISetupInstanceCatalog_FWD_DEFINED__
#define __ISetupInstanceCatalog_FWD_DEFINED__
typedef struct ISetupInstanceCatalog ISetupInstanceCatalog;
#endif

#ifndef __ISetupLocalizedProperties_FWD_DEFINED__
#define __ISetupLocalizedProperties_FWD_DEFINED__
typedef struct ISetupLocalizedProperties ISetupLocalizedProperties;
#endif

#ifndef __IEnumSetupInstances_FWD_DEFINED__
#define __IEnumSetupInstances_FWD_DEFINED__
typedef struct IEnumSetupInstances IEnumSetupInstances;
#endif

#ifndef __ISetupConfiguration_FWD_DEFINED__
#define __ISetupConfiguration_FWD_DEFINED__
typedef struct ISetupConfiguration ISetupConfiguration;
#endif

#ifndef __ISetupConfiguration2_FWD_DEFINED__
#define __ISetupConfiguration2_FWD_DEFINED__
typedef struct ISetupConfiguration2 ISetupConfiguration2;
#endif

#ifndef __ISetupPackageReference_FWD_DEFINED__
#define __ISetupPackageReference_FWD_DEFINED__
typedef struct ISetupPackageReference ISetupPackageReference;
#endif

#ifndef __ISetupProductReference_FWD_DEFINED__
#define __ISetupProductReference_FWD_DEFINED__
typedef struct ISetupProductReference ISetupProductReference;
#endif

#ifndef __ISetupProductReference2_FWD_DEFINED__
#define __ISetupProductReference2_FWD_DEFINED__
typedef struct ISetupProductReference2 ISetupProductReference2;
#endif

#ifndef __ISetupHelper_FWD_DEFINED__
#define __ISetupHelper_FWD_DEFINED__
typedef struct ISetupHelper ISetupHelper;
#endif

#ifndef __ISetupErrorInfo_FWD_DEFINED__
#define __ISetupErrorInfo_FWD_DEFINED__
typedef struct ISetupErrorInfo ISetupErrorInfo;
#endif

#ifndef __ISetupErrorState_FWD_DEFINED__
#define __ISetupErrorState_FWD_DEFINED__
typedef struct ISetupErrorState ISetupErrorState;
#endif

#ifndef __ISetupErrorState2_FWD_DEFINED__
#define __ISetupErrorState2_FWD_DEFINED__
typedef struct ISetupErrorState2 ISetupErrorState2;
#endif

#ifndef __ISetupErrorState3_FWD_DEFINED__
#define __ISetupErrorState3_FWD_DEFINED__
typedef struct ISetupErrorState3 ISetupErrorState3;
#endif

#ifndef __ISetupFailedPackageReference_FWD_DEFINED__
#define __ISetupFailedPackageReference_FWD_DEFINED__
typedef struct ISetupFailedPackageReference ISetupFailedPackageReference;
#endif

#ifndef __ISetupFailedPackageReference2_FWD_DEFINED__
#define __ISetupFailedPackageReference2_FWD_DEFINED__
typedef struct ISetupFailedPackageReference2 ISetupFailedPackageReference2;
#endif

#ifndef __ISetupFailedPackageReference3_FWD_DEFINED__
#define __ISetupFailedPackageReference3_FWD_DEFINED__
typedef struct ISetupFailedPackageReference3 ISetupFailedPackageReference3;
#endif

#ifndef __ISetupPropertyStore_FWD_DEFINED__
#define __ISetupPropertyStore_FWD_DEFINED__
typedef struct ISetupPropertyStore ISetupPropertyStore;
#endif

#ifndef __ISetupLocalizedPropertyStore_FWD_DEFINED__
#define __ISetupLocalizedPropertyStore_FWD_DEFINED__
typedef struct ISetupLocalizedPropertyStore ISetupLocalizedPropertyStore;
#endif

#ifndef __ISetupPolicy_FWD_DEFINED__
#define __ISetupPolicy_FWD_DEFINED__
typedef struct ISetupPolicy ISetupPolicy;
#endif

// Forward class declarations
//
#ifndef __SetupConfiguration_FWD_DEFINED__
#define __SetupConfiguration_FWD_DEFINED__

#ifdef __cplusplus
typedef class SetupConfiguration SetupConfiguration;
#endif

#endif

#ifdef __cplusplus
extern "C" {
#endif

// Interface definitions
//
EXTERN_C const IID IID_ISetupInstance;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Information about an instance of a product.
/// </summary>
struct DECLSPEC_UUID("B41463C3-8866-43B5-BC33-2B0676F7F42E") DECLSPEC_NOVTABLE ISetupInstance : public IUnknown
{
    /// <summary>
    /// Gets the instance identifier (should match the name of the parent instance directory).
    /// </summary>
    /// <param name="pbstrInstanceId">The instance identifier.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
    STDMETHOD(GetInstanceId)(
        _Out_ BSTR* pbstrInstanceId
        ) = 0;

    /// <summary>
    /// Gets the local date and time when the installation was originally installed.
    /// </summary>
    /// <param name="pInstallDate">The local date and time when the installation was originally installed.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
    STDMETHOD(GetInstallDate)(
        _Out_ LPFILETIME pInstallDate
        ) = 0;

    /// <summary>
    /// Gets the unique name of the installation, often indicating the branch and other information used for telemetry.
    /// </summary>
    /// <param name="pbstrInstallationName">The unique name of the installation, often indicating the branch and other information used for telemetry.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
    STDMETHOD(GetInstallationName)(
        _Out_ BSTR* pbstrInstallationName
        ) = 0;

    /// <summary>
    /// Gets the path to the installation root of the product.
    /// </summary>
    /// <param name="pbstrInstallationPath">The path to the installation root of the product.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
    STDMETHOD(GetInstallationPath)(
        _Out_ BSTR* pbstrInstallationPath
        ) = 0;

    /// <summary>
    /// Gets the version of the product installed in this instance.
    /// </summary>
    /// <param name="pbstrInstallationVersion">The version of the product installed in this instance.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
    STDMETHOD(GetInstallationVersion)(
        _Out_ BSTR* pbstrInstallationVersion
        ) = 0;

    /// <summary>
    /// Gets the display name (title) of the product installed in this instance.
    /// </summary>
    /// <param name="lcid">The LCID for the display name.</param>
    /// <param name="pbstrDisplayName">The display name (title) of the product installed in this instance.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
    STDMETHOD(GetDisplayName)(
        _In_ LCID lcid,
        _Out_ BSTR* pbstrDisplayName
        ) = 0;

    /// <summary>
    /// Gets the description of the product installed in this instance.
    /// </summary>
    /// <param name="lcid">The LCID for the description.</param>
    /// <param name="pbstrDescription">The description of the product installed in this instance.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
    STDMETHOD(GetDescription)(
        _In_ LCID lcid,
        _Out_ BSTR* pbstrDescription
        ) = 0;

    /// <summary>
    /// Resolves the optional relative path to the root path of the instance.
    /// </summary>
    /// <param name="pwszRelativePath">A relative path within the instance to resolve, or NULL to get the root path.</param>
    /// <param name="pbstrAbsolutePath">The full path to the optional relative path within the instance. If the relative path is NULL, the root path will always terminate in a backslash.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
    STDMETHOD(ResolvePath)(
        _In_opt_z_ LPCOLESTR pwszRelativePath,
        _Out_ BSTR* pbstrAbsolutePath
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupInstance2;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Information about an instance of a product.
/// </summary>
struct DECLSPEC_UUID("89143C9A-05AF-49B0-B717-72E218A2185C") DECLSPEC_NOVTABLE ISetupInstance2 : public ISetupInstance
{
    /// <summary>
    /// Gets the state of the instance.
    /// </summary>
    /// <param name="pState">The state of the instance.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
    STDMETHOD(GetState)(
        _Out_ InstanceState* pState
        ) = 0;

    /// <summary>
    /// Gets an array of package references registered to the instance.
    /// </summary>
    /// <param name="ppsaPackages">Pointer to an array of <see cref="ISetupPackageReference"/>.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the packages property is not defined.</returns>
    STDMETHOD(GetPackages)(
        _Out_ LPSAFEARRAY* ppsaPackages
        ) = 0;

    /// <summary>
    /// Gets a pointer to the <see cref="ISetupPackageReference"/> that represents the registered product.
    /// </summary>
    /// <param name="ppPackage">Pointer to an instance of <see cref="ISetupPackageReference"/>. This may be NULL if <see cref="GetState"/> does not return <see cref="eComplete"/>.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the packages property is not defined.</returns>
    STDMETHOD(GetProduct)(
        _Outptr_result_maybenull_ ISetupPackageReference** ppPackage
        ) = 0;

    /// <summary>
    /// Gets the relative path to the product application, if available.
    /// </summary>
    /// <param name="pbstrProductPath">The relative path to the product application, if available.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
    STDMETHOD(GetProductPath)(
        _Outptr_result_maybenull_ BSTR* pbstrProductPath
        ) = 0;

    /// <summary>
    /// Gets the error state of the instance, if available.
    /// </summary>
    /// <param name="pErrorState">The error state of the instance, if available.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
    STDMETHOD(GetErrors)(
        _Outptr_result_maybenull_ ISetupErrorState** ppErrorState
        ) = 0;

    /// <summary>
    /// Gets a value indicating whether the instance can be launched.
    /// </summary>
    /// <param name="pfIsLaunchable">Whether the instance can be launched.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    /// <remarks>
    /// An instance could have had errors during install but still be launched. Some features may not work correctly, but others will.
    /// </remarks>
    STDMETHOD(IsLaunchable)(
        _Out_ VARIANT_BOOL* pfIsLaunchable
        ) = 0;

    /// <summary>
    /// Gets a value indicating whether the instance is complete.
    /// </summary>
    /// <param name="pfIsLaunchable">Whether the instance is complete.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    /// <remarks>
    /// An instance is complete if it had no errors during install, resume, or repair.
    /// </remarks>
    STDMETHOD(IsComplete)(
        _Out_ VARIANT_BOOL* pfIsComplete
        ) = 0;

    /// <summary>
    /// Gets product-specific properties.
    /// </summary>
    /// <param name="ppPropeties">A pointer to an instance of <see cref="ISetupPropertyStore"/>. This may be NULL if no properties are defined.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
    STDMETHOD(GetProperties)(
        _Outptr_result_maybenull_ ISetupPropertyStore** ppProperties
        ) = 0;

    /// <summary>
    /// Gets the directory path to the setup engine that installed the instance.
    /// </summary>
    /// <param name="pbstrEnginePath">The directory path to the setup engine that installed the instance.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
    STDMETHOD(GetEnginePath)(
        _Outptr_result_maybenull_ BSTR* pbstrEnginePath
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupInstanceCatalog;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Information about a catalog used to install an instance.
/// </summary>
struct DECLSPEC_UUID("9AD8E40F-39A2-40F1-BF64-0A6C50DD9EEB") DECLSPEC_NOVTABLE ISetupInstanceCatalog : public IUnknown
{
    /// <summary>
    /// Gets catalog information properties.
    /// </summary>
    /// <param name="ppCatalogInfo">A pointer to an instance of <see cref="ISetupPropertyStore"/>.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property does not exist.</returns>
    STDMETHOD(GetCatalogInfo)(
        _Out_ ISetupPropertyStore** ppCatalogInfo
    ) = 0;

    /// <summary>
    /// Gets a value indicating whether the catalog is a prerelease.
    /// </summary>
    /// <param name="pfIsPrerelease">Whether the catalog for the instance is a prerelease version.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property does not exist.</returns>
    STDMETHOD(IsPrerelease)(
        _Out_ VARIANT_BOOL* pfIsPrerelease
    ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupLocalizedProperties;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Provides localized properties of an instance of a product.
/// </summary>
struct DECLSPEC_UUID("F4BD7382-FE27-4AB4-B974-9905B2A148B0") DECLSPEC_NOVTABLE ISetupLocalizedProperties : public IUnknown
{
    /// <summary>
    /// Gets localized product-specific properties.
    /// </summary>
    /// <param name="ppLocalizedProperties">A pointer to an instance of <see cref="ISetupLocalizedPropertyStore"/>. This may be NULL if no properties are defined.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetLocalizedProperties)(
        _Outptr_result_maybenull_ ISetupLocalizedPropertyStore** ppLocalizedProperties
    ) = 0;

    /// <summary>
    /// Gets localized channel-specific properties.
    /// </summary>
    /// <param name="ppLocalizedChannelProperties">A pointer to an instance of <see cref="ISetupLocalizedPropertyStore"/>. This may be NULL if no channel properties are defined.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetLocalizedChannelProperties)(
        _Outptr_result_maybenull_ ISetupLocalizedPropertyStore** ppLocalizedChannelProperties
    ) = 0;
};
#endif

EXTERN_C const IID IID_IEnumSetupInstances;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// An enumerator of installed <see cref="ISetupInstance"/> objects.
/// </summary>
struct DECLSPEC_UUID("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848") DECLSPEC_NOVTABLE IEnumSetupInstances : public IUnknown
{
    /// <summary>
    /// Retrieves the next set of product instances in the enumeration sequence.
    /// </summary>
    /// <param name="celt">The number of product instances to retrieve.</param>
    /// <param name="rgelt">A pointer to an array of <see cref="ISetupInstance"/>.</param>
    /// <param name="pceltFetched">A pointer to the number of product instances retrieved. If <paramref name="celt"/> is 1 this parameter may be NULL.</param>
    /// <returns>S_OK if the number of elements were fetched, S_FALSE if nothing was fetched (at end of enumeration), E_INVALIDARG if <paramref name="celt"/> is greater than 1 and pceltFetched is NULL, or E_OUTOFMEMORY if an <see cref="ISetupInstance"/> could not be allocated.</returns>
    STDMETHOD(Next)(
        _In_ ULONG celt,
        _Out_writes_to_(celt, *pceltFetched) ISetupInstance** rgelt,
        _Out_opt_ _Deref_out_range_(0, celt) ULONG* pceltFetched
        ) = 0;

    /// <summary>
    /// Skips the next set of product instances in the enumeration sequence.
    /// </summary>
    /// <param name="celt">The number of product instances to skip.</param>
    /// <returns>S_OK if the number of elements could be skipped; otherwise, S_FALSE;</returns>
    STDMETHOD(Skip)(
        _In_ ULONG celt
        ) = 0;

    /// <summary>
    /// Resets the enumeration sequence to the beginning.
    /// </summary>
    /// <returns>Always returns S_OK;</returns>
    STDMETHOD(Reset)(void) = 0;

    /// <summary>
    /// Creates a new enumeration object in the same state as the current enumeration object: the new object points to the same place in the enumeration sequence.
    /// </summary>
    /// <param name="ppenum">A pointer to a pointer to a new <see cref="IEnumSetupInstances"/> interface. If the method fails, this parameter is undefined.</param>
    /// <returns>S_OK if a clone was returned; otherwise, E_OUTOFMEMORY.</returns>
    STDMETHOD(Clone)(
        _Deref_out_opt_ IEnumSetupInstances** ppenum
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupConfiguration;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Gets information about product instances installed on the machine.
/// </summary>
struct DECLSPEC_UUID("42843719-DB4C-46C2-8E7C-64F1816EFD5B") DECLSPEC_NOVTABLE ISetupConfiguration : public IUnknown
{
    /// <summary>
    /// Enumerates all launchable product instances installed.
    /// </summary>
    /// <param name="ppEnumInstances">An enumeration of completed, installed product instances.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(EnumInstances)(
        _Out_ IEnumSetupInstances** ppEnumInstances
        ) = 0;

    /// <summary>
    /// Gets the instance for the current process path.
    /// </summary>
    /// <param name="ppInstance">The instance for the current process path.</param>
    /// <returns>
    /// The instance for the current process path, or E_NOTFOUND if not found.
    /// The <see cref="ISetupInstance::GetState"/> may indicate the instance is invalid.
    /// </returns>
    /// <remarks>
    /// The returned instance may not be launchable.
    /// </remarks>
STDMETHOD(GetInstanceForCurrentProcess)(
        _Out_ ISetupInstance** ppInstance
        ) = 0;

    /// <summary>
    /// Gets the instance for the given path.
    /// </summary>
    /// <param name="ppInstance">The instance for the given path.</param>
    /// <returns>
    /// The instance for the given path, or E_NOTFOUND if not found.
    /// The <see cref="ISetupInstance::GetState"/> may indicate the instance is invalid.
    /// </returns>
    /// <remarks>
    /// The returned instance may not be launchable.
    /// </remarks>
STDMETHOD(GetInstanceForPath)(
        _In_z_ LPCWSTR wzPath,
        _Out_ ISetupInstance** ppInstance
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupConfiguration2;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Gets information about product instances.
/// </summary>
struct DECLSPEC_UUID("26AAB78C-4A60-49D6-AF3B-3C35BC93365D") DECLSPEC_NOVTABLE ISetupConfiguration2 : public ISetupConfiguration
{
    /// <summary>
    /// Enumerates all product instances.
    /// </summary>
    /// <param name="ppEnumInstances">An enumeration of all product instances.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(EnumAllInstances)(
        _Out_ IEnumSetupInstances** ppEnumInstances
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupPackageReference;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// A reference to a package.
/// </summary>
struct DECLSPEC_UUID("da8d8a16-b2b6-4487-a2f1-594ccccd6bf5") DECLSPEC_NOVTABLE ISetupPackageReference : public IUnknown
{
    /// <summary>
    /// Gets the general package identifier.
    /// </summary>
    /// <param name="pbstrId">The general package identifier.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetId)(
        _Out_ BSTR* pbstrId
        ) = 0;

    /// <summary>
    /// Gets the version of the package.
    /// </summary>
    /// <param name="pbstrVersion">The version of the package.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetVersion)(
        _Out_ BSTR* pbstrVersion
        ) = 0;

    /// <summary>
    /// Gets the target process architecture of the package.
    /// </summary>
    /// <param name="pbstrChip">The target process architecture of the package.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetChip)(
        _Out_ BSTR* pbstrChip
        ) = 0;

    /// <summary>
    /// Gets the language and optional region identifier.
    /// </summary>
    /// <param name="pbstrLanguage">The language and optional region identifier.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetLanguage)(
        _Out_ BSTR* pbstrLanguage
        ) = 0;

    /// <summary>
    /// Gets the build branch of the package.
    /// </summary>
    /// <param name="pbstrBranch">The build branch of the package.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetBranch)(
        _Out_ BSTR* pbstrBranch
        ) = 0;

    /// <summary>
    /// Gets the type of the package.
    /// </summary>
    /// <param name="pbstrType">The type of the package.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetType)(
        _Out_ BSTR* pbstrType
        ) = 0;

    /// <summary>
    /// Gets the unique identifier consisting of all defined tokens.
    /// </summary>
    /// <param name="pbstrUniqueId">The unique identifier consisting of all defined tokens.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_UNEXPECTED if no Id was defined (required).</returns>
    STDMETHOD(GetUniqueId)(
        _Out_ BSTR* pbstrUniqueId
        ) = 0;

    /// <summary>
    /// Gets a value indicating whether the package refers to an external extension.
    /// </summary>
    /// <param name="pfIsExtension">A value indicating whether the package refers to an external extension.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_UNEXPECTED if no Id was defined (required).</returns>
    STDMETHOD(GetIsExtension)(
        _Out_ VARIANT_BOOL* pfIsExtension
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupProductReference;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// A reference to a product package.
/// </summary>
struct DECLSPEC_UUID("a170b5ef-223d-492b-b2d4-945032980685") DECLSPEC_NOVTABLE ISetupProductReference : public ISetupPackageReference
{
    /// <summary>
    /// Gets a value indicating whether the product package is installed.
    /// </summary>
    /// <param name="pfIsInstalled">A value indicating whether the product package is installed.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_NOTSUPPORTED if the reference is not to a product, or E_UNEXPECTED if the Installed property is the wrong type.</returns>
    STDMETHOD(GetIsInstalled)(
        _Out_ VARIANT_BOOL* pfIsInstalled
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupProductReference2;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// A reference to a product package.
/// </summary>
struct DECLSPEC_UUID("279a5db3-7503-444b-b34d-308f961b9a06") DECLSPEC_NOVTABLE ISetupProductReference2 : public ISetupProductReference
{
    /// <summary>
    /// Gets a value indicating whether the product supports extensions.
    /// </summary>
    /// <param name="pfSupportsExtensions">A value indicating whether the product supports extensions.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_NOTSUPPORTED if the reference is not to a product, or E_UNEXPECTED if the SupportsExtensions property is the wrong type.</returns>
    STDMETHOD(GetSupportsExtensions)(
        _Out_ VARIANT_BOOL* pfSupportsExtensions
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupHelper;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Helper functions.
/// </summary>
/// <remarks>
/// You can query for this interface from the <see cref="SetupConfiguration"/> class.
/// </remarks>
struct DECLSPEC_UUID("42b21b78-6192-463e-87bf-d577838f1d5c") DECLSPEC_NOVTABLE ISetupHelper : public IUnknown
{
    /// <summary>
    /// Parses a dotted quad version string into a 64-bit unsigned integer.
    /// </summary>
    /// <param name="pwszVersion">The dotted quad version string to parse, e.g. 1.2.3.4.</param>
    /// <param name="pullVersion">A 64-bit unsigned integer representing the version. You can compare this to other versions.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_INVALIDARG if the version is not valid.</returns>
    STDMETHOD(ParseVersion)(
        _In_ LPCOLESTR pwszVersion,
        _Out_ PULONGLONG pullVersion
        ) = 0;

    /// <summary>
    /// Parses a dotted quad version string into a 64-bit unsigned integer.
    /// </summary>
    /// <param name="pwszVersionRange">The string containing 1 or 2 dotted quad version strings to parse, e.g. [1.0,) that means 1.0.0.0 or newer.</param>
    /// <param name="pullMinVersion">A 64-bit unsigned integer representing the minimum version, which may be 0. You can compare this to other versions.</param>
    /// <param name="pullMaxVersion">A 64-bit unsigned integer representing the maximum version, which may be MAXULONGLONG. You can compare this to other versions.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_INVALIDARG if the version range is not valid.</returns>
    STDMETHOD(ParseVersionRange)(
        _In_ LPCOLESTR pwszVersionRange,
        _Out_ PULONGLONG pullMinVersion,
        _Out_ PULONGLONG pullMaxVersion
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupErrorInfo;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Information about errors that occured during install of an instance.
/// </summary>
/// <remarks>
/// Objects may also implement <see cref="IErrorInfo"/> and <see cref="ISetupPropertyStore"/>.
/// </remarks>
struct DECLSPEC_UUID("2A2F3292-958E-4905-B36E-013BE84E27AB") DECLSPEC_NOVTABLE ISetupErrorInfo : public IUnknown
{
    /// <summary>
    /// Gets the HRESULT of the error.
    /// </summary>
    /// <param name="plHResult">The HRESULT of the error.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetErrorHResult)(
        _Out_ HRESULT* plHResult
    ) = 0;

    /// <summary>
    /// Gets the class name of the error (exception).
    /// </summary>
    /// <param name="pbstrClassName">The class name of the error (exception).</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetErrorClassName)(
        _Outptr_result_maybenull_ BSTR* pbstrClassName
    ) = 0;

    /// <summary>
    /// Gets the error message.
    /// </summary>
    /// <param name="pbstrMessage">The error message.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetErrorMessage)(
        _Outptr_result_maybenull_ BSTR* pbstrMessage
    ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupErrorState;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Information about the error state of an instance.
/// </summary>
struct DECLSPEC_UUID("46DCCD94-A287-476A-851E-DFBC2FFDBC20") DECLSPEC_NOVTABLE ISetupErrorState : public IUnknown
{
    /// <summary>
    /// Gets an array of failed package references.
    /// </summary>
    /// <param name="ppsaPackages">Pointer to an array of <see cref="ISetupFailedPackageReference"/>, if packages have failed.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetFailedPackages)(
        _Outptr_result_maybenull_ LPSAFEARRAY* ppsaFailedPackages
        ) = 0;

    /// <summary>
    /// Gets an array of skipped package references.
    /// </summary>
    /// <param name="ppsaPackages">Pointer to an array of <see cref="ISetupPackageReference"/>, if packages have been skipped.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetSkippedPackages)(
        _Outptr_result_maybenull_ LPSAFEARRAY* ppsaSkippedPackages
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupErrorState2;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Information about the error state of an instance.
/// </summary>
struct DECLSPEC_UUID("9871385B-CA69-48F2-BC1F-7A37CBF0B1EF") DECLSPEC_NOVTABLE ISetupErrorState2 : public ISetupErrorState
{
    /// <summary>
    /// Gets the path to the error log.
    /// </summary>
    /// <param name="pbstrChip">The path to the error log.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetErrorLogFilePath)(
        _Outptr_result_maybenull_ BSTR* pbstrErrorLogFilePath
        ) = 0;

    /// <summary>
    /// Gets the path to the main setup log.
    /// </summary>
    /// <param name="pbstrChip">The path to the main setup log.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetLogFilePath)(
        _Outptr_result_maybenull_ BSTR* pbstrLogFilePath
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupErrorState3;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Information about the error state of an instance.
/// </summary>
struct DECLSPEC_UUID("290019AD-28E2-46D5-9DE5-DA4B6BCF8057") DECLSPEC_NOVTABLE ISetupErrorState3 : public ISetupErrorState2
{
    /// <summary>
    /// Gets the runtime error that occured during install of an instance.
    /// </summary>
    /// <param name="pbstrChip">The runtime error that occured during install of an instance.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetRuntimeError)(
        _Outptr_result_maybenull_ ISetupErrorInfo** ppErrorInfo
        ) = 0;
};
#endif

EXTERN_C const IID IID_ISetupFailedPackageReference;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// A reference to a failed package.
/// </summary>
struct DECLSPEC_UUID("E73559CD-7003-4022-B134-27DC650B280F") DECLSPEC_NOVTABLE ISetupFailedPackageReference : public ISetupPackageReference
{
};

#endif

EXTERN_C const IID IID_ISetupFailedPackageReference2;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// A reference to a failed package.
/// </summary>
struct DECLSPEC_UUID("0FAD873E-E874-42E3-B268-4FE2F096B9CA") DECLSPEC_NOVTABLE ISetupFailedPackageReference2 : public ISetupFailedPackageReference
{
    /// <summary>
    /// Gets the path to the optional package log.
    /// </summary>
    /// <param name="pbstrId">The path to the optional package log.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetLogFilePath)(
        _Outptr_result_maybenull_ BSTR* pbstrLogFilePath
        ) = 0;

    /// <summary>
    /// Gets the description of the package failure.
    /// </summary>
    /// <param name="pbstrId">The description of the package failure.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetDescription)(
        _Outptr_result_maybenull_ BSTR* pbstrDescription
        ) = 0;

    /// <summary>
    /// Gets the signature to use for feedback reporting.
    /// </summary>
    /// <param name="pbstrId">The signature to use for feedback reporting.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetSignature)(
        _Outptr_result_maybenull_ BSTR* pbstrSignature
        ) = 0;

    /// <summary>
    ///  Gets the array of details for this package failure.
    /// </summary>
    /// <param name="ppsaDetails">Pointer to an array of details as BSTRs.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetDetails)(
        _Out_ LPSAFEARRAY* ppsaDetails
        ) = 0;

    /// <summary>
    /// Gets an array of packages affected by this package failure.
    /// </summary>
    /// <param name="ppsaPackages">Pointer to an array of <see cref="ISetupPackageReference"/> for packages affected by this package failure. This may be NULL.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetAffectedPackages)(
        _Out_ LPSAFEARRAY* ppsaAffectedPackages
        ) = 0;
};

#endif

EXTERN_C const IID IID_ISetupFailedPackageReference3;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// A reference to a failed package.
/// </summary>
struct DECLSPEC_UUID("EBC3AE68-AD15-44E8-8377-39DBF0316F6C") DECLSPEC_NOVTABLE ISetupFailedPackageReference3 : public ISetupFailedPackageReference2
{
    /// <summary>
    /// Gets the action attempted when the package failed.
    /// </summary>
    /// <param name="pbstrAction">The action, eg: Install, Download, etc.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetAction)(
        _Outptr_result_maybenull_ BSTR* pbstrAction
        ) = 0;

    /// <summary>
    /// Gets the return code of the failure.
    /// </summary>
    /// <param name="pbstrReturnCode">The return code.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetReturnCode)(
        _Outptr_result_maybenull_ BSTR* pbstrReturnCode
        ) = 0;
};

#endif

EXTERN_C const IID IID_ISetupPropertyStore;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Provides named properties.
/// </summary>
/// <remarks>
/// You can get this from an <see cref="ISetupInstance"/>, <see cref="ISetupPackageReference"/>, or derivative.
/// </remarks>
struct DECLSPEC_UUID("C601C175-A3BE-44BC-91F6-4568D230FC83") DECLSPEC_NOVTABLE ISetupPropertyStore : public IUnknown
{
    /// <summary>
    /// Gets an array of property names in this property store.
    /// </summary>
    /// <param name="ppsaNames">Pointer to an array of property names as BSTRs.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetNames)(
        _Out_ LPSAFEARRAY* ppsaNames
        ) = 0;

    /// <summary>
    /// Gets the value of a named property in this property store.
    /// </summary>
    /// <param name="pwszName">The name of the property to get.</param>
    /// <param name="pvtValue">The value of the property.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_NOTFOUND if the property is not defined or E_NOTSUPPORTED if the property type is not supported.</returns>
    STDMETHOD(GetValue)(
        _In_ LPCOLESTR pwszName,
        _Out_ LPVARIANT pvtValue
        ) = 0;
};

#endif

EXTERN_C const IID IID_ISetupLocalizedPropertyStore;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Provides localized named properties.
/// </summary>
/// <remarks>
/// You can get this from an <see cref="ISetupLocalizedProperties"/>.
/// </remarks>
struct DECLSPEC_UUID("5BB53126-E0D5-43DF-80F1-6B161E5C6F6C") DECLSPEC_NOVTABLE ISetupLocalizedPropertyStore : public IUnknown
{
    /// <summary>
    /// Gets an array of property names in this property store.
    /// </summary>
    /// <param name="lcid">The LCID for the property names.</param>
    /// <param name="ppsaNames">Pointer to an array of property names as BSTRs.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetNames)(
        _In_ LCID lcid,
        _Out_ LPSAFEARRAY* ppsaNames
        ) = 0;

    /// <summary>
    /// Gets the value of a named property in this property store.
    /// </summary>
    /// <param name="pwszName">The name of the property to get.</param>
    /// <param name="lcid">The LCID for the property.</param>
    /// <param name="pvtValue">The value of the property.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_NOTFOUND if the property is not defined or E_NOTSUPPORTED if the property type is not supported.</returns>
    STDMETHOD(GetValue)(
        _In_ LPCOLESTR pwszName,
        _In_ LCID lcid,
        _Out_ LPVARIANT pvtValue
        ) = 0;
};

#endif

EXTERN_C const IID IID_ISetupPolicy;

#if defined(__cplusplus) && !defined(CINTERFACE)
/// <summary>
/// Gets setup policy values.
/// </summary>
/// <remarks>
/// You can get this from an <see cref="ISetupConfiguration"/>.
/// </remarks>
struct DECLSPEC_UUID("E1DA4CBD-64C4-4C44-821D-98FAB64C4DA7") DECLSPEC_NOVTABLE ISetupPolicy : public IUnknown
{
    /// <summary>
    /// Gets the value of the SharedInstallationPath policy.
    /// </summary>
    /// <param name="pbstrSharedInstallationPath">The value of the SharedInstallationPath policy.</param>
    /// <returns>Standard HRESULT indicating success or failure.</returns>
    STDMETHOD(GetSharedInstallationPath)(
        _Out_ BSTR* pbstrSharedInstallationPath
        ) = 0;

    /// <summary>
    /// Gets the value of a named policy.
    /// </summary>
    /// <param name="pwszName">The name of the policy to get.</param>
    /// <param name="pvtValue">The value of the named policy.</param>
    /// <returns>Standard HRESULT indicating success or failure, including E_NOTSUPPORTED if the policy is not supported by this implementation.</returns>
    STDMETHOD(GetValue)(
        _In_ LPCOLESTR pwszName,
        _Out_ LPVARIANT pvtValue
        ) = 0;
};

#endif

// Class declarations
//
EXTERN_C const CLSID CLSID_SetupConfiguration;

#ifdef __cplusplus
/// <summary>
/// This class implements <see cref="ISetupConfiguration"/>, <see cref="ISetupConfiguration2"/>, and <see cref="ISetupHelper"/>.
/// </summary>
class DECLSPEC_UUID("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D") SetupConfiguration;
#endif

// Function declarations
//
/// <summary>
/// Gets an <see cref="ISetupConfiguration"/> that provides information about product instances installed on the machine.
/// </summary>
/// <param name="ppConfiguration">The <see cref="ISetupConfiguration"/> that provides information about product instances installed on the machine.</param>
/// <param name="pReserved">Reserved for future use.</param>
/// <returns>Standard HRESULT indicating success or failure.</returns>
STDMETHODIMP GetSetupConfiguration(
    _Out_ ISetupConfiguration** ppConfiguration,
    _Reserved_ LPVOID pReserved
);

#ifdef __cplusplus
}
#endif


text:
class PortfolioEntry < ActiveRecord::Base

  validates_presence_of :title

  # call to gems included in refinery.
  has_friendly_id :title, :use_slug => true
  acts_as_tree :order => "position"

  has_and_belongs_to_many :images

  def content
    self.body
  end

  def content=(value)
    self.body = value
  end

  def image_ids=(ids)
    self.images.clear

    ids.reject{|id| id.blank? }.each do |image_id|
      image = Image.find(image_id.to_i) rescue nil
      self.images << image unless image.nil?
    end
  end

  def indented_title
    "#{"--" * self.ancestors.size} #{self.title}".chomp
  end

end


text:
#include <X11/Xlibint.h>
#include <stdio.h>

#include "savagecontext.h"
#include "context.h"
#include "matrix.h"
#include "framebuffer.h"
#include "renderbuffer.h"
#include "simple_list.h"

#include "utils.h"

#include "extensions.h"

#include "swrast/swrast.h"
#include "swrast_setup/swrast_setup.h"
#include "tnl/tnl.h"
#include "vbo/vbo.h"

#include "tnl/t_pipeline.h"

#include "drivers/common/driverfuncs.h"

#include "savagedd.h"
#include "savagestate.h"
#include "savagetex.h"
#include "savagespan.h"
#include "savagetris.h"
#include "savageioctl.h"
#include "savage_bci.h"

#include "savage_dri.h"

#include "drirenderbuffer.h"
#include "texmem.h"

#define need_GL_ARB_multisample
#define need_GL_ARB_texture_compression
#define need_GL_ARB_vertex_buffer_object
#define need_GL_EXT_secondary_color
#include "extension_helper.h"

#include "xmlpool.h"

/* Driver-specific options
 */
#define SAVAGE_ENABLE_VDMA(def) \
DRI_CONF_OPT_BEGIN(enable_vdma,bool,def) \
	DRI_CONF_DESC(en,"Use DMA for vertex transfers") \
	DRI_CONF_DESC(de,"Benutze DMA für Vertextransfers") \
DRI_CONF_OPT_END
#define SAVAGE_ENABLE_FASTPATH(def) \
DRI_CONF_OPT_BEGIN(enable_fastpath,bool,def) \
	DRI_CONF_DESC(en,"Use fast path for unclipped primitives") \
	DRI_CONF_DESC(de,"Schneller Codepfad für ungeschnittene Polygone") \
DRI_CONF_OPT_END
#define SAVAGE_SYNC_FRAMES(def) \
DRI_CONF_OPT_BEGIN(sync_frames,bool,def) \
	DRI_CONF_DESC(en,"Synchronize with graphics hardware after each frame") \
	DRI_CONF_DESC(de,"Synchronisiere nach jedem Frame mit Grafikhardware") \
DRI_CONF_OPT_END

/* Configuration
 */
PUBLIC const char __driConfigOptions[] =
DRI_CONF_BEGIN
    DRI_CONF_SECTION_QUALITY
        DRI_CONF_TEXTURE_DEPTH(DRI_CONF_TEXTURE_DEPTH_FB)
        DRI_CONF_COLOR_REDUCTION(DRI_CONF_COLOR_REDUCTION_DITHER)
        DRI_CONF_FLOAT_DEPTH(false)
    DRI_CONF_SECTION_END
    DRI_CONF_SECTION_PERFORMANCE
        SAVAGE_ENABLE_VDMA(true)
        SAVAGE_ENABLE_FASTPATH(true)
        SAVAGE_SYNC_FRAMES(false)
        DRI_CONF_MAX_TEXTURE_UNITS(2,1,2)
    	DRI_CONF_TEXTURE_HEAPS(DRI_CONF_TEXTURE_HEAPS_ALL)
        DRI_CONF_FORCE_S3TC_ENABLE(false)
    DRI_CONF_SECTION_END
    DRI_CONF_SECTION_DEBUG
        DRI_CONF_NO_RAST(false)
    DRI_CONF_SECTION_END
DRI_CONF_END;
static const GLuint __driNConfigOptions = 10;

static const struct dri_debug_control debug_control[] =
{
    { "fall",  DEBUG_FALLBACKS },
    { "api",   DEBUG_VERBOSE_API },
    { "tex",   DEBUG_VERBOSE_TEX },
    { "verb",  DEBUG_VERBOSE_MSG },
    { "dma",   DEBUG_DMA },
    { "state", DEBUG_STATE },
    { NULL,    0 }
};
#ifndef SAVAGE_DEBUG
int SAVAGE_DEBUG = 0;
#endif

/*For time caculating test*/
#if defined(DEBUG_TIME) && DEBUG_TIME
struct timeval tv_s,tv_f;
unsigned long time_sum=0;
struct timeval tv_s1,tv_f1;
#endif

static const struct dri_extension card_extensions[] =
{
    { "GL_ARB_multisample",                GL_ARB_multisample_functions },
    { "GL_ARB_multitexture",               NULL },
    { "GL_ARB_texture_compression",        GL_ARB_texture_compression_functions },
    { "GL_ARB_vertex_buffer_object",       GL_ARB_vertex_buffer_object_functions },
    { "GL_EXT_stencil_wrap",               NULL },
    { "GL_EXT_texture_lod_bias",           NULL },
    { "GL_EXT_secondary_color",            GL_EXT_secondary_color_functions },
    { NULL,                                NULL }
};

static const struct dri_extension s4_extensions[] =
{
    { "GL_ARB_texture_env_add",            NULL },
    { "GL_ARB_texture_mirrored_repeat",    NULL },
    { NULL,                                NULL }
};

extern struct tnl_pipeline_stage _savage_texnorm_stage;
extern struct tnl_pipeline_stage _savage_render_stage;

static const struct tnl_pipeline_stage *savage_pipeline[] = {

   &_tnl_vertex_transform_stage,
   &_tnl_normal_transform_stage,
   &_tnl_lighting_stage,
   &_tnl_fog_coordinate_stage,
   &_tnl_texgen_stage,
   &_tnl_texture_transform_stage,
   &_savage_texnorm_stage,
   &_savage_render_stage,
   &_tnl_render_stage,
   0,
};

PUBLIC const __DRIextension *savageScreenExtensions[] = {
    &driCoreExtension.base,
    &driLegacyExtension.base,
    &driReadDrawableExtension,
};

static GLboolean
savageInitDriver(__DRIscreenPrivate *sPriv)
{
  savageScreenPrivate *savageScreen;
  SAVAGEDRIPtr         gDRIPriv = (SAVAGEDRIPtr)sPriv->pDevPriv;

   if (sPriv->devPrivSize != sizeof(SAVAGEDRIRec)) {
      fprintf(stderr,"\nERROR!  sizeof(SAVAGEDRIRec) does not match passed size from device driver\n");
      return GL_FALSE;
   }

   /* Allocate the private area */
   savageScreen = (savageScreenPrivate *)Xmalloc(sizeof(savageScreenPrivate));
   if (!savageScreen)
      return GL_FALSE;

   savageScreen->driScrnPriv = sPriv;
   sPriv->private = (void *)savageScreen;

   savageScreen->chipset=gDRIPriv->chipset;
   savageScreen->width=gDRIPriv->width;
   savageScreen->height=gDRIPriv->height;
   savageScreen->mem=gDRIPriv->mem;
   savageScreen->cpp=gDRIPriv->cpp;
   savageScreen->zpp=gDRIPriv->zpp;

   savageScreen->agpMode=gDRIPriv->agpMode;

   savageScreen->bufferSize=gDRIPriv->bufferSize;

   if (gDRIPriv->cpp == 4)
       savageScreen->frontFormat = DV_PF_8888;
   else
       savageScreen->frontFormat = DV_PF_565;
   savageScreen->frontOffset=gDRIPriv->frontOffset;
   savageScreen->backOffset = gDRIPriv->backOffset;
   savageScreen->depthOffset=gDRIPriv->depthOffset;

   savageScreen->textureOffset[SAVAGE_CARD_HEAP] =
                                   gDRIPriv->textureOffset;
   savageScreen->textureSize[SAVAGE_CARD_HEAP] =
                                   gDRIPriv->textureSize;
   savageScreen->logTextureGranularity[SAVAGE_CARD_HEAP] =
                                   gDRIPriv->logTextureGranularity;

   savageScreen->textureOffset[SAVAGE_AGP_HEAP] =
                                   gDRIPriv->agpTextureHandle;
   savageScreen->textureSize[SAVAGE_AGP_HEAP] =
                                   gDRIPriv->agpTextureSize;
   savageScreen->logTextureGranularity[SAVAGE_AGP_HEAP] =
                                   gDRIPriv->logAgpTextureGranularity;

   savageScreen->agpTextures.handle = gDRIPriv->agpTextureHandle;
   savageScreen->agpTextures.size   = gDRIPriv->agpTextureSize;
   if (gDRIPriv->agpTextureSize) {
       if (drmMap(sPriv->fd,
		  savageScreen->agpTextures.handle,
		  savageScreen->agpTextures.size,
		  (drmAddress *)&(savageScreen->agpTextures.map)) != 0) {
	   Xfree(savageScreen);
	   sPriv->private = NULL;
	   return GL_FALSE;
       }
   } else
       savageScreen->agpTextures.map = NULL;

   savageScreen->texVirtual[SAVAGE_CARD_HEAP] =
             (drmAddress)(((GLubyte *)sPriv->pFB)+gDRIPriv->textureOffset);
   savageScreen->texVirtual[SAVAGE_AGP_HEAP] =
                        (drmAddress)(savageScreen->agpTextures.map);

   savageScreen->aperture.handle = gDRIPriv->apertureHandle;
   savageScreen->aperture.size   = gDRIPriv->apertureSize;
   savageScreen->aperturePitch   = gDRIPriv->aperturePitch;
   if (drmMap(sPriv->fd,
	      savageScreen->aperture.handle,
	      savageScreen->aperture.size,
	      (drmAddress *)&savageScreen->aperture.map) != 0)
   {
      Xfree(savageScreen);
      sPriv->private = NULL;
      return GL_FALSE;
   }

   savageScreen->bufs = drmMapBufs(sPriv->fd);

   savageScreen->sarea_priv_offset = gDRIPriv->sarea_priv_offset;

   /* parse information in __driConfigOptions */
   driParseOptionInfo (&savageScreen->optionCache,
		       __driConfigOptions, __driNConfigOptions);

   sPriv->extensions = savageScreenExtensions;

#if 0
   savageDDFastPathInit();
   savageDDTrifuncInit();
   savageDDSetupInit();
#endif
   return GL_TRUE;
}

/* Accessed by dlsym from dri_mesa_init.c
 */
static void
savageDestroyScreen(__DRIscreenPrivate *sPriv)
{
   savageScreenPrivate *savageScreen = (savageScreenPrivate *)sPriv->private;

   if (savageScreen->bufs)
       drmUnmapBufs(savageScreen->bufs);

   /* free all option information */
   driDestroyOptionInfo (&savageScreen->optionCache);

   Xfree(savageScreen);
   sPriv->private = NULL;
}

static GLboolean
savageCreateContext( const __GLcontextModes *mesaVis,
		     __DRIcontextPrivate *driContextPriv,
		     void *sharedContextPrivate )
{
   GLcontext *ctx, *shareCtx;
   savageContextPtr imesa;
   __DRIscreenPrivate *sPriv = driContextPriv->driScreenPriv;
   struct dd_function_table functions;
   savageScreenPrivate *savageScreen = (savageScreenPrivate *)sPriv->private;
   drm_savage_sarea_t *saPriv=(drm_savage_sarea_t *)(((char*)sPriv->pSAREA)+
						 savageScreen->sarea_priv_offset);
   int textureSize[SAVAGE_NR_TEX_HEAPS];
   int i;
   imesa = (savageContextPtr)Xcalloc(sizeof(savageContext), 1);
   if (!imesa) {
      return GL_FALSE;
   }

   /* Init default driver functions then plug in savage-specific texture
    * functions that are needed as early as during context creation. */
   _mesa_init_driver_functions( &functions );
   savageDDInitTextureFuncs( &functions );

   /* Allocate the Mesa context */
   if (sharedContextPrivate)
      shareCtx = ((savageContextPtr) sharedContextPrivate)->glCtx;
   else
      shareCtx = NULL;
   ctx = _mesa_create_context(mesaVis, shareCtx, &functions, imesa);
   if (!ctx) {
      Xfree(imesa);
      return GL_FALSE;
   }
   driContextPriv->driverPrivate = imesa;

   imesa->cmdBuf.size = SAVAGE_CMDBUF_SIZE;
   imesa->cmdBuf.base = imesa->cmdBuf.write =
       malloc(SAVAGE_CMDBUF_SIZE * sizeof(drm_savage_cmd_header_t));
   if (!imesa->cmdBuf.base)
       return GL_FALSE;

   /* Parse configuration files */
   driParseConfigFiles (&imesa->optionCache, &savageScreen->optionCache,
                        sPriv->myNum, "savage");

   imesa->float_depth = driQueryOptionb(&imesa->optionCache, "float_depth") &&
       savageScreen->chipset >= S3_SAVAGE4;
   imesa->no_rast = driQueryOptionb(&imesa->optionCache, "no_rast");

#if 0
   ctx->Const.MinLineWidth = 1.0;
   ctx->Const.MinLineWidthAA = 1.0;
   ctx->Const.MaxLineWidth = 3.0;
   ctx->Const.MaxLineWidthAA = 3.0;
   ctx->Const.LineWidthGranularity = 1.0;
#endif

   /* Dri stuff
    */
   imesa->hHWContext = driContextPriv->hHWContext;
   imesa->driFd = sPriv->fd;
   imesa->driHwLock = &sPriv->pSAREA->lock;

   imesa->savageScreen = savageScreen;
   imesa->driScreen = sPriv;
   imesa->sarea = saPriv;
   imesa->glBuffer = NULL;

   /* DMA buffer */

   for(i=0;i<5;i++)
   {
       imesa->apertureBase[i] = (GLubyte *)savageScreen->aperture.map +
	   0x01000000 * i;
   }

   imesa->aperturePitch = savageScreen->aperturePitch;

   /* change texHeap initialize to support two kind of texture heap*/
   /* here is some parts of initialization, others in InitDriver() */

   (void) memset( imesa->textureHeaps, 0, sizeof( imesa->textureHeaps ) );
   make_empty_list( & imesa->swapped );

   textureSize[SAVAGE_CARD_HEAP] = savageScreen->textureSize[SAVAGE_CARD_HEAP];
   textureSize[SAVAGE_AGP_HEAP] = savageScreen->textureSize[SAVAGE_AGP_HEAP];
   imesa->lastTexHeap = savageScreen->texVirtual[SAVAGE_AGP_HEAP] ? 2 : 1;
   switch(driQueryOptioni (&imesa->optionCache, "texture_heaps")) {
   case DRI_CONF_TEXTURE_HEAPS_CARD: /* only use card memory, if available */
       if (textureSize[SAVAGE_CARD_HEAP])
	   imesa->lastTexHeap = 1;
       break;
   case DRI_CONF_TEXTURE_HEAPS_GART: /* only use gart memory, if available */
       if (imesa->lastTexHeap == 2 && textureSize[SAVAGE_AGP_HEAP])
	   textureSize[SAVAGE_CARD_HEAP] = 0;
       break;
   /*default: Nothing to do, use all available memory. */
   }

   for (i = 0; i < imesa->lastTexHeap; i++) {
       imesa->textureHeaps[i] = driCreateTextureHeap(
	   i, imesa,
	   textureSize[i],
	   11,					/* 2^11 = 2k alignment */
	   SAVAGE_NR_TEX_REGIONS,
	   (drmTextureRegionPtr)imesa->sarea->texList[i],
	    &imesa->sarea->texAge[i],
	    &imesa->swapped,
	    sizeof( savageTexObj ),
	    (destroy_texture_object_t *) savageDestroyTexObj );
       /* If textureSize[i] == 0 textureHeaps[i] is NULL. This can happen
	* if there is not enough card memory for a card texture heap. */
       if (imesa->textureHeaps[i])
	   driSetTextureSwapCounterLocation( imesa->textureHeaps[i],
					     & imesa->c_textureSwaps );
   }
   imesa->texture_depth = driQueryOptioni (&imesa->optionCache,
					   "texture_depth");
   if (imesa->texture_depth == DRI_CONF_TEXTURE_DEPTH_FB)
       imesa->texture_depth = ( savageScreen->cpp == 4 ) ?
	   DRI_CONF_TEXTURE_DEPTH_32 : DRI_CONF_TEXTURE_DEPTH_16;

   if (savageScreen->chipset >= S3_SAVAGE4)
       ctx->Const.MaxTextureUnits = 2;
   else
       ctx->Const.MaxTextureUnits = 1;
   if (driQueryOptioni(&imesa->optionCache, "texture_units") <
       ctx->Const.MaxTextureUnits)
       ctx->Const.MaxTextureUnits =
	   driQueryOptioni(&imesa->optionCache, "texture_units");
   ctx->Const.MaxTextureImageUnits = ctx->Const.MaxTextureUnits;
   ctx->Const.MaxTextureCoordUnits = ctx->Const.MaxTextureUnits;

   driCalculateMaxTextureLevels( imesa->textureHeaps,
				 imesa->lastTexHeap,
				 & ctx->Const,
				 4,
				 11, /* max 2D texture size is 2048x2048 */
				 0,  /* 3D textures unsupported. */
				 0,  /* cube textures unsupported. */
				 0,  /* texture rectangles unsupported. */
				 12,
				 GL_FALSE,
				 0 );
   if (ctx->Const.MaxTextureLevels <= 6) { /*spec requires at least 64x64*/
       __driUtilMessage("Not enough texture memory. "
			"Falling back to indirect rendering.");
       Xfree(imesa);
       return GL_FALSE;
   }

   imesa->hw_stencil = mesaVis->stencilBits && mesaVis->depthBits == 24;
   imesa->depth_scale = (imesa->savageScreen->zpp == 2) ?
       (1.0F/0xffff):(1.0F/0xffffff);

   imesa->bufferSize = savageScreen->bufferSize;
   imesa->dmaVtxBuf.total = 0;
   imesa->dmaVtxBuf.used = 0;
   imesa->dmaVtxBuf.flushed = 0;

   imesa->clientVtxBuf.total = imesa->bufferSize / 4;
   imesa->clientVtxBuf.used = 0;
   imesa->clientVtxBuf.flushed = 0;
   imesa->clientVtxBuf.buf = (u_int32_t *)malloc(imesa->bufferSize);

   imesa->vtxBuf = &imesa->clientVtxBuf;

   imesa->firstElt = -1;

   /* Uninitialized vertex format. Force setting the vertex state in
    * savageRenderStart.
    */
   imesa->vertex_size = 0;

   /* Utah stuff
    */
   imesa->new_state = ~0;
   imesa->new_gl_state = ~0;
   imesa->RenderIndex = ~0;
   imesa->dirty = ~0;
   imesa->lostContext = GL_TRUE;
   imesa->CurrentTexObj[0] = 0;
   imesa->CurrentTexObj[1] = 0;

   /* Initialize the software rasterizer and helper modules.
    */
   _swrast_CreateContext( ctx );
   _vbo_CreateContext( ctx );
   _tnl_CreateContext( ctx );

   _swsetup_CreateContext( ctx );

   /* Install the customized pipeline:
    */
   _tnl_destroy_pipeline( ctx );
   _tnl_install_pipeline( ctx, savage_pipeline );

   imesa->enable_fastpath = driQueryOptionb(&imesa->optionCache,
					    "enable_fastpath");
   /* DRM versions before 2.1.3 would only render triangle lists. ELTS
    * support was added in 2.2.0. */
   if (imesa->enable_fastpath && sPriv->drm_version.minor < 2) {
      fprintf (stderr,
	       "*** Disabling fast path because your DRM version is buggy "
	       "or doesn't\n*** support ELTS. You need at least Savage DRM "
	       "version 2.2.\n");
      imesa->enable_fastpath = GL_FALSE;
   }

   if (!savageScreen->bufs || savageScreen->chipset == S3_SUPERSAVAGE)
       imesa->enable_vdma = GL_FALSE;
   else
       imesa->enable_vdma = driQueryOptionb(&imesa->optionCache, "enable_vdma");

   imesa->sync_frames = driQueryOptionb(&imesa->optionCache, "sync_frames");

   /* Configure swrast to match hardware characteristics:
    */
   _tnl_allow_pixel_fog( ctx, GL_FALSE );
   _tnl_allow_vertex_fog( ctx, GL_TRUE );
   _swrast_allow_pixel_fog( ctx, GL_FALSE );
   _swrast_allow_vertex_fog( ctx, GL_TRUE );

   ctx->DriverCtx = (void *) imesa;
   imesa->glCtx = ctx;

#ifndef SAVAGE_DEBUG
   SAVAGE_DEBUG = driParseDebugString( getenv( "SAVAGE_DEBUG" ),
				       debug_control );
#endif

   driInitExtensions( ctx, card_extensions, GL_TRUE );
   if (savageScreen->chipset >= S3_SAVAGE4)
       driInitExtensions( ctx, s4_extensions, GL_FALSE );
   if (ctx->Mesa_DXTn ||
       driQueryOptionb (&imesa->optionCache, "force_s3tc_enable")) {
       _mesa_enable_extension( ctx, "GL_S3_s3tc" );
       if (savageScreen->chipset >= S3_SAVAGE4)
	   /* This extension needs DXT3 and DTX5 support in hardware.
	    * Not available on Savage3D/MX/IX. */
	   _mesa_enable_extension( ctx, "GL_EXT_texture_compression_s3tc" );
   }

   savageDDInitStateFuncs( ctx );
   savageDDInitSpanFuncs( ctx );
   savageDDInitDriverFuncs( ctx );
   savageDDInitIoctlFuncs( ctx );
   savageInitTriFuncs( ctx );

   savageDDInitState( imesa );

   driContextPriv->driverPrivate = (void *) imesa;

   return GL_TRUE;
}

static void
savageDestroyContext(__DRIcontextPrivate *driContextPriv)
{
   savageContextPtr imesa = (savageContextPtr) driContextPriv->driverPrivate;
   GLuint i;

   assert (imesa); /* should never be NULL */
   if (imesa) {
      savageFlushVertices(imesa);
      savageReleaseIndexedVerts(imesa);
      savageFlushCmdBuf(imesa, GL_TRUE); /* release DMA buffer */
      WAIT_IDLE_EMPTY(imesa);

      for (i = 0; i < imesa->lastTexHeap; i++)
	 driDestroyTextureHeap(imesa->textureHeaps[i]);

      free(imesa->cmdBuf.base);
      free(imesa->clientVtxBuf.buf);

      _swsetup_DestroyContext(imesa->glCtx );
      _tnl_DestroyContext( imesa->glCtx );
      _vbo_DestroyContext( imesa->glCtx );
      _swrast_DestroyContext( imesa->glCtx );

      /* free the Mesa context */
      imesa->glCtx->DriverCtx = NULL;
      _mesa_destroy_context(imesa->glCtx);

      /* no longer use vertex_dma_buf*/
      Xfree(imesa);
   }
}

static GLboolean
savageCreateBuffer( __DRIscreenPrivate *driScrnPriv,
		    __DRIdrawablePrivate *driDrawPriv,
		    const __GLcontextModes *mesaVis,
		    GLboolean isPixmap)
{
   savageScreenPrivate *screen = (savageScreenPrivate *) driScrnPriv->private;

   if (isPixmap) {
      return GL_FALSE; /* not implemented */
   }
   else {
      GLboolean swStencil = mesaVis->stencilBits > 0 && mesaVis->depthBits != 24;
      struct gl_framebuffer *fb = _mesa_create_framebuffer(mesaVis);
      /*
       * XXX: this value needs to be set according to the config file
       * setting.  But we don't get that until we create a rendering
       * context!!!!
       */
      GLboolean float_depth = GL_FALSE;

      {
         driRenderbuffer *frontRb
            = driNewRenderbuffer(GL_RGBA,
                                 (GLubyte *) screen->aperture.map
                                 + 0x01000000 * TARGET_FRONT,
                                 screen->cpp,
                                 screen->frontOffset, screen->aperturePitch,
                                 driDrawPriv);
         savageSetSpanFunctions(frontRb, mesaVis, float_depth);
         assert(frontRb->Base.Data);
         _mesa_add_renderbuffer(fb, BUFFER_FRONT_LEFT, &frontRb->Base);
      }

      if (mesaVis->doubleBufferMode) {
         driRenderbuffer *backRb
            = driNewRenderbuffer(GL_RGBA,
                                 (GLubyte *) screen->aperture.map
                                 + 0x01000000 * TARGET_BACK,
                                 screen->cpp,
                                 screen->backOffset, screen->aperturePitch,
                                 driDrawPriv);
         savageSetSpanFunctions(backRb, mesaVis, float_depth);
         assert(backRb->Base.Data);
         _mesa_add_renderbuffer(fb, BUFFER_BACK_LEFT, &backRb->Base);
      }

      if (mesaVis->depthBits == 16) {
         driRenderbuffer *depthRb
            = driNewRenderbuffer(GL_DEPTH_COMPONENT16,
                                 (GLubyte *) screen->aperture.map
                                 + 0x01000000 * TARGET_DEPTH,
                                 screen->zpp,
                                 screen->depthOffset, screen->aperturePitch,
                                 driDrawPriv);
         savageSetSpanFunctions(depthRb, mesaVis, float_depth);
         _mesa_add_renderbuffer(fb, BUFFER_DEPTH, &depthRb->Base);
      }
      else if (mesaVis->depthBits == 24) {
         driRenderbuffer *depthRb
            = driNewRenderbuffer(GL_DEPTH_COMPONENT24,
                                 (GLubyte *) screen->aperture.map
                                 + 0x01000000 * TARGET_DEPTH,
                                 screen->zpp,
                                 screen->depthOffset, screen->aperturePitch,
                                 driDrawPriv);
         savageSetSpanFunctions(depthRb, mesaVis, float_depth);
         _mesa_add_renderbuffer(fb, BUFFER_DEPTH, &depthRb->Base);
      }

      if (mesaVis->stencilBits > 0 && !swStencil) {
         driRenderbuffer *stencilRb
            = driNewRenderbuffer(GL_STENCIL_INDEX8_EXT,
                                 (GLubyte *) screen->aperture.map
                                 + 0x01000000 * TARGET_DEPTH,
                                 screen->zpp,
                                 screen->depthOffset, screen->aperturePitch,
                                 driDrawPriv);
         savageSetSpanFunctions(stencilRb, mesaVis, float_depth);
         _mesa_add_renderbuffer(fb, BUFFER_STENCIL, &stencilRb->Base);
      }

      _mesa_add_soft_renderbuffers(fb,
                                   GL_FALSE, /* color */
                                   GL_FALSE, /* depth */
                                   swStencil,
                                   mesaVis->accumRedBits > 0,
                                   GL_FALSE, /* alpha */
                                   GL_FALSE /* aux */);
      driDrawPriv->driverPrivate = (void *) fb;

      return (driDrawPriv->driverPrivate != NULL);
   }
}

static void
savageDestroyBuffer(__DRIdrawablePrivate *driDrawPriv)
{
   _mesa_unreference_framebuffer((GLframebuffer **)(&(driDrawPriv->driverPrivate)));
}

#if 0
void XMesaSwapBuffers(__DRIdrawablePrivate *driDrawPriv)
{
   /* XXX should do swap according to the buffer, not the context! */
   savageContextPtr imesa = savageCtx;

   FLUSH_VB( imesa->glCtx, "swap buffers" );
   savageSwapBuffers(imesa);
}
#endif

void savageXMesaSetClipRects(savageContextPtr imesa)
{
   __DRIdrawablePrivate *dPriv = imesa->driDrawable;

   if ((dPriv->numBackClipRects == 0)
       || (imesa->glCtx->DrawBuffer->_ColorDrawBufferIndexes[0] == BUFFER_FRONT_LEFT)) {
      imesa->numClipRects = dPriv->numClipRects;
      imesa->pClipRects = dPriv->pClipRects;
      imesa->drawX = dPriv->x;
      imesa->drawY = dPriv->y;
   } else {
      imesa->numClipRects = dPriv->numBackClipRects;
      imesa->pClipRects = dPriv->pBackClipRects;
      imesa->drawX = dPriv->backX;
      imesa->drawY = dPriv->backY;
   }

   savageCalcViewport( imesa->glCtx );
}

static void savageXMesaWindowMoved( savageContextPtr imesa )
{
   __DRIdrawablePrivate *const drawable = imesa->driDrawable;
   __DRIdrawablePrivate *const readable = imesa->driReadable;

   if (0)
      fprintf(stderr, "savageXMesaWindowMoved\n\n");

   savageXMesaSetClipRects(imesa);

   driUpdateFramebufferSize(imesa->glCtx, drawable);
   if (drawable != readable) {
      driUpdateFramebufferSize(imesa->glCtx, readable);
   }
}

static GLboolean
savageUnbindContext(__DRIcontextPrivate *driContextPriv)
{
   savageContextPtr savage = (savageContextPtr) driContextPriv->driverPrivate;
   if (savage)
      savage->dirty = ~0;

   return GL_TRUE;
}

#if 0
static GLboolean
savageOpenFullScreen(__DRIcontextPrivate *driContextPriv)
{

    if (driContextPriv) {
      savageContextPtr imesa = (savageContextPtr) driContextPriv->driverPrivate;
      imesa->IsFullScreen = GL_TRUE;
      imesa->backup_frontOffset = imesa->savageScreen->frontOffset;
      imesa->backup_backOffset = imesa->savageScreen->backOffset;
      imesa->backup_frontBitmapDesc = imesa->savageScreen->frontBitmapDesc;
      imesa->savageScreen->frontBitmapDesc = imesa->savageScreen->backBitmapDesc;
      imesa->toggle = TARGET_BACK;
   }

    return GL_TRUE;
}

static GLboolean
savageCloseFullScreen(__DRIcontextPrivate *driContextPriv)
{

    if (driContextPriv) {
      savageContextPtr imesa = (savageContextPtr) driContextPriv->driverPrivate;
      WAIT_IDLE_EMPTY(imesa);
      imesa->IsFullScreen = GL_FALSE;
      imesa->savageScreen->frontOffset = imesa->backup_frontOffset;
      imesa->savageScreen->backOffset = imesa->backup_backOffset;
      imesa->savageScreen->frontBitmapDesc = imesa->backup_frontBitmapDesc;
   }
    return GL_TRUE;
}
#endif

static GLboolean
savageMakeCurrent(__DRIcontextPrivate *driContextPriv,
		  __DRIdrawablePrivate *driDrawPriv,
		  __DRIdrawablePrivate *driReadPriv)
{
   if (driContextPriv) {
      savageContextPtr imesa
         = (savageContextPtr) driContextPriv->driverPrivate;
      struct gl_framebuffer *drawBuffer
         = (GLframebuffer *) driDrawPriv->driverPrivate;
      struct gl_framebuffer *readBuffer
         = (GLframebuffer *) driReadPriv->driverPrivate;
      driRenderbuffer *frontRb = (driRenderbuffer *)
         drawBuffer->Attachment[BUFFER_FRONT_LEFT].Renderbuffer;
      driRenderbuffer *backRb = (driRenderbuffer *)
         drawBuffer->Attachment[BUFFER_BACK_LEFT].Renderbuffer;

      assert(frontRb->Base.Data);
      if (imesa->glCtx->Visual.doubleBufferMode) {
         assert(backRb->Base.Data);
      }

      imesa->driReadable = driReadPriv;
      imesa->driDrawable = driDrawPriv;
      imesa->dirty = ~0;

      _mesa_make_current(imesa->glCtx, drawBuffer, readBuffer);

      savageXMesaWindowMoved( imesa );
   }
   else
   {
      _mesa_make_current(NULL, NULL, NULL);
   }
   return GL_TRUE;
}

void savageGetLock( savageContextPtr imesa, GLuint flags )
{
   __DRIdrawablePrivate *const drawable = imesa->driDrawable;
   __DRIdrawablePrivate *const readable = imesa->driReadable;
   __DRIscreenPrivate *sPriv = imesa->driScreen;
   drm_savage_sarea_t *sarea = imesa->sarea;
   int me = imesa->hHWContext;
   int stamp = drawable->lastStamp;
   int heap;
   unsigned int timestamp = 0;

   /* We know there has been contention.
    */
   drmGetLock(imesa->driFd, imesa->hHWContext, flags);

   /* Note contention for throttling hint
    */
   imesa->any_contend = 1;

   /* If the window moved, may need to set a new cliprect now.
    *
    * NOTE: This releases and regains the hw lock, so all state
    * checking must be done *after* this call:
    */
   DRI_VALIDATE_DRAWABLE_INFO(sPriv, drawable);
   if (drawable != readable) {
      DRI_VALIDATE_DRAWABLE_INFO(sPriv, readable);
   }

   /* If we lost context, need to dump all registers to hardware.
    * Note that we don't care about 2d contexts, even if they perform
    * accelerated commands, so the DRI locking in the X server is even
    * more broken than usual.
    */
   if (sarea->ctxOwner != me) {
      imesa->dirty |= (SAVAGE_UPLOAD_LOCAL |
		       SAVAGE_UPLOAD_GLOBAL |
		       SAVAGE_UPLOAD_FOGTBL |
		       SAVAGE_UPLOAD_TEX0 |
		       SAVAGE_UPLOAD_TEX1 |
		       SAVAGE_UPLOAD_TEXGLOBAL);
      imesa->lostContext = GL_TRUE;
      sarea->ctxOwner = me;
   }

   for (heap = 0; heap < imesa->lastTexHeap; ++heap) {
      /* If a heap was changed, update its timestamp. Do this before
       * DRI_AGE_TEXTURES updates the local_age. */
      if (imesa->textureHeaps[heap] &&
	  imesa->textureHeaps[heap]->global_age[0] >
	  imesa->textureHeaps[heap]->local_age) {
	 if (timestamp == 0)
	    timestamp = savageEmitEventLocked(imesa, 0);
	 imesa->textureHeaps[heap]->timestamp = timestamp;
      }
      DRI_AGE_TEXTURES( imesa->textureHeaps[heap] );
   }

   if (drawable->lastStamp != stamp) {
      driUpdateFramebufferSize(imesa->glCtx, drawable);
      savageXMesaWindowMoved( imesa );
   }
}

static const  __DRIconfig **
savageFillInModes( __DRIscreenPrivate *psp,
		   unsigned pixel_bits, unsigned depth_bits,
		   unsigned stencil_bits, GLboolean have_back_buffer )
{
    __DRIconfig **configs;
    __GLcontextModes * m;
    unsigned depth_buffer_factor;
    unsigned back_buffer_factor;
    GLenum fb_format;
    GLenum fb_type;
    int i;

    /* Right now GLX_SWAP_COPY_OML isn't supported, but it would be easy
     * enough to add support.  Basically, if a context is created with an
     * fbconfig where the swap method is GLX_SWAP_COPY_OML, pageflipping
     * will never be used.
     *
     * FK: What about drivers that don't use page flipping? Could they
     * just expose GLX_SWAP_COPY_OML?
     */
    static const GLenum back_buffer_modes[] = {
	GLX_NONE, GLX_SWAP_UNDEFINED_OML /*, GLX_SWAP_COPY_OML */
    };

    u_int8_t depth_bits_array[2];
    u_int8_t stencil_bits_array[2];

    depth_bits_array[0] = depth_bits;
    depth_bits_array[1] = depth_bits;

    /* Just like with the accumulation buffer, always provide some modes
     * with a stencil buffer.  It will be a sw fallback, but some apps won't
     * care about that.
     */
    stencil_bits_array[0] = 0;
    stencil_bits_array[1] = (stencil_bits == 0) ? 8 : stencil_bits;

    depth_buffer_factor = ((depth_bits != 0) || (stencil_bits != 0)) ? 2 : 1;
    back_buffer_factor  = (have_back_buffer) ? 2 : 1;

    if ( pixel_bits == 16 ) {
        fb_format = GL_RGB;
        fb_type = GL_UNSIGNED_SHORT_5_6_5;
    }
    else {
        fb_format = GL_BGR;
        fb_type = GL_UNSIGNED_INT_8_8_8_8_REV;
    }

    configs = driCreateConfigs(fb_format, fb_type,
			       depth_bits_array, stencil_bits_array,
			       depth_buffer_factor,
			       back_buffer_modes, back_buffer_factor);
    if (configs == NULL) {
	fprintf( stderr, "[%s:%u] Error creating FBConfig!\n",
		 __func__, __LINE__ );
	return NULL;
    }

    /* Mark the visual as slow if there are "fake" stencil bits.
     */
    for (i = 0; configs[i]; i++) {
	m = &configs[i]->modes;
	if ((m->stencilBits != 0) && (m->stencilBits != stencil_bits)) {
	    m->visualRating = GLX_SLOW_CONFIG;
	}
    }

    return (const __DRIconfig **) configs;
}

/**
 * This is the driver specific part of the createNewScreen entry point.
 *
 * \todo maybe fold this into intelInitDriver
 *
 * \return the __GLcontextModes supported by this driver
 */
static const __DRIconfig **
savageInitScreen(__DRIscreenPrivate *psp)
{
   static const __DRIversion ddx_expected = { 2, 0, 0 };
   static const __DRIversion dri_expected = { 4, 0, 0 };
   static const __DRIversion drm_expected = { 2, 1, 0 };
   SAVAGEDRIPtr dri_priv = (SAVAGEDRIPtr)psp->pDevPriv;

   if ( ! driCheckDriDdxDrmVersions2( "Savage",
				      &psp->dri_version, & dri_expected,
				      &psp->ddx_version, & ddx_expected,
				      &psp->drm_version, & drm_expected ) )
      return NULL;

   /* Calling driInitExtensions here, with a NULL context pointer,
    * does not actually enable the extensions.  It just makes sure
    * that all the dispatch offsets for all the extensions that
    * *might* be enables are known.  This is needed because the
    * dispatch offsets need to be known when _mesa_context_create is
    * called, but we can't enable the extensions until we have a
    * context pointer.
    *
    * Hello chicken.  Hello egg.  How are you two today?
    */
   driInitExtensions( NULL, card_extensions, GL_FALSE );

   if (!savageInitDriver(psp))
       return NULL;

   return savageFillInModes( psp,
			     dri_priv->cpp*8,
			     (dri_priv->cpp == 2) ? 16 : 24,
			     (dri_priv->cpp == 2) ? 0  : 8,
			     (dri_priv->backOffset != dri_priv->depthOffset) );
}

const struct __DriverAPIRec driDriverAPI = {
   savageInitScreen,
   savageDestroyScreen,
   savageCreateContext,
   savageDestroyContext,
   savageCreateBuffer,
   savageDestroyBuffer,
   savageSwapBuffers,
   savageMakeCurrent,
   savageUnbindContext
};


text:
require 'base64'

class Cookie
  attr_reader :hash

  def initialize(cookie_string)
    @hash = process(cookie_string)
  end

  def process(cookie_string)
    normal_cookie_hash = interpret_cookie_string(cookie_string)
    if normal_cookie_hash["FirstServerCookie"]
      our_actual_cookie = decrypt_cookie(normal_cookie_hash["FirstServerCookie"])
      final_cookie_hash = interpret_cookie_string(our_actual_cookie)
    else
      # construct brand new cookie_hash that will unify the prexisting cookie variables into a more 'secure' cookie, with a whitelist of variables
      final_cookie_hash = Hash.new
      ["count", "user_id", "user visits"].each do |key|
        final_cookie_hash[key] = normal_cookie_hash[key]
      end
      final_cookie_hash
    end
  end

  def headers
    string = ""
    last_key = hash.keys.last
    hash.each do |key, value|
      if key == last_key
        string << "#{key}=#{value}"
      else
        string << "#{key}=#{value}; "
      end
    end
    "Set-Cookie: FirstServerCookie=#{Base64.encode64(CIPHER.encrypt(string)).gsub("\n", ' ').squeeze(' ')};"
  end

  private

  def interpret_cookie_string(cookie_string)
    hash = Hash.new
    cookie_string.split("; ").each do |key_value_pair|
      array = key_value_pair.split("=")
      key = array[0]
      value = array[1]
      # integer regex - http://stackoverflow.com/a/1235990/4765379
      if (/\A[-+]?\d+\z/ === value)
        value = value.to_i
      end
      hash["#{key}"] = value
    end
    hash
  end

  def decrypt_cookie(cookie_string)
    base64_cookie = Base64.decode64(cookie_string)
    CIPHER.decrypt(base64_cookie)
  rescue
    "count=0"
  end

end


text:
require 'set'

module Loofah
  module Elements
    STRICT_BLOCK_LEVEL_HTML4 = Set.new %w[
      address
      blockquote
      center
      dir
      div
      dl
      fieldset
      form
      h1
      h2
      h3
      h4
      h5
      h6
      hr
      isindex
      menu
      noframes
      noscript
      ol
      p
      pre
      table
      ul
    ]

    # https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
    STRICT_BLOCK_LEVEL_HTML5 = Set.new %w[
      address
      article
      aside
      blockquote
      canvas
      dd
      div
      dl
      dt
      fieldset
      figcaption
      figure
      footer
      form
      h1
      h2
      h3
      h4
      h5
      h6
      header
      hgroup
      hr
      li
      main
      nav
      noscript
      ol
      output
      p
      pre
      section
      table
      tfoot
      ul
      video
    ]

    STRICT_BLOCK_LEVEL = STRICT_BLOCK_LEVEL_HTML4 + STRICT_BLOCK_LEVEL_HTML5

    # The following elements may also be considered block-level
    # elements since they may contain block-level elements
    LOOSE_BLOCK_LEVEL = Set.new %w[dd
      dt
      frameset
      li
      tbody
      td
      tfoot
      th
      thead
      tr
    ]

    BLOCK_LEVEL = STRICT_BLOCK_LEVEL + LOOSE_BLOCK_LEVEL
  end

  ::Loofah::MetaHelpers.add_downcased_set_members_to_all_set_constants ::Loofah::Elements
end