text:
<title>Class: 'NMR Case'</title>
<meta http-equiv='content-type' content='text/html;charset=utf8'>
<link rel='stylesheet' href='../default.css' type='text/css' />

Class: 'NMR Case'

http://nmrML.org/nmrCV#NMR:1400203

Annotations (2)

comment "def: The NMR Case is an economical NMR sample changer for laboratories with modest automation needs. It expands the maximum number of samples your spectrometer can process during unattended operation to 24. The NMR Case consists of multiple components. The NMR Case exchange module installed atop your cryostat. The two front legs are adjustable, making the NMR Case compatible with many different cryostats.
   defprov: Bruker website" (string)

label "NMR Case" (string)

Superclasses (1)

'Bruker autosampler'

Usage (1)

Class: 'NMR Case'


text:
<?php
/**
 * Description of CreateDomainController
 *
 * @author jost
 */
class CreateDomainController extends BaseController {
	#
	/*public function index() {
		if(!Input::has('upperDomainId') && !Input::has('university'))
			return null;
		$upperDomainId = Input::get('upperDomainId');
		if(Input::has('group'))
			return $this::createGroup(Input::get('group'), $upperDomainId);
		if(Input::has('lab'))
			return $this::createLab(Input::get('lab'), $upperDomainId);
		if(Input::has('department'))
			return $this::createDeparment(Input::get('department'), $upperDomainId);
		if(Input::has('university'))
			return $this::createUniversity(Input::get('university'));
		return null;
	}*/

	public function index() {
		if(!Input::has('groupName'))
			return "Missing parameter groupName";
		if(Auth::user()->group_id != null && Group::find(Auth::user()->group_id)->active != 1 && UserRole::getUserRole(UserRole::SUPER_ADMIN) == null)
			return "You cannot create a new group/lab, because your last group/lab creation is still pending";
		if(!Input::has('labId')) {
			if(!Input::has('labName'))
				return "Missing parameter labName";
			$lab = Lab::where('name', '=', Input::get('labName'))->first();
			if($lab == null) {
				$labId = $this::createLab(Input::get('labName'))->id;
				$labCreated = true;
			}
			else {
				$labId = $lab->id;
				$labCreated = false;
			}

		} else {
			$labId = Input::get('labId');
			$labCreated = false;
		}
		$result = $this::createGroup(Input::get('groupName'), $labId, $labCreated);
		return $result;
	}

	private function createGroup($name, $labId, $labCreated) {
		if(!$labCreated && Lab::find($labId)->active == 0)
			return "Lab is not active";
		$isGroupActive = UserRole::getUserRole(UserRole::LAB_LEADER) != null;
		$group = Group::where('name', '=', $name)->where('lab_id', '=', $labId)->first();
		if($group == null) {
			$group = new Group;
			$group->name = $name;
			$group->lab_id = $labId;
			$group->active = $isGroupActive;
			$group->save();
			//mail sending
			$lab = $group->lab;
			$admin = $lab->getAdmin();
			$author = $admin->author;
			$authorName = $author->first_name.' '.$author->last_name;
			$user = Auth::user();
			Mail::send('emails/group_created', array('user' => $user), function($message) use ($author, $authorName) {
				$message->to($author->email, $authorName)
					->subject('group creation')
					->from('noreply@da-sense.de', 'PHDPapertool');
			});
		}
		$user = Auth::user();
		$user->group_confirmed = $isGroupActive;
		$user->group_id = $group->id;
		$user->save();
		//$this::updateRole(UserRole::GROUP_LEADER, $isGroupActive);
		return "true";
	}

	private function createLab($name) {//, $departmentId) {
		$lab = new Lab;
		$lab->name = $name;
		//$lab->department_id = $departmentId;
		$lab->active = 0;
		$lab->save();
		//$this::updateRole(UserRole::LAB_LEADER, false);

		//Mail an Super-Admin schicken.
		$author = Author::findOrFail(1);
		$authorName = $author->first_name.' '.$author->last_name;
		$user = Auth::user();
		Mail::send('emails/lab_created', array('user' => $user), function($message) use ($author, $authorName) {
			$message->to($author->email, $authorName)
				->subject('lab creation')
				->from('noreply@da-sense.de', 'PHDPapertool');
		});

		return $lab;
	}

   /* private function updateRole($roleId, $isActive) {
		$role = UserRole::getUserRole($roleId);
		if($role != null) {
			$role->active = $isActive;
			return $role;
		}
		$newRole = new User_role;
		$newRole->user_id = Auth::user()->id;
		$newRole->role_id = $roleId;
		$newRole->active = $isActive;
		$newRole->save();
		return $newRole;
	}*/

   /*private function createDepartment($name, $universityId) {
		$department = new Department;
		$department->name = $name;
		$department->university_id = $universityId;
		$department->save();
		return $department;
	}

	private function createUniversity($name) {
		$university = new University;
		$university->name = $name;
		$university->save();
		return $university;
	}*/
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Extension\Optimizers;

use PHPUnit\Framework\TestCase;
use Stub\Optimizers\ACos;
use Stub\Optimizers\ASin;
use Stub\Optimizers\Cos;
use Stub\Optimizers\Ldexp;
use Stub\Optimizers\Sin;
use Stub\Optimizers\Sqrt;
use Stub\Optimizers\Tan;

final class MathTest extends TestCase
{
    public function testLdexp(): void
    {
        $test = new Ldexp();

        $this->assertSame(16.0, $test->testInt());
        $this->assertSame(16.0, $test->testVar());
        $this->assertSame(16.0, $test->testIntValue1());
        $this->assertSame(16.0, $test->testDoubleInt());
        $this->assertSame(16.0, $test->testDouble());
        $this->assertSame(524288.0, $test->testIntParameter(8, 16));
        $this->assertSame(524288.0, $test->testvarParameter(8, 16));
    }

    public function testSqrt(): void
    {
        $test = new Sqrt();

        $this->assertSame(2.0, $test->testInt());
        $this->assertSame(2.0, $test->testVar());

        $this->assertSame(2.0, $test->testIntValue1());
        $this->assertSame(4.0, $test->testIntValue2());

        $this->assertSame(2.0, $test->testIntParameter(4));
        $this->assertSame(4.0, $test->testIntParameter(16));

        $this->assertSame(2.0, $test->testVarParameter(4));
        $this->assertSame(4.0, $test->testVarParameter(16));
    }

    public function testSin(): void
    {
        $test = new Sin();

        $this->assertSame(sin(4), $test->testInt());
        $this->assertSame(sin(4), $test->testVar());

        $this->assertSame(sin(4), $test->testIntValue1());
        $this->assertSame(sin(16), $test->testIntValue2());

        $this->assertSame(sin(4), $test->testIntParameter(4));
        $this->assertSame(sin(16), $test->testIntParameter(16));

        $this->assertSame(sin(4), $test->testVarParameter(4));
        $this->assertSame(sin(16), $test->testVarParameter(16));
    }

    public function testCos(): void
    {
        $test = new Cos();

        $this->assertSame(cos(4), $test->testInt());
        $this->assertSame(cos(4), $test->testVar());

        $this->assertSame(cos(4), $test->testIntValue1());
        $this->assertSame(cos(16), $test->testIntValue2());

        $this->assertSame(cos(4), $test->testIntParameter(4));
        $this->assertSame(cos(16), $test->testIntParameter(16));

        $this->assertSame(cos(4), $test->testVarParameter(4));
        $this->assertSame(cos(16), $test->testVarParameter(16));
    }

    public function testACos(): void
    {
        $test = new ACos();

        $this->assertSame(acos(1), $test->testInt());
        $this->assertSame(acos(1), $test->testVar());

        $this->assertSame(acos(0), $test->testIntValue1());

        $this->assertSame(acos(1), $test->testIntParameter(1));
        $this->assertSame(acos(0), $test->testIntParameter(0));

        $this->assertSame(acos(1), $test->testVarParameter(1));
        $this->assertSame(acos(0), $test->testVarParameter(0));
    }

    public function testASin(): void
    {
        $test = new ASin();

        $this->assertSame(asin(1), $test->testInt());
        $this->assertSame(asin(1), $test->testVar());

        $this->assertSame(asin(0), $test->testIntValue1());

        $this->assertSame(asin(1), $test->testIntParameter(1));
        $this->assertSame(asin(0), $test->testIntParameter(0));

        $this->assertSame(asin(1), $test->testVarParameter(1));
        $this->assertSame(asin(0), $test->testVarParameter(0));
    }

