text:
#ifndef Vsa_IEvaluatorPool_Ex3_Interface
#define Vsa_IEvaluatorPool_Ex3_Interface

#ifndef Vsa_IEvaluatorPool_Ex3
#define Vsa_IEvaluatorPool_Ex3 extern
#endif

/*********************
 *****  Library  *****
 *********************/

#include "Vsa.h"

/************************
 *****  Components  *****
 ************************/

#include "Vsa_IEvaluatorPool_Ex2.h"

/**************************
 *****  Declarations  *****
 **************************/

class VString;

VINTERFACE_TEMPLATE_INSTANTIATIONS (Vsa,IEvaluatorPool_Ex3)

/*************************
 *****  Definitions  *****
 *************************/

namespace Vsa {
    VINTERFACE_ROLE (IEvaluatorPool_Ex3, IEvaluatorPool_Ex2)
        VINTERFACE_ROLE_3 (TakeWorkerOffline, VString const &, bool, IVReceiver<VString const &>*);
        VINTERFACE_ROLE_3 (MakeWorkerOnline, VString const &, bool, IVReceiver<VString const &>*);
        VINTERFACE_ROLE_4 (EvaluateUsingOfflineWorker, VString const &, VString const &, bool, IEvaluatorClient *);
        VINTERFACE_ROLE_3 (RetireOfflineWorker, VString const &, bool, IVReceiver<VString const &>*);

        VINTERFACE_ROLE_3 (DumpPoolQueue, VString const &, Vca::U32, IVReceiver<VString const &>*);
        VINTERFACE_ROLE_2 (DumpWorkingWorkers, VString const &, IVReceiver<VString const &>*);
        VINTERFACE_ROLE_4 (DumpWorker, VString const &, bool, VString const &, IVReceiver<VString const &>*);

        VINTERFACE_ROLE_3 (GetWorker_Ex, VString const &, bool, IVReceiver<IVUnknown*>*);
        VINTERFACE_ROLE_1 (GetWorkersStatistics, IVReceiver<VString const&>*);
        VINTERFACE_ROLE_2 (GetGenerationStatistics, Vca::U32, IVReceiver<VString const&>*);
    VINTERFACE_ROLE_END

    /**
     * @class IEvaluatorPool_Ex3
     *
     * Pool interface extension 3; adds several worker and stats operations.
     */
    VsaINTERFACE (IEvaluatorPool_Ex3, IEvaluatorPool_Ex2);
        /**
         * Sends a directive to take a worker offline to the pool.
         *
         * @param p1 the worker ID.
         * @param p2 true if P2 is specified using a PID, false if pool-internal worker ID format is used.
         * @param p3 receiver for the return message from the pool.
         */
        VINTERFACE_METHOD_3 (TakeWorkerOffline, VString const &, bool, IVReceiver<VString const &>*);
        /**
         * Sends a directive to make an offline worker online to a pool.
         *
         * @param p1 the worker ID.
         * @param p2 true if P2 is specified using a PID, false if pool-internal worker ID format is used.
         * @param p3 receiver for the return message from the pool.
         */
        VINTERFACE_METHOD_3 (MakeWorkerOnline, VString const &, bool, IVReceiver<VString const &>*);
        /**
         * Requests that the pool use a particular offline worker to evaluate a given query.
         *
         * @param p1 the query string.
         * @param p2 the worker ID.
         * @param p3 true if P2 is specified using a PID, false if pool-internal worker ID format is used.
         * @param p4 the IEvaluatorClient that the pool should send query results to.
         */
        VINTERFACE_METHOD_4 (EvaluateUsingOfflineWorker, VString const &, VString const &, bool, IEvaluatorClient *);
        /**
         * Sends a directive to retire an offline worker to the pool.
         *
         * @param p1 the worker ID.
         * @param p2 true if P2 is specified using a PID, false if pool-internal worker ID format is used.
         * @param p3 receiver for the return message from the pool.
         */
        VINTERFACE_METHOD_3 (RetireOfflineWorker, VString const &, bool, IVReceiver<VString const &>*);

        /**
         * Dumps this pool's queue information to a file.
         *
         * @param p1 the filename to dump to.
         * @param p2 currently unused.
         * @param p3 receiver for the return message from the pool.
         */
        VINTERFACE_METHOD_3 (DumpPoolQueue, VString const &, Vca::U32, IVReceiver<VString const &>*);
        /**
         * Dumps this pool's working worker statistics to a file.
         *
         * @param p1 the filename to dump to.
         * @param p2 receiver for the return message from the pool.
         */
        VINTERFACE_METHOD_2 (DumpWorkingWorkers, VString const &, IVReceiver<VString const &>*);
        /**
         * Dumps a worker's statistics to a file.
         *
         * @param p1 the worker ID.
         * @param p2 true if P2 is specified using a PID, false if pool-internal worker ID format is used.
         * @param p3 the filename to dump to.
         * @param p4 receiver for the return message from the pool.
         */
        VINTERFACE_METHOD_4 (DumpWorker, VString const &, bool, VString const &, IVReceiver<VString const &>*);

        /**
         * Retrieves a worker interface given a worker ID.
         *
         * @param p1 the worker ID.
         * @param p2 true if P2 is specified using a PID, false if pool-internal worker ID format is used.
         * @param p3 receiver for the interface to be returned by the pool.
         */
        VINTERFACE_METHOD_3 (GetWorker_Ex, VString const &, bool, IVReceiver<IVUnknown*>*);
        /**
         * Requests worker statistics from the pool.
         *
         * @param p1 receiver for the worker statistics to be returned by the pool.
         */
        VINTERFACE_METHOD_1 (GetWorkersStatistics, IVReceiver<VString const&>*);
        /**
         * Requests generation statistics from the pool.
         *
         * @param p1 receiver for the generation statistics to be returned by the pool.
         */
        VINTERFACE_METHOD_2 (GetGenerationStatistics, Vca::U32, IVReceiver<VString const&>*);
    VINTERFACE_END
}

#endif


text:
class CChatWindow : public CDialog
{
// Construction
public:
	void sendChat( CString text );
	CChatWindow(CWnd* pParent = NULL, bool bEcho = TRUE );   // standard constructor

	void putOldText( String oldText );
	void addNewMessage( const MetaClient::Chat chat );

// Dialog Data
	//{{AFX_DATA(CChatWindow)
	enum { IDD = IDD_CHATWINDOW_DIALOG };
		// NOTE: the ClassWizard will add data members here
	//}}AFX_DATA

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CChatWindow)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	void OnCancel();
	void OnOK();

	// Generated message map functions
	//{{AFX_MSG(CChatWindow)
	virtual BOOL OnInitDialog();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()

private:
	CChatView			*m_wndChatView;
	CChatEdit			m_wndChatEdit;
	bool				m_bEcho;
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_CHATWINDOW_H__A50D4281_70FF_11D7_9412_00001CDB2E9A__INCLUDED_)

redpajama_set_name: RedPajamaGithub


text:
require "spec_helper"
require "nutella/core_ext/object"

