text:
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

#[cfg(feature = "testing")]
use crate::natives::util::make_test_only_native_from_func;
use crate::{natives::util::make_native_from_func, pop_vec_arg};
#[cfg(feature = "testing")]
use aptos_crypto::bls12381::ProofOfPossession;
#[cfg(feature = "testing")]
use aptos_crypto::bls12381::{PrivateKey, PublicKey};
#[cfg(feature = "testing")]
use aptos_crypto::test_utils::KeyPair;
#[cfg(feature = "testing")]
use aptos_crypto::SigningKey;
#[cfg(feature = "testing")]
use aptos_crypto::Uniform;
use aptos_crypto::{bls12381, traits};
use move_binary_format::errors::PartialVMError;
use move_binary_format::errors::PartialVMResult;
use move_core_types::gas_algebra::{
    InternalGas, InternalGasPerArg, InternalGasPerByte, NumArgs, NumBytes,
};
use move_core_types::vm_status::StatusCode;
use move_vm_runtime::native_functions::{NativeContext, NativeFunction};
use move_vm_types::values::Struct;
use move_vm_types::{
    loaded_data::runtime_types::Type, natives::function::NativeResult, pop_arg, values::Value,
};
#[cfg(feature = "testing")]
use rand_core::OsRng;
use smallvec::smallvec;
use std::{collections::VecDeque, convert::TryFrom};

/// Pops a Vec<T> off the argument stack and converts it to a Vec<Vec<u8>> by reading the first
/// field of T, which is a Vec<u8> field named `bytes`.
fn pop_vec_of_vec_u8(arguments: &mut VecDeque<Value>) -> PartialVMResult<Vec<Vec<u8>>> {
    let structs = pop_vec_arg!(arguments, Struct);
    let mut v = Vec::with_capacity(structs.len());

    for s in structs {
        let field = s
            .unpack()?
            .next()
            .ok_or_else(|| PartialVMError::new(StatusCode::INTERNAL_TYPE_ERROR))?;

        v.push(field.value_as::<Vec<u8>>()?);
    }

    PartialVMResult::Ok(v)
}

#[derive(Debug, Clone)]
pub struct GasParameters {
    pub base: InternalGas,

    pub per_pubkey_deserialize: InternalGasPerArg,
    pub per_pubkey_aggregate: InternalGasPerArg,
    pub per_pubkey_subgroup_check: InternalGasPerArg,

    pub per_sig_deserialize: InternalGasPerArg,
    pub per_sig_aggregate: InternalGasPerArg,
    pub per_sig_subgroup_check: InternalGasPerArg,

    pub per_sig_verify: InternalGasPerArg,
    pub per_pop_verify: InternalGasPerArg,

    pub per_pairing: InternalGasPerArg, // a size-n BLS aggregate signature requires n+1 pairings

    pub per_msg_hashing: InternalGasPerArg,
    pub per_byte_hashing: InternalGasPerByte, // signature verification involves signing |msg| bytes
}

impl GasParameters {
    /// Deserializes a vector of PK bytes into bls12381::PublicKey structs.
    fn bls12381_deserialize_pks(
        &self,
        pks_serialized: Vec<Vec<u8>>,
        cost: &mut InternalGas,
    ) -> Vec<bls12381::PublicKey> {
        let mut pks = vec![];

        for pk_bytes in pks_serialized {
            let pk = match self.bls12381_deserialize_pk(pk_bytes, cost) {
                Some(key) => key,
                // If PK does not deserialize correctly, break early
                None => break,
            };

            pks.push(pk);
        }

        pks
    }

    /// Deserializes a sequence of bytes into bls12381::PublicKey struct.
    fn bls12381_deserialize_pk(
        &self,
        pk_bytes: Vec<u8>,
        cost: &mut InternalGas,
    ) -> Option<bls12381::PublicKey> {
        *cost += self.per_pubkey_deserialize * NumArgs::one();

        match bls12381::PublicKey::try_from(&pk_bytes[..]) {
            Ok(key) => Some(key),
            // If PK does not deserialize correctly, return None
            Err(_) => None,
        }
    }

    /// Deserializes a vector of signature bytes into bls12381::Signature structs.
    fn bls12381_deserialize_sigs(
        &self,
        sigs_serialized: Vec<Vec<u8>>,
        cost: &mut InternalGas,
    ) -> Vec<bls12381::Signature> {
        let mut sigs = vec![];

        for sig_bytes in sigs_serialized {
            let sig = match self.bls12381_deserialize_sig(sig_bytes, cost) {
                Some(sig) => sig,
                // If sig does not deserialize correctly, break early
                None => break,
            };

            sigs.push(sig);
        }

        sigs
    }

    /// Deserializes a sequence of bytes into bls12381::Signature struct.
    fn bls12381_deserialize_sig(
        &self,
        sig_bytes: Vec<u8>,
        cost: &mut InternalGas,
    ) -> Option<bls12381::Signature> {
        *cost += self.per_sig_deserialize * NumArgs::one();

        match bls12381::Signature::try_from(&sig_bytes[..]) {
            Ok(sig) => Some(sig),
            // If PK does not deserialize correctly, return None
            Err(_) => None,
        }
    }

    /// Deserializes a sequence of bytes into bls12381::Signature struct.
    fn bls12381_deserialize_pop(
        &self,
        pop_bytes: Vec<u8>,
        cost: &mut InternalGas,
    ) -> Option<bls12381::ProofOfPossession> {
        *cost += self.per_sig_deserialize * NumArgs::one();

        match bls12381::ProofOfPossession::try_from(&pop_bytes[..]) {
            Ok(pop) => Some(pop),
            // If PK does not deserialize correctly, break early
            Err(_) => None,
        }
    }

    /// Checks prime-order subgroup membership on a bls12381::PublicKey struct.
    fn bls12381_pk_subgroub_check(&self, pk: &bls12381::PublicKey, cost: &mut InternalGas) -> bool {
        // NOTE(Gas): constant-time; around 39 microseconds on Apple M1
        *cost += self.per_pubkey_deserialize * NumArgs::one();
        pk.subgroup_check().is_ok()
    }

    /// Checks prime-order subgroup membership on a bls12381::Signature struct.
    fn bls12381_sig_subgroub_check(
        &self,
        sig: &bls12381::Signature,
        cost: &mut InternalGas,
    ) -> bool {
        *cost += self.per_sig_subgroup_check * NumArgs::one();
        sig.subgroup_check().is_ok()
    }

    /// Verifies a signature on an arbitrary message.
    fn signature_verify<S: traits::Signature>(
        &self,
        sig: &S,
        pk: &S::VerifyingKeyMaterial,
        msg: Vec<u8>,
        cost: &mut InternalGas,
    ) -> bool {
        *cost += self.per_sig_verify * NumArgs::one()
            + self.per_msg_hashing * NumArgs::one()
            + self.per_byte_hashing * NumBytes::new(msg.len() as u64);

        sig.verify_arbitrary_msg(&msg[..], pk).is_ok()
    }

    /// This is a helper function called by our `bls12381_verify_*` functions for:
    ///  * normal (non-aggregated) signatures,
    ///  * signature shares (in the multisignature scheme & the aggregate signature scheme)
    ///  * multisignatures
    ///
    /// Gas cost: base_cost + per_pubkey_deserialize_cost
    ///                     +? ( per_pubkey_subgroup_check_cost * check_pk_subgroup
    ///                          +? ( per_sig_deserialize_cost
    ///                              +? ( per_sig_verify_cost + per_msg_hashing_cost
    ///                                   + per_byte_hashing_cost * |msg| ) ) )
    ///
    /// where +? indicates that the expression stops evaluating there if the previous gas-charging step
    /// failed.
    pub fn bls12381_verify_signature_helper(
        &self,
        _context: &mut NativeContext,
        _ty_args: Vec<Type>,
        mut arguments: VecDeque<Value>,
        check_pk_subgroup: bool,
    ) -> PartialVMResult<NativeResult> {
        debug_assert!(_ty_args.is_empty());
        debug_assert!(arguments.len() == 3);

        let mut cost = self.base;
        let msg_bytes = pop_arg!(arguments, Vec<u8>);
        let aggpk_bytes = pop_arg!(arguments, Vec<u8>);
        let multisig_bytes = pop_arg!(arguments, Vec<u8>);

        let pk = match self.bls12381_deserialize_pk(aggpk_bytes, &mut cost) {
            Some(pk) => pk,
            None => {
                return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)]));
            }
        };

        if check_pk_subgroup && !self.bls12381_pk_subgroub_check(&pk, &mut cost) {
            return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)]));
        }

        let sig = match self.bls12381_deserialize_sig(multisig_bytes, &mut cost) {
            Some(sig) => sig,
            None => {
                return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)]));
            }
        };

        // NOTE(Gas): 2 bilinear pairings and a hash-to-curve
        let verify_result = self.signature_verify(&sig, &pk, msg_bytes, &mut cost);

        Ok(NativeResult::ok(
            cost,
            smallvec![Value::bool(verify_result)],
        ))
    }
}

/***************************************************************************************************
 * native fun bls12381_aggregate_pop_verified_pubkeys
 *
 *   gas cost: base_cost + per_pubkey_deserialize_cost * min(num_validatable_pubkeys + 1, num_pubkeys)
 *                       +? per_pubkey_aggregate_cost * num_pubkeys
 *
 * where +? indicates that the expression stops evaluating there if the previous gas-charging step
 * failed, num_pubkeys is the # of public keys given as input, and num_validatable_pubkeys is the
 * # of public keys that deserialize successfully.
 *
 * NOTE(ValidatablePK): We refer to the public keys that deserialize correctly as "validatable"
 * above, since successful deserialization is not a sufficient criteria for the "validatability"
 * of a PK: e.g., the PK could still be susceptible to small-subgroup attacks or rogue-key attacks.
 *
 * NOTE: If all PKs deserialize, then per_pubkey_deserialize_cost is charged num_pubkeys times.
 * Otherwise, if only num_validatable_pubkeys deserialize correctly, an extra per_pubkey_deserialize_cost
 * must be charged for the failed deserialization.
 **************************************************************************************************/
fn native_bls12381_aggregate_pubkeys(
    gas_params: &GasParameters,
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    debug_assert!(_ty_args.is_empty());
    debug_assert!(arguments.len() == 1);

    // Parses a Vec<Vec<u8>> of all serialized public keys
    let pks_bytes = pop_vec_of_vec_u8(&mut arguments)?;
    let num_pks = pks_bytes.len();
    let mut cost = gas_params.base;

    // If zero PKs were given as input, return None.
    if pks_bytes.is_empty() {
        return Ok(NativeResult::ok(
            cost,
            smallvec![Value::vector_u8(vec![]), Value::bool(false)],
        ));
    }

    let pks = gas_params.bls12381_deserialize_pks(pks_bytes, &mut cost);
    debug_assert!(pks.len() <= num_pks);

    // If not all PKs were successfully deserialized, return None and only charge for the actual work done
    if pks.len() != num_pks {
        return Ok(NativeResult::ok(
            cost,
            smallvec![Value::vector_u8(vec![]), Value::bool(false)],
        ));
    }

    // Aggregate the public keys (this will NOT subgroup-check the individual PKs)
    // NOTE(Gas): |pks| elliptic curve additions
    cost += gas_params.per_pubkey_aggregate * NumArgs::new(num_pks as u64);
    let aggpk =
        match bls12381::PublicKey::aggregate(pks.iter().collect::<Vec<&bls12381::PublicKey>>()) {
            Ok(aggpk) => aggpk,
            Err(_) => {
                return Ok(NativeResult::ok(
                    cost,
                    smallvec![Value::vector_u8(vec![]), Value::bool(false)],
                ))
            }
        };

    Ok(NativeResult::ok(
        cost,
        smallvec![
            Value::vector_u8(aggpk.to_bytes().to_vec()),
            Value::bool(true)
        ],
    ))
}