    public function testTan(): void
    {
        $test = new Tan();

        $this->assertSame(tan(0), $test->testInt());
        $this->assertSame(tan(0), $test->testVar());

        $this->assertSame(tan(1), $test->testVar2());
        $this->assertSame(tan(1), $test->testIntValue1());
        $this->assertSame(tan(2), $test->testIntValue2());

        $this->assertSame(tan(0), $test->testIntParameter(0));
        $this->assertSame(tan(1), $test->testIntParameter(1));
        $this->assertSame(tan(2), $test->testIntParameter(2));
        $this->assertSame(tan(3), $test->testIntParameter(3));
        $this->assertSame(tan(4), $test->testIntParameter(4));

        $this->assertSame(tan(0), $test->testVarParameter(0));
        $this->assertSame(tan(1), $test->testVarParameter(1));
        $this->assertSame(tan(2), $test->testVarParameter(2));
        $this->assertSame(tan(3), $test->testVarParameter(3));
        $this->assertSame(tan(4), $test->testVarParameter(4));
        $this->assertSame(tan(0), $test->testVarParameter('0'));
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Shared.Core.Extensions.Lambda
{
    public static class ExpressionExtensions
    {
        public static string GetPath<T>(Expression<Func<T, object>> expr)
        {
            var stack = new Stack<string>();

            MemberExpression me;
            switch (expr.Body.NodeType)
            {
                case ExpressionType.Convert:
                case ExpressionType.ConvertChecked:
                    var ue = expr.Body as UnaryExpression;
                    me = ((ue != null) ? ue.Operand : null) as MemberExpression;
                    break;
                default:
                    me = expr.Body as MemberExpression;
                    break;
            }

            while (me != null)
            {
                stack.Push(me.Member.Name);
                me = me.Expression as MemberExpression;
            }

            return string.Join(".", stack.ToArray());
        }

        public static string GetPath<T, TP>(Expression<Func<T, TP>> expr)
        {
            var stack = new Stack<string>();

            MemberExpression me;
            switch (expr.Body.NodeType)
            {
                case ExpressionType.Convert:
                case ExpressionType.ConvertChecked:
                    var ue = expr.Body as UnaryExpression;
                    me = ((ue != null) ? ue.Operand : null) as MemberExpression;
                    break;
                default:
                    me = expr.Body as MemberExpression;
                    break;
            }

            while (me != null)
            {
                stack.Push(me.Member.Name);
                me = me.Expression as MemberExpression;
            }

            return string.Join(".", stack.ToArray());
        }

        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
            // build parameter map (from parameters of second to parameters of first)
            var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);

            // replace parameters in the second lambda expression with parameters from the first
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);

            // apply composition of lambda expression bodies to parameters from the first
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }

        /// <summary>
        /// Combines two predicates with AND operator
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <returns></returns>
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }

        /// <summary>
        /// Combines two predicates with OR operator
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <returns></returns>
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.Or);
        }

        public static Action<T, TProperty> Setter<T, TProperty>(this Expression<Func<T, TProperty>> expression)
        {
            var newValue = Expression.Parameter(expression.Body.Type);
            var assign = Expression.Lambda<Action<T, TProperty>>(
                Expression.Assign(expression.Body, newValue),
                expression.Parameters[0], newValue);

            return assign.Compile();
        }

        public static Func<T, TProperty> Getter<T, TProperty>(this Expression<Func<T, TProperty>> expression)
        {
            return expression.Compile();
        }

        /// <summary>
        /// Returns the underlying type of value selected by expression.
        /// </summary>
        public static Type GetValueType<T>(this Expression<Func<T, object>> expression)
        {
            if (expression.Body.NodeType == ExpressionType.Convert || expression.Body.NodeType == ExpressionType.ConvertChecked)
            {
                var unary = expression.Body as UnaryExpression;

                if (unary != null)
                    return unary.Operand.Type;
            }

            return expression.Body.Type;
        }
        /// <summary>
        /// Checks, whther selector returns instance of a class.
        /// String is not a class in this method.
        /// </summary>
        public static bool IsClassSelector<T>(this Expression<Func<T, object>> selector)
        {
            var selectorType = selector.GetValueType();
            var isClass = selectorType.IsClass || selectorType.Implements<IEnumerable>();

            return isClass && selectorType != typeof(string); // selector is for class, but not string
        }

        /// <summary>
        /// Checks, whether underlying type of value returned by selector matches the underlying type of value.
        /// </summary>
        /// <param name="value"></param>
        public static bool MatchesTypeOf<T>(this Expression<Func<T, object>> selector, object value, bool matchEnumAndInt = true)
        {
            var selectorType = selector.GetValueType();
            var selectorUnderlyingType = Nullable.GetUnderlyingType(selectorType);

            var isClass = selectorType.IsClass || selectorType.Implements<IEnumerable>();

            var enumMatch = (matchEnumAndInt    // match Enum to int selector,
                         && value != null       // value is not null
                         && value is Enum)      // and is Enum
                         && (                   // and
                                selectorType == typeof(int)             // selector is for int
                             || selectorUnderlyingType == typeof(int)   // or selector is for int?
                             );

            return (isClass && value == null) // selector is for class and value is null
                || (selectorUnderlyingType != null && (value == null || selectorUnderlyingType == value.GetType())) // selector is for Nullable<> and value is null or matches the underlying type
                || selectorType == value.GetType() // selector is for value type and types have to match
                || enumMatch;  // selector is for int or int? and value is Enum
        }
    }
}


text:
/**
 * @author Andreas Gyr <andygyr@gmx.ch>
 */
package parser.sax;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import model.Connection;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import parser.ConnectionsParserInterface;
import util.SimpleErrorHandler;

public class ConnectionsSAXParser implements ConnectionsParserInterface {
	private File xmlFile;
	private ArrayList<Connection> connections;

	public ConnectionsSAXParser() {
		this.connections = new ArrayList<Connection>();
	}

	public void setXMLFile(File xmlFile) {
		this.xmlFile = xmlFile;
	}

	public void parse() throws Exception {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = getValidParser(xmlFile, factory);

		// parse connections
		ConnectionsSAXHandler connectionsHandler = new ConnectionsSAXHandler();
		parser.parse(xmlFile, connectionsHandler);
		connections = connectionsHandler.getConnections();
	}

	public ArrayList<Connection> getConnections() {
		return connections;
	}

	/**
	 * ------------------------------------------------------------------------
	 * The following methods are public and static for reusability reasons. I
	 * tried to implement the method dependency injection pattern.
	 * ------------------------------------------------------------------------
	 */

	/**
	 * If the xmlFile is valid it creates a Document, otherwise it will throw
	 * Exceptions.
	 *
	 * @param xmlFile
	 *            XML Source File
	 * @param factory
	 *            Factory for SAX Parser
	 * @return A validated Parser or Exceptions
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public static SAXParser getValidParser(File xmlFile,
			SAXParserFactory factory) throws ParserConfigurationException,
			SAXException, IOException {
		factory.setValidating(true);
		factory.setNamespaceAware(true);

		SAXParser parser = factory.newSAXParser();
		parser.setProperty(
				"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
				"http://www.w3.org/2001/XMLSchema");

		XMLReader reader = parser.getXMLReader();
		reader.setErrorHandler(new SimpleErrorHandler());
		reader.parse(new InputSource(xmlFile.getPath()));

		return parser;
	}

}


text:
title: Volcanic Air Safaris

listing-type: attractions
island: north
region: bay-of-plenty
destination: Bay of Plenty

order: a
image-path: volcanic-air-white-island-flights.jpg
image-alt: Volcanic Air Safaris
refer-url: http://www.volcanicair.co.nz/presentation/VolcanicAirNormal07Pres.aspx?ID=9830
---
Offers flights to & landings on the active volcano  of White Island. Also includes a one hour guided walk of this fascinating natural attraction.


text:
Examples of how to use nap

---

[LICENSE](LICENSE)


text:
"""
Editra Control Library: Encoding Dialog

A simple choice dialog for selecting a file encoding type from. The dialog
can work with either a passed in list of choices to display or by default will
list all encodings found on the system using their normalized names.

@summary: Encoding choice dialog

"""

__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: encdlg.py 70230 2012-01-01 01:47:42Z CJP $"
__revision__ = "$Revision: 70230 $"

__all__ = ['EncodingDialog', 'GetAllEncodings']

#--------------------------------------------------------------------------#
# Imports
import locale
import encodings
import wx

# Editra Control Library Imports
import choicedlg

#--------------------------------------------------------------------------#
# Globals
EncodingDialogNameStr = u"EncodingDialog"

#--------------------------------------------------------------------------#

class EncodingDialog(choicedlg.ChoiceDialog):
    """Dialog for choosing an file encoding from the list of available
    encodings on the system.

    """
    def __init__(self, parent, id=wx.ID_ANY, msg=u'', title=u'',
                  elist=list(), default=u'',
                  style=wx.CAPTION, pos=wx.DefaultPosition,
                  size=wx.DefaultSize,
                  name=EncodingDialogNameStr):
        """Create the encoding dialog
        @param parent: Parent Window
        @keyword id: Dialog ID
        @keyword msg: Dialog Message
        @keyword title: Dialog Title
        @keyword elist: list of encodings to use or None to use all
        @keyword default: Default selected encoding
        @keyword style: Dialog Style bitmask
        @keyword pos: Dialog Postion
        @keyword size: Dialog Size
        @keyword name: Dialog Name

        """
        if not len(elist):
            elist = GetAllEncodings()

        default = encodings.normalize_encoding(default)
        if default and default.lower() in elist:
            sel = default.lower()
        else:
            sel = locale.getpreferredencoding(False)

        super(EncodingDialog, self).__init__(parent, id, msg, title,
                                             elist, sel, pos, size, style)

    def GetEncoding(self):
        """Get the selected encoding
        @return: string

        """
        return self.GetStringSelection()

#--------------------------------------------------------------------------#
# Utilities

def GetAllEncodings():
    """Get all encodings found on the system
    @return: list of strings

    """
    elist = encodings.aliases.aliases.values()
    elist = list(set(elist))
    elist.sort()
    elist = [ enc for enc in elist if not enc.endswith('codec') ]
    return elist

#--------------------------------------------------------------------------#


text:
package io.advantageous.qbit.metrics.support;

import io.advantageous.qbit.metrics.StatReplicator;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * created by rhightower on 1/28/15.
 */
public class DebugReplicator implements StatReplicator {

