text:
import utils from '../utils'
import { Vector2, Vector3 } from 'three'

/**
 * Calculate min & max radius of a sphere slice between zMin & zMax
 *
 * @param {Vector3} center - center of the sphere
 * @param {number} radius  - sphere radius
 * @param {number} zMin - lower bound of the slice
 * @param {number} zMax - upper bound of the slice
 */
function _getSphereSliceRadiusRange(center, radius, zMin, zMax) {
  const dzMin = zMin - center.z
  const dzMax = zMax - center.z
  const rzMin = Math.sqrt(Math.max(radius * radius - dzMin * dzMin, 0.0))
  const rzMax = Math.sqrt(Math.max(radius * radius - dzMax * dzMax, 0.0))

  const rMin = Math.min(rzMin, rzMax)
  let rMax

  if (zMin <= center.z && zMax >= center.z) {
    // sphere's main diameter is inside slice
    rMax = radius
  } else {
    rMax = Math.max(rzMin, rzMax)
  }

  return [rMin, rMax]
}

/**
 * Calculate min & max radius of a circle slice between yMin & yMax.
 *
 * To maintain analogy with _getSphereSliceRadiusRange we call radius what in fact is
 * half-width (along X axis) of the slice, i.e. 1D-sphere radius.
 *
 * @param {Vector3} center - center of the circle (z can be ignored)
 * @param {number} radius  - circle radius
 * @param {number} yMin - lower bound of the slice
 * @param {number} yMax - upper bound of the slice
 * @returns {Array} - array of two numbers (min & max radius, or half-width)
 */
function _getCircleSliceRadiusRange(center, radius, yMin, yMax) {
  const dyMin = yMin - center.y
  const dyMax = yMax - center.y
  const ryMin = Math.sqrt(Math.max(radius * radius - dyMin * dyMin, 0.0))
  const ryMax = Math.sqrt(Math.max(radius * radius - dyMax * dyMax, 0.0))

  const rMin = Math.min(ryMin, ryMax)
  let rMax

  if (yMin <= center.y && yMax >= center.y) {
    // slice's main diameter is inside slice
    rMax = radius
  } else {
    rMax = Math.max(ryMin, ryMax)
  }

  return [rMin, rMax]
}

/**
 * VoxelWorld constructor
 *
 * @param {Box3} box - bounding box of the volume to be partitioned
 * @param {Vector3} vCellSizeHint - target voxel size (actual voxel size may differ from this)
 */
class VoxelWorld {
  constructor(box, vCellSizeHint) {
    this._box = box.clone()
    const size = new Vector3()
    box.getSize(size)
    this._count = size
      .clone()
      .divide(vCellSizeHint)
      .floor()
      .max(new Vector3(1, 1, 1))
    this._last = this._count.clone().subScalar(1)
    this._cellSize = size.clone().divide(this._count)
    this._cellInnerR =
      0.5 *
      Math.min(Math.min(this._cellSize.x, this._cellSize.y), this._cellSize.z)
    this._cellOuterR = 0.5 * Math.sqrt(this._cellSize.dot(this._cellSize))

    // array of voxels, each element contains index of first atom in voxel
    const numVoxels = this._count.x * this._count.y * this._count.z
    this._voxels = utils.allocateTyped(Int32Array, numVoxels)
    for (let i = 0; i < numVoxels; ++i) {
      this._voxels[i] = -1
    }

    // array of atoms that stores multiple single-linked lists
    // two elements for each atom: Atom ref, index of next atom (in this array
    this._atoms = []
  }

  /**
   * Add all atoms from a complex to voxel world
   *
   * @param {Complex} complex - complex
   */
  addAtoms(complex) {
    const self = this

    let idx = this._atoms.length

    // resize array of atoms
    this._atoms.length += 2 * complex.getAtomCount()

    complex.forEachAtom((atom) => {
      // find which voxel contains this atom
      const voxelIdx = self._findVoxel(atom.position)

      // push current atom to the head of voxel's atom list
      self._atoms[idx] = atom
      self._atoms[idx + 1] = self._voxels[voxelIdx]
      self._voxels[voxelIdx] = idx

      idx += 2
    })
  }

  /**
   * Get voxel that contains specified 3D point (we use clamp at the edges)
   *
   * @param {Vector3} point - a point in 3D
   * @returns {number} - index of voxel
   */
  static _zero = new Vector3(0, 0, 0)

  static _voxel = new Vector3()

  _findVoxel(point) {
    const zero = VoxelWorld._zero
    const voxel = VoxelWorld._voxel
    voxel
      .copy(point)
      .sub(this._box.min)
      .divide(this._cellSize)
      .floor()
      .clamp(zero, this._last)
    return voxel.x + this._count.x * (voxel.y + this._count.y * voxel.z)
  }

  /**
   * Call a function for each atom in voxel
   *
   * @param {number} voxel - index of voxel
   * @param {function(Atom)} process - function to call
   */
  _forEachAtomInVoxel(voxel, process) {
    for (let i = this._voxels[voxel]; i >= 0; i = this._atoms[i + 1]) {
      process(this._atoms[i])
    }
  }

  /**
   * Call a function for each voxel that is touched by given sphere. Callback also takes flag
   * isInside specifying whether voxel lies inside the sphere entirely.
   *
   * @param {Vector3} center - center of the sphere
   * @param {number} radius  - sphere radius
   * @param {function(number,bool)} process - function to call that takes voxel index and boolean isInside
   */

  static _xRange = new Vector2()

  static _yRange = new Vector2()

  static _zRange = new Vector2()

  _forEachVoxelWithinRadius(center, radius, process) {
    const xRange = VoxelWorld._xRange
    const yRange = VoxelWorld._yRange
    const zRange = VoxelWorld._zRange

    // switch to a faster method unless cell size is much smaller than sphere radius
    if (radius / this._cellInnerR < 10) {
      this._forEachVoxelWithinRadiusSimple(center, radius, process)
      return
    }

    let rRangeXY
    let rRangeX
    let xVal
    let yVal
    let zVal
    let isInsideX
    let isInsideY
    let isInsideZ

    zRange.set(center.z - radius, center.z + radius)
    zRange
      .subScalar(this._box.min.z)
      .divideScalar(this._cellSize.z)
      .floor()
      .clampScalar(0, this._count.z - 1)

    for (let z = zRange.x; z <= zRange.y; ++z) {
      zVal = [
        this._box.min.z + z * this._cellSize.z,
        this._box.min.z + (z + 1) * this._cellSize.z
      ]

      isInsideZ = center.z - radius <= zVal[0] && zVal[1] <= center.z + radius

      rRangeXY = _getSphereSliceRadiusRange(center, radius, zVal[0], zVal[1])

      yRange.set(center.y - rRangeXY[1], center.y + rRangeXY[1])
      yRange
        .subScalar(this._box.min.y)
        .divideScalar(this._cellSize.y)
        .floor()
        .clampScalar(0, this._count.y - 1)

      for (let y = yRange.x; y <= yRange.y; ++y) {
        yVal = [
          this._box.min.y + y * this._cellSize.y,
          this._box.min.y + (y + 1) * this._cellSize.y
        ]

        isInsideY =
          center.y - rRangeXY[0] <= yVal[0] && yVal[1] <= center.y + rRangeXY[0]

        rRangeX = _getCircleSliceRadiusRange(
          center,
          rRangeXY[1],
          yVal[0],
          yVal[1]
        )

        xRange.set(center.x - rRangeX[1], center.x + rRangeX[1])
        xRange
          .subScalar(this._box.min.x)
          .divideScalar(this._cellSize.x)
          .floor()
          .clampScalar(0, this._count.x - 1)

        for (let { x } = xRange; x <= xRange.y; ++x) {
          xVal = [
            this._box.min.x + x * this._cellSize.x,
            this._box.min.x + (x + 1) * this._cellSize.x
          ]
          isInsideX =
            center.x - rRangeX[0] <= xVal[0] && xVal[1] <= center.x + rRangeX[0]

          process(
            x + this._count.x * (y + this._count.y * z),
            isInsideX && isInsideY && isInsideZ
          )
        }
      }
    }
  }

  /**
   * Call a function for each voxel that is touched by given sphere. Callback also takes flag
   * isInside specifying whether voxel lies inside the sphere entirely.
   * This is a version of method that doesn't try to "calculate" what voxels fall inside radius
   * but instead just checks all voxels inside sphere's bounding box. This should be faster
   * unless cell size is much smaller than sphere radius.
   *
   * @param {Vector3} center - center of the sphere
   * @param {number} radius  - sphere radius
   * @param {function(number,bool)} process - function to call that takes voxel index and boolean isInside
   */

  static _vCenter = new Vector3()

  _forEachVoxelWithinRadiusSimple(center, radius, process) {
    const xRange = VoxelWorld._xRange
    const yRange = VoxelWorld._yRange
    const zRange = VoxelWorld._zRange
    const vCenter = VoxelWorld._vCenter

    const distTouch2 = (radius + this._cellOuterR) * (radius + this._cellOuterR)
    let distInside2 = -1.0
    if (radius > this._cellOuterR) {
      distInside2 = (radius - this._cellOuterR) * (radius - this._cellOuterR)
    }

    // calculate bounding box for the sphere
    xRange.set(center.x - radius, center.x + radius)
    xRange.subScalar(this._box.min.x).divideScalar(this._cellSize.x).floor()
    xRange.x = Math.min(Math.max(xRange.x, 0), this._count.x - 1)
    xRange.y = Math.min(Math.max(xRange.y, 0), this._count.x - 1)

    yRange.set(center.y - radius, center.y + radius)
    yRange.subScalar(this._box.min.y).divideScalar(this._cellSize.y).floor()
    yRange.x = Math.min(Math.max(yRange.x, 0), this._count.y - 1)
    yRange.y = Math.min(Math.max(yRange.y, 0), this._count.y - 1)

    zRange.set(center.z - radius, center.z + radius)
    zRange.subScalar(this._box.min.z).divideScalar(this._cellSize.z).floor()
    zRange.x = Math.min(Math.max(zRange.x, 0), this._count.z - 1)
    zRange.y = Math.min(Math.max(zRange.y, 0), this._count.z - 1)

    for (let z = zRange.x; z <= zRange.y; ++z) {
      const zVal = [
        this._box.min.z + z * this._cellSize.z,
        this._box.min.z + (z + 1) * this._cellSize.z
      ]
      vCenter.z = 0.5 * (zVal[0] + zVal[1])

      for (let y = yRange.x; y <= yRange.y; ++y) {
        const yVal = [
          this._box.min.y + y * this._cellSize.y,
          this._box.min.y + (y + 1) * this._cellSize.y
        ]
        vCenter.y = 0.5 * (yVal[0] + yVal[1])

        for (let { x } = xRange; x <= xRange.y; ++x) {
          const xVal = [
            this._box.min.x + x * this._cellSize.x,
            this._box.min.x + (x + 1) * this._cellSize.x
          ]
          vCenter.x = 0.5 * (xVal[0] + xVal[1])

          const d2 = center.distanceToSquared(vCenter)
          if (d2 <= distTouch2) {
            process(
              x + this._count.x * (y + this._count.y * z),
              d2 <= distInside2
            )
          }
        }
      }
    }
  }

