text:
<?php
require_once __DIR__.'/../../../config.inc.php';
use TPGwidget\Data\{Lines, Stops};

function error() {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}

$fileUrl = 'http://prod.ivtr-od.tpg.ch/v1/GetPhysicalStops.json?key='.getenv('TPG_API_KEY');
$fileContents = @file_get_contents($fileUrl);
if (!$fileContents) {
    error();
}

$stops = json_decode($fileContents, true);
if (!$stops || !isset($stops['stops'])) {
    error();
}

header('Content-type: application/json; charset=utf-8');

const FEATURED_STOPS = ['CVIN', 'BAIR', 'RIVE', 'AERO', 'COUT', 'PLPA', 'NATI', 'JOCT', 'CRGE', 'ESRT', 'HOPI', 'BHET'];
$output = ['featured' => [], 'all' => [], 'error' => null];

// Stops list
$byStopCode = [];
foreach ($stops['stops'] as $stop) {
    $lines = [];
    $geolocation = null;

    $physicalStops = $stop['physicalStops'];

    // Average geolocation
    $average = function($prop) use ($physicalStops) {
        $result = 0;
        $count = 0;

        foreach ($physicalStops as $stop) {
            $value = $stop['coordinates'][$prop] ?? null;
            if (is_null($value)) {
                continue;
            }

            $result += $value;
            $count += 1;
        }

        if ($count === 0) {
            return null;
        }

        return $result / $count;
    };

    $geolocation = [
        'latitude' => $average('latitude'),
        'longitude' => $average('longitude'),
    ];

    if (is_null($geolocation['latitude']) || is_null($geolocation['longitude'])) {
        $geolocation = null;
    }

    // Lines
    $lineCodes = [];
    foreach ($physicalStops as $physicalStop) {
        foreach ($physicalStop['connections'] as $connection) {
            $lineCodes[] = $connection['lineCode'];
        }
    }
    $lineCodes = array_unique($lineCodes);
    sort($lineCodes);
    $lines = array_map(function ($lineCode) {
        return Lines::get($lineCode);
    }, $lineCodes);

    $nameFormatted = Stops::format($stop['stopName'] ?? '');
    $stopData = [
        'id' => $stop['stopCode'] ?? null,
        'name' => [
            'formatted' => $nameFormatted,
            'corrected' => strip_tags($nameFormatted),
            'raw' => $stop['stopName'],
        ],
        'lines' => $lines,
        'geolocation' => $geolocation,
    ];

    $output['all'][] = $stopData;
    $byStopCode[$stop['stopCode'] ?? ''] = $stopData;
}

// Sort stops
uasort($output['all'], function($a, $b) {
    return strcmp(strip_tags($a['name']['formatted']), strip_tags($b['name']['formatted']));
});
$output['all'] = array_values($output['all']);

// Featured stops
foreach (FEATURED_STOPS as $featured) {
    if (array_key_exists($featured, $byStopCode)) {
        $output['featured'][] = $byStopCode[$featured];
    }
}

echo json_encode($output);


text:
//
// MacWebView.cs
//
// Author:
//       Lluis Sanchez Gual <lluis@xamarin.com>
//       Vsevolod Kukol <sevo@sevo.org>
//
// Copyright (c) 2014 Xamarin, Inc (http://www.xamarin.com)
//
// 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.
using System;
using Xwt.GtkBackend;
using Xwt.Backends;
using MonoMac.Foundation;

namespace Xwt.Gtk.Mac
{
	public class WebViewBackend : WidgetBackend, IWebViewBackend
	{
		MonoMac.WebKit.WebView view;

		public WebViewBackend ()
		{
		}

		#region IWebViewBackend implementation
		public override void Initialize()
		{
			base.Initialize ();

			view = new MonoMac.WebKit.WebView ();
			Widget = GtkMacInterop.NSViewToGtkWidget (view);
			Widget.Show ();
		}

		public string Url {
			get { return view.MainFrameUrl; }
			set {
				view.MainFrameUrl = value;
			}
		}

		public string Title {
			get {
				return view.MainFrameTitle;
			}
		}

		public double LoadProgress {
			get {
				return view.EstimatedProgress;
			}
		}

		public bool CanGoBack {
			get {
				return view.CanGoBack ();
			}
		}

		public bool CanGoForward {
			get {
				return view.CanGoForward ();
			}
		}

		public void GoBack ()
		{
			view.GoBack ();
		}

		public void GoForward ()
		{
			view.GoForward ();
		}

		public void Reload ()
		{
			view.MainFrame.Reload ();
		}

		public void StopLoading ()
		{
			view.MainFrame.StopLoading ();
		}

		public void LoadHtml (string content, string base_uri)
		{
			view.MainFrame.LoadHtmlString (content, new NSUrl(base_uri));
		}

		protected new IWebViewEventSink EventSink {
			get { return (IWebViewEventSink)base.EventSink; }
		}

		public override void EnableEvent (object eventId)
		{
			base.EnableEvent (eventId);
			if (eventId is WebViewEvent) {
				switch ((WebViewEvent)eventId) {
					case WebViewEvent.NavigateToUrl: view.StartedProvisionalLoad += HandleStartedProvisionalLoad; break;
					case WebViewEvent.Loading: view.CommitedLoad += HandleLoadStarted; break;
					case WebViewEvent.Loaded: view.FinishedLoad += HandleLoadFinished; break;
					case WebViewEvent.TitleChanged: view.ReceivedTitle += HandleTitleChanged; break;
				}
			}
		}

		public override void DisableEvent (object eventId)
		{
			base.DisableEvent (eventId);
			if (eventId is WebViewEvent) {
				switch ((WebViewEvent)eventId) {
					case WebViewEvent.NavigateToUrl: view.StartedProvisionalLoad -= HandleStartedProvisionalLoad; break;
					case WebViewEvent.Loading: view.CommitedLoad += HandleLoadStarted; break;
					case WebViewEvent.Loaded: view.FinishedLoad -= HandleLoadFinished; break;
					case WebViewEvent.TitleChanged: view.ReceivedTitle -= HandleTitleChanged; break;
				}
			}
		}

		void HandleStartedProvisionalLoad (object sender, MonoMac.WebKit.WebFrameEventArgs e)
		{
			var url = String.Empty;
			if (e.ForFrame.ProvisionalDataSource.Request.MainDocumentURL != null)
				url = e.ForFrame.ProvisionalDataSource.Request.MainDocumentURL.ToString ();
			if (String.IsNullOrEmpty (url))
				return;

			bool cancel = false;
			ApplicationContext.InvokeUserCode (delegate {
				cancel = EventSink.OnNavigateToUrl(url);
			});
			if (cancel)
				e.ForFrame.StopLoading ();
		}

		void HandleLoadStarted (object o, EventArgs args)
		{
			ApplicationContext.InvokeUserCode (delegate {
				EventSink.OnLoading ();
			});
		}

		void HandleLoadFinished (object o, EventArgs args)
		{
			ApplicationContext.InvokeUserCode (delegate {
				EventSink.OnLoaded ();
			});
		}

		void HandleTitleChanged (object sender, MonoMac.WebKit.WebFrameTitleEventArgs e)
		{
			ApplicationContext.InvokeUserCode (delegate {
				EventSink.OnTitleChanged ();
			});
		}
		#endregion
	}
}

redpajama_set_name: RedPajamaGithub


text:
from unittest.mock import Mock
from clustaar.authorize.rules import AccessRule
from clustaar.authorize.context import Context
import pytest

@pytest.fixture
def resolver(user):
    def handler(context):
        context["user"] = user

    return handler

@pytest.fixture
def condition():
    return Mock(return_value=False)

@pytest.fixture
def user():
    return Mock()

@pytest.fixture
def rule(resolver, condition):
    return AccessRule(resolvers=(resolver,), condition=condition)

class TestCall(object):
    def test_sends_context_to_condition(self, rule, user, condition):
        context = Context(kwargs={"user_id": 1})
        rule(context)
        context = condition.call_args_list[0][0][0]
        assert context["user"] == user

    def test_returns_value_from_condition(self, rule):
        context = Context()
        assert not rule(context)


text:
---
layout: jsdoc
title: "Source: lib/log-helper.js"
jsdocNav:
  - Modules:
    - workbox-background-sync
    - workbox-broadcast-cache-update
    - workbox-build
    - workbox-cache-expiration
    - workbox-cacheable-response
    - workbox-google-analytics
    - workbox-precaching
    - workbox-routing
    - workbox-runtime-caching
    - workbox-sw
    - workbox-webpack-plugin
---

/* eslint-disable no-console */

import LogGroup from './log-group';
import environment from './environment';

self.workbox = self.workbox || {};
self.workbox.LOG_LEVEL = self.workbox.LOG_LEVEL || {
  none: -1,
  verbose: 0,
  debug: 1,
  warn: 2,
  error: 3,
};

const LIGHT_GREY = `#bdc3c7`;
const DARK_GREY = `#7f8c8d`;
const LIGHT_GREEN = `#2ecc71`;
const LIGHT_YELLOW = `#f1c40f`;
const LIGHT_RED = `#e74c3c`;
const LIGHT_BLUE = `#3498db`;

/**
 * A class that will only log given the current log level
 * defined by the developer.
 *
 * Define custom log level by setting `self.workbox.logLevel`.
 *
 * @example
 *
 * self.workbox.logLevel = self.workbox.LOG_LEVEL.verbose;
 *
 * @private
 */
class LogHelper {
  /**
   * LogHelper constructor.
   */
  constructor() {
    this._defaultLogLevel = environment.isDevBuild() ?
      self.workbox.LOG_LEVEL.debug :
      self.workbox.LOG_LEVEL.warn;
  }

  /**
   * The most verbose log level.
   *
   * @param {Object} options The options of the log.
   */
  log(options) {
    this._printMessage(self.workbox.LOG_LEVEL.verbose, options);
  }

  /**
   * Useful for logs that are more exceptional that log()
   * but not severe.
   *
   * @param {Object} options The options of the log.
   */
  debug(options) {
    this._printMessage(self.workbox.LOG_LEVEL.debug, options);
  }

  /**
   * Warning messages.
   *
   * @param {Object} options The options of the log.
   */
  warn(options) {
    this._printMessage(self.workbox.LOG_LEVEL.warn, options);
  }

  /**
   * Error logs.
   *
   * @param {Object} options The options of the log.
   */
  error(options) {
    this._printMessage(self.workbox.LOG_LEVEL.error, options);
  }

  /**
   * Method to print to the console.
   * @param {number} logLevel
   * @param {Object} logOptions
   */
  _printMessage(logLevel, logOptions) {
    if (!this._shouldLogMessage(logLevel, logOptions)) {
      return;
    }

    const logGroups = this._getAllLogGroups(logLevel, logOptions);
    logGroups.print();
  }

  /**
   * Print a user friendly log to the console.
   * @param  {numer} logLevel A number from self.workbox.LOG_LEVEL
   * @param  {Object} logOptions Arguments to print to the console
   * @return {LogGroup} Returns a log group to print to the console.
   */
  _getAllLogGroups(logLevel, logOptions) {
    const topLogGroup = new LogGroup({
      isPrimary: true,
      title: 'workbox log.',
    });

    const primaryMessage = this._getPrimaryMessageDetails(logLevel, logOptions);
    topLogGroup.addLog(primaryMessage);

    if (logOptions.error) {
      const errorMessage = {
        message: logOptions.error,
        logFunc: console.error,
      };
      topLogGroup.addLog(errorMessage);
    }

    const extraInfoGroup = new LogGroup({title: 'Extra Information.'});
    if (logOptions.that && logOptions.that.constructor &&
      logOptions.that.constructor.name) {
      const className = logOptions.that.constructor.name;
      extraInfoGroup.addLog(
        this._getKeyValueDetails('class', className)
      );
    }

    if (logOptions.data) {
      if (typeof logOptions.data === 'object' &&
        !(logOptions.data instanceof Array)) {
        Object.keys(logOptions.data).forEach((keyName) => {
          extraInfoGroup.addLog(
            this._getKeyValueDetails(keyName, logOptions.data[keyName])
          );
        });
      } else {
        extraInfoGroup.addLog(
          this._getKeyValueDetails('additionalData', logOptions.data)
        );
      }
    }

    topLogGroup.addChildGroup(extraInfoGroup);

    return topLogGroup;
  }