    public final AtomicLong count = new AtomicLong();

    public boolean out = false;

    public DebugReplicator(@SuppressWarnings("SameParameterValue") boolean out) {
        this.out = out;
    }

    public DebugReplicator() {
    }

    @Override
    public void replicateCount(String name, long count, long now) {
        this.count.addAndGet(count);
        if (out) System.out.println("DEBUG REPLICATOR" + name + count + now + this.count.get());
    }

    @Override
    public void replicateLevel(String name, long level, long now) {
        this.count.set(level);
        if (out) System.out.println("DEBUG REPLICATOR" + name + count + now + this.count.get());
    }

    @Override
    public void replicateTiming(String name, long level, long time) {
        this.count.set(level);
        if (out) System.out.println("DEBUG REPLICATOR" + name + count + time + this.count.get());

    }
}


text:
using Assets.Scripts.Attributes;
using Assets.Scripts.Constants;
using UnityEngine;
using GameScriptEvent = Assets.Scripts.Constants.GameScriptEvent;

namespace Assets.Scripts.GameScripts.GameLogic.Animator
{
    [AddComponentMenu("ObjectAnimator/CharacterAnimator")]
    [RequireComponent(typeof(UnityEngine.Animator))]
    public class CharacterAnimator : ObjectAnimator
    {
        [GameScriptEvent(GameScriptEvent.UpdateFacingDirection)]
        public void UpdateFacingDirection(FacingDirection facingDirection)
        {
            Animator.SetFloat(AnimatorControllerConstants.AnimatorParameterName.FacingDirection, (int)facingDirection);
        }

        [GameScriptEvent(GameScriptEvent.OnCharacterMove)]
        public void OnObjectMove(Vector2 direction)
        {
            SetAnimatorBoolState(AnimatorControllerConstants.AnimatorParameterName.Move);
        }

        [GameScriptEvent(GameScriptEvent.OnObjectHasNoHitPoint)]
        public void PlayDeathAnimation()
        {
            SetAnimatorBoolState(AnimatorControllerConstants.AnimatorParameterName.Death);
        }

        [GameScriptEvent(GameScriptEvent.OnCharacterInterrupted)]
        public void InterruptCharacter()
        {
            SetAnimatorBoolState(AnimatorControllerConstants.AnimatorParameterName.Interrupt);
        }

