text:
package com.google.android.enterprise.connectedapps.robotests;

import static com.google.android.enterprise.connectedapps.SharedTestUtilities.INTERACT_ACROSS_USERS;
import static com.google.common.truth.Truth.assertThat;

import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION_CODES;
import android.os.IBinder;
import android.os.Parcelable;
import android.util.Pair;
import androidx.test.core.app.ApplicationProvider;
import com.google.android.enterprise.connectedapps.RobolectricTestUtilities;
import com.google.android.enterprise.connectedapps.TestCustomWrapperCallbackListenerImpl;
import com.google.android.enterprise.connectedapps.TestExceptionCallbackListener;
import com.google.android.enterprise.connectedapps.TestParcelableCallbackListenerImpl;
import com.google.android.enterprise.connectedapps.TestScheduledExecutorService;
import com.google.android.enterprise.connectedapps.exceptions.UnavailableProfileException;
import com.google.android.enterprise.connectedapps.testapp.CustomWrapper;
import com.google.android.enterprise.connectedapps.testapp.CustomWrapper2;
import com.google.android.enterprise.connectedapps.testapp.ParcelableContainingBinder;
import com.google.android.enterprise.connectedapps.testapp.ParcelableObject;
import com.google.android.enterprise.connectedapps.testapp.SerializableObject;
import com.google.android.enterprise.connectedapps.testapp.SimpleFuture;
import com.google.android.enterprise.connectedapps.testapp.StringWrapper;
import com.google.android.enterprise.connectedapps.testapp.configuration.TestApplication;
import com.google.android.enterprise.connectedapps.testapp.connector.TestProfileConnector;
import com.google.android.enterprise.connectedapps.testapp.types.ProfileTestCrossProfileType;
import com.google.android.enterprise.connectedapps.testapp.types.TestCrossProfileType;
import com.google.android.enterprise.connectedapps.testapp.types.TestCrossProfileType_SingleSenderCanThrow;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.ParameterizedRobolectricTestRunner;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.LooperMode;

@LooperMode(LooperMode.Mode.LEGACY)
@RunWith(ParameterizedRobolectricTestRunner.class)
@Config(minSdk = VERSION_CODES.O)
public class TypesTest {

  private static final String STRING = "string";
  private static final byte BYTE = 1;
  private static final byte[] BYTE_ARRAY = new byte[]{BYTE};
  private static final byte[][][] MULTIDIMENSIONAL_BYTE_ARRAY = new byte[][][] {{BYTE_ARRAY}};
  private static final Byte BYTE_BOXED = 1;
  private static final short SHORT = 1;
  private static final short[] SHORT_ARRAY = new short[]{SHORT};
  private static final short[][][] MULTIDIMENSIONAL_SHORT_ARRAY = new short[][][] {{SHORT_ARRAY}};
  private static final Short SHORT_BOXED = 1;
  private static final int INT = 1;
  private static final int[] INT_ARRAY = new int[]{INT};
  private static final int[][][] MULTIDIMENSIONAL_INT_ARRAY = new int[][][] {{INT_ARRAY}};
  private static final Integer INTEGER = 1;
  private static final long LONG = 1;
  private static final long[] LONG_ARRAY = new long[]{LONG};
  private static final long[][][] MULTIDIMENSIONAL_LONG_ARRAY = new long[][][] {{LONG_ARRAY}};
  private static final Long LONG_BOXED = 1L;
  private static final float FLOAT = 1;
  private static final float[] FLOAT_ARRAY = new float[]{FLOAT};
  private static final float[][][] MULTIDIMENSIONAL_FLOAT_ARRAY = new float[][][] {{FLOAT_ARRAY}};
  private static final Float FLOAT_BOXED = 1f;
  private static final double DOUBLE = 1;
  private static final double[] DOUBLE_ARRAY = new double[]{DOUBLE};
  private static final double[][][] MULTIDIMENSIONAL_DOUBLE_ARRAY =
      new double[][][] {{DOUBLE_ARRAY}};
  private static final Double DOUBLE_BOXED = 1d;
  private static final char CHAR = 1;
  private static final char[] CHAR_ARRAY = new char[]{CHAR};
  private static final char[][][] MULTIDIMENSIONAL_CHAR_ARRAY = new char[][][] {{CHAR_ARRAY}};
  private static final Character CHARACTER = 1;
  private static final boolean BOOLEAN = true;
  private static final boolean[] BOOLEAN_ARRAY = new boolean[]{BOOLEAN};
  private static final boolean[][][] MULTIDIMENSIONAL_BOOLEAN_ARRAY =
      new boolean[][][] {{BOOLEAN_ARRAY}};
  private static final Boolean BOOLEAN_BOXED = true;
  private static final ParcelableObject PARCELABLE = new ParcelableObject("test");
  private static final SerializableObject SERIALIZABLE = new SerializableObject("test");
  private static final List<String> listOfString = Collections.singletonList(STRING);
  private static final List<List<String>> listOfListOfString = ImmutableList.of(listOfString);
  private static final List<ParcelableObject> listOfParcelable = ImmutableList.of(PARCELABLE);
  private static final List<SerializableObject> listOfSerializable = ImmutableList.of(SERIALIZABLE);
  private static final ImmutableMap<String, String> IMMUTABLE_MAP_STRING_TO_STRING =
      ImmutableMap.of(STRING, STRING);
  private static final Set<String> setOfString = ImmutableSet.of(STRING);
  private static final Collection<String> collectionOfString = ImmutableList.of(STRING);
  // private static final TestProto PROTO = TestProto.newBuilder().setText(STRING).build();
  // private static final List<TestProto> listOfProto = ImmutableList.of(PROTO);
  private static final String[] arrayOfString = new String[] {STRING};
  private static final Collection<String[]> collectionOfStringArray =
      ImmutableList.of(arrayOfString);
  private static final ParcelableObject[] arrayOfParcelable = new ParcelableObject[] {PARCELABLE};
  private static final SerializableObject[] arrayOfSerializable =
      new SerializableObject[] {SERIALIZABLE};
  private static final Collection<ParcelableObject[]> collectionOfParcelableArray =
      ImmutableList.of(arrayOfParcelable);
  private static final Collection<SerializableObject[]> collectionOfSerializableArray =
      ImmutableList.of(arrayOfSerializable);
  // private static final TestProto[] arrayOfProto = new TestProto[] {PROTO};
  private static final String[] emptyStringArray = new String[] {};
  private static final CustomWrapper<String> CUSTOM_WRAPPER = new CustomWrapper<>(STRING);
  private static final CustomWrapper2<String> CUSTOM_WRAPPER2 = new CustomWrapper2<>(STRING);
  private static final StringWrapper STRING_WRAPPER = new StringWrapper(STRING);
  private static final Optional<ParcelableObject> GUAVA_OPTIONAL = Optional.of(PARCELABLE);
  private static final int[] BITMAP_PIXELS = {1, 2, 3, 4, 5, 6, 7, 8, 9};
  private static final CharSequence CHAR_SEQUENCE = STRING;