  /**
   * Call a function for each atom within given sphere
   *
   * @param {Vector3} center - center of the sphere
   * @param {number} radius  - sphere radius
   * @param {function(Atom)} process - function to call
   */
  forEachAtomWithinRadius(center, radius, process) {
    const self = this
    const r2 = radius * radius

    self._forEachVoxelWithinRadius(center, radius, (voxel, isInside) => {
      if (isInside) {
        self._forEachAtomInVoxel(voxel, process)
      } else {
        self._forEachAtomInVoxel(voxel, (atom) => {
          if (center.distanceToSquared(atom.position) <= r2) {
            process(atom)
          }
        })
      }
    })
  }

  /**
   * Call a function for each atom of given complex within given distance from group of atoms defined by mask
   *
   * @param {Complex} complex - complex
   * @param {number} mask - bit mask
   * @param {number} dist - distance
   * @param {function(Atom)} process - function to call
   */
  forEachAtomWithinDistFromMasked(complex, mask, dist, process) {
    this._forEachAtomWithinDistFromGroup(
      (atomProc) => {
        complex.forEachAtom((atom) => {
          if ((atom.mask & mask) !== 0) {
            atomProc(atom)
          }
        })
      },
      dist,
      process
    )
  }

  /**
   * Call a function for each atom of given complex within given distance from group of atoms defined by selector
   *
   * @param {Complex} complex - complex
   * @param {number} selector - selector
   * @param {number} dist - distance
   * @param {function(Atom)} process - function to call
   */
  forEachAtomWithinDistFromSelected(complex, selector, dist, process) {
    this._forEachAtomWithinDistFromGroup(
      (atomProc) => {
        complex.forEachAtom((atom) => {
          if (selector.includesAtom(atom)) {
            atomProc(atom)
          }
        })
      },
      dist,
      process
    )
  }

  /**
   * Call a function for each atom of given complex within given distance from group of atoms
   *
   * @param {function} forEachAtom - enumerator of atoms in the group
   * @param {number} dist - distance
   * @param {function(Atom)} process - function to call
   */
  _forEachAtomWithinDistFromGroup(forEachAtom, dist, process) {
    const self = this
    const r2 = dist * dist

    const voxels = []
    const atoms = []
    let idx = 0

    // build "within radius" atom list for each voxel
    forEachAtom((atom) => {
      self._forEachVoxelWithinRadius(atom.position, dist, (voxel, isInside) => {
        if (isInside) {
          // this voxel is inside circle -- no check will be required
          voxels[voxel] = -1
        } else if (typeof voxels[voxel] === 'undefined') {
          // this voxel isn't covered yet -- start building list of atoms
          atoms.push(atom)
          atoms.push(-1)
          voxels[voxel] = idx
          idx += 2
        } else if (voxels[voxel] !== -1) {
          // this voxel has a list of atoms required for distance check -- add atom to the list
          atoms.push(atom)
          atoms.push(voxels[voxel])
          voxels[voxel] = idx
          idx += 2
        }
      })
    })

    let voxel

    const processIfWithin = function (atom) {
      if (typeof voxels[voxel] === 'undefined') {
        return
      }

      idx = voxels[voxel]
      if (idx === -1) {
        // this voxel is fully covered
        process(atom)
        return
      }

      // check distance to each atom within radius from this voxel
      for (; idx >= 0; idx = atoms[idx + 1]) {
        if (atom.position.distanceToSquared(atoms[idx].position) < r2) {
          process(atom)
          break
        }
      }
    }

    // for each marked voxel
    for (voxel in voxels) {
      if (Object.hasOwn(voxels, voxel)) {
        self._forEachAtomInVoxel(voxel, processIfWithin)
      }
    }
  }
}

export default VoxelWorld


text:
title: Wavefront REST API
keywords: getting started
tags: [getting started]
sidebar: doc_sidebar
permalink: wavefront_api.html
summary: Learn about the REST API for managing Tanzu Observability by Wavefront.
---

The Wavefront REST API enables you to write scripts to perform management tasks, such as defining alerts and creating events. You can use the REST API to perform any task that is supported by the Tanzu Observability GUI. The REST API is based on Swagger, so you can generate the API client of your choice (including a CLI client).

## REST API Overview

All interactions between the UI and your Wavefront instance occur through the Wavefront API. You can perform those actions using REST - or you can create an API client using Swagger, discussed below.

The current version of the REST API is v2. You can access the API at `<your_instance>/api/v2`. The v1 API (`<your_instance>/api/`) was deprecated in 2017 and is no longer supported.

{% include note.html content="The Wavefront REST API is not the same as the `/api` endpoint that you specify for the Wavefront proxy."%}

## API Documentation (Wavefront Instance)