        protected override void Deinitialize()
        {
        }

    }
}


text:
var autoprefixer = require('autoprefixer-core');
var babelify = require('babelify');
var browserify = require('browserify');
var browserifyShim = require('browserify-shim');
var concat = require('gulp-concat');
var gulp = require('gulp');
var sass = require('gulp-sass');
var livereload = require('gulp-livereload');
var notify = require('gulp-notify');
var path = require('path');
var postcss = require('gulp-postcss');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var $ = require('gulp-load-plugins')();
var _ = require('underscore');

const files = {
    bundle: 'app.js',
    bundle_min: 'app.min.js',
    entry: 'index.js',
    lib: 'lib.min.js',
    sass_entry: 'main.scss'
};

ROOT = '.'
PROJ_ROOT = ROOT + '/public'

const paths = {
    bundle: PROJ_ROOT + '/js/' + files.bundle,
    bundle_min: PROJ_ROOT + '/js/' + files.bundle_min,
    css: PROJ_ROOT + '/stylesheets',
    sass: ROOT + '/sass/**/*.scss',
    sass_entry: ROOT + '/sass/' + files.sass_entry,
    dist: PROJ_ROOT + '/js',
    html: ROOT + '/views',
    lib: ROOT + '/vendor',
    react: ROOT + '/app/**/*.jsx',
    root: ROOT + '/app',
    scripts: ROOT + '/app/**/*.js',
    styles: ROOT + '/sass/*.scss'
};

var dependencies = [
  'jquery.min.js',
  'pubsub.js',
  'chance.min.js',
  'lodash.min.js',
  'react-addons.js',
  'sketch.js'
]
dependencies = _.map(dependencies, function(x) { return paths.lib + '/' + x });

function not(path) {
    return '!' + path;
}

gulp.task('styles', function() {
  return gulp.src('./sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(paths.css))
    .pipe(notify({ message: 'styles task complete' }));
});

gulp.task('js:lib', function() {
  return gulp.src(dependencies)
    .pipe(concat(files.lib))
    .pipe(gulp.dest(paths.dist))
    .pipe(notify({ message: 'js:lib task complete' }));
});

gulp.task('bundle', function() {
    var bundle = browserify({
            debug: true,
            extensions: ['.js', '.jsx'],
            entries: path.resolve(paths.root, files.entry)
        });

    return executeBundle(bundle);
});

gulp.task('js:app', function() {
    var bundle = browserify({
        debug: true,
        extensions: ['.js', '.jsx'],
        entries: path.resolve(paths.root, files.entry),
        cache: {},
        packageCache: {}
    });
    bundle = watchify(bundle, { poll: 100 });
    bundle.transform(babelify.configure({
    }));
    bundle.on('update', function(){
        console.log('starting rebundle..');
        executeBundle(bundle);
    });
    return executeBundle(bundle);
});

function executeBundle(bundle) {
    var start = Date.now();
    bundle
        .bundle()
        .on("error", function (err) { console.log("Error : " + err.message); })
        .pipe(source(files.bundle))
        .pipe(gulp.dest(paths.dist))
        .pipe($.notify(function() {
            console.log('bundle finished in ' + (Date.now() - start) + 'ms');
        }))
        .pipe($.filter(files.bundle));
}

gulp.task('clean', function() {
    gulp.src(path.resolve(paths.dist, '*'))
        .pipe($.clean({force: true}));
});

gulp.task('js:app:minify', function() {
    gulp.src(paths.bundle)
        .pipe($.uglify())
        .pipe(concat(files.bundle_min))
        .pipe(gulp.dest(paths.dist))
        .pipe($.size({
            showFiles: true,
            title: 'js:app:minify:'
        }));
});

gulp.task('watch', function() {
  gulp.watch([paths.scripts, paths.react], ['js:app']);
  gulp.watch([paths.lib], ['js:lib']);
  gulp.watch([paths.sass], ['styles']);

  livereload.listen();
  dirs = [
      ROOT + '/**/*.py',
      PROJ_ROOT + '/js/**/*.js',
      PROJ_ROOT + '/stylesheets/**/*.css',
      ROOT + '/views/**/*.ejs',
    ]
  gulp.watch(dirs).on('change', livereload.changed);

});

gulp.task('dev',
    ['watch']
);

gulp.task('default', ['dev']);


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.remote;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.MethodDelegation;
import org.openqa.selenium.Beta;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.HasCapabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WrapsDriver;
import org.openqa.selenium.internal.Require;
import org.openqa.selenium.remote.html5.AddApplicationCache;
import org.openqa.selenium.remote.html5.AddLocationContext;
import org.openqa.selenium.remote.html5.AddWebStorage;
import org.openqa.selenium.remote.mobile.AddNetworkConnection;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static net.bytebuddy.matcher.ElementMatchers.anyOf;
import static net.bytebuddy.matcher.ElementMatchers.named;

/**
 * Enhance the interfaces implemented by an instance of the
 * {@link org.openqa.selenium.WebDriver} based on the returned
 * {@link org.openqa.selenium.Capabilities} of the driver.
 *
 * Note: this class is still experimental. Use at your own risk.
 */
@Beta
public class Augmenter {
  private final Set<Augmentation<?>> augmentations;

  public Augmenter() {
    this.augmentations = Collections.emptySet();
    addDriverAugmentation(new AddApplicationCache());
    addDriverAugmentation(new AddLocationContext());
    addDriverAugmentation(new AddNetworkConnection());
    addDriverAugmentation(new AddRotatable());
    addDriverAugmentation(new AddWebStorage());

    StreamSupport.stream(ServiceLoader.load(AugmenterProvider.class).spliterator(), false)
      .forEach(this::addDriverAugmentation);
  }

  private Augmenter(Set<Augmentation<?>> augmentations, Augmentation<?> toAdd) {
    Require.nonNull("Current list of augmentations", augmentations);
    Require.nonNull("Augmentation to add", toAdd);

    Set<Augmentation<?>> toUse = new HashSet<>(augmentations.size() + 1);
    toUse.addAll(augmentations);
    toUse.add(toAdd);

    this.augmentations = Collections.unmodifiableSet(toUse);
  }

  public <X> Augmenter addDriverAugmentation(AugmenterProvider<X> provider) {
    Require.nonNull("Interface provider", provider);

    return addDriverAugmentation(
      provider.isApplicable(),
      provider.getDescribedInterface(),
      provider::getImplementation);
  }

  public <X> Augmenter addDriverAugmentation(
    String capabilityName,
    Class<X> implementThis,
    BiFunction<Capabilities, ExecuteMethod, X> usingThis) {
    Require.nonNull("Capability name", capabilityName);
    Require.nonNull("Interface to implement", implementThis);
    Require.nonNull("Concrete implementation", usingThis, "of %s", implementThis);

    return addDriverAugmentation(check(capabilityName), implementThis, usingThis);
  }

  public <X> Augmenter addDriverAugmentation(
    Predicate<Capabilities> whenThisMatches,
    Class<X> implementThis,
    BiFunction<Capabilities, ExecuteMethod, X> usingThis) {
    Require.nonNull("Capability predicate", whenThisMatches);
    Require.nonNull("Interface to implement", implementThis);
    Require.nonNull("Concrete implementation", usingThis, "of %s", implementThis);
    Require.precondition(implementThis.isInterface(), "Expected %s to be an interface", implementThis);

    return new Augmenter(augmentations, new Augmentation<>(whenThisMatches, implementThis, usingThis));
  }

  private Predicate<Capabilities> check(String capabilityName) {
    return caps -> {
      Require.nonNull("Capability name", capabilityName);

      Object value = caps.getCapability(capabilityName);
      if (value instanceof Boolean && !((Boolean) value)) {
        return false;
      }
      return value != null;
    };
  }

  /**
   * Enhance the interfaces implemented by this instance of WebDriver iff that instance is a
   * {@link org.openqa.selenium.remote.RemoteWebDriver}.
   *
   * The WebDriver that is returned may well be a dynamic proxy. You cannot rely on the concrete
   * implementing class to remain constant.
   *
   * @param driver The driver to enhance
   * @return A class implementing the described interfaces.
   */
  public WebDriver augment(WebDriver driver) {
    Require.nonNull("WebDriver", driver);
    Require.precondition(driver instanceof HasCapabilities, "Driver must have capabilities", driver);

    Capabilities caps = ImmutableCapabilities.copyOf(((HasCapabilities) driver).getCapabilities());

    // Collect the interfaces to apply
    List<Augmentation<?>> matchingAugmenters = augmentations.stream()
      // Only consider the augmenters that match interfaces we don't already implement
      .filter(augmentation -> !augmentation.interfaceClass.isAssignableFrom(driver.getClass()))
      // And which match an augmentation we have
      .filter(augmentation -> augmentation.whenMatches.test(caps))
      .collect(Collectors.toList());

    if (matchingAugmenters.isEmpty()) {
      return driver;
    }

    // Grab a remote execution method, if possible
    RemoteWebDriver remote = extractRemoteWebDriver(driver);
    ExecuteMethod execute = remote == null ?
      (commandName, parameters) -> { throw new WebDriverException("Cannot execute remote command: " + commandName); } :
      new RemoteExecuteMethod(remote);

    DynamicType.Builder<? extends WebDriver> builder = new ByteBuddy()
      .subclass(driver.getClass())
      .annotateType(AnnotationDescription.Builder.ofType(Augmentable.class).build())
      .method(named("isAugmented")).intercept(FixedValue.value(true));

    for (Augmentation<?> augmentation : augmentations) {
      Class<?> iface = augmentation.interfaceClass;

      Object instance = augmentation.implementation.apply(caps, execute);

      builder = builder.implement(iface)
        .method(anyOf(iface.getDeclaredMethods()))
        .intercept(MethodDelegation.to(instance, iface));
    }

    Class<? extends WebDriver> definition = builder.make()
      .load(driver.getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
      .getLoaded()
      .asSubclass(driver.getClass());

    try {
      WebDriver toReturn = definition.getDeclaredConstructor().newInstance();

      copyFields(driver.getClass(), driver, toReturn);

      return toReturn;
    } catch (ReflectiveOperationException e) {
      throw new IllegalStateException("Unable to create new proxy", e);
    }
  }

  private RemoteWebDriver extractRemoteWebDriver(WebDriver driver) {
    Require.nonNull("WebDriver", driver);

    if (driver instanceof RemoteWebDriver) {
      return (RemoteWebDriver) driver;
    }

    if (driver instanceof WrapsDriver) {
      return extractRemoteWebDriver(((WrapsDriver) driver).getWrappedDriver());
    }

    return null;
  }

  private void copyFields(Class<?> clazz, Object source, Object target) {
    if (Object.class.equals(clazz)) {
      // Stop!
      return;
    }

    for (Field field : clazz.getDeclaredFields()) {
      copyField(source, target, field);
    }

    copyFields(clazz.getSuperclass(), source, target);
  }

  private void copyField(Object source, Object target, Field field) {
    if (Modifier.isFinal(field.getModifiers())) {
      return;
    }

    try {
      field.setAccessible(true);
      Object value = field.get(source);
      field.set(target, value);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }

  private static class Augmentation<X> {
    public final Predicate<Capabilities> whenMatches;
    public final Class<X> interfaceClass;
    public final BiFunction<Capabilities, ExecuteMethod, X> implementation;

    public Augmentation(
      Predicate<Capabilities> whenMatches,
      Class<X> interfaceClass,
      BiFunction<Capabilities, ExecuteMethod, X> implementation) {
      this.whenMatches = Require.nonNull("Capabilities predicate", whenMatches);
      this.interfaceClass = Require.nonNull("Interface to implement", interfaceClass);
      this.implementation = Require.nonNull("Interface implementation", implementation);

      Require.precondition(
        interfaceClass.isInterface(),
        "%s must be an interface, not a concrete class",
        interfaceClass);
    }
  }
}


text:
	<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

Prompt for Wednesday, Feb 12. D3 axes, Calculating π.

<svg height="200" width="200"></svg>

A scale is an abstract mapping from data to aesthetics. Scales are closely related to guides and axes. Here's an example of a useful d3 tool for building axes for position scales. We'll use it to create a stochastic estimate of π.

Discussion: data resolution, small multiples

We will look at this article showing multiple ways to present data about the New York City bike share program.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Framework.Provisioning.Connectors;
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers;
using OfficeDevPnP.Core.Framework.Provisioning.Providers;
using SharePointPnP.PowerShell.CmdletHelpAttributes;
using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml;
using OfficeDevPnP.Core.Utilities;
using SharePointPnP.PowerShell.Commands.Enums;
using File = System.IO.File;
using Resources = SharePointPnP.PowerShell.Commands.Properties.Resources;

namespace SharePointPnP.PowerShell.Commands.Branding
{
    [Cmdlet(VerbsCommon.Get, "SPOProvisioningTemplate", SupportsShouldProcess = true)]
    [CmdletHelp("Generates a provisioning template from a web",
        Category = CmdletHelpCategory.Branding)]
    [CmdletExample(
       Code = @"PS:> Get-SPOProvisioningTemplate -Out template.xml",
       Remarks = "Extracts a provisioning template in XML format from the current web.",
       SortOrder = 1)]
    [CmdletExample(
        Code = @"PS:> Get-SPOProvisioningTemplate -Out template.xml -Schema V201503",
        Remarks = "Extracts a provisioning template in XML format from the current web and saves it in the V201503 version of the schema.",
        SortOrder = 2)]
    [CmdletExample(
        Code = @"PS:> Get-SPOProvisioningTemplate -Out template.xml -IncludeAllTermGroups",
        Remarks = "Extracts a provisioning template in XML format from the current web and includes all term groups, term sets and terms from the Managed Metadata Service Taxonomy.",
        SortOrder = 3)]
    [CmdletExample(
        Code = @"PS:> Get-SPOProvisioningTemplate -Out template.xml -IncludeSiteCollectionTermGroup",
        Remarks = "Extracts a provisioning template in XML format from the current web and includes the term group currently (if set) assigned to the site collection.",
        SortOrder = 4)]
    [CmdletExample(
        Code = @"PS:> Get-SPOProvisioningTemplate -Out template.xml -PersistComposedLookFiles",
        Remarks = "Extracts a provisioning template in XML format from the current web and saves the files that make up the composed look to the same folder as where the template is saved.",
        SortOrder = 5)]
    [CmdletExample(
        Code = @"PS:> Get-SPOProvisioningTemplate -Out template.xml -Handlers Lists, SiteSecurity",
        Remarks = "Extracts a provisioning template in XML format from the current web, but only processes lists and site security when generating the template.",
        SortOrder = 5)]
    [CmdletExample(
        Code = @"
PS:> $handler1 = New-SPOExtensibilityHandlerObject -Assembly Contoso.Core.Handlers -Type Contoso.Core.Handlers.MyExtensibilityHandler1
PS:> $handler2 = New-SPOExtensibilityHandlerObject -Assembly Contoso.Core.Handlers -Type Contoso.Core.Handlers.MyExtensibilityHandler1
PS:> Get-SPOProvisioningTemplate -Out NewTemplate.xml -ExtensibilityHandlers $handler1,$handler2",
        Remarks = @"This will create two new ExtensibilityHandler objects that are run during extraction of the template",
        SortOrder = 6)]

    public class GetProvisioningTemplate : SPOWebCmdlet
    {
        [Parameter(Mandatory = false, Position = 0, HelpMessage = "Filename to write to, optionally including full path")]
        public string Out;

        [Parameter(Mandatory = false, Position = 1, HelpMessage = "The schema of the output to use, defaults to the latest schema")]
        public XMLPnPSchemaVersion Schema = XMLPnPSchemaVersion.LATEST;

        [Parameter(Mandatory = false, HelpMessage = "If specified, all term groups will be included. Overrides IncludeSiteCollectionTermGroup.")]
        public SwitchParameter IncludeAllTermGroups;

        [Parameter(Mandatory = false, HelpMessage = "If specified, all the site collection term groups will be included. Overridden by IncludeAllTermGroups.")]
        public SwitchParameter IncludeSiteCollectionTermGroup;

        [Parameter(Mandatory = false, HelpMessage = "If specified all site groups will be included.")]
        public SwitchParameter IncludeSiteGroups;

        [Parameter(Mandatory = false, HelpMessage = "If specified the files used for masterpages, sitelogo, alternate CSS and the files that make up the composed look will be saved.")]
        public SwitchParameter PersistBrandingFiles;

        [Parameter(Mandatory = false, HelpMessage = "If specified the files making up the composed look (background image, font file and color file) will be saved.")]
        [Obsolete("Use PersistBrandingFiles instead.")]
        public SwitchParameter PersistComposedLookFiles;

        [Parameter(Mandatory = false, HelpMessage = "If specified the files used for the publishing feature will be saved.")]
        public SwitchParameter PersistPublishingFiles;

        [Parameter(Mandatory = false, HelpMessage = "If specified, out of the box / native publishing files will be saved.")]
        public SwitchParameter IncludeNativePublishingFiles;

        [Parameter(Mandatory = false, HelpMessage = "Allows you to only process a specific type of artifact in the site. Notice that this might result in a non-working template, as some of the handlers require other artifacts in place if they are not part of what your extracting.")]
        public Handlers Handlers;

        [Parameter(Mandatory = false, HelpMessage = "Allows you to run all handlers, excluding the ones specified.")]
        public Handlers ExcludeHandlers;

        [Parameter(Mandatory = false, HelpMessage = "Allows you to specify ExtensbilityHandlers to execute while extracting a template")]
        public ExtensibilityHandler[] ExtensibilityHandlers;

        [Parameter(Mandatory = false, HelpMessage = "Overwrites the output file if it exists.")]
        public SwitchParameter Force;

        [Parameter(Mandatory = false, HelpMessage = "Exports the template without the use of a base template, causing all OOTB artifacts to be included. Using this switch is generally not required/recommended.")]
        [Obsolete("Use of this method is generally not required/recommended")]
        public SwitchParameter NoBaseTemplate;

        [Parameter(Mandatory = false)]
        public System.Text.Encoding Encoding = System.Text.Encoding.Unicode;

        protected override void ExecuteCmdlet()
        {
            if (!string.IsNullOrEmpty(Out))
            {
                if (!Path.IsPathRooted(Out))
                {
                    Out = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out);
                }
                if (File.Exists(Out))
                {
                    if (Force || ShouldContinue(string.Format(Resources.File0ExistsOverwrite, Out), Resources.Confirm))
                    {
                        var xml = GetProvisioningTemplateXML(Schema, new FileInfo(Out).DirectoryName);

                        File.WriteAllText(Out, xml, Encoding);
                    }
                }
                else
                {
                    var xml = GetProvisioningTemplateXML(Schema, new FileInfo(Out).DirectoryName);

                    File.WriteAllText(Out, xml, Encoding);
                }
            }
            else
            {
                var xml = GetProvisioningTemplateXML(Schema, SessionState.Path.CurrentFileSystemLocation.Path);

                WriteObject(xml);
            }
        }

        private string GetProvisioningTemplateXML(XMLPnPSchemaVersion schema, string path)
        {
            SelectedWeb.EnsureProperty(w => w.Url);

            var creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb);

            if (this.MyInvocation.BoundParameters.ContainsKey("Handlers"))
            {
                creationInformation.HandlersToProcess = Handlers;
            }
            if (this.MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers"))
            {
                foreach (var handler in (OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers[])Enum.GetValues(typeof(Handlers)))
                {
                    if (!ExcludeHandlers.Has(handler) && handler != Handlers.All)
                    {
                        Handlers = Handlers | handler;
                    }
                }
                creationInformation.HandlersToProcess = Handlers;
            }

            creationInformation.PersistBrandingFiles = PersistBrandingFiles || PersistComposedLookFiles;
            creationInformation.PersistPublishingFiles = PersistPublishingFiles;
            creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles;
            creationInformation.IncludeSiteGroups = IncludeSiteGroups;
            if (ExtensibilityHandlers != null)
            {
                creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList<ExtensibilityHandler>();
            }
            creationInformation.FileConnector = new FileSystemConnector(path, "");

#pragma warning disable CS0618 // Type or member is obsolete
            if (NoBaseTemplate)
            {
                creationInformation.BaseTemplate = null;
            }
            else
            {
                creationInformation.BaseTemplate = this.SelectedWeb.GetBaseTemplate();
            }
#pragma warning restore CS0618 // Type or member is obsolete

            creationInformation.ProgressDelegate = (message, step, total) =>
            {
                WriteProgress(new ProgressRecord(0, string.Format("Extracting Template from {0}", SelectedWeb.Url), message) { PercentComplete = (100 / total) * step });
            };
            creationInformation.MessagesDelegate = (message, type) =>
            {
                if (type == ProvisioningMessageType.Warning)
                {
                    WriteWarning(message);
                }
            };

            if (IncludeAllTermGroups)
            {
                creationInformation.IncludeAllTermGroups = true;
            }
            else
            {
                if (IncludeSiteCollectionTermGroup)
                {
                    creationInformation.IncludeSiteCollectionTermGroup = true;
                }
            }

            var template = SelectedWeb.GetProvisioningTemplate(creationInformation);

            ITemplateFormatter formatter = null;
            switch (schema)
            {
                case XMLPnPSchemaVersion.LATEST:
                    {
                        formatter = XMLPnPSchemaFormatter.LatestFormatter;
                        break;
                    }
                case XMLPnPSchemaVersion.V201503:
                    {
#pragma warning disable CS0618 // Type or member is obsolete
                        formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_03);
#pragma warning restore CS0618 // Type or member is obsolete
                        break;
                    }
                case XMLPnPSchemaVersion.V201505:
                    {
                        formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_05);
                        break;
                    }
                case XMLPnPSchemaVersion.V201508:
                    {
                        formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_08);
                        break;
                    }
                case XMLPnPSchemaVersion.V201512:
                    {
                        formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_12);
                        break;
                    }
            }
            var _outputStream = formatter.ToFormattedTemplate(template);
            StreamReader reader = new StreamReader(_outputStream);

            return reader.ReadToEnd();

        }
    }
}