  /**
   * This is a helper function to wrap key value pairss to a colored key
   * value string.
   * @param  {string} key
   * @param  {string} value
   * @return {Object} The object containing a message, color and Arguments
   * for the console.
   */
  _getKeyValueDetails(key, value) {
    return {
      message: `%c${key}: `,
      colors: [`color: ${LIGHT_BLUE}`],
      args: value,
    };
  }

  /**
   * Helper method to color the primary message for the log
   * @param  {number} logLevel   One of self.workbox.LOG_LEVEL
   * @param  {Object} logOptions Arguments to print to the console
   * @return {Object} Object containing the message and color info to print.
   */
  _getPrimaryMessageDetails(logLevel, logOptions) {
    let logLevelName;
    let logLevelColor;
    switch (logLevel) {
      case self.workbox.LOG_LEVEL.verbose:
        logLevelName = 'Info';
        logLevelColor = LIGHT_GREY;
        break;
      case self.workbox.LOG_LEVEL.debug:
        logLevelName = 'Debug';
        logLevelColor = LIGHT_GREEN;
        break;
      case self.workbox.LOG_LEVEL.warn:
        logLevelName = 'Warn';
        logLevelColor = LIGHT_YELLOW;
        break;
      case self.workbox.LOG_LEVEL.error:
        logLevelName = 'Error';
        logLevelColor = LIGHT_RED;
        break;
    }

    let primaryLogMessage = `%c🔧 %c[${logLevelName}]`;
    const primaryLogColors = [
      `color: ${LIGHT_GREY}`,
      `color: ${logLevelColor}`,
    ];

    let message;
    if(typeof logOptions === 'string') {
      message = logOptions;
    } else if (logOptions.message) {
      message = logOptions.message;
    }

    if (message) {
      message = message.replace(/\s+/g, ' ');
      primaryLogMessage += `%c ${message}`;
      primaryLogColors.push(`color: ${DARK_GREY}; font-weight: normal`);
    }

    return {
      message: primaryLogMessage,
      colors: primaryLogColors,
    };
  }

  /**
   * Test if the message should actually be logged.
   * @param {number} logLevel The level of the current log to be printed.
   * @param {Object|String} logOptions The options to log.
   * @return {boolean} Returns true of the message should be printed.
   */
  _shouldLogMessage(logLevel, logOptions) {
    if (!logOptions) {
      return false;
    }

    let minValidLogLevel = this._defaultLogLevel;
    if (self && self.workbox && typeof self.workbox.logLevel === 'number') {
      minValidLogLevel = self.workbox.logLevel;
    }

    if (minValidLogLevel === self.workbox.LOG_LEVEL.none ||
      logLevel < minValidLogLevel) {
      return false;
    }

    return true;
  }
}

export default new LogHelper();


text:
mvn clean package
java -Xmx800m -jar target/formsapiservice-1.0-SNAPSHOT.jar server configuration.yml


text:
import Island from './Island';
import IslandGroup from './IslandGroup';

export default Island;
export { Island, IslandGroup };


text:
package com.lucaslz.uicomponentexamples;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;

import com.lucaslz.component.activity.SingleFragmentActivity;

/**
 * Created by lucas on 2017/10/8.
 */
public abstract class GoBackActivity extends SingleFragmentActivity {

    private String mActionBarTitle;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar == null) {
            return;
        }
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void setActionBarTitle(String actionBarTitle) {
        mActionBarTitle = actionBarTitle;

        ActionBar actionBar = getSupportActionBar();
        if (actionBar == null) {
            return;
        }
        actionBar.setTitle(actionBarTitle);
    }

    public String getActionBarTitle() {
        return mActionBarTitle;
    }
}


text:
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * DS202: Simplify dynamic range loops
 * DS206: Consider reworking classes to avoid initClass
 * DS207: Consider shorter variations of null checks
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
Number.prototype.toRad = function() { return (this * Math.PI) / 180; };
Number.prototype.toDeg = function() { return (this * 180) / Math.PI; };

const GSVHyperlapseHeading = {
	BACKWARD: "backward",
	LOOKAT: "lookat",
	NORTH: "north",
	BEGINNING: "begin"
};

const GSVHyperlapseMethod = {
	DRECTION: 'direction',
	PANOID: 'panoid'
};

const pointOnLine = function(t, a, b) {
	const lat1 = a.lat().toRad();
	const lng1 = a.lng().toRad();

	const lat2 = b.lat().toRad();
	const lng2 = b.lng().toRad();

	const x = lat1 + (t * (lat2 - lat1));
	const y = lng1 + (t * (lng2 - lng1));

	return new google.maps.LatLng(x.toDeg(), y.toDeg());
};

const getFollowedPath = function(m, a, b) {
	const d = google.maps.geometry.spherical.computeDistanceBetween(a, b);

	if ((m < 0) || (d < m)) {
		alert("error getFolowedPath");
	}

	const t = m / d;

	return pointOnLine(t, a, b);
};

// http://hideichi.com/archives/94
const uniqueID = function() {
	const randam = Math.floor(Math.random()*1000);
	const date = new Date();
	const time = date.getTime();
	return randam + time.toString();
};

class GSVHyperlapse {
	static initClass() {

		// const
		this.DIST_BETWEEN_PTS = 5;
		this.MAX_PTS = 100;

		// static var
		this.dirService = new google.maps.DirectionsService({});
		this.dirRegex = /dir\/([0-9.-]*),([0-9.-]*)\/([0-9.-]*),([0-9.-]*)\/@([0-9.-]*),([0-9.-]*),([0-9]*)z(.*)(\/data=(.*))?$/;
		// @dirRegex = /\/@([0-9.-]*),([0-9.-]*),([0-9]*)z(.*)(\/data=(.*))?$/
		this.dataRegex = /!1d([0-9.-]*)!2d([0-9.-]*)/g;
		this.dataLatLngRegex = /!1d([0-9.-]*)!2d([0-9.-]*)/;
	}

	// event
	static onError(err) { return alert("error"); }
	static onMessage() { return null; }
	static onPanoramaLoad() { return null; }
	static onAnalyzeComplete() { return null; }
	static onComposeComplete() { return null; }
	static onProgress() { return null; }
	static onCancel() { return null; }

	// constructor
	constructor(name, map) {
		this.name = name;

		this.bCancel = false;
		this.bWaiting = false;
		this.uid = uniqueID();
		this.panoList = [];
		this.client = new google.maps.StreetViewService();
		this.gsvp = new GSVPANO.PanoLoader();
		if (map != null) {
			this.map = new google.maps.Map(map, {
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				zoom: 16
			}
			);
		}
	}

	// methods
	cancel() {
		this.bCancel = true;
		if (!this.bWaiting) {
			return GSVHyperlapse.onCancel.call(this);
		}
	}

	// --------------------------------------------------------
	// class method
	createPanoData(res) {
		return {
			id: res.location.pano,
			rotation: res.tiles.centerHeading,// * Math.PI / 180.0
			pitch: res.tiles.originPitch,// * Math.PI / 180.0
			latLng: res.location.latLng,
			date: res.imageDate
		};
	}

	setParameters(params) {

		this.method 		= params.method;
		this.travelMode 	= params.travelMode;
		this.step 			= parseFloat(params.step);
		this.searchRadius	= parseFloat(params.searchRadius);
		this.headingMode	= params.headingMode;
		this.zoom 			= parseInt(params.zoom);

		this.gsvp.setZoom( this.zoom );

		// check headingMode
		if (this.headingMode === GSVHyperlapseHeading.LOOKAT) {
			const result = /([0-9.]+), ([0-9.]+)/.exec( params.lookat );
			if ((result == null)) {
				alert("lookat latLng cannot be parsed");
				return;
			}
			return this.lookat = new google.maps.LatLng( result[1], result[2] );
		}
	}

	// --------------------------------------------------------
	createFromDirection(originName, destinationName){

		let destination;
		const rawPts = [];
		let routeRes = null;
		let prevId = '';
		this.method = GSVHyperlapseMethod.DIRECTION;

		let origin = (destination = null);

		// ===================================
		// 0. retrieve lat lng from place name

		const createRequest = () => {

			let checkRetrieved;
			const geocoder = new google.maps.Geocoder();

			geocoder.geocode({'address': originName}, (results, status) => {
				if (status === google.maps.GeocoderStatus.OK) {
					origin = results[0].geometry.location;

					console.log(results[0].geometry.location.lat);
					window.origin = results;
					return checkRetrieved();
				} else {
					return alert("origin returns ZERO_RESULTS");
				}
			});

			geocoder.geocode({'address': destinationName}, (results, status) => {
				if (status === google.maps.GeocoderStatus.OK) {
					destination = results[0].geometry.location;
				} else {
					alert("destination returns ZERO_RESULTS");
				}
				return checkRetrieved();
			});

			return checkRetrieved = () => {
				if ((origin !== null) && (destination !== null)) {
					console.log("Unco");
					return requestRoute();
				}
			};
		};

		// ===================================
		// 1. request route
		var requestRoute = () => {

			// calc bounds
			const bounds = new google.maps.LatLngBounds();

			bounds.extend(origin);
			bounds.extend(destination);

			this.map.fitBounds(bounds);

			console.log(this.travelMode);

			const req = {
				origin,
				destination,
				travelMode: this.travelMode
			};

			// parse waypoint from data
			// waypoints = []

			// if (result = result[8].match( GSVHyperlapse.dataRegex ))?
			// 	for i, r of result
			// 		m = GSVHyperlapse.dataLatLngRegex.exec( r )
			// 		wp = new google.maps.LatLng( m[2], m[1] )
			// 		waypoints.push
			// 			location: wp.toString()
			// 			stopover: false

			// 	req.waypoints = waypoints

			return GSVHyperlapse.dirService.route(req, (res, status) => {

				if (status === google.maps.DirectionsStatus.OK) {
					routeRes = res;
					// next
					return subdivideRoute();
				} else {
					return GSVHyperlapse.onMessage.call(this, "cannot get route.");
				}
			});
		};

		// ===================================
		// 2. subdivide route
		var subdivideRoute = () => {

			let b;
			if (this.bCancel) {
				GSVHyperlapse.onCancel.call(this);
				return;
			}

			GSVHyperlapse.onMessage.call(this, "subdividing route..");

			// get points
			const route = routeRes.routes[0];
			const path = route.overview_path;

			// show info
			GSVHyperlapse.onMessage.call(this,
				`path length: ${parseInt(google.maps.geometry.spherical.computeLength(path))}(m), \
step: ${this.step}(m), search radius: ${this.searchRadius} (m)`
			);

			let d = 0; // distance between a and b (m)
			let r = 0; // always must be < step
			let m = 0; // current midpoint
			let a = (b = null);

			// retrive to way points
			for (let i = 0, end = path.length-2, asc = 0 <= end; asc ? i <= end : i >= end; asc ? i++ : i--) {

				a = path[i];
				b = path[i+1];
				d = google.maps.geometry.spherical.computeDistanceBetween(a, b);

				// offset -r
				m = -r + this.step;

				if (d < m) {
					r += d;
				} else {
					// subdivide
					while (m < d) {
						const pt = getFollowedPath(m, a, b);
						rawPts.push( pt );
						m += this.step;
					}

					r = this.step - (m - d);
				}
			}

			// fit bound and add polyline
			this.map.fitBounds( route.bounds );

			GSVHyperlapse.onMessage.call(this, `number of waypoints: ${rawPts.length}`);

			// next
			return retrivePanoData();
		};

		// ===================================
		// 3. retrive pano data and splice duplicated id
		var retrivePanoData = () => {
			GSVHyperlapse.onMessage.call(this, "retriving pano id..");

			let idx = 0;

			var onLoad = (res, status) => {
				if (this.bCancel) {
					GSVHyperlapse.onCancel.call(this);
					return;
				}

				if (status === google.maps.StreetViewStatus.OK) {

					const pano = this.createPanoData(res);

					if (pano.id !== prevId) {
						this.panoList.push( pano );
						const marker = new google.maps.Marker({
							position: pano.latLng,
							map: this.map,
							title: `${idx}`
						});

						prevId = pano.id;
					}
				}

				GSVHyperlapse.onProgress.call(this, idx, rawPts.length);

				if (++idx < rawPts.length) {
					// next
					return this.client.getPanoramaByLocation(rawPts[idx], this.searchRadius, onLoad);
				} else {
					// end
					this.bWaiting = false;
					GSVHyperlapse.onMessage.call(this, `total pano id: ${this.panoList.length}`);
					GSVHyperlapse.onProgress.call(this, idx, rawPts.length);
					return GSVHyperlapse.onAnalyzeComplete.call(this);
				}
			};

			// init GSVPano
			this.bWaiting = true;
			prevId = '';
			return this.client.getPanoramaByLocation(rawPts[idx], this.searchRadius, onLoad);
		};

		// trigger
		return createRequest();
	}

