text:
/**************************/
// Localisation strings and methods
// Used for text labels and buttons withing the UI

// overridden by top level pages
function localisationComplete()
{

}

var Localisation={

    CURRENT_LANGUAGE:{name:"", shortcode:"", strings:{}},
	AVAILABLE_LANGUAGES:[{name:"", shortcode:"", strings:{}}],

	// inits the Localisation by retrieving the JSON set
	// or loading it from the local db
	init:function(url, alreadyHave, forceRefresh, inAppFile)
	{

		if(alreadyHave)
		{
			// either we have been here before and we have the data
			if (PrecAppUtils.isNotNull(window.localStorage.getItem('LOCALISATION_JSON')))
			{
				if (!forceRefresh)
				{
					console.log("Use localisation local storage file");
                    var data = window.localStorage.getItem('LOCALISATION_JSON');
					Localisation.parseLocalisationJson(data);
					return;
				}
			}
			else // or not
			{

				// ..... continue

			}
		}

		//!important to purge this in order to prevent multiple online Localisation calls
		if (forceRefresh)
		{
			window.localStorage.setItem('FORCE_REFRESH', "false");
		}

		// connection check, because we can't fetch unless we are online
		var userIsOnline = PrecAppUtils.verifyConnection(false);
		if (!userIsOnline && !inAppFile)
		{
			var data = window.localStorage.getItem('LOCALISATION_JSON');
			Localisation.parseLocalisationJson(data);
			return;
		}

		if (inAppFile || url=="") //if we want to force it or if no url was specified
		{
			url = "data/in-app-localisation.json";

		}

		Localisation.AVAILABLE_LANGUAGES=[];
		$.ajax(
			{
				url: url,
				dataType: 'text',
				success: function(data)
				{

                    console.log("Use localisation file:"+url);
                    Localisation.parseLocalisationJson(data);
                    window.localStorage.setItem('LOCALISATION_JSON',data);
				},
				error: function(data)
				{

				}
			}
		);
	},

	parseLocalisationJson:function(data){

		var parsedLocalisationData = $.parseJSON(data);
		for (n in parsedLocalisationData)
		{
			var obj = parsedLocalisationData[n];

			var name = obj['Name'];
			var shortcode = (obj['LanguageCode']);

			var obj = obj['Strings'];
			var strings = [];

			// assign the name value pairs
			for (i in obj)
			{
				var newObj={};

				newObj.name = obj[i].Name;
				newObj.value = obj[i].Value;

				strings.push(newObj);
			}

			Localisation.AVAILABLE_LANGUAGES.push({name:name, shortcode:shortcode, strings:strings});
		}

		var defaultLanguage = "EN";
		Localisation.setDefaultLanguage(defaultLanguage);
	},

	setDefaultLanguage:function(shortcode)
	{
		// check to see if the user has a language preference already
		var userLang = window.localStorage.getItem('languageShortcode');

		if (PrecAppUtils.isNull(userLang))
		{
			window.localStorage.setItem('languageShortcode', shortcode);
		}
		else
		{
			shortcode = window.localStorage.getItem('languageShortcode');

			// #1 error checking
			if (PrecAppUtils.isNull(shortcode))
				shortcode="EN";

			// #2 if the user has set Kilngon as a language , but Klingon not available for this event!!
			var langFoundInSet = false; // prove true

			for (var i=0;i<Localisation.AVAILABLE_LANGUAGES.length;i++)
			{
				var langToGet = Localisation.AVAILABLE_LANGUAGES[i].shortcode.toUpperCase();

				if (langToGet==shortcode.toUpperCase())
					langFoundInSet=true;
			}

			if (!langFoundInSet)
				shortcode="EN";
		}

		Localisation.setLanguageFromShortcode(shortcode);
		localisationComplete();
	},

	// sets the current language according to user options
	setLanguageFromShortcode:function(shortcode)
	{
		window.localStorage.setItem('languageShortcode', shortcode);

		for (var i=0;i<Localisation.AVAILABLE_LANGUAGES.length;i++)
		{
			var currentShortcode = Localisation.AVAILABLE_LANGUAGES[i].shortcode;

			if (shortcode.toUpperCase()==currentShortcode.toUpperCase())
			{
				Localisation.CURRENT_LANGUAGE=Localisation.AVAILABLE_LANGUAGES[i];
				return;
			}
		}

		//default to English in case for some reason there is no match
		Localisation.CURRENT_LANGUAGE = Localisation.AVAILABLE_LANGUAGES[0];
	},

	setCurrentLanguage:function(lang)
	{
		Localisation.CURRENT_LANGUAGE=lang;
	},

	getShortcode:function()
	{
		return Localisation.CURRENT_LANGUAGE.shortcode.toUpperCase();
	},

	// UI label gets
	getStr:function(label, forceEnglish)
	{
		label = label.toUpperCase();

		if (forceEnglish) // we can force it to search for English strings from the UI
		{
			var englishLanguageSet = [];

			for (var i=0;i<Localisation.AVAILABLE_LANGUAGES.length;i++)
			{
				var currentShortcode = Localisation.AVAILABLE_LANGUAGES[i].shortcode;

				if (currentShortcode.toUpperCase()=="EN")
				{
					englishLanguageSet=Localisation.AVAILABLE_LANGUAGES[i];
				}
			}

			for (var i = 0;i<englishLanguageSet.strings.length;i++)
			{
				var name = englishLanguageSet.strings[i].name;

				if (label==name.toUpperCase())
				{
					var value = englishLanguageSet.strings[i].value;
					return value;
				}
			}
		}
		else
		{
			for (var i = 0;i<Localisation.CURRENT_LANGUAGE.strings.length;i++)
			{
				var name = Localisation.CURRENT_LANGUAGE.strings[i].name;

				if (label==name.toUpperCase())
				{
					var value = Localisation.CURRENT_LANGUAGE.strings[i].value;
					return value;
				}
			}
		}

		// default will return the original Localisation search string as uppercase
		return label;
	}
}


text:
namespace xcite.tdn {
    /// <summary> Describes elementary TDN element types. </summary>
    public enum ETdnDataType {
        /// <summary> The data type is not known. </summary>
        Unknown,

        /// <summary> 64 bit integer (long) </summary>
        Int64,

        /// <summary> Double </summary>
        Double,

        /// <summary> Decimal </summary>
        Decimal,

        /// <summary> String </summary>
        String,

        /// <summary> Boolean </summary>
        Bool,

        /// <summary> NULL </summary>
        Null
    }
}

redpajama_set_name: RedPajamaGithub