  private final Application context = ApplicationProvider.getApplicationContext();
  // Android type can't be static due to Robolectric
  private final Pair<String, Integer> pair = new Pair<>(STRING, INTEGER);
  private final Bitmap bitmap = Bitmap.createBitmap(BITMAP_PIXELS, 3, 3, Bitmap.Config.ARGB_8888);
  private final ParcelableContainingBinder parcelableContainingBinder =
      new ParcelableContainingBinder();
  private final Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);

  private final TestScheduledExecutorService scheduledExecutorService =
      new TestScheduledExecutorService();
  private final TestProfileConnector testProfileConnector =
      TestProfileConnector.create(context, scheduledExecutorService);
  private final RobolectricTestUtilities testUtilities =
      new RobolectricTestUtilities(testProfileConnector, scheduledExecutorService);

  private interface SenderProvider {
    TestCrossProfileType_SingleSenderCanThrow provide(
        Context context, TestProfileConnector testProfileConnector);
  }

  @ParameterizedRobolectricTestRunner.Parameters(name = "{0}")
  public static Collection<Object[]> data() {

    SenderProvider currentProfileSenderProvider =
        (Context context, TestProfileConnector testProfileConnector) ->
            (TestCrossProfileType_SingleSenderCanThrow)
                ProfileTestCrossProfileType.create(testProfileConnector).current();
    SenderProvider otherProfileSenderProvider =
        (Context context, TestProfileConnector testProfileConnector) ->
            ProfileTestCrossProfileType.create(testProfileConnector).other();

    return Arrays.asList(
        new Object[][] {
          {"CurrentProfile", currentProfileSenderProvider},
          {"OtherProfile", otherProfileSenderProvider},
        });
  }

  @Before
  public void setUp() {
    Service profileAwareService = Robolectric.setupService(TestApplication.getService());
    testUtilities.initTests();
    IBinder binder = profileAwareService.onBind(/* intent= */ null);
    testUtilities.setBinding(binder, TestProfileConnector.class.getName());
    testUtilities.createWorkUser();
    testUtilities.turnOnWorkProfile();
    testUtilities.setRunningOnPersonalProfile();
    testUtilities.setRequestsPermissions(INTERACT_ACROSS_USERS);
    testUtilities.grantPermissions(INTERACT_ACROSS_USERS);
    testUtilities.addDefaultConnectionHolderAndWait();
  }

  private SenderProvider senderProvider;

  public TypesTest(String profile, SenderProvider senderProvider) {
    this.senderProvider = senderProvider;
  }

  @Test
  public void voidMethodWithNoArguments_callsMethod() throws UnavailableProfileException {
    TestCrossProfileType.voidMethodCalls = 0;

    senderProvider.provide(context, testProfileConnector).voidMethod();

    assertThat(TestCrossProfileType.voidMethodCalls).isEqualTo(1);
  }

  @Test
  public void voidMethodWithArguments_callsMethod() throws UnavailableProfileException {
    TestCrossProfileType.voidMethodCalls = 0;

    senderProvider.provide(context, testProfileConnector).voidMethod("argument");

    assertThat(TestCrossProfileType.voidMethodCalls).isEqualTo(1);
  }

  @Test
  public void stringReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityStringMethod(STRING))
        .isEqualTo(STRING);
  }

  @Test
  public void byteReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityByteMethod(BYTE))
        .isEqualTo(BYTE);
  }

  @Test
  public void boxedByteReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityByteMethod(BYTE_BOXED))
        .isEqualTo(BYTE_BOXED);
  }

  @Test
  public void shortReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityShortMethod(SHORT))
        .isEqualTo(SHORT);
  }

  @Test
  public void boxedShortReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider.provide(context, testProfileConnector).identityShortMethod(SHORT_BOXED))
        .isEqualTo(SHORT_BOXED);
  }

  @Test
  public void intReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityIntMethod(INT))
        .isEqualTo(INT);
  }

  @Test
  public void integerReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityIntegerMethod(INTEGER))
        .isEqualTo(INTEGER);
  }

  @Test
  public void longReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityLongMethod(LONG))
        .isEqualTo(LONG);
  }

  @Test
  public void boxedLongReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityLongMethod(LONG_BOXED))
        .isEqualTo(LONG_BOXED);
  }

  @Test
  public void floatReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityFloatMethod(FLOAT))
        .isEqualTo(FLOAT);
  }

  @Test
  public void boxedFloatReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider.provide(context, testProfileConnector).identityFloatMethod(FLOAT_BOXED))
        .isEqualTo(FLOAT_BOXED);
  }

  @Test
  public void doubleReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityDoubleMethod(DOUBLE))
        .isEqualTo(DOUBLE);
  }

  @Test
  public void boxedDoubleReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityDoubleMethod(DOUBLE_BOXED))
        .isEqualTo(DOUBLE_BOXED);
  }

  @Test
  public void charReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityCharMethod(CHAR))
        .isEqualTo(CHAR);
  }

  @Test
  public void characterReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityCharacterMethod(CHARACTER))
        .isEqualTo(CHARACTER);
  }

  @Test
  public void booleanReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityBooleanMethod(BOOLEAN))
        .isEqualTo(BOOLEAN);
  }

  @Test
  public void boxedBooleanReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityBooleanMethod(BOOLEAN_BOXED))
        .isEqualTo(BOOLEAN_BOXED);
  }

  @Test
  public void parcelableReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityParcelableMethod(PARCELABLE))
        .isEqualTo(PARCELABLE);
  }

  @Test
  public void serializableReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identitySerializableObjectMethod(SERIALIZABLE))
        .isEqualTo(SERIALIZABLE);
  }

  @Test
  public void parcelableWrapperOfParcelableTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityParcelableWrapperOfParcelableMethod(listOfParcelable))
        .isEqualTo(listOfParcelable);
  }

  @Test
  public void parcelableWrapperOfSerializableTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityParcelableWrapperOfSerializableMethod(listOfSerializable))
        .isEqualTo(listOfSerializable);
  }

  @Test
  public void parcelableWrapperOfParcelableWrapperTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityParcelableWrapperOfParcelableWrapperMethod(listOfListOfString))
        .isEqualTo(listOfListOfString);
  }

  @Test
  public void listReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider.provide(context, testProfileConnector).identityListMethod(listOfString))
        .isEqualTo(listOfString);
  }

  @Test
  public void mapReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityMapMethod(IMMUTABLE_MAP_STRING_TO_STRING))
        .isEqualTo(IMMUTABLE_MAP_STRING_TO_STRING);
  }

  @Test
  public void immutableMapReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityImmutableMapMethod(IMMUTABLE_MAP_STRING_TO_STRING))
        .isEqualTo(IMMUTABLE_MAP_STRING_TO_STRING);
  }

  @Test
  public void setReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identitySetMethod(setOfString))
        .isEqualTo(setOfString);
  }

  @Test
  public void collectionReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityCollectionMethod(collectionOfString))
        .containsExactlyElementsIn(collectionOfString);
  }

  @Test
  public void arrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityStringArrayMethod(arrayOfString))
        .asList()
        .containsExactlyElementsIn(arrayOfString);
  }

  @Test
  public void collectionOfArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    TestCrossProfileType_SingleSenderCanThrow sender =
        senderProvider.provide(context, testProfileConnector);

    List<String[]> originalAsList = new ArrayList<>(collectionOfStringArray);
    List<String[]> resultAsList =
        new ArrayList<>(sender.identityCollectionOfStringArrayMethod(collectionOfStringArray));

    assertThat(sender.identityCollectionOfStringArrayMethod(collectionOfStringArray))
        .hasSize(collectionOfStringArray.size());
    for (int i = 0; i < collectionOfStringArray.size(); i++) {
      assertThat(resultAsList.get(i)).asList().containsExactlyElementsIn(originalAsList.get(i));
    }
  }

  @Test
  public void parcelableArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityParcelableObjectArrayMethod(arrayOfParcelable))
        .asList()
        .containsExactlyElementsIn(arrayOfParcelable);
  }

  @Test
  public void serializableArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identitySerializableObjectArrayMethod(arrayOfSerializable))
        .asList()
        .containsExactlyElementsIn(arrayOfSerializable);
  }

  @Test
  public void collectionOfParcelableArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    TestCrossProfileType_SingleSenderCanThrow sender =
        senderProvider.provide(context, testProfileConnector);

    List<ParcelableObject[]> originalAsList = new ArrayList<>(collectionOfParcelableArray);
    List<ParcelableObject[]> resultAsList =
        new ArrayList<>(
            sender.identityCollectionOfParcelableObjectArrayMethod(collectionOfParcelableArray));

    assertThat(resultAsList).hasSize(collectionOfParcelableArray.size());
    for (int i = 0; i < collectionOfParcelableArray.size(); i++) {
      assertThat(resultAsList.get(i)).asList().containsExactlyElementsIn(originalAsList.get(i));
    }
  }

  @Test
  public void collectionOfSerializableArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    TestCrossProfileType_SingleSenderCanThrow sender =
        senderProvider.provide(context, testProfileConnector);

    List<SerializableObject[]> originalAsList = new ArrayList<>(collectionOfSerializableArray);
    List<SerializableObject[]> resultAsList =
        new ArrayList<>(
            sender.identityCollectionOfSerializableObjectArrayMethod(
                collectionOfSerializableArray));

    assertThat(resultAsList).hasSize(collectionOfSerializableArray.size());
    for (int i = 0; i < collectionOfSerializableArray.size(); i++) {
      assertThat(resultAsList.get(i)).asList().containsExactlyElementsIn(originalAsList.get(i));
    }
  }

  @Test
  public void pairReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityPairMethod(pair))
        .isEqualTo(pair);
  }

  @Test
  public void optionalReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityGuavaOptionalMethod(GUAVA_OPTIONAL))
        .isEqualTo(GUAVA_OPTIONAL);
  }

  // TODO: Disabled because use of Optional fails lint check. Re-enable when this is disabled.
  // @Test
  // public void optionalReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
  //   assertThat(senderProvider.provide(context,
  // testProfileConnector).identityOptionalMethod(OPTIONAL_OF_STRING)).isEqualTo(OPTIONAL_OF_STRING);
  // }

  @Test
  public void voidObjectReturnType_works() throws UnavailableProfileException {
    TestCrossProfileType.voidMethodCalls = 0;

    assertThat(senderProvider.provide(context, testProfileConnector).identityVoidMethod())
        .isEqualTo(null);
    assertThat(TestCrossProfileType.voidMethodCalls).isEqualTo(1);
  }

  @Test
  public void methodWhichReturnsNull_works() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).getNull()).isNull();
  }

  @Test
  public void methodWhichReturnsNullCollection_works() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).getNullCollection()).isNull();
  }

  @Test
  public void methodWhichReturnsNullList_works() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).getNullList()).isNull();
  }

  @Test
  public void methodWhichReturnsNullMap_works() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).getNullMap()).isNull();
  }

  // @Test
  // public void methodWhichReturnsNullOptional_works() throws UnavailableProfileException {
  //   assertThat(senderProvider.provide(context, testProfileConnector).getNullOptional()).isNull();
  // }

  @Test
  public void methodWhichReturnsNullSet_works() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).getNullSet()).isNull();
  }

  // @Test
  // public void methodWhichReturnsNullProto_works() throws UnavailableProfileException {
  //   assertThat(senderProvider.provide(context, testProfileConnector).getNullProto()).isNull();
  // }

  @Test
  public void emptyArray_works() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityStringArrayMethod(emptyStringArray))
        .asList()
        .containsExactlyElementsIn(emptyStringArray);
  }

  @Test
  public void nullArray_works() throws UnavailableProfileException {
    assertThat(
            senderProvider.provide(context, testProfileConnector).identityStringArrayMethod(null))
        .isNull();
  }

  @Test
  public void customParcelableWrapperDefinedOnTypeReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityCustomWrapper2Method(CUSTOM_WRAPPER2))
        .isEqualTo(CUSTOM_WRAPPER2);
  }

  @Test
  public void customParcelableWrapperReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityCustomWrapperMethod(CUSTOM_WRAPPER))
        .isEqualTo(CUSTOM_WRAPPER);
  }

  @Test
  public void customParcelableWrapperFutureReturnType_works()
      throws ExecutionException, InterruptedException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .listenableFutureIdentityCustomWrapperMethod(CUSTOM_WRAPPER)
                .get())
        .isEqualTo(CUSTOM_WRAPPER);
  }

  @Test
  public void customParcelableWrapperAsyncMethod_works() {
    TestCustomWrapperCallbackListenerImpl callbackListener =
        new TestCustomWrapperCallbackListenerImpl();
    TestExceptionCallbackListener exceptionListener = new TestExceptionCallbackListener();

    senderProvider
        .provide(context, testProfileConnector)
        .asyncIdentityCustomWrapperMethod(CUSTOM_WRAPPER, callbackListener, exceptionListener);

    assertThat(callbackListener.customWrapperCallbackValue).isEqualTo(CUSTOM_WRAPPER);
  }

  @Test
  public void customFutureWrapper_works() {
    SimpleFuture<String> future =
        senderProvider
            .provide(context, testProfileConnector)
            .simpleFutureIdentityStringMethodWithNonBlockingDelay(STRING, /* secondsDelay= */ 5);
    testUtilities.advanceTimeBySeconds(10);

    assertThat(future.get()).isEqualTo(STRING);
  }

  @Test
  public void parcelableWrapperWithoutGenericReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityStringWrapperMethod(STRING_WRAPPER))
        .isEqualTo(STRING_WRAPPER);
  }

  @Test
  public void bitmapReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    Bitmap returnBitmap =
        senderProvider.provide(context, testProfileConnector).identityBitmapMethod(bitmap);

    assertThat(returnBitmap.getConfig()).isEqualTo(bitmap.getConfig());
    assertThat(returnBitmap.getWidth()).isEqualTo(bitmap.getWidth());
    assertThat(returnBitmap.getHeight()).isEqualTo(bitmap.getHeight());
    assertThat(getBitmapPixels(returnBitmap)).isEqualTo(BITMAP_PIXELS);
  }

  private static int[] getBitmapPixels(Bitmap bitmap) {
    int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
    bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
    return pixels;
  }

  @Test
  public void nullBitmap_works() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityBitmapMethod(null))
        .isNull();
  }

  @Test
  public void contextArgument_works() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).isContextArgumentPassed())
        .isTrue();
  }

  @Test
  public void parcelableArgumentAndReturnType_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector)
        .identityParcelableMethod((Parcelable) PARCELABLE)).isEqualTo(PARCELABLE);
  }

  @Test
  public void parcelableContainingBinderArgumentAndReturnType_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityParcelableMethod(parcelableContainingBinder))
        .isEqualTo(parcelableContainingBinder);
  }

  @Test
  public void parcelableContainingBinderAsyncMethod_works() {
    TestParcelableCallbackListenerImpl callbackListener = new TestParcelableCallbackListenerImpl();
    TestExceptionCallbackListener exceptionListener = new TestExceptionCallbackListener();

    senderProvider
        .provide(context, testProfileConnector)
        .asyncIdentityParcelableMethod(
            parcelableContainingBinder, callbackListener, exceptionListener);

    assertThat(callbackListener.parcelableCallbackValue).isEqualTo(parcelableContainingBinder);
  }

  @Test
  public void futureParcelableContainingBinder_works() throws Exception {
    ListenableFuture<Parcelable> future =
        senderProvider
            .provide(context, testProfileConnector)
            .futureIdentityParcelableMethod(parcelableContainingBinder);

    assertThat(future.get()).isEqualTo(parcelableContainingBinder);
  }

  @Test
  public void charSequenceReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector)
                   .identityCharSequenceMethod(CHAR_SEQUENCE).toString())
        .isEqualTo(CHAR_SEQUENCE.toString());
  }

  @Test
  public void floatArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityFloatArrayMethod(FLOAT_ARRAY))
        .isEqualTo(FLOAT_ARRAY);
  }

  @Test
  public void multidimensionalFloatArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityMultidimensionalFloatArrayMethod(MULTIDIMENSIONAL_FLOAT_ARRAY))
        .isEqualTo(MULTIDIMENSIONAL_FLOAT_ARRAY);
  }

  @Test
  public void byteArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityByteArrayMethod(BYTE_ARRAY))
        .isEqualTo(BYTE_ARRAY);
  }

  @Test
  public void multidimensionalByteArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityMultidimensionalByteArrayMethod(MULTIDIMENSIONAL_BYTE_ARRAY))
        .isEqualTo(MULTIDIMENSIONAL_BYTE_ARRAY);
  }

  @Test
  public void shortArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityShortArrayMethod(SHORT_ARRAY))
        .isEqualTo(SHORT_ARRAY);
  }

  @Test
  public void multidimensionalShortArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityMultidimensionalShortArrayMethod(MULTIDIMENSIONAL_SHORT_ARRAY))
        .isEqualTo(MULTIDIMENSIONAL_SHORT_ARRAY);
  }

  @Test
  public void intArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityIntArrayMethod(INT_ARRAY))
        .isEqualTo(INT_ARRAY);
  }

  @Test
  public void multidimensionalIntArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityMultidimensionalIntArrayMethod(MULTIDIMENSIONAL_INT_ARRAY))
        .isEqualTo(MULTIDIMENSIONAL_INT_ARRAY);
  }

  @Test
  public void longArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityLongArrayMethod(LONG_ARRAY))
        .isEqualTo(LONG_ARRAY);
  }

  @Test
  public void multidimensionalLongArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityMultidimensionalLongArrayMethod(MULTIDIMENSIONAL_LONG_ARRAY))
        .isEqualTo(MULTIDIMENSIONAL_LONG_ARRAY);
  }

  @Test
  public void doubleArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityDoubleArrayMethod(DOUBLE_ARRAY))
        .isEqualTo(DOUBLE_ARRAY);
  }

  @Test
  public void multidimensionalDoubleArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityMultidimensionalDoubleArrayMethod(MULTIDIMENSIONAL_DOUBLE_ARRAY))
        .isEqualTo(MULTIDIMENSIONAL_DOUBLE_ARRAY);
  }

  @Test
  public void charArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityCharArrayMethod(CHAR_ARRAY))
        .isEqualTo(CHAR_ARRAY);
  }

  @Test
  public void multidimensionalCharArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityMultidimensionalCharArrayMethod(MULTIDIMENSIONAL_CHAR_ARRAY))
        .isEqualTo(MULTIDIMENSIONAL_CHAR_ARRAY);
  }

  @Test
  public void booleanArrayReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    assertThat(senderProvider.provide(context, testProfileConnector).identityBooleanArrayMethod(BOOLEAN_ARRAY))
        .isEqualTo(BOOLEAN_ARRAY);
  }

  @Test
  public void multidimensionalBooleanArrayReturnTypeAndArgument_bothWork()
      throws UnavailableProfileException {
    assertThat(
            senderProvider
                .provide(context, testProfileConnector)
                .identityMultidimensionalBooleanArrayMethod(MULTIDIMENSIONAL_BOOLEAN_ARRAY))
        .isEqualTo(MULTIDIMENSIONAL_BOOLEAN_ARRAY);
  }

  @Test
  public void drawableReturnTypeAndArgument_bothWork() throws UnavailableProfileException {
    Drawable returnDrawable =
        senderProvider.provide(context, testProfileConnector).identityDrawableMethod(drawable);

    assertThat(returnDrawable.getIntrinsicHeight()).isEqualTo(drawable.getIntrinsicHeight());
    assertThat(returnDrawable.getIntrinsicWidth()).isEqualTo(drawable.getIntrinsicWidth());
    assertThat(getDrawablePixels(returnDrawable)).isEqualTo(BITMAP_PIXELS);
  }

  private static int[] getDrawablePixels(Drawable drawable) {
    Bitmap bitmap = Bitmap.createBitmap(
        drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    drawable.draw(new Canvas(bitmap));

    int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
    bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
    return pixels;
  }
}