	// --------------------------------------------------------
	createFromPanoId(list) {

		let idx = 0;

		GSVHyperlapse.onMessage.call(this, "start compose..");
		GSVHyperlapse.onMessage.call(this, `eadingMode:${this.headingMode}`);

		var onLoad = (res, status)=> {
			if (idx === 0) {
				GSVHyperlapse.onMessage.call(this, "analyzing..");
			}

			if (status === google.maps.StreetViewStatus.OK) {
				if (this.bCancel) {
					GSVHyperlapse.onCancel.call(this);
					return;
				}

				const pano = this.createPanoData( res );
				this.panoList.push( pano );

				if (idx === 0) {
					this.map.setCenter( pano.latLng );
					this.map.setZoom( 13 );
				}

				const marker = new google.maps.Marker({
					position: pano.latLng,
					map: this.map,
					title: `${idx}`
				});

				GSVHyperlapse.onProgress.call(this, idx, list.length);

				if (++idx < list.length) {
					// next
					return this.client.getPanoramaById(list[idx], onLoad);
				} else {
					// end
					this.bWaiting = false;
					GSVHyperlapse.onMessage.call(this, `total pano id: ${this.panoList.length}`);
					GSVHyperlapse.onProgress.call(this, idx, list.length);
					return GSVHyperlapse.onAnalyzeComplete.call(this);
				}

			} else {
				return alert(`error on createFromPanoId() : ${status}`);
			}
		};

		// trigger

		this.bWaiting = true;
		return this.client.getPanoramaById(list[idx], onLoad);
	}

	// --------------------------------------------------------
	compose(callback){

		if (this.panoList.length === 0) {
			GSVHyperlapse.onMessage.call(this, "there is no pano id.");
			return;
		}

		GSVHyperlapse.onMessage.call(this, `composing panorama.. size:${this.gsvp.width}x${this.gsvp.height}`);

		if ((this.headingMode === GSVHyperlapseHeading.BACKWARD) || (this.headingMode === GSVHyperlapseHeading.BEGIN)) {
			if (this.panoList.length < 2) {
				alert("pano id's length must be 2 at least");
				return;
			}
		}

		const loadPanorama = () => {
			// calc rotation
			if ((this.panoList[idx].heading == null)) {
				let h = 0;
				if (this.headingMode === GSVHyperlapseHeading.BACKWARD) {
					const i = idx === 0 ? 1 : idx;
					h = google.maps.geometry.spherical.computeHeading(
						this.panoList[i].latLng, this.panoList[i-1].latLng );

				} else if (this.headingMode === GSVHyperlapseHeading.LOOKAT) {
					h = google.maps.geometry.spherical.computeHeading(
						this.panoList[idx].latLng, this.lookat);

				} else if (this.headingMode === GSVHyperlapseHeading.BEGIN) {
					h = google.maps.geometry.spherical.computeHeading(
						this.panoList[1].latLng, this.panoList[0].latLng);
				}

				this.panoList[idx].heading = h;

				return this.gsvp.composePanorama( this.panoList[idx].id, this.panoList[idx].heading);
			}
		};

		const onCompose = () => {

			if (this.bCancel) {
				GSVHyperlapse.onCancel.call(this);
				return;
			}

			// event
			GSVHyperlapse.onProgress.call(this, idx, this.panoList.length);
			GSVHyperlapse.onPanoramaLoad.call(this, idx, this.gsvp.canvas, this.panoList[idx]);

			// next
			if (++idx < this.panoList.length) {
				return loadPanorama();
			} else {
				this.bWaiting = false;
				console.log("complete");
				GSVHyperlapse.onProgress.call(this, idx, this.panoList.length);
				GSVHyperlapse.onMessage.call(this, `complete - total: ${this.panoList.length}, duration: ${this.panoList.length / 24}`);
				GSVHyperlapse.onComposeComplete.call(this);
				if (callback != null) {
					return callback();
				}
			}
		};

		// trigger
		this.gsvp.onPanoramaLoad = onCompose;
		this.gsvp.onError = msg => alert(`error onCompose() : ${msg}`);
		this.gsvp.onNoPanoramaData = status => alert(`error onNoPanoramaData() : ${status}`);

		var idx = 0;
		this.bWaiting = true;

		return loadPanorama();
	}
}
GSVHyperlapse.initClass();


text:
function [pdem, facets,nodes] = obtain_geometry( L_body)
warning 'off'

shp = alphaShape(L_body(:,1),L_body(:,2),L_body(:,3),16);
%plot(shp)
[facets,nodes] = boundaryFacets(shp);
[tri,V] = alphaTriangulation(shp);
%tri = triangulateFaces(shp.tri);
%trimesh(tri,V(:,1),V(:,2),V(:,3));

[N]=numConnect(facets,nodes);
logicThree=N==3;
%remove3connected points
[Ft,Vt,~,L]=triSurfRemoveThreeConnect(facets,nodes,[]);
C=double(L);
%surface smoothening
cPar.n=25;      %check the best value
cPar.Method='HC';
[Vt]=patchSmooth(Ft,Vt,[],cPar);

%get the model

model = createpde();

geometryFromMesh(model,Vt',Ft');
msh = generateMesh(model,'GeometricOrder','linear','Hmax',1.5,'Hmin',1.3);
nodes = msh.Nodes;
elems = msh.Elements;
pdem = createpde;
geometryFromMesh(pdem,nodes,elems);

%figure
%generateMesh(model,'GeometricOrder','linear','Hmax',7,'Hmin',1);
%pdegplot(model,'FaceAlpha',1), hold on;

end


text:
package org.powlab.jeye.tests.shortcirc;

//TODO here: убрал 'final' boolean у аргументов a и b
public class ShortCircuitAssignTest1a {
    public boolean test1(boolean a, boolean b, boolean c) {
        System.out.println(b && a == (c = b) && b);
        return c;
    }
}


text:
@interface MusicItem : NSObject

//歌曲地址
@property (nonatomic,strong) NSString * mp3Url;
//歌曲ID
@property (nonatomic,strong) NSString * ID;
//歌曲名字
@property (nonatomic,strong) NSString * name;
//歌曲图片地址
@property (nonatomic,strong) NSString * picUrl;
//模糊图地址
@property (nonatomic,strong) NSString * blurPicUrl;
//专辑名字
@property (nonatomic,strong) NSString * album;
//歌手
@property (nonatomic,strong) NSString * singer;
//持续时间
@property (nonatomic,assign) NSInteger  duration;
//歌手名字
@property (nonatomic,strong) NSString * artists_name;

@end


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),

            new Sonata\BlockBundle\SonataBlockBundle(),
            new Sonata\jQueryBundle\SonatajQueryBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new Sonata\CoreBundle\SonataCoreBundle(),
            new Sonata\AdminBundle\SonataAdminBundle(),
            new Sonata\DoctrineMongoDBAdminBundle\SonataDoctrineMongoDBAdminBundle(),

            new Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle(),
            new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
            new IamPersistent\MongoDBAclBundle\IamPersistentMongoDBAclBundle(),
            new FOS\FacebookBundle\FOSFacebookBundle(),
            new A2lix\TranslationFormBundle\A2lixTranslationFormBundle(),
            new JMS\SerializerBundle\JMSSerializerBundle(),
            new FOS\RestBundle\FOSRestBundle(),

            new Skrepka\CompanyBundle\CompanyBundle(),
            new Skrepka\GestBookBundle\GuestBookBundle(),
            new Skrepka\UserBundle\UserBundle(),
            new FOS\UserBundle\FOSUserBundle(),
            new Skrepka\ActorBundle\ActorBundle(),
            new Skrepka\FilmBundle\FilmBundle(),
            new Skrepka\CategoryBundle\CategoryBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
            $bundles[] = new IsmaAmbrosi\Bundle\GeneratorBundle\IsmaAmbrosiGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
#include <aws/ssm/model/UpdateAssociationStatusResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::SSM::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

UpdateAssociationStatusResult::UpdateAssociationStatusResult()
{
}

UpdateAssociationStatusResult::UpdateAssociationStatusResult(const AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

UpdateAssociationStatusResult& UpdateAssociationStatusResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
  const JsonValue& jsonValue = result.GetPayload();
  if(jsonValue.ValueExists("AssociationDescription"))
  {
    m_associationDescription = jsonValue.GetObject("AssociationDescription");

  }

  return *this;
}


text:
// HeaterMeter Copyright 2011 Bryan Mayland <bmayland@capnbry.net>
#ifndef __STRINGS_H__
#define __STRINGS_H__

#include "serialxor.h"
#include <avr/pgmspace.h>

//const unsigned char LCD_ARROWUP[] PROGMEM = { 0x4,0xe,0x1f,0x00,0x00,0x4,0xe,0x1f };
//const unsigned char LCD_ARROWDN[] PROGMEM = { 0x1f,0xe,0x4,0x00,0x00,0x1f,0xe,0x4 };

#define CSV_DELIMITER ","

#ifndef HM_BOARD_REV
#define HM_BOARD_REV 'B'
#endif

#define DEGREE "\xdf" // \xdf is the degree symbol on the Hitachi HD44780
#define HM_VERSION "20141003"

const char LCD_LINE1_UNPLUGGED[] PROGMEM = "- No Pit Probe -";

inline void Serial_char(char c) { SerialX.write(c); }
inline void Serial_nl(void) { SerialX.nl(); }
inline void Serial_csv(void) { Serial_char(CSV_DELIMITER[0]); }
inline void print_P(const char PROGMEM *s) {  while (unsigned char c = pgm_read_byte(s++)) Serial_char(c); }

#endif /* __STRINGS_H__ */


text:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Process_1
{
  public static void main(String[] args)
  {
    try
      {
	Runtime r = Runtime.getRuntime();
	String s = "Hello World";
	String[] a = { "echo", s };
	Process p = r.exec(a);
	InputStream is = p.getInputStream();
	InputStreamReader isr = new InputStreamReader(is);
	BufferedReader br = new BufferedReader(isr);
	String result = br.readLine();
	if (! s.equals(result))
	  {
	    System.out.println("bad 1");
	    return;
	  }
	result = br.readLine();
	if (result != null)
	  {
	    System.out.println("bad 2");
	    return;
	  }
	int c = p.waitFor();
	System.out.println(c == 0 ? "ok" : "bad 3");
      }
    catch (Exception ex)
      {
	System.out.println(ex.toString());
      }
  }
}


text:
#include "gui/events/appkit.h++"

namespace skui::gui::events
{
  appkit::appkit(gui::window& window)
    : base{window}
  {}

  appkit::~appkit() = default;

  void appkit::exec()
  {}
}


text:
//
//  UIImage+KYSAddition.h
//  KYSKitDemo
//
//  Created by Liu Zhao on 16/2/24.
//  Copyright © 2016年 Kang YongShuai. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIImage (KYSAddition)

#pragma mark - create
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size;

//填充mask利用mask不透明部分创建纯色图片
//如果maskImage为空就相当于添加纯色蒙板
+ (UIImage*)imageWithColor:(UIColor*)color
             tintBlendMode:(CGBlendMode)tintBlendMode
                 maskImage:(UIImage*)maskImage;

+ (BOOL)isAnimatedGIFData:(NSData *)data;

+ (BOOL)isAnimatedGIFFile:(NSString *)path;;

+ (UIImage *)imageWithSmallGIFData:(NSData *)data scale:(CGFloat)scale;

#pragma mark - resize
//生成其他尺寸图片
- (UIImage *)imageByResizeToSize:(CGSize)size;

//裁剪某一区域并生成图片
- (UIImage *)imageByClipToRect:(CGRect)clipRect;

- (UIImage *)imageByCropToRect:(CGRect)rect;

//压缩图片的质量
- (UIImage *)imageByCompressionQuality:(CGFloat)compressionQuality;

#pragma mark - 水印
- (UIImage *) imageWithWaterMark:(UIImage*)mark
                      pointArray:(NSArray *)pointArray;