Each Wavefront instance includes Swagger-generated documentation for the REST API. In our blog post [Did You Know that Our API Docs Are Alive](https://tanzu.vmware.com/content/vmware-tanzu-observability-blog/did-you-know-that-our-api-docs-are-alive) we explain how you can experiment with our API directly from this in-product documentation.

To access the REST API documentation :

1. Log in to your Wavefront instance.
2. Display the doc from the UI or using a URL:
  * In the UI, click the gear icon  at the top right of the toolbar and select **API Documentation**.
  * Type `https://<your_instance>.com/api-docs/ui/`

![REST API in a Wavefront instance](/images/rest_api.png)

## API Documentation (VMware code)

If you don't have access to a Wavefront instance, you can have a look at our API doc [on the VMware code site](https://code.vmware.com/apis/714/wavefront-rest).

We include an overview and a Swagger-generated API Reference. We update the reference with each release.

![REST API in VMware code](/images/vmware_code_api.png)

The [VMware code website](https://code.vmware.com/samples?categories=Sample&tags=wavefront) also includes some samples, for example, for getting data into Tanzu Observability. We're providing these samples as is - some are from our team, others will come from the community.

## Managing API Tokens

Before you can invoke the Wavefront API using `curl` or from an API client, you must have an API token.

An API token is a string of hexadecimal characters and dashes. For example:

```
a411c16b-3cf7-4f03-bf11-8ca05aab898d
```
Tanzu Observability by Wavefront allows [user accounts](user-accounts.html) and [service accounts](service-accounts.html) to use the [Wavefront REST API](wavefront_api.html).

{% include tip.html content="You generate API tokens for your user account explicitly. For service accounts, a user with the **Accounts** permission can generate tokens from the **Service Accounts** page." %}

### Generate and Manage the API Tokens for Your User Account

{% include note.html content="All users can use and manage their existing API tokens. You must have the [API Tokens permission](permissions_overview.html) to generate new API tokens for your user account." %}

1. Log in to your Wavefront instance.
2. Click the gear icon   at the top right of the toolbar and select your user name.
2. On the **API Access** tab, click **Generate**.

    You can have up to 20 tokens at any given time. If you want to generate a new token but already have 20 tokens, then you must revoke one of the existing tokens.
3. To revoke a token, click the **Revoke** button for the token.

    If you run a script that uses a revoked token, the script returns an authorization error.
4. To add a name or rename an API token, click the **Edit** icon for the token, enter the name, and press Enter.

![Generate API Token](/images/generate_token.png)

{% include warning.html content="Do not share your API token with anyone. The token provides full access to the API. Accounts that have the token can authenticate without a username/password."%}

### Generate and Manage the API Tokens for a Service Account

As a user with the **Accounts** permission, you can generate API tokens for [service accounts](service-accounts.html) upon creation or at a later stage. To generate an API token for an existing **service account**:

1. Log in to your Wavefront instance as a user with the **Accounts** permission.
2. Click the gear icon  at the top right of the toolbar and select **Accounts**.
3. On the **Service Accounts** tab, click the ellipsis icon next to the service account for which you want to generate an API token, and select **Edit**.
4. To generate a new token, in the Tokens section, click **Generate**.

    You can have up to 20 tokens per service account at any given time. If you want to generate a new token but already have 20 tokens, then you must revoke one of the existing tokens.
5. To revoke a token, click the **Revoke** button for the token.

    Revoking a token cannot be undone.
5. To rename an API token, click the **Edit** icon for the token, enter the name, and press Enter.
6. Select the appropriate permissions for the service account and click **Update**.

### View and Manage the API Tokens in Your Organization

As a user with the **Accounts** permission, you can view and revoke the API token of any user or service account in your organization.

1. Log in to your Wavefront instance as a user with the **Accounts** permission.
2. Click the gear icon   at the top right of the toolbar and select **Accounts**.
3. Click the **API Tokens** tab.

  You see the API tokens for all user and service accounts in a paginated table format.

![The API Tokens page shows the tokens table, the search field above the table, and the preconfigured filters and the saved searches in the left panel](/images/API_tokens.png)

{% include important.html content="Revoking a token cannot be undone. Any script that uses a revoked token returns an authorization error." %}

On the API Tokens page, you can:
- Sort the API tokens table by column.
- Search and, optionally, save and share your search.
- Filter the API tokens by account type, usage, particular accounts, or your saved search.
- Revoke an API token from the vertical ellipsis icon for the token.

## Invoking the API

You can invoke the Wavefront API using `curl` or from an API client. In either case, you must use an API token. See [Use the Wavefront REST API](using_wavefront_api.html) for details and examples.

## Generate an API Client Using Swagger

Because we expose the Wavefront REST API via Swagger, you can generate a working implementation of the API for the programming language or CLI you want to use.

{% include note.html content="Using the default Swagger configuration settings might result in errors. Create your own configuration file instead."%}

Here's an example for generating a Java client:

1. Create a file `swagger-config.json`. Here's an example:
```
{
"modelPackage": "com.wavefront.rest.models",
"apiPackage": "com.wavefront.rest.api.client",
"groupId": "com.wavefront.rest.api.client",
"artifactId": "wavefront-java-sdk",
"artifactVersion": "19.10",
"sourceFolder": "src/main/java",
"java8": true,
"dateLibrary": "java8"
}
```
2. Generate the client, for example:

`swagger-codegen generate -i https://mydomain.wavefront.com/api/v2/swagger.json -c swagger-config.json -l java`

## Wavefront REST API Categories

The REST API supports the following objects corresponding to different categories of management tasks:

- **Access Policy** - Lets you allow or deny access to embedded charts. For information, see [Allow or Deny Access to Embedded Charts](ui_sharing.html#allow-or-deny-access-to-embedded-charts).
- **Access** - Provides information on the access level of an entity. See [Notes on the Access Category](#access) below.
- **Account (User and Service Account)** - Allows users with [**Accounts** permission](permissions_overview.html) to retrieve a list of all [accounts](users_roles.html), create, update, and delete accounts and manage permissions and groups associated with accounts.
- **Alert** - Retrieve active, snoozed, in-maintenance, and invalid alerts. Users with [**Alerts** permission](permissions_overview.html) can create and update alerts.
- **ApiToken** - Allows users with [**Accounts** permission](permissions_overview.html) to retrieve, create, and manage API tokens. Used primarily in conjunction with service accounts.
- **Cloud Integration** - Retrieve cloud integration data types such as those available with the [AWS integration](integrations_aws_metrics.html). Users with [**Proxies** permission](permissions_overview.html) can add and remove cloud integration data types.
- **Dashboard** - Retrieve data about dashboards, list dashboards, and return version history. Users with [**Dashboards** permission](permissions_overview.html) can save, create, delete, clone, undelete dashboards.
- **Derived Metric** - Manage derived metrics.
- **Direct Ingestion** - Perform [direct ingestion](direct_ingestion.html) instead of using a proxy.
- **Event** - Retrieve events and tags associated with a specific event. Users with [**Events** permission](permissions_overview.html) can create, update, and delete events. Deleting events is limited to non-system events. System events include events based on alert firings, error events, and maintenance windows.
- **External Link** - Navigate external links. Users with [**External Links** permission](permissions_overview.html) can create, update, and delete external links.
- **Integration** - Retrieve integrations. Users with [**Integrations** permission](permissions_overview.html) can install and uninstall integration dashboards.
- **Maintenance Window** - Retrieve a complete or filtered list of existing maintenance windows. Users with [**Alerts** permission](permissions_overview.html) can create, close, update, and delete maintenance windows.
- **Message** - Retrieve messages and mark messages read.
- **Metric** - Retrieve details on a metric.
- **Notificant** - Allows users with Users with [**Alerts** permission](permissions_overview.html) to create, delete, update, or test alert notification targets.
- **Proxy** - Retrieve information about Wavefront proxies. Users with [**Proxies** permission](permissions_overview.html) can add and remove Wavefront proxies.
- **Query** - Perform queries.
- **Role** - Retrieve information about a role and manage roles and role assignees.
- **Saved Search** - Retrieve, add, and remove saved searches.
- **Search** - Search agents, alerts, integrations, dashboards, external links, maintenance windows, sources, and webhook alert targets.
- **Source** - Retrieve sources and tags associated with a source. Users with [**Source Tags** permission](permissions_overview.html) can add and remove source tags and set descriptions.
- **Usage** - Retrieve information about usage associated with ingestion policies and manage policies.
- **User** - Deprecated API. Use **Account (User and Service Account)** instead.
- **UserGroup** - Allows users with [**Accounts** permission](permissions_overview.html) to retrieve a list of all groups, create, update, and delete groups, and manage the users and roles associated with a group.
- **Webhook** - Retrieve webhooks. Users with [**Alerts** permission](permissions_overview.html) can create, update, and delete webhooks.

### Notes on the Access Category

The `/api/access/{entity}` endpoint provides information on how often an entity has been accessed.  Supported entities are metric, histogram, span.

{% include important.html content="In order to use this API, users must have both the Direct Data Ingestion and Metrics [permissions](permissions_overview.html)."%}

{% include note.html content="Tanzu Observability by Wavefront uses a bloom filter to determine the access pattern. As a result, even if data access returns true, there's a very low probability that data actually hasn't been accessed. If data access returns false, it is guaranteed that the data has not been accessed.
"%}

This GET endpoint has the following parameters:

Parameter	Description

name
Entity name,  e.g, cpu.usage (for a metric).

hostPrefix
Prefix of the host name, e.g. you can use test-2a-app67 if the whole host name is test-2a-app67-id-12345

Warning:hostPrefix must be somewhat specific. There's a limit on how many hosts Tanzu Observability scans.

usageThresholdDays
How many days to look back. 7 days by default.

includeDailyDetail
Whether to provide additional data on daily usage. False by default.

If includeDailyDetail is false, GET returns true if the data has been accessed in the past usageThresholdDays, and false otherwise.

If includeDailyDetail is true, GET returns daily access details.

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace BoringDotNet.Random
{
    // ReSharper disable InconsistentNaming
    public static class IRandomSourceExtensions
    // ReSharper restore InconsistentNaming
    {
        /// <summary>
        /// Get a random integer between <para>minValue</para> (inclusive) and <para>maxValue</para> (exclusive).
        /// </summary>
        public static int NextInt(this IRandomSource random, int minValue, int maxValue)
        {
            double doubleResult = random.Next();
            double candidate = minValue + (doubleResult * (maxValue - minValue)) - 0.5;
            double rounded = Math.Round(candidate, 0, MidpointRounding.AwayFromZero);
            return (int)Math.Min(Math.Max(rounded, minValue), maxValue);
        }

        public static string NextString(this IRandomSource random, string validCharacters, int length)
        {
            if (validCharacters == null)
                throw new ArgumentNullException("validCharacters");
            if (validCharacters.Length == 0)
                throw new ArgumentException("validCharacters must constain at least one character", "validCharacters");
            if (length < 0)
                throw new ArgumentOutOfRangeException("length", length, "length must be >= 0");

            string result = string.Empty;
            for (int i = 0; i < length; i++)
                result += random.NextCharacter(validCharacters);
            return result;
        }

        private static char NextCharacter(this IRandomSource random, string validCharacters)
        {
            var i = random.NextInt(0, validCharacters.Length);
            return validCharacters[i];
        }
    }
}


text:
import assert from 'assert';
import {find} from '../../util';

describe('test/Export/Class:', ()=>{
  it('is exported that default export', () =>{
    const doc = find('longname', 'src/Export/Class.js~TestExportClass1');
    assert.equal(doc.export, true);
  });

  it('is exported that named export', () =>{
    const doc = find('longname', 'src/Export/Class.js~TestExportClass2');
    assert.equal(doc.export, true);
  });

  it('is exported that indirect with declaration', () =>{
    const doc = find('longname', 'src/Export/Class.js~TestExportClass3');
    assert.equal(doc.export, true);
  });

  it('is exported that indirect with expression', () =>{
    const doc = find('longname', 'src/Export/Class.js~TestExportClass4');
    assert.equal(doc.export, true);
  });

  it('is not exported that non export', () =>{
    const doc = find('longname', 'src/Export/Class.js~TestExportClass5');
    assert.equal(doc.export, false);
  });

  it('is exported that multiple named export', ()=>{
    const [doc1, doc2] = find('longname',
      'src/Export/Class.js~TestExportClass6',
      'src/Export/Class.js~TestExportClass7'
    );

    assert.equal(doc1.export, true);
    assert.equal(doc2.export, true);
  });
});


text:
<?php

namespace Numbers\Tenants\Tenants\Form\Activation;
class Modules extends \Object\Form\Wrapper\Base {
	public $form_link = 'tm_module_activation_form';
	public $module_code = 'TM';
	public $title = 'T/M Activation Modules Form';
	public $options = [
		'segment' => [
			'type' => 'primary',
			'header' => [
				'icon' => ['type' => 'cubes'],
				'title' => 'Activate Module:'
			]
		],
		'actions' => [
			'refresh' => true,
			'back' => true,
			'activate_feature' => ['href' => '/Numbers/Tenants/Tenants/Controller/Activation/Features/_Edit?__submit_blank=1', 'value' => 'Activate Feature', 'icon' => 'far fa-file']
		],
		'no_ajax_form_reload' => true
	];
	public $containers = [
		'default' => ['default_row_type' => 'grid', 'order' => 1]
	];
	public $rows = [];
	public $elements = [
		'default' => [
			'tm_module_module_code' => [
				'tm_module_module_code' => ['order' => 1, 'row_order' => 100, 'label_name' => 'Module', 'domain' => 'module_code', 'percent' => 100, 'required' => true, 'method' => 'select', 'options_model' => '\Numbers\Tenants\Tenants\DataSource\Activation\Module\Modules'],
			],
			'tm_module_name' => [
				'tm_module_name' => ['order' => 1, 'row_order' => 200, 'label_name' => 'Name', 'domain' => 'name', 'percent' => 100, 'required' => 'c'],
			],
			self::BUTTONS => [
				self::BUTTON_SUBMIT => self::BUTTON_SUBMIT_DATA
			]
		]
	];

	public function validate(& $form) {
		if (!empty($form->values['tm_module_module_code'])) {
			$modules = \Numbers\Backend\System\Modules\Model\Modules::getStatic();
			if (!empty($modules[$form->values['tm_module_module_code']]['sm_module_multiple']) && empty($form->values['tm_module_name'])) {
				$form->error('danger', \Object\Content\Messages::REQUIRED_FIELD, 'tm_module_name');
			}
		}
	}

	public function save(& $form) {
		$result = \Numbers\Tenants\Tenants\Model\Activation::activateModule($form->values['tm_module_module_code'], $form->values['tm_module_name']);
		if ($result['success']) {
			$form->error('success', 'Module has been activated!');
			return true;
		} else {
			$form->error('danger', $result['error']);
			return false;
		}
	}
}


text:
    #include <boost/proto/transform/detail/preprocessed/construct_pod_funop.hpp>

#elif !defined(BOOST_PP_IS_ITERATING)

    #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
        #pragma wave option(preserve: 2, line: 0, output: "preprocessed/construct_pod_funop.hpp")
    #endif

    ///////////////////////////////////////////////////////////////////////////////
    /// \file construct_pod_funop.hpp
    /// Overloads of construct_\<\>::operator().
    //
    //  Copyright 2008 Eric Niebler. Distributed under the Boost
    //  Software License, Version 1.0. (See accompanying file
    //  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

    #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
        #pragma wave option(preserve: 1)
    #endif

    #define BOOST_PP_ITERATION_PARAMS_1                                                         \
        (3, (1, BOOST_PROTO_MAX_ARITY, <boost/proto/transform/detail/construct_pod_funop.hpp>))
    #include BOOST_PP_ITERATE()

    #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
        #pragma wave option(output: null)
    #endif

#else

    #define N BOOST_PP_ITERATION()

    template<BOOST_PP_ENUM_PARAMS(N, typename A)>
    BOOST_FORCEINLINE
    Type operator ()(BOOST_PP_ENUM_BINARY_PARAMS(N, A, &a)) const
    {
        Type that = {BOOST_PP_ENUM_PARAMS(N, a)};
        return that;
    }

    #undef N

#endif


text:
package info.rmapproject.webapp.service;

import java.net.URI;
import java.util.List;

import info.rmapproject.core.model.RMapTriple;
import info.rmapproject.core.model.request.RMapSearchParams;
import info.rmapproject.core.model.request.ResultBatch;
import info.rmapproject.webapp.domain.Graph;
import info.rmapproject.webapp.domain.PageStatus;
import info.rmapproject.webapp.domain.PaginatorType;
import info.rmapproject.webapp.domain.ResourceDescription;
import info.rmapproject.webapp.service.dto.AgentDTO;
import info.rmapproject.webapp.service.dto.DiSCODTO;
import info.rmapproject.webapp.service.dto.EventDTO;

/**
 * Service to retrieve packages of data to be used in webpage display.
 *
 * @author khanson
 */
public interface DataDisplayService {

	/**
	 * Get DiSCO data package for URI provided. Data package contains elements used on web page views
	 *
	 * @param discoUri the DiSCO URI
	 * @return the DiSCO DTO
	 * @throws Exception the exception
	 */
	public DiSCODTO getDiSCODTO(String sDiscoUri) throws Exception;

	/**
	 * Gets a graph of the DiSCO. If the DiSCO too large it will return null.
	 * @param discoDTO
	 * @return graph representing the DiSCO
	 * @throws Exception
	 */
	public Graph getDiSCOGraph(DiSCODTO discoDTO) throws Exception;

	/**
	 * Gets list of ResourceDescriptions based on DiSCO DTO. This method groups together resource statements based on a matching subject value
	 * and returns a list of ResourceDescription objects. Each ResourceDescription represents a single resource found in the DiSCO.
	 * The list is truncated according to how many data rows can be displayed on a page (per property setting). So it will create ResourceDescriptions
	 * and tally up the statements in them until it runs out of space - this means a ResourceDescription may only show some of the relevant statements
	 * for that resource DiSCO if the cut-off is met mid-list. The offset supports pagination through the data where it cannot fit on one page.
	 *
	 * @param discoDTO the DiSCO DTO object to paginate over
	 * @param offset for large DiSCOs, this will start the list at row number offset.
	 * @return the resource descriptions
	 * @throws Exception the exception
	 */
	public List<ResourceDescription> getDiSCOTableData(DiSCODTO discoDTO, Integer offset) throws Exception;

	/**
	 * Generates an appropriate PageStatus for the DiSCO page. PageStatus is used to pass the relevant pagination values to the webpage
	 * (startPosition, endPosition, hasNext etc)
	 * @param triples - list of triples to paginate over.
	 * @param offset current page offset - the row number to start the list at
	 * @return PageStatus object
	 */
	public PageStatus getDiSCOPageStatus(List<RMapTriple> triples, Integer offset);

	/**
	 * Retrieves a batch of triples for a resource, offsets the list according to offset provided. PaginatorType determines
	 * the number of rows returned from the offset based on the appropriate property, and determines whether or not literals
	 * are included in the results batch
	 * @param resourceUri URI of the resource to retrieve triples for
	 * @param offset Starting point for record batch
	 * @param statusFilter active, inactive or all
	 * @param view PaginatorType either RESOURCE_GRAPH or RESOURCE_TABLE - determines batch size and whether literals are included
	 * @return ResultBatch of triples referencing the resource URI
	 * @throws Exception
	 */
	public ResultBatch<RMapTriple> getResourceBatch(String resourceUri, RMapSearchParams params, PaginatorType view) throws Exception;

	/**
	 * Organizes the batch of triples provided into a Graph object for use in creating the graph visualization.
	 *
	 * @param triplebatch a batch of triples
	 * @return the Resource graph
	 * @throws Exception the exception
	 */
	public Graph getResourceGraph(ResultBatch<RMapTriple> triplebatch, RMapSearchParams params) throws Exception;

	/**
	 * Organizes the batch of triples provided into a ResourceDescription, which is used to display the data in tabular format
	 * for the Resource URI provided. Also retrieves a list of types specified for the resource.
	 * @param resourceUri URI of the resource that is the focus of the triple batch
	 * @param triplebatch batch of triples to be organized as a ResourceDescriptionbatch
	 * @param statusFilter active, inactive or all
	 * @return ResourceDescription
	 * @throws Exception
	 */
	public ResourceDescription getResourceTableData(String resourceUri, ResultBatch<RMapTriple> triplebatch, RMapSearchParams params, boolean bothDirections) throws Exception;

	/**
	 * Organizes the batch of triples provided into a ResourceDescription, which is used to display the data in tabular format
	 * for the Resource URI provided. Also retrieves a list of types specified for the resource. Context URI ensures that the
	 * type list for the resource is limited to the scope of the RMap object. For example, if a DiSCO URI is provided, then only
	 * types defined within that DiSCO will be included in the type list of the ResourceDescription
	 * @param resourceUri URI of the resource that is the focus of the triple batch
	 * @param triplebatch batch of triples to be organized as a ResourceDescription
	 * @param contextUri the object ID for the RMap object, used to filter types to batch
	 * @param statusFilter active, inactive or all
	 * @return ResourceDescription
	 * @throws Exception
	 */
	public ResourceDescription getResourceTableDataInContext(String resourceUri, ResultBatch<RMapTriple> triplebatch, String contextUri, boolean bothDirections) throws Exception;

	/**is
	 * Retrieves a batch of DiSCO URIs that mention the resource URI provided. ResultSet will start at offset provided. Default offset  0.
	 * @param resourceUri URI of resource to get DiSCOs for
	 * @param offset starting point for result batch
	 * @param statusFilter active, inactive or all
	 * @return ResultBatch of DiSCO URIs
	 * @throws Exception
	 */
	public ResultBatch<URI> getResourceRelatedDiSCOs(String resourceUri, RMapSearchParams params) throws Exception;

	/**
	 * Generates an appropriate PageStatus for a result batch. PageStatus is used to pass the relevant pagination values to the webpage
	 * (startPosition, endPosition, hasNext etc). PaginatorType determines the limit on the number of records displayed using the appropriate property
	 * @param results batch of triples or URIs from database
	 * @param paginator type - e.g. RESOURCE_GRAPH
	 * @return PageStatus object
	 */
	public PageStatus getPageStatus(ResultBatch<?> results, PaginatorType pageType);

	/**
	 * Get Agent data package for URI provided. Data package contains elements used on web page views
	 *
	 * @param agentUri the Agent URI
	 * @return the Agent DTO object
	 * @throws Exception the exception
	 */
	public AgentDTO getAgentDTO(String agentUri) throws Exception;

	/**
	 * Get Agent graph based on Agent DTO provided
	 *
	 * @param agentDTO the Agent data package
	 * @return the Agent Graph object
	 * @throws Exception the exception
	 */
	public Graph getAgentGraph(AgentDTO agentDTO) throws Exception;

	/**
	 * Retrieves a batch of URIs for DiSCOs that were created by the Agent provided. Result batch starts at offset. Default offset is 0.
	 * @param agentUri URI of RMap Agent to retrieve DiSCOs for
	 * @param offset starting point of results batch for large sets of results. Default is 0.
	 * @return result batch of URIs
	 * @throws Exception the exception
	 */
	public ResultBatch<URI> getAgentDiSCOs(String agentUri, RMapSearchParams params) throws Exception;

	/**
	 * Get Event data package for URI provided. Data package contains elements used on web page views
	 *
	 * @param eventUri the Event URI
	 * @return the Event DTO
	 * @throws Exception the exception
	 */
	public EventDTO getEventDTO(String eventUri) throws Exception;

	/**
	 * Retrieve batch of triples where the subject is the resourceUri provided and the object (of the triple) is a literal.
	 * This is used in popup node data.
	 * @param resourceUri the resource URI
	 * @param offset Number of rows to offset returned recordset
	 * @param statusFilter active, inactive or all
	 * @return batch of triples where subject is resourceUri and the object is a literal
	 * @throws Exception the exception
	 */
	public ResultBatch<RMapTriple> getResourceLiterals(String resourceUri, RMapSearchParams params) throws Exception;

	/**
	 * Retrieve batch of triples where the subject is the resourceUri provided and the object (of the triple) is a literal.
	 * This is used in popup node data. This version of the method limits the list of literal triples a specific graph URI / context
	 * e.g. only retrieves triples within an Agent, DiSCO or Event.
	 *
	 * @param resourceUri The resource URI
	 * @param graphUri the RMap object URI to filter the data by (e.g. DiSCO URI, Agent URI or Event URI).
	 * @param offset number of rows to offset returned recordset
	 * @return Batch of triples where subject is resourceUri, the object is a literal, filtered by graphUri
	 * @throws Exception the exception
	 */
	public ResultBatch<RMapTriple> getResourceLiteralsInContext(String resourceUri, String graphUri, RMapSearchParams params) throws Exception;

	/**
	 * Retrieve list of RDF types as URIs corresponding to resource URI provided.
	 * @param resourceUri the resource URI
	 * @param status Status to filter label list by
	 * @return list of URIs
	 * @throws Exception
	 */
	public List<URI> getResourceRDFTypes(URI resourceUri, RMapSearchParams params) throws Exception;

	/**
	 * Determine whether the URI provided is an RMap object, or just a regular resource.
	 * If it is an RMap resource return the type name as string.
	 * @param resourceUri the resource URI
	 * @return the RMap type display name
	 * @throws Exception the exception
	 */
	public String getRMapTypeDisplayName(URI resourceUri) throws Exception;

	/**
	 * Calculates a node label for the Resource URI provided.
	 * @param resourceUri the resource URI
	 * @param status Status to filter label list by
	 * @return
	 * @throws Exception
	 */
	public String getResourceLabel(String resourceUri, RMapSearchParams params) throws Exception;

	/**
	 * Checks whether there is such a resource in RMap based on params provided. True if there is a match
	 * @param resource
	 * @param agentUri
	 * @param status
	 * @param dateFrom
	 * @param dateTo
	 * @return true if there is a resource matching string passed, false if not.
	 * @throws Exception
	 */
	public boolean isResourceInRMap(String resource, RMapSearchParams params) throws Exception;

}


text:
package com.alibaba.ttl.integration.vertx3.agent.transformlet;

import com.alibaba.ttl.threadpool.agent.transformlet.helper.AbstractExecutorTtlTransformlet;

import java.util.HashSet;
import java.util.Set;

/**
 * {@link com.alibaba.ttl.threadpool.agent.transformlet.TtlTransformlet}
 * for {@link io.netty.util.concurrent.SingleThreadEventExecutor}.
 *
 * @author tk (305809299 at qq dot com)
 * @see io.netty.util.concurrent.SingleThreadEventExecutor
 * @see io.vertx.core.eventbus.EventBus
 * @see io.vertx.core.impl.EventLoopContext
 * @see io.vertx.core.eventbus.Message
 */
public final class NettySingleThreadEventExecutorTtlTransformlet extends AbstractExecutorTtlTransformlet {

    private static Set<String> getExecutorClassNames() {
        Set<String> executorClassNames = new HashSet<>();

        executorClassNames.add("io.netty.util.concurrent.SingleThreadEventExecutor");

        return executorClassNames;
    }

    public NettySingleThreadEventExecutorTtlTransformlet() {
        super(getExecutorClassNames(), false);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>React starter app</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function finalize_setup_phase</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../index.html" title="Boost.Test">
<link rel="up" href="../../../header/boost/test/framework_hpp.html" title="Header <boost/test/framework.hpp>">
<link rel="prev" href="init_idm46165630116864.html" title="Function init">
<link rel="next" href="shutdown.html" title="Function shutdown">

Home
Libraries
People
FAQ
More

Function finalize_setup_phase

boost::unit_test::framework::finalize_setup_phase — This function applies all the decorators and figures out default run status. This argument facilitates an ability of the test cases to prepare some other test units (primarily used internally for self testing).

Synopsis

// In header: <boost/test/framework.hpp>

void finalize_setup_phase(test_unit_id tu = INV_TEST_UNIT_ID);

Description

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Parameters:

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tu

Optional id of the test unit representing root of test tree. If absent, master test suite is used

Copyright © 2001-2015 Boost.Test contributors

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package com.tearsofaunicorn.wordpress.api.model.converter;

import com.tearsofaunicorn.wordpress.api.model.Category;
import junit.framework.Assert;
import org.junit.Test;
import java.util.Set;

public class CategoriesConverterTest extends ConverterTest<Object[]> {

    @Test
    public void testConvert() throws Exception {
        Object[] xmlrpcResponse = loadObject("./src/test/resources/data/categories-object.stream");

        Set<Category> categories = new CategoriesConverter().convert(xmlrpcResponse);
        Assert.assertNotNull(categories);
        Assert.assertFalse(categories.isEmpty());
    }
}


text:
<?php

namespace Drush\User;

abstract class UserSingleBase {

  // A Drupal user entity.
  public $account;

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

  /**
   * A flatter and simpler array presentation of a Drupal $user object.
   *
   * @return array
   */
  public function info() {
    return array(
      'uid' => $this->account->id(),
      'name' => $this->account->getUsername(),
      'password' => $this->account->getPassword(),
      'mail' => $this->account->getEmail(),
      'user_created' => $this->account->getCreatedTime(),
      'created' => format_date($this->account->getCreatedTime()),
      'user_access' => $this->account->getLastAccessedTime(),
      'access' => format_date($this->account->getLastAccessedTime()),
      'user_login' => $this->account->getLastLoginTime(),
      'login' => format_date($this->account->getLastLoginTime()),
      'user_status' => $this->account->get('status')->value,
      'status' => $this->account->isActive() ? 'active' : 'blocked',
      'timezone' => $this->account->getTimeZone(),
      'roles' => $this->account->getRoles(),
      'langcode' => $this->account->getPreferredLangcode(),
      'uuid' => $this->account->uuid->value,
    );
  }

  /**
   * Block a user from login.
   */
  public function block() {
    $this->account->block();
    $this->account->save();
  }

  /**
   * Unblock a user from login.
   */
  public function unblock() {
    $this->account->get('status')->value = 1;
    $this->account->save();
  }

  /**
   * Add a role to the current user.
   *
   * @param $rid
   *   A role ID.
   */
  public function addRole($rid) {
    $this->account->addRole($rid);
    $this->account->save();
  }

  /**
   * Remove a role from the current user.
   *
   * @param $rid
   *   A role ID.
   */
  public function removeRole($rid) {
    $this->account->removeRole($rid);
    $this->account->save();
  }

  /**
   * Block a user and remove or reassign their content.
   */
  public function cancel() {
      if (drush_get_option('delete-content')) {
        user_cancel(array(), $this->id(), 'user_cancel_delete');
      }
      else {
        user_cancel(array(), $this->id(), 'user_cancel_reassign');
      }
      // I got the following technique here: http://drupal.org/node/638712
      $batch =& batch_get();
      $batch['progressive'] = FALSE;
      batch_process();
  }

  /**
   * Change a user's password.
   *
   * @param $password
   */
  public function password($password) {
    $this->account->setPassword($password);
    $this->account->save();
  }

  /**
   * Build a one time login link.
   *
   * @param string $path
   * @return string
   */
  public function passResetUrl($path = '') {
    $url = user_pass_reset_url($this->account);
    if ($path) {
      $url .= '?destination=' . $path;
    }
    return $url;
  }

  /**
   * Get a user's name.
   * @return string
   */
  public function getUsername() {
    return $this->account->getUsername();
  }

  /**
   * Return an id from a Drupal user account.
   * @return int
   */
  public function id() {
    return $this->account->id();
  }
}


text:
typedef double (*matrix_form) (int num, double *x, double *weights,
        double *u, double *dudx, double *v, double *dvdx,
        double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
        double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM], void *user_data);

typedef double (*vector_form) (int num, double *x, double *weights,
        double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
               double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
               double *v, double *dvdx,
        void *user_data);

typedef double (*matrix_form_surf) (double x, double u, double dudx,
        double v, double dvdx, double u_prev[MAX_SLN_NUM][MAX_EQN_NUM],
        double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM], void *user_data);

typedef double (*vector_form_surf) (double x, double u_prev[MAX_SLN_NUM][MAX_EQN_NUM],
        double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM], double v, double dvdx,
        void *user_data);

class DiscreteProblem {

public:
    DiscreteProblem();
    void add_matrix_form(int i, int j, matrix_form fn, int marker=ANY);
    void add_vector_form(int i, vector_form fn, int marker=ANY);
    void add_matrix_form_surf(int i, int j, matrix_form_surf fn, int bdy_index);
    void add_vector_form_surf(int i, vector_form_surf fn, int bdy_index);
    // c is solution component
    void process_vol_forms(Mesh *mesh, Matrix *mat, double *res,
                           int matrix_flag);
    // c is solution component
    void process_surf_forms(Mesh *mesh, Matrix *mat, double *res,
                            int matrix_flag, int bdy_index);
    void assemble(Mesh *mesh, Matrix *mat, double *res, int matrix_flag);
    void assemble_matrix_and_vector(Mesh *mesh, Matrix *mat, double *res);
    void assemble_matrix(Mesh *mesh, Matrix *mat);
    void assemble_vector(Mesh *mesh, double *res);

private:
	struct MatrixFormVol {
		int i, j;
		matrix_form fn;
	        int marker;
	};
	struct MatrixFormSurf {
		int i, j, bdy_index;
		matrix_form_surf fn;
	};
	struct VectorFormVol {
		int i;
		vector_form fn;
	        int marker;
	};
	struct VectorFormSurf {
		int i, bdy_index;
		vector_form_surf fn;
	};
	std::vector<MatrixFormVol> matrix_forms_vol;
	std::vector<MatrixFormSurf> matrix_forms_surf;
	std::vector<VectorFormVol> vector_forms_vol;
	std::vector<VectorFormSurf> vector_forms_surf;
};

// return coefficients for all shape functions on the element m,
// for all solution components
void calculate_elem_coeffs(Element *e, double **coeffs, int n_eq);

void element_quadrature(double a, double b,
                        int order, double *pts, double *weights, int *num);

void element_shapefn(double a, double b,
		     int k, int order, double *val, double *der);

void element_shapefn_point(double x_ref, double a, double b,
			   int k, double &val, double &der);

void newton(DiscreteProblem *dp, Mesh *mesh,
            CommonSolver *solver,
            double newton_tol, int newton_maxiter,
            bool verbose=true);

void jfnk_cg(DiscreteProblem *dp, Mesh *mesh,
             double matrix_solver_tol, int matrix_solver_maxiter,
	     double jfnk_epsilon, double jfnk_tol, int jfnk_maxiter, bool verbose=true);

#endif


text:
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _inert = require('inert');

var _inert2 = _interopRequireDefault(_inert);

var _constants = require('../../../config/constants');

var _constants2 = _interopRequireDefault(_constants);

var _BaseFrameworkStrategy = require('../BaseFrameworkStrategy/BaseFrameworkStrategy');

var _BaseFrameworkStrategy2 = _interopRequireDefault(_BaseFrameworkStrategy);

var _hapi = require('hapi');

var _hapi2 = _interopRequireDefault(_hapi);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var HapiFrameworkStrategy = function (_BaseFrameworkStrateg) {
  _inherits(HapiFrameworkStrategy, _BaseFrameworkStrateg);

  function HapiFrameworkStrategy(config) {
    var _ret;

    _classCallCheck(this, HapiFrameworkStrategy);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(HapiFrameworkStrategy).call(this, Object.assign({}, config, {
      type: _BaseFrameworkStrategy2.default.constants.HAPI
    })));

    _this.framework = _hapi2.default;
    return _ret = _this, _possibleConstructorReturn(_this, _ret);
  }

  _createClass(HapiFrameworkStrategy, [{
    key: 'forceSecure',
    value: function forceSecure(request, reply) {
      if (request.connection.info.protocol !== 'https') {
        return reply().redirect('https://' + request.headers.host + request.url.path).code(301);
      }
      reply.continue();
    }
  }, {
    key: 'start',
    value: function start() {
      var _this2 = this;

      var superStart = _get(Object.getPrototypeOf(HapiFrameworkStrategy.prototype), 'start', this).bind(this);
      var port = this.config.http && this.config.http.port || _BaseFrameworkStrategy2.default.constants.DEFAULT_PORT;

      this.server = new this.framework.Server();

      return new Promise(function (resolve) {

        _this2.server.register(_inert2.default, function (err) {

          if (err) {
            throw err;
          }

          _this2.server.connection({
            host: 'localhost',
            port: port
          });

          if (_this2.forceHttps) {

            _this2.server.connection({
              host: '0.0.0.0',
              port: _this2.config.https.port,
              tls: _this2.config.https.options
            });

            _this2.server.ext('onRequest', _this2.forceSecure.bind(_this2));
          }

          if (_this2.config.cors) {
            _this2.server.connection.routes = {
              cors: true
            };
          }

          _this2.server.start(function () {
            superStart();
            resolve(_this2);
          });
        });
      });
    }
  }, {
    key: 'stop',
    value: function stop() {
      if (this.isStarted()) {
        this.server.root.stop();
        this._isStarted = false;
      }
    }
  }, {
    key: 'addRoute',
    value: function addRoute(path, config) {
      var _this3 = this;

      path = path === '*' ? '/{path*}' : path;

      for (var method in config) {

        this.server.route({
          path: path,
          method: method.toUpperCase(),
          handler: function handler(request, reply) {

            _this3.hapiRequest = request;
            _this3.hapiReply = reply;

            config[method](_this3.request(), _this3.respond());
          }
        });
      }
    }
  }, {
    key: 'request',
    value: function request() {
      var _this4 = this;

      return {
        getPath: function getPath() {
          return _this4.hapiRequest.url.path;
        },
        getBody: function getBody() {
          return _this4.hapiRequest.payload;
        },
        getCookies: function getCookies() {
          return _this4.hapiRequest.state;
        }
      };
    }
  }, {
    key: 'respond',
    value: function respond() {
      var _this5 = this;

      return {

        with: function _with(code, body) {

          if (code >= 300 && code <= 308) {
            _this5.hapiReply.redirect(body).code(code);
            return;
          }

          _this5.hapiReply(body).code(code);
        },

        withFile: function withFile(fileLocation) {

          _this5.hapiReply.file(fileLocation);
        }
      };
    }
  }]);

  return HapiFrameworkStrategy;
}(_BaseFrameworkStrategy2.default);

module.exports = HapiFrameworkStrategy;


text:
package checkinproto

//go:generate protoc --go_out=. checkin.proto


text:
#include "config.h"
#include <wtf/WorkQueue.h>

#include <wtf/text/WTFString.h>

void WorkQueue::platformInitialize(const char* name, Type, QOS)
{
    LockHolder locker(m_initializeRunLoopConditionMutex);
    m_workQueueThread = Thread::create(name, [this] {
        {
            LockHolder locker(m_initializeRunLoopConditionMutex);
            m_runLoop = &RunLoop::current();
            m_initializeRunLoopCondition.notifyOne();
        }
        m_runLoop->run();
    });
    m_initializeRunLoopCondition.wait(m_initializeRunLoopConditionMutex);
}

void WorkQueue::platformInvalidate()
{
    if (m_runLoop)
        m_runLoop->stop();
    if (m_workQueueThread) {
        m_workQueueThread->detach();
        m_workQueueThread = nullptr;
    }
}

void WorkQueue::dispatch(Function<void()>&& function)
{
    RefPtr<WorkQueue> protect(this);
    m_runLoop->dispatch([protect, function = WTFMove(function)] {
        function();
    });
}

void WorkQueue::dispatchAfter(Seconds delay, Function<void()>&& function)
{
    RefPtr<WorkQueue> protect(this);
    m_runLoop->dispatchAfter(delay, [protect, function = WTFMove(function)] {
        function();
    });
}


text:
<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
    'id' => 'sub-customer-custom-field-assignment-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation' => false,
        // 'htmlOptions'=>array('enctype'=>'multipart/form-data'),
        ));
?>

Fields with * are required.

<?php echo $form->errorSummary($model); ?>

<?php echo $form->textFieldRow($model, 'value', array('class' => 'span5', 'maxlength' => 45)); ?>
<?php // echo $form->textFieldRow($model, 'customer_custom_field_assignment_id', array('class' => 'span5')); ?>
<input style="display:none" class="span5" value="<?php echo $pId; ?>" name="SubCustomerCustomFieldAssignment[customer_custom_field_assignment_id]" id="SubCustomerCustomFieldAssignment_customer_custom_field_assignment_id" type="text">

    <?php
    $this->widget('bootstrap.widgets.TbButton', array(
        'buttonType' => 'submit',
        'type' => 'primary',
        'label' => $model->isNewRecord ? 'Create' : 'Save',
    ));
    ?>

<?php $this->endWidget(); ?>


text:
class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
  has_many :assignments
  has_many :projects, :through => :assignments, before_remove: :before_project_removal
  has_many :timesheets, :dependent => :destroy

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  # :registerable,
  devise :database_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :username, :working_hours, :presence => true

  scope :active, -> { where(:active => true).order('username') }

  scope :developer, -> { joins(:roles).where('roles.name = ?', :developer).order('username') }

  def has_role?(role_sym)
    roles.any? { |r| r.name.underscore.to_sym == role_sym }
  end

  def active_for_authentication?
    super && active
  end

  def can_remove_user_from_project(project)
    hours = Entry.joins(:timesheet).where(timesheets: {user_id: self.id}).joins(:task).where(tasks: {project_id: project.id}).sum(:hours).to_i
    hours == 0
  end

  def planned_hours_by_project_in_week(week)
    PlannedHour.select("projects.name, projects.id AS project_id, SUM(planned_hours.hours) AS hours")
               .joins(:assignment => :project)
               .where(assignments: {user_id: self.id})
               .where("planned_hours.week >= ? AND planned_hours.week <= ?", week, week)
               .order("projects.name")
               .group("projects.name, projects.id").to_a
  end

  def actual_hours_by_project_in_week(week)
    Entry.select("tasks.project_id, projects.name AS project_name, SUM(entries.hours) AS hours")
         .joins(:task => :project)
         .joins(:timesheet)
         .where(timesheets: {user_id: self.id})
         .where("timesheets.date >= ? AND timesheets.date <= ?", week.beginning_of_week, week.end_of_week)
         .group("tasks.project_id").to_a
  end

  private

  def before_project_removal(project)
    # check if the user has already worked on this project
    if not self.can_remove_user_from_project(project)
      raise "Cannot remove project '#{project.name}', because the user has already worked on it."
    else
      # remove assigned planned hours (reason: https://github.com/rails/rails/issues/3722)
      assignment = Assignment.find_by_user_id_and_project_id self.id, project.id
      if assignment and assignment.planned_hours
        assignment.planned_hours.each { |ph| ph.destroy }
      end
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Sonata\AdminBundle\Tests\App\FieldDescription;

use Sonata\AdminBundle\FieldDescription\BaseFieldDescription;

final class FieldDescription extends BaseFieldDescription
{
    public function setAssociationMapping($associationMapping): void
    {
    }

    public function getTargetEntity(): ?string
    {
        return null;
    }

    public function getTargetModel(): ?string
    {
        return null;
    }

    public function setFieldMapping(array $fieldMapping): void
    {
    }

    public function setParentAssociationMappings(array $parentAssociationMappings): void
    {
    }

    public function isIdentifier(): bool
    {
        return false;
    }

    public function getValue(object $object)
    {
        return $this->getFieldValue($object, $this->fieldName);
    }

    public function describesSingleValuedAssociation(): bool
    {
        return false;
    }

    public function describesCollectionValuedAssociation(): bool
    {
        return false;
    }
}


text:
/*global exports:true*/
'use strict';
var Syntax = require('jstransform').Syntax;
var utils = require('jstransform/src/utils');

function renderXJSLiteral(object, isLast, state, start, end) {
  var lines = object.value.split(/\r\n|\n|\r/);

  if (start) {
    utils.append(start, state);
  }

  var lastNonEmptyLine = 0;

  lines.forEach(function(line, index) {
    if (line.match(/[^ \t]/)) {
      lastNonEmptyLine = index;
    }
  });

  lines.forEach(function(line, index) {
    var isFirstLine = index === 0;
    var isLastLine = index === lines.length - 1;
    var isLastNonEmptyLine = index === lastNonEmptyLine;

    // replace rendered whitespace tabs with spaces
    var trimmedLine = line.replace(/\t/g, ' ');

    // trim whitespace touching a newline
    if (!isFirstLine) {
      trimmedLine = trimmedLine.replace(/^[ ]+/, '');
    }
    if (!isLastLine) {
      trimmedLine = trimmedLine.replace(/[ ]+$/, '');
    }

    if (!isFirstLine) {
      utils.append(line.match(/^[ \t]*/)[0], state);
    }

    if (trimmedLine || isLastNonEmptyLine) {
      utils.append(
        JSON.stringify(trimmedLine) +
        (!isLastNonEmptyLine ? ' + \' \' +' : ''),
        state);

      if (isLastNonEmptyLine) {
        if (end) {
          utils.append(end, state);
        }
        if (!isLast) {
          utils.append(', ', state);
        }
      }

      // only restore tail whitespace if line had literals
      if (trimmedLine && !isLastLine) {
        utils.append(line.match(/[ \t]*$/)[0], state);
      }
    }

    if (!isLastLine) {
      utils.append('\n', state);
    }
  });

  utils.move(object.range[1], state);
}

function renderXJSExpressionContainer(traverse, object, isLast, path, state) {
  // Plus 1 to skip `{`.
  utils.move(object.range[0] + 1, state);
  utils.catchup(object.expression.range[0], state);
  traverse(object.expression, path, state);

  if (!isLast && object.expression.type !== Syntax.XJSEmptyExpression) {
    // If we need to append a comma, make sure to do so after the expression.
    utils.catchup(object.expression.range[1], state, trimLeft);
    utils.append(', ', state);
  }

  // Minus 1 to skip `}`.
  utils.catchup(object.range[1] - 1, state, trimLeft);
  utils.move(object.range[1], state);
  return false;
}

function quoteAttrName(attr) {
  // Quote invalid JS identifiers.
  if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) {
    return '"' + attr + '"';
  }
  return attr;
}