describe Object do
  describe "aliases" do
    test_alias Object, :is_an?, :is_a?
  end

  describe "#blank?" do
    it "is blank when nil" do
      expect(nil).to be_blank
    end

    it "is blank when false" do
      expect(false).to be_blank
    end

    it "is not blank when true" do
      expect(true).not_to be_blank
    end

    it "is not blank when numeric" do
      [0, 1].each { |n| expect(n).not_to be_blank }
    end

    context "when a string" do
      it "is blank if the string is empty" do
        expect("").to be_blank
      end

      it "is blank if only whitespace" do
        ["  ", "\n  \t"].each { |str| expect(str).to be_blank }
        expect("  something here  ").not_to be_blank
      end

      it "is not blank if the string has content" do
        expect("string").not_to be_blank
      end
    end

    context "when a collection" do
      it "is blank if the collection is empty" do
        [[], {}].each { |collection| expect(collection).to be_blank }
      end

      it "is not blank if there are elements in the collection" do
        [[1, 2, 3], { 1 => 2, 3 => 4 }].each do |collection|
          expect(collection).not_to be_blank
        end
      end
    end
  end

  describe "#present?" do
    it "is the inverse of #blank?" do
      [0, 1].each { |n| expect(n).to be_present }
      [[], {}].each { |collection| expect(collection).not_to be_present }
      ["", "  "].each { |str| expect(str).not_to be_present }
      ["str", "  str "].each { |str| expect(str).to be_present }
    end
  end

  describe "#presence" do
    it "returns the object if the object is present" do
      expect(1.presence).to eq(1)
      expect("str".presence).to eq("str")
    end

    it "returns nil if the object is not present" do
      expect("".presence).to be_nil
      expect(false.presence).to be_nil
    end
  end
end


text:
package org.apache.curator.framework.recipes.locks;

public interface LockInternalsSorter
{
    public String           fixForSorting(String str, String lockName);
}


text:
package org.springframework.jmx.support;

/**
 * Indicates registration behavior when attempting to register an MBean that already
 * exists.
 *
 * @author Phillip Webb
 * @author Chris Beams
 * @since 3.2
 */
public enum RegistrationPolicy {

	/**
	 * Registration should fail when attempting to register an MBean under a name that
	 * already exists.
	 */
	FAIL_ON_EXISTING,

	/**
	 * Registration should ignore the affected MBean when attempting to register an MBean
	 * under a name that already exists.
	 */
	IGNORE_EXISTING,

	/**
	 * Registration should replace the affected MBean when attempting to register an MBean
	 * under a name that already exists.
	 */
	REPLACE_EXISTING;

	/**
	 * Translate from an {@link MBeanRegistrationSupport} registration behavior constant
	 * to a {@link RegistrationPolicy} enum value.
	 * @param registrationBehavior one of the now-deprecated REGISTRATION_* constants
	 * available in {@link MBeanRegistrationSupport}.
	 */
	@SuppressWarnings("deprecation")
	static RegistrationPolicy valueOf(int registrationBehavior) {
		switch (registrationBehavior) {
			case MBeanRegistrationSupport.REGISTRATION_IGNORE_EXISTING:
				return RegistrationPolicy.IGNORE_EXISTING;
			case MBeanRegistrationSupport.REGISTRATION_REPLACE_EXISTING:
				return RegistrationPolicy.REPLACE_EXISTING;
			case MBeanRegistrationSupport.REGISTRATION_FAIL_ON_EXISTING:
				return RegistrationPolicy.FAIL_ON_EXISTING;
		}
		throw new IllegalArgumentException(
				"Unknown MBean registration behavior: " + registrationBehavior);
	}

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Dept. Agric. Porto Rico 16: 178 (1932)

#### Original name
Phyllachora tetraspora Chardón, 1932

### Remarks
null


text:
using System;
using System.Diagnostics;
using UnionFind;

long lastTimeQuickFind = 0;
long lastTimeQuickUnion = 0;
long lastTimeWeightedQuickUnion = 0;
for (var n = 2000; n < 100000; n *= 2)
{
    Console.WriteLine("N:" + n);
    var quickFindUf = new QuickFindUf(n);
    var quickUnionUf = new QuickUnionUf(n);
    var weightedQuickUnionUf = new WeightedQuickUnionUf(n);

    // quick-find
    Console.WriteLine("quick-find");
    var nowTime = RunTest(quickFindUf);
    if (lastTimeQuickFind == 0)
    {
        Console.WriteLine("用时:" + nowTime);
        lastTimeQuickFind = nowTime;
    }
    else
    {
        Console.WriteLine("用时:" + nowTime + " 比值:" + (double)nowTime / lastTimeQuickFind);
        lastTimeQuickFind = nowTime;
    }

    Console.WriteLine();

    // quick-union
    Console.WriteLine("quick-union");
    nowTime = RunTest(quickUnionUf);
    if (lastTimeQuickUnion == 0)
    {
        Console.WriteLine("用时:" + nowTime);
        lastTimeQuickUnion = nowTime;
    }
    else
    {
        Console.WriteLine("用时:" + nowTime + " 比值:" + (double)nowTime / lastTimeQuickUnion);
        lastTimeQuickUnion = nowTime;
    }

    Console.WriteLine();

    // weighted-quick-union
    Console.WriteLine("weighted-quick-union");
    nowTime = RunTest(weightedQuickUnionUf);
    if (lastTimeWeightedQuickUnion == 0)
    {
        Console.WriteLine("用时:" + nowTime);
        lastTimeWeightedQuickUnion = nowTime;
    }
    else
    {
        Console.WriteLine("用时:" + nowTime + " 比值:" + (double)nowTime / lastTimeWeightedQuickUnion);
        lastTimeWeightedQuickUnion = nowTime;
    }

    Console.WriteLine();

    Console.WriteLine();
}

// 进行若干次随机试验,输出平均 union 次数,返回平均耗时。
static long RunTest(Uf uf)
{
    var timer = new Stopwatch();
    var total = 0;
    var repeatTime = 10;
    timer.Start();
    for (var i = 0; i < repeatTime; i++)
    {
        total += ErdosRenyi.Count(uf);
    }

    timer.Stop();
    Console.WriteLine("平均次数:" + total / repeatTime);

    return timer.ElapsedMilliseconds / repeatTime;
}


text:
<!doctype html>

		<meta charset="utf-8">
		<title>HTML5 Shiv</title>
		<link rel="stylesheet" href="style.css">

This sentence has 3px solid border with these words highlighted.

static swfobject

			<object id="static-id" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="480" height="420">
				<param name="movie" value="data/paramtracer.swf">

					<object type="application/x-shockwave-flash" data="data/paramtracer.swf" width="480" height="420">

						<param name="flashvars" value="aFlashVar=aFlashVarValue">
						<param name="wmode" value="transparent">

					</object>

			</object>

dynamic swfobject

innerHTML object

			<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="480" height="420">
				<param name="movie" value="data/paramtracer.swf">

					<object type="application/x-shockwave-flash" data="data/paramtracer.swf" width="480" height="420">

						<param name="flashvars" value="aFlashVar=aFlashVarValue">
						<param name="wmode" value="transparent">

					</object>