//高亮与非高亮图片size要相同
- (UIImage *) imageWithWaterMark:(UIImage*)mark
              highlightWaterMark:(UIImage *)highMark
                      pointArray:(NSArray *)pointArray
                  highlightArray:(NSArray *)highlightArray;

#pragma mark - rotate flip
- (UIImage *)imageByRotate:(CGFloat)radians fitSize:(BOOL)fitSize;

- (UIImage *)imageByFlipHorizontal:(BOOL)horizontal vertical:(BOOL)vertical;

- (UIImage *)imageByRotateLeft90;

- (UIImage *)imageByRotateRight90;

- (UIImage *)imageByRotate180;

- (UIImage *)imageByFlipVertical;

- (UIImage *)imageByFlipHorizontal;

#pragma mark - blur saturation mark
//毛玻璃与饱和度
/**
 @param blurRadius 0无毛玻璃效果.
 @param saturation 以1为基准
 */
- (UIImage *)imageByBlurRadius:(CGFloat)blurRadius saturation:(CGFloat)saturation;

- (UIImage *)imageByGray;//灰色

- (UIImage *)imageBySoft;

- (UIImage *)imageByLight;

- (UIImage *)imageByExtraLight;

- (UIImage *)imageByDark;

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>

									Apache CloudStack v4.6.0 Root Admin API Reference

updateSnapshotPolicy

Updates the snapshot policy.

Request parameters

Parameter Name	Description	Required

customid	an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only	false

fordisplay	an optional field, whether to the display the snapshot policy to the end user or not.	false

id	the ID of the snapshot policy	false

Response Tags

Response Name	Description

id	the ID of the snapshot policy

fordisplay	is this policy for display to the regular user

intervaltype	the interval type of the snapshot policy

maxsnaps	maximum number of snapshots retained

schedule	time the snapshot is scheduled to be taken.

timezone	the time zone of the snapshot policy

volumeid	the ID of the disk volume

Copyright © 2015 The Apache Software Foundation, Licensed under the
                   Apache License, Version 2.0.

                Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo  and the Apache feather logo are trademarks of The Apache Software Foundation.


text:
public partial class TestEntity {

    public NameAgeComponent nameAge { get { return (NameAgeComponent)GetComponent(TestComponentsLookup.NameAge); } }
    public bool hasNameAge { get { return HasComponent(TestComponentsLookup.NameAge); } }

    public void AddNameAge(string newName, int newAge) {
        var index = TestComponentsLookup.NameAge;
        var component = (NameAgeComponent)CreateComponent(index, typeof(NameAgeComponent));
        component.name = newName;
        component.age = newAge;
        AddComponent(index, component);
    }

    public void ReplaceNameAge(string newName, int newAge) {
        var index = TestComponentsLookup.NameAge;
        var component = (NameAgeComponent)CreateComponent(index, typeof(NameAgeComponent));
        component.name = newName;
        component.age = newAge;
        ReplaceComponent(index, component);
    }

    public void RemoveNameAge() {
        RemoveComponent(TestComponentsLookup.NameAge);
    }
}

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by Entitas.CodeGeneration.Plugins.ComponentEntityApiInterfaceGenerator.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class TestEntity : INameAgeEntity { }

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherApiGenerator.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class TestMatcher {

    static Entitas.IMatcher<TestEntity> _matcherNameAge;

    public static Entitas.IMatcher<TestEntity> NameAge {
        get {
            if (_matcherNameAge == null) {
                var matcher = (Entitas.Matcher<TestEntity>)Entitas.Matcher<TestEntity>.AllOf(TestComponentsLookup.NameAge);
                matcher.componentNames = TestComponentsLookup.componentNames;
                _matcherNameAge = matcher;
            }

            return _matcherNameAge;
        }
    }
}


text:
package com.artemis;

import com.artemis.component.ComponentX;
import com.artemis.component.ComponentY;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AspectSubscriptionManagerTest {

	private World world;

	@Before
	public void setup() {
		world = new World();
		world.initialize();
	}

	private void entity(Class<? extends Component>... components) {
		EntityEdit ee = world.createEntity().edit();
		for (Class<? extends Component> c : components) {
			ee.create(c);
		}
	}

	@Test
	public void creating_subscriptions_at_any_time() {
		AspectSubscriptionManager asm = world.getManager(AspectSubscriptionManager.class);
		EntitySubscription subscription1 = asm.get(Aspect.all(ComponentY.class));

		entity(ComponentX.class, ComponentY.class);

		world.process();

		EntitySubscription subscription2 = asm.get(Aspect.all(ComponentX.class));

		assertEquals(1, subscription1.getEntities().size());
		assertEquals(1, subscription2.getEntities().size());
	}
}


text:
/**********************************************************************
* $Id$		lpc17xx_spi.h				2010-05-21
*//**
* @file		lpc17xx_spi.h
* @brief	Contains all macro definitions and function prototypes
* 			support for SPI firmware library on LPC17xx
* @version	2.0
* @date		21. May. 2010
* @author	NXP MCU SW Application Team
*
* Copyright(C) 2010, NXP Semiconductor
* All rights reserved.
*
***********************************************************************
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* products. This software is supplied "AS IS" without any warranties.
* NXP Semiconductors assumes no responsibility or liability for the
* use of the software, conveys no license or title under any patent,
* copyright, or mask work right to the product. NXP Semiconductors
* reserves the right to make changes in the software without
* notification. NXP Semiconductors also make no representation or
* warranty that such application will be suitable for the specified
* use without further testing or modification.
**********************************************************************/

/* Peripheral group ----------------------------------------------------------- */
/** @defgroup SPI SPI
 * @ingroup LPC1700CMSIS_FwLib_Drivers
 * @{
 */

#ifndef LPC17XX_SPI_H_
#define LPC17XX_SPI_H_

/* Includes ------------------------------------------------------------------- */
#include "LPC17xx.h"
#include "lpc_types.h"

#ifdef __cplusplus
extern "C"
{
#endif

/* Public Macros -------------------------------------------------------------- */
/** @defgroup SPI_Public_Macros SPI Public Macros
 * @{
 */

/*********************************************************************//**
 * SPI configuration parameter defines
 **********************************************************************/
/** Clock phase control bit */
#define SPI_CPHA_FIRST			((uint32_t)(0))
#define SPI_CPHA_SECOND			((uint32_t)(1<<3))

/** Clock polarity control bit */
#define SPI_CPOL_HI				((uint32_t)(0))
#define SPI_CPOL_LO				((uint32_t)(1<<4))

/** SPI master mode enable */
#define SPI_SLAVE_MODE			((uint32_t)(0))
#define SPI_MASTER_MODE			((uint32_t)(1<<5))

/** LSB enable bit */
#define SPI_DATA_MSB_FIRST		((uint32_t)(0))
#define SPI_DATA_LSB_FIRST		((uint32_t)(1<<6))

/** SPI data bit number defines */
#define SPI_DATABIT_16		SPI_SPCR_BITS(0)		/*!< Databit number = 16 */
#define SPI_DATABIT_8		SPI_SPCR_BITS(0x08) 	/*!< Databit number = 8 */
#define SPI_DATABIT_9		SPI_SPCR_BITS(0x09) 	/*!< Databit number = 9 */
#define SPI_DATABIT_10		SPI_SPCR_BITS(0x0A) 	/*!< Databit number = 10 */
#define SPI_DATABIT_11		SPI_SPCR_BITS(0x0B) 	/*!< Databit number = 11 */
#define SPI_DATABIT_12		SPI_SPCR_BITS(0x0C) 	/*!< Databit number = 12 */
#define SPI_DATABIT_13		SPI_SPCR_BITS(0x0D) 	/*!< Databit number = 13 */
#define SPI_DATABIT_14		SPI_SPCR_BITS(0x0E) 	/*!< Databit number = 14 */
#define SPI_DATABIT_15		SPI_SPCR_BITS(0x0F) 	/*!< Databit number = 15 */

/*********************************************************************//**
 * SPI Status Flag defines
 **********************************************************************/
/** Slave abort */
#define SPI_STAT_ABRT		SPI_SPSR_ABRT
/** Mode fault */
#define SPI_STAT_MODF		SPI_SPSR_MODF
/** Read overrun */
#define SPI_STAT_ROVR		SPI_SPSR_ROVR
/** Write collision */
#define SPI_STAT_WCOL		SPI_SPSR_WCOL
/** SPI transfer complete flag */
#define SPI_STAT_SPIF		SPI_SPSR_SPIF

/* SPI Status Implementation definitions */
#define SPI_STAT_DONE		(1UL<<8)		/**< Done */
#define SPI_STAT_ERROR		(1UL<<9)		/**< Error */

/**
 * @}
 */

/* Private Macros ------------------------------------------------------------- */
/** @defgroup SPI_Private_Macros SPI Private Macros
 * @{
 */

/* --------------------- BIT DEFINITIONS -------------------------------------- */
/*********************************************************************//**
 * Macro defines for SPI Control Register
 **********************************************************************/
/** Bit enable, the SPI controller sends and receives the number
 * of bits selected by bits 11:8 */
#define SPI_SPCR_BIT_EN			((uint32_t)(1<<2))
/** Clock phase control bit */
#define SPI_SPCR_CPHA_SECOND	((uint32_t)(1<<3))
/** Clock polarity control bit */
#define SPI_SPCR_CPOL_LOW 		((uint32_t)(1<<4))
/** SPI master mode enable */
#define SPI_SPCR_MSTR		 	((uint32_t)(1<<5))
/** LSB enable bit */
#define SPI_SPCR_LSBF			((uint32_t)(1<<6))
/** SPI interrupt enable bit */
#define SPI_SPCR_SPIE			((uint32_t)(1<<7))
/**  When bit 2 of this register is 1, this field controls the
number of bits per transfer */
#define SPI_SPCR_BITS(n)		((n==0) ? ((uint32_t)0) : ((uint32_t)((n&0x0F)<<8)))
/** SPI Control bit mask */
#define SPI_SPCR_BITMASK		((uint32_t)(0xFFC))

/*********************************************************************//**
 * Macro defines for  SPI Status Register
 **********************************************************************/
/** Slave abort */
#define SPI_SPSR_ABRT		((uint32_t)(1<<3))
/** Mode fault */
#define SPI_SPSR_MODF		((uint32_t)(1<<4))
/** Read overrun */
#define SPI_SPSR_ROVR		((uint32_t)(1<<5))
/** Write collision */
#define SPI_SPSR_WCOL		((uint32_t)(1<<6))
/** SPI transfer complete flag */
#define SPI_SPSR_SPIF 		((uint32_t)(1<<7))
/** SPI Status bit mask */
#define SPI_SPSR_BITMASK	((uint32_t)(0xF8))

/*********************************************************************//**
 * Macro defines for SPI Data Register
 **********************************************************************/
/** SPI Data low bit-mask */
#define SPI_SPDR_LO_MASK	((uint32_t)(0xFF))
/** SPI Data high bit-mask */
#define SPI_SPDR_HI_MASK	((uint32_t)(0xFF00))
/** SPI Data bit-mask */
#define SPI_SPDR_BITMASK	((uint32_t)(0xFFFF))

/*********************************************************************//**
 * Macro defines for SPI Clock Counter Register
 **********************************************************************/
/** SPI clock counter setting */
#define SPI_SPCCR_COUNTER(n) 	((uint32_t)(n&0xFF))
/** SPI clock counter bit-mask */
#define SPI_SPCCR_BITMASK		((uint32_t)(0xFF))

/***********************************************************************
 * Macro defines for SPI Test Control Register
 **********************************************************************/
/** SPI Test bit */
#define SPI_SPTCR_TEST_MASK	((uint32_t)(0xFE))
/** SPI Test register bit mask */
#define SPI_SPTCR_BITMASK	((uint32_t)(0xFE))

/*********************************************************************//**
 * Macro defines for SPI Test Status Register
 **********************************************************************/
/** Slave abort */
#define SPI_SPTSR_ABRT		((uint32_t)(1<<3))
/** Mode fault */
#define SPI_SPTSR_MODF		((uint32_t)(1<<4))
/** Read overrun */
#define SPI_SPTSR_ROVR		((uint32_t)(1<<5))
/** Write collision */
#define SPI_SPTSR_WCOL		((uint32_t)(1<<6))
/** SPI transfer complete flag */
#define SPI_SPTSR_SPIF 		((uint32_t)(1<<7))
/** SPI Status bit mask */
#define SPI_SPTSR_MASKBIT	((uint32_t)(0xF8))

/*********************************************************************//**
 * Macro defines for SPI Interrupt Register
 **********************************************************************/
/** SPI interrupt flag */
#define SPI_SPINT_INTFLAG 	((uint32_t)(1<<0))
/** SPI interrupt register bit mask */
#define SPI_SPINT_BITMASK 	((uint32_t)(0x01))

/* ---------------- CHECK PARAMETER DEFINITIONS ---------------------------- */
/** Macro to determine if it is valid SPI port number */
#define PARAM_SPIx(n)	(((uint32_t *)n)==((uint32_t *)LPC_SPI))

/** Macro check Clock phase control mode */
#define PARAM_SPI_CPHA(n) 	((n==SPI_CPHA_FIRST) || (n==SPI_CPHA_SECOND))

/** Macro check Clock polarity control mode */
#define PARAM_SPI_CPOL(n)	((n==SPI_CPOL_HI) || (n==SPI_CPOL_LO))

/** Macro check master/slave mode */
#define PARAM_SPI_MODE(n)	((n==SPI_SLAVE_MODE) || (n==SPI_MASTER_MODE))

/** Macro check LSB/MSB mode */
#define PARAM_SPI_DATA_ORDER(n) ((n==SPI_DATA_MSB_FIRST) || (n==SPI_DATA_LSB_FIRST))

/** Macro check databit value */
#define PARAM_SPI_DATABIT(n)	((n==SPI_DATABIT_16) || (n==SPI_DATABIT_8) \
|| (n==SPI_DATABIT_9) || (n==SPI_DATABIT_10) \
|| (n==SPI_DATABIT_11) || (n==SPI_DATABIT_12) \
|| (n==SPI_DATABIT_13) || (n==SPI_DATABIT_14) \
|| (n==SPI_DATABIT_15))

