text:
Combat occurs between at least two opponents on a hexagonal playing grid in which combatants fight enemies using both ranged and melee weapons.

Combat occurs in real time. The combatants are organized into "teams". There is no limit on the amount of teams that can be present on any given map.

Combantants strategize based on enemy positions to plan their attacks. Each combatant assesses the capabilities of combatants that they can detect and makes decisions based on sets of rules and behavioral algorithms given their environment.

**Flow for combatant**

1. Combatant assess options by weighing the battlefield
 * Detects Enemies
 * Assesses capabilities
2. Combatant chooses a target and course of action
 * (Target is optional)
 * Move
 * Attack
 * Hide
 * Retreat
 * Defend
 * Do Nothing
3. [INTERRUPT] During action, combatant can be interrupted. If so, return to step 1.
4. Finish action
5. Reassess

###What's involved?

####**1.** Weighing the battlefield

* Receive messages from Allies
* Survey all enemies
 * From all enemies, narrow down to which the combatant can detect
 * Filter based on messages from Allies
 * Filter based on personal bias
 * See if anyone is left

 *The above describes a chain of responsibility. Each step can be a function. The function takes the array of enemy combatants. It can run filtering operations and pass it to the next function, or it can declare the process finished and not pass it along the chain. The final function is a default method of narrowing down the options. It could be a combatant-specific algorithm: random, only melee combatants (and from there random) etc.*

 Part of filtering process can be based on keywords associated with each combatant. Keywords can include:

* Melee
* Ranged
* Sniper
* Medic
* Commander
* Weak
* Sneaky

Keywords can be based on ENUMS declared as static variables somewhere...

 **Still need to figure out what to do after combatant is chosen. Maybe it doesn't matter. They can choose a target but still run away in the next phase (which is choosing a course of action)**

####**2.** Choose a course of action

* Receive messages from Allies
* Decide behavior based on algorithm specific to that character or character type
  * If action is being interrupted, determine whether or not to continue action or change course
  * Determine whether Ally messages will be used or ignored
  * If Ally messages ignored, run behavioral algorithm

**Behavioral Algorithm** should check for different conditions in a hierarchical order. When conditions are met, a prescribed action should be taken (attack, move, retreat, defend, etc.). If none of the conditions listed are met, there should be a default action.

####**3.** Send Message [OPTIONAL]

* Send message to fellow combatants

 **Note:** Messages from allies can be split into categories - choosing targets vs. course of action. Choosing Target messages can be filtering functions, Course of Action messages can be behavioral functions which use the Combatant object interface to perform actions. Or Course of Action can be strings which name possible actions, passed with a data object (if relevant). The data object would hold information such as which Hex to move to, which enemy to attack.

 **Note:** Part of a character's attributes can be a) How much influence they have with other people, b) How much they are willing to listen to others' messages. If the chances are low that a character will listen to others' messages, those messages are simply discarded unused.

 **Note:** A combatant can send messages to an enemy. Messages from enemies will rate the message based on danger. Messages to attack or move somewhere will be high danger, and so incredibly unlikely to be followed. Messages to retreat will be lower danger, so more likely to be followed (especially as health gets lower).

####**4.** Begin chosen action

####**5.** Interrupt [OPTIONAL]

* Check for interrupt events during action execution
* If combatant is being interrupted, go back to Step 1

####**6.** Finish Action

* Finish
* Go back to step 1 to reassess

##Notes on Actions

* Develop Action "abstract" class with specific subclasses for specific action types
* Action classes need to provide an implementation for carrying out the action
* Should have an instance variable for whether or not the action is finished
* Need to bake in a way for animations to be a part of the action.

###Interruptions during actions

Interruptions need to be delivered via the special "Interrupt" stream.

* Interruptions simulate emergencies / urgent commands rather than suggestions of the next thing to do.
* Interruptions should be split into different types (enums?) that the character can either follow or ignore
* The "Interruption Decision" algorithm needs to be configurable.
* Interruptions are delivered with 3 pieces of information: the type, the sender/initiator, and a function to execute if the character accepts the interruption
  * Examples of possible uses for the callback are to increase modifiers (similar to a pre-asses message) or alter other pieces of game state as relevant
* Another use for Interruptions might be to buff a character while they're in the middle of an action. So an interrupt type of "BUFF" should be constructed
* If the character is not performing an action, the Interruption stream will be fed into the pre-assess message stream.

###Current Tasks

* Finish implementing Action subtypes
* modify chain callers for Action section of the chain to be aware of the new Action interface
* Document the Action interface

redpajama_set_name: RedPajamaGithub


text:
namespace InControl
{
	// @cond nodoc
	[AutoDiscover]
	public class GenericLinuxProfile : UnityInputDeviceProfile
	{
		public GenericLinuxProfile()
		{
			Name = "Generic Controller";
			Meta = "Generic Controller on Linux";

			DeviceClass = InputDeviceClass.Controller;

			IncludePlatforms = new[] {
				"Linux"
			};

			JoystickRegex = new[] {
				"."
			};

			MinUnityVersion = new VersionInfo( 5, 0, 0, 0 );

			ButtonMappings = new[] {
				new InputControlMapping {
					Handle = "A",
					Target = InputControlType.Action1,
					Source = Button0
				},
				new InputControlMapping {
					Handle = "B",
					Target = InputControlType.Action2,
					Source = Button1
				},
				new InputControlMapping {
					Handle = "X",
					Target = InputControlType.Action3,
					Source = Button2
				},
				new InputControlMapping {
					Handle = "Y",
					Target = InputControlType.Action4,
					Source = Button3
				},
				new InputControlMapping {
					Handle = "Left Bumper",
					Target = InputControlType.LeftBumper,
					Source = Button4
				},
				new InputControlMapping {
					Handle = "Right Bumper",
					Target = InputControlType.RightBumper,
					Source = Button5
				},
				new InputControlMapping {
					Handle = "Back",
					Target = InputControlType.Back,
					Source = Button6
				},
				new InputControlMapping {
					Handle = "Start",
					Target = InputControlType.Start,
					Source = Button7
				},
				new InputControlMapping {
					Handle = "Menu",
					Target = InputControlType.Menu,
					Source = Button8
				},
				new InputControlMapping {
					Handle = "Left Stick Button",
					Target = InputControlType.LeftStickButton,
					Source = Button9
				},
				new InputControlMapping {
					Handle = "Right Stick Button",
					Target = InputControlType.RightStickButton,
					Source = Button10
				},
				new InputControlMapping {
					Handle = "DPad Left",
					Target = InputControlType.DPadLeft,
					Source = Button11,
					Invert = true
				},
				new InputControlMapping {
					Handle = "DPad Right",
					Target = InputControlType.DPadRight,
					Source = Button12,
				},
				new InputControlMapping {
					Handle = "DPad Up",
					Target = InputControlType.DPadUp,
					Source = Button13,
					Invert = true
				},
				new InputControlMapping {
					Handle = "DPad Down",
					Target = InputControlType.DPadDown,
					Source = Button14,
				}
			};

			AnalogMappings = new[] {
				LeftStickLeftMapping( Analog0 ),
				LeftStickRightMapping( Analog0 ),
				LeftStickUpMapping( Analog1 ),
				LeftStickDownMapping( Analog1 ),

				RightStickLeftMapping( Analog3 ),
				RightStickRightMapping( Analog3 ),
				RightStickUpMapping( Analog4 ),
				RightStickDownMapping( Analog4 ),

				DPadLeftMapping( Analog6 ),
				DPadRightMapping( Analog6 ),
				DPadUpMapping( Analog7 ),
				DPadDownMapping( Analog7 ),

				new InputControlMapping {
					Handle = "Left Trigger",
					Target = InputControlType.LeftTrigger,
					Source = Analog2
				},
				new InputControlMapping {
					Handle = "Right Trigger",
					Target = InputControlType.RightTrigger,
					Source = Analog5
				},
			};
		}
	}
	// @endcond
}


text:
require 'spec_helper'

describe SmartRpc::RequestHandler::Http do
  let(:request) do
    OpenStruct.new(
      :app => 'foo',
      :authentication_data => {'api_key' => 'ABCDEF'},
      :location => "http://example.com",
      :resource_details => OpenStruct.new(
        :action => :create,
        :location => "open_structs.json",
        :message => {:user => {:name => "Test"}}
      )
    )
  end

  subject{ SmartRpc::RequestHandler::Http.new }

  describe "#perform" do
    before { subject.register_actions(:crud) }

    context "when the action requested is registered with the handler" do
      context "when the response from the remote application is OK" do
        before :each do
          stub_request(:post, "http://example.com/open_structs.json?api_key=ABCDEF").
            with(:body => "user[name]=Test").
            to_return(:status => 200, :body => "{\"id\":1,\"name\":\"Test\"}", :headers => {})
        end

        it "should return back the response" do
          result = subject.perform(request)
          JSON.parse(result.body).should eq({"name" => "Test", "id" => 1})
        end
      end

      context "when the response from the remote application is a server error" do
        before :each do
          stub_request(:post, "http://example.com/open_structs.json?api_key=ABCDEF").
            with(:body => "user[name]=Test").
            to_return(:status => [500, "Internal Server Error"])
        end

        it "should raise an error" do
          expect{ subject.perform(request) }.to raise_exception(SmartRpc::RequestError)
        end
      end
    end

    context "when the action is not registered with the handler" do
      it "should raise an exception" do
        request.resource_details.stub!(:action).and_return(:notify)
        expect {subject.perform(request)}.to raise_exception(SmartRpc::ActionNotFoundError)
      end
    end
  end

  describe "#register_actions" do
    before do
      stub_request(:post, "http://some-server.com/resource.json").
        to_return(:status => 200, :body => "", :headers => {})
    end

    context "when a hash of actions mapping to verbs are passed" do
      it "should register the given actions with the http verb" do
        subject.register_actions(:create => :post)
        subject.instance_variable_get('@actions').should eq({:create => :post})
      end
    end

    context "when the mapping passed is :crud" do
      it "should map the crud actions to the http verbs" do
        subject.register_actions(:crud)
        subject.instance_variable_get('@actions').should eq({
          :create => :post,
          :read   => :get,
          :update => :put,
          :delete => :delete
        })
      end
    end
  end