text:
// This is the feature extraction phase of the ColourFAST feature detector, as described in:
//
// A. Ensor and S. Hall. ColourFAST: GPU-based feature point detection and tracking on mobile devices. 28th International Conference of Image and Vision Computing, New Zealand, 2013, p. 124-129.
//
// Seth Hall, "GPU accelerated feature algorithms for mobile devices", PhD thesis, School of Computing and Mathematical Sciences, Auckland University of Technology 2014.
// http://aut.researchgateway.ac.nz/handle/10292/7991

@interface GPUImageColourFASTSamplingOperation : GPUImageTwoInputFilter
{
    GLint texelWidthUniform, texelHeightUniform;

    CGFloat texelWidth, texelHeight;
    BOOL hasOverriddenImageSizeFactor;
}

// The texel width and height determines how far out to sample from this texel. By default, this is the normalized width of a pixel, but this can be overridden for different effects.
@property(readwrite, nonatomic) CGFloat texelWidth;
@property(readwrite, nonatomic) CGFloat texelHeight;

@end


text:
void map_load_globals();
void map_set(const struct map *m);
void map_free();
void map_step(int ms);
int map_move(float *x, float *y, float dx, float dy);
void map_damage(float x, float y, float scale, int dmg);
void map_set_exit(int x, int y);

// Ai
enum map_ai {
	MAI_THUG1,
	MAI_THUG2,
	MAI_THUG3,
	MAI_SLEEPER,
	MAI_RUNNER,
	MAI_BOSS,
};

void mapai_reset();
void mapai_info_player(float x, float y);
void mapai_spawn(enum map_ai mai, int x, int y, float dir);
int mapai_frame(int ms);
void mapai_render();
void mapai_spread(float *x, float *y);
int mapai_damage(float x, float y, float rad, int dmg);

#endif


text:
'use strict';

