dispose => {
    const [counter, setCounter] = createSignal(0);

    const captured: number[] = [];

    createCompositeEffect(throttle(counter, x => captured.push(x), 10));

    setTimeout(() => {
      assert.equal(captured, [], "initial state should not be captured immediately");
      setCounter(1);
      assert.equal(captured, [], "first change should not be captured immediately");
    }, 0);

    setTimeout(() => {
      assert.equal(captured, [0], "after delay, only the initial state should be captured");
      setCounter(7);
      setCounter(9);
      setTimeout(() => {
        assert.equal(
          captured,
          [0, 7],
          "after delay, only the next first change should be captured"
        );
        dispose();
      }, 15);
    }, 15);
  }


() => {
      assert.equal(captured, [0], "after delay, only the initial state should be captured");
      setCounter(7);
      setCounter(9);
      setTimeout(() => {
        assert.equal(
          captured,
          [0, 7],
          "after delay, only the next first change should be captured"
        );
        dispose();
      }, 15);
    }


() => {
        assert.equal(
          captured,
          [0, 7],
          "after delay, only the next first change should be captured"
        );
        dispose();
      }


() => {
  createRoot(dispose => {
    const [counter, setCounter] = createSignal(0);

    const captured1: number[] = [];
    const captured2: number[] = [];

    createCompositeEffect(
      whenever(
        () => counter() % 2 === 0,
        () => captured1.push(counter())
      )
    );

    createCompositeEffect(
      whenever(
        createMemo(() => counter() >= 3),
        () => captured2.push(counter())
      )
    );

    setTimeout(() => {
      assert.equal(captured1, [0], "initial state should be captured for 1");
      assert.equal(captured2, [], "initial state should not be captured for 2");
      setCounter(1);
      assert.equal(captured1, [0], "first change should not be captured for 1");
      assert.equal(captured2, [], "first change should not be captured for 2");
      setCounter(2);
      assert.equal(captured1, [0, 2], "2 should be added for 1");
      assert.equal(captured2, [], "2 should not be added for 2");
      setCounter(3);
      assert.equal(captured1, [0, 2], "3 should not be added for 1");
      assert.equal(captured2, [3], "3 should be added for 2");
      setCounter(4);
      assert.equal(captured1, [0, 2, 4], "4 should be added for 1");
      assert.equal(captured2, [3], "4 should not be added for 2");
    }, 0);
  });
}


dispose => {
    const [counter, setCounter] = createSignal(0);

    const captured1: number[] = [];
    const captured2: number[] = [];

    createCompositeEffect(
      whenever(
        () => counter() % 2 === 0,
        () => captured1.push(counter())
      )
    );

    createCompositeEffect(
      whenever(
        createMemo(() => counter() >= 3),
        () => captured2.push(counter())
      )
    );

    setTimeout(() => {
      assert.equal(captured1, [0], "initial state should be captured for 1");
      assert.equal(captured2, [], "initial state should not be captured for 2");
      setCounter(1);
      assert.equal(captured1, [0], "first change should not be captured for 1");
      assert.equal(captured2, [], "first change should not be captured for 2");
      setCounter(2);
      assert.equal(captured1, [0, 2], "2 should be added for 1");
      assert.equal(captured2, [], "2 should not be added for 2");
      setCounter(3);
      assert.equal(captured1, [0, 2], "3 should not be added for 1");
      assert.equal(captured2, [3], "3 should be added for 2");
      setCounter(4);
      assert.equal(captured1, [0, 2, 4], "4 should be added for 1");
      assert.equal(captured2, [3], "4 should not be added for 2");
    }, 0);
  }


() => counter() % 2 === 0


() => captured1.push(counter())


() => counter() >= 3


() => captured2.push(counter())


() => {
      assert.equal(captured1, [0], "initial state should be captured for 1");
      assert.equal(captured2, [], "initial state should not be captured for 2");
      setCounter(1);
      assert.equal(captured1, [0], "first change should not be captured for 1");
      assert.equal(captured2, [], "first change should not be captured for 2");
      setCounter(2);
      assert.equal(captured1, [0, 2], "2 should be added for 1");
      assert.equal(captured2, [], "2 should not be added for 2");
      setCounter(3);
      assert.equal(captured1, [0, 2], "3 should not be added for 1");
      assert.equal(captured2, [3], "3 should be added for 2");
      setCounter(4);
      assert.equal(captured1, [0, 2, 4], "4 should be added for 1");
      assert.equal(captured2, [3], "4 should not be added for 2");
    }


() => {
  createRoot(dispose => {
    const [counter, setCounter] = createSignal(0);

    const captured: number[] = [];

    const { pause, resume, toggle } = createCompositeEffect(
      pausable(counter, () => captured.push(counter()), { active: false })
    );

    setTimeout(() => {
      assert.equal(captured, [], "initial state should not be captured");
      setCounter(1);
      assert.equal(captured, [], "first change should not be captured");
      resume();
      setCounter(2);
      assert.equal(captured, [2], "after resume() change should be captured");
      pause();
      setCounter(3);
      assert.equal(captured, [2], "after pause() change should not be captured");
      toggle();
      setCounter(4);
      assert.equal(captured, [2, 4], "after toggle() change should be captured");
      toggle(true);
      setCounter(5);
      assert.equal(captured, [2, 4, 5], "after toggle(true) change should be captured");
      toggle(false);
      setCounter(6);
      assert.equal(captured, [2, 4, 5], "after toggle(false) change should not be captured");
      dispose();
    }, 0);
  });
}


dispose => {
    const [counter, setCounter] = createSignal(0);

    const captured: number[] = [];

    const { pause, resume, toggle } = createCompositeEffect(
      pausable(counter, () => captured.push(counter()), { active: false })
    );

    setTimeout(() => {
      assert.equal(captured, [], "initial state should not be captured");
      setCounter(1);
      assert.equal(captured, [], "first change should not be captured");
      resume();
      setCounter(2);
      assert.equal(captured, [2], "after resume() change should be captured");
      pause();
      setCounter(3);
      assert.equal(captured, [2], "after pause() change should not be captured");
      toggle();
      setCounter(4);
      assert.equal(captured, [2, 4], "after toggle() change should be captured");
      toggle(true);
      setCounter(5);
      assert.equal(captured, [2, 4, 5], "after toggle(true) change should be captured");
      toggle(false);
      setCounter(6);
      assert.equal(captured, [2, 4, 5], "after toggle(false) change should not be captured");
      dispose();
    }, 0);
  }


() => captured.push(counter())


() => {
      assert.equal(captured, [], "initial state should not be captured");
      setCounter(1);
      assert.equal(captured, [], "first change should not be captured");
      resume();
      setCounter(2);
      assert.equal(captured, [2], "after resume() change should be captured");
      pause();
      setCounter(3);
      assert.equal(captured, [2], "after pause() change should not be captured");
      toggle();
      setCounter(4);
      assert.equal(captured, [2, 4], "after toggle() change should be captured");
      toggle(true);
      setCounter(5);
      assert.equal(captured, [2, 4, 5], "after toggle(true) change should be captured");
      toggle(false);
      setCounter(6);
      assert.equal(captured, [2, 4, 5], "after toggle(false) change should not be captured");
      dispose();
    }


() => {
  createRoot(dispose => {
    const [counter, setCounter] = createSignal(0);

    const captured: number[] = [];

    const { ignoreNext, ignore } = createCompositeEffect(
      ignorable(counter, x => {
        captured.push(x);
        // next effect will be ignored:
        ignoreNext();
        setCounter(p => p + 1);

        // this change happens in the same effect, so it will also be ignored
        setCounter(5);
      })
    );

    setTimeout(() => {
      assert.equal(captured, [0], "initial state should be captured");
      assert.is(counter(), 5, "although it wasn't captured, the counter should be 5");
      ignore(() => {
        // both changes will be ignored:
        setCounter(420);
        setCounter(69);
      });
      assert.equal(captured, [0], "changes in ignore() should not be captured");
      assert.equal(counter(), 69, "changes in ignore() were executed applied");
      // but not this one:
      setCounter(p => 111);
      assert.equal(captured, [0, 111], "changes after ignore() should be captured");
      dispose();
    }, 0);
  });
}


dispose => {
    const [counter, setCounter] = createSignal(0);

    const captured: number[] = [];

    const { ignoreNext, ignore } = createCompositeEffect(
      ignorable(counter, x => {
        captured.push(x);
        // next effect will be ignored:
        ignoreNext();
        setCounter(p => p + 1);

        // this change happens in the same effect, so it will also be ignored
        setCounter(5);
      })
    );

    setTimeout(() => {
      assert.equal(captured, [0], "initial state should be captured");
      assert.is(counter(), 5, "although it wasn't captured, the counter should be 5");
      ignore(() => {
        // both changes will be ignored:
        setCounter(420);
        setCounter(69);
      });
      assert.equal(captured, [0], "changes in ignore() should not be captured");
      assert.equal(counter(), 69, "changes in ignore() were executed applied");
      // but not this one:
      setCounter(p => 111);
      assert.equal(captured, [0, 111], "changes after ignore() should be captured");
      dispose();
    }, 0);
  }


x => {
        captured.push(x);
        // next effect will be ignored:
        ignoreNext();
        setCounter(p => p + 1);

        // this change happens in the same effect, so it will also be ignored
        setCounter(5);
      }


p => p + 1


() => {
      assert.equal(captured, [0], "initial state should be captured");
      assert.is(counter(), 5, "although it wasn't captured, the counter should be 5");
      ignore(() => {
        // both changes will be ignored:
        setCounter(420);
        setCounter(69);
      });
      assert.equal(captured, [0], "changes in ignore() should not be captured");
      assert.equal(counter(), 69, "changes in ignore() were executed applied");
      // but not this one:
      setCounter(p => 111);
      assert.equal(captured, [0, 111], "changes after ignore() should be captured");
      dispose();
    }


() => {
        // both changes will be ignored:
        setCounter(420);
        setCounter(69);
      }


p => 111


(a: TransactionDetails, b: TransactionDetails) => b.addedTime - a.addedTime


(sortedRecentTransaction: TransactionDetails) => {
  const { hash, receipt } = sortedRecentTransaction

  if (!hash) {
    return { icon: <Loader />, color: 'text' }
  }

  if (hash && receipt?.status === 1) {
    return { icon: <CheckmarkCircleIcon color="success" />, color: 'success' }
  }

  return { icon: <ErrorIcon color="failure" />, color: 'failure' }
}