end


text:
package org.joml;

import java.text.NumberFormat;

/**
 * Internal class to detect features of the runtime.
 *
 * @author Kai Burjack
 */
public final class Runtime {

    public static final boolean HAS_floatToRawIntBits = hasFloatToRawIntBits();
    public static final boolean HAS_doubleToRawLongBits = hasDoubleToRawLongBits();
    public static final boolean HAS_Long_rotateLeft = hasLongRotateLeft();
    public static final boolean HAS_Math_fma = Options.USE_MATH_FMA && hasMathFma();

    private static boolean hasMathFma() {
        try {
            java.lang.Math.class.getDeclaredMethod("fma", new Class[] { float.class, float.class, float.class });
            return true;
        } catch (NoSuchMethodException e) {
            return false;
        }
    }

    private Runtime() {
    }

    private static boolean hasFloatToRawIntBits() {
        try {
            Float.class.getDeclaredMethod("floatToRawIntBits", new Class[] { float.class });
            return true;
        } catch (NoSuchMethodException e) {
            return false;
        }
    }

    private static boolean hasDoubleToRawLongBits() {
        try {
            Double.class.getDeclaredMethod("doubleToRawLongBits", new Class[] { double.class });
            return true;
        } catch (NoSuchMethodException e) {
            return false;
        }
    }

    private static boolean hasLongRotateLeft() {
        try {
            Long.class.getDeclaredMethod("rotateLeft", new Class[] { long.class, int.class });
            return true;
        } catch (NoSuchMethodException e) {
            return false;
        }
    }

    public static int floatToIntBits(float flt) {
        if (HAS_floatToRawIntBits)
            return floatToIntBits1_3(flt);
        return floatToIntBits1_2(flt);
    }
    private static int floatToIntBits1_3(float flt) {
        return Float.floatToRawIntBits(flt);
    }
    private static int floatToIntBits1_2(float flt) {
        return Float.floatToIntBits(flt);
    }

    public static long doubleToLongBits(double dbl) {
        if (HAS_doubleToRawLongBits)
            return doubleToLongBits1_3(dbl);
        return doubleToLongBits1_2(dbl);
    }
    private static long doubleToLongBits1_3(double dbl) {
        return Double.doubleToRawLongBits(dbl);
    }
    private static long doubleToLongBits1_2(double dbl) {
        return Double.doubleToLongBits(dbl);
    }

    public static String formatNumbers(String str) {
        StringBuffer res = new StringBuffer();
        int eIndex = Integer.MIN_VALUE;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == 'E') {
                eIndex = i;
            } else if (c == ' ' && eIndex == i - 1) {
                // workaround Java 1.4 DecimalFormat bug
                res.append('+');
                continue;
            } else if (Character.isDigit(c) && eIndex == i - 1) {
                res.append('+');
            }
            res.append(c);
        }
        return res.toString();
    }

    public static String format(double number, NumberFormat format) {
        if (Double.isNaN(number)) {
            return padLeft(format, " NaN");
        } else if (Double.isInfinite(number)) {
            return padLeft(format, number > 0.0 ? " +Inf" : " -Inf");
        }
        return format.format(number);
    }

    private static String padLeft(NumberFormat format, String str) {
        int len = format.format(0.0).length();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < len - str.length() + 1; i++) {
            sb.append(" ");
        }
        return sb.append(str).toString();
    }

    public static boolean equals(float a, float b, float delta) {
        return Float.floatToIntBits(a) == Float.floatToIntBits(b) || Math.abs(a - b) <= delta;
    }

    public static boolean equals(double a, double b, double delta) {
        return Double.doubleToLongBits(a) == Double.doubleToLongBits(b) || Math.abs(a - b) <= delta;
    }

}


text:
FactoryBot.define do
  trait :base_badge do
    link_url { generate(:url) }
    image_url { generate(:url) }
  end

  factory :project_badge, traits: [:base_badge], class: 'ProjectBadge' do
    project
  end

  factory :group_badge, aliases: [:badge], traits: [:base_badge], class: 'GroupBadge' do
    group
  end
end


text:
> Yeah, but does it scale?

Noticing how most conference talks are all same bullshit, here's a long-awaited tool for generating talk titles.
Now you don't even have to think before call for papers!

## Implementation

Uses Markov chains from real Devoxx talks. No, it's not reactive.

## Build Setup

``` bash
# install dependencies
npm install

# serve with hot reload at localhost:8080
npm run dev

# build for production with minification
npm run build
```
For detailed explanation on how things work, consult the [docs for vue-loader](http://vuejs.github.io/vue-loader).


text:
<<<<<<< HEAD
/**
 * Module dependencies.
 */

var merge = require('merge-descriptors');
var connect = require('connect')
  , proto = require('./application')
  , Route = require('./router/route')
  , Router = require('./router')
  , req = require('./request')
  , res = require('./response')
  , utils = connect.utils;

/**
 * Expose `createApplication()`.
 */

exports = module.exports = createApplication;

/**
 * Expose mime.
 */

exports.mime = connect.mime;

/**
 * Create an express application.
 *
 * @return {Function}
 * @api public
 */

function createApplication() {
  var app = connect();
  utils.merge(app, proto);
  app.request = { __proto__: req, app: app };
  app.response = { __proto__: res, app: app };
  app.init();
  return app;
}

/**
 * Expose connect.middleware as express.*
 * for example `express.logger` etc.
 */

merge(exports, connect.middleware);

/**
 * Error on createServer().
 */

exports.createServer = function(){
  console.warn('Warning: express.createServer() is deprecated, express');
  console.warn('applications no longer inherit from http.Server,');
  console.warn('please use:');
  console.warn('');
  console.warn('  var express = require("express");');
  console.warn('  var app = express();');
  console.warn('');
  return createApplication();
};

/**
 * Expose the prototypes.
 */

exports.application = proto;
exports.request = req;
exports.response = res;

/**
 * Expose constructors.
 */

exports.Route = Route;
exports.Router = Router;

// Error handler title

exports.errorHandler.title = 'Express';

=======
/**
 * Module dependencies.
 */

var merge = require('merge-descriptors');
var connect = require('connect')
  , proto = require('./application')
  , Route = require('./router/route')
  , Router = require('./router')
  , req = require('./request')
  , res = require('./response')
  , utils = connect.utils;

/**
 * Expose `createApplication()`.
 */

exports = module.exports = createApplication;

/**
 * Expose mime.
 */

exports.mime = connect.mime;

/**
 * Create an express application.
 *
 * @return {Function}
 * @api public
 */

function createApplication() {
  var app = connect();
  utils.merge(app, proto);
  app.request = { __proto__: req, app: app };
  app.response = { __proto__: res, app: app };
  app.init();
  return app;
}

/**
 * Expose connect.middleware as express.*
 * for example `express.logger` etc.
 */

merge(exports, connect.middleware);

/**
 * Error on createServer().
 */

exports.createServer = function(){
  console.warn('Warning: express.createServer() is deprecated, express');
  console.warn('applications no longer inherit from http.Server,');
  console.warn('please use:');
  console.warn('');
  console.warn('  var express = require("express");');
  console.warn('  var app = express();');
  console.warn('');
  return createApplication();
};

/**
 * Expose the prototypes.
 */

exports.application = proto;
exports.request = req;
exports.response = res;

/**
 * Expose constructors.
 */

exports.Route = Route;
exports.Router = Router;

// Error handler title

exports.errorHandler.title = 'Express';

>>>>>>> aa62bd0b22a9815fa4d6409af30c17ab815b91f5


text:
package vep.app.seo.views.render

import vep.app.common.page.Page
import vep.app.production.company.show.ShowWithDependencies

import scala.xml.NodeSeq

trait SitemapRender extends Render {
  type Link = (String, String)
  type Links = Seq[Link]

  def renderSitemap(
    pages: Seq[Page],
    shows: Seq[ShowWithDependencies]
  ): String = render("Carte du site") {
    Carte du site

          {renderInformation(pages)}
          {renderShows(shows)}

  }

  private def renderInformation(pages: Seq[Page]): NodeSeq = {

Information

      {renderLinks(pages.map(page => seo.pageUrl(page) -> seo.pageTitle(page)))}

  }

  private def renderShows(shows: Seq[ShowWithDependencies]): NodeSeq = {

Spectacles

      {shows.map(renderShow)}

  }

  private def renderShow(show: ShowWithDependencies): NodeSeq = {
    val showLink = seo.showUrl(show) -> seo.showTitle(show)
    val playLinks = show.plays.map { play =>
      seo.playUrl(show, play) -> seo.playTitle(play)
    }

{show.show.title}

      {renderLinks(showLink +: playLinks)}

  }

  private def renderLinks(links: Links): NodeSeq = {

      {links.map(renderLink)}

  }

  private def renderLink(link: Link): NodeSeq = {

{link._2}

  }
}


text:
.. _admin-plugins-combo-handler:

Combo Handler Plugin
********************

.. Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.

This plugin provides an intelligent way to combine multiple URLs into a single
URL, and have Apache Traffic Server combine the components into one
response. This is useful for example to create URLs that combine multiple CSS
or Javascript files into one.

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

This plugin is only built if the configure option ::

    --enable-experimental-plugins

is given at build time. Note that this plugin is built and installed in
combination with the ESI module, since they share common code.

Configuration
=============

The arguments in the :file:`plugin.config` line in order represent

1. The path that should triggers combo handler (defaults to
   "admin/v1/combo")

2. The name of the key used for signature verification (disabled by
   default)

A "-" can be supplied as a value for any of these arguments to request
default value be applied.

Also, just like the original combohandler, this plugin generates URLs of
the form ``http://localhost/<dir>/<file-path>``. ``<dir>`` here defaults
to ``l`` unless specified by the file path in the query parameter using
a colon. For example::

    http://combo.com/admin/v1/combo?filepath1&dir1:filepath2&filepath3

Will result in these three pages being fetched::

    http://localhost/l/filepath1
    http://localhost/dir1/filepath2
    http://localhost/l/filepath3

Remap rules have to be specified to map the above URLs to desired
content servers.

The plugin also supports a prefix parameter. Common parts of successive
file paths can be extracted and specified separately using a 'p' query
parameter. Successive file path parameters are appended to this prefix
to create complete file paths. The prefix will remain active until
changed or cleared (set to an empty string). For example, the query ::

    "/file1&p=/path1/&file2&file3&p=&/file4&p=/dir:path2/&file5&file6"

results in these file paths being "reconstructed"::

    /file1
    /path1/file2
    /path1/file3
    /file4
    /dir:path2/file5
    /dir:path2/file6

Caching
=======
Combohandler follows a few rules for the "Cache-Control" header:

1) All requested documents must have "immutable" for the combo'd
   response to also have "immutable".