/***************************************************************************************************
 * native fun bls12381_aggregate_signatures
 *
 *   gas cost: base_cost + num_viable_sigs * per_sig_deserialize_cost
 *                       +? num_sigs * per_sig_aggregate_cost
 *
 * where +? indicates that the expression stops evaluating there if the previous gas-charging step
 * failed
 *
 * NOTE(ViableSig): We refer to the signatures that deserialize correctly as "viable" above, since
 * successful deserialization is not a sufficient criteria for the "viability" of a signature: e.g.,
 * the signature might not verify under the desired (message, public key) pair, or the signature
 * could lie in a small-order subgroup.
 **************************************************************************************************/
pub fn native_bls12381_aggregate_signatures(
    gas_params: &GasParameters,
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    debug_assert!(_ty_args.is_empty());
    debug_assert!(arguments.len() == 1);

    // Parses a Vec<Vec<u8>> of all serialized signatures
    let sigs_serialized = pop_vec_of_vec_u8(&mut arguments)?;
    let num_sigs = sigs_serialized.len();

    let mut cost = gas_params.base;

    // If zero signatures were given as input, return None.
    if sigs_serialized.is_empty() {
        return Ok(NativeResult::ok(
            cost,
            smallvec![Value::vector_u8(vec![]), Value::bool(false)],
        ));
    }

    let sigs = gas_params.bls12381_deserialize_sigs(sigs_serialized, &mut cost);

    if sigs.len() != num_sigs {
        return Ok(NativeResult::ok(
            cost,
            smallvec![Value::vector_u8(vec![]), Value::bool(false)],
        ));
    }

    // Aggregate the signatures (this will NOT group-check the individual signatures)
    // NOTE(Gas): |sigs| elliptic curve additions
    cost += gas_params.per_sig_aggregate * NumArgs::new(sigs.len() as u64);
    let aggsig = match bls12381::Signature::aggregate(sigs) {
        Ok(aggsig) => aggsig,
        Err(_) => {
            return Ok(NativeResult::ok(
                cost,
                smallvec![Value::vector_u8(vec![]), Value::bool(false)],
            ))
        }
    };

    Ok(NativeResult::ok(
        cost,
        smallvec![
            Value::vector_u8(aggsig.to_bytes().to_vec()),
            Value::bool(true)
        ],
    ))
}

/***************************************************************************************************
 * native fun bls12381_signature_subgroup_check
 *
 *   gas cost: base_cost + per_sig_deserialize_cost +? per_sig_subgroup_check_cost
 *
 * where +? indicates that the expression stops evaluating there if the previous gas-charging step
 * failed
 **************************************************************************************************/
pub fn native_bls12381_signature_subgroup_check(
    gas_params: &GasParameters,
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    debug_assert!(_ty_args.is_empty());
    debug_assert!(arguments.len() == 1);

    let mut cost = gas_params.base;

    let sig_bytes = pop_arg!(arguments, Vec<u8>);

    let sig = match gas_params.bls12381_deserialize_sig(sig_bytes, &mut cost) {
        Some(key) => key,
        None => return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])),
    };

    let valid = gas_params.bls12381_sig_subgroub_check(&sig, &mut cost);

    Ok(NativeResult::ok(cost, smallvec![Value::bool(valid)]))
}

/***************************************************************************************************
 * native fun bls12381_validate_pubkey
 *
 *   gas cost: base_cost + per_pubkey_deserialize_cost +? per_pubkey_subgroup_check_cost
 *
 * where +? indicates that the expression stops evaluating there if the previous gas-charging step
 * failed
 **************************************************************************************************/
fn native_bls12381_validate_pubkey(
    gas_params: &GasParameters,
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    debug_assert!(_ty_args.is_empty());
    debug_assert!(arguments.len() == 1);

    let mut cost = gas_params.base;
    let pk_bytes = pop_arg!(arguments, Vec<u8>);

    let pk = match gas_params.bls12381_deserialize_pk(pk_bytes, &mut cost) {
        Some(key) => key,
        None => return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])),
    };

    let valid = gas_params.bls12381_pk_subgroub_check(&pk, &mut cost);

    Ok(NativeResult::ok(cost, smallvec![Value::bool(valid)]))
}

/***************************************************************************************************
* native fun native_bls12381_verify_aggregate_signature
*
*   gas cost: base_cost + per_pubkey_deserialize_cost * min(num_validatable_pubkeys + 1, num_pubkeys)
*                       +? ( per_sig_deserialize_cost * min(num_viable_sigs + 1, num_sigs)
*                            +? ( per_pairing_cost + per_msg_hashing_cost ) * num_msgs
*                                 + per_byte_hashing_cost * total_msg_bytes )
*
* where:
*    +? indicates the expression stops evaluating there if the previous gas-charging step failed,
*    num_pubkeys is the # of public keys given as input,
*    num_validatable_pubkeys is the # of public keys that deserialize successfully (i.e., "validatable"),
*    num_sigs is the # of signatures given as input,
*    num_viable_sigs is the # of signatures that deserialize successfully (i.e., "viable"),
*    total_msg_bytes is the cumulative size in bytes of all messages.
*
* NOTE(ValidatablePK): We refer to the public keys that deserialize correctly as "validatable"
* above, since successful deserialization is not a sufficient criteria for the "validatability"
* of a PK: e.g., the PK could still be susceptible to small-subgroup attacks or rogue-key attacks.
*
* NOTE(ViableSig): We refer to the signatures that deserialize correctly as "viable" above, since
* successful deserialization is not a sufficient criteria for the "viability" of a signature: e.g.,
* the signature might not verify under the desired (message, public key) pair, or the signature
* could lie in a small-order subgroup.

* NOTE: If all PKs deserialize, then per_pubkey_deserialize_cost is charged num_pubkeys times.
* Otherwise, if only num_validatable_pubkeys deserialize correctly, an extra per_pubkey_deserialize_cost
* must be charged for the failed deserialization. We proceed similarly for per_sig_deserialize_cost.
**************************************************************************************************/
pub fn native_bls12381_verify_aggregate_signature(
    gas_params: &GasParameters,
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    debug_assert!(_ty_args.is_empty());
    debug_assert!(arguments.len() == 3);

    let mut cost = gas_params.base;

    // Parses a Vec<Vec<u8>> of all messages
    let messages = pop_vec_arg!(arguments, Vec<u8>);
    // Parses a Vec<Vec<u8>> of all serialized public keys
    let pks_serialized = pop_vec_of_vec_u8(&mut arguments)?;
    let num_pks = pks_serialized.len();

    // Parses the signature as a Vec<u8>
    let aggsig_bytes = pop_arg!(arguments, Vec<u8>);

    // Number of messages must match number of public keys
    if pks_serialized.len() != messages.len() {
        return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)]));
    }

    let pks = gas_params.bls12381_deserialize_pks(pks_serialized, &mut cost);
    debug_assert!(pks.len() <= num_pks);

    // If less PKs than expected were deserialized, return None.
    if pks.len() != num_pks {
        return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)]));
    }

    let aggsig = match gas_params.bls12381_deserialize_sig(aggsig_bytes, &mut cost) {
        Some(aggsig) => aggsig,
        None => return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])),
    };

    let msgs_refs = messages
        .iter()
        .map(|m| m.as_slice())
        .collect::<Vec<&[u8]>>();
    let pks_refs = pks.iter().collect::<Vec<&bls12381::PublicKey>>();

    // The cost of verifying a size-n aggregate signatures involves n+1 parings and hashing all
    // the messages to elliptic curve points (proportional to sum of all message lengths).
    cost += gas_params.per_pairing * NumArgs::new((messages.len() + 1) as u64)
        + gas_params.per_msg_hashing * NumArgs::new(messages.len() as u64)
        + gas_params.per_byte_hashing
            * messages.iter().fold(NumBytes::new(0), |sum, msg| {
                sum + NumBytes::new(msg.len() as u64)
            });

    let verify_result = aggsig
        .verify_aggregate_arbitrary_msg(&msgs_refs, &pks_refs)
        .is_ok();

    Ok(NativeResult::ok(
        cost,
        smallvec![Value::bool(verify_result)],
    ))
}

/***************************************************************************************************
 * native fun bls12381_verify_multisignature
 *
 *   gas cost: base_cost + per_pubkey_deserialize_cost
 *                       +? ( per_sig_deserialize_cost
 *                            +? ( per_sig_verify_cost + per_msg_hashing_cost
 *                                 + per_byte_hashing_cost * |msg| ) )
 *
 * where +? indicates that the expression stops evaluating there if the previous gas-charging step
 * failed
 **************************************************************************************************/
pub fn native_bls12381_verify_multisignature(
    gas_params: &GasParameters,
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    let check_pk_subgroup = false;
    gas_params.bls12381_verify_signature_helper(_context, _ty_args, arguments, check_pk_subgroup)
}

/***************************************************************************************************
 * native fun bls12381_verify_normal_signature
 *
 *   gas cost: base_cost + per_pubkey_deserialize_cost
 *                       +? ( per_sig_deserialize_cost
 *                            +? ( per_pubkey_subgroup_check_cost
 *                                 +? ( per_sig_verify_cost + per_msg_hashing_cost
 *                                     + per_byte_hashing_cost * |msg| ) ) )
 *
 * where +? indicates that the expression stops evaluating there if the previous gas-charging step
 * failed
 **************************************************************************************************/
pub fn native_bls12381_verify_normal_signature(
    gas_params: &GasParameters,
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    // For normal (non-aggregated) signatures, PK's typically don't come with PoPs and the caller
    // might forget to check prime-order subgroup membership of the PK. Therefore, we always enforce
    // it here.
    let check_pk_subgroup = true;
    gas_params.bls12381_verify_signature_helper(_context, _ty_args, arguments, check_pk_subgroup)
}

/***************************************************************************************************
 * native fun bls12381_verify_proof_of_possession
 *
 *   gas cost: base_cost + per_pubkey_deserialize_cost
 *                       +? ( per_sig_deserialize_cost
 *                            +? per_pop_verify_cost )
 *
 * where +? indicates that the expression stops evaluating there if the previous gas-charging step
 * failed
 **************************************************************************************************/
fn native_bls12381_verify_proof_of_possession(
    gas_params: &GasParameters,
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    debug_assert!(_ty_args.is_empty());
    debug_assert!(arguments.len() == 2);

    let mut cost = gas_params.base;
    let pop_bytes = pop_arg!(arguments, Vec<u8>);
    let key_bytes = pop_arg!(arguments, Vec<u8>);

    let pk = match gas_params.bls12381_deserialize_pk(key_bytes, &mut cost) {
        Some(pk) => pk,
        None => return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])),
    };

    let pop = match gas_params.bls12381_deserialize_pop(pop_bytes, &mut cost) {
        Some(pop) => pop,
        None => return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])),
    };

    // NOTE(Gas): 2 bilinear pairings and a hash-to-curve
    cost += gas_params.per_pop_verify * NumArgs::one();
    let valid = pop.verify(&pk).is_ok();

    Ok(NativeResult::ok(cost, smallvec![Value::bool(valid)]))
}

/***************************************************************************************************
 * native fun bls12381_verify_signature_share
 *
 *   gas cost: base_cost + per_pubkey_deserialize_cost
 *                       +? ( per_sig_deserialize_cost
 *                            +? ( per_sig_verify_cost + per_msg_hashing_cost
 *                                 + per_byte_hashing_cost * |msg| ) )
 *
 * where +? indicates that the expression stops evaluating there if the previous gas-charging step
 * failed
 **************************************************************************************************/
pub fn native_bls12381_verify_signature_share(
    gas_params: &GasParameters,
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    // For signature shares, the caller is REQUIRED to check the PK's PoP, and thus the PK is in the
    // prime-order subgroup.
    let check_pk_subgroup = false;
    gas_params.bls12381_verify_signature_helper(_context, _ty_args, arguments, check_pk_subgroup)
}

#[cfg(feature = "testing")]
pub fn native_generate_keys(
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    mut _arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    let key_pair = KeyPair::<PrivateKey, PublicKey>::generate(&mut OsRng);
    Ok(NativeResult::ok(
        InternalGas::zero(),
        smallvec![
            Value::vector_u8(key_pair.private_key.to_bytes()),
            Value::vector_u8(key_pair.public_key.to_bytes()),
        ],
    ))
}

