text:
Bucky
=====

Bucky is a client and server for sending performance data from the client into statsd+graphite, OpenTSDB, InfluxDB, or any
other stats aggregator of your choice.

Bucky can measure how long your pages take to load, how long AJAX requests take, and how long
various functions take to run.  Most importantly, it's taking the measurements on actual page loads,
so the data has the potential to be much more valuable than in vitro measurements.

If you already use statsd, OpenTSDB or InfluxDB, you can get started in just a few minutes.  If you're not
collecting stats, you [should start](http://github.hubspot.com/BuckyServer/getting_started/choosing_a_stats_service/)!
What gets measured gets managed.

### Server

You can play with Bucky just using the client, but if you'd like to start collecting data, see the
[Server Instructions](http://github.hubspot.com/BuckyServer/).

### Setup

#### From The Client

Include [bucky.js](https://raw.github.com/HubSpot/BuckyClient/v0.3.0/bucky.min.js) on your page. All of the required configuration can be done right in the script tag:

```html
<script src="bucky.js" data-bucky-host="/bucky" data-bucky-page data-bucky-requests></script>
```

The example above sets up Bucky to report on page load performance and all XMLHttpRequests. The [data-bucky-host] attribute configures Bucky to send the reporting data to a server that's listening at /bucky.  Since no key string was listed Bucky will automatically generate a key name based on the url of the page.  If you'd like, you can also specify it manually:

```html
<script src="bucky.js" data-bucky-host="/bucky" data-bucky-page="index" data-bucky-requests="index"></script>
```

Here are the full list of options available as attributes with example values:
- `data-bucky-host="/bucky"`: Where we can reach your [Bucky server](http://github.com/HubSpot/BuckyServer), including the
  APP_ROOT.

  The Bucky server has a very liberal CORS config, so we should be able to connect to it even if
  it's on a different domain, but hosting it on the same domain and port will save you some preflight requests.

- `data-bucky-page="page"`: Turns on page performance logging, this example assigns the key "page".

- `data-bucky-requests="xhr"`: Turns on XMLHttpRequest monitoring, this example assigns the key "xhr".

- `data-bucky-json="true"`: Setting this flag to true changes the output to json. By default Bucky outputs using a line format similar to what's used by statsd.

- `data-bucky-influx-line-protocol="true"`: Change the output to use InfluxDB Line Protocol. The data-bucky-json attribute must setting must be set to true for this option.

- `data-bucky-query-string="escape|replace"`: This option only applies to InfluxDB Line Protocol. The two accepted values for this attribute are "escape" and "replace". When InfluxDB Line protocol is used the full URL will be attached as a tag. If the URL contains a query string, due to InfluxDB Line Protocol restrictions, either the = in the query string will need to be escaped to make the query string part of the URL, or the ? and & need to be replaced with commas to create additional tags.

This will create a `Bucky` object with the set attributes. This object will be available globally but there is nothing you need to call for basic usage.

Bucky can also be loaded with AMD or Browserify (see the methods below).

#### From Node

```bash
npm install bucky
```

```coffeescript
Bucky = require 'bucky'
```

### Configuring

Before sending any data you can call the `setOptions` to set any configuration options. Be aware that configuration set using `setOptions` will override any data attributes that were set in the script tag.

```javascript
Bucky.setOptions({
  host: 'http://my.web.hostname:5999/bucky'
});
```

Some options you might be interested in:

- `host`: Where we can reach your [Bucky server](http://github.com/HubSpot/BuckyServer), including the
  APP_ROOT.

  The Bucky server has a very liberal CORS config, so we should be able to connect to it even if
  it's on a different domain, but hosting it on the same domain and port will save you some preflight requests.

- `active`: Should Bucky actually send data?  Use this to disable Bucky during local dev for example.
- `sample`: What fraction of clients should actually send data?  Use to subsample your clients if you have
  too much data coming in.
- `json`: Boolean flag for sending data to the server as json instead of statsd line protocol. Default is false (to use statsd line protocol).
- `influxLineProtocol`: Boolean flag to change the format of the output to optimize for InfluxDB Line Protocol. Default is False. (influxLineProtocol requires the json flag to be set to true).
- `queryString`: This option only applies to InfluxDB Line Protocol. The two accepted values are "escape" and "replace". When InfluxDB Line protocol is used the full URL will be attached as a tag. If the URL contains a query string, due to InfluxDB Line Protocol restrictions, either the = in the query string will need to be escaped to make the query string part of the URL, or the ? and & need to be replaced with commas to create additional tags. The default is null.
Take a look at [the source](http://github.com/HubSpot/BuckyClient/blob/master/bucky.coffee#L34) for a
full list of options.

#### Sending Page Performance

Modern browsers log a bunch of page performance data, bucky includes a method for writing all of this in
one go.  It won't do anything on browsers which don't support the performance.timing api.  Call it whenever,
it will bind an event if the data isn't ready yet.

```coffeescript
Bucky.sendPagePerformance 'key.for.the.data'
```

This function gets called by default if the `data-bucky-page` attribute is set in the script tag.

The two most relevant stats provided are `responseEnd` which is the amount of time it took for the
original page to be loaded and `domInteractive` which is the amount of time before the page has
finished loaded and can be interacted with by the user.

As a reminder: this data is browser specific, so it will likely skew lower than what users on
old browsers see.

If you're using Backbone, it might be a good idea to send your data based on route:

```coffeescript
Backbone.history.on 'route', (router, route) ->
   # Will only send on the initial page load:
   Bucky.sendPagePerformance "key.page.#{ route }"
```

This is how the data will be sent to the server after page has fully loaded:

With the default statsd line protocol style syntax:

```text
key.page.routeName.connectEnd:172.000|ms
key.page.routeName.connectStart:106.000|ms
key.page.routeName.domComplete:1029.000|ms
key.page.routeName.domContentLoadedEventEnd:1019.000|ms
key.page.routeName.domContentLoadedEventStart:980.000|ms
key.page.routeName.domInteractive:980.000|ms
```

With JSON turned on:

```javascript
{
  "key.page.routeName.domLoading": "254.000|ms",
  "key.page.routeName.domainLookupEnd": "106.000|ms",
  "key.page.routeName.domainLookupStart": "106.000|ms",
  "key.page.routeName.fetchStart": "103.000|ms",
  "key.page.routeName.loadEventEnd": "1030.000|ms",
  "key.page.routeName.loadEventStart": "1029.000|ms"
}
```

And with JSON and Influx Line Protocol:

```javascript
{
  "key.page.routeName,url=http://window.location.string,timing=navigationStart": "0.000|ms",
  "key.page.routeName,url=http://window.location.string,timing=requestStart": "173.000|ms",
  "key.page.routeName,url=http://window.location.string,timing=responseEnd": "243.000|ms",
  "key.page.routeName,url=http://window.location.string,timing=responseStart": "235.000|ms",
  "key.page.routeName,url=http://window.location.string,timing=secureConnectionStart": "106.000|ms"
}
```

A description of what each datapoint represents is included in [the spec](http://www.w3.org/TR/navigation-timing-2/#sec-PerformanceNavigationTiming).

#### Sending AJAX Request Time

Bucky can automatically log all ajax requests made by hooking into XMLHttpRequest and doing some transformations
on the url to try and create a graphite key from it.  Enable it as early in your app's load as is possible:

```coffeescript
Bucky.requests.monitor 'my.project.requests'
```

This function gets called by default if the `data-bucky-requests` attribute is set in the script tag.

This is how the data will be sent to the server for a GET request to
`api.hubapi.com/automation/v2/workflows`:

With the default statsd line protocol style syntax:

```text
my.project.requests.api.hubapi.automation.v2.workflows.get:656.794|ms
my.project.requests.api.hubapi.automation.v2.workflows.get.2xx:1|c
my.project.requests.api.hubapi.automation.v2.workflows.get.200:1|c
```

With JSON turned on:

```javascript
{
  "my.project.requests.api.hubapi.automation.v2.workflows.get.headers": "436.737|ms",
  "my.project.requests.api.hubapi.automation.v2.workflows.get.receiving": "0.182|ms"
}
```

And with JSON and Influx Line Protocol:

```javascript
{
  "my.project.requests,url=http://window.location,endpoint=http://api.hubapi.com/automation/v2/workflows,method=get,status=sending": "0.059|ms",
  "my.project.requests,url=http://window.location,endpoint=http://api.hubapi.com/automation/v2/workflows,method=get,status=waiting": "206.035|ms"
}
```

#### Prefixing

You can build a client which will prefix all of your datapoints by calling bucky as a function:

```coffeescript
myBucky = Bucky 'awesome.app.view'

# You can then use all of the normal methods:
myBucky.send 'data.point', 5
```

You can repeatedly call clients to add more prefixes:

```coffeescript
contactsBucky = bucky 'contacts'
cwBucky = contactsBucky 'web'

cwBucky.send('x', 1) # Data goes in contacts.web.x
```

#### Counting Things

By default `send` sends absolute values, this is rarely what you want when working from the client, incrementing
a counter is usually more helpful:

```coffeescript
bucky.count 'my.awesome.thing'
bucky.count 'number.of.chips.eaten', 5
```

#### Timing Things

You can manually send ms durations using `timer.send`:

```coffeescript
bucky.timer.send 'timed.thing', 55
```

Bucky includes a method to time async functions:

```coffeescript
bucky.timer.time 'my.awesome.function', (done) ->
  asyncThingy ->
    done()
```

You can also manually start and stop your timer:

```coffeescript
bucky.timer.start 'my.awesome.function'

asyncThingy ->
  bucky.timer.stop 'my.awesome.function'
```

You can time synchronous functions as well:

```coffeescript
bucky.timer.timeSync 'my.awesome.function', ->
  Math.sqrt 100
```

The `time` and `timeSync` functions also accept a context and arguments to pass to the
called function:

```coffeescript
bucky.timer.timeSync 'my.render.function', @render, @, arg1, arg2
```

You can wrap existing functions using `wrap`:

```coffeescript
func = bucky.timer.wrap 'func.time', func
```

It also supports a special syntax for methods:

```coffeescript
class SomeClass
  render: bucky.timer.wrap('render') ->
    # Normal render stuff
```

Note that this wrapping does not play nice with CoffeeScript `super` calls.

Bucky also includes a function for measuring the time since the navigationStart event was fired (the beginning of the request):

```coffeescript
bucky.timer.mark 'my.thing.happened'
```

It acts like a timer where the start is always navigation start.

The stopwatch method allows you to begin a timer which can be stopped multiple times:

```coffeescript
watch = bucky.stopwatch 'some.prefix.if.you.want'
```

You can then call `watch.mark('key')` to send the time since the stopwatch started, or
`watch.split('key')` to send the time since the last split.

### Sending Points

If you want to send absolute values (rare from the client), you can use send directly.

The one use we've had for this is sending `+new Date` from every client to get an idea
of how skewed their clocks are.

```coffeescript
Bucky.send 'my.awesome.datapoint', 2432.43434
```

### Your Stats

You can find your stats in the `stats` and `stats.timing` folders in graphite, or as written in OpenTSDB.

### Send Frequency

Bucky will send your data in bulk from the client either five seconds after the last datapoint is added, or thirty seconds after
the last send, whichever comes first.  If you log multiple datapoints within this send frequency, the points will
be averaged (and the appropriate frequency information will be sent to statsd) (with the exception of counters, they
are incremented).  This means that the max and min numbers you get from statsd actually represent the max and min
5-30 second bucket.  Note that this is per-client, not for the entire bucky process (it's generally only important
on the server where you might be pushing out many points with the same key).

### Bucky Object

The Bucky object provides a couple extra properties you can access:

- `Bucky.history`: The history of all datapoints ever sent.
- `Bucky.active`: Is Bucky sending data?  This can change if you change the `active` or `sample` settings.
- `Bucky.flush()`: Send the Bucky queue immediately
- `Bucky.timer.now()`: A clock based on the most precise time available (not guarenteed to be from the epoch)

### URL -> Key Transformation

`request.monitor` attempts to automatically transform your urls into keys.  It does a bunch of transformations
with the goal of removing anything which will vary per-request, so you end up with stats per-endpoint.  These
tranformations include:

- Stripping GUIDS, IDs, SHA1s, MD5s
- Stripping email addresses
- Stripping domains

If you find these tranformations too invasive, or not invasive enough, you can modify them.

```javascript
// You can diable tranforms with `.disable`
Bucky.requests.transforms.disable('guid');

// You can enable transforms with `.enable`
Bucky.requests.tranforms.enable('guid');

// `.enable` can also be used to add a new tranform:
Bucky.requests.transforms.enable('my-ids', /[0-9]{4}-[0-9]{12}/g)

// The third argument defines what the match is replaced with (rather than just eliminating it):
Bucky.requests.transforms.enable('campaign', /campaigns\/\w{15}/ig, '/campaigns')

// You can also just provide a function which takes in the url, and returns it modified:
Bucky.request.transforms.enable('soup', function(url){ return url.split('').reverse().join(''); })
```

Enabled tests will be added to the beginning of the `enabled` list, meaning they will be executed before
any other tranform.  Edit the `Bucky.requests.tranforms.enabled` array if you need more specific control.

The order of the transforms is very important.  If you, for example, were to run the `id` transform before
the `guid` one, the `guid` transform wouldn't match any guid which began with a number (as the number would
have already been stripped out, making the guid the wrong length).

When you first enable request monitoring, it's a good idea to keep an eye on the Bucky logs to get
an idea of what sort of data points are being created.

### App Server

This project pushes data to the Bucky Server.

[Server Documentation](http://github.hubspot.com/BuckyServer)

<script src="http://github.hubspot.com/BuckyClient/bucky.js"></script>


text:
package util;

import java.util.Collection;
import java.util.HashMap;
import java.util.Set;
import java.util.Vector;

public class Table2List<A,B extends Comparable<B>>
{

//Attributes

	private HashMap<A,Vector<B>> multimap;
	private int size;

//Constructors

	/**
	 * Constructs a new empty Table
	 */
	public Table2List()
	{
		multimap = new HashMap<A,Vector<B>>();
		size = 0;
	}

	/**
	 * Constructs a new Table that is a copy of
	 * the given Table
	 * @param m: the Table to copy
	 */
	public Table2List(Table2List<A,B> m)
	{
		multimap = new HashMap<A,Vector<B>>();
		size = m.size;
		Set<A> keys = m.keySet();
		for(A a : keys)
			multimap.put(a, new Vector<B>(m.get(a)));
	}

//Public Methods

	/**
	 * Adds the value for the given key to the Table, or
	 * upgrades the value if an equal value already exists
	 * (and if compareTo and equals differ)
	 * @param key: the key to add to the Table
	 * @param value: the value to add to the Table
	 */
	public void add(A key, B value)
	{
		Vector<B> list = multimap.get(key);
		if(!contains(key,value))
			size++;
		if(list == null)
		{
			list = new Vector<B>(0,1);
			list.add(value);
			multimap.put(key, list);
		}
		else
		{
			int index = list.indexOf(value);
			if(index == -1)
				list.add(value);
			else if(value.compareTo(list.get(index)) > 0)
			{
				list.remove(index);
				list.add(value);
			}
		}
	}

	/**
	 * Adds the value for the given key to the Table
	 * @param key: the key to add to the Table
	 * @param values: the value to add to the Table
	 */
	public void addAll(A key, Collection<B> values)
	{
		for(B val : values)
			add(key, val);
	}

	/**
	 * @param key: the key to search in the Table
	 * @return whether the Table contains the key
	 */
	public boolean contains(A key)
	{
		return multimap.containsKey(key);
	}

	/**
	 * @param key: the key to search in the Table
	 * @param value: the value to search in the Table
	 * @return whether the Table contains an entry with the key and value
	 */
	public boolean contains(A key, B value)
	{
		return multimap.containsKey(key) &&
			multimap.get(key).contains(value);
	}

	/**
	 * @param key: the key to search in the Table
	 * @return the number of entries with key
	 */
	public int entryCount(A key)
	{
		Vector<B> list = multimap.get(key);
		if(list == null)
			return 0;
		return list.size();
	}

	/**
	 * @param key: the key to search in the Table
	 * @return the Vector with all entries for key
	 */
	public Vector<B> get(A key)
	{
		return multimap.get(key);
	}

	/**
	 * @return the set of keys in the Table
	 */
	public Set<A> keySet()
	{
		return multimap.keySet();
	}

	/**
	 * @return the number of keys in the Table
	 */
	public int keyCount()
	{
		return multimap.size();
	}

	/**
	 * Removes all values for the given key
	 * @param key: the key to remove from the Table
	 */
	public void remove(A key)
	{
		if(multimap.get(key) != null)
			size -= multimap.get(key).size();
		multimap.remove(key);
	}

	/**
	 * Removes the given value for the given key
	 * @param key: the key to search in the Table
	 * @param value: the value to remove from the Table
	 */
	public void remove(A key, B value)
	{
		Vector<B> values = multimap.get(key);
		if(values != null)
		{
			values.remove(value);
			size--;
		}
	}

	/**
	 * @return the total number of entries in the Table
	 */
	public int size()
	{
		return size;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.bitdecay.jump.collision;

import com.bitdecay.jump.BitBody;
import com.bitdecay.jump.geom.BitPoint;
import com.bitdecay.jump.geom.GeomUtils;
import com.bitdecay.jump.geom.MathUtils;
import com.bitdecay.jump.level.Direction;
import com.bitdecay.jump.level.TileBody;

/**
 * Created by Monday on 6/16/2016.
 */
public class CollisionUtilities {
    public static BitPoint getRelativeMovement(BitBody body, BitBody otherBody, BitPoint cumulativeResolution) {
        // this line is just taking where the body tried to move and the partially resolved position into account to
        // figure out the relative momentum.
        BitPoint bodyAttempt = body.resolutionLocked ? new BitPoint(0, 0) : body.currentAttempt;
        BitPoint otherBodyAttempt = otherBody.resolutionLocked ? new BitPoint(0, 0) : otherBody.currentAttempt;
        return bodyAttempt.plus(cumulativeResolution).minus(otherBodyAttempt);
    }

    public static boolean isTileValidCollision(TileBody otherBody, Manifold manifold, float resolutionPosition, float lastPosition) {
        if (!axisValidForNValue(manifold, otherBody)) {
            return true;
        }

        if (MathUtils.opposing(resolutionPosition, lastPosition)) {
            // all collisions should push a body backwards according to the
            // relative movement. If it's not doing so, it's not a valid case.
            return true;
        }

        if (manifold.distance < 0 && (lastPosition > resolutionPosition)) {
            return true;
        }

        if (manifold.distance > 0 && lastPosition < resolutionPosition) {
            return true;
        }

        if (otherBody.collisionAxis != null) {
            if (manifold.axis.equals(otherBody.collisionAxis)) {
                if (manifold.distance < 0) {
                    return true;
                }
            } else if (manifold.axis.equals(otherBody.collisionAxis.scale(-1))) {
                if (manifold.distance > 0) {
                    return true;
                }
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * This method finds what axis should be used for resolution. This method takes into account the relative
     * speeds of the objects being resolved. A resolution will only be applied to an object that is AGAINST
     * the relative movement between it and what it has collided against.
     *
     * This logic is here to ensure corners feel crisp when a body is landing on the edge of a platform.
     *
     * <b>NOTE:</b> Due to logic to make sure the feel is correct, there are situations (such as one-way
     * platforms) that can result in NO axis (aka the Zero-axis) being set on the resolution.
     *
     *  @param body the body being resolved
     * @param otherBody the other body that participated in the collision
     * @param cumulativeResolution the current partially built resolved position
     */
    public static Manifold solve(ManifoldBundle bundle, BitBody body, BitBody otherBody, BitPoint cumulativeResolution) {
        bundle.getCandidates().sort((o1, o2) -> Float.compare(Math.abs(o1.distance), Math.abs(o2.distance)));

        BitPoint relativeMovement = CollisionUtilities.getRelativeMovement(body, otherBody, cumulativeResolution);

        float dotProd;
        for (Manifold manifold : bundle.getCandidates()) {
            dotProd = relativeMovement.dot(manifold.axis);
            if (dotProd != 0 && !MathUtils.sameSign(dotProd, manifold.distance)) {
                if (otherBody instanceof TileBody) {
                    // confirm that body came from past this thing
                    float resolutionPosition = body.aabb.xy.plus(cumulativeResolution).plus(manifold.result).dot(manifold.axis);
                    float lastPosition = body.lastPosition.dot(manifold.axis);

                    if (CollisionUtilities.isTileValidCollision((TileBody) otherBody, manifold, resolutionPosition, lastPosition)) {
                        continue;
                    }
                }
                return manifold;
            }
        }
        /*
         * This is a fallback, I can't think of a scenario where we would get here, but better to do
         * something than to leave ourselves open to an NPE
         */
        return GeomUtils.ZERO_MANIFOLD;
    }

    public static boolean axisValidForNValue(Manifold axisOver, TileBody body) {
        if (axisOver.axis.equals(GeomUtils.X_AXIS) && (body.nValue & Direction.RIGHT) == 0) {
            return true;
        } else if (axisOver.axis.equals(GeomUtils.NEG_X_AXIS) && (body.nValue & Direction.LEFT) == 0) {
            return true;
        } else if (axisOver.axis.equals(GeomUtils.Y_AXIS) && (body.nValue & Direction.UP) == 0) {
            return true;
        } else if (axisOver.axis.equals(GeomUtils.NEG_Y_AXIS) && (body.nValue & Direction.DOWN) == 0) {
            return true;
        } else {
            return false;
        }
    }

    public static Manifold getSolutionCandidate(BitBody body, BitBody against, BitPoint cumulativeResolution) {
        ManifoldBundle bundle = ProjectionUtilities.getBundle(body.aabb.copyOf().translate(cumulativeResolution), against.aabb);
        if (bundle == null) {
            return GeomUtils.ZERO_MANIFOLD;
        } else {
            return solve(bundle, body, against, cumulativeResolution);
        }
    }
}


text:
using Basement.BLFramework.Core.Context;
using Basement.BLFramework.Core.Factories;
using Basement.BLFramework.Core.Util;
using Basement.Common;

namespace Basement.BLFramework.Essential.Rewards.Result
{
    public class WrappedRewardResult : RewardResult
    {
        public IRewardResult rewardResult { get; private set; }

        public WrappedRewardResult(string type, IRewardResult rewardResult, IContext context = null)
            : base(type, context)
        {
            this.rewardResult = rewardResult;
        }

        public WrappedRewardResult(RawNode node, IContext context) : base(node, context)
        {
            rewardResult = FactoryManager.Build<RewardResult>(node.GetNode("result"), context);
        }

        public override object Serialize()
        {
            return SerializeUtil.Dict().SetArgs("type", type, "result", rewardResult.Serialize());
        }
    }
}


text:
short-description: Automatic modification of the build system files
...

# Meson file rewriter

Since version 0.50.0, Meson has the functionality to perform some
basic modification on the `meson.build` files from the command line.
The currently supported operations are:

- For build targets:
  - Add/Remove source files
  - Add/Remove targets
  - Modify a select set of kwargs
  - Print some JSON information
- For dependencies:
  - Modify a select set of kwargs
- For the project function:
  - Modify a select set of kwargs
  - Modify the default options list

The rewriter has both, a normal command line interface and a "script
mode". The normal CLI is mostly designed for everyday use. The "script
mode", on the other hand, is meant to be used by external programs
(IDEs, graphical frontends, etc.)

The rewriter itself is considered stable, however the user interface
and the "script mode" API might change in the future. These changes
may also break backwards comaptibility to older releases.

We are also open to suggestions for API improvements.

## Using the rewriter

All rewriter functions are accessed via `meson rewrite`. The Meson
rewriter assumes that it is run inside the project root directory. If
this isn't the case, use `--sourcedir` to specify the actual project
source directory.

### Adding and removing sources

The most common operations will probably be the adding and removing of source
files to a build target. This can be easily done with:

```bash
meson rewrite target <target name/id> {add/rm} [list of sources]
```

For instance, given the following example

```meson
src = ['main.cpp', 'fileA.cpp']

exe1 = executable('testExe', src)
```

the source `fileB.cpp` can be added with:

```bash
meson rewrite target testExe add fileB.cpp
```

After executing this command, the new `meson.build` will look like this:

```meson
src = ['main.cpp', 'fileA.cpp', 'fileB.cpp']

exe1 = executable('testExe', src)
```

In this case, `exe1` could also have been used for the target name.
This is possible because the rewriter also searches for assignments
and unique Meson IDs, which can be acquired with introspection. If
there are multiple targets with the same name, Meson will do nothing
and print an error message.

For more information see the help output of the rewriter target
command.

### Setting the project version

It is also possible to set kwargs of specific functions with the
rewriter. The general command for setting or removing kwargs is:

```bash
meson rewrite kwargs {set/delete} <function type> <function ID> <key1> <value1> <key2> <value2> ...
```

For instance, setting the project version can be achieved with this command:

```bash
meson rewrite kwargs set project / version 1.0.0
```

Currently, only the following function types are supported:

- dependency
- target (any build target, the function ID is the target name/ID)
- project (the function ID must be `/` since project() can only be called once)

For more information see the help output of the rewrite kwargs command.

Note msys bash may expand `/` to a path. Passing `//` will be
converted to `/` by msys bash but in order to keep usage
shell-agnostic, the rewrite command also allows `//` as the function
ID such that it will work in both msys bash and other shells.

### Setting the project default options

For setting and deleting default options, use the following command:

```bash
meson rewrite default-options {set/delete} <opt1> <value1> <opt2> <value2> ...
```

## Limitations

Rewriting a Meson file is not guaranteed to keep the indentation of
the modified functions. Additionally, comments inside a modified
statement will be removed. Furthermore, all source files will be
sorted alphabetically.

For instance adding `e.c` to srcs in the following code

```meson
# Important comment

srcs = [
'a.c', 'c.c', 'f.c',
# something important about b
       'b.c', 'd.c', 'g.c'
]

# COMMENT
```

would result in the following code:

```meson
# Important comment

srcs = [
  'a.c',
  'b.c',
  'c.c',
  'd.c',
  'e.c',
  'f.c',
  'g.c'
]

# COMMENT
```

## Using the "script mode"

The "script mode" should be the preferred API for third party
programs, since it offers more flexibility and higher API stability.
The "scripts" are stored in JSON format and executed with `meson
rewrite command <JSON file or string>`.

The JSON format is defined as follows:

```json
[
  {
    "type": "function to execute",
    ...
  }, {
    "type": "other function",
    ...
  },
  ...
]
```

Each object in the main array must have a `type` entry which specifies which
function should be executed.

Currently, the following functions are supported:

- target
- kwargs
- default_options

### Target modification format

The format for the type `target` is defined as follows:

```json
{
  "type": "target",
  "target": "target ID/name/assignment variable",
  "operation": "one of ['src_add', 'src_rm', 'target_rm', 'target_add', 'info']",
  "sources": ["list", "of", "source", "files", "to", "add, remove"],
  "subdir": "subdir where the new target should be added (only has an effect for operation 'tgt_add')",
  "target_type": "function name of the new target -- same as in the CLI (only has an effect for operation 'tgt_add')"
}
```

The keys `sources`, `subdir` and `target_type` are optional.

### kwargs modification format

The format for the type `target` is defined as follows:

```json
{
  "type": "kwargs",
  "function": "one of ['dependency', 'target', 'project']",
  "id": "function ID",
  "operation": "one of ['set', 'delete', 'add', 'remove', 'remove_regex', 'info']",
  "kwargs": {
    "key1": "value1",
    "key2": "value2",
    ...
  }
}
```

### Default options modification format

The format for the type `default_options` is defined as follows:

```json
{
  "type": "default_options",
  "operation": "one of ['set', 'delete']",
  "options": {
    "opt1": "value1",
    "opt2": "value2",
    ...
  }
}
```

For operation `delete`, the values of the `options` can be anything
(including `null`)

## Extracting information

The rewriter also offers operation `info` for the types `target` and
`kwargs`. When this operation is used, Meson will print a JSON dump to
stderr, containing all available information to the rewriter about the
build target / function kwargs in question.

The output format is currently experimental and may change in the future.


text:
module API
  module Helpers
    PRIVATE_TOKEN_HEADER = "HTTP_PRIVATE_TOKEN"
    PRIVATE_TOKEN_PARAM = :private_token
    SUDO_HEADER ="HTTP_SUDO"
    SUDO_PARAM = :sudo

    def parse_boolean(value)
      [ true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON' ].include?(value)
    end

    def current_user
      private_token = (params[PRIVATE_TOKEN_PARAM] || env[PRIVATE_TOKEN_HEADER]).to_s
      @current_user ||= (User.find_by(authentication_token: private_token) || doorkeeper_guard)

      unless @current_user && Gitlab::UserAccess.allowed?(@current_user)
        return nil
      end

      identifier = sudo_identifier()

      # If the sudo is the current user do nothing
      if identifier && !(@current_user.id == identifier || @current_user.username == identifier)
        render_api_error!('403 Forbidden: Must be admin to use sudo', 403) unless @current_user.is_admin?
        @current_user = User.by_username_or_id(identifier)
        not_found!("No user id or username for: #{identifier}") if @current_user.nil?
      end

      @current_user
    end

    def sudo_identifier()
      identifier ||= params[SUDO_PARAM] || env[SUDO_HEADER]

      # Regex for integers
      if !!(identifier =~ /^[0-9]+$/)
        identifier.to_i
      else
        identifier
      end
    end

    def user_project
      @project ||= find_project(params[:id])
      @project || not_found!("Project")
    end

    def find_project(id)
      project = Project.find_with_namespace(id) || Project.find_by(id: id)

      if project && can?(current_user, :read_project, project)
        project
      else
        nil
      end
    end

    def project_service
      @project_service ||= begin
        underscored_service = params[:service_slug].underscore

        if Service.available_services_names.include?(underscored_service)
          user_project.build_missing_services

          service_method = "#{underscored_service}_service"

          send_service(service_method)
        end
      end

      @project_service || not_found!("Service")
    end

    def send_service(service_method)
      user_project.send(service_method)
    end

    def service_attributes
      @service_attributes ||= project_service.fields.inject([]) do |arr, hash|
        arr << hash[:name].to_sym
      end
    end

    def find_group(id)
      begin
        group = Group.find(id)
      rescue ActiveRecord::RecordNotFound
        group = Group.find_by!(path: id)
      end

      if can?(current_user, :read_group, group)
        group
      else
        not_found!('Group')
      end
    end

    def paginate(relation)
      relation.page(params[:page]).per(params[:per_page].to_i).tap do |data|
        add_pagination_headers(data)
      end
    end

    def authenticate!
      unauthorized! unless current_user
    end

    def authenticate_by_gitlab_shell_token!
      input = params['secret_token'].try(:chomp)
      unless Devise.secure_compare(secret_token, input)
        unauthorized!
      end
    end

    def authenticated_as_admin!
      forbidden! unless current_user.is_admin?
    end

    def authorize!(action, subject)
      forbidden! unless abilities.allowed?(current_user, action, subject)
    end

    def authorize_push_project
      authorize! :push_code, user_project
    end

    def authorize_admin_project
      authorize! :admin_project, user_project
    end

    def require_gitlab_workhorse!
      unless env['HTTP_GITLAB_WORKHORSE'].present?
        forbidden!('Request should be executed via GitLab Workhorse')
      end
    end

    def can?(object, action, subject)
      abilities.allowed?(object, action, subject)
    end

    # Checks the occurrences of required attributes, each attribute must be present in the params hash
    # or a Bad Request error is invoked.
    #
    # Parameters:
    #   keys (required) - A hash consisting of keys that must be present
    def required_attributes!(keys)
      keys.each do |key|
        bad_request!(key) unless params[key].present?
      end
    end

    def attributes_for_keys(keys, custom_params = nil)
      params_hash = custom_params || params
      attrs = {}
      keys.each do |key|
        if params_hash[key].present? or (params_hash.has_key?(key) and params_hash[key] == false)
          attrs[key] = params_hash[key]
        end
      end
      ActionController::Parameters.new(attrs).permit!
    end

    # Helper method for validating all labels against its names
    def validate_label_params(params)
      errors = {}

      if params[:labels].present?
        params[:labels].split(',').each do |label_name|
          label = user_project.labels.create_with(
            color: Label::DEFAULT_COLOR).find_or_initialize_by(
              title: label_name.strip)

          if label.invalid?
            errors[label.title] = label.errors
          end
        end
      end

      errors
    end

    def validate_access_level?(level)
      Gitlab::Access.options_with_owner.values.include? level.to_i
    end

    def issuable_order_by
      if params["order_by"] == 'updated_at'
        'updated_at'
      else
        'created_at'
      end
    end

    def issuable_sort
      if params["sort"] == 'asc'
        :asc
      else
        :desc
      end
    end

    def filter_by_iid(items, iid)
      items.where(iid: iid)
    end

    # error helpers

    def forbidden!(reason = nil)
      message = ['403 Forbidden']
      message << " - #{reason}" if reason
      render_api_error!(message.join(' '), 403)
    end

    def bad_request!(attribute)
      message = ["400 (Bad request)"]
      message << "\"" + attribute.to_s + "\" not given"
      render_api_error!(message.join(' '), 400)
    end

    def not_found!(resource = nil)
      message = ["404"]
      message << resource if resource
      message << "Not Found"
      render_api_error!(message.join(' '), 404)
    end

    def unauthorized!
      render_api_error!('401 Unauthorized', 401)
    end

    def not_allowed!
      render_api_error!('405 Method Not Allowed', 405)
    end

    def conflict!(message = nil)
      render_api_error!(message || '409 Conflict', 409)
    end

    def file_to_large!
      render_api_error!('413 Request Entity Too Large', 413)
    end

    def not_modified!
      render_api_error!('304 Not Modified', 304)
    end

    def render_validation_error!(model)
      if model.errors.any?
        render_api_error!(model.errors.messages || '400 Bad Request', 400)
      end
    end

    def render_api_error!(message, status)
      error!({ 'message' => message }, status)
    end

    # Projects helpers

    def filter_projects(projects)
      # If the archived parameter is passed, limit results accordingly
      if params[:archived].present?
        projects = projects.where(archived: parse_boolean(params[:archived]))
      end

      if params[:search].present?
        projects = projects.search(params[:search])
      end

      if params[:visibility].present?
        projects = projects.search_by_visibility(params[:visibility])
      end

      projects.reorder(project_order_by => project_sort)
    end

    def project_order_by
      order_fields = %w(id name path created_at updated_at last_activity_at)

      if order_fields.include?(params['order_by'])
        params['order_by']
      else
        'created_at'
      end
    end

    def project_sort
      if params["sort"] == 'asc'
        :asc
      else
        :desc
      end
    end

    # file helpers

    def uploaded_file(field, uploads_path)
      if params[field]
        bad_request!("#{field} is not a file") unless params[field].respond_to?(:filename)
        return params[field]
      end

      return nil unless params["#{field}.path"] && params["#{field}.name"]

      # sanitize file paths
      # this requires all paths to exist
      required_attributes! %W(#{field}.path)
      uploads_path = File.realpath(uploads_path)
      file_path = File.realpath(params["#{field}.path"])
      bad_request!('Bad file path') unless file_path.start_with?(uploads_path)

      UploadedFile.new(
        file_path,
        params["#{field}.name"],
        params["#{field}.type"] || 'application/octet-stream',
      )
    end

    def present_file!(path, filename, content_type = 'application/octet-stream')
      filename ||= File.basename(path)
      header['Content-Disposition'] = "attachment; filename=#{filename}"
      header['Content-Transfer-Encoding'] = 'binary'
      content_type content_type

      # Support download acceleration
      case headers['X-Sendfile-Type']
      when 'X-Sendfile'
        header['X-Sendfile'] = path
        body
      else
        file FileStreamer.new(path)
      end
    end

    private

    def add_pagination_headers(paginated_data)
      header 'X-Total',       paginated_data.total_count.to_s
      header 'X-Total-Pages', paginated_data.total_pages.to_s
      header 'X-Per-Page',    paginated_data.limit_value.to_s
      header 'X-Page',        paginated_data.current_page.to_s
      header 'X-Next-Page',   paginated_data.next_page.to_s
      header 'X-Prev-Page',   paginated_data.prev_page.to_s
      header 'Link',          pagination_links(paginated_data)
    end

    def pagination_links(paginated_data)
      request_url = request.url.split('?').first
      request_params = params.clone
      request_params[:per_page] = paginated_data.limit_value

      links = []

      request_params[:page] = paginated_data.current_page - 1
      links << %(<#{request_url}?#{request_params.to_query}>; rel="prev") unless paginated_data.first_page?

      request_params[:page] = paginated_data.current_page + 1
      links << %(<#{request_url}?#{request_params.to_query}>; rel="next") unless paginated_data.last_page?

      request_params[:page] = 1
      links << %(<#{request_url}?#{request_params.to_query}>; rel="first")

      request_params[:page] = paginated_data.total_pages
      links << %(<#{request_url}?#{request_params.to_query}>; rel="last")

      links.join(', ')
    end

    def abilities
      @abilities ||= begin
                       abilities = Six.new
                       abilities << Ability
                       abilities
                     end
    end

    def secret_token
      File.read(Gitlab.config.gitlab_shell.secret_file).chomp
    end

    def handle_member_errors(errors)
      error!(errors[:access_level], 422) if errors[:access_level].any?
      not_found!(errors)
    end
  end
end


text:
import { registerSubclass } from './Element';
import { HTMLElement } from './HTMLElement';
import { reflectProperties } from './enhanceElement';
import { HTMLInputLabelsMixin } from './HTMLInputLabelsMixin';
import { TransferrableKeys } from '../../transfer/TransferrableKeys';

export class HTMLProgressElement extends HTMLElement {
  private [TransferrableKeys.indeterminate]: boolean = true;
  private [TransferrableKeys.value]: number = 0;
  private dirtyValue: boolean = false;

  get position(): number {
    return this[TransferrableKeys.indeterminate] ? -1 : this.value / this.max;
  }

  get value(): number {
    return !this.dirtyValue ? Number(this.getAttribute('value')) || 0 : this[TransferrableKeys.value];
  }

  set value(value: number) {
    this[TransferrableKeys.indeterminate] = false;
    this[TransferrableKeys.value] = value;
    this.dirtyValue = true;
    // TODO(KB) This is a property mutation needing tracked.
  }
}
registerSubclass('progress', HTMLProgressElement);
HTMLInputLabelsMixin(HTMLProgressElement);

// Reflected Properties
// HTMLModElement.max => number, reflected attribute
reflectProperties([{ max: [1] }], HTMLProgressElement);


text:
package com.navercorp.pinpoint.bootstrap.config;

import com.navercorp.pinpoint.bootstrap.util.NumberUtils;
import com.navercorp.pinpoint.bootstrap.util.spring.PropertyPlaceholderHelper;
import com.navercorp.pinpoint.common.annotations.VisibleForTesting;
import com.navercorp.pinpoint.common.util.StringUtils;
import com.navercorp.pinpoint.common.util.logger.CommonLogger;
import com.navercorp.pinpoint.common.util.PropertyUtils;
import com.navercorp.pinpoint.common.util.logger.StdoutCommonLoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * @author emeroad
 * @author netspider
 */
public class DefaultProfilerConfig implements ProfilerConfig {
    private static final CommonLogger logger = StdoutCommonLoggerFactory.INSTANCE.getLogger(DefaultProfilerConfig.class.getName());
    private static final String DEFAULT_IP = "127.0.0.1";

    private final Properties properties;
    private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");

    @Deprecated
    public static final String INSTRUMENT_ENGINE_JAVASSIST = "JAVASSIST";
    public static final String INSTRUMENT_ENGINE_ASM = "ASM";

    public static final int DEFAULT_AGENT_STAT_COLLECTION_INTERVAL_MS = 5 * 1000;
    public static final int DEFAULT_NUM_AGENT_STAT_BATCH_SEND = 6;

    public interface ValueResolver {
        String resolve(String value, Properties properties);
    }

    private static class BypassResolver implements ValueResolver {
        public static final ValueResolver RESOLVER = new BypassResolver();

        @Override
        public String resolve(String value, Properties properties) {
            return value;
        }
    }

    private class PlaceHolderResolver implements ValueResolver {
        @Override
        public String resolve(String value, Properties properties) {
            if (value == null) {
                return null;
            }
            return propertyPlaceholderHelper.replacePlaceholders(value, properties);
        }
    }

    public static ProfilerConfig load(String pinpointConfigFileName) throws IOException {
        try {
            Properties properties = PropertyUtils.loadProperty(pinpointConfigFileName);
            return new DefaultProfilerConfig(properties);
        } catch (FileNotFoundException fe) {
            if (logger.isWarnEnabled()) {
                logger.warn(pinpointConfigFileName + " file does not exist. Please check your configuration.");
            }
            throw fe;
        } catch (IOException e) {
            if (logger.isWarnEnabled()) {
                logger.warn(pinpointConfigFileName + " file I/O error. Error:" + e.getMessage(), e);
            }
            throw e;
        }
    }

    private boolean profileEnable = false;

    private String profileInstrumentEngine = INSTRUMENT_ENGINE_ASM;
    private boolean instrumentMatcherEnable = true;
    private InstrumentMatcherCacheConfig instrumentMatcherCacheConfig = new InstrumentMatcherCacheConfig();

    private int interceptorRegistrySize = 1024 * 8;

    @VisibleForTesting
    private boolean staticResourceCleanup = false;

    private String collectorSpanServerIp = DEFAULT_IP;
    private int collectorSpanServerPort = 9996;

    private String collectorStatServerIp = DEFAULT_IP;
    private int collectorStatServerPort = 9995;

    private String collectorTcpServerIp = DEFAULT_IP;
    private int collectorTcpServerPort = 9994;

    private int spanDataSenderWriteQueueSize = 1024 * 5;
    private int spanDataSenderSocketSendBufferSize = 1024 * 64 * 16;
    private int spanDataSenderSocketTimeout = 1000 * 3;
    private int spanDataSenderChunkSize = 1024 * 16;
    private String spanDataSenderTransportType = "UDP";
    private String spanDataSenderSocketType = "OIO";

    private int statDataSenderWriteQueueSize = 1024 * 5;
    private int statDataSenderSocketSendBufferSize = 1024 * 64 * 16;
    private int statDataSenderSocketTimeout = 1000 * 3;
    private int statDataSenderChunkSize = 1024 * 16;
    private String statDataSenderTransportType = "UDP";
    private String statDataSenderSocketType = "OIO";

    private boolean tcpDataSenderCommandAcceptEnable = false;
    private boolean tcpDataSenderCommandActiveThreadEnable = false;
    private boolean tcpDataSenderCommandActiveThreadCountEnable = false;
    private boolean tcpDataSenderCommandActiveThreadDumpEnable = false;
    private boolean tcpDataSenderCommandActiveThreadLightDumpEnable = false;

    private boolean traceAgentActiveThread = true;

    private boolean traceAgentDataSource = false;
    private int dataSourceTraceLimitSize = 20;

    private boolean deadlockMonitorEnable = true;
    private long deadlockMonitorInterval = 60000L;

    private int callStackMaxDepth = 512;

    private int jdbcSqlCacheSize = 1024;
    private boolean traceSqlBindValue = false;
    private int maxSqlBindValueSize = 1024;

    // Sampling
    private boolean samplingEnable = true;
    private int samplingRate = 1;

    // span buffering
    private boolean ioBufferingEnable;
    private int ioBufferingBufferSize;

    private String profileJvmVendorName;
    private String profileOsName;
    private int profileJvmStatCollectIntervalMs = DEFAULT_AGENT_STAT_COLLECTION_INTERVAL_MS;
    private int profileJvmStatBatchSendCount = DEFAULT_NUM_AGENT_STAT_BATCH_SEND;
    private boolean profilerJvmStatCollectDetailedMetrics;

    private Filter<String> profilableClassFilter = new SkipFilter<String>();

    private final long DEFAULT_AGENT_INFO_SEND_RETRY_INTERVAL = 5 * 60 * 1000L;
    private long agentInfoSendRetryInterval = DEFAULT_AGENT_INFO_SEND_RETRY_INTERVAL;

    private String applicationServerType;
    private List<String> applicationTypeDetectOrder = Collections.emptyList();
    private List<String> disabledPlugins = Collections.emptyList();

    private boolean propagateInterceptorException = false;
    private boolean supportLambdaExpressions = true;

    private boolean proxyHttpHeaderEnable = true;

    private List<String> httpStatusCodeErrors = Collections.emptyList();

    private String injectionModuleFactoryClazzName = null;

    public DefaultProfilerConfig() {
        this.properties = new Properties();
    }

    public DefaultProfilerConfig(Properties properties) {
        if (properties == null) {
            throw new NullPointerException("properties must not be null");
        }
        this.properties = properties;
        readPropertyValues();
    }

    @Override
    public int getInterceptorRegistrySize() {
        return interceptorRegistrySize;
    }

    @Override
    public String getCollectorSpanServerIp() {
        return collectorSpanServerIp;
    }

    @Override
    public int getCollectorSpanServerPort() {
        return collectorSpanServerPort;
    }

    @Override
    public String getCollectorStatServerIp() {
        return collectorStatServerIp;
    }

    @Override
    public int getCollectorStatServerPort() {
        return collectorStatServerPort;
    }

    @Override
    public String getCollectorTcpServerIp() {
        return collectorTcpServerIp;
    }

    @Override
    public int getCollectorTcpServerPort() {
        return collectorTcpServerPort;
    }

    @Override
    public int getStatDataSenderWriteQueueSize() {
        return statDataSenderWriteQueueSize;
    }

    @Override
    public int getStatDataSenderSocketSendBufferSize() {
        return statDataSenderSocketSendBufferSize;
    }

    @Override
    public int getStatDataSenderSocketTimeout() {
        return statDataSenderSocketTimeout;
    }

    @Override
    public String getStatDataSenderSocketType() {
        return statDataSenderSocketType;
    }

    @Override
    public String getStatDataSenderTransportType() {
        return statDataSenderTransportType;
    }

    @Override
    public int getSpanDataSenderWriteQueueSize() {
        return spanDataSenderWriteQueueSize;
    }

    @Override
    public int getSpanDataSenderSocketSendBufferSize() {
        return spanDataSenderSocketSendBufferSize;
    }

    @Override
    public boolean isTcpDataSenderCommandAcceptEnable() {
        return tcpDataSenderCommandAcceptEnable;
    }

    @Override
    public boolean isTcpDataSenderCommandActiveThreadEnable() {
        return tcpDataSenderCommandActiveThreadEnable;
    }

    @Override
    public boolean isTcpDataSenderCommandActiveThreadCountEnable() {
        return tcpDataSenderCommandActiveThreadCountEnable;
    }

    @Override
    public boolean isTcpDataSenderCommandActiveThreadDumpEnable() {
        return tcpDataSenderCommandActiveThreadDumpEnable;
    }

    @Override
    public boolean isTcpDataSenderCommandActiveThreadLightDumpEnable() {
        return tcpDataSenderCommandActiveThreadLightDumpEnable;
    }

    @Override
    public boolean isTraceAgentActiveThread() {
        return traceAgentActiveThread;
    }

    @Override
    public boolean isTraceAgentDataSource() {
        return traceAgentDataSource;
    }

    @Override
    public int getDataSourceTraceLimitSize() {
        return dataSourceTraceLimitSize;
    }

    @Override
    public boolean isDeadlockMonitorEnable() {
        return deadlockMonitorEnable;
    }

    @Override
    public long getDeadlockMonitorInterval() {
        return deadlockMonitorInterval;
    }

    @Override
    public int getSpanDataSenderSocketTimeout() {
        return spanDataSenderSocketTimeout;
    }

    @Override
    public String getSpanDataSenderSocketType() {
        return spanDataSenderSocketType;
    }

    @Override
    public String getSpanDataSenderTransportType() {
        return spanDataSenderTransportType;
    }

    @Override
    public int getSpanDataSenderChunkSize() {
        return spanDataSenderChunkSize;
    }

    @Override
    public int getStatDataSenderChunkSize() {
        return statDataSenderChunkSize;
    }

    @Override
    public boolean isProfileEnable() {
        return profileEnable;
    }

    @Override
    public int getJdbcSqlCacheSize() {
        return jdbcSqlCacheSize;
    }

    @Override
    public boolean isTraceSqlBindValue() {
        return traceSqlBindValue;
    }

    @Override
    public int getMaxSqlBindValueSize() {
        return maxSqlBindValueSize;
    }

    @Override
    public boolean isSamplingEnable() {
        return samplingEnable;
    }

    @Override
    public int getSamplingRate() {
        return samplingRate;
    }

    @Override
    public boolean isIoBufferingEnable() {
        return ioBufferingEnable;
    }

    @Override
    public int getIoBufferingBufferSize() {
        return ioBufferingBufferSize;
    }

    @Override
    public String getProfilerJvmVendorName() {
        return profileJvmVendorName;
    }

    @Override
    public String getProfilerOSName() {
        return profileOsName;
    }

    @Override
    public int getProfileJvmStatCollectIntervalMs() {
        return profileJvmStatCollectIntervalMs;
    }

    @Override
    public int getProfileJvmStatBatchSendCount() {
        return profileJvmStatBatchSendCount;
    }

    @Override
    public boolean isProfilerJvmStatCollectDetailedMetrics() {
        return profilerJvmStatCollectDetailedMetrics;
    }

    @Override
    public long getAgentInfoSendRetryInterval() {
        return agentInfoSendRetryInterval;
    }

    @Override
    public boolean getStaticResourceCleanup() {
        return staticResourceCleanup;
    }

    public void setStaticResourceCleanup(boolean staticResourceCleanup) {
        this.staticResourceCleanup = staticResourceCleanup;
    }

    @Override
    public Filter<String> getProfilableClassFilter() {
        return profilableClassFilter;
    }

    @Override
    public List<String> getApplicationTypeDetectOrder() {
        return applicationTypeDetectOrder;
    }

    @Override
    public List<String> getDisabledPlugins() {
        return disabledPlugins;
    }

    @Override
    public String getApplicationServerType() {
        return applicationServerType;
    }

    public void setApplicationServerType(String applicationServerType) {
        this.applicationServerType = applicationServerType;
    }

    @Override
    public int getCallStackMaxDepth() {
        return callStackMaxDepth;
    }

    public void setCallStackMaxDepth(int callStackMaxDepth) {
        this.callStackMaxDepth = callStackMaxDepth;
    }

    @Override
    public boolean isPropagateInterceptorException() {
        return propagateInterceptorException;
    }

    @Override
    public String getProfileInstrumentEngine() {
        return profileInstrumentEngine;
    }

    @Override
    public boolean isSupportLambdaExpressions() {
        return supportLambdaExpressions;
    }

    @Override
    public boolean isInstrumentMatcherEnable() {
        return instrumentMatcherEnable;
    }

    @Override
    public InstrumentMatcherCacheConfig getInstrumentMatcherCacheConfig() {
        return instrumentMatcherCacheConfig;
    }

    @Override
    public boolean isProxyHttpHeaderEnable() {
        return proxyHttpHeaderEnable;
    }

    @Override
    public List<String> getHttpStatusCodeErrors() {
        return httpStatusCodeErrors;
    }

    @Override
    public String getInjectionModuleFactoryClazzName() {
        return injectionModuleFactoryClazzName;
    }

    // for test
    void readPropertyValues() {
        // TODO : use Properties' default value instead of using a temp variable.
        final ValueResolver placeHolderResolver = new PlaceHolderResolver();

        this.profileEnable = readBoolean("profiler.enable", true);
        this.profileInstrumentEngine = readString("profiler.instrument.engine", INSTRUMENT_ENGINE_ASM);
        this.instrumentMatcherEnable = readBoolean("profiler.instrument.matcher.enable", true);

        this.instrumentMatcherCacheConfig.setInterfaceCacheSize(readInt("profiler.instrument.matcher.interface.cache.size", 4));
        this.instrumentMatcherCacheConfig.setInterfaceCacheEntrySize(readInt("profiler.instrument.matcher.interface.cache.entry.size", 16));
        this.instrumentMatcherCacheConfig.setAnnotationCacheSize(readInt("profiler.instrument.matcher.annotation.cache.size", 4));
        this.instrumentMatcherCacheConfig.setAnnotationCacheEntrySize(readInt("profiler.instrument.matcher.annotation.cache.entry.size", 4));
        this.instrumentMatcherCacheConfig.setSuperCacheSize(readInt("profiler.instrument.matcher.super.cache.size", 4));
        this.instrumentMatcherCacheConfig.setSuperCacheEntrySize(readInt("profiler.instrument.matcher.super.cache.entry.size", 4));

        this.interceptorRegistrySize = readInt("profiler.interceptorregistry.size", 1024 * 8);

        this.collectorSpanServerIp = readString("profiler.collector.span.ip", DEFAULT_IP, placeHolderResolver);
        this.collectorSpanServerPort = readInt("profiler.collector.span.port", 9996);

        this.collectorStatServerIp = readString("profiler.collector.stat.ip", DEFAULT_IP, placeHolderResolver);
        this.collectorStatServerPort = readInt("profiler.collector.stat.port", 9995);

        this.collectorTcpServerIp = readString("profiler.collector.tcp.ip", DEFAULT_IP, placeHolderResolver);
        this.collectorTcpServerPort = readInt("profiler.collector.tcp.port", 9994);

        this.spanDataSenderWriteQueueSize = readInt("profiler.spandatasender.write.queue.size", 1024 * 5);
        this.spanDataSenderSocketSendBufferSize = readInt("profiler.spandatasender.socket.sendbuffersize", 1024 * 64 * 16);
        this.spanDataSenderSocketTimeout = readInt("profiler.spandatasender.socket.timeout", 1000 * 3);
        this.spanDataSenderChunkSize = readInt("profiler.spandatasender.chunk.size", 1024 * 16);
        this.spanDataSenderSocketType = readString("profiler.spandatasender.socket.type", "OIO");
        this.spanDataSenderTransportType = readString("profiler.spandatasender.transport.type", "UDP");

        this.statDataSenderWriteQueueSize = readInt("profiler.statdatasender.write.queue.size", 1024 * 5);
        this.statDataSenderSocketSendBufferSize = readInt("profiler.statdatasender.socket.sendbuffersize", 1024 * 64 * 16);
        this.statDataSenderSocketTimeout = readInt("profiler.statdatasender.socket.timeout", 1000 * 3);
        this.statDataSenderChunkSize = readInt("profiler.statdatasender.chunk.size", 1024 * 16);
        this.statDataSenderSocketType = readString("profiler.statdatasender.socket.type", "OIO");
        this.statDataSenderTransportType = readString("profiler.statdatasender.transport.type", "UDP");

        this.tcpDataSenderCommandAcceptEnable = readBoolean("profiler.tcpdatasender.command.accept.enable", false);
        this.tcpDataSenderCommandActiveThreadEnable = readBoolean("profiler.tcpdatasender.command.activethread.enable", false);
        this.tcpDataSenderCommandActiveThreadCountEnable = readBoolean("profiler.tcpdatasender.command.activethread.count.enable", false);
        this.tcpDataSenderCommandActiveThreadDumpEnable = readBoolean("profiler.tcpdatasender.command.activethread.threaddump.enable", false);
        this.tcpDataSenderCommandActiveThreadLightDumpEnable = readBoolean("profiler.tcpdatasender.command.activethread.threadlightdump.enable", false);

        this.traceAgentActiveThread = readBoolean("profiler.pinpoint.activethread", true);

        this.traceAgentDataSource = readBoolean("profiler.pinpoint.datasource", false);
        this.dataSourceTraceLimitSize = readInt("profiler.pinpoint.datasource.tracelimitsize", 20);

        this.deadlockMonitorEnable = readBoolean("profiler.monitor.deadlock.enable", true);
        this.deadlockMonitorInterval = readLong("profiler.monitor.deadlock.interval", 60000L);

        // CallStack
        this.callStackMaxDepth = readInt("profiler.callstack.max.depth", 64);
        if (this.callStackMaxDepth < 2) {
            this.callStackMaxDepth = 2;
        }

        // JDBC
        this.jdbcSqlCacheSize = readInt("profiler.jdbc.sqlcachesize", 1024);
        this.traceSqlBindValue = readBoolean("profiler.jdbc.tracesqlbindvalue", false);

        this.samplingEnable = readBoolean("profiler.sampling.enable", true);
        this.samplingRate = readInt("profiler.sampling.rate", 1);

        // configuration for sampling and IO buffer
        this.ioBufferingEnable = readBoolean("profiler.io.buffering.enable", true);

        // it may be a problem to be here.  need to modify(delete or move or .. )  this configuration.
        this.ioBufferingBufferSize = readInt("profiler.io.buffering.buffersize", 20);

        //OS
        this.profileOsName = readString("profiler.os.name", null);

        // JVM
        this.profileJvmVendorName = readString("profiler.jvm.vendor.name", null);
        this.profileJvmStatCollectIntervalMs = readInt("profiler.jvm.stat.collect.interval", DEFAULT_AGENT_STAT_COLLECTION_INTERVAL_MS);
        this.profileJvmStatBatchSendCount = readInt("profiler.jvm.stat.batch.send.count", DEFAULT_NUM_AGENT_STAT_BATCH_SEND);
        this.profilerJvmStatCollectDetailedMetrics = readBoolean("profiler.stat.jvm.collect.detailed.metrics", false);

        this.agentInfoSendRetryInterval = readLong("profiler.agentInfo.send.retry.interval", DEFAULT_AGENT_INFO_SEND_RETRY_INTERVAL);

        // service type
        this.applicationServerType = readString("profiler.applicationservertype", null);

        // application type detector order
        this.applicationTypeDetectOrder = readList("profiler.type.detect.order");

        this.disabledPlugins = readList("profiler.plugin.disable");

        // TODO have to remove
        // profile package included in order to test "call stack view".
        // this config must not be used in service environment because the size of  profiling information will get heavy.
        // We may need to change this configuration to regular expression.
        final String profilableClass = readString("profiler.include", "");
        if (!profilableClass.isEmpty()) {
            this.profilableClassFilter = new ProfilableClassFilter(profilableClass);
        }

        this.propagateInterceptorException = readBoolean("profiler.interceptor.exception.propagate", false);
        this.supportLambdaExpressions = readBoolean("profiler.lambda.expressions.support", true);

        // proxy http header names
        this.proxyHttpHeaderEnable = readBoolean("profiler.proxy.http.header.enable", true);

        this.httpStatusCodeErrors = readList("profiler.http.status.code.errors");

        this.injectionModuleFactoryClazzName = readString("profiler.guice.module.factory", null);

        logger.info("configuration loaded successfully.");
    }

    @Override
    public String readString(String propertyName, String defaultValue) {
        return readString(propertyName, defaultValue, BypassResolver.RESOLVER);
    }

    private String readString(String propertyName, String defaultValue, ValueResolver valueResolver) {
        if (valueResolver == null) {
            throw new NullPointerException("valueResolver must not be null");
        }
        String value = properties.getProperty(propertyName, defaultValue);
        value = valueResolver.resolve(value, properties);
        if (logger.isInfoEnabled()) {
            logger.info(propertyName + "=" + value);
        }
        return value;
    }

    @Override
    public int readInt(String propertyName, int defaultValue) {
        String value = properties.getProperty(propertyName);
        int result = NumberUtils.parseInteger(value, defaultValue);
        if (logger.isInfoEnabled()) {
            logger.info(propertyName + "=" + result);
        }
        return result;
    }

    @Override
    public DumpType readDumpType(String propertyName, DumpType defaultDump) {
        String propertyValue = properties.getProperty(propertyName);
        if (propertyValue == null) {
            propertyValue = defaultDump.name();
        }
        String value = propertyValue.toUpperCase();
        DumpType result;
        try {
            result = DumpType.valueOf(value);
        } catch (IllegalArgumentException e) {
            result = defaultDump;
        }
        if (logger.isInfoEnabled()) {
            logger.info(propertyName + "=" + result);
        }
        return result;
    }

    @Override
    public long readLong(String propertyName, long defaultValue) {
        String value = properties.getProperty(propertyName);
        long result = NumberUtils.parseLong(value, defaultValue);
        if (logger.isInfoEnabled()) {
            logger.info(propertyName + "=" + result);
        }
        return result;
    }

    @Override
    public List<String> readList(String propertyName) {
        String value = properties.getProperty(propertyName);
        if (StringUtils.isEmpty(value)) {
            return Collections.emptyList();
        }
        return StringUtils.tokenizeToStringList(value, ",");
    }

    @Override
    public boolean readBoolean(String propertyName, boolean defaultValue) {
        String value = properties.getProperty(propertyName, Boolean.toString(defaultValue));
        boolean result = Boolean.parseBoolean(value);
        if (logger.isInfoEnabled()) {
            logger.info(propertyName + "=" + result);
        }
        return result;
    }

    @Override
    public Map<String, String> readPattern(String propertyNamePatternRegex) {
        final Pattern pattern = Pattern.compile(propertyNamePatternRegex);
        final Map<String, String> result = new HashMap<String, String>();
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            if (entry.getKey() instanceof String && entry.getValue() instanceof String) {
                final String key = (String) entry.getKey();
                if (pattern.matcher(key).matches()) {
                    final String value = (String) entry.getValue();
                    result.put(key, value);
                }
            }
        }

        if (logger.isInfoEnabled()) {
            logger.info(propertyNamePatternRegex + "=" + result);
        }

        return result;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("DefaultProfilerConfig{");
        sb.append("properties=").append(properties);
        sb.append(", propertyPlaceholderHelper=").append(propertyPlaceholderHelper);
        sb.append(", profileEnable=").append(profileEnable);
        sb.append(", profileInstrumentEngine='").append(profileInstrumentEngine).append('\'');
        sb.append(", instrumentMatcherEnable=").append(instrumentMatcherEnable);
        sb.append(", instrumentMatcherCacheConfig=").append(instrumentMatcherCacheConfig);
        sb.append(", interceptorRegistrySize=").append(interceptorRegistrySize);
        sb.append(", collectorSpanServerIp='").append(collectorSpanServerIp).append('\'');
        sb.append(", collectorSpanServerPort=").append(collectorSpanServerPort);
        sb.append(", collectorStatServerIp='").append(collectorStatServerIp).append('\'');
        sb.append(", collectorStatServerPort=").append(collectorStatServerPort);
        sb.append(", collectorTcpServerIp='").append(collectorTcpServerIp).append('\'');
        sb.append(", collectorTcpServerPort=").append(collectorTcpServerPort);
        sb.append(", spanDataSenderWriteQueueSize=").append(spanDataSenderWriteQueueSize);
        sb.append(", spanDataSenderSocketSendBufferSize=").append(spanDataSenderSocketSendBufferSize);
        sb.append(", spanDataSenderSocketTimeout=").append(spanDataSenderSocketTimeout);
        sb.append(", spanDataSenderChunkSize=").append(spanDataSenderChunkSize);
        sb.append(", spanDataSenderTransportType='").append(spanDataSenderTransportType).append('\'');
        sb.append(", spanDataSenderSocketType='").append(spanDataSenderSocketType).append('\'');
        sb.append(", statDataSenderWriteQueueSize=").append(statDataSenderWriteQueueSize);
        sb.append(", statDataSenderSocketSendBufferSize=").append(statDataSenderSocketSendBufferSize);
        sb.append(", statDataSenderSocketTimeout=").append(statDataSenderSocketTimeout);
        sb.append(", statDataSenderChunkSize=").append(statDataSenderChunkSize);
        sb.append(", statDataSenderTransportType='").append(statDataSenderTransportType).append('\'');
        sb.append(", statDataSenderSocketType='").append(statDataSenderSocketType).append('\'');
        sb.append(", tcpDataSenderCommandAcceptEnable=").append(tcpDataSenderCommandAcceptEnable);
        sb.append(", tcpDataSenderCommandActiveThreadEnable=").append(tcpDataSenderCommandActiveThreadEnable);
        sb.append(", tcpDataSenderCommandActiveThreadCountEnable=").append(tcpDataSenderCommandActiveThreadCountEnable);
        sb.append(", tcpDataSenderCommandActiveThreadDumpEnable=").append(tcpDataSenderCommandActiveThreadDumpEnable);
        sb.append(", tcpDataSenderCommandActiveThreadLightDumpEnable=").append(tcpDataSenderCommandActiveThreadLightDumpEnable);
        sb.append(", traceAgentActiveThread=").append(traceAgentActiveThread);
        sb.append(", traceAgentDataSource=").append(traceAgentDataSource);
        sb.append(", dataSourceTraceLimitSize=").append(dataSourceTraceLimitSize);
        sb.append(", deadlockMonitorEnable=").append(deadlockMonitorEnable);
        sb.append(", deadlockMonitorInterval=").append(deadlockMonitorInterval);
        sb.append(", callStackMaxDepth=").append(callStackMaxDepth);
        sb.append(", jdbcSqlCacheSize=").append(jdbcSqlCacheSize);
        sb.append(", traceSqlBindValue=").append(traceSqlBindValue);
        sb.append(", maxSqlBindValueSize=").append(maxSqlBindValueSize);
        sb.append(", samplingEnable=").append(samplingEnable);
        sb.append(", samplingRate=").append(samplingRate);
        sb.append(", ioBufferingEnable=").append(ioBufferingEnable);
        sb.append(", ioBufferingBufferSize=").append(ioBufferingBufferSize);
        sb.append(", profileOsName='").append(profileOsName).append('\'');
        sb.append(", profileJvmVendorName='").append(profileJvmVendorName).append('\'');
        sb.append(", profileJvmStatCollectIntervalMs=").append(profileJvmStatCollectIntervalMs);
        sb.append(", profileJvmStatBatchSendCount=").append(profileJvmStatBatchSendCount);
        sb.append(", profilerJvmStatCollectDetailedMetrics=").append(profilerJvmStatCollectDetailedMetrics);
        sb.append(", profilableClassFilter=").append(profilableClassFilter);
        sb.append(", DEFAULT_AGENT_INFO_SEND_RETRY_INTERVAL=").append(DEFAULT_AGENT_INFO_SEND_RETRY_INTERVAL);
        sb.append(", agentInfoSendRetryInterval=").append(agentInfoSendRetryInterval);
        sb.append(", applicationServerType='").append(applicationServerType).append('\'');
        sb.append(", applicationTypeDetectOrder=").append(applicationTypeDetectOrder);
        sb.append(", disabledPlugins=").append(disabledPlugins);
        sb.append(", propagateInterceptorException=").append(propagateInterceptorException);
        sb.append(", supportLambdaExpressions=").append(supportLambdaExpressions);
        sb.append(", proxyHttpHeaderEnable=").append(proxyHttpHeaderEnable);
        sb.append(", httpStatusCodeErrors=").append(httpStatusCodeErrors);
        sb.append(", injectionModuleFactoryClazzName=").append(injectionModuleFactoryClazzName);
        sb.append('}');
        return sb.toString();
    }
}


text:
namespace JustinCredible.SampleApp.Controllers {

    export class LogsListController extends BaseController<ViewModels.LogsListViewModel> {

        //#region Injection

        public static ID = "LogsListController";

        public static get $inject(): string[] {
            return [
                "$scope",
                "$ionicPopover",
                Services.Logger.ID,
                Services.UIHelper.ID
            ];
        }

        constructor(
            $scope: ng.IScope,
            private $ionicPopover: ionic.popover.IonicPopoverService,
            private Logger: Services.Logger,
            private UIHelper: Services.UIHelper) {
            super($scope, ViewModels.LogsListViewModel);
        }

        //#endregion

        private _filterMenu: ionic.popover.IonicPopoverController;

        //#region BaseController Overrides

        protected view_beforeEnter(event?: ng.IAngularEvent, eventArgs?: Interfaces.ViewEventArguments): void {
            super.view_beforeEnter(event, eventArgs);

            this.UIHelper.createPopover(LogFilterMenuController.ID)
                .then((popover: ionic.popover.IonicPopoverController) => {

                this._filterMenu = popover;
                this._filterMenu.scope.$on("filtersChanged", _.bind(this.filterMenu_filtersChanged, this));
            });

            this.viewModel.showError = true;
            this.viewModel.showWarn = true;
            this.viewModel.showFatal = true;

            this.populateViewModel(this.Logger.logs);
        }

        //#endregion

        //#region Events

        private filterMenu_filtersChanged($event: ng.IAngularEvent, filters: ViewModels.LogFilterMenuViewModel): void {

            this.viewModel.showTrace = filters.showTrace;
            this.viewModel.showDebug = filters.showDebug;
            this.viewModel.showInfo = filters.showInfo;
            this.viewModel.showWarn = filters.showWarn;
            this.viewModel.showError = filters.showError;
            this.viewModel.showFatal = filters.showFatal;

            this.populateViewModel(this.Logger.logs);
        }

        //#endregion

        //#region Private Helper Methods

        private populateViewModel(logEntries: Models.LogEntry[]): void {

            if (logEntries == null) {
                logEntries = [];
            }

            this.viewModel.logs = {};

            // First, lets sort by the time stamp ascending, then reverse
            // it so we have the most recent log entries at the top.
            logEntries = _.sortBy(logEntries, "timestamp").reverse();

            // Now use the actual log entry to create the view model.
            logEntries.forEach((logEntry: Models.LogEntry) => {
                var formattedDate: string,
                    viewModel: ViewModels.LogEntryViewModel;

                if (!this.isApplicableForCurrentFilter(logEntry)) {
                    return;
                }

                viewModel = new ViewModels.LogEntryViewModel();

                // Put the actual log entry into the view model.
                viewModel.logEntry = logEntry;

                viewModel.time = moment(logEntry.timestamp).format("h:mm:ss a");
                viewModel.icon = this.Logger.getIconForLevel(logEntry.level);
                viewModel.color = this.Logger.getColorForLevel(logEntry.level);
                viewModel.levelDisplay = this.Logger.getDisplayLevelForLevel(logEntry.level);

                // Format the date and time for display.
                formattedDate = moment(logEntry.timestamp).format("l");

                // The view model is a dictionary of formatted dates to an
                // array of log entries that happened on that date. So first,
                // we'll make sure the array exists for this date...
                if (!this.viewModel.logs[formattedDate]) {
                    this.viewModel.logs[formattedDate] = [];
                }

                // ... then we'll push this entry into that days collection.
                this.viewModel.logs[formattedDate].push(viewModel);
            });
        }

        private isApplicableForCurrentFilter(logEntry: Models.LogEntry): boolean {

            if (!logEntry || logEntry.level == null) {
                return true;
            }

            switch (logEntry.level) {
                case Models.LogLevel.TRACE:
                    return this.viewModel.showTrace;
                case Models.LogLevel.DEBUG:
                    return this.viewModel.showDebug;
                case Models.LogLevel.WARN:
                    return this.viewModel.showWarn;
                case Models.LogLevel.INFO:
                    return this.viewModel.showInfo;
                case Models.LogLevel.ERROR:
                    return this.viewModel.showError;
                case Models.LogLevel.FATAL:
                    return this.viewModel.showFatal;
                default:
                    return true;
            }
        }

        //#endregion

        //#region Controller Methods

        protected filter_click(event: ng.IAngularEvent) {

            let filters = new ViewModels.LogFilterMenuViewModel();
            filters.showTrace = this.viewModel.showTrace;
            filters.showDebug = this.viewModel.showDebug;
            filters.showInfo = this.viewModel.showInfo;
            filters.showWarn = this.viewModel.showWarn;
            filters.showError = this.viewModel.showError;
            filters.showFatal = this.viewModel.showFatal;

            this._filterMenu.scope.$broadcast("setFilters", filters);

            this._filterMenu.show(event);
        }

        protected clear_click() {
            this.UIHelper.confirm("Are you sure you want to clear the logs?", "Clear Logs").then((result: string) => {
                if (result === Constants.Buttons.Yes) {
                    this.Logger.clear();
                    this.viewModel.logs = {};
                }
            });
        }

        //#endregion
    }
}


text: virtual stock game