2) If one or more requested documents has "private" set, then the combo'd
   response will also have "private". If no requested documents have a
   publicity setting, then the default is "public".

3) The "max-age" value will be set to the smallest of all the requested "max-age"
   values. If no documents has "max-age" set, then the default is 10 years.


text:
var Util = require('util');
var EventEmitter = require('events').EventEmitter;

/**
 * Parse the WebDAV extended If header.
 *
 * For grammar, see http://tools.ietf.org/html/rfc4918#section-10.4
 *
 * Emits:
 * - resourceTag: A resource tag -- a URI to a resource.
 * - startList: Start a list
 * - not: Indicates Not was found.
 * - stateToken: A lock ID (state token)
 * - eTag: An ETag. This may be in double-quotes.
 * - endList: End a list
 * - end: parsing done
 * - error: Something broke.
 *
 * The basic usage of the parser is this:
 *
 * 1. Create a new parser with `new IfParser(rule)`
 * 2. Attach event listeners to the parser.
 * 3. Run `parse()`
 *
 * The parser is a recursive descent parsers. It begins with a top level
 * rule (`rule()`) and attempts to follow the grammer in RFC 4918.
 */
function IfParser(rule, logger) {
  //this.d("Scanning: "+ rule);
  this.tokens = rule;
  this.scanner = new Scanner(rule);
  this.logger = logger;
}
module.exports = IfParser;
Util.inherits(IfParser, EventEmitter);

IfParser.prototype.d = function (msg) {
  console.log(msg);
}

/**
 * Parse the rule, emitting events as we go.
 */
IfParser.prototype.parse = function () {
  //this.d('Parse');
  this.position = 0;
  try {
    this.rule();
    this.emit('end');
  }
  catch (e) {
    if (e) {
      this.emit('error', e);
      return;
    }
  }

}

/**
 * Top-level rule.
 *
 * This is the first rule called by the parser.
 */
IfParser.prototype.rule = function () {
  //this.d('->rule()');
  // queue the first token:
  this.scanner.nextToken();

  this.consumeWhitespace();
  // Spec says we can only do one or the other.
  this.tagList() || this.noTagList();

  //this.d('<-rule()');
}

/**
 * Parse lists that have no resource tag.
 *
 * This is exclusive of tagList().
 */
IfParser.prototype.noTagList = function () {
  //this.d('noTagList');
  while (this.list())  {
    this.consumeWhitespace();
    // Loop as long as we keep finding lists.
  }
}

/**
 * Parse lists that have a resource tag.
 *
 * This is exclusive of noTagList().
 */
IfParser.prototype.tagList = function () {
  //this.d('tagList');
  if (this.resourceTag()) {
    this.consumeWhitespace();
    while(this.list()) {
      this.consumeWhitespace();
    }
    // Recurse to get more resource tags. This allows
    // for a series of resource tag rules.
    this.tagList();
    return true;
  }
  return false;
}

/**
 * Get a list of conditions.
 */
IfParser.prototype.list = function() {
  // this.d('  ->list ' + this.scanner.token);
  if (this.scanner.token == '(') {
    this.emit('startList');
    this.scanner.nextToken();

    // Make sure that we progress.
    var lastPos = -1;
    while (this.scanner.token != ')' && !this.scanner.done && lastPos != this.scanner.pos) {
      lastPos = this.scanner.pos;
      this.condition();

    }
    if( this.scanner.token != ')') {
      throw new Error('Expected List End (")"), got ' + this.scanner.token);
    }
    this.scanner.nextToken();
    this.emit('endList');
    // this.d('  <-list');
    return true;
  }
  return false;
}

/**
 * Parse a resource tag.
 */
IfParser.prototype.resourceTag = function () {
  if (this.scanner.token  == '<') {
    this.scanner.nextToken();
    var resTag = this.charsUntil('>');
    if (this.scanner.token != '>') {
      throw new Error('Expected ">", got ' + this.scanner.token);
    }

    this.emit('resourceTag', resTag);
    this.scanner.nextToken();
    return true;
  }
  return false;
}

/**
 * Parse a state token (lock ID).
 */
IfParser.prototype.stateToken = function () {
  if (this.scanner.token  == '<') {
    this.scanner.nextToken();
    var lockId = this.charsUntil('>');
    if (this.scanner.token != '>') {
      throw new Error('Expected ">", got ' + this.scanner.token);
    }

    this.emit('stateToken', lockId);
    this.scanner.nextToken();

  }
}

/**
 * Parse conditions, where a condition may be Not, an ETag, or a State
 * Token.
 */
IfParser.prototype.condition = function () {
  // this.d('    ->condition');
  this.consumeWhitespace();
  this.notTag();
  this.stateToken();
  this.eTag();
  // this.d('    <-condition');
}

/**
 * Parse a negation.
 */
IfParser.prototype.notTag = function () {
  var b = '';
  if (this.scanner.token == 'N') {
    this.scanner.nextToken();
    b = this.scanner.token;
    this.scanner.nextToken();
    b += this.scanner.token;
    if (b != 'ot') {
      throw new Error('Expected Not, got N' + b);
    }
    this.emit('not');
    this.scanner.nextToken();

  }
}

/**
 * Parse an ETag.
 *
 * ETags may be strong or weak:
 *
 * - "strong"
 * - W/"weak"
 */
IfParser.prototype.eTag = function () {
  if (this.scanner.token == '[') {
    this.scanner.nextToken();
    var eTag = this.charsUntil(']');
    if (this.scanner.token != ']') {
      throw new Error('Expected "]", got ' + this.scanner.token);
    }
    this.emit('eTag', eTag);
    this.scanner.nextToken();
  }
}

/**
 * Consume sequential whitespace.
 *
 * This throws no events, since whitespace is incidental.
 */
IfParser.prototype.consumeWhitespace = function () {
  // this.d('consumeWhitespace()');
  var count = 0;
  while (this.scanner.token == " " || this.scanner.token == "\t") {
    //this.d("->");
    if (!this.scanner.nextToken()) {
      return;
    }
    ++count;
  }
  return count;
}

/**
 * Build a character sequence containing everything up to the stopping
 * condition or EOF.
 */
IfParser.prototype.charsUntil = function (stop) {
  var buffer = '';
  while (this.scanner.token != stop) {
    buffer += this.scanner.token;

    // We hit the end of the token sequence.
    if(!this.scanner.nextToken()) {
      // this.d('Premature end of token sequence.');
      return buffer;
    }
  }
  return buffer;
}

/**
 * The scanner.
 *
 * This is private.
 */
function Scanner(str) {
  this.tokens = str;
  this.pos = -1;
  this.token = '';
  this.done = false;
}

/**
 * Read the next token into the buffer.
 */
Scanner.prototype.nextToken = function () {
  var newPos = this.pos + 1;
  // console.log("%d of %d", newPos, this.tokens.length);
  if (this.tokens.length > newPos) {
    this.pos = newPos;
    this.token = this.value = this.tokens[newPos];
    this.code = this.tokens.charCodeAt[newPos];
    //this.token = Token.char;
    return true;
  }
  //this.recurse = true;
  // console.log("==========DONE===============")
  this.done = true;
  return false;
}