(function() {
	// Catmenus Controller Spec
	describe('Catmenus Controller Tests', function() {
		// Initialize global variables
		var CatmenusController,
		scope,
		$httpBackend,
		$stateParams,
		$location;

		// The $resource service augments the response object with methods for updating and deleting the resource.
		// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
		// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
		// When the toEqualData matcher compares two objects, it takes only object properties into
		// account and ignores methods.
		beforeEach(function() {
			jasmine.addMatchers({
				toEqualData: function(util, customEqualityTesters) {
					return {
						compare: function(actual, expected) {
							return {
								pass: angular.equals(actual, expected)
							};
						}
					};
				}
			});
		});

		// Then we can start by loading the main application module
		beforeEach(module(ApplicationConfiguration.applicationModuleName));

		// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
		// This allows us to inject a service but then attach it to a variable
		// with the same name as the service.
		beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
			// Set a new global scope
			scope = $rootScope.$new();

			// Point global variables to injected services
			$stateParams = _$stateParams_;
			$httpBackend = _$httpBackend_;
			$location = _$location_;

			// Initialize the Catmenus controller.
			CatmenusController = $controller('CatmenusController', {
				$scope: scope
			});
		}));

		it('$scope.find() should create an array with at least one Catmenu object fetched from XHR', inject(function(Catmenus) {
			// Create sample Catmenu using the Catmenus service
			var sampleCatmenu = new Catmenus({
				name: 'New Catmenu'
			});

			// Create a sample Catmenus array that includes the new Catmenu
			var sampleCatmenus = [sampleCatmenu];

			// Set GET response
			$httpBackend.expectGET('catmenus').respond(sampleCatmenus);

			// Run controller functionality
			scope.find();
			$httpBackend.flush();

			// Test scope value
			expect(scope.catmenus).toEqualData(sampleCatmenus);
		}));

		it('$scope.findOne() should create an array with one Catmenu object fetched from XHR using a catmenuId URL parameter', inject(function(Catmenus) {
			// Define a sample Catmenu object
			var sampleCatmenu = new Catmenus({
				name: 'New Catmenu'
			});

			// Set the URL parameter
			$stateParams.catmenuId = '525a8422f6d0f87f0e407a33';

			// Set GET response
			$httpBackend.expectGET(/catmenus\/([0-9a-fA-F]{24})$/).respond(sampleCatmenu);

			// Run controller functionality
			scope.findOne();
			$httpBackend.flush();

			// Test scope value
			expect(scope.catmenu).toEqualData(sampleCatmenu);
		}));

		it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Catmenus) {
			// Create a sample Catmenu object
			var sampleCatmenuPostData = new Catmenus({
				name: 'New Catmenu'
			});

			// Create a sample Catmenu response
			var sampleCatmenuResponse = new Catmenus({
				_id: '525cf20451979dea2c000001',
				name: 'New Catmenu'
			});

			// Fixture mock form input values
			scope.name = 'New Catmenu';

			// Set POST response
			$httpBackend.expectPOST('catmenus', sampleCatmenuPostData).respond(sampleCatmenuResponse);

			// Run controller functionality
			scope.create();
			$httpBackend.flush();

			// Test form inputs are reset
			expect(scope.name).toEqual('');

			// Test URL redirection after the Catmenu was created
			expect($location.path()).toBe('/catmenus/' + sampleCatmenuResponse._id);
		}));

		it('$scope.update() should update a valid Catmenu', inject(function(Catmenus) {
			// Define a sample Catmenu put data
			var sampleCatmenuPutData = new Catmenus({
				_id: '525cf20451979dea2c000001',
				name: 'New Catmenu'
			});

			// Mock Catmenu in scope
			scope.catmenu = sampleCatmenuPutData;

			// Set PUT response
			$httpBackend.expectPUT(/catmenus\/([0-9a-fA-F]{24})$/).respond();

			// Run controller functionality
			scope.update();
			$httpBackend.flush();

			// Test URL location to new object
			expect($location.path()).toBe('/catmenus/' + sampleCatmenuPutData._id);
		}));

		it('$scope.remove() should send a DELETE request with a valid catmenuId and remove the Catmenu from the scope', inject(function(Catmenus) {
			// Create new Catmenu object
			var sampleCatmenu = new Catmenus({
				_id: '525a8422f6d0f87f0e407a33'
			});

			// Create new Catmenus array and include the Catmenu
			scope.catmenus = [sampleCatmenu];

			// Set expected DELETE response
			$httpBackend.expectDELETE(/catmenus\/([0-9a-fA-F]{24})$/).respond(204);

			// Run controller functionality
			scope.remove(sampleCatmenu);
			$httpBackend.flush();

			// Test array after successful delete
			expect(scope.catmenus.length).toBe(0);
		}));
	});
}());


text:
/
static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
{
    // TODO use VERIFY macros to check for null when they are merged.
    if(NULL == firstId || NULL == secondId)
    {
        return false;
    }
    // Check empty uuid string
    if('\0' == firstId->id[0] || '\0' == secondId->id[0])
    {
        return false;
    }
    for(int i = 0; i < UUID_LENGTH; i++)
    {
        if(firstId->id[i] != secondId->id[i])
        {
            return false;
        }
    }
    return true;
}

void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
{
    if (NULL == context)
    {
        return;
    }

    // Clear stateful context variables.
    memset(&context->subject, 0, sizeof(context->subject));
    memset(&context->resource, 0, sizeof(context->resource));
    context->permission = 0x0;
    context->amsProcessing = false;
    context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;

    if (context->amsMgrContext)
    {
        if (context->amsMgrContext->requestInfo)
        {
            FreeCARequestInfo(context->amsMgrContext->requestInfo);
        }
        OICFree(context->amsMgrContext->endpoint);
        memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
    }

    // Set state.
    context->state = state;
}

/**
 * Compare the request's subject to DevOwner.
 *
 * @return true if context->subjectId == GetDoxmDevOwner(), else false.
 */
static bool IsRequestFromDevOwner(PEContext_t *context)
{
    bool retVal = false;

    if(NULL == context)
    {
        return retVal;
    }

    /*
    if(OC_STACK_OK == GetDoxmDevOwnerId(&ownerid))
    {
        retVal = UuidCmp(&context->subject, &ownerid);
    }
    */

    // TODO: Added as workaround for CTT
    OicSecDoxm_t* doxm = (OicSecDoxm_t*) GetDoxmResourceData();
    if (doxm)
    {
        retVal = UuidCmp(&doxm->owner, &context->subject);
    }
    return retVal;
}

#ifdef MULTIPLE_OWNER
/**
 * Compare the request's subject to SubOwner.
 *
 * @return true if context->subjectId exist subowner list, else false.
 */
static bool IsRequestFromSubOwner(PEContext_t *context)
{
    bool retVal = false;

    if(NULL == context)
    {
        return retVal;
    }

    if(IsSubOwner(&context->subject))
    {
        retVal = true;
    }

    if(true == retVal)
    {
        OIC_LOG(INFO, TAG, "PE.IsRequestFromSubOwner(): returning true");
    }
    else
    {
        OIC_LOG(INFO, TAG, "PE.IsRequestFromSubOwner(): returning false");
    }

    return retVal;
}

/**
 * Verify the SubOwner's request.
 *
 * @return true if request is valid, else false.
 */
static bool IsValidRequestFromSubOwner(PEContext_t *context)
{
    bool isValidRequest = false;

    if(NULL == context)
    {
        return isValidRequest;
    }

    switch(context->resourceType)
    {
        case OIC_R_DOXM_TYPE:
            //SubOwner has READ permission only for DOXM
            if(PERMISSION_READ == context->permission)
            {
                isValidRequest = true;
            }
            break;
        case OIC_R_PSTAT_TYPE:
            //SubOwner has full permsion for PSTAT except RESET
            isValidRequest = IsValidPstatAccessForSubOwner(context->payload, context->payloadSize);
            break;
        case OIC_R_CRED_TYPE:
            //SubOwner can only access the credential which is registered as the eowner.
            isValidRequest = IsValidCredentialAccessForSubOwner(&context->subject, context->payload, context->payloadSize);
            break;
        case OIC_R_ACL_TYPE:
            //SubOwner can only access the ACL which is registered as the eowner.
            isValidRequest = IsValidAclAccessForSubOwner(&context->subject, context->payload, context->payloadSize);
            break;
        default:
            //SubOwner has full permission for all resource except the security resource
            isValidRequest = true;
            break;
    }

    if(isValidRequest)
    {
        OIC_LOG(INFO, TAG, "PE.IsValidRequestFromSubOwner(): returning true");
    }
    else
    {
        OIC_LOG(INFO, TAG, "PE.IsValidRequestFromSubOwner(): returning false");
    }

    return isValidRequest;
}
#endif //MULTIPLE_OWNER

// TODO - remove these function placeholders as they are implemented
// in the resource entity handler code.
// Note that because many SVRs do not have a rowner, in those cases we
// just return "OC_STACK_ERROR" which results in a "false" return by
// IsRequestFromResourceOwner().
// As these SVRs are revised to have a rowner, these functions should be
// replaced (see pstatresource.c for example of GetPstatRownerId).

OCStackResult GetCrlRownerId(OicUuid_t *rowner)
{
    OC_UNUSED(rowner);
    rowner = NULL;
    return OC_STACK_ERROR;
}

OCStackResult GetSaclRownerId(OicUuid_t *rowner)
{
    OC_UNUSED(rowner);
    rowner = NULL;
    return OC_STACK_ERROR;
}

