text:
module m_errors
  !!Module contains error handling procedures
  use iso_fortran_env, only: output_unit
  use variableKind
  implicit none

  integer(i32), parameter :: IO_OPEN = 1
    !! Constant for file open used by fErr
  integer(i32), parameter :: IO_READ = 2
    !! Constant for file read used by fErr
  integer(i32), parameter :: IO_WRITE = 3
    !! Constant for file write used by fErr
  integer(i32), parameter :: IO_CLOSE = 4
    !! Constant for file close used by fErr

contains
  !====================================================================!
  subroutine mErr(istat, aMsg, alloc, iunit)
    !! Checks for successful (de)allocation.  Stops the code.
    !!
    !! Use this after an allocate/deallocate statement
    !! allocate(x(nz,ny,nx), stat=istat); call mErr(istat,'x',1)
    !! deallocate(x, stat=istat); call mErr(istat,'x',2)
    !====================================================================!
    integer(i32), intent(in) :: istat
      !! results of stat=istat in (de)allocate
    character(len=*), intent(in) :: aMsg
      !! Message associated with the (de)allocate
    integer(i32), intent(in) :: alloc
      !! 1 = allocate, 2 = deallocate
    integer(i32), optional, intent(in) :: iunit
      !! Optional file id to write the message to

    character(len=:), allocatable :: tmp

    if (istat == 0) return
    ! If istat is not zero, there is an error.
    tmp=''
    select case(alloc)
    case(1)
      tmp='Allocating Memory: '//trim(aMsg)
    case(2)
      tmp='Deallocating Memory: '//trim(aMsg)
    end select
    call eMsg(tmp, iunit)
  end subroutine
  !====================================================================!
  !====================================================================!
  subroutine msg(aMsg, iunit)
    !! Write a message
    !====================================================================!
    character(len=*), intent(in) :: aMsg
      !! Message to write
    integer(i32), optional, intent(in) :: iunit
      !! file id to write the message to

    if (present(iunit)) then
      write(iunit,'(a)') trim(aMsg)
      write(output_unit,'(a)') trim(aMsg)
    else
      write(output_unit,'(a)') trim(aMsg)
    endif
  end subroutine
  !====================================================================!
  !====================================================================!
  subroutine wMsg(aMsg, iunit)
    !! Write a Warning message
    !====================================================================!
    character(len=*), intent(in) :: aMsg
      !! Message to write
    integer(i32), optional, intent(in) :: iunit
      !! file id to write the message to

    call msg('Warning:'//trim(aMsg), iunit)
  end subroutine
  !====================================================================!
  !====================================================================!
  subroutine eMsg(aMsg, iunit)
    !! Write an Error message. Stops the code
    !====================================================================!
    character(len=*), intent(in) :: aMsg
      !! Message to write
    integer(i32), optional, intent(in) :: iunit
      !! file id to write the message to

    call Msg('Error:'//trim(aMsg), iunit)
    if (present(iunit)) close(iunit)
    stop
  end subroutine
  !====================================================================!
  !====================================================================!
  subroutine fErr(istat, fname, flg, iunit)
    !! Checks for a file error
    !====================================================================!
    integer(i32), intent(in) :: istat
      !! Result of iostat=istat for open,read,write,close
    character(len=*), intent(in) :: fname
      !! Name of the file
    integer(i32), intent(in) :: flg
      !! IO_OPEN=Open, IO_READ=Read, IO_WRITE=Write, IO_CLOSE=Close
    integer(i32), optional, intent(in) :: iunit
      !! file id to write the error to

    character(len=:),allocatable :: Amsg

    if (istat == 0) return

    Amsg=''
    select case(flg)
    case(IO_OPEN)
      Amsg='Opening file: '//trim(fname)
    case(IO_READ)
      Amsg='Reading from: '//trim(fname)
    case(IO_WRITE)
      Amsg='Writing to file: '//trim(fname)
    case(IO_CLOSE)
      Amsg='Closing file: '//trim(fname)
    case default
      Amsg='Error:Invalid error flag [1-4]'
    end select

    call eMsg(aMsg, iunit)
  end subroutine
  !====================================================================!
end module m_errors


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/dialogflow/v2/conversation_profile.proto

namespace Google\Cloud\Dialogflow\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Metadata for a [ConversationProfile.ClearSuggestionFeatureConfig][]
 * operation.
 *
 * Generated from protobuf message google.cloud.dialogflow.v2.ClearSuggestionFeatureConfigOperationMetadata
 */
class ClearSuggestionFeatureConfigOperationMetadata extends \Google\Protobuf\Internal\Message
{
    /**
     * The resource name of the conversation profile. Format:
     * `projects/<Project ID>/locations/<Location
     * ID>/conversationProfiles/<Conversation Profile ID>`
     *
     * Generated from protobuf field string conversation_profile = 1;
     */
    private $conversation_profile = '';
    /**
     * Required. The participant role to remove the suggestion feature
     * config. Only HUMAN_AGENT or END_USER can be used.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.Participant.Role participant_role = 2 [(.google.api.field_behavior) = REQUIRED];
     */
    private $participant_role = 0;
    /**
     * Required. The type of the suggestion feature to remove.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.SuggestionFeature.Type suggestion_feature_type = 3 [(.google.api.field_behavior) = REQUIRED];
     */
    private $suggestion_feature_type = 0;
    /**
     * Timestamp whe the request was created. The time is measured on server side.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 4;
     */
    private $create_time = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $conversation_profile
     *           The resource name of the conversation profile. Format:
     *           `projects/<Project ID>/locations/<Location
     *           ID>/conversationProfiles/<Conversation Profile ID>`
     *     @type int $participant_role
     *           Required. The participant role to remove the suggestion feature
     *           config. Only HUMAN_AGENT or END_USER can be used.
     *     @type int $suggestion_feature_type
     *           Required. The type of the suggestion feature to remove.
     *     @type \Google\Protobuf\Timestamp $create_time
     *           Timestamp whe the request was created. The time is measured on server side.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Dialogflow\V2\ConversationProfile::initOnce();
        parent::__construct($data);
    }

    /**
     * The resource name of the conversation profile. Format:
     * `projects/<Project ID>/locations/<Location
     * ID>/conversationProfiles/<Conversation Profile ID>`
     *
     * Generated from protobuf field string conversation_profile = 1;
     * @return string
     */
    public function getConversationProfile()
    {
        return $this->conversation_profile;
    }

    /**
     * The resource name of the conversation profile. Format:
     * `projects/<Project ID>/locations/<Location
     * ID>/conversationProfiles/<Conversation Profile ID>`
     *
     * Generated from protobuf field string conversation_profile = 1;
     * @param string $var
     * @return $this
     */
    public function setConversationProfile($var)
    {
        GPBUtil::checkString($var, True);
        $this->conversation_profile = $var;

        return $this;
    }

    /**
     * Required. The participant role to remove the suggestion feature
     * config. Only HUMAN_AGENT or END_USER can be used.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.Participant.Role participant_role = 2 [(.google.api.field_behavior) = REQUIRED];
     * @return int
     */
    public function getParticipantRole()
    {
        return $this->participant_role;
    }

    /**
     * Required. The participant role to remove the suggestion feature
     * config. Only HUMAN_AGENT or END_USER can be used.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.Participant.Role participant_role = 2 [(.google.api.field_behavior) = REQUIRED];
     * @param int $var
     * @return $this
     */
    public function setParticipantRole($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\Dialogflow\V2\Participant\Role::class);
        $this->participant_role = $var;

        return $this;
    }

    /**
     * Required. The type of the suggestion feature to remove.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.SuggestionFeature.Type suggestion_feature_type = 3 [(.google.api.field_behavior) = REQUIRED];
     * @return int
     */
    public function getSuggestionFeatureType()
    {
        return $this->suggestion_feature_type;
    }

    /**
     * Required. The type of the suggestion feature to remove.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.SuggestionFeature.Type suggestion_feature_type = 3 [(.google.api.field_behavior) = REQUIRED];
     * @param int $var
     * @return $this
     */
    public function setSuggestionFeatureType($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\Dialogflow\V2\SuggestionFeature\Type::class);
        $this->suggestion_feature_type = $var;

        return $this;
    }

    /**
     * Timestamp whe the request was created. The time is measured on server side.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 4;
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getCreateTime()
    {
        return $this->create_time;
    }

    public function hasCreateTime()
    {
        return isset($this->create_time);
    }

    public function clearCreateTime()
    {
        unset($this->create_time);
    }

    /**
     * Timestamp whe the request was created. The time is measured on server side.
     *
     * Generated from protobuf field .google.protobuf.Timestamp create_time = 4;
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setCreateTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->create_time = $var;

        return $this;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * App Settings
 */

/**
 * Master Root Tag
 * The tag with the id blow can't be deleted from the App and should't be removed in the DB either
 */
Configure::write('RootTag', 1);

/**
 * Fixed first folder
 */
Configure::write('FirstFolderID', 2);

/**
 * Recovery Configuration (Danger when turning on with existing database)
 */
Configure::write('Recovery.Enable', false);
Configure::write('Recovery.Key', null);

/**
 * Minimum Password length
 */
Configure::write('MinPasswordLength', 8);

/**
 * Invite valid duration in sec
 * If null invites never expires
 */
Configure::write('InviteTimeOut', null);

/**
 * Max access_level for Administration Tab
 * Counting the AccessLevel Down (UserAccessLevel <= AccessLevel.Administration == true && UserAccessLevel > 0)
 */
Configure::write('AccessLevel.Administration', 1);

/**
 * Enable/Disable Strict Tagging
 * When Strict Tagging is enabled you can only assign and see Tags to Password in which you are subscribed
 */
Configure::write('StrictTagging.enable', true);

//################################################# UI Config ####################################################
/**
 * Select Folder Style (Accepted values: folder_small folder_big)
 */
Configure::write('Style.folder', 'folder_small');

/**
 * Set the folder search prefix
 */
Configure::write('UI.FolderSearchPrefix', '::');

/**
 * QuickAccess Configuration
 */
//Enable QuickAccess: Accepted Values: true , false
Configure::write('QuickAccess.Enable', true);