/**
 * Check whether the token is a char.
 *
 * This checks Basic Plane unicode for UTF-8.
 */
Scanner.prototype.isCharToken = function () {

  // Low control codes
  if (this.code <= 0x001F || this.code == 0x007F) {
    return false;
  }

  // Latin-1 Supplement control codes
  if (this.code >= 0x0080 && this.code < 0x00A0) {
    return false;
  }

  return true;
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: York
 * Date: 01.10.2017
 * Time: 17:56
 */
use backend\assets\AppAsset;
use yii\bootstrap\ActiveForm;
use yii\bootstrap\Html;

/* @var $this yii\web\View */
/* @var $model common\models\Block */
/* @var $form yii\widgets\ActiveForm */

AppAsset::register($this);
?>

<?php $form = ActiveForm::begin(); ?>

    <?=Html::hiddenInput('run', '')?>
    <?=Html::submitButton()?>
<? ActiveForm::end()?>


text:
'use strict';

var _ = require('underscore');

var db = require('./db'),
    Query = require('./query');

var TYPE_DEFAULTS = _.indexBy([
  { type : Number,  defaults: db.TYPES.Int },
  { type : Boolean, defaults: db.TYPES.Bit },
  { type : String,  defaults: db.TYPES.VarChar },
  { type : Date,    defaults: db.TYPES.DateTime },
  { type : Buffer,  defaults: db.TYPES.Binary },
], 'type');

/* Model class constructor
 *
 * @param {String} name the model name
 * @param {Object} schema the model schema definition
 * @param {DataType} schema.field.type the field type
 * @param {String} schema.field.column the column name in the database
 * @param {Boolean} schema.field.nullable whether the field allows null values (default: false)
 * @param {Object} schema.field.default the field default value
 * @param {Function} schema.field.get custom getter function
 * @param {Function} schema.field.set custom setter function
 * @param {Object} schema.field.validate specify model based validations (see docs)
 * @param {Object} options specify schema options
 */
var Model = function (name, schema, options) {
  this.name = name;
  this._schema = normalizeSchema(schema);
  this._options = options || {};
};

Model.prototype.create = function(obj) {

};

Model.prototype.findById = function(id, options) {

};

Model.prototype.find = function(query, options) {

};

Model.prototype.findOne = function(query, options) {

};

Model.prototype.remove = function(query) {

};

Model.prototype.update = function(query, updates) {

};

Model.prototype.findByIdAndUpdate = function(query, updates) {

};

Model.prototype.count = function(query) {

};

Model.prototype.validate = function(fn, msg) {

};

Model.TYPES = db.TYPES;

var isDriverType = function(type){
  return _.contains(db.TYPES, type);
};

var isNativeType = function(type){
  return _.has(TYPE_DEFAULTS, type);
};

var FIELD_OPTIONS = [
  { name : 'column',   validate : _.isString   },
  { name : 'nullable', validate : _.isBoolean  },
  { name : 'default'                           },
  { name : 'get',      validate : _.isFunction },
  { name : 'set',      validate : _.isFunction },
  { name : 'validate', validate : _.isObject   },
];

var normalizeSchema = function(schema) {
  var normalized = {};
  _.each(schema, function(props, fieldName) {
    var fieldData = {};

    // Validate and normalize field type
    if(isDriverType(props)) {
      fieldData.type = props;
    }
    else if(isNativeType(props)) {
      fieldData.type = TYPE_DEFAULTS[props].defaults;
    }
    else if(_.isObject(props) && props.type){
      if(isNativeType(props.type)){
        props.type = TYPE_DEFAULTS[props.type].defaults;
      }
      else if(!isDriverType(props.type)){
        throw new Error('Invalid type for field ' + fieldName);
      }
    }
    else if(_.isObject(props)){
      throw new Error('Type declaration missing for field ' + fieldName);
    }
    else {
      throw new Error('Invalid type for field ' + fieldName);
    }

    // Validate options
    _.each(FIELD_OPTIONS, function(opt){
      if(props[opt.name]){
        if(!opt.validate || opt.validate( props[opt.name] )){
          fieldData[opt.name] = props[opt.name];
        }
        else {
          throw new Error('Invalid value for field option ' + opt.name);
        }
      }
    });

    // Save the normalized field data
    normalized[fieldName] = fieldData;
  });

  return normalized;
};

module.exports = Model;


text:
package org.gradle.profile;

import org.gradle.internal.html.SimpleHtmlWriter;
import org.gradle.internal.time.TimeFormatting;
import org.gradle.reporting.HtmlReportRenderer;
import org.gradle.reporting.ReportRenderer;
import org.gradle.reporting.TabbedPageRenderer;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class ProfileReportRenderer {

    public void writeTo(BuildProfile buildProfile, File file) {
        HtmlReportRenderer renderer = new HtmlReportRenderer();
        renderer.renderSinglePage(buildProfile, new ProfilePageRenderer(), file);
    }

    private static class ProfilePageRenderer extends TabbedPageRenderer<BuildProfile> {
        private static final URL STYLE_URL = ProfilePageRenderer.class.getResource("style.css");

        @Override
        protected String getTitle() {
            return "Profile report";
        }

        @Override
        protected URL getStyleUrl() {
            return STYLE_URL;
        }

        @Override
        protected ReportRenderer<BuildProfile, SimpleHtmlWriter> getHeaderRenderer() {
            return new ReportRenderer<BuildProfile, SimpleHtmlWriter>() {
                @Override
                public void render(BuildProfile model, SimpleHtmlWriter htmlWriter) throws IOException {
                    htmlWriter.startElement("div").attribute("id", "header")
                        .startElement("p").characters(model.getBuildDescription()).endElement()
                        .startElement("p").characters(model.getBuildStartedDescription()).endElement()
                    .endElement();
                }
            };
        }

        @Override
        protected  ReportRenderer<BuildProfile, SimpleHtmlWriter> getContentRenderer() {
            return new ReportRenderer<BuildProfile, SimpleHtmlWriter>() {
                @Override
                public void render(BuildProfile model, SimpleHtmlWriter htmlWriter) throws IOException {
                    CompositeOperation<Operation> profiledProjectConfiguration = model.getProjectConfiguration();

                    htmlWriter.startElement("div").attribute("id", "tabs")
                        .startElement("ul").attribute("class", "tabLinks")
                            .startElement("li").startElement("a").attribute("href", "#tab0").characters("Summary").endElement().endElement()
                            .startElement("li").startElement("a").attribute("href", "#tab1").characters("Configuration").endElement().endElement()
                            .startElement("li").startElement("a").attribute("href", "#tab2").characters("Dependency Resolution").endElement().endElement()
                            .startElement("li").startElement("a").attribute("href", "#tab3").characters("Task Execution").endElement().endElement()
                        .endElement();
                        htmlWriter.startElement("div").attribute("class", "tab").attribute("id", "tab0");
                            htmlWriter.startElement("h2").characters("Summary").endElement();
                            htmlWriter.startElement("table");
                                htmlWriter.startElement("thead");
                                    htmlWriter.startElement("tr");
                                        htmlWriter.startElement("th").characters("Description").endElement();
                                        htmlWriter.startElement("th").attribute("class", "numeric").characters("Duration").endElement();
                                    htmlWriter.endElement();
                                htmlWriter.endElement();
                                htmlWriter.startElement("tr");
                                    htmlWriter.startElement("td").characters("Total Build Time").endElement();
                                    htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(model.getElapsedTotal())).endElement();
                                htmlWriter.endElement();
                                htmlWriter.startElement("tr");
                                    htmlWriter.startElement("td").characters("Startup").endElement();
                                    htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(model.getElapsedStartup())).endElement();
                                htmlWriter.endElement();
                                htmlWriter.startElement("tr");
                                    htmlWriter.startElement("td").characters("Settings and BuildSrc").endElement();
                                    htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(model.getElapsedSettings())).endElement();
                                htmlWriter.endElement();
                                htmlWriter.startElement("tr");
                                    htmlWriter.startElement("td").characters("Loading Projects").endElement();
                                    htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(model.getElapsedProjectsLoading())).endElement();
                                htmlWriter.endElement();
                                htmlWriter.startElement("tr");
                                    htmlWriter.startElement("td").characters("Configuring Projects").endElement();
                                    htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(profiledProjectConfiguration.getElapsedTime())).endElement();
                                htmlWriter.endElement();
                                htmlWriter.startElement("tr");
                                    htmlWriter.startElement("td").characters("Task Execution").endElement();
                                    htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(model.getElapsedTotalExecutionTime())).endElement();
                                htmlWriter.endElement();
                            htmlWriter.endElement();
                        htmlWriter.endElement();
                        htmlWriter.startElement("div").attribute("class", "tab").attribute("id", "tab1");
                            htmlWriter.startElement("h2").characters("Configuration").endElement();
                            htmlWriter.startElement("table");
                                htmlWriter.startElement("thead");
                                    htmlWriter.startElement("tr");
                                        htmlWriter.startElement("th").characters("Project").endElement();
                                        htmlWriter.startElement("th").attribute("class", "numeric").characters("Duration").endElement();
                                    htmlWriter.endElement();
                                htmlWriter.endElement();
                                htmlWriter.startElement("tr");
                                    htmlWriter.startElement("td").characters("All projects").endElement();
                                    htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(profiledProjectConfiguration.getElapsedTime())).endElement();
                                htmlWriter.endElement();
                                for (Operation operation : profiledProjectConfiguration) {
                                    htmlWriter.startElement("tr");
                                        htmlWriter.startElement("td").characters(operation.getDescription()).endElement();
                                        htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(operation.getElapsedTime())).endElement();
                                    htmlWriter.endElement();
                                }
                            htmlWriter.endElement()
                        .endElement();
                        htmlWriter.startElement("div").attribute("class", "tab").attribute("id", "tab2");
                            htmlWriter.startElement("h2").characters("Dependency Resolution").endElement()
                                .startElement("table")
                                    .startElement("thead");
                                    htmlWriter.startElement("tr");
                                        htmlWriter.startElement("th").characters("Dependencies").endElement();
                                        htmlWriter.startElement("th").attribute("class", "numeric").characters("Duration").endElement();
                                    htmlWriter.endElement();
                                htmlWriter.endElement();
                                htmlWriter.startElement("tr");
                                    htmlWriter.startElement("td").characters("All dependencies").endElement();
                                    htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(model.getDependencySets().getElapsedTime())).endElement();
                                htmlWriter.endElement();

                                for (Operation operation : model.getDependencySets()) {
                                    htmlWriter.startElement("tr");
                                        htmlWriter.startElement("td").characters(operation.getDescription()).endElement();
                                        htmlWriter.startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(operation.getElapsedTime())).endElement();
                                    htmlWriter.endElement();
                                }
                            htmlWriter.endElement()
                        .endElement();
                        htmlWriter.startElement("div").attribute("class", "tab").attribute("id", "tab3");
                            htmlWriter.startElement("h2").characters("Task Execution").endElement()
                            .startElement("table")
                                .startElement("thead")
                                    .startElement("tr")
                                        .startElement("th").characters("Task").endElement()
                                        .startElement("th").attribute("class", "numeric").characters("Duration").endElement()
                                        .startElement("th").characters("Result").endElement()
                                    .endElement()
                                .endElement();
                                for (ProjectProfile project : model.getProjects()) {
                                   htmlWriter.startElement("tr")
                                        .startElement("td").characters(project.getPath()).endElement()
                                        .startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(project.getElapsedTime())).endElement()
                                        .startElement("td").characters("(total)").endElement()
                                    .endElement();
                                    for (TaskExecution taskExecution : project.getTasks()) {
                                        htmlWriter.startElement("tr")
                                            .startElement("td").attribute("class", "indentPath").characters(taskExecution.getPath()).endElement()
                                            .startElement("td").attribute("class", "numeric").characters(TimeFormatting.formatDurationVeryTerse(taskExecution.getElapsedTime())).endElement()
                                            .startElement("td").characters(taskExecution.getStatus()).endElement()
                                        .endElement();
                                    }
                                }
                            htmlWriter.endElement()
                        .endElement()
                    .endElement();
                }
            };
        }
    }
}