			</object>


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<script src="script-tests/canvas-scale-drawImage-shadow.js"></script>
</body>
</html>


text:
*Topic automatically generated on: 2015-06-11*

Returns a stored credential from the Windows Credential Manager
##Syntax
```powershell
Get-SPOStoredCredential -Name <String> [-Type <CredentialType>]
```

##Parameters
Parameter|Type|Required|Description
---------|----|--------|-----------
|Name|String|True|The credential to retrieve.|
|Type|CredentialType|False|The object type of the credential to return from the Credential Manager. Possible valus are 'O365', 'OnPrem' or 'PSCredential'|
##Examples

###Example 1
    PS:> Get-SPOnlineStoredCredential -Name O365
Returns the credential associated with the specified identifier
<!-- Ref: 215D94FE875F661197E31D96027B8A40 -->


text:
describe('Check battery levels, charging, development version', function() {
  beforeEach(function() {
    browser.get('http://localhost:3000/test/pages/charging.html');
  });

  it('should have battery-level element', function() {
    expect(element(by.tagName('battery-level')).isPresent()).toBe(true);
  });

  it('should have battery-icon element', function() {
    expect(element(by.tagName('battery-icon')).isPresent()).toBe(true);
  });

  /*
   Levels to test

    Charging:
    20, 30, 50, 60, 80, 90
    full
    unknown
   */

  it('should not have alert icon', function() {
    var levelElement = element(by.tagName('battery-level'));
    var icon = element(by.tagName('battery-icon'));
    var input = element(by.model('level'));

    for(var i = -2; i < 10; i++) {
      input.clear();
      input.sendKeys(i);
      expect(icon.getAttribute('icon')).not.toEqual('battery_alert');
    }
  });

  it('should have 20% charge', function() {
    var levelElement = element(by.tagName('battery-level'));
    var icon = element(by.tagName('battery-icon'));
    var input = element(by.model('level'));

    for(var i = 10; i < 30; i++) {
      input.clear();
      input.sendKeys(i);
      expect(icon.getAttribute('icon')).toEqual('battery_charging_20');
    }
  });

  it('should have 30% charge', function() {
    var levelElement = element(by.tagName('battery-level'));
    var icon = element(by.tagName('battery-icon'));
    var input = element(by.model('level'));

    for(var i = 30; i < 50; i++) {
      input.clear();
      input.sendKeys(i);
      expect(icon.getAttribute('icon')).toEqual('battery_charging_30');
    }
  });

  it('should have 50% charge', function() {
    var levelElement = element(by.tagName('battery-level'));
    var icon = element(by.tagName('battery-icon'));
    var input = element(by.model('level'));

    for(var i = 50; i < 60; i++) {
      input.clear();
      input.sendKeys(i);
      expect(icon.getAttribute('icon')).toEqual('battery_charging_50');
    }
  });

  it('should have 60% charge', function() {
    var levelElement = element(by.tagName('battery-level'));
    var icon = element(by.tagName('battery-icon'));
    var input = element(by.model('level'));

    for(var i = 60; i < 80; i++) {
      input.clear();
      input.sendKeys(i);
      expect(icon.getAttribute('icon')).toEqual('battery_charging_60');
    }
  });

  it('should have 80% charge', function() {
    var levelElement = element(by.tagName('battery-level'));
    var icon = element(by.tagName('battery-icon'));
    var input = element(by.model('level'));

    for(var i = 80; i < 90; i++) {
      input.clear();
      input.sendKeys(i);
      expect(icon.getAttribute('icon')).toEqual('battery_charging_80');
    }
  });

  it('should have 90% charge', function() {
    var levelElement = element(by.tagName('battery-level'));
    var icon = element(by.tagName('battery-icon'));
    var input = element(by.model('level'));

    for(var i = 90; i < 100; i++) {
      input.clear();
      input.sendKeys(i);
      expect(icon.getAttribute('icon')).toEqual('battery_charging_90');
    }
  });

  it('should have full charge', function() {
    var levelElement = element(by.tagName('battery-level'));
    var icon = element(by.tagName('battery-icon'));
    var input = element(by.model('level'));

    input.clear();
    input.sendKeys(100);
    expect(icon.getAttribute('icon')).toEqual('battery_charging_full');

    input.clear();
    input.sendKeys(120);
    expect(icon.getAttribute('icon')).toEqual('battery_charging_full');
  });

});


text:
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string name="label_application">HQ Lighttts</string>

    <string name="appwidget_light_refresh_content_description">Refresh</string>
    <string name="appwidget_timestamp">Last updated at %1$s</string>
    <string name="appwidget_light_failure">Failed to fetch status</string>

</resources>


text:
package org.purl.accessor.purl.command;

import org.ten60.netkernel.layer1.nkf.INKFConvenienceHelper;
import org.ten60.netkernel.layer1.nkf.INKFResponse;
import org.ten60.netkernel.xml.representation.IAspectXDA;
import org.ten60.netkernel.xml.xda.IXDAReadOnly;
import org.apache.commons.lang.StringEscapeUtils;
import com.ten60.netkernel.urii.IURRepresentation;

public class PURLPartialRedirectResolveCommand extends PURLResolveCommand {

    private boolean ignoreExtension = false;

    public PURLPartialRedirectResolveCommand(boolean ignoreExtension) {
        this.ignoreExtension = ignoreExtension;

    }

    @Override
    public INKFResponse execute(INKFConvenienceHelper context, IAspectXDA purl) {
        INKFResponse resp = null;
        IXDAReadOnly purlXDARO = purl.getXDA();
        try {
            String path = context.getThisRequest().getArgument("path").substring(6);

            String pid = purlXDARO.getText("/purl/id", true);
            String url = purlXDARO.getText("/purl/target/url", true);
            String queryChar = "?";
            if(!path.equals(pid)) {
                String remainder =  path.substring(pid.length());
                if (url.contains(queryChar)) {

                    if (remainder.contains(queryChar)) {
                        remainder = remainder.replaceFirst("\\?", "&");
                        queryChar="&";
                    }
                    if (remainder.startsWith("/")) {
                        remainder = remainder.replaceFirst("/", "");
                    }
                }
                if (ignoreExtension) {
                    String query = "";
                    if (remainder.contains(queryChar)) {
                        query = remainder.substring(remainder.indexOf(queryChar));
                        remainder = remainder.substring(0, remainder.indexOf(queryChar));
                    }
                    if (remainder.contains(".")) {
                        remainder = remainder.substring(0,remainder.lastIndexOf('.'));
                    }
                    remainder = remainder+query;
                }
                url = url + remainder;
            }

            IURRepresentation bodyDoc = context.source("ffcpl:/pub/redirect.html");

            // We treat the partial redirect as a 302
            resp = generateResponseCode(context, "302", url,
                    parameterizeBodyDoc(context, bodyDoc, "302", url),
                    "text/html; charset=iso-8859-1");

        } catch(Throwable t) {
            t.printStackTrace();
        }
        return resp;
    }

}


text:
{% extends 'base.html' %}
{% load gravatar_url_resolver %}
{% load crispy_forms_tags %}
{% load render_bundle from webpack_loader %}

{% block styles %}
    {{ block.super }}
    {% render_bundle 'profiles' 'css' %}
{% endblock %}

{% block title %}
    Finn brukere - Online
{% endblock title %}

{% block content %}

Brukersøk

Her kan du søke i brukere og komitemedlemmer. Brukere som har skjult profilen sin vil ikke dukke opp her.

			<form action="" role="search" method="get">
				<input type="text" id="search-users" autocomplete="off" name="search-users" placeholder="Søk etter bruker" />
			</form>

			{% for group in groups %}

{{ group }}

					{% for user in group.user_set.all %}
						{% if user.privacy.visible_for_other_users %}

											{% gravatar_url user 120 as gravatar_url %}

{{ user.get_full_name|striptags }}