OCStackResult GetSvcRownerId(OicUuid_t *rowner)
{
    OC_UNUSED(rowner);
    rowner = NULL;
    return OC_STACK_ERROR;
}

static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
    GetAclRownerId,
    GetAmaclRownerId,
    GetCredRownerId,
    GetCrlRownerId,
    GetDoxmRownerId,
    GetDpairingRownerId,
    GetPconfRownerId,
    GetPstatRownerId,
    GetSaclRownerId,
    GetSvcRownerId
};

/**
 * Compare the request's subject to resource.ROwner.
 *
 * @return true if context->subjectId equals SVR rowner id, else return false
 */
bool IsRequestFromResourceOwner(PEContext_t *context)
{
    bool retVal = false;
    OicUuid_t resourceOwner;

    if(NULL == context)
    {
        return false;
    }

    if((OIC_R_ACL_TYPE <= context->resourceType) && \
        (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
    {
        if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
        {
            retVal = UuidCmp(&context->subject, &resourceOwner);
        }
    }

    if(true == retVal)
    {
        OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning true");
    }
    else
    {
        OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning false");
    }

    return retVal;
}

INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
{
    OicUuid_t emptySubject = {.id={0}};

    if(NULL == context)
    {
        return false;
    }

    return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
            true : false;
}

/**
 * Bitwise check to see if 'permission' contains 'request'.
 *
 * @param permission is the allowed CRUDN permission.
 * @param request is the CRUDN permission being requested.
 *
 * @return true if 'permission' bits include all 'request' bits.
 */
INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
    const uint16_t request)
{
    if (request == (request & permission))
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * Compare the passed subject to the wildcard (aka anonymous) subjectId.
 *
 * @return true if 'subject' is the wildcard, false if it is not.
 */
INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
{
    if(NULL == subject)
    {
        return false;
    }

    // Because always comparing to string literal, use strcmp()
    if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * Copy the subject, resource and permission into the context fields.
 */
static void CopyParamsToContext(PEContext_t     *context,
                                const OicUuid_t *subjectId,
                                const char      *resource,
                                const uint16_t  requestedPermission)
{
    size_t length = 0;

    if (NULL == context || NULL == subjectId || NULL == resource)
    {
        return;
    }

    memcpy(&context->subject, subjectId, sizeof(OicUuid_t));

    // Copy the resource string into context.
    length = sizeof(context->resource) - 1;
    strncpy(context->resource, resource, length);
    context->resource[length] = '\0';

    // Assign the permission field.
    context->permission = requestedPermission;
}

/**
 * Check whether 'resource' is getting accessed within the valid time period.
 *
 * @param acl is the ACL to check.
 *
 * @return true if access is within valid time period or if the period or recurrence is not present.
 * false if period and recurrence present and the access is not within valid time period.
 */
static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
{
#ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
    //lack of absolute time
    if (NULL== ace || NULL == ace->validities)
    {
        return true;
    }

    //periods & recurrences rules are paired.
    if (NULL == ace->validities->recurrences)
    {
        return false;
    }

    OicSecValidity_t* validity =  NULL;
    LL_FOREACH(ace->validities, validity)
    {
        for(size_t i = 0; i < validity->recurrenceLen; i++)
        {
            if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(validity->period,
                validity->recurrences[i]))
            {
                OIC_LOG(INFO, TAG, "Access request is in allowed time period");
                return true;
            }
        }
    }
    OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
    return false;

#else
    return true;
#endif
}

/**
 * Check whether 'resource' is in the passed ACE.
 *
 * @param resource is the resource being searched.
 * @param ace is the ACE to check.
 *
 * @return true if 'resource' found, otherwise false.
 */
 static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
{
    if (NULL== ace || NULL == resource)
    {
        return false;
    }

    OicSecRsrc_t* rsrc = NULL;
    LL_FOREACH(ace->resources, rsrc)
    {
         if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
             0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
         {
             return true;
         }
    }
    return false;
}

/**
 * Find ACLs containing context->subject.
 * Search each ACL for requested resource.
 * If resource found, check for context->permission and period validity.
 * If the ACL is not found locally and AMACL for the resource is found
 * then sends the request to AMS service for the ACL.
 * Set context->retVal to result from first ACL found which contains
 * correct subject AND resource.
 */
static void ProcessAccessRequest(PEContext_t *context)
{
    OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
    if (NULL != context)
    {
        const OicSecAce_t *currentAce = NULL;
        OicSecAce_t *savePtr = NULL;

        // Start out assuming subject not found.
        context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;

        char *strUuid = NULL;
        if (OC_STACK_OK == ConvertUuidToStr(&context->subject, &strUuid))
        {
            OIC_LOG_V(DEBUG, TAG, "%s: subject : %s" ,__func__, strUuid);
            OICFree(strUuid);
        }
        else
        {
            OIC_LOG(ERROR, TAG, "Can't convert subject uuid to string");
        }

        // Loop through all ACLs with a matching Subject searching for the right
        // ACL for this request.
        do
        {
            OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
            currentAce = GetACLResourceData(&context->subject, &savePtr);

            if (NULL != currentAce)
            {
                // Found the subject, so how about resource?
                OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);

                // Subject was found, so err changes to Rsrc not found for now.
                context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
                OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
                if (IsResourceInAce(context->resource, currentAce))
                {
                    OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);

                    // Found the resource, so it's down to valid period & permission.
                    context->retVal = ACCESS_DENIED_INVALID_PERIOD;
                    if (IsAccessWithinValidTime(currentAce))
                    {
                        context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
                        if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
                        {
                            context->retVal = ACCESS_GRANTED;
                        }
                    }
                }
            }
            else
            {
                OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
            }
        } while ((NULL != currentAce) && (ACCESS_GRANTED != context->retVal));

        if (IsAccessGranted(context->retVal))
        {
            OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
        }
        else
        {
            OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
        }
    }
    else
    {
        OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
    }
}

SRMAccessResponse_t CheckPermission(PEContext_t     *context,
                                    const OicUuid_t *subjectId,
                                    const char      *resource,
                                    const uint16_t  requestedPermission)
{
    SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;

    VERIFY_NON_NULL(TAG, context, ERROR);
    VERIFY_NON_NULL(TAG, subjectId, ERROR);
    VERIFY_NON_NULL(TAG, resource, ERROR);

    // Each state machine context can only be processing one request at a time.
    // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
    // state, return error. Otherwise, change to BUSY state and begin processing request.
    if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
    {
        if (AWAITING_REQUEST == context->state)
        {
            SetPolicyEngineState(context, BUSY);
            CopyParamsToContext(context, subjectId, resource, requestedPermission);
        }

        // Before doing any ACL processing, check if request a) coming
        // from DevOwner AND b) the device is in Ready for OTM or Reset state
        // (which in IoTivity is equivalent to isOp == false && owned == false)
        // AND c) the request is for a SVR resource.
        // If all 3 conditions are met, grant request.
        bool isDeviceOwned = true; // default to value that will not grant access
        if (OC_STACK_OK != GetDoxmIsOwned(&isDeviceOwned)) // if runtime error, don't grant
        {
            context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
        }
        // If we were able to get the value of doxm->isOwned, proceed with
        // test for implicit access...
        else if (IsRequestFromDevOwner(context) // if from DevOwner
        && (GetPstatIsop() == false) // AND if pstat->isOp == false
        && (isDeviceOwned == false) // AND if doxm->isOwned == false
        && (context->resourceType != NOT_A_SVR_RESOURCE)) // AND if SVR type
        {
            context->retVal = ACCESS_GRANTED;
        }
        // If not granted via DevOwner status and not a subowner,
        // then check if request is for a SVR and coming from rowner
        else if (IsRequestFromResourceOwner(context))
        {
            context->retVal = ACCESS_GRANTED;
        }
#ifdef MULTIPLE_OWNER
        //Then check if request from SubOwner
        else if(IsRequestFromSubOwner(context))
        {
            if(IsValidRequestFromSubOwner(context))
            {
                context->retVal = ACCESS_GRANTED;
            }
        }
#endif //MULTIPLE_OWNER
        // Else request is a "normal" request that must be tested against ACL
        else
        {
            OicUuid_t saveSubject = {.id={0}};
            bool isSubEmpty = IsRequestSubjectEmpty(context);

            ProcessAccessRequest(context);

            // If access not already granted, and requested subject != wildcard,
            // try looking for a wildcard ACE that grants access.
            if ((ACCESS_GRANTED != context->retVal) && \
              (false == IsWildCardSubject(&context->subject)))
            {
                //Saving subject for Amacl check
                memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));

                //Setting context subject to WILDCARD_SUBJECT_ID
                //TODO: change ProcessAccessRequest method signature to
                //ProcessAccessRequest(context, subject) so that context
                //subject is not tempered.
                memset(&context->subject, 0, sizeof(context->subject));
                memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
                ProcessAccessRequest(context); // TODO anonymous subj can result
                                               // in confusing err code return.
            }

            //No local ACE found for the request so checking Amacl resource
            if (ACCESS_GRANTED != context->retVal)
            {
                //If subject is not empty then restore the original subject
                //else keep the subject to WILDCARD_SUBJECT_ID
                if(!isSubEmpty)
                {
                    memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
                }

                //FoundAmaclForRequest method checks for Amacl and fills up
                //context->amsMgrContext->amsDeviceId with the AMS deviceId
                //if Amacl was found for the requested resource.
                if(FoundAmaclForRequest(context))
                {
                    ProcessAMSRequest(context);
                }
            }
        }
    }
    else
    {
        context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
    }

    // Capture retVal before resetting state for next request.
    retVal = context->retVal;

   if (!context->amsProcessing)
    {
        OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
        SetPolicyEngineState(context, AWAITING_REQUEST);
    }