//QuickAccess Title: Accepted Values: any string
Configure::write('QuickAccess.Title', "QuickAccess ");

/* Links
	 *Format : "link" => "name"
	 *Use "---" to create a separator
	 */
$links = array(
    "http://mail.mbox.lu" => "Mail Box",
    "http://mixvoip.slack.com" => "Slack",
    "---",
    "https://internal.mixvoip.com:12663" => "Internal Wiki",
    "---",
    "http://www.mixvoip.com" => "Homepage"
);

//Add debug-entrys to the QuickAccess
if (Configure::read('debug') > 0) {
    $links[] = "---";
    $links['/Password_Manager/debug'] = "Debug Page";
}
Configure::write('QuickAccess.Menu', $links);


text:
package automation;

import simulator.interfaces.SimAutomator;

public class BotAutomator {

    private SimAutomator simAutomator;

    public BotAutomator(SimAutomator simAutomator) {
        super();
        this.simAutomator = simAutomator;
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>relatedTarget property - RelatedEvent class - polymer_app_layout.behaviors library - Dart API</title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the relatedTarget property from the RelatedEvent class, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

polymer_app_layout_template

polymer_app_layout.behaviors

RelatedEvent

relatedTarget

relatedTarget

polymer_app_layout_template

polymer_app_layout.behaviors

RelatedEvent

relatedTarget

property
 relatedTarget

polymer_app_layout_template

polymer_app_layout.behaviors

RelatedEvent

Properties

bubbles

cancelable

clipboardData

currentTarget

defaultPrevented

eventPhase

matchingTarget

path

relatedTarget

target

timeStamp

type

Methods

preventDefault

stopImmediatePropagation

stopPropagation

        EventTarget
        relatedTarget

            read-only

Not documented.

                  polymer_app_layout_template 0.1.0 api docs

                •

                •

                  cc license


text:
#ifndef KEYBOARD_H
#define KEYBOARD_H

#include "inputs.h"

enum KeyType {KEYTYPE_STD, KEYTYPE_ARROW};

class Keyboard
{
public:
    Keyboard();
    bool LoopKeys();
    // this is reseted at each loop
    bool KeyPressed;
    // Indicates which is the arrow that has been pressed
    bool ArrowsLTRB[4];
    int LastKeyNumber;
    char LastKeyChar;
    KeyType LastKeyType;
    ~Keyboard();
};

#endif // KEYBOARD_H


text:
#include "config.h"
#include "core/layout/LayoutWordBreak.h"

#include "core/html/HTMLElement.h"

namespace blink {

LayoutWordBreak::LayoutWordBreak(HTMLElement* element)
    : RenderText(element, StringImpl::empty())
{
}

const char* LayoutWordBreak::renderName() const
{
    return "LayoutWordBreak";
}

bool LayoutWordBreak::isWordBreak() const
{
    return true;
}

}


text:
package boofcv.alg.segmentation.slic;

import boofcv.factory.segmentation.FactorySegmentationAlg;
import boofcv.struct.ConnectRule;
import boofcv.struct.image.GrayU8;
import boofcv.struct.image.ImageType;

/**
 * Implementation of {@link SegmentSlic} for image of type {@link GrayU8}.
 *
 * @author Peter Abeles
 */
public class SegmentSlic_U8 extends SegmentSlic<GrayU8> {
	private static ImageType IT;
	public SegmentSlic_U8(int numberOfRegions, float m, int totalIterations,
						  ConnectRule connectRule, ImageType IT, FactorySegmentationAlg FSA ) {
		super(numberOfRegions, m , totalIterations, connectRule,IT.single(GrayU8.class), FSA);
	}

	@Override
	public void setColor(float[] color, int x, int y) {
		color[0] = input.unsafe_get(x,y);
	}

	@Override
	public void addColor(float[] color, int index, float weight) {
		color[0] += (input.data[index]&0xFF)*weight;
	}

	@Override
	public float colorDistance(float[] color, int index) {
		float difference = color[0] - (input.data[index]&0xFF);
		return difference*difference;
	}

	@Override
	public float getIntensity(int x, int y) {
		return input.get(x,y);
	}
}


text:
<?php
abstract class PleesherImplementation
{
	public function isExtensionEnabled(User $user = null)
	{
		if (is_null($user) && isset($GLOBALS['wgUser']))
			$user = $GLOBALS['wgUser'];

		if (isset($GLOBALS['wgPleesherAccessChecker']) && is_callable($GLOBALS['wgPleesherAccessChecker']))
			return $GLOBALS['wgPleesherAccessChecker']($user);

		return true;
	}

	public abstract function getGoalData();

	public abstract function getI18nPrefix();

	public function getGoalCategories()
	{
		return [];
	}

	public function getLogger()
	{
		$logger = new \Monolog\Logger('pleesher');
		$logger->pushHandler(new \Monolog\Handler\RotatingFileHandler(__DIR__ . '/logs/warning.log', 0, \Monolog\Logger::WARNING));
		$logger->pushHandler(new \Monolog\Handler\RotatingFileHandler(__DIR__ . '/logs/error.log', 0, \Monolog\Logger::ERROR));

		return $logger;
	}

	public function getGoalCheckingContext()
	{
		return [];
	}

	public function fillUser(User $user)
	{
		return $user;
	}

	public function fillGoal($goal)
	{
		return $goal;
	}

	public function getUserPageData(User $user)
	{
		return [];
	}

	public function getViewsFolder()
	{
		return null;
	}
}


text:
PROG8020 Project
================

Someone asked me, in class, what is the application of the bits and pieces of Javascript and PHP that we have been learning. For a project in this course, I have built the bits and pieces into a larger Antique Boating Ecommerce Web App. You can see the [source code here.](https://github.com/rhildred/PROG8020phpjavascript/tree/master/php/projectStart). You can see the [code working here.](http://apps.syndicateme.net/BoatProject)

![Boating](http://farm1.staticflickr.com/58/195102390_6d9329e412_n.jpg "Boating")

The project start builds on the php that we learned by using php to access 3 mysql database tables. A categories table holds the types of items that we are selling. The categories are displayed across the NAV-Bar of the application:

	CREATE TABLE IF NOT EXISTS `categories` (
	  `id` int(11) NOT NULL AUTO_INCREMENT,
	  `name` varchar(64) COLLATE utf8_bin NOT NULL,
	  `display_id` int(11) NOT NULL,
	  PRIMARY KEY (`id`),
	  KEY `display_id` (`display_id`)
	) ENGINE=InnoDB;

The products are grouped by categories (Categories have products) and displayed on the different "pages" of the website in those groupings:

	CREATE TABLE IF NOT EXISTS `products` (
	  `id` int(11) NOT NULL AUTO_INCREMENT,
	  `category_id` int(11) NOT NULL,
	  `name` varchar(64) COLLATE utf8_bin NOT NULL,
	  `description` varchar(255) COLLATE utf8_bin NOT NULL,
	  `price` decimal(10,2) NOT NULL,
	  `paypal_url` varchar(255) COLLATE utf8_bin NOT NULL,
	  PRIMARY KEY (`id`),
	  KEY `category_id` (`category_id`)
	) ENGINE=InnoDB;

Products have images, and the first image for each product is displayed in a carousel at the bottom of the page:

	CREATE TABLE IF NOT EXISTS `images` (
	  `id` int(11) NOT NULL AUTO_INCREMENT,
	  `item_id` int(11) NOT NULL,
	  `sequence_id` int(11) NOT NULL,
	  `url` varchar(64) COLLATE utf8_bin NOT NULL,
	  PRIMARY KEY (`id`)
	) ENGINE=InnoDB;

The php code to provide this data as a restful web server is almost as simple as the cds php code:

	$db = new PDO ( "mysql:host=localhost;dbname=swag", "root", "" );

	// check if last part of url is numeric
	$aUrls = explode('/', $_SERVER['REQUEST_URI']);
	$nId =  array_pop($aUrls);

	$sTable = array_pop($aUrls);
	$sSQL = "SELECT * FROM ";
	$sWhere = "";
	$aBinds = array();
	switch($sTable){
		case 'categories':
			$sSQL .= 'categories';
			if(is_numeric($nId)){
				$sWhere .= 'id = ?';
				array_push($aBinds, $nId);
			}
			break;
		case 'products':
			$sSQL = 'SELECT a.*, b.url FROM products AS a, images AS b';
			$sWhere .= 'a.id = b.item_id AND b.sequence_id = 1 AND category_id = ?';
			array_push($aBinds, array_pop($aUrls));
			if(is_numeric($nId)){
				$sWhere .= ' AND a.id = ?';
				array_push($aBinds, $nId);
			}
			break;
		case 'images':
			$sSQL .= 'images';
			$sWhere .= 'item_id = ?';
			array_push($aBinds, array_pop($aUrls));
			if(is_numeric($nId)){
				$sWhere .= ' AND sequence_id = ?';
				array_push($aBinds, $nId);
			}
			break;
		default:
			throw(new Exception("bad path " . $sTable));
	}
	if(is_numeric($nId)){
		// get a single item
		$stmt = $db->prepare($sSQL . " WHERE ". $sWhere);
		$stmt->execute($aBinds);
		$result = $stmt->fetchObject();
	} else {
		// get all of the items
		if($sWhere != ""){
			$sSQL .= " WHERE " . $sWhere;
		}
		$stmt = $db->prepare($sSQL);
		$stmt->execute($aBinds);
		$result = $stmt->fetchAll ( PDO::FETCH_OBJ );
	}
	echo json_encode($result);

This code exposes the API in a categories folder with product and images sub-folders. This should look similar to our previous API with just more code.

Also similar are the templates that we use to display the screens. Again there are just more of them. Particularly interesting is a template to display the product details and a "Buy Now" button:

Please notice the use of the `if(paypal_url !== "")` to only display the Buy Now button if the paypal_url is populated in the database. A big part of getting your enhancements to this site working is to populate all of those paypal_urls with URLs that you set up in the sandbox.

Finally the router code:

	var SwagRouter = Backbone.Router.extend({
		oCategoryList : new Backbone.Collection(),
		oItemList : new Backbone.Collection(),
		oImageList : new Backbone.Collection(),
		nCategoryId: null,
		nProductId: null,
		fNavTemplate : _.template(jQuery('#navTemplate').html()),
		fProductTemplate : _.template(jQuery('#productTemplate').html()),
		fIndicatorTemplate : _.template(jQuery('#indicatorTemplate').html()),
		fImageTemplate : _.template(jQuery('#myCarousel1Template').html()),
		fPreviewTemplate: _.template(jQuery('#previewTemplate').html()),
		initialize : function() {
			this.oCategoryList.url = 'categories/';
			this.oCategoryList.fetch({
				success : jQuery.proxy(this.renderNav, this),
				error : function(collection, err) {
					throw err.status + " " + err.statusText;
				}
			});
			return this;
		},
		renderNav: function(){
			this.oCategoryList.models.forEach(function(oCategory) {
				// we append a single cd into the cdlist div
				jQuery("#navPlaceHolder").append(this.fNavTemplate(oCategory.attributes));
			}, this);
			jQuery("#navPlaceHolder").append(this.fNavTemplate({name: 'about', id: 10001}));
			jQuery("#navPlaceHolder").append(this.fNavTemplate({name: 'contact', id: 10002}));
			Backbone.history.start();

		},
		renderImages: function(){
			var nImage = 0;
			jQuery("#myCarousel1PlaceHolder").html("");
			jQuery("#indicatorPlaceHolder").html("");
			this.oImageList.models.forEach(function(oImage) {
				// we append a single image into #myCarousel1
				oImage.set('title', this.oItemList.get(this.nProductId).get('title'));
				var sActiveClass = "";
				if(nImage == 0){
					sActiveClass = 'active';
				}
				oImage.set('activeClass', sActiveClass);
				jQuery("#indicatorPlaceHolder").append(this.fIndicatorTemplate({nImage: nImage, activeClass: sActiveClass}));
				jQuery("#myCarousel1PlaceHolder").append(this.fImageTemplate(oImage.attributes));
				nImage++;
			}, this);
		},
		renderItem: function(){
			var oItem = this.oItemList.get(this.nProductId);
			jQuery('#productPlaceHolder').html(this.fProductTemplate(oItem.attributes));
			this.oImageList.url = 'categories/' + this.nCategoryId + '/products/' + this.nProductId + '/images/';
			this.oImageList.fetch({
				success : jQuery.proxy(this.renderImages, this),
				error : function(collection, err) {
					throw err.status + " " + err.statusText;
				}
			});
		},
		renderItems: function(){
			if(!this.nProductId) this.nProductId = this.oItemList.models[0].id;
			this.renderItem();
			var i = 0;
			var curDiv = null;
			jQuery("#myCarousel2PlaceHolder").html("");
			this.oItemList.models.forEach(function(oItem) {
				if(!(i % 4)){
					// then we need to render an item div
					if(curDiv) jQuery("#myCarousel2PlaceHolder").append(curDiv);
					curDiv = jQuery("

");
					if(i==0){
						curDiv.addClass("active");
					}
				}
				curDiv.append(this.fPreviewTemplate(oItem.attributes));
				i++;
			}, this);
		},
		routes : {
			"about" : "showAbout",
			"contact": "showContact",
			"(:category)(/:productid)" : "showProduct",
		},
		showProduct : function(nCategoryId, nProductId) {
			jQuery("#product").show();
			jQuery("#contact").hide();
			jQuery("#about").hide();
			jQuery("#home").hide();
			if(nCategoryId == null){
				nCategoryId = this.oCategoryList.at(0).id;
			}else if(isNaN(parseInt(nCategoryId))){
				nCategoryId = this.oCategoryList.findWhere({name: nCategoryId}).id;
			}
			this.nProductId = nProductId;
			if(this.nCategoryId != nCategoryId ){
				this.nCategoryId = nCategoryId;
				this.oItemList.url = 'categories/' + nCategoryId + '/products/';
				this.oItemList.fetch({
					success : jQuery.proxy(this.renderItems, this),
					error : function(collection, err) {
						throw err.status + " " + err.statusText;
					}
				});
			}else{
				this.renderItem();
			}
		},
		showAbout: function(){
			jQuery("#product").hide();
			jQuery("#contact").hide();
			jQuery("#about").show();
			jQuery("#home").hide();
		},
		showContact: function(){
			jQuery("#product").hide();
			jQuery("#contact").show();
			jQuery("#about").hide();
			jQuery("#home").hide();
		}
	});

Again there is more code, but again it is not substantially different from what we did in the CD example. The simplest route to look at are the `showAbout` and `showContact` routes. These just hide all but the contents of the relevant div. You will see code at the start of the `showProduct` route that functions similarly. The various `render...` methods render the templates that are defined at the start of the object.


text:
package org.elasticsearch.ingest.processor;

import java.util.Locale;

/**
 * Processor that converts the content of string fields to lowercase.
 * Throws exception is the field is not of type string.
 */

public class LowercaseProcessor extends AbstractStringProcessor {

    public static final String TYPE = "lowercase";

    LowercaseProcessor(String processorTag, String field) {
        super(processorTag, field);
    }

    @Override
    protected String process(String value) {
        return value.toLowerCase(Locale.ROOT);
    }

    @Override
    public String getType() {
        return TYPE;
    }

    public static class Factory extends AbstractStringProcessor.Factory<LowercaseProcessor> {
        @Override
        protected LowercaseProcessor newProcessor(String tag, String field) {
            return new LowercaseProcessor(tag, field);
        }
    }
}


text:
An Account is a unique identity within a [Directory](directory), with a
unique username and/or email address.  An Account can log in to an
[Application](application) using either the email address or username
associated with it.  Accounts can represent your end users (*people*), but
they can also be used to represent services, daemons, processes, or any
"entity" that needs to login to a Stormpath-powered application.

Additionally, an Account may only exist in a single Directory and may be in
multiple Groups owned by that Directory.  Accounts may not be assigned to
groups within other directories.

It should be noted that the words "User" and "Account" usually mean the same
thing, but there is a subtle difference that can be important at times:

* An Account is a unique identity within a Directory.  An Account can exist in
  only a single Directory but can be a part of multiple groups owned by that
  Directory.
* When an Account is granted access to an Application (*by
  [mapping a Directory or Group][] that contains the Account to the
  Application*), it becomes a "User" of that Application.

Therefore an Account can be called a "User" of an Application if/when it can
log into the Application.

An Account resource has predefined fields that are useful to many applications,
but you are likely to have your own custom data that you need to associate with
an Account as well.  You can create your own custom data fields when creating
an Account with [application.createAccount](application#createAccount) or
[directory.createAccount](directory#createAccount).  Custom data can be set
directly on an Account resource or independently.

**Since**: 0.1

---

### method addToGroup(groupOrGroupHref, *[options,]* callback)

Adds the Account to the specified [Group](group).  The Group must have already
been persisted - new groups cannot be created via this method.

#### Usage

You may specify a Group directly:

```javascript
account.addToGroup(group, function(err, membership) {
  console.log(membership);
});
```

Or just an group's `href`:

```javascript
account.addToGroup(groupHref, function(err, membership) {
  console.log(membership);
});
```

In both cases, the [GroupMembership](groupMembership) representing the
group-to-account association will be provided to the callback as the callback's
second parameter.  You can obtain either the Group or the Account via
`membership.group` or `membership.account`, respectively.

#### Parameters

      Parameter
      Type
      Presence
      Description

      `groupOrGroupHref`
      `object` or `string`
      required
      Either a previously-persisted [Group](group) resource or the `href` string of a previously-persisted group.

      _`options`_
      `object`
      _optional_
      Name/value pairs to use as query parameters, for example, for returned resource reference expansion.

      `callback`
      function
      required
      The callback to execute upon server response.  The 1st parameter is an [error](resourceError).  The 2nd parameter is the [GroupMembership](groupMembership) that reflects the group-to-account association. You can obtain either the group or the account via `membership.group` or 'membership.account`, respectively.

#### Returns

If the association fails, the callback's first parameter (`err`) will report
the failure.  If the association succeeds, the
[GroupMembership](groupMembership) will be provided to the `callback` as the
callback's second parameter.  You can obtain either the Group or the Account
via `membership.group` or `membership.account`, respectively.

---

### method createApiKey(callback)

Creates an [Api Key](apiKey) for this account, which can be used to authenticate a request to your service. For more information please read [Using Stormpath to Secure and Manage API Services](http://docs.stormpath.com/guides/securing-your-api/)

#### Usage

````javascript
account.createApiKey(function(err,apiKey){
  console.log(apiKey);
})
````

#### Parameters

      Parameter
      Type
      Presence
      Description

    `callback`
      function
      required

        The function to call when the Api Key has been created,
        will be called with an error or instance of `ApiKey`.

---

### method getApiKeys(*[options,]* callback)

Retrieves a [collection](collectionResource) of the account's [Api Keys](apiKey) and provides the collection to the specified `callback`.
You can pass an `id` property on the `options` object to search for an Api Key by it's id.

When retrieving the API Key from Stormpath, it is doubly encrypted: in transit over SSL by default, but also the API Key secret is additionally encrypted to ensure that nothing before or after SSL transit may even see the secret.  Additionally, API Key secret values remain encrypted if caching is enabled, so you don't have to worry if your cache supports encryption.

This all happens by default; there is nothing you need to configure to obtain these benefits.  However, if you would like to customize the secondary encryption options, you may do so:

For those interested, password-based AES 256 encryption is used: the password is the API Key Secret you used to configure the SDK Client.  The PBKDF2 implementation will use 1024 iterations by default to derive the AES 256 key.  At the risk of potentially decreased security, you can use the `options` argument to specify a lower level of encryption key size, like 192 or 128.  You can also request a lower number of key iterations. This can reduce the CPU time required to decrypt the key after transit or when retrieving from cache. It is not recommended to go much lower than 1024 (if at all) in security sensitive environments.

#### Usage

````javascript
account.getApiKeys(function(err,collectionResult){
  collectionResult.each(function(apiKey){
    console.log(apiKey);
  })
})
````

#### Parameters

      Parameter
      Type
      Presence
      Description

      `options`
      `object`
      optional

An object which allows you to modify the query parameters for this request, the following properties are valid:

`id` - search for a specific key by id

`encryptionKeySize` - Set to `128` or `192` to change the AES key encryption size

`encryptionKeyIterations` - Defaults to `1024`

    `callback`
      function
      required

        The function to call when the request is complete,
        it will be called with an error or a [collection](collectionResource) that contains
        `ApiKey` instances.

---

### method getGroups(*[options,]* callback)

Retrieves a [collection](collectionResource) of the account's assigned
[Group](group)s and provides the collection to the specified `callback`.

If no options are specified, all of the account's groups are retrieved.  If
options (*query parameters*) are specified for a search, only those groups
matching the search will be retrieved.  If the search does not return any
results, the collection will be empty.

#### Usage

If you want to retrieve *all* of the account's groups:

```javascript
account.getGroups(function(err, groups) {
  groups.each(function(group) {
    console.log(group);
  });
});
```

As you can see, the [Collection](collectionResource) provided to the `callback`
has an `each` function that accepts its own callback.  The collection will
iterate over all of the groups in the collection, and invoke the callback for
each one.

If you don't want all groups, and only want specific ones, you can search for
them by specifying the *options* argument with [account group][] search query
parameters:

```javascript
account.getGroups({name: '*bar*'}, function(err, groups) {
  groups.each(function(account) {
    console.log(account);
  });
});
```

The above code example would only print out the account's groups with the text
fragment `bar` in their name.  See the [account group documentation][] for
other supported query parameters, such as reference expansion.

#### Parameters

      Parameter
      Type
      Presence
      Description

      *`options`*
      `object`
      *optional*
      Name/value pairs to use as query parameters, for example, for [account group](http://docs.stormpath.com/rest/product-guide/#account-groups) search or reference expansion.

    `callback`
      function
      required
      The callback to execute upon resource retrieval. The 1st parameter is an `Error` object.  The 2nd parameter is a [collection](collectionResource) containing zero or more [Group](group) resources.

#### Returns

The retrieved collection of [Group](group)s will be provided to the `callback`
as the callback's second parameter.

---

### method getGroupMemberships(*[options,]* callback)

Retrieves a [collection](collectionResource) of the account's
[GroupMembership](groupMembership)s and provides the collection to the
specified `callback`.

If no options are specified, all of the account's groupMemberships are
retrieved.  If options (*query parameters*) are specified for expansion, the
returned memberships will have references expanded as necessary.

#### Usage

If you want to retrieve all of the group's memberships/associations:

```javascript
account.getGroupMemberships(function(err, memberships) {
  memberships.each(function(membership) {
    console.log(membership);
  });
});
```

As you can see, the [Collection](collectionResource) provided to the `callback`
has an `each` function that accepts its own callback.  The collection will
iterate over all of the memberships in the collection, and invoke the callback
for each one.

If you want the returned memberships to have their groups expanded (*so you can
access the membership and its associated group*), you can specify an `expand`
query parameter:

```javascript
account.getGroupMemberships({expand: 'group'}, function(err, memberships) {
  memberships.each(function(membership) {
    console.log(membership);
    console.log(membership.group);
  });
});
```

#### Parameters

      Parameter
      Type
      Presence
      Description

      *`options`*
      `object`
      *optional*
      Name/value pairs to use as query parameters, for example, for reference expansion.

    `callback`
      function
      required
      The callback to execute upon resource retrieval.  The 1st parameter is an `Error` object.  The 2nd parameter is a [collection](collectionResource) containing zero or more [GroupMembership](groupMembership) resources.

#### Returns

The retrieved [collection](collectionResource) of the account's
[GroupMembership](groupMembership)s will be provided to the `callback` as the
callback's second parameter.

---

### method getDirectory(*[options,]* callback)

Retrieves the account's parent [Directory](directory) and provides it to the
specified `callback`.

#### Usage

```javascript
account.getDirectory(function(err, directory) {
  console.log(directory);
});
```

You can also use [resource expansion][] options (*query params*) to obtain
linked resources in the same request:

```javascript
account.getDirectory({expand:'groups'}, function(err, directory) {
  console.log(directory);
});
```

#### Parameters

      Parameter
      Type
      Presence
      Description

      _`options`_
      `object`
      _optional_
      Name/value pairs to use as query parameters, for example, for [resource expansion](http://docs.stormpath.com/rest/product-guide/#link-expansion).

      `callback`
      function
      required
      The callback to execute upon resource retrieval. The 1st parameter is an `Error` object.  The 2nd parameter is the retrieved [Directory](directory) resource.

#### Returns

The retrieved [Directory](directory) resource will be provided to the `callback`
as the callback's second parameter.

---

### method getTenant(*[options,]* callback)

Retrieves the account's owning [Tenant](tenant) and provides it to the
specified `callback`.

#### Usage

```javascript
account.getTenant(function(err, tenant) {
  console.log(tenant);
});
```

You can also use [resource expansion][] options (*query params*) to obtain
linked resources in the same request:

```javascript
account.getTenant({expand:'applications'}, function(err, tenant) {
  console.log(tenant);
  tenant.applications.each(function(application) {
    console.log(application);
  });
});
```

#### Parameters

      Parameter
      Type
      Presence
      Description

      _`options`_
      `object`
      _optional_
      Name/value pairs to use as query parameters, for example, for [resource expansion](http://docs.stormpath.com/rest/product-guide/#link-expansion).

      `callback`
      function
      required
      The callback to execute upon resource retrieval. The 1st parameter is an `Error` object.  The 2nd parameter is the retrieved [Tenant](tenant) resource.

#### Returns

The retrieved `Tenant` resource will be provided to the `callback` as the
callback's second parameter.

---

### method getCustomData(*[options,]* callback)

Retrieves the [CustomData](customData) resource of the `Account` and provides
it to the specified `callback`.

#### Usage

```javascript
account.getCustomData(function(err, customData) {
  console.log(customData);
});
```

#### Parameters

      Parameter
      Type
      Presence
      Description

      options
      object
      optional
      An object literal of name/value pairs to use as query parameters, for example, [resource expansion](http://docs.stormpath.com/rest/product-guide/#account-retrieve).

      callback
      function
      required
      The callback to execute upon resource retrieval.
       The 1st parameter is an `Error` object.
       The 2nd parameter is the retrieved [CustomData](customData) resource.

#### Returns

The retrieved `CustomData` resource will be provided to the `callback` as the
callback's second parameter.

---

### method getProviderData(*[options,]* callback)

Retrieves the account's `providerData` information and provides it to the
specified `callback`.  If `providerData` not set, `callback` will be called
without parameters

#### Usage

```javascript
account.getProviderData(function(err, providerData) {
  console.log(providerData);
});
```

#### Parameters

      Parameter
      Type
      Presence
      Description

      _`options`_
      `object`
      _optional_
      Name/value pairs to use as query parameters, for example, for [resource expansion](http://docs.stormpath.com/rest/product-guide/#link-expansion).

      `callback`
      function
      required
      The callback to execute upon resource retrieval.
        The 1st parameter is an `Error` object.
        The 2nd parameter is the retrieved `ProviderData` resource.

#### Returns

The retrieved `providerData` resource will be provided to the `callback` as the
callback's second parameter.

---

  [mapping a Directory or Group]: http://docs.stormpath.com/rest/product-guide/#account-store-mappings "Stormpath Account Store Mappings"
  [account group]: http://docs.stormpath.com/rest/product-guide/#account-groups "Stormpath Account Groups"
  [account group documentation]: http://docs.stormpath.com/rest/product-guide/#account-groups "Stormpath Account Group Documentation"
  [resource expansion]: http://docs.stormpath.com/rest/product-guide/#link-expansion "Stormpath Resource Expansion"


text:
/*
 * @version: 1.1 March 2014
 * @autor: Sascha Peukert
 */

package de.ifsr.trafficwidget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

public class MyWidgetProvider extends AppWidgetProvider {

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

		// Get all ids
		ComponentName thisWidget = new ComponentName(context,
				MyWidgetProvider.class);
		int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
		// Build the intent to call the service
		Intent intent = new Intent(context.getApplicationContext(),
				UpdateWidgetService.class);
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

		// Update the widgets via the service
		context.startService(intent);

	}
}


text:
'use strict'

import { Fact } from '../src/index'

describe('Fact', () => {
  describe('Fact::constructor', () => {
    function subject (id, definition, options) {
      return new Fact(id, definition, options)
    }

    it('works for constant facts', () => {
      let fact = subject('factId', 10)
      expect(fact.id).to.equal('factId')
      expect(fact.value).to.equal(10)
    })

    it('works for dynamic facts', () => {
      let fact = subject('factId', () => 10)
      expect(fact.id).to.equal('factId')
      expect(fact.calculate()).to.equal(10)
    })

    it('allows options to be passed', () => {
      let opts = { test: true, cache: false }
      let fact = subject('factId', 10, opts)
      expect(fact.options).to.eql(opts)
    })

    describe('validations', () => {
      it('throws if no id provided', () => {
        expect(subject).to.throw(/factId required/)
      })

      it('throws if no definition provided', () => {
        expect(subject.bind(null, 'factId')).to.throw(/facts must have a value or method/)
      })
    })
  })
})


text:
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Threading;

namespace Ripper
{
    using Ripper.Core.Components;
    using Ripper.Core.Objects;

    ///
    /// Worker class to get images from ImageCrack.com
    ///
    public class ImageCrack : ServiceTemplate
    {
        public ImageCrack(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable)
            : base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable)
        {
            // Add constructor logic here
        }

        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return true;
            }

            var strFilePath = string.Empty;

            var CCObj = new CacheObject();
            CCObj.IsDownloaded = false;
            CCObj.FilePath = strFilePath;
            CCObj.Url = strImgURL;
            try
            {
                this.EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return true;
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return false;
                }
                else
                {
                    this.EventTable.Add(strImgURL, CCObj);
                }
            }

            var strIVPage = this.GetImageHostPage(ref strImgURL);

            if (strIVPage.Length < 10)
            {
                return false;
            }

            var strNewURL = string.Empty;
            strNewURL = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1);

            var iStartIMG = 0;
            var iStartSRC = 0;
            var iEndSRC = 0;
            iStartIMG = strIVPage.IndexOf("
<img ");

            if (iStartIMG < 0)
            {
                return false;
            }

            iStartSRC = strIVPage.IndexOf("src='", iStartIMG);

            if (iStartSRC < 0)
            {
                return false;
            }

            iStartSRC += 5;

            iEndSRC = strIVPage.IndexOf("' id=thepic", iStartSRC);

            if (iEndSRC < 0)
            {
                return false;
            }

            strNewURL = strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC);

            strFilePath = strNewURL.Substring(strNewURL.LastIndexOf("/") + 1);

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            try
            {
                if (!Directory.Exists(this.SavePath))
                    Directory.CreateDirectory(this.SavePath);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return false;
            }

            //////////////////////////////////////////////////////////////////////////
            HttpWebRequest lHttpWebRequest;
            HttpWebResponse lHttpWebResponse;
            Stream lHttpWebResponseStream;

            // FileStream lFileStream = new FileStream(strFilePath, FileMode.Create);

            // int bytesRead;
            try
            {
                lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strNewURL);

                lHttpWebRequest.UserAgent =
                    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6";
                lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5");
                lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate");
                lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                lHttpWebRequest.Referer = strImgURL;
                lHttpWebRequest.Accept = "image/png,*/*;q=0.5";
                lHttpWebRequest.KeepAlive = true;

                lHttpWebResponse = (HttpWebResponse)lHttpWebRequest.GetResponse();
                lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream();

                if (lHttpWebResponse.ContentType.IndexOf("image") < 0)
                {
                    // if (lFileStream != null)
                    // 	lFileStream.Close();
                    return false;
                }

                if (lHttpWebResponse.ContentType.ToLower() == "image/jpeg")
                    strFilePath += ".jpg";
                else if (lHttpWebResponse.ContentType.ToLower() == "image/gif")
                    strFilePath += ".gif";
                else if (lHttpWebResponse.ContentType.ToLower() == "image/png")
                    strFilePath += ".png";

                var NewAlteredPath = Utility.GetSuitableName(strFilePath);
                if (strFilePath != NewAlteredPath)
                {
                    strFilePath = NewAlteredPath;
                    ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
                }

                lHttpWebResponseStream.Close();

                var client = new WebClient();
                client.Headers.Add("Accept-Language: en-us,en;q=0.5");
                client.Headers.Add("Accept-Encoding: gzip,deflate");
                client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add(
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);

                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return true;
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return true;
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return false;
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;

            // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic =
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return true;
        }

        //////////////////////////////////////////////////////////////////////////

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:spring="http://www.springframework.org/schema/beans"
      xmlns:http="http://www.mulesoft.org/schema/mule/http"
      xmlns:vm="http://www.mulesoft.org/schema/mule/vm"
      xmlns:protobuf="http://www.mulesoft.org/schema/mule/protobuf"
      xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting"
      xsi:schemaLocation="http://wPutww.springframework.org/schema/beans
      classpath:org/springframework/beans/factory/xml/spring-beans-3.0.xsd
        http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
        http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
        http://www.mulesoft.org/schema/mule/protobuf http://www.mulesoft.org/schema/mule/protobuf/current/mule-protobuf.xsd
        http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd
        http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd">
    <description>
    This configuration uses REST services and ZeroMQ endpoints to receive
    requests.
    </description>

    <configuration>
    <default-threading-profile maxThreadsActive="3"/>
    </configuration>

    <custom-transformer name="ExceptionToString" class="com.msi.tough.workflow.core.ExceptionToString"/>
    <custom-transformer name="ExceptionToErrorResponse" class="com.msi.tough.workflow.core.ExceptionToErrorResponse"/>
    <custom-transformer name="HttpRequestToParameter" class="org.mule.transport.servlet.transformers.HttpRequestToParameter"/>
    <custom-transformer name="ObjectToString" class="org.mule.transformer.simple.ObjectToString"/>

    <spring:bean id="muleWorkflow" factory-method="getInstance"
    class="com.msi.tough.workflow.core.MuleWorkflow">
    </spring:bean>
    <spring:bean id="zmqReturnProcessor" factory-method="getInstance"
    destroy-method="destroy"
    class="com.msi.tough.workflow.core.RemoteWorkflowResponder">
    </spring:bean>

    <!-- Global exception strategy; return an error response to requestor -->
    <custom-exception-strategy name="sendErrorBack" class="com.msi.tough.workflow.core.MuleExceptionStrategy">
            <outbound-endpoint ref="SystemErrorHandlerIn"/>
    </custom-exception-strategy>

    <!-- Global exception strategy; record abnormal termination of async tasks -->
    <!-- TODO: async error recording -->

    <!-- === Zero MQ processing === -->
    <flow name="ZMQEntry">
        <inbound-endpoint ref="DirectToZMQEntry"/>
        <set-session-variable variableName="returnAddress" value="#[payload[1]]"/>
        <expression-transformer evaluator="groovy" expression="payload[0]"/>
        <first-successful>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.CreateAutoScalingGroupMessage$CreateAutoScalingGroupRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.CreateLaunchConfigurationMessage$CreateLaunchConfigurationRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DeleteAutoScalingGroupMessage$DeleteAutoScalingGroupRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DeletePolicyMessage$DeletePolicyRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DescribeAdjustmentTypesMessage$DescribeAdjustmentTypesRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DescribeAutoScalingGroupsMessage$DescribeAutoScalingGroupsRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DescribeAutoScalingInstancesMessage$DescribeAutoScalingInstancesRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DescribeLaunchConfigurationsMessage$DescribeLaunchConfigurationsRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DescribePoliciesMessage$DescribePoliciesRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DescribeScalingActivitiesMessage$DescribeScalingActivitiesRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DescribeScalingProcessTypesMessage$DescribeScalingProcessTypesRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.DescribeTerminationPolicyTypesMessage$DescribeTerminationPolicyTypesRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.ExecutePolicyMessage$ExecutePolicyRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.PutScalingPolicyMessage$PutScalingPolicyRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.PutScheduledUpdateGroupActionMessage$PutScheduledUpdateGroupActionRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.ResumeProcessesMessage$ResumeProcessesRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.SetDesiredCapacityMessage$SetDesiredCapacityRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.SetInstanceHealthMessage$SetInstanceHealthRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.SuspendProcessesMessage$SuspendProcessesRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.TerminateInstanceInAutoScalingGroupMessage$TerminateInstanceInAutoScalingGroupRequestMessage"/>
            <protobuf:deserialize protobufClass="com.transcend.autoscale.message.UpdateAutoScalingGroupMessage$UpdateAutoScalingGroupRequestMessage"/>
        </first-successful>
        <log-component />
        <flow-ref name="ActionEntry"/>
        <catch-exception-strategy>
            <outbound-endpoint ref="SystemErrorHandlerIn"/>
        </catch-exception-strategy>
    </flow>

    <!-- === Standard Action entry point processing === -->
    <flow name="ActionEntry">
        <inbound-endpoint ref="ActionIn"/>
        <log-component />
        <choice>
            <when expression="payload instanceof com.transcend.autoscale.message.CreateAutoScalingGroupMessage$CreateAutoScalingGroupRequestMessage" evaluator="groovy">
                <flow-ref name="CreateAutoScalingGroupRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.CreateLaunchConfigurationMessage$CreateLaunchConfigurationRequestMessage" evaluator="groovy">
                <flow-ref name="CreateLaunchConfigurationRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DeleteAutoScalingGroupMessage$DeleteAutoScalingGroupRequestMessage" evaluator="groovy">
                <flow-ref name="DeleteAutoScalingGroupRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DeletePolicyMessage$DeletePolicyRequestMessage" evaluator="groovy">
                <flow-ref name="DeletePolicyRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DescribeAdjustmentTypesMessage$DescribeAdjustmentTypesRequestMessage" evaluator="groovy">
                <flow-ref name="DescribeAdjustmentTypesRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DescribeAutoScalingGroupsMessage$DescribeAutoScalingGroupsRequestMessage" evaluator="groovy">
                <flow-ref name="DescribeAutoScalingGroupsRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DescribeAutoScalingInstancesMessage$DescribeAutoScalingInstancesRequestMessage" evaluator="groovy">
                <flow-ref name="DescribeAutoScalingInstancesRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DescribeLaunchConfigurationsMessage$DescribeLaunchConfigurationsRequestMessage" evaluator="groovy">
                <flow-ref name="DescribeLaunchConfigurationsRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DescribePoliciesMessage$DescribePoliciesRequestMessage" evaluator="groovy">
                <flow-ref name="DescribePoliciesRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DescribeScalingActivitiesMessage$DescribeScalingActivitiesRequestMessage" evaluator="groovy">
                <flow-ref name="DescribeScalingActivitiesRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DescribeScalingProcessTypesMessage$DescribeScalingProcessTypesRequestMessage" evaluator="groovy">
                <flow-ref name="DescribeScalingProcessTypesRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.DescribeTerminationPolicyTypesMessage$DescribeTerminationPolicyTypesRequestMessage" evaluator="groovy">
                <flow-ref name="DescribeTerminationPolicyTypesRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.ExecutePolicyMessage$ExecutePolicyRequestMessage" evaluator="groovy">
                <flow-ref name="ExecutePolicyRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.PutScalingPolicyMessage$PutScalingPolicyRequestMessage" evaluator="groovy">
                <flow-ref name="PutScalingPolicyRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.PutScheduledUpdateGroupActionMessage$PutScheduledUpdateGroupActionRequestMessage" evaluator="groovy">
                <flow-ref name="PutScheduledUpdateGroupActionRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.ResumeProcessesMessage$ResumeProcessesRequestMessage" evaluator="groovy">
                <flow-ref name="ResumeProcessesRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.SetDesiredCapacityMessage$SetDesiredCapacityRequestMessage" evaluator="groovy">
                <flow-ref name="SetDesiredCapacityRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.SetInstanceHealthMessage$SetInstanceHealthRequestMessage" evaluator="groovy">
                <flow-ref name="SetInstanceHealthRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.SuspendProcessesMessage$SuspendProcessesRequestMessage" evaluator="groovy">
                <flow-ref name="SuspendProcessesRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.TerminateInstanceInAutoScalingGroupMessage$TerminateInstanceInAutoScalingGroupRequestMessage" evaluator="groovy">
                <flow-ref name="TerminateInstanceInAutoScalingGroupRequest"/>
            </when>
            <when expression="payload instanceof com.transcend.autoscale.message.UpdateAutoScalingGroupMessage$UpdateAutoScalingGroupRequestMessage" evaluator="groovy">
                <flow-ref name="UpdateAutoScalingGroupRequest"/>
            </when>
            <otherwise>
                <flow-ref name="SystemErrorHandler"/>
            </otherwise>
        </choice>
    </flow>

    <!-- Request/Response flow for CreateAutoScalingGroup -->

    <flow name="CreateAutoScalingGroupRequest">
        <component>
            <spring-object bean="CreateAutoScalingGroupWorker"/>
        </component>

        <flow-ref name="CreateAutoScalingGroupResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="CreateAutoScalingGroupResponse" >
        <component>
            <spring-object bean="CreateAutoScalingGroup"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <!-- Request/Response flow for CreateLaunchConfiguration -->
     <flow name="CreateLaunchConfigurationRequest">
        <component>
            <spring-object bean="CreateLaunchConfigurationWorker"/>
        </component>

        <flow-ref name="CreateLaunchConfigurationResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <flow name="CreateLaunchConfigurationResponse" >
        <component>
            <spring-object bean="CreateLaunchConfiguration"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <!-- Request/Response flow for DeleteAutoScalingGroup -->
     <flow name="DeleteAutoScalingGroupRequest">
        <component>
            <spring-object bean="DeleteAutoScalingGroupWorker"/>
        </component>

        <flow-ref name="DeleteAutoScalingGroupResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <flow name="DeleteAutoScalingGroupResponse" >
        <component>
            <spring-object bean="DeleteAutoScalingGroup"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <!-- Request/Response flow for DeletePolicy -->
     <flow name="DeletePolicyRequest">
        <component>
            <spring-object bean="DeletePolicyWorker"/>
        </component>

        <flow-ref name="DeletePolicyResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <flow name="DeletePolicyResponse" >
        <component>
            <spring-object bean="DeletePolicy"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

   <!-- Request/Response flow for DescribeAdjustmentTypes -->
     <flow name="DescribeAdjustmentTypesRequest">
        <component>
            <spring-object bean="DescribeAdjustmentTypesWorker"/>
        </component>

        <flow-ref name="DescribeAdjustmentTypesResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <flow name="DescribeAdjustmentTypesResponse" >
        <component>
            <spring-object bean="DescribeAdjustmentTypes"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <!-- Request/Response flow for DescribeAutoScalingGroups -->
     <flow name="DescribeAutoScalingGroupsRequest">
        <component>
            <spring-object bean="DescribeAutoScalingGroupsWorker"/>
        </component>

        <flow-ref name="DescribeAutoScalingGroupsResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <flow name="DescribeAutoScalingGroupsResponse" >
        <component>
            <spring-object bean="DescribeAutoScalingGroups"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <!-- Request/Response flow for DescribeAutoScalingInstances -->
     <flow name="DescribeAutoScalingInstancesRequest">
        <component>
            <spring-object bean="DescribeAutoScalingInstancesWorker"/>
        </component>

        <flow-ref name="DescribeAutoScalingInstancesResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <flow name="DescribeAutoScalingInstancesResponse" >
        <component>
            <spring-object bean="DescribeAutoScalingInstances"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

   <!-- Request/Response flow for DescribeLaunchConfigurations -->
     <flow name="DescribeLaunchConfigurationsRequest">
        <component>
            <spring-object bean="DescribeLaunchConfigurationsWorker"/>
        </component>

        <flow-ref name="DescribeLaunchConfigurationsResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

     <flow name="DescribeLaunchConfigurationsResponse" >
        <component>
            <spring-object bean="DescribeLaunchConfigurations"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

   <!-- Request/Response flow for DescribePolicies -->

    <flow name="DescribePoliciesRequest">
        <component>
            <spring-object bean="DescribePoliciesWorker"/>
        </component>

        <flow-ref name="DescribePoliciesResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="DescribePoliciesResponse" >
        <component>
            <spring-object bean="DescribePolicies"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

   <!-- Request/Response flow for DescribeScalingActivities -->

    <flow name="DescribeScalingActivitiesRequest">
        <component>
            <spring-object bean="DescribeScalingActivitiesWorker"/>
        </component>

        <flow-ref name="DescribeScalingActivitiesResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="DescribeScalingActivitiesResponse" >
        <component>
            <spring-object bean="DescribeScalingActivities"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

   <!-- Request/Response flow for DescribeScalingProcessTypes -->

    <flow name="DescribeScalingProcessTypesRequest">
        <component>
            <spring-object bean="DescribeScalingProcessTypesWorker"/>
        </component>

        <flow-ref name="DescribeScalingProcessTypesResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="DescribeScalingProcessTypesResponse" >
        <component>
            <spring-object bean="DescribeScalingProcessTypes"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

   <!-- Request/Response flow for DescribeTerminationPolicyTypes -->

    <flow name="DescribeTerminationPolicyTypesRequest">
        <component>
            <spring-object bean="DescribeTerminationPolicyTypesWorker"/>
        </component>

        <flow-ref name="DescribeTerminationPolicyTypesResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="DescribeTerminationPolicyTypesResponse" >
        <component>
            <spring-object bean="DescribeTerminationPolicyTypes"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <!-- Request/Response flow for ExecutePolicy -->

    <flow name="ExecutePolicyRequest">
        <component>
            <spring-object bean="ExecutePolicyWorker"/>
        </component>

        <flow-ref name="ExecutePolicyResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="ExecutePolicyResponse" >
        <component>
            <spring-object bean="ExecutePolicy"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <!-- Request/Response flow for PutScalingPolicy -->

    <flow name="PutScalingPolicyRequest">
        <component>
            <spring-object bean="PutScalingPolicyWorker"/>
        </component>

        <flow-ref name="PutScalingPolicyResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="PutScalingPolicyResponse" >
        <component>
            <spring-object bean="PutScalingPolicy"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

   <!-- Request/Response flow for PutScheduledUpdateGroupAction -->

    <flow name="PutScheduledUpdateGroupActionRequest">
        <component>
            <spring-object bean="PutScheduledUpdateGroupActionWorker"/>
        </component>

        <flow-ref name="PutScheduledUpdateGroupActionResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="PutScheduledUpdateGroupActionResponse" >
        <component>
            <spring-object bean="PutScheduledUpdateGroupAction"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

   <!-- Request/Response flow for ResumeProcesses -->

    <flow name="ResumeProcessesRequest">
        <component>
            <spring-object bean="ResumeProcessesWorker"/>
        </component>

        <flow-ref name="ResumeProcessesResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="ResumeProcessesResponse" >
        <component>
            <spring-object bean="ResumeProcesses"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <!-- Request/Response flow for SetDesiredCapacity -->

    <flow name="SetDesiredCapacityRequest">
        <component>
            <spring-object bean="SetDesiredCapacityWorker"/>
        </component>

        <flow-ref name="SetDesiredCapacityResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="SetDesiredCapacityResponse" >
        <component>
            <spring-object bean="SetDesiredCapacity"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

   <!-- Request/Response flow for SetInstanceHealth -->

    <flow name="SetInstanceHealthRequest">
        <component>
            <spring-object bean="SetInstanceHealthWorker"/>
        </component>

        <flow-ref name="SetInstanceHealthResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="SetInstanceHealthResponse" >
        <component>
            <spring-object bean="SetInstanceHealth"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <!-- Request/Response flow for SuspendProcesses -->

    <flow name="SuspendProcessesRequest">
        <component>
            <spring-object bean="SuspendProcessesWorker"/>
        </component>

        <flow-ref name="SuspendProcessesResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="SuspendProcessesResponse" >
        <component>
            <spring-object bean="SuspendProcesses"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <!-- Request/Response flow for UpdateAutoScalingGroup -->

    <flow name="UpdateAutoScalingGroupRequest">
        <component>
            <spring-object bean="UpdateAutoScalingGroupWorker"/>
        </component>

        <flow-ref name="UpdateAutoScalingGroupResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="UpdateAutoScalingGroupResponse" >
        <component>
            <spring-object bean="UpdateAutoScalingGroup"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <!-- Request/Response flow for TerminateInstanceInAutoScalingGroup -->

    <flow name="TerminateInstanceInAutoScalingGroupRequest">
        <component>
            <spring-object bean="TerminateInstanceInAutoScalingGroupWorker"/>
        </component>

        <flow-ref name="TerminateInstanceInAutoScalingGroupResponse"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <flow name="TerminateInstanceInAutoScalingGroupResponse" >
        <component>
            <spring-object bean="TerminateInstanceInAutoScalingGroup"/>
        </component>

        <flow-ref name="ClientResponder"/>
        <exception-strategy ref="sendErrorBack"/>
    </flow>

    <!-- General system flows -->

    <flow name="ZMQResponder">
        <log-component />
        <processor ref="zmqReturnProcessor"/>
    </flow>

    <flow name="ClientResponder">
        <component>
            <spring-object bean="autoscaleServiceAsync"/>
        </component>
    </flow>

    <!-- Handle any unexpected errors. Errors could also be routed elsewhere,
        e.g. into an error file, send via email to a list, stored in a database, etc. -->
    <flow name="SystemErrorHandler">
        <inbound-endpoint ref="SystemErrorHandlerIn"/>
        <choice>
            <when expression="#[org.mule.util.StringUtils.isNotEmpty(sessionVars['returnAddress'])]">
                <flow-ref name="ZMQResponder"/>
            </when>
            <otherwise>
                <flow-ref name="ClientResponder"/>
            </otherwise>
        </choice>
    </flow>

</mule>


text:
namespace chrome {
namespace android {

ReaderModeSceneLayer::ReaderModeSceneLayer(JNIEnv* env, jobject jobj)
    : SceneLayer(env, jobj) {
}

ReaderModeSceneLayer::~ReaderModeSceneLayer() {
}

void ReaderModeSceneLayer::CreateReaderModeLayer(
    JNIEnv* env,
    const JavaParamRef<jobject>& object,
    const JavaParamRef<jobject>& jresource_manager) {
  ui::ResourceManager* resource_manager =
      ui::ResourceManagerImpl::FromJavaObject(jresource_manager);
  reader_mode_layer_ = ReaderModeLayer::Create(resource_manager);
  layer_->AddChild(reader_mode_layer_->layer());
}

void ReaderModeSceneLayer::SetResourceIds(
    JNIEnv* env,
    const JavaParamRef<jobject>& object,
    jint text_resource_id,
    jint bar_background_resource_id,
    jint bar_shadow_resource_id,
    jint panel_icon_resource_id,
    jint close_icon_resource_id) {

  reader_mode_layer_->SetResourceIds(
      text_resource_id,
      bar_background_resource_id,
      bar_shadow_resource_id,
      panel_icon_resource_id,
      close_icon_resource_id);
}

void ReaderModeSceneLayer::Update(
    JNIEnv* env,
    const JavaParamRef<jobject>& object,
    jfloat dp_to_px,
    const JavaParamRef<jobject>& jcontent_view_core,
    jfloat panel_X,
    jfloat panel_y,
    jfloat panel_width,
    jfloat panel_height,
    jfloat bar_margin_side,
    jfloat bar_height,
    jfloat text_opacity,
    jboolean bar_border_visible,
    jfloat bar_border_height,
    jboolean bar_shadow_visible,
    jfloat bar_shadow_opacity) {
  // NOTE(mdjones): It is possible to render the panel before content has been
  // created. If this is the case, do not attempt to access the ContentViewCore
  // and instead pass null.
  content::ContentViewCore* content_view_core =
      !jcontent_view_core ? NULL
                          : content::ContentViewCore::GetNativeContentViewCore(
                                env, jcontent_view_core);

  reader_mode_layer_->SetProperties(
      dp_to_px,
      content_view_core,
      panel_X,
      panel_y,
      panel_width,
      panel_height,
      bar_margin_side,
      bar_height,
      text_opacity,
      bar_border_visible,
      bar_border_height,
      bar_shadow_visible,
      bar_shadow_opacity);
}

static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& jobj) {
  // This will automatically bind to the Java object and pass ownership there.
  ReaderModeSceneLayer* reader_mode_scene_layer =
      new ReaderModeSceneLayer(env, jobj);
  return reinterpret_cast<intptr_t>(reader_mode_scene_layer);
}

bool RegisterReaderModeSceneLayer(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

}  // namespace android
}  // namespace chrome


text:
class Follow < ActiveRecord::Base
  belongs_to :follower, foreign_key: 'follower_id', class_name: 'User'
  belongs_to :following, foreign_key: 'following_id', class_name: 'User'
end


text:
      <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Konto</button>

 Action

 Separated link


text:
namespace blink {

NGCustomLayoutAlgorithm::NGCustomLayoutAlgorithm(
    const NGLayoutAlgorithmParams& params)
    : NGLayoutAlgorithm(params), params_(params) {
  DCHECK(params.space.IsNewFormattingContext());
}

MinMaxSizesResult NGCustomLayoutAlgorithm::ComputeMinMaxSizes(
    const MinMaxSizesFloatInput& input) {
  if (!Node().IsCustomLayoutLoaded())
    return FallbackMinMaxSizes(input);

  ScriptForbiddenScope::AllowUserAgentScript allow_script;
  CustomLayoutScope scope;

  const AtomicString& name = Style().DisplayLayoutCustomName();
  const Document& document = Node().GetDocument();
  LayoutWorklet* worklet = LayoutWorklet::From(*document.domWindow());
  CSSLayoutDefinition* definition = worklet->Proxy()->FindDefinition(name);

  // TODO(ikilpatrick): Cache the instance of the layout class.
  CSSLayoutDefinition::Instance* instance = definition->CreateInstance();

  if (!instance) {
    // TODO(ikilpatrick): Report this error to the developer.
    return FallbackMinMaxSizes(input);
  }

  bool depends_on_block_constraints = false;
  IntrinsicSizesResultOptions* intrinsic_sizes_result_options = nullptr;
  LogicalSize border_box_size{
      container_builder_.InlineSize(),
      ComputeBlockSizeForFragment(
          ConstraintSpace(), Style(), BorderPadding(),
          CalculateDefaultBlockSize(ConstraintSpace(), Node(), BreakToken(),
                                    BorderScrollbarPadding()),
          container_builder_.InlineSize())};
  if (!instance->IntrinsicSizes(
          ConstraintSpace(), document, Node(), border_box_size,
          BorderScrollbarPadding(), ChildAvailableSize().block_size, &scope,
          &intrinsic_sizes_result_options, &depends_on_block_constraints)) {
    // TODO(ikilpatrick): Report this error to the developer.
    return FallbackMinMaxSizes(input);
  }

  MinMaxSizes sizes;
  sizes.max_size = LayoutUnit::FromDoubleRound(
      intrinsic_sizes_result_options->maxContentSize());
  sizes.min_size = std::min(
      sizes.max_size, LayoutUnit::FromDoubleRound(
                          intrinsic_sizes_result_options->minContentSize()));

  sizes.min_size.ClampNegativeToZero();
  sizes.max_size.ClampNegativeToZero();

  return MinMaxSizesResult(sizes, depends_on_block_constraints);
}

const NGLayoutResult* NGCustomLayoutAlgorithm::Layout() {
  DCHECK(!IsResumingLayout(BreakToken()));

  if (!Node().IsCustomLayoutLoaded())
    return FallbackLayout();

  ScriptForbiddenScope::AllowUserAgentScript allow_script;
  CustomLayoutScope scope;

  const AtomicString& name = Style().DisplayLayoutCustomName();
  const Document& document = Node().GetDocument();
  LayoutWorklet* worklet = LayoutWorklet::From(*document.domWindow());
  CSSLayoutDefinition* definition = worklet->Proxy()->FindDefinition(name);

  // TODO(ikilpatrick): Cache the instance of the layout class.
  CSSLayoutDefinition::Instance* instance = definition->CreateInstance();

  if (!instance) {
    // TODO(ikilpatrick): Report this error to the developer.
    return FallbackLayout();
  }

  FragmentResultOptions* fragment_result_options = nullptr;
  scoped_refptr<SerializedScriptValue> fragment_result_data;
  LogicalSize border_box_size{
      container_builder_.InlineSize(),
      ComputeBlockSizeForFragment(
          ConstraintSpace(), Style(), BorderPadding(),
          CalculateDefaultBlockSize(ConstraintSpace(), Node(), BreakToken(),
                                    BorderScrollbarPadding()),
          container_builder_.InlineSize())};
  if (!instance->Layout(ConstraintSpace(), document, Node(), border_box_size,
                        BorderScrollbarPadding(), &scope,
                        fragment_result_options, &fragment_result_data)) {
    // TODO(ikilpatrick): Report this error to the developer.
    return FallbackLayout();
  }

  const HeapVector<Member<CustomLayoutFragment>>& child_fragments =
      fragment_result_options->childFragments();

  NGLayoutInputNode child = Node().FirstChild();
  for (auto fragment : child_fragments) {
    if (!fragment->IsValid()) {
      // TODO(ikilpatrick): Report this error to the developer.
      return FallbackLayout();
    }

    AddAnyOutOfFlowPositionedChildren(&child);

    // TODO(ikilpatrick): Implement paint order. This should abort this loop,
    // and go into a "slow" loop which allows developers to control the paint
    // order of the children.
    if (!child || child != fragment->GetLayoutNode()) {
      // TODO(ikilpatrick): Report this error to the developer.
      return FallbackLayout();
    }

    // TODO(ikilpatrick): At this stage we may need to perform a re-layout on
    // the given child. (The LayoutFragment may have been produced from a
    // different LayoutFragmentRequest).

    LayoutUnit inline_offset =
        LayoutUnit::FromDoubleRound(fragment->inlineOffset());
    LayoutUnit block_offset =
        LayoutUnit::FromDoubleRound(fragment->blockOffset());
    container_builder_.AddResult(fragment->GetLayoutResult(),
                                 {inline_offset, block_offset});

    child = child.NextSibling();
  }

  // We've exhausted the inflow fragments list, but we may still have
  // OOF-positioned children to add to the fragment builder.
  AddAnyOutOfFlowPositionedChildren(&child);

  // Currently we only support exactly one LayoutFragment per LayoutChild.
  if (child) {
    // TODO(ikilpatrick): Report this error to the developer.
    return FallbackLayout();
  }

  // Compute the final block-size.
  LayoutUnit auto_block_size = std::max(
      BorderScrollbarPadding().BlockSum(),
      LayoutUnit::FromDoubleRound(fragment_result_options->autoBlockSize()));
  LayoutUnit block_size = ComputeBlockSizeForFragment(
      ConstraintSpace(), Style(), BorderPadding(), auto_block_size,
      container_builder_.InitialBorderBoxSize().inline_size);

  // TODO(ikilpatrick): Allow setting both the first/last baseline instead of a
  // general baseline.
  if (fragment_result_options->hasBaseline()) {
    LayoutUnit baseline =
        LayoutUnit::FromDoubleRound(fragment_result_options->baseline());
    container_builder_.SetBaselines(baseline);
  }

  container_builder_.SetCustomLayoutData(std::move(fragment_result_data));
  container_builder_.SetIntrinsicBlockSize(auto_block_size);
  container_builder_.SetFragmentsTotalBlockSize(block_size);

  NGOutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run();

  return container_builder_.ToBoxFragment();
}

// Seeks forward through any children starting at |child|. If any children are
// OOF-positioned, adds them as a candidate, then proceeds to the next child.
//
// |child| will end up being the next inflow child, or empty.
void NGCustomLayoutAlgorithm::AddAnyOutOfFlowPositionedChildren(
    NGLayoutInputNode* child) {
  DCHECK(child);
  while (*child && child->IsOutOfFlowPositioned()) {
    container_builder_.AddOutOfFlowChildCandidate(
        To<NGBlockNode>(*child), BorderScrollbarPadding().StartOffset());
    *child = child->NextSibling();
  }
}

MinMaxSizesResult NGCustomLayoutAlgorithm::FallbackMinMaxSizes(
    const MinMaxSizesFloatInput& input) const {
  return NGBlockLayoutAlgorithm(params_).ComputeMinMaxSizes(input);
}

const NGLayoutResult* NGCustomLayoutAlgorithm::FallbackLayout() {
  return NGBlockLayoutAlgorithm(params_).Layout();
}

}  // namespace blink


text:
const category = (state = {}, action) => {
  switch (action.type) {
    case 'GET_CATEGORY_RESOLVED':
      return {
        ...state,
        list: action.payload
      };
    default:
      return state;
  }
};

export default category;


text:
package osutils

import (
	"os"
	"path"
	"path/filepath"

	"github.com/pkg/sftp"
)

type sftpClient interface {
	Create(path string) (*sftp.File, error)
	Mkdir(path string) error
	ReadDir(p string) ([]os.FileInfo, error)
}

// SafeCreateSSH creates a file, creating parent directories if needed on a remote machine via an ssh client
func SafeCreateSSH(client sftpClient, name ...string) (file *sftp.File, err error) {
	ssh := sshClientBucket{
		client: client,
	}
	fpath := path.Join(name...)
	basepath := filepath.Dir(fpath)

	if err = ssh.remoteSafeMkdirAll(basepath); err == nil {
		file, err = client.Create(fpath)
	}
	return
}

type sshClientBucket struct {
	client sftpClient
}

func (s sshClientBucket) remoteSafeMkdirAll(base string) (err error) {

	if !s.exists(base) {
		parentdir := filepath.Dir(base)

		if !s.exists(parentdir) {
			err = s.remoteSafeMkdirAll(filepath.Dir(parentdir))
		}

		if err == nil {
			err = s.client.Mkdir(base)
		}
	}
	return
}

func (s sshClientBucket) exists(fpath string) (ok bool) {
	ok = false

	if _, err := s.client.ReadDir(fpath); err == nil {
		ok = true
	}
	return
}

// SafeCreate creates a file, creating parent directories if needed
func SafeCreate(name ...string) (file *os.File, err error) {
	p, e := ensurePath(path.Join(name...))

	if e != nil {
		return nil, e
	}
	return os.Create(p)
}

func ensurePath(path string) (string, error) {
	base := filepath.Dir(path)
	e, _ := Exists(base)
	if e {
		return path, nil
	}

	// Create missing directory recursively
	err := os.MkdirAll(base, 0777)
	return path, err
}

func Exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>WPILIB: PIDController.cpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css">
<link href="doxygen.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Classes

Files

File List

File Members

PIDController.cpp File Reference
#include "PIDController.h"

#include "Notifier.h"

#include "PIDSource.h"

#include "PIDOutput.h"

#include <math.h>

#include "Synchronized.h"

Go to the source code of this file.

<address style="text-align: right;">Generated on Wed Feb 9 11:20:45 2011 for WPILIB by

 1.5.8 </address>


text:
var getNamespace = require('continuation-local-storage').getNamespace,
    context = getNamespace('com.neon');

module.exports = function(){
  var request = context.get('request');
  if(request.user && request.user.dataValues.admin === true){
    return true;
  } else {
    return false;
  }
};


text:
class CreateAuthentications < ActiveRecord::Migration
  def change
    create_table :authentications do |t|
      t.string :channel,    null: false
      t.text   :parameters

      t.timestamps
    end

    add_index :authentications, :channel, unique: true
  end
end


text:
package io.undertow.websockets.core.protocol;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.undertow.testutils.DefaultServer;
import io.undertow.util.NetworkUtils;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.WebSocketProtocolHandshakeHandler;
import io.undertow.websockets.core.AbstractReceiveListener;
import io.undertow.websockets.core.BufferedBinaryMessage;
import io.undertow.websockets.core.WebSocketCallback;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.core.WebSockets;
import io.undertow.websockets.spi.WebSocketHttpExchange;
import io.undertow.websockets.utils.FrameChecker;
import io.undertow.websockets.utils.WebSocketTestClient;
import org.junit.Test;
import org.xnio.FutureResult;
import org.xnio.Pooled;

import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Norman Maurer
 */
public class WebSocket07ServerTest extends AbstractWebSocketServerTest {
    @Override
    protected WebSocketVersion getVersion() {
        return WebSocketVersion.V07;
    }

    @Test
    public void testPing() throws Exception {
        final AtomicBoolean connected = new AtomicBoolean(false);
        DefaultServer.setRootHandler(new WebSocketProtocolHandshakeHandler(new WebSocketConnectionCallback() {
            @Override
            public void onConnect(final WebSocketHttpExchange exchange, final WebSocketChannel channel) {
                connected.set(true);
                channel.getReceiveSetter().set(new AbstractReceiveListener() {
                    @Override
                    protected void onFullPingMessage(WebSocketChannel channel, BufferedBinaryMessage message) throws IOException {
                        final Pooled<ByteBuffer[]> data = message.getData();
                        WebSockets.sendPong(data.getResource(), channel, new WebSocketCallback<Void>() {
                            @Override
                            public void complete(WebSocketChannel channel, Void context) {
                                data.free();
                            }

                            @Override
                            public void onError(WebSocketChannel channel, Void context, Throwable throwable) {
                                data.free();
                            }
                        });
                    }
                });
                channel.resumeReceives();
            }
        }));

        final FutureResult latch = new FutureResult();
        final byte[] payload =  "payload".getBytes();

        WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + NetworkUtils.formatPossibleIpv6Address(DefaultServer.getHostAddress("default")) + ':' + DefaultServer.getHostPort("default") + '/'));
        client.connect();
        client.send(new PingWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(PongWebSocketFrame.class, payload, latch));
        latch.getIoFuture().get();
        client.destroy();
    }
}


text:
import gettext

_ = gettext.gettext


text:
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

from .lapjv import lapjv

__all__ = ['lapjv']


text:
import * as Promise                 from "bluebird";
import HttpClient                   from "../utility/HttpClient";
import { ConfigManager }            from "../utility/ConfigManager";
import {
        GenericResponse,
        CanonicalResponse,
        RetrieveWatchlist
       }                            from "../SchemaModule";
import { TMTokenBearerSingature }   from "../utility/TMAuthData";
import { TMAuth }                   from "../utility/TMAuth";

export namespace WatchlistProxy {
    export class WatchlistClient {
        private static httpClient: HttpClient;
        private static configManager: ConfigManager.IConfiguration;
        private static configData: ConfigManager.IConfigData;
        private userAuthHeader: string;
        constructor(user: TMTokenBearerSingature, configManager?: ConfigManager.IConfiguration) {
            WatchlistClient.httpClient = new HttpClient();
            WatchlistClient.configManager = configManager || new ConfigManager.Configuration();
            WatchlistClient.configData = WatchlistClient.configManager.get();
            this.userAuthHeader = new TMAuth(WatchlistClient.configManager).GetUserAuthHeader(user);
        }

        retrieveWatchlist(): Promise<CanonicalResponse<RetrieveWatchlist.RetrieveWatchlist>> {
            let servicePath: string = "MyTradeMe/Watchlist/All";
            let apiUri: string = WatchlistClient.configData.ApiUri;
            return WatchlistClient.httpClient.get<RetrieveWatchlist.RetrieveWatchlist>(`${apiUri}/v1/${servicePath}.json`, this.userAuthHeader);
        }

        addWatchlist(listingId: number): Promise<CanonicalResponse<GenericResponse.Response>> {
            let servicePath: string = "MyTradeMe/WatchList/";
            let apiUri: string = WatchlistClient.configData.ApiUri;
            return WatchlistClient.httpClient.post<any, GenericResponse.Response>(`${apiUri}/v1/${servicePath}${listingId}.json`, null, this.userAuthHeader);
        }

        removeWatchlist(listingId: number): Promise<CanonicalResponse<GenericResponse.Response>> {
            let servicePath: string = "MyTradeMe/WatchList/";
            let apiUri: string = WatchlistClient.configData.ApiUri;
            return WatchlistClient.httpClient.delete<GenericResponse.Response>(`${apiUri}/v1/${servicePath}${listingId}.json`, this.userAuthHeader);
        }
    }
}


text:
package org.eclipse.paho.mqttsn.udpclient.utils;

import java.util.LinkedList;
import java.util.NoSuchElementException;

public class MsgQueue {

   private LinkedList<Object> queue;
	private volatile boolean isClosed;

	public MsgQueue() {
		queue = new LinkedList<Object>();
		isClosed = false;
	}

	public void close() {
		synchronized (queue) {
			isClosed = true;
			queue.notifyAll();
		}
	}

	/**
	 * @param o
	 */
	public void addLast(Object o) {
		synchronized (queue) {
			if(isClosed) {
				throw new IllegalStateException("Queue is closed.");
			}
			queue.add(o);
			queue.notify();
		}
	}

	/**
	 * @param o
	 */
	public void addFirst(Object o) {
		synchronized (queue) {
			if(isClosed) {
				throw new IllegalStateException("Queue is closed.");
			}
			queue.addFirst(o);
			queue.notify();
		}
	}

	public Object get() throws InterruptedException {
		synchronized (queue) {
			if(isClosed) {
				throw new IllegalStateException("Queue is closed.");
			}
			while (queue.isEmpty() & !this.isClosed)
				queue.wait();
			Object res=null;
			try {
				res=queue.removeFirst();
			} catch(NoSuchElementException e) {
				res=null;
			}
			return res;
		}
	}

	/**
	 * @return
	 */
	public int size() {
		return queue.size();
	}
}


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class VspanPortConflict extends DvsFault {
  public String vspanSessionKey1;
  public String vspanSessionKey2;
  public String portKey;

  public String getVspanSessionKey1() {
    return this.vspanSessionKey1;
  }

  public String getVspanSessionKey2() {
    return this.vspanSessionKey2;
  }

  public String getPortKey() {
    return this.portKey;
  }

  public void setVspanSessionKey1(String vspanSessionKey1) {
    this.vspanSessionKey1=vspanSessionKey1;
  }

  public void setVspanSessionKey2(String vspanSessionKey2) {
    this.vspanSessionKey2=vspanSessionKey2;
  }

  public void setPortKey(String portKey) {
    this.portKey=portKey;
  }
}