text:
<?php

namespace Magyp\RendicionDeCajaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * EventoProveedor
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Magyp\RendicionDeCajaBundle\Entity\EventoProveedorRepository")
 */
class EventoProveedor extends Evento
{
//    /**
//     * @var integer
//     *
//     * @ORM\Column(name="id", type="integer")
//     * @ORM\Id
//     * @ORM\GeneratedValue(strategy="AUTO")
//     */
//    private $id;

    /**
     * @var Magyp\RendicionDeCajaBundle\Entity\Proveedor $proveedor
     * @ORM\ManyToOne(targetEntity="\Magyp\RendicionDeCajaBundle\Entity\Proveedor")
     * @ORM\JoinColumn(name="proveedor_id",referencedColumnName="id")
     */
    private $proveedor;

    /**
     * Set proveedor
     *
     * @param Magyp\RendicionDeCajaBundle\Entity\Proveedor $proveedor
     * @return EventoProveedor
     */
    public function setProveedor($proveedor)
    {
        $this->proveedor = $proveedor;

        return $this;
    }

    /**
     * Get proveedor
     *
     * @return string Magyp\RendicionDeCajaBundle\Entity\Proveedor
     */
    public function getProveedor()
    {
        return $this->proveedor;
    }

	function __construct($usuario, $tipoEvento, $proveedor, $proveedorAnterior = null, $request = null) {
		$this->setUsuario($usuario);
		$this->setFecha(new \DateTime());
		$this->setProveedor($proveedor);
		$this->setTipoEvento($tipoEvento);
		if(!is_null($request))$this->request = $request;
		if($tipoEvento == self::MODIFICIACION){
			//echo '<br>es modificacion';
			$modifaciones = $this->BuscarCambios($proveedorAnterior); // busca diferencias entre El comprobante This y el comprobanteAnterior.
			//var_dump($modifaciones);
			if(count($modifaciones)){ // si hay modifiaciones
				$this->setListaDeCambios($modifaciones); // asi o de otra forma,. revisar.
			}
			$this->mensajeActualizado('Accion','Se han guardado los datos del proveedor ' .$this->getProveedor()->getDescripcion());
		}
		if($tipoEvento == self::NUEVO)$this->mensajeNuevo('Accion','Se ha generado el Proveedor ' .$this->getProveedor()->getDescripcion());
		if($tipoEvento == self::BORRAR)$this->mensajeBorrar('Accion','Se ha borrado el proveedor ' .$this->getProveedor()->getDescripcion());
		if($tipoEvento == self::RESTAURAR)$this->mensajeRestaurar('Accion','Se ha restaurado el proveedor ' .$this->getProveedor()->getDescripcion());

	}
		function BuscarCambios($proveedorAnterior){
		$item = array();
		var_dump($proveedorAnterior->getDescripcion());
		var_dump($this->getProveedor()->getDescripcion());

		if(strcmp($proveedorAnterior->getDescripcion(), $this->getProveedor()->getDescripcion())){		//si hay cambios logue esto.
			$item[] = new LogRegistroDato($this, 'Descripcion', $proveedorAnterior->getDescripcion(), $this->getProveedor()->getDescripcion());
		}
		return $item;
	}

}


text:
<?php
namespace Scotch\Repositories;

use Scotch\Utilities\Utilities as Utilities;
use	Scotch\Data\SqlParameterDirections as SqlParameterDirections;

/**
* Base repository object.  Provides a few basic methods for repositories.
*
*/
abstract class SqlRepository
{
	protected $sqlSession;

	function __construct()
	{
		$this->sqlSession = $this->getSqlSession();
	}

	protected abstract function getSqlSession();

	/**
	* Parameter to extract a value from a specified array and key and provides
	* cleansing ability and the ability to grab missing keys and set those to null.
	*
	* @param array $parameters the array to look up the key in
	* @param string $key the key to lookup in the specified array
	* @return mixed the value stored at the specified key in the specified array.  If the key is not found then null is returned.
	*/
	public function getParameterValue($parameters, $key)
	{
		return Utilities::getInstance()->getValue($parameters, $key);
	}

	/**
	* Extracts the output parameters from a list of Kohva\Scotch\Data\SqlParameter objects into a list.
	*
	* @param array $dataArray the array to store the list of output parameters into
	* @param array $parameters the array of parameters to search for output parameters in.
	*/
	public function setOutputParameters(&$dataArray, $parameters)
	{
		foreach($parameters as $parameter)
		{
			if($parameter->direction != SqlParameterDirections::In)
			{
				$dataArray[$parameter->name] = $parameter->value;
			}
		}
	}
}
?>

redpajama_set_name: RedPajamaGithub


text:
import {describe, expect, it, inject, beforeEachProviders} from 'angular2/testing';
import {Property} from './property.component';
import {PropertyModel} from '../models/propertyModel';

describe('Property', () => {

  beforeEachProviders(() => [Property]);

  it('emit removeProperty event when calling remove()', inject([Property],
    (property: Property) => {
      spyOn(property.removeProperty, 'emit').and.callThrough();
      property.remove(new Event('click'), new PropertyModel({ id: 1 }));
      expect(property.removeProperty.emit).toHaveBeenCalled();
    }));

  it('emit addProperty event when calling add()', inject([Property],
    (property: Property) => {
      spyOn(property.addProperty, 'emit').and.callThrough();
      property.add(new Event('click'), new PropertyModel({ id: 1 }));
      expect(property.addProperty.emit).toHaveBeenCalled();
    }));
});


text:
AI
==========
Nez includes several different options for setting up AI ranging from a super simple transitionless finite state machine (FSM) to extendable behavior trees to ultra-flexible Utility Based AI. You can mix and match them as you see fit.

Simple State Machine
==========
The fastest and easiest way to get AI up and running. `SimpleStateMachine` is a Component subclass that lets you set an enum as its generic constraint and it will use that enum to control the state machine. The enum values each map to a state and can have optional enter/tick/exit methods. The naming conventions for these methods are best shown with an example:

```csharp
enum SomeEnum
{
    Walking,
    Idle
}

public class YourClass : SimpleStateMachine<SomeEnum>()
{
    void onAddedToEntity()
    {
        initialState = SomeEnum.Idle;
    }

    void Walking_Enter() {}
    void Walking_Tick() {}
    void Walking_Exit() {}

    void Idle_Enter() {}
    void Idle_Tick() {}
    void Idle_Exit() {}
}
```

State Machine
==========
The next step up is `StateMachine` which implements the "states as objects" pattern. `StateMachine` uses separate classes for each state so it is a better choice for more complex systems.

We start to get into the concept of a **context** with `StateMachine`. In coding, the context is just the class used to satisfy a generic constraint. in a `List<string>` the *string* would be the context class, the class that the list operates on. With all of the rest of the AI solutions you get to specify the context class. It could be your Enemy class, Player class or a helper object that contains any information relevant to your AI (such as the Player, a list of Enemies, navigation information, etc).

Here is a simple example showing the usage (with the State subclasses omitted for brevity):

```csharp
// create a state machine that will work with an object of type SomeClass as the focus with an initial state of PatrollingState
var machine = new SKStateMachine<SomeClass>( someClass, new PatrollingState() );

// we can now add any additional states
machine.addState( new AttackState() );
machine.addState( new ChaseState() );

// this method would typically be called in an update of an object
machine.update( Time.deltaTime );

// change states. the state machine will automatically create and cache an instance of the class (in this case ChasingState)
machine.changeState<ChasingState>();
```

Behavior Trees
==========
The de facto standard for composing AI for the last decade. Behavior trees are composed of a tree of nodes. Nodes can make decisions and perform actions based on the state of the world. Nez includes a `BehaviorTreeBuilder` class that provides a fluent API for setting up a behavior tree. The `BehaviorTreeBuilder` is a great way to reduce the barrier of entry to using behavior trees and get up and running quickly.

## Composites
Composites are parent nodes in a behavior tree. They house 1 or more children and execute them in different ways.

- **Sequence<T>:** returns failure as soon as one of its children returns failure. If a child returns success it will sequentially run the next child in the next tick of the tree.
- **Selector<T>:** returns success as soon as one of its child tasks return success. If a child task returns failure then it will sequentially run the next child in the next tick.
- **Parallel<T>:** runs each child until a child returns failure. It differs from `Sequence` only in that it runs all children every tick
- **ParallelSelector<T>:** like a `Selector` except it will run all children every tick
- **RandomSequence<T>:** a `Sequence` that shuffles its children before executing
- **RandomSelector<T>:** a `Selector` that shuffles its children before executing

## Conditionals
Conditionals are binary success/failure nodes. They are identified by the IConditional interface. They check some condition of your game world and either return success or failure. These are inherently game specific so Nez only provides a single generic Conditional out of the box and a helper Conditional that wraps an Action so you can avoid having to make a separate class for each Conditional.

- **RandomProbability<T>:** return success when the random probability is above the specified success probability
- **ExecuteActionConditional<T>:** wraps a Func and executes it as the Conditional. Useful for prototyping and to avoid creating separate classes for simple Conditionals.

## Decorators
Decorators are wrapper tasks that have a single child. They can modify the behavior of the child task in various ways such as inverting the result, running it until failure, etc.

- **AlwaysFail<T>:** always returns failure regardless of the child result
- **AlwaysSucceed<T>:** always returns success regardless of the child result
- **ConditionalDecorator<T>:** wraps a Conditional and will only run its child if a condition is met
- **Inverter<T>:** inverts the result of its child
- **Repeater<T>:** repeats its child task a specified number of times
- **UntilFail<T>:** keeps executing its child task until it returns failure
- **UntilSuccess<T>:** keeps executing its child task until it returns success

## Actions
Actions are the leaf nodes of the behavior tree. This is where stuff happens such as playing an animation, triggering an event, etc.

- **ExecuteAction<T>:** wraps a Func and executes it as its action. Useful for prototyping and to avoid creating separate classes for simple Actions.
- **WaitAction<T>:** waits a specified amount of time
- **LogAction<T>:** logs a string to the console. Useful for debugging.
- **BehaviorTreeReference<T>:** runs another BehaviorTree<T>

Goal Oriented Action Planning (GOAP)
==========
GOAP differs quite a bit from the other AI solutions. With GOAP, you provide the planner with a list of the actions that the AI can perform, the current world state and the desired world state (goal state). GOAP will then attempt to find a series of actions that will get the AI to the goal state.

GOAP was made popular by the old FPS F.E.A.R. The AI in F.E.A.R. consisted of a GOAP and a state machine with just 3 states: GoTo, Animate, UseSmartObject. Jeff Orkin's [web page](http://alumni.media.mit.edu/~jorkin/goap.html) is a treasure trove of great information.