											Telefon
											{% if user.privacy.expose_phone_number %}
												{% firstof user.phone_number|striptags 'Ikke tilgjengelig' %}
											{% else %}
												Ikke tilgjengelig
											{% endif %}

											Epost {% if user.privacy.expose_email %}
												{% firstof user.get_email.email|striptags 'Ikke tilgjengelig' %}
											{% else %}
												Ikke tilgjenglig
											{% endif %}

						{% endif %}
					{% endfor %}

			{% endfor %}

Laster inn profilbilder...

					{% for group in groups %}

							{{ group }}

					{% endfor %}

{% endblock %}

{% block js %}
    {{ block.super }}
    {% render_bundle 'profiles' 'js' %}
{% endblock %}


text:
#ifndef WebKitWebRes_h
#define WebKitWebRes_h

namespace content {

extern char calendarPickerCss[4046];
extern char calendarPickerJs[83088];
extern char colorSuggestionPickerCss[596];
extern char colorSuggestionPickerJs[4098];
extern char listPickerCss[190];
extern char listPickerJs[12829];
extern char pickerButtonCss[1165];
extern char pickerCommonCss[124];
extern char pickerCommonJs[5723];
extern char suggestionPickerCss[750];
extern char suggestionPickerJs[8952];
extern char PrivateScriptRunnerJs[4109];
extern char HTMLMarqueeElementJs[14511];
extern char PluginPlaceholderElementJs[4296];
extern char DebuggerScriptSourceJs[19016];
extern char InspectorOverlayPageHtml[26549];
extern char InjectedScriptSourceJs[70694];
extern char fullscreenCss[1531];

}

#endif // WebKitWebRes_h


text:
#import "YLProgressBar.h"

#import "ARCMacro.h"

// Sizes
#define YLProgressBarSizeInset              1
#define YLProgressBarSizeStripeWidth        7

// Colors
#define YLProgressBarColorBackground        [UIColor colorWithRed:0.0980f green:0.1137f blue:0.1294f alpha:1.0f]
#define YLProgressBarColorBackgroundGlow    [UIColor colorWithRed:0.0666f green:0.0784f blue:0.0901f alpha:1.0f]

@interface YLProgressBar ()
{
    UIColor* _progressTintColor;
    UIColor* _progressTintColorDark;
}
@property (nonatomic, assign)               double      progressOffset;
@property (nonatomic, assign)               CGFloat     cornerRadius;
@property (nonatomic, SAFE_ARC_PROP_RETAIN) NSTimer*    animationTimer;

/** Init the progress bar. */
- (void)initializeProgressBar;

/** Build the stripes. */
- (UIBezierPath *)stripeWithOrigin:(CGPoint)origin bounds:(CGRect)frame;

/** Draw the background (track) of the slider. */
- (void)drawBackgroundWithRect:(CGRect)rect;
/** Draw the progress bar. */
- (void)drawProgressBarWithRect:(CGRect)rect;
/** Draw the gloss into the given rect. */
- (void)drawGlossWithRect:(CGRect)rect;
/** Draw the stipes into the given rect. */
- (void)drawStripesWithRect:(CGRect)rect;

@end

@implementation YLProgressBar
@synthesize progressOffset, cornerRadius, animationTimer;
@synthesize animated;

- (void)dealloc
{
    if (animationTimer && [animationTimer isValid])
    {
        [animationTimer invalidate];
    }

    SAFE_ARC_RELEASE (animationTimer);
    SAFE_ARC_RELEASE (_progressTintColor);
    SAFE_ARC_RELEASE (_progressTintColorDark);

    SAFE_ARC_SUPER_DEALLOC ();
}

-(id)initWithFrame:(CGRect)frameRect
{
    if ((self = [super initWithFrame:frameRect]))
    {
        [self initializeProgressBar];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];

    [self initializeProgressBar];
}

- (void)drawRect:(CGRect)rect
{
    // Refresh the corner radius value
    self.cornerRadius   = rect.size.height / 2;

    // Compute the progressOffset for the animation
    self.progressOffset = (self.progressOffset > 2 * YLProgressBarSizeStripeWidth - 1) ? 0 : ++self.progressOffset;

    // Draw the background track
    [self drawBackgroundWithRect:rect];

    if (self.progress > 0)
    {
        CGRect innerRect = CGRectMake(YLProgressBarSizeInset,
                                      YLProgressBarSizeInset,
                                      rect.size.width * self.progress - 2 * YLProgressBarSizeInset,
                                      rect.size.height - 2 * YLProgressBarSizeInset);

        [self drawProgressBarWithRect:innerRect];
        [self drawStripesWithRect:innerRect];
        [self drawGlossWithRect:innerRect];
    }
}

- (void)setProgressTintColor:(UIColor *)aProgressTintColor
{
    SAFE_ARC_RELEASE(_progressTintColor);
    _progressTintColor = SAFE_ARC_RETAIN(aProgressTintColor);
    const CGFloat* components = CGColorGetComponents(_progressTintColor.CGColor);
    _progressTintColorDark = SAFE_ARC_RETAIN([UIColor colorWithRed:components[0] / 4.0f
                                                             green:components[1] / 4.0f
                                                              blue:components[2] / 4.0f
                                                             alpha:CGColorGetAlpha(_progressTintColor.CGColor)]);
}

- (UIColor*)progressTintColor
{
    if (!_progressTintColor)
    {
        [self setProgressTintColor:[UIColor purpleColor]];
    }
    return _progressTintColor;
}

#pragma mark -
#pragma mark YLProgressBar Public Methods

- (void)setAnimated:(BOOL)_animated
{
    animated = _animated;

    if (animated)
    {
        if (self.animationTimer == nil)
        {
            self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/30
                                                                   target:self
                                                                 selector:@selector(setNeedsDisplay)
                                                                 userInfo:nil
                                                                  repeats:YES];
        }
    } else
    {
        if (self.animationTimer && [animationTimer isValid])
        {
            [animationTimer invalidate];
        }

        self.animationTimer = nil;
    }
}

#pragma mark YLProgressBar Private Methods

- (void)initializeProgressBar
{
    self.progressOffset     = 0;
    self.animationTimer     = nil;
    self.animated           = YES;
}

- (UIBezierPath *)stripeWithOrigin:(CGPoint)origin bounds:(CGRect)frame
{
    float height = frame.size.height;

    UIBezierPath *rect = [UIBezierPath bezierPath];

    [rect moveToPoint:origin];
    [rect addLineToPoint:CGPointMake(origin.x + YLProgressBarSizeStripeWidth, origin.y)];
    [rect addLineToPoint:CGPointMake(origin.x + YLProgressBarSizeStripeWidth - 8, origin.y + height)];
    [rect addLineToPoint:CGPointMake(origin.x - 8, origin.y + height)];
    [rect addLineToPoint:origin];
    [rect closePath];

    return rect;
}

- (void)drawBackgroundWithRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);
    {
        // Draw the white shadow
        [[UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:0.2] set];

        UIBezierPath* shadow        = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0.5, 0, rect.size.width - 1, rect.size.height - 1)
                                                          cornerRadius:cornerRadius];
        [shadow stroke];

        // Draw the track
        [YLProgressBarColorBackground set];

        UIBezierPath* roundedRect   = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, rect.size.width, rect.size.height-1) cornerRadius:cornerRadius];
        [roundedRect fill];

        // Draw the inner glow
        [YLProgressBarColorBackgroundGlow set];

        CGMutablePathRef glow       = CGPathCreateMutable();
        CGPathMoveToPoint(glow, NULL, cornerRadius, 0);
        CGPathAddLineToPoint(glow, NULL, rect.size.width - cornerRadius, 0);
        CGContextAddPath(context, glow);
        CGContextDrawPath(context, kCGPathStroke);
        CGPathRelease(glow);
    }
    CGContextRestoreGState(context);
}