/** Macro check status flag */
#define PARAM_SPI_STAT(n)	((n==SPI_STAT_ABRT) || (n==SPI_STAT_MODF) \
|| (n==SPI_STAT_ROVR) || (n==SPI_STAT_WCOL) \
|| (n==SPI_STAT_SPIF))

/**
 * @}
 */

/* Public Types --------------------------------------------------------------- */
/** @defgroup SPI_Public_Types SPI Public Types
 * @{
 */

/** @brief SPI configuration structure */
typedef struct {
	uint32_t Databit; 		/** Databit number, should be SPI_DATABIT_x,
							where x is in range from 8 - 16 */
	uint32_t CPHA;			/** Clock phase, should be:
							- SPI_CPHA_FIRST: first clock edge
							- SPI_CPHA_SECOND: second clock edge */
	uint32_t CPOL;			/** Clock polarity, should be:
							- SPI_CPOL_HI: high level
							- SPI_CPOL_LO: low level */
	uint32_t Mode;			/** SPI mode, should be:
							- SPI_MASTER_MODE: Master mode
							- SPI_SLAVE_MODE: Slave mode */
	uint32_t DataOrder;		/** Data order, should be:
							- SPI_DATA_MSB_FIRST: MSB first
							- SPI_DATA_LSB_FIRST: LSB first */
	uint32_t ClockRate;		/** Clock rate,in Hz, should not exceed
							(SPI peripheral clock)/8 */
} SPI_CFG_Type;

/**
 * @brief SPI Transfer Type definitions
 */
typedef enum {
	SPI_TRANSFER_POLLING = 0,	/**< Polling transfer */
	SPI_TRANSFER_INTERRUPT		/**< Interrupt transfer */
} SPI_TRANSFER_Type;

/**
 * @brief SPI Data configuration structure definitions
 */
typedef struct {
	void *tx_data;				/**< Pointer to transmit data */
	void *rx_data;				/**< Pointer to transmit data */
	uint32_t length;			/**< Length of transfer data */
	uint32_t counter;			/**< Data counter index */
	uint32_t status;			/**< Current status of SPI activity */
} SPI_DATA_SETUP_Type;

/**
 * @}
 */

/* Public Functions ----------------------------------------------------------- */
/** @defgroup SPI_Public_Functions SPI Public Functions
 * @{
 */

/* SPI Init/DeInit functions ---------*/
void SPI_Init(LPC_SPI_TypeDef *SPIx, SPI_CFG_Type *SPI_ConfigStruct);
void SPI_DeInit(LPC_SPI_TypeDef *SPIx);
void SPI_SetClock (LPC_SPI_TypeDef *SPIx, uint32_t target_clock);
void SPI_ConfigStructInit(SPI_CFG_Type *SPI_InitStruct);

/* SPI transfer functions ------------*/
void SPI_SendData(LPC_SPI_TypeDef *SPIx, uint16_t Data);
uint16_t SPI_ReceiveData(LPC_SPI_TypeDef *SPIx);
int32_t SPI_ReadWrite (LPC_SPI_TypeDef *SPIx, SPI_DATA_SETUP_Type *dataCfg, SPI_TRANSFER_Type xfType);

/* SPI Interrupt functions ---------*/
void SPI_IntCmd(LPC_SPI_TypeDef *SPIx, FunctionalState NewState);
IntStatus SPI_GetIntStatus (LPC_SPI_TypeDef *SPIx);
void SPI_ClearIntPending(LPC_SPI_TypeDef *SPIx);

/* SPI get information functions-----*/
uint8_t SPI_GetDataSize (LPC_SPI_TypeDef *SPIx);
uint32_t SPI_GetStatus(LPC_SPI_TypeDef *SPIx);
FlagStatus SPI_CheckStatus (uint32_t inputSPIStatus,  uint8_t SPIStatus);

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* LPC17XX_SPI_H_ */

/**
 * @}
 */

/* --------------------------------- End Of File ------------------------------ */


text:
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/interrupt.h>

#include <asm/etraxgpio.h>
#include <arch/svinto.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <arch/io_interface_mux.h>

#define GPIO_MAJOR 120  /* experimental MAJOR number */

#define D(x)

#if 0
static int dp_cnt;
#define DP(x) do { dp_cnt++; if (dp_cnt % 1000 == 0) x; }while(0)
#else
#define DP(x)
#endif

static char gpio_name[] = "etrax gpio";

#if 0
static wait_queue_head_t *gpio_wq;
#endif

static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
static ssize_t gpio_write(struct file *file, const char __user *buf,
	size_t count, loff_t *off);
static int gpio_open(struct inode *inode, struct file *filp);
static int gpio_release(struct inode *inode, struct file *filp);
static unsigned int gpio_poll(struct file *filp, struct poll_table_struct *wait);

/* private data per open() of this driver */

struct gpio_private {
	struct gpio_private *next;
	/* These fields are for PA and PB only */
	volatile unsigned char *port, *shadow;
	volatile unsigned char *dir, *dir_shadow;
	unsigned char changeable_dir;
	unsigned char changeable_bits;
	unsigned char clk_mask;
	unsigned char data_mask;
	unsigned char write_msb;
	unsigned char pad1, pad2, pad3;
	/* These fields are generic */
	unsigned long highalarm, lowalarm;
	wait_queue_head_t alarm_wq;
	int minor;
};

/* linked list of alarms to check for */

static struct gpio_private *alarmlist;

static int gpio_some_alarms; /* Set if someone uses alarm */
static unsigned long gpio_pa_irq_enabled_mask;

static DEFINE_SPINLOCK(gpio_lock); /* Protect directions etc */

/* Port A and B use 8 bit access, but Port G is 32 bit */
#define NUM_PORTS (GPIO_MINOR_B+1)

static volatile unsigned char *ports[NUM_PORTS] = {
	R_PORT_PA_DATA,
	R_PORT_PB_DATA,
};
static volatile unsigned char *shads[NUM_PORTS] = {
	&port_pa_data_shadow,
	&port_pb_data_shadow
};

/* What direction bits that are user changeable 1=changeable*/
#ifndef CONFIG_ETRAX_PA_CHANGEABLE_DIR
#define CONFIG_ETRAX_PA_CHANGEABLE_DIR 0x00
#endif
#ifndef CONFIG_ETRAX_PB_CHANGEABLE_DIR
#define CONFIG_ETRAX_PB_CHANGEABLE_DIR 0x00
#endif

#ifndef CONFIG_ETRAX_PA_CHANGEABLE_BITS
#define CONFIG_ETRAX_PA_CHANGEABLE_BITS 0xFF
#endif
#ifndef CONFIG_ETRAX_PB_CHANGEABLE_BITS
#define CONFIG_ETRAX_PB_CHANGEABLE_BITS 0xFF
#endif

static unsigned char changeable_dir[NUM_PORTS] = {
	CONFIG_ETRAX_PA_CHANGEABLE_DIR,
	CONFIG_ETRAX_PB_CHANGEABLE_DIR
};
static unsigned char changeable_bits[NUM_PORTS] = {
	CONFIG_ETRAX_PA_CHANGEABLE_BITS,
	CONFIG_ETRAX_PB_CHANGEABLE_BITS
};

static volatile unsigned char *dir[NUM_PORTS] = {
	R_PORT_PA_DIR,
	R_PORT_PB_DIR
};

static volatile unsigned char *dir_shadow[NUM_PORTS] = {
	&port_pa_dir_shadow,
	&port_pb_dir_shadow
};

/* All bits in port g that can change dir. */
static const unsigned long int changeable_dir_g_mask = 0x01FFFF01;

/* Port G is 32 bit, handle it special, some bits are both inputs
   and outputs at the same time, only some of the bits can change direction
   and some of them in groups of 8 bit. */
static unsigned long changeable_dir_g;
static unsigned long dir_g_in_bits;
static unsigned long dir_g_out_bits;
static unsigned long dir_g_shadow; /* 1=output */

#define USE_PORTS(priv) ((priv)->minor <= GPIO_MINOR_B)

static unsigned int gpio_poll(struct file *file, poll_table *wait)
{
	unsigned int mask = 0;
	struct gpio_private *priv = file->private_data;
	unsigned long data;
	unsigned long flags;

	spin_lock_irqsave(&gpio_lock, flags);

	poll_wait(file, &priv->alarm_wq, wait);
	if (priv->minor == GPIO_MINOR_A) {
		unsigned long tmp;
		data = *R_PORT_PA_DATA;
		/* PA has support for high level interrupt -
		 * lets activate for those low and with highalarm set
		 */
		tmp = ~data & priv->highalarm & 0xFF;
		tmp = (tmp << R_IRQ_MASK1_SET__pa0__BITNR);

		gpio_pa_irq_enabled_mask |= tmp;
		*R_IRQ_MASK1_SET = tmp;
	} else if (priv->minor == GPIO_MINOR_B)
		data = *R_PORT_PB_DATA;
	else if (priv->minor == GPIO_MINOR_G)
		data = *R_PORT_G_DATA;
	else {
		mask = 0;
		goto out;
	}

	if ((data & priv->highalarm) ||
	    (~data & priv->lowalarm)) {
		mask = POLLIN|POLLRDNORM;
	}

out:
	spin_unlock_irqrestore(&gpio_lock, flags);
	DP(printk("gpio_poll ready: mask 0x%08X\n", mask));

	return mask;
}

int etrax_gpio_wake_up_check(void)
{
	struct gpio_private *priv;
	unsigned long data = 0;
        int ret = 0;
	unsigned long flags;

	spin_lock_irqsave(&gpio_lock, flags);
	priv = alarmlist;
	while (priv) {
		if (USE_PORTS(priv))
			data = *priv->port;
		else if (priv->minor == GPIO_MINOR_G)
			data = *R_PORT_G_DATA;

		if ((data & priv->highalarm) ||
		    (~data & priv->lowalarm)) {
			DP(printk("etrax_gpio_wake_up_check %i\n",priv->minor));
			wake_up_interruptible(&priv->alarm_wq);
                        ret = 1;
		}
		priv = priv->next;
	}
	spin_unlock_irqrestore(&gpio_lock, flags);
        return ret;
}

static irqreturn_t
gpio_poll_timer_interrupt(int irq, void *dev_id)
{
	if (gpio_some_alarms) {
		etrax_gpio_wake_up_check();
                return IRQ_HANDLED;
	}
        return IRQ_NONE;
}