text:
/**
 * @file
 */

#include <org/opensplice/core/Mutex.hpp>
#include <org/opensplice/core/ReportUtils.hpp>

org::opensplice::core::Mutex::Mutex()
{
    os_result osr;

    osr = os_mutexInit(&this->mtx, NULL);
    if (osr != os_resultSuccess) {
        ISOCPP_THROW_EXCEPTION(ISOCPP_ERROR, "Could not initialize mutex.");
    }

}

org::opensplice::core::Mutex::~Mutex()
{
    os_mutexDestroy(&this->mtx);
}

void
org::opensplice::core::Mutex::lock() const
{
    os_mutexLock((os_mutex *)&this->mtx);
}

bool
org::opensplice::core::Mutex::try_lock() const
{
    os_result osr = os_mutexTryLock((os_mutex *)&this->mtx);
    if (osr == os_resultSuccess) { return true;  }
    if (osr == os_resultBusy   ) { return false; }
    assert(false);
    return false;
}

void
org::opensplice::core::Mutex::unlock() const
{
    os_mutexUnlock((os_mutex *)&this->mtx);
}

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Spoom\Core;

use Spoom\Core\Helper\Collection;
use Spoom\Core\Helper;
use Spoom\Core\Helper\Number;
use Spoom\Core\Helper\Text;

//
interface StorageInterface extends \ArrayAccess, \Iterator, \Countable {

  /**
   * Key separator in the indexes
   */
  const SEPARATOR_KEY = '.';
  /**
   * Separator char for the namespace in the indexes
   */
  const SEPARATOR_NAMESPACE = ':';
  /**
   * Type forcing separator in the indexes
   */
  const SEPARATOR_TYPE = '!';

  /**
   * Text result type
   */
  const TYPE_STRING = 'string';
  /**
   * Number (int or float) result type
   */
  const TYPE_NUMBER = 'number';
  /**
   * Int result type
   */
  const TYPE_INTEGER = 'integer';
  /**
   * Float result type
   */
  const TYPE_FLOAT = 'float';
  /**
   * Boolean result type
   */
  const TYPE_BOOLEAN = 'boolean';
  /**
   * Array result type
   */
  const TYPE_ARRAY = 'array';
  /**
   * Object result type
   */
  const TYPE_OBJECT = 'object';
  /**
   * Callable result type
   */
  const TYPE_CALLABLE = 'callable';

  /**
   * Get any value from the storage
   *
   * @param string $index
   * @param mixed  $default
   *
   * @return mixed
   */
  public function get( string $index, $default = null );
  /**
   * Get indexed (only string type) value from the storage
   *
   * ..or the second parameter if index not exist or not string
   *
   * @param string      $index   The index in the storage
   * @param string|null $default The returned value if index not found
   *
   * @return string|null
   */
  public function getString( string $index, ?string $default = '' ): ?string;
  /**
   * Get indexed (only number type) value from the storage
   *
   * ..or the second parameter if index not exist, not int or
   * float
   *
   * @param string         $index   The index in the storage
   * @param int|float|null $default The returned value if index not found
   *
   * @return int|float|null
   */
  public function getNumber( string $index, $default = 0 );
  /**
   * Get indexed (only int type) value from the storage
   *
   * ..or the second parameter if index not exist, not int or
   * float
   *
   * @param string   $index   The index in the storage
   * @param int|null $default The returned value if index not found
   *
   * @return int|null
   */
  public function getInteger( string $index, ?int $default = 0 ): ?int;
  /**
   * Get indexed (only float type) value from the storage
   *
   * ..or the second parameter if index not exist, not int or
   * float
   *
   * @param string     $index   The index in the storage
   * @param float|null $default The returned value if index not found
   *
   * @return float|null
   */
  public function getFloat( string $index, ?float $default = 0.0 ): ?float;
  /**
   * Get indexed (only array type) value from the storage
   *
   * ..or the second parameter if index not exist or not a
   * collection. Object will be typecasted to array
   *
   * @param string     $index   The index in the storage
   * @param array|null $default The returned value if index not found
   *
   * @return array|null
   */
  public function getArray( string $index, ?array $default = [] ): ?array;
  /**
   * Get indexed (only object type) value from the storage
   *
   * ..or the second parameter if index not exist or not a
   * collection. Arrays will be typecasted to object
   *
   * @param string      $index   The index in the storage
   * @param object|null $default The returned value if index not found
   *
   * @return object|null
   */
  public function getObject( string $index, $default = null );
  /**
   * Get indexed (only bool type) value from the storage
   *
   * ..or the second parameter if index not exist, not bool
   * or not 1/0 value
   *
   * @param string    $index   The index in the storage
   * @param bool|null $default The returned value if index not found
   *
   * @return bool|null
   */
  public function getBoolean( string $index, ?bool $default = false ): ?bool;
  /**
   * Get indexed (only callable type) value from the storage
   *
   * ..or the second parameter if index not exist or not
   * callable
   *
   * @param string        $index   The index in the storage
   * @param callable|null $default The returned value if index not found
   *
   * @return callable|null
   */
  public function getCallable( string $index, ?callable $default = null ): ?callable;
  /**
   * Same as the getString method, but insert data to string with Text::insert()
   *
   * @param string       $index
   * @param array|object $insertion
   * @param string|null  $default
   *
   * @return string|null
   */
  public function getPattern( string $index, $insertion, ?string $default = '' ): ?string;