const RecentTransactionsModal = ({ onDismiss = defaultOnDismiss, translateString }: RecentTransactionsModalProps) => {
  const TranslateString = translateString
  const { account, chainId } = useActiveWeb3React()
  const allTransactions = useAllTransactions()

  // Logic taken from Web3Status/index.tsx line 175
  const sortedRecentTransactions = useMemo(() => {
    const txs = Object.values(allTransactions)
    return txs.filter(isTransactionRecent).sort(newTransactionsFirst)
  }, [allTransactions])

  return (
    <Modal title={TranslateString(1202, 'Recent transactions')} onDismiss={onDismiss}>
      {!account && (
        <Flex justifyContent="center" flexDirection="column" alignItems="center">
          <Text mb="8px" bold>
            Please connect your wallet to view your recent transactions
          </Text>
          <Button variant="tertiary" scale="sm" onClick={onDismiss}>
            Close
          </Button>
        </Flex>


({ onDismiss = defaultOnDismiss, translateString }: RecentTransactionsModalProps) => {
  const TranslateString = translateString
  const { account, chainId } = useActiveWeb3React()
  const allTransactions = useAllTransactions()

  // Logic taken from Web3Status/index.tsx line 175
  const sortedRecentTransactions = useMemo(() => {
    const txs = Object.values(allTransactions)
    return txs.filter(isTransactionRecent).sort(newTransactionsFirst)
  }, [allTransactions])

  return (
    <Modal title={TranslateString(1202, 'Recent transactions')} onDismiss={onDismiss}>
      {!account && (
        <Flex justifyContent="center" flexDirection="column" alignItems="center">
          <Text mb="8px" bold>
            Please connect your wallet to view your recent transactions
          </Text>
          <Button variant="tertiary" scale="sm" onClick={onDismiss}>
            Close
          </Button>
        </Flex>


() => {
    const txs = Object.values(allTransactions)
    return txs.filter(isTransactionRecent).sort(newTransactionsFirst)
  }


(sortedRecentTransaction) => {
          const { hash, summary } = sortedRecentTransaction
          const { icon, color } = getRowStatus(sortedRecentTransaction)

          return (
            <>
              <Flex key={hash} alignItems="center" justifyContent="space-between" mb="4px">
                <LinkExternal href={getBscScanLink(chainId, hash, 'transaction')} color={color}>
                  {summary ?? hash}


type RecentTransactionsModalProps = {
  onDismiss?: () => void
  translateString: (translationId: number, fallback: string) => (string)
}


TranslateString(1202, 'Recent transactions')


() => {
  let component: AccountPickerComponent;
  let fixture: ComponentFixture<AccountPickerComponent>;
  let userServiceSpy;

  beforeEach(async(() => {
    const subFn = { subscribe: () => {} };
    const getValueFn = { getValue: () => {} };
    userServiceSpy = jasmine.createSpyObj('UserService', [
      'userAccounts',
      'activeAccount',
      'setActiveAccount',
    ]);
    userServiceSpy.activeAccount = jasmine.createSpyObj('activeAccount', subFn);

    userServiceSpy.userAccounts = jasmine.createSpyObj(
      'userAccounts',
      getValueFn,
    );

    TestBed.configureTestingModule({
      declarations: [AccountPickerComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [{ provide: UserService, useValue: userServiceSpy }],
      imports: [TruncatePublicKeyPipeModule],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AccountPickerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
}


() => {
    const subFn = { subscribe: () => {} };
    const getValueFn = { getValue: () => {} };
    userServiceSpy = jasmine.createSpyObj('UserService', [
      'userAccounts',
      'activeAccount',
      'setActiveAccount',
    ]);
    userServiceSpy.activeAccount = jasmine.createSpyObj('activeAccount', subFn);

    userServiceSpy.userAccounts = jasmine.createSpyObj(
      'userAccounts',
      getValueFn,
    );

    TestBed.configureTestingModule({
      declarations: [AccountPickerComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [{ provide: UserService, useValue: userServiceSpy }],
      imports: [TruncatePublicKeyPipeModule],
    }).compileComponents();
  }


() => {
    fixture = TestBed.createComponent(AccountPickerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }


export interface CredentialStatus {
  id: string
  type: string
}


/**
 * A JWT payload representation of a Credential
 * @see https://www.w3.org/TR/vc-data-model/#jwt-encoding
 */
export interface JwtCredentialPayload {
  iss?: string
  sub?: string
  vc: Extensible<{
    '@context': string[] | string
    type: string[] | string
    credentialSubject: JwtCredentialSubject
    credentialStatus?: CredentialStatus
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    evidence?: any
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    termsOfUse?: any
  }>
  nbf?: number
  aud?: string | string[]
  exp?: number
  jti?: string
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [x: string]: any
}


/**
 * A JWT payload representation of a Presentation
 * @see https://www.w3.org/TR/vc-data-model/#jwt-encoding
 */
export interface JwtPresentationPayload {
  vp: Extensible<{
    '@context': string[] | string
    type: string[] | string
    verifiableCredential?: VerifiableCredential[] | VerifiableCredential
  }>
  iss?: string
  aud?: string | string[]
  nbf?: number
  exp?: number
  jti?: string
  nonce?: string
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [x: string]: any
}


/**
 * used as input when creating Verifiable Credentials
 */
interface FixedCredentialPayload {
  '@context': string | string[]
  id?: string
  type: string | string[]
  issuer: IssuerType
  issuanceDate: DateType
  expirationDate?: DateType
  credentialSubject: Extensible<{
    id?: string
  }>
  credentialStatus?: CredentialStatus
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  evidence?: any
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  termsOfUse?: any
}


/**
 * This is meant to reflect unambiguous types for the properties in `CredentialPayload`
 */
interface NarrowCredentialDefinitions {
  '@context': string[]
  type: string[]
  issuer: Exclude<IssuerType, string>
  issuanceDate: string
  expirationDate?: string
}


/**
 * used as input when creating Verifiable Presentations
 */
export interface FixedPresentationPayload {
  '@context': string | string[]
  type: string | string[]
  id?: string
  verifiableCredential?: VerifiableCredential[]
  holder: string
  verifier?: string | string[]
  issuanceDate?: string
  expirationDate?: string
}


interface NarrowPresentationDefinitions {
  '@context': string[]
  type: string[]
  verifier: string[]
  verifiableCredential?: Verifiable<W3CCredential>[]
}


export interface Proof {
  type?: string
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [x: string]: any
}


/**
 * Represents a tuple of a DID-URL with a `Signer` and associated algorithm.
 */
export interface Issuer {
  did: string
  // eslint-disable-next-line
// @ts-ignore
  signer: Signer
  alg?: string
}


/**
 * Represents the Creation Options that can be passed to the createVerifiableCredentialJwt method.
 */
export interface CreateCredentialOptions {
  /**
   * Determines whether the JSON->JWT transformation will remove the original fields from the input payload.
   * See https://www.w3.org/TR/vc-data-model/#jwt-encoding
   *
   * @default true
   */
  removeOriginalFields?: boolean

  /**
   * Allows including or overriding some header parameters for the resulting JWT.
   * If the issuer or holder does not list an `alg`, then the one specified in `header` will be used
   */
  // eslint-disable-next-line
// @ts-ignore
  header?: Partial<JWTHeader>
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [x: string]: any
}


/**
 * Represents the Verification Options that can be passed to the verifyPresentation method.
 * The verification will fail if given options are NOT satisfied.
 */
export interface VerifyPresentationOptions extends VerifyCredentialOptions {
  domain?: string
  challenge?: string
}


/**
 * Represents the Creation Options that can be passed to the createVerifiablePresentationJwt method.
 */
export interface CreatePresentationOptions extends CreateCredentialOptions {
  domain?: string
  challenge?: string
}


// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type JwtCredentialSubject = Record<string, any>


export type IssuerType = Extensible<{ id: string }> | string


export type DateType = string | Date


/**
 * A more flexible representation of a {@link W3CCredential} that can be used as input to methods
 * that expect it.
 */
export type CredentialPayload = Extensible<FixedCredentialPayload>


/**
 * Replaces the matching property types of T with the ones in U
 */
type Replace<T, U> = Omit<T, keyof U> & U


// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Extensible<T> = T & { [x: string]: any }


/**
 * This data type represents a parsed VerifiableCredential.
 * It is meant to be an unambiguous representation of the properties of a Credential and is usually the result of a transformation method.
 *
 * `issuer` is always an object with an `id` property and potentially other app specific issuer claims
 * `issuanceDate` is an ISO DateTime string
 * `expirationDate`, is a nullable ISO DateTime string
 *
 * Any JWT specific properties are transformed to the broader W3C variant and any app specific properties are left intact
 */
export type W3CCredential = Extensible<Replace<FixedCredentialPayload, NarrowCredentialDefinitions>>


/**
 * A more flexible representation of a {@link W3CPresentation} that can be used as input to methods
 * that expect it.
 */
export type PresentationPayload = Extensible<FixedPresentationPayload>


/**
 * This data type represents a parsed Presentation payload.
 * It is meant to be an unambiguous representation of the properties of a Presentation and is usually the result of a transformation method.
 *
 * The `verifiableCredential` array should contain parsed `Verifiable<Credential>` elements.
 * Any JWT specific properties are transformed to the broader W3C variant and any other app specific properties are left intact.
 */
export type W3CPresentation = Extensible<Replace<FixedPresentationPayload, NarrowPresentationDefinitions>>


/**
 * Represents a readonly representation of a verifiable object, including the {@link Proof}
 * property that can be used to verify it.
 */
export type Verifiable<T> = Readonly<T> & { readonly proof: Proof }


export type JWT = string


/**
 * A union type for both possible representations of a Credential (JWT and W3C standard)
 *
 * @see https://www.w3.org/TR/vc-data-model/#proof-formats
 */
export type VerifiableCredential = JWT | Verifiable<W3CCredential>


/**
 * A union type for both possible representations of a Presentation (JWT and W3C standard)
 *
 * @see https://www.w3.org/TR/vc-data-model/#proof-formats
 */
export type VerifiablePresentation = JWT | Verifiable<W3CPresentation>


// eslint-disable-next-line
// @ts-ignore
export type VerifiedJWT = JWTVerified


/**
 * Represents the result of a Presentation verification.
 * It includes the properties produced by `did-jwt` and a W3C compliant representation of
 * the Presentation that was just verified.
 *
 * This is usually the result of a verification method and not meant to be created by generic code.
 */
export type VerifiedPresentation = VerifiedJWT & {
  verifiablePresentation: Verifiable<W3CPresentation>
}


/**
 * Represents the result of a Credential verification.
 * It includes the properties produced by `did-jwt` and a W3C compliant representation of
 * the Credential that was just verified.
 *
 * This is usually the result of a verification method and not meant to be created by generic code.
 */
export type VerifiedCredential = VerifiedJWT & {
  verifiableCredential: Verifiable<W3CCredential>
}


/**
 * Represents the Verification Options that can be passed to the verifyCredential method.
 * These options are forwarded to the lower level verification code
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type VerifyCredentialOptions = Record<string, any>


(): { activeAddress: string; setActiveAddress: (address: string) => void } => {
  const [activeAddress, setActiveAddress] = useState<string>();
  const web3 = useWeb3();

  useEffect(() => web3.onAccountsChanged((accounts) => setActiveAddress(accounts[0])), []);

  return { activeAddress, setActiveAddress };
}


() => web3.onAccountsChanged((accounts) => setActiveAddress(accounts[0]))


(accounts) => setActiveAddress(accounts[0])


() => ({ getDevice: () => mockDevice })


() => mockDevice


(): SensorListProps => {
    const pins: Pins = {
      50: {
        mode: 1,
        value: 500,
      },
      51: {
        mode: 0,
        value: 1,
      },
      52: {
        mode: 0,
        value: 1,
      },
      53: {
        mode: 0,
        value: 0,
      },
    };
    const fakeSensor1 = fakeSensor();
    const fakeSensor2 = fakeSensor();
    const fakeSensor3 = fakeSensor();
    const fakeSensor4 = fakeSensor();
    fakeSensor1.body.id = 1;
    fakeSensor1.body.pin = 51;
    fakeSensor1.body.mode = 0;
    fakeSensor1.body.label = "GPIO 51";
    fakeSensor2.body.id = 2;
    fakeSensor2.body.pin = 50;
    fakeSensor2.body.mode = 1;
    fakeSensor2.body.label = "GPIO 50 - Moisture";
    fakeSensor3.body.id = 3;
    fakeSensor3.body.pin = 52;
    fakeSensor3.body.mode = 0;
    fakeSensor3.body.label = "GPIO 52 - Tool Verification";
    fakeSensor4.body.id = 4;
    fakeSensor4.body.pin = 53;
    fakeSensor4.body.mode = 0;
    fakeSensor4.body.label = "GPIO 53 - Tool Verification";
    return {
      dispatch: jest.fn(),
      sensors: [fakeSensor2, fakeSensor1, fakeSensor3, fakeSensor4],
      pins,
      disabled: false
    };
  }


(pin_number: number, pin_mode: 0 | 1) =>
    ({
      pin_number,
      label: `pin${pin_number}`,
      pin_mode
    })


() => {
    const wrapper = mount(<SensorList {...fakeProps()} />);
    const readSensorBtn = wrapper.find("button");
    readSensorBtn.at(0).simulate("click");
    expect(mockDevice.readPin).toHaveBeenCalledWith(expectedPayload(51, 0));
    readSensorBtn.at(1).simulate("click");
    expect(mockDevice.readPin).toHaveBeenLastCalledWith(expectedPayload(50, 1));
    expect(mockDevice.readPin).toHaveBeenCalledTimes(2);
  }


() => {
    const p = fakeProps();
    p.disabled = true;
    const wrapper = mount(<SensorList {...p} />);
    const readSensorBtn = wrapper.find("button");
    readSensorBtn.first().simulate("click");
    readSensorBtn.last().simulate("click");
    expect(mockDevice.readPin).not.toHaveBeenCalled();
  }


() => {
    const p = fakeProps();
    p.pins[50] && (p.pins[50].value = 600);
    const wrapper = mount(<SensorList {...p} />);
    expect(wrapper.html()).toContain("margin-left: -3.5rem");
  }


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  isLoading: boolean;

  constructor() {}

  ngOnInit() {
    this.isLoading = true;
  }

}


ngOnInit() {
    this.isLoading = true;
  }


export function isMockFunction(fn: any): fn is EnhancedSpy {
  return typeof fn === 'function'
  && '__isSpy' in fn
  && fn.__isSpy
}


export function spyOn<T, K extends keyof T>(
  obj: T,
  method: K,
  accessType?: 'get' | 'set',
): T[K] extends (...args: infer TArgs) => infer TReturnValue
    ? JestMockCompat<TArgs, TReturnValue> : JestMockCompat {
  const dictionary = {
    get: 'getter',
    set: 'setter',
  } as const
  const objMethod = accessType ? { [dictionary[accessType]]: method } : method

  const stub = tinyspy.spyOn(obj, objMethod as any)

  return enhanceSpy(stub) as any
}


function enhanceSpy<TArgs extends any[], TReturns>(
  spy: SpyImpl<TArgs, TReturns>,
): JestMockCompat<TArgs, TReturns> {
  const stub = spy as unknown as EnhancedSpy<TArgs, TReturns>

  let implementation: ((...args: TArgs) => TReturns) | undefined

  const instances: any[] = []

  const mockContext = {
    get calls() {
      return stub.calls
    },
    get instances() {
      return instances
    },
    // not supported
    get invocationCallOrder() {
      return []
    },
    get results() {
      return stub.results.map(([callType, value]) => {
        const type = callType === 'error' ? 'throw' : 'return'
        return { type, value }
      })
    },
  }

  let onceImplementations: ((...args: TArgs) => TReturns)[] = []

  let name: string = (stub as any).name

  stub.getMockName = () => name || 'vi.fn()'
  stub.mockName = (n) => {
    name = n
    return stub
  }

  stub.mockClear = () => {
    stub.reset()
    return stub
  }

  stub.mockReset = () => {
    stub.reset()
    implementation = () => undefined as unknown as TReturns
    onceImplementations = []
    return stub
  }

  stub.mockRestore = () => {
    stub.mockReset()
    implementation = undefined
    return stub
  }

  stub.getMockImplementation = () => implementation
  stub.mockImplementation = (fn: (...args: TArgs) => TReturns) => {
    implementation = fn
    return stub
  }

  stub.mockImplementationOnce = (fn: (...args: TArgs) => TReturns) => {
    onceImplementations.push(fn)
    return stub
  }

  stub.mockReturnThis = () =>
    stub.mockImplementation(function(this: TReturns) {
      return this
    })

  stub.mockReturnValue = (val: TReturns) => stub.mockImplementation(() => val)
  stub.mockReturnValueOnce = (val: TReturns) => stub.mockImplementationOnce(() => val)

  stub.mockResolvedValue = (val: Awaited<TReturns>) =>
    stub.mockImplementation(() => Promise.resolve(val as TReturns))

  stub.mockResolvedValueOnce = (val: Awaited<TReturns>) =>
    stub.mockImplementationOnce(() => Promise.resolve(val as TReturns))

  stub.mockRejectedValue = (val: unknown) =>
    stub.mockImplementation(() => Promise.reject(val))

  stub.mockRejectedValueOnce = (val: unknown) =>
    stub.mockImplementationOnce(() => Promise.reject(val))

  util.addProperty(stub, 'mock', () => mockContext)

  stub.willCall(function(this: unknown, ...args) {
    instances.push(this)
    const impl = onceImplementations.shift() || implementation || stub.getOriginal() || (() => {})
    return impl.apply(this, args)
  })

  spies.add(stub)

  return stub as any
}


export function fn<TArgs extends any[] = any[], R = any>(): JestMockCompatFn<TArgs, R>


export function fn<TArgs extends any[] = any[], R = any>(
  implementation: (...args: TArgs) => R
): JestMockCompatFn<TArgs, R>


export function fn<TArgs extends any[] = any[], R = any>(
  implementation?: (...args: TArgs) => R,
): JestMockCompatFn<TArgs, R> {
  return enhanceSpy(tinyspy.spyOn({ fn: implementation || (() => {}) }, 'fn')) as unknown as JestMockCompatFn
}


([callType, value]) => {
        const type = callType === 'error' ? 'throw' : 'return'
        return { type, value }
      }


() => name || 'vi.fn()'


(n) => {
    name = n
    return stub
  }


() => {
    stub.reset()
    return stub
  }


() => {
    stub.reset()
    implementation = () => undefined as unknown as TReturns
    onceImplementations = []
    return stub
  }


() => undefined as unknown as TReturns


() => {
    stub.mockReset()
    implementation = undefined
    return stub
  }


() => implementation


(fn: (...args: TArgs) => TReturns) => {
    implementation = fn
    return stub
  }


(fn: (...args: TArgs) => TReturns) => {
    onceImplementations.push(fn)
    return stub
  }


() =>
    stub.mockImplementation(function(this: TReturns) {
      return this
    })


(val: TReturns) => stub.mockImplementation(() => val)


() => val


(val: TReturns) => stub.mockImplementationOnce(() => val)


(val: Awaited<TReturns>) =>
    stub.mockImplementation(() => Promise.resolve(val as TReturns))


() => Promise.resolve(val as TReturns)


(val: Awaited<TReturns>) =>
    stub.mockImplementationOnce(() => Promise.resolve(val as TReturns))


(val: unknown) =>
    stub.mockImplementation(() => Promise.reject(val))


() => Promise.reject(val)


(val: unknown) =>
    stub.mockImplementationOnce(() => Promise.reject(val))


() => mockContext


interface MockResultReturn<T> {
  type: 'return'
  value: T
}


interface MockResultIncomplete {
  type: 'incomplete'
  value: undefined
}


interface MockResultThrow {
  type: 'throw'
  value: any
}


export interface JestMockCompatContext<T, Y> {
  calls: Y[]
  instances: T[]
  // TODO: doesn't work
  invocationCallOrder: number[]
  results: MockResult<T>[]
}


export interface JestMockCompat<TArgs extends any[] = any[], TReturns = any> {
  getMockName(): string
  mockName(n: string): this
  mock: JestMockCompatContext<TArgs, TReturns>
  mockClear(): this
  mockReset(): this
  mockRestore(): void
  getMockImplementation(): ((...args: TArgs) => TReturns) | undefined
  mockImplementation(fn: ((...args: TArgs) => TReturns) | (() => Promise<TReturns>)): this
  mockImplementationOnce(fn: ((...args: TArgs) => TReturns) | (() => Promise<TReturns>)): this
  mockReturnThis(): this
  mockReturnValue(obj: TReturns): this
  mockReturnValueOnce(obj: TReturns): this
  mockResolvedValue(obj: Awaited<TReturns>): this
  mockResolvedValueOnce(obj: Awaited<TReturns>): this
  mockRejectedValue(obj: any): this
  mockRejectedValueOnce(obj: any): this
}


export interface JestMockCompatFn<TArgs extends any[] = any, TReturns = any> extends JestMockCompat<TArgs, TReturns> {
  (...args: TArgs): TReturns
}


export interface MockWithArgs<T extends MockableFunction>
  extends JestMockCompatFn<ArgumentsOf<T>, ReturnType<T>> {
  new (...args: ConstructorArgumentsOf<T>): T
  (...args: ArgumentsOf<T>): ReturnType<T>
}


type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete


export type MockableFunction = (...args: Array<any>) => any


export type MethodKeysOf<T> = {
  [K in keyof T]: T[K] extends MockableFunction ? K : never;
}[keyof T]


export type PropertyKeysOf<T> = {
  [K in keyof T]: T[K] extends MockableFunction ? never : K;
}[keyof T]


export type ArgumentsOf<T> = T extends (...args: infer A) => any ? A : never


export type ConstructorArgumentsOf<T> = T extends new (...args: infer A) => any
  ? A
  : never


export type MaybeMockedConstructor<T> = T extends new (
  ...args: Array<any>
) => infer R
  ? JestMockCompatFn<ConstructorArgumentsOf<T>, R>
  : T


export type MockedFunction<T extends MockableFunction> = MockWithArgs<T> & {
  [K in keyof T]: T[K];
}


export type MockedFunctionDeep<T extends MockableFunction> = MockWithArgs<T> &
MockedObjectDeep<T>


export type MockedObject<T> = MaybeMockedConstructor<T> & {
  [K in MethodKeysOf<T>]: T[K] extends MockableFunction
    ? MockedFunction<T[K]>
    : T[K];
} & {[K in PropertyKeysOf<T>]: T[K]}


export type MockedObjectDeep<T> = MaybeMockedConstructor<T> & {
  [K in MethodKeysOf<T>]: T[K] extends MockableFunction
    ? MockedFunctionDeep<T[K]>
    : T[K];
} & {[K in PropertyKeysOf<T>]: MaybeMockedDeep<T[K]>}


export type MaybeMockedDeep<T> = T extends MockableFunction
  ? MockedFunctionDeep<T>
  : T extends object
    ? MockedObjectDeep<T>
    : T


export type MaybeMocked<T> = T extends MockableFunction
  ? MockedFunction<T>
  : T extends object
    ? MockedObject<T>
    : T


export type EnhancedSpy<TArgs extends any[] = any[], TReturns = any> = JestMockCompat<TArgs, TReturns> & SpyImpl<TArgs, TReturns>


type Awaited<T> = T extends Promise<infer R> ? R : never


(app: App) => {
  app.component(MeLoading.name, MeLoading);
}


export interface CirclePackingOptions extends Omit<Options, 'data'> {
  /**
   * @title 数据字段
   */
  readonly data?: Record<string, any>;
  /**
   * @title 层级布局配置
   */
  readonly hierarchyConfig?: Omit<HierarchyOption, 'as' | 'type' | 'field'>;
  /**
   * @title 颜色字段
   */
  readonly colorField?: string;
  /**
   * @title 颜色
   */
  readonly color?: ColorAttr;
  /**
   * @title 大小字段
   */
  readonly sizeField?: string;
  /**
   * @title 源字段
   */
  readonly rawFields?: string[];

  // 暂不提供自定义 size，内部计算
  // readonly size?: SizeAttr;

  // 暂不提供 shape 配置，默认：circle.
  // readonly shape?: string;

  /**
   * @title 图形样式
   */
  readonly pointStyle?: StyleAttr;
  /**
   * @title 交互
   * @description 下钻交互
   */
  readonly drilldown?: DrillDownCfg;
}


() => {
    it('renders an <span> tag by default', () => {
        expect(render(<Label />)).toMatchHtmlTag('span');
    });

    it('renders the children', () => {
        expect(render(<Label>Content</Label>).getByText('Content')).toBeInTheDocument();
    });

    it('has the correct default colors', () => {
        expect(render(<Label />).container.firstChild).toHaveStyle(`
            color: ${Colors.AUTHENTIC_BLUE_900};
            border-color: ${Colors.AUTHENTIC_BLUE_200};
            background-color: ${Colors.AUTHENTIC_BLUE_50};
        `);
    });

    it('has the correct info variant colors', () => {
        expect(render(<Label variant="info" />).container.firstChild).toHaveStyle(`
            color: ${Colors.ACTION_BLUE_900};
            border-color: ${Colors.ACTION_BLUE_350};
            background-color: ${Colors.ACTION_BLUE_50};
        `);
    });

    it('has the correct success variant colors', () => {
        expect(render(<Label variant="success" />).container.firstChild).toHaveStyle(`
            color: ${Colors.POSITIVE_GREEN_1000};
            border-color: ${Colors.POSITIVE_GREEN_350};
            background-color: ${Colors.POSITIVE_GREEN_50};
        `);
    });

    it('has the correct danger variant colors', () => {
        expect(render(<Label variant="danger" />).container.firstChild).toHaveStyle(`
            color: ${Colors.NEGATIVE_ORANGE_1000};
            border-color: ${Colors.NEGATIVE_ORANGE_350};
            background-color: ${Colors.NEGATIVE_ORANGE_50};
        `);
    });

    it('uses the filled version if set', () => {
        expect(render(<Label variant="success" filled />).container.firstChild).toHaveStyle(`
            color: ${Colors.WHITE};
            border-color: ${Colors.POSITIVE_GREEN_900};
            backgroundColor: ${Colors.POSITIVE_GREEN_900};
        `);
    });
});


() => {
        expect(render(<Label />)).toMatchHtmlTag('span');
    }


() => {
        expect(render(<Label>Content</Label>).getByText('Content')).toBeInTheDocument();
    }


() => {
        expect(render(<Label />).container.firstChild).toHaveStyle(`
            color: ${Colors.AUTHENTIC_BLUE_900};
            border-color: ${Colors.AUTHENTIC_BLUE_200};
            background-color: ${Colors.AUTHENTIC_BLUE_50};
        `);
    });

    it('has the correct info variant colors', () => {
        expect(render(<Label variant="info" />).container.firstChild).toHaveStyle(`
            color: ${Colors.ACTION_BLUE_900};
            border-color: ${Colors.ACTION_BLUE_350};
            background-color: ${Colors.ACTION_BLUE_50};
        `);
    });

    it('has the correct success variant colors', () => {
        expect(render(<Label variant="success" />).container.firstChild).toHaveStyle(`
            color: ${Colors.POSITIVE_GREEN_1000};
            border-color: ${Colors.POSITIVE_GREEN_350};
            background-color: ${Colors.POSITIVE_GREEN_50};
        `);
    });

    it('has the correct danger variant colors', () => {
        expect(render(<Label variant="danger" />).container.firstChild).toHaveStyle(`
            color: ${Colors.NEGATIVE_ORANGE_1000};
            border-color: ${Colors.NEGATIVE_ORANGE_350};
            background-color: ${Colors.NEGATIVE_ORANGE_50};
        `);
    });

    it('uses the filled version if set', () => {
        expect(render(<Label variant="success" filled />).container.firstChild).toHaveStyle(`
            color: ${Colors.WHITE};
            border-color: ${Colors.POSITIVE_GREEN_900};
            backgroundColor: ${Colors.POSITIVE_GREEN_900};
        `);
    });
});


export function stringSorter<T>(mapToString: (obj: T) => string): Sorter<T> {
  // eslint-disable-next-line no-nested-ternary
  return (a, b) => ((mapToString(a).toLowerCase() < mapToString(b).toLowerCase()) ? -1
    : (mapToString(a).toLowerCase() > mapToString(b).toLowerCase()) ? 1 : 0);
}


(a, b) => ((mapToString(a).toLowerCase() < mapToString(b).toLowerCase()) ? -1
    : (mapToString(a).toLowerCase() > mapToString(b).toLowerCase()) ? 1 : 0)


@NgModule({
  declarations: [
    AppComponent,
    QuoteComponent,
    QuoteDetailComponent,
    QuoteFormComponent,
    DateAgoPipe,
    HighlightDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


function getScrollBarWidth() {
  // Add a hidden scrolling div to the page to get the width of a scrollbar
  const scrollDiv = document.createElement('div')
  scrollDiv.style.width = '99px'
  scrollDiv.style.height = '99px'
  scrollDiv.style.position = 'absolute'
  scrollDiv.style.top = '-9999px'
  scrollDiv.style.overflow = 'scroll'

  document.body.appendChild(scrollDiv)
  const scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
  document.body.removeChild(scrollDiv)

  return scrollbarWidth
}


function getBodyCurrentStyle(): BodyStyle {
  return document !== undefined
    ? pick(document.body.style, ['overflow', 'paddingRight'])
    : null
}


function setBodyStyles() {
  if (document !== undefined) {
    // Is there a vertical scrollbar?
    if (window.innerWidth > document.documentElement.clientWidth) {
      const scrollbarWidth = getScrollBarWidth()
      const curPaddingRight = window
        .getComputedStyle(document.body)
        .getPropertyValue('padding-right')
      if (curPaddingRight.indexOf('calc') === -1) {
        document.body.style.paddingRight = `calc(${curPaddingRight} + ${scrollbarWidth}px)`
      }
    }
    document.body.style.overflow = 'hidden'
  }
}


function resetBodyStyles(previousStyle: BodyStyle) {
  if (previousStyle) {
    document.body.style.paddingRight = previousStyle.paddingRight
    document.body.style.overflow = previousStyle.overflow
  }
}


export function getActiveScrollLock(lockMap: ScrollLockMap) {
  // Sort the elements according to dom position and return the last
  // which we assume to be stacked on top since all components using Portal
  // share a single zIndexFloor and use dom order to determine stacking
  const elements = Object.values(lockMap)
  if (elements.length === 0) return null

  const sortedElements = elements.sort((elementA, elementB) => {
    const relationship = elementA.compareDocumentPosition(elementB)
    return relationship > 3 ? 1 : -1
  })
  return sortedElements[0] || null
}


export function activateScrollLock(element: HTMLElement) {
  let scrollTop = window.scrollY
  let scrollTarget: EventTarget | HTMLElement | null = document

  // Handler for scroll event is needed since body overflow: hidden
  // won't stop other scroll-able elements from scrolling
  function stopScroll(e: Event) {
    if (e.target !== null && e.target !== scrollTarget) {
      // If the user has started scrolling in a new scroll-able element
      // we need to update the stored scroll top position
      scrollTarget = e.target
      scrollTop =
        scrollTarget instanceof Element
          ? scrollTarget.scrollTop
          : window.scrollY
    }
    if (
      scrollTarget instanceof Element &&
      !(element && element.contains(scrollTarget))
    ) {
      scrollTarget.scrollTop = scrollTop
    } else if (scrollTarget === document) {
      // Scroll event can't actually be prevented so instead we
      // scroll the window back to the stored position
      window.scrollTo({ top: scrollTop })
    }
  }

  const previousStyle = getBodyCurrentStyle()

  setBodyStyles()
  window.addEventListener('scroll', stopScroll, true)

  return () => {
    window.removeEventListener('scroll', stopScroll, true)
    resetBodyStyles(previousStyle)
  }
}


// Handler for scroll event is needed since body overflow: hidden
// won't stop other scroll-able elements from scrolling
function stopScroll(e: Event) {
    if (e.target !== null && e.target !== scrollTarget) {
      // If the user has started scrolling in a new scroll-able element
      // we need to update the stored scroll top position
      scrollTarget = e.target
      scrollTop =
        scrollTarget instanceof Element
          ? scrollTarget.scrollTop
          : window.scrollY
    }
    if (
      scrollTarget instanceof Element &&
      !(element && element.contains(scrollTarget))
    ) {
      scrollTarget.scrollTop = scrollTop
    } else if (scrollTarget === document) {
      // Scroll event can't actually be prevented so instead we
      // scroll the window back to the stored position
      window.scrollTo({ top: scrollTop })
    }
  }


(elementA, elementB) => {
    const relationship = elementA.compareDocumentPosition(elementB)
    return relationship > 3 ? 1 : -1
  }


() => {
    window.removeEventListener('scroll', stopScroll, true)
    resetBodyStyles(previousStyle)
  }


export interface ScrollLockMap {
  [key: string]: HTMLElement
}


// For the purposes of scroll lock, we're only interested in
// the overflow and paddingRight properties
type BodyStyle = Pick<CSSStyleDeclaration, 'overflow' | 'paddingRight'> | null


() => {
  let component: ReactWrapper<DateTimePickerProps>;
  const onChangeMock = jest.fn();
  const onCloseMock = jest.fn();
  const onOpenMock = jest.fn();

  beforeEach(() => {
    jest.clearAllMocks();
    component = mount(
      <DesktopDateTimePicker
        autoOk
        variant="outlined"
        onChange={onChangeMock}
        onClose={onCloseMock}
        onOpen={onOpenMock}
        inputFormat={format}
        KeyboardButtonProps={{ id: 'keyboard-button' }}
        value={utilsToUse.date('2018-01-01T00:00:00.000Z')}
      />
    );
  }


() => {
    jest.clearAllMocks();
    component = mount(
      <DesktopDateTimePicker
        autoOk
        variant="outlined"
        onChange={onChangeMock}
        onClose={onCloseMock}
        onOpen={onOpenMock}
        inputFormat={format}
        KeyboardButtonProps={{ id: 'keyboard-button' }}


() => {
    component.find('button#keyboard-button').simulate('click');
    expect(component.find('WithStyles(ForwardRef(Popover))').props().open).toBeTruthy();
    expect(onOpenMock).toHaveBeenCalled();
  }


() => {
    component.find('input').simulate('change', { target: { value: '02/01/2018 10:00' } });
    expect(onChangeMock).toHaveBeenCalled();
  }


interface RoundedButtonStylesType {
  button: ViewStyle
  buttonText: TextStyle
}


async(event: APIGatewayEvent): Promise<any> => {
  console.log(event);
  return {
    statusCode: 200,
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({"message": {"itemId": event.pathParameters?.itemId, "itemName": "Sample Item 1"}})
  };
}


export default class StopRotation extends GameClientPacket {
  CharObjectId!: number;
  Degree!: number;
  Speed!: number;
  // @Override
  readImpl(): boolean {
    const _id = this.readC();

    this.CharObjectId = this.readD();
    this.Degree = this.readD();
    this.Speed = this.readD();

    return true;
  }
}


// @Override
readImpl(): boolean {
    const _id = this.readC();

    this.CharObjectId = this.readD();
    this.Degree = this.readD();
    this.Speed = this.readD();

    return true;
  }


(value: vscode.Diagnostic) => {
            return value.severity === vscode.DiagnosticSeverity.Error &&
                value.code === RazorFullyQualifiedCodeActionTranslator.expectedCode;
        }


export class RazorFullyQualifiedCodeActionTranslator implements IRazorCodeActionTranslator {

    private static expectedCode = 'CS0246';

    public applyEdit(
        uri: vscode.Uri,
        edit: vscode.TextEdit): [vscode.Uri | undefined, vscode.TextEdit | undefined] {
        // The edit for this should just translate without additional help.
        throw new Error('Method not implemented.');
    }

    public canHandleEdit(uri: vscode.Uri, edit: vscode.TextEdit): boolean {
        // The edit for this should just translate without additional help.
        return false;
    }

    public canHandleCodeAction(
        codeAction: vscode.Command,
        codeContext: vscode.CodeActionContext,
        document: vscode.TextDocument): boolean {
        const isMissingDiag = (value: vscode.Diagnostic) => {
            return value.severity === vscode.DiagnosticSeverity.Error &&
                value.code === RazorFullyQualifiedCodeActionTranslator.expectedCode;
        };

        const diagnostic = codeContext.diagnostics.find(isMissingDiag);
        if (!diagnostic) {
            return false;
        }

        const codeRange = diagnostic.range;
        const associatedValue = document.getText(codeRange);

        // Once we have the correct diagnostic we want to make sure we have the correct CodeAction.
        // Unfortunately there's no ID for CodeActions, so we have to examine the human-readable title.
        // The title for the fully-qualified code action is just the fully qualified type, so we just ensure
        // 1. It's not a sentence (no spaces).
        // 2. It ends with the short TypeName (so it at least COULD be the Fully-Qualified type).
        if (codeAction.arguments &&
            !codeAction.title.includes(' ') &&
            codeAction.title.endsWith(associatedValue)) {
            return true;
        }

        return false;
    }
}


public applyEdit(
        uri: vscode.Uri,
        edit: vscode.TextEdit): [vscode.Uri | undefined, vscode.TextEdit | undefined] {
        // The edit for this should just translate without additional help.
        throw new Error('Method not implemented.');
    }


public canHandleEdit(uri: vscode.Uri, edit: vscode.TextEdit): boolean {
        // The edit for this should just translate without additional help.
        return false;
    }


public canHandleCodeAction(
        codeAction: vscode.Command,
        codeContext: vscode.CodeActionContext,
        document: vscode.TextDocument): boolean {
        const isMissingDiag = (value: vscode.Diagnostic) => {
            return value.severity === vscode.DiagnosticSeverity.Error &&
                value.code === RazorFullyQualifiedCodeActionTranslator.expectedCode;
        };

        const diagnostic = codeContext.diagnostics.find(isMissingDiag);
        if (!diagnostic) {
            return false;
        }

        const codeRange = diagnostic.range;
        const associatedValue = document.getText(codeRange);

        // Once we have the correct diagnostic we want to make sure we have the correct CodeAction.
        // Unfortunately there's no ID for CodeActions, so we have to examine the human-readable title.
        // The title for the fully-qualified code action is just the fully qualified type, so we just ensure
        // 1. It's not a sentence (no spaces).
        // 2. It ends with the short TypeName (so it at least COULD be the Fully-Qualified type).
        if (codeAction.arguments &&
            !codeAction.title.includes(' ') &&
            codeAction.title.endsWith(associatedValue)) {
            return true;
        }

        return false;
    }


export type CustomerAddressTypes = Core.CustomerAddressTypes


export type CustomerAddressSchema =
  Core.CustomerAddressSchema<CustomerAddressTypes>


userList => {
          this.userTransferData = userList.map(user => {
            return {
              key: user.userId,
              label: user.name
            }
          })
          this.loadRoleUser()
        }


user => {
            return {
              key: user.userId,
              label: user.name
            }
          }


error => {
          this.loading = false
          this.errorMessage('加载用户角色信息发生错误', error)
        }


() => {
            this.successMessage('保存成功')
          }


error => {
            this.errorMessage('设置人员失败', error)
          }


data => {
            this.loading = false
            this.userTransferModel = data
          }


error => {
            this.loading = false
            this.errorMessage('加载用户角色信息发生错误', error)
          }


data () {
    return {
      // 人员穿梭框数据
      userTransferData: [],
      // 选中的人员信息
      userTransferModel: [],
      loading: false
    }
  }


mounted () {
    this.loading = true
    ApiService.postAjax('sys/user/list', {})
        .then(userList => {
          this.userTransferData = userList.map(user => {
            return {
              key: user.userId,
              label: user.name
            }
          })
          this.loadRoleUser()
        }).catch(error => {
          this.loading = false
          this.errorMessage('加载用户角色信息发生错误', error)
        })
  }


/**
     * 监控角色ID变化
     */
roleId (_new, old) {
      if (_new !== old) {
        this.loadRoleUser()
      }
    }


/**
     * 设置角色用户
     */
handleSetUser () {
      const parameter = {}
      parameter[this.roleId] = this.userTransferModel
      ApiService.postAjax('sys/role/updateUser', parameter)
          .then(() => {
            this.successMessage('保存成功')
          }).catch(error => {
            this.errorMessage('设置人员失败', error)
          })
    }


loadRoleUser () {
      this.loading = true
      ApiService.postAjax('sys/role/getRoleUserId', { roleId: this.roleId })
          .then(data => {
            this.loading = false
            this.userTransferModel = data
          }).catch(error => {
            this.loading = false
            this.errorMessage('加载用户角色信息发生错误', error)
          })
    }


@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    FooterComponent,
    HomeComponent,
    LoginComponent,
    StartFRComponent,
    ContributeAmountComponent,
    ContributeComponent,
    DashboardComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }


({ currentPage, numPages }) => {
  return (
    <Wrapper>
      {currentPage > 1 && (
        <PageLink to={currentPage === 2 ? "/" : `/page/${currentPage - 1}`}


/**
 * @category Core
 */
export class InteractionManager {
    private readonly externalInteractors: IExternalInteractor[];
    private readonly particleInteractors: IParticlesInteractor[];

    constructor(private readonly container: Container) {
        const interactors = Plugins.getInteractors(container);

        this.externalInteractors = [
            new Bouncer(container),
            new Bubbler(container),
            new Connector(container),
            new Grabber(container),
            new MouseLighter(container),
            new MouseAttractor(container),
            new Repulser(container),
            new TrailMaker(container),
        ];

        this.particleInteractors = [
            new ParticlesAttractor(container),
            new ParticlesLighter(container),
            new Collider(container),
            new Linker(container),
        ];

        for (const interactor of interactors) {
            switch (interactor.type) {
                case InteractorType.External:
                    this.externalInteractors.push(interactor as IExternalInteractor);
                    break;
                case InteractorType.Particles:
                    this.particleInteractors.push(interactor as IParticlesInteractor);
                    break;
            }
        }
    }

    externalInteract(delta: IDelta): void {
        for (const interactor of this.externalInteractors) {
            if (interactor.isEnabled()) {
                interactor.interact(delta);
            }
        }
    }

    particlesInteract(particle: Particle, delta: IDelta): void {
        for (const interactor of this.externalInteractors) {
            interactor.reset(particle);
        }

        /* interaction auto between particles */
        for (const interactor of this.particleInteractors) {
            if (interactor.isEnabled(particle)) {
                interactor.interact(particle, delta);
            }
        }
    }
}


externalInteract(delta: IDelta): void {
        for (const interactor of this.externalInteractors) {
            if (interactor.isEnabled()) {
                interactor.interact(delta);
            }
        }
    }


particlesInteract(particle: Particle, delta: IDelta): void {
        for (const interactor of this.externalInteractors) {
            interactor.reset(particle);
        }

        /* interaction auto between particles */
        for (const interactor of this.particleInteractors) {
            if (interactor.isEnabled(particle)) {
                interactor.interact(particle, delta);
            }
        }
    }


/** @public */
export interface ICastableToString {
  toString: () => string;
}


/** @public */
export interface IColorRamp extends ICastableToString {
  values: string[];
  index: number;
}


/** @public */
export interface ITokenResolver {
  dependsOn: string | string[];
  resolve?: (arg: ITokenLiteral[], theme: ITheme) => ITokenLiteral;
}


/** @public */
export interface ITheme {
  direction: "rtl" | "ltr";

  colors: IThemeColorDefinition;

  fonts: {
    default: string;
    userContent: string;
    mono: string;
    [key: string]: string;
  };

  fontSizes: {
    base: number;
    scale: number;
    unit: "px" | "rem" | "pt";
  };

  animations: {
    fadeIn: {};
    fadeOut: {};
  };

  spacing: {
    base: number;
    scale: number;
    unit: "px" | "rem";
  };

  radius: {
    base: number;
    scale: number;
    unit: "px" | "rem" | "%";
  };

  icons: {};

  components: IComponentOverrideGroup;

  schemes: {
    [key: string]: ITheme;
  };
}


/** @public */
export type IColor = string;


/** @public */
export type ITokenLiteral = string | number | ICastableToString;


/** @public */
export type IToken =
  | ITokenLiteral
  | ((theme: ITheme) => ITokenLiteral)
  | ITokenResolver;


/** @public */
export type IResolvedTokens<TTokens> = {
  [key in keyof TTokens]: ITokenLiteral;
};


type IComponentOverrides = {
  tokens?: any;
  styles?: any;
  slots?: any;
};


type IComponentOverrideGroup = { [componentName: string]: IComponentOverrides };


export type IThemeColorDefinition = {
  background: IColor;
  bodyText: IColor;
  subText: IColor;
  disabledText: IColor;

  brand: IColorRamp;
  accent: IColorRamp;

  neutral: IColorRamp;

  success: IColorRamp;
  warning: IColorRamp;
  danger: IColorRamp;

  [key: string]: IColorRamp | string;
};


export type DeepPartial<T> = {
  [key in keyof T]?: {
    [key2 in keyof T[key]]?: T[key][key2];
  };
};


export type IPartialTheme = DeepPartial<Omit<ITheme, "schemes">> & {
  schemes?: {
    [key: string]: IPartialTheme;
  };
};


@Module({
  imports: [],
  controllers: [AppController, TodoController],
  providers: [AppService, SearchTodoService],
})
export class AppModule {}


(bill: number) => {}


(newInfo: string) => {}


loggedIn => {
      if (loggedIn) {
        this.api.getPrices()
      .subscribe(res => {
        this.cryptos = res;
      });

        this._getTvshows();

        this._getProducts();

        this.api.dailyForecast()
        .subscribe(res => {
          console.log(res);

        });

      } else {
        this.tvshows = null;
        this._destroyTvshowsSubscription();
        this.products = null;
        this._destroyProductsSubscription();
      }
    }


res => {
        this.cryptos = res;
      }


res => {
          console.log(res);

        }


data => {
        this.tvshows = data;
      }


err => console.warn(err)


() => console.log('Request complete')


data => {
        this.products = data['products'];

        console.log(name);
      }


() => console.log('Product Request complete')


@Component({
  moduleId: module.id,
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
  objectKeys = Object.keys;
  cryptos: any;
  tvshows: any[];
  name: any;
  price: any;
  authSubscription: Subscription;
  tvshowsSubscription: Subscription;
  products: any;
  productsSubscription: Subscription;
  chart = []; // This will hold our chart info
  city = [];
  country = [];
  currentWeather = [];
  constructor(
       private api: ApiService,
       public auth: AuthService) { }

  ngOnInit() {
    // Subscribe to login status subject
    // If authenticated, subscribe to tvshows data observable
    // If not authenticated, unsubscribe from tvshows data
    this.authSubscription = this.auth.loggedIn$.
    subscribe(loggedIn => {
      if (loggedIn) {
        this.api.getPrices()
      .subscribe(res => {
        this.cryptos = res;
      });

        this._getTvshows();

        this._getProducts();

        this.api.dailyForecast()
        .subscribe(res => {
          console.log(res);

        });

      } else {
        this.tvshows = null;
        this._destroyTvshowsSubscription();
        this.products = null;
        this._destroyProductsSubscription();
      }
    });
  }

  ngOnDestroy() {
    // Unsubscribe from observables
    this.authSubscription.unsubscribe();
    this._destroyTvshowsSubscription();
    this._destroyProductsSubscription();
  }

  private _getTvshows() {
    // Subscribe to tvshows API observable
    this.tvshowsSubscription = this.api.getTvshows$()
    .subscribe(
      data => {
        this.tvshows = data;
      },
      err => console.warn(err),
      () => console.log('Request complete')
    );
  }

  private _destroyTvshowsSubscription() {
    // If a tvshows subscription exists, unsubscribe
    if (this.tvshowsSubscription) {
      this.tvshowsSubscription.unsubscribe();
    }
  }

  get tvshowsExist() {
    return !!this.tvshows && this.tvshows.length;
  }

  private _getProducts() {
    // Subscribe to products API observable
    this.productsSubscription = this.api.getProducts$()
    .subscribe(
      data => {
        this.products = data['products'];

        console.log(name);
      },
      err => console.warn(err),
      () => console.log('Product Request complete')
    );
  }

  private _destroyProductsSubscription() {
    // If a products subscription exists, unsubscribe
    if (this.productsSubscription) {
      this.productsSubscription.unsubscribe();
    }
  }

  get productsExist() {
    return !!this.products && this.products.length;
  }
}


ngOnInit() {
    // Subscribe to login status subject
    // If authenticated, subscribe to tvshows data observable
    // If not authenticated, unsubscribe from tvshows data
    this.authSubscription = this.auth.loggedIn$.
    subscribe(loggedIn => {
      if (loggedIn) {
        this.api.getPrices()
      .subscribe(res => {
        this.cryptos = res;
      });

        this._getTvshows();

        this._getProducts();

        this.api.dailyForecast()
        .subscribe(res => {
          console.log(res);

        });

      } else {
        this.tvshows = null;
        this._destroyTvshowsSubscription();
        this.products = null;
        this._destroyProductsSubscription();
      }
    });
  }


ngOnDestroy() {
    // Unsubscribe from observables
    this.authSubscription.unsubscribe();
    this._destroyTvshowsSubscription();
    this._destroyProductsSubscription();
  }


private _getTvshows() {
    // Subscribe to tvshows API observable
    this.tvshowsSubscription = this.api.getTvshows$()
    .subscribe(
      data => {
        this.tvshows = data;
      },
      err => console.warn(err),
      () => console.log('Request complete')
    );
  }


private _destroyTvshowsSubscription() {
    // If a tvshows subscription exists, unsubscribe
    if (this.tvshowsSubscription) {
      this.tvshowsSubscription.unsubscribe();
    }
  }


private _getProducts() {
    // Subscribe to products API observable
    this.productsSubscription = this.api.getProducts$()
    .subscribe(
      data => {
        this.products = data['products'];

        console.log(name);
      },
      err => console.warn(err),
      () => console.log('Product Request complete')
    );
  }


private _destroyProductsSubscription() {
    // If a products subscription exists, unsubscribe
    if (this.productsSubscription) {
      this.productsSubscription.unsubscribe();
    }
  }


/**
 * https://standards.buildingsmart.org/IFC/RELEASE/IFC4/ADD2/HTML/link/ifcmechanicalfastenertype.htm
 */
export class IfcMechanicalFastenerType extends IfcElementComponentType {
	PredefinedType : IfcMechanicalFastenerTypeEnum
	NominalDiameter : IfcPositiveLengthMeasure // optional
	NominalLength : IfcPositiveLengthMeasure // optional

    constructor(globalId : IfcGloballyUniqueId, predefinedType : IfcMechanicalFastenerTypeEnum) {
        super(globalId)
		this.PredefinedType = predefinedType

    }
    getStepParameters() : string {
        var parameters = new Array<string>();
		parameters.push(BaseIfc.toStepValue(this.GlobalId))
		parameters.push(BaseIfc.toStepValue(this.OwnerHistory))
		parameters.push(BaseIfc.toStepValue(this.Name))
		parameters.push(BaseIfc.toStepValue(this.Description))
		parameters.push(BaseIfc.toStepValue(this.ApplicableOccurrence))
		parameters.push(BaseIfc.toStepValue(this.HasPropertySets))
		parameters.push(BaseIfc.toStepValue(this.RepresentationMaps))
		parameters.push(BaseIfc.toStepValue(this.Tag))
		parameters.push(BaseIfc.toStepValue(this.ElementType))
		parameters.push(BaseIfc.toStepValue(this.PredefinedType))
		parameters.push(BaseIfc.toStepValue(this.NominalDiameter))
		parameters.push(BaseIfc.toStepValue(this.NominalLength))

        return parameters.join();
    }
}


getStepParameters() : string {
        var parameters = new Array<string>();
		parameters.push(BaseIfc.toStepValue(this.GlobalId))
		parameters.push(BaseIfc.toStepValue(this.OwnerHistory))
		parameters.push(BaseIfc.toStepValue(this.Name))
		parameters.push(BaseIfc.toStepValue(this.Description))
		parameters.push(BaseIfc.toStepValue(this.ApplicableOccurrence))
		parameters.push(BaseIfc.toStepValue(this.HasPropertySets))
		parameters.push(BaseIfc.toStepValue(this.RepresentationMaps))
		parameters.push(BaseIfc.toStepValue(this.Tag))
		parameters.push(BaseIfc.toStepValue(this.ElementType))
		parameters.push(BaseIfc.toStepValue(this.PredefinedType))
		parameters.push(BaseIfc.toStepValue(this.NominalDiameter))
		parameters.push(BaseIfc.toStepValue(this.NominalLength))

        return parameters.join();
    }


class Test {
    public static test() {
        console.log("hej")
    }
}


public static test() {
        console.log("hej")
    }


(result) => {
        this.allPokemonByType = result.pokemon;
      }


(error) => {
        console.error(`Something went wrong!: ${error.message}`)
      }


({ type }) => {
            return (
              <button onClick={() => this.clickHandler(type.name)}


i => {
            return (
              <pokemon-link text={i.pokemon.name} url={`/profile/${i.pokemon.name}`}


@Component({
  tag: 'pokemon-types',
  styleUrl: 'pokemon-types.css',
  shadow: true,
})
export class PokemonTypes {

  @State() allPokemonByType: PokemonTypeItem[];

  /** the pokemon types */
  @Prop() types!: PokemonType[]

  async clickHandler(name) {
    await getPokemonByType(name)
      .then((result) => {
        this.allPokemonByType = result.pokemon;
      }).catch((error) => {
        console.error(`Something went wrong!: ${error.message}`)
      })
  }

  render() {
    return (

Types

          {this.types.map(({ type }) => {
            return (
              <button onClick={() => this.clickHandler(type.name)}>
                {type.name}
              </button>
            )
          })}


async clickHandler(name) {
    await getPokemonByType(name)
      .then((result) => {
        this.allPokemonByType = result.pokemon;
      }).catch((error) => {
        console.error(`Something went wrong!: ${error.message}`)
      })
  }


render() {
    return (

Types

          {this.types.map(({ type }) => {
            return (
              <button onClick={() => this.clickHandler(type.name)}>
                {type.name}
              </button>
            )
          })}


isEncrypted(): boolean {
      return (
        getPathMatchedKeys(this.$themeConfig.encrypt, this.article.path)
          .length !== 0 || Boolean(this.article.frontmatter.password)
      );
    }


// Simple
export interface Group {
  GroupID?: number
  GroupName?: string
}


export interface Science {
  Group?: number
  ScienceID?: number
  ScienceName?: string
}


export interface Branch {
  Science?: number
  BranchID?: number
  BranchName?: string
  Desc?: string
}


export interface Subject {
  Science?: number
  Branch?: number
  SubjectID?: number
  SubjectName?: string
}


export interface Formula {
  Subject?: number
  ID?: number
  Name?: string
  Content?: string
  Difficulty?: number
  Unit?: string
  Quantities?: Quantity | Quantity[]
}


// Objects
export interface ScienceObject {
  ScienceName?: string
  ScienceID?: number
  Group?: {
    _id?: string
    GroupID?: number
    GroupName?: string
  }
}


export interface BranchObject {
  BranchName?: string
  BranchID?: number
  Science?: ScienceObject
  Subjects?: SubjectObject[] | (Subject & { _id: string })[]
}


export interface SubjectObject {
  Branch?: number
  SubjectName?: string
  SubjectID?: number
  Formulas?: Formula[]
}


interface Quantity {
  Symbol?: string
  Content?: string
}


(la) => la.id === newMessage.room_id


@Injectable()
export class ExhibitsService {
  public live_auctions: IAuction[];
  public psuedo_auto_users: IUser[];

  private readonly logger = new Logger(ExhibitsService.name);

  constructor(
    @InjectModel("User") private readonly userModel: Model<IUser>,
    @InjectModel("Message") private readonly messageModel: Model<IMessage>,
    @InjectModel("Login") private readonly loginModel: Model<ILogin>,
    @Inject("PUB_SUB") private pubSub: PubSub,
    private usersService: UsersService,
    private notesService: NotesService,
    private httpService: HttpService,
  ) {

  }

  sendWinnerNote(auction: IAuction): void {
    const content = `You winned the auction. Please check here. ${process.env.SITE_URL}auctions/${auction.id}`; // need to fix "completed when uncomment above comments"
    try {
      this.pubSub.publish("privateNoteUpdated", {
        privateNoteUpdated: {
          title: "winner",
          content,
          receiver: auction.bidders[0].user.id,
        },
      });
    } catch (e) {
      console.log("exception private notedata....", e);
    }
  }

  getFilter(filter: Filter): any {
    const filterQuery =
      filter.cat === "All"
        ? {
            "product.title": { $regex: filter.key, $options: "i" },
          }
        : {
            "product.title": { $regex: filter.key, $options: "i" },
            "product.category": filter.cat,
          };

    return filterQuery;
  }

  getSort(filter: Filter): any {
    let sortQuery = {};
    if (filter.sort === "latest") sortQuery = { created_at: -1 };
    else if (filter.sort === "oldest") sortQuery = { created_at: 1 };
    else if (filter.sort === "highest") sortQuery = { "product.price": -1 };
    else if (filter.sort === "lowest") sortQuery = { "product.price": 1 };
    else if (filter.sort === "most") sortQuery = { fund_percent: -1 };
    else if (filter.sort === "fewest") sortQuery = { fund_percent: 1 };
    else if (filter.sort === "soon") sortQuery = { timer: 1 };
    else if (filter.sort === "manual") sortQuery = { manual: 1 };

    return sortQuery;
  }

  async addToChatters(newMessage: IMessage): Promise<void> {
    const chat_auction = this.live_auctions.filter(
      (la) => la.id === newMessage.room_id,
    )[0];
    if (chat_auction && !chat_auction.chatters.includes(newMessage.user_id)) {
      chat_auction.chatters.push(newMessage.user_id);
      this.pubSub.publish("auctionUpdated", { auctionUpdated: { auction: chat_auction, timestamp: new Date().getTime() } });
    }
  }

  async createMessage(newMessageInput: MessageInput): Promise<boolean> {
    const messageModel = new this.messageModel(newMessageInput);
    const newMessage = await messageModel.save();

    this.addToChatters(newMessage);

    return newMessage ? true : false;
  }

  async findMessages(): Promise<IMessage[]> {
    const messages = await this.messageModel.find({}).exec();
    return messages;
  }

  }


sendWinnerNote(auction: IAuction): void {
    const content = `You winned the auction. Please check here. ${process.env.SITE_URL}auctions/${auction.id}`; // need to fix "completed when uncomment above comments"
    try {
      this.pubSub.publish("privateNoteUpdated", {
        privateNoteUpdated: {
          title: "winner",
          content,
          receiver: auction.bidders[0].user.id,
        },
      });
    } catch (e) {
      console.log("exception private notedata....", e);
    }
  }


getFilter(filter: Filter): any {
    const filterQuery =
      filter.cat === "All"
        ? {
            "product.title": { $regex: filter.key, $options: "i" },
          }
        : {
            "product.title": { $regex: filter.key, $options: "i" },
            "product.category": filter.cat,
          };

    return filterQuery;
  }


getSort(filter: Filter): any {
    let sortQuery = {};
    if (filter.sort === "latest") sortQuery = { created_at: -1 };
    else if (filter.sort === "oldest") sortQuery = { created_at: 1 };
    else if (filter.sort === "highest") sortQuery = { "product.price": -1 };
    else if (filter.sort === "lowest") sortQuery = { "product.price": 1 };
    else if (filter.sort === "most") sortQuery = { fund_percent: -1 };
    else if (filter.sort === "fewest") sortQuery = { fund_percent: 1 };
    else if (filter.sort === "soon") sortQuery = { timer: 1 };
    else if (filter.sort === "manual") sortQuery = { manual: 1 };

    return sortQuery;
  }


async addToChatters(newMessage: IMessage): Promise<void> {
    const chat_auction = this.live_auctions.filter(
      (la) => la.id === newMessage.room_id,
    )[0];
    if (chat_auction && !chat_auction.chatters.includes(newMessage.user_id)) {
      chat_auction.chatters.push(newMessage.user_id);
      this.pubSub.publish("auctionUpdated", { auctionUpdated: { auction: chat_auction, timestamp: new Date().getTime() } });
    }
  }


async createMessage(newMessageInput: MessageInput): Promise<boolean> {
    const messageModel = new this.messageModel(newMessageInput);
    const newMessage = await messageModel.save();

    this.addToChatters(newMessage);

    return newMessage ? true : false;
  }


async findMessages(): Promise<IMessage[]> {
    const messages = await this.messageModel.find({}).exec();
    return messages;
  }


export declare function getSemanticTokenLegend(): {
    types: string[];
    modifiers: string[];
};


export declare function getSemanticTokens(jsLanguageService: ts.LanguageService, currentTextDocument: TextDocument, fileName: string): SemanticTokenData[];


export declare const enum TokenType {
    class = 0,
    enum = 1,
    interface = 2,
    namespace = 3,
    typeParameter = 4,
    type = 5,
    parameter = 6,
    variable = 7,
    property = 8,
    function = 9,
    method = 10,
    _ = 11
}


export declare const enum TokenModifier {
    declaration = 0,
    static = 1,
    async = 2,
    readonly = 3,
    _ = 4
}


/** Class representing a MeshSecret. */
export class MeshSecret {
  private readonly client: ServiceFabricClientContext;

  /**
   * Create a MeshSecret.
   * @param {ServiceFabricClientContext} client Reference to the service client.
   */
  constructor(client: ServiceFabricClientContext) {
    this.client = client;
  }

  /**
   * Creates a Secret resource with the specified name, description and properties. If Secret
   * resource with the same name exists, then it is updated with the specified description and
   * properties. Once created, the kind and contentType of a secret resource cannot be updated.
   * @summary Creates or updates a Secret resource.
   * @param secretResourceName The name of the secret resource.
   * @param secretResourceDescription Description for creating a secret resource.
   * @param [options] The optional parameters
   * @returns Promise<Models.MeshSecretCreateOrUpdateResponse>
   */
  createOrUpdate(secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, options?: msRest.RequestOptionsBase): Promise<Models.MeshSecretCreateOrUpdateResponse>;
  /**
   * @param secretResourceName The name of the secret resource.
   * @param secretResourceDescription Description for creating a secret resource.
   * @param callback The callback
   */
  createOrUpdate(secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void;
  /**
   * @param secretResourceName The name of the secret resource.
   * @param secretResourceDescription Description for creating a secret resource.
   * @param options The optional parameters
   * @param callback The callback
   */
  createOrUpdate(secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void;
  createOrUpdate(secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescription>, callback?: msRest.ServiceCallback<Models.SecretResourceDescription>): Promise<Models.MeshSecretCreateOrUpdateResponse> {
    return this.client.sendOperationRequest(
      {
        secretResourceName,
        secretResourceDescription,
        options
      },
      createOrUpdateOperationSpec,
      callback) as Promise<Models.MeshSecretCreateOrUpdateResponse>;
  }

  /**
   * Gets the information about the Secret resource with the given name. The information include the
   * description and other properties of the Secret.
   * @summary Gets the Secret resource with the given name.
   * @param secretResourceName The name of the secret resource.
   * @param [options] The optional parameters
   * @returns Promise<Models.MeshSecretGetResponse>
   */
  get(secretResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.MeshSecretGetResponse>;
  /**
   * @param secretResourceName The name of the secret resource.
   * @param callback The callback
   */
  get(secretResourceName: string, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void;
  /**
   * @param secretResourceName The name of the secret resource.
   * @param options The optional parameters
   * @param callback The callback
   */
  get(secretResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void;
  get(secretResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescription>, callback?: msRest.ServiceCallback<Models.SecretResourceDescription>): Promise<Models.MeshSecretGetResponse> {
    return this.client.sendOperationRequest(
      {
        secretResourceName,
        options
      },
      getOperationSpec,
      callback) as Promise<Models.MeshSecretGetResponse>;
  }

  /**
   * Deletes the specified Secret resource and all of its named values.
   * @summary Deletes the Secret resource.
   * @param secretResourceName The name of the secret resource.
   * @param [options] The optional parameters
   * @returns Promise<msRest.RestResponse>
   */
  deleteMethod(secretResourceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
  /**
   * @param secretResourceName The name of the secret resource.
   * @param callback The callback
   */
  deleteMethod(secretResourceName: string, callback: msRest.ServiceCallback<void>): void;
  /**
   * @param secretResourceName The name of the secret resource.
   * @param options The optional parameters
   * @param callback The callback
   */
  deleteMethod(secretResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
  deleteMethod(secretResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
    return this.client.sendOperationRequest(
      {
        secretResourceName,
        options
      },
      deleteMethodOperationSpec,
      callback);
  }

  /**
   * Gets the information about all secret resources in a given resource group. The information
   * include the description and other properties of the Secret.
   * @summary Lists all the secret resources.
   * @param [options] The optional parameters
   * @returns Promise<Models.MeshSecretListResponse>
   */
  list(options?: msRest.RequestOptionsBase): Promise<Models.MeshSecretListResponse>;
  /**
   * @param callback The callback
   */
  list(callback: msRest.ServiceCallback<Models.PagedSecretResourceDescriptionList>): void;
  /**
   * @param options The optional parameters
   * @param callback The callback
   */
  list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PagedSecretResourceDescriptionList>): void;
  list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PagedSecretResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.PagedSecretResourceDescriptionList>): Promise<Models.MeshSecretListResponse> {
    return this.client.sendOperationRequest(
      {
        options
      },
      listOperationSpec,
      callback) as Promise<Models.MeshSecretListResponse>;
  }
}


/**
   * Creates a Secret resource with the specified name, description and properties. If Secret
   * resource with the same name exists, then it is updated with the specified description and
   * properties. Once created, the kind and contentType of a secret resource cannot be updated.
   * @summary Creates or updates a Secret resource.
   * @param secretResourceName The name of the secret resource.
   * @param secretResourceDescription Description for creating a secret resource.
   * @param [options] The optional parameters
   * @returns Promise<Models.MeshSecretCreateOrUpdateResponse>
   */
createOrUpdate(secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, options?: msRest.RequestOptionsBase): Promise<Models.MeshSecretCreateOrUpdateResponse>;


/**
   * @param secretResourceName The name of the secret resource.
   * @param secretResourceDescription Description for creating a secret resource.
   * @param callback The callback
   */
createOrUpdate(secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void;


/**
   * @param secretResourceName The name of the secret resource.
   * @param secretResourceDescription Description for creating a secret resource.
   * @param options The optional parameters
   * @param callback The callback
   */
createOrUpdate(secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void;


createOrUpdate(secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescription>, callback?: msRest.ServiceCallback<Models.SecretResourceDescription>): Promise<Models.MeshSecretCreateOrUpdateResponse> {
    return this.client.sendOperationRequest(
      {
        secretResourceName,
        secretResourceDescription,
        options
      },
      createOrUpdateOperationSpec,
      callback) as Promise<Models.MeshSecretCreateOrUpdateResponse>;
  }


/**
   * Gets the information about the Secret resource with the given name. The information include the
   * description and other properties of the Secret.
   * @summary Gets the Secret resource with the given name.
   * @param secretResourceName The name of the secret resource.
   * @param [options] The optional parameters
   * @returns Promise<Models.MeshSecretGetResponse>
   */
get(secretResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.MeshSecretGetResponse>;


/**
   * @param secretResourceName The name of the secret resource.
   * @param callback The callback
   */
get(secretResourceName: string, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void;


/**
   * @param secretResourceName The name of the secret resource.
   * @param options The optional parameters
   * @param callback The callback
   */
get(secretResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void;


get(secretResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescription>, callback?: msRest.ServiceCallback<Models.SecretResourceDescription>): Promise<Models.MeshSecretGetResponse> {
    return this.client.sendOperationRequest(
      {
        secretResourceName,
        options
      },
      getOperationSpec,
      callback) as Promise<Models.MeshSecretGetResponse>;
  }


/**
   * Deletes the specified Secret resource and all of its named values.
   * @summary Deletes the Secret resource.
   * @param secretResourceName The name of the secret resource.
   * @param [options] The optional parameters
   * @returns Promise<msRest.RestResponse>
   */
deleteMethod(secretResourceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;


/**
   * @param secretResourceName The name of the secret resource.
   * @param callback The callback
   */
deleteMethod(secretResourceName: string, callback: msRest.ServiceCallback<void>): void;


/**
   * @param secretResourceName The name of the secret resource.
   * @param options The optional parameters
   * @param callback The callback
   */
deleteMethod(secretResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;


deleteMethod(secretResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
    return this.client.sendOperationRequest(
      {
        secretResourceName,
        options
      },
      deleteMethodOperationSpec,
      callback);
  }


/**
   * Gets the information about all secret resources in a given resource group. The information
   * include the description and other properties of the Secret.
   * @summary Lists all the secret resources.
   * @param [options] The optional parameters
   * @returns Promise<Models.MeshSecretListResponse>
   */
list(options?: msRest.RequestOptionsBase): Promise<Models.MeshSecretListResponse>;


/**
   * @param callback The callback
   */
list(callback: msRest.ServiceCallback<Models.PagedSecretResourceDescriptionList>): void;


/**
   * @param options The optional parameters
   * @param callback The callback
   */
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PagedSecretResourceDescriptionList>): void;


list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PagedSecretResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.PagedSecretResourceDescriptionList>): Promise<Models.MeshSecretListResponse> {
    return this.client.sendOperationRequest(
      {
        options
      },
      listOperationSpec,
      callback) as Promise<Models.MeshSecretListResponse>;
  }


async function bootstrap() {
  const appPort = process.env.APP_PORT;

  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.enableCors({
    origin: process.env.CLIENT_URL,
  });

  await app.listen(appPort);
}


(clusterHealth: ClusterHealth) => {
        const nodesHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Node);
        this.nodesDashboard = DashboardViewModel.fromHealthStateCount('Nodes', 'Node', true, nodesHealthStateCount, this.data.routes, RoutesService.getNodesViewPath());

        const appsHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Application);
        this.appsDashboard = DashboardViewModel.fromHealthStateCount('Applications', 'Application', true, appsHealthStateCount, this.data.routes, RoutesService.getAppsViewPath());

        const servicesHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Service);
        this.servicesDashboard = DashboardViewModel.fromHealthStateCount('Services', 'Service', false, servicesHealthStateCount);

        const partitionsDashboard = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Partition);
        this.partitionsDashboard = DashboardViewModel.fromHealthStateCount('Partitions', 'Partition', false, partitionsDashboard);

        const replicasHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Replica);
        this.replicasDashboard = DashboardViewModel.fromHealthStateCount('Replicas', 'Replica', false, replicasHealthStateCount);
        clusterHealth.checkExpiredCertStatus();
    }


apps => {
                    this.upgradeAppsCount = apps.collection.filter(app => app.isUpgrading).length;
                }


app => app.isUpgrading


() => {this.updateItemInEssentials(); }


err => of(null)


(manifest) => {
        if (manifest.isRepairManagerEnabled) {
          return this.repairtaskCollection.refresh(messageHandler);
        }else{
          return of(null);
        }
      }


() => {
      this.updateItemInEssentials();
    }


@Component({
  selector: 'app-essentials',
  templateUrl: './essentials.component.html',
  styleUrls: ['./essentials.component.scss']
})
export class EssentialsComponent extends BaseControllerDirective {

  clusterUpgradeProgress: ClusterUpgradeProgress;
  nodes: NodeCollection;
  clusterHealth: ClusterHealth;
  systemApp: SystemApplication;
  clusterManifest: ClusterManifest;
  repairtaskCollection: RepairTaskCollection;

  nodesDashboard: IDashboardViewModel;
  appsDashboard: IDashboardViewModel;
  servicesDashboard: IDashboardViewModel;
  partitionsDashboard: IDashboardViewModel;
  replicasDashboard: IDashboardViewModel;
  upgradesDashboard: IDashboardViewModel;
  upgradeAppsCount = 0;

  essentialItems: IEssentialListItem[] = [];

  constructor(public data: DataService,
              public injector: Injector,
              public settings: SettingsService,
              private routes: RoutesService) {
    super(injector);
  }

  setup() {
    this.clusterHealth = this.data.getClusterHealth(HealthStateFilterFlags.Default, HealthStateFilterFlags.None, HealthStateFilterFlags.None);
    this.clusterUpgradeProgress = this.data.clusterUpgradeProgress;
    this.nodes = this.data.nodes;
    this.systemApp = this.data.systemApp;
    this.repairtaskCollection = this.data.repairCollection;
  }

  refresh(messageHandler?: IResponseMessageHandler): Observable<any> {
    return forkJoin([
      this.clusterHealth.refresh(messageHandler).pipe(map((clusterHealth: ClusterHealth) => {
        const nodesHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Node);
        this.nodesDashboard = DashboardViewModel.fromHealthStateCount('Nodes', 'Node', true, nodesHealthStateCount, this.data.routes, RoutesService.getNodesViewPath());

        const appsHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Application);
        this.appsDashboard = DashboardViewModel.fromHealthStateCount('Applications', 'Application', true, appsHealthStateCount, this.data.routes, RoutesService.getAppsViewPath());

        const servicesHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Service);
        this.servicesDashboard = DashboardViewModel.fromHealthStateCount('Services', 'Service', false, servicesHealthStateCount);

        const partitionsDashboard = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Partition);
        this.partitionsDashboard = DashboardViewModel.fromHealthStateCount('Partitions', 'Partition', false, partitionsDashboard);

        const replicasHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Replica);
        this.replicasDashboard = DashboardViewModel.fromHealthStateCount('Replicas', 'Replica', false, replicasHealthStateCount);
        clusterHealth.checkExpiredCertStatus();
    })),
      this.data.getApps(true, messageHandler)
                .pipe(map(apps => {
                    this.upgradeAppsCount = apps.collection.filter(app => app.isUpgrading).length;
                })),
      this.nodes.refresh(messageHandler).pipe(map(() => {this.updateItemInEssentials(); })),
      this.systemApp.refresh(messageHandler).pipe(catchError(err => of(null))),
      this.clusterUpgradeProgress.refresh(messageHandler),
      this.data.getClusterManifest().pipe(map((manifest) => {
        if (manifest.isRepairManagerEnabled) {
          return this.repairtaskCollection.refresh(messageHandler);
        }else{
          return of(null);
        }
      }))
    ]).pipe(map(() => {
      this.updateItemInEssentials();
    }));
  }

  updateItemInEssentials() {
    this.essentialItems = [
      {
        descriptionName: 'Code Version',
        copyTextValue: this.clusterUpgradeProgress?.raw?.CodeVersion,
        displayText: this.clusterUpgradeProgress?.raw?.CodeVersion,
      },
      {
        descriptionName: 'Fault Domains',
        displayText: this.nodes.faultDomains.length.toString(),
        copyTextValue: this.nodes.faultDomains.length.toString()
      },
      {
        descriptionName: 'Upgrade Domains',
        displayText: this.nodes.upgradeDomains.length.toString(),
        copyTextValue: this.nodes.upgradeDomains.length.toString()
      },
      {
        descriptionName: 'Healthy Seed Nodes',
        displayText: this.nodes.healthySeedNodes,
        copyTextValue: this.nodes.healthySeedNodes
      }
    ];
  }
}


setup() {
    this.clusterHealth = this.data.getClusterHealth(HealthStateFilterFlags.Default, HealthStateFilterFlags.None, HealthStateFilterFlags.None);
    this.clusterUpgradeProgress = this.data.clusterUpgradeProgress;
    this.nodes = this.data.nodes;
    this.systemApp = this.data.systemApp;
    this.repairtaskCollection = this.data.repairCollection;
  }


refresh(messageHandler?: IResponseMessageHandler): Observable<any> {
    return forkJoin([
      this.clusterHealth.refresh(messageHandler).pipe(map((clusterHealth: ClusterHealth) => {
        const nodesHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Node);
        this.nodesDashboard = DashboardViewModel.fromHealthStateCount('Nodes', 'Node', true, nodesHealthStateCount, this.data.routes, RoutesService.getNodesViewPath());

        const appsHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Application);
        this.appsDashboard = DashboardViewModel.fromHealthStateCount('Applications', 'Application', true, appsHealthStateCount, this.data.routes, RoutesService.getAppsViewPath());

        const servicesHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Service);
        this.servicesDashboard = DashboardViewModel.fromHealthStateCount('Services', 'Service', false, servicesHealthStateCount);

        const partitionsDashboard = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Partition);
        this.partitionsDashboard = DashboardViewModel.fromHealthStateCount('Partitions', 'Partition', false, partitionsDashboard);

        const replicasHealthStateCount = HealthUtils.getHealthStateCount(clusterHealth.raw, HealthStatisticsEntityKind.Replica);
        this.replicasDashboard = DashboardViewModel.fromHealthStateCount('Replicas', 'Replica', false, replicasHealthStateCount);
        clusterHealth.checkExpiredCertStatus();
    })),
      this.data.getApps(true, messageHandler)
                .pipe(map(apps => {
                    this.upgradeAppsCount = apps.collection.filter(app => app.isUpgrading).length;
                })),
      this.nodes.refresh(messageHandler).pipe(map(() => {this.updateItemInEssentials(); })),
      this.systemApp.refresh(messageHandler).pipe(catchError(err => of(null))),
      this.clusterUpgradeProgress.refresh(messageHandler),
      this.data.getClusterManifest().pipe(map((manifest) => {
        if (manifest.isRepairManagerEnabled) {
          return this.repairtaskCollection.refresh(messageHandler);
        }else{
          return of(null);
        }
      }))
    ]).pipe(map(() => {
      this.updateItemInEssentials();
    }));
  }


updateItemInEssentials() {
    this.essentialItems = [
      {
        descriptionName: 'Code Version',
        copyTextValue: this.clusterUpgradeProgress?.raw?.CodeVersion,
        displayText: this.clusterUpgradeProgress?.raw?.CodeVersion,
      },
      {
        descriptionName: 'Fault Domains',
        displayText: this.nodes.faultDomains.length.toString(),
        copyTextValue: this.nodes.faultDomains.length.toString()
      },
      {
        descriptionName: 'Upgrade Domains',
        displayText: this.nodes.upgradeDomains.length.toString(),
        copyTextValue: this.nodes.upgradeDomains.length.toString()
      },
      {
        descriptionName: 'Healthy Seed Nodes',
        displayText: this.nodes.healthySeedNodes,
        copyTextValue: this.nodes.healthySeedNodes
      }
    ];
  }


({
  value: valueProp,
  ...rest
}: any) => {
  const [value, setValue] = useState(valueProp);

  return (
    <lib.RcThemeProvider>
      <lib.RcTextField
        {...rest}
        value={value}
        onChange={(e)


() => {
  it("cities list", () => {
    const cities = listCities;
    expect(cities.length).toBe(1001);
  });

  it("suggest cities by prefix", () => {
    const cities = suggest("d");
    expect(cities.length).toBe(39);
  });

  it("suggest cities by empty prefix returns empty", () => {
    const cities = suggest("");
    expect(cities.length).toBe(0);
  });

}


() => {
    const cities = listCities;
    expect(cities.length).toBe(1001);
  }


() => {
    const cities = suggest("d");
    expect(cities.length).toBe(39);
  }


() => {
    const cities = suggest("");
    expect(cities.length).toBe(0);
  }


export function defaults(): State {
    return {
      mediaQuery: {
        orientation: undefined,
        isHandset: undefined,
      },
      selected: { theme: 'normal' },
    };
  }


export interface State {
    mediaQuery: MediaQuery;
    selected: Selected;
  }


export interface MediaQuery {
    orientation: PageOrientation;
    isHandset: boolean;
  }


export interface Selected {
    theme: Theme;
  }


export type Theme = 'normal' | 'dark';


export type PageOrientation = 'landscape' | 'portrait';


function changeParentHandler(updatedValues) {
    if (!onChange || typeof onChange !== 'function') {
      return;
    }

    onChange(removeEmptyJsonValues(updatedValues));
  }