text:
**Current Version: 5.4.0**

## 1. Overview
The SmartDeviceLink protocol specification describes the method for establishing communication between an application and head unit and registering the application for continued communication with the head unit. The protocol is used as the base formation of packets sent from one module to another.

All new SDL implementations should implement the newest version of the protocol.

### 1.1 Common Terms

| Term | Description |
|------|-------------|
|**Module / Head Unit**| Hardware implementing the sdl_core software|
|**Application**| Smart device application that implements the proxy library (iOS or Android)|

## 2. Frames
All transported data is formed with a header followed by an optional payload. The combination of header and payload is referred to as a frame.

### 2.1 Version 1 Frame Header
>Deprecated: Protocol versions 2 and higher. Only used as initial `StartService` packet for establishing communication and version negotiation from application

    Byte 1
    Byte 2
    Byte 3
    Byte 4

    Version
    C
    Frame Type
    Service Type
    Frame Info
    Session ID

    Byte 5
    Byte 6
    Byte 7
    Byte 8

    Data Size

### 2.2 Version 2 Frame Header
>Required: Protocol versions 2 and higher

    Byte 1
    Byte 2
    Byte 3
    Byte 4

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session ID

    Byte 5
    Byte 6
    Byte 7
    Byte 8

    Data Size

    Byte 9
    Byte 10
    Byte 11
    Byte 12

    Message ID

### 2.3 Frame Header Fields

    Field
    Size
    Description

    Version
    4 bit

      Protocol Version

      0x1 Protocol version 1 - uses a version 1 Frame Header

      0x2 Protocol version 2 - uses a version 2 Frame Header

      0x3 Protocol version 3 - uses a version 2 Frame Header

      0x4 Protocol version 4 - uses a version 2 Frame Header

      0x5 Protocol version 5 - uses a version 2 Frame Header

      0x6 - 0xF Reserved

    C
    1 bit
    Compression Flag
 0x0 This packet is not compressed
 0x1 This packet is compressed
 Note: Only available in Protocol Version 1

    E
    1 bit
    Encryption Flag
 0x0 This packet is not encrypted
 0x1 This packet is encrypted
 Note: Only available in Protocol Version 2 and higher

    Frame Type
    3 bit

      0x00 Control Frame

      0x01 Single Frame

      0x02 First Frame

      0x03 Consecutive Frame

      0x04 - 0x07 Reserved

    Service Type
    8 bit

      0x00 Control Service

      0x01 - 0x06 Reserved

      0x07 Remote Procedure Call (RPC) Service

      0x08 - 0x09 Reserved

      0x0A Audio Service

      0x0B Video Service

      0x0C - 0x0E Reserved

      0x0F Bulk Data (Hybrid Service)

      0x10 - 0xFF Reserved

    Frame Info
    8 bit

      Frame Type = 0x00 (Control Frame)

      0x00 Heartbeat

      0x01 Start Service

      0x02 Start Service ACK

      0x03 Start Service NAK

      0x04 End Service

      0x05 End Service ACK

      0x06 End Service NAK

      0x07 Register Secondary Transport

      0x08 Register Secondary Transport ACK

      0x09 Register Secondary Transport NAK

      0x0A - 0xFC Reserved

      0xFD Transport Event Update

      0xFE Service Data ACK

      0xFF Heartbeat ACK

      Frame Type = 0x01 (Single Frame)

      0x00 - 0xFF Reserved

      Frame Type = 0x02 (First Frame)

      0x00 - 0xFF Reserved

      Frame Type = 0x03 (Consecutive Frame)

      0x00 Last Frame

      0x01 - 0xFF Frame Number

    Session ID
    8 bit
    The session identifier

    Data Size
    32 bit

      Frame Type = 0x00 (Control Frame)

      0x0 - 0xFFFFFFFF reserved.

      Frame Type = 0x02 (First Frame)

      0x08 The data size for a first frame is always 8 bytes. In the payload, the first four bytes denote the Total Size of the data contained in all consecutive frames, and the second four bytes denote the number of consecutive frames following this one

      Frame Type = 0x01 or 0x03 (Single or Consecutive Frame)

      The total bytes in this frame's payload

    Message ID
    32 bit
    The message identifier, used to uniquely identify this message.

    Note: Only included in protocol version 2 frame headers and higher

### 2.4 Max Transport Units
The max transport unit (MTU) of a frame varies based on version. The MTU includes the frame header and payload. The current supported versions and their MTU's respectively are described below.

| Version | MTU (bytes) |
|------|-------------|
|**1**| 1500|
|**2**| 1500|
|**3**| 131,084 |
|**4**| 131,084|
|**5**| 131,084 default or negotiated *(See Control Frame Payloads)*

#### 2.4.1 Payload Size
The payload size is determined by the MTU - Frame Header Size.

| Version | Max Payload Size (bytes) |
|------|-------------|
|**1**| 1488|
|**2**| 1488|
|**3**| 131,072 |
|**4**| 131,072|
|**5**| 131,072 default or (Negotiated MTU - 12 bytes) *(See Control Frame Payloads)*

#### 2.4.2 Encrypted MTU
While the supported MTU is the maximum size for that version, if a frame is encrypted it will be subject to the MTU of that encryption protocol as well. That means the MTU will have to be the minimum between SDL's MTU  and the encryption protocol's MTU.

## 3. Frame Types

### 3.1 Control Frame
Control frames are the lowest-level type of packets. They can be sent over any of the defined services. They are used for the control of the services in which they are sent.

#### 3.1.1 Special Header Definitions:
| Header Value |Expected values| Description |
|--------------|---------------|-------------|
|Frame Info| `0x00` - `0x06`, `0xFE`, `0xFF`|See below "Frame Info Definitions"|
|Data Size| `0x00`, `0x04`|`0x00` - Majority of control packets do not have payloads

 `0x04` - Used for `StartServiceACK` where the payload is a HashID |

#### 3.1.2 Frame Info Definitions:
| Frame Info Value| Name | Description |
|------------|------|-------------|
| 0x00| Heartbeat| A ping packet that is sent to ensure the connection is still active and the service is still valid|
| 0x01 | Start Service |Requests that a specific type of service is started |
| 0x02 | Start Service ACK | Acknowledges that the specific service has been started successfully
| 0x03 | Start Service NAK | Negatively acknowledges that the specific service was *not* started
| 0x04 | End Service | Requests that a specific type of service is ended
| 0x05 | End Service ACK | Acknowledges that the specific service has been ended successfully
| 0x06 | End Service NAK |  Negatively acknowledges that the specific service was *not* ended or has not yet been started
| 0x07 | Register Secondary Transport | Request for a session registered on a primary transport to use a secondary transport.
This frame should only be sent on the Secondary Transport that the session is requesting.
| 0x08 | Register Secondary Transport ACK | Acknowledges that the supplied session is registered to use the requested Secondary Transport. The application is only allowed to send additional frames on the Secondary Transport after this frame is received.
This frame must be sent on the Secondary Transport in which the original request was sent.
| 0x09 | Register Secondary Transport NAK | Negatively acknowledges that the session is not registered or able to use the current Secondary Transport. The application cannot use this transport for any other messages.
This frame must be sent on the Secondary Transport in which the original request was sent.
| 0xFD | Transport Event Update | Indicates that status or configuration of one or more transports are updated. This frame must only be sent after the successful starting of the RPC service which includes the protocol version negotiation.
| 0xFE | Service Data ACK | *Deprecated*
| 0xFF | Heartbeat ACK | Acknowledges that a Heartbeat control packet has been received

#### 3.1.3 Payloads
>Added: Protocol Version 5

>*Note: All parameters are optional*