## ActionPlanner
The brains of the operation. You give the ActionPlanner all of your Actions, the current world state and your goal state and it will give you back the best possible plan to achieve the goal state.

## Action/ActionT
Actions define a list of pre conditions that they require and a list of post conditions that will occur when the Action is performed. ActionT is just a subclass of Action with a handy context object of type T.

## Agent
Agent is a helper class that encapsulates an AI agent. It keeps a list of available Actions and a reference to the ActionPlanner. Agent is abstract and requires you to define the `getWorldState` and `getGoalState` methods. With those in place getting a plan is as simple as calling `agent.plan()`.

Utility Based AI
==========
Utility Theory for games. The most complex of the AI solutions. Best used in very dynamic environments where its scoring system works best. Utility based AI are more appropriate in situations where there are a large number of potentially competing actions the AI can take such as in a RTS. A great overview of utility AI is [available here](http://www.gdcvault.com/play/1012410/Improving-AI-Decision-Modeling-Through).

## Reasoner
Selects the best Consideration from a list of Considerations attached to the Reasoner. The root of a utility AI.

## Consideration
Houses a list of Appraisals and an Action. Calculates a score that represents numerically the utility of its Action.

## Appraisal
One or more Appraisals can be added to a Consideration. They calculate and return a score which is used by the Consideration.

## Action
The action that the AI executes when a specific Consideration is selected.


text:
const _ = require('lodash');

const describe = require('./util/describe');
const keys = require('./keys');
const {getSpec} = require('./def');

const wrapSpec = require('./util/wrapSpec');

function merge(...predicates) {
    const f = ({req, opt}, p) => {
        const spec = getSpec(p);
        return {
            req: _.concat(req, spec.req),
            opt: _.concat(opt, spec.opt)
        };
    };

    const {req, opt} = _.reduce(predicates, f, {req: [], opt: []});
    const spec = keys({req, opt});
    return wrapSpec(spec, 'describe', () => [merge.name, ...describe(predicates)]);
}

module.exports = merge;


text:
@interface TSNPeerBluetooth : NSObject

// Properties.
@property (nonatomic, weak) id<TSNPeerBluetoothDelegate> delegate;

// Class initializer.
- (instancetype)initWithServiceType:(NSUUID *)serviceType
                     peerIdentifier:(NSUUID *)peerIdentifier
                           peerName:(NSString *)peerName;

// Starts peer Bluetooth.
- (void)start;

// Stops peer Bluetooth.
- (void)stop;

// Updates the location.
- (void)updateLocation:(CLLocation *)location;

// Updates the status. Returns YES if successful; otherwise, NO. A return value of NO
// indicates that the status string was too long.
- (BOOL)updateStatus:(NSString *)status;

@end


text:
/*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.21.0.4666 modeling language!*/

import java.util.*;

// line 7 "WarehouseSystem.ump"
// line 148 "WarehouseSystem.ump"
public class SlotSet extends MovementLocation
{

  //------------------------
  // MEMBER VARIABLES
  //------------------------

  //SlotSet Associations
  private BoxOrPallet boxOrPallet;
  private List<Slot> slots;

  //------------------------
  // CONSTRUCTOR
  //------------------------

  public SlotSet()
  {
    super();
    slots = new ArrayList<Slot>();
  }

  //------------------------
  // INTERFACE
  //------------------------

  public BoxOrPallet getBoxOrPallet()
  {
    return boxOrPallet;
  }

  public boolean hasBoxOrPallet()
  {
    boolean has = boxOrPallet != null;
    return has;
  }

  public Slot getSlot(int index)
  {
    Slot aSlot = slots.get(index);
    return aSlot;
  }

  public List<Slot> getSlots()
  {
    List<Slot> newSlots = Collections.unmodifiableList(slots);
    return newSlots;
  }

  public int numberOfSlots()
  {
    int number = slots.size();
    return number;
  }

  public boolean hasSlots()
  {
    boolean has = slots.size() > 0;
    return has;
  }

  public int indexOfSlot(Slot aSlot)
  {
    int index = slots.indexOf(aSlot);
    return index;
  }

  public boolean setBoxOrPallet(BoxOrPallet aNewBoxOrPallet)
  {
    boolean wasSet = false;
    if (aNewBoxOrPallet == null)
    {
      BoxOrPallet existingBoxOrPallet = boxOrPallet;
      boxOrPallet = null;

      if (existingBoxOrPallet != null && existingBoxOrPallet.getSlotSet() != null)
      {
        existingBoxOrPallet.setSlotSet(null);
      }
      wasSet = true;
      return wasSet;
    }

    BoxOrPallet currentBoxOrPallet = getBoxOrPallet();
    if (currentBoxOrPallet != null && !currentBoxOrPallet.equals(aNewBoxOrPallet))
    {
      currentBoxOrPallet.setSlotSet(null);
    }

    boxOrPallet = aNewBoxOrPallet;
    SlotSet existingSlotSet = aNewBoxOrPallet.getSlotSet();

    if (!equals(existingSlotSet))
    {
      aNewBoxOrPallet.setSlotSet(this);
    }
    wasSet = true;
    return wasSet;
  }

  public static int minimumNumberOfSlots()
  {
    return 0;
  }

  public Slot addSlot(int aNumber, double aWidth, Level aLevel)
  {
    return new Slot(aNumber, aWidth, this, aLevel);
  }

  public boolean addSlot(Slot aSlot)
  {
    boolean wasAdded = false;
    if (slots.contains(aSlot)) { return false; }
    SlotSet existingSlotSet = aSlot.getSlotSet();
    boolean isNewSlotSet = existingSlotSet != null && !this.equals(existingSlotSet);
    if (isNewSlotSet)
    {
      aSlot.setSlotSet(this);
    }
    else
    {
      slots.add(aSlot);
    }
    wasAdded = true;
    return wasAdded;
  }

  public boolean removeSlot(Slot aSlot)
  {
    boolean wasRemoved = false;
    //Unable to remove aSlot, as it must always have a slotSet
    if (!this.equals(aSlot.getSlotSet()))
    {
      slots.remove(aSlot);
      wasRemoved = true;
    }
    return wasRemoved;
  }

  public boolean addSlotAt(Slot aSlot, int index)
  {
    boolean wasAdded = false;
    if(addSlot(aSlot))
    {
      if(index < 0 ) { index = 0; }
      if(index > numberOfSlots()) { index = numberOfSlots() - 1; }
      slots.remove(aSlot);
      slots.add(index, aSlot);
      wasAdded = true;
    }
    return wasAdded;
  }

  public boolean addOrMoveSlotAt(Slot aSlot, int index)
  {
    boolean wasAdded = false;
    if(slots.contains(aSlot))
    {
      if(index < 0 ) { index = 0; }
      if(index > numberOfSlots()) { index = numberOfSlots() - 1; }
      slots.remove(aSlot);
      slots.add(index, aSlot);
      wasAdded = true;
    }
    else
    {
      wasAdded = addSlotAt(aSlot, index);
    }
    return wasAdded;
  }

  public void delete()
  {
    if (boxOrPallet != null)
    {
      boxOrPallet.setSlotSet(null);
    }
    for(int i=slots.size(); i > 0; i--)
    {
      Slot aSlot = slots.get(i - 1);
      aSlot.delete();
    }
    super.delete();
  }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>de.iterable</groupId>
	<artifactId>teavm-jquery</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>

	<name>teavm-jquery</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<teavm.version>0.4.3</teavm.version>
	</properties>

	<modules>
		<module>core</module>
		<module>utils</module>
		<module>demos</module>
	</modules>

	<dependencies>
		<!-- TeaVM -->
		<!-- Emulator of Java class library for TeaVM -->
		<dependency>
			<groupId>org.teavm</groupId>
			<artifactId>teavm-classlib</artifactId>
			<version>${teavm.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JavaScriptObjects (JSO) - a JavaScript binding for TeaVM -->
		<dependency>
			<groupId>org.teavm</groupId>
			<artifactId>teavm-jso</artifactId>
			<version>${teavm.version}</version>
			<scope>provided</scope>
		</dependency>
		<!-- dependency>
			<groupId>de.iterable</groupId>
			<artifactId>teavm-utils</artifactId>
			<version>0.0.1-SNAPSHOT</version>
			<scope>provided</scope>
		</dependency-->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.1</version>
					<configuration>
						<source>${java.version}</source>
						<target>${java.version}</target>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-source-plugin</artifactId>
					<executions>
						<execution>
							<id>attach-sources</id>
							<goals>
								<goal>jar</goal>
							</goals>
						</execution>
					</executions>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>


text:
package ariba.ui.aribaweb.core;

import ariba.ui.aribaweb.util.AWArrayManager;
import ariba.ui.aribaweb.util.AWBase64;
import ariba.ui.aribaweb.util.AWBaseObject;
import ariba.ui.aribaweb.util.AWEncodedString;
import ariba.ui.aribaweb.util.Log;
import ariba.util.core.Assert;
import ariba.util.core.FastStringBuffer;
import ariba.util.core.Fmt;
import ariba.util.core.GrowOnlyHashtable;
import ariba.util.core.PerformanceStateCore;
import ariba.util.core.PerformanceStateCounter;
import ariba.util.core.StringUtil;

/**
 * Maintains a cache of AWElementIdPath's.  The ElementIdPath holds all useful representations of a path to
 * an AW element: the path itself (an array of chars), a checksum value computed from this array, and the
 * elemenId which is an Base64 encoded string version of the checksum.
 */
public class AWElementIdPath extends AWBaseObject
{
    private static GrowOnlyHashtable ElementIdPaths = new GrowOnlyHashtable();
    private static GrowOnlyHashtable ElementIdPathsByString = new GrowOnlyHashtable();
    private static int ElementIdCacheMaxSize = Integer.MAX_VALUE;
    private static final AWElementIdPath EmptyPath;
    private static final AWElementIdPath NoOpPath;
    public static final int LevelMaxSize = (int)Character.MAX_VALUE;
    public static PerformanceStateCounter ElemendIdInstantiationsCounter =
            new PerformanceStateCounter("Element Id Instantiations", 220,
                    PerformanceStateCore.LOG_COUNT);

    // Using chars here reduces memory usage for the path objects, but assumes we'll never exceed 65,535
    // at any level in a path.  For aw applications, this should be safe.
    // Note that _path is trimmed to proper length
    private final char[] _path;
    private final int _hashcode;
    private final AWEncodedString _elementId;

    static {
        AWElementIdGenerator elementIdGenerator = new AWElementIdGenerator();
        EmptyPath = AWElementIdPath.sharedInstance(elementIdGenerator);
        NoOpPath = new AWElementIdPath(new NoOpEncodedString());
    }

    public static int size ()
    {
        return ElementIdPaths.size();
    }

    protected static int computeHashcode (char[] path, int length)
    {
        // crc32Hash is a bit more crude than the CRC32, so a bit faster.
        return AWChecksum.crc32Hash(path, length);
    }

    /**
     * @param path must be a trimmed array and should not have any empty capacity on its end
     */
    private AWElementIdPath (char[] path)
    {
        _path = path;
        if (path == null) {
            _hashcode = 0;
            _elementId = null;
            Assert.that(false, "null path not allowed");
        }
        else {
            _hashcode = AWElementIdPath.computeHashcode(path, path.length);

            // Now create a short string to represent this _path.
            long checksum = AWChecksum.checksumWithLength(_path, _path.length);
            String checksumString = AWBase64.base64EncodeLong(checksum);

            // IE is case insensitive to element ids, so we need to lower case all ids
            String newElementIdString = StringUtil.strcat("_", checksumString.toLowerCase());
            int index = 0;
            Object collidingElementIdPath;
            // Iterate until no collision exists with the elementIdString. -- this should be extremely rare (1:4billion odds)
            // However, we increased the chance of collision, since we need to lower case all ids now
            while ((collidingElementIdPath = ElementIdPathsByString.get(newElementIdString)) != null) {
                char[] collidingPath = ((AWElementIdPath)collidingElementIdPath).privatePath();
                long collidingChecksum = AWChecksum.checksumWithLength(collidingPath, collidingPath.length);
                if (checksum == collidingChecksum) {
                    // report if this is a real collision (with the ids in their original form)
                    int count = 15;
                    while (count-- > 0) {
                        Log.aribaweb.debug("surprise! real collision in element id: %s", checksumString);
                    }
                }
                newElementIdString = checksumString + Integer.toString(index, 16);
                index++;
            }
            _elementId = new AWEncodedString(newElementIdString);
            ElementIdPathsByString.put(_elementId.string(), this);
        }
    }

    private AWElementIdPath (AWEncodedString encodedString)
    {
        _path = null;
        _hashcode = 0;
        _elementId = encodedString;
    }

    public static AWElementIdPath emptyPath ()
    {
        return EmptyPath;
    }

    public static AWElementIdPath noOpPath ()
    {
        return NoOpPath;
    }

    public static void setElementIdCacheMaxSize (int maxSize)
    {
        ElementIdCacheMaxSize = maxSize;
    }

    // This is the only way to get a new AWElementIdPath (maintains a cache of them)
    protected static AWElementIdPath sharedInstance (AWElementIdGenerator elementIdGenerator)
    {
        elementIdGenerator.prepareForHashlookup();
        AWElementIdPath elementIdPath = (AWElementIdPath)ElementIdPaths.get(elementIdGenerator);
        if (elementIdPath == null) {
            char[] path = (char[])elementIdGenerator.charArrayManager().trimmedArrayCopy();
            elementIdPath = new AWElementIdPath(path);
            ElemendIdInstantiationsCounter.addCount(1);
            if (ElementIdPaths.size() > ElementIdCacheMaxSize) {
                ElementIdPaths = new GrowOnlyHashtable();
                ElementIdPathsByString = new GrowOnlyHashtable();
                Log.aribawebexec_elementId.info(10547);
            }
            ElementIdPaths.put(elementIdPath, elementIdPath);
        }
        return elementIdPath;
    }

    protected static AWElementIdPath lookup (String elementIdString)
    {
        AWElementIdPath elementIdPath =
            (AWElementIdPath)ElementIdPathsByString.get(elementIdString);
        if (elementIdPath == null && Log.aribawebexec_elementId.isDebugEnabled()) {
            Log.logStack(Log.aribawebexec_elementId,
                Fmt.S(" <<< Lookup cache miss: %s should not occur unless the server has " +
                      "restarted since page was generated.", elementIdString));
        }
        return elementIdPath;
    }

    protected char get (int index)
    {
        return _path[index];
    }

    protected AWEncodedString elementId ()
    {
        return _elementId;
    }

    public int hashCode ()
    {
        // this is the hascode of the char[]
        return _hashcode;
    }

    public boolean equals (Object otherObject)
    {
        boolean isEqual = this == otherObject;
        if (!isEqual) {
            char[] thisPath = _path;
            char[] otherPath = null;
            int otherPathLength = 0;
            if (otherObject instanceof AWElementIdGenerator) {
                AWElementIdGenerator charArrayElementId = (AWElementIdGenerator)otherObject;
                // note: charArrayElementId._path may have empty capacity on the end,
                // so must use charArrayElementId._pathLength.
                AWArrayManager charArrayManager = charArrayElementId.charArrayManager();
                otherPath = (char[])charArrayManager.array();
                otherPathLength = charArrayManager.size();
            }
            else if (otherObject instanceof AWElementIdPath) {
                AWElementIdPath elementIdPath = (AWElementIdPath)otherObject;
                // here elementIdPath._path has no empty capacity on its end, so can use otherPath.thisPathLength.
                otherPath = elementIdPath._path;
                otherPathLength = otherPath.length;
            }
            else {
                return false;
            }
            int thisPathLength = thisPath.length;
            if (thisPathLength == otherPathLength) {
                isEqual = true;
                // scan backwards as its more likely that diffs will be at end
                for (int index = thisPathLength - 1; index > -1; index--) {
                    if (thisPath[index] != otherPath[index]) {
                        return false;
                    }
                }
            }
        }
        return isEqual;
    }

    protected int hashCodeSkipping (int prefixLength)
    {
        return AWChecksum.crc32Hash(_path, prefixLength, _path.length);
    }

    public boolean equalsSkipping (AWElementIdPath elementIdPath, int skipLength)
    {
        char[] thisPath = _path;
        char[] otherPath = elementIdPath._path;
        int otherPathLength = otherPath.length;
        int thisPathLength = thisPath.length;
        if (thisPathLength == otherPathLength) {
            // scan backwards as its more likely that diffs will be at end
            skipLength--;
            for (int index = thisPathLength - 1; index > skipLength; index--) {
                if (thisPath[index] != otherPath[index]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    /*
        Determines whether arg is our parent of the.  Since pushLevel() does an increment()
         followed by pushing a zero, we'll pop the trailing zero from the parent.
     */
    public boolean hasPrefix (AWElementIdPath parent)
    {
        char[] thisPath = _path;
        char[] parentPath = parent._path;

        int parentLength = parentPath.length;
        if (parentLength > thisPath.length) return false;
        // don't require match on the trailing 0 on the parent
        if (parentPath[parentLength-1] == 0) parentLength--;
        for (int i=0; i < parentLength; i++) {
            if (thisPath[i] != parentPath[i]) {
                return false;
            }
        }
        return true;
    }

    /*
        Determines whether arg is our parent or anticedent sibling, or "uncle"
     */
    public boolean isParentOrSiblingPredecessor (AWElementIdPath parent)
    {
        char[] thisPath = _path;
        char[] parentPath = parent._path;

        int parentLength = parentPath.length;
        if (parentLength > thisPath.length) return false;
        // don't require match on the trailing 0 on the parent
        for (int i=0; i < parentLength-1; i++) {
            if (thisPath[i] != parentPath[i]) {
                return false;
            }
        }
        return thisPath[parentLength-1] >= parentPath[parentLength-1];
    }

    /**
     * This should only be called by AWElementIdGenerator.nextPrefixMatches().
     * Nobody else should have access to the _path directly.
     */
    protected char[] privatePath ()
    {
        return _path;
    }

    static void debug_dumpElementIdPath (AWRequestContext requestContext,
                                         String msg,
                                         String phase)
    {
        String s = debugElementIdPath(requestContext.currentElementIdPath());
        Log.aribaweb.debug("ElementId path debug: %s -- %s -- %s --",
                           s.toString(), msg, phase);
    }

    static String debugElementIdPath (AWElementIdPath elementIdPath)
    {
        return debugElementIdPathWithDelimiter(elementIdPath, ".");
    }

    static String debugElementIdPathWithDelimiter (AWElementIdPath elementIdPath,
                                                   String delimiter)
    {
        if (elementIdPath == null) {
            return null;
        }
        char[] path = elementIdPath.privatePath();
        FastStringBuffer sb = new FastStringBuffer();
        for (int i=0; i < path.length; i++) {
            int element = (int)path[i];
            sb.append(String.valueOf(element));
            sb.append(delimiter);
        }
        return sb.toString();
    }

    public String toString ()
    {
        return _elementId.string();
    }

    static class NoOpEncodedString extends AWEncodedString
    {
        public NoOpEncodedString ()
        {
            super("");
        }

        public String toString ()
        {
            Assert.fail("No-op string cannot be rendered.");
            return super.toString();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 317663 $ -->
<refentry xml:id="function.wincache-unlock" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>wincache_unlock</refname>
  <refpurpose>
   Releases an exclusive lock on a given key
  </refpurpose>
 </refnamediv>
 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>bool</type><methodname>wincache_unlock</methodname>
   <methodparam><type>string</type><parameter>key</parameter></methodparam>
  </methodsynopsis>
  <para>
   Releases an exclusive lock that was obtained on a given key by using <function>wincache_lock</function>.
   If any other process was blocked waiting for the lock on this key, that process will be able to obtain
   the lock.
  </para>
  <warning>
   <simpara>
    Using of the <function>wincache_lock</function> and <function>wincache_unlock</function> can cause deadlocks when
    executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are
    absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to
    use these functions.
   </simpara>
  </warning>
 </refsect1>
 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>key</parameter></term>
     <listitem>
      <para>
       Name of the key in the cache to release the lock on.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>
 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   &return.success;
  </para>
 </refsect1>
 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title>Using <function>wincache_unlock</function></title>
    <programlisting role="php">
<![CDATA[
<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (wincache_lock("lock_txt_lock")) { // do an exclusive lock
    ftruncate($fp, 0); // truncate file
    fwrite($fp, "Write something here\n");
    wincache_unlock("lock_txt_lock"); // release the lock
} else {
    echo "Couldn't get the lock!";
}
fclose($fp);
?>
]]>
    </programlisting>
   </example>
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>wincache_lock</function></member>
    <member><function>wincache_ucache_set</function></member>
    <member><function>wincache_ucache_get</function></member>
    <member><function>wincache_ucache_delete</function></member>
    <member><function>wincache_ucache_clear</function></member>
    <member><function>wincache_ucache_exists</function></member>
    <member><function>wincache_ucache_meminfo</function></member>
    <member><function>wincache_ucache_info</function></member>
    <member><function>wincache_scache_info</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_title"
    tools:context=".TitleActivity"
    android:background="@color/greenBackground"
    android:keepScreenOn="true">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TextView
            android:layout_weight="2"
            android:layout_height="0dp"
            android:layout_width="fill_parent"
            android:gravity="center"
            android:typeface="serif"
            android:textStyle="bold"
            android:textSize="@dimen/large_counter_text_size"
            android:text="@string/app_name"
            android:textColor="#FFFFFF"/>

        <TextView
            android:layout_weight="1"
            android:layout_height="0dp"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:typeface="serif"
            android:textStyle="bold"
            android:textSize="@dimen/small_counter_text_size"
            android:text="@string/select_level"
            android:textColor="#FFFFFF"/>

        <LinearLayout
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:orientation="horizontal" >

            <Button
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:layout_width="0dp"
                android:layout_gravity="center"
                android:text="@string/minus"
                android:onClick="decreaseLevel" />

            <TextView
                android:layout_weight="6"
                android:id="@+id/level_num"
                android:layout_height="wrap_content"
                android:layout_width="0dp"
                android:gravity="center|bottom"
                android:typeface="serif"
                android:textStyle="bold"
                android:textSize="@dimen/small_counter_text_size"
                android:textColor="#FFFFFF"/>

            <Button
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:layout_width="0dp"
                android:layout_gravity="center"
                android:text="@string/plus"
                android:onClick="increaseLevel" />
        </LinearLayout>

        <TextView
            android:id="@+id/level_description"
            android:layout_weight="2"
            android:layout_height="0dp"
            android:layout_width="wrap_content"
            android:gravity="center"
            android:typeface="serif"
            android:textStyle="italic"
            android:textSize="@dimen/small_counter_text_size"
            android:textColor="#FFFFFF"/>

        <Button
            android:layout_weight="1"
            android:layout_height="0dp"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:text="@string/start_game"
            android:onClick="startGame" />

        <Button
            android:layout_weight="1"
            android:layout_height="0dp"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:text="@string/options"
            android:onClick="showOptions" />
    </LinearLayout>
</RelativeLayout>


text:
#import <UIKit/UIKit.h>
#import <ArcGIS/ArcGIS.h>

@interface OffsetViewController : UIViewController <AGSMapViewLayerDelegate>

@property (nonatomic, strong) IBOutlet UIToolbar *toolbar1;
@property (nonatomic, strong) IBOutlet UIToolbar *toolbar2;
@property (nonatomic, strong) IBOutlet UISegmentedControl *segmentedControl;
@property (nonatomic, strong) IBOutlet UISlider *distanceSlider;
@property (nonatomic, strong) IBOutlet UISlider *bevelSlider;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *distance;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *bevel;
@property (nonatomic, strong) IBOutlet UISegmentedControl *geometrySelect;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *addButton;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *offsetButton;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *resetButton;
@property (nonatomic, strong) IBOutlet UILabel *userInstructions;

@property (nonatomic, strong) IBOutlet AGSMapView *mapView;
@property (nonatomic, strong) AGSSketchGraphicsLayer *sketchLayer;
@property (nonatomic, strong) AGSGraphicsLayer *graphicsLayer;
@property (nonatomic, strong) NSMutableArray *lastOffset;

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>VGL compiler in browser</title>
    <link rel="stylesheet" href="../node_modules/mocha/mocha.css">


text:
const models = require('../../models');
const {i18n} = require('../../lib/common');
const errors = require('@tryghost/errors');

module.exports = {
    docName: 'webhooks',

    add: {
        statusCode: 201,
        headers: {
            // NOTE: remove if there is ever a 'read' method
            location: false
        },
        options: [],
        data: [],
        permissions: true,
        async query(frame) {
            const webhook = await models.Webhook.getByEventAndTarget(
                frame.data.webhooks[0].event,
                frame.data.webhooks[0].target_url,
                frame.options
            );

            if (webhook) {
                throw new errors.ValidationError({message: i18n.t('errors.api.webhooks.webhookAlreadyExists')});
            }

            try {
                const newWebhook = await models.Webhook.add(frame.data.webhooks[0], frame.options);
                return newWebhook;
            } catch (error) {
                if (error.errno === 1452 || (error.code === 'SQLITE_CONSTRAINT' && /SQLITE_CONSTRAINT: FOREIGN KEY constraint failed/.test(error.message))) {
                    throw new errors.ValidationError({
                        message: i18n.t('notices.data.validation.index.schemaValidationFailed', {
                            key: 'integration_id'
                        }),
                        context: i18n.t('errors.api.webhooks.nonExistingIntegrationIdProvided.context'),
                        help: i18n.t('errors.api.webhooks.nonExistingIntegrationIdProvided.help')
                    });
                }
            }
        }
    },

    edit: {
        permissions: {
            before: (frame) => {
                if (frame.options.context && frame.options.context.integration && frame.options.context.integration.id) {
                    return models.Webhook.findOne({id: frame.options.id})
                        .then((webhook) => {
                            if (!webhook) {
                                throw new errors.NotFoundError({
                                    message: i18n.t('errors.api.resource.resourceNotFound', {
                                        resource: 'Webhook'
                                    })
                                });
                            }

                            if (webhook.get('integration_id') !== frame.options.context.integration.id) {
                                throw new errors.NoPermissionError({
                                    message: i18n.t('errors.api.webhooks.noPermissionToEdit.message', {
                                        method: 'edit'
                                    }),
                                    context: i18n.t('errors.api.webhooks.noPermissionToEdit.context', {
                                        method: 'edit'
                                    })
                                });
                            }
                        });
                }
            }
        },
        data: [
            'name',
            'event',
            'target_url',
            'secret',
            'api_version'
        ],
        options: [
            'id'
        ],
        validation: {
            options: {
                id: {
                    required: true
                }
            }
        },
        query({data, options}) {
            return models.Webhook.edit(data.webhooks[0], Object.assign(options, {require: true}))
                .catch(models.Webhook.NotFoundError, () => {
                    throw new errors.NotFoundError({
                        message: i18n.t('errors.api.resource.resourceNotFound', {
                            resource: 'Webhook'
                        })
                    });
                });
        }
    },

    destroy: {
        statusCode: 204,
        headers: {},
        options: [
            'id'
        ],
        validation: {
            options: {
                id: {
                    required: true
                }
            }
        },
        permissions: {
            before: (frame) => {
                if (frame.options.context && frame.options.context.integration && frame.options.context.integration.id) {
                    return models.Webhook.findOne({id: frame.options.id})
                        .then((webhook) => {
                            if (!webhook) {
                                throw new errors.NotFoundError({
                                    message: i18n.t('errors.api.resource.resourceNotFound', {
                                        resource: 'Webhook'
                                    })
                                });
                            }

                            if (webhook.get('integration_id') !== frame.options.context.integration.id) {
                                throw new errors.NoPermissionError({
                                    message: i18n.t('errors.api.webhooks.noPermissionToEdit.message', {
                                        method: 'destroy'
                                    }),
                                    context: i18n.t('errors.api.webhooks.noPermissionToEdit.context', {
                                        method: 'destroy'
                                    })
                                });
                            }
                        });
                }
            }
        },
        query(frame) {
            frame.options.require = true;

            return models.Webhook.destroy(frame.options)
                .then(() => null)
                .catch(models.Webhook.NotFoundError, () => {
                    return Promise.reject(new errors.NotFoundError({
                        message: i18n.t('errors.api.resource.resourceNotFound', {
                            resource: 'Webhook'
                        })
                    }));
                });
        }
    }
};


text:
{% extends "base.html" %}

{% load static from staticfiles %}
{% load bootstrap %}
{% load thread_tags %}
{% load django_select2_tags %}

{% block headers %}
{% import_django_select2_js %}
{% import_django_select2_css light=1 %}
<link type="text/css" rel="stylesheet" href="{% static 'ui/css/announcements.css' %}" />
{% endblock %}

{% block content %}
{% if manager_positions %}
<button class="btn btn-primary pull-right" id="show_announcement_form" type="button"> New Announcement</button>
{% endif %}

{{ page_name }}

{% if manager_positions %}
<form id="new_announcement_form" method="post">
  {% csrf_token %}

    {{ announcement_form|bootstrap }}

        <button type="submit" class="btn btn-success" name="post_announcement">
           Announce
        </button>
        <button type="button" class="btn btn-default" id="hide_announcement_form">
           Hide
        </button>

</form>
{% endif %}
{% if not announcements_dict %}

No announcements found.

{% else %}

  {% for announcement, pin_form in announcements_dict %}
  {% if forloop.counter > 1 %}

  {% endif %}

      {{ announcement.manager }}
      ({{ announcement.incumbent|display_user:user }}), {{ announcement.post_date }}:

{{ announcement.body|safe }}
      {% if pin_form %}
      <form class="pull-right" method="post">
        {% csrf_token %}
        {{ pin_form|bootstrap }}
        {% if announcement.pinned %}
        <button type="submit" class="main_link warning_link" name="unpin" title="Unpin from homepage">Unpin</button>
        {% else %}
        <button type="submit" class="main_link success_link" name="unpin" title="Pin to homepage">Pin</button>
        {% endif %}
      </form>
      <form class="pull-right" action="{% url 'managers:edit_announcement' announcement_pk=announcement.pk %}">
        <button type="submit" class="main_link primary_link" title="Edit this announcement">Edit</button>
      </form>
      {% endif %}

  {% endfor %}
  {% endif %}

{% if announcements_dict %}

  {{ announcements_dict|length }} announcement{{ announcements_dict|length|pluralize }} in total.

{% endif %}
{% endblock %}

{% block endscripts %}

{% endblock %}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/pnor/pnor_utils.C $                                   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2011,2022                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/****************** Description *****************************************/
//This file provides a variety of utility functions primarily interacting
//with the table of contents(TOC) of pnor flash. This code is shared by HB
//with the bootloader code (/src/bootloader) so traces can be tricky,
//use the PNOR_UTIL macros to record logs.
/************************************************************************/

#include "pnor_utils.H"
#include <pnor/pnor_const.H>

#ifdef BOOTLOADER
#include <bootloader/bootloader_trace.H>
#include <bootloader/bootloader.H>
#include <bootloader/hbblreasoncodes.H>
#define PNOR_UTIL_TRACE(arg0, args...) BOOTLOADER_TRACE(arg0)
#define PNOR_UTIL_TRACE_W_BRK(arg0, args...) BOOTLOADER_TRACE_W_BRK(arg0)
#define PNOR_UTIL_TRACE_BL_SKIP(arg0, args...)

#else // HBI and HBRT

#include <errl/errlmanager.H>
#include <assert.h>

#ifdef __HOSTBOOT_RUNTIME
extern trace_desc_t* g_trac_hbrt;;
#define PNOR_UTIL_TRACE(arg0, args...) TRACFCOMP(g_trac_hbrt, args)
#define PNOR_UTIL_TRACE_W_BRK(arg0, args...) TRACFCOMP(g_trac_hbrt, args)
#define PNOR_UTIL_TRACE_BL_SKIP(arg0, args...) TRACFCOMP(g_trac_hbrt, args)

#else //HBI
extern trace_desc_t* g_trac_pnor;;
#define PNOR_UTIL_TRACE(arg0, args...) TRACFCOMP(g_trac_pnor, args)
#define PNOR_UTIL_TRACE_W_BRK(arg0, args...) TRACFCOMP(g_trac_pnor, args)
#define PNOR_UTIL_TRACE_BL_SKIP(arg0, args...) TRACFCOMP(g_trac_pnor, args)

#endif

#endif

#include "common/ffs_hb.H"
#include <util/align.H>
#include <securerom/ROM.H>

#include <pnor/pnorif.H>

/**
 * @brief calculates the checksum on data(ffs header/entry) and will return
 *    0 if the checksums match
 */
uint32_t PNOR::pnor_ffs_checksum(void* i_data, size_t i_size)
{
    uint32_t checksum = 0;
    for (size_t i = 0; i < (i_size/4); i++)
    {
        checksum ^= ((uint32_t*)i_data)[i];
    }
    checksum = htobe32(checksum);

    return checksum;
}

//RTC: 147939 Refactor Local Memset
void * localMemset(void *i_dest, int8_t i_value, uint8_t i_size)
{
    unsigned char *buf = (unsigned char *)i_dest;
    while (i_size--)
    {
        *(buf++) = (unsigned char)i_value;
    }
    return i_dest;
}

/**
* @brief Set up some initial information about the sections of the TOC.
*        The section's ID and flashAddr are set to specific values while
*        the rest of the data for the struct is set to 0.
*/
void PNOR::initializeSections(PNOR::SectionData_t io_toc[NUM_SECTIONS])
{
    for( size_t id = PNOR::FIRST_SECTION;
          id <= PNOR::NUM_SECTIONS; //include extra entry for error paths
          ++id )
    {
        localMemset(&io_toc[id], 0, sizeof(io_toc[id]));

        //Set the id to be the name corresponding to this section
        io_toc[id].id = (PNOR::SectionId)id;

        //All sections are initially set to INVALID_FLASH_OFFSET
        //this is large value that is not in the valid addressing range.
        //We chose a large value instead of 0 because the first section
        //has a flash addr of 0 and we want to avoid confusion.
        io_toc[id].flashAddr = INVALID_FLASH_OFFSET;

    }
}

/**
  * @brief Perform a series of checks on the header of the table of contents
  *        These checks include: looking for valid magic #, valid block size,
  *        valid block count, valid entry size, valid entry count, version and
  *        total size.
  *
  */
void PNOR::checkHeader (ffs_hdr* i_ffs_hdr,
                        uint32_t& io_errCode)
{
    uint64_t spaceUsed = (sizeof(ffs_entry))*i_ffs_hdr->entry_count;

    // Checking FFS Header to make sure it looks valid
    // Not breaking after one error, want to collect them all
    if(i_ffs_hdr->magic != FFS_MAGIC)
    {
        PNOR_UTIL_TRACE_W_BRK(BTLDR_TRC_UTILS_CHECKHEADER_MAGIC,
                               "E>PNOR::checkHeader: Invalid magic"
                " number in FFS header: 0x%.4X",i_ffs_hdr->magic);
        io_errCode |= INVALID_MAGIC;
    }
    if(i_ffs_hdr->version != SUPPORTED_FFS_VERSION)
    {
        PNOR_UTIL_TRACE_W_BRK(BTLDR_TRC_UTILS_CHECKHEADER_VERSION,
          "E>PNOR::checkHeader:Unsupported FFS"
                " Header version: 0x%.4X", i_ffs_hdr->version);
        io_errCode |= UNSUPPORTED_FFS;
    }
    if(i_ffs_hdr->entry_size != sizeof(ffs_entry))
    {
        PNOR_UTIL_TRACE_W_BRK(BTLDR_TRC_UTILS_CHECKHEADER_ENTRYSIZE,
                               "E>PNOR::checkHeader: Unexpected"
                " entry_size(0x%.8x) in FFS header: 0x%.4X",
                i_ffs_hdr->entry_size);
        io_errCode |= INVALID_ENTRY_SIZE;
    }
    if(i_ffs_hdr->entry_count == 0)
    {
        PNOR_UTIL_TRACE_W_BRK(BTLDR_TRC_UTILS_CHECKHEADER_ENTRYCNT,
                               "E>PNOR::checkHeader:"
                                " FFS Header pointer to entries is NULL.");
        io_errCode |= NO_ENTRIES;
    }
    if(i_ffs_hdr->block_size != PAGESIZE)
    {
        PNOR_UTIL_TRACE_W_BRK(BTLDR_TRC_UTILS_CHECKHEADER_BLOCKSIZE,
                              "E>PNOR::checkHeader:  Unsupported"
                              " Block Size(0x%.4X). PNOR Blocks must be 4k",
                              i_ffs_hdr->block_size);
        io_errCode |= INVALID_BLOCK_SIZE;
    }
    if(i_ffs_hdr->block_count == 0)
    {
        PNOR_UTIL_TRACE_W_BRK(BTLDR_TRC_UTILS_CHECKHEADER_BLOCKCNT,
                              "E>PNOR::checkHeader:  Unsupported"
                " Block COunt(0x%.4X). Device cannot be zero"
                " blocks in length.",i_ffs_hdr->block_count);
        io_errCode |= INVALID_BLOCK_COUNT;
    }
    //Make sure all the entries fit in specified partition
    //table size
    if(spaceUsed >
        ((i_ffs_hdr->block_size*i_ffs_hdr->size)-sizeof(ffs_hdr)))
    {
        PNOR_UTIL_TRACE_W_BRK(BTLDR_TRC_UTILS_CHECKHEADER_HDRSIZE,
                              "E>PNOR::checkHeader:  FFS Entries"
                        " (0x%.16X) go past end of FFS Table.",spaceUsed);
        io_errCode |= INVALID_HEADER_SIZE;

    }
    if(io_errCode != NO_ERROR)
    {
        io_errCode |= HEADER_ERR;
    }
}

/**
  * @brief Takes in an ffs_entry and returns the enum version of the section
  *         title.
  */
void PNOR::getSectionEnum (const ffs_entry* i_entry,
                           SectionId* o_secId)
{
    *o_secId = PNOR::INVALID_SECTION;
    //Figure out section enum
    for(uint32_t eyeIndex=PNOR::TOC;eyeIndex<PNOR::NUM_SECTIONS;
                      eyeIndex++)
    {
        if(strcmp(PNOR::SectionIdToString(eyeIndex),i_entry->name) == 0)
        {
            *o_secId = SectionId(eyeIndex);
            break;
        }
    }
}

/**
  * @brief Iterate through the entries, each which represent a section in pnor.
  *         During the iteration we are checking that the entries are valid
  *        and we set the sectionData_t for each section in the TOC.
  */
#ifdef BOOTLOADER
void
#else
errlHndl_t
#endif
PNOR::parseEntries (ffs_hdr* i_ffs_hdr,
                    uint32_t& io_errCode,
                    PNOR::SectionData_t * io_TOC,
                    ffs_entry*& o_err_entry)
{
#ifndef BOOTLOADER
    errlHndl_t l_errhdl = nullptr;
#endif

    //Walk through all the entries in the table and parse the data.
    for(uint32_t i=0; i<i_ffs_hdr->entry_count; i++)
    {
        ffs_entry* cur_entry = (&i_ffs_hdr->entries[i]);
        PNOR::SectionId secId = PNOR::INVALID_SECTION;

        // ffs entry check, 0 if checksums match
        if( PNOR::pnor_ffs_checksum(cur_entry, FFS_ENTRY_SIZE) != 0)
        {
            PNOR_UTIL_TRACE_W_BRK(BTLDR_TRC_UTILS_PARSE_CHECKSUM_ERROR,
                                   "E>PNOR::parseEntries:  "
                                   "Check sum error while parseing entry "
                                   "%d in TOC", i);
            io_errCode |= ENTRY_ERR;
            io_errCode |= ENTRY_CHECKSUM_ERR;
            //note the entry we failed on
            o_err_entry = cur_entry;
            //break beacuse we are going to waste time checking other entries
            break;
        }
        //Figure out section enum
        getSectionEnum(cur_entry, &secId);

        if(secId == PNOR::INVALID_SECTION)
        {
            PNOR_UTIL_TRACE_BL_SKIP(BTLDR_TRC_UTILS_PARSE_INVALID_SECTION,
                                    "PNOR::parseEntries: "
                                    "Unsupported section found while parsing "
                                    "entry %d in TOC \n Entry name is \"%s\"",
                                    i, cur_entry->name);
            //continue to skip invalid section
            continue;
        }
        ffs_hb_user_t* ffsUserData = NULL;
        ffsUserData = (ffs_hb_user_t*)&(cur_entry->user);

        //size
        io_TOC[secId].size =
                        ((uint64_t)cur_entry->size)*(i_ffs_hdr->block_size);

        //flashAddr
        io_TOC[secId].flashAddr=
                          ((uint64_t)cur_entry->base)*(i_ffs_hdr->block_size);

        //chipSelect
        io_TOC[secId].chip = ffsUserData->chip;

        //user data
        io_TOC[secId].integrity = ffsUserData->dataInteg;
        io_TOC[secId].version = ffsUserData->verCheck;
        io_TOC[secId].misc = ffsUserData->miscFlags;
        if((io_TOC[secId].flashAddr + io_TOC[secId].size) >
                (i_ffs_hdr->block_count*PAGESIZE))
        {
            PNOR_UTIL_TRACE_W_BRK(BTLDR_TRC_UTILS_PARSE_EXCEEDS_FLASH,
                                  "E>PNOR::parseEntries:  "
                                   "Exceeded flash while parsing entry "
                                   "%d in TOC \n Entry name is \"%s\"", i,
                                    cur_entry->name);
            io_errCode |= ENTRY_ERR;
            io_errCode |= ENTRY_EXTENDS_BEYOND_FLASH;
            //note the entry we failed on
            o_err_entry = cur_entry;
            break;
        }

        if (io_TOC[secId].integrity == FFS_INTEG_ECC_PROTECT)
        {
            io_TOC[secId].size = ALIGN_PAGE_DOWN
                                ((io_TOC[secId].size * 8 ) / 9);
        }

        // isEnforcedSecureSection should always handle SB compiled in or not,
        // but if that ever changes, force flag to false in PNOR TOC.
#if defined CONFIG_SECUREBOOT || defined BOOTLOADER
        io_TOC[secId].secure = PNOR::isEnforcedSecureSection(secId);
#else
        io_TOC[secId].secure = false;
#endif

        // If secureboot is compiled in, skip header if not a secure section
        // Otherwise always skip header as the secure flag is always false and
        // SpnorRp will not handle skipping the header if one is indicated in PNOR
        if ( (io_TOC[secId].version & FFS_VERS_SHA512)
              && !io_TOC[secId].secure)
        {
            //increment flash addr for sha header
            if (io_TOC[secId].integrity == FFS_INTEG_ECC_PROTECT)
            {
                io_TOC[secId].flashAddr += PAGESIZE_PLUS_ECC ;
            }
            else
            {
                io_TOC[secId].flashAddr += PAGESIZE ;
            }

            // now that we've skipped the header
            // adjust the size to reflect that
            io_TOC[secId].size -= PAGESIZE;
        }

    } // For TOC Entries

#ifndef BOOTLOADER
    return l_errhdl;
#endif

}

bool PNOR::isEnforcedSecureSection(const uint32_t i_section)
{
#if defined CONFIG_SECUREBOOT || defined BOOTLOADER
    #ifdef BOOTLOADER
        return i_section == HB_BASE_CODE;
    #else
        return i_section == HB_BOOTLOADER ||
               i_section == HB_EXT_CODE ||
               i_section == HB_DATA ||
               i_section == SBE_IPL ||
               i_section == PAYLOAD ||
#ifdef CONFIG_LOAD_PHYP_FROM_BOOTKERNEL
               i_section == BOOTKERNEL ||
#endif
               i_section == SBKT ||
               i_section == OCC ||
               i_section == HCODE ||
               i_section == HCODE_LID ||
               i_section == HB_RUNTIME ||
               i_section == WOFDATA ||
               i_section == CAPP ||
               i_section == TESTLOAD ||
               i_section == VERSION ||
               i_section == OCMBFW;
    #endif
#else
    return false;
#endif
}

bool PNOR::isCoreRootOfTrustSection(const PNOR::SectionId i_section)
{
#if defined CONFIG_SECUREBOOT || defined BOOTLOADER
    #ifdef BOOTLOADER
        return i_section == HB_BASE_CODE;
    #else
        return i_section == HB_BOOTLOADER ||
               i_section == HB_EXT_CODE ||
               i_section == HB_DATA ||
               i_section == SBE_IPL ||
               i_section == HB_BASE_CODE;
    #endif
#else
    return false;
#endif
}

const char * PNOR::SectionIdToString( uint32_t i_secIdIndex )
{
    /**
     * Eyecatcher strings for PNOR TOC entries
     * Use an array vs switch statement for O(1) lookup
     * Not using std::array so we can check the actual size filled in vs N
     *   in std:array<const char*, N>.
     */
    static const char* SectionIdToStringArr[] =
    {
        "part",        /**< PNOR::TOC            : Table of Contents */
#ifndef BOOTLOADER
        "HBI",         /**< PNOR::HB_EXT_CODE    : Hostboot Extended Image */
#endif
        "HBB",         /**< PNOR::HB_BASE_CODE   : Hostboot Base Image */
#ifndef BOOTLOADER
        "SBE",         /**< PNOR::SBE_IPL        : Self-Boot Enginer IPL image */
        "HCODE",       /**< PNOR::HCODE          : HCODE Reference image */
        "PAYLOAD",     /**< PNOR::PAYLOAD        : HAL/OPAL */
        "HBRT",        /**< PNOR::HB_RUNTIME     : Hostboot Runtime(for Sapphire)*/
        "HBD",         /**< PNOR::HB_DATA        : Hostboot Data */
        "GUARD",       /**< PNOR::GUARD_DATA     : Hostboot Data */
        "HBEL",        /**< PNOR::HB_ERRLOGS     : Hostboot Error log Repository */
        "DJVPD",       /**< PNOR::DIMM_JEDEC_VPD : Dimm JEDEC VPD */
        "MVPD",        /**< PNOR::MODULE_VPD     : Module VPD */
        "NVRAM",       /**< PNOR::NVRAM          : OPAL Storage */
        "OCC",         /**< PNOR::OCC            : OCC LID */
        "FIRDATA",     /**< PNOR::FIRDATA        : DEPRECATED: FIRs for checkstop analysis */
        "ATTR_TMP",    /**< PNOR::ATTR_TMP       : Temporary Attribute Overrides */
        "ATTR_PERM",   /**< PNOR::ATTR_PERM      : Permanent Attribute Overrides */
        "CAPP",        /**< PNOR::CAPP           : CAPP LID */
        "VERSION",     /**< PNOR::VERSION        : PNOR Version string */
        "HBBL",        /**<PNOR::HB_BOOTLOADER   : Hostboot Bootloader image */
        "TEST",        /**< PNOR::TEST           : Test space for PNOR*/
        "TESTRO",      /**< PNOR::TESTRO         : ReadOnly Test space for PNOR */
        "BACKUP_PART", /**PNOR::BACKUP_PART      : Backup of PART*/
        "RINGOVD",     /**< PNOR::RINGOVD        : Ring overrides */
        "WOFDATA",     /**< PNOR::WOFDATA        : VFRT data tables for WOF */
        "SBKT",        /**< PNOR::SBKT           : SecureBoot Key Transition */
        "HB_VOLATILE", /**< PNOR::HB_VOLATILE    : Semi volatile partition */
        "TESTLOAD",    /**< PNOR::TESTLOAD       : Secureboot Test Load */
        "HDAT",        /**< PNOR::HDAT           : Hdat Data */
        "EECACHE",     /**< PNOR::EECACHE        : Cached data from various EEPROMs */
        "OCMBFW",      /**< PNOR::OCMBFW         : OCMB image */
#ifdef CONFIG_DEVTREE
        "DEVTREE",     /**< PNOR::DEVTREE        : DEVTREE image */
#endif
#ifdef CONFIG_LOAD_PHYP_FROM_BOOTKERNEL
        "BOOTKERNEL",  /**< PNOR::BOOTKERNEL     : OPAL == petitboot,PHYP == PowerVM */
#endif
        "HCODE_LID",   /**< PNOR::HCODE_LID      : HCODE_LID Reference image */
        "HBD_RW",      /**< PNOR::HB_DATA_RW     : Hostboot Data ReadWrite   */
#endif
    };

    // Get actual number of entries of array.
    const size_t numEntries = sizeof(SectionIdToStringArr)/sizeof(char*);

    // Assert that the number of entries equals PNOR::NUM_SECTIONS
    static_assert (numEntries == (PNOR::NUM_SECTIONS),
               "Mismatch between number of SectionIds and correlating strings");

    // Assert if accessing index out of array or not INVALID section
    assert(i_secIdIndex <= (PNOR::NUM_SECTIONS),
#ifdef BOOTLOADER
           BTLDR_TRC_UTILS_PNOR_SECID_OUT_OF_RANGE,
           Bootloader::RC_PNOR_SECID_OUT_OF_RANGE
#else
           "SectionIdToString PNOR section id out of range"
#endif
    );

    const char * l_str = "INVALID_SECTION";
    if(i_secIdIndex < PNOR::INVALID_SECTION)
    {
       l_str = SectionIdToStringArr[i_secIdIndex];
    }

    return l_str;
}

#ifndef BOOTLOADER
const char * PNOR::SectionIdToRTString(uint32_t i_secIdIndex)
{
    const char * str = "INVALID SECTION";
    if(i_secIdIndex == PNOR::HB_DATA)
    {
        str = "HBD_RT";
    }
    else if(i_secIdIndex == PNOR::WOFDATA)
    {
        str = "WOFDATA_RT";
    }
    return str;
}
#endif

bool PNOR::cmpSecurebootMagicNumber(const uint8_t* i_vaddr)
{
    // Assert if accessing index out of array.
    assert(i_vaddr != nullptr,
#ifdef BOOTLOADER
           BTLDR_TRC_UTILS_CMP_MAGIC_NUM_NULLPTR,
           Bootloader::RC_PNOR_NULLPTR
#else
           "cmpSecurebootMagicNumber requested address to compare is a nullptr"
#endif
    );

    return memcmp(&ROM_MAGIC_NUMBER, i_vaddr, sizeof(ROM_MAGIC_NUMBER))==0;
}


text:
using namespace noise::module;

Select::Select ():
  Module (GetSourceModuleCount ()),
  m_edgeFalloff (DEFAULT_SELECT_EDGE_FALLOFF),
  m_lowerBound (DEFAULT_SELECT_LOWER_BOUND),
  m_upperBound (DEFAULT_SELECT_UPPER_BOUND)
{
}

double Select::GetValue (double x, double y, double z) const
{
  assert (m_pSourceModule[0] != NULL);
  assert (m_pSourceModule[1] != NULL);
  assert (m_pSourceModule[2] != NULL);

  double controlValue = m_pSourceModule[2]->GetValue (x, y, z);
  double alpha;
  if (m_edgeFalloff > 0.0) {
    if (controlValue < (m_lowerBound - m_edgeFalloff)) {
      // The output value from the control module is below the selector
      // threshold; return the output value from the first source module.
      return m_pSourceModule[0]->GetValue (x, y, z);

    } else if (controlValue < (m_lowerBound + m_edgeFalloff)) {
      // The output value from the control module is near the lower end of the
      // selector threshold and within the smooth curve. Interpolate between
      // the output values from the first and second source modules.
      double lowerCurve = (m_lowerBound - m_edgeFalloff);
      double upperCurve = (m_lowerBound + m_edgeFalloff);
      alpha = SCurve3 (
        (controlValue - lowerCurve) / (upperCurve - lowerCurve));
      return LinearInterp (m_pSourceModule[0]->GetValue (x, y, z),
        m_pSourceModule[1]->GetValue (x, y, z),
        alpha);

    } else if (controlValue < (m_upperBound - m_edgeFalloff)) {
      // The output value from the control module is within the selector
      // threshold; return the output value from the second source module.
      return m_pSourceModule[1]->GetValue (x, y, z);

    } else if (controlValue < (m_upperBound + m_edgeFalloff)) {
      // The output value from the control module is near the upper end of the
      // selector threshold and within the smooth curve. Interpolate between
      // the output values from the first and second source modules.
      double lowerCurve = (m_upperBound - m_edgeFalloff);
      double upperCurve = (m_upperBound + m_edgeFalloff);
      alpha = SCurve3 (
        (controlValue - lowerCurve) / (upperCurve - lowerCurve));
      return LinearInterp (m_pSourceModule[1]->GetValue (x, y, z),
        m_pSourceModule[0]->GetValue (x, y, z),
        alpha);

    } else {
      // Output value from the control module is above the selector threshold;
      // return the output value from the first source module.
      return m_pSourceModule[0]->GetValue (x, y, z);
    }
  } else {
    if (controlValue < m_lowerBound || controlValue > m_upperBound) {
      return m_pSourceModule[0]->GetValue (x, y, z);
    } else {
      return m_pSourceModule[1]->GetValue (x, y, z);
    }
  }
}

void Select::SetBounds (double lowerBound, double upperBound)
{
  assert (lowerBound < upperBound);

  m_lowerBound = lowerBound;
  m_upperBound = upperBound;

  // Make sure that the edge falloff curves do not overlap.
  SetEdgeFalloff (m_edgeFalloff);
}

void Select::SetEdgeFalloff (double edgeFalloff)
{
  // Make sure that the edge falloff curves do not overlap.
  double boundSize = m_upperBound - m_lowerBound;
  m_edgeFalloff = (edgeFalloff > boundSize / 2)? boundSize / 2: edgeFalloff;
}


text:
package service

import (
	"fmt"
	"net/http"
	"path"
	"strings"

	"sync"

	"context"

	"github.com/speedland/go/gae/service/config"
	xtaskqueue "github.com/speedland/go/gae/taskqueue"
	"github.com/speedland/go/web"
	"github.com/speedland/go/web/middleware/session"
	"github.com/speedland/go/web/response"
	"github.com/speedland/go/web/response/view"
	"github.com/speedland/go/x/xcontext"
	"google.golang.org/appengine"
)

// ContextKey is a key to get a service.
var ContextKey = xcontext.NewKey("service")

// Service is a set of endpoints
type Service struct {
	Init      func(*web.Request)
	Every     func(*web.Request)
	OnError   func(*web.Request, error) *response.Response
	Config    *config.Config // Configuration that admin can update.
	APIConfig *BuiltInAPIConfig
	once      sync.Once // for Init control
	key       string    // service key
	urlPrefix string    // url base path
	namespace string    // datastore/memcache namespace for services
	crons     []*Cron
	queues    []*xtaskqueue.PushQueue
	tasks     []*Task
	router    *web.Router // service router
}

// FromContext returns a service object associated with the context
func FromContext(ctx context.Context) *Service {
	service, ok := ctx.Value(ContextKey).(*Service)
	if ok {
		return service
	}
	return nil
}

// WithContext returns a new context.Context associated with the service
func WithContext(ctx context.Context, s *Service) context.Context {
	return context.WithValue(ctx, ContextKey, s)
}

// MustFromContext is like FromContext but panics if a service is not in the context
func MustFromContext(ctx context.Context) *Service {
	service, ok := ctx.Value(ContextKey).(*Service)
	if !ok {
		panic(fmt.Errorf("not a service context"))
	}
	return service
}

// New returns a new *Service instance
func New(key string) *Service {
	return NewWithURLAndNamespace(
		key,
		strings.Replace(key, "-", "/", -1),
		strings.Replace(key, "-", ".", -1),
	)
}

// NewWithURLAndNamespace is like New with using the given url prefix and namespece instead of 'key' value.
func NewWithURLAndNamespace(key string, url string, namespace string) *Service {
	if key == "" {
		panic(fmt.Errorf("service key must not be nil"))
	}
	option := &web.Option{
		HMACKey: web.DefaultOption.HMACKey,
		InitContext: func(r *http.Request) context.Context {
			return appengine.NewContext(r)
		},
	}
	s := &Service{
		key:       key,
		urlPrefix: url,
		namespace: namespace,
		router:    web.NewRouter(option),
		Config:    config.New(),
		APIConfig: &BuiltInAPIConfig{
			AuthNamespace: "",
		},
	}
	s.router.Use(namespaceMiddleware(s))
	s.router.Use(errorMiddleware)
	s.Use(initMiddleware)
	s.Use(session.Default)
	s.Use(everyMiddleware)
	return s
}

// Run register the service on http.Hander
func (s *Service) Run() {
	http.Handle("/", s.router)
}

// ServeHTTP implements http.Handler#ServeHTTP
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.router.ServeHTTP(w, r)
}

// Key returns a key string
func (s *Service) Key() string {
	return s.key
}

// URLPrefix returns a url prefix string
func (s *Service) URLPrefix() string {
	return s.urlPrefix
}

// Namespace returns a namespace string
func (s *Service) Namespace() string {
	return s.namespace
}

// WithNamespace sets the namespace of the given context
func (s *Service) WithNamespace(ctx context.Context) context.Context {
	ctx, err := appengine.Namespace(ctx, s.namespace)
	if err != nil {
		panic(err)
	}
	return ctx
}

// Use adds the middleware onto the service router
func (s *Service) Use(handlers ...web.Handler) {
	s.router.Use(handlers...)
}

// Get defines an endpoint for GET
func (s *Service) Get(path string, handlers ...web.Handler) {
	s.router.Get(s.Path(path), handlers...)
}

// Post defines an endpoint for POST
func (s *Service) Post(path string, handlers ...web.Handler) {
	s.router.Post(s.Path(path), handlers...)
}

// Put defines an endpoint for PUT
func (s *Service) Put(path string, handlers ...web.Handler) {
	s.router.Put(s.Path(path), handlers...)
}

// Delete defines an endpoint for DELETE
func (s *Service) Delete(path string, handlers ...web.Handler) {
	s.router.Delete(s.Path(path), handlers...)
}

// Page defines an endpoint for view.Page interaface
func (s *Service) Page(path string, p view.Page) {
	view.Mount(s.router, s.Path(path), p)
}

// Path returns an absolute path for this s.
func (s *Service) Path(p string) string {
	if s.urlPrefix != "" {
		if path.Ext(p) == "" {
			return path.Join("/", s.urlPrefix, p) + "/"
		}
		return path.Join("/", s.urlPrefix, p)
	}
	if p == "/" {
		return p
	}
	if path.Ext(p) == "" {
		return path.Join(p) + "/"
	}
	return p
}


text:
package org.eclipse.rdf4j.console.setting;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

/**
 * Test log level setting
 *
 * @author Bart Hanssens
 */
public class LogLevelTest extends AbstractSettingTest {
	private Level originalLevel;

	@BeforeEach
	@Override
	public void setUp() {
		originalLevel = ((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).getLevel();
		settings.put(LogLevel.NAME, new LogLevel());
		super.setUp();
	}

	@AfterEach
	public void tearDown() throws Exception {
		((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(originalLevel);
	}

	@Test
	public void testNoValueShowsCurrentLevel() {
		Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
		logger.setLevel(Level.INFO);

		setParameters.execute("set", "log");

		verify(mockConsoleIO).writeln("log: info");
		verifyNoMoreInteractions(mockConsoleIO);
	}

	@Test
	public void testSettingLogChangesLevel() {
		Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
		logger.setLevel(Level.DEBUG);

		setParameters.execute("set", "log=warning");

		assertEquals(Level.WARN, logger.getLevel());
	}

	@Test
	public void testSettingUnknownLevelIsLoggedAsError() {
		setParameters.execute("set", "log=chatty");

		verify(mockConsoleIO).writeError("unknown logging level: chatty");
		verifyNoMoreInteractions(mockConsoleIO);
	}

	@Test
	public void testLevelsThatDoNotMatchSlf4jAreMapped() {
		Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
		logger.setLevel(Level.WARN);

		setParameters.execute("set", "log");

		verify(mockConsoleIO).writeln("log: warning");
		verifyNoMoreInteractions(mockConsoleIO);
	}
}


text:
'use strict';

var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var bleetService = require('./../src/server/bleet-service/index.js');
var userService = require('./../src/server/user-service/index.js');

var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');

var util = require('util');

var proxyMiddleware = require('http-proxy-middleware');

function browserSyncInit(baseDir, browser) {
  browser = browser === undefined ? 'default' : browser;

  var routes = null;
  if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
    routes = {
      '/bower_components': 'bower_components'
    };
  }

  var server = {
    baseDir: baseDir,
    routes: routes
  };

  //init the server
  var bleetServicePort = 3003;
  var userServicePort = 3004;
  var bleetServiceMiddleware = bleetService(bleetServicePort);
  var userServiceMiddleWare = userService(userServicePort);

  /*
   * You can add a proxy to your backend by uncommenting the line below.
   * You just have to configure a context which will we redirected and the target url.
   * Example: $http.get('/users') requests will be automatically proxified.
   *
   * For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.9.0/README.md
   */
  server.middleware = [
    proxyMiddleware('/api/bleets', {target: 'http://localhost:' + bleetServicePort, changeOrigin: true}),
    proxyMiddleware('/api/users', {target: 'http://localhost:' + userServicePort, changeOrigin: true})
  ];

  browserSync.instance = browserSync.init({
    startPath: '/',
    server: server,
    browser: browser,
    online: true
  });
}

browserSync.use(browserSyncSpa({
  selector: '[ng-app]'// Only needed for angular apps
}));

gulp.task('serve', ['watch'], function () {
  browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});

gulp.task('serve:dist', ['build'], function () {
  browserSyncInit(conf.paths.dist);
});

gulp.task('serve:e2e', ['inject'], function () {
  browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});

gulp.task('serve:e2e-dist', ['build'], function () {
  browserSyncInit(conf.paths.dist, []);
});


text:
II.3 Land Development Financing

Financing – Land Development (II.3.)

Land acquisitions require
    equity (and some debt).

The land for development is usually funded by equity capital.

Sometimes debt capital is used to acquire the property

Construction requires accruing debt for hard costs, equity contributions for soft costs.

Some or all direct construction costs (aka hard costs) can be funded with an interest accruing construction loan
        from a commercial bank.

Indirect construction costs aka soft costs) are usually funded with equity capital.

Land sales require a "release price" to remove the building ready land parcels from the construction
    mortgage.

Finished building lots that are being sold to a building developers must be "released" from the construction
        mortgage lien.

This release requires a payment to the construction lender that exceeds the pro-rata share of the finished
        building lot's value in the entire encumbered property.

The construction lender's intent is have the loan paid off before all of the lots are sold.

This effectively delays the land developer's cash proceeds until the last lots are sold.

Performance or completion bonds are required.

These bonds assure the bond holder (the lender) that the bonding company will funds provided need to complete
        the development in the event the contractor defaults during construction.

Fiduciary bonds.

These bond provide a financial guaranty to the municipality in the event that the improvements fail after
        construction .

This is a "beat the clock" game. Can the building lots be sold before the construction mortgage comes due?

The land developer must be ready to start construction as soon as the land is acquired so that the improvements
        can be constructed and the building lots are sold prior to the end of the construction loan term.

 Otherwise, the construction loans must be extended or paid off.

Determine the financing of subsequent phases.

A large land development usually is built in phases.

Consequently, the land developer must determine a way to 'bank" the subsequent phases while the current phase is
        under construction.

Delayed closing provision in the original sale s agreement.

 Option to purchase the future phases when they are ready for development.

Equity investors.

Land contracts.

A good example of the financing of a land development for a warehouse industrial office part would be: http://dankohlhepp.com/uploads/3/0/6/8/3068213/war._1985_t.l._james.pdf


text:
import supertest from "supertest"
import api from "./api"

const path = "./test-data/songs"
const request = supertest(api({ path }))

test("200 for song list", () =>
  request
    .get("/songs")
    .expect("Content-Type", /json/)
    .expect(200)
    .then(({ body }) => expect(body).toMatchSnapshot()))

test("400 for invalid id", () =>
  request.get("/song/this is invalid.doc").expect(400, /Invalid song ID/))

test("404 for unknown file", () =>
  request
    .get("/song/unknown-song")
    .expect(404, /Cannot GET \/song\/unknown-song/))

test("200 for known file", () =>
  request
    .get("/song/test-song")
    .expect(200)
    .then(({ body }) => expect(body.toString()).toMatchSnapshot()))


text:
@implementation TJBusClient

+ (TJBusClient *)sharedClient{
    static TJBusClient *sharedClient = nil;
    static dispatch_once_t token;
    dispatch_once(&token,^{
        sharedClient = [[TJBusClient alloc]init];
    });

    return sharedClient;
}

- (void)GET:(NSString *)api
 parameters:(NSDictionary *)parameters
    success:(void (^)(AFHTTPRequestOperation *, id))success{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *url = [NSString stringWithFormat:@"%@%@",BASE_URL,api];

    [manager GET:url
      parameters:parameters
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             success(operation,responseObject);
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             success(operation,nil);
             NSLog(@"Error: %@", error);
    }];
}

- (void)getAllRouteWithID:(NSString *)idNumber
                 password:(NSString *)password
          andSuccessBlock:(void (^) (NSDictionary *)) block{
    [self GET:GET_ROUTE
   parameters:@{@"username" : idNumber,@"password" : password, @"weekend" : @0}
      success:^(AFHTTPRequestOperation *operation, id responseObject){
          NSDictionary *dic = responseObject;
          block(dic);
      }];
}

- (void)getTimeTableWithRouteId:(NSString *)idNumber
                andSuccessBlock:(void (^) (NSArray *)) block{
    [self GET:GET_TIMETABLE
   parameters:@{@"route_id" : idNumber}
      success:^(AFHTTPRequestOperation *operation, id responseObject){
          NSArray *array = responseObject;
          block(array);
      }];
}

@end


text:
//
//  WebHelpers.h
//  opendatacon
//
//  Created by Alan Murray on 14/09/2014.
//
//

#ifndef __opendatacon__WebHelpers__
#define __opendatacon__WebHelpers__

#include <opendatacon/asio.h>
#include <opendatacon/util.h>
#include <opendatacon/ParamCollection.h>
#ifdef USE_HTTPS
#include <server_https.hpp>
using WebServer = SimpleWeb::Server<SimpleWeb::HTTPS>;
#define OPTIONAL_CERTS web_crt, web_key
#else
#include <server_http.hpp>
using WebServer = SimpleWeb::Server<SimpleWeb::HTTP>;
#define OPTIONAL_CERTS
#endif
#include <fstream>
#include <string>
#include <unordered_map>

const std::string& GetMimeType(const std::string& rUrl);
void read_and_send(const std::shared_ptr<WebServer::Response> response, const std::shared_ptr<std::ifstream> ifs, const std::shared_ptr<std::vector<char>> buffer);

#endif /* defined(__opendatacon__WebHelpers__) */


text:
const fs = require('fs')
const path = require('path')

var file = fs.readFileSync(path.join(__dirname, 'config.json'), 'utf-8')
file = file.replace(/\/\*[\s\S]+?\*\//g, '')
json = JSON.parse(file)
if (json.imageManagerListPath.substr(0, 1) != '/') {
    json.imageManagerListPath =  '/' + json.imageManagerListPath
}
if (json.fileManagerListPath.substr(0, 1) != '/') {
    json.fileManagerListPath = '/' + json.fileManagerListPath
}
module.exports = json


text:
package com.github.florent37.materialviewpager.worldmovies.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.github.florent37.materialviewpager.worldmovies.Config;
import com.github.florent37.materialviewpager.worldmovies.R;
import com.github.florent37.materialviewpager.worldmovies.adapter.SearchResultsAdapter;
import com.github.florent37.materialviewpager.worldmovies.framework.CredentialsHandler;
import com.github.florent37.materialviewpager.worldmovies.framework.ResultListScrollListener;
import com.github.florent37.materialviewpager.worldmovies.framework.Search;
import com.github.florent37.materialviewpager.worldmovies.framework.SearchPresenter;
import com.github.florent37.materialviewpager.worldmovies.http.CustomJSONObjectRequest;
import com.github.florent37.materialviewpager.worldmovies.http.CustomVolleyRequestQueue;
import com.github.florent37.materialviewpager.worldmovies.model.TrendsObject;
import com.spotify.sdk.android.player.Spotify;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.TimeUnit;

import kaaes.spotify.webapi.android.models.Track;

/**
 * Created by aaron on 2016/8/26.
 */
public class TrendsMusicTabFragment extends Fragment implements Search.View {
    private TrendsObject trendsObject;
    private RecyclerView resultsList;
    private SearchView searchView;
    private RequestQueue mQueue;
    private TrendsMusicTabFragment musicTabFragment;
    private LinearLayoutManager searchLayoutManager;
    private Search.ActionListener mActionListener;
    private static final String KEY_CURRENT_QUERY = "CURRENT_QUERY";
    private com.spotify.sdk.android.player.Player mPlayer;
    private SearchResultsAdapter searchAdapter;
    private ScrollListener mScrollListener;

    public static TrendsMusicTabFragment newInstance(TrendsObject trendsObject) {
        TrendsMusicTabFragment fragment = new TrendsMusicTabFragment();
        Bundle args = new Bundle();
        args.putSerializable("trends", trendsObject);
        fragment.setArguments(args);
        return fragment;
    }

    private class ScrollListener extends ResultListScrollListener {

        public ScrollListener(LinearLayoutManager layoutManager) {
            super(layoutManager);
        }

        @Override
        public void onLoadMore() {
            mActionListener.loadMoreResults();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
        musicTabFragment = this;
        trendsObject = (TrendsObject) getArguments().getSerializable("trends");
        final View view = inflater.inflate(R.layout.music_fragment, container, false);
        String token = CredentialsHandler.getToken(getActivity());

        if (token != null) {

            setupPlayer(token, view);

            if (savedInstanceState != null) {
                String currentQuery = savedInstanceState.getString(KEY_CURRENT_QUERY);
                mActionListener.search(currentQuery);
            }

        } else {

            mQueue = CustomVolleyRequestQueue.getInstance(getActivity()).getRequestQueue();
            CustomJSONObjectRequest jsonRequest_q = null;
            String refreshToken = CredentialsHandler.getRefreshToken(getActivity());
            String url = Config.HOST_NAME+"refresh_token?refresh_token="+refreshToken;

            jsonRequest_q = new CustomJSONObjectRequest(Request.Method.GET, url, new JSONObject(), new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        Log.d("0828", String.valueOf(response));
                        long expires_in = 3600;
                        String token = response.getString("access_token");
                        CredentialsHandler.setToken(getActivity(), token, expires_in, TimeUnit.SECONDS);
                        setupPlayer(token, view);

                        if (savedInstanceState != null) {
                            String currentQuery = savedInstanceState.getString(KEY_CURRENT_QUERY);
                            mActionListener.search(currentQuery);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
//                    Toast.makeText(getActivity(), "Remote Server connect fail!", Toast.LENGTH_SHORT).show();
                }
            });

            mQueue.add(jsonRequest_q);
        }

        return view;
    }

    public void setupPlayer(String token, View view) {
        com.spotify.sdk.android.player.Config playerConfig = new com.spotify.sdk.android.player.Config(getActivity(), token, Config.CLIENT_ID);
        mPlayer = Spotify.getPlayer(playerConfig, this, new com.spotify.sdk.android.player.Player.InitializationObserver() {
            @Override
            public void onInitialized(com.spotify.sdk.android.player.Player player) {
            }

            @Override
            public void onError(Throwable throwable) {
                Log.e("MainActivity", "Could not initialize player: " + throwable.getMessage());
            }
        });

        searchLayoutManager = new LinearLayoutManager(getActivity());
        mScrollListener = new ScrollListener(searchLayoutManager);
        mActionListener = new SearchPresenter(getActivity(), this, mPlayer);
        mActionListener.init(token);
        // Setup search results list
        searchAdapter = new SearchResultsAdapter(getActivity(), new SearchResultsAdapter.ItemSelectedListener() {
            @Override
            public void onItemSelected(View itemView, Track item) {
                mActionListener.selectTrack(item);
            }
        });
        resultsList = (RecyclerView) view.findViewById(R.id.search_results);
        resultsList.setHasFixedSize(true);
        resultsList.setLayoutManager(searchLayoutManager);
        resultsList.setAdapter(searchAdapter);
        resultsList.addOnScrollListener(mScrollListener);
//        mPlayer.play("spotify:track:5RkoL37LfZVEyYaHEvKgTc");
        // Setup search field
        searchView = (SearchView) view.findViewById(R.id.search_view);
        int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView textView = (TextView) view.findViewById(id);
        textView.setTextColor(Color.BLACK);

        searchView.post(new Runnable() {
            @Override
            public void run() {
                searchView.setQuery(trendsObject.getTitle(), true);
            }
        });

        searchView.clearFocus();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                mActionListener.search(query);
                searchView.clearFocus();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mActionListener!= null)
            mActionListener.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mActionListener!= null)
            mActionListener.resume();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mActionListener!= null)
            if (mActionListener.getCurrentQuery() != null) outState.putString(KEY_CURRENT_QUERY, mActionListener.getCurrentQuery());

    }

    @Override
    public void reset() {
        mScrollListener.reset();
        searchAdapter.clearData();
    }

    @Override
    public void addData(List<Track> items) {
        searchAdapter.addData(items);
    }

    @Override
    public void onDestroy() {
        if (mActionListener!= null)
            mActionListener.destroy();
        super.onDestroy();
    }
}


text:
service "apparmor" do
  action :nothing
  supports [ :restart, :reload, :status ]
end