function trimLeft(value) {
  return value.replace(/^[ ]+/, '');
}

exports.renderXJSExpressionContainer = renderXJSExpressionContainer;
exports.renderXJSLiteral = renderXJSLiteral;
exports.quoteAttrName = quoteAttrName;
exports.trimLeft = trimLeft;


text:
/*  =========================================================================
    sprk_msg - sprk msg protocol

    Codec class for sprk_msg.

    ** WARNING *************************************************************
    THIS SOURCE FILE IS 100% GENERATED. If you edit this file, you will lose
    your changes at the next build cycle. This is great for temporary printf
    statements. DO NOT MAKE ANY CHANGES YOU WISH TO KEEP. The correct places
    for commits are:

     * The XML model used for this code generation: sprk_msg.xml, or
     * The code generation script that built this file: zproto_codec_c
    ************************************************************************
    =========================================================================
*/

/*
@header
    sprk_msg - sprk msg protocol
@discuss
@end
*/

#include "../include/sprk_msg.h"

//  Structure of our class

struct _sprk_msg_t {
    zframe_t *routing_id;               //  Routing_id from ROUTER, if any
    int id;                             //  sprk_msg message ID
    byte *needle;                       //  Read/write pointer for serialization
    byte *ceiling;                      //  Valid upper limit for read pointer
    char block_id [256];                //  block_id
    char descriptor_uri [256];          //  descriptor_uri
    uint64_t descriptor_offset;         //  descriptor_offset
    uint64_t descriptor_length;         //  descriptor_length
    uint32_t descriptor_row_size;       //  descriptor_row_size
};