#[cfg(feature = "testing")]
pub fn native_sign(
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    let msg = pop_arg!(arguments, Vec<u8>);
    let sk_bytes = pop_arg!(arguments, Vec<u8>);
    let sk = PrivateKey::try_from(sk_bytes.as_slice()).unwrap();
    let sig = sk.sign_arbitrary_message(msg.as_slice());
    Ok(NativeResult::ok(
        InternalGas::zero(),
        smallvec![Value::vector_u8(sig.to_bytes()),],
    ))
}

#[cfg(feature = "testing")]
pub fn native_generate_proof_of_possession(
    _context: &mut NativeContext,
    _ty_args: Vec<Type>,
    mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
    let sk_bytes = pop_arg!(arguments, Vec<u8>);
    let sk = PrivateKey::try_from(sk_bytes.as_slice()).unwrap();
    let pop = ProofOfPossession::create(&sk);
    Ok(NativeResult::ok(
        InternalGas::zero(),
        smallvec![Value::vector_u8(pop.to_bytes()),],
    ))
}

/***************************************************************************************************
 * module
 *
 **************************************************************************************************/
pub fn make_all(gas_params: GasParameters) -> impl Iterator<Item = (String, NativeFunction)> {
    let mut natives = vec![];
    natives.append(&mut vec![
        // BLS over BLS12-381
        (
            "aggregate_pubkeys_internal",
            make_native_from_func(gas_params.clone(), native_bls12381_aggregate_pubkeys),
        ),
        (
            "aggregate_signatures_internal",
            make_native_from_func(gas_params.clone(), native_bls12381_aggregate_signatures),
        ),
        (
            "signature_subgroup_check_internal",
            make_native_from_func(gas_params.clone(), native_bls12381_signature_subgroup_check),
        ),
        (
            "validate_pubkey_internal",
            make_native_from_func(gas_params.clone(), native_bls12381_validate_pubkey),
        ),
        (
            "verify_aggregate_signature_internal",
            make_native_from_func(
                gas_params.clone(),
                native_bls12381_verify_aggregate_signature,
            ),
        ),
        (
            "verify_multisignature_internal",
            make_native_from_func(gas_params.clone(), native_bls12381_verify_multisignature),
        ),
        (
            "verify_normal_signature_internal",
            make_native_from_func(gas_params.clone(), native_bls12381_verify_normal_signature),
        ),
        (
            "verify_proof_of_possession_internal",
            make_native_from_func(
                gas_params.clone(),
                native_bls12381_verify_proof_of_possession,
            ),
        ),
        (
            "verify_signature_share_internal",
            make_native_from_func(gas_params, native_bls12381_verify_signature_share),
        ),
    ]);
    #[cfg(feature = "testing")]
    natives.append(&mut vec![
        (
            "generate_keys_internal",
            make_test_only_native_from_func(native_generate_keys),
        ),
        (
            "sign_internal",
            make_test_only_native_from_func(native_sign),
        ),
        (
            "generate_proof_of_possession_internal",
            make_test_only_native_from_func(native_generate_proof_of_possession),
        ),
    ]);
    crate::natives::helpers::make_module_natives(natives)
}


