text:
# Insets for Jetpack Compose

[![Maven Central](https://img.shields.io/maven-central/v/com.google.accompanist/accompanist-insets)](https://search.maven.org/search?q=g:com.google.accompanist)

!!! warning
    **This library is deprecated, with official insets support in androidx.compose.foundation.** The migration guide and original documentation is below.

## Migration

The official `androidx.compose.foundation` insets support is very similar to accompanist/insets, with a few changes.

`androidx.compose.foundation` also does not disable window decor fitting, so you still need to call [`WindowCompat.setDecorFitsSystemWindows(window, false)`](https://developer.android.com/reference/androidx/core/view/WindowCompat#setDecorFitsSystemWindows(android.view.Window,%20boolean)) from your Activity.
You also still need to set the system bar backgrounds to be transparent, which can be done with our [System UI Controller](../systemuicontroller) library.

If you are using insets for IME support, you also still need to ensure that the activity's `windowSoftInputMode` is set to `adjustResize`:

```xml
<activity
      android:name=".MyActivity"
      android:windowSoftInputMode="adjustResize">
</activity>
```

## Migration steps:

1. Remove `ProvideWindowInsets` (there is no equivalent in `androidx.compose.foundation`)
1. Remove `ViewWindowInsetObserver` (there is no equivalent in `androidx.compose.foundation`)
1. Replace padding modifiers with `androidx.compose.foundation` equivalents. If using `additionalPadding` or only applying the insets to certain sides, use the corresponding [`WindowInsets.add`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets).add(androidx.compose.foundation.layout.WindowInsets)) and [`WindowInsets.only`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets).only(androidx.compose.foundation.layout.WindowInsetsSides)) extensions.
1. Replace `rememberInsetsPaddingValues` with the equivalent `WindowInsets.asPaddingValues`.
1. Replace direct calculations from `LocalWindowInsets.current` with calculations on `WindowInsets`.
1. Continue using the non-deprecated [`insets-ui`](#inset-aware-layouts-insets-ui) for now.

For reference, consult the [Migration table](#migration-table) below.

## Inset consumption

The biggest behavioral change between `accompanist/insets` and `androidx.compose.foundation` is in the consumption behavior of padding modifiers.

In `accompanist/insets`, the padding modifiers always padded the full size of the specified inset types, which led to some unintuitive duplicate padding when nesting modifiers.

For example, let's look at what happens when we have nested boxes, where the outer one has Modifier.systemBarsPadding() applied, and the inner has Modifier.imePadding():

```kotlin
Box(Modifier.systemBarsPadding()) {
    Box(Modifier.imePadding()) {
        // content
    }
}
```

Let's assume that the bottom system bar padding is `30dp`, to account for the navigation bar padding, and let's assume that when the IME is visible, the height of the IME is `150dp`.

When the IME is closed, the outer box will apply the bottom `30dp` as padding, and the inner box will apply zero additional padding, since the IME isn't visible.

When the IME opens, the outer box will continue to apply the bottom `30dp` as the system bar padding, and the inner box will now apply `150dp` bottom padding, since that is the full height of the IME.

This results in a total padding of `180dp` applied to the content, which double pads the bottom navigation bar padding.
The solutions to this issue were using `derivedWindowInsetsTypeOf`, built-in derived types like `Modifier.navigationBarsWithImePadding()`, or performing calculations manually to apply the remaining padding.

In `androidx.compose.foundation`, when the IME is open, the outer box still apply the bottom `30dp`, but the inner box will only apply the remaining `120dp` needed to have the content be padded a total of `150dp` to match the height of the IME.

This behavior can be influenced further in `androidx.compose.foundation` with [`Modifier.consumedWindowInsets()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).consumedWindowInsets(androidx.compose.foundation.layout.WindowInsets))

As a result, the equivalent of `Modifier.navigationBarsWithImePadding()` is simply `Modifier.navigationBarsPadding().imePadding()`.

## Migration table:

| accompanist/insets                                                                                | androidx.compose.foundation                                                                                |
|-----------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `ProvideWindowInsets`                                                                                | (remove)                                                                                |
| `Modifier.systemBarsPadding()`                                                                                | [`Modifier.systemBarsPadding()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).systemBarsPadding())                                                                                |
| `Modifier.systemBarsPadding(bottom = false)`                                                                                | [`Modifier.windowInsetsPadding(WindowInsets.systemBars.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top))`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.ui.Modifier).windowInsetsPadding(androidx.compose.foundation.layout.WindowInsets))                                                                                |
| `Modifier.statusBarsPadding()`                                                                                | [`Modifier.statusBarsPadding()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).statusBarsPadding())                                                                                |
| `Modifier.navigationBarsPadding()`                                                                                | [`Modifier.navigationBarsPadding()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).navigationBarsPadding())                                                                                |
| `Modifier.imePadding()`                                                                                | [`Modifier.imePadding()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).imePadding())                                                                                |
| `Modifier.cutoutPadding()`                                                                                | [`Modifier.displayCutoutPadding()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).displayCutoutPadding())                                                                                |
| `Modifier.navigationBarsWithImePadding()`                                                                                | [`Modifier.navigationBarsPadding().imePadding()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).imePadding())                                                                                |
| `Modifier.statusBarsHeight()`                                                                                | [`Modifier.windowInsetsTopHeight(WindowInsets.statusBars)`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).windowInsetsTopHeight(androidx.compose.foundation.layout.WindowInsets))                                                                                |
| `Modifier.navigationBarsHeight()`                                                                                | [`Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars)`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).windowInsetsBottomHeight(androidx.compose.foundation.layout.WindowInsets))                                                                                |
| `Modifier.navigationBarsWidth()`                                                                                | [`Modifier.windowInsetsStartWidth(WindowInsets.navigationBars)`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).windowInsetsStartWidth(androidx.compose.foundation.layout.WindowInsets)) / [`Modifier.windowInsetsEndWidth(WindowInsets.navigationBars)`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).windowInsetsEndWidth(androidx.compose.foundation.layout.WindowInsets)) |
| `rememberInsetsPaddingValues(insets = LocalWindowInsets.current.statusBars, applyStart = true, applyTop = true, applyEnd = true)` | [`WindowInsets.statusBars.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top).asPaddingValues()`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets).asPaddingValues())                                                                                |
| `derivedWindowInsetsTypeOf`                                                                                | [`WindowInsets.union(windowInsets: WindowInsets)`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets).union(androidx.compose.foundation.layout.WindowInsets))                                                                                |
| `LocalWindowInsets.current.navigationBars`                                                                                | [`WindowInsets.navigationBars`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets.Companion).navigationBars())                                                                                |
| `LocalWindowInsets.current.statusBars`                                                                                | [`WindowInsets.statusBars`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets.Companion).statusBars())                                                                                |
| `LocalWindowInsets.current.ime`                                                                                | [`WindowInsets.ime`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets.Companion).ime())                                                                                |
| `LocalWindowInsets.current.systemGestures`                                                                                | [`WindowInsets.systemGestures`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets.Companion).systemGestures())                                                                                |
| `LocalWindowInsets.current.systemBars`                                                                                | [`WindowInsets.systemBars`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets.Companion).systemBars())                                                                                |
| `LocalWindowInsets.current.displayCutout`                                                                                | [`WindowInsets.displayCutout`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets.Companion).displayCutout())                                                                                |
| `LocalWindowInsets.current.ime.bottom`                                                                                | [`WindowInsets.ime.getBottom(LocalDensity.current)`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/WindowInsets#getBottom(androidx.compose.ui.unit.Density))                                                                                |
| `WindowInsets.Type.isVisible`                                                                                | [`WindowInsets.isImeVisible`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#(androidx.compose.foundation.layout.WindowInsets.Companion).isImeVisible()), etc.                                                                                |
| `WindowInsets.Type.animationInProgress`                                                                                | [Bug: 217770337](https://issuetracker.google.com/issues/217770337)                                                                                |
| `WindowInsets.Type.animationFraction`                                                                                | [Bug: 217770337](https://issuetracker.google.com/issues/217770337)                                                                                |
| `WindowInsets.Type.layoutInsets`                                                                                | [Bug: 217770337](https://issuetracker.google.com/issues/217770337)                                                                                |
| `WindowInsets.Type.animatedInsets`                                                                                | [Bug: 217770337](https://issuetracker.google.com/issues/217770337)                                                                                |
| `rememberImeNestedScrollConnection()`                                                                                | [`Modifier.imeNestedScroll()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).imeNestedScroll())                                                                                |

## Original docs

Insets for Jetpack Compose takes a lot of the ideas which drove [Insetter][insetter-view] for views, and applies them for use in composables.

## Usage
To setup Insets in your composables, you need to call the `ProvideWindowInsets` function and
wrap your content. This would typically be done near the top level of your composable hierarchy:

``` kotlin
setContent {
  MaterialTheme {
    ProvideWindowInsets {
      // your content
    }
  }
}
```