//  --------------------------------------------------------------------------
//  Network data encoding macros

//  Put a block of octets to the frame
#define PUT_OCTETS(host,size) { \
    memcpy (self->needle, (host), size); \
    self->needle += size; \
}

//  Get a block of octets from the frame
#define GET_OCTETS(host,size) { \
    if (self->needle + size > self->ceiling) { \
        zsys_warning ("sprk_msg: GET_OCTETS failed"); \
        goto malformed; \
    } \
    memcpy ((host), self->needle, size); \
    self->needle += size; \
}

//  Put a 1-byte number to the frame
#define PUT_NUMBER1(host) { \
    *(byte *) self->needle = (host); \
    self->needle++; \
}

//  Put a 2-byte number to the frame
#define PUT_NUMBER2(host) { \
    self->needle [0] = (byte) (((host) >> 8)  & 255); \
    self->needle [1] = (byte) (((host))       & 255); \
    self->needle += 2; \
}

//  Put a 4-byte number to the frame
#define PUT_NUMBER4(host) { \
    self->needle [0] = (byte) (((host) >> 24) & 255); \
    self->needle [1] = (byte) (((host) >> 16) & 255); \
    self->needle [2] = (byte) (((host) >> 8)  & 255); \
    self->needle [3] = (byte) (((host))       & 255); \
    self->needle += 4; \
}

