text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.security.wycheproof;

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

import com.google.security.wycheproof.WycheproofRunner.NoPresubmitTest;
import com.google.security.wycheproof.WycheproofRunner.ProviderType;
import com.google.security.wycheproof.WycheproofRunner.SlowTest;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.KeyAgreement;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Testing Diffie-Hellman key agreement.
 *
 *
Subgroup confinment attacks: The papers by van Oorshot and Wiener rsp. Lim and Lee show that
 * Diffie-Hellman keys can be found much faster if the short exponents are used and if the
 * multiplicative group modulo p contains small subgroups. In particular an attacker can try to send
 * a public key that is an element of a small subgroup. If the receiver does not check for such
 * elements then may be possible to find the private key modulo the order of the small subgroup.
 * Several countermeasures against such attacks have been proposed: For example IKE uses fields of
 * order p where p is a safe prime (i.e. q=(p-1)/2), hence the only elements of small order are 1
 * and p-1.
 *
 *
NIST SP 800-56A rev. 2, Section 5.5.1.1 only requires that the size of the subgroup generated
 * by the generator g is big enough to prevent the baby-step giant-step algorithm. I.e. for 80-bit
 * security p must be at least 1024 bits long and the prime q must be at least 160 bits long. A 2048
 * bit prime p and a 224 bit prime q are sufficient for 112 bit security. To avoid subgroup
 * confinment attacks NIST requires that public keys are validated, i.e. by checking that a public
 * key y satisfies the conditions 2 <= y <= p-2 and y^q mod p == 1 (Section 5.6.2.3.1). Further,
 * after generating the shared secret z = y_a ^ x_b mod p each party should check that z != 1. RFC
 * 2785 contains similar recommendations.
 *
 *
The public key validation described by NIST requires that the order q of the generator g is
 * known to the verifier. Unfortunately, the order q is missing in PKCS #3. PKCS #3 describes the
 * Diffie-Hellman parameters only by the values p, g and optionally the key size in bits.
 *
 *
The class DHParameterSpec that defines the Diffie-Hellman parameters in JCE contains the same
 * values as PKCS#3. In particular, it does not contain the order of the subgroup q. Moreover, the
 * SUN provider uses the minimal sizes specified by NIST for q. Essentially the provider reuses the
 * parameters for DSA.
 *
 *
Therefore, there is no guarantee that an implementation of Diffie-Hellman is secure against
 * subgroup confinement attacks. Without a key validation it is insecure to use the key-pair
 * generation from NIST SP 800-56A Section 5.6.1.1 (The key-pair generation there only requires that
 * static and ephemeral private keys are randomly chosen in the range 1..q-1).
 *
 *
To avoid big disasters the tests below require that key sizes are not minimal. I.e., currently
 * the tests require at least 512 bit keys for 1024 bit fields. We use this lower limit because that
 * is what the SUN provider is currently doing. TODO(bleichen): Find a reference supporting or
 * disproving that decision.
 *
 *
References: P. C. van Oorschot, M. J. Wiener, "On Diffie-Hellman key agreement with short
 * exponents", Eurocrypt 96, pp 332–343.
 *
 *
C.H. Lim and P.J. Lee, "A key recovery attack on discrete log-based schemes using a prime
 * order subgroup", CRYPTO' 98, pp 249–263.
 *
 *
NIST SP 800-56A, revision 2, May 2013
 * http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
 *
 *
PKCS #3, Diffie–Hellman Key Agreement
 * http://uk.emc.com/emc-plus/rsa-labs/standards-initiatives/pkcs-3-diffie-hellman-key-agreement-standar.htm
 *
 *
RFC 2785, "Methods for Avoiding 'Small-Subgroup' Attacks on the Diffie-Hellman Key Agreement
 * Method for S/MIME", March 2000
 * https://www.ietf.org/rfc/rfc2785.txt
 *
 *
D. Adrian et al. "Imperfect Forward Secrecy: How Diffie-Hellman Fails in Practice"
 * https://weakdh.org/imperfect-forward-secrecy-ccs15.pdf
 * A good analysis of various DH implementations. Some misconfigurations pointed out in the paper
 * are: p is composite, p-1 contains no large prime factor, q is used instead of the generator g.
 *
 *
Sources that might be used for additional tests:
 *
 *
CVE-2015-3193: The Montgomery squaring implementation in crypto/bn/asm/x86_64-mont5.pl in
 * OpenSSL 1.0.2 before 1.0.2e on the x86_64 platform, as used by the BN_mod_exp function,
 * mishandles carry propagation
 * https://blog.fuzzing-project.org/31-Fuzzing-Math-miscalculations-in-OpenSSLs-BN_mod_exp-CVE-2015-3193.html
 *
 *
CVE-2016-0739: libssh before 0.7.3 improperly truncates ephemeral secrets generated for the
 * (1) diffie-hellman-group1 and (2) diffie-hellman-group14 key exchange methods to 128 bits ...
 *
 *
CVE-2015-1787 The ssl3_get_client_key_exchange function in s3_srvr.c in OpenSSL 1.0.2 before
 * 1.0.2a, when client authentication and an ephemeral Diffie-Hellman ciphersuite are enabled,
 * allows remote attackers to cause a denial of service (daemon crash) via a ClientKeyExchange
 * message with a length of zero.
 *
 *
CVE-2015-0205 The ssl3_get_cert_verify function in s3_srvr.c in OpenSSL 1.0.0 before 1.0.0p
 * and 1.0.1 before 1.0.1k accepts client authentication with a Diffie-Hellman (DH) certificate
 * without requiring a CertificateVerify message, which allows remote attackers to obtain access
 * without knowledge of a private key via crafted TLS Handshake Protocol traffic to a server that
 * recognizes a Certification Authority with DH support.
 *
 *
CVE-2016-0701 The DH_check_pub_key function in crypto/dh/dh_check.c in OpenSSL 1.0.2 before
 * 1.0.2f does not ensure that prime numbers are appropriate for Diffie-Hellman (DH) key exchange,
 * which makes it easier for remote attackers to discover a private DH exponent by making multiple
 * handshakes with a peer that chose an inappropriate number, as demonstrated by a number in an
 * X9.42 file.
 *
 *
CVE-2006-1115 nCipher HSM before 2.22.6, when generating a Diffie-Hellman public/private key
 * pair without any specified DiscreteLogGroup parameters, chooses random parameters that could
 * allow an attacker to crack the private key in significantly less time than a brute force attack.
 *
 *
CVE-2015-1716 Schannel in Microsoft Windows Server 2003 SP2, Windows Vista SP2, Windows Server
 * 2008 SP2 and R2 SP1, Windows 7 SP1, Windows 8, Windows 8.1, Windows Server 2012 Gold and R2, and
 * Windows RT Gold and 8.1 does not properly restrict Diffie-Hellman Ephemeral (DHE) key lengths,
 * which makes it easier for remote attackers to defeat cryptographic protection mechanisms via
 * unspecified vectors, aka "Schannel Information Disclosure Vulnerability.
 *
 *
CVE-2015-2419: Random generation of the prime p allows Pohlig-Hellman and probably other
 * stuff.
 *
 *
J. Fried et al. "A kilobit hidden SNFS discrete logarithm computation".
 * http://eprint.iacr.org/2016/961.pdf
 * Some crypto libraries use fields that can be broken with the SNFS.
 *
 * @author bleichen@google.com (Daniel Bleichenbacher)
 */
@RunWith(JUnit4.class)
public class DhTest {
  public DHParameterSpec ike1536() {
    final BigInteger p =
        new BigInteger(
            "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74"
                + "020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437"
                + "4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed"
                + "ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05"
                + "98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb"
                + "9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff",
            16);
    final BigInteger g = new BigInteger("2");
    return new DHParameterSpec(p, g);
  }

  public DHParameterSpec ike2048() {
    final BigInteger p =
        new BigInteger(
            "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74"
                + "020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437"
                + "4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed"
                + "ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05"
                + "98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb"
                + "9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b"
                + "e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718"
                + "3995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff",
            16);
    final BigInteger g = new BigInteger("2");
    return new DHParameterSpec(p, g);
  }

  // The default parameters returned for 1024 bit DH keys from OpenJdk as defined in
  // openjdk7/releases/v6/trunk/jdk/src/share/classes/sun/security/provider/ParameterCache.java
  // I.e., these are the same parameters as used for DSA.
  public DHParameterSpec openJdk1024() {
    final BigInteger p =
        new BigInteger(
            "fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669"
                + "455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b7"
                + "6b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb"
                + "83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c7",
            16);
    final BigInteger unusedQ = new BigInteger("9760508f15230bccb292b982a2eb840bf0581cf5", 16);
    final BigInteger g =
        new BigInteger(
            "f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d078267"
                + "5159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e1"
                + "3c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243b"
                + "cca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a",
            16);
    return new DHParameterSpec(p, g);
  }

  /** Check that key agreement using DH works. */
  @SuppressWarnings("InsecureCryptoUsage")
  @Test
  public void testDh() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
    DHParameterSpec dhparams = ike2048();
    keyGen.initialize(dhparams);
    KeyPair keyPairA = keyGen.generateKeyPair();
    KeyPair keyPairB = keyGen.generateKeyPair();