text: [link to site](http://jezgarcia.github.io/Portfolio)


text:
<?php
/**
 * Contains \garethp\ews\API\Enumeration\FlagStatusType.
 */

namespace garethp\ews\API\Enumeration;

use garethp\ews\API\Enumeration;

/**
 * Class representing FlagStatusType
 *
 *
 * XSD Type: FlagStatusType
 */
class FlagStatusType extends Enumeration
{

    const COMPLETE = 'Complete';

    const FLAGGED = 'Flagged';

    const NOT_FLAGGED = 'NotFlagged';
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface MWMNetworkPolicy (UI)

- (void)callOnlineApi:(MWMBoolBlock)onlineCall;
- (void)callOnlineApi:(MWMBoolBlock)onlineCall forceAskPermission:(BOOL)askPermission;

@end

NS_ASSUME_NONNULL_END


text:
namespace sandbox {
using base::win::StartupInformation;

// Wraps base::win::StartupInformation and allows some querying of what is
// set. This is specialized for the dance between
// BrokerServices::SpawnTarget() and TargetProcess::Create().
class StartupInformationHelper {
 public:
  StartupInformationHelper();
  ~StartupInformationHelper();

  // Adds flags to the |dwFlags| field.
  void UpdateFlags(DWORD flags);
  // Sets |lpDesktop|. If |desktop| is empty, sets as nullptr.
  void SetDesktop(std::wstring desktop);
  // Creates PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY based on |flags|.
  void SetMitigations(MitigationFlags flags);
  // Creates PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY if |restrict| is true.
  void SetRestrictChildProcessCreation(bool restrict);
  // Sets stdout and stderr handles. Also allows these to be inherited into
  // the child process. Should be called once only.
  void SetStdHandles(HANDLE stdout_handle, HANDLE stderr_handle);
  // Ignores duplicate or invalid handles.
  void AddInheritedHandle(HANDLE handle);
  // Create PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES and
  //        PROC_THREAD_ATTRIBUTE_ALL_APPLICATION_PACKAGES_POLICY
  // based on |container|. |container| should be valid.
  void SetAppContainer(scoped_refptr<AppContainerBase> container);
  // Creates PROC_THREAD_ATTRIBUTE_JOB_LIST with |job_handle|. Not valid before
  // Windows 10.
  void AddJobToAssociate(HANDLE job_handle);

  // Will one or more jobs be associated via the wrapped StartupInformation.
  bool HasJobsToAssociate() { return !job_handle_list_.empty(); }
  // Have handles been provided for secure inheritance?
  bool ShouldInheritHandles() { return inherit_handles_; }

  // Compiles fields into PROC_THREAD_ attributes and populates startup
  // information. Must be called before GetStartupInformation().
  bool BuildStartupInformation();

  // Gets wrapped object, valid once BuildStartupInformation() has been called.
  base::win::StartupInformation* GetStartupInformation() {
    return &startup_info_;
  }

 private:
  void operator=(const StartupInformationHelper&) = delete;
  StartupInformationHelper(const StartupInformationHelper&) = delete;

  int CountAttributes();

  // Fields that are not passed into CreateProcessAsUserW().
  scoped_refptr<AppContainerBase> app_container_;
  bool restrict_child_process_creation_ = false;
  HANDLE stdout_handle_ = INVALID_HANDLE_VALUE;
  HANDLE stderr_handle_ = INVALID_HANDLE_VALUE;
  bool inherit_handles_ = false;
  size_t mitigations_size_ = 0;

  // startup_info_.startup_info() is passed to CreateProcessAsUserW().
  StartupInformation startup_info_;

  // These need to have the same lifetime as startup_info_.startup_info();
  std::wstring desktop_;
  DWORD64 mitigations_[2]{};
  COMPONENT_FILTER component_filter_{};
  DWORD child_process_creation_ = 0;
  DWORD all_applications_package_policy_ = 0;
  std::vector<HANDLE> inherited_handle_list_;
  std::vector<HANDLE> job_handle_list_;
  std::unique_ptr<SecurityCapabilities> security_capabilities_;
};
}  // namespace sandbox

#endif  // SANDBOX_WIN_SRC_STARTUP_INFORMATION_HELPER_H_


text:
package com.example.hahaha.musicplayer.service.listener;

import android.os.Handler;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import com.example.hahaha.musicplayer.model.entity.internal.PositionInfo;
import com.example.hahaha.musicplayer.service.aid.PositionListener;
import java.lang.ref.WeakReference;
import rx.functions.Func0;

public class PositionListenerManager {

  private static class BroadcastTask implements Runnable {
    WeakReference<PositionListenerManager> mWeakRef;
    BroadcastTask(PositionListenerManager manager) {
      mWeakRef = new WeakReference<>(manager);
    }

    @Override public void run() {
      PositionListenerManager manager = mWeakRef.get();
      if (manager == null) return;
      manager.broadcast();
    }
  }

  private static final long DELAY_MILLIS = 600;

  private Func0<Integer> mGetPosition;
  private Func0<Integer> mGetDuration;
  private RemoteCallbackList<PositionListener> mListenerList;
  private Handler mMainHandler;
  private Boolean mHasMsg;
  private BroadcastTask mBroadcastTask;

  public PositionListenerManager(Func0<Integer> getPosition, Func0<Integer> getDuration) {
    this.mGetPosition = getPosition;
    this.mGetDuration = getDuration;
    mListenerList = new RemoteCallbackList<>();
    mMainHandler = new Handler();
    mBroadcastTask = new BroadcastTask(this);
    mHasMsg = false;
  }

  public void register(PositionListener listener) {
    mListenerList.register(listener);
    synchronized (this) {
      if (mHasMsg) return;
      mHasMsg = true;
      mMainHandler.postDelayed(mBroadcastTask, DELAY_MILLIS);
    }
  }

  public void unregister(PositionListener listener) {
    mListenerList.unregister(listener);
  }

  public void finish() {
    mListenerList.kill();
  }

  private void broadcast() {
    int length = mListenerList.beginBroadcast();
    synchronized (this) {
      if (length == 0) {
        mListenerList.finishBroadcast();
        mHasMsg = false;
        return;
      }
    }
    try {
      PositionInfo positionInfo = new PositionInfo(mGetPosition.call(), mGetDuration.call());
      for (int i = 0; i < length; ++i) {
        try {
          mListenerList.getBroadcastItem(i).onPositionChange(positionInfo);
        } catch (RemoteException e) {
          e.printStackTrace();
        }
      }
    } catch (Exception e) {}
    finally {
      mListenerList.finishBroadcast();
      mMainHandler.postDelayed(mBroadcastTask, DELAY_MILLIS);
    }
  }

}


text:
import os
from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='cointk',
    version='0.0.12',
    author='Alex Gajewski, Wanqi Zhu, Ashwin Aggarwal, Jonathan Lipman',
    author_email='agajews@gmail.com, 1213.ghs@gmail.com, aaggarw99@gmail.com, jlipman500@gmail.com',

    description=('An open-sourced platform for rapid prototyping and testing '
                 'of BitCoin trading strategies, with visualiaztion features '
                 'via our open-sourced iOS app BitBox. Machine Learning '
                 'algorithms coming Soon.'),
    license='MIT',
    url='http://github.com/CoinTK',
    packages=find_packages(),
    long_description=read('README.md'),
    install_requires=['numpy', 'pprint', 'plotly']
)


text:
.. module:: sqlalchemy.schema

.. _metadata_defaults_toplevel:

.. _metadata_defaults:

Column INSERT/UPDATE Defaults
=============================

Column INSERT and UPDATE defaults refer to functions that create a **default
value** for a particular column in a row as an INSERT or UPDATE statement is
proceeding against that row, in the case where **no value was provided to the
INSERT or UPDATE statement for that column**.  That is, if a table has a column
called "timestamp", and an INSERT statement proceeds which does not include a
value for this column, an INSERT default would create a new value, such as
the current time, that is used as the value to be INSERTed into the "timestamp"
column.  If the statement *does* include a value  for this column, then the
default does *not* take place.

Column defaults can be server-side functions or constant values which are
defined in the database along with the schema in :term:`DDL`, or as SQL
expressions which are rendered directly within an INSERT or UPDATE statement
emitted by SQLAlchemy; they may also be client-side Python functions or
constant values which are invoked by SQLAlchemy before data is passed to the
database.

.. note::

    A column default handler should not be confused with a construct that
    intercepts and modifies incoming values for INSERT and UPDATE statements
    which *are* provided to the statement as it is invoked.  This is known
    as :term:`data marshalling`, where a column value is modified in some way
    by the application before being sent to the database.  SQLAlchemy provides
    a few means of achieving this which include using :ref:`custom datatypes
    <types_typedecorator>`, :ref:`SQL execution events <core_sql_events>` and
    in the ORM :ref:`custom  validators <simple_validators>` as well as
    :ref:`attribute events <orm_attribute_events>`.    Column defaults are only
    invoked when there is **no value present** for a column in a SQL
    :term:`DML` statement.

SQLAlchemy provides an array of features regarding default generation
functions which take place for non-present values during INSERT and UPDATE
statements. Options include:

* Scalar values used as defaults during INSERT and UPDATE operations
* Python functions which execute upon INSERT and UPDATE operations
* SQL expressions which are embedded in INSERT statements (or in some cases execute beforehand)
* SQL expressions which are embedded in UPDATE statements
* Server side default values used during INSERT
* Markers for server-side triggers used during UPDATE

The general rule for all insert/update defaults is that they only take effect
if no value for a particular column is passed as an ``execute()`` parameter;
otherwise, the given value is used.

Scalar Defaults
---------------

The simplest kind of default is a scalar value used as the default value of a column::

    Table("mytable", meta,
        Column("somecolumn", Integer, default=12)
    )

Above, the value "12" will be bound as the column value during an INSERT if no
other value is supplied.

A scalar value may also be associated with an UPDATE statement, though this is
not very common (as UPDATE statements are usually looking for dynamic
defaults)::

    Table("mytable", meta,
        Column("somecolumn", Integer, onupdate=25)
    )

Python-Executed Functions
-------------------------

The :paramref:`.Column.default` and :paramref:`.Column.onupdate` keyword arguments also accept Python
functions. These functions are invoked at the time of insert or update if no
other value for that column is supplied, and the value returned is used for
the column's value. Below illustrates a crude "sequence" that assigns an
incrementing counter to a primary key column::

    # a function which counts upwards
    i = 0
    def mydefault():
        global i
        i += 1
        return i

    t = Table("mytable", meta,
        Column('id', Integer, primary_key=True, default=mydefault),
    )

It should be noted that for real "incrementing sequence" behavior, the
built-in capabilities of the database should normally be used, which may
include sequence objects or other autoincrementing capabilities. For primary
key columns, SQLAlchemy will in most cases use these capabilities
automatically. See the API documentation for
:class:`~sqlalchemy.schema.Column` including the :paramref:`.Column.autoincrement` flag, as
well as the section on :class:`~sqlalchemy.schema.Sequence` later in this
chapter for background on standard primary key generation techniques.

To illustrate onupdate, we assign the Python ``datetime`` function ``now`` to
the :paramref:`.Column.onupdate` attribute::

    import datetime

    t = Table("mytable", meta,
        Column('id', Integer, primary_key=True),

        # define 'last_updated' to be populated with datetime.now()
        Column('last_updated', DateTime, onupdate=datetime.datetime.now),
    )

When an update statement executes and no value is passed for ``last_updated``,
the ``datetime.datetime.now()`` Python function is executed and its return
value used as the value for ``last_updated``. Notice that we provide ``now``
as the function itself without calling it (i.e. there are no parenthesis
following) - SQLAlchemy will execute the function at the time the statement
executes.

.. _context_default_functions:

Context-Sensitive Default Functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The Python functions used by :paramref:`.Column.default` and
:paramref:`.Column.onupdate` may also make use of the current statement's
context in order to determine a value. The `context` of a statement is an
internal SQLAlchemy object which contains all information about the statement
being executed, including its source expression, the parameters associated with
it and the cursor. The typical use case for this context with regards to
default generation is to have access to the other values being inserted or
updated on the row. To access the context, provide a function that accepts a
single ``context`` argument::

    def mydefault(context):
        return context.get_current_parameters()['counter'] + 12

    t = Table('mytable', meta,
        Column('counter', Integer),
        Column('counter_plus_twelve', Integer, default=mydefault, onupdate=mydefault)
    )

The above default generation function is applied so that it will execute for
all INSERT and UPDATE statements where a value for ``counter_plus_twelve`` was
otherwise not provided, and the value will be that of whatever value is present
in the execution for the ``counter`` column, plus the number 12.

For a single statement that is being executed using "executemany" style, e.g.
with multiple parameter sets passed to :meth:`.Connection.execute`, the user-
defined function is called once for each set of parameters. For the use case of
a multi-valued :class:`.Insert` construct (e.g. with more than one VALUES
clause set up via the :meth:`.Insert.values` method), the user-defined function
is also called once for each set of parameters.

When the function is invoked, the special method
:meth:`.DefaultExecutionContext.get_current_parameters` is available from
the context object (an subclass of :class:`.DefaultExecutionContext`).  This
method returns a dictionary of column-key to values that represents the
full set of values for the INSERT or UPDATE statement.   In the case of a
multi-valued INSERT construct, the subset of parameters that corresponds to
the individual VALUES clause is isolated from the full parameter dictionary
and returned alone.

.. versionadded:: 1.2

    Added :meth:`.DefaultExecutionContext.get_current_parameters` method,
    which improves upon the still-present
    :attr:`.DefaultExecutionContext.current_parameters` attribute
    by offering the service of organizing multiple VALUES clauses
    into individual parameter dictionaries.

Client-Invoked SQL Expressions
------------------------------

The :paramref:`.Column.default` and :paramref:`.Column.onupdate` keywords may
also be passed SQL expressions, which are in most cases rendered inline within the
INSERT or UPDATE statement::

    t = Table("mytable", meta,
        Column('id', Integer, primary_key=True),

        # define 'create_date' to default to now()
        Column('create_date', DateTime, default=func.now()),

        # define 'key' to pull its default from the 'keyvalues' table
        Column('key', String(20), default=select([keyvalues.c.key]).where(keyvalues.c.type='type1')),

        # define 'last_modified' to use the current_timestamp SQL function on update
        Column('last_modified', DateTime, onupdate=func.utc_timestamp())
        )

Above, the ``create_date`` column will be populated with the result of the
``now()`` SQL function (which, depending on backend, compiles into ``NOW()``
or ``CURRENT_TIMESTAMP`` in most cases) during an INSERT statement, and the
``key`` column with the result of a SELECT subquery from another table. The
``last_modified`` column will be populated with the value of
the SQL ``UTC_TIMESTAMP()`` MySQL function when an UPDATE statement is
emitted for this table.

.. note::

    When using SQL functions with the :attr:`.func` construct, we "call" the
    named function, e.g. with parenthesis as in ``func.now()``.   This differs
    from when we specify a Python callable as a default such as
    ``datetime.datetime``, where we pass the function itself, but we don't
    invoke it ourselves.   In the case of a SQL function, invoking
    ``func.now()`` returns the SQL expression object that will render the
    "NOW" function into the SQL being emitted.

Default and update SQL expressions specified by :paramref:`.Column.default` and
:paramref:`.Column.onupdate` are invoked explicitly by SQLAlchemy when an
INSERT or UPDATE statement occurs, typically rendered inline within the DML
statement except in certain cases listed below.   This is different than a
"server side" default, which is part of the table's DDL definition, e.g. as
part of the "CREATE TABLE" statement, which are likely more common.   For
server side defaults, see the next section :ref:`server_defaults`.

When a SQL expression indicated by :paramref:`.Column.default` is used with
primary key columns, there are some cases where SQLAlchemy must "pre-execute"
the default generation SQL function, meaning it is invoked in a separate SELECT
statement, and the resulting value is passed as a parameter to the INSERT.
This only occurs for primary key columns for an INSERT statement that is being
asked to return this primary key value, where RETURNING or ``cursor.lastrowid``
may not be used.   An :class:`.Insert` construct that specifies the
:paramref:`~.expression.insert.inline` flag will always render default expressions
inline.

When the statement is executed with a single set of parameters (that is, it is
not an "executemany" style execution), the returned
:class:`~sqlalchemy.engine.ResultProxy` will contain a collection accessible
via :meth:`.ResultProxy.postfetch_cols` which contains a list of all
:class:`~sqlalchemy.schema.Column` objects which had an inline-executed
default. Similarly, all parameters which were bound to the statement, including
all Python and SQL expressions which were pre-executed, are present in the
:meth:`.ResultProxy.last_inserted_params` or
:meth:`.ResultProxy.last_updated_params` collections on
:class:`~sqlalchemy.engine.ResultProxy`. The
:attr:`.ResultProxy.inserted_primary_key` collection contains a list of primary
key values for the row inserted (a list so that single-column and composite-
column primary keys are represented in the same format).

.. _server_defaults:

Server-invoked DDL-Explicit Default Expressions
-----------------------------------------------

A variant on the SQL expression default is the :paramref:`.Column.server_default`, which gets
placed in the CREATE TABLE statement during a :meth:`.Table.create` operation:

.. sourcecode:: python+sql

    t = Table('test', meta,
        Column('abc', String(20), server_default='abc'),
        Column('created_at', DateTime, server_default=func.sysdate()),
        Column('index_value', Integer, server_default=text("0"))
    )

A create call for the above table will produce::

    CREATE TABLE test (
        abc varchar(20) default 'abc',
        created_at datetime default sysdate,
        index_value integer default 0
    )

The above example illustrates the two typical use cases for :paramref:`.Column.server_default`,
that of the SQL function (SYSDATE in the above example) as well as a server-side constant
value (the integer "0" in the above example).  It is advisable to use the
:func:`.text` construct for any literal SQL values as opposed to passing the
raw value, as SQLAlchemy does not typically perform any quoting or escaping on
these values.

Like client-generated expressions, :paramref:`.Column.server_default` can accommodate
SQL expressions in general, however it is expected that these will usually be simple
functions and expressions, and not the more complex cases like an embedded SELECT.

.. _triggered_columns:

Marking Implicitly Generated Values, timestamps, and Triggered Columns
----------------------------------------------------------------------

Columns which generate a new value on INSERT or UPDATE based on other
server-side database mechanisms, such as database-specific auto-generating
behaviors such as seen with TIMESTAMP columns on some platforms, as well as
custom triggers that invoke upon INSERT or UPDATE to generate a new value,
may be called out using :class:`.FetchedValue` as a marker::

    t = Table('test', meta,
        Column('id', Integer, primary_key=True),
        Column('abc', TIMESTAMP, server_default=FetchedValue()),
        Column('def', String(20), server_onupdate=FetchedValue())
    )

The :class:`.FetchedValue` indicator does not affect the rendered DDL for the
CREATE TABLE.  Instead, it marks the column as one that will have a new value
populated by the database during the process of an INSERT or UPDATE statement,
and for supporting  databases may be used to indicate that the column should be
part of a RETURNING or OUTPUT clause for the statement.    Tools such as the
SQLAlchemy ORM then make use of this marker in order to know how to get at the
value of the column after such an operation.   In particular, the
:meth:`.ValuesBase.return_defaults` method can be used with an :class:`.Insert`
or :class:`.Update` construct to indicate that these values should be
returned.

For details on using :class:`.FetchedValue` with the ORM, see
:ref:`orm_server_defaults`.

.. seealso::

    :ref:`orm_server_defaults`

Defining Sequences
------------------

SQLAlchemy represents database sequences using the
:class:`~sqlalchemy.schema.Sequence` object, which is considered to be a
special case of "column default". It only has an effect on databases which
have explicit support for sequences, which currently includes PostgreSQL,
Oracle, and Firebird. The :class:`~sqlalchemy.schema.Sequence` object is
otherwise ignored.

The :class:`~sqlalchemy.schema.Sequence` may be placed on any column as a
"default" generator to be used during INSERT operations, and can also be
configured to fire off during UPDATE operations if desired. It is most
commonly used in conjunction with a single integer primary key column::

    table = Table("cartitems", meta,
        Column(
            "cart_id",
            Integer,
            Sequence('cart_id_seq', metadata=meta), primary_key=True),
        Column("description", String(40)),
        Column("createdate", DateTime())
    )

Where above, the table "cartitems" is associated with a sequence named
"cart_id_seq". When INSERT statements take place for "cartitems", and no value
is passed for the "cart_id" column, the "cart_id_seq" sequence will be used to
generate a value.   Typically, the sequence function is embedded in the
INSERT statement, which is combined with RETURNING so that the newly generated
value can be returned to the Python code::

    INSERT INTO cartitems (cart_id, description, createdate)
    VALUES (next_val(cart_id_seq), 'some description', '2015-10-15 12:00:15')
    RETURNING cart_id

When the :class:`~sqlalchemy.schema.Sequence` is associated with a
:class:`.Column` as its **Python-side** default generator, the
:class:`.Sequence` will also be subject to "CREATE SEQUENCE" and "DROP
SEQUENCE" DDL when similar DDL is emitted for the owning :class:`.Table`.
This is a limited scope convenience feature that does not accommodate for
inheritance of other aspects of the :class:`.MetaData`, such as the default
schema.  Therefore, it is best practice that for a :class:`.Sequence` which
is local to a certain :class:`.Column` / :class:`.Table`, that it be
explicitly associated with the :class:`.MetaData` using the
:paramref:`.Sequence.metadata` parameter.  See the section
:ref:`sequence_metadata` for more background on this.

Associating a Sequence on a SERIAL column
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

PostgreSQL's SERIAL datatype is an auto-incrementing type that implies
the implicit creation of a PostgreSQL sequence when CREATE TABLE is emitted.
If a :class:`.Column` specifies an explicit :class:`.Sequence` object
which also specifies a true value for the :paramref:`.Sequence.optional`
boolean flag, the :class:`.Sequence` will not take effect under PostgreSQL,
and the SERIAL datatype will proceed normally.   Instead, the :class:`.Sequence`
will only take effect when used against other sequence-supporting
databases, currently Oracle and Firebird.

Executing a Sequence Standalone
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A SEQUENCE is a first class schema object in SQL and can be used to generate
values independently in the database.   If you have a :class:`.Sequence`
object, it can be invoked with its "next value" instruction by
passing it directly to a SQL execution method::

    with my_engine.connect() as conn:
        seq = Sequence('some_sequence')
        nextid = conn.execute(seq)

In order to embed the "next value" function of a :class:`.Sequence`
inside of a SQL statement like a SELECT or INSERT, use the :meth:`.Sequence.next_value`
method, which will render at statement compilation time a SQL function that is
appropriate for the target backend::

    >>> my_seq = Sequence('some_sequence')
    >>> stmt = select([my_seq.next_value()])
    >>> print stmt.compile(dialect=postgresql.dialect())
    SELECT nextval('some_sequence') AS next_value_1

.. _sequence_metadata:

Associating a Sequence with the MetaData
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For many years, the SQLAlchemy documentation referred to the
example of associating a :class:`.Sequence` with a table as follows::

    table = Table("cartitems", meta,
        Column("cart_id", Integer, Sequence('cart_id_seq'),
               primary_key=True),
        Column("description", String(40)),
        Column("createdate", DateTime())
    )

While the above is a prominent idiomatic pattern, it is recommended that
the :class:`.Sequence` in most cases be explicitly associated with the
:class:`.MetaData`, using the :paramref:`.Sequence.metadata` parameter::

    table = Table("cartitems", meta,
        Column(
            "cart_id",
            Integer,
            Sequence('cart_id_seq', metadata=meta), primary_key=True),
        Column("description", String(40)),
        Column("createdate", DateTime())
    )

The :class:`.Sequence` object is a first class
schema construct that can exist independently of any table in a database, and
can also be shared among tables.   Therefore SQLAlchemy does not implicitly
modify the :class:`.Sequence` when it is associated with a :class:`.Column`
object as either the Python-side or server-side default  generator.  While the
CREATE SEQUENCE / DROP SEQUENCE DDL is emitted for a  :class:`.Sequence`
defined as a Python side generator at the same time the table itself is subject
to CREATE or DROP, this is a convenience feature that does not imply that the
:class:`.Sequence` is fully associated with the :class:`.MetaData` object.

Explicitly associating the :class:`.Sequence` with :class:`.MetaData`
allows for the following behaviors:

* The :class:`.Sequence` will inherit the :paramref:`.MetaData.schema`
  parameter specified to the target :class:`.MetaData`, which
  affects the production of CREATE / DROP DDL, if any.

* The :meth:`.Sequence.create` and :meth:`.Sequence.drop` methods
  automatically use the engine bound to the :class:`.MetaData`
  object, if any.

* The :meth:`.MetaData.create_all` and :meth:`.MetaData.drop_all`
  methods will emit CREATE / DROP for this :class:`.Sequence`,
  even if the :class:`.Sequence` is not associated with any
  :class:`.Table` / :class:`.Column` that's a member of this
  :class:`.MetaData`.

Since the vast majority of cases that deal with :class:`.Sequence` expect
that :class:`.Sequence` to be fully "owned" by the associated :class:`.Table`
and that options like default schema are propagated, setting the
:paramref:`.Sequence.metadata` parameter should be considered a best practice.

Associating a Sequence as the Server Side Default
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. note:: The following technique is known to work only with the PostgreSQL
   database.  It does not work with Oracle.

The preceding sections illustrate how to associate a :class:`.Sequence` with a
:class:`.Column` as the **Python side default generator**::

    Column(
        "cart_id", Integer, Sequence('cart_id_seq', metadata=meta),
        primary_key=True)

In the above case, the :class:`.Sequence` will automatically be subject
to CREATE SEQUENCE / DROP SEQUENCE DDL when the related :class:`.Table`
is subject to CREATE / DROP.  However, the sequence will **not** be present
as the server-side default for the column when CREATE TABLE is emitted.

If we want the sequence to be used as a server-side default,
meaning it takes place even if we emit INSERT commands to the table from
the SQL command line, we can use the :paramref:`.Column.server_default`
parameter in conjunction with the value-generation function of the
sequence, available from the :meth:`.Sequence.next_value` method.  Below
we illustrate the same :class:`.Sequence` being associated with the
:class:`.Column` both as the Python-side default generator as well as
the server-side default generator::

    cart_id_seq = Sequence('cart_id_seq', metadata=meta)
    table = Table("cartitems", meta,
        Column(
            "cart_id", Integer, cart_id_seq,
            server_default=cart_id_seq.next_value(), primary_key=True),
        Column("description", String(40)),
        Column("createdate", DateTime())
    )

or with the ORM::

    class CartItem(Base):
        __tablename__ = 'cartitems'

        cart_id_seq = Sequence('cart_id_seq', metadata=Base.metadata)
        cart_id = Column(
            Integer, cart_id_seq,
            server_default=cart_id_seq.next_value(), primary_key=True)
        description = Column(String(40))
        createdate = Column(DateTime)

When the "CREATE TABLE" statement is emitted, on PostgreSQL it would be
emitted as::

    CREATE TABLE cartitems (
        cart_id INTEGER DEFAULT nextval('cart_id_seq') NOT NULL,
        description VARCHAR(40),
        createdate TIMESTAMP WITHOUT TIME ZONE,
        PRIMARY KEY (cart_id)
    )

Placement of the :class:`.Sequence` in both the Python-side and server-side
default generation contexts ensures that the "primary key fetch" logic
works in all cases.  Typically, sequence-enabled databases also support
RETURNING for INSERT statements, which is used automatically by SQLAlchemy
when emitting this statement.  However if RETURNING is not used for a particular
insert, then SQLAlchemy would prefer to "pre-execute" the sequence outside
of the INSERT statement itself, which only works if the sequence is
included as the Python-side default generator function.

The example also associates the :class:`.Sequence` with the enclosing
:class:`.MetaData` directly, which again ensures that the :class:`.Sequence`
is fully associated with the parameters of the :class:`.MetaData` collection
including the default schema, if any.

.. seealso::

    :ref:`postgresql_sequences` - in the PostgreSQL dialect documentation

    :ref:`oracle_returning` - in the Oracle dialect documentation

Default Objects API
-------------------

.. autoclass:: ColumnDefault

.. autoclass:: DefaultClause

.. autoclass:: DefaultGenerator

.. autoclass:: FetchedValue

.. autoclass:: PassiveDefault

.. autoclass:: Sequence
    :members:


text:
#include <apr_lib.h>
#include <apr_strings.h>
#include <apr_date.h>

#include "serf.h"
#include "serf_bucket_util.h"
#include "serf_private.h"

typedef struct {
    serf_bucket_t *stream;
    serf_bucket_t *body;        /* Pointer to the stream wrapping the body. */
    serf_bucket_t *headers;     /* holds parsed headers */

    enum {
        STATE_STATUS_LINE,      /* reading status line */
        STATE_HEADERS,          /* reading headers */
        STATE_BODY,             /* reading body */
        STATE_TRAILERS,         /* reading trailers */
        STATE_DONE              /* we've sent EOF */
    } state;

    /* Buffer for accumulating a line from the response. */
    serf_linebuf_t linebuf;

    serf_status_line sl;

    int chunked;                /* Do we need to read trailers? */
    int head_req;               /* Was this a HEAD request? */
} response_context_t;

/* Returns 1 if according to RFC2626 this response can have a body, 0 if it
   must not have a body. */
static int expect_body(response_context_t *ctx)
{
    if (ctx->head_req)
        return 0;

    /* 100 Continue and 101 Switching Protocols */
    if (ctx->sl.code >= 100 && ctx->sl.code < 200)
        return 0;

    /* 204 No Content */
    if (ctx->sl.code == 204)
        return 0;

    /* 205? */

    /* 304 Not Modified */
    if (ctx->sl.code == 304)
        return 0;

    return 1;
}

serf_bucket_t *serf_bucket_response_create(
    serf_bucket_t *stream,
    serf_bucket_alloc_t *allocator)
{
    response_context_t *ctx;

    ctx = serf_bucket_mem_alloc(allocator, sizeof(*ctx));
    ctx->stream = stream;
    ctx->body = NULL;
    ctx->headers = serf_bucket_headers_create(allocator);
    ctx->state = STATE_STATUS_LINE;
    ctx->chunked = 0;
    ctx->head_req = 0;

    serf_linebuf_init(&ctx->linebuf);

    return serf_bucket_create(&serf_bucket_type_response, allocator, ctx);
}

void serf_bucket_response_set_head(
    serf_bucket_t *bucket)
{
    response_context_t *ctx = bucket->data;

    ctx->head_req = 1;
}

serf_bucket_t *serf_bucket_response_get_headers(
    serf_bucket_t *bucket)
{
    return ((response_context_t *)bucket->data)->headers;
}

static void serf_response_destroy_and_data(serf_bucket_t *bucket)
{
    response_context_t *ctx = bucket->data;

    if (ctx->state != STATE_STATUS_LINE) {
        serf_bucket_mem_free(bucket->allocator, (void*)ctx->sl.reason);
    }

    serf_bucket_destroy(ctx->stream);
    if (ctx->body != NULL)
        serf_bucket_destroy(ctx->body);
    serf_bucket_destroy(ctx->headers);

    serf_default_destroy_and_data(bucket);
}

static apr_status_t fetch_line(response_context_t *ctx, int acceptable)
{
    return serf_linebuf_fetch(&ctx->linebuf, ctx->stream, acceptable);
}

static apr_status_t parse_status_line(response_context_t *ctx,
                                      serf_bucket_alloc_t *allocator)
{
    int res;
    char *reason; /* ### stupid APR interface makes this non-const */

    /* ctx->linebuf.line should be of form: HTTP/1.1 200 OK */
    res = apr_date_checkmask(ctx->linebuf.line, "HTTP/#.# ###*");
    if (!res) {
        /* Not an HTTP response?  Well, at least we won't understand it. */
        return SERF_ERROR_BAD_HTTP_RESPONSE;
    }

    ctx->sl.version = SERF_HTTP_VERSION(ctx->linebuf.line[5] - '0',
                                        ctx->linebuf.line[7] - '0');
    ctx->sl.code = apr_strtoi64(ctx->linebuf.line + 8, &reason, 10);

    /* Skip leading spaces for the reason string. */
    if (apr_isspace(*reason)) {
        reason++;
    }

    /* Copy the reason value out of the line buffer. */
    ctx->sl.reason = serf_bstrmemdup(allocator, reason,
                                     ctx->linebuf.used
                                     - (reason - ctx->linebuf.line));

    return APR_SUCCESS;
}

/* This code should be replaced with header buckets. */
static apr_status_t fetch_headers(serf_bucket_t *bkt, response_context_t *ctx)
{
    apr_status_t status;

    /* RFC 2616 says that CRLF is the only line ending, but we can easily
     * accept any kind of line ending.
     */
    status = fetch_line(ctx, SERF_NEWLINE_ANY);
    if (SERF_BUCKET_READ_ERROR(status)) {
        return status;
    }
    /* Something was read. Process it. */

    if (ctx->linebuf.state == SERF_LINEBUF_READY && ctx->linebuf.used) {
        const char *end_key;
        const char *c;

        end_key = c = memchr(ctx->linebuf.line, ':', ctx->linebuf.used);
        if (!c) {
            /* Bad headers? */
            return SERF_ERROR_BAD_HTTP_RESPONSE;
        }

        /* Skip over initial ':' */
        c++;

        /* And skip all whitespaces. */
        for(; c < ctx->linebuf.line + ctx->linebuf.used; c++)
        {
            if (!apr_isspace(*c))
            {
              break;
            }
        }

        /* Always copy the headers (from the linebuf into new mem). */
        /* ### we should be able to optimize some mem copies */
        serf_bucket_headers_setx(
            ctx->headers,
            ctx->linebuf.line, end_key - ctx->linebuf.line, 1,
            c, ctx->linebuf.line + ctx->linebuf.used - c, 1);
    }

    return status;
}

/* Perform one iteration of the state machine.
 *
 * Will return when one the following conditions occurred:
 *  1) a state change
 *  2) an error
 *  3) the stream is not ready or at EOF
 *  4) APR_SUCCESS, meaning the machine can be run again immediately
 */
static apr_status_t run_machine(serf_bucket_t *bkt, response_context_t *ctx)
{
    apr_status_t status = APR_SUCCESS; /* initialize to avoid gcc warnings */

    switch (ctx->state) {
    case STATE_STATUS_LINE:
        /* RFC 2616 says that CRLF is the only line ending, but we can easily
         * accept any kind of line ending.
         */
        status = fetch_line(ctx, SERF_NEWLINE_ANY);
        if (SERF_BUCKET_READ_ERROR(status))
            return status;

        if (ctx->linebuf.state == SERF_LINEBUF_READY) {
            /* The Status-Line is in the line buffer. Process it. */
            status = parse_status_line(ctx, bkt->allocator);
            if (status)
                return status;

            /* Good times ahead: we're switching protocols! */
            if (ctx->sl.code == 101) {
                ctx->body =
                    serf_bucket_barrier_create(ctx->stream, bkt->allocator);
                ctx->state = STATE_DONE;
                break;
            }

            /* Okay... move on to reading the headers. */
            ctx->state = STATE_HEADERS;
        }
        else {
            /* The connection closed before we could get the next
             * response.  Treat the request as lost so that our upper
             * end knows the server never tried to give us a response.
             */
            if (APR_STATUS_IS_EOF(status)) {
                return SERF_ERROR_REQUEST_LOST;
            }
        }
        break;
    case STATE_HEADERS:
        status = fetch_headers(bkt, ctx);
        if (SERF_BUCKET_READ_ERROR(status))
            return status;

        /* If an empty line was read, then we hit the end of the headers.
         * Move on to the body.
         */
        if (ctx->linebuf.state == SERF_LINEBUF_READY && !ctx->linebuf.used) {
            const void *v;

            /* Advance the state. */
            ctx->state = STATE_BODY;

            /* If this is a response to a HEAD request, or code == 1xx,204 or304
               then we don't receive a real body. */
            if (!expect_body(ctx)) {
                ctx->body = serf_bucket_simple_create(NULL, 0, NULL, NULL,
                                                      bkt->allocator);
                ctx->state = STATE_BODY;
                break;
            }

            ctx->body =
                serf_bucket_barrier_create(ctx->stream, bkt->allocator);

            /* Are we C-L, chunked, or conn close? */
            v = serf_bucket_headers_get(ctx->headers, "Content-Length");
            if (v) {
                apr_uint64_t length;
                length = apr_strtoi64(v, NULL, 10);
                if (errno == ERANGE) {
                    return APR_FROM_OS_ERROR(ERANGE);
                }
                ctx->body = serf_bucket_response_body_create(
                              ctx->body, length, bkt->allocator);
            }
            else {
                v = serf_bucket_headers_get(ctx->headers, "Transfer-Encoding");

                /* Need to handle multiple transfer-encoding. */
                if (v && strcasecmp("chunked", v) == 0) {
                    ctx->chunked = 1;
                    ctx->body = serf_bucket_dechunk_create(ctx->body,
                                                           bkt->allocator);
                }
            }
            v = serf_bucket_headers_get(ctx->headers, "Content-Encoding");
            if (v) {
                /* Need to handle multiple content-encoding. */
                if (v && strcasecmp("gzip", v) == 0) {
                    ctx->body =
                        serf_bucket_deflate_create(ctx->body, bkt->allocator,
                                                   SERF_DEFLATE_GZIP);
                }
                else if (v && strcasecmp("deflate", v) == 0) {
                    ctx->body =
                        serf_bucket_deflate_create(ctx->body, bkt->allocator,
                                                   SERF_DEFLATE_DEFLATE);
                }
            }
        }
        break;
    case STATE_BODY:
        /* Don't do anything. */
        break;
    case STATE_TRAILERS:
        status = fetch_headers(bkt, ctx);
        if (SERF_BUCKET_READ_ERROR(status))
            return status;

        /* If an empty line was read, then we're done. */
        if (ctx->linebuf.state == SERF_LINEBUF_READY && !ctx->linebuf.used) {
            ctx->state = STATE_DONE;
            return APR_EOF;
        }
        break;
    case STATE_DONE:
        return APR_EOF;
    default:
        /* Not reachable */
        return APR_EGENERAL;
    }

    return status;
}

static apr_status_t wait_for_body(serf_bucket_t *bkt, response_context_t *ctx)
{
    apr_status_t status;

    /* Keep reading and moving through states if we aren't at the BODY */
    while (ctx->state != STATE_BODY) {
        status = run_machine(bkt, ctx);

        /* Anything other than APR_SUCCESS means that we cannot immediately
         * read again (for now).
         */
        if (status)
            return status;
    }
    /* in STATE_BODY */

    return APR_SUCCESS;
}

apr_status_t serf_bucket_response_wait_for_headers(
    serf_bucket_t *bucket)
{
    response_context_t *ctx = bucket->data;

    return wait_for_body(bucket, ctx);
}

apr_status_t serf_bucket_response_status(
    serf_bucket_t *bkt,
    serf_status_line *sline)
{
    response_context_t *ctx = bkt->data;
    apr_status_t status;

    if (ctx->state != STATE_STATUS_LINE) {
        /* We already read it and moved on. Just return it. */
        *sline = ctx->sl;
        return APR_SUCCESS;
    }

    /* Running the state machine once will advance the machine, or state
     * that the stream isn't ready with enough data. There isn't ever a
     * need to run the machine more than once to try and satisfy this. We
     * have to look at the state to tell whether it advanced, though, as
     * it is quite possible to advance *and* to return APR_EAGAIN.
     */
    status = run_machine(bkt, ctx);
    if (ctx->state == STATE_HEADERS) {
        *sline = ctx->sl;
    }
    else {
        /* Indicate that we don't have the information yet. */
        sline->version = 0;
    }

    return status;
}

static apr_status_t serf_response_read(serf_bucket_t *bucket,
                                       apr_size_t requested,
                                       const char **data, apr_size_t *len)
{
    response_context_t *ctx = bucket->data;
    apr_status_t rv;

    rv = wait_for_body(bucket, ctx);
    if (rv) {
        /* It's not possible to have read anything yet! */
        if (APR_STATUS_IS_EOF(rv) || APR_STATUS_IS_EAGAIN(rv)) {
            *len = 0;
        }
        return rv;
    }

    rv = serf_bucket_read(ctx->body, requested, data, len);
    if (SERF_BUCKET_READ_ERROR(rv))
        return rv;

    if (APR_STATUS_IS_EOF(rv)) {
        if (ctx->chunked) {
            ctx->state = STATE_TRAILERS;
            /* Mask the result. */
            rv = APR_SUCCESS;
        } else {
            ctx->state = STATE_DONE;
        }
    }
    return rv;
}

static apr_status_t serf_response_readline(serf_bucket_t *bucket,
                                           int acceptable, int *found,
                                           const char **data, apr_size_t *len)
{
    response_context_t *ctx = bucket->data;
    apr_status_t rv;

    rv = wait_for_body(bucket, ctx);
    if (rv) {
        return rv;
    }

    /* Delegate to the stream bucket to do the readline. */
    return serf_bucket_readline(ctx->body, acceptable, found, data, len);
}

apr_status_t serf_response_full_become_aggregate(serf_bucket_t *bucket)
{
    response_context_t *ctx = bucket->data;
    serf_bucket_t *bkt;
    char buf[256];
    int size;

    serf_bucket_aggregate_become(bucket);

    /* Add reconstructed status line. */
    size = apr_snprintf(buf, 256, "HTTP/%d.%d %d ",
                        SERF_HTTP_VERSION_MAJOR(ctx->sl.version),
                        SERF_HTTP_VERSION_MINOR(ctx->sl.version),
                        ctx->sl.code);
    bkt = serf_bucket_simple_copy_create(buf, size,
                                         bucket->allocator);
    serf_bucket_aggregate_append(bucket, bkt);
    bkt = serf_bucket_simple_copy_create(ctx->sl.reason, strlen(ctx->sl.reason),
                                         bucket->allocator);
    serf_bucket_aggregate_append(bucket, bkt);
    bkt = SERF_BUCKET_SIMPLE_STRING_LEN("\r\n", 2,
                                        bucket->allocator);
    serf_bucket_aggregate_append(bucket, bkt);

    /* Add headers and stream buckets in order. */
    serf_bucket_aggregate_append(bucket, ctx->headers);
    serf_bucket_aggregate_append(bucket, ctx->stream);

    serf_bucket_mem_free(bucket->allocator, ctx);

    return APR_SUCCESS;
}

/* ### need to implement */
#define serf_response_peek NULL

const serf_bucket_type_t serf_bucket_type_response = {
    "RESPONSE",
    serf_response_read,
    serf_response_readline,
    serf_default_read_iovec,
    serf_default_read_for_sendfile,
    serf_default_read_bucket,
    serf_response_peek,
    serf_response_destroy_and_data,
};


text:
package be.objectify.deadbolt.scala.views.di.restrictTest

import be.objectify.deadbolt.scala.AuthenticatedRequest
import be.objectify.deadbolt.scala.{anyOf => anyOfRoles, allOf => allOfRoles, allOfGroup}
import be.objectify.deadbolt.scala._
import be.objectify.deadbolt.scala.models.Subject
import be.objectify.deadbolt.scala.testhelpers.SecurityRole
import be.objectify.deadbolt.scala.views.di.AbstractViewTest
import be.objectify.deadbolt.scala.views.html.di.restrictOr
import be.objectify.deadbolt.scala.views.html.di.restrictTest.restrictOrContent
import play.api.test.{FakeRequest, Helpers, WithApplication}

/**
  * @author Steve Chaloner (steve@objectify.be)
  */
class RestrictOrTest extends AbstractViewTest {

  val admin: Option[Subject] = Some(user(roles = List(SecurityRole("admin"))))
  val watchdog: Option[Subject] = Some(user(roles = List(SecurityRole("watchdog"))))
  val adminWatchdog: Option[Subject] = Some(user(roles = List(SecurityRole("admin"), SecurityRole("watchdog"))))
  val regularUser: Option[Subject] = Some(user(roles = List(SecurityRole("user"))))
  val noRoles: Option[Subject] = Some(user())

   "when protected by a single role, the view" should {
     "hide constrained content and show fallback content when subject is not present" in new WithApplication(testApp(handler())) {
       val html = constraint(handler())(allOfGroup("foo"))(new AuthenticatedRequest(FakeRequest(), None))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "hide constrained content and show fallback content when subject does not have necessary role" in new WithApplication(testApp(handler(subject = regularUser))) {
       val html = constraint(handler(subject = regularUser))(allOfGroup("admin"))(new AuthenticatedRequest(FakeRequest(), regularUser))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "hide constrained content and show fallback content when subject does not have any roles" in new WithApplication(testApp(handler(subject = noRoles))) {
       val html = constraint(handler(subject = noRoles))(allOfGroup("admin"))(new AuthenticatedRequest(FakeRequest(), noRoles))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "hide constrained content and show fallback content when subject has other roles" in new WithApplication(testApp(handler(subject = regularUser))) {
       val html = constraint(handler(subject = regularUser))(allOfGroup("admin"))(new AuthenticatedRequest(FakeRequest(), regularUser))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "show constrained content and hide fallback content when subject has necessary role" in new WithApplication(testApp(handler(subject = admin))) {
       val html = constraint(handler(subject = admin))(allOfGroup("admin"))(new AuthenticatedRequest(FakeRequest(), admin))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must contain("This is protected by the constraint.")
       content must not contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }
   }

   "when protected by two ANDed roles, the view" should {
     "hide constrained content and show fallback content when subject is not present" in new WithApplication(testApp(handler())) {
       val html = constraint(handler())(allOfGroup("admin", "watchdog"))(new AuthenticatedRequest(FakeRequest(), None))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "hide constrained content and show fallback content when subject does not have necessary role" in new WithApplication(testApp(handler(subject = regularUser))) {
       val html = constraint(handler(subject = regularUser))(allOfGroup("admin", "watchdog"))(new AuthenticatedRequest(FakeRequest(), regularUser))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "hide constrained content and show fallback content when subject does not have any roles" in new WithApplication(testApp(handler(subject = noRoles))) {
       val html = constraint(handler(subject = noRoles))(allOfGroup("admin", "watchdog"))(new AuthenticatedRequest(FakeRequest(), noRoles))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "show constrained content and hide fallback content when subject has both roles" in new WithApplication(testApp(handler(subject = adminWatchdog))) {
       val html = constraint(handler(subject = adminWatchdog))(allOfGroup("admin", "watchdog"))(new AuthenticatedRequest(FakeRequest(), adminWatchdog))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must contain("This is protected by the constraint.")
       content must not contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }
   }

   "when protected by two ORed roles, the view" should {
     "hide constrained content and show fallback content when subject is not present" in new WithApplication(testApp(handler())) {
       val html = constraint(handler())(anyOfRoles(allOfRoles("admin"), allOfRoles("watchdog")))(new AuthenticatedRequest(FakeRequest(), None))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "hide constrained content and show fallback content when subject does not have either of the necessary roles" in new WithApplication(testApp(handler(subject = regularUser))) {
       val html = constraint(handler(subject = regularUser))(anyOfRoles(allOfRoles("admin"), allOfRoles("watchdog")))(new AuthenticatedRequest(FakeRequest(), regularUser))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "hide constrained content and show fallback content when subject does not have any roles" in new WithApplication(testApp(handler(subject = noRoles))) {
       val html = constraint(handler(subject = noRoles))(anyOfRoles(allOfRoles("admin"), allOfRoles("watchdog")))(new AuthenticatedRequest(FakeRequest(), noRoles))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "show constrained content and hide fallback content when subject has both roles" in new WithApplication(testApp(handler(subject = adminWatchdog))) {
       val html = constraint(handler(subject = adminWatchdog)).apply(anyOfRoles(allOfRoles("admin"), allOfRoles("watchdog")))(new AuthenticatedRequest(FakeRequest(), adminWatchdog))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must contain("This is protected by the constraint.")
       content must not contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "show constrained content and hide fallback content when subject has one of the roles" in new WithApplication(testApp(handler(subject = admin))) {
       val html = constraint(handler(subject = admin))(anyOfRoles(allOfRoles("admin"), allOfRoles("watchdog")))(new AuthenticatedRequest(FakeRequest(), admin))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must contain("This is protected by the constraint.")
       content must not contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "show constrained content and hide fallback content when subject has another one of the roles" in new WithApplication(testApp(handler(subject = watchdog))) {
       val html = constraint(handler(subject = watchdog))(anyOfRoles(allOfRoles("admin"), allOfRoles("watchdog")))(new AuthenticatedRequest(FakeRequest(), watchdog))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must contain("This is protected by the constraint.")
       content must not contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }
   }

   "when a single role is present and negated, the view" should {
     "hide constrained content and show fallback content when subject is not present" in new WithApplication(testApp(handler())) {
       val html = constraint(handler())(allOfGroup("!foo"))(new AuthenticatedRequest(FakeRequest(), None))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "hide constrained content and show fallback content when subject has the negated role" in new WithApplication(testApp(handler(subject = admin))) {
       val html = constraint(handler(subject = admin))(allOfGroup("!admin"))(new AuthenticatedRequest(FakeRequest(), admin))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "show constrained content and hide fallback content when subject does not have the negated role" in new WithApplication(testApp(handler(subject = regularUser))) {
       val html = constraint(handler(subject = regularUser))(allOfGroup("!admin"))(new AuthenticatedRequest(FakeRequest(), regularUser))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must contain("This is protected by the constraint.")
       content must not contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }
   }

   "when ANDed roles contain a negated role, the view" should {
     "show constrained content and hide fallback content when subject is not present" in new WithApplication(testApp(handler())) {
       val html = constraint(handler())(allOfGroup("!admin", "watchdog"))(new AuthenticatedRequest(FakeRequest(), None))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "hide constrained content and show fallback content when subject has the negated role" in new WithApplication(testApp(handler(subject = adminWatchdog))) {
       val html = constraint(handler(subject = adminWatchdog))(allOfGroup("!admin", "watchdog"))(new AuthenticatedRequest(FakeRequest(), adminWatchdog))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must not contain("This is protected by the constraint.")
       content must contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }

     "show constrained content and hide fallback content when subject has the non-negated role but does not have the negated role" in new WithApplication(testApp(handler(subject = watchdog))) {
       val html = constraint(handler(subject = watchdog))(allOfGroup("!admin", "watchdog"))(new AuthenticatedRequest(FakeRequest(), watchdog))

       private val content: String = Helpers.contentAsString(html)
       content must contain("This is before the constraint.")
       content must contain("This is protected by the constraint.")
       content must not contain("This is default content in case the constraint denies access to the protected content.")
       content must contain("This is after the constraint.")
     }
   }

  def constraint(handler: DeadboltHandler): restrictOrContent = new restrictOrContent(new restrictOr(viewSupport(), handlerCache(handler)))
}


text:
/**
 * @Probject Name: WFJ-Base-Server-Dev
 * @Path: com.jack.netty.util.infcResourceLoader.java
 * @Create By Jack
 * @Create In 2016年8月16日 上午9:56:31
 * TODO
 */
package com.jack.netty.conf.infc;

import com.jack.netty.conf.util.ResourceUtils;

/**
 * @Class Name ResourceLoader
 * @Author Jack
 * @Create In 2016年8月16日
 */
public interface ResourceLoader {

    /**
     * Pseudo URL prefix for loading from the class path: "classpath:"
     */
    String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;

    /**
     * Return a Resource handle for the specified resource.
     * The handle should always be a reusable resource descriptor,
     * allowing for multiple {@link Resource#getInputStream()} calls.
     *

     *
Must support fully qualified URLs, e.g. "file:C:/test.dat".
     *
Must support classpath pseudo-URLs, e.g. "classpath:test.dat".
     *
Should support relative file paths, e.g. "WEB-INF/test.dat".
     * (This will be implementation-specific, typically provided by an
     * ApplicationContext implementation.)
     *

     *
Note that a Resource handle does not imply an existing resource;
     * you need to invoke {@link Resource#exists} to check for existence.
     *
     * @param location the resource location
     * @return a corresponding Resource handle
     * @see #CLASSPATH_URL_PREFIX
     * @see org.springframework.core.io.Resource#exists
     * @see org.springframework.core.io.Resource#getInputStream
     */
    Resource getResource(String location);

    /**
     * Expose the ClassLoader used by this ResourceLoader.
     *
Clients which need to access the ClassLoader directly can do so
     * in a uniform manner with the ResourceLoader, rather than relying
     * on the thread context ClassLoader.
     *
     * @return the ClassLoader (never {@code null})
     */
    ClassLoader getClassLoader();

}


text:
@class MBTagLabel;
@interface RadarTaskCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *numberLabel;
@property (weak, nonatomic) IBOutlet MBTagLabel *statusLabel;
@property (weak, nonatomic) IBOutlet UILabel *radarTitleLabel;

@property (nonatomic, assign, getter=isImported) BOOL imported;

@end


text:
[![Build Status](https://travis-ci.org/coffeedriven/card.js.png)](https://travis-ci.org/coffeedriven/card.js)
[![Code Coverage](https://codeclimate.com/github/coffeedriven/card.js/badges/coverage.svg)](https://codeclimate.com/github/coffeedriven/card.js)
[![Code Climate](https://codeclimate.com/github/coffeedriven/card.js/badges/gpa.svg)](https://codeclimate.com/github/coffeedriven/card.js)

# card.js
card.js - parse and validate credit card number in javascript.

## Features

  - Credit card type detection based on IIN number. See more on [wikipedia](http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29)
  - Credit card type detection for full length card number
  - Luhn algorithm validation

## Loading

The library is the single JavaScript file *card.js* (or minified, *card.min.js*).

It can be loaded via a script tag in an HTML document for the browser

    <script src='./relative/path/to/card.js'></script>

(check [examples/browser](examples/browser)) or as a CommonJS, [Node.js](http://nodejs.org).

For Node, put the *card.js* file into the same directory as the file that is requiring it and use

    var card = require('./card.js');

or put it in a *node_modules* directory within the directory and use `require('card.js')`. See example in [examples/nodejs](examples/nodejs).

The library is also available from the [npm](https://npmjs.org/) registry, so

    $ npm install card.js

will install this module in a *node_modules* directory within the current directory.

## Usage

```
card('4111111111111111').getType(); // output: visa
card('41').getIINType(); // output: visa
card('4111111111111111').isValid(); // output: true
```

## Supported browsers

  - Chrome
  - Firefox
  - Internet Explorer 9
  - Safari
  - Opera

## Supported card types:

Issuing network | card type returned by `getType`
--- | ---
Visa | visa
Mastercard | mastercard
American Express | amex
Maestro | meastro
Diners Club | diners
Discover | discover
JCB | jcb
UATP | uatp
InterPayment | interpayment
InstaPayment | instapayment
China UnionPay | unionpay
Dankort | dankort


text:
package com.rgpt.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class RGPTParams {
	public static String LOAD_APPLET_REQUEST = "Load Applet Request";
	public static String EDIT_PDF_TEMPLATE_REQUEST = "Edit PDF Template";
	public static String VIEW_PDF_REQUEST = "View PDF Request";
	public static String EDIT_SAVED_PDF_REQUEST = "Edit Save PDF Request";
	public static String APPROVE_PDF_REQUEST = "Approve PDF Request";
	public static String VIEW_IMAGE_ASSETS = "View Customer Assets";
	public static String UPLOAD_BATCH_FILE = "Upload Batch File";
	public static String UPLOAD_PSP_ASSET = "Upload PSP Asset";
	public static String UPLOAD_UPDATED_ASSET = "Upload Updated Asset";
	public static String UPLOAD_DIGITAL_ASSETS = "Upload Digital Assets";

	// Asset Types Supported
	public static String PDF_TEMPLATE_ASSET = "PDF Template Asset";
	public static String FAST_SHOPPING_ASSET = "Fast Shopping Asset";

	public static String m_RequestType;
	public static double m_TransferRate;
	public int m_FrameWidth;
	public int m_FrameHeight;
	public static int m_ServiceIdentifier;
	public static int m_DigitalAssetId;

	// This indicates the Server that will execute the request in the backend.
	public static String m_ServerName;

	// URL from where the Applet got loaded
	public static URL m_AppletURL;

	// This parameters are added by PDFPageInfoManager as place holders to use
	// in future Server Calls
	public static String m_SrcDir;
	public static String m_SerializedFileName;

	// This variables are used to set the PDF Approval with in EBook Viewer
	public static boolean m_ImageBatchUpload;

	// pointer to resource folder
	public static String IMAGE_PATH = "res/pdfviewer/";

	public static Map<String, String> m_RGPTParamValues = new HashMap<String, String>();

	// Default Constructor used by Standalone Application
	public RGPTParams() {
	}

	public static void putVal(String name, String value) {
		m_RGPTParamValues.put(name, value);
	}

	public static String getVal(String name) {
		return getVal(name, "");
	}

	public static String getVal(String name, String defVal) {
		String val = m_RGPTParamValues.get(name);
		if (val == null)
			val = defVal;
		return val;
	}

	public static int getIntVal(String name) {
		String val = m_RGPTParamValues.get(name);
		if (val == null)
			return -1;
		return Integer.parseInt(val);
	}

	public static float getFloatVal(String name) {
		String val = m_RGPTParamValues.get(name);
		if (val == null)
			return 0.0f;
		return Float.parseFloat(val);
	}

	public static boolean getBoolVal(String name) {
		return getBoolVal(name, false);
	}

	public static boolean getBoolVal(String name, boolean defVal) {
		String val = m_RGPTParamValues.get(name);
		if (val == null)
			return defVal;
		return Boolean.parseBoolean(val);
	}

	public static RGPTFileFilter getFileFilter() {
		String name = "file_type";
		String val = m_RGPTParamValues.get(name);
		if (val == null)
			return null;
		return FileFilterFactory.getFileFilter4FileType(val);
	}

	public String toString() {
		StringBuffer mesg = new StringBuffer("Applet Parameters for: "
				+ m_RequestType);
		mesg.append(" is: Service Provider Id: " + m_ServiceIdentifier);
		mesg.append(" Server Name: " + m_ServerName);
		mesg.append(" " + m_RGPTParamValues.toString());
		if (m_AppletURL != null)
			mesg.append("\n URL: " + m_AppletURL.toString());
		return mesg.toString();
	}

	// Server Settings
	public static Properties m_RGPTProperties;

	public static void setServerProperties(Properties servProp) {
		m_RGPTProperties = servProp;
	}

	public static Properties createServerProperties() {
		return createServerProperties(null, false);
	}

	public static Properties createServerProperties(Class<?> caller,
			boolean isServerMode) {
		if (m_RGPTProperties != null)
			return m_RGPTProperties;
		String propFile = null;
		InputStream ipStream = null;
		BufferedInputStream propStream = null;
		try {
			// Read properties file. This will be moved out into a seperate
			// Utility class in future
			if (isServerMode)
				propFile = "res/server_prod.properties";
			else
				propFile = "res/server_dev.properties";
			try {
				ipStream = new FileInputStream(new File(propFile));
			} catch (Exception ex) {
				// ex.printStackTrace();
				propFile = "/" + propFile;
				try {
					ipStream = caller.getResourceAsStream(propFile);
				} catch (Exception exp) {
					exp.printStackTrace();
				}
			}
			if (ipStream == null) {
				System.err.println("Couldn't find file: " + propFile);
				return null;
			}
			m_RGPTProperties = new Properties();
			propStream = new BufferedInputStream(ipStream);
			RGPTLogger.logToConsole("Property Stream Not Null: " + propStream);
			RGPTLogger.logToConsole("Property Stream: "
					+ propStream.available());
			m_RGPTProperties.load(propStream);
			// RGPTLogger.logToConsole("Server Property: " +
			// m_ServerProperties.toString());
			createPropertySet();
			return m_RGPTProperties;
		} catch (Throwable ex) {
			try {
				java.io.FileInputStream fileStream = new java.io.FileInputStream(
						propFile);
				RGPTLogger.logToConsole("Available Size: "
						+ fileStream.available());
				m_RGPTProperties.load(fileStream);
				return m_RGPTProperties;
			} catch (Exception exp) {
				exp.printStackTrace();
				throw new RuntimeException("Unable to Load Server Properties");
			}
		} finally {
			if (ipStream != null) {
				try {
					ipStream.close();
				} catch (Exception ex) {
				}
			}
			if (propStream != null) {
				try {
					propStream.close();
				} catch (Exception ex) {
				}
			}
		}
	}

	public static void createPropertySet() {
		Set<String> propNameSet = m_RGPTProperties.stringPropertyNames();
		RGPTLogger.logToConsole("Prop Name Set Value: " + m_RGPTProperties);
		String[] propNames = propNameSet.toArray(new String[0]);
		for (int i = 0; i < propNames.length; i++) {
			m_RGPTParamValues.put(propNames[i],
					m_RGPTProperties.getProperty(propNames[i]));
		}
		RGPTLogger.logToConsole("Server Properties: " + m_RGPTParamValues);
	}

}


text:
package org.keycloak.federation.ldap;

import org.jboss.logging.Logger;
import org.keycloak.federation.kerberos.impl.KerberosUsernamePasswordAuthenticator;
import org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator;
import org.keycloak.federation.ldap.idm.model.LDAPObject;
import org.keycloak.federation.ldap.idm.query.Condition;
import org.keycloak.federation.ldap.idm.query.QueryParameter;
import org.keycloak.federation.ldap.idm.query.internal.LDAPQuery;
import org.keycloak.federation.ldap.idm.query.internal.LDAPQueryConditionsBuilder;
import org.keycloak.federation.ldap.idm.store.ldap.LDAPIdentityStore;
import org.keycloak.federation.ldap.kerberos.LDAPProviderKerberosConfig;
import org.keycloak.federation.ldap.mappers.LDAPFederationMapper;
import org.keycloak.models.CredentialValidationOutput;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionTask;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.ModelException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserCredentialValueModel;
import org.keycloak.mappers.UserFederationMapper;
import org.keycloak.models.UserFederationMapperModel;
import org.keycloak.models.UserFederationProvider;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.UserFederationSyncResult;
import org.keycloak.models.UserModel;
import org.keycloak.constants.KerberosConstants;
import org.keycloak.models.utils.KeycloakModelUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Marek Posolda
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class LDAPFederationProvider implements UserFederationProvider {
    private static final Logger logger = Logger.getLogger(LDAPFederationProvider.class);

    protected LDAPFederationProviderFactory factory;
    protected KeycloakSession session;
    protected UserFederationProviderModel model;
    protected LDAPIdentityStore ldapIdentityStore;
    protected EditMode editMode;
    protected LDAPProviderKerberosConfig kerberosConfig;

    protected final Set<String> supportedCredentialTypes = new HashSet<>();

    public LDAPFederationProvider(LDAPFederationProviderFactory factory, KeycloakSession session, UserFederationProviderModel model, LDAPIdentityStore ldapIdentityStore) {
        this.factory = factory;
        this.session = session;
        this.model = model;
        this.ldapIdentityStore = ldapIdentityStore;
        this.kerberosConfig = new LDAPProviderKerberosConfig(model);
        this.editMode = ldapIdentityStore.getConfig().getEditMode();

        supportedCredentialTypes.add(UserCredentialModel.PASSWORD);
        if (kerberosConfig.isAllowKerberosAuthentication()) {
            supportedCredentialTypes.add(UserCredentialModel.KERBEROS);
        }
    }

    public KeycloakSession getSession() {
        return session;
    }

    public UserFederationProviderModel getModel() {
        return model;
    }

    public LDAPIdentityStore getLdapIdentityStore() {
        return this.ldapIdentityStore;
    }

    public EditMode getEditMode() {
        return editMode;
    }

    @Override
    public UserModel validateAndProxy(RealmModel realm, UserModel local) {
        LDAPObject ldapObject = loadAndValidateUser(realm, local);
        if (ldapObject == null) {
            return null;
        }

        return proxy(realm, local, ldapObject);
    }

    protected UserModel proxy(RealmModel realm, UserModel local, LDAPObject ldapObject) {
        UserModel proxied = local;
        switch (editMode) {
            case READ_ONLY:
                proxied = new ReadonlyLDAPUserModelDelegate(local, this);
                break;
            case WRITABLE:
                proxied = new WritableLDAPUserModelDelegate(local, this, ldapObject);
                break;
            case UNSYNCED:
                proxied = new UnsyncedLDAPUserModelDelegate(local, this);
        }

        Set<UserFederationMapperModel> federationMappers = realm.getUserFederationMappersByFederationProvider(model.getId());
        for (UserFederationMapperModel mapperModel : federationMappers) {
            LDAPFederationMapper ldapMapper = getMapper(mapperModel);
            proxied = ldapMapper.proxy(mapperModel, this, ldapObject, proxied, realm);
        }

        return proxied;
    }

    @Override
    public Set<String> getSupportedCredentialTypes(UserModel local) {
        Set<String> supportedCredentialTypes = new HashSet<String>(this.supportedCredentialTypes);
        if (editMode == EditMode.UNSYNCED ) {
            for (UserCredentialValueModel cred : local.getCredentialsDirectly()) {
                if (cred.getType().equals(UserCredentialModel.PASSWORD)) {
                    // User has changed password in KC local database. Use KC password instead of LDAP password
                    supportedCredentialTypes.remove(UserCredentialModel.PASSWORD);
                }
            }
        }
        return supportedCredentialTypes;
    }

    @Override
    public Set<String> getSupportedCredentialTypes() {
        return new HashSet<String>(this.supportedCredentialTypes);
    }

    @Override
    public boolean synchronizeRegistrations() {
        return "true".equalsIgnoreCase(model.getConfig().get(LDAPConstants.SYNC_REGISTRATIONS)) && editMode == EditMode.WRITABLE;
    }

    @Override
    public UserModel register(RealmModel realm, UserModel user) {
        if (editMode == EditMode.READ_ONLY || editMode == EditMode.UNSYNCED) throw new IllegalStateException("Registration is not supported by this ldap server");
        if (!synchronizeRegistrations()) throw new IllegalStateException("Registration is not supported by this ldap server");

        LDAPObject ldapUser = LDAPUtils.addUserToLDAP(this, realm, user);
        LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());
        user.setSingleAttribute(LDAPConstants.LDAP_ID, ldapUser.getUuid());
        user.setSingleAttribute(LDAPConstants.LDAP_ENTRY_DN, ldapUser.getDn().toString());

        return proxy(realm, user, ldapUser);
    }

    @Override
    public boolean removeUser(RealmModel realm, UserModel user) {
        if (editMode == EditMode.READ_ONLY || editMode == EditMode.UNSYNCED) {
            logger.warnf("User '%s' can't be deleted in LDAP as editMode is '%s'", user.getUsername(), editMode.toString());
            return false;
        }

        LDAPObject ldapObject = loadAndValidateUser(realm, user);
        if (ldapObject == null) {
            logger.warnf("User '%s' can't be deleted from LDAP as it doesn't exist here", user.getUsername());
            return false;
        }

        ldapIdentityStore.remove(ldapObject);
        return true;
    }

    @Override
    public List<UserModel> searchByAttributes(Map<String, String> attributes, RealmModel realm, int maxResults) {
        List<UserModel> searchResults =new LinkedList<UserModel>();

        List<LDAPObject> ldapUsers = searchLDAP(realm, attributes, maxResults);
        for (LDAPObject ldapUser : ldapUsers) {
            String ldapUsername = LDAPUtils.getUsername(ldapUser, this.ldapIdentityStore.getConfig());
            if (session.userStorage().getUserByUsername(ldapUsername, realm) == null) {
                UserModel imported = importUserFromLDAP(session, realm, ldapUser);
                searchResults.add(imported);
            }
        }

        return searchResults;
    }

    protected List<LDAPObject> searchLDAP(RealmModel realm, Map<String, String> attributes, int maxResults) {

        List<LDAPObject> results = new ArrayList<LDAPObject>();
        if (attributes.containsKey(USERNAME)) {
            LDAPObject user = loadLDAPUserByUsername(realm, attributes.get(USERNAME));
            if (user != null) {
                results.add(user);
            }
        }

        if (attributes.containsKey(EMAIL)) {
            LDAPObject user = queryByEmail(realm, attributes.get(EMAIL));
            if (user != null) {
                results.add(user);
            }
        }

        if (attributes.containsKey(FIRST_NAME) || attributes.containsKey(LAST_NAME)) {
            LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm);
            LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();

            // Mapper should replace parameter with correct LDAP mapped attributes
            if (attributes.containsKey(FIRST_NAME)) {
                ldapQuery.where(conditionsBuilder.equal(new QueryParameter(FIRST_NAME), attributes.get(FIRST_NAME)));
            }
            if (attributes.containsKey(LAST_NAME)) {
                ldapQuery.where(conditionsBuilder.equal(new QueryParameter(LAST_NAME), attributes.get(LAST_NAME)));
            }

            List<LDAPObject> ldapObjects = ldapQuery.getResultList();
            results.addAll(ldapObjects);
        }

        return results;
    }

    /**
     * @param local
     * @return ldapUser corresponding to local user or null if user is no longer in LDAP
     */
    protected LDAPObject loadAndValidateUser(RealmModel realm, UserModel local) {
        LDAPObject ldapUser = loadLDAPUserByUsername(realm, local.getUsername());
        if (ldapUser == null) {
            return null;
        }
        LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());

        if (ldapUser.getUuid().equals(local.getFirstAttribute(LDAPConstants.LDAP_ID))) {
            return ldapUser;
        } else {
            logger.warnf("LDAP User invalid. ID doesn't match. ID from LDAP [%s], LDAP ID from local DB: [%s]", ldapUser.getUuid(), local.getFirstAttribute(LDAPConstants.LDAP_ID));
            return null;
        }
    }

    @Override
    public boolean isValid(RealmModel realm, UserModel local) {
        return loadAndValidateUser(realm, local) != null;
    }

    @Override
    public UserModel getUserByUsername(RealmModel realm, String username) {
        LDAPObject ldapUser = loadLDAPUserByUsername(realm, username);
        if (ldapUser == null) {
            return null;
        }

        return importUserFromLDAP(session, realm, ldapUser);
    }

    protected UserModel importUserFromLDAP(KeycloakSession session, RealmModel realm, LDAPObject ldapUser) {
        String ldapUsername = LDAPUtils.getUsername(ldapUser, ldapIdentityStore.getConfig());
        LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());

        UserModel imported = session.userStorage().addUser(realm, ldapUsername);
        imported.setEnabled(true);

        Set<UserFederationMapperModel> federationMappers = realm.getUserFederationMappersByFederationProvider(getModel().getId());
        for (UserFederationMapperModel mapperModel : federationMappers) {
            if (logger.isTraceEnabled()) {
                logger.tracef("Using mapper %s during import user from LDAP", mapperModel);
            }
            LDAPFederationMapper ldapMapper = getMapper(mapperModel);
            ldapMapper.onImportUserFromLDAP(mapperModel, this, ldapUser, imported, realm, true);
        }

        String userDN = ldapUser.getDn().toString();
        imported.setFederationLink(model.getId());
        imported.setSingleAttribute(LDAPConstants.LDAP_ID, ldapUser.getUuid());
        imported.setSingleAttribute(LDAPConstants.LDAP_ENTRY_DN, userDN);

        logger.debugf("Imported new user from LDAP to Keycloak DB. Username: [%s], Email: [%s], LDAP_ID: [%s], LDAP Entry DN: [%s]", imported.getUsername(), imported.getEmail(),
                ldapUser.getUuid(), userDN);
        return proxy(realm, imported, ldapUser);
    }

    protected LDAPObject queryByEmail(RealmModel realm, String email) {
        LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm);
        LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();

        // Mapper should replace "email" in parameter name with correct LDAP mapped attribute
        Condition emailCondition = conditionsBuilder.equal(new QueryParameter(UserModel.EMAIL), email);
        ldapQuery.where(emailCondition);

        return ldapQuery.getFirstResult();
    }

    @Override
    public UserModel getUserByEmail(RealmModel realm, String email) {
        LDAPObject ldapUser = queryByEmail(realm, email);
        if (ldapUser == null) {
            return null;
        }

        // Check here if user already exists
        String ldapUsername = LDAPUtils.getUsername(ldapUser, ldapIdentityStore.getConfig());
        if (session.userStorage().getUserByUsername(ldapUsername, realm) != null) {
            throw new ModelDuplicateException("User with username '" + ldapUsername + "' already exists in Keycloak. It conflicts with LDAP user with email '" + email + "'");
        }

        return importUserFromLDAP(session, realm, ldapUser);
    }

    @Override
    public void preRemove(RealmModel realm) {
        // complete Don't think we have to do anything
    }

    @Override
    public void preRemove(RealmModel realm, RoleModel role) {
        // TODO: Maybe mappers callback to ensure role deletion propagated to LDAP by RoleLDAPFederationMapper?
    }

    public boolean validPassword(RealmModel realm, UserModel user, String password) {
        if (kerberosConfig.isAllowKerberosAuthentication() && kerberosConfig.isUseKerberosForPasswordAuthentication()) {
            // Use Kerberos JAAS (Krb5LoginModule)
            KerberosUsernamePasswordAuthenticator authenticator = factory.createKerberosUsernamePasswordAuthenticator(kerberosConfig);
            return authenticator.validUser(user.getUsername(), password);
        } else {
            // Use Naming LDAP API
            LDAPObject ldapUser = loadAndValidateUser(realm, user);
            return ldapIdentityStore.validatePassword(ldapUser, password);
        }
    }

    @Override
    public boolean validCredentials(RealmModel realm, UserModel user, List<UserCredentialModel> input) {
        for (UserCredentialModel cred : input) {
            if (cred.getType().equals(UserCredentialModel.PASSWORD)) {
                return validPassword(realm, user, cred.getValue());
            } else {
                return false; // invalid cred type
            }
        }
        return true;
    }

    @Override
    public boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input) {
        return validCredentials(realm, user, Arrays.asList(input));
    }

    @Override
    public CredentialValidationOutput validCredentials(RealmModel realm, UserCredentialModel credential) {
        if (credential.getType().equals(UserCredentialModel.KERBEROS)) {
            if (kerberosConfig.isAllowKerberosAuthentication()) {
                String spnegoToken = credential.getValue();
                SPNEGOAuthenticator spnegoAuthenticator = factory.createSPNEGOAuthenticator(spnegoToken, kerberosConfig);

                spnegoAuthenticator.authenticate();

                Map<String, String> state = new HashMap<String, String>();
                if (spnegoAuthenticator.isAuthenticated()) {

                    // TODO: This assumes that LDAP "uid" is equal to kerberos principal name. Like uid "hnelson" and kerberos principal "hnelson@KEYCLOAK.ORG".
                    // Check if it's correct or if LDAP attribute for mapping kerberos principal should be available (For ApacheDS it seems to be attribute "krb5PrincipalName" but on MSAD it's likely different)
                    String username = spnegoAuthenticator.getAuthenticatedUsername();
                    UserModel user = findOrCreateAuthenticatedUser(realm, username);

                    if (user == null) {
                        logger.warnf("Kerberos/SPNEGO authentication succeeded with username [%s], but couldn't find or create user with federation provider [%s]", username, model.getDisplayName());
                        return CredentialValidationOutput.failed();
                    } else {
                        String delegationCredential = spnegoAuthenticator.getSerializedDelegationCredential();
                        if (delegationCredential != null) {
                            state.put(KerberosConstants.GSS_DELEGATION_CREDENTIAL, delegationCredential);
                        }

                        return new CredentialValidationOutput(user, CredentialValidationOutput.Status.AUTHENTICATED, state);
                    }
                }  else {
                    state.put(KerberosConstants.RESPONSE_TOKEN, spnegoAuthenticator.getResponseToken());
                    return new CredentialValidationOutput(null, CredentialValidationOutput.Status.CONTINUE, state);
                }
            }
        }

        return CredentialValidationOutput.failed();
    }

    @Override
    public void close() {
    }

    /**
     * Called after successful kerberos authentication
     *
     * @param realm realm
     * @param username username without realm prefix
     * @return finded or newly created user
     */
    protected UserModel findOrCreateAuthenticatedUser(RealmModel realm, String username) {
        UserModel user = session.userStorage().getUserByUsername(username, realm);
        if (user != null) {
            logger.debugf("Kerberos authenticated user [%s] found in Keycloak storage", username);
            if (!model.getId().equals(user.getFederationLink())) {
                logger.warnf("User with username [%s] already exists, but is not linked to provider [%s]", username, model.getDisplayName());
                return null;
            } else {
                LDAPObject ldapObject = loadAndValidateUser(realm, user);
                if (ldapObject != null) {
                    return proxy(realm, user, ldapObject);
                } else {
                    logger.warnf("User with username [%s] aready exists and is linked to provider [%s] but is not valid. Stale LDAP_ID on local user is: %s",
                            username,  model.getDisplayName(), user.getFirstAttribute(LDAPConstants.LDAP_ID));
                    logger.warn("Will re-create user");
                    session.userStorage().removeUser(realm, user);
                }
            }
        }

        // Creating user to local storage
        logger.debugf("Kerberos authenticated user [%s] not in Keycloak storage. Creating him", username);
        return getUserByUsername(realm, username);
    }

    public LDAPObject loadLDAPUserByUsername(RealmModel realm, String username) {
        LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm);
        LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();

        String usernameMappedAttribute = this.ldapIdentityStore.getConfig().getUsernameLdapAttribute();
        Condition usernameCondition = conditionsBuilder.equal(new QueryParameter(usernameMappedAttribute), username);
        ldapQuery.where(usernameCondition);

        LDAPObject ldapUser = ldapQuery.getFirstResult();
        if (ldapUser == null) {
            return null;
        }

        return ldapUser;
    }

    public LDAPFederationMapper getMapper(UserFederationMapperModel mapperModel) {
        LDAPFederationMapper ldapMapper = (LDAPFederationMapper) getSession().getProvider(UserFederationMapper.class, mapperModel.getFederationMapperType());
        if (ldapMapper == null) {
            throw new ModelException("Can't find mapper type with ID: " + mapperModel.getFederationMapperType());
        }

        return ldapMapper;
    }
}


text:
/**
 * @file
 * @author  Jan Olszak (j.olszak@samsung.com)
 * @brief   Synchronization latch
 */

#include "config.hpp"

#include "utils/typeinfo.hpp"

#include <string>
#include <cxxabi.h>
#include <stdexcept>

namespace utils {

std::string getTypeName(const std::type_info& ti)
{
    int status;
    char* demangled = abi::__cxa_demangle(ti.name() , 0, 0, &status);
    if (status) {
        std::string message = "abi::__cxa_demangle failed with ret code: " + std::to_string(status);
        throw std::runtime_error(message);
    }

    std::string ret(demangled);
    free(demangled);
    return ret;
}

} // namespace utils