static irqreturn_t
gpio_interrupt(int irq, void *dev_id)
{
	unsigned long tmp;
	unsigned long flags;

	spin_lock_irqsave(&gpio_lock, flags);

	/* Find what PA interrupts are active */
	tmp = (*R_IRQ_READ1);

	/* Find those that we have enabled */
	tmp &= gpio_pa_irq_enabled_mask;

	/* Clear them.. */
	*R_IRQ_MASK1_CLR = tmp;
	gpio_pa_irq_enabled_mask &= ~tmp;

	spin_unlock_irqrestore(&gpio_lock, flags);

	if (gpio_some_alarms)
		return IRQ_RETVAL(etrax_gpio_wake_up_check());

        return IRQ_NONE;
}

static void gpio_write_bit(struct gpio_private *priv,
	unsigned char data, int bit)
{
	*priv->port = *priv->shadow &= ~(priv->clk_mask);
	if (data & 1 << bit)
		*priv->port = *priv->shadow |= priv->data_mask;
	else
		*priv->port = *priv->shadow &= ~(priv->data_mask);

	/* For FPGA: min 5.0ns (DCC) before CCLK high */
	*priv->port = *priv->shadow |= priv->clk_mask;
}

static void gpio_write_byte(struct gpio_private *priv, unsigned char data)
{
	int i;

	if (priv->write_msb)
		for (i = 7; i >= 0; i--)
			gpio_write_bit(priv, data, i);
	else
		for (i = 0; i <= 7; i++)
			gpio_write_bit(priv, data, i);
}

static ssize_t gpio_write(struct file *file, const char __user *buf,
	size_t count, loff_t *off)
{
	struct gpio_private *priv = file->private_data;
	unsigned long flags;
	ssize_t retval = count;

	if (priv->minor != GPIO_MINOR_A && priv->minor != GPIO_MINOR_B)
		return -EFAULT;

	if (!access_ok(VERIFY_READ, buf, count))
		return -EFAULT;

	spin_lock_irqsave(&gpio_lock, flags);

	/* It must have been configured using the IO_CFG_WRITE_MODE */
	/* Perhaps a better error code? */
	if (priv->clk_mask == 0 || priv->data_mask == 0) {
		retval = -EPERM;
		goto out;
	}

	D(printk(KERN_DEBUG "gpio_write: %02X to data 0x%02X "
		"clk 0x%02X msb: %i\n",
		count, priv->data_mask, priv->clk_mask, priv->write_msb));

	while (count--)
		gpio_write_byte(priv, *buf++);

out:
	spin_unlock_irqrestore(&gpio_lock, flags);
	return retval;
}

static int
gpio_open(struct inode *inode, struct file *filp)
{
	struct gpio_private *priv;
	int p = iminor(inode);
	unsigned long flags;

	if (p > GPIO_MINOR_LAST)
		return -EINVAL;

	priv = kzalloc(sizeof(struct gpio_private), GFP_KERNEL);

	if (!priv)
		return -ENOMEM;

	priv->minor = p;

	/* initialize the io/alarm struct */

	if (USE_PORTS(priv)) { /* A and B */
		priv->port = ports[p];
		priv->shadow = shads[p];
		priv->dir = dir[p];
		priv->dir_shadow = dir_shadow[p];
		priv->changeable_dir = changeable_dir[p];
		priv->changeable_bits = changeable_bits[p];
	} else {
		priv->port = NULL;
		priv->shadow = NULL;
		priv->dir = NULL;
		priv->dir_shadow = NULL;
		priv->changeable_dir = 0;
		priv->changeable_bits = 0;
	}

	priv->highalarm = 0;
	priv->lowalarm = 0;
	priv->clk_mask = 0;
	priv->data_mask = 0;
	init_waitqueue_head(&priv->alarm_wq);

	filp->private_data = priv;

	/* link it into our alarmlist */
	spin_lock_irqsave(&gpio_lock, flags);
	priv->next = alarmlist;
	alarmlist = priv;
	spin_unlock_irqrestore(&gpio_lock, flags);

	return 0;
}

static int
gpio_release(struct inode *inode, struct file *filp)
{
	struct gpio_private *p;
	struct gpio_private *todel;
	unsigned long flags;

	spin_lock_irqsave(&gpio_lock, flags);

	p = alarmlist;
	todel = filp->private_data;

	/* unlink from alarmlist and free the private structure */

	if (p == todel) {
		alarmlist = todel->next;
	} else {
		while (p->next != todel)
			p = p->next;
		p->next = todel->next;
	}

	kfree(todel);
	/* Check if there are still any alarms set */
	p = alarmlist;
	while (p) {
		if (p->highalarm | p->lowalarm) {
			gpio_some_alarms = 1;
			goto out;
		}
		p = p->next;
	}
	gpio_some_alarms = 0;
out:
	spin_unlock_irqrestore(&gpio_lock, flags);
	return 0;
}

/* Main device API. ioctl's to read/set/clear bits, as well as to
 * set alarms to wait for using a subsequent select().
 */
unsigned long inline setget_input(struct gpio_private *priv, unsigned long arg)
{
	/* Set direction 0=unchanged 1=input,
	 * return mask with 1=input */
	if (USE_PORTS(priv)) {
		*priv->dir = *priv->dir_shadow &=
		~((unsigned char)arg & priv->changeable_dir);
		return ~(*priv->dir_shadow) & 0xFF; /* Only 8 bits */
	}

	if (priv->minor != GPIO_MINOR_G)
		return 0;

	/* We must fiddle with R_GEN_CONFIG to change dir */
	if (((arg & dir_g_in_bits) != arg) &&
	    (arg & changeable_dir_g)) {
		arg &= changeable_dir_g;
		/* Clear bits in genconfig to set to input */
		if (arg & (1<<0)) {
			genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, g0dir);
			dir_g_in_bits |= (1<<0);
			dir_g_out_bits &= ~(1<<0);
		}
		if ((arg & 0x0000FF00) == 0x0000FF00) {
			genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, g8_15dir);
			dir_g_in_bits |= 0x0000FF00;
			dir_g_out_bits &= ~0x0000FF00;
		}
		if ((arg & 0x00FF0000) == 0x00FF0000) {
			genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, g16_23dir);
			dir_g_in_bits |= 0x00FF0000;
			dir_g_out_bits &= ~0x00FF0000;
		}
		if (arg & (1<<24)) {
			genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, g24dir);
			dir_g_in_bits |= (1<<24);
			dir_g_out_bits &= ~(1<<24);
		}
		D(printk(KERN_DEBUG "gpio: SETINPUT on port G set "
			 "genconfig to 0x%08lX "
			 "in_bits: 0x%08lX "
			 "out_bits: 0x%08lX\n",
			 (unsigned long)genconfig_shadow,
			 dir_g_in_bits, dir_g_out_bits));
		*R_GEN_CONFIG = genconfig_shadow;
		/* Must be a >120 ns delay before writing this again */

	}
	return dir_g_in_bits;
} /* setget_input */

unsigned long inline setget_output(struct gpio_private *priv, unsigned long arg)
{
	if (USE_PORTS(priv)) {
		*priv->dir = *priv->dir_shadow |=
			((unsigned char)arg & priv->changeable_dir);
		return *priv->dir_shadow;
	}
	if (priv->minor != GPIO_MINOR_G)
		return 0;

	/* We must fiddle with R_GEN_CONFIG to change dir */
	if (((arg & dir_g_out_bits) != arg) &&
	    (arg & changeable_dir_g)) {
		/* Set bits in genconfig to set to output */
		if (arg & (1<<0)) {
			genconfig_shadow |= IO_MASK(R_GEN_CONFIG, g0dir);
			dir_g_out_bits |= (1<<0);
			dir_g_in_bits &= ~(1<<0);
		}
		if ((arg & 0x0000FF00) == 0x0000FF00) {
			genconfig_shadow |= IO_MASK(R_GEN_CONFIG, g8_15dir);
			dir_g_out_bits |= 0x0000FF00;
			dir_g_in_bits &= ~0x0000FF00;
		}
		if ((arg & 0x00FF0000) == 0x00FF0000) {
			genconfig_shadow |= IO_MASK(R_GEN_CONFIG, g16_23dir);
			dir_g_out_bits |= 0x00FF0000;
			dir_g_in_bits &= ~0x00FF0000;
		}
		if (arg & (1<<24)) {
			genconfig_shadow |= IO_MASK(R_GEN_CONFIG, g24dir);
			dir_g_out_bits |= (1<<24);
			dir_g_in_bits &= ~(1<<24);
		}
		D(printk(KERN_INFO "gpio: SETOUTPUT on port G set "
			 "genconfig to 0x%08lX "
			 "in_bits: 0x%08lX "
			 "out_bits: 0x%08lX\n",
			 (unsigned long)genconfig_shadow,
			 dir_g_in_bits, dir_g_out_bits));
		*R_GEN_CONFIG = genconfig_shadow;
		/* Must be a >120 ns delay before writing this again */
	}
	return dir_g_out_bits & 0x7FFFFFFF;
} /* setget_output */

static int
gpio_leds_ioctl(unsigned int cmd, unsigned long arg);