  /**
   * @return bool
   */
  public function isCaching(): bool;
  /**
   * @param bool $value
   */
  public function setCaching( bool $value = true );
  /**
   * @return array|object
   */
  public function getSource();
}

//
class Storage implements StorageInterface, Helper\AccessableInterface {
  use Helper\Accessable;

  /**
   * Cache for search results
   *
   * @var StorageMetaSearch[]
   */
  private $cache = [];

  /**
   * @var int
   */
  private $iterator_cursor = 0;
  /**
   * @var array
   */
  private $iterator_key = [];

  /**
   * Use caching or not
   *
   * @var bool
   */
  private $_caching = false;
  /**
   * Internal data storage
   *
   * @var array
   */
  private $_source = [];

  /**
   * @param array|object $source
   * @param bool         $caching
   *
   * @throws \TypeError Wrong type of source
   */
  public function __construct( $source, bool $caching = true ) {
    if( !Collection::is( $source ) ) throw new \TypeError( 'Storage can contain only array or object' );
    else {

      $this->_caching = $caching;
      $this->_source  = $source;
    }
  }

  /**
   * Create deep copy from the source and clears the cache
   */
  public function __clone() {

    $this->_source = Collection::copy( $this->_source );
    $this->cache   = [];
  }

  //
  public function get( string $index, $default = null ) {
    $tmp = $this[ $index ];
    return $tmp ?? $default;
  }
  //
  public function getString( string $index, ?string $default = '' ): ?string {
    $tmp = $this[ $index . static::SEPARATOR_TYPE . static::TYPE_STRING ];
    return $tmp ?? $default;
  }
  //
  public function getNumber( string $index, $default = 0 ) {
    $tmp = $this[ $index . static::SEPARATOR_TYPE . static::TYPE_NUMBER ];
    return $tmp ?? $default;
  }
  //
  public function getInteger( string $index, ?int $default = 0 ): ?int {
    $tmp = $this[ $index . static::SEPARATOR_TYPE . static::TYPE_INTEGER ];
    return $tmp ?? $default;
  }
  //
  public function getFloat( string $index, ?float $default = 0.0 ): ?float {
    $tmp = $this[ $index . static::SEPARATOR_TYPE . static::TYPE_FLOAT ];
    return $tmp ?? $default;
  }
  //
  public function getArray( string $index, ?array $default = [] ): ?array {
    $tmp = $this[ $index . static::SEPARATOR_TYPE . static::TYPE_ARRAY ];
    return $tmp ?? $default;
  }
  //
  public function getObject( string $index, $default = null ) {
    $tmp = $this[ $index . static::SEPARATOR_TYPE . static::TYPE_OBJECT ];
    return $tmp ?? $default;
  }
  //
  public function getBoolean( string $index, ?bool $default = false ): ?bool {
    $tmp = $this[ $index . static::SEPARATOR_TYPE . static::TYPE_BOOLEAN ];
    return $tmp ?? $default;
  }
  //
  public function getCallable( string $index, ?callable $default = null ): ?callable {
    $tmp = $this[ $index . static::SEPARATOR_TYPE . static::TYPE_CALLABLE ];
    return $tmp ?? $default;
  }
  //
  public function getPattern( string $index, $insertion, ?string $default = '' ): ?string {

    $tmp = $this->getString( $index, $default );
    return $tmp !== null ? Text::apply( $tmp, $insertion ) : $tmp;
  }

  /**
   * @param StorageMeta $meta
   * @param bool        $build   Build structure if not exist (when true, the third parameter can't be true)
   * @param bool        $is_read The search result will be used to read or write operation (don't use simple cache for write)
   *
   * @return StorageMetaSearch
   */
  protected function search( StorageMeta $meta, bool $build = false, bool $is_read = true ): StorageMetaSearch {

    // check the cache. Only load from cache if its getting ( read operation ) because if it's build then the returned value may changed outside
    if( $this->_caching && $is_read && isset( $this->cache[ $meta->id ] ) ) return $this->cache[ $meta->id ];
    else {

      $result = new StorageMetaSearch( $this->_source, $meta->token, $build );
      if( $this->_caching ) {
        $this->cache[ $meta->id ] = Collection::copy( $result, false );
      }

      return $result;
    }
  }
  /**
   * Clean the search cache based on the index
   *
   * @param string|StorageMeta|null $meta
   */
  protected function clean( $meta = null ) {

    //
    if( $meta && !( $meta instanceof StorageMeta ) ) {
      $meta = $this->getMeta( (string) $meta );
    }

    // clear the cache
    if( !$meta || empty( $meta->token ) ) $this->cache = [];
    else foreach( $this->cache as $i => $_ ) {

      if( empty( $i ) || $i == $meta->token[ 0 ] || strpos( $i, $meta->token[ 0 ] ) === 0 ) {
        unset( $this->cache[ $i ] );
      }
    }
  }

  /**
   * @param string $index
   *
   * @return StorageMeta
   */
  private function getMeta( string $index ): StorageMeta {
    return StorageMeta::instance( $index );
  }

  //
  public function isCaching(): bool {
    return $this->_caching;
  }
  //
  public function setCaching( bool $value = true ) {
    $this->_caching = $value;
    $this->clean();
  }
  //
  public function getSource() {
    return $this->_source;
  }
  /**
   * Set the source directly (mostly for resets)
   *
   * @param \StdClass|\Traversable|array|null $value
   * @param null|string                       $key
   */
  protected function setSource( $value, ?string $key = null ) {
    if( $key === null ) $this->_source = $value === null ? [] : $value;
    else if( $value === null ) unset( $this->_source[ $key ] );
    else $this->_source[ $key ] = $value;

    // reset iterations and clean caches
    $this->rewind();
    $this->clean();
  }

  //
  public function offsetExists( $offset ) {
    return $this->search( $this->getMeta( $offset ) )->exist;
  }
  //
  public function offsetGet( $offset ) {

    // define the default result
    $tmp = $this->search( $index = $this->getMeta( $offset ) );
    if( !$tmp->exist ) $result = null;
    else if( $tmp->key === null ) $result = $tmp->container;
    else if( $tmp->container instanceof StorageInterface ) $result = $tmp->container[ $tmp->key . static::SEPARATOR_TYPE . $index->type ];
    else if( Collection::is( $tmp->container, false, true ) ) $result = $tmp->container[ $tmp->key ];
    else $result = $tmp->container->{$tmp->key};

    // switch result based on the type
    switch( $index->type ) {
      // force string type
      case static::TYPE_STRING:

        if( $tmp->exist && ( Text::is( $result ) ) ) $result = Text::cast( $result );
        else $result = null;

        break;

      // force numeric type
      case 'num':
      case static::TYPE_NUMBER:

        $result = $tmp->exist ? Number::cast( $result, null ) : null;
        break;

      // force integer type
      case 'int':
      case static::TYPE_INTEGER:

        $result = $tmp->exist && Number::is( $result ) ? ( (int) Number::cast( $result ) ) : null;
        break;

      // force float type
      case 'double':
      case 'real':
      case static::TYPE_FLOAT:

        $result = $tmp->exist && Number::is( $result ) ? ( (float) Number::cast( $result ) ) : null;
        break;

      // force array type
      case static::TYPE_ARRAY:

        $result = $tmp->exist ? Collection::cast( $result, null ) : null;
        break;

      // force object type
      case static::TYPE_OBJECT:

        $result = $tmp->exist ? (object) Collection::cast( $result, null ) : null;
        break;

      // force boolean type
      case 'bool':
      case static::TYPE_BOOLEAN:

        $result = $tmp->exist && ( is_bool( $result ) || in_array( $result, [ 1, 0, '1', '0' ], true ) ) ? (bool) $result : null;
        break;

      // force callable type
      case static::TYPE_CALLABLE:

        $result = $tmp->exist && is_callable( $result ) ? $result : null;
        break;
    }

    return $result;
  }
  //
  public function offsetSet( $offset, $value ) {

    $result = $this->search( $index = $this->getMeta( $offset ), true, false );
    if( $result->exist ) {

      if( $result->key === null ) $result->container = $value;
      else if( Collection::is( $result->container, false, true ) ) $result->container[ $result->key ] = $value;
      else $result->container->{$result->key} = $value;

      // clear the cache or the cache index
      if( $this->_caching ) $this->clean( $index );
    }
  }
  //
  public function offsetUnset( $offset ) {

    $result = $this->search( $index = $this->getMeta( $offset ), false, false );
    if( $result->exist ) {

      if( $result->key === null ) $result->container = [];
      else if( Collection::is( $result->container, false, true ) ) unset( $result->container[ $result->key ] );
      else unset( $result->container->{$result->key} );

      // clear the cache or the cache index
      if( $this->_caching ) $this->clean( $index );
    }
  }

  //
  public function current() {
    $tmp = $this->key();
    return is_object( $this->_source ) ? $this->_source->{$tmp} : $this->_source[ $tmp ];
  }
  //
  public function next() {
    ++$this->iterator_cursor;
  }
  //
  public function key() {
    return $this->iterator_key[ $this->iterator_cursor ];
  }
  //
  public function valid() {
    return isset( $this->iterator_key[ $this->iterator_cursor ] );
  }
  //
  public function rewind() {
    $this->iterator_cursor = 0;
    $this->iterator_key    = array_keys( is_object( $this->_source ) ? get_object_vars( $this->_source ) : $this->_source );
  }

  //
  public function count() {
    return count( $this->_source );
  }

  /**
   * @param array|object|StorageInterface $data
   *
   * @return StorageInterface
   * @throws \TypeError
   */
  public static function instance( $data ) {
    return $data instanceof StorageInterface ? $data : new static( $data );
  }
}

//
class StorageMeta {

  /**
   * @var array<StorageMeta>
   */
  protected static $cache = [];

  /**
   * @var string
   */
  public $id = '';
  /**
   * @var string|null
   */
  public $namespace = null;
  /**
   * @var string|null
   */
  public $type;
  /**
   * @var array
   */
  public $token = [];