text:
package flydb

import (
    "testing"
)

func TestFormatXML(t *testing.T) {
    t.Skip("XML format not supported currently")
    // format := GetFormat("xml")

    // doTestFormat(t, format)
}


text:
package org.xbib.elasticsearch.action.termlist;

import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.client.ElasticsearchClient;

public class TermlistRequestBuilder extends ActionRequestBuilder<TermlistRequest, TermlistResponse, TermlistRequestBuilder> {

    public TermlistRequestBuilder(ElasticsearchClient client) {
        super(client, TermlistAction.INSTANCE, new TermlistRequest());
    }

    public TermlistRequestBuilder setField(String field) {
        request.setField(field);
        return this;
    }

    public TermlistRequestBuilder setTerm(String term) {
        request.setTerm(term);
        return this;
    }

    public TermlistRequestBuilder setFrom(Integer from) {
        request.setFrom(from);
        return this;
    }

    public TermlistRequestBuilder setSize(Integer size) {
        request.setSize(size);
        return this;
    }

    public TermlistRequestBuilder sortByDocFreq(boolean sortByDocFreq) {
        request.sortByDocFreq(sortByDocFreq);
        return this;
    }

    public TermlistRequestBuilder sortByTotalFreq(boolean sortByTotalFreq) {
        request.sortByTotalFreq(sortByTotalFreq);
        return this;
    }

}


text:
/**
 * class SponsorEngines defines a Sponsor Data Storage
 * capability for the PacNEM Game.
 *
 * Storage is done in window.localStorage (IE >= 10)
 *
 * @author  Grégory Saive <greg@evias.be> (https://github.com/evias)
 */
var SponsorEngine = function(API) {
    this.API_ = API;

    /**
     * This method reads Sponsor Engine data from the
     * localStorage.
     *
     * @return  {Object}
     */
    this.read = function() {
        var storage = window.localStorage;
        if (!storage)
        //XXX display frontend error message
            return self;

        try {
            var data = storage.getItem("evias.pacnem:sponsor-engine") || "{}";
            return JSON.parse(data);
        } catch (e) {
            return {};
        }
    };

    /**
     * This method writes Sponsor Engine data to the
     * localStorage.
     *
     * @return  {SponsorEngine}
     */
    this.write = function(data) {
        var storage = window.localStorage;
        if (!storage)
        //XXX display frontend error message
            return self;

        storage.setItem("evias.pacnem:sponsor-engine", JSON.stringify(data));
        return this;
    };

    /**
     * This method will save an ad view for the given
     * sponsor and player and communicate with
     * the Backend through the `API_` object.
     *
     * @param   {NEMSponsor}    sponsor Should contain key `slug`
     * @param   {Object}        player  Should contain key `address`
     * @return  {SponsorEngine}
     */
    this.watched = function(sponsor, player) {
        var self = this;
        var data = self.read();

        if (!sponsor.slug || !sponsor.slug.length)
            return self;

        if (data.hasOwnProperty(sponsor.slug)) {
            data[sponsor.slug].counter++;
        } else {
            data[sponsor.slug] = { counter: 1 };
        }

        // Backend determines whether the ad view is relevant
        self.store(sponsor, player, function(response) {
            // only write to localStorage if adView was relevant
            if (!response.status == 'ok' || !response.item || !response.item.total)
                return self;

            return self.write(data);
        });
        return self;
    };

    /**
     * This method will communicate with the API to store
     * the given Sponsor Ad View for the given Player.
     *
     * @param   {NEMSponsor}    sponsor Should contain key `slug`
     * @param   {Object}        player  Should contain key `address`
     * @return  {SponsorEngine}
     */
    this.store = function(sponsor, player, callback) {
        this.API_.storeSponsorAdView(sponsor, player, function(response) {
            if (callback) return callback(response);
        });
        return this;
    };

    var self = this; {
        // nothing to do upon instanciation
    };
};


text:
<?php
/**
 * The Header for our theme.
 *
 * Displays all of the  section and everything up till

 *
 * @package WordPress
 * @subpackage Twenty_Eleven
 * @since Twenty Eleven 1.0
 */
?><!DOCTYPE html>

<html <?php language_attributes(); ?> class="no-js">

<link rel="icon" type="image/png" href="favicon.ico"/>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<title>Le site de la Fédé B</title>

<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<link href="http://www.fedeb.net/wp-content/themes/fedeb/css/menu-responsive.css" rel="stylesheet">

<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />

<?php
	/* We add some JavaScript to pages with the comment form
	 * to support sites with threaded comments (when in use).
	 */
	if ( is_singular() && get_option( 'thread_comments' ) )
		wp_enqueue_script( 'comment-reply' );

	/* Always have wp_head() just before the closing
	 * tag of your theme, or you will break many plugins, which
	 * generally use this hook to add elements to  such
	 * as styles, scripts, and meta tags.
	 */
	wp_head();
?>

							<hgroup>

							</hgroup>

Menu

									<?php wp_nav_menu(array(
										'theme_location' => 'nav'
									)); ?>

							<?php if (function_exists('slideshow')) { slideshow($output = true, $post_id = false, $gallery_id = false, $params = array()); } ?>

Ce site est la propriété de la Fédé B
							Fédé B - Fédération des Associations Etudiantes de Bretagne Occidentale

							UFR Sciences et Techniques
							6 av. Victor Le Gorgeu
							CS 93 837
							29238 Brest Cedex 3

							Tél : 02 98 01 29 36
							Fax :  09 52 94 41 83
							Courriel : contact@fedeb.net

							Réalisation du site :
							Conception technique : Benjamin Buton, www.benjaminbuton.fr
							Conception graphique : Maxime Gourmelen

					<?php include('sidebar.php'); ?>

<?php wp_footer(); ?>

		<?php
			if ( function_exists('register_sidebar'))
			register_sidebar(array(
			'name' => 'Footer Left',));

			if ( function_exists('register_sidebar'))
			register_sidebar(array(
			'name' => 'Footer Center',));

			if ( function_exists('register_sidebar'))
			register_sidebar(array(
			'name' => 'Footer Right',));
		?>

Navigation

Fédé B

Présentation

Fonctionnement

Historique

Bureau

Formation

Réseau

Associations du réseau

Agenda des assos

Animation

Impro U

Les Pétarades

Opérations de rentrée

Représentation

La représentation des étudiants

L'UBO

Le Crous

Le Bureau Information Jeunesse

Solidarité

Agoraé

Téléthon