static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
	unsigned long flags;
	unsigned long val;
        int ret = 0;

	struct gpio_private *priv = file->private_data;
	if (_IOC_TYPE(cmd) != ETRAXGPIO_IOCTYPE)
		return -EINVAL;

	switch (_IOC_NR(cmd)) {
	case IO_READBITS: /* Use IO_READ_INBITS and IO_READ_OUTBITS instead */
		// read the port
		spin_lock_irqsave(&gpio_lock, flags);
		if (USE_PORTS(priv)) {
			ret =  *priv->port;
		} else if (priv->minor == GPIO_MINOR_G) {
			ret =  (*R_PORT_G_DATA) & 0x7FFFFFFF;
		}
		spin_unlock_irqrestore(&gpio_lock, flags);

		break;
	case IO_SETBITS:
		// set changeable bits with a 1 in arg
		spin_lock_irqsave(&gpio_lock, flags);

		if (USE_PORTS(priv)) {
			*priv->port = *priv->shadow |=
			  ((unsigned char)arg & priv->changeable_bits);
		} else if (priv->minor == GPIO_MINOR_G) {
			*R_PORT_G_DATA = port_g_data_shadow |= (arg & dir_g_out_bits);
		}
		spin_unlock_irqrestore(&gpio_lock, flags);

		break;
	case IO_CLRBITS:
		// clear changeable bits with a 1 in arg
		spin_lock_irqsave(&gpio_lock, flags);
		if (USE_PORTS(priv)) {
			*priv->port = *priv->shadow &=
			 ~((unsigned char)arg & priv->changeable_bits);
		} else if (priv->minor == GPIO_MINOR_G) {
			*R_PORT_G_DATA = port_g_data_shadow &= ~((unsigned long)arg & dir_g_out_bits);
		}
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_HIGHALARM:
		// set alarm when bits with 1 in arg go high
		spin_lock_irqsave(&gpio_lock, flags);
		priv->highalarm |= arg;
		gpio_some_alarms = 1;
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_LOWALARM:
		// set alarm when bits with 1 in arg go low
		spin_lock_irqsave(&gpio_lock, flags);
		priv->lowalarm |= arg;
		gpio_some_alarms = 1;
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_CLRALARM:
		/* clear alarm for bits with 1 in arg */
		spin_lock_irqsave(&gpio_lock, flags);
		priv->highalarm &= ~arg;
		priv->lowalarm  &= ~arg;
		{
			/* Must update gpio_some_alarms */
			struct gpio_private *p = alarmlist;
			int some_alarms;
			p = alarmlist;
			some_alarms = 0;
			while (p) {
				if (p->highalarm | p->lowalarm) {
					some_alarms = 1;
					break;
				}
				p = p->next;
			}
			gpio_some_alarms = some_alarms;
		}
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_READDIR: /* Use IO_SETGET_INPUT/OUTPUT instead! */
		/* Read direction 0=input 1=output */
		spin_lock_irqsave(&gpio_lock, flags);
		if (USE_PORTS(priv)) {
			ret = *priv->dir_shadow;
		} else if (priv->minor == GPIO_MINOR_G) {
			/* Note: Some bits are both in and out,
			 * Those that are dual is set here as well.
			 */
			ret = (dir_g_shadow | dir_g_out_bits) & 0x7FFFFFFF;
		}
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_SETINPUT: /* Use IO_SETGET_INPUT instead! */
		/* Set direction 0=unchanged 1=input,
		 * return mask with 1=input
		 */
		spin_lock_irqsave(&gpio_lock, flags);
		ret = setget_input(priv, arg) & 0x7FFFFFFF;
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_SETOUTPUT: /* Use IO_SETGET_OUTPUT instead! */
		/* Set direction 0=unchanged 1=output,
		 * return mask with 1=output
		 */
		spin_lock_irqsave(&gpio_lock, flags);
		ret =  setget_output(priv, arg) & 0x7FFFFFFF;
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_SHUTDOWN:
		spin_lock_irqsave(&gpio_lock, flags);
		SOFT_SHUTDOWN();
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_GET_PWR_BT:
		spin_lock_irqsave(&gpio_lock, flags);
#if defined (CONFIG_ETRAX_SOFT_SHUTDOWN)
		ret = (*R_PORT_G_DATA & ( 1 << CONFIG_ETRAX_POWERBUTTON_BIT));
#else
		ret = 0;
#endif
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_CFG_WRITE_MODE:
		spin_lock_irqsave(&gpio_lock, flags);
		priv->clk_mask = arg & 0xFF;
		priv->data_mask = (arg >> 8) & 0xFF;
		priv->write_msb = (arg >> 16) & 0x01;
		/* Check if we're allowed to change the bits and
		 * the direction is correct
		 */
		if (!((priv->clk_mask & priv->changeable_bits) &&
		      (priv->data_mask & priv->changeable_bits) &&
		      (priv->clk_mask & *priv->dir_shadow) &&
		      (priv->data_mask & *priv->dir_shadow)))
		{
			priv->clk_mask = 0;
			priv->data_mask = 0;
			ret = -EPERM;
		}
		spin_unlock_irqrestore(&gpio_lock, flags);
		break;
	case IO_READ_INBITS:
		/* *arg is result of reading the input pins */
		spin_lock_irqsave(&gpio_lock, flags);
		if (USE_PORTS(priv)) {
			val = *priv->port;
		} else if (priv->minor == GPIO_MINOR_G) {
			val = *R_PORT_G_DATA;
		}
		spin_unlock_irqrestore(&gpio_lock, flags);
		if (copy_to_user((void __user *)arg, &val, sizeof(val)))
			ret = -EFAULT;
		break;
	case IO_READ_OUTBITS:
		 /* *arg is result of reading the output shadow */
		spin_lock_irqsave(&gpio_lock, flags);
		if (USE_PORTS(priv)) {
			val = *priv->shadow;
		} else if (priv->minor == GPIO_MINOR_G) {
			val = port_g_data_shadow;
		}
		spin_unlock_irqrestore(&gpio_lock, flags);
		if (copy_to_user((void __user *)arg, &val, sizeof(val)))
			ret = -EFAULT;
		break;
	case IO_SETGET_INPUT:
		/* bits set in *arg is set to input,
		 * *arg updated with current input pins.
		 */
		if (copy_from_user(&val, (void __user *)arg, sizeof(val)))
		{
			ret = -EFAULT;
			break;
		}
		spin_lock_irqsave(&gpio_lock, flags);
		val = setget_input(priv, val);
		spin_unlock_irqrestore(&gpio_lock, flags);
		if (copy_to_user((void __user *)arg, &val, sizeof(val)))
			ret = -EFAULT;
		break;
	case IO_SETGET_OUTPUT:
		/* bits set in *arg is set to output,
		 * *arg updated with current output pins.
		 */
		if (copy_from_user(&val, (void __user *)arg, sizeof(val))) {
			ret = -EFAULT;
			break;
		}
		spin_lock_irqsave(&gpio_lock, flags);
		val = setget_output(priv, val);
		spin_unlock_irqrestore(&gpio_lock, flags);
		if (copy_to_user((void __user *)arg, &val, sizeof(val)))
			ret = -EFAULT;
		break;
	default:
		spin_lock_irqsave(&gpio_lock, flags);
		if (priv->minor == GPIO_MINOR_LEDS)
			ret = gpio_leds_ioctl(cmd, arg);
		else
			ret = -EINVAL;
		spin_unlock_irqrestore(&gpio_lock, flags);
	} /* switch */

	return ret;
}

static int
gpio_leds_ioctl(unsigned int cmd, unsigned long arg)
{
	unsigned char green;
	unsigned char red;

	switch (_IOC_NR(cmd)) {
	case IO_LEDACTIVE_SET:
		green = ((unsigned char)arg) & 1;
		red   = (((unsigned char)arg) >> 1) & 1;
		CRIS_LED_ACTIVE_SET_G(green);
		CRIS_LED_ACTIVE_SET_R(red);
		break;

	case IO_LED_SETBIT:
		CRIS_LED_BIT_SET(arg);
		break;

	case IO_LED_CLRBIT:
		CRIS_LED_BIT_CLR(arg);
		break;

	default:
		return -EINVAL;
	} /* switch */

	return 0;
}

static const struct file_operations gpio_fops = {
	.owner          = THIS_MODULE,
	.poll           = gpio_poll,
	.unlocked_ioctl = gpio_ioctl,
	.write          = gpio_write,
	.open           = gpio_open,
	.release        = gpio_release,
	.llseek		= noop_llseek,
};

static void ioif_watcher(const unsigned int gpio_in_available,
	const unsigned int gpio_out_available,
	const unsigned char pa_available,
	const unsigned char pb_available)
{
	unsigned long int flags;

	D(printk(KERN_DEBUG "gpio.c: ioif_watcher called\n"));
	D(printk(KERN_DEBUG "gpio.c: G in: 0x%08x G out: 0x%08x "
		"PA: 0x%02x PB: 0x%02x\n",
		gpio_in_available, gpio_out_available,
		pa_available, pb_available));

	spin_lock_irqsave(&gpio_lock, flags);

	dir_g_in_bits = gpio_in_available;
	dir_g_out_bits = gpio_out_available;

	/* Initialise the dir_g_shadow etc. depending on genconfig */
	/* 0=input 1=output */
	if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g0dir, out))
		dir_g_shadow |= (1 << 0);
	if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g8_15dir, out))
		dir_g_shadow |= 0x0000FF00;
	if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g16_23dir, out))
		dir_g_shadow |= 0x00FF0000;
	if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g24dir, out))
		dir_g_shadow |= (1 << 24);

	changeable_dir_g = changeable_dir_g_mask;
	changeable_dir_g &= dir_g_out_bits;
	changeable_dir_g &= dir_g_in_bits;

	/* Correct the bits that can change direction */
	dir_g_out_bits &= ~changeable_dir_g;
	dir_g_out_bits |= dir_g_shadow;
	dir_g_in_bits &= ~changeable_dir_g;
	dir_g_in_bits |= (~dir_g_shadow & changeable_dir_g);

	spin_unlock_irqrestore(&gpio_lock, flags);

	printk(KERN_INFO "GPIO port G: in_bits: 0x%08lX out_bits: 0x%08lX "
		"val: %08lX\n",
	       dir_g_in_bits, dir_g_out_bits, (unsigned long)*R_PORT_G_DATA);
	printk(KERN_INFO "GPIO port G: dir: %08lX changeable: %08lX\n",
	       dir_g_shadow, changeable_dir_g);
}

/* main driver initialization routine, called from mem.c */

static int __init gpio_init(void)
{
	int res;
#if defined (CONFIG_ETRAX_CSP0_LEDS)
	int i;
#endif

	res = register_chrdev(GPIO_MAJOR, gpio_name, &gpio_fops);
	if (res < 0) {
		printk(KERN_ERR "gpio: couldn't get a major number.\n");
		return res;
	}

	/* Clear all leds */
#if defined (CONFIG_ETRAX_CSP0_LEDS) ||  defined (CONFIG_ETRAX_PA_LEDS) || defined (CONFIG_ETRAX_PB_LEDS)
	CRIS_LED_NETWORK_SET(0);
	CRIS_LED_ACTIVE_SET(0);
	CRIS_LED_DISK_READ(0);
	CRIS_LED_DISK_WRITE(0);

#if defined (CONFIG_ETRAX_CSP0_LEDS)
	for (i = 0; i < 32; i++)
		CRIS_LED_BIT_SET(i);
#endif

#endif
	/* The I/O interface allocation watcher will be called when
	 * registering it. */
	if (cris_io_interface_register_watcher(ioif_watcher)){
		printk(KERN_WARNING "gpio_init: Failed to install IO "
			"if allocator watcher\n");
	}

	printk(KERN_INFO "ETRAX 100LX GPIO driver v2.5, (c) 2001-2008 "
		"Axis Communications AB\n");
	/* We call etrax_gpio_wake_up_check() from timer interrupt and
	 * from cpu_idle() in kernel/process.c
	 * The check in cpu_idle() reduces latency from ~15 ms to ~6 ms
	 * in some tests.
	 */
	res = request_irq(TIMER0_IRQ_NBR, gpio_poll_timer_interrupt,
		IRQF_SHARED | IRQF_DISABLED, "gpio poll", gpio_name);
	if (res) {
		printk(KERN_CRIT "err: timer0 irq for gpio\n");
		return res;
	}
	res = request_irq(PA_IRQ_NBR, gpio_interrupt,
		IRQF_SHARED | IRQF_DISABLED, "gpio PA", gpio_name);
	if (res)
		printk(KERN_CRIT "err: PA irq for gpio\n");

	return res;
}

/* this makes sure that gpio_init is called during kernel boot */
module_init(gpio_init);


text:
package org.vaadin.addons.layouts;

import com.vaadin.ui.Label;

import junit.framework.Assert;

import org.junit.Test;

public class CardLayoutTest {

