text:
package com.cloud.network;

import com.cloud.dc.DataCenter;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.framework.config.ConfigKey;
import com.cloud.network.addr.PublicIp;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.StaticNat;
import com.cloud.user.Account;
import com.cloud.utils.db.DB;
import com.cloud.vm.NicProfile;
import com.cloud.vm.VirtualMachineProfile;

import java.util.List;

public interface IpAddressManager {
    static final String UseSystemPublicIpsCK = "use.system.public.ips";
    static final ConfigKey<Boolean> UseSystemPublicIps = new ConfigKey<>("Advanced", Boolean.class, UseSystemPublicIpsCK, "true",
            "If true, when account has dedicated public ip range(s), once the ips dedicated to the account have been consumed ips will be acquired from the system pool",
            true, ConfigKey.Scope.Account);

    /**
     * Assigns a new public ip address.
     *
     * @param dcId
     * @param podId       TODO
     * @param owner
     * @param type
     * @param networkId
     * @param requestedIp TODO
     * @param allocatedBy TODO
     * @return
     * @throws InsufficientAddressCapacityException
     */
    PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isSystem)
            throws InsufficientAddressCapacityException;

    /**
     * Do all of the work of releasing public ip addresses. Note that if this method fails, there can be side effects.
     *
     * @param userId
     * @param caller    TODO
     * @param IpAddress
     * @return true if it did; false if it didn't
     */
    boolean disassociatePublicIpAddress(long id, long userId, Account caller);

    boolean applyRules(List<? extends FirewallRule> rules, FirewallRule.Purpose purpose, NetworkRuleApplier applier, boolean continueOnError)
            throws ResourceUnavailableException;

    /**
     * @param userId
     * @param accountId
     * @param zoneId
     * @param vlanId
     * @throws ResourceAllocationException          TODO
     * @throws InsufficientCapacityException        Associates an ip address list to an account. The list of ip addresses are all addresses associated
     *                                              with the
     *                                              given vlan id.
     * @throws InsufficientAddressCapacityException
     * @throws
     */
    boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network guestNetwork) throws InsufficientCapacityException,
            ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException;

    boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException;

    boolean applyIpAssociations(Network network, boolean rulesRevoked, boolean continueOnError, List<? extends PublicIpAddress> publicIps)
            throws ResourceUnavailableException;

    IPAddressVO markIpAsUnavailable(long addrId);

    String acquireGuestIpAddress(Network network, String requestedIp);

    String acquireGuestIpAddressForRouter(Network network, String requestedIp);

    boolean applyStaticNats(List<? extends StaticNat> staticNats, boolean continueOnError, boolean forRevoke) throws ResourceUnavailableException;

    IpAddress assignSystemIp(long networkId, Account owner, boolean forElasticLb, boolean forElasticIp) throws InsufficientAddressCapacityException;

    boolean handleSystemIpRelease(IpAddress ip);

    void allocateDirectIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Network network, String requestedIpv4, String requestedIpv6)
            throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException;

    /**
     * @param owner
     * @param guestNetwork
     * @return
     * @throws ConcurrentOperationException
     * @throws InsufficientAddressCapacityException
     */
    PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) throws InsufficientAddressCapacityException, ConcurrentOperationException;

    /**
     * @param ipAddrId
     * @param networkId
     * @param releaseOnFailure TODO
     */
    IPAddressVO associateIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException,
            InsufficientAddressCapacityException, ConcurrentOperationException;

    IpAddress allocatePortableIp(Account ipOwner, Account caller, long dcId, Long networkId, Long vpcID) throws ConcurrentOperationException,
            ResourceAllocationException, InsufficientAddressCapacityException;

    boolean releasePortableIpAddress(long addrId);

    IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException,
            ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException;

    IPAddressVO disassociatePortableIPToGuestNetwork(long ipAddrId, long networkId) throws ResourceAllocationException, ResourceUnavailableException,
            InsufficientAddressCapacityException, ConcurrentOperationException;

    boolean isPortableIpTransferableFromNetwork(long ipAddrId, long networkId);

    void transferPortableIP(long ipAddrId, long currentNetworkId, long newNetworkId) throws ResourceAllocationException, ResourceUnavailableException,
            InsufficientAddressCapacityException, ConcurrentOperationException;

    /**
     * @param addr
     */
    void markPublicIpAsAllocated(IPAddressVO addr);

    /**
     * @param owner
     * @param guestNtwkId
     * @param vpcId
     * @param dcId
     * @param isSourceNat
     * @return
     * @throws ConcurrentOperationException
     * @throws InsufficientAddressCapacityException
     */
    PublicIp assignDedicateIpAddress(Account owner, Long guestNtwkId, Long vpcId, long dcId, boolean isSourceNat) throws ConcurrentOperationException,
            InsufficientAddressCapacityException;

    IpAddress allocateIp(Account ipOwner, boolean isSystem, Account caller, long callerId, DataCenter zone, Boolean displayIp) throws ConcurrentOperationException,
            ResourceAllocationException, InsufficientAddressCapacityException;

    PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List<Long> vlanDbIds, Long networkId, String requestedIp,
                                            boolean isSystem) throws InsufficientAddressCapacityException;

    @DB
    void allocateNicValues(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Network network, String requestedIpv4,
                           String requestedIpv6) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException;

    int getRuleCountForIp(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state);

    public String allocateGuestIP(Network network, String requestedIp) throws InsufficientAddressCapacityException;

    String allocatePublicIpForGuestNic(Network network, Long podId, Account ipOwner, String requestedIp) throws InsufficientAddressCapacityException;
}


text:
package com.google.walkaround.wave.server.servlet;

import com.google.appengine.api.users.UserServiceFactory;
import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.gxp.AuthPopup;
import com.google.walkaround.wave.server.util.AbstractHandler;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Logs out the current user.  This is useful for switching between admin and
 * non-admin when running locally.
 *
 * @author ohler@google.com (Christian Ohler)
 */
public class LogoutHandler extends AbstractHandler {

  public static class SelfClosingPageHandler extends AbstractHandler {
    @Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
      resp.setContentType("text/html");
      AuthPopup.write(resp.getWriter(), new GxpContext(req.getLocale()),
          analyticsAccount, null);
    }
  }

  @SuppressWarnings("unused")
  private static final Logger log = Logger.getLogger(LogoutHandler.class.getName());

  public LogoutHandler() {
  }

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String redirect;
    if (req.getParameter("switchUser") != null) {
      redirect = "/switchSuccess";
    } else {
      redirect = "/loggedout.html";
    }
    resp.sendRedirect(UserServiceFactory.getUserService().createLogoutURL(redirect));
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

Foo

This tests the style information in the paint callback.

See the devtools console for test output. The console should log:

color: [CSSStyleValue=rgb(255, 0, 0)]

line-height: [CSSSimpleLength=2px]


text:
package org.flowable.app.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
@ComponentScan({ "org.flowable.rest.dmn.exception", "org.flowable.rest.dmn.service.api" })
@EnableAsync
public class DmnDispatcherServletConfiguration extends WebMvcConfigurationSupport {

    protected final Logger log = LoggerFactory.getLogger(DmnDispatcherServletConfiguration.class);

}


text:
```
ADS1147          - ADS1147 ADC (Analog-Digital-Converter)
ADS7846          - ADS7846/TSC2046 Touch-Controller
ArdOSC           - OSC for RedFly
CANdiy_Shield    - CANdiy-Shield (CAN-Bus)
DAC8760          - DAC8760 DAC (Digital-Analog-Converter)
digitalWriteFast - Fast pin access for AVR
DisplayI2C       - MI0283QT-Adapter v2 + GLCD-Shield (SPI)
DisplaySPI       - MI0283QT-Adapter v2 + GLCD-Shield (I2C)
DS1307           - DS1307 RTC (Real-Time-Clock)
GraphicsLib      - General Grahipcs Library
LCD_BackPack     - LCD-BackPack (for HD44780 compatible displays)
light_ws2812     - WS2812 RGB LED
MCP2515          - MCP2515 CAN-Controller
MI0283QT2        - MI0283QT-2 Display (HX8347D, SPI)
MI0283QT9        - MI0283QT-9 / -9A / -11 Display (ILI9341, SPI)
mSD_Shield       - mSD-Shield (Display, microSD, RTC)
RedFly           - RedFly-Shield (WiFi/WLAN)
RotaryEncoder    - Rotary Encoder
RV8523           - RV-8523 RTC (Real-Time-Clock)
S65L2F50         - S65 L2F50 Display (SPI)
S65LPH88         - S65 LPH88 Display (SPI)
S65LS020         - S65 LS020 Display (SPI)
SSD1331          - OLED-Display (SSD1331, SPI)
TinyWire         - I2C/TWI library for for ATtiny microcontrollers
```