    KeyAgreement kaA = KeyAgreement.getInstance("DH");
    KeyAgreement kaB = KeyAgreement.getInstance("DH");
    kaA.init(keyPairA.getPrivate());
    kaB.init(keyPairB.getPrivate());
    kaA.doPhase(keyPairB.getPublic(), true);
    kaB.doPhase(keyPairA.getPublic(), true);
    byte[] kAB = kaA.generateSecret();
    byte[] kBA = kaB.generateSecret();
    assertEquals(TestUtil.bytesToHex(kAB), TestUtil.bytesToHex(kBA));
  }

  /**
   * Returns the product of primes that can be found by a simple variant of Pollard-rho. The result
   * should contain all prime factors of n smaller than 10^8. This method is heuristic, since it
   * could in principle find large prime factors too. However, for a random 160-bit prime q the
   * probability of this should be less than 2^{-100}.
   */
  private BigInteger smoothDivisor(BigInteger n) {
    // By examination we verified that for every prime p < 10^8
    // the iteration x_n = x_{n-1}^2 + 1 mod p enters a cycle of size < 50000 after at
    // most 50000 steps.
    int pollardRhoSteps = 50000;
    BigInteger u = new BigInteger("2");
    for (int i = 0; i < pollardRhoSteps; i++) {
      u = u.multiply(u).add(BigInteger.ONE).mod(n);
    }
    BigInteger v = u;
    BigInteger prod = BigInteger.ONE;
    for (int i = 0; i < pollardRhoSteps; i++) {
      v = v.multiply(v).add(BigInteger.ONE).mod(n);
      // This implementation is only looking for the product of small primes.
      // Therefore, instead of continuously computing gcds of v-u and n, it is sufficient
      // and more efficient to compute the product of v-u for all v and compute the gcd
      // at the end.
      prod = prod.multiply(v.subtract(u).abs()).mod(n);
    }
    BigInteger result = BigInteger.ONE;
    while (true) {
      BigInteger f = n.gcd(prod);
      if (f.equals(BigInteger.ONE)) {
        return result;
      }
      result = result.multiply(f);
      n = n.divide(f);
    }
  }

  private void testKeyPair(KeyPair keyPair, int expectedKeySize) throws Exception {
    DHPrivateKey priv = (DHPrivateKey) keyPair.getPrivate();
    BigInteger p = priv.getParams().getP();
    BigInteger g = priv.getParams().getG();
    int keySize = p.bitLength();
    assertEquals("wrong key size", expectedKeySize, keySize);

    // Checks the key size of the private key.
    // NIST SP 800-56A requires that x is in the range (1, q-1).
    // Such a choice would require a full key validation. Since such a validation
    // requires the value q (which is not present in the DH parameters) larger keys
    // should be chosen to prevent attacks.
    int minPrivateKeyBits = keySize / 2;
    BigInteger x = priv.getX();
    assertTrue(x.bitLength() >= minPrivateKeyBits - 32);
    // TODO(bleichen): add tests for weak random number generators.

    // Verify the DH parameters.
    System.out.println("p=" + p.toString(16));
    System.out.println("g=" + g.toString(16));
    System.out.println("testKeyPairGenerator L=" + priv.getParams().getL());
    // Basic parameter checks
    assertTrue("Expecting g > 1", g.compareTo(BigInteger.ONE) > 0);
    assertTrue("Expecting g < p - 1", g.compareTo(p.subtract(BigInteger.ONE)) < 0);
    // Expecting p to be prime.
    // No high certainty is needed, since this is a unit test.
    assertTrue(p.isProbablePrime(4));
    // The order of g should be a large prime divisor q of p-1.
    // (see e.g. NIST SP 800-56A, section 5.5.1.1.)
    // If the order of g is composite then the Decision Diffie Hellman assumption is
    // not satisfied for the group generated by g. Moreover, attacks using Pohlig-Hellman
    // might be feasible.
    // A good way to achieve these requirements is to select a safe prime p (i.e. a prime
    // where q=(p-1)/2 is prime too. NIST SP 800-56A does not require (or even recommend)
    // safe primes and allows Diffie-Hellman parameters where q is significantly smaller.
    // Unfortunately, the key does not contain q and thus the conditions above  cannot be
    // tested easily.
    // We perform a partial test that performs a partial factorization of p-1 and then
    // test whether one of the small factors found by the partial factorization divides
    // the order of g.
    boolean isSafePrime = p.shiftRight(1).isProbablePrime(4);
    System.out.println("p is a safe prime:" + isSafePrime);
    BigInteger r; // p-1 divided by small prime factors.
    if (isSafePrime) {
      r = p.shiftRight(1);
    } else {
      BigInteger p1 = p.subtract(BigInteger.ONE);
      r = p1.divide(smoothDivisor(p1));
    }
    System.out.println("r=" + r.toString(16));
    assertEquals(
        "g likely does not generate a prime oder subgroup", BigInteger.ONE, g.modPow(r, p));

    // Checks that there are not too many short prime factors.
    // I.e., subgroup confinment attacks can find at least keySize - r.bitLength() bits of the key.
    // At least 160 unknown bits should remain.
    // Only very weak parameters are detected here, since the factorization above only finds small
    // prime factors.
    assertTrue(minPrivateKeyBits - (keySize - r.bitLength()) > 160);

    // DH parameters are sometime misconfigures and g and q are swapped.
    // A large g that divides p-1 is suspicious.
    if (g.bitLength() >= 160) {
      assertTrue(p.mod(g).compareTo(BigInteger.ONE) > 0);
    }
  }

  /**
   * Tests Diffie-Hellman key pair generation.
   *
   *
This is a slow test since some providers (e.g. BouncyCastle) generate new safe primes for
   * each new key.
   */
  @SuppressWarnings("InsecureCryptoUsage")
  @SlowTest(providers = {ProviderType.BOUNCY_CASTLE, ProviderType.SPONGY_CASTLE})
  @Test
  public void testKeyPairGenerator() throws Exception {
    int keySize = 1024;
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
    keyGen.initialize(keySize);
    KeyPair keyPair = keyGen.generateKeyPair();
    testKeyPair(keyPair, keySize);
  }

  /**
   * Tests the default Diffie-Hellman key pair generation.
   *
   *
This test uses NIST SP 800-57 part1, revision 4
   * http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r4.pdf . Table 2 on page
   * 53 recommends 2048 bits as the minimal key length for Diffie-Hellman for new keys that expire
   * before the year 2030.
   *
   *
Note that JCE documentation is outdated. According to
   * https://docs.oracle.com/javase/7/docs/api/java/security/KeyPairGenerator.html an implementation
   * of the Java platform is only required to support 1024 bit keys.
   */
  @NoPresubmitTest(
    providers = {ProviderType.OPENJDK, ProviderType.BOUNCY_CASTLE},
    bugs = {"b/33190860", "b/33190677"}
  )
  @SlowTest(providers = {ProviderType.BOUNCY_CASTLE, ProviderType.SPONGY_CASTLE})
  @Test
  public void testDefaultKeyPairGenerator() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
    KeyPair keyPair;
    try {
      keyPair = keyGen.generateKeyPair();
    } catch (Exception ex) {
      // When a provider decides not to implement a default key size then this is still better than
      // implementing a default that is out of date. Hence the test should not fail in this case.
      System.out.println("Cannot generate a DH key without initialize: " + ex.getMessage());
      return;
    }
    DHPrivateKey priv = (DHPrivateKey) keyPair.getPrivate();
    int keySize = priv.getParams().getP().bitLength();
    assertTrue("Default key size for DH is too small. Key size = " + keySize, keySize >= 2048);
    testKeyPair(keyPair, keySize);
  }

  /** This test tries a key agreement with keys using distinct parameters. */
  @SuppressWarnings("InsecureCryptoUsage")
  @Test
  public void testDHDistinctParameters() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
    keyGen.initialize(ike1536());
    KeyPair keyPairA = keyGen.generateKeyPair();

    keyGen.initialize(ike2048());
    KeyPair keyPairB = keyGen.generateKeyPair();

    KeyAgreement kaA = KeyAgreement.getInstance("DH");
    kaA.init(keyPairA.getPrivate());
    try {
      kaA.doPhase(keyPairB.getPublic(), true);
      byte[] kAB = kaA.generateSecret();
      fail("Generated secrets with mixed keys " + TestUtil.bytesToHex(kAB) + ", ");
    } catch (java.security.GeneralSecurityException ex) {
      // This is expected.
    }
  }

  /**
   * Tests whether a provider accepts invalid public keys that result in predictable shared secrets.
   * This test is based on RFC 2785, Section 4 and NIST SP 800-56A, If an attacker can modify both
   * public keys in an ephemeral-ephemeral key agreement scheme then it may be possible to coerce
   * both parties into computing the same predictable shared key.
   *
   *
Note: the test is quite whimsical. If the prime p is not a safe prime then the provider
   * itself cannot prevent all small-subgroup attacks because of the missing parameter q in the
   * Diffie-Hellman parameters. Implementations must add additional countermeasures such as the ones
   * proposed in RFC 2785.
   *
   *
CVE-2016-1000346: BouncyCastle before v.1.56 did not validate the other parties public key.
   */
  @SuppressWarnings("InsecureCryptoUsage")
  @Test
  public void testSubgroupConfinement() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
    DHParameterSpec params = ike2048();
    BigInteger p = params.getP();
    BigInteger g = params.getG();
    keyGen.initialize(params);
    PrivateKey priv = keyGen.generateKeyPair().getPrivate();
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    BigInteger[] weakPublicKeys = {
      BigInteger.ZERO,
      BigInteger.ONE,
      p.subtract(BigInteger.ONE),
      p,
      p.add(BigInteger.ONE),
      BigInteger.ONE.negate()
    };
    for (BigInteger weakKey : weakPublicKeys) {
      ka.init(priv);
      try {
        KeyFactory kf = KeyFactory.getInstance("DH");
        DHPublicKeySpec weakSpec = new DHPublicKeySpec(weakKey, p, g);
        PublicKey pub = kf.generatePublic(weakSpec);
        ka.doPhase(pub, true);
        byte[] kAB = ka.generateSecret();
        fail(
            "Generated secrets with weak public key:"
                + weakKey.toString()
                + " secret:"
                + TestUtil.bytesToHex(kAB));
      } catch (GeneralSecurityException ex) {
        // this is expected
      }
    }
  }
}