//  Put a 8-byte number to the frame
#define PUT_NUMBER8(host) { \
    self->needle [0] = (byte) (((host) >> 56) & 255); \
    self->needle [1] = (byte) (((host) >> 48) & 255); \
    self->needle [2] = (byte) (((host) >> 40) & 255); \
    self->needle [3] = (byte) (((host) >> 32) & 255); \
    self->needle [4] = (byte) (((host) >> 24) & 255); \
    self->needle [5] = (byte) (((host) >> 16) & 255); \
    self->needle [6] = (byte) (((host) >> 8)  & 255); \
    self->needle [7] = (byte) (((host))       & 255); \
    self->needle += 8; \
}

//  Get a 1-byte number from the frame
#define GET_NUMBER1(host) { \
    if (self->needle + 1 > self->ceiling) { \
        zsys_warning ("sprk_msg: GET_NUMBER1 failed"); \
        goto malformed; \
    } \
    (host) = *(byte *) self->needle; \
    self->needle++; \
}

//  Get a 2-byte number from the frame
#define GET_NUMBER2(host) { \
    if (self->needle + 2 > self->ceiling) { \
        zsys_warning ("sprk_msg: GET_NUMBER2 failed"); \
        goto malformed; \
    } \
    (host) = ((uint16_t) (self->needle [0]) << 8) \
           +  (uint16_t) (self->needle [1]); \
    self->needle += 2; \
}