text:
$(function () {
  'use strict';

  QUnit.module('scrollspy plugin')

  QUnit.test('should be defined on jquery object', function (assert) {
    assert.expect(1)
    assert.ok($(document.body).scrollspy, 'scrollspy method is defined')
  })

  QUnit.module('scrollspy', {
    beforeEach: function () {
      // Run all tests in noConflict mode -- it's the only way to ensure that the plugin works in noConflict mode
      $.fn.bootstrapScrollspy = $.fn.scrollspy.noConflict()
    },
    afterEach: function () {
      $.fn.scrollspy = $.fn.bootstrapScrollspy
      delete $.fn.bootstrapScrollspy
    }
  })

  QUnit.test('should provide no conflict', function (assert) {
    assert.expect(1)
    assert.strictEqual($.fn.scrollspy, undefined, 'scrollspy was set back to undefined (org value)')
  })

  QUnit.test('should return jquery collection containing the element', function (assert) {
    assert.expect(2)
    var $el = $('
')
    var $scrollspy = $el.bootstrapScrollspy()
    assert.ok($scrollspy instanceof $, 'returns jquery collection')
    assert.strictEqual($scrollspy[0], $el[0], 'collection contains element')
  })

  QUnit.test('should only switch "active" class on current target', function (assert) {
    assert.expect(1)
    var done = assert.async()

    var sectionHTML = '
'
        + '
'
        + '
'
        + '
'
        + '
'
        + '
Overview
'
        + '
Detail
'
        + '
'
        + '
'
        + '
'
        + '
'
        + '
'
        + '
'
        + '
Overview
'
        + '
'
        + 'Ad leggings keytar, brunch id art party dolor labore.'
        + '
'
        + '
'
        + '
'
        + '
Detail
'
        + '
'
        + 'Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard.'
        + '
'
        + '
'
        + '
'
        + '
'
    var $section = $(sectionHTML).appendTo('#qunit-fixture')

    var $scrollspy = $section
      .show()
      .find('#scrollspy-example')
      .bootstrapScrollspy({ target: '#ss-target' })

    $scrollspy.on('scroll.bs.scrollspy', function () {
      assert.ok($section.hasClass('active'), '"active" class still on root node')
      done()
    })

    $scrollspy.scrollTop(350)
  })

  QUnit.test('should correctly select middle navigation option when large offset is used', function (assert) {
    assert.expect(3)
    var done = assert.async()

    var sectionHTML = '

'
        + ''
        + '
'
        + '
One
'
        + '
Two
'
        + '
Three
'
        + '
'
        + ''
        + '
'
        + '

'
        + '

'
        + '

'
        + '
'
    var $section = $(sectionHTML).appendTo('#qunit-fixture')
    var $scrollspy = $section
      .show()
      .filter('#content')

    $scrollspy.bootstrapScrollspy({ target: '#navigation', offset: $scrollspy.position().top })

    $scrollspy.on('scroll.bs.scrollspy', function () {
      assert.ok(!$section.find('#one-link').parent().hasClass('active'), '"active" class removed from first section')
      assert.ok($section.find('#two-link').parent().hasClass('active'), '"active" class on middle section')
      assert.ok(!$section.find('#three-link').parent().hasClass('active'), '"active" class not on last section')
      done()
    })

    $scrollspy.scrollTop(550)
  })

  QUnit.test('should add the active class to the correct element', function (assert) {
    assert.expect(2)
    var navbarHtml =
        ''
      + '
'
      + '
div 1
'
      + '
div 2
'
      + '
'
      + ''
    var contentHtml =
        '
'
      + '
div 1
'
      + '
div 2
'
      + '
'

    $(navbarHtml).appendTo('#qunit-fixture')
    var $content = $(contentHtml)
      .appendTo('#qunit-fixture')
      .bootstrapScrollspy({ offset: 0, target: '.navbar' })

    var testElementIsActiveAfterScroll = function (element, target) {
      var deferred = $.Deferred()
      var scrollHeight = Math.ceil($content.scrollTop() + $(target).position().top)
      var done = assert.async()
      $content.one('scroll', function () {
        assert.ok($(element).hasClass('active'), 'target:' + target + ', element' + element)
        done()
        deferred.resolve()
      })
      $content.scrollTop(scrollHeight)
      return deferred.promise()
    }

    $.when(testElementIsActiveAfterScroll('#li-1', '#div-1'))
      .then(function () { return testElementIsActiveAfterScroll('#li-2', '#div-2') })
  })

  QUnit.test('should add the active class correctly when there are nested elements at 0 scroll offset', function (assert) {
    assert.expect(6)
    var times = 0
    var done = assert.async()
    var navbarHtml = ''
      + '
'
      + '
div 1'
      + '
'
      + '
div 2
'
      + '
'
      + '
'
      + '
'
      + ''

    var contentHtml = '
'
      + '
'
      + '
div 2
'
      + '
'
      + '
'

    $(navbarHtml).appendTo('#qunit-fixture')

    var $content = $(contentHtml)
      .appendTo('#qunit-fixture')
      .bootstrapScrollspy({ offset: 0, target: '#navigation' })

    !function testActiveElements() {
      if (++times > 3) return done()

      $content.one('scroll', function () {
        assert.ok($('#li-1').hasClass('active'), 'nav item for outer element has "active" class')
        assert.ok($('#li-2').hasClass('active'), 'nav item for inner element has "active" class')
        testActiveElements()
      })

      $content.scrollTop($content.scrollTop() + 10)
    }()
  })

  QUnit.test('should clear selection if above the first section', function (assert) {
    assert.expect(3)
    var done = assert.async()

    var sectionHTML = '

'
        + ''
        + '
'
        + '
One
'
        + '
Two
'
        + '
Three
'
        + '
'
        + ''
    $(sectionHTML).appendTo('#qunit-fixture')

    var scrollspyHTML = '
'
        + '
'
        + '
'
        + '
'
        + '
'
        + '
'
        + '
'
    var $scrollspy = $(scrollspyHTML).appendTo('#qunit-fixture')

    $scrollspy
      .bootstrapScrollspy({
        target: '#navigation',
        offset: $scrollspy.position().top
      })
      .one('scroll.bs.scrollspy', function () {
        assert.strictEqual($('.active').length, 1, '"active" class on only one element present')
        assert.strictEqual($('.active').has('#two-link').length, 1, '"active" class on second section')

        $scrollspy
          .one('scroll.bs.scrollspy', function () {
            assert.strictEqual($('.active').length, 0, 'selection cleared')
            done()
          })
          .scrollTop(0)
      })
      .scrollTop(201)
  })

  QUnit.test('should correctly select navigation element on backward scrolling when each target section height is 100%', function (assert) {
    assert.expect(5)
    var navbarHtml =
        ''
      + '
'
      + '
div 1
'
      + '
div 2
'
      + '
div 3
'
      + '
div 4
'
      + '
div 5
'
      + '
'
      + ''
    var contentHtml =
        '
'
      + '
div 1
'
      + '
div 2
'
      + '
div 3
'
      + '
div 4
'
      + '
div 5
'
      + '
'

    $(navbarHtml).appendTo('#qunit-fixture')
    var $content = $(contentHtml)
      .appendTo('#qunit-fixture')
      .bootstrapScrollspy({ offset: 0, target: '.navbar' })

    var testElementIsActiveAfterScroll = function (element, target) {
      var deferred = $.Deferred()
      var scrollHeight = Math.ceil($content.scrollTop() + $(target).position().top)
      var done = assert.async()
      $content.one('scroll', function () {
        assert.ok($(element).hasClass('active'), 'target:' + target + ', element: ' + element)
        done()
        deferred.resolve()
      })
      $content.scrollTop(scrollHeight)
      return deferred.promise()
    }

    $.when(testElementIsActiveAfterScroll('#li-100-5', '#div-100-5'))
      .then(function () { return testElementIsActiveAfterScroll('#li-100-4', '#div-100-4') })
      .then(function () { return testElementIsActiveAfterScroll('#li-100-3', '#div-100-3') })
      .then(function () { return testElementIsActiveAfterScroll('#li-100-2', '#div-100-2') })
      .then(function () { return testElementIsActiveAfterScroll('#li-100-1', '#div-100-1') })
  })

})

redpajama_set_name: RedPajamaGithub


text:
local Troll = {}

local optionAutoSwap = Menu.AddOption({"Hero Specific", "Troll Warlord"}, "Auto Swap", "Auto Swap between range and melee")
local optionEnableKey = Menu.AddOption({"Hero Specific", "Troll Warlord"}, "Enable Key", "On/Off")
local keyAxeMelee = Menu.AddKeyOption({"Hero Specific", "Troll Warlord"}, "Whirling Axe (Melee) Key", Enum.ButtonCode.KEY_W)
local keyAxeRanged = Menu.AddKeyOption({"Hero Specific", "Troll Warlord"}, "Whirling Axes (Ranged) Key", Enum.ButtonCode.KEY_E)

function Troll.OnPrepareUnitOrders(orders)
    if not Menu.IsEnabled(optionAutoSwap) then return true end
    if not orders then return true end

    local myHero = Heroes.GetLocal()
    if not myHero or NPC.GetUnitName(myHero) ~= "npc_dota_hero_troll_warlord" then return true end
    if NPC.IsStunned(myHero) or NPC.IsSilenced(myHero) then return true end

    local swap = NPC.GetAbilityByIndex(myHero, 0)
    if not swap or not Ability.IsCastable(swap, 0) then return true end

    -- swap to melee when running
    if not Ability.GetToggleState(swap) and
        (orders.order == Enum.UnitOrder.DOTA_UNIT_ORDER_MOVE_TO_POSITION
            or orders.order == Enum.UnitOrder.DOTA_UNIT_ORDER_MOVE_TO_TARGET
            or orders.order == Enum.UnitOrder.DOTA_UNIT_ORDER_ATTACK_MOVE)
        then
        Ability.Toggle(swap, true)
        return true
    end

    -- auto swap between melee and range
    local melee_attack_range = 150
    local range = melee_attack_range + 100
    if orders.order == Enum.UnitOrder.DOTA_UNIT_ORDER_ATTACK_TARGET then
        if NPC.IsEntityInRange(myHero, orders.target, range) and not Ability.GetToggleState(swap) then
            Ability.Toggle(swap, true)
            return true
        end

        if not NPC.IsEntityInRange(myHero, orders.target, range) and Ability.GetToggleState(swap) then
            Ability.Toggle(swap, true)
            return true
        end
    end

    return true
end

function Troll.OnUpdate()
    if not Menu.IsEnabled(optionEnableKey) then return end

    local myHero = Heroes.GetLocal()
    if not myHero or NPC.GetUnitName(myHero) ~= "npc_dota_hero_troll_warlord" then return end

    local swap = NPC.GetAbility(myHero, "troll_warlord_berserkers_rage")
    local axe_melee = NPC.GetAbility(myHero, "troll_warlord_whirling_axes_melee")
    local axe_ranged = NPC.GetAbility(myHero, "troll_warlord_whirling_axes_ranged")

    -- melee axe
    if Menu.IsKeyDownOnce(keyAxeMelee) and Ability.IsCastable(axe_melee, NPC.GetMana(myHero)) then
        if swap and not Ability.GetToggleState(swap) then
            Ability.Toggle(swap)
            Ability.CastNoTarget(axe_melee)
            Ability.Toggle(swap)
        else
            Ability.CastNoTarget(axe_melee)
        end
    end

    -- ranged axe
    if Menu.IsKeyDownOnce(keyAxeRanged) and Ability.IsCastable(axe_ranged, NPC.GetMana(myHero)) then
        if swap and Ability.GetToggleState(swap) then
            Ability.Toggle(swap)
            Ability.CastPosition(axe_ranged, Input.GetWorldCursorPos())
            Ability.Toggle(swap)
        else
            Ability.CastPosition(axe_ranged, Input.GetWorldCursorPos())
        end
    end
end

return Troll


text:
package org.apache.geode.management.internal.api;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import org.apache.geode.management.api.ClusterManagementService;
import org.apache.geode.management.api.ClusterManagementServiceTransport;
import org.apache.geode.management.api.ConnectionConfig;
import org.apache.geode.management.api.RestTemplateClusterManagementServiceTransport;
import org.apache.geode.management.internal.ClientClusterManagementService;

public abstract class BaseManagementServiceBuilder<T extends BaseManagementServiceBuilder<?>> {

  private ClusterManagementServiceTransport transport;

  private String username;
  private String password;
  private HostnameVerifier hostnameVerifier;
  private SSLContext sslContext;
  private String authToken;
  private Boolean followRedirects;

  /**
   * Build a new {@link ClusterManagementService} instance
   *
   * @return a ClusterManagementService
   */
  public ClusterManagementService build() {
    return new ClientClusterManagementService(configureTransport());
  }

  private ClusterManagementServiceTransport configureTransport() {
    if (transport == null) {
      ConnectionConfig connectionConfig = createConnectionConfig();
      connectionConfig = configureConnectionConfig(connectionConfig);
      return new RestTemplateClusterManagementServiceTransport(connectionConfig);
    }
    return transport;
  }

  @SuppressWarnings("unchecked")
  private T self() {
    return (T) this;
  }

  public T setTransport(ClusterManagementServiceTransport transport) {
    this.transport = transport;
    return self();
  }

  public T setAuthToken(String token) {
    authToken = token;
    return self();
  }

  public T setSslContext(SSLContext sslContext) {
    this.sslContext = sslContext;
    return self();
  }

  public T setUsername(String username) {
    this.username = username;
    return self();
  }

  public T setPassword(String password) {
    this.password = password;
    return self();
  }

  public T setHostnameVerifier(HostnameVerifier hostnameVerifier) {
    this.hostnameVerifier = hostnameVerifier;
    return self();
  }

  public T setFollowRedirects(boolean followRedirects) {
    this.followRedirects = followRedirects;
    return self();
  }

  protected abstract ConnectionConfig createConnectionConfig();

  protected ConnectionConfig configureConnectionConfig(ConnectionConfig newConnectionConfig) {
    if (authToken != null) {
      newConnectionConfig.setAuthToken(authToken);
    }
    if (followRedirects != null) {
      newConnectionConfig.setFollowRedirects(followRedirects);
    }
    if (hostnameVerifier != null) {
      newConnectionConfig.setHostnameVerifier(hostnameVerifier);
    }
    if (username != null) {
      newConnectionConfig.setUsername(username);
    }
    if (password != null) {
      newConnectionConfig.setPassword(password);
    }
    if (sslContext != null) {
      newConnectionConfig.setSslContext(sslContext);
    }
    return newConnectionConfig;
  }
}


text:
$.couch.app(function(app) {

  // setup the account widget
  $("#account").evently("account", app);

  $("#home").evently("home", app);
  $.evently.connect($("#account"), $("#home"), ["loggedIn", "loggedOut"]);
});


text:
@implementation RKHouse

@dynamic city;
@dynamic createdAt;
@dynamic ownerId;
@dynamic railsID;
@dynamic state;
@dynamic street;
@dynamic updatedAt;
@dynamic zip;

@end


text:
class CreateGacodes < ActiveRecord::Migration
  def change
    create_table :gacodes do |t|
			t.integer :user_id
			t.string :code
      t.timestamps
    end
		add_index :gacodes, :user_id
  end
end


text:
package com.alibaba.nacos.naming.core.v2.client.manager.impl;

import com.alibaba.nacos.api.remote.RemoteConstants;
import com.alibaba.nacos.core.remote.Connection;
import com.alibaba.nacos.core.remote.ConnectionMeta;
import com.alibaba.nacos.naming.consistency.ephemeral.distro.v2.DistroClientVerifyInfo;
import com.alibaba.nacos.naming.constants.ClientConstants;
import com.alibaba.nacos.naming.core.v2.client.ClientAttributes;
import com.alibaba.nacos.naming.core.v2.client.impl.ConnectionBasedClient;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.env.MockEnvironment;

import java.util.Collection;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class ConnectionBasedClientManagerTest {

    ConnectionBasedClientManager connectionBasedClientManager;

    private final String connectionId = System.currentTimeMillis() + "_127.0.0.1_80";

    @Mock
    private ConnectionBasedClient client;

    @Mock
    private Connection connection;

    @Mock
    private ConnectionMeta connectionMeta;

    @Mock
    private ClientAttributes clientAttributes;

    @BeforeClass
    public static void setUpBeforeClass() {
        EnvUtil.setEnvironment(new MockEnvironment());
    }

    @Before
    public void setUp() throws Exception {
        connectionBasedClientManager = new ConnectionBasedClientManager();
        when(client.isNative()).thenReturn(true);
        when(connectionMeta.getConnectionId()).thenReturn(connectionId);
        when(connection.getMetaInfo()).thenReturn(connectionMeta);
        when(connectionMeta.getLabel(RemoteConstants.LABEL_MODULE)).thenReturn(RemoteConstants.LABEL_MODULE_NAMING);

        when(clientAttributes.getClientAttribute(ClientConstants.REVISION, 0)).thenReturn(0);
        assertTrue(connectionBasedClientManager.syncClientConnected(connectionId, clientAttributes));
        assertTrue(connectionBasedClientManager.verifyClient(new DistroClientVerifyInfo(connectionId, 0)));
        connectionBasedClientManager.clientConnected(connection);

    }

    @Test
    public void testAllClientId() {
        Collection<String> allClientIds = connectionBasedClientManager.allClientId();
        assertEquals(1, allClientIds.size());
        assertTrue(connectionBasedClientManager.verifyClient(new DistroClientVerifyInfo(connectionId, 0)));
        assertTrue(allClientIds.contains(connectionId));
    }

    @Test
    public void testContainsConnectionId() {
        assertTrue(connectionBasedClientManager.verifyClient(new DistroClientVerifyInfo(connectionId, 0)));
        assertTrue(connectionBasedClientManager.contains(connectionId));
        String unUsedClientId = "127.0.0.1:8888#true";
        assertFalse(connectionBasedClientManager.verifyClient(new DistroClientVerifyInfo(unUsedClientId, 0)));
        assertFalse(connectionBasedClientManager.contains(unUsedClientId));
    }

    @Test
    public void testIsResponsibleClient() {
        assertTrue(connectionBasedClientManager.isResponsibleClient(client));
    }

    @After
    public void tearDown() {
        connectionBasedClientManager.clientDisConnected(connection);
    }
}


text:
package mysqlctl

import (
	"fmt"
	"regexp"
	"strings"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/vt/mysqlctl/proto"
)

var autoIncr = regexp.MustCompile(" AUTO_INCREMENT=\\d+")

// GetSchema returns the schema for database for tables listed in
// tables. If tables is empty, return the schema for all tables.
func (mysqld *Mysqld) GetSchema(dbName string, tables, excludeTables []string, includeViews bool) (*proto.SchemaDefinition, error) {
	sd := &proto.SchemaDefinition{}

	// get the database creation command
	qr, fetchErr := mysqld.fetchSuperQuery("SHOW CREATE DATABASE " + dbName)
	if fetchErr != nil {
		return nil, fetchErr
	}
	if len(qr.Rows) == 0 {
		return nil, fmt.Errorf("empty create database statement for %v", dbName)
	}
	sd.DatabaseSchema = strings.Replace(qr.Rows[0][1].String(), "`"+dbName+"`", "`{{.DatabaseName}}`", 1)

	// build a list of regexp to match table names against
	var tableRegexps []*regexp.Regexp
	if len(tables) > 0 {
		tableRegexps = make([]*regexp.Regexp, len(tables))
		for i, table := range tables {
			var err error
			tableRegexps[i], err = regexp.Compile(table)
			if err != nil {
				return nil, fmt.Errorf("cannot compile regexp %v for table: %v", table, err)
			}
		}
	}
	var excludeTableRegexps []*regexp.Regexp
	if len(excludeTables) > 0 {
		excludeTableRegexps = make([]*regexp.Regexp, len(excludeTables))
		for i, table := range excludeTables {
			var err error
			excludeTableRegexps[i], err = regexp.Compile(table)
			if err != nil {
				return nil, fmt.Errorf("cannot compile regexp %v for excludeTable: %v", table, err)
			}
		}
	}

	// get the list of tables we're interested in
	sql := "SELECT table_name, table_type, data_length, table_rows FROM information_schema.tables WHERE table_schema = '" + dbName + "'"
	if !includeViews {
		sql += " AND table_type = '" + proto.TABLE_BASE_TABLE + "'"
	}
	qr, err := mysqld.fetchSuperQuery(sql)
	if err != nil {
		return nil, err
	}
	if len(qr.Rows) == 0 {
		return sd, nil
	}

	sd.TableDefinitions = make([]proto.TableDefinition, 0, len(qr.Rows))
	for _, row := range qr.Rows {
		tableName := row[0].String()
		tableType := row[1].String()

		// check it's a table we want
		if tableRegexps != nil {
			foundMatch := false
			for _, tableRegexp := range tableRegexps {
				if tableRegexp.Match(row[0].Raw()) {
					foundMatch = true
					break
				}
			}
			if !foundMatch {
				continue
			}
		}
		foundMatch := false
		for _, tableRegexp := range excludeTableRegexps {
			if tableRegexp.Match(row[0].Raw()) {
				foundMatch = true
				break
			}
		}
		if foundMatch {
			continue
		}

		// compute dataLength
		var dataLength uint64
		if !row[2].IsNull() {
			// dataLength is NULL for views, then we use 0
			dataLength, err = row[2].ParseUint64()
			if err != nil {
				return nil, err
			}
		}

		// get row count
		var rowCount uint64
		if !row[3].IsNull() {
			rowCount, err = row[3].ParseUint64()
			if err != nil {
				return nil, err
			}
		}

		qr, fetchErr := mysqld.fetchSuperQuery("SHOW CREATE TABLE " + dbName + "." + tableName)
		if fetchErr != nil {
			return nil, fetchErr
		}
		if len(qr.Rows) == 0 {
			return nil, fmt.Errorf("empty create table statement for %v", tableName)
		}

		// Normalize & remove auto_increment because it changes on every insert
		// FIXME(alainjobart) find a way to share this with
		// vt/tabletserver/table_info.go:162
		norm := qr.Rows[0][1].String()
		norm = autoIncr.ReplaceAllLiteralString(norm, "")
		if tableType == proto.TABLE_VIEW {
			// Views will have the dbname in there, replace it
			// with {{.DatabaseName}}
			norm = strings.Replace(norm, "`"+dbName+"`", "`{{.DatabaseName}}`", -1)
		}

		td := proto.TableDefinition{}
		td.Name = tableName
		td.Schema = norm

		td.Columns, err = mysqld.GetColumns(dbName, tableName)
		if err != nil {
			return nil, err
		}
		td.PrimaryKeyColumns, err = mysqld.GetPrimaryKeyColumns(dbName, tableName)
		if err != nil {
			return nil, err
		}
		td.Type = tableType
		td.DataLength = dataLength
		td.RowCount = rowCount
		sd.TableDefinitions = append(sd.TableDefinitions, td)
	}

	sd.GenerateSchemaVersion()
	return sd, nil
}

// ResolveTables returns a list of actual tables+views matching a list
// of regexps
func (mysqld *Mysqld) ResolveTables(dbName string, tables []string) ([]string, error) {
	sd, err := mysqld.GetSchema(dbName, tables, nil, true)
	if err != nil {
		return nil, err
	}
	result := make([]string, len(sd.TableDefinitions))
	for i, td := range sd.TableDefinitions {
		result[i] = td.Name
	}
	return result, nil
}

// GetColumns returns the columns of table.
func (mysqld *Mysqld) GetColumns(dbName, table string) ([]string, error) {
	conn, err := mysqld.dbaPool.Get()
	if err != nil {
		return nil, err
	}
	defer conn.Recycle()
	qr, err := conn.ExecuteFetch(fmt.Sprintf("select * from %v.%v where 1=0", dbName, table), 0, true)
	if err != nil {
		return nil, err
	}
	columns := make([]string, len(qr.Fields))
	for i, field := range qr.Fields {
		columns[i] = field.Name
	}
	return columns, nil

}

// GetPrimaryKeyColumns returns the primary key columns of table.
func (mysqld *Mysqld) GetPrimaryKeyColumns(dbName, table string) ([]string, error) {
	conn, err := mysqld.dbaPool.Get()
	if err != nil {
		return nil, err
	}
	defer conn.Recycle()
	qr, err := conn.ExecuteFetch(fmt.Sprintf("show index from %v.%v", dbName, table), 100, true)
	if err != nil {
		return nil, err
	}
	keyNameIndex := -1
	seqInIndexIndex := -1
	columnNameIndex := -1
	for i, field := range qr.Fields {
		switch field.Name {
		case "Key_name":
			keyNameIndex = i
		case "Seq_in_index":
			seqInIndexIndex = i
		case "Column_name":
			columnNameIndex = i
		}
	}
	if keyNameIndex == -1 || seqInIndexIndex == -1 || columnNameIndex == -1 {
		return nil, fmt.Errorf("Unknown columns in 'show index' result: %v", qr.Fields)
	}

	columns := make([]string, 0, 5)
	var expectedIndex int64 = 1
	for _, row := range qr.Rows {
		// skip non-primary keys
		if row[keyNameIndex].String() != "PRIMARY" {
			continue
		}

		// check the Seq_in_index is always increasing
		seqInIndex, err := row[seqInIndexIndex].ParseInt64()
		if err != nil {
			return nil, err
		}
		if seqInIndex != expectedIndex {
			return nil, fmt.Errorf("Unexpected index: %v != %v", seqInIndex, expectedIndex)
		}
		expectedIndex++

		columns = append(columns, row[columnNameIndex].String())
	}
	return columns, err
}

// PreflightSchemaChange will apply the schema change to a fake
// database that has the same schema as the target database, see if it
// works.
func (mysqld *Mysqld) PreflightSchemaChange(dbName string, change string) (*proto.SchemaChangeResult, error) {
	// gather current schema on real database
	beforeSchema, err := mysqld.GetSchema(dbName, nil, nil, true)
	if err != nil {
		return nil, err
	}

	// populate temporary database with it
	sql := "SET sql_log_bin = 0;\n"
	sql += "DROP DATABASE IF EXISTS _vt_preflight;\n"
	sql += "CREATE DATABASE _vt_preflight;\n"
	sql += "USE _vt_preflight;\n"
	for _, td := range beforeSchema.TableDefinitions {
		if td.Type == proto.TABLE_BASE_TABLE {
			sql += td.Schema + ";\n"
		}
	}
	if err = mysqld.ExecuteMysqlCommand(sql); err != nil {
		return nil, err
	}

	// apply schema change to the temporary database
	sql = "SET sql_log_bin = 0;\n"
	sql += "USE _vt_preflight;\n"
	sql += change
	if err = mysqld.ExecuteMysqlCommand(sql); err != nil {
		return nil, err
	}

	// get the result
	afterSchema, err := mysqld.GetSchema("_vt_preflight", nil, nil, true)
	if err != nil {
		return nil, err
	}

	// and clean up the extra database
	sql = "SET sql_log_bin = 0;\n"
	sql += "DROP DATABASE _vt_preflight;\n"
	if err = mysqld.ExecuteMysqlCommand(sql); err != nil {
		return nil, err
	}

	return &proto.SchemaChangeResult{beforeSchema, afterSchema}, nil
}

// ApplySchemaChange will apply the schema change to the given database.
func (mysqld *Mysqld) ApplySchemaChange(dbName string, change *proto.SchemaChange) (*proto.SchemaChangeResult, error) {
	// check current schema matches
	beforeSchema, err := mysqld.GetSchema(dbName, nil, nil, false)
	if err != nil {
		return nil, err
	}
	if change.BeforeSchema != nil {
		schemaDiffs := proto.DiffSchemaToArray("actual", beforeSchema, "expected", change.BeforeSchema)
		if len(schemaDiffs) > 0 {
			for _, msg := range schemaDiffs {
				log.Warningf("BeforeSchema differs: %v", msg)
			}

			// let's see if the schema was already applied
			if change.AfterSchema != nil {
				schemaDiffs = proto.DiffSchemaToArray("actual", beforeSchema, "expected", change.AfterSchema)
				if len(schemaDiffs) == 0 {
					// no diff between the schema we expect
					// after the change and the current
					// schema, we already applied it
					return &proto.SchemaChangeResult{beforeSchema, beforeSchema}, nil
				}
			}

			if change.Force {
				log.Warningf("BeforeSchema differs, applying anyway")
			} else {
				return nil, fmt.Errorf("BeforeSchema differs")
			}
		}
	}

	sql := change.Sql
	if !change.AllowReplication {
		sql = "SET sql_log_bin = 0;\n" + sql
	}

	// add a 'use XXX' in front of the SQL
	sql = "USE " + dbName + ";\n" + sql

	// execute the schema change using an external mysql process
	// (to benefit from the extra commands in mysql cli)
	if err = mysqld.ExecuteMysqlCommand(sql); err != nil {
		return nil, err
	}

	// get AfterSchema
	afterSchema, err := mysqld.GetSchema(dbName, nil, nil, false)
	if err != nil {
		return nil, err
	}

	// compare to the provided AfterSchema
	if change.AfterSchema != nil {
		schemaDiffs := proto.DiffSchemaToArray("actual", afterSchema, "expected", change.AfterSchema)
		if len(schemaDiffs) > 0 {
			for _, msg := range schemaDiffs {
				log.Warningf("AfterSchema differs: %v", msg)
			}
			if change.Force {
				log.Warningf("AfterSchema differs, not reporting error")
			} else {
				return nil, fmt.Errorf("AfterSchema differs")
			}
		}
	}

	return &proto.SchemaChangeResult{beforeSchema, afterSchema}, nil
}


text:
import json

from django.conf import settings
from django.shortcuts import redirect

from site_config.site_config import SiteConfig

class SiteMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        host = request.GET.get("_hostname", request.META.get("HTTP_HOST"))
        if host:
            host = host.casefold()
        host_config = HOSTNAMES.get(host)

        if not host_config:
            if settings.SITE_REDIRECT:
                return redirect("{scheme}://{host}{path}".format(
                    scheme=request.scheme,
                    host=DEFAULT_CONFIG.hostname,
                    path=request.get_full_path()
                ))
            else:
                host_config = DEFAULT_CONFIG
        request.urlconf = host_config.urlconf
        request.site_config = host_config
        request.site_hostname = host
        request.site_name = host_config.hostname

        return self.get_response(request)

def context_processor(request):
    if request.site_config:
        js_config = request.site_config.js_config
        context = {"site_config": json.dumps(js_config),
                   "hostname": request.site_hostname,
                   "logo_text": request.site_config.logo_text}
        context.update(request.site_config.extra_context)
        return context

    return {}

def site_config(site_name) -> SiteConfig:
    return HOSTNAMES.get(site_name, DEFAULT_CONFIG)

by_hostname = site_config

def by_name(name: str) -> SiteConfig:
    return NAMES.get(name.lower())

def base_url(site_name):
    return site_config(site_name).hostname

# Maps module hostnames to their configuration.
DEFAULT_CONFIG = None
HOSTNAMES = {}
NAMES = {}

def find_site_configurations():
    from importlib import import_module

    configs = getattr(settings, "SITE_CONFIG", {})
    for name, config_dict in configs.items():
        site_module = import_module(config_dict["module"])
        config = getattr(site_module, "SITE_CONFIG", None)
        if config:
            if "hostnames" in config_dict:
                config.hostnames = config_dict["hostnames"]
            add_configuration(config, site_module, name)

def add_configuration(config: SiteConfig, module, name):
    hostnames = config.hostnames
    if not hostnames:
        raise Exception(
            f"Site configuration '{name}' must have at least one hostname")

    NAMES[config.name.lower()] = config

    for hostname in hostnames:
        if hostname == "default":
            global DEFAULT_CONFIG
            DEFAULT_CONFIG = config
            continue
        if hostname not in HOSTNAMES:
            HOSTNAMES[hostname] = config
        else:
            return False

    return True

find_site_configurations()


text:
'use strict';

let getPage = (caseData, startPageUrl) => {
    let info = caseData.data.info;
    let first = null;
    for (let name in info) {
        first = info[name];
        break;
    }
    for (let i = 0; i < first.length; i++) {
        let item = first[i];
        if(item.url !== startPageUrl) {
            continue;
        }
        let requestHeaders = item.requestHeaders;
        for (let j = 0; j < requestHeaders.length; j++) {
            let headerItem = requestHeaders[j];
            if (headerItem.name === 'Accept' && headerItem.value.indexOf('text/html,application/xhtml+xml,application/xml') === 0) {
                return item;
            }
        }
    }

    throw new Error('fail to find page');
};

module.exports = {
    getPage
};


text:
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Newtonsoft.Json;
using Wox.Infrastructure.Storage;
using Wox.Plugin;

namespace Wox.Storage
{
    public class UserSelectedRecordStorage : JsonStrorage<UserSelectedRecordStorage>
    {
        [JsonProperty]
        private Dictionary<string, int> records = new Dictionary<string, int>();

        protected override string FileName { get; } = "UserSelectedRecords";

        public void Add(Result result)
        {
            if (records.ContainsKey(result.ToString()))
            {
                records[result.ToString()] += 1;
            }
            else
            {
                records.Add(result.ToString(), 1);
            }
            Save();
        }

        public int GetSelectedCount(Result result)
        {
            if (records.ContainsKey(result.ToString()))
            {
                return records[result.ToString()];
            }
            return 0;
        }
    }
}


text:
from __future__ import unicode_literals
from __future__ import absolute_import
from .packages.docker.client import APIError
import logging
import re
import os
import sys
from .container import Container

log = logging.getLogger(__name__)

DOCKER_CONFIG_KEYS = ['image', 'command', 'hostname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'volumes_from', 'entrypoint', 'privileged']
DOCKER_CONFIG_HINTS = {
    'link'      : 'links',
    'port'      : 'ports',
    'privilege' : 'privileged',
    'priviliged': 'privileged',
    'privilige' : 'privileged',
    'volume'    : 'volumes',
}

class BuildError(Exception):
    pass

class CannotBeScaledError(Exception):
    pass

class ConfigError(ValueError):
    pass

class Service(object):
    def __init__(self, name, client=None, project='default', links=[], **options):
        if not re.match('^[a-zA-Z0-9]+$', name):
            raise ConfigError('Invalid name: %s' % name)
        if not re.match('^[a-zA-Z0-9]+$', project):
            raise ConfigError('Invalid project: %s' % project)
        if 'image' in options and 'build' in options:
            raise ConfigError('Service %s has both an image and build path specified. A service can either be built to image or use an existing image, not both.' % name)

        supported_options = DOCKER_CONFIG_KEYS + ['build', 'expose']

        for k in options:
            if k not in supported_options:
                msg = "Unsupported config option for %s service: '%s'" % (name, k)
                if k in DOCKER_CONFIG_HINTS:
                    msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
                raise ConfigError(msg)

        self.name = name
        self.client = client
        self.project = project
        self.links = links or []
        self.options = options

    def containers(self, stopped=False, one_off=False):
        l = []
        for container in self.client.containers(all=stopped):
            name = get_container_name(container)
            if not name or not is_valid_name(name, one_off):
                continue
            project, name, number = parse_name(name)
            if project == self.project and name == self.name:
                l.append(Container.from_ps(self.client, container))
        return l

    def start(self, **options):
        for c in self.containers(stopped=True):
            if not c.is_running:
                log.info("Starting %s..." % c.name)
                self.start_container(c, **options)

    def stop(self, **options):
        for c in self.containers():
            log.info("Stopping %s..." % c.name)
            c.stop(**options)

    def kill(self, **options):
        for c in self.containers():
            log.info("Killing %s..." % c.name)
            c.kill(**options)

    def scale(self, desired_num):
        if not self.can_be_scaled():
            raise CannotBeScaledError()

        # Create enough containers
        containers = self.containers(stopped=True)
        while len(containers) < desired_num:
            containers.append(self.create_container())

        running_containers = []
        stopped_containers = []
        for c in containers:
            if c.is_running:
                running_containers.append(c)
            else:
                stopped_containers.append(c)
        running_containers.sort(key=lambda c: c.number)
        stopped_containers.sort(key=lambda c: c.number)

        # Stop containers
        while len(running_containers) > desired_num:
            c = running_containers.pop()
            log.info("Stopping %s..." % c.name)
            c.stop(timeout=1)
            stopped_containers.append(c)

        # Start containers
        while len(running_containers) < desired_num:
            c = stopped_containers.pop(0)
            log.info("Starting %s..." % c.name)
            self.start_container(c)
            running_containers.append(c)

    def remove_stopped(self, **options):
        for c in self.containers(stopped=True):
            if not c.is_running:
                log.info("Removing %s..." % c.name)
                c.remove(**options)

    def create_container(self, one_off=False, **override_options):
        """
        Create a container for this service. If the image doesn't exist, attempt to pull
        it.
        """
        container_options = self._get_container_create_options(override_options, one_off=one_off)
        try:
            return Container.create(self.client, **container_options)
        except APIError as e:
            if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
                log.info('Pulling image %s...' % container_options['image'])
                self.client.pull(container_options['image'])
                return Container.create(self.client, **container_options)
            raise

    def recreate_containers(self, **override_options):
        """
        If a container for this service doesn't exist, create one. If there are
        any, stop them and create new ones. Does not remove the old containers.
        """
        containers = self.containers(stopped=True)

        if len(containers) == 0:
            log.info("Creating %s..." % self.next_container_name())
            return ([], [self.create_container(**override_options)])
        else:
            old_containers = []
            new_containers = []

            for c in containers:
                log.info("Recreating %s..." % c.name)
                (old_container, new_container) = self.recreate_container(c, **override_options)
                old_containers.append(old_container)
                new_containers.append(new_container)

            return (old_containers, new_containers)

    def recreate_container(self, container, **override_options):
        if container.is_running:
            container.stop(timeout=1)

        intermediate_container = Container.create(
            self.client,
            image=container.image,
            volumes_from=container.id,
            entrypoint=['echo'],
            command=[],
        )
        intermediate_container.start()
        intermediate_container.wait()
        container.remove()

        options = dict(override_options)
        options['volumes_from'] = intermediate_container.id
        new_container = self.create_container(**options)

        return (intermediate_container, new_container)

    def start_container(self, container=None, **override_options):
        if container is None:
            container = self.create_container(**override_options)

        options = self.options.copy()
        options.update(override_options)

        port_bindings = {}

        if options.get('ports', None) is not None:
            for port in options['ports']:
                port = str(port)
                if ':' in port:
                    external_port, internal_port = port.split(':', 1)
                else:
                    external_port, internal_port = (None, port)

                port_bindings[internal_port] = external_port

        volume_bindings = {}

        if options.get('volumes', None) is not None:
            for volume in options['volumes']:
                if ':' in volume:
                    external_dir, internal_dir = volume.split(':')
                    volume_bindings[os.path.abspath(external_dir)] = internal_dir

        privileged = options.get('privileged', False)

        container.start(
            links=self._get_links(link_to_self=override_options.get('one_off', False)),
            port_bindings=port_bindings,
            binds=volume_bindings,
            privileged=privileged,
        )
        return container

    def next_container_name(self, one_off=False):
        bits = [self.project, self.name]
        if one_off:
            bits.append('run')
        return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])

    def next_container_number(self, one_off=False):
        numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]

        if len(numbers) == 0:
            return 1
        else:
            return max(numbers) + 1

    def _get_links(self, link_to_self):
        links = []
        for service, link_name in self.links:
            for container in service.containers():
                if link_name:
                    links.append((container.name, link_name))
                links.append((container.name, container.name))
                links.append((container.name, container.name_without_project))
        if link_to_self:
            for container in self.containers():
                links.append((container.name, container.name))
                links.append((container.name, container.name_without_project))
        return links

    def _get_container_create_options(self, override_options, one_off=False):
        container_options = dict((k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options)
        container_options.update(override_options)

        container_options['name'] = self.next_container_name(one_off)

        if 'ports' in container_options or 'expose' in self.options:
            ports = []
            all_ports = container_options.get('ports', []) + self.options.get('expose', [])
            for port in all_ports:
                port = str(port)
                if ':' in port:
                    port = port.split(':')[-1]
                if '/' in port:
                    port = tuple(port.split('/'))
                ports.append(port)
            container_options['ports'] = ports

        if 'volumes' in container_options:
            container_options['volumes'] = dict((split_volume(v)[1], {}) for v in container_options['volumes'])

        if self.can_be_built():
            if len(self.client.images(name=self._build_tag_name())) == 0:
                self.build()
            container_options['image'] = self._build_tag_name()

        # Priviliged is only required for starting containers, not for creating them
        if 'privileged' in container_options:
            del container_options['privileged']

        return container_options

    def build(self):
        log.info('Building %s...' % self.name)

        build_output = self.client.build(
            self.options['build'],
            tag=self._build_tag_name(),
            stream=True
        )

        image_id = None

        for line in build_output:
            if line:
                match = re.search(r'Successfully built ([0-9a-f]+)', line)
                if match:
                    image_id = match.group(1)
            sys.stdout.write(line)

        if image_id is None:
            raise BuildError()

        return image_id

    def can_be_built(self):
        return 'build' in self.options

    def _build_tag_name(self):
        """
        The tag to give to images built for this service.
        """
        return '%s_%s' % (self.project, self.name)

    def can_be_scaled(self):
        for port in self.options.get('ports', []):
            if ':' in str(port):
                return False
        return True

NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')

def is_valid_name(name, one_off=False):
    match = NAME_RE.match(name)
    if match is None:
        return False
    if one_off:
        return match.group(3) == 'run_'
    else:
        return match.group(3) is None

def parse_name(name, one_off=False):
    match = NAME_RE.match(name)
    (project, service_name, _, suffix) = match.groups()
    return (project, service_name, int(suffix))

def get_container_name(container):
    if not container.get('Name') and not container.get('Names'):
        return None
    # inspect
    if 'Name' in container:
        return container['Name']
    # ps
    for name in container['Names']:
        if len(name.split('/')) == 2:
            return name[1:]

def split_volume(v):
    """
    If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
    If v is of the format INTERNAL, returns (None, INTERNAL).
    """
    if ':' in v:
        return v.split(':', 1)
    else:
        return (None, v)


text:
#include <osapi.h>
#include <os_type.h>
#include "user_interface.h"
#include <espconn.h>
#include <mem.h>
#include "cloud/data.h"

char *_miid;
char *_security;

ip_addr_t dummy_ip;
int _active = 0;

typedef struct {
	char *buf;
	http_response_callback cb;
	void *cb_arg;
} HttpReq;

char * ICACHE_FLASH_ATTR http_parse_response(char *pdata, int *status)
{
	char *lenStr = strstr(pdata, "\r\n\r\n");
	if (lenStr != NULL)
	{
		char *lenStrEnd = strstr(lenStr+4, "\r\n");
		if (lenStrEnd != NULL)
		{
			int len = strtol(lenStr+4, NULL, 16);
			char *code = lenStrEnd+2;
			*(code+len) = 0;
			DEBUG_MSG("http resp(len=%d):\n%s\n", len, code);
			*status = 200; //TODO:
			return code;
		}
		else
		{
			__printf("parse http response err1\n");
		}
	}
	else
	{
		__printf("parse http response err2: %s\n", pdata);
	}
	*status = -1;
	return NULL;
}

/**
  * @brief  Client received callback function.
  * @param  arg: contain the ip link information
  * @param  pdata: received data
  * @param  len: the lenght of received data
  * @retval None
  */
static void ICACHE_FLASH_ATTR cloud_data_on_recv_cb(void *arg, char *pdata, unsigned short len)
{
	struct espconn *pConn = (struct espconn *)arg;

	int status = -1;
	char *res = http_parse_response(pdata, &status);

	HttpReq *req = pConn->reverse;
	if (req->cb)
	{
		req->cb(status, res, req->cb_arg);
		req->cb = NULL;
	}

	//TODO: concat more then one package
	espconn_disconnect(pConn);
}

/**
  * @brief  Tcp client disconnect success callback function.
  * @param  arg: contain the ip link information
  * @retval None
  */
static void ICACHE_FLASH_ATTR cloud_data_on_discon_cb(void *arg)
{
    struct espconn *pConn = (struct espconn *)arg;

	HttpReq *req = pConn->reverse;

	if (req->cb)
	{
		req->cb(-1, NULL, req->cb_arg);
		req->cb = NULL;
	}

	os_free(req->buf);
	os_free(req);
	os_free(pConn->proto.tcp);
	os_free(pConn);
	_active --;

    DEBUG_MSG("tcp client disconnect(active=%d)\n", _active);
}

static void ICACHE_FLASH_ATTR cloud_data_on_recon_cb(void *arg, sint8 errType)
{
    struct espconn *pConn = (struct espconn *)arg;

    DEBUG_MSG("tcp client reconnect\n");
}

/**
  * @brief  Tcp client connect success callback function.
  * @param  arg: contain the ip link information
  * @retval None
  */
static void ICACHE_FLASH_ATTR cloud_data_on_connect_cb(void *arg)
{
    struct espconn *pConn = (struct espconn *)arg;
	HttpReq *req = pConn->reverse;

    DEBUG_MSG("tcp client connect\n");

    espconn_regist_disconcb(pConn, cloud_data_on_discon_cb);
    espconn_regist_recvcb(pConn, cloud_data_on_recv_cb);////////
    //espconn_regist_sentcb(pConn, tcpclient_sent_cb);///////

	espconn_sent(pConn, req->buf, os_strlen(req->buf));
}

static void ICACHE_FLASH_ATTR cloud_data_on_dns_found(const char *host, ip_addr_t *ipaddr, void *arg)
{
    struct espconn *pespconn = (struct espconn *)arg;
    if (ipaddr != NULL)
    {
        char buf[16];
        char *p = (char*)&(ipaddr->addr);
        os_memcpy(pespconn->proto.tcp->remote_ip, &(ipaddr->addr), 4);
		_active ++;
        DEBUG_MSG("connection to "IPSTR"...(active=%d)\n", p[0], p[1], p[2], p[3], _active);

        espconn_connect(pespconn);
    }
	else
	{
		__printf("dns failed!\n");
		espconn_gethostbyname(pespconn, host, &dummy_ip, cloud_data_on_dns_found);
	}
}

void ICACHE_FLASH_ATTR http_get (const char *host, char *send, http_response_callback cb, void *cb_arg)
{
	struct espconn *pFetchConn;

	HttpReq *req = (HttpReq*)os_malloc(sizeof(HttpReq));
	req->buf = (char *)os_malloc(os_strlen(send)+1);
	os_strcpy(req->buf, send);
	req->cb = cb;
	req->cb_arg = cb_arg;

    pFetchConn = (struct espconn *)os_zalloc(sizeof(struct espconn));
	pFetchConn->reverse = req;
    pFetchConn->type = ESPCONN_TCP;
    pFetchConn->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));

    pFetchConn->proto.tcp->local_port = espconn_port();

    espconn_regist_connectcb(pFetchConn, cloud_data_on_connect_cb);
    espconn_regist_reconcb(pFetchConn, cloud_data_on_recon_cb);
    pFetchConn->proto.tcp->remote_port = 80;
    espconn_gethostbyname(pFetchConn, host, &dummy_ip, cloud_data_on_dns_found);
}