text:
class CreateAccounts < ActiveRecord::Migration
  def change
    create_table :accounts do |t|
      t.integer :user_id
      t.string :login, :null => false, :limit => 40
      t.string :name, :default => ""

      t.timestamps
    end
    add_index :accounts, :user_id
    add_index :accounts, :login, :unique => true
  end
end

redpajama_set_name: RedPajamaGithub


text:
 **Dimensional Lock**

**School** abjuration; **Level** cleric 8, sorcerer/wizard 8

**Casting Time** 1 standard action

**Components** V, S

**Range** medium (100 ft. + 10 ft./level)

**Area** 20-ft.-radius emanation centered on a point in space

**Duration** 1 day/level

**Saving Throw** none; **[Spell Resistance](../glossary#_spell-resistance)** yes

You create a shimmering emerald barrier that completely blocks extradimensional travel. Forms of movement barred include _ [astral projection](astralProjection#_astral-projection), blink, [dimension door](dimensionDoor#_dimension-door), [ethereal jaunt](etherealJaunt#_ethereal-jaunt), [etherealness](etherealness#_etherealness), [gate](gate#_gate), [maze](maze#_maze), [plane shift](planeShift#_plane-shift), [shadow walk](shadowWalk#_shadow-walk), [teleport](teleport#_teleport), _and similar spell-like abilities. Once _dimensional lock _is in place, extradimensional travel into or out of the area is not possible.

A _dimensional lock _does not interfere with the movement of creatures already in ethereal or astral form when the spell is cast, nor does it block extradimensional perception or attack forms. Also, the spell does not prevent summoned creatures from disappearing at the end of a summoning spell.


text:
namespace Forum.App.Controllers
{
    using Forum.App.Controllers.Contracts;
    using Forum.App.UserInterface;
    using Forum.App.UserInterface.Contracts;

    public class MainController : IController, IUserRestrictedController
    {
        private const int COMMAND_COUNT = 3;

        public MainController()
        {
            this.LoggedInUser = false;
        }

        public bool LoggedInUser { get; private set; }

        public IView GetView(string userName)
        {
            return new MainView(userName);
        }

        public MenuState ExecuteCommand(int index)
        {
            if (LoggedInUser)
            {
                switch ((UserCommand)index)
                {
                    case UserCommand.Categories:
                        return MenuState.Categories;
                    case UserCommand.AddPost:
                        return MenuState.AddPost;
                    case UserCommand.LogOut:
                        return MenuState.LoggedOut;
                }
            }

            switch ((GuestCommand)index)
            {
                case GuestCommand.Categories:
                    return MenuState.Categories;
                case GuestCommand.Login:
                    return MenuState.Login;
                case GuestCommand.SignUp:
                    return MenuState.Signup;
            }

            throw new InvalidCommandException();
        }

        public void UserLogIn()
        {
            this.LoggedInUser = true;
        }

        public void UserLogOut()
        {
            this.LoggedInUser = false;
        }

        private enum GuestCommand
        {
            Categories, Login, SignUp
        }

        private enum UserCommand
        {
            Categories, AddPost, LogOut
        }
    }
}


text:
class CreatePilotPlanes < ActiveRecord::Migration
  def change
    create_table :pilot_planes do |t|
      t.integer :pilot_id
      t.integer :plane_id
      t.timestamps null: false
    end
  end
end


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Features.RQName;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.LanguageServices
{
    ///
    /// Helpers related to <see cref="RQName"/>s. The resulting strings are suitable to pass as the pszRQName
    /// arguments to methods in <see cref="IVsRefactorNotify"/> and <see cref="IVsSymbolicNavigationNotify"/>.
    ///
    public static class RQName
    {
        ///
        /// Returns an RQName for the given symbol, or nullif the symbol cannot be represented by an RQName.
        ///
        /// <param name="symbol">The symbol to build an RQName for.</param>
        /// <returns>A string suitable to pass as the pszRQName argument to methods in <see cref="IVsRefactorNotify"/>
        /// and <see cref="IVsSymbolicNavigationNotify"/>.</returns>
        public static string From(ISymbol symbol)
            => RQNameInternal.From(symbol);
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="description" content="">
	<meta name="author" content="">

	<title>Rival - Multipurpose Template</title>

	<link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/simpletextrotator.css" rel="stylesheet">
	<link href="assets/css/font-awesome.min.css" rel="stylesheet">
	<link href="assets/css/et-line-font.css" rel="stylesheet">
	<link href="assets/css/magnific-popup.css" rel="stylesheet">
	<link href="assets/css/flexslider.css" rel="stylesheet">
	<link href="assets/css/owl.carousel.css" rel="stylesheet">
	<link href="assets/css/animate.css" rel="stylesheet">
	<link href="assets/css/style.css" rel="stylesheet">

Loading...

				<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#custom-collapse">
					Toggle navigation

				</button>
				Rival

						Home

								One Page

Image Parallax 1

Image Parallax 2

Slider Parallax 1

Slider Parallax 2

Text rotator 1

Text rotator 2

Gradient Overlay 1

Gradient Overlay 2

Video background 1

Video background 2

								Multi Page

Image Parallax 1

Image Parallax 2

Slider Parallax 1

Slider Parallax 2

Text rotator 1

Text rotator 2

Gradient Overlay 1

Gradient Overlay 2

Video background 1

Video background 2

								Restaurant

Image Parallax

Slider Parallax

Video background

Text rotator

						Pages

								About

About 1

About 2

About 3

About 4

About 5

								Services

Services 1

Services 2

								Pricing

Pricing 1

Pricing 2

								Gallery

2 Columns

3 Columns

4 Columns

6 Columns

								Contact

Contact 1

Contact 2

Contact 3

								Restaurant menu

Menu 2 Columns

Menu 3 Columns

FAQ

Page 404

						Portfolio

								Boxed

2 Columns

3 Columns

4 Columns

5 Columns

Hover Black

Hover Gradient

								Boxed - Gutter

2 Columns

3 Columns

4 Columns

5 Columns

Hover Black

Hover Gradient

								Boxed - Masonry

2 Columns

3 Columns

4 Columns

5 Columns

Hover Black

Hover Gradient

								Wide

2 Columns

3 Columns

4 Columns

5 Columns

Hover Black

Hover Gradient

								Wide - Gutter

2 Columns

3 Columns

4 Columns

5 Columns

Hover Black

Hover Gradient

								Wide - Masonry

2 Columns

3 Columns

4 Columns

5 Columns

Hover Black

Hover Gradient

								Single

Single 1

Single 2

Single 3

Single 4

Single 5

Single 6

Single 7

Single 8

Single 9

						Blog

								Standart

Sidebar Left

Sidebar Right

								Grid

2 Columns

3 Columns

4 Columns

								Masonry

2 Columns

3 Columns

4 Columns

								Single

Sidebar Left

Sidebar Right

						Features

 Alerts and Wells

 Buttons

 Collapses & Tabs

 Contents Box

 Forms

 Icons

 Progress Bars

 Typography

						Search

									<form role="form">
										<input type="text" class="form-control" placeholder="Search...">
										<button class="search-btn" type="submit"></button>
									</form>

						English

English

France

Germany

Buttons

Rival buttons

							<button type="submit" class="btn btn-g btn-round">Submit</button>
							<button type="submit" class="btn btn-d btn-round">Submit</button>
							<button type="submit" class="btn btn-b btn-round">Submit</button>
							<button type="submit" class="btn btn-border-d btn-round">Submit</button>

							<button type="submit" class="btn btn-g btn-circle">Submit</button>
							<button type="submit" class="btn btn-d btn-circle">Submit</button>
							<button type="submit" class="btn btn-b btn-circle">Submit</button>
							<button type="submit" class="btn btn-border-d btn-circle">Submit</button>

Rival buttons on dark

								<button type="submit" class="btn btn-w btn-round">Submit</button>
								<button type="submit" class="btn btn-border-w btn-round">Submit</button>
								<button type="submit" class="btn btn-w btn-circle">Submit</button>
								<button type="submit" class="btn btn-border-w btn-circle">Submit</button>

Bootstrap buttons

							<button type="button" class="btn btn-default btn-round">Submit</button>
							<button type="button" class="btn btn-primary btn-round">Submit</button>
							<button type="button" class="btn btn-success btn-round">Submit</button>
							<button type="button" class="btn btn-info btn-round">Submit</button>
							<button type="button" class="btn btn-warning btn-round">Submit</button>
							<button type="button" class="btn btn-danger btn-round">Submit</button>

							<button type="button" class="btn btn-default btn-circle">Submit</button>
							<button type="button" class="btn btn-primary btn-circle">Submit</button>
							<button type="button" class="btn btn-success btn-circle">Submit</button>
							<button type="button" class="btn btn-info btn-circle">Submit</button>
							<button type="button" class="btn btn-warning btn-circle">Submit</button>
							<button type="button" class="btn btn-danger btn-circle">Submit</button>

Buttons size

<button type="submit" class="btn btn-g btn-round btn-lg">Submit</button>

<button type="submit" class="btn btn-g btn-round">Submit</button>

<button type="submit" class="btn btn-g btn-round btn-sm">Submit</button>

<button type="submit" class="btn btn-g btn-round btn-xs">Submit</button>

<button type="submit" class="btn btn-d btn-circle btn-lg">Submit</button>

<button type="submit" class="btn btn-d btn-circle">Submit</button>

<button type="submit" class="btn btn-d btn-circle btn-sm">Submit</button>

<button type="submit" class="btn btn-d btn-circle btn-xs">Submit</button>

<button type="submit" class="btn btn-success btn-round btn-lg">Submit</button>

<button type="submit" class="btn btn-success btn-round">Submit</button>

<button type="submit" class="btn btn-success btn-round btn-sm">Submit</button>

<button type="submit" class="btn btn-success btn-round btn-xs">Submit</button>

Block buttons

<button type="submit" class="btn btn-g btn-round btn-block">Submit</button>

<button type="submit" class="btn btn-d btn-round btn-block">Submit</button>

<button type="submit" class="btn btn-border-d btn-round btn-block">Submit</button>

<button type="submit" class="btn btn-g btn-circle btn-block">Submit</button>

<button type="submit" class="btn btn-d btn-circle btn-block">Submit</button>

<button type="submit" class="btn btn-border-d btn-circle btn-block">Submit</button>

<button type="button" class="btn btn-primary btn-round btn-block">Submit</button>

<button type="button" class="btn btn-info btn-round btn-block">Submit</button>

<button type="button" class="btn btn-success btn-circle btn-block">Submit</button>

Buttons with icons

<button type="submit" class="btn btn-g btn-round"> Submit</button>

<button type="submit" class="btn btn-d btn-round"> Submit</button>

<button type="submit" class="btn btn-border-d btn-round"> Submit</button>

<button type="submit" class="btn btn-g btn-circle"> Submit</button>

<button type="submit" class="btn btn-d btn-circle"> Submit</button>

<button type="submit" class="btn btn-border-d btn-circle"> Submit</button>

<button type="button" class="btn btn-primary btn-round"> Submit</button>

<button type="button" class="btn btn-info btn-round"> Submit</button>

<button type="button" class="btn btn-success btn-circle"> Submit</button>

About Rival

The languages only differ in their grammar, their pronunciation and their most common words.

Phone: +1 234 567 89 10
Fax: +1 234 567 89 10

Email: somecompany@example.com

Recent Comments

Maria on Designer Desk Essentials

John on Realistic Business Card Mockup

Andy on Eco bag Mockup

Jack on Bottle Mockup

Mark on Our trip to the Alps

Categories

Photography - 7

Web Design - 3

Illustration - 12

Marketing - 1

WordPress - 16

Popular posts

											Designer Desk Essentials

											23 November

											Realistic Business Card Mockup

											15 November

© 2015 Rival, All Rights Reserved.


text:
package org.estatio.module.base.fixtures.security.perms.personas;

import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.fixturescripts.FixtureScript;

@Programmatic
public class EstatioRolesAndPermissions extends FixtureScript {

    @Override
    protected void execute(ExecutionContext executionContext) {
        executionContext.executeChild(this, new EstatioAdminRoleAndPermissions());
        executionContext.executeChild(this, new EstatioUserRoleAndPermissions());
        executionContext.executeChild(this, new EstatioSuperuserRoleAndPermissions());
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-2dp" android:bottom="-2dp" android:left="-2dp">
        <shape android:shape="rectangle">
           <solid android:color="@android:color/transparent" />
            <stroke android:width="1dp" android:color="@color/right_separator_color_bl" />
        </shape>
    </item>
</layer-list>


text:
<?php

declare(strict_types=1);

/**
 * This file is part of Narrowspark Framework.
 *
 * (c) Daniel Bannert <d.bannert@anolilab.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Viserio\Component\Console\Command;

use Closure;
use ReflectionException;
use ReflectionFunction;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ClosureCommand extends AbstractCommand
{
    /**
     * Closure based command.
     *
     * @var Closure
     */
    protected $callback;

    /**
     * Create a new command instance.
     *
     * @param string  $signature
     * @param Closure $callback
     *
     * @throws \Symfony\Component\Console\Exception\LogicException
     */
    public function __construct(string $signature, Closure $callback)
    {
        $this->callback = $callback;
        $this->signature = $signature;

        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @param \Symfony\Component\Console\Input\InputInterface   $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     *
     * @throws ReflectionException
     * @throws \Invoker\Exception\InvocationException
     * @throws \Invoker\Exception\NotEnoughParametersException
     * @throws \Invoker\Exception\NotCallableException
     *
     * @return null|int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $inputs = \array_merge($input->getArguments(), $input->getOptions());
        $parameters = [];

        foreach ((new ReflectionFunction($this->callback))->getParameters() as $parameter) {
            if (isset($inputs[$parameter->name])) {
                $parameters[$parameter->name] = $inputs[$parameter->name];
            }
        }

        return (int) $this->invoker->call(
            $this->callback->bindTo($this, $this),
            $parameters
        );
    }
}


text:
/**
 * <!-- Package description. -->
 * Demonstrates data ignite cache usage.
 */
package org.apache.ignite.examples.java8.datagrid;


text:
var nma = require("nma");
var apiKey = "apiKeyHere";

module.exports = function(ICM) {
  ICM.events.on("alarmStatusChanged", function(alarmStatus) {
    if (alarmStatus == 1 || alarmStatus == 2) {
      nma(
        apiKey,
        "alarm",
        alarmStatus == 1 ? "*** Security Alarm ***" : "*** Fire Alarm ***",
        ICM.getAlarmStatusDetail(false),
        2,
        "http://mydomain.com"
      );

      console.log("nma notification sent.");
    }
  });
};


text:
- [Near-field communication in Mbed OS](#near-field-communication-in-mbed-os)
    - [Table of contents](#table-of-contents)
    - [Revision history](#revision-history)
- [Introduction](#introduction)
    - [Overview and background](#overview-and-background)
    - [Use cases](#use-cases)
        - [Commissioning](#commissioning)
            - [Identification](#identification)
            - [Transport](#transport)
        - [BLE pairing](#ble-pairing)
- [System architecture and high-level design](#system-architecture-and-high-level-design)
    - [Compliance with NFC forum specifications](#compliance-with-nfc-forum-specifications)
    - [User-facing API](#user-facing-api)
    - [Phase 1: MicroNFC stack integration](#phase-1-micronfc-stack-integration)
    - [Phase 2: NFC host/controller split, NCI and NFC HAL API](#phase-2-nfc-hostcontroller-split-nci-and-nfc-hal-api)
- [Detailed design](#detailed-design)
    - [User-facing APIs](#user-facing-apis)
        - [NFC controller](#nfc-controller)
        - [Endpoints](#endpoints)
            - [NFC remote endpoint](#nfc-remote-endpoint)
            - [NFC NDEF capable](#nfc-ndef-capable)
            - [NFC remote initiator](#nfc-remote-initiator)
            - [NFC target](#nfc-target)
            - [NFC EEPROM](#nfc-eeprom)
            - [NFC remote target](#nfc-remote-target)
    - [NDEF API](#ndef-api)
        - [Common objects](#common-objects)
        - [Parsing](#parsing)
            - [ndef::MessageParser](#ndefmessageparser)
                - [ndef::MessageParser::Delegate](#ndefmessageparserdelegate)
            - [NDEF record parsing](#ndef-record-parsing)
                - [ndef::RecordParser](#ndefrecordparser)
                - [ndef::RecordParserChain](#ndefrecordparserchain)
                - [ndef::GenericRecordParser<ParserImplementation, ParsingResult>](#ndefgenericrecordparserparserimplementation-parsingresult)
                    - [ndef::GenericRecordParser<ParserImplementation, ParsingResult>::Delegate](#ndefgenericrecordparserparserimplementation-parsingresultdelegate)
            - [Common parsers](#common-parsers)
            - [Simple parser](#simple-parser)
                - [Delegate](#delegate)
        - [Serialization](#serialization)
    - [HAL APIs](#hal-apis)
        - [NFC EEPROM API](#nfc-eeprom-api)
        - [NCI driver APIs](#nci-driver-apis)
- [Testing strategy](#testing-strategy)
    - [NFC forum compliance](#nfc-forum-compliance)
    - [Interoperability](#interoperability)
    - [HAL testing](#hal-testing)
- [Dependencies](#dependencies)

## Revision history

| Revision 	| Date           	| Authors                                                	| Mbed OS version 	| Comments         	|
|----------	|----------------	|--------------------------------------------------------	|-----------------	|------------------	|
| 1.0      	| 24 August 2018 	| Donatien Garnier ([@donatieng](https://github.com/donatieng/)); Vincent Coubard ([@pan-](https://github.com/pan-/)) 	| 5.10+           	| Initial revision 	|

#   Introduction

##  Overview and background

NFC offers a straightforward and secure way of commissioning IoT devices in the field, and we are seeing increasing demand for this from prospective customers. We have a plan to introduce NFC into Mbed OS. This is the first phase to add a reference implementation of card emulation mode.

NFC offers three modes:

1. NFC card emulation.
2. NFC reader/writer.
3. NFC peer to peer.

To support new use cases, such as commissioning, BLE pairing and identification and authentication of NFC-enabled IoT endpoints, Mbed OS should support the card emulation mode.

However, the architecture should be future-proofed and should also be extendable to support other NFC modes in the future.

## Use cases

### Commissioning

NFC is a medium that can support commissioning requirements.

#### Identification

You can use an NDEF message to carry a device's unique identifier. This eases identification before handing over to another transport medium, such as BLE.

#### Transport

If the NFC controller can emulate a smartcard, no handover is necessary, and the full commissioning flow can happen over NFC.

### BLE pairing

You can use a specifically crafted NDEF message to facilitate out-of-band pairing with man-in-the-middle protection as specified in the [Bluetooth® Secure Simple Pairing Using NFC](https://members.nfc-forum.org/apps/group_public/download.php/18688/NFCForum-AD-BTSSP_1_1.pdf) document.

# System architecture and high-level design

##  Compliance with NFC forum specifications

The NFC Forum is one the bodies producing NFC standards. Most smartphones supporting NFC today are compliant with the NFC Forum's specifications. In that consideration, the NFC component in Mbed OS should map with the relevant standards from the NFC Forum, and NFC Forum terminology should be used where possible.

## User-facing API

The NFC API exposed to the user should provide high-level, object-oriented C++ APIs for the following:

- Starting/Stopping a discovery loop.
- Listing wired targets (NFC EEPROMs).
- Exchanging NDEF messages with an initiator or a wired target.
- Emulate ISO7816-4 applications if supported.

##  Phase 1: MicroNFC stack integration

The first step toward adding NFC to Mbed OS is the integration of the MicroNFC stack, which has drivers for the PN512 and derivatives.

Architecture:

![phase_1_architecture]

## Phase 2: NFC host/controller split, NCI and NFC HAL API

At the moment, the MicroNFC stack is split into two components:

- Applications protocols and upper stack.
- Transceiver-specific polling loop and drivers.

To more closely match with the NFC Forum standard and add a well-defined way for Partners to add support for their transceivers, we will amend that split to be compliant with the NFC Forum's NFC Communication Interface (NCI) protocol.

The generic part of the controller stack will be clearly separated, so Partners can use it if they wish (approach 1).

For NFC controllers natively supporting the NCI protocol, Partners would only have to write a transport driver (approach 2).

![phase_2_architecture]

Examples of NCI-compliant controllers:

- ST ST21NFC.
- NXP PN7120 and PN7150.

Examples of transceivers that are *not* NCI-compliant:

- NXP PN512.
- NXP PN5180.
- AMS AS395x series.

# Detailed design

## User-facing APIs

We designed the user-facing APIs with the following principles:

- Abstracting the underlying complexities of NFC from the user.
- Offering a high-level C++ object-oriented API to the user.
- Ensuring compliance with the NFC Forum's standards and terminology.
- Ensuring consistency with the Mbed OS codebase.

Class diagram:

###  NFC controller

![nfc_controller_diagram]

The `NFCController` class is the entrypoint into NFC for the user.

When NCI integration is complete (phase 2), this class will be able to drive a `NCIDriver` instance. For now, the one controller we support is the PN512, which implements the `NFCControllerDriver` class. This class is specific to the current MicroNFC release.

```cpp
NFCController(NFCControllerDriver *driver, events::EventQueue *queue, const Span<uint8_t> &ndef_buffer);
```

The user instantiates the `NFCController` class using a driver, an event queue used for asynchronous operations and a scratch buffer used for NDEF processing.

It offers the following methods:

```cpp
void set_delegate(Delegate *delegate);
```

Set the instance's delegate.

```cpp
struct nfc_rf_protocols_bitmask_t
{
    uint8_t initiator_t1t : 1;
    uint8_t initiator_t2t : 1;
    uint8_t initiator_t3t : 1;
    uint8_t initiator_iso_dep : 1;
    uint8_t initiator_nfc_dep : 1;
    uint8_t initiator_t5t : 1;

    uint8_t target_t1t : 1;
    uint8_t target_t2t : 1;
    uint8_t target_t3t : 1;
    uint8_t target_iso_dep : 1;
    uint8_t target_nfc_dep : 1;
    uint8_t target_t5t : 1;
};

nfc_rf_protocols_bitmask_t get_supported_rf_protocols() const;
```

Retrieve the list of supported RF protocols. These are mapped against NFC Forum-defined protocols.

- T1T is based on ISO/IEC 14443A-3 and commonly known as Topaz (Innovision).
- T2T is based on ISO/IEC 14443A-3 and commonly known as Mifare Ultralight/NTAG (NXP).
- T3T is based on JIS X6319-4, also known as Felica (Sony).
- ISO-DEP is based on ISO/IEC 14443-4 and is the common interface for contactless smartcards. The underlying radio protocol can either be ISO/IEC 14443A or ISO/IEC 14443B.
- NFC-DEP is based on ISO/IEC 18092/FIXME and is the basis for NFC peer-to-peer communication.
- T5T is also known as ISO/IEC 15963.

```cpp
nfc_err_t initialize();
```

Initialize the NFC controller.

```cpp
nfc_err_t configure_rf_protocols(nfc_rf_protocols_bitmask_t rf_protocols);
```

Configure which protocols should be enabled during the discovery process.

```cpp
nfc_err_t start_discovery();
```

Start the discovery process.

```cpp
nfc_err_t cancel_discovery();
```

Cancel the discovery process (if running).

**Delegate**

A `NFCController` instance needs to be configured with a delegate to receive events.

```cpp
enum nfc_discovery_terminated_reason_t {
    nfc_discovery_terminated_completed = 0
    nfc_discovery_terminated_canceled,
    nfc_discovery_terminated_rf_error
};

void on_discovery_terminated(nfc_discovery_terminated_reason_t reason);
```

Let the user know when a discovery loop has been terminated (either because endpoints have been found, the user canceled it or an error occurred).

```cpp
void on_nfc_initiator_discovered(const mbed::SharedPtr<NFCRemoteInitiator> &nfc_initiator);

void on_nfc_target_discovered(const mbed::SharedPtr<NFCRemoteTarget> &nfc_target);
```

These methods called when a remote initiator (the local controller is acting as a target) or a remote target (the local controller is acting as an initiator) is detected.

These methods use shared pointers, so the user does not have to maintain the lifetime of these objects. The `NFCController` instance releases its reference when the endpoint is lost (see below).

### Endpoints

![nfc_endpoints_diagram]

#### NFC remote endpoint

A remote endpoint is a generic NFC-enabled device with which the controller is communicating over the air interface:

```cpp
nfc_err_t connect();
```

Establish a connection with the remote endpoint.

```cpp
nfc_err_t disconnect();
```

Drop the connection with the remote endpoint.

```cpp
bool is_connected() const;
```

Set to true when the remote endpoint activates the connection and selects it.

```cpp
bool is_disconnected() const;
```

Set to true when the remote endpoint is lost and the `NFCController` instance releases its reference to the shared pointer.

```cpp
nfc_rf_protocols_bitmask_t rf_protocols() const;
```

List the RF protocols that have been activated to communicate with that endpoint.

**Delegate**

```cpp
virtual void on_connected();
```

This is called when a connection to this endpoint is succesfully established.

```cpp
virtual void on_disconnected();
```

This is called when this endpoint is lost and the controller instance is about to release the reference to the shared pointer.

#### NFC NDEF capable

This class is the ancestor class for all endpoints which have the capability of handling NDEF data.

User-facing API:

```cpp
NFCNDEFCapable(const Span<uint8_t> &buffer);
```

The class is constructed using a scratch buffer which is used to encode and/or decode NDEF messages.

```cpp
bool is_ndef_supported() const;
```

API used by descendant classes:

```cpp
void parse_ndef_message(const ac_buffer_t &buffer);
void build_ndef_message(ac_buffer_builder_t &buffer_builder);
ndef_msg_t *ndef_message();
```

API implemented by descendant classes:
```cpp
virtual NFCNDEFCapable::Delegate *ndef_capable_delegate();
```

**Delegate**

The instance receives requests to encode and decode NDEF messages, and the user can choose how to handle them using the relevant builders and parsers.

```cpp
void parse_ndef_message(const Span<const uint8_t> &buffer);
```

The user receives the encoded NDEF message for processing.

```cpp
size_t build_ndef_message(const Span<uint8_t> &buffer);
```

The user can encode a NDEF message in the buffer provided and return its size (or 0).

#### NFC remote initiator

This class derives from the base `NFCRemoteEndpoint` and `NFCNDEFCapable` classes.

```cpp
enum nfc_tag_type_t {
    nfc_tag_type_1,
    nfc_tag_type_2,
    nfc_tag_type_3,
    nfc_tag_type_4a,
    nfc_tag_type_4b,
    nfc_tag_type_5
};
```

```cpp
nfc_tag_type_t nfc_tag_type();
```

Additionally, the user can recover the type of NFC tag (1 to 5) being emulated. Type 4 is implemented on either one of two technologies; therefore, this enum both includes type 4a and type 4b to identify the underlying technology.

*Note: ISO7816 is only used internally for the initial release*

```cpp
bool is_iso7816_supported();
void add_iso7816_application(nfc_tech_iso7816_app_t *application);
```

If the underlying technology supports it (ISO-DEP), the user can emulate a contactless smartcard and register ISO7816-4 applications using this API.

**Delegate**

The delegate derives from delegates of `NFCRemoteEndpoint` and `NFCNDEFCapable`.

#### NFC target

This is the base class for NFC targets that can be of two types:

- NFC EEPROMs (Dual-interface wired devices).
- Remote NFC targets (NFC devices over NFC RF interface).

Apart from the actual transport (wired or NFC), the use is similar, which explains why these methods are shared across these devices types.

This class derives from `NFCNDEFCapable`.

```cpp
void write_ndef_message();
void erase_ndef_message();
void read_ndef_message();
```

The user can trigger the appropriate NDEF parsing/building process using these methods if handlers are registered in the `NFCNDEFCapable` instance.

**Delegate**

```cpp
void on_ndef_message_erased(nfc_err_t result);
void on_ndef_message_written(nfc_err_t result);
void on_ndef_message_read(nfc_err_t result);
```

#### NFC EEPROM

The `NFCEEPROM` class derives from `NFCTarget` and shares the same API. The user must pass a pointer to a `NFCEEPROMDriver` instance (see below) in the constructor.

#### NFC remote target

*Note: This is out of scope for the initial release*

The `NFCRemoteTarget` class derives from `NFCTarget` and additionally from `NFCRemoteEndpoint`.

## NDEF API

The NDEF API is constructed with these requirements:

- Minimizing memory allocation and copies.
- NFC Forum compliance.
- Ease of use.
- Extensibility.

### Common objects

We will provide multiple helpers to make it easy to create and parse common record types:

- URI.
- Text.
- Smart poster.
- MIME data.

For instance, the `URI`'s class API is:

```cpp
void set_uri(uri_identifier_code_t id, const Span<const uint8_t> &uri_field)

uri_identifier_code_t get_id() const;
Span<const uint8_t> get_uri_field() const;
```

**Note:** These types can be replaced by user defined ones if parsing and serialization logic is provided.

### Parsing

#### ndef::MessageParser

![ndef_message_parser_diagram]

A `MessageParser`, which produces `Record` instances to its client, parses messages incoming from the peer. The parsing operation is event-driven: A message parser client registers a delegate inside the message parser. This delegate is notified whenever an interesting event happens during the parsing.

```cpp
void set_delegate(Delegate *delegate);
void parse(const Span<const uint8_t> &data_buffer);
```

It is important to note that the data_buffer in the entry of the parse function must contain the entire NDEF message.

##### ndef::MessageParser::Delegate

```cpp
virtual void on_parsing_started() { }
virtual void on_record_parsed(const Record &record) { }
virtual void on_parsing_terminated() { }
virtual void on_parsing_error(MessageParser::error_t error) { }
```

The delegate is notified by the parser when the parsing starts or ends, when an error is encountered or when an NDEF `Record` has been parsed.

To reduce memory consumption, `Record` instances generated by the parser are short lived. They are only valid during the callback invocation. If a client is interested in the content of a message parsed and wants to use it after the parsing callback, then it must make a copy of the record object.

#### NDEF record parsing

![ndef_record_parser_diagram]

NDEF records can contain any type of content. Therefore, parsing of records is specific to the application. To help the developer, an optional NDEF record parsing framework is included. It follows the _chain-of-responsibility_ design pattern that facilitates the integration of record parsers defined by client code.

##### ndef::RecordParser

It is the base building block of the record parsing frame working. It parses a record then returns true if the record has been parsed or false otherwise.

```cpp
virtual bool parse(const Record&);
```

##### ndef::RecordParserChain

It aggregates `RecordParser` instances and defers parsing to the instances it contains.

```cpp
bool parse(const Record &record);
void set_next_parser(RecordParser *parser);
```

##### ndef::GenericRecordParser<ParserImplementation, ParsingResult>

This is a partial implementation of the `RecordParser` interface. It exposes a delegate type that clients of this parser can implement and register. This delegate expects objects of the parsing result type.

```cpp
bool parse(const Record&)
void set_delegate(Delegate *delegate)
```

Implementation of this class must expose the following nonvirtual function:

```c++
bool do_parse(const Record &record, ParsingResult &parsing_result);
```

If the parsing is successful, then it should return true and fill `parsing_result`; otherwise, it should return false and leave `parsing_result` untouched.

**Note:** The Curiously recurring template pattern (CRTP) is used to implement the delegation mechanism in a type-safe fashion. This is not achievable with _regular_ polymorphism.

###### ndef::GenericRecordParser<ParserImplementation, ParsingResult>::Delegate

Clients of this class must implement this delegate. It receives the objects parsed.

```cpp
virtual void on_record_parsed(const ParsingResult &record, const RecordID *id);
```

**Note:** Usually, clients are client of an implementation of an ndef::GenericRecordParser<ParserImplementation, ParsingResult> . They can refer to the delegate as `ImplementationName::Delegate`.

#### Common parsers

![ndef_common_parsers_diagram]

Parsers for each common record type exist. They inherit from the `GenericRecordParser` to exposes a common delegate interface:

```cpp
virtual void on_record_parsed(const <ParsedType> &result, const ndef::RecordID *id)
```

#### Simple parser

The APIs provide a class named `SimpleMessageParser` that glues together a `MessageParser` and a chain `RecordParser` containing the parsers for the common types.

![ndef_simple_parser_diagram]

Clients of the class can register a delegate, parse a message or add a new `RecordParser` in the parsing chain.

```cpp
void set_delegate(Delegate *delegate);
void parse(const Span<const uint8_t> &data_buffer);
void add_record_parser(ndef::RecordParser *parser);
```

##### Delegate

Clients of this class must implement this delegate. It receives events from the parsing process:

```cpp
virtual void on_parsing_error(ndef::MessageParser::error_t error);
virtual void on_parsing_started();
virtual void on_text_parsed(const Text& text, const ndef::RecordID &id);
virtual void on_mime_parsed(const Mime& text, const ndef::RecordID &id);
virtual void on_uri_parsed(const URI& uri, const ndef::RecordID &id);
virtual void on_unknown_record_parsed(const ndef::Record &record);
virtual void on_parsing_terminated();
```

### Serialization

The class `MessageBuilder` is used to map a record into an NDEF message. It includes a data buffer that contains the _raw_ message. Client code uses the function `append_record` to append a new record into the message being built.

![ndef_message_builder_diagram]

For convenience, serialization functions for common types are provided in the common types we provide.

## HAL APIs

### NFC EEPROM API

To create the hardware-specific APIs to add support for a new NFC EEPROM, vendors need to derive from `NFCEEPROMDriver` and implement its virtual methods.

From the upper layer's point of view, the EEPROM is a byte array that can be read from or written to. Long operations (reads, writes, erasures) must happen asynchronously. Booleans indicate whether a particular operation was succesful.

Address 0 means the start of the NDEF buffer (not necessarily at address 0 in the EEPROM).

When a buffer is passed to the backend, the reference remains valid until the corresponding event is called.

The `set_size()` command is called to change the size of the NDEF buffer (within the limits set by `get_max_size()`). Inversely, that buffer size can be read using `get_size()`.

`start_session()` and `end_session()` are used before a series of memory operations to allow the driver to lock or unlock the RF interface during these operations to avoid having concurrent access to the memory.

```cpp
void reset();
size_t get_max_size();
void start_session(bool force = true);
void end_session();
void read_bytes(uint32_t address, size_t count);
void write_bytes(uint32_t address, const uint8_t *bytes, size_t count);
void read_size(size_t count);
void write_size();
void erase_bytes(uint32_t address, size_t size)
```

The following events must be called to signal completion of long operations:

```cpp
void on_session_started(bool success);
void on_session_ended(bool success);
void on_bytes_read(size_t count);
void on_bytes_written(size_t count);
void on_size_read(bool success, size_t size);
void on_size_written(bool success);
void on_bytes_erased(size_t count);
```

The implementation also has access to an event queue in case asynchronous operations need to be run:

```cpp
Delegate *delegate();
events::EventQueue *event_queue();
```

### NCI driver APIs

This API will be defined in phase 2.

# Testing strategy

## NFC forum compliance

A dongle driven by [PyNFC](https://nfcpy.readthedocs.io/en/latest/index.html) will be used to run Greentea-based tests to ensure that the implementation behaves correctly for a range of system tests.

Unit tests will cover all internal logic and NFC endpoints can be mocked/emulated where possible.

In the future, we could run NFC Forum test suites using approved testing equipment.

## Interoperability

Interoperability is important with a technology such as NFC. Therefore, our testing rig will include a selection of smartphones and NFC tags that can be connected using analog switches to the relevant NFC-enabled platform running Mbed OS.

![interop_test_rig]

## HAL testing

Greentea tests will be provided to Partners to ensure compliance with the NFC EEPROM backend API.

# Dependencies

- Event Queue

There are currently at least four event queues (Plaftorm, BLE, USB and IP) in Mbed OS, and NFC will also require an event queing mechanism. We should try to reuse one of these existing queues with the longterm goal of unifying these code bases.

[phase_1_architecture]: phase_1_architecture.png
[phase_2_architecture]: phase_2_architecture.png
[nfc_controller_diagram]: uml_diagram_controller.png
[nfc_endpoints_diagram]: uml_diagram_endpoints.png
[interop_test_rig]: interop_test_rig.png
[ndef_message_parser_diagram]: uml_diagram_ndef_message_parser.png
[ndef_record_parser_diagram]: uml_diagram_ndef_record_parser.png
[ndef_common_parsers_diagram]: uml_diagram_ndef_common_parsers.png
[ndef_simple_parser_diagram]: uml_diagram_ndef_simple_parser.png
[ndef_message_builder_diagram]: uml_diagram_ndef_message_builder_diagram.png


text:
@implementation YYBBFloatLimitTextField

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initUI];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self initUI];
}

- (void)initUI {
    self.delegate = self;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 长度限制
    // 输入类型限定
    ZZTextFieldInputLimit inputLimit = self.inputLimit;
    NSString *aString = nil;
    switch (inputLimit) {
        case ZZTextFieldInputUnLimit:
            break;
        case ZZTextFieldInputLimitNum:
            aString = kOnlyNum;
            break;
        case ZZTextFieldInputLimitLetter:
            aString = kOnlyLetter;
            break;
        case ZZTextFieldInputLimitLetterAndNum:
            aString = kOnlyLetterAndNum;
            break;
        default:
            break;
    }
    // 内容限制
    BOOL inputContentValid;
    if (inputLimit == ZZTextFieldInputUnLimit) {
        inputContentValid = YES;
    } else {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:aString] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        inputContentValid = [string isEqualToString:filtered];
    }

    // 长度限制
    BOOL lengthValid;
    if (self.maxLength <= 0) {
        lengthValid = YES;
    } else {
        NSUInteger oldLength = [textField.text length];
        NSUInteger replacementLength = [string length];
        NSUInteger rangeLength = range.length;
        NSUInteger newLength = oldLength - rangeLength + replacementLength;
        BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
        lengthValid = newLength <= self.maxLength || returnKey;
    }

    return inputContentValid && lengthValid;
}

@end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

#if UNITY_ANDROID && INCONTROL_OUYA && !UNITY_EDITOR
using tv.ouya.console.api;
#endif

namespace InControl
{
	public class OuyaEverywhereDeviceManager : InputDeviceManager
	{
		bool[] deviceConnected = new bool[] { false, false, false, false };

		public OuyaEverywhereDeviceManager()
		{
			for (int deviceIndex = 0; deviceIndex < 4; deviceIndex++)
			{
				devices.Add( new OuyaEverywhereDevice( deviceIndex ) );
			}
		}

		public override void Update( ulong updateTick, float deltaTime )
		{
			for (int deviceIndex = 0; deviceIndex < 4; deviceIndex++)
			{
				var device = devices[deviceIndex] as OuyaEverywhereDevice;

				if (device.IsConnected != deviceConnected[deviceIndex])
				{
					if (device.IsConnected)
					{
						device.BeforeAttach();
						InputManager.AttachDevice( device );
					}
					else
					{
						InputManager.DetachDevice( device );
					}

					deviceConnected[deviceIndex] = device.IsConnected;
				}
			}
		}

		public static void Enable()
		{
			#if UNITY_ANDROID && INCONTROL_OUYA && !UNITY_EDITOR
			if (OuyaSDK.isRunningOnOUYASupportedHardware())
			{
				Debug.Log( "[InControl] All systems go; firing up OUYA adapter." );
				InputManager.AddDeviceManager<OuyaEverywhereDeviceManager>();
			}
			else
			{
				Debug.Log( "[InControl] OuyaSDK.isRunningOnOUYASupportedHardware() has returned false." );
			}
			#endif
		}
	}
}


text:
/*!
 * (C) Ionic http://ionicframework.com - MIT License
 * Built with http://stenciljs.com
 */
Ionic.defineComponents(

/**** module id (dev mode) ****/
'ion-input',

/**** component modules ****/
function importComponent(exports, h, t, Core, publicPath) {
function createThemedClasses(mode, color, classList) {
    var allClassObj = {};
    return classList.split(' ')
        .reduce(function (classObj, classString) {
        classObj[classString] = true;
        if (mode) {
            classObj[classString + "-" + mode] = true;
            if (color) {
                classObj[classString + "-" + color] = true;
                classObj[classString + "-" + mode + "-" + color] = true;
            }
        }
        return classObj;
    }, allClassObj);
}

var Input = (function () {
    function Input() {
        /**
         * @input {string} Indicates whether the value of the control can be automatically completed by the browser. Defaults to `"off"`.
         */
        this.autocomplete = 'off';
        /**
         * @input {string} Whether autocorrection should be enabled when the user is entering/editing the text value. Defaults to `"off"`.
         */
        this.autocorrect = 'off';
        /**
         * @input {boolean} If true and the type is `checkbox` or `radio`, the control is selected by default. Defaults to `false`.
         */
        this.checked = false;
        /**
         * @input {boolean} If true, a clear icon will appear in the input when there is a value. Clicking it clears the input. Defaults to `false`.
         */
        this.clearInput = false;
        /**
         * @input {boolean} If true, the user cannot interact with this element. Defaults to `false`.
         */
        this.disabled = false;
        /**
         * @input {boolean} If true, the user cannot modify the value. Defaults to `false`.
         */
        this.readonly = false;
        /**
         * @input {string} If true, the element will have its spelling and grammar checked. Defaults to `false`.
         */
        this.spellcheck = false;
        /**
         * @input {string} The type of control to display. The default type is text. Possible values are: `"text"`, `"password"`, `"email"`, `"number"`, `"search"`, `"tel"`, or `"url"`.
         */
        this.type = 'text';
    }
    /**
     * @hidden
     */
    Input.prototype.setChecked = function () {
        this.emitStyle();
    };
    /**
     * @hidden
     */
    Input.prototype.setDisabled = function () {
        this.emitStyle();
    };
    Input.prototype["componentDidLoad"] = function () {
        this.emitStyle();
        // By default, password inputs clear after focus when they have content
        if (this.type === 'password' && this.clearOnEdit !== false) {
            this.clearOnEdit = true;
        }
    };
    Input.prototype.emitStyle = function () {
        var _this = this;
        clearTimeout(this.styleTmr);
        var styles = {
            'input': true,
            'input-checked': this.checked,
            'input-disabled': this.disabled,
            'input-has-value': this.hasValue(),
            'input-has-focus': this.hasFocus()
        };
        this.styleTmr = setTimeout(function () {
            _this.ionStyle.emit(styles);
        });
    };
    /**
     * @hidden
     */
    Input.prototype.hasValue = function () {
        return (this.value !== null && this.value !== undefined && this.value !== '');
    };
    /**
     * @hidden
     */
    Input.prototype.inputBlurred = function (ev) {
        this.ionBlur.emit(ev);
        this.focusChange(this.hasFocus());
        this.emitStyle();
    };
    /**
     * @hidden
     */
    Input.prototype.inputChanged = function (ev) {
        this.value = ev.target && ev.target.value;
        this.emitStyle();
    };
    /**
     * @hidden
     */
    Input.prototype.inputFocused = function (ev) {
        this.ionFocus.emit(ev);
        this.focusChange(this.hasFocus());
        this.emitStyle();
    };
    /**
     * @hidden
     */
    Input.prototype.hasFocus = function () {
        // check if an input has focus or not
        return this.el && (this.el.querySelector(':focus') === this.el.querySelector('input'));
    };
    /**
     * @hidden
     */
    Input.prototype.focusChange = function (inputHasFocus) {
        // If clearOnEdit is enabled and the input blurred but has a value, set a flag
        if (this.clearOnEdit && !inputHasFocus && this.hasValue()) {
            this.didBlurAfterEdit = true;
        }
    };
    /**
     * @hidden
     */
    Input.prototype.inputKeydown = function () {
        this.checkClearOnEdit();
    };
    /**
    * Check if we need to clear the text input if clearOnEdit is enabled
    * @hidden
    */
    Input.prototype.checkClearOnEdit = function () {
        if (!this.clearOnEdit) {
            return;
        }
        // Did the input value change after it was blurred and edited?
        if (this.didBlurAfterEdit && this.hasValue()) {
            // Clear the input
            this.clearTextInput();
        }
        // Reset the flag
        this.didBlurAfterEdit = false;
    };
    /**
     * @hidden
     */
    Input.prototype.clearTextInput = function () {
        console.debug('Should clear input', this.el);
        this.value = '';
    };
    Input.prototype.render = function () {
        var themedClasses = createThemedClasses(this.mode, this.color, 'text-input');
        // TODO aria-labelledby={this.item.labelId}
        // OLD RENDER
        // '<input [(ngModel)]="_value" [type]="type" (blur)="inputBlurred($event)" (focus)="inputFocused($event)" [placeholder]="placeholder" [disabled]="disabled" [readonly]="readonly" class="text-input" [ngClass]="\'text-input-\' + _mode" *ngIf="_type!==\'textarea\'"  #input>' +
        // '<textarea [(ngModel)]="_value" (blur)="inputBlurred($event)" (focus)="inputFocused($event)" [placeholder]="placeholder" [disabled]="disabled" [readonly]="readonly" class="text-input" [ngClass]="\'text-input-\' + _mode" *ngIf="_type===\'textarea\'" #textarea></textarea>' +
        // '<input [type]="type" aria-hidden="true" next-input *ngIf="_useAssist">' +
        // '<ion-button clear [hidden]="!clearInput" type="button" class="text-input-clear-icon" (click)="clearTextInput()" (mousedown)="clearTextInput()"></ion-button>' +
        // '<div (touchstart)="pointerStart($event)" (touchend)="pointerEnd($event)" (mousedown)="pointerStart($event)" (mouseup)="pointerEnd($event)" class="input-cover" tappable *ngIf="_useAssist"></div>',
        return (h("input", { "c": themedClasses, "o": { "blur": this.inputBlurred.bind(this), "input": this.inputChanged.bind(this), "focus": this.inputFocused.bind(this), "keydown": this.inputKeydown.bind(this) }, "a": { "aria-disabled": this.disabled ? 'true' : false, "disabled": this.disabled }, "p": { "autoComplete": this.autocomplete, "autoCorrect": this.autocorrect, "autoFocus": this.autofocus, "checked": this.checked, "min": this.min, "max": this.max, "placeholder": this.placeholder, "readOnly": this.readonly, "spellCheck": this.spellcheck, "step": this.step, "type": this.type, "value": this.value } }));
    };
    return Input;
}());

exports['ION-INPUT'] = Input;
},

/***************** ion-input *****************/
[
/** ion-input: [0] tag **/
'ION-INPUT',

/** ion-input: [1] host **/
{"theme":"input"},

/** ion-input: [2] states **/
0 /* no states */,

/** ion-input: [3] propWillChanges **/
0 /* no prop will change methods */,

/** ion-input: [4] propDidChanges **/
[
  [
    /*****  ion-input prop did change [0] ***** /
    /* [0] prop name **/ 'checked',
    /* [1] call fn *****/ 'setChecked'
  ],
  [
    /*****  ion-input prop did change [1] ***** /
    /* [0] prop name **/ 'disabled',
    /* [1] call fn *****/ 'setDisabled'
  ]
],

/** ion-input: [5] events **/
[
  [
    /*****  ion-input ionBlur ***** /
    /* [0] event name ***/ 'ionBlur',
    /* [1] method name **/ 'ionBlur',
    /* [2] bubbles ******/ '1 /* true **/',
    /* [3] cancelable ***/ '1 /* true **/',
    /* [4] composed *****/ '1 /* true **/'
  ],
  [
    /*****  ion-input ionFocus ***** /
    /* [0] event name ***/ 'ionFocus',
    /* [1] method name **/ 'ionFocus',
    /* [2] bubbles ******/ '1 /* true **/',
    /* [3] cancelable ***/ '1 /* true **/',
    /* [4] composed *****/ '1 /* true **/'
  ],
  [
    /*****  ion-input ionStyle ***** /
    /* [0] event name ***/ 'ionStyle',
    /* [1] method name **/ 'ionStyle',
    /* [2] bubbles ******/ '1 /* true **/',
    /* [3] cancelable ***/ '1 /* true **/',
    /* [4] composed *****/ '1 /* true **/'
  ]
],

/** ion-input: [6] methods **/
0 /* no methods */,

/** ion-input: [7] hostElementMember **/
'el'

]
)


text:
static GDCALLINGCONV void *wrapper_create(void *data, const void *type_tag, godot_object *instance) {
	godot::_Wrapped *wrapper_memory = (godot::_Wrapped *)godot::api->godot_alloc(sizeof(godot::_Wrapped));

	if (!wrapper_memory)
		return NULL;
	wrapper_memory->_owner = instance;
	wrapper_memory->_type_tag = (size_t)type_tag;

	return (void *)wrapper_memory;
}

static GDCALLINGCONV void wrapper_destroy(void *data, void *wrapper) {
	if (wrapper)
		godot::api->godot_free(wrapper);
}

namespace godot {

void *_RegisterState::nativescript_handle;
int _RegisterState::language_index;

const godot_gdnative_core_api_struct *api = nullptr;
const godot_gdnative_core_1_1_api_struct *core_1_1_api = nullptr;
const godot_gdnative_core_1_2_api_struct *core_1_2_api = nullptr;

const godot_gdnative_ext_nativescript_api_struct *nativescript_api = nullptr;
const godot_gdnative_ext_nativescript_1_1_api_struct *nativescript_1_1_api = nullptr;
const godot_gdnative_ext_pluginscript_api_struct *pluginscript_api = nullptr;
const godot_gdnative_ext_android_api_struct *android_api = nullptr;
const godot_gdnative_ext_arvr_api_struct *arvr_api = nullptr;
const godot_gdnative_ext_videodecoder_api_struct *videodecoder_api = nullptr;
const godot_gdnative_ext_net_api_struct *net_api = nullptr;
const godot_gdnative_ext_net_3_2_api_struct *net_3_2_api = nullptr;

const void *gdnlib = NULL;

void Godot::print(const String &message) {
	godot::api->godot_print((godot_string *)&message);
}

void Godot::print_warning(const String &description, const String &function, const String &file, int line) {
	int len;

	char *c_desc = description.alloc_c_string();
	char *c_func = function.alloc_c_string();
	char *c_file = file.alloc_c_string();

	if (c_desc != nullptr && c_func != nullptr && c_file != nullptr) {
		godot::api->godot_print_warning(c_desc, c_func, c_file, line);
	};

	if (c_desc != nullptr)
		godot::api->godot_free(c_desc);
	if (c_func != nullptr)
		godot::api->godot_free(c_func);
	if (c_file != nullptr)
		godot::api->godot_free(c_file);
}

void Godot::print_error(const String &description, const String &function, const String &file, int line) {
	int len;

	char *c_desc = description.alloc_c_string();
	char *c_func = function.alloc_c_string();
	char *c_file = file.alloc_c_string();

	if (c_desc != nullptr && c_func != nullptr && c_file != nullptr) {
		godot::api->godot_print_error(c_desc, c_func, c_file, line);
	};

	if (c_desc != nullptr)
		godot::api->godot_free(c_desc);
	if (c_func != nullptr)
		godot::api->godot_free(c_func);
	if (c_file != nullptr)
		godot::api->godot_free(c_file);
}

void ___register_types();
void ___init_method_bindings();

void Godot::gdnative_init(godot_gdnative_init_options *options) {
	godot::api = options->api_struct;
	godot::gdnlib = options->gd_native_library;

	const godot_gdnative_api_struct *core_extension = godot::api->next;

	while (core_extension) {
		if (core_extension->version.major == 1 && core_extension->version.minor == 1) {
			godot::core_1_1_api = (const godot_gdnative_core_1_1_api_struct *)core_extension;
		} else if (core_extension->version.major == 1 && core_extension->version.minor == 2) {
			godot::core_1_2_api = (const godot_gdnative_core_1_2_api_struct *)core_extension;
		}
		core_extension = core_extension->next;
	}

	// now find our extensions
	for (int i = 0; i < godot::api->num_extensions; i++) {
		switch (godot::api->extensions[i]->type) {
			case GDNATIVE_EXT_NATIVESCRIPT: {
				godot::nativescript_api = (const godot_gdnative_ext_nativescript_api_struct *)godot::api->extensions[i];

				const godot_gdnative_api_struct *extension = godot::nativescript_api->next;

				while (extension) {
					if (extension->version.major == 1 && extension->version.minor == 1) {
						godot::nativescript_1_1_api = (const godot_gdnative_ext_nativescript_1_1_api_struct *)extension;
					}

					extension = extension->next;
				}
			} break;
			case GDNATIVE_EXT_PLUGINSCRIPT: {
				godot::pluginscript_api = (const godot_gdnative_ext_pluginscript_api_struct *)godot::api->extensions[i];
			} break;
			case GDNATIVE_EXT_ANDROID: {
				godot::android_api = (const godot_gdnative_ext_android_api_struct *)godot::api->extensions[i];
			} break;
			case GDNATIVE_EXT_ARVR: {
				godot::arvr_api = (const godot_gdnative_ext_arvr_api_struct *)godot::api->extensions[i];
			} break;
			case GDNATIVE_EXT_VIDEODECODER: {
				godot::videodecoder_api = (const godot_gdnative_ext_videodecoder_api_struct *)godot::api->extensions[i];
			} break;
			case GDNATIVE_EXT_NET: {
				godot::net_api = (const godot_gdnative_ext_net_api_struct *)godot::api->extensions[i];

				const godot_gdnative_api_struct *extension = godot::net_api->next;

				while (extension) {
					if (extension->version.major == 3 && extension->version.minor == 2) {
						godot::net_3_2_api = (const godot_gdnative_ext_net_3_2_api_struct *)extension;
					}

					extension = extension->next;
				}
			} break;

			default:
				break;
		}
	}

	// Initialize the `language_index` here since `__register_types()` makes use of it.
	godot_instance_binding_functions binding_funcs = {};
	binding_funcs.alloc_instance_binding_data = wrapper_create;
	binding_funcs.free_instance_binding_data = wrapper_destroy;

	godot::_RegisterState::language_index = godot::nativescript_1_1_api->godot_nativescript_register_instance_binding_data_functions(binding_funcs);

	// register these now
	___register_types();
	___init_method_bindings();
}

void Godot::gdnative_terminate(godot_gdnative_terminate_options *options) {
	// reserved for future use.
}

void Godot::gdnative_profiling_add_data(const char *p_signature, uint64_t p_time) {
	godot::nativescript_1_1_api->godot_nativescript_profiling_add_data(p_signature, p_time);
}

void Godot::nativescript_init(void *handle) {
	godot::_RegisterState::nativescript_handle = handle;
}

void Godot::nativescript_terminate(void *handle) {
	godot::nativescript_1_1_api->godot_nativescript_unregister_instance_binding_data_functions(godot::_RegisterState::language_index);
}

} // namespace godot


text:
'use strict';

var randu = require( '@stdlib/random/iter/randu' );
var iterMap = require( '@stdlib/iter/map' );
var iterEvery = require( './../lib' );

function threshold( r ) {
	return ( r <= 0.95 );
}

// Create an iterator which generates uniformly distributed pseudorandom numbers:
var opts = {
	'iter': 100
};
var riter = randu( opts );

// Create an iterator which applies a threshold to generated numbers:
var miter = iterMap( riter, threshold );

// Determine if all values are "truthy":
var bool = iterEvery( miter );
// returns <boolean>

console.log( bool );


text:
extern Vector *call_stack;

LispObject *eval(ConsCell *args);
LispObject *eval_sub(LispObject *obj);
LispObject *apply(ConsCell *args);
LispObject *apply_sub(LispObject *function, ConsCell *function_arguments);
LispObject *do_(ConsCell *args);
LispObject *quote(ConsCell *args);
LispObject *cons(ConsCell *args);
LispObject *list(ConsCell *args);
LispObject *macro(ConsCell *args);
LispObject *fn(ConsCell *args);
LispObject *def(ConsCell *args);
LispObject *car(ConsCell *args);
LispObject *cdr(ConsCell *args);
LispObject *if_(ConsCell *args);
LispObject *equals(ConsCell *args);
LispObject *equals_sub(LispObject *a, LispObject *b);
LispObject *plus(ConsCell *args);
LispObject *minus(ConsCell *args);
LispObject *print(ConsCell *args);
LispObject *while_(ConsCell *args);
LispObject *set(ConsCell *args);
LispObject *show_symbol_table(ConsCell *args);
LispObject *try_catch(ConsCell *args);
void register_builtin_functions();

#endif


text:
/* United
 * Bootswatch
 *= require_self
 *= require united/loader
 *= require united/bootswatch
*/


text:
using Arthas.Utility.Element;
using System.Windows.Controls;

namespace Arthas.Controls
{
    public class MetroGroupBox : GroupBox
    {
        static MetroGroupBox()
        {
            ElementBase.DefaultStyle<MetroGroupBox>(DefaultStyleKeyProperty);
        }
    }
}