text:
package org.pathvisio.pluginmanager.impl.dialogs;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;

import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.pathvisio.pluginmanager.impl.PluginManager;
import org.pathvisio.pluginmanager.impl.PluginManager.PluginManagerStatus;
import org.pathvisio.pluginmanager.impl.data.PVRepository;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * StatusPanel.java
 * creates JPanel object shown in the
 * plugin manager dialog tab "Status"
 *
 * @author martina
 *
 */
public class StatusPanel extends JPanel {

	private PluginManager manager;

	public StatusPanel(PluginManager manager) {
		this.manager = manager;
		this.setBackground(Color.white);
		this.setLayout(new BorderLayout());

		if(manager.getStatus().equals(PluginManagerStatus.CONNECTION_COMPLETED_FAILURE)) {
			// TODO: add warning about connection failure
			// TODO: enable retrying connection
			this.add(getConnectionErrorPanel(), BorderLayout.NORTH);
		} else if (manager.getStatus().equals(PluginManagerStatus.CONNECTION_COMPLETED_SUCCESSFULLY)) {
			// TODO show all repositories
			this.add(getConnectionSuccessPanel(), BorderLayout.NORTH);
			this.add(getRepositoryList(), BorderLayout.CENTER);
		} else {
			// print that connection is still busy building up
			this.add(progressPanel(), BorderLayout.NORTH);
		}
	}

	private JPanel getConnectionSuccessPanel() {
		FormLayout layout = new FormLayout("5dlu,pref,5dlu,pref,fill:pref:grow","10dlu,pref,5dlu,pref,15dlu");
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setBackground(Color.white);
		CellConstraints cc = new CellConstraints();

		builder.addLabel(manager.getStatusMessage(), cc.xy(2, 2));

		builder.addSeparator("", cc.xyw(2, 5, 4));

		return builder.getPanel();
	}

	private JComponent getRepositoryList() {
		int count = manager.getOnlineRepos().size();
		String row = "10dlu,pref,5dlu,";
		for(int i = 0; i < count; i++) {
			row = row + "pref, 5dlu,";
		}
		row = row + "5dlu";

		FormLayout layout = new FormLayout("5dlu,pref,5dlu,pref,5dlu",row);
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setBackground(Color.white);
		CellConstraints cc = new CellConstraints();

		builder.addLabel("Repository name", cc.xy(2, 2));
		builder.addLabel("URL", cc.xy(4, 2));

		int currRow = 4;
		for(PVRepository repo : manager.getOnlineRepos()) {
			JLabel name = new JLabel(repo.getName());
			Font newLabelFont=new Font(name.getFont().getName(),Font.ITALIC, name.getFont().getSize());
			name.setFont(newLabelFont);
			builder.add(name, cc.xy(2, currRow));

			JEditorPane link = new JEditorPane();
			link.setBackground(Color.white);
			link.setEditable(false);
			link.setContentType("text/html");
			link.setText("" + repo.getUrl() + "");
			link.addHyperlinkListener(manager.getDesktop().getSwingEngine());
			builder.add(link, cc.xy(4, currRow));
			currRow = currRow + 2;
		}
		return builder.getPanel();
	}

	private JPanel getConnectionErrorPanel() {
		FormLayout layout = new FormLayout("5dlu,pref,5dlu,pref,fill:pref:grow","10dlu,pref,5dlu,pref,15dlu");
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setBackground(Color.white);
		CellConstraints cc = new CellConstraints();

		builder.addLabel(manager.getStatusMessage(), cc.xy(2, 2));

		builder.addSeparator("", cc.xyw(2, 5, 4));

		return builder.getPanel();
	}

	private JPanel progressPanel() {
		FormLayout layout = new FormLayout("5dlu,pref,5dlu,pref,fill:pref:grow","10dlu,pref,5dlu,pref,15dlu");
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setBackground(Color.white);
		CellConstraints cc = new CellConstraints();

		builder.addLabel(manager.getStatusMessage(), cc.xy(2, 2));

		builder.addSeparator("", cc.xyw(2, 5, 4));

		return builder.getPanel();
	}

}


text:
package com.intrbiz.blog.router;

import org.apache.log4j.Logger;

import com.intrbiz.balsa.engine.route.Router;
import com.intrbiz.balsa.error.http.BalsaNotFound;
import com.intrbiz.balsa.error.view.BalsaViewNotFound;
import com.intrbiz.balsa.http.HTTP.HTTPStatus;
import com.intrbiz.balsa.metadata.WithDataAdapter;
import com.intrbiz.blog.BlogApp;
import com.intrbiz.blog.db.BlogAdapter;
import com.intrbiz.blog.model.CategoryInfo;
import com.intrbiz.blog.model.PostInfo;
import com.intrbiz.metadata.Any;
import com.intrbiz.metadata.Before;
import com.intrbiz.metadata.Catch;
import com.intrbiz.metadata.Order;
import com.intrbiz.metadata.Prefix;
import com.intrbiz.metadata.Status;
import com.intrbiz.metadata.Template;

@Prefix("/")
@Template("theme/main")
public class BlogRouter extends Router<BlogApp>
{
    private Logger logger = Logger.getLogger(BlogRouter.class);

    @Any("/**")
    @Before()
    @WithDataAdapter(BlogAdapter.class)
    public void themeCommon(BlogAdapter data)
    {
        // setup common theme stuff
        model("main_menu", data.getMenu("main_menu"));
    }

    @Any("/")
    @WithDataAdapter(BlogAdapter.class)
    public void index(BlogAdapter data)
    {
        var("posts", data.getRecentPosts(10));
        encode("theme/index", "pages/index");
    }

    @Any("/category/**:category")
    @Order(10)
    @WithDataAdapter(BlogAdapter.class)
    public void category(BlogAdapter data, String name)
    {
        CategoryInfo category = var("category", data.getCategory(name));
        if (category == null) throw new BalsaNotFound("The category " + name + " could not be found");
        var("posts", category.getRecentPosts(10));
        encode("theme/category", "categories/" + name);
    }

    @Any("/post/**:post")
    @Order(10)
    @WithDataAdapter(BlogAdapter.class)
    public void post(BlogAdapter data, String name)
    {
        PostInfo post = var("post", data.getPost(name));
        if (post == null) throw new BalsaNotFound("The post " + name + " could not be found");
        encode("theme/post", "posts/" + name);
    }

    @Any("/**:page")
    @Order(100)
    public void page(String page)
    {
        encode("theme/page", "pages/" + page);
    }

    @Any("/**")
    @Catch(BalsaViewNotFound.class)
    @Catch(BalsaNotFound.class)
    @Status(HTTPStatus.NotFound)
    public void notFound()
    {
        encode("theme/notfound");
    }

    @Any("/**")
    @Catch()
    @Order(Order.LAST)
    @Status(HTTPStatus.InternalServerError)
    public void error()
    {
        logger.error("Internal server error whilst processing request", balsa().getException());
        encode("theme/error");
    }
}

redpajama_set_name: RedPajamaGithub


text:
import styled from 'styled-components';

const FormGroup = styled.div`
  overflow: auto;
  padding-bottom: 10px;
`;

export default FormGroup;


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>dangle-studies</artifactId>
        <groupId>com.diguage.dangle</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>dangle-io</artifactId>
    <packaging>jar</packaging>

    <name>dangle-io</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
// Karma configuration
// Generated on Wed Jul 15 2015 09:44:02 GMT+0200 (Romance Daylight Time)

module.exports = function(config) {
  config.set({

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'source-map-support'],

    // list of files / patterns to load in the browser
    files: [

      'node_modules/es6-shim/es6-shim.js',
      'node_modules/systemjs/dist/system-polyfills.js', // PhantomJS2 (and possibly others) might require it

      // zone-microtask must be included first as it contains a Promise monkey patch
      'node_modules/zone.js/dist/zone-microtask.js',
      'node_modules/zone.js/dist/long-stack-trace-zone.js',
      'node_modules/zone.js/dist/jasmine-patch.js',

      'node_modules/systemjs/dist/system.src.js',
      {pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false, served: true},
      'node_modules/reflect-metadata/Reflect.js',

      'tools/build/file2modulename.js',
      {pattern: 'node_modules/angular2/**/*.js', included: false, watched: false},

      {pattern: 'test/**', included: false, watched: true},

      'test-main.js'
    ],

    // list of files / patterns to exclude
    exclude: [
      'node_modules/angular2/bundles/**',
      'node_modules/angular2/es6/**',
      'node_modules/angular2/examples/**',
      'node_modules/angular2/**/*_spec.js',
      'node_modules/angular2/**/*.min.js',
      'node_modules/rxjs/bundles/**',
      'node_modules/rxjs/testing/**'
    ],

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha'],

    // web server port
    port: 9876,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
      'Chrome',
      'PhantomJS2'
    ],

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    }
  });

  if (process.env.TRAVIS) {
    config.browsers = ['Chrome_travis_ci'];
    config.singleRun = true;
  }
};


text:
from django.conf.urls import patterns, include, url
import apps.staff.views

# These urls are included in apps.core.urls
# so they are relative to /staff. For example
# users_home is set to ^users$ but it's accessible
# at /staff/users/

urlpatterns = [
    url(r'^users$', apps.staff.views.Index.as_view(), name='users_home'),
    url(r'^users/create$', apps.staff.views.Create.as_view(), name='users_create'),
    url(r'^users/(?P<pk>[0-9]+)/delete$',
      apps.staff.views.Delete.as_view(), name='users_delete'),
    url(r'^users/(?P<pk>[0-9]+)/update$',
      apps.staff.views.Update.as_view(), name='users_update'),
]


text:
<!DOCTYPE html>

	<title>VIKI | Home</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="UTF-8">

	<link href="css/4-col-portfolio.css" rel="stylesheet">
	<link href="css/bootstrap.min.css" rel="stylesheet">
	<link rel="stylesheet" href="css/bootstrap-switch.css" />

Portas

Porta #1

                                        <input type="checkbox" checked>

                                        <input type="checkbox" checked>

Porta #2

                                    <input type="checkbox" checked>

                                    <input type="checkbox" checked>

Janela

Janela #1

                                    <input type="checkbox" checked>

                                    <input type="checkbox" checked>

Janela #2

                                    <input type="checkbox" checked>

                                    <input type="checkbox" checked>


text:
plugin.video.spi0n
==================

a Kodi addon that allows you to watch your Le Zap de Spi0ns on your Kodi-powered TV

## Install

in order to make this plugin work again, install the dailymotion 4k plugin first (provided in this repo). After install restart Kodi and install the zip of the spi0n plugin.

## Licence

The MIT License (MIT)

Copyright (c) 2014-2016 Matthias Klan

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.


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit16281ad7eb1eff1d63d1645657ee2a89::getLoader();


text:
. ./infra.inc
TESTDIR=pushreceivepack

echo "*** Running test Push with receive-pack command line -- positive test - standard"

rm -rf $TESTDIR
mkdir $TESTDIR && cd $TESTDIR

mkdir remote && cd remote
createBareRepo
cd ..

mkdir local && cd local
cloneRepo ../remote

# we need to write something to the remote repository, otherwise this won't do the trick...
echo "test" > dummy.txt
git add dummy.txt
git commit -m "first commit"
git push origin

# we need another entry, which the script may now commit
echo "test2" >dummy2.txt

$SUBJECT -s -c -m "dummy commit message" -p origin -r "receive_pack dummy" -g $PWD/../../git_check_for_receivepack.sh

# testing against zero return code is alraedy enough - the core of the check is implemented in git_check_for_receivepack.sh

if [ $? != 0 ]; then
	echo "ERROR: Non-zero exit on test"
	exit 1
fi

cd ..

cd ..
rm -rf $TESTDIR


text:
import iam = require('@aws-cdk/aws-iam');
import cdk = require('@aws-cdk/cdk');
import { Alarm, ComparisonOperator, TreatMissingData } from './alarm';
export declare type DimensionHash = {
    [dim: string]: any;
};
/**
 * Properties for a metric
 */