void ICACHE_FLASH_ATTR cloud_data_append (const char *cloudid, const char *v0, const char *v1, const char *v2, http_response_callback cb, void *cb_arg)
{
	char buf0[512], buf1[512];
	os_sprintf(buf1, CLOUD_APPEND_URL, _miid, _security, cloudid, v0, v1, v2);
	os_sprintf(buf0, HTTP_QUERY, buf1);

	http_get(CLOUD_HOST, buf0, cb, cb_arg);
}


text:
module.exports = function(server){
    var router = server.middleware.router();

    var app = require('./enterprise');

    /* 商户账号部分 */
    router.get('ent_account_login', 'account/login',  app.account.login.get);
    router.post('ent_account_login_check', 'account/login/check', app.account.login.post);
    router.get('ent_account_register', 'account/register', app.account.register.get);
    router.post('ent_account_register_save', 'account/register/save', app.account.register.post);
    router.get('ent_account_space_enterprise_list', 'account/space/enterprise_list', app.account.space.enterprise_list.get);
    router.post('ent_account_space_enterprise_list', 'account/space/enterprise_list', app.account.space.enterprise_list.post);
    /* 商户管理面板 -- 详情模块 */
    router.get('ent_board_profile', ':eid/dashboard/profile', app.dashboard.profile.index.get);
    /* 商户管理面板 -- 设置模块 */
    router.get('ent_board_settings_info', ':eid/dashboard/settings/info', app.dashboard.settings.info.view.get);
    router.post('ent_board_settings_info', ':eid/dashboard/settings/info', app.dashboard.settings.info.view.post);
    router.post('ent_board_settings_info_save', ':eid/dashboard/settings/info/save', app.dashboard.settings.info.save);
    router.get('ent_board_settings_store_list', ':eid/dashboard/settings/store/list', app.dashboard.settings.store.list.get);
    router.post('ent_board_settings_store_list', ':eid/dashboard/settings/store/list', app.dashboard.settings.store.list.post);
    router.get('ent_board_settings_store_new', ':eid/dashboard/settings/store/new', app.dashboard.settings.store.new.get);
    router.post('ent_board_settings_store_new', ':eid/dashboard/settings/store/new', app.dashboard.settings.store.new.post);
    router.post('ent_board_settings_store_new_get_citys_list', ':eid/dashboard/settings/store/new/get/citys_list', app.dashboard.settings.store.new.citys_list);
    router.get('ent_board_settings_store_edit', ':eid/dashboard/settings/store/edit', app.dashboard.settings.store.edit.get);
    router.post('ent_board_settings_store_edit', ':eid/dashboard/settings/store/edit', app.dashboard.settings.store.edit.post);
    router.post('ent_board_settings_store_edit_save', ':eid/dashboard/settings/store/edit/save', app.dashboard.settings.store.edit.save);
    /* 商户管理面板 -- 会员模块 */
    router.get('ent_board_vip_member_vipcard', ':eid/dashboard/vip_member/vipcard/index', app.dashboard.vip_member.vipcard.index.get);
    router.get('ent_board_vip_member_vipcard_edit', ':eid/dashboard/vip_member/vipcard/edit', app.dashboard.vip_member.vipcard.edit.get);
    router.post('ent_board_vip_member_vipcard_edit', ':eid/dashboard/vip_member/vipcard/edit', app.dashboard.vip_member.vipcard.edit.post);
    router.post('ent_board_vip_member_vipcard_edit_save', ':eid/dashboard/vip_member/vipcard/edit/save', app.dashboard.vip_member.vipcard.edit.save);
    router.get('ent_board_vip_member_vipcard_manage', ':eid/dashboard/vip_member/vipcard/manage', app.dashboard.vip_member.vipcard.manage.get);
    router.post('ent_board_vip_member_vipcard_manage', ':eid/dashboard/vip_member/vipcard/manage', app.dashboard.vip_member.vipcard.manage.post);
    router.get('ent_board_vip_member_vipmanage', ':eid/dashboard/vip_member/vipmanage/list', app.dashboard.vip_member.vipmanage.list.get);
    router.post('ent_board_vip_member_vipmanage', ':eid/dashboard/vip_member/vipmanage/list', app.dashboard.vip_member.vipmanage.list.post);
    router.get('ent_board_vip_member_vipmanage_details', ':eid/dashboard/vip_member/vipmanage/details', app.dashboard.vip_member.vipmanage.details.get);
    router.get('ent_board_vip_member_vipmember_edit', ':eid/dashboard/vip_member/vipmember/edit', app.dashboard.vip_member.vipmember.edit.get);
    router.get('ent_board_vip_member_vipmember_recordsPay', ':eid/dashboard/vip_member/vipmember/recordsPay', app.dashboard.vip_member.vipmember.recordsPay.get);
    router.get('ent_board_vip_member_vipmember_recordsRech', ':eid/dashboard/vip_member/vipmember/recordsRech', app.dashboard.vip_member.vipmember.recordsRech.get);
    router.get('ent_board_vip_member_vipmember_recordsBuy', ':eid/dashboard/vip_member/vipmember/recordsBuy', app.dashboard.vip_member.vipmember.recordsBuy.get);
    router.get('ent_board_vip_member_vipmember_recordsInte', ':eid/dashboard/vip_member/vipmember/recordsInte', app.dashboard.vip_member.vipmember.recordsInte.get);
    router.get('ent_board_vip_member_vipmember_recordsCancel', ':eid/dashboard/vip_member/vipmember/recordsCancel', app.dashboard.vip_member.vipmember.recordsCancel.get);
    router.get('ent_board_vip_member_vipmember_recordsGift', ':eid/dashboard/vip_member/vipmember/recordsGift', app.dashboard.vip_member.vipmember.recordsGift.get);
    router.get('ent_board_vip_member_viplabel', ':eid/dashboard/vip_member/viplabel/manage', app.dashboard.vip_member.viplabel.manage.get);
    router.get('ent_board_vip_member_viplabel_divide', ':eid/dashboard/vip_member/viplabel/divide', app.dashboard.vip_member.viplabel.divide.get);
    router.get('ent_board_vip_member_viplabel_new', ':eid/dashboard/vip_member/viplabel/new', app.dashboard.vip_member.viplabel.new.get);
    router.get('ent_board_vip_member_viplevel', ':eid/dashboard/vip_member/viplevel/type', app.dashboard.vip_member.viplevel.type.get);
    router.get('ent_board_vip_member_viplevel_settings', ':eid/dashboard/vip_member/viplevel/settings', app.dashboard.vip_member.viplevel.settings.get);

    // 注册简单数据访问协议中间件
    router.use(server.library.general.simple_data_access_protocol);
    // RESTful 信息反馈中间件
    router.use(server.library.general.restful);
    // 注册模板渲染器到上下文
    router.use(server.library.general.render(server));
    // 注册post数据解析
    router.use(server.middleware.postbody());
    // 注册post表单验证转义中间件
    router.use(server.library.general.parse_post);
    // 注册登录信息获取中间件
    router.use(server.library.general.session_manager);
    // 错误页中间件
    router.use(server.library.general.error_page);
    // 商家信息中间件
    router.use(server.library.enterprise.info_provider);
    // 注册微信接口通用交互中间件
    router.use(server.library.wechat.networkProvider);
    // 微信公众平台信息中间
    router.use(server.library.wechat.mpInfoProvider);

    return router;
};