- (void)drawProgressBarWithRect:(CGRect)rect
{
    CGContextRef context        = UIGraphicsGetCurrentContext();

    CGColorSpaceRef colorSpace  = CGColorSpaceCreateDeviceRGB();

    CGContextSaveGState(context);
    {
        UIBezierPath *progressBounds    = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
        CGContextAddPath(context, [progressBounds CGPath]);
        CGContextClip(context);

//        size_t num_locations            = 2;
        CGFloat locations[]             = {0.0, 1.0};
        CFArrayRef colors = (CFArrayRef) [NSArray arrayWithObjects:(id)_progressTintColorDark.CGColor,
                                          (id)self.progressTintColor.CGColor,
                                          nil];

        CGGradientRef gradient          = CGGradientCreateWithColors (colorSpace, colors, locations);

        CGContextDrawLinearGradient(context, gradient, CGPointMake(rect.origin.x, rect.origin.y), CGPointMake(rect.origin.x + rect.size.width, rect.origin.y), (kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation));

        CGGradientRelease(gradient);
    }
    CGContextRestoreGState(context);

    CGColorSpaceRelease(colorSpace);
}

- (void)drawGlossWithRect:(CGRect)rect
{
    CGContextRef context        = UIGraphicsGetCurrentContext();

    CGColorSpaceRef colorSpace  = CGColorSpaceCreateDeviceRGB();

    CGContextSaveGState(context);
    {
        // Draw the gloss
        CGContextSetBlendMode(context, kCGBlendModeOverlay);
        CGContextBeginTransparencyLayerWithRect(context, CGRectMake(rect.origin.x, rect.origin.y + floorf(rect.size.height) / 2, rect.size.width, floorf(rect.size.height) / 2), NULL);
        {
            const CGFloat glossGradientComponents[] = {1.0f, 1.0f, 1.0f, 0.47f, 0.0f, 0.0f, 0.0f, 0.0f};
            const CGFloat glossGradientLocations[] = {1.0, 0.0};
            CGGradientRef glossGradient = CGGradientCreateWithColorComponents(colorSpace, glossGradientComponents, glossGradientLocations, (kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation));
            CGContextDrawLinearGradient(context, glossGradient, CGPointMake(0, 0), CGPointMake(0, rect.size.width), 0);
            CGGradientRelease(glossGradient);
        }
        CGContextEndTransparencyLayer(context);

        // Draw the gloss's drop shadow
        CGContextSetBlendMode(context, kCGBlendModeSoftLight);
        CGContextBeginTransparencyLayer(context, NULL);
        {
            CGRect fillRect = CGRectMake(rect.origin.x, rect.origin.y + floorf(rect.size.height / 2), rect.size.width, floorf(rect.size.height / 2));

            const CGFloat glossDropShadowComponents[] = {0.0f, 0.0f, 0.0f, 0.56f, 0.0f, 0.0f, 0.0f, 0.0f};
            CGColorRef glossDropShadowColor = CGColorCreate(colorSpace, glossDropShadowComponents);

            CGContextSaveGState(context);
            {
                CGContextSetShadowWithColor(context, CGSizeMake(0, -1), 4, glossDropShadowColor);
                CGContextFillRect(context, fillRect);
                CGColorRelease(glossDropShadowColor);
            }
            CGContextRestoreGState(context);

            CGContextSetBlendMode(context, kCGBlendModeClear);
            CGContextFillRect(context, fillRect);
        }
        CGContextEndTransparencyLayer(context);
    }
    CGContextRestoreGState(context);

    UIBezierPath *progressBounds    = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];

    // Draw progress bar glow
    CGContextSaveGState(context);
    {
        CGContextAddPath(context, [progressBounds CGPath]);
        const CGFloat progressBarGlowComponents[] = {1.0f, 1.0f, 1.0f, 0.12f};
        CGColorRef progressBarGlowColor = CGColorCreate(colorSpace, progressBarGlowComponents);

        CGContextSetBlendMode(context, kCGBlendModeOverlay);
        CGContextSetStrokeColorWithColor(context, progressBarGlowColor);
        CGContextSetLineWidth(context, 2.0f);
        CGContextStrokePath(context);
        CGColorRelease(progressBarGlowColor);
    }
    CGContextRestoreGState(context);

    CGColorSpaceRelease(colorSpace);
}

- (void)drawStripesWithRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB ();

    CGContextSaveGState(context);
    {
        UIBezierPath *allStripes = [UIBezierPath bezierPath];

        for (int i = 0; i <= rect.size.width / (2 * YLProgressBarSizeStripeWidth) + (2 * YLProgressBarSizeStripeWidth); i++)
        {
            UIBezierPath* stripe = [self stripeWithOrigin:CGPointMake(i * 2 * YLProgressBarSizeStripeWidth + self.progressOffset, YLProgressBarSizeInset)
                                                   bounds:rect];
            [allStripes appendPath:stripe];
        }

        // Clip the progress frame
        UIBezierPath *clipPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];

        CGContextAddPath(context, [clipPath CGPath]);
        CGContextClip(context);

        CGContextSaveGState(context);
        {
            // Clip the stripes
            CGContextAddPath(context, [allStripes CGPath]);
            CGContextClip(context);

            const CGFloat stripesColorComponents[] = { 0.0f, 0.0f, 0.0f, 0.28f };
            CGColorRef stripesColor = CGColorCreate(colorSpace, stripesColorComponents);

            CGContextSetFillColorWithColor(context, stripesColor);
            CGContextFillRect(context, rect);

            CGColorRelease(stripesColor);
        }
        CGContextRestoreGState(context);
    }
    CGContextRestoreGState(context);

    CGColorSpaceRelease(colorSpace);
}

@end


text:
from yozuch.generators.template import TemplateEntry, TemplateGenerator
from yozuch.paginator import Paginator

class BlogIndexGenerator(TemplateGenerator):

    def __init__(self, url_template, name, template, posts_per_page=0, pagination_url=None):
        super().__init__(url_template, name, template)
        self.posts_per_page = posts_per_page
        self.pagination_url = pagination_url

    def generate(self, context):
        if self.pagination_url is not None and self.posts_per_page > 0:
            paginator = Paginator(context.site['posts'], self.posts_per_page)
            for page in paginator.pages:
                template_vars = {
                    'paginator': paginator,
                    'paginator_page': page,
                }
                page_id = self.name
                page.url = self.url_template
                if page.number > 1:
                    page.url = self.pagination_url.format(number=page.number)
                    page_id = '{}/{}'.format(self.name, page.number)
                yield TemplateEntry(page.url, self.template, page_id, template_vars=template_vars)
        else:
            yield TemplateEntry(self.url_template, self.template, self.name)


text:
#include "SettingsWindow.hpp"

/**
 * @brief SettingsWindow::SettingsWindow
 *
 * The constructor of the settings window.
 * Sets up the SIGNALS, UI and the tabs.
 */