  /**
   * @param string $index
   */
  public function __construct( string $index ) {

    // trim separators from the index
    $index = trim( $index, " \t\n\r\0\x0B" . StorageInterface::SEPARATOR_KEY );
    $index = ltrim( $index, StorageInterface::SEPARATOR_NAMESPACE );
    $index = rtrim( $index, StorageInterface::SEPARATOR_TYPE );

    // process the index
    $buffer = '';
    for( $i = 0, $length = strlen( $index ); $i < $length; ++$i ) {
      switch( $index{$i} ) {

        // simple token separator
        case StorageInterface::SEPARATOR_KEY:
          if( $buffer !== '' ) $this->token[] = $buffer;
          $buffer = '';
          break;

        // namespace definition
        case StorageInterface::SEPARATOR_NAMESPACE:
          if( $this->namespace === null ) {
            $this->namespace = $this->token[] = $buffer;
            $buffer          = '';
          }
          break;

        // type separator at the end
        case StorageInterface::SEPARATOR_TYPE:
          $this->type = substr( $index, $i + 1 );
          if( $buffer !== '' ) $this->token[] = $buffer;
          $buffer = '';
          break 2;

        default:

          $buffer .= $index{$i};
      }
    }
    if( $buffer !== '' ) $this->token[] = $buffer;

    // define the unique id for this index
    if( $this->namespace ) $this->id .= $this->namespace . StorageInterface::SEPARATOR_NAMESPACE;
    $this->id .= implode( StorageInterface::SEPARATOR_KEY, $this->namespace ? array_slice( $this->token, 1 ) : $this->token );
    if( $this->type ) $this->id .= StorageInterface::SEPARATOR_TYPE . $this->type;
  }

  /**
   * @param string $index
   *
   * @return static
   */
  public static function instance( string $index ) {
    return static::$cache[ $index ] ?? ( static::$cache[ $index ] = new static( $index ) );
  }
}
//
class StorageMetaSearch {

  /**
   * @var bool
   */
  public $exist = true;
  /**
   * @var string|null
   */
  public $key = null;
  /**
   * @var array|object
   */
  public $container;

  /**
   * @param array|object $source
   * @param array        $token
   * @param bool         $build
   */
  public function __construct( &$source, array $token, bool $build ) {

    $this->container = &$source;
    if( count( $token ) ) {

      $this->exist = false;
      for( $count = count( $token ), $i = 0; $i < $count - 1; ++$i ) {

        // check the container type
        if( !Collection::is( $this->container ) ) {

          if( $build ) $this->container = [];
          else return;
        }

        // handle new key check for two different data type
        $key = $token[ $i ];
        if( is_array( $this->container ) ) { // handle like an array

          if( !isset( $this->container[ $key ] ) ) {
            if( $build ) $this->container[ $key ] = [];
            else return;
          }

          // FIXME this reference will ruin your life! DO NOT USE IT! EVER!
          $this->container = &$this->container[ $key ];

        } else if( is_object( $this->container ) ) {   // handle like an object

          if( $this->container instanceof StorageInterface ) break;
          else {

            if( !isset( $this->container->{$key} ) ) {
              if( $build ) $this->container->{$key} = [];
              else return;
            }

            $this->container = &$this->container->{$key};
          }
        }
      }

      // select key if container exist
      $key = implode( StorageInterface::SEPARATOR_KEY, array_slice( $token, $i ) );
      if( Collection::is( $this->container ) ) {

        if( is_array( $this->container ) ) {
          if( !isset( $this->container[ $key ] ) ) {
            if( $build ) $this->container[ $key ] = null;
            else return;
          }
        } else if( !( $this->container instanceof StorageInterface ) ) {
          if( !isset( $this->container->{$key} ) ) {
            if( $build ) $this->container->{$key} = null;
            else return;
          }
        }

        // setup the result
        $this->key   = $key;
        $this->exist = true;
      }
    }
  }
}


text:
package io.truthencode.ddo.model.feats

import io.truthencode.ddo.model.classes.HeroicCharacterClass
import io.truthencode.ddo.model.classes.HeroicCharacterClass.Monk
import io.truthencode.ddo.support.requisite.{FeatRequisiteImpl, GrantsToClass, RequiresAllOfClass}

/**
 * Created by adarr on 3/17/2017.
 */
trait PurityOfBody
  extends FeatRequisiteImpl with Passive with GrantsToClass with RequiresAllOfClass {
  override def grantToClass: Seq[(HeroicCharacterClass, Int)] =
    List((Monk, 5))

  override def allOfClass: Seq[(HeroicCharacterClass, Int)] =
    List((Monk, 5))
}


text:
using NodaTime;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds.Enumerators;
using QuantConnect.Logging;
using QuantConnect.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using HistoryRequest = QuantConnect.Data.HistoryRequest;

namespace QuantConnect.Lean.Engine.HistoricalData
{
    /// <summary>
    /// Provides an implementation of <see cref="IHistoryProvider"/> which
    /// acts as a wrapper to use multiple history providers together
    /// </summary>
    public class HistoryProviderManager : HistoryProviderBase
    {
        private IBrokerage _brokerage;
        private bool _initialized;

        /// <summary>
        /// Collection of history providers being used
        /// </summary>
        /// <remarks>Protected for testing purposes</remarks>
        private List<IHistoryProvider> _historyProviders = new();

        /// <summary>
        /// Gets the total number of data points emitted by this history provider
        /// </summary>
        public override int DataPointCount => GetDataPointCount();

        /// <summary>
        /// Sets the brokerage to be used for historical requests
        /// </summary>
        /// <param name="brokerage">The brokerage instance</param>
        public void SetBrokerage(IBrokerage brokerage)
        {
            _brokerage = brokerage;
        }

        /// <summary>
        /// Initializes this history provider to work for the specified job
        /// </summary>
        /// <param name="parameters">The initialization parameters</param>
        public override void Initialize(HistoryProviderInitializeParameters parameters)
        {
            if (_initialized)
            {
                // let's make sure no one tries to change our parameters values
                throw new InvalidOperationException("BrokerageHistoryProvider can only be initialized once");
            }
            _initialized = true;

            var dataProvidersList = parameters.Job?.HistoryProvider.DeserializeList() ?? new List<string>();
            if (dataProvidersList.IsNullOrEmpty())
            {
                dataProvidersList.AddRange(Config.Get("history-provider", "SubscriptionDataReaderHistoryProvider").DeserializeList());
            }

            foreach (var historyProviderName in dataProvidersList)
            {
                var historyProvider = Composer.Instance.GetExportedValueByTypeName<IHistoryProvider>(historyProviderName);
                if (historyProvider is BrokerageHistoryProvider)
                {
                    (historyProvider as BrokerageHistoryProvider).SetBrokerage(_brokerage);
                }
                historyProvider.Initialize(parameters);
                historyProvider.InvalidConfigurationDetected += (sender, args) => { OnInvalidConfigurationDetected(args); };
                historyProvider.NumericalPrecisionLimited += (sender, args) => { OnNumericalPrecisionLimited(args); };
                historyProvider.StartDateLimited += (sender, args) => { OnStartDateLimited(args); };
                historyProvider.DownloadFailed += (sender, args) => { OnDownloadFailed(args); };
                historyProvider.ReaderErrorDetected += (sender, args) => { OnReaderErrorDetected(args); };
                _historyProviders.Add(historyProvider);
            }

            Log.Trace($"HistoryProviderManager.Initialize(): history providers [{string.Join(",", _historyProviders.Select(x => x.GetType().Name))}]");
        }

        /// <summary>
        /// Gets the history for the requested securities
        /// </summary>
        /// <param name="requests">The historical data requests</param>
        /// <param name="sliceTimeZone">The time zone used when time stamping the slice instances</param>
        /// <returns>An enumerable of the slices of data covering the span specified in each request</returns>
        public override IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone)
        {
            List<IEnumerator<Slice>> historyEnumerators = new(_historyProviders.Count);
            var historyRequets = requests.ToList();
            foreach (var historyProvider in _historyProviders)
            {
                try
                {
                    var history = historyProvider.GetHistory(historyRequets, sliceTimeZone);
                    historyEnumerators.Add(history.GetEnumerator());
                }
                catch (Exception e)
                {
                    // ignore
                }
            }
            using var synchronizer = new SynchronizingSliceEnumerator(historyEnumerators);
            Slice latestMergeSlice = null;
            while (synchronizer.MoveNext())
            {
                if (synchronizer.Current == null)
                {
                    continue;
                }
                if (latestMergeSlice == null)
                {
                    latestMergeSlice = synchronizer.Current;
                    continue;
                }
                if (synchronizer.Current.UtcTime > latestMergeSlice.UtcTime)
                {
                    // a newer slice we emit the old and keep a reference of the new
                    // so in the next loop we merge if required
                    yield return latestMergeSlice;
                    latestMergeSlice = synchronizer.Current;
                }
                else
                {
                    // a new slice with same time we merge them into 'latestMergeSlice'
                    latestMergeSlice.MergeSlice(synchronizer.Current);
                }
            }
            if (latestMergeSlice != null)
            {
                yield return latestMergeSlice;
            }
        }

        private int GetDataPointCount()
        {
            var dataPointCount = 0;
            foreach (var historyProvider in _historyProviders)
            {
                dataPointCount += historyProvider.DataPointCount;
            }
            return dataPointCount;
        }
    }
}


text:
package docker

import (
	"context"

	"github.com/alexei-led/pumba/pkg/chaos"
	"github.com/alexei-led/pumba/pkg/container"
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
)

// `docker kill` command
type removeCommand struct {
	client  container.Client
	names   []string
	pattern string
	labels  []string
	force   bool
	links   bool
	volumes bool
	limit   int
	dryRun  bool
}

// NewRemoveCommand create new Kill Command instance
func NewRemoveCommand(client container.Client, params *chaos.GlobalParams, force, links, volumes bool, limit int) chaos.Command {
	remove := &removeCommand{
		client:  client,
		names:   params.Names,
		pattern: params.Pattern,
		labels:  params.Labels,
		force:   force,
		links:   links,
		volumes: volumes,
		limit:   limit,
		dryRun:  params.DryRun,
	}
	return remove
}