Bien être étudiant

Contact du Bureau

UFR Sciences et Techniques

										6 av. Victor Le Gorgeu

										CS 93 837

										29238 Brest Cedex 3

										contact@fedeb.net

										02 98 01 29 36

										09 52 94 41 83

										http://www.fedeb.net

Partenaires

Copyright © 2013 - Site propriétaire de la Fédé B - Tous droits réservés - Mentions légales


text:
<?php

namespace Ridrog\Boilerplate\Http\Controllers;

use Illuminate\Http\Request;

class BoilerplateController extends Controller
{
    public function test()
    {
        return "The Controller worked";
    }
}


text:
Pixiv.Net is pixiv client library that targeting .NET Standard 2.0.
**This library does not include pixiv API keys.**


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$this->load->view("common/header");
?>
<div class="page-banner" style="padding:40px 0; background: url(<?=base_url()?>images/slide-02-bg.jpg) center #f9f9f9;">

 Disclaimer

We Are Professional

Home

 Disclaimer

 AyJo Consulting Disclaimer

					AyJo Consulting Inc. or represented by (www.AyJoConsulting.com) reserves the right not be held responsible for correctness, topicality, completeness or quality of the information provided on our website. AyJo Consulting Inc. shall not be liable for any claim or right to receive damages, including, but not limited to, loss of profit or data, or other similar claims, even if we have been specifically advised of the possibility of such damages. AyJo Consulting Inc. cannot be held liable for any damage caused by the use of any information provided, including any kind of information which is complete, incomplete or incorrect, will therefore be rejected. AyJo Consulting Inc. also cannot be held liable for any damage(s) caused from any of the products or services provided by us to our customers.

Any information or Promotions on our website can be extended, changed or partly or completely deleted by AyJo Consulting Inc. at any time without separate announcement. All offers on the Website are not-binding and without obligation.

By using our website and services you agree to the above terms and conditions. Any questions regarding this policy should be forwarded to info@ayjoconsulting.com

 Development Policy

					AyJo Consulting reserves the right to decline any project believed to promote racism, pornography, or any other content objectionable in nature. AyJo Consulting reserves the right to include the following phrase, or one very similar to, on all Web sites we develop: "Website designed & Marketed by AyJo Consulting". This phrase will only be placed at the bottom of the page and will in no way effect the look or style of any page or site. We further reserve the right to include any Web site created and developed by us in our portfolio.

 Delivery Policy

					All our software products and services are provided as a Software as a service or available as a download only. We do not provide hard copy or CD or DVD version of any software.

 Quotation

Any quotation of service will be valid for 30 days from the date issued. Any features or services not included in the original quote will be subject to extra charges.

 Limitation of Liability

AyJo Consulting will not be held liable for any indirect, special, or consequential damages or any loss of profits or revenue which may arise in connection with any of the projects we develop. We reserve the right to stop or delay any project for any reason without liability. AyJo Consulting will notify the client of any changes in the project development status and make appropriate arrangements without any delay. If the project is stopped as a result of actions taken by AyJo Consulting, a refund will be given to the client minus any billable hours at a sole discretion of AyJo Consulting. AyJo Consulting will not be held responsible for any issues, damage, email problems, Web site hacks or attempts, or downtime which results from the use of any of our services or any outside hosting company, internet service provider, domain name registrar, or any other outside agency. Outside services are considered independent to those offered by AyJo Consulting.

 Project Contents

Any digital or non-digital materials supplied to AyJo Consulting by the client for the purpose of project development must be either owned by the client or the client must have been given copyright permission for publication. AyJo Consulting will not be held responsible for any copyright infringements found on these materials. Any materials supplied to AyJo Consulting will not be shared with any other party. All original files (PSD, FLA, etc.) remain the property of the creator and will not be shared.

 Web Site Content

The client is responsible for providing all textual content to be used on any given Web page. If requested, AyJo Consulting can supply the textual content for an additional charge based on the amount of content required. All textual content supplied by the consumer WILL NOT be checked for spelling or grammar errors. It is the responsibility of the client to ensure no such errors exist and AyJo Consulting will not be held responsible for such errors. If requested, AyJo Consulting will offer a proofreading/rewriting service for an additional charge.

<?php
$this->load->view("common/footer");
?>


text:
/*
	A* implementation with SFBDS

	notes:
	- the hash function is from statehash.h and hence only supports
	  a maximum of 2^32 states for graphState and dimensions
	  2^16x2^16 for map locations
*/

#ifndef SFBDS_AStar
#define SFBDS_AStar

#include <queue>
#include <ext/hash_set>
#include <cstdlib>
#include "SearchEnvironment.h"
#include "GraphEnvironment.h"
#include "Map2DEnvironment.h"
#include "statehash.h"

template<class state, class action>
class SFBDSAStar {

public:
	SFBDSAStar( SearchEnvironment<state,action> *env );
	~SFBDSAStar();

	/*----------------------------------------------------------------------------
	| type definitions
	----------------------------------------------------------------------------*/
	class QueueNode {
		public:
		state s1, s2; // search a path from s1 to s2

		// note that we would actually only need one parent
		// BUT, we might want to use this test code to expand both sides
		// and work on the cross product...
		state p1, p2; // parent of s1 and s2, we only have to keep one parent for
		              // backward reference but we use the second one for more pruning
		unsigned int coming_from;
		  // smallest bit sets whether p1 is set
			// second bit sets whether p2 is set
			// third bit sets whether we come from p1 (=0) or p2 (=1)
		double gcost1, gcost2; // gcosts from start and goal
		double fcost; // gcost1 + gcost2 + hcost where hcost = h(s1,s2)
	};

	/*----------------------------------------------------------------------------
	| search functions
	----------------------------------------------------------------------------*/
	// this procedure does the entire search
	double astar( state start, state goal, std::vector<state> &path, int expandheuristic_param = 0 );

	// for visualization purposes we can also initialize and search step by step
	void initialize( state start, state goal, int expandheuristic_param = 0 );
	// expands the next node
	// (takes nodes from the open queue until one can be expanded)
	// the flag expanded returns which side has been expanded
	// if true => start side, if false => goal side
	QueueNode step( bool &expanded );

	// sets a flag whether advanced pruning (with both sides gcosts) should be done
	// advanced_pruning is on by default
	void use_pruning( bool use ) { use_advanced_pruning = use; };
	// if you want the algorithm to use
	// max( h(x,y), h(y,x) ) instead of just plain h(x,y)
	// set this flag to true. This only makes sense if the heuristic is non-symmetric
	// this is disabled by default
	void use_asymmetric_heuristic( bool use ) { use_asymmetric_h = use; };

	/*----------------------------------------------------------------------------
	| visualization
	----------------------------------------------------------------------------*/
	void OpenGLDraw( GLdouble rad ) const;
	void OpenGLDraw( QueueNode q, bool side, GLdouble rad ) const;

	/*----------------------------------------------------------------------------
	| statistics
	----------------------------------------------------------------------------*/
	unsigned int nodesExpanded;
	unsigned int nodesPoppedFromOpenQueue;
	unsigned int successorsTouched;
	//unsigned int predecessorOperatorPruning;
	unsigned int distancePruning;
	unsigned int distanceSuccessorPruning;
	unsigned int closedListPrunes;
	unsigned int numberOfJumps;
	unsigned int numberOfJumpsInSolution;
	unsigned int reopenedNodes;
	unsigned int bpmxUpdates;
	unsigned int oneSidedReopenings; // does not work unless you disable gcost caches when nodes are
	                                 // put into the open queue

	unsigned int GetOpenQueueSize() { return( open.size() ); };

protected:

	// the most important function to this research
	// if expand_heuristic is true the start will be expanded
	// otherwise the goal will be expanded
	bool expandheuristic( QueueNode &q );
	double heuristicLookup( state &s, state &g, bool bothSides );

	// updates the coming_from tag as described below
	unsigned int update_coming_from( unsigned int &old_flag, bool &expand );

	struct QueueNodeCompare {
		bool operator() ( const QueueNode q1, const QueueNode q2 ) const {
			if( fequal( q1.fcost, q2.fcost ) )
				return( fless( q1.gcost1 + q1.gcost2, q2.gcost1 + q2.gcost2 ) );
			return( q1.fcost > q2.fcost );
		};
	};
	typedef std::priority_queue<QueueNode, std::vector<QueueNode>, QueueNodeCompare> AStarOpenQueue;

	// Definition of CLOSED queue
	struct QueueNodeHash {
		size_t operator() ( const QueueNode q ) const {
			return sfbds_state_hash<state>( q.s1, q.s2 );
		};
	};
	struct QueueNodeEqual {
		size_t operator() ( const QueueNode q1, const QueueNode q2 ) const {
			return( (q1.s1 == q2.s1 && q1.s2 == q2.s2) || (q1.s1 == q2.s2 && q1.s2 == q2.s1) );
		};
	};
	typedef __gnu_cxx::hash_set<QueueNode, QueueNodeHash, QueueNodeEqual> AStarClosedList;

	// closed lists for single searches from start and goal
	struct RegularHash {
		size_t operator() ( const state s ) const {
			return regular_state_hash<state>( s );
		};
	};
	typedef __gnu_cxx::hash_map<state, double, RegularHash> DistanceList;

	// traces back the path from q using the closed list
	void trace_back_path( QueueNode q, std::vector<state> &path );