export interface MetricProps {
    /**
     * Dimensions of the metric
     *
     * @default No dimensions
     */
    dimensions?: DimensionHash;
    /**
     * Namespace of the metric.
     */
    namespace: string;
    /**
     * Name of the metric.
     */
    metricName: string;
    /**
     * The period over which the specified statistic is applied.
     *
     * Specify time in seconds, in multiples of 60.
     *
     * @default 300
     */
    periodSec?: number;
    /**
     * What function to use for aggregating.
     *
     * Can be one of the following (case insensitive)
     *
     * - "minimum" | "min"
     * - "maximum" | "max"
     * - "average" | "avg"
     * - "sum"
     * - "samplecount | "n"
     * - "pNN.NN"
     *
     * @default Average
     */
    statistic?: string;
    /**
     * Unit for the metric that is associated with the alarm
     */
    unit?: Unit;
    /**
     * Label for this metric when added to a Graph in a Dashboard
     */
    label?: string;
    /**
     * Color for this metric when added to a Graph in a Dashboard
     */
    color?: string;
}
/**
 * A metric emitted by a service
 *
 * The metric is a combination of a metric identifier (namespace, name and dimensions)
 * and an aggregation function (statistic, period and unit).
 *
 * It also contains metadata which is used only in graphs, such as color and label.
 * It makes sense to embed this in here, so that compound constructs can attach
 * that metadata to metrics they expose.
 *
 * This class does not represent a resource, so hence is not a construct. Instead,
 * Metric is an abstraction that makes it easy to specify metrics for use in both
 * alarms and graphs.
 */
export declare class Metric {
    /**
     * Grant permissions to the given identity to write metrics.
     *
     * @param identity The IAM identity to give permissions to.
     */
    static grantPutMetricData(identity?: iam.IIdentityResource): void;
    readonly dimensions?: DimensionHash;
    readonly namespace: string;
    readonly metricName: string;
    readonly periodSec: number;
    readonly statistic: string;
    readonly unit?: Unit;
    readonly label?: string;
    readonly color?: string;
    constructor(props: MetricProps);
    /**
     * Return a copy of Metric with properties changed.
     *
     * All properties except namespace and metricName can be changed.
     *
     * @param props The set of properties to change.
     */
    with(props: MetricCustomization): Metric;
    /**
     * Make a new Alarm for this metric
     *
     * Combines both properties that may adjust the metric (aggregation) as well
     * as alarm properties.
     */
    newAlarm(parent: cdk.Construct, name: string, props: NewAlarmProps): Alarm;
    /**
     * Return the dimensions of this Metric as a list of Dimension.
     */
    dimensionsAsList(): Dimension[];
}
/**
 * Metric dimension
 */
export interface Dimension {
    /**
     * Name of the dimension
     */
    name: string;
    /**
     * Value of the dimension
     */
    value: any;
}
/**
 * Statistic to use over the aggregation period
 */
export declare enum Statistic {
    SampleCount = "SampleCount",
    Average = "Average",
    Sum = "Sum",
    Minimum = "Minimum",
    Maximum = "Maximum"
}
/**
 * Unit for metric
 */
export declare enum Unit {
    Seconds = "Seconds",
    Microseconds = "Microseconds",
    Milliseconds = "Milliseconds",
    Bytes_ = "Bytes",
    Kilobytes = "Kilobytes",
    Megabytes = "Megabytes",
    Gigabytes = "Gigabytes",
    Terabytes = "Terabytes",
    Bits = "Bits",
    Kilobits = "Kilobits",
    Megabits = "Megabits",
    Gigabits = "Gigabits",
    Terabits = "Terabits",
    Percent = "Percent",
    Count = "Count",
    BytesPerSecond = "Bytes/Second",
    KilobytesPerSecond = "Kilobytes/Second",
    MegabytesPerSecond = "Megabytes/Second",
    GigabytesPerSecond = "Gigabytes/Second",
    TerabytesPerSecond = "Terabytes/Second",
    BitsPerSecond = "Bits/Second",
    KilobitsPerSecond = "Kilobits/Second",
    MegabitsPerSecond = "Megabits/Second",
    GigabitsPerSecond = "Gigabits/Second",
    TerabitsPerSecond = "Terabits/Second",
    CountPerSecond = "Count/Second",
    None = "None"
}
/**
 * Properties of a metric that can be changed
 */
export interface MetricCustomization {
    /**
     * Dimensions of the metric
     *
     * @default No dimensions
     */
    dimensions?: DimensionHash;
    /**
     * The period over which the specified statistic is applied.
     *
     * Specify time in seconds, in multiples of 60.
     *
     * @default 300
     */
    periodSec?: number;
    /**
     * What function to use for aggregating.
     *
     * Can be one of the following:
     *
     * - "Minimum" | "min"
     * - "Maximum" | "max"
     * - "Average" | "avg"
     * - "Sum" | "sum"
     * - "SampleCount | "n"
     * - "pNN.NN"
     *
     * @default Average
     */
    statistic?: string;
    /**
     * Unit for the metric that is associated with the alarm
     */
    unit?: Unit;
    /**
     * Label for this metric when added to a Graph in a Dashboard
     */
    label?: string;
    /**
     * Color for this metric when added to a Graph in a Dashboard
     */
    color?: string;
}
/**
 * Properties to make an alarm from a metric
 */
export interface NewAlarmProps {
    /**
     * The period over which the specified statistic is applied.
     *
     * Specify time in seconds, in multiples of 60.
     *
     * @default 300
     */
    periodSec?: number;
    /**
     * What function to use for aggregating.
     *
     * Can be one of the following:
     *
     * - "Minimum" | "min"
     * - "Maximum" | "max"
     * - "Average" | "avg"
     * - "Sum" | "sum"
     * - "SampleCount | "n"
     * - "pNN.NN"
     *
     * @default Average
     */
    statistic?: string;
    /**
     * Name of the alarm
     *
     * @default Automatically generated name
     */
    alarmName?: string;
    /**
     * Description for the alarm
     *
     * @default No description
     */
    alarmDescription?: string;
    /**
     * Comparison to use to check if metric is breaching
     *
     * @default GreaterThanOrEqualToThreshold
     */
    comparisonOperator?: ComparisonOperator;
    /**
     * The value against which the specified statistic is compared.
     */
    threshold: number;
    /**
     * The number of periods over which data is compared to the specified threshold.
     */
    evaluationPeriods: number;
    /**
     * Specifies whether to evaluate the data and potentially change the alarm state if there are too few data points to be statistically significant.
     *
     * Used only for alarms that are based on percentiles.
     */
    evaluateLowSampleCountPercentile?: string;
    /**
     * Sets how this alarm is to handle missing data points.
     *
     * @default TreatMissingData.Missing
     */
    treatMissingData?: TreatMissingData;
    /**
     * Whether the actions for this alarm are enabled
     *
     * @default true
     */
    actionsEnabled?: boolean;
}


text:
package typhon

import "context"

type metadataKey struct{}

// Metadata provides a transport agnostic way to pass metadata with Typhon.
// It aligns to the interface of Go's default HTTP header type for convenience.
type Metadata map[string][]string

// NewMetadata creates a metadata struct from a map of strings.
func NewMetadata(data map[string]string) Metadata {
	meta := make(Metadata, len(data))
	for k, v := range data {
		meta[k] = []string{v}
	}
	return meta
}

// AppendMetadataToContext sets the metadata on the context.
func AppendMetadataToContext(ctx context.Context, md Metadata) context.Context {
	return context.WithValue(ctx, metadataKey{}, md)
}

// MetadataFromContext retrieves the metadata from the context.
func MetadataFromContext(ctx context.Context) Metadata {
	meta, ok := ctx.Value(metadataKey{}).(Metadata)
	if !ok {
		return Metadata{}
	}
	return meta
}


text:
package com.fluxchess.pulse;

import static com.fluxchess.pulse.MoveList.RootEntry;

interface Protocol {

	void sendBestMove(int bestMove, int ponderMove);

	void sendStatus(int currentDepth, int currentMaxDepth, long totalNodes, int currentMove, int currentMoveNumber);

	void sendStatus(boolean force, int currentDepth, int currentMaxDepth, long totalNodes, int currentMove, int currentMoveNumber);

	void sendMove(RootEntry entry, int currentDepth, int currentMaxDepth, long totalNodes);

	void sendInfo(String message);

	void sendDebug(String message);
}


text:
<?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\helpers\Url;
$session = Yii::$app->session;