// Run remove command
func (r *removeCommand) Run(ctx context.Context, random bool) error {
	log.Debug("removing all matching containers")
	log.WithFields(log.Fields{
		"names":   r.names,
		"pattern": r.pattern,
		"labels":  r.labels,
		"limit":   r.limit,
		"random":  random,
	}).Debug("listing matching containers")
	containers, err := container.ListNContainers(ctx, r.client, r.names, r.pattern, r.labels, r.limit)
	if err != nil {
		return errors.Wrap(err, "error listing containers")
	}
	if len(containers) == 0 {
		log.Warning("no containers to remove")
		return nil
	}

	// select single random container from matching container and replace list with selected item
	if random {
		if c := container.RandomContainer(containers); c != nil {
			containers = []*container.Container{c}
		}
	}

	for _, container := range containers {
		log.WithFields(log.Fields{
			"container": container,
			"force":     r.force,
			"links":     r.links,
			"volumes":   r.volumes,
		}).Debug("removing container")
		c := container
		err = r.client.RemoveContainer(ctx, c, r.force, r.links, r.volumes, r.dryRun)
		if err != nil {
			return errors.Wrap(err, "failed to remove container")
		}
	}
	return nil
}


text:
package com.tom.factory.tileentity;

import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;

import com.tom.lib.api.energy.EnergyStorage;
import com.tom.recipes.handler.MachineCraftingHandler;
import com.tom.recipes.handler.MachineCraftingHandler.ItemStackChecker;

public class TileEntityLaserEngraver extends TileEntityMachineBase {
	private EnergyStorage energy = new EnergyStorage(50000, 100);
	public int clientEnergy = 0;
	private int maxProgress = 0;

	@Override
	public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) {
		return index == 0 || index == 4;
	}

	@Override
	public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction) {
		return index == 1;
	}

	@Override
	public int getSizeInventory() {
		return 4;
	}

	@Override
	public boolean isItemValidForSlot(int index, ItemStack stack) {
		return true;
	}

	@Override
	public String getName() {
		return "laserEngraver";
	}

	@Override
	public EnergyStorage getEnergy() {
		return energy;
	}

	@Override
	public int getUpgradeSlot() {
		return 3;
	}

	@Override
	public int getMaxProcessTimeNormal() {
		return 2;
	}

	@Override
	public void readFromNBT(NBTTagCompound compound) {
		super.readFromNBT(compound);
		this.progress = compound.getInteger("progress");
		this.maxProgress = compound.getInteger("maxProgress");
	}

	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound compound) {
		super.writeToNBT(compound);
		compound.setInteger("progress", progress);
		compound.setInteger("maxProgress", maxProgress);
		return compound;
	}

	public int getClientEnergyStored() {
		return MathHelper.ceil(energy.getEnergyStored());
	}

	public long getMaxEnergyStored() {
		return energy.getMaxEnergyStored();
	}

	@Override
	public void updateProgress() {
		int upgradeC = getSpeedUpgradeCount();
		int p = upgradeC + MathHelper.floor(10 * (getMaxProcessTimeNormal() / TYPE_MULTIPLIER_SPEED[getType()])) + (upgradeC / 2);
		progress = Math.max(0, progress - p);
		energy.extractEnergy(2 * p, false);
	}
	@Override
	public int getField(int id) {
		return id == 1 ? maxProgress : super.getField(id);
	}

	@Override
	public ResourceLocation getFront() {
		return new ResourceLocation("tomsmodfactory:textures/blocks/laserEngraver.png");
	}

	@Override
	public int[] getOutputSlots() {
		return new int[]{1};
	}

	@Override
	public int[] getInputSlots() {
		return new int[]{0};
	}

	@Override
	public void checkItems() {
		int lvl = 2 - getType();
		ItemStackChecker s = MachineCraftingHandler.getLaserEngraverOutput(inv.getStackInSlot(0), inv.getStackInSlot(2));
		if (s != null && s.getExtra4() <= lvl) {
			checkItems(s, 1, maxProgress = s.getExtra3(), 0, -1);
			setOut(0, s);
		}
	}

	@Override
	public void finish() {
		addItemsAndSetProgress(getOutput(0), 1, 0, -1);
	}
}


text:
<?php

namespace Cv\Entity;

use Core\Entity\EntityInterface;

interface LanguageInterface extends EntityInterface
{

    /*
     * name of the language de,en,fr
     */
    public function setLanguage($language);
    public function getLanguage();

    /*
     * A1 - C2
     */
    public function setLevelListening($level);
    public function getLevelListening();
    public function setLevelReading($level);
    public function getLevelReading();
    public function setLevelSpokenInteraction($level);
    public function getLevelSpokenInteraction();
    public function setLevelSpokenProduction($level);
    public function getLevelSpokenProduction();
    public function setLevelWriting($level);
    public function getLevelWriting();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2021 The Android Open Source Project

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
   -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="appsearch_no_documents_error" msgid="7957333381856121779">"ڈیٹا بیس میں AppSearch کی کوئی دستاویز نہیں ملی۔ توثیق کریں کہ ڈیٹا بیس کا نام درست ہے اور اسٹوریج کی صحیح قسم منتخب کی گئی تھی۔"</string>
    <string name="appsearch_no_schema_types_error" msgid="5825283982305113887">"AppSearch سکیما کی کوئی قسم نہیں ملی۔ توثیق کریں کہ ڈیٹا بیس کا نام درست ہے اور اسٹوریج کی صحیح قسم منتخب کی گئی تھی۔"</string>
    <string name="appsearch_documents_loading" msgid="1689893533003672860">"AppSearch کی دستاویزات لوڈ ہو رہی ہیں..."</string>
    <string name="appsearch_schema_types_loading" msgid="4961123108404531766">"AppSearch سکیما کی اقسام لوڈ ہو رہی ہیں..."</string>
    <string name="appsearch_schema_version" msgid="7000254633719373917">"سکیما ورژن: %d"</string>
</resources>


text:
using Newtonsoft.Json;
namespace LoginRadiusSDK.V2.Models.ResponseModels

{

    /// <summary>
    ///	Response containing consent version information
    /// </summary>
    public class ConsentVersions
    {
		/// <summary>
		///	Allowed events: Login, Register, UpdateProfile, ResetPassword, ChangePassword, emailVerification, AddEmail, RemoveEmail, BlockAccount, DeleteAccount, SetUsername, AssignRoles, UnassignRoles, SetPassword, LinkAccount, UnlinkAccount, UpdatePhoneId, VerifyPhoneNumber, CreateCustomObject, UpdateCustomobject, DeleteCustomObject
		/// </summary>
		[JsonProperty(PropertyName = "Event")]
        public  string Event {get;set;}

		/// <summary>
		///	true/false
		/// </summary>
		[JsonProperty(PropertyName = "IsCustom")]
        public  bool? IsCustom {get;set;}

		/// <summary>
		///	privacy policy version
		/// </summary>
		[JsonProperty(PropertyName = "Version")]
        public  int? Version {get;set;}

    }
}


text:
package com.codahale.metrics.ehcache;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;

import static com.codahale.metrics.MetricRegistry.name;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assume.assumeThat;

public class InstrumentedCacheDecoratorFactoryTest {
    private static final CacheManager MANAGER = CacheManager.create();

    private MetricRegistry registry;
    private Ehcache cache;

    @Before
    public void setUp() throws Exception {
        this.cache = MANAGER.getEhcache("test-config");
        assumeThat(cache, is(CoreMatchers.notNullValue()));

        this.registry = SharedMetricRegistries.getOrCreate("cache-metrics");
    }

    @Test
    public void measuresGets() throws Exception {
        cache.get("woo");

        assertThat(registry.timer(name(Cache.class, "test-config", "gets")).getCount())
                .isEqualTo(1);

    }

    @Test
    public void measuresPuts() throws Exception {
        cache.put(new Element("woo", "whee"));

        assertThat(registry.timer(name(Cache.class, "test-config", "puts")).getCount())
                .isEqualTo(1);
    }
}


text:
use std::sync::Once;
static START: Once = Once::new();

mod utils;

mod wolf {
    use crate::START;
    use lumol::input::Input;
    use lumol::units;
    use std::path::Path;

    #[test]
    fn constant_energy() {
        START.call_once(::env_logger::init);
        let path = Path::new(file!()).parent()
                                     .unwrap()
                                     .join("data")
                                     .join("md-nacl")
                                     .join("nve-wolf-small.toml");
        let mut config = Input::new(path).unwrap().read().unwrap();

        let e_initial = config.system.total_energy();
        config.simulation.run(&mut config.system, config.nsteps);

        let e_final = config.system.total_energy();
        assert!(f64::abs((e_initial - e_final) / e_final) < 1e-4);
    }

    #[test]
    fn anisotropic_berendsen() {
        START.call_once(::env_logger::init);
        let path = Path::new(file!()).parent()
                                     .unwrap()
                                     .join("data")
                                     .join("md-nacl")
                                     .join("npt-wolf-small.toml");
        let mut config = Input::new(path).unwrap().read().unwrap();

        let collector = crate::utils::Collector::starting_at(9000);
        let temperatures = collector.temperatures();
        let pressures = collector.pressures();

        config.simulation.add_output(Box::new(collector));
        config.simulation.run(&mut config.system, config.nsteps);

        let expected = units::from(50000.0, "bar").unwrap();
        let pressure = crate::utils::mean(pressures);
        assert!(f64::abs(pressure - expected) / expected < 2e-3);

        let expected = units::from(273.0, "K").unwrap();
        let temperature = crate::utils::mean(temperatures);
        assert!(f64::abs(temperature - expected) / expected < 1e-2);
    }
}

mod ewald {
    use crate::START;
    use lumol::input::Input;
    use std::path::Path;

    #[test]
    fn constant_energy() {
        START.call_once(::env_logger::init);
        let path = Path::new(file!()).parent()
                                     .unwrap()
                                     .join("data")
                                     .join("md-nacl")
                                     .join("nve-ewald-small.toml");
        let mut config = Input::new(path).unwrap().read().unwrap();

        let e_initial = config.system.total_energy();
        config.simulation.run(&mut config.system, config.nsteps);
        let e_final = config.system.total_energy();
        assert!(f64::abs((e_initial - e_final) / e_final) < 5e-3);
    }