SettingsWindow::SettingsWindow(int subDirNum){
    subDir = subDirNum;
    settingsDict = SettingsBackend::getSettings(subDirNum);

    tabs = new QTabWidget;
    layout = new LayoutTab(&settingsDict, this);
    behaviour = new BehaviourTab(&settingsDict, this);
    changed = false;
    tabs->addTab(layout, "Layout");
    connect(layout, &LayoutTab::contentChanged, this, &SettingsWindow::changedTrue);
    tabs->addTab(behaviour, "Behaviour");
    connect(behaviour, &BehaviourTab::contentChanged, this, &SettingsWindow::changedTrue);

    auto horizontal = new QHBoxLayout;
    horizontal->addWidget(tabs, 1);

    auto applyBut = new QPushButton(tr("Apply Changes"));
    auto applycloseBut = new QPushButton(tr("Apply and Exit"));
    auto closeBut = new QPushButton(tr("Close"));
    connect(applyBut, &QPushButton::clicked, this, &SettingsWindow::apply);
    connect(applycloseBut, &QPushButton::clicked, this, &SettingsWindow::applyClose);
    connect(closeBut, &QPushButton::clicked, this, &SettingsWindow::tryClose);

    auto buttons = new QHBoxLayout;
    buttons->addStretch(1);
    buttons->addWidget(applyBut);
    buttons->addWidget(applycloseBut);
    buttons->addWidget(closeBut);

    auto main = new QVBoxLayout;
    main->addLayout(horizontal);
    main->addStretch(1);
    main->addSpacing(12);
    main->addLayout(buttons);

    setLayout(main);
    setWindowTitle(tr("VeToLC | Editor Settings"));
}

/**
 * @brief SettingsWindow::~SettingsWindow
 *
 * Destructor of the SettingsWindow class.
 * Cleans up after the window was close.
 */
SettingsWindow::~SettingsWindow(){
    delete layout;
    delete behaviour;
    delete tabs;
}

/**
 * @brief SettingsWindow::apply
 *
 * applies the changes made in the window.
 */
void SettingsWindow::apply() noexcept{
    if(changed){
        QApplication::setStyle(settingsDict["Design"].toString());
        repaint();
        update();

        SettingsBackend::addSettings("Design", settingsDict["Design"]);
        SettingsBackend::addSettings("OpenFiles", settingsDict["OpenFiles"]);

        settingsDict.remove("Design");
        settingsDict.remove("OpenFiles");

        SettingsBackend::saveSettingsFor(subDir, settingsDict);

        changed = false;
    }
}

/**
 * @brief SettingsWindow::applyClose
 *
 * calls apply() and close(), thus saving the changes and exiting the window.
 */
void SettingsWindow::applyClose() noexcept{
    apply();
    close();
}

/**
 * @brief SettingsWindow::tryClose
 *
 * if there are unsaved changes, this method will create a checkbox
 * asking the user whether he/she wants to quit. Otherwise, it will just exit.
 */
void SettingsWindow::tryClose() noexcept{
    if(changed){
        auto question = QMessageBox::warning(this, tr("VeToLC"),
                                tr("The settings have been modified"
                                   " but are unsaved.\n"
                                "Do you want to save your changes?"),
                                QMessageBox::Save | QMessageBox::Discard
                                | QMessageBox::Cancel);
        if(question == QMessageBox::Save)
            apply();
        else if(question == QMessageBox::Cancel)
            return;
    }
    close();
}

/**
 * @brief SettingsWindow::setChanged
 *
 * setter for the changed flag. Sets the flag to true.
 * This will result in the apply function having effect.
 */
void SettingsWindow::changedTrue() noexcept{
    changed = true;
}


text:
module Feldspar.Future where

import Feldspar
import Feldspar.Vector as V

withFuture :: (Syntax a, Syntax b)
           => a -> (Future a -> b) -> b
withFuture = share . future

-- TODO enable again
-- withFutures :: (Syntax a, Syntax b, Shapely sh)
--             => Pull sh a -> (Manifest sh (Future a) -> b) -> b
-- withFutures coll = share $ store $ V.map future coll


text:
from django.conf.urls import patterns, include, url
from django.views.generic import ListView, DetailView

from .models import Venue

urlpatterns = patterns('',#'venues.views',
    url(r'^$', ListView.as_view(model=Venue, context_object_name='venues'), name='venue-list'),
    #url(r'^add/$', 'idea_add', name='idea-create'),
    url(r'^(?P<pk>\d+)/$', DetailView.as_view(model=Venue, context_object_name='venue'), name='venue-detail'),
    #url(r'^(?P<idea_id>\d+)/$', 'venue_detail', name='venue-detail'),
    #url(r'^(?P<idea_id>\d+)/up/$', 'idea_vote', {'direction': 1}, name='idea-vote-up'),
    #url(r'^(?P<idea_id>\d+)/down/$', 'idea_vote', {'direction': -1}, name='idea-vote-down'),
    #url(r'^(?P<idea_id>\d+)/comment/$', 'idea_comment', name='idea-comment'),
)


text:
![1 stars](../../images/ic_star_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png) 1

To use the OpenX skill, try saying...

* *Alexa, ask OpenX what makes them different.*

* *Alexa, ask OpenX why quality matters.*

* *Alexa, ask OpenX to tell me about header bidding.*

Learn more about OpenX with Alexa. You can ask Alexa to tell you about us, what we do, and how we partner with publishers to drive superior monetization.

***

### Skill Details

* **Invocation Name:** openx
* **Category:** null
* **ID:** amzn1.echo-sdk-ams.app.57a87c6d-edb3-4523-ab56-a97e6be53327
* **ASIN:** B01H4ETXFW
* **Author:** OpenX
* **Release Date:** August 8, 2016 @ 03:07:55
* **Privacy Policy:** http://openx.com/legal/privacypolicy/
* **Terms of Use:** http://openx.com/legal/terms-and-conditions/
* **In-App Purchasing:** No


text:
package org.apache.commons.logging.avalon;

import org.apache.avalon.framework.logger.NullLogger;
import org.apache.commons.logging.impl.AvalonLogger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.AbstractLogTest;

import junit.framework.Test;
import junit.framework.TestSuite;

/**
 * @author Neeme Praks
 * @version $Revision$ $Date$
 */
public class AvalonLoggerTestCase extends AbstractLogTest {

    public static Test suite() {
        TestSuite suite = new TestSuite();
        suite.addTestSuite(AvalonLoggerTestCase.class);
        return suite;
    }

    public Log getLogObject() {
        // Output does not seem to be used, so don't display it.
        Log log = new AvalonLogger(new NullLogger());
        return log;
    }
}


text:
#ifndef _cschannel_h__
#define _cschannel_h__