//  Get a 4-byte number from the frame
#define GET_NUMBER4(host) { \
    if (self->needle + 4 > self->ceiling) { \
        zsys_warning ("sprk_msg: GET_NUMBER4 failed"); \
        goto malformed; \
    } \
    (host) = ((uint32_t) (self->needle [0]) << 24) \
           + ((uint32_t) (self->needle [1]) << 16) \
           + ((uint32_t) (self->needle [2]) << 8) \
           +  (uint32_t) (self->needle [3]); \
    self->needle += 4; \
}

//  Get a 8-byte number from the frame
#define GET_NUMBER8(host) { \
    if (self->needle + 8 > self->ceiling) { \
        zsys_warning ("sprk_msg: GET_NUMBER8 failed"); \
        goto malformed; \
    } \
    (host) = ((uint64_t) (self->needle [0]) << 56) \
           + ((uint64_t) (self->needle [1]) << 48) \
           + ((uint64_t) (self->needle [2]) << 40) \
           + ((uint64_t) (self->needle [3]) << 32) \
           + ((uint64_t) (self->needle [4]) << 24) \
           + ((uint64_t) (self->needle [5]) << 16) \
           + ((uint64_t) (self->needle [6]) << 8) \
           +  (uint64_t) (self->needle [7]); \
    self->needle += 8; \
}

//  Put a string to the frame
#define PUT_STRING(host) { \
    size_t string_size = strlen (host); \
    PUT_NUMBER1 (string_size); \
    memcpy (self->needle, (host), string_size); \
    self->needle += string_size; \
}

//  Get a string from the frame
#define GET_STRING(host) { \
    size_t string_size; \
    GET_NUMBER1 (string_size); \
    if (self->needle + string_size > (self->ceiling)) { \
        zsys_warning ("sprk_msg: GET_STRING failed"); \
        goto malformed; \
    } \
    memcpy ((host), self->needle, string_size); \
    (host) [string_size] = 0; \
    self->needle += string_size; \
}

//  Put a long string to the frame
#define PUT_LONGSTR(host) { \
    size_t string_size = strlen (host); \
    PUT_NUMBER4 (string_size); \
    memcpy (self->needle, (host), string_size); \
    self->needle += string_size; \
}

//  Get a long string from the frame
#define GET_LONGSTR(host) { \
    size_t string_size; \
    GET_NUMBER4 (string_size); \
    if (self->needle + string_size > (self->ceiling)) { \
        zsys_warning ("sprk_msg: GET_LONGSTR failed"); \
        goto malformed; \
    } \
    free ((host)); \
    (host) = (char *) malloc (string_size + 1); \
    memcpy ((host), self->needle, string_size); \
    (host) [string_size] = 0; \
    self->needle += string_size; \
}

//  --------------------------------------------------------------------------
//  Create a new sprk_msg

sprk_msg_t *
sprk_msg_new (void)
{
    sprk_msg_t *self = (sprk_msg_t *) zmalloc (sizeof (sprk_msg_t));
    return self;
}

//  --------------------------------------------------------------------------
//  Destroy the sprk_msg

void
sprk_msg_destroy (sprk_msg_t **self_p)
{
    assert (self_p);
    if (*self_p) {
        sprk_msg_t *self = *self_p;

        //  Free class properties
        zframe_destroy (&self->routing_id);

        //  Free object itself
        free (self);
        *self_p = NULL;
    }
}

//  --------------------------------------------------------------------------
//  Receive a sprk_msg from the socket. Returns 0 if OK, -1 if
//  there was an error. Blocks if there is no message waiting.

int
sprk_msg_recv (sprk_msg_t *self, zsock_t *input)
{
    assert (input);

    if (zsock_type (input) == ZMQ_ROUTER) {
        zframe_destroy (&self->routing_id);
        self->routing_id = zframe_recv (input);
        if (!self->routing_id || !zsock_rcvmore (input)) {
            zsys_warning ("sprk_msg: no routing ID");
            return -1;          //  Interrupted or malformed
        }
    }
    zmq_msg_t frame;
    zmq_msg_init (&frame);
    int size = zmq_msg_recv (&frame, zsock_resolve (input), 0);
    if (size == -1) {
        zsys_warning ("sprk_msg: interrupted");
        goto malformed;         //  Interrupted
    }
    //  Get and check protocol signature
    self->needle = (byte *) zmq_msg_data (&frame);
    self->ceiling = self->needle + zmq_msg_size (&frame);

    uint16_t signature;
    GET_NUMBER2 (signature);
    if (signature != (0xAAA0 | 0)) {
        zsys_warning ("sprk_msg: invalid signature");
        //  TODO: discard invalid messages and loop, and return
        //  -1 only on interrupt
        goto malformed;         //  Interrupted
    }
    //  Get message id and parse per message type
    GET_NUMBER1 (self->id);

    switch (self->id) {
        case SPRK_MSG_ASSIGN_BLOCK:
            GET_STRING (self->block_id);
            GET_STRING (self->descriptor_uri);
            GET_NUMBER8 (self->descriptor_offset);
            GET_NUMBER8 (self->descriptor_length);
            GET_NUMBER4 (self->descriptor_row_size);
            break;

        case SPRK_MSG_BLOCK_ASSIGNED:
            GET_STRING (self->block_id);
            break;

        default:
            zsys_warning ("sprk_msg: bad message ID");
            goto malformed;
    }
    //  Successful return
    zmq_msg_close (&frame);
    return 0;

    //  Error returns
    malformed:
        zsys_warning ("sprk_msg: sprk_msg malformed message, fail");
        zmq_msg_close (&frame);
        return -1;              //  Invalid message
}

//  --------------------------------------------------------------------------
//  Send the sprk_msg to the socket. Does not destroy it. Returns 0 if
//  OK, else -1.

int
sprk_msg_send (sprk_msg_t *self, zsock_t *output)
{
    assert (self);
    assert (output);

    if (zsock_type (output) == ZMQ_ROUTER)
        zframe_send (&self->routing_id, output, ZFRAME_MORE + ZFRAME_REUSE);

    size_t frame_size = 2 + 1;          //  Signature and message ID
    switch (self->id) {
        case SPRK_MSG_ASSIGN_BLOCK:
            frame_size += 1 + strlen (self->block_id);
            frame_size += 1 + strlen (self->descriptor_uri);
            frame_size += 8;            //  descriptor_offset
            frame_size += 8;            //  descriptor_length
            frame_size += 4;            //  descriptor_row_size
            break;
        case SPRK_MSG_BLOCK_ASSIGNED:
            frame_size += 1 + strlen (self->block_id);
            break;
    }
    //  Now serialize message into the frame
    zmq_msg_t frame;
    zmq_msg_init_size (&frame, frame_size);
    self->needle = (byte *) zmq_msg_data (&frame);
    PUT_NUMBER2 (0xAAA0 | 0);
    PUT_NUMBER1 (self->id);
    size_t nbr_frames = 1;              //  Total number of frames to send

    switch (self->id) {
        case SPRK_MSG_ASSIGN_BLOCK:
            PUT_STRING (self->block_id);
            PUT_STRING (self->descriptor_uri);
            PUT_NUMBER8 (self->descriptor_offset);
            PUT_NUMBER8 (self->descriptor_length);
            PUT_NUMBER4 (self->descriptor_row_size);
            break;

        case SPRK_MSG_BLOCK_ASSIGNED:
            PUT_STRING (self->block_id);
            break;

    }
    //  Now send the data frame
    zmq_msg_send (&frame, zsock_resolve (output), --nbr_frames? ZMQ_SNDMORE: 0);

    return 0;
}