    @Test
    public void testFirstComponentIsVisible() {
        CardLayout layout = new CardLayout();
        Assert.assertTrue(layout.isEmpty());
        Assert.assertEquals(0, layout.size());

        Label label = new Label("foo");
        label.setVisible(false);
        layout.addComponent(label);

        Assert.assertEquals(1, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        Assert.assertEquals(label, layout.getVisibleComponent());
        Assert.assertTrue(label.isVisible());
    }

    @Test
    public void testFirstComponentIsVisibleAfterAddition() {
        CardLayout layout = new CardLayout();

        Label label = new Label("foo");
        label.setVisible(false);
        layout.addComponent(label);
        layout.addComponent(new Label("bar"));

        Assert.assertEquals(2, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        Assert.assertEquals(label, layout.getVisibleComponent());
        Assert.assertTrue(label.isVisible());
    }

    @Test
    public void testAddComponentToFrontByIndex() {
        CardLayout layout = new CardLayout();

        Label label = new Label("foo");
        label.setVisible(false);
        layout.addComponent(label);

        Label label2 = new Label("bar");
        layout.addComponent(label2, 0);

        Assert.assertEquals(2, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        Assert.assertEquals(label2, layout.getVisibleComponent());
        Assert.assertTrue(label2.isVisible());
        Assert.assertFalse(label.isVisible());
    }

    @Test
    public void testAddComponentAsFirst() {
        CardLayout layout = new CardLayout();

        Label label = new Label("foo");
        label.setVisible(false);
        layout.addComponent(label);

        Label label2 = new Label("bar");
        layout.addComponentAsFirst(label2);

        Assert.assertEquals(2, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        Assert.assertEquals(label2, layout.getVisibleComponent());
        Assert.assertTrue(label2.isVisible());
        Assert.assertFalse(label.isVisible());
    }

    @Test
    public void testNext() {
        CardLayout layout = new CardLayout();

        layout.addComponent(new Label("foo"));
        layout.addComponent(new Label("bar"));
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.next();
        Assert.assertEquals(1, layout.getVisibleComponentIndex());
        Assert.assertEquals("bar", ((Label)layout.getVisibleComponent()).getValue());
        layout.next();
        Assert.assertEquals(2, layout.getVisibleComponentIndex());
        Assert.assertEquals("baz", ((Label)layout.getVisibleComponent()).getValue());
        layout.next();
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        Assert.assertEquals("foo", ((Label)layout.getVisibleComponent()).getValue());
    }

    @Test
    public void testPrevious() {
        CardLayout layout = new CardLayout();

        layout.addComponent(new Label("foo"));
        layout.addComponent(new Label("bar"));
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.previous();
        Assert.assertEquals(2, layout.getVisibleComponentIndex());
        Assert.assertEquals("baz", ((Label)layout.getVisibleComponent()).getValue());
        layout.previous();
        Assert.assertEquals(1, layout.getVisibleComponentIndex());
        Assert.assertEquals("bar", ((Label)layout.getVisibleComponent()).getValue());
        layout.previous();
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        Assert.assertEquals("foo", ((Label)layout.getVisibleComponent()).getValue());
    }

    @Test
    public void testFirstLast() {
        CardLayout layout = new CardLayout();

        layout.addComponent(new Label("foo"));
        layout.addComponent(new Label("bar"));
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.last();
        Assert.assertEquals(2, layout.getVisibleComponentIndex());
        Assert.assertEquals("baz", ((Label)layout.getVisibleComponent()).getValue());
        layout.first();
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        Assert.assertEquals("foo", ((Label)layout.getVisibleComponent()).getValue());
    }

    @Test
    public void testShowByIndex() {
        CardLayout layout = new CardLayout();

        layout.addComponent(new Label("foo"));
        layout.addComponent(new Label("bar"));
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.show(1);
        Assert.assertEquals(1, layout.getVisibleComponentIndex());
        Assert.assertEquals("bar", ((Label)layout.getVisibleComponent()).getValue());

        try {
            layout.show(100);
            Assert.fail("Exceptions should have been thrown");
        } catch (IndexOutOfBoundsException e) {
            // ignore
        }
    }

    @Test
    public void testShowByComponent() {
        CardLayout layout = new CardLayout();

        Label label = new Label("bar");
        layout.addComponent(new Label("foo"));
        layout.addComponent(label);
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.show(null);
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.show(label);
        Assert.assertEquals(1, layout.getVisibleComponentIndex());
        Assert.assertEquals("bar", ((Label)layout.getVisibleComponent()).getValue());
    }

    @Test
    public void testRemoveNonVisible() {
        CardLayout layout = new CardLayout();

        Label label = new Label("bar");
        layout.addComponent(new Label("foo"));
        layout.addComponent(label);
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.removeComponent(label);
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
    }

    @Test
    public void testRemoveVisible() {
        CardLayout layout = new CardLayout();

        Label label = new Label("bar");
        layout.addComponent(new Label("foo"));
        layout.addComponent(label);
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.show(label);
        Assert.assertEquals(1, layout.getVisibleComponentIndex());
        layout.removeComponent(label);
        Assert.assertEquals(1, layout.getVisibleComponentIndex());
        Assert.assertEquals("baz", ((Label)layout.getVisibleComponent()).getValue());
    }

    @Test
    public void testReplaceNonVisible() {
        CardLayout layout = new CardLayout();

        Label label = new Label("bar");
        Label label2 = new Label("baz");
        layout.addComponent(new Label("foo"));
        layout.addComponent(label);
        layout.addComponent(label2);

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.replaceComponent(label, label2);
        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
    }

    @Test
    public void testReplaceVisible() {
        CardLayout layout = new CardLayout();

        Label label = new Label("foo");
        Label label2 = new Label("bar");
        layout.addComponent(label);
        layout.addComponent(label2);
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.replaceComponent(label, label2);
        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        Assert.assertEquals("bar", ((Label)layout.getVisibleComponent()).getValue());
    }

    @Test
    public void testReplaceVisibleWithNew() {
        CardLayout layout = new CardLayout();

        Label label = new Label("foo");
        layout.addComponent(label);
        layout.addComponent(new Label("bar"));
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.replaceComponent(label, new Label("goo"));
        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        Assert.assertEquals("goo", ((Label)layout.getVisibleComponent()).getValue());
    }

    @Test
    public void testRemoveAll() {
        CardLayout layout = new CardLayout();

        layout.addComponent(new Label("foo"));
        layout.addComponent(new Label("bar"));
        layout.addComponent(new Label("baz"));

        Assert.assertEquals(3, layout.size());
        Assert.assertEquals(0, layout.getVisibleComponentIndex());
        layout.removeAllComponents();
        Assert.assertEquals(0, layout.size());
        Assert.assertEquals(-1, layout.getVisibleComponentIndex());
    }
}


text:
pub use self::{displace::*, rotate_point::*, scale_point::*, translate_point::*, turbulence::*};

mod displace;
mod rotate_point;
mod scale_point;
mod translate_point;
mod turbulence;


text:
layout: post
title: "Mapping County Unemployment with blscrapeR"
categories: r
tags: [r, bls]
---

The [blscrapeR package](https://github.com/keberwein/blscrapeR) makes it easy to produce choropleth maps of various employment and unemployment rates from the Bureau of Labor Statistics (BLS.) It's easy enough to pull a metric for a certain county. The code below pulls the unemployment rates for Orange County, FL from the BLS API.

{% highlight r %}
library(blscrapeR)
df <- bls_api("LAUCN120950000000003",
              startyear = 2016, endyear = 2016)

head(df)
{% endhighlight %}

The only problem is, there are over 3,000 counties in the United States and an API query of that size would push any user well over the daily query limits of the BLS API.

To resolve the issue, the `blscrapeR` package includes a function that allows us to pull county statistics in the form of a text file from the BLS servers, which don't count against a user's daily query limit.

**NOTE:** You can use arguments to get data for a specific month, but if there is no date argument, the function will pull the most recent month in the data set.

{% highlight r %}
library(blscrapeR)
df <- get_bls_county()

head(df)
{% endhighlight %}

**Limitations:** The `get_bls_county()` function is only able to pull labor data for the past 12 months at time of query.

## Choropleth Mapping

Now that we've got the data, it's time for the mapping. There are a few options here, but the simplest option would be to use the package's  `bls_map_county()` function.

{% highlight r %}
library(blscrapeR)
bls_map_county(map_data = df, fill_rate = "unemployed_rate",
               labtitle = "Unemployment Rate by County")
{% endhighlight %}

![](https://github.com/keberwein/keberwein.github.io/blob/master/images/blscrape_county_unemp.png?raw=true)

Maybe you just want one state? That's alright too.

{% highlight r %}
library(blscrapeR)
# Map the unemployment rate for the Southeastern United States.
df <- get_bls_county(stateName = "Florida")

bls_map_county(map_data=df, fill_rate = "unemployed_rate",
               stateName = "Florida")
{% endhighlight %}

![](https://github.com/keberwein/keberwein.github.io/blob/master/images/bus_fl_map.png?raw=true)

## Custom Mapping

The `bls_map_county()` function produces a map that may not be your cup of tea. The function is only provided as a "quick function" to see if your data fit. The `blscrapeR` package provides the fortified map data, which includes longitud, latitude and FIPS codes. This data set is suitable for any kind of ggplot2 map you can think of.

First, call the internal map data set and have a look:

{% highlight r %}
library(blscrapeR)
us_map <- county_map_data

head(us_map)
{% endhighlight %}

{% highlight text %}
##      long      lat order  hole piece   group    id
## 1 1225889 -1275020     1 FALSE     1 01001.1 01001
## 2 1244873 -1272331     2 FALSE     1 01001.1 01001
## 3 1244129 -1267515     3 FALSE     1 01001.1 01001
## 4 1272010 -1262889     4 FALSE     1 01001.1 01001
## 5 1276797 -1295514     5 FALSE     1 01001.1 01001
## 6 1272367 -1296730     6 FALSE     1 01001.1 01001
{% endhighlight %}

Notice the id column looks a lot like one of the FIPS codes returned by the get_bls_county() function? This is actually a concatenation of the state + county FIPS codes. The first two numbers are the state FIPS and the last four are the county FIPS. These boundaries currently represent 20015/2016 and will be updated accordingly so they always represent the current year.

Next, produce your custom map.

{% highlight r %}
library(blscrapeR)
library(ggplot2)
# Get the most recent unemployment rate for each county on a national level.
df <- get_bls_county()
# Get map data
us_map <- county_map_data

# Insert larger breaks in unemployment rates
df$rate_d <- cut(df$unemployed_rate, breaks = c(seq(0, 10, by = 2), 35))
# Plot
ggplot() +
    geom_map(data=us_map, map=us_map,
             aes(x=long, y=lat, map_id=id, group=group),
             fill="#ffffff", color="#0e0e0e", size=0.15) +
    geom_map(data=df, map=us_map, aes_string(map_id="fips", fill=df$rate_d),
             color="#0e0e0e", size=0.15) +
    scale_fill_brewer()+
    coord_equal() +
    theme(axis.line=element_blank(),
          axis.text.x=element_blank(),
          axis.text.y=element_blank(),
          axis.ticks=element_blank(),
          axis.title.x=element_blank(),
          axis.title.y=element_blank(),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.border = element_blank(),
          panel.background = element_blank(),
          legend.title=element_blank())
{% endhighlight %}

![](https://github.com/keberwein/keberwein.github.io/blob/master/images/bls_custom_map.png?raw=true)

If you want more mapping options, there is more information in the `blscrapeR` [package vignettes](https://github.com/keberwein/blscrapeR/tree/master/vignettes).


text:
using Android.OS;
using Android.Runtime;
using Android.Views;
using MyHealth.Client.Core.ViewModels;
using Cirrious.MvvmCross.Binding.Droid.BindingContext;
using Cirrious.MvvmCross.Droid.Support.Fragging;
using Cirrious.MvvmCross.Droid.Support.Fragging.Fragments;
using Android.Widget;
using Android.Graphics;
using Android.Views.Animations;
using System.ComponentModel;
using MyHealth.Client.Droid.Extensions;

namespace MyHealth.Client.Droid.Views
{
    [MvxOwnedViewModelFragment]
    [Register("myhealth.client.droid.views.HomeFragment")]
    public class HomeFragment : MvxFragment<HomeViewModel>
    {
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var ignored = base.OnCreateView(inflater, container, savedInstanceState);
            return this.BindingInflate(Resource.Layout.HomeView, null);
        }

        public override void OnStop()
        {
            base.OnStop();
            StopPillButtonBindings();
            StopHeartAnimation(View);
        }

        public override void OnStart()
        {
            base.OnStart();
            StartHeartAnimation(View);
        }

        private void StopPillButtonBindings()
        {
            this.ViewModel.PropertyChanged -= OnViewModelPropertyChanged;
        }

        public override void OnViewCreated(View view, Bundle savedInstanceState)
        {
            base.OnViewCreated(view, savedInstanceState);
            (Activity as MainActivity)?.SetCustomTitle("Home");
            SetupUI();

            StartPillButtonBindings();
        }

        private void StartPillButtonBindings()
        {
            RefreshMedicineButtonStatus(firstMedicineSelected: ViewModel.FirstMedicineSelected);
            this.ViewModel.PropertyChanged += OnViewModelPropertyChanged;
        }

        private void StopHeartAnimation(View view)
        {
            var heart = view.FindViewById<ImageView>(Resource.Id.heart);
            heart.Animation = null;
        }

        private void StartHeartAnimation(View view)
        {
            var heart = view.FindViewById<ImageView>(Resource.Id.heart);
            var anim = new ScaleAnimation(fromX: 1,
                                            toX: 0.8f,
                                            fromY: 1,
                                            toY: 0.8f,
                                            pivotXType: Dimension.RelativeToSelf,
                                            pivotXValue: 0.5f,
                                            pivotYType: Dimension.RelativeToSelf,
                                            pivotYValue: 0.5f);

            anim.RepeatMode = RepeatMode.Reverse;
            anim.RepeatCount = Animation.Infinite;
            anim.Interpolator = new AccelerateDecelerateInterpolator();
            anim.Duration = 1000;
            heart.Animation = anim;
        }

        private void SetupUI()
        {
            var dailyTipsHeaderTextview = View.FindViewById<TextView>(Resource.Id.dailyTipsHeaderTextView);
            var font = Typeface.CreateFromAsset(Activity.BaseContext.Assets, "fonts/Raleway 700.ttf");
            dailyTipsHeaderTextview.Typeface = font;
        }

        private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "FirstMedicineSelected")
            {
                RefreshMedicineButtonStatus(ViewModel.FirstMedicineSelected);
            }
        }

        private void RefreshMedicineButtonStatus(bool firstMedicineSelected)
        {
            var selectedColor = Color.Argb(0xff, 0x00, 0xd8, 0xcc);
            var unselectedColor = Color.Argb(0xff, 0xc0, 0xc0, 0xc0);
            var btn1 = View.FindViewById<Button>(Resource.Id.medicine1Button);
            var btn2 = View.FindViewById<Button>(Resource.Id.medicine2Button);
            btn1.SetTextColor(firstMedicineSelected ? selectedColor : unselectedColor);
            btn2.SetTextColor(firstMedicineSelected ? unselectedColor : selectedColor);
        }
    }
}