    #[test]
    fn constant_energy_kspace() {
        START.call_once(::env_logger::init);
        let path = Path::new(file!()).parent()
                                     .unwrap()
                                     .join("data")
                                     .join("md-nacl")
                                     .join("nve-ewald-kspace.toml");
        let mut config = Input::new(path).unwrap().read().unwrap();

        let e_initial = config.system.total_energy();
        config.simulation.run(&mut config.system, config.nsteps);
        let e_final = config.system.total_energy();
        assert!(f64::abs((e_initial - e_final) / e_final) < 5e-3);
    }
}


text:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragment"
    android:name="com.abhi.koinarc.MainWithFragmentActivityFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:layout="@layout/fragment_main_with_fragment" />


text:
Sublime Text 3 (not realy support ST2) package for better Symfony 2 usage.

## Instalation

### Manual installation

```sh
git clone git@github.com:sergeylunev/sublimated-symfony.git \
    ~/Library/Application\ Support/Sublime\ Text\ 3/Packages/sublimated-symfony
```

## Usage

### Switch betwen action and view

`ctrl+alt+p` — if pressed in Action opens template file (or create file and open it).
If pressed in template file — open Controller on Action file related to this template

### Switch betwen entity and repository

`ctrl+alt+g` — If pressed in Entity it send you to Repository class witch is
presented in `@ORM\Entity(repositoryClass="Acme\DemoBundle\Entity\Repository\DemoRepository")`.
If pressed in Repository it send you to entity class file with the same name as
Repository `DemoRepository` → `Demo`

### Importing `use` statements

`ctrl+alt+u` — automaticaly add `use` statement when cursor placed on some object
defenition (`new FooBar()`)

### Importing `namespace` related to file

`ctrl+alt+n` — automaticaly add `namespace` statement related to file (please look
for [PSR-0][1] for better understanding)

TODO:
- add some screencasts to illustrate how it works
- working with symfony commands
- jump from inline in twig template to another template or to action/controller
- jump to twig file if we have named in annotation
- add commands execution from ST
- working with routes and other stuff
- try add GoTo by route, actions, entity, repository and other
- workign with generators from editor
- go to template file from twig render or include
- copy methods from interface class

Complete:
- insert `namespace` related to the file
- jump between entity and repository classes

[1]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace TraceMe.Hubs
{
    public class TraceHub : Hub
    {
        public void Dummy()
        {

        }

        public static void Trace(string hook, IPrincipal user, string message)
        {
            var hub = GlobalHost.ConnectionManager.GetHubContext<TraceHub>();

            hub.Clients.All.traceEntry(hook, user.Identity.IsAuthenticated ? user.Identity.Name : "Anonymous", message);
        }
    }
}


text:
package com.mozu.api.security;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.text.SimpleDateFormat;
import java.util.Date;

import mockit.Expectations;
import mockit.Mocked;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Test;

import com.mozu.api.ApiContext;
import com.mozu.api.MozuApiContext;
import com.mozu.api.contracts.appdev.AppAuthInfo;

public class CryptoTest {
	private static final String TEST_SHARED_SECRET = "bc0aa4944cc74341b59ba2fc01666571";

	@Mocked AppAuthenticator mockAppAuthenticator;

    @Test
    public void testCryptoHash () throws Exception {
        String body = "x-vol-tenant-domain=t419.sandbox.mozu-qa.com&x-vol-return-url=https://t419.sandbox.mozu-qa.com/Admin/s-1223/capability/edit/7d7fadf25e9f454eb6cc87df888395ea/#configure";
        String secretKey = "b2dc973d5dec4bd6aa325fa906a64aee";
        String dateString = "Mon, 18 Aug 2014 21:07:21 GMT";
        // Test that values going through the crypto work...
        String hash1 = Crypto.getHash(secretKey, dateString, body);
        String hash2 = Crypto.getHash(secretKey, dateString, body);

        assertEquals(hash1, hash2);

        assertEquals("yJ+gMQm3FZzKfgySi+1jGYcUcSADVjr3x19BwKyFj9w=", hash1);
    }

    @Mocked AppAuthInfo mockAppAuthInfo;

    @Test
    public void validRequestTest() {

        new Expectations() {
            {
                AppAuthenticator.initialize(mockAppAuthInfo);
                AppAuthenticator.getInstance(); returns(mockAppAuthenticator);
                mockAppAuthenticator.getAppAuthInfo(); returns(mockAppAuthInfo);
            }
            { mockAppAuthInfo.getSharedSecret(); returns(TEST_SHARED_SECRET); }
        };

        String body = "This is a test of the crypto validation";
        AppAuthenticator.initialize(mockAppAuthInfo);

        ApiContext apiContext = new MozuApiContext();

        DateTime dTime = new DateTime();
        DateTimeFormatter dtf = DateTimeFormat.forPattern("E, dd MMM yyyy HH:mm:ss zzz");

        String dateString = dtf.print(dTime);
        System.out.println(dateString);

        apiContext.setHeaderDate(dateString);
        String hmacSha256 = Crypto.getHash(TEST_SHARED_SECRET, dateString, body);
        apiContext.setHmacSha256(hmacSha256);

        assertTrue(Crypto.isRequestValid(apiContext, body));

    }