text:
/**
 * Created by zhuzhipeng on 16/3/12.
 */
'use strict';

const express     = require('express');
const usersRouter = new express.Router();
const api         = require('../../api');

usersRouter.get('/list', api.UsersApi.getUsersListIF);

usersRouter.get('/verify', api.UsersApi.getVerifyUserIF);

usersRouter.get('/search', api.UsersApi.searchUsersIF);

module.exports = usersRouter;


text:
namespace Zu.ChromeDevTools.HeadlessExperimental
{
    using Newtonsoft.Json;

    /// <summary>
    /// Disables headless events for the target.
    /// </summary>
    public sealed class DisableCommand : ICommand
    {
        private const string ChromeRemoteInterface_CommandName = "HeadlessExperimental.disable";

        [JsonIgnore]
        public string CommandName
        {
            get { return ChromeRemoteInterface_CommandName; }
        }

    }

    public sealed class DisableCommandResponse : ICommandResponse<DisableCommand>
    {
    }
}


text:
package com.home.amngomes.controller;

public class Constants {

    public static String DATA_FILE_EXTENSION = ".txt";

    public interface Bundle{
        String  SERVER = "server";
    }
}


text:
$(document).ready(function() {
  // This is called after the document has loaded in its entirety
  // This guarantees that any elements we bind to will exist on the page
  // when we try to bind to them

  // See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
  $('.upload-photo').on('submit', function(e){
  	e.preventDefault();
  	var path = $(this).attr('action')
  	console.log(path)
  	// var imageLink = $('.upload-photo input[type="text"]').val()
  	// console.log(imageLink)
  	var imagedata = $(this).serialize();
  	console.log(imagedata)
  	 $.ajax({
  		url: path,
  		type:"POST",
  		data: imagedata,
  		dataType: "json"
  	}).done(function(response){
  		console.log("success")
  		$('.user-photos').append(response)
  		$('.no-photo-msg').remove()
  		$('.upload-photo.row input[type="text"]').val("")
  		// console.log(response)
  	}).fail(function(response){
  		console.log("failure")
  	})
  })

  $('.delete-message-button').on('click', function(e){
      e.preventDefault();
      var msgToDelete = $(this).parent();
      var path = $(this).parent().attr("action")
      // console.log(path)
      var theData = $(this).parent().serialize();
      // console.log(theData)
      var request = $.ajax({
      	url: path,
      	type: "delete",
      	data: theData,
      	dataType: "json"
      })
      request.done(function(response){
      	// console.log(msgToDelete)
      	console.log("helo")

      $(".message-div#"+response.msg_id).remove();
      	// console.log()
      })
      request.fail(function(response){
      	console.log("failed")
      })
  })

  $('#edit-photo input[type="submit"]').on('click', function(e){
  	e.preventDefault();
  	var path = $(this).parent().attr("action")
  	// console.log(path);
  	// var photoId = $('#edit-photo input[name="photo_id"]').val();
  	var photoData = $(this).parent().serialize();
  	// console.log(photoId)
  	var request = $.ajax({
  		url: path,
  		type: "put",
  		data: photoData,
  		dataType: "json"
  	})
  	request.done(function(response){
  		console.log("sup")
  		$('#edit-photo input[type="text"]').val(response.newcaption)
  	})
  	request.fail(function(response){
  		console.log("bye")
  	})

  })

  $('.search-bar').on('submit', function(e){
    e.preventDefault();
    var path = $(this).attr('action');
    var searchData = $(this).serialize();
    console.log(searchData);
    var request = $.ajax({
      url: path,
      type: "post",
      data: searchData,
      dataType: "json"
      // console.log(searchDa)
    })
    request.done(function(response){
      console.log('yo')
      console.log(response)
      $('.body-div').remove();
      $('body').append(response);
    })
    request.fail(function(response){
      console.log('snap')
    })
  })

  // $('.accept-request').on('click', 'button[type="submit"]', function(e){
  //   e.preventDefault();
  //   var path = $('.accept-request').attr('action')
  //   var friendData = $('.accept-request').serialize();
  //   var request = $.ajax({
  //     url:path,
  //     data: friendData,
  //     type: "put",
  //     dataType: "json"
  //   })
  //   request.done(function(response){
  //     console.log("hello");
  //     console.log(response.friend_id)
  //     $('li#'+response.friend_id).remove();
  //   })
  //   request.fail(function(response){
  //     console.log("didnt make it")
  //   })
  // })

  // $('.ignore-request').on('click', 'button[type="submit"]', function(e){
  //   e.preventDefault();
  //   var path = $('.ignore-request').attr('action')
  //   var friendData = $('.ignore-request').serialize();
  //   var request = $.ajax({
  //     url:path,
  //     data: friendData,
  //     type: "put",
  //     dataType: "json"
  //   })
  //   request.done(function(response){
  //     console.log('hihi');
  //     $('#friend-requests li#'+response.friend_id).remove();
  //   })
  //   request.fail(function(response){
  //     console.log('bye');
  //   })
  // })

  $('.add-friend-form').on('click', 'input[type="submit"]', function(e){
    // $('.add-friend-form').hide();
    e.preventDefault();
    var path = $('.add-friend-form').attr('action');
    var friendData = $('.add-friend-form').serialize();
    var request = $.ajax({
      url:path,
      data:friendData,
      type: "post",
      dataType: "json"
    })
    request.done(function(response){
      console.log("sup");
      $('.add-friend-form').hide();
    })
    request.fail(function(response){
      console.log("nope");
    })

  })

  $('#welcome-text').fadeIn(2500);

});