//  --------------------------------------------------------------------------
//  Print contents of message to stdout

void
sprk_msg_print (sprk_msg_t *self)
{
    assert (self);
    switch (self->id) {
        case SPRK_MSG_ASSIGN_BLOCK:
            zsys_debug ("SPRK_MSG_ASSIGN_BLOCK:");
            zsys_debug ("    block_id='%s'", self->block_id);
            zsys_debug ("    descriptor_uri='%s'", self->descriptor_uri);
            zsys_debug ("    descriptor_offset=%ld", (long) self->descriptor_offset);
            zsys_debug ("    descriptor_length=%ld", (long) self->descriptor_length);
            zsys_debug ("    descriptor_row_size=%ld", (long) self->descriptor_row_size);
            break;

        case SPRK_MSG_BLOCK_ASSIGNED:
            zsys_debug ("SPRK_MSG_BLOCK_ASSIGNED:");
            zsys_debug ("    block_id='%s'", self->block_id);
            break;

    }
}

//  --------------------------------------------------------------------------
//  Get/set the message routing_id

zframe_t *
sprk_msg_routing_id (sprk_msg_t *self)
{
    assert (self);
    return self->routing_id;
}

void
sprk_msg_set_routing_id (sprk_msg_t *self, zframe_t *routing_id)
{
    if (self->routing_id)
        zframe_destroy (&self->routing_id);
    self->routing_id = zframe_dup (routing_id);
}

//  --------------------------------------------------------------------------
//  Get/set the sprk_msg id

int
sprk_msg_id (sprk_msg_t *self)
{
    assert (self);
    return self->id;
}

void
sprk_msg_set_id (sprk_msg_t *self, int id)
{
    self->id = id;
}

//  --------------------------------------------------------------------------
//  Return a printable command string

const char *
sprk_msg_command (sprk_msg_t *self)
{
    assert (self);
    switch (self->id) {
        case SPRK_MSG_ASSIGN_BLOCK:
            return ("ASSIGN_BLOCK");
            break;
        case SPRK_MSG_BLOCK_ASSIGNED:
            return ("BLOCK_ASSIGNED");
            break;
    }
    return "?";
}

//  --------------------------------------------------------------------------
//  Get/set the block_id field

const char *
sprk_msg_block_id (sprk_msg_t *self)
{
    assert (self);
    return self->block_id;
}

void
sprk_msg_set_block_id (sprk_msg_t *self, const char *value)
{
    assert (self);
    assert (value);
    if (value == self->block_id)
        return;
    strncpy (self->block_id, value, 255);
    self->block_id [255] = 0;
}

//  --------------------------------------------------------------------------
//  Get/set the descriptor_uri field

const char *
sprk_msg_descriptor_uri (sprk_msg_t *self)
{
    assert (self);
    return self->descriptor_uri;
}

void
sprk_msg_set_descriptor_uri (sprk_msg_t *self, const char *value)
{
    assert (self);
    assert (value);
    if (value == self->descriptor_uri)
        return;
    strncpy (self->descriptor_uri, value, 255);
    self->descriptor_uri [255] = 0;
}

//  --------------------------------------------------------------------------
//  Get/set the descriptor_offset field

uint64_t
sprk_msg_descriptor_offset (sprk_msg_t *self)
{
    assert (self);
    return self->descriptor_offset;
}

void
sprk_msg_set_descriptor_offset (sprk_msg_t *self, uint64_t descriptor_offset)
{
    assert (self);
    self->descriptor_offset = descriptor_offset;
}

//  --------------------------------------------------------------------------
//  Get/set the descriptor_length field

uint64_t
sprk_msg_descriptor_length (sprk_msg_t *self)
{
    assert (self);
    return self->descriptor_length;
}

void
sprk_msg_set_descriptor_length (sprk_msg_t *self, uint64_t descriptor_length)
{
    assert (self);
    self->descriptor_length = descriptor_length;
}

//  --------------------------------------------------------------------------
//  Get/set the descriptor_row_size field

uint32_t
sprk_msg_descriptor_row_size (sprk_msg_t *self)
{
    assert (self);
    return self->descriptor_row_size;
}

void
sprk_msg_set_descriptor_row_size (sprk_msg_t *self, uint32_t descriptor_row_size)
{
    assert (self);
    self->descriptor_row_size = descriptor_row_size;
}

//  --------------------------------------------------------------------------
//  Selftest

void
sprk_msg_test (bool verbose)
{
    printf (" * sprk_msg:");

    if (verbose)
        printf ("\n");

    //  @selftest
    //  Simple create/destroy test
    sprk_msg_t *self = sprk_msg_new ();
    assert (self);
    sprk_msg_destroy (&self);
    //  Create pair of sockets we can send through
    //  We must bind before connect if we wish to remain compatible with ZeroMQ < v4
    zsock_t *output = zsock_new (ZMQ_DEALER);
    assert (output);
    int rc = zsock_bind (output, "inproc://selftest-sprk_msg");
    assert (rc == 0);

    zsock_t *input = zsock_new (ZMQ_ROUTER);
    assert (input);
    rc = zsock_connect (input, "inproc://selftest-sprk_msg");
    assert (rc == 0);

    //  Encode/send/decode and verify each message type
    int instance;
    self = sprk_msg_new ();
    sprk_msg_set_id (self, SPRK_MSG_ASSIGN_BLOCK);

    sprk_msg_set_block_id (self, "Life is short but Now lasts for ever");
    sprk_msg_set_descriptor_uri (self, "Life is short but Now lasts for ever");
    sprk_msg_set_descriptor_offset (self, 123);
    sprk_msg_set_descriptor_length (self, 123);
    sprk_msg_set_descriptor_row_size (self, 123);
    //  Send twice
    sprk_msg_send (self, output);
    sprk_msg_send (self, output);

    for (instance = 0; instance < 2; instance++) {
        sprk_msg_recv (self, input);
        assert (sprk_msg_routing_id (self));
        assert (streq (sprk_msg_block_id (self), "Life is short but Now lasts for ever"));
        assert (streq (sprk_msg_descriptor_uri (self), "Life is short but Now lasts for ever"));
        assert (sprk_msg_descriptor_offset (self) == 123);
        assert (sprk_msg_descriptor_length (self) == 123);
        assert (sprk_msg_descriptor_row_size (self) == 123);
    }
    sprk_msg_set_id (self, SPRK_MSG_BLOCK_ASSIGNED);

    sprk_msg_set_block_id (self, "Life is short but Now lasts for ever");
    //  Send twice
    sprk_msg_send (self, output);
    sprk_msg_send (self, output);

    for (instance = 0; instance < 2; instance++) {
        sprk_msg_recv (self, input);
        assert (sprk_msg_routing_id (self));
        assert (streq (sprk_msg_block_id (self), "Life is short but Now lasts for ever"));
    }

    sprk_msg_destroy (&self);
    zsock_destroy (&input);
    zsock_destroy (&output);
    //  @end

    printf ("OK\n");
}


text:
import * as React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@mui/material/styles';
import MuiSnackbar from '@mui/material/Snackbar';
import { snackbarContentClasses } from '@mui/material/SnackbarContent';
import Slide from '@mui/material/Slide';
import CloseIcon from '@mui/icons-material/Close';
import InfoIcon from '@mui/icons-material/Info';
import IconButton from '@mui/material/IconButton';

const styles = ({ theme }) => ({
  [`& .${snackbarContentClasses.root}`]: {
    backgroundColor: theme.palette.secondary.light,
    color: theme.palette.text.primary,
    flexWrap: 'inherit',
    [theme.breakpoints.up('md')]: {
      borderTopLeftRadius: 0,
      borderTopRightRadius: 0,
      borderBottomRightRadius: 4,
      borderBottomLeftRadius: 4,
    },
  },
  [`& .${snackbarContentClasses.message}`]: {
    fontSize: 16,
    display: 'flex',
    alignItems: 'center',
  },
  [`& .${snackbarContentClasses.action}`]: {
    paddingLeft: theme.spacing(2),
  },
  '& .MuiSnackbarContent-info': {
    flexShrink: 0,
    marginRight: theme.spacing(2),
  },
  '& .MuiSnackbarContent-close': {
    padding: theme.spacing(1),
  },
});

function Transition(props) {
  return <Slide {...props} direction="down" />;
}

function Snackbar(props) {
  const { message, closeFunc, ...other } = props;
  const classes = {
    info: 'MuiSnackbarContent-info',
    close: 'MuiSnackbarContent-close',
  };

  return (
    <MuiSnackbar
      anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      autoHideDuration={6000}
      TransitionComponent={Transition}
      message={
        <React.Fragment>
          <InfoIcon className={classes.info} />
          <span>{message}</span>
        </React.Fragment>
      }
      action={[
        <IconButton
          key="close"
          aria-label="close"
          color="inherit"
          className={classes.close}
          onClick={() => closeFunc && closeFunc()}
        >
          <CloseIcon />
        </IconButton>,
      ]}
      {...other}
    />
  );
}

Snackbar.propTypes = {
  closeFunc: PropTypes.func,
  /**
   * The message to display.
   */
  message: PropTypes.node,
};

export default styled(Snackbar)(styles);


text:
namespace cym { namespace uix {
  class CApplication : public CObject {
    protected:
      static CApplication* sInstance;
      HINSTANCE            mHandle   = {NULL};
      bool                 mRunning  = {false};
      CLoop*               mLoop     = {nullptr};
    public:
      CApplication(HINSTANCE = ::GetModuleHandle(NULL));
      ~CApplication();
      CApplication(const CApplication&);
      CApplication& operator =(const CApplication&);
      explicit operator       HINSTANCE();
      explicit operator const HINSTANCE() const;
    protected:
      bool init();
      bool free();
    public:
      int  exec(int = 0);
      int  quit(int = 0);
    public:
      static CApplication* getInstance();
    protected:
      virtual void onInit();
      virtual void onTick(int = 0);
      virtual void onExit();
  };
}}

#define DECLARE_APPLICATION(cls)                                                                                \
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {                      \
  std::cout << "::WinMain(HINSTANCE,HINSTANCE,LPSTR,int)::" << hInstance << std::endl;                                 \
  auto app   = new cls;                                                                                \
  INT result = app->exec();                                                                                \
  delete app;                                                                                \
  return result;                                                                                \
}                                                                                //

#endif //__cym_uix_capplication_hpp__