    @Test
    public void oldRequestTest() {
        new Expectations() {
            {
                AppAuthenticator.initialize(mockAppAuthInfo);
                AppAuthenticator.getInstance(); returns(mockAppAuthenticator);
                mockAppAuthenticator.getAppAuthInfo(); returns(mockAppAuthInfo);
            }
            { mockAppAuthInfo.getSharedSecret(); returns(TEST_SHARED_SECRET); }
        };

        String body = "This is a test of the crypto validation";
        AppAuthenticator.initialize(mockAppAuthInfo);

        ApiContext apiContext = new MozuApiContext();

        SimpleDateFormat sdf  = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zzz");
        long cur = new Date().getTime();
        cur = cur - (181*1000);
        String dateString = sdf.format(new Date(cur));

        apiContext.setHeaderDate(dateString);
        String hmacSha256 = Crypto.getHash(TEST_SHARED_SECRET, dateString, body);
        apiContext.setHmacSha256(hmacSha256);

        assertFalse(Crypto.isRequestValid(apiContext, body));

    }
}


text:
import { FORM_ERROR } from 'final-form'
import * as React from 'react'
import * as RF from 'react-final-form'
import * as redux from 'react-redux'
import { useHistory } from 'react-router-dom'

import Working from 'components/Working'
import * as NamedRoutes from 'utils/NamedRoutes'
import * as Sentry from 'utils/Sentry'
import Link from 'utils/StyledLink'
import defer from 'utils/defer'
import validate, * as validators from 'utils/validators'

import * as Layout from './Layout'
import { useSignOut } from './SignOut'
import { changePassword } from './actions'
import * as errors from './errors'
import * as selectors from './selectors'

const Container = Layout.mkLayout('Change Password')

function SignOut() {
  const waiting = redux.useSelector(selectors.waiting)
  const signOutRef = React.useRef<() => void>()
  signOutRef.current = useSignOut()
  React.useEffect(() => {
    if (!waiting) signOutRef.current!()
  }, [waiting, signOutRef])
  return (
    <Container>
      <Working style={{ textAlign: 'center' }}>Signing out</Working>
    </Container>
  )
}

interface FormProps {
  onSuccess(): void
  link: string
}

function Form({ onSuccess, link }: FormProps) {
  const { urls } = NamedRoutes.use()
  const sentry = Sentry.use()
  const dispatch = redux.useDispatch()

  const onSubmit = async ({ password }: { password: string }) => {
    try {
      const result = defer()
      dispatch(changePassword(link, password, result.resolver))
      await result.promise
      onSuccess()
      return undefined
    } catch (e) {
      if (e instanceof errors.PassChangeInvalidToken) {
        return { [FORM_ERROR]: 'invalidToken' }
      }
      if (e instanceof errors.PassChangeNotAllowed) {
        return { [FORM_ERROR]: 'notAllowed' }
      }
      if (e instanceof errors.PassChangeUserNotFound) {
        return { [FORM_ERROR]: 'userNotFound' }
      }
      if (e instanceof errors.InvalidPassword) {
        return { [FORM_ERROR]: 'invalid' }
      }
      sentry('captureException', e)
      return { [FORM_ERROR]: 'unexpected' }
    }
  }

  return (
    <Container>
      <RF.Form onSubmit={onSubmit}>
        {({
          error,
          handleSubmit,
          hasSubmitErrors,
          hasValidationErrors,
          modifiedSinceLastSubmit,
          submitError,
          submitFailed,
          submitting,
        }) => (
          <form onSubmit={handleSubmit}>
            <RF.Field
              // @ts-expect-error
              component={Layout.Field}
              name="password"
              type="password"
              // @ts-expect-error
              validate={validators.required}
              disabled={submitting}
              floatingLabelText="New password"
              errors={{
                required: 'Enter a password',
              }}
            />
            <RF.Field
              // @ts-expect-error
              component={Layout.Field}
              name="passwordCheck"
              type="password"
              validate={validators.composeAsync(
                validators.required,
                validate('check', validators.matchesField('password')),
              )}
              disabled={submitting}
              floatingLabelText="Re-enter your new password"
              errors={{
                required: 'Enter the password again',
                check: 'Passwords must match',
              }}
              fullWidth
            />
            <Layout.Error
              {...{
                submitFailed,
                error: error || (!modifiedSinceLastSubmit && submitError),
              }}
              errors={{
                invalidToken: (
                  <>
                    This reset link is invalid (probably expired). Try{' '}
                    <Link to={urls.passReset()}>resetting password</Link> again.
                  </>
                ),
                invalid: 'Password must be at least 8 characters long',
                notAllowed: 'You are not allowed to set password.',
                userNotFound:
                  'User not found for this reset link. Please contact support.',
                unexpected: 'Something went wrong. Try again later.',
              }}
            />
            <Layout.Actions>
              <Layout.Submit
                label="Change Password"
                disabled={
                  submitting ||
                  (hasValidationErrors && submitFailed) ||
                  (hasSubmitErrors && !modifiedSinceLastSubmit)
                }
                busy={submitting}
              />
            </Layout.Actions>
          </form>
        )}
      </RF.Form>
    </Container>
  )
}

function Success() {
  const { urls } = NamedRoutes.use()
  return (
    <Container>
      <Layout.Message>Your password has been changed.</Layout.Message>
      <Layout.Message>
        <>
          Now you can <Link to={urls.signIn()}>sign in</Link> using your new password.
        </>
      </Layout.Message>
    </Container>
  )
}

const LINK_PLACEHOLDER = '_'

interface PassChangeProps {
  match: { params: { link: string } }
}

export default function PassChange({
  match: {
    params: { link },
  },
}: PassChangeProps) {
  const { urls } = NamedRoutes.use()

  const authenticated = redux.useSelector(selectors.authenticated)
  const [done, setDone] = React.useState(false)
  const onSuccess = React.useCallback(() => setDone(true), [setDone])

  const [storedLink] = React.useState(link)
  const history = useHistory()
  const cleanUrl = urls.passChange(LINK_PLACEHOLDER)

  React.useEffect(() => {
    if (link !== LINK_PLACEHOLDER) history.replace(cleanUrl)
  }, [link, history, cleanUrl])

  if (authenticated) return <SignOut />
  if (done) return <Success />
  return <Form {...{ onSuccess, link: storedLink }} />
}


text:
@implementation Channel

@synthesize activated;
@synthesize channelAddresses;
@synthesize channelNo;

- (NSString *)description {
	if ((description == nil) || ([description isEqualToString:@""])) {
		if ([self channelNo] == -1) {
			return @"[unknown]";
		} else {
			return [NSString stringWithFormat:@"%d", [self channelNo]];
		}
	} else {
		return description;
	}
}
- (void)setDescription:(NSString *)value {
	if (value != description) {
		[description release];
		[self willChangeValueForKey:@"description"];
		description = [[value copy] retain];
		[self didChangeValueForKey:@"description"];
	}
}

+ (Channel *)channelWithChannel:(NSInteger)lNumber {
	return [[[Channel alloc] initWithChannel:lNumber] autorelease];
}
- (id)initWithChannel:(NSInteger)lNumber {
	self = [super init];
	if (self != nil) {
		[self setActivated:YES];
		channelNo = lNumber;
		channelAddresses = [[NSArray array] retain];
		[self setDescription:[NSString string]];

		[self activateObserving];
	}
	return self;
}
- (id)init {
	return [self initWithChannel:[[Services sharedServices] getNewChannelNumberFrom:1 positive:YES]];
}
- (void)dealloc {
	[self deactivateObserving];

	[description release];
	[channelAddresses release];

	[super dealloc];
}

- (id)initWithCoder:(NSCoder *)coder {
	self = [super init];
	if (self != nil) {
		[self setActivated:[coder decodeBoolForKey:@"activated"]];
		[self setDescription:[coder decodeObjectForKey:@"description"]];
		channelNo = [coder decodeIntForKey:@"channelNo"];
		channelAddresses = [[NSArray array] retain];

		NSArray *addressList = [[coder decodeObjectForKey:@"addresses"] retain];
		NSMutableArray *tempArray;

		Services *services = [Services sharedServices];
		if (services != nil) {
			NSArray *availableChannelAddresses = [services channelAddressesFromTuner];

			NSEnumerator *addressEnum = [addressList objectEnumerator];
			NSString *currentAddressId;
			while(currentAddressId = [addressEnum nextObject]) {
				NSEnumerator *availableChannelAddressesEnum = [availableChannelAddresses objectEnumerator];
				HDChannelAddress *availableChannelAddress;
				while(availableChannelAddress = [availableChannelAddressesEnum nextObject]) {
					if ([[availableChannelAddress uniqueId] isEqualToString:currentAddressId]) {
						tempArray = [[self channelAddresses] mutableCopy];
						[tempArray addObject:availableChannelAddress];
						[self setChannelAddresses:tempArray];
						break;
					}
				}
			}
		}

		[self activateObserving];
	}
	return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
	[coder encodeBool:[self activated] forKey:@"activated"];
	[coder encodeObject:[self description] forKey:@"description"];
	[coder encodeInt:[self channelNo] forKey:@"channelNo"];

	NSMutableArray *addressList = [NSMutableArray array];
	NSEnumerator *addressEnum = [[self channelAddresses] objectEnumerator];
	HDChannelAddress *currentAddress;
	while(currentAddress = [addressEnum nextObject]) {
		[addressList addObject:[currentAddress uniqueId]];
	}
	[coder encodeObject:addressList forKey:@"addresses"];
}
- (id)copyWithZone:(NSZone *)zone {
    Channel *copy = [[self class] allocWithZone: zone];

	[copy initWithChannel:[self channelNo]];

	[copy setActivated:[self activated]];
	[copy setChannelAddresses:[self channelAddresses]];
	[copy setDescription:[self description]];

    return copy;
}

- (void)activateObserving {
	[self addObserver:self forKeyPath:@"channelAddresses" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)deactivateObserving {
	[self removeObserver:self forKeyPath:@"channelAddresses"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqual:@"channelAddresses"]) {
		[[Services sharedServices] informationUpdated];
    }
}

- (BOOL)isValid {
	BOOL result = YES;

	NSEnumerator *addressEnum = [[self channelAddresses] objectEnumerator];
	HDChannelAddress *currentAddress;
	NSMutableArray *response = [NSMutableArray array];
	while(currentAddress = [addressEnum nextObject]) {
		result = result && [currentAddress isValidWithResponse:response];
	}

	// Write response messages
	NSEnumerator *responseEnum = [response objectEnumerator];
	NSString *responseText;
	while(responseText = [responseEnum nextObject]) {
		[Services globalMessage:responseText];
	}

	if ([self channelNo] == -1) {
		[Services globalMessage:[NSString stringWithFormat:@"Channel number for channel %@ is unknown.", self]];
		result = NO;
	}

	Services *services = [Services sharedServices];
	if (services != nil) {
		NSArray *tunerChannelAddresses = [services channelAddressesFromTuner];
		BOOL found;

		NSEnumerator *channelChannelAddressesEnum = [[self channelAddresses]  objectEnumerator];
		HDChannelAddress *channelChannelAddress;
		while(channelChannelAddress = [channelChannelAddressesEnum nextObject]) {
			found = NO;

			NSEnumerator *tunerChannelAddressesEnum = [tunerChannelAddresses objectEnumerator];
			HDChannelAddress *tunerChannelAddress;
			while(tunerChannelAddress = [tunerChannelAddressesEnum nextObject]) {
				if (tunerChannelAddress == channelChannelAddress) {
					found = YES;
				}
			}

			if (!found) {
				[Services globalMessage:[NSString stringWithFormat:@"Channel address %@ is not in tuner list.", tunerChannelAddress]];
				result = NO;
			}
		}
	}

	return result;
}
- (BOOL)repair:(BOOL)force {
	Services *services = [Services sharedServices];

	if ([self channelNo] == -1) {
		if (services == nil) {
			return NO;
		} else {
			[self setChannelNo:[services getNewChannelNumberFrom:1 positive:YES]];
		}
	}

	if (services != nil) {
		NSArray *tunerChannelAddresses = [services channelAddressesFromTuner];
		NSMutableArray *removeList = [NSMutableArray array];
		BOOL found;

		NSEnumerator *channelChannelAddressesEnum = [[self channelAddresses]  objectEnumerator];
		HDChannelAddress *channelChannelAddress;
		while(channelChannelAddress = [channelChannelAddressesEnum nextObject]) {
			found = NO;

			NSEnumerator *tunerChannelAddressesEnum = [tunerChannelAddresses objectEnumerator];
			HDChannelAddress *tunerChannelAddress;
			while(tunerChannelAddress = [tunerChannelAddressesEnum nextObject]) {
				if (tunerChannelAddress == channelChannelAddress) {
					found = YES;
				}
			}

			if (!found) {
				[removeList addObject:channelChannelAddress];
			}
		}

		[services removeChannelAddresses:removeList];
	}

	return YES;
}

- (HDChannelAddress *)getFirstChannelAddressForTuner:(HDHomeRunTuner *)lTuner {
	NSEnumerator *adressEnum = [[self channelAddresses] objectEnumerator];
	HDChannelAddress *currentAddress;
	while(currentAddress = [adressEnum nextObject]) {
		if ([currentAddress tuner] == lTuner) {
			return currentAddress;
		}
	}
	return nil;
}

- (BOOL)tuneOnTuner:(HDHomeRunTuner *)lTuner {
	HDChannelAddress *channelAddress = [self getFirstChannelAddressForTuner:lTuner];

	if (channelAddress == nil) {
		return NO;

	} else {
		return ([self tuneToChannelAddress:channelAddress] != nil);
	}
}
- (HDHomeRunTuner *)tuneToChannelAddress:(HDChannelAddress *)address {
	if (address == nil) {
		[Services globalMessage:@"Channel address is unknown."];
		return nil;

	} else {
		if ([address tuner] == nil) {
			[Services globalMessage:[NSString stringWithFormat:@"Tuner for address %@ is unknown.", address]];
			return nil;

		} else {
			if ([[address tuner] unit] == nil) {
				[Services globalMessage:[NSString stringWithFormat:@"Unit for address %@ is unknown.", address]];
				return nil;

			} else {
				if ([[[address tuner] unit] unitId] == -1) {
					[Services globalMessage:[NSString stringWithFormat:@"Unit-id for address %@ is unknown.", address]];
					return nil;

				} else {
					if ([[address tuner] isReceiving]) {
						if ([[address tuner] lastChannelAddress] == nil) {
							[Services globalMessage:[NSString stringWithFormat:@"Tuner %d on unit %@ is already receiving from null address.", [address tuner], [[address tuner] unit]]];
						} else {
							[Services globalMessage:[NSString stringWithFormat:@"Tuner %d on unit %@ is already receiving for address %@.", [address tuner], [[address tuner] unit], [[address tuner] lastChannelAddress]]];
						}
						return nil;

					} else { // Not receiving
						[[address tuner] cancelData];
						BOOL result =  [[address tuner] isReceiving];

            [[address tuner] tuneToChannelAddress:address];
						[[address tuner] startStream];

						if (result == NO) {
							[Services globalMessage:[NSString stringWithFormat:@"Tuner %d on unit %@ is already receiving for address %@.", [address tuner], [[address tuner] unit], [[address tuner] lastChannelAddress]]];
						}

						return [address tuner];
					}
				}
			}
		}
	}
}

- (NSColor *)color {
	if ([self activated]) {
		return [NSColor greenColor];
	} else {
		return [NSColor redColor];
	}
}

@end


text:
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import '../../assets/styles/tailwind.postcss'

import FeathersVuexFormWrapper from '../src/FeathersVuexFormWrapper'
import Readme from './README.md'

import store from '../../store/store.dev'
import { models } from 'feathers-vuex'

export default {
  title: 'FeathersVuexFormWrapper',
  parameters: {
    component: FeathersVuexFormWrapper,
    readme: {
      sidebar: Readme
    }
  }
}

export const Basic = () => ({
  components: { FeathersVuexFormWrapper },
  data: () => ({
    date: null,
    UserModel: models.api.User
  }),
  store,
  template: `<div class="p-3">
  <FeathersVuexFormWrapper
    :id="'new'"
    :model="UserModel"
  >
    <template v-slot="{ clone, isNew, isDirty, save, reset, remove }">
      <FormComponent
        :item="clone"
        :is-new="isNew"
        :is-dirty="isDirty"
        @save="save"
        @reset="reset"
        @remove="remove"
      >
      </FormComponent>
    </template>
  </FeathersVuexFormWrapper>
</div>`
})


text:
require 'rspec'
require 'fakeweb'

$:.unshift(File.dirname(__FILE__) + '/../lib') unless $:.include?(File.dirname(__FILE__) + '/../../lib')

#Use local plugin
require 'limited_red'
require 'limited_red/plugins/rspec'

FakeWeb.allow_net_connect = false