/*!
 * @mainpage Streaming secure channel in C.
 *
 * This project wraps the horrible Microsoft Security Support Provider Interface
 * (SSPI) API for use with the Microsoft Secure Channel, a TLS/SSL
 * implementation.  The API is somewhat difficult to use correctly and requires
 * much experimentation and testing.
 *
 * The project aims at providing a TLS/SSL implementation which is:
 *
 * @li @b convenient: integration in existing applications requires a minimal
 *  amount of code
 * @li @b reliable: the implementation is already debugged and supports a wide
 *  variety of situations, including corner cases
 * @li @b compatible: the implementation does not impose a network model and is
 *  compatible with any communucation transport providing reliable, ordered
 *  delivery of a stream of bytes.
 *
 * <b>Table of contents:</b>
 *
 * @li @ref license
 * @li @ref motivation
 * @li @ref design
 *
 * @section license Software license
 *
 * The software is released under an Open Source Initiative (OSI) approved
 * licence (MIT) with maximal compatibility with your business model, be it open
 * or closed source.
 *
 * The software is Copyright(c) Andre Caron, 2009-2011:
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @section motivation Motivation
 *
 * Microsoft's TLS/SSL implementation, Secure Channel (SChannel) is exposed
 * through the Microsoft Security Support Provider Interface (SSPI) API.  This
 * API is designed to be very generic and is therefore very complicated to use;
 * applications look like they're using a generic encryption mechanism, rather
 * than a TLS/SSL implementation.
 *
 * All in all, the API is difficult to use, and documentation is not very
 * helpful as far as corner cases are concerned.  Examples in the Platform SDK
 * only demonstrate simple cases and leave difficult corner cases as "an
 * exercise for the reader".
 *
 * This project provides a simple facade for this Secure Channel beast as a
 * standalone library with no other dependencies.  It is suitable for use in a
 * wide range of use cases and should be easily pluggable into any application.
 *
 * @section design Design
 *
 * The implementation is based on a finite state machine, which is interruptible
 * at (almost) any moment.  It does no I/O on its own and thus does not block on
 * networking operations, making it suitable for use in high-performance
 * networking applications based on asynchronous I/O (using I/O completion
 * ports, for example).
 */

/* standard library. */
#include <stddef.h>

/* microsoft secure channel api. */
#ifndef SECURITY_WIN32
#   define SECURITY_WIN32
#endif
#include <WinSock2.h>
#include <WinCrypt.h>
#include <SChnlSp.h>
#include <Security.h>