text:
namespace mozc {
namespace session {

class KeyEventTransformer final {
 public:
  using Table = absl::flat_hash_map<std::string, commands::KeyEvent>;

  KeyEventTransformer();

  KeyEventTransformer(const KeyEventTransformer &) = default;
  KeyEventTransformer &operator=(const KeyEventTransformer &) = default;

  ~KeyEventTransformer() = default;

  // Updates the transform table accoding to config.
  void ReloadConfig(const config::Config &config);

  // Transforms key event accoding to transform table.
  // We should update table using ReloadConfig() before calling a this function.
  bool TransformKeyEvent(commands::KeyEvent *key_event) const;

  const Table &table() const { return table_; }
  config::Config::NumpadCharacterForm numpad_character_form() const {
    return numpad_character_form_;
  }

 private:
  // Transform the key event base on the rule.  This function is used
  // for special treatment with numpad keys.
  bool TransformKeyEventForNumpad(commands::KeyEvent *key_event) const;

  // Transform symbols for Kana input.  Character transformation for
  // Romanji input is performed in preedit/table.cc
  bool TransformKeyEventForKana(commands::KeyEvent *key_event) const;

  Table table_;
  config::Config::NumpadCharacterForm numpad_character_form_;
};

}  // namespace session
}  // namespace mozc