exit:
    return retVal;
}

OCStackResult InitPolicyEngine(PEContext_t *context)
{
    if(NULL == context)
    {
        return OC_STACK_ERROR;
    }

    context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
    if(NULL == context->amsMgrContext)
    {
        return OC_STACK_ERROR;
    }

    SetPolicyEngineState(context, AWAITING_REQUEST);
    return OC_STACK_OK;
}

void DeInitPolicyEngine(PEContext_t *context)
{
    if(NULL != context)
    {
        SetPolicyEngineState(context, STOPPED);
        OICFree(context->amsMgrContext);
    }
    return;
}


text:
classdef splinepwp < closedcurve
% SPLINEPWP is a periodic piecewise spline with corners.
%
% G = splinepwp(knots, corners)
% The corners array is a set of indicies of the knots array which dictates
% which knots in the list will be corners. The array corners should be
% strictly monotonically increasing with
%   1 <= corners(1) and corners(end) <= numel(knots).
% If corners(1) ~= 1, then the knots and corners arrays will be rearranged
% so that this is the case.
%
% Currently the corner angles are determined strictly by the angles of
% neighboring knots, by pretending we are making a polygon with the knots
% as vertices.
%
% This class is mainly for testing corner cases on boundaries that aren't
% polygons. For instance it is completely arbitrary that the value of the
% tangent at a corner is the average of the incoming and outgoing tangent
% vectors. In fact to create the splines between corners, the endpoint
% tangent vectors arbitrarily have a magnitude of 5, which was selected
% because it gives the "nicest, natural" distribution of points for an
% evenly spaced discrete parameterization.

% This file is a part of the CMToolkit.
% It is licensed under the BSD 3-clause license.
% (See LICENSE.)

% Copyright Toby Driscoll, 2014.
% Written by Everett Kropf, 2014.

properties(SetAccess=protected)
    knots               % Complex array of spline knots.
    corners             % Vector of index values for knots indicating corners.
    alpha               % Array of calculated corner interior angles.
    tknots              % Parameter values for knots.
    cornerTangent       % Incoming/outgoing corner tangent vectors.
end

properties(Dependent)
    breaks
end

properties(Access=protected)
    ppx
    ppy
end

methods
    function G = splinepwp(knots, corners)
        % Constructor.

        if ~nargin
            return
        end

        % Check input.
        corners = corners(:);
        knots = knots(:);
        if knots(1) == knots(end)
            knots = knots(1:end-1);
        end
        if any(diff(corners) <= 0)
            error('CMT:BadArguemnt', ...
                'The corners array must be strictly monotonically increasing.')
        end
        try
            knots(corners);
        catch err
            if strcmp(err.identifier, 'MATLAB:badsubscript')
                error('CMT:BadArgument', ...
                    'The corners array must be a valid set of indices for knots.')
            else
                rethrow(err)
            end
        end

        % Constructor work.
        G.knots = knots;
        G.corners = corners;
        G = calculateSplines(G);
    end

    function tk = get.breaks(G)
        tk = [G.tknots(G.corners); 1];
    end

    function z = point(G, t)
        % Point on curve at t.

        z = paramEval(G, t, 0);
    end

    function zt = tangent(G, t)
        % Tangent to curve at t. With average corner tangents.

        zt = paramEval(G, t, 1);
        cavg = sum(G.cornerTangent, 2)/2;
        ct = G.breaks;
        for k = 1:numel(ct)-1
           ctL = abs(t - ct(k)) < 10*eps;
           zt(ctL) = cavg(k);
        end
    end
end

methods(Access=protected)
    function G = calculateSplines(G)
        v = G.knots;
        cv = G.corners;
        if cv(1) ~= 1
            % Shift corners and knots.
            shift = cv(1) - 1;
            v = circshift(v, -shift);
            cv = cv - shift;
        end

        % Pseudo arc length parameterization via chordal arclengths.
        nv = numel(v);
        v = [v; v(1)];
        dL = abs(diff(v));
        t = [0; cumsum(dL)];
        t = t/t(end);

        % Corner angles determined by neighboring knots.
        pv = mod(cv - 2, nv) + 1;
        fv = mod(cv, nv) + 1;
        alpha_ = mod(angle((v(pv) - v(cv))./(v(fv) - v(cv)))/pi, 2);

        % Outgoing/incoming tangent vectors.
        vtan = [ v(fv) - v(cv), v(cv) - v(pv) ];
        mu = 5; % (arbitrary) tangent vector magnitude
        vtan = mu*vtan./abs(vtan);

        % Compute piecewise polynomial splines for segments between corners.
        ncv = numel(cv);
        ppx_(ncv, 3) = mkpp([1 1], [1 1]);
        ppy_ = ppx_;
        for k = 1:ncv
            if k + 1 <= ncv
                vdx = cv(k):cv(k+1);
            else
                vdx = cv(k):nv+1;
            end
            vex = [vtan(k,1); v(vdx); vtan(mod(k, ncv)+1,2)];
            tk = t(vdx);

            % Piecewise polynomials and derivatives.
            ppx_(k,1) = spline(tk, real(vex));
            ppx_(k,2:3) = splinepwp.ppderivs(ppx_(k,1));
            ppy_(k,1) = spline(tk, imag(vex));
            ppy_(k,2:3) = splinepwp.ppderivs(ppy_(k,1));
        end

        G.knots = v(1:end-1);
        G.corners = cv;
        G.alpha = alpha_;
        G.ppx = ppx_;
        G.ppy = ppy_;
        G.tknots = t;
        G.cornerTangent = vtan;
    end

    function z = paramEval(G, t, d)
        % Evaluate curve given parameter using derivative level d.

        if nargin < 3
            % No derivative.
            d = 0;
        end
        d = d + 1;
        t = modparam(G, t);
        z = nan(size(t));

        brks = G.breaks;
        for k = 1:numel(G.corners)
            tL = brks(k) <= t & t < brks(k+1);
            z(tL) = complex(ppval(G.ppx(k,d), t(tL)), ppval(G.ppy(k,d), t(tL)));
        end
    end
end

methods(Static, Access=private)
    function ppd = ppderivs(pp)
        % First and second derivatives of piecewise polynomial pp.
        coef = pp.coefs;
        ppd = [ mkpp(pp.breaks, [3*coef(:,1), 2*coef(:,2), coef(:,3)]), ...
            mkpp(pp.breaks, [6*coef(:,1), 2*coef(:,2)]) ];
    end
end

end


text:
package cmd

import (
	"fmt"
	"strings"

	"github.com/aptly-dev/aptly/deb"
	"github.com/smira/commander"
)

func aptlyPublishShow(cmd *commander.Command, args []string) error {
	var err error
	if len(args) < 1 || len(args) > 2 {
		cmd.Usage()
		return commander.ErrCommandError
	}

	distribution := args[0]
	param := "."

	if len(args) == 2 {
		param = args[1]
	}

	storage, prefix := deb.ParsePrefix(param)

	repo, err := context.CollectionFactory().PublishedRepoCollection().ByStoragePrefixDistribution(storage, prefix, distribution)
	if err != nil {
		return fmt.Errorf("unable to show: %s", err)
	}

	if repo.Storage != "" {
		fmt.Printf("Storage: %s\n", repo.Storage)
	}
	fmt.Printf("Prefix: %s\n", repo.Prefix)
	if repo.Distribution != "" {
		fmt.Printf("Distribution: %s\n", repo.Distribution)
	}
	fmt.Printf("Architectures: %s\n", strings.Join(repo.Architectures, " "))

	fmt.Printf("Sources:\n")
	for component, sourceID := range repo.Sources {
		var name string
		if repo.SourceKind == deb.SourceSnapshot {
			source, e := context.CollectionFactory().SnapshotCollection().ByUUID(sourceID)
			if e != nil {
				continue
			}
			name = source.Name
		} else if repo.SourceKind == deb.SourceLocalRepo {
			source, e := context.CollectionFactory().LocalRepoCollection().ByUUID(sourceID)
			if e != nil {
				continue
			}
			name = source.Name
		}

		if name != "" {
			fmt.Printf("  %s: %s [%s]\n", component, name, repo.SourceKind)
		}
	}

	return err
}

func makeCmdPublishShow() *commander.Command {
	cmd := &commander.Command{
		Run:       aptlyPublishShow,
		UsageLine: "show <distribution> [[<endpoint>:]<prefix>]",
		Short:     "shows details of published repository",
		Long: `
Command show displays full information of a published repository.

Example:

    $ aptly publish show wheezy
`,
	}

	return cmd
}