## Installation
Download the complete libraries [here](https://github.com/watterott/Arduino-Libs/archive/master.zip).

Copy the content of the ZIP-Archive to your Arduino library folder ```/arduino/libraries/``` or to your Arduino user documents folder ```/My Documents/Arduino/libraries/```.
If there are existing folders from a previous installation, please delete them before copying.

Further infos: http://arduino.cc/en/Guide/Libraries and http://arduino.cc/en/Hacking/Libraries

## License
See [license.txt](https://raw.github.com/watterott/Arduino-Libs/master/license.txt).

### Third party libraries/software
Each package has its own copyright and license agreement, and it is your responsibility to comply with the terms of those agreements.
* [ArdOSC](https://github.com/recotana/ArdOSC/)
* [digitalwritefast](http://code.google.com/p/digitalwritefast)
* [light_ws2812](https://github.com/cpldcpu/light_ws2812)
* [MCP2515](https://github.com/franksmicro/Arduino/tree/master/libraries/MCP2515)
* [TinyWire](https://github.com/sudar/TinyWire)


text:
/**
*	Construct a new print object
*	@class
*	@constructor
*	@extends LilyObjectBase
*/
function $typeof()
{
	var thisPtr=this;

	this.inlet1=new this.inletClass("inlet1",this,"messages to route by type");
	this.outlet1 = new this.outletClass("outlet1",this,"booleans will be routed to this outlet");
	this.outlet2 = new this.outletClass("outlet2",this,"arrays will be routed to this outlet");
	this.outlet3 = new this.outletClass("outlet3",this,"numbers will be routed to this outlet");
	this.outlet4 = new this.outletClass("outlet4",this,"objects will be routed to this outlet");
	this.outlet5 = new this.outletClass("outlet5",this,"strings will be routed to this outlet");

	this.inlet1["anything"]=function(msg) {
		if(typeof msg=='boolean') {
			thisPtr.outlet1.doOutlet(msg);
		} else if(LilyUtils.typeOf(msg)=='array') {
			thisPtr.outlet2.doOutlet(msg);
		} else if(typeof msg=='number') {
			thisPtr.outlet3.doOutlet(msg);
		} else if(typeof msg=='object') {
			thisPtr.outlet4.doOutlet(msg);
		} else if(typeof msg=='string') {
			thisPtr.outlet5.doOutlet(msg);
		}
	}

	return this;
}

var $typeofMetaData = {
	textName:"typeof",
	htmlName:"typeof",
	objectCategory:"Control",
	objectSummary:"Route messages based on type.",
	objectArguments:""
}


text:
## Objective

Implement the server-side portion of the v0 RTP design.

## Background

Rise to Power! is a browser-based MMO with a Civilization flavor. Players vie for power by controlling the most land and vassals. Here we document the server-side design of the Rise to Power! system.

## Overview

There are two main server types in this design: frontends and backends. Frontends authenticate users, serve them the UI bundle, and offload them to an appropriate backend. Backends are mostly concerned with handling mutations of game state, and verifying orders entered through the client.

In order for frontends to know how to dispatch the client to the right backend, especially in the presence of frontend and backend failure, we also run an etcd cluster, which holds registrations of all running servers. Frontends are resilient by default due to their light, stateless nature.

Backends are responsible for storing the game state for their assigned shard as well, which is accomplished through a custom append-only style datastore, implemented via Raft. To provide for resilience to failure, the raft master backend also distributes each shard's data to some number (three by default) backends, where one is the primary server of that data, through which all mutations occur, and the others are slave nodes that serve merely as backups should the primary server fail.

In addition to their normal responsibilities in the raft protocol, the backend node that is the raft master is in charge of dispatching work, in the form of game state shards, signalling end of turn, and instructing other backend nodes to store copies of each other's data.

## Infrastructure

- [JSONRPC](http://json-rpc.org) and [websockets](http://www.websocket.org/aboutwebsocket.html) are used for client communication.
- [Etcd](http://coreos.com/using-coreos/etcd/) is for global state storage and master election.

## Detailed Design

(**NOTE**: Where v(-1) is used in this document, it refers to a non-productionized, but otherwise feature-complete version of the v0 code.)

For v0 of this project, we're interested in satisfying the following requirements:

- RTP communicates over standard web protocols in order to serve users a web page (json transports/ajax/websocket may all be employed).
- RTP authenticates players.
- RTP persists user order list modifications.
- RTP persists the previous turn game state.
- RTP disallows modification to Order lists for a turn after that turn's Turn Resolution Phase has started.
- RTP presents Administrators with a privileged view of the game state and the operations of the server which also supports otherwise-illegal, but only-ever-sane modifications to the game state.

Obviously, these basic requirements embody a list of other implied requirements. To satisfy both set of requirements, we propose the following design:

### Client Flow

1. Browser hits '/' on the game subdomain of rise-to-power.com. This hits a frontend server.
2. Frontend server responds with an HTML page that includes the javascript and resources to bootstrap a rise-to-power client.
3. Client code, after loading, sends a GET request to the /_api/backendAddress endpoint.
4. If the user is logged in, the frontend server sends a response containing the address of the backend server to which the client should connect as a plain string (skip to step 7). Otherwise, the server sends a 403 status code to indicate that the client needs to log in.
5. The client requests credentials from the user, and sends them as a JSON object with 'Username' and 'Password' fields in the body of a request to the /_api/login endpoint.
6. If the credentials are correct, the frontend sets an auth cookie in an otherwise empty response to the client (go to step 3). Otherwise, the frontend sends a 403 status code to the client.
7. The client connects to the /_api/connect endpoint on the indicated backend server via websockets (NOTE: this will eventually change to using socket.io, but Go support needs to be updated/written first, and so is unsuitable for v0).
8. If the backend is the incorrect backend for the connected client, it sends a ClientCommand object of type REDIRECT with the address of the correct server in the payload (go to step 7). Otherwise, it sends a ClientCommand object of type GAME_STATE, with the payload as specified in the data model section below.
9. As the user enters orders, the client sends ClientCommand objects of type VALIDATE_ORDER as described in the data model section
10. The server responds with a ClientAck object as appropriate to indicate whether the suggested order is valid.
11. The client sends a ClientCommand of type ORDER when the user sets an order in the UI, with contents as described in the data model section.
12. The server sends a ClientAck object when that order has been persisted to permanent storage and replicated accordingly.
13. When an end of turn is signaled to the backend server, it sends an END_OF_TURN_START ClientCommand to the client. When the end of turn processing is done, it sends END_OF_TURN_STOP, which includes the new state of the world. The structure of all of these messages is included in the data model section of this document.

### Frontend Servers

The frontend serves mostly as a blind relayer of information from the rest of the system. It 'knows' (in v(-1) via flags) where the content it should serve as the client is to be read from, and it 'knows' (in v(-1), also flags) where the backend nodes are, so that it can determine where to send the client. It also is assumed to know how to authenticate users in v(-1).

### Backend Servers

Backend servers exist in two different modes: 'master' and 'worker'.

#### Master Node

The system ensures that there is only one master backend node at any given time by performing master election with the etcd instance.

When master, the node is responsible for ensuring that all state is replicated the correct number of times (default: 3), and
storing the information about replication in the etcd state, which is where the other servers pick it up. As part of this, it also tracks server outages, and updates the information in the etcd state as applicable.

In addition, it is responsible for deciding when end-of-turn happens, and putting that machinery in motion. It is also needed to perform some of the work in that state. At the end of each turn, after all processing has occurred, the master distributes rule and code updates to all backends. This may involve reloading backends, and clients connections to backends that have not yet upgraded are rejected to prevent problems with inconsistent rule enforcement.

Master nodes also do the work of a worker node.

#### Worker Node

The worker node has to respond to client requests and calculate end-of-turn:

##### Client Requests

Backends expose a websocket on the /_api/connect endpoint, which is the sole channel for client requests. They respond to three kinds of client requests (specific data format is contained in the data model section):

- *STATE_REFRESH*: The backend sends back a full dump of the current game state, similar to what happens when a client first initiates a connection.
- *VALIDATE_ORDER*: The backend verifies a given order according to the current rules. **NOTE**: This is a still-questionable design decision.
- *ORDER*: The backend verifies the validity of the order, commits it to permanent storage, ensures it has been committed to the replicas, then returns back to the user.

##### Turn End Calculation

When the master signals that the end of turn has occurred, all backend servers start participating in the end of turn calculation. To do this, the following steps are taken by each backend independently:

1. Farms produce food.
1. Extractors produce resources.
1. Refineries refine.
1. Barracks train.

Then, all backends that contain information about a given player communicate to perform:

5. Troop keep-up,
6. Emissary messages
7. Unit movement.

Each backend then calculates:

8. Combat outcomes
9. Municipality ownership

Then finally, the backends cooperatively communicate again to perform:

10. Power level resolution
11. Player relationship changes
12. Player resource summation

### Data Model

The following data is serialized to JSON as specified in the [Go documentation](http://golang.org/pkg/encoding/json/#Marshal), except that pointers to objects are serialized as though they were a string field containing that object's 'Id' field.

#### ClientCommand

```go
type RedirectClientCommand struct {
  Type string  // Always "REDIRECT"
  Url  string
}

type GameStateClientCommand struct {
  Type    string // Always "GAME_STATE"
  Map     []Municipality // All Municipalities the player owns, or has units in.
  Squares []Square // All squares in all Municipalities contained above.
  Units   []Unit
  Player  Player
}

type ValidateOrderClientCommand struct {
  Type  string // Always "VALIDATE_ORDER"
  Order *Order
}

type OrderClientCommand struct {
  Type  string // Always "ORDER"
  Order *Order
}

type EndOfTurnStartClientCommand struct {
  Type       string // Always "END_OF_TURN_START"
  TurnNumber int
}

type EndOfTurnStopClientCommand struct {
  Type       string // Always "END_OF_TURN_STOP"
  TurnNumber int
  NewState   GameStateClientCommand
}

type StateRefreshClientCommand struct {
  Type string // Always "STATE_REFRESH"
}

type ClientAckClientCommand struct {
  Type    string // Always "CLIENT_ACK"
  OrderId int
}
```

#### Game State

```go
type TitleEnum string

type Player struct {
  Id        string
  Name      string
  Friends   []*Player // List of players with whom we are friends.
  Hostiles  []*Player // List of players with whom we are enemies.
  OwnedLand []*Municipality // List of municipalities that this player has direct control over
  Title     TitleEnum // Enum representing power level
  Liege     *Player // Higher-up Player, null if none
  Vassals   []*Player // List of immediately lower players, empty if none
  Orders    []*Order // List of Order IDs the player has created
}

type Municipality struct {
  Id        string
  X         int // X coordinate of this municipality's origin.
  Y         int // Y coordinate of this municipality's origin.
  Owner     *Player // Player that owns this land, null if unowned
  Conqueror *Player // The Player who has just conquered this municipality, null if owner is non null.
  Appointee *Player // The Player the conqueror of this Municipality has appointed.
}

type Square struct {
  Id                 string
  Terrain            *Terrain // The type of the terrain of this square
  X                  int // X coordinate of the square.
  Y                  int // Y coordinate of the square.
  BuildingProduction *ProductionLevel // The ProductionLevel of a building being built here
  Building           *Building // The building that exists here, null if empty
  Resource           *ResourceBlueprint // A ResourceBlueprint that can be extracted (by an extractor), null if no resource present here.
}

type ResourceQuantity struct {
  Id       string
  Type     *ResourceBlueprint
  Quantity int
}

type ProductionLevel struct {
  Id       string
  Type     *Production // The kind of production that's happening
  Location *Square // The Square this production is happening on
  Building *Building // The building this production is happening on, null if no building
  Rate     float64 // a double between 0 and 1 denoting the rate at which progress should be made on this production, defaults to 1
  Progress int // integer progress out of 100
  Stalled  bool // boolean, true if the costs of this production aren't currently met.
}

type Building struct {
  Id               string
  Type             *BuildingBlueprint // A BuildingBlueprint denoting the type of building
  Location         *Square // The Square that this building is built on
  ProductionLevels []ProductionLevel // list of ProductionLevels, one for each Production in the type, that stores the current progress on that Production
  Storage          []ResourceQuantity // a list of the things currently stored in this building
}

type Unit struct {
  Id       string
  Type     *UnitBlueprint
  Owner    *Player
  Location *Square // The Square that this unit is currently in
  Power    int // Integer representing this unit's current power
  Group    string // A unique identifier for a group of units. All units in a group share this identifier.
}

// Note: Used only as an anonymous member of other structs.
type Order struct {
  Id    string
  Name  string // A UI-friendly name for this order
  Type  string // The name of the type of order this is.
  Order interface{} // One of the order types below.
}

type MovementOrder struct {
  Unit        *Unit // The unit that is moving, or any unit in a group that is moving.
  Destination *Square // The destination Square
  Path        []*Square // a list of Squares denoting the current path that terminates at the destination Square.
}

type BuildBuildingOrder struct {
  Location *Square // The Square the building should be built on
  Building *BuildingBlueprint // The BuildingBlueprint that should be constructed here
}

type CancelBuildingOrder struct {
  Location *Square // The Square the building is being built on
}

type FormGroupOrder struct {
  Units []*Unit // A list of units to form into a group
}

type SplitGroupOrder struct {
  Unit *Unit // Any unit in a group that should be split up.
}

type AdjustProductionRateOrder struct {
  Production *ProductionLevel // The ProductionLevel to adjust
  Rate       float64 // double, the new rate to set the production level to.
}

type FoundCityOrder struct {
  Timestamp    time.Time // The timestamp that this order was received by the server (for ordering purposes).
  Municipality *Municipality // The Municipality that the player is attempting to own.
}

type AppointSubordinateOrder struct {
  Municipality *Municipality // The recently vacated Municipality that the player is attempting to appoint a subordinate to.
  Player       *Player // The subordinate Player.
}

type SetRelationsOrder struct {
  OtherPlayer    *Player // The other Player
  RelationStatus string // The new Relation status
}

type AcceptAppointmentOrder struct {
  Municipality *Municipality // The vacant Municipality whose liege has appointed this player.
}

type RejectAppointmentOrder struct {
  Municipality *Municipality // The vacant Municipality whose liege has appointed this player.
}
```

#### Game Rule Structs

```go
type Terrain struct {
  Name      string // UI name of this terrain
  Image     string // path to the image file for this terrain
  Modifiers []*Modifier // Modifiers that are invoked on units or buildings that are on squares of this kind of terrain.
}

type ResourceBlueprint struct {
  Id    string
  Name  string // UI name of this resource
  Image string // path to the image file for this resource
}

type BuildingBlueprint struct {
  Id               string
  Name             string // UI name of this kind of building
  Image            string // path to the image file for this building
  Production       []*Production // list of Productions, each of which can be produced by this kind of building
  ConstructionCost []ResourceQuantity // required to build this building, null denotes that the building cannot be built
}

type UnitBlueprint struct {
  Id        string
  Name      string // UI name of this kind of Unit
  Image     string // path to the image file for this unit
  MaxPower  int // maximum level of power for this type of unit
  Movement  int // number of squares this unit can move
  Modifiers []*Modifier // list of Modifiers that change this units behavior
}

type Modifier struct {
  Id   string
  Type string // A CamelCase string used to refer to this modifier.
  Name string // A UI-friendly name for the modifier
  // note that the actual execution of this modifier and the rules it changes is probably best expressed in code.
}
```

## Project Information

- Contributors: applmak, jwall, swsnider.
- Code is located at https://code.google.com/p/rise-to-power. See the Hacking on RTP doc for more information.
- The client is written in Javascript, using AngularJS, and the backend(s) are written in Go.

## Latency

The main latency concern is the amount of time the server takes to compute the end of turn. We'd like to keep this well under 5 minutes in general.

It's also nice to keep the latency of individual order-setting requests low, but the client already needs to provide queueing and retry logic for these, so the latency requirements are not as high as might be feared.

## Scalability

The system scales pretty trivially, we believe. We can independently adjust the number of frontend and backend servers, and the system will automatically adjust to assign them work.

The only tricky part may be the etcd cluster -- we need to do testing to ensure that the cluster can withstand our write/read load.

It is not yet clear (because we have not yet built the servers, let alone conducted load testing of them) how much QPS/server the system can sustain.

## Redundancy & Reliability

If a frontend server is lost, we lose no important state, and as long as we have one frontend server, we'll be able to serve user requests (though the max sustainable QPS does obviously go down.)

Backend servers are significantly more important, and carry game state that is impossible to reconstruct were all of it to be lost. Therefore, a master (which is elected via the etcd cluster) ensures that some definable number of servers (by default, 3) have any given shard of data at a time.

If a backend server drops out, the master notices, and schedules replication of its data to fill in the gap. User connections to the affected server will be dropped, causing the client to have to query a frontend for a new server to talk to. This will be noticeable to the user only as a lengthing of the queue of un-committed orders.
If the master server drops out, the master election protocol will elect a new one quite quickly, which can start managing the cluster immediately.


text:
package com.rocketfuel.sdbc.h2.jdbc

class OtherSpec
  extends H2Suite {

  test("Serializable value survives round trip") { implicit connection =>

    val original = util.Success(BigDecimal("3.14159"))

    Execute("CREATE TABLE tbl (obj other)").execute()

    Execute("INSERT INTO tbl (obj) VALUES (@obj)").on(
      "obj" -> Serialized(original)
    ).execute()

    val result = Select[Serialized]("SELECT obj FROM tbl").option()

    assertResult(Some(original))(result.map(_.value))

  }

}


text:
<?php namespace MicroStatic;

use MicroStatic\Exception as ClassDoesNotExistException;
use MicroStatic\Exception as IocNotResolvableException;
use MicroStatic\Exception as UnresolvedDependenciesException;

/**
 * Class IOC
 *
 * @package MicroStatic
 */
class IOC
{
    /**
     * @var string
     */
    private static $namespace = "MicroStatic\\";

    /**
     * @var array
     */
    public static $registry = [];

    /**
     * @var array
     */
    public static $singletons = [];

    /**
     * @var array
     */
    public static $bindings = [];

    /**
     * @var array
     */
    public static $providers = [];

    /**
     * @var array
     */
    public static $config = [];

    public static function config($key, $array = null)
    {
        if (is_array($array) && !isset(static::$config[$key])) {
            static::$config[$key] = $array;
        } else {
            return static::$config[$key];
        }
    }

    /**
     * @return string
     */
    public static function getNamespace()
    {
        return self::$namespace;
    }

    /**
     * @param string $namespace
     */
    public static function setNamespace($namespace)
    {
        self::$namespace = $namespace;
    }

    /**
     * @param          $name
     * @param \Closure $class
     */
    public static function register($name, \Closure $class)
    {
        static::$registry[$name] = $class;
    }

    /**
     * @param          $name
     * @param \Closure $singleton
     */
    public static function singleton($name, \Closure $singleton)
    {
        static::$registry[$name] = $singleton();
    }

    /**
     * @param $name
     * @param $binding
     */
    public static function bind($name, $binding)
    {
        static::$bindings[$name] = $binding;
    }

    /**
     * @param          $name
     * @param \Closure $provider
     */
    public static function provide($name, \Closure $provider)
    {
        static::$registry[$name] = $provider;
    }

    /**
     * @param      $name
     * @param null $params
     *
     * @return mixed
     * @throws IocNotResolvableException
     */
    public static function resolve($name, $params = null)
    {
        if ($name = static::registered($name)) {
            $name = static::$registry[$name];
            return $name()->resolve($params);
        }

        throw new IocNotResolvableException(null, [
            'name' => $name,
            'params' => $params
        ]);
    }

    /**
     * @param $name
     *
     * @return bool
     */
    public static function registered($name)
    {
        if (array_key_exists($name, static::$registry)) {
            return $name;
        }

        $alias = str_replace(self::$namespace, '', $name);

        if (array_key_exists($alias, static::$registry)) {
            return $alias;
        }

        return null;
    }

    /**
     * @param $name
     *
     * @return bool
     */
    public static function bound($name)
    {
        return array_key_exists($name, static::$bindings);
    }

    /**
     * @param $class
     *
     * @return \ReflectionClass
     * @throws ClassDoesNotExistException
     */
    public static function reflect($class)
    {
        try {
            return new \ReflectionClass($class);
        } catch (\Exception $e) {
            throw new ClassDoesNotExistException('Class '. $class.' does not exist');
        }
    }

    /**
     * @param \ReflectionClass $reflected
     *
     * @return array
     */
    public static function getDependencies(\ReflectionClass $reflected)
    {
        $dependencies = [];

        if ($constructor = $reflected->getConstructor()) {
            $parameters = $constructor->getParameters();
            foreach ($parameters as $parameter) {
                $dependencies[] = self::getDependency($parameter);
            }
        }
        return $dependencies;
    }

    /**
     * @param \ReflectionParameter $parameter
     *
     * @return mixed|null
     */
    public static function getDependency(\ReflectionParameter $parameter)
    {
        if ($parameter->isArray() || !$parameter->getClass()) {
            return null;
        }

        $class = $parameter->getClass()->name;

        if ($class == 'Closure') {
            return null;
        }

        $reflected = new \ReflectionClass($class);

        if (self::bound($reflected->name)) {
            return self::$bindings[$reflected->name];
        } else {
            return $reflected->name;
        }
    }

    /**
     * @param array $dependencies
     *
     * @return array
     */
    public static function resolveDependencies(array $dependencies)
    {
        foreach ($dependencies as &$dependency) {
            if (is_null($dependency)) {
                $dependency =  null;
            } else {
                if (IOC::registered($dependency)) {
                    $dependency = IOC::resolve($dependency);
                } else {
                    // just try unregistered
                    $dependency = new $dependency();
                }
            }
        }
        return $dependencies;
    }

    /**
     * @param            $class
     * @param array|null $params
     *
     * @return object
     * @throws UnresolvedDependenciesException
     */
    public static function make($class, array $params = null)
    {
        $reflected = self::reflect($class);

        if (empty($reflected->getConstructor())) {
            return $reflected->newInstance();
        }

        $dependencies = self::getDependencies($reflected);

        $instanceArgs = self::resolveDependencies($dependencies);

        if (is_array($params)) {
            foreach($params as $param) {
                foreach ($instanceArgs as &$instanceArg) {
                    if (is_null($instanceArg)) {
                        $instanceArg = $param;
                        break;
                    }
                }
            }
        }

        // TODO: Improve this. A lot.
        if (count($dependencies) != count($instanceArgs)) {
            throw new UnresolvedDependenciesException(
                'Could not resolve all dependencies', [
                'Required' => $dependencies,
                'Resolved' => $instanceArgs
            ]);
        }

        if (is_array($params)) {
            $instanceArgs = array_merge($instanceArgs, $params);
        }

        return $reflected->newInstanceArgs($instanceArgs);
    }

}


text:
package Algorithms.Strings.AlternatingCharacters;

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @className SolutionTest
 * @description Unit test
 * @author dair
 * @date Jun 14, 2016
 *
 */
public class SolutionTest {
    private final String path = this.getClass().getResource(".").getPath().toString().replaceFirst("/", "")
                    .replaceAll("\\w+/classes", "resource");
    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

    @Before
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void cleanUpStreams() {
        System.setOut(null);
    }

    @Test
    public void testMain() throws IOException {
        int index = 1;
        Path inputPath = Paths.get(path, "input.txt");
        Path outputPath = Paths.get(path, "output.txt");

        // for multiple test case
        do {
            System.setIn(Files.newInputStream(inputPath));
            Solution.main(null);
            assertEquals(new String(Files.readAllBytes(outputPath)), outContent.toString().replaceAll("\\s+$", "").replaceAll("\\s+\\n", "\r\n"));
            outContent.reset();
            index++;
        } while (Files.exists(inputPath = Paths.get(path, "input" + index + ".txt"))
                        && Files.exists(outputPath = Paths.get(path, "output" + index + ".txt")));
    }
}


text:
from music21 import *
import math

print "Parsing file..."
s = corpus.parse('bach/bwv1.6.mxl')

print "Transforming data"
#for n in s.flat.getElementsByClass(note.Note):
#	n.offset = s.flat.highestOffset - n.offset
#	n.addLyric(n.offset)
#s.sort()

print "Sending to MuseScore..."
s.show('musicxml')


text:
/* ###
 * IP: GHIDRA
 *
 * 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.
 */
package ghidra.app.util.viewer.listingpanel;

import javax.swing.Icon;

import generic.theme.GIcon;
import ghidra.framework.plugintool.ComponentProviderAdapter;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.model.address.AddressSetView;
import ghidra.program.model.listing.Program;

/**
 * Provider for displaying a ListingCodeComparisonPanel.
 */
public class ListingComparisonProvider extends ComponentProviderAdapter {

	private static final Icon DUAL_LISTING_ICON =
		new GIcon("icon.base.util.listingcompare.provider");
	private ListingCodeComparisonPanel dualListingPanel;

	/**
	 * Constructor for a provider that can display a ListingCodeComparisonPanel.
	 * @param tool the tool that contains this provider.
	 * @param name the owner of this provider, which is usually a plugin name.
	 * @param p1 program for the listing displayed in the left side of the panel.
	 * @param p2 program for the listing displayed in the right side of the panel.
	 * @param set1 the address set indicating the portion of the listing displayed in the left side
	 * of the panel.
	 * @param set2 the address set indicating the portion of the listing displayed in the right side
	 * of the panel.
	 */
	public ListingComparisonProvider(PluginTool tool, String name, Program p1, Program p2,
			AddressSetView set1, AddressSetView set2) {
		super(tool, "Listing Comparison", name);
		setIcon(DUAL_LISTING_ICON);
		dualListingPanel = new ListingCodeComparisonPanel(name, tool);
		dualListingPanel.loadAddresses(p1, p2, set1, set2);
		setTransient();
		tool.addComponentProvider(this, true);
	}

	@Override
	public ListingCodeComparisonPanel getComponent() {
		return dualListingPanel;
	}

}


text:
import { tryCatch } from '../util/tryCatch';
import { errorObject } from '../util/errorObject';
import { OuterSubscriber } from '../OuterSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
export function audit(durationSelector) {
    return function auditOperatorFunction(source) {
        return source.lift(new AuditOperator(durationSelector));
    };
}
class AuditOperator {
    constructor(durationSelector) {
        this.durationSelector = durationSelector;
    }
    call(subscriber, source) {
        return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));
    }
}
class AuditSubscriber extends OuterSubscriber {
    constructor(destination, durationSelector) {
        super(destination);
        this.durationSelector = durationSelector;
        this.hasValue = false;
    }
    _next(value) {
        this.value = value;
        this.hasValue = true;
        if (!this.throttled) {
            const duration = tryCatch(this.durationSelector)(value);
            if (duration === errorObject) {
                this.destination.error(errorObject.e);
            }
            else {
                const innerSubscription = subscribeToResult(this, duration);
                if (!innerSubscription || innerSubscription.closed) {
                    this.clearThrottle();
                }
                else {
                    this.add(this.throttled = innerSubscription);
                }
            }
        }
    }
    clearThrottle() {
        const { value, hasValue, throttled } = this;
        if (throttled) {
            this.remove(throttled);
            this.throttled = null;
            throttled.unsubscribe();
        }
        if (hasValue) {
            this.value = null;
            this.hasValue = false;
            this.destination.next(value);
        }
    }
    notifyNext(outerValue, innerValue, outerIndex, innerIndex) {
        this.clearThrottle();
    }
    notifyComplete() {
        this.clearThrottle();
    }
}
//# sourceMappingURL=audit.js.map


text:
Source code for the file handler lives here

## Concept
The file handler is intended to be the component responisble for reading the binary files in a meaning full maner.


text:
class texture3DS{
private:
    int m_width;
    int m_height;
    int m_bpp;
    int m_format;

public:
	texture3DS(std::string filename, const int textureId);

    int getWidth(){return m_width;}
    int getHeight(){return m_width;}
    int getBpp(){return m_bpp;}

};


text:
import { Component, ViewChild } from '@angular/core';
import { SliderComponent } from '../slider.component';

@Component({
  // eslint-disable-next-line @angular-eslint/component-selector
  selector: 'slider-fixture',
  templateUrl: 'slider.fixture.html'
})
export class SliderFixtureComponent {
  @ViewChild('defaultSlider', { static: true }) defaultSlider: SliderComponent;
  @ViewChild('multiSlider', { static: true }) multiSlider: SliderComponent;

  sliderEvent1: any;
  sliderEvent2: any;
  sliderEvent3: any;
  sliderEvent4: any;
  sliderEvent5: any;
  sliderEvent6: any;
  sliderEvent7: any;
  sliderEvent8: any;
  sliderValue = 85;
  sliderValues = '45,85';
}


text:
#pragma once

#include <map>
#include <set>
#include "api/replay/renderdoc_replay.h"
#include "common/threading.h"
#include "core/core.h"
#include "os/os_specific.h"
#include "serialise/serialiser.h"

using std::set;
using std::map;

// in what way (read, write, etc) was a resource referenced in a frame -
// used to determine if initial contents are needed and to what degree
enum FrameRefType
{
  eFrameRef_Unknown,    // for the initial start of frame pipeline state - can't be marked as
                        // written/read yet until first action.

  // Inputs
  eFrameRef_Read,
  eFrameRef_Write,

  // States
  eFrameRef_ReadOnly,
  eFrameRef_ReadAndWrite,
  eFrameRef_ReadBeforeWrite,
};

// verbose prints with IDs of each dirty resource and whether it was prepared,
// and whether it was serialised.
#define VERBOSE_DIRTY_RESOURCES OPTION_OFF

namespace ResourceIDGen
{
ResourceId GetNewUniqueID();
void SetReplayResourceIDs();
};

struct ResourceRecord;

class ResourceRecordHandler
{
public:
  virtual void MarkDirtyResource(ResourceId id) = 0;
  virtual void MarkCleanResource(ResourceId id) = 0;
  virtual void MarkPendingDirty(ResourceId id) = 0;
  virtual void RemoveResourceRecord(ResourceId id) = 0;
  virtual void MarkResourceFrameReferenced(ResourceId id, FrameRefType refType) = 0;
  virtual void DestroyResourceRecord(ResourceRecord *record) = 0;
};

// This is a generic resource record, that APIs can inherit from and use.
// A resource is an API object that gets tracked on its own, has dependencies on other resources
// and has its own stream of chunks.
//
// This is used to track the necessary resources for a frame, and include only those required
// for the captured frame in its log. It also handles anything resource-specific such as
// shadow CPU copies of data.
struct ResourceRecord
{
  ResourceRecord(ResourceId id, bool lock)
      : RefCount(1),
        ResID(id),
        UpdateCount(0),
        DataInSerialiser(false),
        DataPtr(NULL),
        DataOffset(0),
        Length(0),
        DataWritten(false),
        SpecialResource(false)
  {
    m_ChunkLock = NULL;

    if(lock)
      m_ChunkLock = new Threading::CriticalSection();
  }

  ~ResourceRecord() { SAFE_DELETE(m_ChunkLock); }
  void AddParent(ResourceRecord *r)
  {
    if(Parents.find(r) == Parents.end())
    {
      r->AddRef();
      Parents.insert(r);
    }
  }

  void MarkParentsDirty(ResourceRecordHandler *mgr)
  {
    for(auto it = Parents.begin(); it != Parents.end(); ++it)
      mgr->MarkDirtyResource((*it)->GetResourceID());
  }

  void MarkParentsReferenced(ResourceRecordHandler *mgr, FrameRefType refType)
  {
    for(auto it = Parents.begin(); it != Parents.end(); ++it)
      mgr->MarkResourceFrameReferenced((*it)->GetResourceID(), refType);
  }

  void FreeParents(ResourceRecordHandler *mgr)
  {
    for(auto it = Parents.begin(); it != Parents.end(); ++it)
      (*it)->Delete(mgr);

    Parents.clear();
  }

  void MarkDataUnwritten() { DataWritten = false; }
  void Insert(map<int32_t, Chunk *> &recordlist)
  {
    bool dataWritten = DataWritten;

    DataWritten = true;

    for(auto it = Parents.begin(); it != Parents.end(); ++it)
    {
      if(!(*it)->DataWritten)
      {
        (*it)->Insert(recordlist);
      }
    }

    if(!dataWritten)
      recordlist.insert(m_Chunks.begin(), m_Chunks.end());
  }

  void AddRef() { Atomic::Inc32(&RefCount); }
  int GetRefCount() const { return RefCount; }
  void Delete(ResourceRecordHandler *mgr);

  ResourceId GetResourceID() const { return ResID; }
  void RemoveChunk(Chunk *chunk)
  {
    LockChunks();
    for(auto it = m_Chunks.begin(); it != m_Chunks.end(); ++it)
    {
      if(it->second == chunk)
      {
        m_Chunks.erase(it);
        break;
      }
    }
    UnlockChunks();
  }

  void AddChunk(Chunk *chunk, int32_t ID = 0)
  {
    LockChunks();
    if(ID == 0)
      ID = GetID();
    m_Chunks[ID] = chunk;
    UnlockChunks();
  }

  void LockChunks()
  {
    if(m_ChunkLock)
      m_ChunkLock->Lock();
  }
  void UnlockChunks()
  {
    if(m_ChunkLock)
      m_ChunkLock->Unlock();
  }

  bool HasChunks() const { return !m_Chunks.empty(); }
  size_t NumChunks() const { return m_Chunks.size(); }
  void SwapChunks(ResourceRecord *other)
  {
    LockChunks();
    other->LockChunks();
    m_Chunks.swap(other->m_Chunks);
    m_FrameRefs.swap(other->m_FrameRefs);
    other->UnlockChunks();
    UnlockChunks();
  }

  void AppendFrom(ResourceRecord *other)
  {
    LockChunks();
    other->LockChunks();

    for(auto it = other->m_Chunks.begin(); it != other->m_Chunks.end(); ++it)
      AddChunk(it->second->Duplicate());

    for(auto it = other->Parents.begin(); it != other->Parents.end(); ++it)
      AddParent(*it);

    other->UnlockChunks();
    UnlockChunks();
  }

  void DeleteChunks()
  {
    LockChunks();
    for(auto it = m_Chunks.begin(); it != m_Chunks.end(); ++it)
      SAFE_DELETE(it->second);
    m_Chunks.clear();
    UnlockChunks();
  }

  Chunk *GetLastChunk() const
  {
    RDCASSERT(HasChunks());
    return m_Chunks.rbegin()->second;
  }

  int32_t GetLastChunkID() const
  {
    RDCASSERT(HasChunks());
    return m_Chunks.rbegin()->first;
  }

  void PopChunk() { m_Chunks.erase(m_Chunks.rbegin()->first); }
  byte *GetDataPtr() { return DataPtr + DataOffset; }
  bool HasDataPtr() { return DataPtr != NULL; }
  void SetDataOffset(uint64_t offs) { DataOffset = offs; }
  void SetDataPtr(byte *ptr) { DataPtr = ptr; }
  bool MarkResourceFrameReferenced(ResourceId id, FrameRefType refType);
  void AddResourceReferences(ResourceRecordHandler *mgr);
  void AddReferencedIDs(std::set<ResourceId> &ids)
  {
    for(auto it = m_FrameRefs.begin(); it != m_FrameRefs.end(); ++it)
      ids.insert(it->first);
  }

  uint64_t Length;

  int UpdateCount;
  bool DataInSerialiser;
  bool SpecialResource;    // like the swap chain back buffers
  bool DataWritten;

protected:
  volatile int32_t RefCount;

  byte *DataPtr;
  uint64_t DataOffset;

  ResourceId ResID;

  std::set<ResourceRecord *> Parents;

  int32_t GetID()
  {
    static volatile int32_t globalIDCounter = 10;

    return Atomic::Inc32(&globalIDCounter);
  }

  std::map<int32_t, Chunk *> m_Chunks;
  Threading::CriticalSection *m_ChunkLock;

  map<ResourceId, FrameRefType> m_FrameRefs;
};

// the resource manager is a utility class that's not required but is likely wanted by any API
// implementation.
// It keeps track of resource records, which resources are alive and allows you to query for them by
// ID. It tracks
// which resources are marked as dirty (needing their initial contents fetched before capture).
//
// For APIs that wrap their resources it provides tracking for that.
//
// In the replay application it will also track which 'live' resources are representing which
// 'original'
// resources from the application when it was captured.
template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
class ResourceManager : public ResourceRecordHandler
{
public:
  ResourceManager(LogState state, Serialiser *ser);
  virtual ~ResourceManager();

  void Shutdown();

  struct InitialContentData
  {
    InitialContentData(WrappedResourceType r, uint32_t n, byte *b) : resource(r), num(n), blob(b) {}
    InitialContentData()
        : resource((WrappedResourceType)RecordType::NullResource), num(0), blob(NULL)
    {
    }
    WrappedResourceType resource;
    uint32_t num;
    byte *blob;
  };

  bool IsWriting() { return m_State >= WRITING; }
  bool IsReading() { return m_State < WRITING; }
  ///////////////////////////////////////////
  // Capture-side methods

  // while capturing, resource records containing chunk streams and metadata for resources
  RecordType *GetResourceRecord(ResourceId id);
  bool HasResourceRecord(ResourceId id);
  RecordType *AddResourceRecord(ResourceId id);
  inline void RemoveResourceRecord(ResourceId id);
  void DestroyResourceRecord(ResourceRecord *record);

  // while capturing or replaying, resources and their live IDs
  void AddCurrentResource(ResourceId id, WrappedResourceType res);
  bool HasCurrentResource(ResourceId id);
  WrappedResourceType GetCurrentResource(ResourceId id);
  void ReleaseCurrentResource(ResourceId id);

  void MarkInFrame(bool inFrame) { m_InFrame = inFrame; }
  void ReleaseInFrameResources();

  // insert the chunks for the resources referenced in the frame
  void InsertReferencedChunks(Serialiser *fileSer);

  // mark resource records as unwritten, ready to be written to a new logfile.
  void MarkUnwrittenResources();

  // clear the list of frame-referenced resources - e.g. if you're about to recapture a frame
  void ClearReferencedResources();

  // indicates this resource could have been modified by the GPU,
  // so it's now suspect and the data we have on it might well be out of date
  // and to be correct its contents should be serialised out at the start
  // of the frame.
  inline void MarkDirtyResource(ResourceId res);

  // for use when we might be mid-capture, this will get flushed to dirty state before the
  // next frame but is safe to use mid-capture
  void MarkPendingDirty(ResourceId res);
  void FlushPendingDirty();

  // this can be used when the resource is cleared or similar and it's in a known state
  void MarkCleanResource(ResourceId res);

  // returns if the resource has been marked as dirty
  bool IsResourceDirty(ResourceId res);

  // call callbacks to prepare initial contents for dirty resources
  void PrepareInitialContents();

  InitialContentData GetInitialContents(ResourceId id);
  void SetInitialContents(ResourceId id, InitialContentData contents);
  void SetInitialChunk(ResourceId id, Chunk *chunk);

  // generate chunks for initial contents and insert.
  void InsertInitialContentsChunks(Serialiser *fileSer);

  // Serialise out which resources need initial contents, along with whether their
  // initial contents are in the serialised stream (e.g. RTs might still want to be
  // cleared on frame init).
  void Serialise_InitialContentsNeeded();

  // handle marking a resource referenced for read or write and storing RAW access etc.
  static bool MarkReferenced(map<ResourceId, FrameRefType> &refs, ResourceId id,
                             FrameRefType refType);

  // mark resource referenced somewhere in the main frame-affecting calls.
  // That means this resource should be included in the final serialise out
  inline void MarkResourceFrameReferenced(ResourceId id, FrameRefType refType);

  // check if this resource was read before being written to - can be used to detect if
  // initial states are necessary
  bool ReadBeforeWrite(ResourceId id);

  ///////////////////////////////////////////
  // Replay-side methods

  // Live resources to replace serialised IDs
  void AddLiveResource(ResourceId origid, WrappedResourceType livePtr);
  bool HasLiveResource(ResourceId origid);
  WrappedResourceType GetLiveResource(ResourceId origid);
  void EraseLiveResource(ResourceId origid);

  // when asked for a given id, return the resource for a replacement id
  void ReplaceResource(ResourceId from, ResourceId to);
  bool HasReplacement(ResourceId from);
  void RemoveReplacement(ResourceId id);

  // fetch original ID for a real ID or vice-versa.
  ResourceId GetOriginalID(ResourceId id);
  ResourceId GetLiveID(ResourceId id);

  // Serialise in which resources need initial contents and set them up.
  void CreateInitialContents();

  // Free any initial contents that are prepared (for after capture is complete)
  void FreeInitialContents();

  // Apply the initial contents for the resources that need them, used at the start of a frame
  void ApplyInitialContents();

  // Resource wrapping, allows for querying and adding/removing of wrapper layers around resources
  bool AddWrapper(WrappedResourceType wrap, RealResourceType real);
  bool HasWrapper(RealResourceType real);
  WrappedResourceType GetWrapper(RealResourceType real);
  void RemoveWrapper(RealResourceType real);

protected:
  // 'interface' to implement by derived classes
  virtual bool SerialisableResource(ResourceId id, RecordType *record) = 0;
  virtual ResourceId GetID(WrappedResourceType res) = 0;

  virtual bool ResourceTypeRelease(WrappedResourceType res) = 0;

  virtual bool Force_InitialState(WrappedResourceType res, bool prepare) = 0;
  virtual bool AllowDeletedResource_InitialState() { return false; }
  virtual bool Need_InitialStateChunk(WrappedResourceType res) = 0;
  virtual bool Prepare_InitialState(WrappedResourceType res) = 0;
  virtual bool Serialise_InitialState(ResourceId id, WrappedResourceType res) = 0;
  virtual void Create_InitialState(ResourceId id, WrappedResourceType live, bool hasData) = 0;
  virtual void Apply_InitialState(WrappedResourceType live, InitialContentData initial) = 0;

  LogState m_State;
  Serialiser *m_pSerialiser;

  Serialiser *GetSerialiser() { return m_pSerialiser; }
  bool m_InFrame;

  // very coarse lock, protects EVERYTHING. This could certainly be improved and it may be a
  // bottleneck
  // for performance. Given that the main use cases are write-rarely read-often the lock should be
  // optimised
  // for that as we only want to make sure we're not modifying the objects together, by far the most
  // common
  // operation is looking up data.
  Threading::CriticalSection m_Lock;

  // easy optimisation win - don't use maps everywhere. It's convenient but not optimal, and
  // profiling will
  // likely prove that some or all of these could be a problem

  // used during capture - map from real resource to its wrapper (other way can be done just with an
  // Unwrap)
  map<RealResourceType, WrappedResourceType> m_WrapperMap;

  // used during capture - holds resources referenced in current frame (and how they're referenced)
  map<ResourceId, FrameRefType> m_FrameReferencedResources;

  // used during capture - holds resources marked as dirty, needing initial contents
  set<ResourceId> m_DirtyResources;
  set<ResourceId> m_PendingDirtyResources;

  // used during capture or replay - holds initial contents
  map<ResourceId, InitialContentData> m_InitialContents;
  // on capture, if a chunk was prepared in Prepare_InitialContents and added, don't re-serialise.
  // Some initial contents may not need the delayed readback.
  map<ResourceId, Chunk *> m_InitialChunks;

  // used during capture or replay - map of resources currently alive with their real IDs, used in
  // capture and replay.
  map<ResourceId, WrappedResourceType> m_CurrentResourceMap;

  // used during replay - maps back and forth from original id to live id and vice-versa
  map<ResourceId, ResourceId> m_OriginalIDs, m_LiveIDs;

  // used during replay - holds resources allocated and the original id that they represent
  // for a) in-frame creations and b) pre-frame creations respectively.
  map<ResourceId, WrappedResourceType> m_InframeResourceMap, m_LiveResourceMap;

  // used during capture - holds resource records by id.
  map<ResourceId, RecordType *> m_ResourceRecords;

  // used during replay - holds current resource replacements
  map<ResourceId, ResourceId> m_Replacements;
};

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
ResourceManager<WrappedResourceType, RealResourceType, RecordType>::ResourceManager(LogState state,
                                                                                Serialiser *ser)
{
  if(RenderDoc::Inst().GetCrashHandler())
    RenderDoc::Inst().GetCrashHandler()->RegisterMemoryRegion(this, sizeof(ResourceManager));

  m_State = state;
  m_pSerialiser = ser;

  m_InFrame = false;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::Shutdown()
{
  while(!m_LiveResourceMap.empty())
  {
    auto it = m_LiveResourceMap.begin();
    ResourceId id = it->first;
    ResourceTypeRelease(it->second);

    auto removeit = m_LiveResourceMap.find(id);
    if(removeit != m_LiveResourceMap.end())
      m_LiveResourceMap.erase(removeit);
  }

  while(!m_InframeResourceMap.empty())
  {
    auto it = m_InframeResourceMap.begin();
    ResourceId id = it->first;
    ResourceTypeRelease(it->second);

    auto removeit = m_InframeResourceMap.find(id);
    if(removeit != m_InframeResourceMap.end())
      m_InframeResourceMap.erase(removeit);
  }

  FreeInitialContents();

  RDCASSERT(m_ResourceRecords.empty());
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
ResourceManager<WrappedResourceType, RealResourceType, RecordType>::~ResourceManager()
{
  RDCASSERT(m_LiveResourceMap.empty());
  RDCASSERT(m_InframeResourceMap.empty());
  RDCASSERT(m_InitialContents.empty());
  RDCASSERT(m_ResourceRecords.empty());

  if(RenderDoc::Inst().GetCrashHandler())
    RenderDoc::Inst().GetCrashHandler()->UnregisterMemoryRegion(this);
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
bool ResourceManager<WrappedResourceType, RealResourceType, RecordType>::MarkReferenced(
    map<ResourceId, FrameRefType> &refs, ResourceId id, FrameRefType refType)
{
  if(refs.find(id) == refs.end())
  {
    if(refType == eFrameRef_Read)
      refs[id] = eFrameRef_ReadOnly;
    else if(refType == eFrameRef_Write)
      refs[id] = eFrameRef_ReadAndWrite;
    else    // unknown or existing state
      refs[id] = refType;

    return true;
  }
  else
  {
    if(refType == eFrameRef_Unknown)
    {
      // nothing
    }
    else if(refType == eFrameRef_ReadBeforeWrite)
    {
      // special case, explicitly set to ReadBeforeWrite for when
      // we know that this use will likely be a partial-write
      refs[id] = eFrameRef_ReadBeforeWrite;
    }
    else if(refs[id] == eFrameRef_Unknown)
    {
      if(refType == eFrameRef_Read || refType == eFrameRef_ReadOnly)
        refs[id] = eFrameRef_ReadOnly;
      else
        refs[id] = eFrameRef_ReadAndWrite;
    }
    else if(refs[id] == eFrameRef_ReadOnly && refType == eFrameRef_Write)
    {
      refs[id] = eFrameRef_ReadBeforeWrite;
    }
  }

  return false;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::MarkResourceFrameReferenced(
    ResourceId id, FrameRefType refType)
{
  SCOPED_LOCK(m_Lock);

  if(id == ResourceId())
    return;

  bool newRef = MarkReferenced(m_FrameReferencedResources, id, refType);

  if(newRef)
  {
    RecordType *record = GetResourceRecord(id);

    if(record)
      record->AddRef();
  }
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
bool ResourceManager<WrappedResourceType, RealResourceType, RecordType>::ReadBeforeWrite(ResourceId id)
{
  if(m_FrameReferencedResources.find(id) != m_FrameReferencedResources.end())
    return m_FrameReferencedResources[id] == eFrameRef_ReadBeforeWrite ||
           m_FrameReferencedResources[id] == eFrameRef_ReadOnly;

  return false;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::MarkDirtyResource(ResourceId res)
{
  SCOPED_LOCK(m_Lock);

  if(res == ResourceId())
    return;

  m_DirtyResources.insert(res);
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::MarkPendingDirty(ResourceId res)
{
  SCOPED_LOCK(m_Lock);

  if(res == ResourceId())
    return;

  m_PendingDirtyResources.insert(res);
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::FlushPendingDirty()
{
  SCOPED_LOCK(m_Lock);

  m_DirtyResources.insert(m_PendingDirtyResources.begin(), m_PendingDirtyResources.end());
  m_PendingDirtyResources.clear();
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
bool ResourceManager<WrappedResourceType, RealResourceType, RecordType>::IsResourceDirty(ResourceId res)
{
  SCOPED_LOCK(m_Lock);

  if(res == ResourceId())
    return false;

  return m_DirtyResources.find(res) != m_DirtyResources.end();
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::MarkCleanResource(ResourceId res)
{
  SCOPED_LOCK(m_Lock);

  if(res == ResourceId())
    return;

  if(IsResourceDirty(res))
  {
    m_DirtyResources.erase(res);
  }
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::SetInitialContents(
    ResourceId id, InitialContentData contents)
{
  SCOPED_LOCK(m_Lock);

  RDCASSERT(id != ResourceId());

  auto it = m_InitialContents.find(id);

  if(it != m_InitialContents.end())
  {
    ResourceTypeRelease(it->second.resource);
    Serialiser::FreeAlignedBuffer(it->second.blob);
    m_InitialContents.erase(it);
  }

  m_InitialContents[id] = contents;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::SetInitialChunk(ResourceId id,
                                                                                Chunk *chunk)
{
  SCOPED_LOCK(m_Lock);

  RDCASSERT(id != ResourceId());

  auto it = m_InitialChunks.find(id);

  RDCASSERT(chunk->GetChunkType() == INITIAL_CONTENTS);

  if(it != m_InitialChunks.end())
  {
    RDCERR("Initial chunk set for ID %llu twice", id);
    delete chunk;
    return;
  }

  m_InitialChunks[id] = chunk;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
typename ResourceManager<WrappedResourceType, RealResourceType, RecordType>::InitialContentData ResourceManager<
    WrappedResourceType, RealResourceType, RecordType>::GetInitialContents(ResourceId id)
{
  SCOPED_LOCK(m_Lock);

  if(id == ResourceId())
    return InitialContentData();

  if(m_InitialContents.find(id) != m_InitialContents.end())
    return m_InitialContents[id];

  return InitialContentData();
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::Serialise_InitialContentsNeeded()
{
  SCOPED_LOCK(m_Lock);

  struct WrittenRecord
  {
    ResourceId id;
    bool written;
  };
  vector<WrittenRecord> written;

  // reasonable estimate, and these records are small
  written.reserve(m_FrameReferencedResources.size());

  for(auto it = m_FrameReferencedResources.begin(); it != m_FrameReferencedResources.end(); ++it)
  {
    RecordType *record = GetResourceRecord(it->first);

    if(it->second != eFrameRef_ReadOnly && it->second != eFrameRef_Unknown)
    {
      WrittenRecord wr = {it->first, record ? record->DataInSerialiser : true};

      written.push_back(wr);
    }
  }

  for(auto it = m_DirtyResources.begin(); it != m_DirtyResources.end(); ++it)
  {
    ResourceId id = *it;
    auto ref = m_FrameReferencedResources.find(id);
    if(ref == m_FrameReferencedResources.end() || ref->second == eFrameRef_ReadOnly)
    {
      WrittenRecord wr = {id, true};

      written.push_back(wr);
    }
  }

  uint32_t numWritten = (uint32_t)written.size();
  m_pSerialiser->Serialise("NumWrittenResources", numWritten);

  for(auto it = written.begin(); it != written.end(); ++it)
  {
    m_pSerialiser->Serialise("id", it->id);
    m_pSerialiser->Serialise("WrittenData", it->written);
  }
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::FreeInitialContents()
{
  while(!m_InitialContents.empty())
  {
    auto it = m_InitialContents.begin();
    ResourceTypeRelease(it->second.resource);
    Serialiser::FreeAlignedBuffer(it->second.blob);
    if(!m_InitialContents.empty())
      m_InitialContents.erase(m_InitialContents.begin());
  }
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::CreateInitialContents()
{
  set<ResourceId> neededInitials;

  uint32_t NumWrittenResources = 0;
  m_pSerialiser->Serialise("NumWrittenResources", NumWrittenResources);

  for(uint32_t i = 0; i < NumWrittenResources; i++)
  {
    ResourceId id = ResourceId();
    bool WrittenData = false;

    m_pSerialiser->Serialise("id", id);
    m_pSerialiser->Serialise("WrittenData", WrittenData);

    neededInitials.insert(id);

    if(HasLiveResource(id) && m_InitialContents.find(id) == m_InitialContents.end())
      Create_InitialState(id, GetLiveResource(id), WrittenData);
  }

  for(auto it = m_InitialContents.begin(); it != m_InitialContents.end();)
  {
    ResourceId id = it->first;

    if(neededInitials.find(id) == neededInitials.end())
    {
      ResourceTypeRelease(it->second.resource);
      Serialiser::FreeAlignedBuffer(it->second.blob);
      ++it;
      m_InitialContents.erase(id);
    }
    else
    {
      ++it;
    }
  }
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::ApplyInitialContents()
{
  RDCDEBUG("Applying initial contents");
  uint32_t numContents = 0;
  for(auto it = m_InitialContents.begin(); it != m_InitialContents.end(); ++it)
  {
    ResourceId id = it->first;

    if(HasLiveResource(id))
    {
      WrappedResourceType live = GetLiveResource(id);

      numContents++;

      Apply_InitialState(live, it->second);
    }
  }
  RDCDEBUG("Applied %d", numContents);
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::MarkUnwrittenResources()
{
  SCOPED_LOCK(m_Lock);

  for(auto it = m_ResourceRecords.begin(); it != m_ResourceRecords.end(); ++it)
  {
    it->second->MarkDataUnwritten();
  }
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::InsertReferencedChunks(
    Serialiser *fileSer)
{
  map<int32_t, Chunk *> sortedChunks;

  SCOPED_LOCK(m_Lock);

  RDCDEBUG("%u frame resource records", (uint32_t)m_FrameReferencedResources.size());

  if(RenderDoc::Inst().GetCaptureOptions().RefAllResources)
  {
    for(auto it = m_ResourceRecords.begin(); it != m_ResourceRecords.end(); ++it)
    {
      if(!SerialisableResource(it->first, it->second))
        continue;

      it->second->Insert(sortedChunks);
    }
  }
  else
  {
    for(auto it = m_FrameReferencedResources.begin(); it != m_FrameReferencedResources.end(); ++it)
    {
      RecordType *record = GetResourceRecord(it->first);
      if(record)
        record->Insert(sortedChunks);
    }
  }

  RDCDEBUG("%u frame resource chunks", (uint32_t)sortedChunks.size());

  for(auto it = sortedChunks.begin(); it != sortedChunks.end(); it++)
  {
    fileSer->Insert(it->second);
  }

  RDCDEBUG("inserted to serialiser");
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::PrepareInitialContents()
{
  SCOPED_LOCK(m_Lock);

  RDCDEBUG("Preparing up to %u potentially dirty resources", (uint32_t)m_DirtyResources.size());
  uint32_t prepared = 0;

  for(auto it = m_DirtyResources.begin(); it != m_DirtyResources.end(); ++it)
  {
    ResourceId id = *it;

    if(!HasCurrentResource(id))
      continue;

    RecordType *record = GetResourceRecord(id);
    WrappedResourceType res = GetCurrentResource(id);

    if(record == NULL || record->SpecialResource)
      continue;

    prepared++;

#if ENABLED(VERBOSE_DIRTY_RESOURCES)
    RDCDEBUG("Prepare Resource %llu", id);
#endif

    Prepare_InitialState(res);
  }

  RDCDEBUG("Prepared %u dirty resources", prepared);

  prepared = 0;

  for(auto it = m_CurrentResourceMap.begin(); it != m_CurrentResourceMap.end(); ++it)
  {
    if(it->second == (WrappedResourceType)RecordType::NullResource)
      continue;

    if(Force_InitialState(it->second, true))
    {
      prepared++;
      Prepare_InitialState(it->second);
    }
  }

  RDCDEBUG("Force-prepared %u dirty resources", prepared);
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::InsertInitialContentsChunks(
    Serialiser *fileSerialiser)
{
  SCOPED_LOCK(m_Lock);

  uint32_t dirty = 0;
  uint32_t skipped = 0;

  RDCDEBUG("Checking %u possibly dirty resources", (uint32_t)m_DirtyResources.size());

  for(auto it = m_DirtyResources.begin(); it != m_DirtyResources.end(); ++it)
  {
    ResourceId id = *it;

    if(m_FrameReferencedResources.find(id) == m_FrameReferencedResources.end() &&
       !RenderDoc::Inst().GetCaptureOptions().RefAllResources)
    {
#if ENABLED(VERBOSE_DIRTY_RESOURCES)
      RDCDEBUG("Dirty tesource %llu is GPU dirty but not referenced - skipping", id);
#endif
      skipped++;
      continue;
    }

    WrappedResourceType res = (WrappedResourceType)RecordType::NullResource;
    bool isAlive = HasCurrentResource(id);

    if(!AllowDeletedResource_InitialState() && !isAlive)
    {
#if ENABLED(VERBOSE_DIRTY_RESOURCES)
      RDCDEBUG("Resource %llu no longer exists - skipping", id);
#endif
      continue;
    }

    if(isAlive)
      res = GetCurrentResource(id);

    RecordType *record = GetResourceRecord(id);

    if(record == NULL)
    {
#if ENABLED(VERBOSE_DIRTY_RESOURCES)
      RDCDEBUG("Resource %llu has no resource record - skipping", id);
#endif
      continue;
    }

    if(record->SpecialResource)
    {
#if ENABLED(VERBOSE_DIRTY_RESOURCES)
      RDCDEBUG("Resource %llu is special - skipping", id);
#endif
      continue;
    }

#if ENABLED(VERBOSE_DIRTY_RESOURCES)
    RDCDEBUG("Serialising dirty Resource %llu", id);
#endif

    dirty++;

    if(!Need_InitialStateChunk(res))
    {
      // just need to grab data, don't create chunk
      Serialise_InitialState(id, res);
      continue;
    }

    auto preparedChunk = m_InitialChunks.find(id);
    if(preparedChunk != m_InitialChunks.end())
    {
      fileSerialiser->Insert(preparedChunk->second);
      m_InitialChunks.erase(preparedChunk);
    }
    else
    {
      ScopedContext scope(m_pSerialiser, "Initial Contents", "Initial Contents", INITIAL_CONTENTS,
                          false);

      Serialise_InitialState(id, res);

      fileSerialiser->Insert(scope.Get(true));
    }
  }

  RDCDEBUG("Serialised %u dirty resources, skipped %u unreferenced", dirty, skipped);

  dirty = 0;

  for(auto it = m_CurrentResourceMap.begin(); it != m_CurrentResourceMap.end(); ++it)
  {
    if(it->second == (WrappedResourceType)RecordType::NullResource)
      continue;

    if(Force_InitialState(it->second, false))
    {
      dirty++;

      auto preparedChunk = m_InitialChunks.find(it->first);
      if(preparedChunk != m_InitialChunks.end())
      {
        fileSerialiser->Insert(preparedChunk->second);
        m_InitialChunks.erase(preparedChunk);
      }
      else
      {
        ScopedContext scope(m_pSerialiser, "Initial Contents", "Initial Contents", INITIAL_CONTENTS,
                            false);

        Serialise_InitialState(it->first, it->second);

        fileSerialiser->Insert(scope.Get(true));
      }
    }
  }

  RDCDEBUG("Force-serialised %u dirty resources", dirty);

  // delete/cleanup any chunks that weren't used (maybe the resource was not
  // referenced).
  for(auto it = m_InitialChunks.begin(); it != m_InitialChunks.end(); ++it)
    delete it->second;

  m_InitialChunks.clear();
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::ReleaseInFrameResources()
{
  SCOPED_LOCK(m_Lock);

  // clean up last frame's temporaries - we needed to keep them around so they were valid for
  // pipeline inspection etc after replaying the last log.
  for(auto it = m_InframeResourceMap.begin(); it != m_InframeResourceMap.end(); ++it)
  {
    ResourceTypeRelease(it->second);
  }

  m_InframeResourceMap.clear();
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::ClearReferencedResources()
{
  SCOPED_LOCK(m_Lock);

  for(auto it = m_FrameReferencedResources.begin(); it != m_FrameReferencedResources.end(); ++it)
  {
    RecordType *record = GetResourceRecord(it->first);

    if(record)
      record->Delete(this);
  }

  m_FrameReferencedResources.clear();
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::ReplaceResource(
    ResourceId from, ResourceId to)
{
  SCOPED_LOCK(m_Lock);

  if(HasLiveResource(to))
    m_Replacements[from] = to;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
bool ResourceManager<WrappedResourceType, RealResourceType, RecordType>::HasReplacement(ResourceId from)
{
  SCOPED_LOCK(m_Lock);

  return m_Replacements.find(from) != m_Replacements.end();
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::RemoveReplacement(ResourceId id)
{
  SCOPED_LOCK(m_Lock);

  auto it = m_Replacements.find(id);

  if(it == m_Replacements.end())
    return;

  m_Replacements.erase(it);
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
RecordType *ResourceManager<WrappedResourceType, RealResourceType, RecordType>::GetResourceRecord(
    ResourceId id)
{
  SCOPED_LOCK(m_Lock);

  auto it = m_ResourceRecords.find(id);

  if(it == m_ResourceRecords.end())
    return NULL;

  return it->second;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
bool ResourceManager<WrappedResourceType, RealResourceType, RecordType>::HasResourceRecord(ResourceId id)
{
  SCOPED_LOCK(m_Lock);

  auto it = m_ResourceRecords.find(id);

  if(it == m_ResourceRecords.end())
    return false;

  return true;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
RecordType *ResourceManager<WrappedResourceType, RealResourceType, RecordType>::AddResourceRecord(
    ResourceId id)
{
  SCOPED_LOCK(m_Lock);

  RDCASSERT(m_ResourceRecords.find(id) == m_ResourceRecords.end(), id);

  return (m_ResourceRecords[id] = new RecordType(id));
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::RemoveResourceRecord(
    ResourceId id)
{
  SCOPED_LOCK(m_Lock);

  RDCASSERT(m_ResourceRecords.find(id) != m_ResourceRecords.end(), id);

  m_ResourceRecords.erase(id);
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::DestroyResourceRecord(
    ResourceRecord *record)
{
  delete(RecordType *)record;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
bool ResourceManager<WrappedResourceType, RealResourceType, RecordType>::AddWrapper(
    WrappedResourceType wrap, RealResourceType real)
{
  SCOPED_LOCK(m_Lock);

  bool ret = true;

  if(wrap == (WrappedResourceType)RecordType::NullResource ||
     real == (RealResourceType)RecordType::NullResource)
  {
    RDCERR("Invalid state creating resource wrapper - wrapped or real resource is NULL");
    ret = false;
  }

  if(m_WrapperMap[real] != (WrappedResourceType)RecordType::NullResource)
  {
    RDCERR("Overriding wrapper for resource");
    ret = false;
  }

  m_WrapperMap[real] = wrap;

  return ret;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::RemoveWrapper(
    RealResourceType real)
{
  SCOPED_LOCK(m_Lock);

  if(real == (RealResourceType)RecordType::NullResource || !HasWrapper(real))
  {
    RDCERR(
        "Invalid state removing resource wrapper - real resource is NULL or doesn't have wrapper");
    return;
  }

  m_WrapperMap.erase(m_WrapperMap.find(real));
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
bool ResourceManager<WrappedResourceType, RealResourceType, RecordType>::HasWrapper(RealResourceType real)
{
  SCOPED_LOCK(m_Lock);

  if(real == (RealResourceType)RecordType::NullResource)
    return false;

  return (m_WrapperMap.find(real) != m_WrapperMap.end());
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
WrappedResourceType ResourceManager<WrappedResourceType, RealResourceType, RecordType>::GetWrapper(
    RealResourceType real)
{
  SCOPED_LOCK(m_Lock);

  if(real == (RealResourceType)RecordType::NullResource)
    return (WrappedResourceType)RecordType::NullResource;

  if(real != (RealResourceType)RecordType::NullResource && !HasWrapper(real))
  {
    RDCERR(
        "Invalid state removing resource wrapper - real resource isn't NULL and doesn't have "
        "wrapper");
  }

  return m_WrapperMap[real];
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::AddLiveResource(
    ResourceId origid, WrappedResourceType livePtr)
{
  SCOPED_LOCK(m_Lock);

  if(origid == ResourceId() || livePtr == (WrappedResourceType)RecordType::NullResource)
  {
    RDCERR("Invalid state adding resource mapping - id is invalid or live pointer is NULL");
  }

  m_OriginalIDs[GetID(livePtr)] = origid;
  m_LiveIDs[origid] = GetID(livePtr);

  if(m_InFrame && m_InframeResourceMap.find(origid) != m_InframeResourceMap.end())
  {
    ResourceTypeRelease(m_InframeResourceMap[origid]);
    m_InframeResourceMap.erase(origid);
  }
  else if(!m_InFrame && m_LiveResourceMap.find(origid) != m_LiveResourceMap.end())
  {
    RDCERR("Releasing live resource for duplicate creation: %llu", origid);
    ResourceTypeRelease(m_LiveResourceMap[origid]);
    m_LiveResourceMap.erase(origid);
  }

  if(m_InFrame)
    m_InframeResourceMap[origid] = livePtr;
  else
    m_LiveResourceMap[origid] = livePtr;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
bool ResourceManager<WrappedResourceType, RealResourceType, RecordType>::HasLiveResource(ResourceId origid)
{
  SCOPED_LOCK(m_Lock);

  if(origid == ResourceId())
    return false;

  return (m_Replacements.find(origid) != m_Replacements.end() ||
          m_InframeResourceMap.find(origid) != m_InframeResourceMap.end() ||
          m_LiveResourceMap.find(origid) != m_LiveResourceMap.end());
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
WrappedResourceType ResourceManager<WrappedResourceType, RealResourceType, RecordType>::GetLiveResource(
    ResourceId origid)
{
  SCOPED_LOCK(m_Lock);

  if(origid == ResourceId())
    return (WrappedResourceType)RecordType::NullResource;

  RDCASSERT(HasLiveResource(origid), origid);

  if(m_Replacements.find(origid) != m_Replacements.end())
    return GetLiveResource(m_Replacements[origid]);

  if(m_InframeResourceMap.find(origid) != m_InframeResourceMap.end())
    return m_InframeResourceMap[origid];

  if(m_LiveResourceMap.find(origid) != m_LiveResourceMap.end())
    return m_LiveResourceMap[origid];

  return (WrappedResourceType)RecordType::NullResource;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::EraseLiveResource(
    ResourceId origid)
{
  SCOPED_LOCK(m_Lock);

  RDCASSERT(HasLiveResource(origid), origid);

  if(m_InframeResourceMap.find(origid) != m_InframeResourceMap.end())
  {
    m_InframeResourceMap.erase(origid);
  }
  else
  {
    m_LiveResourceMap.erase(origid);
  }
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::AddCurrentResource(
    ResourceId id, WrappedResourceType res)
{
  SCOPED_LOCK(m_Lock);

  RDCASSERT(m_CurrentResourceMap.find(id) == m_CurrentResourceMap.end(), id);
  m_CurrentResourceMap[id] = res;
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
bool ResourceManager<WrappedResourceType, RealResourceType, RecordType>::HasCurrentResource(ResourceId id)
{
  SCOPED_LOCK(m_Lock);

  return m_CurrentResourceMap.find(id) != m_CurrentResourceMap.end();
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
WrappedResourceType ResourceManager<WrappedResourceType, RealResourceType,
                                    RecordType>::GetCurrentResource(ResourceId id)
{
  SCOPED_LOCK(m_Lock);

  if(m_Replacements.find(id) != m_Replacements.end())
    return GetCurrentResource(m_Replacements[id]);

  RDCASSERT(m_CurrentResourceMap.find(id) != m_CurrentResourceMap.end(), id);
  return m_CurrentResourceMap[id];
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
void ResourceManager<WrappedResourceType, RealResourceType, RecordType>::ReleaseCurrentResource(
    ResourceId id)
{
  SCOPED_LOCK(m_Lock);

  RDCASSERT(m_CurrentResourceMap.find(id) != m_CurrentResourceMap.end(), id);
  m_CurrentResourceMap.erase(id);
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
ResourceId ResourceManager<WrappedResourceType, RealResourceType, RecordType>::GetOriginalID(
    ResourceId id)
{
  if(id == ResourceId())
    return id;

  RDCASSERT(m_OriginalIDs.find(id) != m_OriginalIDs.end(), id);
  return m_OriginalIDs[id];
}

template <typename WrappedResourceType, typename RealResourceType, typename RecordType>
ResourceId ResourceManager<WrappedResourceType, RealResourceType, RecordType>::GetLiveID(ResourceId id)
{
  if(id == ResourceId())
    return id;

  RDCASSERT(m_LiveIDs.find(id) != m_LiveIDs.end(), id);
  return m_LiveIDs[id];
}


text:
package io.fabric8.acme.client.model;

import io.sundr.builder.annotations.Buildable;
import net.minidev.json.JSONObject;

@Buildable(
  generateBuilderPackage = true,
  builderPackage = "io.fabric8.acme.client.builder",
  editableEnabled = false
)
public class Identifier {

  private String type;

  private String value;

  public Identifier(String type, String value) {
    this.type = type;
    this.value = value;
  }

  public String getType() {
    return type;
  }

  public String getValue() {
    return value;
  }

  public JSONObject toJSONObject() {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("type", type);
    jsonObject.put("value", value);
    return jsonObject;
  }

  public static Identifier fromJSONObject(JSONObject jsonObject) {
    if (jsonObject == null) {
      return null;
    }

    return new Identifier((String) jsonObject.get("type"), (String) jsonObject.get("value"));
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/**********************************************************************
svcworker.cpp -- logic for the runtime implementation of the native
image service.

Overview:  the runtime implementation is accessed via a local COM
server implemented in ngen.exe.  That server is simply a stub that
loads the most recent runtime and calls into the actual implementation
in this file.  There are three entrypoints in mscorwks.dll that
are called by the local service in ngen.exe:

NGenWorkerRegisterServer -- called to register ngen.exe as the current
  COM server for CLSID_CorSvcWorker
NGenWorkerUnregisterServer -- unregister ngen.exe as the current COM
  server for CLSID_CorSvcWorker
NGenWorkerEmbedding() -- called when COM invoked the COM server with
  the "-Embedding" flag.  Implements the logic for registering the class
  factory for CLSID_CorSvcWorker and controlling the lifetime of the
  COM server.
**********************************************************************/

#include "common.h"

#ifdef FEATURE_APPX
#include "AppXUtil.h"
#endif

ILocalServerLifetime *g_pLocalServerLifetime = NULL;

SvcLogger::SvcLogger()
    : pss(NULL),
      pCorSvcLogger(NULL)
{
}

inline void SvcLogger::CheckInit()
{
    if(pss == NULL)
    {
        StackSString* psstemp = new StackSString();
        StackSString* pssOrig = InterlockedCompareExchangeT(&pss, psstemp, NULL);
        if(pssOrig)
            delete psstemp;
    }
}

SvcLogger::~SvcLogger()
{
    if (pCorSvcLogger)
    {
//        pCorSvcLogger->Release();
        pCorSvcLogger = NULL;
    }
    if (pss)
        delete pss;
}

void SvcLogger::ReleaseLogger()
{
    if (pCorSvcLogger)
    {
        pCorSvcLogger->Release();
        pCorSvcLogger = NULL;
    }
}

void SvcLogger::Printf(const CHAR *format, ...)
{
    StackSString s;

    va_list args;
    va_start(args, format);
    s.VPrintf(format, args);
    va_end(args);

    if (pCorSvcLogger)
    {
        LogHelper(s);
    }
    else
    {
        wprintf( W("%s"), s.GetUnicode() );
    }
}

void SvcLogger::SvcPrintf(const CHAR *format, ...)
{
    StackSString s;

    va_list args;
    va_start(args, format);
    s.VPrintf(format, args);
    va_end(args);

    LogHelper(s);
}

void SvcLogger::Printf(const WCHAR *format, ...)
{
    StackSString s;

    va_list args;
    va_start(args, format);
    s.VPrintf(format, args);
    va_end(args);

    if (pCorSvcLogger)
    {
        LogHelper(s);
    }
    else
    {
        wprintf( W("%s"), s.GetUnicode() );
    }
}

void SvcLogger::Printf(CorSvcLogLevel logLevel, const WCHAR *format, ...)
{
    StackSString s;

    va_list args;
    va_start(args, format);
    s.VPrintf(format, args);
    va_end(args);

    if (pCorSvcLogger)
    {
        LogHelper(s, logLevel);
    }
    else
    {
        wprintf( W("%s"), s.GetUnicode());
    }
}

void SvcLogger::SvcPrintf(const WCHAR *format, ...)
{
    StackSString s;

    va_list args;
    va_start(args, format);
    s.VPrintf(format, args);
    va_end(args);

    LogHelper(s);
}

void SvcLogger::Log(const WCHAR *message, CorSvcLogLevel logLevel)
{
    LogHelper(StackSString(message), logLevel);
}

void SvcLogger::LogHelper(SString s, CorSvcLogLevel logLevel)
{
    CheckInit();
    pss->Append(s);

    // Does s contain a newline?
    SString::Iterator i = pss->Begin();
    if (pss->FindASCII(i, "\n"))
    {
        if (pCorSvcLogger)
        {
            BSTRHolder bstrHolder(::SysAllocString(pss->GetUnicode()));
            // Can't use the IfFailThrow macro here because in checked
            // builds that macros will try to log an error message
            // that will recursively return to this method.
            HRESULT hr = pCorSvcLogger->Log(logLevel, bstrHolder);
            if (FAILED(hr))
                ThrowHR(hr);
        }
        pss->Clear();
    }
}

void SvcLogger::SetSvcLogger(ICorSvcLogger *pCorSvcLoggerArg)
{
    ReleaseLogger();
    this->pCorSvcLogger = pCorSvcLoggerArg;
    if (pCorSvcLoggerArg)
    {
        pCorSvcLogger->AddRef();
    }
}

BOOL SvcLogger::HasSvcLogger()
{
    return (this->pCorSvcLogger != NULL);
}

ICorSvcLogger* SvcLogger::GetSvcLogger()
{
    return pCorSvcLogger;
}

namespace
{
    SvcLogger *g_SvcLogger = NULL;
}

// As NGen is currently single-threaded, this function is intentionally not thread safe.
// If necessary, change it into an interlocked function.
SvcLogger *GetSvcLogger()
{
    if (g_SvcLogger == NULL)
    {
        g_SvcLogger = new SvcLogger();
    }
    return g_SvcLogger;
}

BOOL HasSvcLogger()
{
    if (g_SvcLogger != NULL)
    {
        return g_SvcLogger->HasSvcLogger();
    }
    return FALSE;
}

#ifdef CROSSGEN_COMPILE
void SetSvcLogger(ICorSvcLogger *pCorSvcLogger)
{
    GetSvcLogger()->SetSvcLogger(pCorSvcLogger);
}
#endif


text:
package org.enemies;

import java.awt.Color;
import static java.lang.System.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import org.players.Player;
import org.resources.Collisions;
import org.resources.ImagePack;
import static java.lang.Math.*;

public class Water extends Enemy {
	private int counter = 10 * (int) Math.round(1000f * Math.random());
	private static final BufferedImage[] ani = new BufferedImage[]{ImagePack.getImage("water/waterTop1.png"),
			ImagePack.getImage("water/waterTop2.png"), ImagePack.getImage("water/waterTop3.png"),
			ImagePack.getImage("water/waterTop4.png"),};
	public Water(int a, int b, int W, int H) {
		x = a;
		y = b;
		w = W;
		h = H;
	}
	public void run() {
		if (Collisions.collides(Player.player, this)) {
			Player.vMultiplier = .6f;
			out.println("hello");
		}
	}
	public void draw(Graphics g) {
		counter++;
		g.setColor(new Color(0, 148, 255, 182));
		g.fillRect(round(x), round(y) + 16, w, h - 16);
		g.clipRect(round(x), round(y), w, h);

		for (int i = round(x); i < x + w; i += 16) {
			g.drawImage(ani[3 - (counter / 15) % 4], i, round(y), null);
		}
		g.setClip(null);
	}
	public boolean preventsNextRoom() {
		return false;
	}

}


text:
package org.apache.james.mailbox.exception;

import org.apache.james.mailbox.model.MailboxACL.MailboxACLRight;

/**
 * Thrown when the current system does not support the given right.
 *
 */
public class UnsupportedRightException extends MailboxSecurityException {

    private static final char INVALID_RIGHT = 0;
    private static final long serialVersionUID = 2959248897018370078L;
    private char unsupportedRight = INVALID_RIGHT;

    public UnsupportedRightException() {
        super();
    }

    public UnsupportedRightException(char right) {
        super("Unsupported right flag '"+ right +"'.");
        this.unsupportedRight  = right;
    }

    public UnsupportedRightException(MailboxACLRight unsupportedRight) {
        this(unsupportedRight.getValue());
    }

    public UnsupportedRightException(String msg, Exception cause) {
        super(msg, cause);
    }

    public char getUnsupportedRight() {
        return unsupportedRight;
    }

}


text:
function [bOk,gpsEph,gpsWeek,ttxSec] = CheckGpsEphInputs(gpsEph,gpsTime)
%[bOk,gpsEph,gpsWeek,ttxSec] = CheckGpsEphInputs(gpsEph,gpsTime)
%check the inputs for GpsEph2Pvt, GpsEph2Xyz, GpsEph2Dtsv

%Author: Frank van Diggelen
%Open Source code for processing Android GNSS Measurements

bOk=false;
if ~isstruct(gpsEph)
    error('gpsEph input must be a structure, as defined by ReadRinexNav')
end

p=length(gpsEph);
%Check that gpsTime is a px2 vector
if any(size(gpsTime) ~= [p 2])
    error('gpsTime must be px2 [gpsWeek, gpsSec], where p =length(gpsEph)')
end
gpsWeek = gpsTime(:,1);
ttxSec  = gpsTime(:,2);

bOk = true;
end %end of function CheckGpsEphInputs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright 2016 Google Inc.
%
% 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.