	// variables
	AStarOpenQueue open;
	AStarClosedList closed;
	DistanceList distances_from_start, distances_from_goal;

	SearchEnvironment<state,action> *env;

	int expandheuristic_param;

	bool use_advanced_pruning;
	bool use_asymmetric_h;

	private:
	double sanity_fcost_check;

	bool *OpenGLDrawState;
	void OpenGLDraw_RegisterClosedState( QueueNode &q );

};

/*------------------------------------------------------------------------------
| Implementation
------------------------------------------------------------------------------*/

// Header
template<class state, class action>
SFBDSAStar<state,action>::SFBDSAStar( SearchEnvironment<state,action> *_env ):
	env( _env ), use_advanced_pruning( true ), use_asymmetric_h(false),
	OpenGLDrawState(NULL) {
};

template<class state, class action>
SFBDSAStar<state,action>::~SFBDSAStar() {
	// the following is not needed because open and closed are normal variables in the class
	// reassign open to an empty queue
	/*
	open = AStarOpenQueue();
	// clear closed
	closed.clear();
	distances_from_start.clear();
	distances_from_goal.clear();
	std::cout << "destroyed class and cleared everything" << std::endl << std::flush;
	*/

	if( OpenGLDrawState != NULL )
		delete OpenGLDrawState;
};

template<class state, class action>
void SFBDSAStar<state,action>::initialize( state s1, state s2, int _expandheuristic_param ) {
	// reset counters
	nodesExpanded = 0;
	nodesPoppedFromOpenQueue = 0;
	successorsTouched  = 0;
	//predecessorOperatorPruning = 0;
	distancePruning = 0;
	distanceSuccessorPruning = 0;
	closedListPrunes = 0;
	numberOfJumps = 0;
	numberOfJumpsInSolution = 0;
	reopenedNodes = 0;
	bpmxUpdates = 0;
	oneSidedReopenings = 0;

	expandheuristic_param = _expandheuristic_param;

	// cleanup just to make sure things are proper
	open = AStarOpenQueue();
	closed.clear();
	distances_from_start.clear();
	distances_from_goal.clear();

	// push the initial state onto the queue
	QueueNode q;
	q.s1 = s1; q.s2 = s2; q.coming_from = 0;
	q.gcost1 = 0;
	q.gcost2 = 0;
	q.fcost = heuristicLookup( s1, s2, use_asymmetric_h );
	sanity_fcost_check = q.fcost;
	open.push( q );
	distances_from_start[q.s1] = q.gcost1;
	distances_from_goal[q.s2]  = q.gcost2;

	// reset the view
	if( OpenGLDrawState != NULL ) {
		delete OpenGLDrawState;
		OpenGLDrawState = NULL;
	}

	return;
};

template<class state,class action>
typename SFBDSAStar<state,action>::QueueNode SFBDSAStar<state,action>::step( bool &expand ) {

	typename AStarClosedList::iterator closediter1 = closed.begin(); // used for expanded node
	typename AStarClosedList::iterator closediter2 = closed.begin(); // used for successors
	typename DistanceList::iterator distancesiter;
	std::vector<state> neighbors;
	typename std::vector<state>::iterator stateiter;
	std::vector<QueueNode> successors;
	typename std::vector<QueueNode>::iterator nodeiter;
	QueueNode q, successor;

	expand = true;

	while( !open.empty() ) {

		q = open.top(); open.pop();
		nodesPoppedFromOpenQueue++;

		bool one_sided_reexpansion = false;

		// sanity check for BPMX that makes the fcost non-decreasing
		if( fgreater( sanity_fcost_check, q.fcost ) ) {
			std::cerr << "ERROR: fcost decreased in the search although we use BPMX" << std::endl << std::flush;
			exit( 1 );
		} else {
			// verbose
			//if( !fequal( sanity_fcost_check, q.fcost ) ) {
			//	std::cout << "after fcost " << sanity_fcost_check << " => " << nodesExpanded << " expanded" << std::endl;
			//}
			sanity_fcost_check = q.fcost;
		}

		if( q.s1 == q.s2 ) return q; // end the search when a terminal is found

		if( use_advanced_pruning ) {
			// prune if the distance from the original start is non-optimal
			distancesiter = distances_from_start.find( q.s1 );
			if( distancesiter != distances_from_start.end() && fless( distancesiter->second, q.gcost1 ) ) {
				distancePruning++;
				continue;
			} else {
				if( distancesiter != distances_from_start.end() && fgreater( distancesiter->second, q.gcost1 ) )
					one_sided_reexpansion = true;
				distances_from_start[q.s1] = q.gcost1;
			}

			// prune if the distance from the original goal is non-optimal
			distancesiter = distances_from_goal.find( q.s2 );
			if( distancesiter != distances_from_goal.end() && fless( distancesiter->second, q.gcost2 ) ) {
				distancePruning++;
				continue;
			} else {
				if( distancesiter != distances_from_goal.end() && fgreater( distancesiter->second, q.gcost2 ) )
					one_sided_reexpansion = true;
				distances_from_goal[q.s2] = q.gcost2;
			}
		}

		// check whether q is already in the closed list
		closediter1 = closed.find( q );
		// prune if we have q already in the closed list with a smaller or equal overall g cost
		if( closediter1 != closed.end() &&
		    (q.gcost1 + q.gcost2 >= closediter1->gcost1 + closediter1->gcost2) ) {
			closedListPrunes++;
			continue;
		}

		if( one_sided_reexpansion )
			oneSidedReopenings++;

		// if we are to expand the node
		break;
	}

	// verbose
	if( closediter1 != closed.end() )
		reopenedNodes++;

	// verbose
	//std::cout << "expanding: " << q.s1 << " " << q.s2 << std::endl;

	// now find out which side of q to expand
	expand = expandheuristic( q );
	if( expand ) env->GetSuccessors( q.s1, neighbors ); // expand q.s1
	else         env->GetSuccessors( q.s2, neighbors ); // expand q.s2
	nodesExpanded++;

	// set the hcost of the current node
	double max_root_hcost;
	// if there is a node in the closed list with this current hcost go for it
	if( closediter1 != closed.end() )
		max_root_hcost = std::max( q.fcost - q.gcost1 - q.gcost2, closediter1->fcost - closediter1->gcost1 - closediter1->gcost2 );
	else
		max_root_hcost = q.fcost - q.gcost1 - q.gcost2;

	// generate all successors and check them against the closed list
	for( stateiter = neighbors.begin(); stateiter != neighbors.end(); stateiter++ ) {

		double transit_cost;
		double hcost;

		successorsTouched++;
		if( expand ){
			successor.p1 = q.s1;
			successor.p2 = q.p2;
			successor.coming_from = update_coming_from( q.coming_from, expand );
			successor.s1 = *stateiter;
			successor.s2 = q.s2;
			transit_cost = env->GCost( q.s1, successor.s1 );
			successor.gcost1 = q.gcost1 + transit_cost;
			successor.gcost2 = q.gcost2;

			if( use_advanced_pruning ) {
				// check whether new successor has sub-optimal distance from the start
				distancesiter = distances_from_start.find( successor.s1 );
				if( distancesiter != distances_from_start.end() &&
				    fless( distancesiter->second, successor.gcost1 ) ) {
					distanceSuccessorPruning++;
					continue;
				} else
					distances_from_start[successor.s1] = successor.gcost1;
			}

		} else { // !expand
			successor.p2 = q.s2;
			successor.p1 = q.p1;
			successor.coming_from = update_coming_from( q.coming_from, expand );
			successor.s1 = q.s1;
			successor.s2 = *stateiter;
			successor.gcost1 = q.gcost1;
			transit_cost = env->GCost( q.s2, successor.s2 );
			successor.gcost2 = q.gcost2 + transit_cost;

			if( use_advanced_pruning ) {
				// check whether new successor has sub-optimal distance from the goal
				distancesiter = distances_from_goal.find( successor.s2 );
				if( distancesiter != distances_from_goal.end() &&
				    fless( distancesiter->second, successor.gcost2 ) ) {
					distanceSuccessorPruning++;
					continue;
				} else
					distances_from_goal[successor.s2] = successor.gcost2;
			}
		}

		// check whether the successor is already in the closed list
		closediter2 = closed.find( successor );
		if( closediter2 != closed.end() &&
		    successor.gcost1 + successor.gcost2 >= closediter2->gcost1 + closediter2->gcost2 )
			continue;

		// finding the hcost of the successor
		hcost = heuristicLookup( successor.s1, successor.s2, use_asymmetric_h );
		successor.fcost = successor.gcost1 + successor.gcost2 + hcost;
		successors.push_back( successor );

		max_root_hcost = std::max( max_root_hcost, hcost - transit_cost );
	} // for all successors

	if( fless( q.fcost, q.gcost1 + q.gcost2 + max_root_hcost ) ) {
		// update the hcost of the parent
		q.fcost = q.gcost1 + q.gcost2 + max_root_hcost;
		bpmxUpdates++;
	}
	// if the element was in the closed list already delete it from there
	if( closediter1 != closed.end() )
		closed.erase( closediter1 );
	// write q to the closed list
	closed.insert( q );
	// update the OPENGL drawing
	OpenGLDraw_RegisterClosedState( q );

	// now update all the hcosts of the successors (BPMX)
	for( nodeiter = successors.begin(); nodeiter != successors.end(); nodeiter++ ) {
		double transit_cost = nodeiter->gcost1 - q.gcost1 + nodeiter->gcost2 - q.gcost2;
		double hcost = nodeiter->fcost - nodeiter->gcost1 - nodeiter->gcost2;
		// maximize BPMX step
		if( hcost < max_root_hcost - transit_cost ) {
			bpmxUpdates++;
			hcost = max_root_hcost - transit_cost;
			// update the fcost
			nodeiter->fcost = nodeiter->gcost1 + nodeiter->gcost2 + hcost;
		};
		// insert into open queue
		open.push( *nodeiter );
	}

	return q;
};