#endif  // MOZC_SESSION_INTERNAL_KEY_EVENT_TRANSFORMER_H_


text:
namespace pdb {

namespace cci = Microsoft_Cci_Pdb;

void DumpTypeInfoStream(FILE* out, TypeInfoEnumerator& type_info_enum) {
  // Read type info stream header.
  const TypeInfoHeader& type_info_header = type_info_enum.type_info_header();

  DumpIndentedText(out, 0, "Type Info Header:\n");
  DumpIndentedText(out, 1, "version: 0x%08X\n", type_info_header.version);
  DumpIndentedText(out, 1, "len: 0x%08X\n", type_info_header.len);
  DumpIndentedText(out, 1, "type_min: 0x%08X\n", type_info_header.type_min);
  DumpIndentedText(out, 1, "type_max: 0x%08X\n", type_info_header.type_max);
  DumpIndentedText(out, 1, "type_info_data_size: 0x%08X\n",
                   type_info_header.type_info_data_size);

  const TypeInfoHashHeader& type_info_hash = type_info_header.type_info_hash;

  DumpIndentedText(out, 0, "Type Info Header Hash:\n");
  DumpIndentedText(out, 1, "stream_number: 0x%04X\n",
                   type_info_hash.stream_number);
  DumpIndentedText(out, 1, "padding: 0x%04X\n", type_info_hash.padding);
  DumpIndentedText(out, 1, "hash_key: 0x%08X\n", type_info_hash.hash_key);
  DumpIndentedText(out, 1, "cb_hash_buckets: 0x%08X\n",
                   type_info_hash.cb_hash_buckets);

  DumpIndentedText(out, 1, "offset_cb_hash_vals: 0x%08X, 0x%08x\n",
            type_info_hash.offset_cb_hash_vals.offset,
            type_info_hash.offset_cb_hash_vals.cb);
  DumpIndentedText(out, 1, "offset_cb_type_info_offset: 0x%08X, 0x%08x\n",
            type_info_hash.offset_cb_type_info_offset.offset,
            type_info_hash.offset_cb_type_info_offset.cb);
  DumpIndentedText(out, 1, "offset_cb_hash_adj: 0x%08X, 0x%08x\n",
            type_info_hash.offset_cb_hash_adj.offset,
            type_info_hash.offset_cb_hash_adj.cb);

  // TODO(mopler): Remove this type info record map from the implementation.
  TypeInfoRecordMap type_info_record_map;
  uint8_t indent_level = 1;

  // Dump each symbol contained in the vector.
  while (!type_info_enum.EndOfStream()) {
    if (!type_info_enum.NextTypeInfoRecord()) {
      LOG(ERROR) << "Unable to read type info stream.";
      return;
    }

    // Add new record to the map.
    TypeInfoRecord type_record;
    type_record.type = type_info_enum.type();
    type_record.start_position = type_info_enum.start_position();
    type_record.len = type_info_enum.len();

    type_info_record_map.insert(
        std::make_pair(type_info_enum.type_id(), type_record));

    // The location in the map is the start of the leaf, which points
    // past the size/type pair.
    DumpIndentedText(out, indent_level, "Type info 0x%04X (at 0x%04X):\n",
                     type_info_enum.type_id(),
                     type_record.start_position - sizeof(cci::SYMTYPE));

    TypeInfoEnumerator::BinaryTypeRecordReader reader(
        type_info_enum.CreateRecordReader());
    common::BinaryStreamParser parser(&reader);
    bool success = DumpLeaf(type_info_record_map, type_record.type, out,
                            &parser, type_record.len, indent_level + 1);

    if (!success) {
      // In case of failure we just dump the hex data of this type info.
      TypeInfoEnumerator::BinaryTypeRecordReader raw_reader(
          type_info_enum.CreateRecordReader());
      common::BinaryStreamParser raw_parser(&reader);
      DumpUnknownLeaf(type_info_record_map, out, &parser, type_record.len,
                      indent_level + 1);
    }
  }
}

}  // namespace pdb


text:
from __future__ import with_statement
try:
  from setuptools import setup, find_packages
except ImportError:
  from ez_setup import use_setuptools
  use_setuptools()
  from setuptools import setup, find_packages

import contextlib
version = None
with contextlib.closing(open('VERSION')) as fp:
  version = fp.read().strip()

setup(
  name='fabric_deploy',
  version=version,
  description='capistrano like deploy recipe for fabric',
  author='Yamashita Yuu',
  author_email='yamashita@geishatokyo.com',
  url='https://github.com/yyuu/fabric_deploy',
  license="http://www.apache.org/licenses/LICENSE-2.0",
  include_package_data=True,
  install_requires=[
    'Fabric>=1.2',
  ],
  packages=find_packages(),
)


text:
document.addEventListener('DOMContentLoaded', function() {
  var search = instantsearch({
    appId: 'latency',
    apiKey: '6be0576ff61c053d5f9a3225e2a90f76',
    indexName: 'instant_search'
  });

  search.addWidget(
    instantsearch.widgets.searchBox({
      container: '#search-box',
      placeholder: 'iphone...'
    })
  );

  search.addWidget(
    instantsearch.widgets.bestResult(
      document.querySelector('#best-result')
    )
  );

  search.start();
});


text:
namespace ash {

namespace tether {

FakeHostScanner::FakeHostScanner() = default;

FakeHostScanner::~FakeHostScanner() = default;

void FakeHostScanner::StopScan() {
  bool was_active = is_active_;
  is_active_ = false;

  if (was_active)
    NotifyScanFinished();
}

void FakeHostScanner::NotifyScanFinished() {
  HostScanner::NotifyScanFinished();
}

bool FakeHostScanner::IsScanActive() {
  return is_active_;
}

void FakeHostScanner::StartScan() {
  ++num_scans_started_;
  is_active_ = true;
}

}  // namespace tether

}  // namespace ash


text:
import { ParsingContext } from "../../../chrono";
import { ParsingComponents, ParsingResult } from "../../../results";
import { AbstractParserWithWordBoundaryChecking } from "../../../common/parsers/AbstractParserWithWordBoundary";
import * as references from "../../../common/casualReferences";

export default class PTCasualDateParser extends AbstractParserWithWordBoundaryChecking {
    innerPattern(context: ParsingContext): RegExp {
        return /(agora|hoje|amanha|amanhã|ontem)(?=\W|$)/i;
    }

    innerExtract(context: ParsingContext, match: RegExpMatchArray): ParsingComponents | ParsingResult {
        const lowerText = match[0].toLowerCase();
        const component = context.createParsingComponents();

        switch (lowerText) {
            case "agora":
                return references.now(context.reference);

            case "hoje":
                return references.today(context.reference);

            case "amanha":
            case "amanhã":
                return references.tomorrow(context.reference);

            case "ontem":
                return references.yesterday(context.reference);
        }

        return component;
    }
}