Control frames use [BSON](http://bsonspec.org) to store payload data. All payload types are directly from the BSON spec. Each control frame info type will have a defined set of available data. Most types will also have differently available data based on their service type.

If there is no data to send for a given parameter, the parameter should not be included.

**Note:** Heartbeat, Heartbeat ACK, and Service Data ACK control frame types are not covered for any service as they were deprecated before payloads were introduced.

##### 3.1.3.1 Control Service

###### 3.1.3.1.1 Register Secondary Transport

>No parameters

###### 3.1.3.1.2 Register Secondary Transport ACK

>No parameters

###### 3.1.3.1.3 Register Secondary Transport NAK

| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
| reason | String | 5.1.0 | A string describing the reason of failure |

###### 3.1.3.1.4 Transport Event Update

| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
| tcpIpAddress | String | 5.1.0 | IP address that can be used to establish a TCP connection. It can be IPv4 address (example: "192.168.1.1") or IPv6 address (example: "fd12:3456:789a::1").
An empty string indicates that the TCP transport becomes unavailable. |
| tcpPort | int32 | 5.1.0 |  TCP Port number that can be used along with the supplied `tcpIpAddress` to establish a TCP connection. If parameter is included, the `tcpIpAddress` parameter must also be included.|

##### 3.1.3.2 RPC Service

###### 3.1.3.2.1 Start Service
**Note:** While this includes a payload, it will remain a v1 frame header to ensure backwards compatibility with older systems.

| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
|protocolVersion|String| 5.0.0 | The max version of the protocol supported by client requesting service to start. Must be in the format *"Major.Minor.Patch"*|

###### 3.1.3.2.2 Start Service ACK
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
|protocolVersion|String| 5.0.0 |The negotiated version of the protocol. Must be in the format *"Major.Minor.Patch"*. The frame header version should match the major version exactly.|
|hashId|int32| 5.0.0 | Hash ID to identify this session and used when sending an `EndService` control frame for the RPC service type|
|mtu| int64 | 5.0.0 | Max transport unit to be used for this service|. If not included the client should use the protocol version default.|
|secondaryTransports|String Array| 5.1.0 | Array of transport types which are allowed to be used as a Secondary Transport. Refer to the table below for possible values.
As of this protocol spec version (5.1.0) only a single Secondary Transport may be used beyond a primary transport for a given session.
If there are no currently available Secondary Transports or the functionality is not supported, this parameter should be omitted or be an empty array.|
|audioServiceTransports|int32 array| 5.1.0 | Ordered list of transport priority types that support the audio service (`0x0A`). Only the values of `1` ("Primary Transport") or `2` ("Secondary Transport") shall be used. If both the primary and secondary transport support the audio service, both should be included (`1` and `2`) in the order they are preferred; otherwise only the single transport priority type should be included. An application must not start the audio service on a transport priority type that is not listed in the array.
If this parameter is not included the Primary Transport should be used for the audio service.|
|videoServiceTransports|int32 array| 5.1.0 | Ordered list of transport priority types that support the video service (`0x0B`). Only the values of `1` ("Primary Transport") or `2` ("Secondary Transport") shall be used. If both the primary and secondary transport support the video service, both should be included (`1` and `2`) in the order they are preferred; otherwise only the single transport priority type should be included. An application must not start the video service on a transport priority type that is not listed in the array.
If this parameter is not included the Primary Transport should be used for the video service.|
|authToken|String| 5.2.0 | Included exclusively when communicating with cloud applications. This token is used by a cloud application to authenticate a user account associated with the vehicle. |
|make|String| 5.4.0 | Vehicle make value. Used by OEM exclusive apps to identify whether current vehicle is supported or not. |
|model|String| 5.4.0 | Vehicle model value. Used by OEM exclusive apps to identify whether current vehicle is supported or not. |
|modelYear|String| 5.4.0 | Vehicle model year value. Used by OEM exclusive apps to identify whether current vehicle is supported or not. |
|trim|String| 5.4.0 | Vehicle trim value. Used by OEM exclusive apps to identify whether current vehicle is supported or not. |
|systemSoftwareVersion|String| 5.4.0 | Vehicle system software version value. Can be specified in any format desired by the OEM. |
|systemHardwareVersion|String| 5.4.0 | Vehicle system hardware version value. Can be specified in any format desired by the OEM. |

**list of transport type strings**

| String | Description |
|--------|-------------|
| IAP\_BLUETOOTH | iAP over Bluetooth |
| IAP\_USB | iAP over USB where it is not possible to distinguish between host or device mode|
| IAP\_USB\_HOST\_MODE | iAP over USB, and the phone is running as host |
| IAP\_USB\_DEVICE\_MODE | iAP over USB, and the phone is running as device |
| IAP\_CARPLAY | iAP over Carplay wireless |
| SPP\_BLUETOOTH | Bluetooth SPP. |
| AOA\_USB | Android Open Accessory |
| TCP\_WIFI | TCP connection over Wi-Fi |

###### 3.1.3.2.3 Start Service NAK
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
| rejectedParams |String Array| 5.0.0 | An array of rejected parameters|
| reason | String | 5.3.0 | A string describing the reason of failure |

###### 3.1.3.2.4 End Service
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
|hashId|int32| 5.0.0 | Hash ID supplied in the `StartServiceACK` for this service type|

###### 3.1.3.2.5 End Service ACK

###### 3.1.3.2.6 End Service NAK
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
| rejectedParams |String Array| 5.0.0 | An array of rejected parameters such as: [`hashId`] |
| reason | String | 5.3.0 | A string describing the reason of failure |

##### 3.1.3.3 Audio Service
###### 3.1.3.3.1 Start Service
>No parameters

###### 3.1.3.3.2 Start Service ACK
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
|mtu| int64 | 5.0.0 | Max transport unit to be used for this service. If not included the client should use the one set via the RPC service or protocol version default.|

###### 3.1.3.3.3 Start Service NAK
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
| rejectedParams |String Array| 5.0.0 | An array of rejected parameters such as: [`videoProtocol`, `videoCodec`] |
| reason | String | 5.3.0 | A string describing the reason of failure |

###### 3.1.3.3.4 End Service
>No parameters

###### 3.1.3.3.5 End Service ACK
>No parameters

###### 3.1.3.3.6 End Service NAK
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
| rejectedParams |String Array| 5.0.0 | An array of rejected parameters such as: [`hashId`] |
| reason | String | 5.3.0 | A string describing the reason of failure |

##### 3.1.3.4 Video Service

###### 3.1.3.4.1 Start Service
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
|height|int32| 5.0.0 | Desired height from the client requesting the video service to start|
|width|int32| 5.0.0 | Desired width from the client requesting the video service to start|
|videoProtocol|String| 5.0.0 | Desired video protocol to be used. See `VideoStreamingProtocol ` RPC|
|videoCodec|String| 5.0.0 | Desired video codec to be used. See `VideoStreamingCodec` RPC|

###### 3.1.3.4.2 Start Service ACK
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
|mtu| int64 | 5.0.0 | Max transport unit to be used for this service. If not included the client should use the one set via the RPC service or protocol version default.|
|height|int32| 5.0.0 | Accepted height from the client requesting the video service to start|
|width|int32| 5.0.0 | Accepted width from the client requesting the video service to start|
|videoProtocol|String| 5.0.0 | Accepted video protocol to be used. See `VideoStreamingProtocol ` RPC|
|videoCodec|String| 5.0.0 | Accepted video codec to be used. See `VideoStreamingCodec` RPC|

###### 3.1.3.4.3 Start Service NAK
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
| rejectedParams |String Array| 5.0.0 | An array of rejected parameters such as: [`videoProtocol`, `videoCodec`] |
| reason | String | 5.3.0 | A string describing the reason of failure |

###### 3.1.3.4.4 End Service
>No parameters

###### 3.1.3.4.5 End Service ACK
>No parameters

###### 3.1.3.4.6 End Service NAK
| Tag Name | Type | Introduced | Description |
|----------|------|------------|-------------|
| rejectedParams |String Array| 5.0.0 | An array of rejected parameters such as: [`hashId`] |
| reason | String | 5.3.0 | A string describing the reason of failure |

### 3.2 Single Frame
A frame of type Single Frame contains all the data for a particular packet in the payload. The majority of frames sent over the protocol utilize this frame type.

  	Single Frame

    Header
    Payload

    Data

#### 3.2.1 Special Header Definitions:

| Header Value |Expected values| Description |
|--------------|---------------|-------------|
|Frame Info| `0x00`|Reserved|
|Data Size| 0x01-0xFFFFFFFF|Total payload size in bytes for this frame|

### 3.3 Multiple Frame Packets
Some payloads will be larger than the maximum transport unit will allow. If that is the case, the payload will be broken up over multiple frames. These frame types are First and Consecutive.

    Data

    Data Chunk 1
    Data Chunk 2
    ...
    Data Chunk n

  	First Frame

     Header
    Payload

     Consecutive Frame 1

	Header
	Payload

     Consecutive Frame 2

	Header
	Payload

     ...

     Consecutive Frame n

	Header
	Payload

#### 3.3.1 First Frame
The First Frame in a multiple frame payload contains information about the entire sequence of frames so that the receiving end can correctly parse all the frames and reassemble the entire payload. The payload of this frame is only eight bytes and contains information regarding the rest of the sequence.

##### 3.3.1.1 Payload:

		Byte
		0
		1
		2
		3
		4
		5
		6
		7

		Total size of the original payload being parsed
		Number of Consecutive Frames in this sequence

##### 3.3.1.2 Special Header Definitions:

| Header Value |Expected values| Description |
|--------------|---------------|-------------|
|Frame Info| `0x00`|Reserved|
|Data Size| `0x08`|This frame contains a fixed data size (8 bytes) for the payload.|

#### 3.3.2 Consecutive Frame
The Consecutive Frames in a multiple frame payload contain the actual raw data of the original payload. The parsed payload contained in each of the Consecutive Frames' payloads should be buffered until the entire sequence is complete.

##### 3.3.2.1 Special Header Definitions:

| Header Value |Expected values| Description |
|--------------|---------------|-------------|
|Frame Info| `0x00` - `0xFF`|Values `0x01` - `0xFF` are used incrementally as each consecutive frame is created and sent in the sequence. eg The first consecutive packet in the sequence will have the value `0x01`, the next consecutive frame that contains the next chunk of data in the sequence will have the value `0x02`.

If the sequence reaches `0xFF` with more frames to create, it shall rollover to `0x01` **not** `0x00` as it is reserved.

`0x00` is only used for the last consecutive frame in a multi-frame sequence and the last frame must have this value.|
|Data Size| `0x01` - `0xFFFFFFFF`|Payload size in bytes for only this frame |

## 4. Establishing Communication

### 4.1 Transport Layer
>Required: All Protocol Versions

A physical transport must be established between a head unit and an application before an SDL session can start.

### 4.2 Version Negotiation
>Required: All Protocol Versions

#### 4.2.1 Overview
Once a physical transport is established, each application must negotiate the maximum supported protocol version with the head unit. To establish basic communication and register with the head unit, the application must start an RPC service (Service Type: 0x07), using a *Version 1 Protocol Header*.

There are two types of version negotiation. Protocol versions 1 through 4 use an old style of negotiation, where as versions 5 and newer use a faster and more intelligent negotiation scheme.

##### 4.2.1.1 Version 1-4 Negotiation
>Required for Protocol Versions 1 through 4

| Proxy| Direction | Core |
|------------|------|-------------|
|`StartService`
 **Version:** v1
 **Payload:** no payload| ----------->|
|| <-----------|`StartServiceACK`
 **Version:** Max supported by Core
 **Payload:** raw bytes for hashID
|`SingleFrame` *(or other RPC supporting Frame Type)*
 **Version:** Highest version supported by both Core and Proxy
 **Payload:** Lots of bytes| ----------->| Sets negotiated version.

##### 4.2.1.2 Version 5+ Negotiation
>Required for Protocol Versions 5 and newer

| Proxy| Direction | Core |
|------------|------|-------------|
|`StartService`
 **Version:** v1
 **Payload:** Constructed payload [protocolVersion: 5.x.x]| ----------->| **v4 Core**: Ignores payload, sends protocol version 4 frame and uses previous negotiation scheme.
 **v5+ Core:** Reads in payload data, uses this information to determine version.
|| <-----------|`StartServiceACK`
 **Version:** Highest version supported by both Core and Proxy
 **Payload:** Constructed payload [protocolVersion: 5.x.x, hashId: 0x9873, mtu: 130687]
|`SingleFrame`
 **Version:** Highest version supported by both Core and Proxy
 **Payload:** Lots of bytes| ----------->|

#### 4.2.2 Starting Communication
The application sends a `StartService` frame to the module containing no payload.

##### Application -> Head Unit

#### 4.2.2.1 Versions 1 - 4

    Version
    C
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size

    1
    no
    Control
    RPC
    Start Service
    0
    0

    0b0001
    0b0
    0b000
    0x07
    0x01
    0x00
    0x00000000

#### 4.2.2.2 Versions 5 and newer
>**Note:** Even though this is a Protocol Version 1 frame header it includes a payload. This is a very special exception.

Payload includes a constructed BSON object that has a single parameter of `protocolVersion` that describes the applications max supported Protocol Version.

    Version
    C
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size

    1
    no
    Control
    RPC
    Start Service
    0
    Size of Payload

    0b0001
    0b0
    0b000
    0x07
    0x01
    0x00
    0xNNNNNNNN

  	Payload

  	 [protocolVersion: x.x.x]</td

#### 4.2.3 Success
If the head unit allows the RPC service to start, it will respond with a `StartServiceACK`. At this time the version will finish its negotiation process.

##### Head Unit -> Application

##### 4.2.3.1 Protocol Versions 1-4

The `StartServiceACK` will contain the module's maximum supported protocol version. The packet structure will also match that of the supplied version; if the module's maximum supported version is 1, the packet will contain an 8 byte header (version 1), otherwise it will contain a 12 byte header (version 2). The application will then find the highest version supported by both the module and the application. This will be the determined version used for this session and will be used for all other packets sent from this point forward as well as all other services.

The payload of the `StartServiceACK` will contain a hash of the service which was started on the head unit if the payload size is greater than 0. This hash should be stored by an application and is needed in the end communication flow.

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    Max Module Version (4)
    no
    Control
    RPC
    Start Service ACK
    Assigned Session
    4
    2

    0b0100
    0b0
    0b000
    0x07
    0x02
    0x01
    0x00000004
    0x0000000n

##### 4.2.3.2 Protocol Versions 5 and newer

The `StartServiceACK` will contain a negotiated version between what the application provided in the `StartService` frame and what the module's maximum supported protocol version. Thus, if it is determined that no such information was sent in the `StartService` frame, the module will assume the previous method of version negotiation and send version 4 to assume it's max version supplied to the application and wait for the incoming `RegisterAppInterface` RPC from the application to finally determine the negotiated version. Either way, the determined version will be used for this session including all other packets sent from this point forward as well as all other services.

The packet structure will also match that of the supplied version; if the module's maximum supported version is 1, the packet will contain an 8 byte header (version 1), otherwise it will contain a 12 byte header (version 2). If the protocol version was determined to be 5 or higher, the payload it contains will be constructed in nature as a BSON object. The application will then find the highest version supported by both the module and the application. This will be the determined version used for this session and will be used for all other packets sent from this point forward as well as all other services.

The payload of the `StartServiceACK` will contain the agreed upon full protocol version *"Major.Minor.Patch"*, a hash of the service which was started on the head unit, and the max transport unit for that session (0x07 RPC). The hash should be stored by an application and is needed in the end communication flow. The MTU should be used as the default MTU for all other services for that session unless otherwise provided in the corresponding `StartServiceACK` for that service.

###### 4.2.3.2.1 Protocol Version Supplied in `StartService`

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    Max major version supported by module and application
    no
    Control
    RPC
    Start Service ACK
    Assigned Session
    Size of payload
    2

    0bNNNN
    0b0
    0b000
    0x07
    0x02
    0x01
    0xNNNNNNNN
    0x0000000n

  		Payload

  		 [protocolVersion: x.x.x, hashId: 0xNNNN, mtu: 130687]</td

###### 4.2.3.2.2 Protocol Version Not Supplied  in `StartService`

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    Max version application can possibly support (4)
    no
    Control
    RPC
    Start Service ACK
    Assigned Session
    4
    2

    0b0100
    0b0
    0b000
    0x07
    0x02
    0x01
    0x00000004
    0x0000000n

##### 4.2.4 Failure
If a session has already been started, or can't be started, a `StartServiceNAK` will be sent in response to the `StartService` packet.

##### Head Unit -> Application

##### 4.2.4.1 Protocol Versions 1 through 4

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    Max Module Version (4)
    no
    Control
    RPC
    Start Service NAK
    0
    0
    0

    0b0100
    0b0
    0b000
    0x07
    0x03
    0x00
    0x00000000
    0x00000000

##### 4.2.4.1 Protocol Versions 5 and Newer

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    Max Module Version (4)
    no
    Control
    RPC
    Start Service NAK
    0
    Size of Payload
    0

    0b0100
    0b0
    0b000
    0x07
    0x03
    0x00
    0xNNNNNNNN
    0x00000000

  		Payload

  		 [rejectedParams:[protocolVersion, x, x]]Required: All Protocol Versions

Each application registers for continued communication with the head unit by sending a `RegisterAppInterface` Request RPC to the head unit via the RPC Service. Additional services can only be started after a successful `RegisterAppInterface` Response RPC has been sent from the head unit to the application.

### 4.4 Starting other services
While the RPC service is the default service that is started to establish a connection and a session, the application may wish to start other services. Similar to the process in Section 4, all services that are to be to started in a session require a `StartService` packet to be sent from the application. If the module supports and allows that service type to be started, it will respond with a `StartServiceACK` that has a payload of the hash ID for that service. If the module is unable to start that service or that application does not have access to that service, it will respond with a `StartServiceNAK`.

### 4.5 Heartbeat
>**Deprecated: Protocol Versions 4 and higher**

>Required: Protocol Version 3

>Added: Protocol Version 3

After a successful start service exchange between the application and head unit both the application and head unit are required to be able to respond to heartbeat messages if the negotiated protocol version is 3. After sending a heartbeat, if the application or head unit does not respond within a timeout (custom per app/head unit), the sender will disconnect. The sender's timer for the heartbeat timeout should be reset every time any message is received. Heartbeats are sent using the Control Service Type (0x00)

#### 4.5.1 Heartbeat Request

>Note: The request can originate from either the Head Unit or the Application

##### Head Unit -> Application

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    4
    no
    Control
    Control
    Heartbeat
    0
    0
    0

    0b0100
    0b0
    0b000
    0x00
    0x00
    0x00
    0x00000000
    0x00000000

#### 4.5.2 Heartbeat ACK

>Note: The response ACK will originate from the Head Unit or the Application based on the origin of the request

##### Application -> Head Unit

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    4
    no
    Control
    Control
    Heartbeat ACK
    0
    0
    0

    0b0100
    0b0
    0b000
    0x00
    0xFF
    0x00
    0x00000000
    0x00000000

#### 4.5.3 Heartbeat NAK
There is currently no heartbeat NAK.

### 4.6 Secondary Transport

>Added: Protocol version 5.1.0

After the RPC service has been established on an initial transport, it is possible to utilize a different transport beyond the initial transport for certain services.  This additional transport is called the "Secondary Transport". The initial transport used to start the RPC service is called the "Primary Transport".

#### 4.6.1 Secondary Transport Registration

The RPC `StartServiceACK` will include information on potential Secondary Transports in the parameter `secondaryTransports` if any are supported. Once received, it is possible to register the session on the Secondary Transport if connected; if the transport is not connected it will have to either wait until an update is received through the `TransportEventUpdated` frame or the physical connection is made.

Once the connection for Secondary Transport is established, if the application wishes to utilize that transport as a SecondaryTransport, the application is required to send a `RegisterSecondaryTransport` frame on that transport. The head unit will respond with either a`RegisterSecondaryTransportACK` or `RegisterSecondaryTransportNAK` frame. If the registration was successful and the application receives a `RegisterSecondaryTransportACK`, it may then utilize the Secondary Transport to start services.

##### 4.6.1.1 RegisterSecondaryTransport

##### Application -> Head Unit

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    Max major version supported by module and application
    no
    Control
    Control
    Register Secondary Transport
    Session Id assigned on Primary Transport
    0
    1

    0bNNNN
    0b0
    0b000
    0x00
    0x07
    0xNN
    0x00000000
    0x00000001

##### 4.6.1.2 RegisterSecondaryTransportACK

##### Head Unit -> Application

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    Max major version supported by module and application
    no
    Control
    Control
    Register Secondary Transport ACK
    Session Id assigned on Primary Transport
    0
    2

    0bNNNN
    0b0
    0b000
    0x00
    0x08
    0xNN
    0x00000000
    0x00000002

##### 4.6.1.3 RegisterSecondaryTransportNAK

##### Head Unit -> Application

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    Max major version supported by module and application if known, otherwise 5
    no
    Control
    Control
    Register Secondary Transport NAK
    Session Id assigned on Primary Transport
    0
    2

    0bNNNN
    0b0
    0b000
    0x00
    0x09
    0xNN
    0x00000000
    0x00000002

#### 4.6.2 Transport Event Update

Some Secondary Transports might require additional details on how they can be established. For example, in order to establish a TCP connection between the application and head unit the IP address and port number are required. The `TransportEventUpdate` control frame is used for this purpose.

The head unit will send out a `TransportEventUpdate` frame whenever its transport configuration is changed, for example when its IP address is updated or Wi-Fi network goes down. The head unit will also send out a `TransportEventUpdate` frame right after the `StartServiceACK` frame that establishes the RPC service so the application can initiate a connection immediately.

The `TransportEventUpdate` frame must always be sent through the Primary Transport. The head unit should not send the frame to applications that don't support protocol versions 5.1.0 or newer.

##### 4.6.2.1 TransportEventUpdate

##### Head Unit -> Application

    Version
    E
    Frame Type
    Service Type
    Frame Info
    Session Id
    Data Size
    Message ID

    Max major version supported by module and application
    no
    Control
    Control
    Transport Event Update
    Session Id assigned on Primary Transport
    Size of payload
    Variable

    0bNNNN
    0b0
    0b000
    0x00
    0xFD
    0xNN
    0xNNNNNNNN
    0xNNNNNNNN

  		Payload

  		 [tcpIpAddress:"x.x.x.x", tcpPort:NNNN]</td

#### 4.6.3 Starting Services on Secondary Transports

A Secondary Transport is capable of carrying  the video and audio services. Other services, including RPC and Hybrid service, must always run on the Primary Transport. (Note: Control service is an inherently started service on a transport and does not need to be established, but frames will be handled on a frame by frame basis of Primary vs Secondary Transport support)

The RPC `StartServiceACK` might include the parameters `audioServiceTransports` and `videoServiceTransports` describing which service is allowed to run on which transport priority type (Primary, Secondary or both). An application honors this information and starts the service(s) only on an allowed transport. For example, if video service is allowed only on a Secondary Transport, the application will not start video streaming until Secondary Transport is established and registered.

The transport priority types included in these parameters are listed in preferred order, for example, `[2,1]` (Secondary , Primary). In this case the priority of the Secondary Transport is higher than that of Primary Transport, the application may stop and restart service(s) when the Secondary Transport is added or removed. However,  each service type must only be started and carried on a single transport at a time.

When starting a service over a Secondary Transport the application, it must follow the previous sections to establish the transport connection and register its session over that transport. At that point it runs the normal sequence described in section 4.4. When starting a service over a Secondary Transport, the session ID that was provided during the establishment of the RPC service should be used.

#### 4.6.4 Terminating Secondary Transport

There is no procedure to terminate a Secondary Transport. However, if the Primary Transport is disconnected or the RPC service is stopped, any Secondary Transport for that session should be unregistered and if no other sessions are registered over that Secondary Transport it should be disconnected.

## 5. Services
Every active session has the ability to start any of the services defined in this protocol spec as long as they have permission on the module in which they are connected. Every session can only have one of each type of service open at a time.

Messages sent have a priority based on their Service Type. Lower values for service type have higher delivery priority. A message's payload's format is based on the different service types defined below.

### 5.1 Control Service
>Required: All Protocol Versions

The control service is the lowest level service available. While Control Frame packets are used frequently, the control service itself is rarely used.

### 5.2 RPC Service
>Required: All Protocol Versions

The RPC service is used to send requests, responses, and notifications between an application and a head unit. Valid messages are defined in the [RPC Specification](https://github.com/smartdevicelink/sdl_core/blob/master/src/components/interfaces/MOBILE_API.xml).

The payload of a message sent via the RPC service, which directly follows the Frame Header in the packet, consists of a Binary Header, and JSON data representing the RPC.

##### RPC Payload

    Binary Header

    JSON Data

#### 5.2.1 Binary Header
>Required: Protocol Version 2 and greater

    Byte 1
    Byte 2
    Byte 3
    Byte 4

    RPC Type
    RPC Function ID

    Correlation ID

    JSON Size

##### 5.2.1.1 Binary Header Fields

    Field
    Size
    Description

    RPC Type
    4 bit

      0x0 Request

      0x1 Response

      0x2 Notification

      0x3 Erroneous Response

      0x4 - 0xF Reserved

    RPC Function ID
    28 bit
    The Function ID of each RPC is specific to each version of the RPC Specification but in general do not change from version to version.

    Correlation ID
    32 bits (signed)
    The Correlation ID is used to map a request to its response. Requests sent in the same session with the same Correlation ID as a pending request will be rejected with an `INVALID_ID` response. Requests that use a Correlation ID less than 0 will be rejected with an `INVALID_ID` response. In Protocol Version 1, when the Binary Header did not exist, the Correlation ID was included as part of the JSON and has a max value of 65536.

    JSON Size
    32 bits
    The size of the JSON Data following the Binary Header in the RPC Payload

### 5.3 Hybrid (Bulk Data) Service
>Required: Protocol Version 2 and greater

The Hybrid Service does not need to be explicitly started; all applications that have successfully started the RPC Service have access to the Hybrid Service.

The Hybrid Service is similar to the RPC Service but adds a bulk data field. The payload of a message sent via the Hybrid service consists of a Binary Header, JSON Data, and Bulk Data.

The size of the Bulk Data field is the Data Size (Found in the Frame Header) minus the 12 Bytes of the Binary Header minus the JSON Size (Found in the Binary Header).

The Binary Header of a message using the Hybrid Service is the same as the Binary Header of a message using the RPC Service.

##### Hybrid Service Payload

    Binary Header

    JSON Data

    Bulk Data

### 5.4 Audio Service (PCM)
>Available: Protocol Version 3 and greater

The application can start the audio service to send PCM audio data to the head unit. After the `StartService` packet is sent and the ACK received, the payload for the Audio Service is only PCM audio data.

### 5.5 Video Service (H.264)
>Available: Protocol Version 3 and greater

The application can start the video service to send H.264 video data to the head unit. After the `StartService` packet is sent and the ACK received, the payload for the Video Service is only H.264 video data.

## 6. Ending Communication
The application may request it's session to be ended outside of a transport disconnect, module power cycle, etc.
### 6.1 Completely Closing  a Session and Ending All Services
To close out a communication session with the head unit, an application sends an `EndService` packet with service type 7 (RPC) to the module. The `EndService` packet payload should include the correct hash ID supplied with the `StartServiceACK`.

### 6.2 Closing Specific Services
If the application doesn't want to completely stop its session, but only wishes to close a specific session it can do so using an `EndService` packet that's service type matches the service that the application is trying to close. The `EndService` packet should include the hash ID in its payload that was contained in the `StartServiceACK` for  that specific service.


text:
#include <iostream>
#include <list>

//#define _DEBUG

#ifdef _WIN32
    typedef unsigned __int64    uint64;
#elif defined (__linux__) || defined (__CYGWIN__)
    typedef unsigned long long  uint64;
#endif
typedef std::list<int> List;

using namespace std;

//////////////////////////////////////////////////////////
// function prototypes
void solve();
void setInput(List &list);
void findOptimal(List &list);
int getMultiOfList(List &list);
int getSumOfList(List &list);
uint64 getMaxFlag(List &list);
int getLeftValue(List &list, uint64 flag);
int getRightValue(List &list, uint64 flag);
int getValue(List &list, uint64 flag, int match);
void pushLeft(List &target, List &org, uint64 flag);
void pushRight(List &target, List &org, uint64 flag);
void push(List &target, List &org, uint64 flag, int match);

uint64 _cost = 0;

int main()
{
    int size;
    cin >> size;
    //cout << size << endl;
    for (int i = 0; i < size; i++)
        solve();
    return 0;
}

void solve()
{
    List list;
    setInput(list);

    findOptimal(list);
    cout << _cost << endl;
}

void setInput(List &list)
{
    int size;
    cin >> size;
    //cout << size << endl;
    int a;
    for (int i = 0; i < size; i++) {
        cin >> a;
        list.push_back(a);
    }
    list.sort();
}

/**
 *
 * finish condition : the size of list is less than 2
 */
void findOptimal(List &list)
{
    // 1. finish condition
    int size = list.size();
    if (size < 2) return;
    if (size == 2) {
        _cost += getMultiOfList(list);
        return;
    }

    // 2. front == 1
    int front = list.front();
    if (front == 1) {
        list.pop_front();
        int next = list.front();
        _cost += next;
        findOptimal(list);
        return;
    }

    // 3. else : devide into 2 lists
    _cost += getMultiOfList(list);

    uint64 flag = 1;
    uint64 optimalFlag = flag;
    const uint64 MAX_FLAG = getMaxFlag(list);
#ifdef _DEBUG
    cout << "max : " << MAX_FLAG<< endl;
#endif
    List list1, list2;

    int currentCost = 0x7FFFFFFF;
    const int SUM_OF_LIST = getSumOfList(list);
    while (flag <= MAX_FLAG) {
        int leftValue = getLeftValue(list, flag);
        int rightValue = SUM_OF_LIST - leftValue;
        if (currentCost > abs(leftValue - rightValue)) {
            currentCost = abs(leftValue - rightValue);
            optimalFlag = flag;
        }
        flag++;
    }
#ifdef _DEBUG
    cout << "flag : " << optimalFlag<< endl;
#endif

    List ll, rl;
    pushLeft(ll, list, optimalFlag);
    pushRight(rl, list, optimalFlag);
    list.clear();

    findOptimal(ll);
    findOptimal(rl);
}

int getMultiOfList(List &list)
{
    int cost = 1;
    List::iterator it = list.begin();
    for (; it != list.end(); it++) {
        cost *= (*it);
    }
    return cost;
}

int getSumOfList(List &list)
{
    int sum = 0;
    List::iterator it = list.begin();
    for (; it != list.end(); it++) {
        sum += (*it);
    }
    return sum;
}

uint64 getMaxFlag(List &list) {
    int size = list.size();
    return (1 << size);
}

int getLeftValue(List &list, uint64 flag)
{
    return getValue(list, flag, 1);
}

int getRightValue(List &list, uint64 flag)
{
    return getValue(list, flag, 0);
}

int getValue(List &list, uint64 flag, int match)
{
    int value = 0;
    List::iterator it = list.begin();
    for (int i = 0; it != list.end(); it++, i++) {
        if (((flag >> i) & 1) == match) {
            value += (*it);
        }
    }
    return value;
}

void pushLeft(List &target, List &org, uint64 flag)
{
    push(target, org, flag, 1);
}

void pushRight(List &target, List &org, uint64 flag)
{
    push(target, org, flag, 0);
}

void push(List &target, List &org, uint64 flag, int match)
{
    List::iterator it = org.begin();
    for (int i = 0; it != org.end(); it++, i++) {
        if (((flag >> i) & 1) == match) {
            target.push_back(*it);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
set -euo pipefail

# Preseeds a node in Kubernetes with critical data migrated from
# an old node.

OLD_NODE_NAME="$1"
NEW_NODE_NAME="$2"
ROLE="$3"

##########################################################

log() { echo "[machine-id migration]: $1 " ; logger -t "machine-id-migration" "$1" ; }

log_changes() {
  log "$2"
  echo  # an empty line here so the next line will be the last.
  echo "changed=$1 comment='"$2"'"
}

exit_changes() {
	log_changes "$1" "$2"
	exit 0
}

get_node_data() {
	local template="$1"
	kubectl --request-timeout=1m get node "$OLD_NODE_NAME" --template="{{$template}}"
}

get_node_labels() {
  kubectl --request-timeout=1m get node "$OLD_NODE_NAME" --template='{{range $key, $value := .metadata.labels}}    {{$key}}: {{$value}}{{"\n"}}{{end}}'
}

exit_handler() {
  # Stashing $? MUST be the first command in the handler.
  code=$?
  if [ "$code" != "0" ]; then
    log_changes "yes" "Unknown failure migrating from $OLD_NODE_NAME to $NEW_NODE_NAME"
  fi
  exit $code
}

trap "exit_handler" INT TERM EXIT

##########################################################

log "migrating $OLD_NODE_NAME to $NEW_NODE_NAME"

kubectl --request-timeout=1m get node $NEW_NODE_NAME && exit_changes "no" "$NEW_NODE_NAME already exists, nothing to migrate"
kubectl --request-timeout=1m get node $OLD_NODE_NAME || exit_changes "no" "$OLD_NODE_NAME does not exist, nothing to migrate"

cat << EOF > /tmp/k8s-node-migration.yaml
apiVersion: v1
kind: Node
metadata:
  name: ${NEW_NODE_NAME}
  labels:
$(get_node_labels)
  annotations:
    node.alpha.kubernetes.io/ttl: '$(get_node_data 'index .metadata.annotations "node.alpha.kubernetes.io/ttl"')'
    volumes.kubernetes.io/controller-managed-attach-detach: '$(get_node_data 'index .metadata.annotations "volumes.kubernetes.io/controller-managed-attach-detach"')'
    flannel.alpha.coreos.com/backend-data: '$(get_node_data 'index .metadata.annotations "flannel.alpha.coreos.com/backend-data"')'
    flannel.alpha.coreos.com/backend-type: '$(get_node_data 'index .metadata.annotations "flannel.alpha.coreos.com/backend-type"')'
    flannel.alpha.coreos.com/public-ip: $(get_node_data 'index .metadata.annotations "flannel.alpha.coreos.com/public-ip"')
    flannel.alpha.coreos.com/kube-subnet-manager: "true"
spec:
  externalID: ${NEW_NODE_NAME}
  podCIDR: $(get_node_data .spec.podCIDR)
EOF

if [[ "$ROLE" == "master" ]]; then
  cat << EOF >> /tmp/k8s-node-migration.yaml
  taints:
  - effect: NoSchedule
    key: node-role.kubernetes.io/master
EOF
fi

kubectl --request-timeout=1m create -f /tmp/k8s-node-migration.yaml 2>/dev/null

rm /tmp/k8s-node-migration.yaml

exit_changes "yes" "Node data migrated from $OLD_NODE_NAME to $NEW_NODE_NAME"


text:
title: "Indigo, minimalist jekyll theme"
layout: post
date: 2016-01-23 22:10
tag: jekyll
image: /assets/images/jekyll-logo-light-solid.png
headerImage: true
projects: true
hidden: true # don't count this post in blog pagination
description: "This is a simple and minimalist template for Jekyll for those who likes to eat noodles."
jemoji: '<img class="emoji" title=":ramen:" alt=":ramen:" src="https://assets.github.com/images/icons/emoji/unicode/1f35c.png" height="20" width="20" align="absmiddle">'
author: johndoe
externalLink: false
---

![Screenshot](https://raw.githubusercontent.com/sergiokopplin/indigo/gh-pages/assets/screen-shot.png)

Example of project - Indigo Minimalist Jekyll Template - [Demo](http://sergiokopplin.github.io/indigo/). This is a simple and minimalist template for Jekyll for those who likes to eat noodles.

---

What has inside?

- Gulp
- BrowserSync
- Stylus
- SVG
- Travis
- No JS
- [98/100](https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fsergiokopplin.github.io%2Findigo%2F)

---

[Check it out](http://sergiokopplin.github.io/indigo/) here.
If you need some help, just [tell me](http://github.com/sergiokopplin/indigo/issues).


text:
#ifndef _IAS_BackgroundJobsExecutor_H_
#define _IAS_BackgroundJobsExecutor_H_

#include "Runnable.h"
#include "Thread.h"
#include "Mutex.h"

#include "../logger/logger.h"
#include "../memory/memory.h"
#include "../memory/ma/PtrHolder.h"
#include "../containers/PtrVector.h"

#include "commonlib/memory/ma/Factory.h"

#include <vector>

namespace IAS {

class BackgroundJob;
class BackgroundJobsQueue;
class BackgroundJobThread;

/*************************************************************************/
/** The class. */
 class BackgroundJobsExecutor {
public:

	BackgroundJobsExecutor(int iNumThreads, int iQueueSize = 100);
	virtual ~BackgroundJobsExecutor() throw();

	void enqueue(BackgroundJob *pJob);

	void setCompleteJobsOnDelete(bool bCompleteJobsOnDelete);

protected:

	void init(int iQueueSize);

	typedef PtrVector<BackgroundJobThread> ThreadsTab;
	ThreadsTab tabThreads;

	int iNumThreads;

	IAS_DFT_FACTORY<BackgroundJobsQueue>::PtrHolder ptrQueue;

	bool bCompleteJobsOnDelete;

	friend class Factory<BackgroundJobsExecutor>;
};

/*************************************************************************/
}

#endif /* _IAS_BACKGROUNDJOBSEXECUTOR_H_ */


text:
#include <isl_multi_macro.h>

/* Does "multi" involve any NaNs?
 */
isl_bool FN(MULTI(BASE),involves_nan)(__isl_keep MULTI(BASE) *multi)
{
	return FN(MULTI(BASE),any)(multi, &FN(EL,involves_nan));
}


text:
package es.magDevs.myLibrary.migracion;

import com.healthmarketscience.jackcess.Row;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
import java.math.BigDecimal;
import java.util.Date;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import es.magDevs.myLibrary.migracion.beans.AutorBean;
import es.magDevs.myLibrary.migracion.beans.CodificacionBean;
import es.magDevs.myLibrary.migracion.beans.ColeccionBean;
import es.magDevs.myLibrary.migracion.beans.EditorialBean;
import es.magDevs.myLibrary.migracion.beans.LibrosBean;
import es.magDevs.myLibrary.migracion.beans.RevistasBean;
import es.magDevs.myLibrary.migracion.beans.Titulo_revistasBean;
import es.magDevs.myLibrary.migracion.beans.UbicacionBean;

public class Rellenador {
	public static AutorBean rellenadorAutorBean(Row row) {
		AutorBean d = new AutorBean();
		d.setNº_autor((Integer)row.get("Nº AUTOR"));
		d.setApellidos((String)row.get("APELLIDOS"));
		d.setNombre((String)row.get("NOMBRE"));
		d.setPais_de_nacimiento((String)row.get("PAIS DE NACIMIENTO"));
		d.setLugar_de_nacimiento((String)row.get("LUGAR DE NACIMIENTO"));
		d.setAño__de_nacimiento((Integer)row.get("AÑO  DE NACIMIENTO"));
		d.setAño_fallecimiento((Integer)row.get("AÑO FALLECIMIENTO"));
		d.setNotas((String)row.get("NOTAS"));
		return d;
	}
	public static List<AutorBean> listadorAutorBean(Database db) {
		Table table;
		try {
			table = db.getTable("AUTOR");
		} catch (IOException e) {
			return null;
		}
		List<AutorBean> list = new ArrayList<AutorBean>();
		for (Row row : table) {
			AutorBean p = Rellenador.rellenadorAutorBean(row);
			list.add(p);
		}
		return list;
	}
	public static CodificacionBean rellenadorCodificacionBean(Row row) {
		CodificacionBean d = new CodificacionBean();
		d.setNúmero_codificacion((Integer)row.get("NÚMERO CODIFICACION"));
		d.setCodigo((String)row.get("CODIGO"));
		return d;
	}
	public static List<CodificacionBean> listadorCodificacionBean(Database db) {
		Table table;
		try {
			table = db.getTable("CODIFICACION");
		} catch (IOException e) {
			return null;
		}
		List<CodificacionBean> list = new ArrayList<CodificacionBean>();
		for (Row row : table) {
			CodificacionBean p = Rellenador.rellenadorCodificacionBean(row);
			list.add(p);
		}
		return list;
	}
	public static ColeccionBean rellenadorColeccionBean(Row row) {
		ColeccionBean d = new ColeccionBean();
		d.setNº_coleccion((Integer)row.get("Nº COLECCION"));
		d.setNombre_coleccion((String)row.get("NOMBRE COLECCION"));
		d.setNombre_editorial((String)row.get("NOMBRE EDITORIAL"));
		return d;
	}
	public static List<ColeccionBean> listadorColeccionBean(Database db) {
		Table table;
		try {
			table = db.getTable("COLECCION");
		} catch (IOException e) {
			return null;
		}
		List<ColeccionBean> list = new ArrayList<ColeccionBean>();
		for (Row row : table) {
			ColeccionBean p = Rellenador.rellenadorColeccionBean(row);
			list.add(p);
		}
		return list;
	}
	public static EditorialBean rellenadorEditorialBean(Row row) {
		EditorialBean d = new EditorialBean();
		d.setNº_editorial((Integer)row.get("Nº EDITORIAL"));
		d.setNombre_editorial((String)row.get("NOMBRE EDITORIAL"));
		d.setCiudad_de_ubicacion((String)row.get("CIUDAD DE UBICACION"));
		return d;
	}
	public static List<EditorialBean> listadorEditorialBean(Database db) {
		Table table;
		try {
			table = db.getTable("EDITORIAL");
		} catch (IOException e) {
			return null;
		}
		List<EditorialBean> list = new ArrayList<EditorialBean>();
		for (Row row : table) {
			EditorialBean p = Rellenador.rellenadorEditorialBean(row);
			list.add(p);
		}
		return list;
	}
	public static LibrosBean rellenadorLibrosBean(Row row) {
		LibrosBean d = new LibrosBean();
		d.setNº_libro((Integer)row.get("Nº LIBRO"));
		d.setTitulo((String)row.get("TITULO"));
		d.setApellidos((String)row.get("APELLIDOS"));
		d.setNombre((String)row.get("NOMBRE"));
		d.setNombre_editorial((String)row.get("NOMBRE EDITORIAL"));
		d.setNombre_coleccion((String)row.get("NOMBRE COLECCION"));
		d.setNº_isbn((String)row.get("Nº ISBN"));
		d.setAño_publicacion((Integer)row.get("AÑO PUBLICACION"));
		d.setNº_edicion((Integer)row.get("Nº EDICION"));
		d.setAño_c((Integer)row.get("AÑO C"));
		d.setNº_paginas((Integer)row.get("Nº PAGINAS"));
		d.setTomo((Integer)row.get("TOMO"));
		d.setTraductor((String)row.get("TRADUCTOR"));
		d.setCodigo((String)row.get("CODIGO"));
		d.setSitio((String)row.get("SITIO"));
		d.setAño_compra((String)row.get("AÑO COMPRA"));
		d.setPrecio((BigDecimal)row.get("PRECIO"));
		d.setNotas((String)row.get("NOTAS"));
		return d;
	}
	public static List<LibrosBean> listadorLibrosBean(Database db) {
		Table table;
		try {
			table = db.getTable("LIBROS");
		} catch (IOException e) {
			return null;
		}
		List<LibrosBean> list = new ArrayList<LibrosBean>();
		for (Row row : table) {
			LibrosBean p = Rellenador.rellenadorLibrosBean(row);
			list.add(p);
		}
		return list;
	}
	public static RevistasBean rellenadorRevistasBean(Row row) {
		RevistasBean d = new RevistasBean();
		d.setId_revista((Integer)row.get("Id REVISTA"));
		d.setTitulo_revista((String)row.get("TITULO REVISTA"));
		d.setNumero((Integer)row.get("NUMERO"));
		d.setMes_año((Integer)row.get("MES/AÑO"));
		d.setCodificacion((String)row.get("CODIFICACION"));
		d.setNº_isbn((String)row.get("Nº ISBN"));
		d.setNº_paginas((Integer)row.get("Nº PAGINAS"));
		d.setTemas((String)row.get("TEMAS"));
		d.setUbicacion((String)row.get("UBICACION"));
		d.setAño_compra((Integer)row.get("AÑO COMPRA"));
		d.setPrecio((Integer)row.get("PRECIO"));
		d.setNotas((String)row.get("NOTAS"));
		return d;
	}
	public static List<RevistasBean> listadorRevistasBean(Database db) {
		Table table;
		try {
			table = db.getTable("REVISTAS");
		} catch (IOException e) {
			return null;
		}
		List<RevistasBean> list = new ArrayList<RevistasBean>();
		for (Row row : table) {
			RevistasBean p = Rellenador.rellenadorRevistasBean(row);
			list.add(p);
		}
		return list;
	}
	public static Titulo_revistasBean rellenadorTitulo_revistasBean(Row row) {
		Titulo_revistasBean d = new Titulo_revistasBean();
		d.setNº_revista((Integer)row.get("Nº REVISTA"));
		d.setTitulo((String)row.get("TITULO"));
		d.setNombre_editorial((String)row.get("NOMBRE EDITORIAL"));
		return d;
	}
	public static List<Titulo_revistasBean> listadorTitulo_revistasBean(Database db) {
		Table table;
		try {
			table = db.getTable("TITULO REVISTAS");
		} catch (IOException e) {
			return null;
		}
		List<Titulo_revistasBean> list = new ArrayList<Titulo_revistasBean>();
		for (Row row : table) {
			Titulo_revistasBean p = Rellenador.rellenadorTitulo_revistasBean(row);
			list.add(p);
		}
		return list;
	}
	public static UbicacionBean rellenadorUbicacionBean(Row row) {
		UbicacionBean d = new UbicacionBean();
		d.setNº_ubicacion((Integer)row.get("Nº UBICACION"));
		d.setSitio((String)row.get("SITIO"));
		return d;
	}
	public static List<UbicacionBean> listadorUbicacionBean(Database db) {
		Table table;
		try {
			table = db.getTable("UBICACION");
		} catch (IOException e) {
			return null;
		}
		List<UbicacionBean> list = new ArrayList<UbicacionBean>();
		for (Row row : table) {
			UbicacionBean p = Rellenador.rellenadorUbicacionBean(row);
			list.add(p);
		}
		return list;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Xml.Linq;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Editing.Attributes;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Controls;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;

namespace Inspector_AddAttributeAsync
{
  internal class AttributeControlViewModel : EmbeddableControl
  {
    private EmbeddableControl _inspectorViewModel = null;
    private UserControl _inspectorView = null;

    public AttributeControlViewModel(XElement options, bool canChangeOptions) : base(options, canChangeOptions)  { }

    /// <summary>
    /// Property for the inspector UI.
    /// </summary>
    public UserControl InspectorView
    {
      get { return _inspectorView; }
      set { SetProperty(ref _inspectorView, value, () => InspectorView); }
    }

    /// <summary>
    /// Access to the view model of the inspector
    /// </summary>
    public EmbeddableControl InspectorViewModel
    {
      get { return _inspectorViewModel; }
      set
      {
        if (value != null)
        {
          _inspectorViewModel = value;
          _inspectorViewModel.OpenAsync();

        }
        else if (_inspectorViewModel != null)
        {
          _inspectorViewModel.CloseAsync();
          _inspectorViewModel = value;
        }

        NotifyPropertyChanged(() => InspectorViewModel);
      }
    }
  }
}


text:
<?php

namespace tagadvance\gilligan\text;

/**
 * This class is designed as a builder with a fluent interface to simplify
 * string construction and manipulation.
 *
 * @author Tag <tagadvance+gilligan@gmail.com>
 */
// TODO: character encoding methods, especially utf-8
// TODO: immutable
// TODO: cho[m]p
class StringClass {

	const WHITESPACE_CHARACTER_MASK = " \t\n\r\0\x0B";

	private $string;

	/**
	 * This factory method allows one to chain method calls.
	 *
	 * @param mixed $string
	 * @return \tagadvance\gilligan\base\StringClass
	 */
	static function valueOf($string): self {
		return $string instanceof self ? $string : new self ( $string );
	}

	static function toNativeString($string): string {
		return $string instanceof self ? $string->string : (string) $string;
	}

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

	/**
	 *
	 * @param mixed $string
	 * @return self
	 */
	function concatenate($string): self {
		$string = self::toNativeString ( $string );
		$concat = $this->string . $string;
		return new self ( $concat );
	}

	/**
	 *
	 * @param unknown $substring
	 * @return bool
	 * @see http://php.net/manual/en/function.strpos.php
	 */
	function contains($substring): bool {
		$substring = self::toNativeString ( $substring );
		$position = strpos ( $this->string, $substring );
		return $position !== false;
	}

	/**
	 *
	 * @param mixed $string
	 * @return bool
	 * @see http://php.net/manual/en/function.strcmp.php
	 */
	function equals($string): bool {
		$string = self::toNativeString ( $string );
		return strcmp ( $this->string, $string ) === 0;
	}

	/**
	 *
	 * @param mixed $string
	 * @return bool
	 * @see http://php.net/manual/en/function.strcasecmp.php
	 */
	function equalsCaseInsensitive ($string): bool {
		$string = self::toNativeString ( $string );
		return strcasecmp ( $this->string, $string ) === 0;
	}

	/**
	 *
	 * @return self
	 * http://php.net/manual/en/function.strtolower.php
	 */
	function toLowercase(): self {
		$lower = strtolower ( $this->string );
		return new self ( $lower );
	}

	/**
	 *
	 * @return self
	 * http://php.net/manual/en/function.strtoupper.php
	 */
	function toUppercase(): self {
		$upper = strtoupper ( $this->string );
		return new self ( $upper );
	}

	/**
	 *
	 * @param string $character_mask
	 * @return self
	 * @see http://php.net/manual/en/function.trim.php
	 */
	function trim(string $character_mask = self::WHITESPACE_CHARACTER_MASK): self {
		$trim = trim ( $this->string, $character_mask );
		return new self ( $trim );
	}

	/**
	 *
	 * @param string $character_mask
	 * @return self
	 * @see http://php.net/manual/en/function.ltrim.php
	 */
	function trimLeft(string $character_mask = self::WHITESPACE_CHARACTER_MASK): self {
		$trim = ltrim ( $this->string, $character_mask );
		return new self ( $trim );
	}

	/**
	 *
	 * @param string $character_mask
	 * @return self
	 * @see http://php.net/manual/en/function.rtrim.php
	 */
	function trimRight(string $character_mask = self::WHITESPACE_CHARACTER_MASK): self {
		$trim = rtrim ( $this->string, $character_mask );
		return new self ( $trim );
	}

	/**
	 *
	 * @param mixed $prefix
	 * @param int $offset
	 * @return bool
	 */
	function startsWith($prefix, int $offset = 0): bool {
		$prefix = self::toNativeString ( $prefix );
		$length = strlen ( $prefix );
		$start = substr ( $this->string, $offset, $length );
		return ($prefix === $start);
	}

	/**
	 *
	 * @param mixed $suffix
	 * @return bool
	 */
	function endsWith($suffix): bool {
		$suffix = self::toNativeString ( $suffix );
		$stringLength = strlen ( $this->string );
		$suffixLength = strlen ( $suffix );
		$start = $stringLength - $suffixLength;
		$substring = substr ( $this->string, $start );
		return ($suffix === $substring);
	}

	/**
	 *
	 * @param unknown $string
	 * @param int $offset
	 * @return mixed
	 * @see http://php.net/manual/en/function.strpos.php
	 */
	function positionOf($string, int $offset = 0) {
		$string = self::toNativeString ( $string );
		return strpos ( $this->string, $string, $offset );
	}

	/**
	 *
	 * @param unknown $string
	 * @param int $offset
	 * @return mixed
	 * @see http://php.net/manual/en/function.strrpos.php
	 */
	function lastPositionOf($string, int $offset = 0) {
		$string = self::toNativeString ( $string );
		return strrpos ( $this->string, $string, $offset );
	}

	/**
	 *
	 * @return bool
	 * @see http://php.net/manual/en/function.empty.php
	 */
	function isEmpty(): bool {
		return empty ( $this->string );
	}

	/**
	 *
	 * @return number
	 * @see http://php.net/manual/en/function.strlen.php
	 */
	function length(): int {
		return strlen ( $this->string );
	}

	/**
	 *
	 * @param string $pattern
	 * @param array $matches
	 * @param int $flags
	 * @param int $offset
	 * @return number
	 * @see http://php.net/manual/en/function.preg-match.php
	 */
	function match(string $pattern, array &$matches = null, int $flags = null, int $offset = null) {
		return preg_match ( $pattern, $this->string, $matches, $flags, $offset );
	}

	/**
	 *
	 * @param string $pattern
	 * @param int $limit
	 * @param int $flags
	 * @return array
	 */
	function split(string $pattern, int $limit = null, int $flags = null): array {
		return preg_split ( $pattern, $this->string, $limit, $flags );
	}

	// TODO: replace with str_replace($search, $replace, $subject)
	function replace($old, $new, $limit = null) {
		$old = self::toNativeString ( $old );
		$new = self::toNativeString ( $new );
		$oldLength = strlen ( $old );
		$newLength = strlen ( $new );
		$string = $this->string;
		$offset = 0;
		for ($i = 0; $limit === null || $i < $limit; $i ++) {
			$position = strpos ( $string, $old, $offset );
			if ($position === false) {
				break;
			}
			$string = substr_replace ( $string, $new, $position, $oldLength );
			$offset += $position + $newLength;
		}
		return new self ( $string );
	}

	/**
	 *
	 * @return self
	 * @see http://php.net/manual/en/function.strrev.php
	 */
	function reverse(): self {
		$reverse = strrev ( $this->string );
		return new self ( $reverse );
	}

	/**
	 *
	 * @param mixed $delimiter
	 * @param int $limit
	 * @return array
	 */
	function explode($delimiter, int $limit = null): array {
		$delimiter = self::toNativeString ( $delimiter );
		if ($limit == null) {
			return explode ( $delimiter, $this->string );
		}
		return explode ( $delimiter, $this->string, $limit );
	}

	/**
	 *
	 * @param int $fromIndex (inclusive)
	 * @param int $toIndex (exclusive)
	 * @throws OutOfBoundsException
	 * @return self
	 * @see http://php.net/manual/en/function.substr.php
	 */
	function substring(int $fromIndex, int $toIndex = null): self {
		if ($toIndex == null) {
			$toIndex = $this->length ();
		} else if ($toIndex < $fromIndex) {
			throw new \OutOfBoundsException ( "!($fromIndex <= $toIndex)" );
		}
		$length = $toIndex - $fromIndex;
		$string = substr ( $this->string, $fromIndex, $length );
		return new self ( $string );
	}

	/**
	 *
	 * @param int $length
	 * @param mixed $string
	 * @return self
	 * @see http://php.net/manual/en/function.str-pad.php
	 */
	function pad(int $length, $string): self {
		$string = self::toNativeString ( $string );
		$result = str_pad ( $this->string, $length, $string, STR_PAD_BOTH );
		return new self ( $result );
	}

	/**
	 *
	 * @param int $length
	 * @param mixed $string
	 * @return self
	 * @see http://php.net/manual/en/function.str-pad.php
	 */
	function padLeft(int $length, $string): self {
		$string = self::toNativeString ( $string );
		$result = str_pad ( $this->string, $length, $string, STR_PAD_LEFT );
		return new self ( $result );
	}

	/**
	 *
	 * @param int $length
	 * @param mixed $string
	 * @return self
	 * @see http://php.net/manual/en/function.str-pad.php
	 */
	function padRight(int $length, $string): self {
		$string = self::toNativeString ( $string );
		$result = str_pad ( $this->string, $length, $string, STR_PAD_RIGHT );
		return new self ( $result );
	}

	function __toString(): string {
		return $this->string;
	}

	function __invoke() {
		return $this->string;
	}

	/**
	 *
	 * @param int $length
	 * @param string $characters
	 * @return self a random string
	 */
	static function random(int $length, $characters = 'abcdefghijklmnopqrstuvwxyz0123456789'): self {
		$min = 0;
		$max = strlen ( $characters ) - 1;

		$randomString = '';
		for ($i = 0; $i < $length; $i ++) {
			$index = rand ( $min, $max );
			$randomString .= $characters {$index};
		}

		return new self ( $randomString );
	}

}


text:
package org.rzats.jsonschema;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

/**
 * The POJO class used to store REST API responses.
 * Automatically converted to JSON by Spring Boot.
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class JsonValidatorResponse {
    private String action;
    private String id;
    private String status;
    private String message;

    /**
     * The class constructor. null parameters are omitted from the JSON representation.
     *
     * @param action  A short name for the action (validateDocument, uploadSchema etc.)
     * @param id      The unique identifier of a JSON schema
     * @param status  The status of the request - "success" if valid, "error" otherwise
     * @param message The error message - either for internal exceptions or JSON validation errors
     */
    public JsonValidatorResponse(String action, String id, String status, String message) {
        this.action = action;
        this.id = id;
        this.status = status;
        this.message = message;
    }

    public String getAction() {
        return action;
    }

    public String getId() {
        return id;
    }

    public String getStatus() {
        return status;
    }

    public String getMessage() {
        return message;
    }

    public String toJsonString() {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        try {
            return ow.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            return String.format("Exception while converting response to string: %s", e.getMessage());
        }
    }
}


text:
/// <reference path="circleDraw.ts" />

module Render{
	export module Draw{

		/*	--------------------------------------------------- *\
				[class] Circle()

				* Dessiner un cercle *

		\*	--------------------------------------------------- */
		export class Circle extends Draw{

			radius: number;

			/*	--------------------------------------------------- *\
					[function] constructor([optional : position.x, position.y, radius])

					* Quand on crée un cercle *

					Return: nil
			\*	--------------------------------------------------- */
			constructor(...parameters: any[]){
				super();
				this.shape = "circle";

				this.position.x = parameters[0] || this.position.x;
				this.position.y = parameters[1] || this.position.y;
				this.radius = parameters[2] || this.radius;

				this.setSize(this.getRadius() * 2, this.getRadius() * 2);

			}

			/*	--------------------------------------------------- *\
					[function] setRadius(radius)

					* Set le radius du cercle *

					Return: nil
			\*	--------------------------------------------------- */
			setRadius(radius:number){
				this.radius = radius;
				this.setSize(radius * 2, radius * 2);
			}

			/*	--------------------------------------------------- *\
					[function] getRadius()

					* Retourne le radius du cercle *

					Return: radius
			\*	--------------------------------------------------- */
			getRadius(){
				return this.radius;
			}
		}
	}
}


text:
//
// Copyright 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// mtl_resources.h:
//    Declares wrapper classes for Metal's MTLTexture and MTLBuffer.
//

#ifndef LIBANGLE_RENDERER_METAL_MTL_RESOURCES_H_
#define LIBANGLE_RENDERER_METAL_MTL_RESOURCES_H_

#import <Metal/Metal.h>

#include <atomic>
#include <memory>

#include "common/FastVector.h"
#include "common/MemoryBuffer.h"
#include "common/angleutils.h"
#include "libANGLE/Error.h"
#include "libANGLE/angletypes.h"
#include "libANGLE/renderer/metal/mtl_common.h"
#include "libANGLE/renderer/metal/mtl_format_utils.h"

namespace rx
{

class ContextMtl;

namespace mtl
{

class CommandQueue;
class BlitCommandEncoder;
class Resource;
class Texture;
class Buffer;

using ResourceRef    = std::shared_ptr<Resource>;
using TextureRef     = std::shared_ptr<Texture>;
using TextureWeakRef = std::weak_ptr<Texture>;
using BufferRef      = std::shared_ptr<Buffer>;
using BufferWeakRef  = std::weak_ptr<Buffer>;

class Resource : angle::NonCopyable
{
  public:
    virtual ~Resource() {}

    // Check whether the resource still being used by GPU including the pending (uncommitted)
    // command buffer.
    bool isBeingUsedByGPU(Context *context) const;
    // Checks whether the last command buffer that uses the given resource has been committed or not
    bool hasPendingWorks(Context *context) const;

    void setUsedByCommandBufferWithQueueSerial(uint64_t serial, bool writing);

    uint64_t getCommandBufferQueueSerial() const { return mUsageRef->cmdBufferQueueSerial; }

    // Flag indicate whether we should synchronize the content to CPU after GPU changed this
    // resource's content.
    bool isCPUReadMemNeedSync() const { return mUsageRef->cpuReadMemNeedSync; }
    void resetCPUReadMemNeedSync() { mUsageRef->cpuReadMemNeedSync = false; }

    // These functions are useful for BufferMtl to know whether it should update the shadow copy
    bool isCPUReadMemDirty() const { return mUsageRef->cpuReadMemDirty; }
    void resetCPUReadMemDirty() { mUsageRef->cpuReadMemDirty = false; }

  protected:
    Resource();
    // Share the GPU usage ref with other resource
    Resource(Resource *other);

    void reset();

  private:
    struct UsageRef
    {
        // The id of the last command buffer that is using this resource.
        uint64_t cmdBufferQueueSerial = 0;

        // This flag means the resource was issued to be modified by GPU, if CPU wants to read
        // its content, explicit synchronization call must be invoked.
        bool cpuReadMemNeedSync = false;

        // This flag is useful for BufferMtl to know whether it should update the shadow copy
        bool cpuReadMemDirty = false;
    };

    // One resource object might just be a view of another resource. For example, a texture 2d
    // object might be a view of one face of a cube texture object. Another example is one texture
    // object of size 2x2 might be a mipmap view of a texture object size 4x4. Thus, if one object
    // is being used by a command buffer, it means the other object is being used also. In this
    // case, the two objects must share the same UsageRef property.
    std::shared_ptr<UsageRef> mUsageRef;
};

class Texture final : public Resource,
                      public WrappedObject<id<MTLTexture>>,
                      public std::enable_shared_from_this<Texture>
{
  public:
    static angle::Result Make2DTexture(ContextMtl *context,
                                       const Format &format,
                                       uint32_t width,
                                       uint32_t height,
                                       uint32_t mips /** use zero to create full mipmaps chain */,
                                       bool renderTargetOnly,
                                       bool allowFormatView,
                                       TextureRef *refOut);

    static angle::Result MakeCubeTexture(ContextMtl *context,
                                         const Format &format,
                                         uint32_t size,
                                         uint32_t mips /** use zero to create full mipmaps chain */,
                                         bool renderTargetOnly,
                                         bool allowFormatView,
                                         TextureRef *refOut);

    static angle::Result Make2DMSTexture(ContextMtl *context,
                                         const Format &format,
                                         uint32_t width,
                                         uint32_t height,
                                         uint32_t samples,
                                         bool renderTargetOnly,
                                         bool allowFormatView,
                                         TextureRef *refOut);

    static angle::Result Make2DArrayTexture(ContextMtl *context,
                                            const Format &format,
                                            uint32_t width,
                                            uint32_t height,
                                            uint32_t mips,
                                            uint32_t arrayLength,
                                            bool renderTargetOnly,
                                            bool allowFormatView,
                                            TextureRef *refOut);

    static angle::Result Make3DTexture(ContextMtl *context,
                                       const Format &format,
                                       uint32_t width,
                                       uint32_t height,
                                       uint32_t depth,
                                       uint32_t mips,
                                       bool renderTargetOnly,
                                       bool allowFormatView,
                                       TextureRef *refOut);

    static TextureRef MakeFromMetal(id<MTLTexture> metalTexture);

    // Allow CPU to read & write data directly to this texture?
    bool isCPUAccessible() const;

    bool supportFormatView() const;

    void replace2DRegion(ContextMtl *context,
                         const MTLRegion &region,
                         const MipmapNativeLevel &mipmapLevel,
                         uint32_t slice,
                         const uint8_t *data,
                         size_t bytesPerRow);

    void replaceRegion(ContextMtl *context,
                       const MTLRegion &region,
                       const MipmapNativeLevel &mipmapLevel,
                       uint32_t slice,
                       const uint8_t *data,
                       size_t bytesPerRow,
                       size_t bytesPer2DImage);

    void getBytes(ContextMtl *context,
                  size_t bytesPerRow,
                  size_t bytesPer2DInage,
                  const MTLRegion &region,
                  const MipmapNativeLevel &mipmapLevel,
                  uint32_t slice,
                  uint8_t *dataOut);

    // Create 2d view of a cube face which full range of mip levels.
    TextureRef createCubeFaceView(uint32_t face);
    // Create a view of one slice at a level.
    TextureRef createSliceMipView(uint32_t slice, const MipmapNativeLevel &level);
    // Create a view of a level.
    TextureRef createMipView(const MipmapNativeLevel &level);
    // Create a view with different format
    TextureRef createViewWithDifferentFormat(MTLPixelFormat format);
    // Same as above but the target format must be compatible, for example sRGB to linear. In this
    // case texture doesn't need format view usage flag.
    TextureRef createViewWithCompatibleFormat(MTLPixelFormat format);
    // Create a swizzled view
    TextureRef createSwizzleView(const TextureSwizzleChannels &swizzle);

    MTLTextureType textureType() const;
    MTLPixelFormat pixelFormat() const;

    uint32_t mipmapLevels() const;
    uint32_t arrayLength() const;
    uint32_t cubeFacesOrArrayLength() const;

    uint32_t width(const MipmapNativeLevel &level) const;
    uint32_t height(const MipmapNativeLevel &level) const;
    uint32_t depth(const MipmapNativeLevel &level) const;

    gl::Extents size(const MipmapNativeLevel &level) const;
    gl::Extents size(const ImageNativeIndex &index) const;

    uint32_t widthAt0() const { return width(kZeroNativeMipLevel); }
    uint32_t heightAt0() const { return height(kZeroNativeMipLevel); }
    uint32_t depthAt0() const { return depth(kZeroNativeMipLevel); }
    gl::Extents sizeAt0() const { return size(kZeroNativeMipLevel); }

    uint32_t samples() const;

    angle::Result resize(ContextMtl *context, uint32_t width, uint32_t height);

    // For render target
    MTLColorWriteMask getColorWritableMask() const { return *mColorWritableMask; }
    void setColorWritableMask(MTLColorWriteMask mask) { *mColorWritableMask = mask; }

    // Get linear color space view. Only usable for sRGB textures.
    TextureRef getLinearColorView();

    // Get stencil view
    TextureRef getStencilView();

    // Change the wrapped metal object. Special case for swapchain image
    void set(id<MTLTexture> metalTexture);

    // sync content between CPU and GPU
    void syncContent(ContextMtl *context, mtl::BlitCommandEncoder *encoder);

  private:
    using ParentClass = WrappedObject<id<MTLTexture>>;

    static angle::Result MakeTexture(ContextMtl *context,
                                     const Format &mtlFormat,
                                     MTLTextureDescriptor *desc,
                                     uint32_t mips,
                                     bool renderTargetOnly,
                                     bool allowFormatView,
                                     TextureRef *refOut);

    Texture(id<MTLTexture> metalTexture);
    Texture(ContextMtl *context,
            MTLTextureDescriptor *desc,
            uint32_t mips,
            bool renderTargetOnly,
            bool allowFormatView);

    // Create a texture view
    Texture(Texture *original, MTLPixelFormat format);
    Texture(Texture *original, MTLTextureType type, NSRange mipmapLevelRange, NSRange slices);
    Texture(Texture *original, const TextureSwizzleChannels &swizzle);

    void syncContentIfNeeded(ContextMtl *context);

    AutoObjCObj<MTLTextureDescriptor> mCreationDesc;

    // This property is shared between this object and its views:
    std::shared_ptr<MTLColorWriteMask> mColorWritableMask;

    // Linear view of sRGB texture
    TextureRef mLinearColorView;

    TextureRef mStencilView;
};

class Buffer final : public Resource, public WrappedObject<id<MTLBuffer>>
{
  public:
    static angle::Result MakeBuffer(ContextMtl *context,
                                    size_t size,
                                    const uint8_t *data,
                                    BufferRef *bufferOut);

    static angle::Result MakeBufferWithSharedMemOpt(ContextMtl *context,
                                                    bool forceUseSharedMem,
                                                    size_t size,
                                                    const uint8_t *data,
                                                    BufferRef *bufferOut);

    static angle::Result MakeBufferWithResOpt(ContextMtl *context,
                                              MTLResourceOptions resourceOptions,
                                              size_t size,
                                              const uint8_t *data,
                                              BufferRef *bufferOut);

    angle::Result reset(ContextMtl *context, size_t size, const uint8_t *data);
    angle::Result resetWithSharedMemOpt(ContextMtl *context,
                                        bool forceUseSharedMem,
                                        size_t size,
                                        const uint8_t *data);
    angle::Result resetWithResOpt(ContextMtl *context,
                                  MTLResourceOptions resourceOptions,
                                  size_t size,
                                  const uint8_t *data);

    const uint8_t *mapReadOnly(ContextMtl *context);
    uint8_t *map(ContextMtl *context);
    uint8_t *mapWithOpt(ContextMtl *context, bool readonly, bool noSync);

    void unmap(ContextMtl *context);
    // Same as unmap but do not do implicit flush()
    void unmapNoFlush(ContextMtl *context);
    void unmapAndFlushSubset(ContextMtl *context, size_t offsetWritten, size_t sizeWritten);
    void flush(ContextMtl *context, size_t offsetWritten, size_t sizeWritten);

    size_t size() const;
    bool useSharedMem() const;

    // Explicitly sync content between CPU and GPU
    void syncContent(ContextMtl *context, mtl::BlitCommandEncoder *encoder);

  private:
    Buffer(ContextMtl *context, bool forceUseSharedMem, size_t size, const uint8_t *data);
    Buffer(ContextMtl *context,
           MTLResourceOptions resourceOptions,
           size_t size,
           const uint8_t *data);

    bool mMapReadOnly = true;
};

class NativeTexLevelArray
{
  public:
    TextureRef &at(const MipmapNativeLevel &level) { return mTexLevels.at(level.get()); }
    const TextureRef &at(const MipmapNativeLevel &level) const
    {
        return mTexLevels.at(level.get());
    }

    TextureRef &operator[](const MipmapNativeLevel &level) { return at(level); }
    const TextureRef &operator[](const MipmapNativeLevel &level) const { return at(level); }

    gl::TexLevelArray<TextureRef>::iterator begin() { return mTexLevels.begin(); }
    gl::TexLevelArray<TextureRef>::const_iterator begin() const { return mTexLevels.begin(); }
    gl::TexLevelArray<TextureRef>::iterator end() { return mTexLevels.end(); }
    gl::TexLevelArray<TextureRef>::const_iterator end() const { return mTexLevels.end(); }

  private:
    gl::TexLevelArray<TextureRef> mTexLevels;
};

}  // namespace mtl
}  // namespace rx

#endif /* LIBANGLE_RENDERER_METAL_MTL_RESOURCES_H_ */


text:
package org.deidentifier.arx.kettle.risk;

import java.util.Arrays;

import org.deidentifier.arx.ARXPopulationModel;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.resources.Resources;
import org.deidentifier.arx.kettle.common.SWTUtil;
import org.deidentifier.arx.risk.RiskEstimateBuilder;
import org.deidentifier.arx.risk.RiskModelSampleRiskDistribution;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.swtchart.Chart;
import org.swtchart.IAxis;
import org.swtchart.IAxisSet;
import org.swtchart.ILineSeries;
import org.swtchart.ISeriesSet;
import org.swtchart.ITitle;
import org.swtchart.Range;
import org.swtchart.ILineSeries.PlotSymbolType;
import org.swtchart.ISeries.SeriesType;

/**
 * Generates the View of the Risk Distribution Table
 * @author Florian Wiedner
 * @category Risk
 * @since 1.7
 * @version 1.0
 *
 */
public class ViewRisksDistributionPlot {

	/** Minimal width of a category label. */
    private static final int MIN_CATEGORY_WIDTH = 10;
	/** View */
    private Composite root;

    /** View */
    private Chart            chart;
    /**
     * The DataHandle from the Input or Output
     */
    private DataHandle data;
    /**
     * The ARXPopulationModel used in the Output
     */
    private ARXPopulationModel population;

    /**
     * Generates the new View of the Risk Distribution Table
     * @param parent The Parent Composite
     * @param data The DataHandle from the input or the result
     * @param population The ARXPopulationModel used in this case
     */
	public ViewRisksDistributionPlot(final Composite parent,DataHandle data,ARXPopulationModel population) {
		this.data=data;
		this.population=population;
		this.build(parent);
	}

	/**
	 * Generates the View of the Distribution Plot
	 * @param parent The Composite Parent
	 */
	private void build(Composite parent){
		this.root = new Composite(parent, SWT.NONE);
        this.root.setLayout(new FillLayout());
        this.root.setLayoutData(SWTUtil.createFillGridDataBoth());

        chart = new Chart(root, SWT.NONE);
        chart.setOrientation(SWT.HORIZONTAL);

        // Show/Hide axis
        chart.addControlListener(new ControlAdapter(){
            @Override
            public void controlResized(ControlEvent arg0) {
                updateCategories();
            }
        });

        // Update font
        FontData[] fd = chart.getFont().getFontData();
        fd[0].setHeight(8);
        final Font font = new Font(chart.getDisplay(), fd[0]);
        chart.setFont(font);
        chart.addDisposeListener(new DisposeListener(){
            public void widgetDisposed(DisposeEvent arg0) {
                if (font != null && !font.isDisposed()) {
                    font.dispose();
                }
            }
        });

        // Update title
        ITitle graphTitle = chart.getTitle();
        graphTitle.setText(""); //$NON-NLS-1$
        graphTitle.setFont(chart.getFont());

        // Set colors
        chart.setBackground(root.getBackground());
        chart.setForeground(root.getForeground());

        // OSX workaround
        if (System.getProperty("os.name").toLowerCase().contains("mac")){ //$NON-NLS-1$ //$NON-NLS-2$
            int r = chart.getBackground().getRed()-13;
            int g = chart.getBackground().getGreen()-13;
            int b = chart.getBackground().getBlue()-13;
            r = r>0 ? r : 0;
            r = g>0 ? g : 0;
            r = b>0 ? b : 0;
            final Color background = new Color(chart.getDisplay(), r, g, b);
            chart.setBackground(background);
            chart.addDisposeListener(new DisposeListener(){
                public void widgetDisposed(DisposeEvent arg0) {
                    if (background != null && !background.isDisposed()) {
                        background.dispose();
                    }
                }
            });
        }

        // Initialize axes
        IAxisSet axisSet = chart.getAxisSet();
        IAxis yAxis = axisSet.getYAxis(0);
        IAxis xAxis = axisSet.getXAxis(0);
        ITitle xAxisTitle = xAxis.getTitle();
        xAxisTitle.setText(""); //$NON-NLS-1$
        xAxis.getTitle().setFont(chart.getFont());
        yAxis.getTitle().setFont(chart.getFont());
        xAxis.getTick().setFont(chart.getFont());
        yAxis.getTick().setFont(chart.getFont());
        xAxis.getTick().setForeground(chart.getForeground());
        yAxis.getTick().setForeground(chart.getForeground());
        xAxis.getTitle().setForeground(chart.getForeground());
        yAxis.getTitle().setForeground(chart.getForeground());

        // Initialize axes
        ITitle yAxisTitle = yAxis.getTitle();
        yAxisTitle.setText(Resources.getMessage("ViewRisksClassDistributionPlot.0")); //$NON-NLS-1$
        xAxisTitle.setText(Resources.getMessage("ViewRisksClassDistributionPlot.1")); //$NON-NLS-1$
        chart.setEnabled(false);
        updateCategories();
     // Enable/disable
        Thread getData=new Thread(new Runnable(){

			@Override
			public void run() {
				final RiskEstimateBuilder builder;
		        builder=data.getRiskEstimator(population);
		        if(builder!=null){
		        	 double[] frequencies;
		             double[] cumulative;
		             double[] threshold;
		             String[] labels;
		             double   max     = 0d;
		             // Perform work
		             RiskModelSampleRiskDistribution model = builder.getSampleBasedRiskDistribution();

		             // Create array
		             frequencies = model.getFractionOfRecordsForRiskThresholds();
		             cumulative = model.getFractionOfRecordsForCumulativeRiskThresholds();
		             threshold = new double[frequencies.length];
		             double enforced = model.getRiskThreshold();
		             labels = new String[frequencies.length];
		             max = 0d;
		             for (int i = 0; i < frequencies.length; i++) {
		                 frequencies[i] *= 100d;
		                 cumulative[i] *= 100d;
		                 if (enforced != 1d && enforced <= model.getAvailableRiskThresholds()[i]) {
		                     threshold[i] = 100d;
		                 }
		                 max = Math.max(max, frequencies[i]);
		                 max = Math.max(max, cumulative[i]);
		                 labels[i] = String.valueOf(SWTUtil.getPrettyString(model.getAvailableRiskThresholds()[i] * 100d));
		             }
		             labels[0] = "<=" + SWTUtil.getPrettyString(1e-6); //$NON-NLS-1$

		             frequencies = insertToBack(frequencies, frequencies[frequencies.length-1]);
		             cumulative = insertToBack(cumulative, cumulative[cumulative.length-1]);
		             threshold = insertToBack(threshold, threshold[threshold.length-1]);
		             labels = insertToBack(labels, "");

		          // Update chart
		             chart.setRedraw(false);

		             ISeriesSet seriesSet = chart.getSeriesSet();

		             ILineSeries series1 = (ILineSeries) seriesSet.createSeries(SeriesType.LINE, Resources.getMessage("ViewRisksClassDistributionPlot.3")); //$NON-NLS-1$
		             series1.getLabel().setVisible(false);
		             series1.getLabel().setFont(chart.getFont());
		             series1.setLineColor(Display.getDefault().getSystemColor(SWT.COLOR_RED));
		             series1.setYSeries(cumulative);
		             series1.setAntialias(SWT.ON);
		             series1.setSymbolType(PlotSymbolType.NONE);
		             series1.enableStep(true);
		             series1.enableArea(true);

		             ILineSeries series2 = (ILineSeries) seriesSet.createSeries(SeriesType.LINE, Resources.getMessage("ViewRisksClassDistributionPlot.2")); //$NON-NLS-1$
		             series2.getLabel().setVisible(false);
		             series2.getLabel().setFont(chart.getFont());
		             series2.setLineColor(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
		             series2.setYSeries(frequencies);
		             series2.setSymbolType(PlotSymbolType.NONE);
		             series2.enableStep(true);
		             series2.enableArea(true);

		             ILineSeries series3 = (ILineSeries) seriesSet.createSeries(SeriesType.LINE, Resources.getMessage("ViewRisksClassDistributionPlot.4")); //$NON-NLS-1$
		             series3.getLabel().setVisible(false);
		             series3.getLabel().setFont(chart.getFont());
		             series3.setLineColor(Display.getDefault().getSystemColor(SWT.COLOR_BLACK));
		             series3.setYSeries(threshold);
		             series3.setAntialias(SWT.ON);
		             series3.setSymbolColor(Display.getDefault().getSystemColor(SWT.COLOR_BLACK));
		             series3.setSymbolType(PlotSymbolType.NONE);
		             series3.enableStep(true);
		             series3.enableArea(true);

		             seriesSet.bringToFront(Resources.getMessage("ViewRisksClassDistributionPlot.2")); //$NON-NLS-1$
		             seriesSet.bringToFront(Resources.getMessage("ViewRisksClassDistributionPlot.4")); //$NON-NLS-1$

		             chart.getLegend().setVisible(true);
		             chart.getLegend().setPosition(SWT.TOP);

		             IAxisSet axisSetI = chart.getAxisSet();

		             IAxis yAxisI = axisSetI.getYAxis(0);
		             yAxisI.setRange(new Range(0d, max));

		             IAxis xAxisI = axisSetI.getXAxis(0);
		             xAxisI.setCategorySeries(labels);
		             xAxisI.adjustRange();
		             updateCategories();

		             chart.updateLayout();
		             chart.update();
		             chart.setRedraw(true);

		        }
			}

        });
        getData.run();
	}

	 /**
     * Makes the chart show category labels or not.
     */
    private void updateCategories(){
        if (chart != null){
            IAxisSet axisSet = chart.getAxisSet();
            if (axisSet != null) {
                IAxis xAxis = axisSet.getXAxis(0);
                if (xAxis != null) {
                    String[] series = xAxis.getCategorySeries();
                    if (series != null) {
                        boolean enoughSpace = chart.getPlotArea().getSize().x / series.length >= MIN_CATEGORY_WIDTH;
                        xAxis.enableCategory(enoughSpace);
                        xAxis.getTick().setVisible(enoughSpace);
                    }
                }
            }
        }
    }

    /**
     * Insert to front
     * @param array
     * @param value
     * @return
     */
    private double[] insertToBack(double[] array, double value) {
        double[] result = Arrays.copyOf(array, array.length + 1);
        result[result.length-1] = value;
        return result;
    }

    /**
     * Insert to front
     * @param array
     * @param value
     * @return
     */
    private String[] insertToBack(String[] array, String value) {
        String[] result = Arrays.copyOf(array, array.length + 1);
        result[result.length-1] = value;
        return result;
    }

}