// SFBDS A* implementation
template<class state, class action>
double SFBDSAStar<state,action>::astar( state s1, state s2, std::vector<state> &path, int expandheuristic_param ) {

	// reset variables
	path.clear();

	initialize( s1, s2, expandheuristic_param );

	if( s1 == s2 ) return 0.;

	QueueNode q;
	bool expanded;
	//unsigned int counter = 0;
	// iterate over the queue
	while( !open.empty() ) {
		q = step( expanded );
		// verbose
		//std::cout
		//	<< "q = (s1=" << q.s1
		//	<< " s2="     << q.s2
		//	<< " coming_from=" << q.coming_from
		//	<< " p1="     << q.p1
		//	<< " p2="     << q.p2
		//	<< " fcost="  << q.fcost
		//	<< " gcost1=" << q.gcost1
		//	<< " gcost2=" << q.gcost2
		//	<< ")" << std::endl;
		if( q.s1 == q.s2 ) break;
		// verbose
		//counter++;
		//if( counter%1000 == 0 ) {
		//	std::cout << "closed: " << closed.size() << "   open: " << open.size() << "  expanded: " << nodesExpanded << std::endl;
		//	counter = 0;
		//}
	}

	trace_back_path( q, path );

	return( q.gcost1 + q.gcost2 );
};

template<class state, class action>
unsigned int SFBDSAStar<state,action>::update_coming_from( unsigned int &old_flag, bool &expand ) {
	// we still have to code this for little endian machines

	unsigned int new_flag = old_flag;

	// set the parent bit to 1
	if( expand ) new_flag |= 1;
	else         new_flag |= 2;

	if( expand ) new_flag &= ~4; // set the third bit to 0, hence coming from p1
	else         new_flag |= 4; // set the third bit to 1, hence coming from p2

	return new_flag;
};

template<class state, class action>
void SFBDSAStar<state,action>::trace_back_path( QueueNode q, std::vector<state> &path ) {
	typename AStarClosedList::iterator closediter;

	// safety check
	assert( q.s1 == q.s2 );

	numberOfJumpsInSolution = 0;
	unsigned int coming_from = q.coming_from & 4;

	// safety if the end position does not have a parent
	path.push_back( q.s1 );

	while( q.coming_from & 3 ) {

		if( ( q.coming_from & 4 ) != coming_from ) {
			coming_from = q.coming_from & 4;
			numberOfJumpsInSolution++;
		}

		if( q.coming_from & 4 ) {
			path.insert( path.end(), q.p2 );
			q.s2 = q.p2;
		} else {
			path.insert( path.begin(), q.p1 );
			q.s1 = q.p1;
		}

		closediter = closed.find( q );
		if( closediter == closed.end() ) {
			std::cout << "ERROR: could not retrace the solution." << std::endl;
			exit(1);
		}
		q = (*closediter);
	}

	// if the first state we expanded was the goal we count this as a jump
	if( coming_from )
		numberOfJumpsInSolution++;

	return;
};

/*------------------------------------------------------------------------------
| visualization
------------------------------------------------------------------------------*/
// see astar.c for implementation
template<>
void SFBDSAStar<graphState,graphMove>::OpenGLDraw( GLdouble rad ) const;
template<>
void SFBDSAStar<graphState,graphMove>::OpenGLDraw( QueueNode q, bool side, GLdouble rad ) const;
template<>
void SFBDSAStar<xyLoc,tDirection>::OpenGLDraw( GLdouble rad ) const;
template<>
void SFBDSAStar<xyLoc,tDirection>::OpenGLDraw( QueueNode q, bool side, GLdouble rad ) const;
// compatibility
template<class state,class action>
void SFBDSAStar<state,action>::OpenGLDraw( GLdouble rad ) const {};
template<class state,class action>
void SFBDSAStar<state,action>::OpenGLDraw( QueueNode q, bool side, GLdouble rad ) const {};

template<>
void SFBDSAStar<graphState,graphMove>::OpenGLDraw_RegisterClosedState( QueueNode &q );
// for compatibility with all other states and action types
template<class state,class action>
void SFBDSAStar<state,action>::OpenGLDraw_RegisterClosedState( QueueNode &q ) {};

/*------------------------------------------------------------------------------
| heuristic for selecting which node to expand
------------------------------------------------------------------------------*/
template<class state, class action>
bool SFBDSAStar<state,action>::expandheuristic( QueueNode &q ) {

	unsigned int num_start, num_goal;
	double h_start = 0., h_goal = 0.;
	long r;
	std::vector<state> successors;
	bool result = true;

	switch( expandheuristic_param ) {
		case 0: return true; // always expand the start node
		case 1: return false; // always expand the goal node

		case 2:
			// return the side with smaller branching factor
			env->GetSuccessors( q.s1, successors );
			num_start = successors.size();
			successors.clear();
			env->GetSuccessors( q.s2, successors );
			num_goal  = successors.size();
			// verbose
			//std::cout << "comparing " << q.s1 << "@" << num_start << " with " << q.s2 << "@" << num_goal << std::endl;

			// if both sides are equal do not change previous direction
			if( num_start == num_goal && (q.coming_from&3) )
				// if q.coming_from&4 is 0 then we come from p1 => return true
				// if q.coming_from&4 is 1 then we come from p2 => return false
				return( !(bool)(q.coming_from&4) );

			// else return the side with smaller branching factor
			result = (num_start <= num_goal);
			break;

		case 3:
			// return randomly weighted with the branching factor of each side
			env->GetSuccessors( q.s1, successors );
			num_start = successors.size();
			successors.clear();
			env->GetSuccessors( q.s2, successors );
			num_goal = successors.size();
			r = random();

			result = ( (double)r < (double)RAND_MAX/(double)(num_start+num_goal) * (double)num_start );
			break;

		case 4:
			// return the side with the higher average hcost - JIL(1)
			env->GetSuccessors( q.s1, successors );
			for( typename std::vector<state>::iterator it = successors.begin(); it != successors.end(); it++ )
				h_start += heuristicLookup( *it, q.s2, use_asymmetric_h );
			h_start /= (double)successors.size();
			successors.clear();
			env->GetSuccessors( q.s2, successors );
			for( typename std::vector<state>::iterator it = successors.begin(); it != successors.end(); it++ )
				h_goal += heuristicLookup( *it, q.s1, use_asymmetric_h );
			h_goal /= (double)successors.size();
			// verbose
			//std::cout << "average hcosts for (" << q.s1 << "," << q.s2 << ") is " << h_start << " " << h_goal << std::endl;

			// if both averages are the same do not change direction
			if( fequal( h_start, h_goal ) && (q.coming_from&3) ) {
				return( !(bool)(q.coming_from&4) );
			}
			// otherwise return the side with greater average heuristic value
			result = (h_start >= h_goal);
			break;

		case 5:
			// jump if and only if both sides have branching factor of 2
			env->GetSuccessors( q.s1, successors );
			num_start = successors.size();
			successors.clear();
			env->GetSuccessors( q.s2, successors );
			num_goal  = successors.size();

			if( num_start == 2 && num_goal == 2 )
				result = (bool)(q.coming_from&4); // change direction
			else if( num_start == 2 )
				result = false;
			else if( num_goal == 2 )
				result = true;
			else
				return( !(bool)(q.coming_from&4) ); // do not change direction
			break;

		case 6:
			// jump if and only if both sides have branching factor of 2
			// use gcost as tie breaker
			env->GetSuccessors( q.s1, successors );
			num_start = successors.size();
			successors.clear();
			env->GetSuccessors( q.s2, successors );
			num_goal = successors.size();

			if( num_start == 2 && num_goal == 2 ) {
				if( fequal( q.gcost1, q.gcost2 ) && (q.coming_from&3) )
					return( !(bool)(q.coming_from&4) );
				else
					result = ( q.gcost1 <= q.gcost2 );
			}
			else if( num_start == 2 )
				result = false;
			else if( num_goal == 2 )
				result = true;
			else
				return( !(bool)(q.coming_from&4) );
			break;

		case 7: // jump if larger
			h_start = heuristicLookup( q.s1, q.s2, false );
			h_goal  = heuristicLookup( q.s2, q.s1, false );
			if( fequal( h_start, h_goal ) && (q.coming_from&3) ) { // don't jump
				return( !(bool)(q.coming_from&4) );
			}
			result = (h_start >= h_goal);
			break;
	}

	// determine whether we have a jump
	if( (bool)(q.coming_from&4) == result )
		numberOfJumps++;

	return result;
};

template<class state,class action>
double SFBDSAStar<state,action>::heuristicLookup( state &s, state &g, bool bothSides ) {
	double result = env->HCost( s, g );
	if( bothSides )
		result = std::max( result, env->HCost( g, s ) );
	return result;
};

#endif