!!! note
    **This library does not disable window decor fitting.** For your view hierarchy to able to receive insets, you need to make sure to call: [`WindowCompat.setDecorFitsSystemWindows(window, false)`](https://developer.android.com/reference/androidx/core/view/WindowCompat#setDecorFitsSystemWindows(android.view.Window,%20boolean)) from your Activity. You also need to set the system bar backgrounds to be transparent, which can be done with our [System UI Controller](../systemuicontroller) library.

`ProvideWindowInsets` allows the library to set an [`OnApplyWindowInsetsListener`][insetslistener] on your content's host view. That listener is used to update the value of a composition local bundled in this library: `LocalWindowInsets`.

`LocalWindowInsets` holds an instance of `WindowInsets` which contains the value of various [WindowInsets][insets] [types][insettypes]. You can use the values manually like so:

``` kotlin
@Composable
fun ImeAvoidingBox() {
    val insets = LocalWindowInsets.current

    val imeBottom = with(LocalDensity.current) { insets.ime.bottom.toDp() }
    Box(Modifier.padding(bottom = imeBottom))
}
```

...but we also provide some easy-to-use [Modifier][modifier]s.

### Modifiers

We provide two types of modifiers for easy handling of insets: padding and size.

#### Padding modifiers
The padding modifiers allow you to apply padding to a composable which matches a specific type of inset. Currently we provide:

- [`Modifier.statusBarsPadding()`](../api/insets/com.google.accompanist.insets/status-bars-padding.html)
- [`Modifier.navigationBarsPadding()`](../api/insets/com.google.accompanist.insets/navigation-bars-padding.html)
- [`Modifier.systemBarsPadding()`](../api/insets/com.google.accompanist.insets/system-bars-padding.html)
- [`Modifier.imePadding()`](../api/insets/com.google.accompanist.insets/ime-padding.html)
- [`Modifier.navigationBarsWithImePadding()`](../api/insets/com.google.accompanist.insets/navigation-bars-with-ime-padding.html)
- [`Modifier.cutoutPadding()`](../api/insets/com.google.accompanist.insets/cutout-padding.html)

These are commonly used to move composables out from under the system bars. The common example would be a [`FloatingActionButton`][fab]:

``` kotlin
FloatingActionButton(
    onClick = { /* TODO */ },
    modifier = Modifier
        .align(Alignment.BottomEnd)
        .padding(16.dp) // normal 16dp of padding for FABs
        .navigationBarsPadding() // Move it out from under the nav bar
) {
    Icon(imageVector = Icons.Default.Add, contentDescription = null)
}
```

#### Size modifiers
The size modifiers allow you to match the size of a composable to a specific type of inset. Currently we provide:

- [`Modifier.statusBarsHeight()`](../api/insets/com.google.accompanist.insets/status-bars-height.html)
- [`Modifier.navigationBarsHeight()`](../api/insets/com.google.accompanist.insets/navigation-bars-height.html)
- [`Modifier.navigationBarsWidth()`](../api/insets/com.google.accompanist.insets/navigation-bars-width.html)

These are commonly used to allow composables behind the system bars, to provide background protection, or similar:

``` kotlin
Spacer(
    Modifier
        .background(Color.Black.copy(alpha = 0.7f))
        .statusBarsHeight() // Match the height of the status bar
        .fillMaxWidth()
)
```

### PaddingValues
Compose also provides the concept of [`PaddingValues`][paddingvalues], a data class which contains the padding values to be applied on all dimensions (similar to a rect). This is commonly used with container composables, such as [`LazyColumn`][lazycolumn], to set the content padding.

You may want to use inset values for content padding, so this library provides the [`rememberInsetsPaddingValues()`](..//api/insets/com.google.accompanist.insets/remember-insets-padding-values.html) extension function to convert between `Insets` and [`PaddingValues`][paddingvalues]. Here's an example of using the system bars insets:

``` kotlin
LazyColumn(
    contentPadding = rememberInsetsPaddingValues(
        insets = LocalWindowInsets.current.systemBars,
        applyTop = true,
        applyBottom = true,
    )
) {
    // content
}
```

For a more complex example, see the [`EdgeToEdgeLazyColumn`](https://github.com/google/accompanist/blob/main/sample/src/main/java/com/google/accompanist/sample/insets/EdgeToEdgeLazyColumn.kt) example:

<a href="images/edge-to-edge-list.jpg">
<img src="images/edge-to-edge-list.jpg" width=300>
</a>

## Inset-aware layouts (`insets-ui`)

Unfortunately, most of Compose Material's layouts do not support the use of content padding, which means that the following code probably doesn't produce the effect you want:

``` kotlin
// 😥 This likely doesn't do what you want
TopAppBar(
    // content
    modifier = Modifier.statusBarsPadding()
)
```

To workaround this, we provide the `insets-ui` companion library which contains versions of commonly used layouts, with the addition of a `contentPadding` parameter. The example below is using our [`TopAppBar`](../api/insets-ui/com.google.accompanist.insets.ui/-top-app-bar.html) layout, providing the status bar insets to use as content padding:

``` kotlin
import com.google.accompanist.insets.ui.TopAppBar

TopAppBar(
    contentPadding = rememberInsetsPaddingValues(
        insets = LocalWindowInsets.current.statusBars,
        applyStart = true,
        applyTop = true,
        applyEnd = true,
    )
) {
    // content
}
```

The library also provides a modified copy of Compose Material's [`Scaffold`](https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#Scaffold(androidx.compose.ui.Modifier,androidx.compose.material.ScaffoldState,kotlin.Function0,kotlin.Function0,kotlin.Function1,kotlin.Function0,androidx.compose.material.FabPosition,kotlin.Boolean,kotlin.Function1,kotlin.Boolean,androidx.compose.ui.graphics.Shape,androidx.compose.ui.unit.Dp,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,kotlin.Function1)) which better supports edge-to-edge layouts, by drawing the top and bottom bars over the content.

``` kotlin
Scaffold(
    topBar = {
        // We use TopAppBar from accompanist-insets-ui which allows us to provide
        // content padding matching the system bars insets.
        TopAppBar(
            title = { Text(stringResource(R.string.insets_title_list)) },
            backgroundColor = MaterialTheme.colors.surface.copy(alpha = 0.9f),
            contentPadding = rememberInsetsPaddingValues(
                LocalWindowInsets.current.statusBars,
                applyBottom = false,
            ),
        )
    },
    bottomBar = {
        // We add a spacer as a bottom bar, which is the same height as
        // the navigation bar
        Spacer(Modifier.navigationBarsHeight().fillMaxWidth())
    },
) { contentPadding ->
    // We apply the contentPadding passed to us from the Scaffold
    Box(Modifier.padding(contentPadding)) {
        // content
    }
}
```

See the [API docs](../api/insets-ui/com.google.accompanist.insets.ui/) for a list of the other layouts provided in the library.

### Animated Insets support

=== "Info"

    ![](images/ime-insets.gif){: align=right loading=lazy }

    The library now has experimental support for [`WindowInsetsAnimations`](https://developer.android.com/reference/android/view/WindowInsetsAnimation), allowing your content is react to inset animations, such as the on screen-keyboard (IME) being animated on/off screen. The `imePadding()` and `navigationBarsWithImePadding()` modifiers are available especially for this use-case.

    This functionality works wherever [WindowInsetsAnimationCompat](https://developer.android.com/reference/androidx/core/view/WindowInsetsAnimationCompat) works, which at the time or writing is on devices running API 21+.

    To enable animated insets support, you need need to new `ProvideWindowInsets` overload, and set `windowInsetsAnimationsEnabled = true`.

=== "Usage"

    ``` kotlin
    ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
        // content
    }
    ```

    You can then use the new `navigationBarsWithImePadding()` modifier like so:

    ``` kotlin
    OutlinedTextField(
        // other params,
        modifier = Modifier.navigationBarsWithImePadding()
    )
    ```

    See the [ImeAnimationSample](https://github.com/google/accompanist/blob/main/sample/src/main/java/com/google/accompanist/sample/insets/ImeAnimationSample.kt) for a working example.

### IME animations
If you're using the animation insets support for IME/keyboard animations, you also need to ensure that the activity's `windowSoftInputMode` is set to `adjustResize`:

``` xml
<activity
      android:name=".MyActivity"
      android:windowSoftInputMode="adjustResize">
</activity>
```

The default value of `windowSoftInputMode` _should_ work, but Compose does not currently set the flags necessary (see [here](https://issuetracker.google.com/154101484)).

## 🚧 Experimental

The features below are experimental, and require developers to [opt-in](https://kotlinlang.org/docs/reference/opt-in-requirements.html).

### Controlling the IME (on-screen keyboard)

=== "Info"

    ![](images/ime-scroll.gif){: loading=lazy align=right }

    This library also has support for controlling the IME from scroll gestures, allowing your scrollable components to pull/push the IME on/off screen. This is achieved through the built-in [`NestedScrollConnection`](https://developer.android.com/reference/kotlin/androidx/compose/ui/gesture/nestedscroll/NestedScrollConnection) implementation returned by [`rememberImeNestedScrollConnection()`](../api/insets/com.google.accompanist.insets/remember-ime-nested-scroll-connection.html).

    This functionality only works when running on devices with API 30+.

=== "Usage"

    ``` kotlin
    // Here we're using a scrollable Column, but it also works with LazyColumn, etc.
    Column(
        // We use the nestedScroll modifier, passing in the
        // the connection from rememberImeNestedScrollConnection()
        modifier = Modifier
            .nestedScroll(connection = rememberImeNestedScrollConnection())
            .verticalScroll(state = rememberScrollState())
    ) {
        // list content
    }
    ```

    See the [ImeAnimationSample](https://github.com/google/accompanist/blob/main/sample/src/main/java/com/google/accompanist/sample/insets/ImeAnimationSample.kt) for a working example.

## Download

[![Maven Central](https://img.shields.io/maven-central/v/com.google.accompanist/accompanist-insets)](https://search.maven.org/search?q=g:com.google.accompanist)

```groovy
repositories {
    mavenCentral()
}

dependencies {
    implementation "com.google.accompanist:accompanist-insets:<version>"
    // If using insets-ui
    implementation "com.google.accompanist:accompanist-insets-ui:<version>"
}
```

Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap]. These are updated on every commit.

## Something not working?

If you find that something isn't working correctly, here's a checklist to try:

- Check that you've called [`WindowCompat.setDecorFitsSystemWindows(window, false)`](https://developer.android.com/reference/androidx/core/view/WindowCompat#setDecorFitsSystemWindows(android.view.Window,%20boolean)) in your Activity. Unless you do that, the window decor will consume the insets, and they will not be dispatched to your content.
- If it's something related to the keyboard, check that the Activity's `windowSoftInputMode` is set to [`adjustResize`](https://developer.android.com/reference/android/view/WindowManager.LayoutParams#SOFT_INPUT_ADJUST_RESIZE). Without that, IME visibility changes will not be sent as inset changes.
- Similarly, if you're setting [`android:windowFullscreen`](https://developer.android.com/reference/android/view/WindowManager.LayoutParams#FLAG_FULLSCREEN) to `true` (or using a `.Fullscreen` theme), be aware that `adjustResize` will not work. Please see the [documentation](https://developer.android.com/reference/android/view/WindowManager.LayoutParams#FLAG_FULLSCREEN) for an alternative.
- If you're using `ProvideWindowInsets` (or `ViewWindowInsetObserver`) in multiple layers of your view hierarchy (i.e. in the activity, _and_ in a fragment), you need to turn off consuming of insets. By default `ProvideWindowInsets` and `ViewWindowInsetObserver` will completely consume any insets passed to it. In the previous example, this means that the activity content will get the insets, but the fragment won't. To disable consuming, pass `consumeWindowInsets = false` to `ProvideWindowInsets` or `ViewWindowInsetObserver.start()`.

[compose]: https://developer.android.com/jetpack/compose
[snap]: https://oss.sonatype.org/content/repositories/snapshots/com/google/accompanist/accompanist-insets/
[insetter-view]: https://github.com/chrisbanes/insetter
[insets]: https://developer.android.com/reference/kotlin/androidx/core/view/WindowInsetsCompat
[insettypes]: https://developer.android.com/reference/kotlin/androidx/core/view/WindowInsetsCompat.Type
[insetslistener]: https://developer.android.com/reference/kotlin/androidx/core/view/OnApplyWindowInsetsListener
[modifier]: https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier
[paddingvalues]: https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/PaddingValues
[lazycolumn]: https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/package-summary#lazycolumn
[fab]: https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#floatingactionbutton
[api-type]: ../api/insets/com.google.accompanist.insets/-window-insets/-type/


text:
/**
* @author Alexander V. Astapchuk
* @version $Revision$
*/

package org.apache.harmony.security.tests.support;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.math.BigInteger;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Principal;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.SignatureException;

import java.security.cert.*;
import java.util.*;

import javax.security.auth.x500.X500Principal;

/**
 * The class contains various utility methods used during the java.security
 * classes testing.
 *
 */

public final class TestCertUtils {

    private TestCertUtils() {
        throw new Error("statics only");
    }

    /**
     * Returns new instance of test certificate each time the method is called.
     *
     * @return test certificate
     */
    public static Certificate getCert() {
        return new TestCertificate();
    }

    /**
     * Returns an array of 3 test certificates. IMP: The array returned is not
     * real chain of certificates, it's just an array of 3 certs. The method
     * returns new array each time it's called. The number of 3 was chosen
     * arbitrarily and is subject to change.
     *
     * @return an array of 3 certificates
     */
    public static Certificate[] getCertChain() {
        Certificate[] chain = { new TestCertificate(), new TestCertificate(),
                new TestCertificate() };
        return chain;
    }

    /**
     * Returns a test CertPath, which uses getCertChain() to obtain a list of
     * certificates to store.
     *
     * @return test cert path
     */
    public static CertPath getCertPath() {
        return new TestCertPath();
    }

    /**
     * Generates and returns an instance of TestCertPath.

     * TestCertificate-s included in the CertPath will be uniq (will have
     * different numbers passed to their ctor-s).

     * The second arguments shows which number will have the first Certificate
     * in the CertPath. The second certificate will have (startID+1) number
     * and so on.
     *
     * @param howMany - shows how many TestCerts must contain the CertPath generated
     * @param startID - specifies the starting ID which the first certificate will have
     * @return TestCertPath
     */
    public static CertPath genCertPath(int howMany, int startID) {
        Certificate[] certs = new Certificate[howMany];
        for (int i = 0; i < howMany; i++) {
            certs[i] = new TestCertificate(Integer.toString(startID + i));
        }
        return new TestCertPath(certs);
    }

    private static Provider provider = null;

    private static final String providerName = "TstPrvdr";

    /**
     * A Principal used to form rootCA's certificate
     */
    public static final X500Principal rootPrincipal = new X500Principal(
            UniGen.rootName);

    /**
     * Some fake rootCA's certificate.
     */
    public static final X509Certificate rootCA = new TestX509Certificate(
            rootPrincipal, rootPrincipal);

    public static void install_test_x509_factory() {
        if (provider == null) {
            provider = new TestProvider(providerName, 0.01,
                    "Test provider for serialization testing");
            Security.insertProviderAt(provider, 1);
        }
    }

    public static void uninstall_test_x509_factory() {
        if (provider != null) {
            Security.removeProvider(providerName);
            provider = null;
        }
    }

    /**
     * The class represents test certificate path.
     *
     */

    public static final class TestCertPath extends CertPath implements
            Serializable {

        private static final byte[] encoded = new byte[] { 1, 2, 3, 4, 5, 6, 7,
                8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };

        private static final String serializedData = "Just a dummy string to be serialized instead of real data";

        private Certificate[] certs;

        /**
         * Default ctor for TestCertPath. Uses {@link TestCertUtils#getCertChain()}
         * to obtain list of certificates.

         * All TestCertPath-s constructed via this ctor will be equals() to each
         * other.
         */
        public TestCertPath() {
            super("testCertPath");
            certs = getCertChain();
        }

        /**
         * Constructs TestCertPath and keeps the given array of certificates.

         * The TestCertPaths constructed via this ctor may be different (if they
         * have different set of certificates)

         * @see TestCertUtils#genCertPath(int, int)
         * @param certs
         */
        public TestCertPath(Certificate[] certs) {
            super("testCertPath");
            this.certs = certs;
        }

        /**
         * @see java.security.cert.CertPath#getCertificates()
         */
        public List<Certificate> getCertificates() {
            return Arrays.asList(certs);
        }

        /**
         * @see java.security.cert.CertPath#getEncoded()
         */
        public byte[] getEncoded() throws CertificateEncodingException {
            return encoded.clone();
        }

        /**
         * @see java.security.cert.CertPath#getEncoded(java.lang.String)
         */
        public byte[] getEncoded(String encoding)
                throws CertificateEncodingException {
            return encoded.clone();
        }

        /**
         * @see java.security.cert.CertPath#getEncodings()
         */
        public Iterator<String> getEncodings() {
            Vector<String> v = new Vector<String>();
            v.add("myTestEncoding");
            return v.iterator();
        }

        public String toString() {
            StringBuffer buf = new StringBuffer(200);
            buf.append("TestCertPath. certs count=");
            if( certs == null ) {
                buf.append("0\n");
            }
            else {
                buf.append(certs.length).append("\n");
                for( int i=0; i<certs.length; i++) {
                    buf.append("\t").append(i).append(" ");
                    buf.append(certs[i]).append("\n");
                }
            }
            return buf.toString();
        }

        /**
         * Writes

         * (String) serializedData

         * (int) number of certificates in this CertPath

         * <array of certificates>
         *
         * @param out
         * @throws IOException
         */
        private void writeObject(ObjectOutputStream out) throws IOException {
            out.writeUTF(serializedData);
            if (certs == null) {
                out.writeInt(0);
            } else {
                out.writeInt(certs.length);
                for (int i = 0; i < certs.length; i++) {
                    out.writeObject(certs[i]);
                }
            }
        }

        private void readObject(ObjectInputStream in) throws IOException,
                ClassNotFoundException {
            String s = in.readUTF();
            if (!serializedData.equals(s)) {
                throw new StreamCorruptedException("expect [" + serializedData
                        + "] got [" + s + "]");
            }
            int count = in.readInt();
            certs = new Certificate[count];
            for (int i = 0; i < count; i++) {
                certs[i] = (Certificate) in.readObject();
            }
        }

        protected Object writeReplace() {
            return this;
        }

        protected Object readResolve() {
            return this;
        }
    }

    /**
     * The class represents empty PublicKey.
     *
     */

    public static final class TestPublicKey implements PublicKey {
        private static final String algo = "testPublicKeyAlgorithm";

        private static final byte[] encoded = new byte[] { 1, 2, 3, 4, 5, 6, 7,
                8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };

        private static final String format = "testPublicKeyFormat";

        public String getAlgorithm() {
            return algo;
        }

        public byte[] getEncoded() {
            return encoded.clone();
        }

        public String getFormat() {
            return format;
        }
    }

    /**
     * The class represents test certificate.
     *
     */

    public static class TestCertificate extends Certificate implements
            Serializable {

        private static final byte[] encoded = new byte[] { 1, 2, 3, 4, 5, 6, 7,
                8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };

        public static final String TYPE = "Test";

        //
        // A String that makes different TestCertificates to be different.
        //
        private String diff = null;

        /**
         * Default ctor. All the TestCertificate-s created with this ctor are equals() to each other.
         * Use TestCertificate(String) if you need non equal TestCertificate-s.
         */
        public TestCertificate() {
            super(TYPE);
        }

        /**
         * A special purpose ctor. Pass different String-s to have different TestCertificates.
         * TestCertificate-s with the same String passed to this ctor are considered equal.
         */
        public TestCertificate(String diff) {
            super(TYPE);
            this.diff = diff;
        }

        /**
         * A ctor that allows to specify both the TYPE of certificate and the
         * diff. Leave the diff null when no difference needed.
         *
         * @param diff
         * @param type
         */
        public TestCertificate(String diff, String type) {
            super(type);
            this.diff = diff;
        }

        public byte[] getEncoded() throws CertificateEncodingException {
            return encoded.clone();
        }

        public void verify(PublicKey key) throws CertificateException,
                NoSuchAlgorithmException, InvalidKeyException,
                NoSuchProviderException, SignatureException {
            // do nothing
        }

        public void verify(PublicKey key, String sigProvider)
                throws CertificateException, NoSuchAlgorithmException,
                InvalidKeyException, NoSuchProviderException,
                SignatureException {
            // do nothing

        }

        public String toString() {
            return "Test certificate - for unit testing only";
        }

        public boolean equals(Object obj) {
            if (obj == null || !(obj instanceof TestCertificate)) {
                return false;
            }
            TestCertificate that = (TestCertificate) obj;
            if (this == that) {
                return true;
            }
            if (this.diff == null) {
                return that.diff == null;
            }
            return this.diff.equals(that.diff);
        }

        public PublicKey getPublicKey() {
            return new TestPublicKey();
        }

        /**
         * Writes:

         * boolean - true if this certificate has a diff string,
         * false otherwise, followed by

         * writeUTF() of string (if presented)
         *
         * @param out
         * @throws IOException
         */
        private void writeObject(ObjectOutputStream out) throws IOException {
            if (diff == null) {
                out.writeBoolean(false);
            } else {
                out.writeBoolean(false);
                out.writeUTF(diff);
            }
        }

        private void readObject(ObjectInputStream in) throws IOException,
                ClassNotFoundException {
            boolean hasDiffString = in.readBoolean();
            if (hasDiffString) {
                diff = in.readUTF();
            }
        }

        protected Object writeReplace() {
            return this;
        }

        protected Object readResolve() {
            return this;
        }
    }

    public static class TestInvalidX509Certificate extends TestX509Certificate {
        public TestInvalidX509Certificate(X500Principal subj,
                X500Principal issuer) {
            super(subj, issuer);
        }
    }

    /**
     *
     * TestX509CErtificate.

     * Does nothing interesting, but

     * a) is not abstract, so it can be instantiated

     * b) returns Encoded form

     *
     */
    public static class TestX509Certificate extends X509Certificate {
        private X500Principal subject;

        private X500Principal issuer;

        public TestX509Certificate(X500Principal subj, X500Principal issuer) {
            this.subject = subj;
            this.issuer = issuer;
        }

        public X500Principal getIssuerX500Principal() {
            return issuer;
        }

        public X500Principal getSubjectX500Principal() {
            return subject;
        }

        /**
         * The encoded for of this X509Certificate is a byte array where
         * first are bytes of encoded form of Subject (as X500Principal),
         * followed by one zero byte
         * and followed by the encoded form of Issuer (as X500Principal)
         *
         */
        public byte[] getEncoded() throws CertificateEncodingException {
            byte[] asubj = subject.getEncoded();
            byte[] aissuer = issuer.getEncoded();
            byte[] data = new byte[asubj.length + aissuer.length + 1];

            System.arraycopy(asubj, 0, data, 0, asubj.length);
            //data[asubj.length] = 0;
            System
                    .arraycopy(aissuer, 0, data, asubj.length + 1,
                            aissuer.length);
            return data;
        }

        public void checkValidity() throws CertificateExpiredException,
                CertificateNotYetValidException {
        }

        public void checkValidity(Date date)
                throws CertificateExpiredException,
                CertificateNotYetValidException {
        }

        public int getBasicConstraints() {
            return 0;
        }

        public Principal getIssuerDN() {
            return null;
        }

        public boolean[] getIssuerUniqueID() {
            return null;
        }

        public boolean[] getKeyUsage() {
            return null;
        }

        public Date getNotAfter() {
            return null;
        }

        public Date getNotBefore() {
            return null;
        }

        public BigInteger getSerialNumber() {
            return null;
        }

        public String getSigAlgName() {
            return null;
        }

        public String getSigAlgOID() {
            return null;
        }

        public byte[] getSigAlgParams() {
            return null;
        }

        public byte[] getSignature() {
            return null;
        }

        public Principal getSubjectDN() {
            return null;
        }

        public boolean[] getSubjectUniqueID() {
            return null;
        }

        public byte[] getTBSCertificate() throws CertificateEncodingException {
            return null;
        }

        public int getVersion() {
            return 0;
        }

        public Set getCriticalExtensionOIDs() {
            return null;
        }

        public byte[] getExtensionValue(String oid) {
            return null;
        }

        public Set getNonCriticalExtensionOIDs() {
            return null;
        }

        public boolean hasUnsupportedCriticalExtension() {
            return false;
        }

        public PublicKey getPublicKey() {
            return null;
        }

        public String toString() {
            return null;
        }

        public void verify(PublicKey key, String sigProvider)
                throws CertificateException, NoSuchAlgorithmException,
                InvalidKeyException, NoSuchProviderException,
                SignatureException {

        }

        public void verify(PublicKey key) throws CertificateException,
                NoSuchAlgorithmException, InvalidKeyException,
                NoSuchProviderException, SignatureException {

        }
    }

    /**
     * TestProvider. Does nothing, but pretends to
     * implement X.509 CertificateFactory.
     */
    public static class TestProvider extends Provider {

        private Provider.Service serv;

        public TestProvider(String name, double version, String info) {
            super(name, version, info);
            serv = new Provider.Service(this, "CertificateFactory", "X.509",
                    TestFactorySpi.class.getName(), new ArrayList<String>(), null);
        }

        public synchronized Set<Provider.Service> getServices() {
            HashSet<Provider.Service> s = new HashSet<Service>();
            s.add(serv);
            return s;
        }
    }

    /**
     * Some kind of Certificate Factory, used during unit testing.
     *
     *
     */
    public static class TestFactorySpi extends CertificateFactorySpi {

        /**
         * Tries to create an instance of TestX509Certificate, basing
         * on the presumption that its {@link TestX509Certificate#getEncoded()
         * encoded} form is stored.

         * @throws CertificateException is the presumption is not met or if
         * any IO problem occurs.
         */
        public Certificate engineGenerateCertificate(InputStream is)
                throws CertificateException {
            byte[] data = new byte[0];
            byte[] chunk = new byte[1024];
            int len;
            try {
                while ((len = is.read(chunk)) > 0) {
                    byte[] tmp = new byte[data.length + len];
                    System.arraycopy(data, 0, tmp, 0, data.length);
                    System.arraycopy(chunk, 0, tmp, data.length, len);
                    data = tmp;
                }
            } catch (IOException ex) {
                throw new CertificateException("IO problem", ex);
            }
            int pos = Arrays.binarySearch(data, (byte) 0);
            if (pos < 0) {
                throw new CertificateException("invalid format");
            }
            byte[] subjNameData = new byte[pos];
            System.arraycopy(data, 0, subjNameData, 0, subjNameData.length);
            byte[] issNameData = new byte[data.length - pos - 1];
            System.arraycopy(data, pos + 1, issNameData, 0, issNameData.length);
            X500Principal subjName = new X500Principal(subjNameData);
            X500Principal issName = new X500Principal(issNameData);
            return new TestX509Certificate(subjName, issName);
        }

        /**
         * Not supported yet.
         * @throws UnsupportedOperationException
         */
        public Collection engineGenerateCertificates(InputStream inStream)
                throws CertificateException {
            throw new UnsupportedOperationException("not yet.");
        }

        /**
         * Not supported yet.
         * @throws UnsupportedOperationException
         */
        public CRL engineGenerateCRL(InputStream inStream) throws CRLException {
            throw new UnsupportedOperationException("not yet.");
        }

        /**
         * Not supported yet.
         * @throws UnsupportedOperationException
         */
        public Collection engineGenerateCRLs(InputStream inStream)
                throws CRLException {
            throw new UnsupportedOperationException("not yet.");
        }

        /**
         * Returns an instance of TestCertPath.

         * @throws CertificateException if
         * a) any of Certificates passed is not an instance of X509Certificate
         * b) any of Certificates passed is an instance of TestInvalidX509Certificate
         */
        public CertPath engineGenerateCertPath(List certs)
                throws CertificateException {
            ArrayList<Certificate> validCerts = new ArrayList<Certificate>();
            for (Iterator i = certs.iterator(); i.hasNext();) {
                Certificate c = (Certificate) i.next();
                if (!(c instanceof X509Certificate)) {
                    throw new CertificateException("Not X509: " + c);
                }
                if (c instanceof TestInvalidX509Certificate) {
                    throw new CertificateException("Invalid (test) X509: " + c);
                }
                validCerts.add(c);
            }
            Certificate[] acerts = new Certificate[validCerts.size()];
            validCerts.toArray(acerts);
            return new TestCertPath(acerts);
        }
    }

    /**
     * Utility class used to generate some amount of uniq names.
     */
    public static class UniGen {
        public static final String rootName = "CN=Alex Astapchuk, OU=SSG, O=Intel ZAO, C=RU";

        private static final String datasNames[] = { "CN", "OU", "O", "C" };

        private static final String datas[][] = {
        // Names database
                { "Alex Astapchuk", null, null, null },
                { "John Doe", null, null, null },
                // 'organisation unit'-s
                { null, "SSG", null, null }, { null, "SSG/DRL", null, null },
                // organizations
                { null, null, "Intel ZAO", null },
                { null, null, "Intel Inc", null },
                // countries
                { null, null, null, "RU" }, { null, null, null, "US" },
                { null, null, null, "GB" }, { null, null, null, "JA" },
                { null, null, null, "KO" }, { null, null, null, "TW" }, };

        //
        // Returns a string from data from a given column and
        // position. The positions are looked for first non-null entry. If there
        // are no non empty items left, then it scans column starting from the
        // beginning.
        //
        // @param col
        // @param startRow
        // @return
        //
        private static String getData(int col, int startRow) {
            startRow = startRow % datas.length;
            for (int i = startRow; i < datas.length; i++) {
                if (datas[i][col] != null) {
                    return datas[i][col];
                }
            }
            // no non-null entries left, check from the beginning
            for (int i = 0; i < datas.length; i++) {
                if (datas[i][col] != null) {
                    return datas[i][col];
                }
            }
            // can't be
            throw new Error();
        }

        //
        // Increments a num.

        // num is interpreted as a number with a base of
        // base and each digit of this number is stored as a
        // separate num's element.
        //
        // @param num
        // @param base
        // @return true if overflow happened
        //
        private static boolean inc(int[] num, int base) {
            for (int i = 0; i < num.length; i++) {
                if ((++num[i]) >= base) {
                    num[i] = 0;
                } else {
                    return false;
                }
            }
            return true;
        }

        /**
         * Generates some amount of uniq names, none of which is equals to
         * {@link #rootName}.
         * @param howMany
         * @return
         */
        public static String[] genNames(int howMany) {
            int counts[] = new int[datasNames.length];
            ArrayList<String> al = new ArrayList<String>();

            // not really the thrifty algorithm...
            for (int i = 0; i < howMany;) {

                //                System.out.print("#"+i+": ");
                //                for( int j=0; j<counts.length; j++) {
                //                    System.out.print(""+counts[j]+"|");
                //                }
                //                System.out.println();

                StringBuffer buf = new StringBuffer();
                int j = 0;
                for (; j < datasNames.length - 1; j++) {
                    String name = datasNames[j];
                    String val = getData(j, counts[j]);
                    buf.append(name).append('=').append(val).append(",");
                }
                String name = datasNames[j];
                String val = getData(j, counts[j]);
                buf.append(name).append('=').append(val);

                name = buf.toString();

                if (!(rootName.equals(name) || al.contains(name))) {
                    ++i;
                    al.add(name);
                    //                    System.out.println("generated: "+name);
                } else {
                    //                    System.out.println("rejected: "+name);
                }

                if (inc(counts, datas.length)) {
                    // if this happened, then just add some data into 'datas'
                    throw new Error(
                            "cant generate so many uniq names. sorry. add some more data.");
                }
            }
            return (String[]) al.toArray(new String[al.size()]);
        }

        /**
         * Generates some amount of uniq X500Principals, none of which is equals
         * has a string equals to {@link #rootName}.
         * @param howMany
         * @return
         */
        public static X500Principal[] genX500s(int howMany) {
            String names[] = genNames(howMany);
            X500Principal[] ps = new X500Principal[howMany];
            for (int i = 0; i < howMany; i++) {
                ps[i] = new X500Principal(names[i]);
            }
            return ps;
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace bid
{

namespace zipped_detail
{

template<class TypeList, template<class> class HasFunctor, template<class> class CanFunctor>
using function_active = tmp::meta_and
<
    tmp::list_foldl<std::false_type, tmp::list_map<TypeList, HasFunctor>, tmp::meta_or>, // at least one range has function
    tmp::list_foldl<std::true_type, tmp::list_map<TypeList, CanFunctor>, tmp::meta_and> // all can do function
>;

template<class TypeList>
using pop_front_active = function_active<TypeList, has_pop_front, can_pop_front>;
template<class TypeList>
using front_active = function_active<TypeList, has_front, can_front>;

template<class TypeList>
using drop_front_active = function_active<TypeList, has_drop_front, can_drop_front>;
template<class TypeList>
using drop_front_amount_active = function_active<TypeList, has_drop_front_amount, can_drop_front>;

}

template<class... RangeTypes>
class zipped_range
{
public:
    typedef range_tag range_tag;
    typedef tmp::list_to_tuple_each
    <
        tmp::cartesian_product<value_type_t<RangeTypes>...>
    > value_type;
    typedef std::size_t size_type; // TODO: pick largest of size_type<RangeTypes>...

    zipped_range(std::tuple<RangeTypes...> ranges)
      : ranges_(std::move(ranges))
    {}

    template<class Visitor, class = std::enable_if_t<zipped_detail::pop_front_active<first_of<tmp::type_list<RangeTypes...>, Visitor>>{}>>
    decltype(auto) pop_front_impl(Visitor&& v)
    {
        return pop_front_impl(std::forward<Visitor>(v), std::tuple<>{}, std::integral_constant<std::size_t, 0>{});
    }
private:
    template<class Visitor, class Tuple, std::size_t CurrentIndex>
    decltype(auto) pop_front_impl(Visitor&& v, Tuple&& last_tuple, std::integral_constant<std::size_t, CurrentIndex>)
    {
        return pop_front(std::get<CurrentIndex>(ranges_), overloaded(
        [&](none_t) -> decltype(auto)
        {
            return std::forward<Visitor>(v)(none);
        },
        [&](auto&& obj) -> decltype(auto)
        {
            return pop_front_impl
            (
                std::forward<Visitor>(v),
                std::tuple_cat(std::forward<Tuple>(last_tuple), std::forward_as_tuple(std::forward<decltype(obj)>(obj))),
                std::integral_constant<std::size_t, CurrentIndex + 1>{}
            );
        }));
    }
    template<class Visitor, class Tuple>
    decltype(auto) pop_front_impl(Visitor&& v, Tuple&& last_tuple, std::integral_constant<std::size_t, sizeof...(RangeTypes)>)
    {
        return std::forward<Visitor>(v)(std::forward<Tuple>(last_tuple));
    }

public:
    template<class Visitor, class = std::enable_if_t<zipped_detail::front_active<first_of<tmp::type_list<RangeTypes...>, Visitor>>{}>>
    decltype(auto) front_impl(Visitor&& v) const
    {
        return front_impl(std::forward<Visitor>(v), std::tuple<>{}, std::integral_constant<std::size_t, 0>{});
    }
private:
    template<class Visitor, class Tuple, std::size_t CurrentIndex>
    decltype(auto) front_impl(Visitor&& v, Tuple&& last_tuple, std::integral_constant<std::size_t, CurrentIndex>) const
    {
        return front(std::get<CurrentIndex>(ranges_), overloaded(
        [&](none_t) -> decltype(auto)
        {
            return std::forward<Visitor>(v)(none);
        },
        [&](auto&& obj) -> decltype(auto)
        {
            return front_impl
            (
                std::forward<Visitor>(v),
                std::tuple_cat(std::forward<Tuple>(last_tuple), std::forward_as_tuple(std::forward<decltype(obj)>(obj))),
                std::integral_constant<std::size_t, CurrentIndex + 1>{}
            );
        }));
    }
    template<class Visitor, class Tuple>
    decltype(auto) front_impl(Visitor&& v, Tuple&& last_tuple, std::integral_constant<std::size_t, sizeof...(RangeTypes)>) const
    {
        return std::forward<Visitor>(v)(std::forward<Tuple>(last_tuple));
    }

public:
    template<class A = void, class = std::enable_if_t<zipped_detail::drop_front_active<first_of<tmp::type_list<RangeTypes...>, A>>{}>>
    void drop_front_impl()
    {
        tuple_for_each(ranges_, [&](auto&& r)
        {
            drop_front(r);
        });
    }
    template<class A = void, class = std::enable_if_t<zipped_detail::drop_front_amount_active<first_of<tmp::type_list<RangeTypes...>, A>>{}>>
    void drop_front_impl(size_type amount)
    {
        tuple_for_each(ranges_, [&](auto&& r)
        {
            drop_front(r, amount); // TODO: casts required?
        });
    }

private:
    std::tuple<RangeTypes...> ranges_;
};

template<class... Ranges>
auto zipped(Ranges&&... ranges) -> zipped_range<std::decay_t<decltype(range(std::forward<Ranges>(ranges)))>...>
{
    return {std::forward_as_tuple(range(std::forward<Ranges>(ranges))...)};
}

struct enumerated_transform
{
    typedef range_transform_tag range_transform_tag;

    template<class Range>
    auto operator()(Range&& r) const
    {
        return zipped(nats(), std::forward<Range>(r));
    }
};

static enumerated_transform enumerated;

template<class Range>
using enumerated_range = decltype(enumerated(std::declval<Range>()));

}

#endif


text:
package fi.ni.ifc2x3;
import fi.ni.ifc2x3.interfaces.*;
import fi.ni.*;
import java.util.*;

/*
 * IFC Java class
 * @author Jyrki Oraskari
 * @license This work is licensed under a Creative Commons Attribution 3.0 Unported License.
 * http://creativecommons.org/licenses/by/3.0/
 */

public class IfcMechanicalMaterialProperties extends IfcMaterialProperties
{
 // The property attributes
 Double dynamicViscosity;
 Double youngModulus;
 Double shearModulus;
 Double poissonRatio;
 Double thermalExpansionCoefficient;

 // Getters and setters of properties

 public Double getDynamicViscosity() {
   return dynamicViscosity;
 }
 public void setDynamicViscosity(String txt){
   Double value = i.toDouble(txt);
   this.dynamicViscosity=value;

 }

 public Double getYoungModulus() {
   return youngModulus;
 }
 public void setYoungModulus(String txt){
   Double value = i.toDouble(txt);
   this.youngModulus=value;

 }

 public Double getShearModulus() {
   return shearModulus;
 }
 public void setShearModulus(String txt){
   Double value = i.toDouble(txt);
   this.shearModulus=value;

 }

 public Double getPoissonRatio() {
   return poissonRatio;
 }
 public void setPoissonRatio(String txt){
   Double value = i.toDouble(txt);
   this.poissonRatio=value;

 }

 public Double getThermalExpansionCoefficient() {
   return thermalExpansionCoefficient;
 }
 public void setThermalExpansionCoefficient(String txt){
   Double value = i.toDouble(txt);
   this.thermalExpansionCoefficient=value;

 }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_item02"
        android:layout_width="match_parent"
        android:layout_height="140dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/she" />

    <TextView
        android:id="@+id/tv_item02"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:padding="5dp"
        android:textColor="#ffffff" />
</RelativeLayout>


text:
package org.onosproject.cli.net;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.net.packet.PacketProcessorEntry;
import org.onosproject.net.packet.PacketService;

import java.util.List;

import static org.onosproject.net.packet.PacketProcessor.ADVISOR_MAX;
import static org.onosproject.net.packet.PacketProcessor.DIRECTOR_MAX;

/**
 * Lists packet processors.
 */
@Command(scope = "onos", name = "packet-processors",
        description = "Lists packet processors")
public class PacketProcessorsListCommand extends AbstractShellCommand {

    private static final String FMT = "priority=%s, class=%s, packets=%d, avgNanos=%d";

    @Override
    protected void execute() {
        PacketService service = get(PacketService.class);
        if (outputJson()) {
            print("%s", json(service.getProcessors()));
        } else {
            service.getProcessors().forEach(this::print);
        }
    }

    private JsonNode json(List<PacketProcessorEntry> processors) {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode result = mapper.createArrayNode();

        for (PacketProcessorEntry p : processors) {
            result.add(mapper.createObjectNode()
                    .put("priority", priorityFormat(p.priority()))
                    .put("class", p.processor().getClass().getName())
                    .put("packets", p.invocations())
                    .put("avgNanos", p.averageNanos()));
        }

        return result;
    }

    private void print(PacketProcessorEntry entry) {
        print(FMT, priorityFormat(entry.priority()),
              entry.processor().getClass().getName(),
              entry.invocations(), entry.averageNanos());
    }

    private String priorityFormat(int priority) {
        if (priority > DIRECTOR_MAX) {
            return "observer(" + (priority - DIRECTOR_MAX - 1) + ")";
        } else if (priority > ADVISOR_MAX) {
            return "director(" + (priority - ADVISOR_MAX - 1) + ")";
        }
        return "advisor(" + (priority - 1) + ")";
    }

}


text:
import os
import cgi, cgitb

cgitb.enable()

form = cgi.FieldStorage()

message=""

#get the fileitem
fileitem=form['userfile']
if fileitem.file:
    #yay...we got a file
    message=fileitem.file.read()

f=open('new.std','w')
f.write(message)
f.close()

os.system('./Main new.std>file 2>file2')

print """\
Content-Type: text/html\n
"""

f=open('file2','r')
m=f.read()

if(m):
	pass
else:
	m="succesfull"

#print "Content-Type:application/octet-stream; name=\"file\"\r\n";
#print "Content-Disposition: attachment; filename=\"file\"\r\n\n";

print("""

Message

 Main page

see csv output file

%s

""" % (m))

f.close()
os.system('rm new.std')


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Functionality for the navigation tree
 *
 * @package PhpMyAdmin-Navigation
 */
if (! defined('PHPMYADMIN')) {
    exit;
}

/**
 * Represents a function node in the navigation tree
 *
 * @package PhpMyAdmin-Navigation
 */
class Node_Function extends Node
{
    /**
     * Initialises the class
     *
     * @param string $name     An identifier for the new node
     * @param int    $type     Type of node, may be one of CONTAINER or OBJECT
     * @param bool   $is_group Whether this object has been created
     *                         while grouping nodes
     *
     * @return Node_Function
     */
    public function __construct($name, $type = Node::OBJECT, $is_group = false)
    {
        parent::__construct($name, $type, $is_group);
        $this->icon  = PMA_Util::getImage('b_routines.png', __('Function'));
        $this->links = array(
            'text' => 'db_routines.php?server=' . $GLOBALS['server']
                    . '&db=%2$s&item_name=%1$s&item_type=FUNCTION'
                    . '&edit_item=1&token=' . $GLOBALS['token'],
            'icon' => 'db_routines.php?server=' . $GLOBALS['server']
                    . '&db=%2$s&item_name=%1$s&item_type=FUNCTION'
                    . '&export_item=1&token=' . $GLOBALS['token']
        );
        $this->classes = 'function';
    }
}

?>


text:
package eu.ydp.empiria.player.client.gin.scopes.page;

import com.google.inject.Inject;
import com.google.inject.Provider;
import eu.ydp.gwtutil.client.gin.scopes.CustomScopedProvider;

public class PageScopedProvider<T> extends CustomScopedProvider<T> {

    @Inject
    public PageScopedProvider(Provider<T> provider, CurrentPageScopeProvider currentScopeProvider) {
        super(provider, currentScopeProvider);
    }

}


text:
class Repeating extends AbstractObserver {
    _name:string = "Repeating";
    _threshold:number;

    constructor(threshold:number, weight:number = 0, penalty:number = 0) {
        super();
        this._threshold = threshold;
        this._weight    = weight;
    }

    validate(password:string) {
        let regex = new RegExp("(.)\\1{" + (this._threshold-1) + ",}");
        return !regex.test(password);
    }

    set threshold(threshold:number) {
        this._threshold = threshold;
    }

    get threshold() {
        return this._threshold;
    }

    score(password:string) {
        return this._weight;
    }
}


text:
package br.com.digilabs.jqplot.renderer.plugin;

import br.com.digilabs.jqplot.JqPlotResources;
import br.com.digilabs.jqplot.renderer.Renderer;

/**
 * A plugin for a jqPlot to render an axis as a series of date values.  This renderer has no options beyond those supplied by the Axis class.
 * It supplies it's own tick formatter, so the tickOptions.formatter option should not be overridden.
 *
 * Dates can be passed into the axis in almost any recognizable value and will be parsed.  They will be rendered on the axis in the format specified by
 * tickOptions.formatString.  e.g. tickOptions.formatString = '%Y-%m-%d'.
 *
 * Accecptable format codes are:
 *
 * <pre>
 Code    Result                  Description
            == Years ==
%Y      2008                Four-digit year
%y      08                  Two-digit year
            == Months ==
%m      09                  Two-digit month
%#m     9                   One or two-digit month
%B      September           Full month name
%b      Sep                 Abbreviated month name
            == Days ==
%d      05                  Two-digit day of month
%#d     5                   One or two-digit day of month
%e      5                   One or two-digit day of month
%A      Sunday              Full name of the day of the week
%a      Sun                 Abbreviated name of the day of the week
%w      0                   Number of the day of the week (0 = Sunday, 6 = Saturday)
%o      th                  The ordinal suffix string following the day of the month
            == Hours ==
%H      23                  Hours in 24-hour format (two digits)
%#H     3                   Hours in 24-hour integer format (one or two digits)
%I      11                  Hours in 12-hour format (two digits)
%#I     3                   Hours in 12-hour integer format (one or two digits)
%p      PM                  AM or PM
            == Minutes ==
%M      09                  Minutes (two digits)
%#M     9                   Minutes (one or two digits)
            == Seconds ==
%S      02                  Seconds (two digits)
%#S     2                   Seconds (one or two digits)
%s      1206567625723       Unix timestamp (Seconds past 1970-01-01 00:00:00)
            == Milliseconds ==
%N      008                 Milliseconds (three digits)
%#N     8                   Milliseconds (one to three digits)
            == Timezone ==
%O      360                 difference in minutes between local time and GMT
%Z      Mountain Standard Time  Name of timezone as reported by browser
%G      -06:00              Hours and minutes between GMT
            == Shortcuts ==
%F      2008-03-26          %Y-%m-%d
%T      05:06:30            %H:%M:%S
%X      05:06:30            %H:%M:%S
%x      03/26/08            %m/%d/%y
%D      03/26/08            %m/%d/%y
%#c     Wed Mar 26 15:31:00 2008  %a %b %e %H:%M:%S %Y
%v      3-Sep-2008          %e-%b-%Y
%R      15:31               %H:%M
%r      3:31:00 PM          %I:%M:%S %p
            == Characters ==
%n      \n                  Newline
%t      \t                  Tab
%%      %                   Percent Symbol
</pre>
 *
 * @author inaiat
 */
@Deprecated
public class DateAxisRenderer implements Renderer {

    private static final long serialVersionUID = -6281926919874791228L;
    private Boolean sortMergedLabels;
    private Renderer tickRenderer;

    /**
     * @return the sortMergedLabels
     */
    public Boolean getSortMergedLabels() {
        return sortMergedLabels;
    }

    /**
     * @param sortMergedLabels the sortMergedLabels to set
     */
    public void setSortMergedLabels(Boolean sortMergedLabels) {
        this.sortMergedLabels = sortMergedLabels;
    }

    /**
     * @return the tickRenderer
     */
    public Renderer getTickRenderer() {
        return tickRenderer;
    }

    /**
     * @param tickRenderer the tickRenderer to set
     */
    public void setTickRenderer(Renderer tickRenderer) {
        this.tickRenderer = tickRenderer;
    }

    public JqPlotResources resource() {
        return JqPlotResources.DateAxisRenderer;
    }
}


text:
using namespace PR;

static bool ServerGood = false;
static bool ClientGood = false;

constexpr uint16_t PORT	 = 4242;
static const char DATA[] = "HELLO";
static void server()
{
	Socket socket;
	if (!socket.bindAndListen(PORT, 1))
		return;

	Socket client = socket.accept();
	if (!client.send(DATA, strlen(DATA) + 1))
		return;
	ServerGood = true;
}
static void client()
{
	Socket socket;
	if (!socket.connect(PORT, "127.0.0.1"))
		return;

	char buffer[64];
	if (!socket.receive(buffer, strlen(DATA) + 1))
		return;

	ClientGood = strcmp(buffer, DATA) == 0;
}

PR_BEGIN_TESTCASE(Network)
PR_TEST("Client")
{
	Socket socket;
	PR_CHECK_TRUE(socket.isValid());
	PR_CHECK_FALSE(socket.isClientConnection());
	bool result = socket.connect(PORT, "localhost");
	PR_CHECK_FALSE(result);
	PR_CHECK_FALSE(socket.isOpen());
}
PR_TEST("Server")
{
	Socket socket;
	PR_CHECK_TRUE(socket.isValid());
	PR_CHECK_FALSE(socket.isClientConnection());
	bool result = socket.bindAndListen(PORT, 0);
	PR_CHECK_TRUE(result);
	PR_CHECK_TRUE(socket.isOpen());
}
PR_TEST("Client-Server")
{
	std::thread t1(server);
	std::this_thread::sleep_for(std::chrono::milliseconds(200));

	std::thread t2(client);

	t2.join();
	t1.join();

	PR_CHECK_TRUE(ServerGood);
	PR_CHECK_TRUE(ClientGood);
}
PR_END_TESTCASE()

// MAIN
PRT_BEGIN_MAIN
PRT_TESTCASE(Network);
PRT_END_MAIN


text:
using aura::client::ScreenPositionClient;

namespace views {

namespace {

aura::Window* GetOwnerRootWindow(views::Widget* owner) {
  return owner ? owner->GetNativeWindow()->GetRootWindow() : NULL;
}

// ActivationChangeObserverImpl is used to observe activation changes and close
// the menu. Additionally it listens for the root window to be destroyed and
// cancel the menu as well.
class ActivationChangeObserverImpl
    : public aura::client::ActivationChangeObserver,
      public aura::WindowObserver,
      public ui::EventHandler {
 public:
  ActivationChangeObserverImpl(MenuController* controller, aura::Window* root)
      : controller_(controller), root_(root) {
    aura::client::GetActivationClient(root_)->AddObserver(this);
    root_->AddObserver(this);
    root_->AddPreTargetHandler(this);
  }

  ~ActivationChangeObserverImpl() override { Cleanup(); }

  // aura::client::ActivationChangeObserver:
  void OnWindowActivated(
      aura::client::ActivationChangeObserver::ActivationReason reason,
      aura::Window* gained_active,
      aura::Window* lost_active) override {
    if (!controller_->drag_in_progress())
      controller_->CancelAll();
  }

  // aura::WindowObserver:
  void OnWindowDestroying(aura::Window* window) override { Cleanup(); }

  // ui::EventHandler:
  void OnCancelMode(ui::CancelModeEvent* event) override {
    controller_->CancelAll();
  }

 private:
  void Cleanup() {
    if (!root_)
      return;
    // The ActivationClient may have been destroyed by the time we get here.
    aura::client::ActivationClient* client =
        aura::client::GetActivationClient(root_);
    if (client)
      client->RemoveObserver(this);
    root_->RemovePreTargetHandler(this);
    root_->RemoveObserver(this);
    root_ = NULL;
  }

  MenuController* controller_;
  aura::Window* root_;

  DISALLOW_COPY_AND_ASSIGN(ActivationChangeObserverImpl);
};

}  // namespace

// static
MenuMessageLoop* MenuMessageLoop::Create() {
  return new MenuMessageLoopAura;
}

MenuMessageLoopAura::MenuMessageLoopAura() : owner_(NULL) {
}

MenuMessageLoopAura::~MenuMessageLoopAura() {
}

void MenuMessageLoopAura::RepostEventToWindow(const ui::LocatedEvent& event,
                                              gfx::NativeWindow window,
                                              const gfx::Point& screen_loc) {
  aura::Window* root = window->GetRootWindow();
  ScreenPositionClient* spc = aura::client::GetScreenPositionClient(root);
  if (!spc)
    return;

  gfx::Point root_loc(screen_loc);
  spc->ConvertPointFromScreen(root, &root_loc);

  ui::MouseEvent clone(static_cast<const ui::MouseEvent&>(event));
  clone.set_location(root_loc);
  clone.set_root_location(root_loc);
  root->GetHost()->dispatcher()->RepostEvent(clone);
}

void MenuMessageLoopAura::Run(MenuController* controller,
                              Widget* owner,
                              bool nested_menu) {
  // |owner_| may be NULL.
  owner_ = owner;
  aura::Window* root = GetOwnerRootWindow(owner_);
  // It is possible for the same MenuMessageLoopAura to start a nested
  // message-loop while it is already running a nested loop. So make sure the
  // quit-closure gets reset to the outer loop's quit-closure once the innermost
  // loop terminates.
  base::AutoReset<base::Closure> reset_quit_closure(&message_loop_quit_,
                                                    base::Closure());

#if defined(OS_WIN)
  internal::MenuMessagePumpDispatcher nested_dispatcher(controller);
  if (root) {
    scoped_ptr<ActivationChangeObserverImpl> observer;
    if (!nested_menu)
      observer.reset(new ActivationChangeObserverImpl(controller, root));
    aura::client::DispatcherRunLoop run_loop(
        aura::client::GetDispatcherClient(root), &nested_dispatcher);
    message_loop_quit_ = run_loop.QuitClosure();
    run_loop.Run();
  } else {
    base::MessageLoopForUI* loop = base::MessageLoopForUI::current();
    base::MessageLoop::ScopedNestableTaskAllower allow(loop);
    base::RunLoop run_loop(&nested_dispatcher);
    message_loop_quit_ = run_loop.QuitClosure();
    run_loop.Run();
  }
#else
  internal::MenuEventDispatcher event_dispatcher(controller);
  scoped_ptr<ui::ScopedEventDispatcher> dispatcher_override;
  if (ui::PlatformEventSource::GetInstance()) {
    dispatcher_override =
        ui::PlatformEventSource::GetInstance()->OverrideDispatcher(
            &event_dispatcher);
  }
  if (root) {
    scoped_ptr<ActivationChangeObserverImpl> observer;
    if (!nested_menu)
      observer.reset(new ActivationChangeObserverImpl(controller, root));
    aura::client::DispatcherRunLoop run_loop(
        aura::client::GetDispatcherClient(root), NULL);
    message_loop_quit_ = run_loop.QuitClosure();
    run_loop.Run();
  } else {
    base::MessageLoopForUI* loop = base::MessageLoopForUI::current();
    base::MessageLoop::ScopedNestableTaskAllower allow(loop);
    base::RunLoop run_loop;
    message_loop_quit_ = run_loop.QuitClosure();
    run_loop.Run();
  }
#endif
}

void MenuMessageLoopAura::QuitNow() {
  CHECK(!message_loop_quit_.is_null());
  message_loop_quit_.Run();

#if !defined(OS_WIN)
  // Ask PlatformEventSource to stop dispatching events in this message loop
  // iteration. We want our menu's loop to return before the next event.
  if (ui::PlatformEventSource::GetInstance())
    ui::PlatformEventSource::GetInstance()->StopCurrentEventStream();
#endif
}

void MenuMessageLoopAura::ClearOwner() {
  owner_ = NULL;
}

}  // namespace views


text:
@interface DemandDetailImageCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *iconView;

+(instancetype)cellWithTableView:(UITableView *)tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconViewHeightCons;

@end


text:
class ModYearMonthDayToPictureStore < ActiveRecord::Migration
  def change
    add_column :picture_stores, :year_month_day, :string
    remove_column :picture_stores, :yaer_month_day
  end
end


text:
@implementation User

@end


text:
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title></title>

    <!-- Bootstrap core CSS -->
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="css/shop-homepage.css" rel="stylesheet">

  </head>


text:
package p09_Google;

class Pokemon {
    private String name;
    private String type;

    Pokemon(String name, String type) {
        this.name = name;
        this.type = type;
    }

    @Override
    public String toString() {
        return String.format("%s %s", this.name, this.type);
    }
}


text:
Run

    script/release.sh [major|minor|patch] # default is minor


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
-->
<!DOCTYPE Test SYSTEM "test.dtd">
<Test
	ID="S_isInstance"
        date-of-creation="2005-08-16"
        timeout="1"
        >
        <!--
        Author: Elena V. Sayapina
        Version: $Revision: 1.5 $
        -->
    	<Copyright value="apache"/>
        <Author value="Elena V. Sayapina"/>
		<APITestDescription>
			<TestedClass name="java.lang.Class"/>
			<TestedMethod name="public boolean isInstance(Object obj)"/>
        	<Description>
        		Emulates the same workload for isInstance(obj) method
        		as Eclipse does during Eclipse "Hello, World" application scenario run.
        	</Description>
		</APITestDescription>

        <Keyword name="stress"/>
        <Source name="S_isInstance.java"/>
        <Modification date="2005-08-16" author="Elena V. Sayapina"/>

        <Runner ID="Runtime">
			<Param name="toRun" value="org.apache.harmony.test.stress.eclipse.emulation.java.lang.Class.S_isInstance.S_isInstance">
				<Option value="$TestSuiteTestRoot/stress/org/apache/harmony/test/stress/eclipse/emulation/java/lang/Class/S_isInstance/auxiliary"/>
				<Option value="$EclipseHome"/>
			</Param>
		</Runner>
		<Restriction name="OtherVMOnly"/>
</Test>


text:
using System;
using System.Collections;
using System.Collections.Specialized;
using Xunit;

namespace System.Diagnostics.Tests
{
    [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters
    public static class PerformanceCounterTests
    {
        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_CreateCounter_EmptyCounter()
        {
            using (PerformanceCounter counterSample = new PerformanceCounter())
            {
                Assert.Equal(".", counterSample.MachineName);
                Assert.Equal(string.Empty, counterSample.CategoryName);
                Assert.Equal(string.Empty, counterSample.CounterName);
                Assert.Equal(string.Empty, counterSample.InstanceName);
                Assert.True(counterSample.ReadOnly);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_CreateCounter_Count0()
        {
            var name = nameof(PerformanceCounter_CreateCounter_Count0) + "_Counter";
            using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
            {
                counterSample.RawValue = 0;

                Assert.Equal(0, counterSample.RawValue);
                Helpers.DeleteCategory(name);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_CreateCounter_ProcessorCounter()
        {
            using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", "."))
            {
                Assert.Equal(0, Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()));

                Assert.True(counterSample.RawValue > 0);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_CreateCounter_MultiInstanceReadOnly()
        {
            var name = nameof(PerformanceCounter_CreateCounter_MultiInstanceReadOnly) + "_Counter";
            var instance = name + "_Instance";

            var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.MultiInstance);

            using (PerformanceCounter counterSample = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter(category, name, instance)))
            {
                Assert.Equal(name, counterSample.CounterName);
                Assert.Equal(category, counterSample.CategoryName);
                Assert.Equal(instance, counterSample.InstanceName);
                Assert.Equal("counter description",  Helpers.RetryOnAllPlatforms(() => counterSample.CounterHelp));
                Assert.True(counterSample.ReadOnly);
                Helpers.DeleteCategory(name);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_CreateCounter_SetReadOnly()
        {
            var name = nameof(PerformanceCounter_CreateCounter_SetReadOnly) + "_Counter";

            var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.SingleInstance);

            using (PerformanceCounter counterSample = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter(category, name)))
            {
                counterSample.ReadOnly = false;

                Assert.False(counterSample.ReadOnly);
            }

            Helpers.DeleteCategory(name);
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_SetProperties_Null()
        {
            using (PerformanceCounter counterSample = new PerformanceCounter())
            {
                Assert.Throws<ArgumentNullException>(() => counterSample.CategoryName = null);
                Assert.Throws<ArgumentNullException>(() => counterSample.CounterName = null);
                Assert.Throws<ArgumentException>(() => counterSample.MachineName = null);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_SetRawValue_ReadOnly()
        {
            using (PerformanceCounter counterSample = new PerformanceCounter())
            {
                Assert.Throws<InvalidOperationException>(() => counterSample.RawValue = 10);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_GetRawValue_EmptyCategoryName()
        {
            var name = nameof(PerformanceCounter_GetRawValue_EmptyCategoryName) + "_Counter";
            using (PerformanceCounter counterSample = new PerformanceCounter())
            {
                counterSample.ReadOnly = false;
                counterSample.CounterName = name;

                Assert.Throws<InvalidOperationException>(() => counterSample.RawValue);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_GetRawValue_EmptyCounterName()
        {
            var name = nameof(PerformanceCounter_GetRawValue_EmptyCounterName) + "_Counter";
            using (PerformanceCounter counterSample = new PerformanceCounter())
            {
                counterSample.ReadOnly = false;
                counterSample.CategoryName = name + "_Category";

                Assert.Throws<InvalidOperationException>(() => counterSample.RawValue);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_GetRawValue_CounterDoesNotExist()
        {
            var name = nameof(PerformanceCounter_GetRawValue_CounterDoesNotExist) + "_Counter";
            using (PerformanceCounter counterSample = new PerformanceCounter())
            {
                counterSample.ReadOnly = false;
                counterSample.CounterName = name;
                counterSample.CategoryName = name + "_Category";

                Assert.Throws<InvalidOperationException>(() => counterSample.RawValue);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_NextValue_ProcessorCounter()
        {
            using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", "."))
            {
                Helpers.RetryOnAllPlatforms(() => counterSample.NextValue());
                System.Threading.Thread.Sleep(30);

                Assert.True(Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()) > 0);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_BeginInit_ProcessorCounter()
        {
            using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", "."))
            {
                counterSample.BeginInit();

                Assert.NotNull(counterSample);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_BeginInitEndInit_ProcessorCounter()
        {
            using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", "."))
            {
                counterSample.BeginInit();
                counterSample.EndInit();

                Assert.NotNull(counterSample);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_Decrement()
        {
            var name = nameof(PerformanceCounter_Decrement) + "_Counter";
            using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
            {
                counterSample.RawValue = 10;
                Helpers.RetryOnAllPlatforms(() => counterSample.Decrement());

                Assert.Equal(9, counterSample.RawValue);
                Helpers.DeleteCategory(name);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_Increment()
        {
            var name = nameof(PerformanceCounter_Increment) + "_Counter";
            using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
            {
                counterSample.RawValue = 10;
                Helpers.RetryOnAllPlatforms(() => counterSample.Increment());

                Assert.Equal(11, Helpers.RetryOnAllPlatforms(() => counterSample.NextSample().RawValue));
                Helpers.DeleteCategory(name);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_IncrementBy_IncrementBy2()
        {
            var name = nameof(PerformanceCounter_IncrementBy_IncrementBy2) + "_Counter";
            using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
            {
                counterSample.RawValue = 10;
                Helpers.RetryOnAllPlatforms(() => counterSample.IncrementBy(2));

                Assert.Equal(12, counterSample.RawValue);
                Helpers.DeleteCategory(name);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_IncrementBy_IncrementByReadOnly()
        {
            var name = nameof(PerformanceCounter_IncrementBy_IncrementByReadOnly) + "_Counter";
            using (PerformanceCounter counterSample = CreateCounterWithCategory(name, true, PerformanceCounterCategoryType.SingleInstance))
            {
                Assert.Throws<InvalidOperationException>(() => counterSample.IncrementBy(2));
                Helpers.DeleteCategory(name);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_Increment_IncrementReadOnly()
        {
            var name = nameof(PerformanceCounter_Increment_IncrementReadOnly) + "_Counter";
            using (PerformanceCounter counterSample = CreateCounterWithCategory(name, true, PerformanceCounterCategoryType.SingleInstance))
            {
                Assert.Throws<InvalidOperationException>(() => counterSample.Increment());
                Helpers.DeleteCategory(name);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_Decrement_DecrementReadOnly()
        {
            var name = nameof(PerformanceCounter_Decrement_DecrementReadOnly) + "_Counter";
            using (PerformanceCounter counterSample = CreateCounterWithCategory(name, true, PerformanceCounterCategoryType.SingleInstance))
            {
                Assert.Throws<InvalidOperationException>(() => counterSample.Decrement());
                Helpers.DeleteCategory(name);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_RemoveInstance()
        {
            var name = nameof(PerformanceCounter_RemoveInstance) + "_Counter";
            using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
            {
                counterSample.RawValue = 100;
                counterSample.RemoveInstance();
                counterSample.Close();

                Assert.NotNull(counterSample);
                Helpers.DeleteCategory(name);
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void PerformanceCounter_NextSample_MultiInstance()
        {
            var name = nameof(PerformanceCounter_NextSample_MultiInstance) + "_Counter";
            var instance = name + "_Instance";

            var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.MultiInstance);

            using (PerformanceCounter counterSample = new PerformanceCounter(category, name, instance, false))
            {
                counterSample.RawValue = 10;
                Helpers.RetryOnAllPlatforms(() => counterSample.Decrement());

                Assert.Equal(9, counterSample.RawValue);
                Helpers.DeleteCategory(name);
            }
        }

        public static PerformanceCounter CreateCounterWithCategory(string name, bool readOnly, PerformanceCounterCategoryType categoryType )
        {
            var category = Helpers.CreateCategory(name, categoryType);

            PerformanceCounter counterSample =  Helpers.RetryOnAllPlatforms(() => new PerformanceCounter(category, name, readOnly));

            return counterSample;
        }
    }
}