$state = $session->get("state");
$logo_url = Html::img(Yii::$app->homeUrl.'images/logo/logo3.png', ['alt'=>'Servicemapp Logo', 'class'=>'', 'style' => 'opacity:.3;
  -webkit-filter: drop-shadow(1px 1px 1px #666) grayscale(100%);', 'width'=>42]);
?>

	<?= $renderIndex ? '
'.Html::a($logo_url, '/', ['class' => '']).'
' : null ?>
	<?php if($state!='' && $renderIndex): ?>

<?= ($state=='order') ? 'Izaberite uslugu koju želite da poručite' : 'Izaberite uslugu koju želite da ponudite' ?>

	<?php endif; ?>
		<?= $this->render('autocomplete.php', ['renderIndex'=>$renderIndex]) ?>

			<?= Html::a('Uslužne delatnosti', null, ['class'=>($renderIndex ? 'industries-six-boxes-link' : 'industries-six-boxes-link-mini')]); ?> |
			<?= Html::a('Predmeti i proizvodi', null, ['class'=>'objects-six-boxes-link']); ?>


text:
__Warning:__ This project was moved to [react-page-renderer](https://github.com/rsamec/react-page-renderer).

[react-publisher](http://react-documets.rhcloud.com/publisher) is application that publishes content created by [react-designer](http://hand-formvalidation.rhcloud.com/designer).

It enables to view, fill in and preview and print documents and it enables to generate to pdf.

You can browse all example documents from [documents gallery](http:/react-documets.rhcloud.com/publisher).

## Features

+   high-quality on-screen output and on-printer output
+   precise visual layout that corresponds to an existing paper version
    +   support for various output formats - html, pdf.
+   application features with comfortable user experience
    +   preview and print documents (responsive and mobile friendly)
    +   fill in data to documents
    +   supports validation using [business rules engine](https://github.com/rsamec/business-rules-engine)
    +   generate pdf documents
    +   search and filter documents

## Basic philosophy

The basic feature is rendering of document (json format - RDOM structure) using [react](https://facebook.github.io/react/).

RDOM is object schema format that represents full description of document.

It is a simple object tree that consists of
-   __containers__ - nodes that are invisible components - usable for logical grouping of reactive parts of document (sections)
-   __boxes__ - terminal nodes (leaf) that are visible components - (react components, boxes, widgets) - it maps to props of react component

minimal RDOM example

```json
{
 "name": "rootContainer",
 "elementName": "ObjectSchema",
 "containers": [
    {
     "name": "container",
     "elementName": "Container",
     "style": { "top": 0, "left": 0, "height": 200, "width": 740, "position": "relative" }
     "boxes": [{
        "name": "TextBox",
        "elementName": "TextBox",
        "style": { "top": 0, "left": 0 },
        "content": "Type your text"
        }],
      "containers": [ ] }
    ]
}
```

The object schema tree is composed using __containers__ property as collection of children.
The __boxes__ on the other hand is a leaf collection that can not have other children.

To render in react is super simple

```js
    createComponent: function (box) {
        var widget =widgets[box.elementName];
        if (widget === undefined) return React.DOM.span(null,'Component ' + box.elementName + ' is not register among widgets.');

        return React.createElement(widget,box, box.content!== undefined?React.DOM.span(null, box.content):undefined);
    },
    render:function(){
       {this.props.boxes.map(function (box, i) {
                var component = this.createComponent(box);
                return (
                       <div style={box.style}>
                            {component}
                       </div>
                       );
       }, this)}
    }

```

# Get started

Run watch task and begin to develop your React components.

```
$ npm install
```

```
$ bower install
```

```
$ gulp dev
```

```
$ gulp pro
```

# Road map

+   support for biometric signature
+   support for electronic signature
+   PDF - support PDF/A format

# Licence

MIT
Copyright (c) 2015 Roman Samec


text:
package org.wso2.carbon.apimgt.impl.definitions;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.carbon.apimgt.api.APIDefinition;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.dto.Environment;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;

import java.util.*;

import static org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException;

public class APIDefinitionFromSwagger12 extends APIDefinition {
    @Override
    @Deprecated
    public Set<URITemplate> getURITemplates(API api, String resourceConfigsJSON) throws APIManagementException {
        JSONParser parser = new JSONParser();
        JSONObject resourceConfigs;
        Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
        try {
            resourceConfigs = (JSONObject) parser.parse(resourceConfigsJSON);
            JSONArray resources = (JSONArray) resourceConfigs.get(APIConstants.SWAGGER_RESOURCES);
            //Iterating each resourcePath config
            for (Object resource : resources) {
                JSONObject resourceConfig = (JSONObject) resource;
                APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
                    getAPIManagerConfigurationService().getAPIManagerConfiguration();

                Map<String, Environment> environments = config.getApiGatewayEnvironments();
                Environment environment = null;
                String endpoint = null;
                if (environments != null) {
                    Set<String> publishedEnvironments = api.getEnvironments();
                    if (publishedEnvironments.isEmpty() || publishedEnvironments.contains(APIConstants.ENVIRONMENTS_NONE)) {
                        environment = environments.values()
                                .toArray(new Environment[environments.size()])[0];
                        String gatewayEndpoint = environment.getApiGatewayEndpoint();
                        if (gatewayEndpoint.contains(",")) {
                            endpoint = gatewayEndpoint.split(",")[0];
                        } else {
                            endpoint = gatewayEndpoint;
                        }
                    } else {
                        for (String environmentName : publishedEnvironments) {
                            // find environment that has hybrid type
                            if (APIConstants.GATEWAY_ENV_TYPE_HYBRID
                                    .equals(environments.get(environmentName).getType())) {
                                environment = environments.get(environmentName);
                                break;
                            }
                        }
                        //if not having any hybrid environment give 1st environment in api published list
                        if (environment == null) {
                            environment = environments.get(publishedEnvironments.toArray()[0]);
                        }
                        String gatewayEndpoint = environment.getApiGatewayEndpoint();
                        if (gatewayEndpoint != null && gatewayEndpoint.contains(",")) {
                            endpoint = gatewayEndpoint.split(",")[0];
                        } else {
                            endpoint = gatewayEndpoint;
                        }
                    }
                }

                // We do not need the version in the base path since with the context version strategy, the version is
                // embedded in the context
                String basePath = endpoint + api.getContext();
                resourceConfig.put(APIConstants.SWAGGER_BASEPATH, basePath);

                JSONArray resource_configs = (JSONArray) resourceConfig.get(APIConstants.API_ARRAY_NAME);

                //Iterating each Sub resourcePath config
                int subResCount = 0;
                while (subResCount < resource_configs.size()) {
                    JSONObject subResource = (JSONObject) resource_configs.get(subResCount);
                    String uriTempVal = (String) subResource.get(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD);
                    uriTempVal = uriTempVal.startsWith("/") ? uriTempVal : ("/" + uriTempVal);

                    JSONArray operations = (JSONArray) subResource.get(APIConstants.SWAGGER_OPERATIONS);
                    //Iterating each operation config
                    for (Object operation : operations) {
                        JSONObject jsonObjectOperation = (JSONObject) operation;
                        String httpVerb = (String) jsonObjectOperation.get(APIConstants.SWAGGER_HTTP_METHOD);

                        URITemplate template = new URITemplate();
                        Scope scope = APIUtil.findScopeByKey(getScopes(resourceConfigsJSON),
                                (String) jsonObjectOperation.get(APIConstants.SWAGGER_SCOPE));

                        String authType = (String) jsonObjectOperation.get(APIConstants.SWAGGER_AUTH_TYPE);
                        if (authType != null) {
                            if ("Application & Application User".equals(authType)) {
                                authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
                            }
                            if ("Application User".equals(authType)) {
                                authType = APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN;
                            }
                        } else {
                            authType = APIConstants.AUTH_NO_AUTHENTICATION;
                        }
                        template.setThrottlingTier((String) jsonObjectOperation.get(APIConstants.API_THROTTLING_TIER));
                        template.setMediationScript((String) jsonObjectOperation.get(APIConstants.API_MEDIATION_SCRIPT));
                        template.setUriTemplate(uriTempVal);
                        template.setHTTPVerb(httpVerb);
                        template.setAuthType(authType);
                        template.setScope(scope);

                        uriTemplates.add(template);

                    }

                    subResCount++;
                }
            }
        } catch (ParseException e) {
            handleException("Invalid resource configuration ", e);
        }
        return uriTemplates;
    }

    @Override
    @Deprecated
    public Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException {
        Set<Scope> scopeList = new LinkedHashSet<Scope>();
        JSONObject resourceConfigs;
        JSONParser parser = new JSONParser();
        try {
            resourceConfigs = (JSONObject) parser.parse(resourceConfigsJSON);
            JSONObject api_doc = (JSONObject) resourceConfigs.get(APIConstants.API_SWAGGER_DOC);
            if (api_doc.get(APIConstants.SWAGGER_12_AUTH) != null) {
                JSONObject authorizations = (JSONObject) api_doc.get(APIConstants.SWAGGER_12_AUTH);
                if (authorizations.get(APIConstants.SWAGGER_12_OAUTH2) != null) {
                    JSONObject oauth2 = (JSONObject) authorizations.get(APIConstants.SWAGGER_12_OAUTH2);
                    if (oauth2.get(APIConstants.SWAGGER_12_SCOPES) != null) {
                        JSONArray scopes = (JSONArray) oauth2.get(APIConstants.SWAGGER_12_SCOPES);

                        if (scopes != null) {
                            for (Object scopeObj : scopes) {
                                Map scopeMap = (Map) scopeObj;
                                if (scopeMap.get(APIConstants.SWAGGER_SCOPE_KEY) != null) {
                                    Scope scope = new Scope();
                                    scope.setKey((String) scopeMap.get(APIConstants.SWAGGER_SCOPE_KEY));
                                    scope.setName((String) scopeMap.get(APIConstants.SWAGGER_NAME));
                                    scope.setRoles((String) scopeMap.get(APIConstants.SWAGGER_ROLES));
                                    scope.setDescription((String) scopeMap.get(APIConstants.SWAGGER_DESCRIPTION));
                                    scopeList.add(scope);
                                }
                            }
                        }
                    }
                }
            }
        } catch (ParseException e) {
            handleException("Invalid resource configuration ", e);
        }

        return scopeList;
    }

    @Override
    @Deprecated
    public void saveAPIDefinition(API api, String apiDefinitionJSON, Registry registry) throws APIManagementException {
        String apiName = api.getId().getApiName();
        String apiVersion = api.getId().getVersion();
        String apiProviderName = api.getId().getProviderName();

        try {
            String resourcePath = APIUtil.getSwagger12DefinitionFilePath(apiName, apiVersion, apiProviderName);
            resourcePath = resourcePath + APIConstants.API_DOC_1_2_RESOURCE_NAME;
            Resource resource = registry.newResource();

            resource.setContent(apiDefinitionJSON);
            resource.setMediaType("application/json");
            registry.put(resourcePath, resource);

            //Set visibility as same as the API visibility
            APIUtil.setResourcePermissions(apiProviderName, api.getVisibility(), null, resourcePath);

        } catch (RegistryException e) {
            handleException("Error while adding Swagger Definition for " + apiName + "-" + apiVersion, e);
        }
    }

    @Override
    @Deprecated
    public String getAPIDefinition(APIIdentifier apiIdentifier, Registry registry) throws APIManagementException {
        String resourcePath = APIUtil.getSwagger12DefinitionFilePath(apiIdentifier.getApiName(),
                apiIdentifier.getVersion(), apiIdentifier.getProviderName());

        JSONParser parser = new JSONParser();
        JSONObject apiJSON = null;
        try {
            if (registry.resourceExists(resourcePath + APIConstants.API_DOC_1_2_RESOURCE_NAME)) {
                Resource apiDocResource = registry.get(resourcePath + APIConstants.API_DOC_1_2_RESOURCE_NAME);
                String apiDocContent = new String((byte[]) apiDocResource.getContent());
                apiJSON = (JSONObject) parser.parse(apiDocContent);
                JSONArray pathConfigs = (JSONArray) apiJSON.get(APIConstants.API_ARRAY_NAME);

                for (Object pathConfig : pathConfigs) {
                    JSONObject jsonObjPathConfig = (JSONObject) pathConfig;
                    String pathName = (String) jsonObjPathConfig.get(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD);
                    pathName = pathName.startsWith("/") ? pathName : ("/" + pathName);

                    Resource pathResource = registry.get(resourcePath + pathName);
                    String pathContent = new String((byte[]) pathResource.getContent());
                    JSONObject pathJSON = (JSONObject) parser.parse(pathContent);
                    jsonObjPathConfig.put(APIConstants.SWAGGER_FILE, pathJSON);
                }
            }
        } catch (RegistryException e) {
            handleException("Error while retrieving Swagger Definition for " + apiIdentifier.getApiName() + "-" +
                    apiIdentifier.getVersion(), e);
        } catch (ParseException e) {
            handleException("Error while parsing Swagger Definition for " + apiIdentifier.getApiName() + "-" +
                    apiIdentifier.getVersion() + " in " + resourcePath, e);
        }

        if (apiJSON != null) {
            return apiJSON.toJSONString();
        }
        return null;
    }

    @Override
    public String generateAPIDefinition(API api) throws APIManagementException {
        JSONParser parser = new JSONParser();
        String pathJsonTemplate = "{\n    \"path\": \"\",\n    \"operations\": []\n}";
        String operationJsonTemplate = "{\n    \"method\": \"\",\n    \"parameters\": []\n}";
        String apiJsonTemplate = "{\n    \"apiVersion\": \"\",\n    \"swaggerVersion\": \"1.2\",\n    " +
            "\"apis\": [],\n    \"info\": {\n        \"title\": \"\",\n        \"description\": \"\",\n       " +
            " \"termsOfServiceUrl\": \"\",\n        \"contact\": \"\",\n        \"license\": \"\",\n        " +
            "\"licenseUrl\": \"\"\n    },\n    \"authorizations\": {\n        \"oauth2\": {\n           " +
            " \"type\": \"oauth2\",\n            \"scopes\": []\n        }\n    }\n}";
        String apiResourceJsontemplate = "{\n    \"apiVersion\": \"\",\n    \"swaggerVersion\": \"1.2\",\n    " +
            "\"resourcePath\":\"\",\n    \"apis\": [],\n    \"info\": {\n        \"title\": \"\",\n        " +
            "\"description\": \"\",\n        \"termsOfServiceUrl\": \"\",\n        \"contact\": \"\",\n        " +
            "\"license\": \"\",\n        \"licenseUrl\": \"\"\n    },\n    \"authorizations\": {\n       " +
            " \"oauth2\": {\n            \"type\": \"oauth2\",\n            \"scopes\": []\n        }\n    }\n}";

        APIIdentifier identifier = api.getId();

        APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
                getAPIManagerConfigurationService().getAPIManagerConfiguration();

        Environment environment = (Environment) config.getApiGatewayEnvironments().values().toArray()[0];
        String endpoints = environment.getApiGatewayEndpoint();
        String[] endpointsSet = endpoints.split(",");
        String version = identifier.getVersion();
        Set<URITemplate> uriTemplates = api.getUriTemplates();
        String description = api.getDescription();

        if (endpointsSet.length < 1) {
            throw new APIManagementException("Error in creating JSON representation of the API" + identifier.getApiName());
        }
        if (description == null) {
            description = "";
        } else {
            description = description.trim();
        }

        Map<String, List<String>> resourceNamepaths = new HashMap<String, List<String>>();

        Map<String, JSONObject> resourceNameJSONs = new HashMap<String, JSONObject>();

        Map<String, List<JSONObject>> resourcePathJSONs = new HashMap<String, List<JSONObject>>();

        JSONObject mainAPIJson = null;

        try {
            mainAPIJson = (JSONObject) parser.parse(apiJsonTemplate);

            for (URITemplate template : uriTemplates) {

                String path = template.getUriTemplate();

                if (path != null && ("/*".equals(path) || ("/".equals(path)))) {
                    path = "/*";
                }
                List<String> resourcePaths;
                int resourceNameEndIndex = path.indexOf("/", 1);
                String resourceName = "/default";
                if (resourceNameEndIndex != -1) {
                    resourceName = path.substring(1, resourceNameEndIndex);
                }

                if (!resourceName.startsWith("/")) {
                    resourceName = "/" + resourceName;
                }

                if (resourceNamepaths.get(resourceName) != null) {
                    resourcePaths = resourceNamepaths.get(resourceName);
                    if (!resourcePaths.contains(path)) {
                        resourcePaths.add(path);
                    }
                    String httpVerbsStrng = template.getMethodsAsString();
                    String[] httpVerbs = httpVerbsStrng.split(" ");
                    for (String httpVerb : httpVerbs) {
                        final JSONObject operationJson = (JSONObject) parser.parse(operationJsonTemplate);
                        operationJson.put(APIConstants.SWAGGER_HTTP_METHOD, httpVerb);
                        operationJson.put(APIConstants.SWAGGER_AUTH_TYPE, template.getAuthType());
                        operationJson.put(APIConstants.API_THROTTLING_TIER, template.getThrottlingTier());

                        if (resourcePathJSONs.get(path) != null) {
                            resourcePathJSONs.get(path).add(operationJson);

                        } else {
                            resourcePathJSONs.put(path, new ArrayList<JSONObject>() {
                                {
                                    add(operationJson);
                                }
                            });
                        }
                    }
                    resourceNamepaths.put(resourceName, resourcePaths);
                } else {
                    JSONObject resourcePathJson = (JSONObject) parser.parse(apiResourceJsontemplate);

                    resourcePathJson.put(APIConstants.API_VERSION, version);
                    resourcePathJson.put(APIConstants.SWAGGER_RESOURCE_PATH, resourceName);
                    resourceNameJSONs.put(resourceName, resourcePathJson);

                    resourcePaths = new ArrayList<String>();
                    resourcePaths.add(path);

                    String httpVerbsStrng = template.getMethodsAsString();
                    String[] httpVerbs = httpVerbsStrng.split(" ");
                    for (String httpVerb : httpVerbs) {
                        final JSONObject operationJson = (JSONObject) parser.parse(operationJsonTemplate);
                        operationJson.put(APIConstants.SWAGGER_HTTP_METHOD, httpVerb);
                        operationJson.put(APIConstants.SWAGGER_AUTH_TYPE, template.getAuthType());
                        operationJson.put(APIConstants.API_THROTTLING_TIER, template.getThrottlingTier());

                        if (resourcePathJSONs.get(path) != null) {
                            resourcePathJSONs.get(path).add(operationJson);

                        } else {
                            resourcePathJSONs.put(path, new ArrayList<JSONObject>() {
                                {
                                    add(operationJson);
                                }
                            });
                        }
                    }
                    resourceNamepaths.put(resourceName, resourcePaths);
                }
            }

            for (Map.Entry<String, List<String>> entry : resourceNamepaths.entrySet()) {
                String resourcePath = entry.getKey();
                JSONObject jsonOb = resourceNameJSONs.get(resourcePath);
                List<String> pathItems = entry.getValue();
                for (String pathItem : pathItems) {
                    JSONObject pathJson = (JSONObject) parser.parse(pathJsonTemplate);
                    pathJson.put(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, pathItem);
                    List<JSONObject> methodJsons = resourcePathJSONs.get(pathItem);
                    for (JSONObject methodJson : methodJsons) {
                        JSONArray operations = (JSONArray) pathJson.get(APIConstants.SWAGGER_OPERATIONS);
                        operations.add(methodJson);
                    }
                    JSONArray apiArray = (JSONArray) jsonOb.get(APIConstants.API_ARRAY_NAME);
                    apiArray.add(pathJson);
                }
            }

            mainAPIJson.put(APIConstants.API_VERSION, version);
            ((JSONObject) mainAPIJson.get(APIConstants.SWAGGER_INFO)).put(APIConstants.SWAGGER_DESCRIPTION, description);
            for (Map.Entry<String, List<String>> entry : resourceNamepaths.entrySet()) {
                String resourcePath = entry.getKey();
                JSONObject jsonOb = resourceNameJSONs.get(resourcePath);
                JSONArray apiArray = (JSONArray) mainAPIJson.get(APIConstants.API_ARRAY_NAME);
                JSONObject pathjob = new JSONObject();
                pathjob.put(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, resourcePath);
                pathjob.put(APIConstants.SWAGGER_DESCRIPTION, "");
                pathjob.put(APIConstants.SWAGGER_FILE, jsonOb);
                apiArray.add(pathjob);

            }
        } catch (ParseException e) {
            throw new APIManagementException("Error while generating swagger 1.2 resource for api "
                    + api.getId().getProviderName()
                    + "-" + api.getId().getApiName()
                    + "-" + api.getId().getVersion(), e);
        }

        return mainAPIJson.toJSONString();
    }

    @Override
    public Map<String, String> getAPISwaggerDefinitionTimeStamps(APIIdentifier apiIdentifier, Registry registry) throws APIManagementException {
        return null;
    }
}


text:
package net.runelite.api.events;

import lombok.Value;
import net.runelite.api.Item;
import net.runelite.api.Tile;

/**
 * Called when an item pile spawns on the ground. When the client loads a new scene,
 * all item piles are implicitly reset and a new spawn event will be sent.
 */
@Value
public class ItemSpawned
{
	private final Tile tile;
	private final Item item;
}


text:
let project = new Project('New Project');
project.addAssets('Assets/**');
project.addSources('Sources');
project.addLibrary('Sdg');
project.addLibrary('haxe-format-tiled');
project.windowOptions.width = 1024;
project.windowOptions.height = 320;
resolve(project);


text:
/*
*
* Mathematics Subpackage (VrMath)
*
*
* Author: Samuel R. Buss, sbuss@ucsd.edu.
* Web page: http://math.ucsd.edu/~sbuss/MathCG
*
*
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*
*
*/

//
// MatrixRmn.cpp:  Matrix over reals  (Variable dimensional vector)
//
//    Not very sophisticated yet.  Needs more functionality
//		To do: better handling of resizing.
//

#include "MatrixRmn.h"

MatrixRmn MatrixRmn::WorkMatrix;		// Temporary work matrix

// Fill the diagonal entries with the value d.  The rest of the matrix is unchanged.
void MatrixRmn::SetDiagonalEntries( double d )
{
	long diagLen = Min( NumRows, NumCols );
	double* dPtr = x;
	for ( ; diagLen>0; diagLen-- ) {
		*dPtr = d;
		dPtr += NumRows+1;
	}
}

// Fill the diagonal entries with values in vector d.  The rest of the matrix is unchanged.
void MatrixRmn::SetDiagonalEntries( const VectorRn& d )
{
	long diagLen = Min( NumRows, NumCols );
	assert ( d.length == diagLen );
	double* dPtr = x;
	double* from = d.x;
	for ( ; diagLen>0; diagLen-- ) {
		*dPtr = *(from++);
		dPtr += NumRows+1;
	}
}

// Fill the superdiagonal entries with the value d.  The rest of the matrix is unchanged.
void MatrixRmn::SetSuperDiagonalEntries( double d )
{
	long sDiagLen = Min( NumRows, (long)(NumCols-1) );
	double* to = x + NumRows;
	for ( ; sDiagLen>0; sDiagLen-- ) {
		*to = d;
		to += NumRows+1;
	}
}

// Fill the superdiagonal entries with values in vector d.  The rest of the matrix is unchanged.
void MatrixRmn::SetSuperDiagonalEntries( const VectorRn& d )
{
	long sDiagLen = Min( (long)(NumRows-1), NumCols );
	assert ( sDiagLen == d.length );
	double* to = x + NumRows;
	double* from = d.x;
	for ( ; sDiagLen>0; sDiagLen-- ) {
		*to = *(from++);
		to += NumRows+1;
	}
}

// Fill the subdiagonal entries with the value d.  The rest of the matrix is unchanged.
void MatrixRmn::SetSubDiagonalEntries( double d )
{
	long sDiagLen = Min( NumRows, NumCols ) - 1;
	double* to = x + 1;
	for ( ; sDiagLen>0; sDiagLen-- ) {
		*to = d;
		to += NumRows+1;
	}
}

// Fill the subdiagonal entries with values in vector d.  The rest of the matrix is unchanged.
void MatrixRmn::SetSubDiagonalEntries( const VectorRn& d )
{
	long sDiagLen = Min( NumRows, NumCols ) - 1;
	assert ( sDiagLen == d.length );
	double* to = x + 1;
	double* from = d.x;
	for ( ; sDiagLen>0; sDiagLen-- ) {
		*to = *(from++);
		to += NumRows+1;
	}
}

// Set the i-th column equal to d.
void MatrixRmn::SetColumn(long i, const VectorRn& d )
{
	assert ( NumRows==d.GetLength() );
	double* to = x+i*NumRows;
	const double* from = d.x;
	for ( i=NumRows; i>0; i-- ) {
		*(to++) = *(from++);
	}
}

// Set the i-th column equal to d.
void MatrixRmn::SetRow(long i, const VectorRn& d )
{
	assert ( NumCols==d.GetLength() );
	double* to = x+i;
	const double* from = d.x;
	for ( i=NumRows; i>0; i-- ) {
		*to = *(from++);
		to += NumRows;
	}
}

// Sets a "linear" portion of the array with the values from a vector d
// The first row and column position are given by startRow, startCol.
// Successive positions are found by using the deltaRow, deltaCol values
//	to increment the row and column indices.  There is no wrapping around.
void MatrixRmn::SetSequence( const VectorRn& d, long startRow, long startCol, long deltaRow, long deltaCol )
{
	long length = d.length;
	assert( startRow>=0 && startRow<NumRows && startCol>=0 && startCol<NumCols );
	assert( startRow+(length-1)*deltaRow>=0 && startRow+(length-1)*deltaRow<NumRows );
 	assert( startCol+(length-1)*deltaCol>=0 && startCol+(length-1)*deltaCol<NumCols );
	double *to = x + startRow + NumRows*startCol;
	double *from = d.x;
	long stride = deltaRow + NumRows*deltaCol;
	for ( ; length>0; length-- ) {
		*to = *(from++);
		to += stride;
	}
}

// The matrix A is loaded, in into "this" matrix, based at (0,0).
//  The size of "this" matrix must be large enough to accomodate A.
//	The rest of "this" matrix is left unchanged.  It is not filled with zeroes!

void MatrixRmn::LoadAsSubmatrix( const MatrixRmn& A )
{
	assert( A.NumRows<=NumRows && A.NumCols<=NumCols );
	int extraColStep = NumRows - A.NumRows;
	double *to = x;
	double *from = A.x;
	for ( long i=A.NumCols; i>0; i-- ) {			// Copy columns of A, one per time thru loop
		for ( long j=A.NumRows; j>0; j-- ) {		// Copy all elements of this column of A
			*(to++) = *(from++);
		}
		to += extraColStep;
	}
}

// The matrix A is loaded, in transposed order into "this" matrix, based at (0,0).
//  The size of "this" matrix must be large enough to accomodate A.
//	The rest of "this" matrix is left unchanged.  It is not filled with zeroes!
void MatrixRmn::LoadAsSubmatrixTranspose( const MatrixRmn& A )
{
	assert( A.NumRows<=NumCols && A.NumCols<=NumRows );
	double* rowPtr = x;
	double* from = A.x;
	for ( long i=A.NumCols; i>0; i-- ) {				// Copy columns of A, once per loop
		double* to = rowPtr;
		for ( long j=A.NumRows; j>0; j-- ) {			// Loop copying values from the column of A
			*to = *(from++);
			to += NumRows;
		}
		rowPtr ++;
	}
}

// Calculate the Frobenius Norm (square root of sum of squares of entries of the matrix)
double MatrixRmn::FrobeniusNorm() const
{
	return sqrt( FrobeniusNormSq() );
}

// Multiply this matrix by column vector v.
// Result is column vector "result"
void MatrixRmn::Multiply( const VectorRn& v, VectorRn& result ) const
{
	assert ( v.GetLength()==NumCols && result.GetLength()==NumRows );
	double* out = result.GetPtr();				// Points to entry in result vector
	const double* rowPtr = x;					// Points to beginning of next row in matrix
	for ( long j = NumRows; j>0; j-- ) {
		const double* in = v.GetPtr();
		const double* m = rowPtr++;
		*out = 0.0f;
		for ( long i = NumCols; i>0; i-- ) {
			*out += (*(in++)) * (*m);
			m += NumRows;
		}
		out++;
	}
}

// Multiply transpose of this matrix by column vector v.
//    Result is column vector "result"
// Equivalent to mult by row vector on left
void MatrixRmn::MultiplyTranspose( const VectorRn& v, VectorRn& result ) const
{
	assert ( v.GetLength()==NumRows && result.GetLength()==NumCols );
	double* out = result.GetPtr();				// Points to entry in result vector
	const double* colPtr = x;					// Points to beginning of next column in matrix
	for ( long i=NumCols; i>0; i-- ) {
		const double* in=v.GetPtr();
		*out = 0.0f;
		for ( long j = NumRows; j>0; j-- ) {
			*out += (*(in++)) * (*(colPtr++));
		}
		out++;
	}
}

// Form the dot product of a vector v with the i-th column of the array
double MatrixRmn::DotProductColumn( const VectorRn& v, long colNum ) const
{
	assert ( v.GetLength()==NumRows );
	double* ptrC = x+colNum*NumRows;
	double* ptrV = v.x;
	double ret = 0.0;
	for ( long i = NumRows; i>0; i-- ) {
		ret += (*(ptrC++))*(*(ptrV++));
	}
	return ret;
}

// Add a constant to each entry on the diagonal
MatrixRmn& MatrixRmn::AddToDiagonal( double d )				// Adds d to each diagonal entry
{
	long diagLen = Min( NumRows, NumCols );
	double* dPtr = x;
	for ( ; diagLen>0; diagLen-- ) {
		*dPtr += d;
		dPtr += NumRows+1;
	}
	return *this;
}

// Add a vector to the entries on the diagonal
MatrixRmn& MatrixRmn::AddToDiagonal( const VectorRn& dVec )				// Adds dVec to the diagonal entries
{
    long diagLen = Min( NumRows, NumCols );
    double* dPtr = x;
    for (int i = 0; i < diagLen && i < dVec.GetLength(); ++i) {
        *dPtr += dVec[i];
        dPtr += NumRows+1;
    }
    return *this;
}

// Multiply two MatrixRmn's
MatrixRmn& MatrixRmn::Multiply( const MatrixRmn& A, const MatrixRmn& B, MatrixRmn& dst )
{
	assert( A.NumCols == B.NumRows && A.NumRows == dst.NumRows && B.NumCols == dst.NumCols );
	long length = A.NumCols;

	double *bPtr = B.x;						// Points to beginning of column in B
	double *dPtr = dst.x;
	for ( long i = dst.NumCols; i>0; i-- ) {
		double *aPtr = A.x;					// Points to beginning of row in A
		for ( long j = dst.NumRows; j>0; j-- ) {
			*dPtr = DotArray( length, aPtr, A.NumRows, bPtr, 1 );
			dPtr++;
			aPtr++;
		}
		bPtr += B.NumRows;
	}

	return dst;
}

// Multiply two MatrixRmn's,  Transpose the first matrix before multiplying
MatrixRmn& MatrixRmn::TransposeMultiply( const MatrixRmn& A, const MatrixRmn& B, MatrixRmn& dst )
{
	assert( A.NumRows == B.NumRows && A.NumCols == dst.NumRows && B.NumCols == dst.NumCols );
	long length = A.NumRows;

	double *bPtr = B.x;										// bPtr Points to beginning of column in B
	double *dPtr = dst.x;
	for ( long i = dst.NumCols; i>0; i-- ) {				// Loop over all columns of dst
		double *aPtr = A.x;									// aPtr Points to beginning of column in A
		for ( long j = dst.NumRows; j>0; j-- ) {			// Loop over all rows of dst
			*dPtr = DotArray( length, aPtr, 1, bPtr, 1 );
			dPtr ++;
			aPtr += A.NumRows;
		}
		bPtr += B.NumRows;
	}

	return dst;
}

// Multiply two MatrixRmn's.  Transpose the second matrix before multiplying
MatrixRmn& MatrixRmn::MultiplyTranspose( const MatrixRmn& A, const MatrixRmn& B, MatrixRmn& dst )
{
	assert( A.NumCols == B.NumCols && A.NumRows == dst.NumRows && B.NumRows == dst.NumCols );
	long length = A.NumCols;

	double *bPtr = B.x;						// Points to beginning of row in B
	double *dPtr = dst.x;
	for ( long i = dst.NumCols; i>0; i-- ) {
		double *aPtr = A.x;					// Points to beginning of row in A
		for ( long j = dst.NumRows; j>0; j-- ) {
			*dPtr = DotArray( length, aPtr, A.NumRows, bPtr, B.NumRows );
			dPtr++;
			aPtr++;
		}
		bPtr++;
	}

	return dst;
}

// Solves the equation   (*this)*xVec = b;
// Uses row operations.  Assumes *this is square and invertible.
// No error checking for divide by zero or instability (except with asserts)
void MatrixRmn::Solve( const VectorRn& b, VectorRn* xVec ) const
{
	assert ( NumRows==NumCols && NumCols==xVec->GetLength() && NumRows==b.GetLength() );

	// Copy this matrix and b into an Augmented Matrix
	MatrixRmn& AugMat = GetWorkMatrix( NumRows, NumCols+1 );
	AugMat.LoadAsSubmatrix( *this );
	AugMat.SetColumn( NumRows, b );

	// Put into row echelon form with row operations
	AugMat.ConvertToRefNoFree();

	// Solve for x vector values using back substitution
	double* xLast = xVec->x+NumRows-1;				// Last entry in xVec
	double* endRow = AugMat.x+NumRows*NumCols-1;	// Last entry in the current row of the coefficient part of Augmented Matrix
	double* bPtr = endRow+NumRows;				// Last entry in augmented matrix (end of last column, in augmented part)
	for ( long i = NumRows; i>0; i-- ) {
		double accum = *(bPtr--);
		// Next loop computes back substitution terms
		double* rowPtr = endRow;					// Points to entries of the current row for back substitution.
		double* xPtr = xLast;						// Points to entries in the x vector (also for back substitution)
		for ( long j=NumRows-i; j>0; j-- ) {
			accum -= (*rowPtr)*(*(xPtr--));
			rowPtr -= NumCols;						// Previous entry in the row
		}
		assert( *rowPtr != 0.0 );					// Are not supposed to be any free variables in this matrix
		*xPtr = accum/(*rowPtr);
		endRow--;
	}
}

// ConvertToRefNoFree
// Converts the matrix (in place) to row echelon form
// For us, row echelon form allows any non-zero values, not just 1's, in the
//		position for a lead variable.
// The "NoFree" version operates on the assumption that no free variable will be found.
// Algorithm uses row operations and row pivoting (only).
// Augmented matrix is correctly accomodated.  Only the first square part participates
//		in the main work of row operations.
void MatrixRmn::ConvertToRefNoFree()
{
	// Loop over all columns (variables)
	// Find row with most non-zero entry.
	// Swap to the highest active row
	// Subtract appropriately from all the lower rows (row op of type 3)
	long numIters = Min(NumRows,NumCols);
	double* rowPtr1 = x;
	const long diagStep = NumRows+1;
	long lenRowLeft = NumCols;
	for ( ; numIters>1; numIters-- ) {
		// Find row with most non-zero entry.
		double* rowPtr2 = rowPtr1;
		double maxAbs = fabs(*rowPtr1);
		double *rowPivot = rowPtr1;
		long i;
		for ( i=numIters-1; i>0; i-- ) {
			const double& newMax = *(++rowPivot);
			if ( newMax > maxAbs ) {
				maxAbs = *rowPivot;
				rowPtr2 = rowPivot;
			}
			else if ( -newMax > maxAbs ) {
				maxAbs = -newMax;
				rowPtr2 = rowPivot;
			}
		}
		// Pivot step: Swap the row with highest entry to the current row
		if ( rowPtr1 != rowPtr2 ) {
			double *to = rowPtr1;
			for ( long i=lenRowLeft; i>0; i-- ) {
				double temp = *to;
				*to = *rowPtr2;
				*rowPtr2 = temp;
				to += NumRows;
				rowPtr2 += NumRows;
			}
		}
		// Subtract this row appropriately from all the lower rows (row operation of type 3)
		rowPtr2 = rowPtr1;
		for ( i=numIters-1; i>0; i-- ) {
			rowPtr2++;
			double* to = rowPtr2;
			double* from = rowPtr1;
			assert( *from != 0.0 );
			double alpha = (*to)/(*from);
			*to = 0.0;
			for ( long j=lenRowLeft-1; j>0; j-- ) {
				to += NumRows;
				from += NumRows;
				*to -= (*from)*alpha;
			}
		}
		// Update for next iteration of loop
		rowPtr1 += diagStep;
		lenRowLeft--;
	}

}

// Calculate the c=cosine and s=sine values for a Givens transformation.
// The matrix M = ( (c, -s), (s, c) ) in row order transforms the
//   column vector (a, b)^T to have y-coordinate zero.
void MatrixRmn::CalcGivensValues( double a, double b, double *c, double *s )
{
	double denomInv = sqrt(a*a + b*b);
	if ( denomInv==0.0 ) {
		*c = 1.0;
		*s = 0.0;
	}
	else {
		denomInv = 1.0/denomInv;
		*c = a*denomInv;
		*s = -b*denomInv;
	}
}

// Applies Givens transform to columns i and i+1.
// Equivalent to postmultiplying by the matrix
//      ( c  -s )
//		( s   c )
// with non-zero entries in rows i and i+1 and columns i and i+1
void MatrixRmn::PostApplyGivens( double c, double s, long idx )
{
	assert ( 0<=idx && idx<NumCols );
	double *colA = x + idx*NumRows;
	double *colB = colA + NumRows;
	for ( long i = NumRows; i>0; i-- ) {
		double temp = *colA;
		*colA = (*colA)*c + (*colB)*s;
		*colB = (*colB)*c - temp*s;
		colA++;
		colB++;
	}
}

// Applies Givens transform to columns idx1 and idx2.
// Equivalent to postmultiplying by the matrix
//      ( c  -s )
//		( s   c )
// with non-zero entries in rows idx1 and idx2 and columns idx1 and idx2
void MatrixRmn::PostApplyGivens( double c, double s, long idx1, long idx2 )
{
	assert ( idx1!=idx2 && 0<=idx1 && idx1<NumCols && 0<=idx2 && idx2<NumCols );
	double *colA = x + idx1*NumRows;
	double *colB = x + idx2*NumRows;
	for ( long i = NumRows; i>0; i-- ) {
		double temp = *colA;
		*colA = (*colA)*c + (*colB)*s;
		*colB = (*colB)*c - temp*s;
		colA++;
		colB++;
	}
}

// ********************************************************************************************
// Singular value decomposition.
// Return othogonal matrices U and V and diagonal matrix with diagonal w such that
//     (this) = U * Diag(w) * V^T     (V^T is V-transpose.)
// Diagonal entries have all non-zero entries before all zero entries, but are not
//		necessarily sorted.  (Someday, I will write ComputedSortedSVD that handles
//		sorting the eigenvalues by magnitude.)
// ********************************************************************************************
void MatrixRmn::ComputeSVD( MatrixRmn& U, VectorRn& w, MatrixRmn& V ) const
{
	assert ( U.NumRows==NumRows && V.NumCols==NumCols
			 && U.NumRows==U.NumCols && V.NumRows==V.NumCols
			 && w.GetLength()==Min(NumRows,NumCols) );

//	double temp=0.0;
	VectorRn& superDiag = VectorRn::GetWorkVector( w.GetLength()-1 );		// Some extra work space.  Will get passed around.

	// Choose larger of U, V to hold intermediate results
	// If U is larger than V, use U to store intermediate results
	// Otherwise use V.  In the latter case, we form the SVD of A transpose,
	//		(which is essentially identical to the SVD of A).
	MatrixRmn* leftMatrix;
	MatrixRmn* rightMatrix;
	if ( NumRows >= NumCols ) {
		U.LoadAsSubmatrix( *this );				// Copy A into U
		leftMatrix = &U;
		rightMatrix = &V;
	}
	else {
		V.LoadAsSubmatrixTranspose( *this );		// Copy A-transpose into V
		leftMatrix = &V;
		rightMatrix = &U;
	}

	// Do the actual work to calculate the SVD
	// Now matrix has at least as many rows as columns
	CalcBidiagonal( *leftMatrix, *rightMatrix, w, superDiag );
	ConvertBidiagToDiagonal( *leftMatrix, *rightMatrix, w, superDiag );

}

void MatrixRmn::ComputeInverse( MatrixRmn& R) const
{
    assert ( this->NumRows==this->NumCols );
    MatrixRmn U(this->NumRows, this->NumCols);
    VectorRn w(this->NumRows);
    MatrixRmn V(this->NumRows, this->NumCols);

    this->ComputeSVD(U, w, V);

    assert(this->DebugCheckSVD(U, w , V));

    double PseudoInverseThresholdFactor = 0.01;
    double pseudoInverseThreshold = PseudoInverseThresholdFactor*w.MaxAbs();

    MatrixRmn VD(this->NumRows, this->NumCols);
    MatrixRmn D(this->NumRows, this->NumCols);
    D.SetZero();
    long diagLength = w.GetLength();
    double* wPtr = w.GetPtr();
    for ( long i = 0; i < diagLength; ++i ) {
        double alpha = *(wPtr++);
        if ( fabs(alpha)>pseudoInverseThreshold ) {
            D.Set(i, i, 1.0/alpha);
        }
    }

    Multiply(V,D,VD);
    MultiplyTranspose(VD,U,R);
}

// ************************************************ CalcBidiagonal **************************
// Helper routine for SVD computation
// U is a matrix to be bidiagonalized.
// On return, U and V are orthonormal and w holds the new diagonal
//	  elements and superDiag holds the super diagonal elements.

void MatrixRmn::CalcBidiagonal( MatrixRmn& U, MatrixRmn& V, VectorRn& w, VectorRn& superDiag )
{
	assert ( U.NumRows>=V.NumRows );

	// The diagonal and superdiagonal entries of the bidiagonalized
	//	  version of the U matrix
	//	  are stored in the vectors w and superDiag (temporarily).

	// Apply Householder transformations to U.
	// Householder transformations come in pairs.
	//   First, on the left, we map a portion of a column to zeros
	//   Second, on the right, we map a portion of a row to zeros
	const long rowStep = U.NumCols;
	const long diagStep = U.NumCols+1;
	double *diagPtr = U.x;
	double* wPtr = w.x;
	double* superDiagPtr = superDiag.x;
	long colLengthLeft = U.NumRows;
	long rowLengthLeft = V.NumCols;
	while (true) {
		// Apply a Householder xform on left to zero part of a column
		SvdHouseholder( diagPtr, colLengthLeft, rowLengthLeft, 1, rowStep, wPtr );

		if ( rowLengthLeft==2 ) {
			*superDiagPtr = *(diagPtr+rowStep);
			break;
		}
		// Apply a Householder xform on the right to zero part of a row
		SvdHouseholder( diagPtr+rowStep, rowLengthLeft-1, colLengthLeft, rowStep, 1, superDiagPtr );

		rowLengthLeft--;
		colLengthLeft--;
		diagPtr += diagStep;
		wPtr++;
		superDiagPtr++;
	}

	int extra = 0;
	diagPtr += diagStep;
	wPtr++;
	if ( colLengthLeft > 2 ) {
		extra = 1;
		// Do one last Householder transformation when the matrix is not square
		colLengthLeft--;
		SvdHouseholder( diagPtr, colLengthLeft, 1, 1, 0, wPtr );
	}
	else {
		*wPtr = *diagPtr;
	}

	// Form U and V from the Householder transformations
	V.ExpandHouseholders( V.NumCols-2, 1, U.x+U.NumRows, U.NumRows, 1 );
	U.ExpandHouseholders( V.NumCols-1+extra, 0, U.x, 1, U.NumRows );

	// Done with bidiagonalization
	return;
}

// Helper routine for CalcBidiagonal
// Performs a series of Householder transformations on a matrix
// Stores results compactly into the matrix:   The Householder vector u (normalized)
//   is stored into the first row/column being transformed.
// The leading term of that row (= plus/minus its magnitude is returned
//	 separately into "retFirstEntry"
void MatrixRmn::SvdHouseholder( double* basePt,
							    long colLength, long numCols, long colStride, long rowStride,
								double* retFirstEntry )
{

	// Calc norm of vector u
	double* cPtr = basePt;
	double norm = 0.0;
	long i;
	for ( i=colLength; i>0 ; i-- ) {
		norm += Square( *cPtr );
		cPtr += colStride;
	}
	norm = sqrt(norm);					// Norm of vector to reflect to axis  e_1

	// Handle sign issues
	double imageVal;					// Choose sign to maximize distance
	if ( (*basePt) < 0.0 ) {
		imageVal = norm;
		norm = 2.0*norm*(norm-(*basePt));
	}
	else {
		imageVal = -norm;
		norm = 2.0*norm*(norm+(*basePt));
	}
	norm = sqrt(norm);					// Norm is norm of reflection vector

	if ( norm==0.0 ) {			// If the vector being transformed is equal to zero
		// Force to zero in case of roundoff errors
		cPtr = basePt;
		for ( i=colLength; i>0; i-- ) {
			*cPtr = 0.0;
			cPtr += colStride;
		}
		*retFirstEntry = 0.0;
		return;
	}

	*retFirstEntry = imageVal;

	// Set up the normalized Householder vector
	*basePt -= imageVal;					// First component changes. Rest stay the same.
	// Normalize the vector
	norm = 1.0/norm;					// Now it is the inverse norm
	cPtr = basePt;
	for ( i=colLength; i>0 ; i-- ) {
		*cPtr *= norm;
		cPtr += colStride;
	}

	// Transform the rest of the U matrix with the Householder transformation
	double *rPtr = basePt;
	for ( long j=numCols-1; j>0; j-- ) {
		rPtr += rowStride;
		// Calc dot product with Householder transformation vector
		double dotP = DotArray( colLength, basePt, colStride, rPtr, colStride );
		// Transform with I - 2*dotP*(Householder vector)
		AddArrayScale( colLength, basePt, colStride, rPtr, colStride, -2.0*dotP );
	}
}

// ********************************* ExpandHouseholders ********************************************
// The matrix will be square.
//   numXforms = number of Householder transformations to concatenate
//		Each Householder transformation is represented by a unit vector
//		Each successive Householder transformation starts one position later
//			and has one more implied leading zero
//	 basePt = beginning of the first Householder transform
//	 colStride, rowStride: Householder xforms are stored in "columns"
//   numZerosSkipped is the number of implicit zeros on the front each
//			Householder transformation vector (only values supported are 0 and 1).
void MatrixRmn::ExpandHouseholders( long numXforms, int numZerosSkipped, const double* basePt, long colStride, long rowStride )
{
	// Number of applications of the last Householder transform
	//     (That are not trivial!)
	long numToTransform = NumCols-numXforms+1-numZerosSkipped;
	assert( numToTransform>0 );

	if ( numXforms==0 ) {
		SetIdentity();
		return;
	}

	// Handle the first one separately as a special case,
	// "this" matrix will be treated to simulate being preloaded with the identity
	long hDiagStride = rowStride+colStride;
	const double* hBase = basePt + hDiagStride*(numXforms-1);	// Pointer to the last Householder vector
	const double* hDiagPtr = hBase + colStride*(numToTransform-1);		// Pointer to last entry in that vector
	long i;
	double* diagPtr = x+NumCols*NumRows-1;					// Last entry in matrix (points to diagonal entry)
	double* colPtr = diagPtr-(numToTransform-1);			// Pointer to column in matrix
	for ( i=numToTransform; i>0; i-- ) {
		CopyArrayScale( numToTransform, hBase, colStride, colPtr, 1, -2.0*(*hDiagPtr) );
		*diagPtr += 1.0;						// Add back in 1 to the diagonal entry (since xforming the identity)
		diagPtr -= (NumRows+1);					// Next diagonal entry in this matrix
		colPtr -= NumRows;						// Next column in this matrix
		hDiagPtr -= colStride;
	}

	// Now handle the general case
	// A row of zeros must be in effect added to the top of each old column (in each loop)
	double* colLastPtr = x + NumRows*NumCols - numToTransform - 1;
	for ( i = numXforms-1; i>0; i-- ) {
		numToTransform++;							// Number of non-trivial applications of this Householder transformation
		hBase -= hDiagStride;						// Pointer to the beginning of the Householder transformation
		colPtr = colLastPtr;
		for ( long j = numToTransform-1; j>0; j-- ) {
			// Get dot product
			double dotProd2N = -2.0*DotArray( numToTransform-1, hBase+colStride, colStride, colPtr+1, 1 );
			*colPtr = dotProd2N*(*hBase);			// Adding onto zero at initial point
			AddArrayScale( numToTransform-1, hBase+colStride, colStride, colPtr+1, 1, dotProd2N );
			colPtr -= NumRows;
		}
		// Do last one as a special case (may overwrite the Householder vector)
		CopyArrayScale( numToTransform, hBase, colStride, colPtr, 1, -2.0*(*hBase) );
		*colPtr += 1.0;				// Add back one one as identity
		// Done with this Householder transformation
		colLastPtr --;
	}

	if ( numZerosSkipped!=0 ) {
		assert( numZerosSkipped==1 );
		// Fill first row and column with identity (More generally: first numZerosSkipped many rows and columns)
		double* d = x;
		*d = 1;
		double* d2 = d;
		for ( i=NumRows-1; i>0; i-- ) {
			*(++d) = 0;
			*(d2+=NumRows) = 0;
		}
	}
}

// **************** ConvertBidiagToDiagonal ***********************************************
// Do the iterative transformation from bidiagonal form to diagonal form using
//		Givens transformation.  (Golub-Reinsch)
// U and V are square.  Size of U less than or equal to that of U.
void MatrixRmn::ConvertBidiagToDiagonal( MatrixRmn& U, MatrixRmn& V, VectorRn& w, VectorRn& superDiag ) const
{
	// These two index into the last bidiagonal block  (last in the matrix, it will be
	//	first one handled.
	long lastBidiagIdx = V.NumRows-1;
	long firstBidiagIdx = 0;
	double eps = 1.0e-15 * Max(w.MaxAbs(), superDiag.MaxAbs());

	while ( true ) {
		bool workLeft = UpdateBidiagIndices( &firstBidiagIdx, &lastBidiagIdx, w, superDiag, eps );
		if ( !workLeft ) {
			break;
		}

		// Get ready for first Givens rotation
		// Push non-zero to M[2,1] with Givens transformation
		double* wPtr = w.x+firstBidiagIdx;
		double* sdPtr = superDiag.x+firstBidiagIdx;
		double extraOffDiag=0.0;
		if ( (*wPtr)==0.0 ) {
			ClearRowWithDiagonalZero( firstBidiagIdx, lastBidiagIdx, U, wPtr, sdPtr, eps );
			if ( firstBidiagIdx>0 ) {
				if ( NearZero( *(--sdPtr), eps ) ) {
					*sdPtr = 0.0;
				}
				else {
					ClearColumnWithDiagonalZero( firstBidiagIdx, V, wPtr, sdPtr, eps );
				}
			}
			continue;
		}

		// Estimate an eigenvalue from bottom four entries of M
		// This gives a lambda value which will shift the Givens rotations
		// Last four entries of M^T * M are  ( ( A, B ), ( B, C ) ).
		double A;
		A = (firstBidiagIdx<lastBidiagIdx-1) ? Square(superDiag[lastBidiagIdx-2]): 0.0;
		double BSq = Square(w[lastBidiagIdx-1]);
		A += BSq;										// The "A" entry of M^T * M
		double C = Square(superDiag[lastBidiagIdx-1]);
		BSq *= C;										// The squared "B" entry
		C += Square(w[lastBidiagIdx]);					// The "C" entry
		double lambda;									// lambda will hold the estimated eigenvalue
		lambda = sqrt( Square((A-C)*0.5) + BSq );		// Use the lambda value that is closest to C.
		if ( A > C ) {
			lambda = -lambda;
		}
		lambda += (A+C)*0.5;						// Now lambda equals the estimate for the last eigenvalue
		double t11 = Square(w[firstBidiagIdx]);
		double t12 = w[firstBidiagIdx]*superDiag[firstBidiagIdx];

		double c, s;
		CalcGivensValues( t11-lambda, t12, &c, &s );
		ApplyGivensCBTD( c, s, wPtr, sdPtr, &extraOffDiag, wPtr+1 );
		V.PostApplyGivens( c, -s, firstBidiagIdx );
		long i;
		for ( i=firstBidiagIdx; i<lastBidiagIdx-1; i++ ) {
			// Push non-zero from M[i+1,i] to M[i,i+2]
			CalcGivensValues( *wPtr, extraOffDiag, &c, &s );
			ApplyGivensCBTD( c, s, wPtr, sdPtr, &extraOffDiag, extraOffDiag, wPtr+1, sdPtr+1 );
			U.PostApplyGivens( c, -s, i );
			// Push non-zero from M[i,i+2] to M[1+2,i+1]
			CalcGivensValues( *sdPtr, extraOffDiag, &c, &s );
			ApplyGivensCBTD( c, s, sdPtr, wPtr+1, &extraOffDiag, extraOffDiag, sdPtr+1, wPtr+2 );
			V.PostApplyGivens( c, -s, i+1 );
			wPtr++;
			sdPtr++;
		}
		// Push non-zero value from M[i+1,i] to M[i,i+1] for i==lastBidiagIdx-1
		CalcGivensValues( *wPtr, extraOffDiag, &c, &s );
		ApplyGivensCBTD( c, s, wPtr, &extraOffDiag, sdPtr, wPtr+1 );
		U.PostApplyGivens( c, -s, i );

		// DEBUG
		// DebugCalcBidiagCheck( V, w, superDiag, U );
	}
}

// This is called when there is a zero diagonal entry, with a non-zero superdiagonal entry on the same row.
// We use Givens rotations to "chase" the non-zero entry across the row; when it reaches the last
//	column, it is finally zeroed away.
// wPtr points to the zero entry on the diagonal.  sdPtr points to the non-zero superdiagonal entry on the same row.
void MatrixRmn::ClearRowWithDiagonalZero( long firstBidiagIdx, long lastBidiagIdx, MatrixRmn& U, double *wPtr, double *sdPtr, double eps )
{
	double curSd = *sdPtr;		// Value being chased across the row
	*sdPtr = 0.0;
	long i=firstBidiagIdx+1;
	while (true) {
		// Rotate row i and row firstBidiagIdx (Givens rotation)
		double c, s;
		CalcGivensValues( *(++wPtr), curSd, &c, &s );
		U.PostApplyGivens( c, -s, i, firstBidiagIdx );
		*wPtr = c*(*wPtr) - s*curSd;
		if ( i==lastBidiagIdx ) {
			break;
		}
		curSd = s*(*(++sdPtr));		// New value pops up one column over to the right
		*sdPtr = c*(*sdPtr);
		i++;
	}
}

// This is called when there is a zero diagonal entry, with a non-zero superdiagonal entry in the same column.
// We use Givens rotations to "chase" the non-zero entry up the column; when it reaches the last
//	column, it is finally zeroed away.
// wPtr points to the zero entry on the diagonal.  sdPtr points to the non-zero superdiagonal entry in the same column.
void MatrixRmn::ClearColumnWithDiagonalZero( long endIdx, MatrixRmn& V, double *wPtr, double *sdPtr, double eps )
{
	double curSd = *sdPtr;		// Value being chased up the column
	*sdPtr = 0.0;
	long i = endIdx-1;
	while ( true ) {
		double c, s;
		CalcGivensValues( *(--wPtr), curSd, &c, &s );
		V.PostApplyGivens( c, -s, i, endIdx );
		*wPtr = c*(*wPtr) - s*curSd;
		if ( i==0 ) {
			break;
		}
		curSd = s*(*(--sdPtr));		// New value pops up one row above
		if ( NearZero( curSd, eps ) ) {
			break;
		}
		*sdPtr = c*(*sdPtr);
		i--;
	}
}

// Matrix A is  ( ( a c ) ( b d ) ), i.e., given in column order.
// Mult's G[c,s]  times  A, replaces A.
void MatrixRmn::ApplyGivensCBTD( double cosine, double sine, double *a, double *b, double *c, double *d )
{
	double temp = *a;
	*a = cosine*(*a) - sine*(*b);
	*b = sine*temp + cosine*(*b);
	temp = *c;
	*c = cosine*(*c) - sine*(*d);
	*d = sine*temp + cosine*(*d);
}

// Now matrix A given in row order, A = ( ( a b c ) ( d e f ) ).
// Return G[c,s] * A, replace A.  d becomes zero, no need to return.
//  Also, it is certain the old *c value is taken to be zero!
void MatrixRmn::ApplyGivensCBTD( double cosine, double sine, double *a, double *b, double *c,
															 double  d, double *e, double *f )
{
	*a = cosine*(*a) - sine*d;
	double temp = *b;
	*b = cosine*(*b) - sine*(*e);
	*e = sine*temp + cosine*(*e);
	*c =  -sine*(*f);
	*f =  cosine*(*f);
}

// Helper routine for SVD conversion from bidiagonal to diagonal
bool MatrixRmn::UpdateBidiagIndices( long *firstBidiagIdx, long *lastBidiagIdx, VectorRn& w, VectorRn& superDiag, double eps )
{
	long lastIdx = *lastBidiagIdx;
	double* sdPtr = superDiag.GetPtr( lastIdx-1 );		// Entry above the last diagonal entry
	while ( NearZero(*sdPtr, eps) ) {
		*(sdPtr--) = 0.0;
		lastIdx--;
		if ( lastIdx == 0 ) {
			return false;
		}
	}
	*lastBidiagIdx = lastIdx;
	long firstIdx = lastIdx-1;
	double* wPtr = w.GetPtr( firstIdx );
	while ( firstIdx > 0 ) {
		if ( NearZero( *wPtr, eps ) ) {			// If this diagonal entry (near) zero
			*wPtr = 0.0;
			break;
		}
		if ( NearZero(*(--sdPtr), eps) ) {		// If the entry above the diagonal entry is (near) zero
			*sdPtr = 0.0;
			break;
		}
		wPtr--;
		firstIdx--;
	}
	*firstBidiagIdx = firstIdx;
	return true;
}

// ******************************************DEBUG STUFFF

bool MatrixRmn::DebugCheckSVD( const MatrixRmn& U, const VectorRn& w, const MatrixRmn& V ) const
{
	// Special SVD test code

	MatrixRmn IV( V.GetNumRows(), V.GetNumColumns() );
	IV.SetIdentity();
	MatrixRmn VTV( V.GetNumRows(), V.GetNumColumns() );
	MatrixRmn::TransposeMultiply( V, V, VTV );
	IV -= VTV;
	double error = IV.FrobeniusNorm();

	MatrixRmn IU( U.GetNumRows(), U.GetNumColumns() );
	IU.SetIdentity();
	MatrixRmn UTU( U.GetNumRows(), U.GetNumColumns() );
	MatrixRmn::TransposeMultiply( U, U, UTU );
	IU -= UTU;
	error += IU.FrobeniusNorm();

	MatrixRmn Diag( U.GetNumRows(), V.GetNumRows() );
	Diag.SetZero();
	Diag.SetDiagonalEntries( w );
	MatrixRmn B(U.GetNumRows(), V.GetNumRows() );
	MatrixRmn C(U.GetNumRows(), V.GetNumRows() );
	MatrixRmn::Multiply( U, Diag, B );
	MatrixRmn::MultiplyTranspose( B, V, C );
	C -= *this;
	error += C.FrobeniusNorm();

	bool ret = ( fabs(error)<=1.0e-13*w.MaxAbs() );
	assert ( ret );
	return ret;
}

bool MatrixRmn::DebugCheckInverse( const MatrixRmn& MInv ) const
{
    assert ( this->NumRows==this->NumCols );
    assert ( MInv.NumRows==MInv.NumCols );
    MatrixRmn I(this->NumRows, this->NumCols);
    I.SetIdentity();
    MatrixRmn MMInv(this->NumRows, this->NumCols);
    Multiply(*this, MInv, MMInv);
    I -= MMInv;
    double error = I.FrobeniusNorm();
    bool ret = ( fabs(error)<=1.0e-13 );
    assert ( ret );
    return ret;
}

bool MatrixRmn::DebugCalcBidiagCheck( const MatrixRmn& U, const VectorRn& w, const VectorRn& superDiag, const MatrixRmn& V ) const
{
	// Special SVD test code

	MatrixRmn IV( V.GetNumRows(), V.GetNumColumns() );
	IV.SetIdentity();
	MatrixRmn VTV( V.GetNumRows(), V.GetNumColumns() );
	MatrixRmn::TransposeMultiply( V, V, VTV );
	IV -= VTV;
	double error = IV.FrobeniusNorm();

	MatrixRmn IU( U.GetNumRows(), U.GetNumColumns() );
	IU.SetIdentity();
	MatrixRmn UTU( U.GetNumRows(), U.GetNumColumns() );
	MatrixRmn::TransposeMultiply( U, U, UTU );
	IU -= UTU;
	error += IU.FrobeniusNorm();

	MatrixRmn DiagAndSuper( U.GetNumRows(), V.GetNumRows() );
	DiagAndSuper.SetZero();
	DiagAndSuper.SetDiagonalEntries( w );
	if ( this->GetNumRows()>=this->GetNumColumns() ) {
		DiagAndSuper.SetSequence( superDiag, 0, 1, 1, 1 );
	}
	else {
		DiagAndSuper.SetSequence( superDiag, 1, 0, 1, 1 );
	}
	MatrixRmn B(U.GetNumRows(), V.GetNumRows() );
	MatrixRmn C(U.GetNumRows(), V.GetNumRows() );
	MatrixRmn::Multiply( U, DiagAndSuper, B );
	MatrixRmn::MultiplyTranspose( B, V, C );
	C -= *this;
	error += C.FrobeniusNorm();

	bool ret = ( fabs(error)<1.0e-13*Max(w.MaxAbs(),superDiag.MaxAbs()) );
	assert ( ret );
	return ret;
}


text:
========
Overview
========

Requirements
============

#. PHP 5.3, 5.4, 5.5, 5.6, or HHVM.
#. PHP compiled with cURL.

.. _installation:

Installation
============

The recommended way to install PHP Curl Class is with
`Composer <https://getcomposer.org>`_. Composer is a dependency manager for php.

.. code-block:: bash

    # Install Composer
    curl -sS https://getcomposer.org/installer | php

Install PHP Curl Class as a dependency using composer:

.. code-block:: bash

    composer require php-curl-class/php-curl-class

Composer generates a ``vendor/autoload.php`` file. You can simply include this
file and you will get autoloading for free:

.. code-block:: php

    require __DIR__ . 'vendor/autoload.php';

License
=======

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

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 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.

For more information, please refer to <http://unlicense.org/>

Contributing
============

#. Check for open issues or open a new issue to start a discussion around a bug or feature.
#. Fork the repository on GitHub to start making your changes.
#. Write one or more tests for the new feature or that expose the bug.
#. Make code changes to implement the feature or fix the bug.
#. Send a pull request to get your changes merged and published.


text:
/
public class BaseActivator implements BundleActivator {
	private String bundleId;
	private Vector<BundleResource> bundleResources = new Vector<BundleResource>();

	/**
	 * Creates an instance of the BaseActivator
	 *
	 * @param bundleId
	 *            unique bundle identifier (e.g., oic.bundle.hue)
	 */
	public BaseActivator(String bundleId) {
		this.bundleId = bundleId;
	}

	static {
		try {
			System.loadLibrary("rcs_container");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Bundle activation needs to be provided by the subclass.
	 */
	public void activateBundle() {

	}

	/**
	 * Deactivates the bundle and unregisters its resources.
	 */
	public void deactivateBundle() {
		System.out.println("Deactivating bundle (Base Activator).");
		for (BundleResource bundleResource : bundleResources) {
			unregisterResource(bundleResource);
		}
	}

	/**
	 * Registers a bundle resource at the resource container.
	 *
	 * @param resource
	 *            bundle resource instance that should be made available as OIC
	 *            resource
         * @return int
         *       0        in case of an success
         *       -EEXIST  when the resource already exists and was not registered
         *       -EINVAL  when it was not possible to create such a resource
         */
	public int registerResource(BundleResource resource) {
		bundleResources.add(resource);
		return registerJavaResource(resource, resource.getAttributeKeys(), bundleId,
				resource.getURI(), resource.getResourceType(),
				resource.getName());
	}

	/**
	 * Wrapper to retrieve the resource configuration of the bundle resources.
	 *
	 * @return List of resource configurations.
	 */
	public List<ResourceConfig> getConfiguredBundleResources() {
		int configuredResources = getNumberOfConfiguredResources(bundleId);

		Vector<ResourceConfig> configs = new Vector<ResourceConfig>();

		for (int i = 0; i < configuredResources; i++) {
			String[] resourceParams = getConfiguredResourceParams(bundleId, i);
			ResourceConfig config = new ResourceConfig(resourceParams);
			configs.add(config);

		}
		return configs;
	}

	/**
	 * Unregisters a resource from the resource container.
	 */
	public void unregisterResource(BundleResource resource) {
		bundleResources.remove(resource);
		unregisterJavaResource(resource, resource.getURI());
	}

	/**
	 * Native method that calls to the resource container.
	 *
	 * @param attributes
	 *            String array of attribute names
	 * @param bundleId
	 *            unique bundle identifier
	 * @param uri
	 *            Uri that should be used to register the resource
         *
         * @return int
         *       0        in case of an success
         *       -EEXIST  when the resource already exists and was not registered
         *       -EINVAL  when it was not possible to create such a resource
         */
	private native int registerJavaResource(BundleResource resource,
			String[] attributes, String bundleId, String uri,
			String resourceType, String name);

	/**
	 * Native method that calls to the resource container.
	 *
	 * @param resource
	 * @param uri
	 */
	private native void unregisterJavaResource(BundleResource resource,
			String uri);

	/**
	 * Native method to retrieve the number of configured resources.
	 *
	 * @param bundleId
	 *            unique bundle identifier
	 */
	private native int getNumberOfConfiguredResources(String bundleId);

	/**
	 * Native method to retrieve the configured resource parameters.
	 *
	 * @param bundleId
	 *            unique bundle identifier
	 * @param resId
	 *            get the resource params for a certain resource
	 */
	private native String[] getConfiguredResourceParams(String bundleId,
			int resId);

}


text: PYTHONPATH=.:$PYTHONPATH python3 -m nose -v pyltr


text:
title: selection of a theme Flexberry ASP.NET
sidebar: flexberry-aspnet_sidebar
keywords: Flexberry ASP-NET
toc: true
permalink: en/fa_choose-theme.html
lang: en
autotranslated: true
hash: d027014a2f622c3a12f6672767858a5358e29a032d29ff32da42e1eb7ebb30d1
---

Application themes are responsible for its appearance. When you change themes changes:

* Color range
* Fonts
* Icons
* Indentation
* and so on.

Appearance themes, you can appreciate in the following pictures:

### Default

[WOLV](fa_web-object-list-view.html):

![](/images/pages/products/flexberry-aspnet/themes/default.png)

[Web edit form](fa_editform.html):

![](/images/pages/products/flexberry-aspnet/themes/edit-page-default.png)

### Light

[WOLV](fa_web-object-list-view.html):

![](/images/pages/products/flexberry-aspnet/themes/light.png)

[Web edit form](fa_editform.html):

![](/images/pages/products/flexberry-aspnet/themes/edit-page-light.png)

### Smart

[WOLV](fa_web-object-list-view.html):

![](/images/pages/products/flexberry-aspnet/themes/smart.png)

[Web edit form](fa_editform.html):

![](/images/pages/products/flexberry-aspnet/themes/edit-page-smart.png)

### Spring

[WOLV](fa_web-object-list-view.html):

![](/images/pages/products/flexberry-aspnet/themes/spring.png)

[Web edit form](fa_editform.html):

![](/images/pages/products/flexberry-aspnet/themes/edit-page-spring.png)

## the Choice of theme in your Web application

To set the default theme in the Web-application is sufficient in the configuration file `web.config` to enter the name of the theme

```xml
<pages validateRequest="false" enableSessionState="true" theme="Spring" maintainScrollPositionOnPostBack="true">
```

in the theme property=.

The default theme of Spring.

The list of topics supplied at the generation of the application:

* Default (despite the name it is not selected by default)
* Light
* Smart
* Spring (selected by default)

It is possible to switch threads in user mode. On any page in the lower left corner there is a line where you can specify what topic you need
to use. The selected theme is set for this particular user. The theme, the default can only be changed in the configuration file.


text:
var checkLayerCount = function(selectionCount) {
  var isMoreThanZeroLayersSelected = false

  if (selectionCount > 0) {
    isMoreThanZeroLayersSelected = true
  } else {
    var app = NSApplication.sharedApplication()
    app.displayDialog_withTitle("You must select a layer first.", "Change Title Case")
  }

  return isMoreThanZeroLayersSelected
}


text:
START_ATF_NAMESPACE
    typedef NMCBEDRAGBEGINA *LPNMCBEDRAGBEGINA;
END_ATF_NAMESPACE


text:
package com.opengamma.analytics.financial.interestrate.bond.calculator;

import org.apache.commons.lang.Validate;

import com.opengamma.analytics.financial.interestrate.AbstractInstrumentDerivativeVisitor;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.interestrate.bond.definition.BillSecurity;
import com.opengamma.analytics.financial.interestrate.bond.definition.BondFixedSecurity;
import com.opengamma.analytics.financial.interestrate.bond.method.BillSecurityDiscountingMethod;
import com.opengamma.analytics.financial.interestrate.bond.method.BondSecurityDiscountingMethod;

/**
 * Calculate dirty price for bonds.
 */
public final class YieldFromCurvesCalculator extends AbstractInstrumentDerivativeVisitor<YieldCurveBundle, Double> {

  /**
   * The calculator instance.
   */
  private static final YieldFromCurvesCalculator s_instance = new YieldFromCurvesCalculator();

  /**
   * Return the calculator instance.
   * @return The instance.
   */
  public static YieldFromCurvesCalculator getInstance() {
    return s_instance;
  }

  /**
   * Private constructor.
   */
  private YieldFromCurvesCalculator() {
  }

  /**
   * The method used for different instruments.
   */
  private static final BillSecurityDiscountingMethod METHOD_BILL_SECURITY = BillSecurityDiscountingMethod.getInstance();

  @Override
  public Double visitBondFixedSecurity(final BondFixedSecurity bond, final YieldCurveBundle curves) {
    Validate.notNull(curves);
    Validate.notNull(bond);
    final BondSecurityDiscountingMethod method = BondSecurityDiscountingMethod.getInstance();
    return method.yieldFromCurves(bond, curves);
  }

  @Override
  public Double visitBillSecurity(final BillSecurity bill, final YieldCurveBundle curves) {
    Validate.notNull(curves);
    Validate.notNull(bill);
    return METHOD_BILL_SECURITY.yieldFromCurves(bill, curves);
  }

}


text:
{-# LANGUAGE TupleSections #-}

module Akari where

import Control.Applicative
import Data.Attoparsec.ByteString
import Data.Attoparsec.ByteString.Char8
import Data.Char (ord)
import Data.SBV
import Control.Monad.Writer
import Data.Map (Map, (!))
import Data.List (transpose)
import Data.Maybe (fromJust, catMaybes)

import Util

-- Akari (or Light Up)
-- Light Up is played on a rectangular grid of white and black cells.
-- The player places light bulbs in white cells such that no two bulbs shine on each other,
-- until the entire grid is lit up. A bulb sends rays of light horizontally and vertically,
-- illuminating its entire row and column unless its light is blocked by a black cell.
-- A black cell may have a number on it from 0 to 4, indicating how many bulbs must be
-- placed adjacent to its four sides; for example, a cell with a 4 must have four bulbs around it,
-- one on each side, and a cell with a 0 cannot have a bulb next to any of its sides.
-- An unnumbered black cell may have any number of light bulbs adjacent to it, or none.
-- Bulbs placed diagonally adjacent to a numbered cell do not contribute to the bulb count.

data AkariType = Wall | Space

type AkariInst = [[(AkariType, Maybe Integer)]]

type Elem = SWord32
type Row = [Elem]
type Board = [Row]

rules :: AkariInst -> Symbolic SBool
rules inst = do
    let width = length (head inst)
    let height = length inst

    board <-
        forM [0..height-1] $ \r ->
            forM [0..width-1] $ \c ->
                (symbolic (show r ++ "-" ++ show c) :: Symbolic SBool)

    let getVar r c = if r >= 0 && r < height && c >= 0 && c < width then Just $ (board !! r) !! c else Nothing

    addConstraints $ do
        forM_ (zip3 [0 .. ] inst board) $ \(r, instRow, boardRow) ->
            forM_ (zip3 [0 .. ] instRow boardRow) $ \(c, instCell, var) ->
                do
                    -- constraints to match input numbers

                    case instCell
                      of (_, Just i) -> do
                            -- number of bulbs adjacent to this square are correct
                            addConstraint $ literal i .==
                                (sum $ map (\var -> ite var (literal 1) (literal 0)) $
                                catMaybes $ [getVar (r+1) c, getVar (r-1) c, getVar r (c-1), getVar r (c+1)])
                         (_, Nothing) ->
                            return ()

                    -- general bulb constraints

                    case instCell
                      of (Wall, _) -> do
                            -- no bulb on a wall
                            addConstraint $ var .== literal False
                         (Space, _) -> do
                            -- this space is LIT
                            let visibleSpaceInclusive = getVisibleSpace inst (r, c)
                            addConstraint $ orList $ map (\(r, c) -> (board !! r) !! c) visibleSpaceInclusive

                            -- this space cannot simulatenously have a bulb if it is otherwise lit
                            let visibleSpaceExclusive = filter (/= (r, c)) visibleSpaceInclusive
                            forM_ visibleSpaceExclusive $ \(r1, c1) -> do
                                addConstraint $ bnot $ var &&& ((board !! r1) !! c1)
  where
    getVisibleSpace inst (r, c) =
      let
        width = length (head inst)
        height = length inst
        getRun r c deltaR deltaC =
          let
            r1 = r + deltaR
            c1 = c + deltaC
            isSpace = if r1 >= 0 && c1 >= 0 && r1 < height && c1 < width then
                case (inst !! r1) !! c1 of (Wall, _) -> False
                                           (Space, _) -> True
                else False
          in
            if isSpace then (r1, c1) : getRun r1 c1 deltaR deltaC
                       else []
      in
        [(r,c)] ++ getRun r c 0 (-1) ++ getRun r c 0 1 ++ getRun r c 1 0 ++ getRun r c (-1) 0

getSolution :: AkariInst -> Map String CW -> String
getSolution inst m =
  let
    width = length (head inst)
    height = length inst
  in
    concat $ map (++ "\n") $ map concat $
    map (\i ->
        map (\j ->
            if (fromCW $ m ! (show i ++ "-" ++ show j) :: Bool) then
                "+" -- light bulb
            else
                case ((inst !! i) !! j) of (_, Just i) -> show i
                                           (Space, Nothing) -> " "
                                           (Wall, Nothing) -> "#"
        ) [0..width-1]
    ) [0..height-1]

solvePuzzle :: Symbolic SBool -> (Map String CW -> a) -> IO [a]
solvePuzzle prob fn = do
    res <- allSat prob
    return $ map fn (getModelDictionaries res)

akari :: AkariInst -> IO ()
akari puzzle = do
    res <- solvePuzzle (rules puzzle) (getSolution puzzle)
    putStrLn $ (show $ length res) ++ " solution(s)"
    forM_ res $ \soln ->
        putStrLn $ soln

-- Note that there needs to be an empty line to signal the end of the puzzle.
akariParser :: Parser AkariInst
akariParser = do
    puz <- many $ do
        row <- many1 cellParser
        endOfLine
        pure row
    endOfLine
    pure puz
    where
    cellParser :: Parser (AkariType, Maybe Integer)
    cellParser =
        ((Wall,) . Just . subtract 48 . toInteger . ord <$> digit)
        <|> (char '#' *> pure (Wall, Nothing))
        <|> (char '.' *> pure (Space, Nothing))