/* don't mangle names. */
#ifdef __cplusplus
extern "C" {
#endif

/*!
 * @brief Enumeration of secure channel error states.
 */
enum secure_channel_error
{
    secure_channel_good,
    secure_channel_fail,
};

/*!
 * @brief Enumeration of secure channel states.
 */
enum secure_channel_state
{
    secure_channel_failed=-1,
    secure_channel_virgin,
    secure_channel_unsafe,
    secure_channel_secure,
    secure_channel_expire,
};

/*!
 * @brief Enumeration of secure channel roles.
 */
enum secure_channel_role
{
    secure_channel_client,
    secure_channel_server,
};

/*!
 * @brief Information about the host's identity (local, self).
 */
struct security_certificate
{
    /*!
     * @brief Handle to opaque certificate state.
     */
    PCCERT_CONTEXT handle;
};

/*!
 * @brief Information about the host's identity (local, self).
 */
struct security_credentials
{
    /*!
     * @brief Description of the identity exposed by the channel.
     */
    SCHANNEL_CRED identity;

    /*!
     * @brief Handle to opaque credentials state.
     */
    CredHandle handle;
};

/*!
 * @brief Information about the security service provider.
 */
struct security_package
{
    /*!
     * @brief Maximum size of a negotiation token, in bytes.
     */
    DWORD token_size;
};

/*!
 * @brief Enumeration of possible errors codes when using TLS 1.
 */
enum tls1_alert
{
    tls1_alert_certificate_invalid   = TLS1_ALERT_BAD_CERTIFICATE,
    tls1_alert_certificate_support   = TLS1_ALERT_UNSUPPORTED_CERT,
    tls1_alert_certificate_revoked   = TLS1_ALERT_CERTIFICATE_REVOKED,
    tls1_alert_certificate_expired   = TLS1_ALERT_CERTIFICATE_EXPIRED,
    tls1_alert_certificate_unkonwn   = TLS1_ALERT_CERTIFICATE_UNKNOWN,
    tls1_alert_unknown_authority     = TLS1_ALERT_UNKNOWN_CA,
    tls1_alert_access_denied         = TLS1_ALERT_ACCESS_DENIED,
    tls1_alert_insufficient_security = TLS1_ALERT_INSUFFIENT_SECURITY,
    tls1_alert_user_cancelled        = TLS1_ALERT_USER_CANCELED,
    tls1_alert_no_renegotiation      = TLS1_ALERT_NO_RENEGOTIATION,
};

/*!
 * @brief High-level wrapper for the security channel interface.
 */
struct secure_channel
{
    /*!
     * @brief Current channel state.
     */
    enum secure_channel_state state;

    /*!
     * @brief Current channel error state.
     */
    enum secure_channel_error error;

    /*!
     * @brief Channel role.
     */
    enum secure_channel_role role;

    /*!
     * @brief Host certificate (local peer, self).
     */
    struct security_certificate certificate;

    /*!
     * @brief Host credentials (local peer, self).
     */
    struct security_credentials credentials;

    /*!
     * @brief Set to 1 to request client certificate, 0 by default.
     *
     * @ingroup server
     */
    int mutual_authentication;

    /*!
     * @brief Set to 0 to disable quick reconnect.
     */
    int allow_reconnect;

    /*!
     * @brief Set to 0 to deny renegotiation requests.
     */
    int allow_renegotiation;

    /*!
     * @private
     * @brief Set to 1 when renegotiation is requested.
     */
    int requested_renegotiation;

    /*!
     * @private
     * @brief Handle to opaque secure channel state.
     */
    CtxtHandle handle;

    /*!
     * @private
     * @brief Maximum token size, in bytes.
     */
    DWORD token_size;

    /*!
     * @private
     * @brief Maximum message header size, in bytes.
     */
    DWORD header_size;

    /*!
     * @private
     * @brief Maximum message stream size, in bytes.
     */
    DWORD stream_size;

    /*!
     * @private
     * @brief Maximum message footer size, in bytes.
     */
    DWORD footer_size;

    /*!
     * @addtogroup buffers
     */
    /// @{

    /*!
     * @private
     * @brief Buffer for in-bound negotiation token data.
     */
    void * itoken;

    /*!
     * @private
     * @brief Buffer for out-bound negotiation token data.
     */
    void * otoken;

    /*!
     * @private
     * @brief Buffer for out-bound message header.
     * @invariant Points to 0 or an array of @c header_size bytes.
     */
    void * emheader;

    /*!
     * @private
     * @brief Buffer for out-bound message stream.
     * @invariant Points to 0 or an array of @c stream_size bytes.
     */
    void * emstream;

    /*!
     * @private
     * @brief Buffer for out-bound message footer.
     * @invariant Points to 0 or an array of @c footer_size bytes.
     */
    void * emfooter;

    /*!
     * @private
     * @brief Buffer for in-bound message stream.
     * @invariant Points to 0 or an array of @c stream_size bytes.
     */
    void * dmstream;

    /*!
     * @private
     * @brief Buffers passed to security package.
     */
    SecBuffer buffers[12];

    /*!
     * @private
     * @brief Buffer for in-bound token data (received from peer).
     * @invariant References entries in @c buffers.
     */
    SecBufferDesc itbuffer;

    /*!
     * @private
     * @brief Buffer for out-bound token data (to be sent to peer).
     * @invariant References entries in @c buffers.
     */
    SecBufferDesc otbuffer;

    /*!
     * @private
     * @brief Buffer for encrypting messages, passed to security package.
     * @invariant References entries in @c buffers.
     */
    SecBufferDesc embuffer;

    /*!
     * @private
     * @brief Buffer for decrypting messages, passed to security package.
     * @invariant References entries in @c buffers.
     */
    SecBufferDesc dmbuffer;

    /// @}

    /*!
     * @public
     * @brief Set to 1 when the stream expects a @c secure_channel_pull() call.
     */
    int need_pull;

    /*!
     * @public
     * @brief Set to 1 when the stream expects a @c secure_channel_push() call.
     */
    int need_push;

    /*!
     * @addtogroup memory
     */
    /// @{

    /*!
     * @public
     * @brief Custom memory allocator's allocation function.
     *
     * If not specified, the secure channel will use @c malloc().
     *
     * @see release_buffer
     * @warning It is highly likely that setting only one of @c acquire_buffer
     *  or @c release_buffer is a logic error.  Always set both.
     */
    void*(*acquire_buffer)(struct secure_channel*, size_t);

    /*!
     * @public
     * @brief Custom memory allocator's cleanup function.
     *
     * If not specified, the secure channel will use @c free().
     *
     * @see acquire_buffer
     * @warning It is highly likely that setting only one of @c acquire_buffer
     *  or @c release_buffer is a logic error.  Always set both.
     */
    void (*release_buffer)(struct secure_channel*, void *);

    /// @}

    /*!
     * @public
     * @brief Callback invoked to notify of unused data in decryption.
     * @ingroup callback
     */
    void(*accept_overflow)(struct secure_channel*, const void*, size_t);

    /*!
     * @public
     * @brief Callback invoked to notify of availabile encrypted data.
     * @ingroup callback
     */
    void(*accept_encrypted)(struct secure_channel*, const void*, size_t);

    /*!
     * @public
     * @brief Callback invoked to notify of availabile decrypted data.
     * @ingroup callback
     */
    void(*accept_decrypted)(struct secure_channel*, const void*, size_t);

    /*!
     * @public
     * @brief Extra context, used by application-layer code (in callbacks).
     */
    void * object;
};

/*!
 * @brief Obtain information about the security package.
 * @param package Security package description to fill in.
 *
 * @ingroup export
 *
 * This function is mainly used to request the maximum token size, in bytes.
 * The specified limit is used to allocate token buffers on each side of the
 * connection.
 *
 * @note Call once and re-use for all channels.
 */
void security_package_setup ( struct security_package * package );

/*!
 * @brief Clear channel state and set default settings.
 * @param channel Secure channel instance to clear.
 *
 * @ingroup export
 *
 * All modifications to default settings should be made after a call to this
 * function is made.
 *
 * @see secure_channel_clear()
 *
 * @warning Calls to this function after a call to @c secure_channel_setup() has
 *  been made results in undefined behavior.  Common effects include memory
 *  leaks or large stream and token buffers.
 */
void secure_channel_clear ( struct secure_channel * channel );

/*!
 * @brief Finish initialization and start negotiation.
 * @param package Security package description.
 * @param channel Security channel instance for which to start initialization.
 * @param role Indicates whether the local host should initate negotiation or if
 *  the remote peer is expected to.
 *
 * @ingroup export
 *
 * For clients, this function produces the initial negotation token, which must
 * be sent to the server for negotiation to continue.  All modifications to
 * default settings should be made before this call is invoked.
 *
 * @see secure_channel_clear()
 */
void secure_channel_setup ( const struct security_package * package,
    struct secure_channel * channel, enum secure_channel_role role );

/*!
 * @brief Buffer message data for encryption (at a later time).
 * @param channel Security channel used for encryption.
 * @param data Pointer to first byte of data to encrypt.
 * @param size Number of bytes, starting at @a data, to encrypt.
 * @return Number of bytes consumed by the channel, in [0, @a size].
 *
 * @ingroup export
 *
 * Function used to process data before it is sent to the peer.  All data to
 * exchange over the secured connection must be passed to this filter.
 *
 * This function does not encrypt data.  The application should invoke the
 * @c secure_channel_flush method when a complete "message" is ready to be
 * encrypted.  Whenever data is encrypted, the resulting message data is passed
 * back to the application using the secure_channel::accept_encrypted callback.
 *
 * @see secure_channel_flush()
 */
size_t secure_channel_push
    ( struct secure_channel * channel, const char * data, size_t size );

/*!
 * @brief Attempt to message decryption.
 * @param channel Security channel used for encryption.
 * @param data Pointer to first byte of data to decrypt.
 * @param size Number of bytes, starting at @a data, to decrypt.
 * @return Number of bytes consumed by the channel, in [0, @a size].
 *
 * @ingroup export
 *
 * Function used to process data received from the peer, before it is used by
 * the application.  All data to exchange over the secured connection must be
 * passed to this filter.
 *
 * This function @e attempts to decrypt received data.  Because the secure
 * channel is @e message-based and the transport mechanism is @e stream-based,
 * it is possible to receive data in chunks smaller than the entire message.  In
 * such a case, data is buffered and kept until further data is provided and the
 * message is completely received.  Whenever data is decrypted, the resulting
 * message data is passed back to the application using the
 * secure_channel::accept_decrypted callback.
 */
size_t secure_channel_pull
    ( struct secure_channel * channel, const char * data, size_t size );

/*!
 * @brief Force any buffered data to be output.
 * @param channel Secure channel instance for which to encrypt buffered data.
 *
 * The secure channel allows the application to provide message parts in
 * multiple calls to the secure_channel_pull() function.  Because of this, the
 * secure channel requires a call to this function to actually encrypt data.
 *
 * @note Depending on the security package limits (maximum message size) and
 *  channel configuration, it is possible that a message be encrypted without
 *  a call to this function.  However, to ensure that data has been encrypted,
 *  this function a call!
 *
 * @ingroup export
 */
void secure_channel_flush ( struct secure_channel * channel );

/*!
 * @brief Notify peer of intent to re-negotiate.
 * @param channel Secure channel instance for which to request re-negotiation
 *
 * @ingroup export
 *
 * Re-negotiating the encryption keys is recommended after 1 Gigabyte or data
 * has been exchanged, or 1 hour has elapsed since the last negotiation,
 * whichever occurs first.  However, re-negotiation is optional, and the request
 * may be denied by the peer.  Thus, the secure channel does not attempt to
 * re-negotiate automatically and it is up to the application to request it if
 * desired.
 *
 * @note Re-negotiation of the connection is always optional.  The peer may
 *  decide not to acknowledge the request.  Also, the peer may continue to
 *  encrypt data until it ptocesses the renegotiation request.  Because of these
 *  two limitations, the secure channel cannot determine if the peer ever
 *  processes the renegotiation request.
 */
void secure_channel_renegotiate ( struct secure_channel * channel );

/*!
 * @brief Initiate shutdown.
 * @param channel Secure channel instance to close.
 *
 * A call to this function produces a token that notifies the peer of the intent
 * to shutdown the connection.
 *
 * @todo Figure out if the local channel can still decrypt data.
 *
 * @note Unlike network sockets, the secure channel does not support unilateral
 *  shutdown.  Moreover, the channel might need to re-negotiate at the peer's
 *  request, even if the application is only receiving data.  Therefore,
 *  applications should be careful not to request a shutdown until all data is
 *  exchanged, and to keep the socket open even if a one-way socket shutdown is
 *  possible.
 *
 * @ingroup export
 */
void secure_channel_close ( struct secure_channel * channel );

/* don't mangle names. */
#ifdef __cplusplus
}
#endif

#endif /* _cschannel_h__ */