text:
#include "platform/audio/Biquad.h"

#include "platform/audio/AudioUtilities.h"
#include "platform/audio/DenormalDisabler.h"
#include "wtf/MathExtras.h"

#include <algorithm>
#include <complex>
#include <stdio.h>
#if OS(MACOSX)
#include <Accelerate/Accelerate.h>
#endif

namespace blink {

#if OS(MACOSX)
const int kBufferSize = 1024;
#endif

Biquad::Biquad()
    : m_hasSampleAccurateValues(false)
{
#if OS(MACOSX)
    // Allocate two samples more for filter history
    m_inputBuffer.allocate(kBufferSize + 2);
    m_outputBuffer.allocate(kBufferSize + 2);
#endif

    // Allocate enough space for the a-rate filter coefficients to handle a rendering quantum of 128
    // frames.
    m_b0.allocate(AudioUtilities::kRenderQuantumFrames);
    m_b1.allocate(AudioUtilities::kRenderQuantumFrames);
    m_b2.allocate(AudioUtilities::kRenderQuantumFrames);
    m_a1.allocate(AudioUtilities::kRenderQuantumFrames);
    m_a2.allocate(AudioUtilities::kRenderQuantumFrames);

    // Initialize as pass-thru (straight-wire, no filter effect)
    setNormalizedCoefficients(0, 1, 0, 0, 1, 0, 0);

    reset(); // clear filter memory
}

Biquad::~Biquad()
{
}

void Biquad::process(const float* sourceP, float* destP, size_t framesToProcess)
{
    // WARNING: sourceP and destP may be pointing to the same area of memory!
    // Be sure to read from sourceP before writing to destP!
    if (hasSampleAccurateValues()) {
        int n = framesToProcess;

        // Create local copies of member variables
        double x1 = m_x1;
        double x2 = m_x2;
        double y1 = m_y1;
        double y2 = m_y2;

        const double* b0 = m_b0.data();
        const double* b1 = m_b1.data();
        const double* b2 = m_b2.data();
        const double* a1 = m_a1.data();
        const double* a2 = m_a2.data();

        for (int k = 0; k < n; ++k) {
            // FIXME: this can be optimized by pipelining the multiply adds...
            float x = *sourceP++;
            float y = b0[k]*x + b1[k]*x1 + b2[k]*x2 - a1[k]*y1 - a2[k]*y2;

            *destP++ = y;

            // Update state variables
            x2 = x1;
            x1 = x;
            y2 = y1;
            y1 = y;
        }

        // Local variables back to member. Flush denormals here so we
        // don't slow down the inner loop above.
        m_x1 = DenormalDisabler::flushDenormalFloatToZero(x1);
        m_x2 = DenormalDisabler::flushDenormalFloatToZero(x2);
        m_y1 = DenormalDisabler::flushDenormalFloatToZero(y1);
        m_y2 = DenormalDisabler::flushDenormalFloatToZero(y2);

        // There is an assumption here that once we have sample accurate values we can never go back
        // to not having sample accurate values.  This is currently true in the way
        // AudioParamTimline is implemented: once an event is inserted, sample accurate processing
        // is always enabled.
        //
        // If so, then we never have to update the state variables for the MACOSX path.  The
        // structure of the state variable in these cases aren't well documented so it's not clear
        // how to update them anyway.
    } else {
#if OS(MACOSX)
        double* inputP = m_inputBuffer.data();
        double* outputP = m_outputBuffer.data();

        // Set up filter state.  This is needed in case we're switching from
        // filtering with variable coefficients (i.e., with automations) to
        // fixed coefficients (without automations).
        inputP[0] = m_x2;
        inputP[1] = m_x1;
        outputP[0] = m_y2;
        outputP[1] = m_y1;

        // Use vecLib if available
        processFast(sourceP, destP, framesToProcess);

        // Copy the last inputs and outputs to the filter memory variables.
        // This is needed because the next rendering quantum might be an
        // automation which needs the history to continue correctly.  Because
        // sourceP and destP can be the same block of memory, we can't read from
        // sourceP to get the last inputs.  Fortunately, processFast has put the
        // last inputs in input[0] and input[1].
        m_x1 = inputP[1];
        m_x2 = inputP[0];
        m_y1 = destP[framesToProcess - 1];
        m_y2 = destP[framesToProcess - 2];

#else
        int n = framesToProcess;

        // Create local copies of member variables
        double x1 = m_x1;
        double x2 = m_x2;
        double y1 = m_y1;
        double y2 = m_y2;

        double b0 = m_b0[0];
        double b1 = m_b1[0];
        double b2 = m_b2[0];
        double a1 = m_a1[0];
        double a2 = m_a2[0];

        while (n--) {
            // FIXME: this can be optimized by pipelining the multiply adds...
            float x = *sourceP++;
            float y = b0*x + b1*x1 + b2*x2 - a1*y1 - a2*y2;

            *destP++ = y;

            // Update state variables
            x2 = x1;
            x1 = x;
            y2 = y1;
            y1 = y;
        }

        // Local variables back to member. Flush denormals here so we
        // don't slow down the inner loop above.
        m_x1 = DenormalDisabler::flushDenormalFloatToZero(x1);
        m_x2 = DenormalDisabler::flushDenormalFloatToZero(x2);
        m_y1 = DenormalDisabler::flushDenormalFloatToZero(y1);
        m_y2 = DenormalDisabler::flushDenormalFloatToZero(y2);
#endif
    }
}

#if OS(MACOSX)

// Here we have optimized version using Accelerate.framework

void Biquad::processFast(const float* sourceP, float* destP, size_t framesToProcess)
{
    double filterCoefficients[5];
    filterCoefficients[0] = m_b0[0];
    filterCoefficients[1] = m_b1[0];
    filterCoefficients[2] = m_b2[0];
    filterCoefficients[3] = m_a1[0];
    filterCoefficients[4] = m_a2[0];

    double* inputP = m_inputBuffer.data();
    double* outputP = m_outputBuffer.data();

    double* input2P = inputP + 2;
    double* output2P = outputP + 2;

    // Break up processing into smaller slices (kBufferSize) if necessary.

    int n = framesToProcess;

    while (n > 0) {
        int framesThisTime = n < kBufferSize ? n : kBufferSize;

        // Copy input to input buffer
        for (int i = 0; i < framesThisTime; ++i)
            input2P[i] = *sourceP++;

        processSliceFast(inputP, outputP, filterCoefficients, framesThisTime);

        // Copy output buffer to output (converts float -> double).
        for (int i = 0; i < framesThisTime; ++i)
            *destP++ = static_cast<float>(output2P[i]);

        n -= framesThisTime;
    }
}

void Biquad::processSliceFast(double* sourceP, double* destP, double* coefficientsP, size_t framesToProcess)
{
    // Use double-precision for filter stability
    vDSP_deq22D(sourceP, 1, coefficientsP, destP, 1, framesToProcess);

    // Save history.  Note that sourceP and destP reference m_inputBuffer and m_outputBuffer respectively.
    // These buffers are allocated (in the constructor) with space for two extra samples so it's OK to access
    // array values two beyond framesToProcess.
    sourceP[0] = sourceP[framesToProcess - 2 + 2];
    sourceP[1] = sourceP[framesToProcess - 1 + 2];
    destP[0] = destP[framesToProcess - 2 + 2];
    destP[1] = destP[framesToProcess - 1 + 2];
}

#endif // OS(MACOSX)

void Biquad::reset()
{
#if OS(MACOSX)
    // Two extra samples for filter history
    double* inputP = m_inputBuffer.data();
    inputP[0] = 0;
    inputP[1] = 0;

    double* outputP = m_outputBuffer.data();
    outputP[0] = 0;
    outputP[1] = 0;

#endif
    m_x1 = m_x2 = m_y1 = m_y2 = 0;
}

void Biquad::setLowpassParams(int index, double cutoff, double resonance)
{
    // Limit cutoff to 0 to 1.
    cutoff = clampTo(cutoff, 0.0, 1.0);

    if (cutoff == 1) {
        // When cutoff is 1, the z-transform is 1.
        setNormalizedCoefficients(index,
            1, 0, 0,
            1, 0, 0);
    } else if (cutoff > 0) {
        // Compute biquad coefficients for lowpass filter

        resonance = pow(10, resonance / 20);
        double theta = piDouble * cutoff;
        double alpha = sin(theta) / (2 * resonance);
        double cosw = cos(theta);
        double beta = (1 - cosw) / 2;

        double b0 = beta;
        double b1 = 2 * beta;
        double b2 = beta;

        double a0 = 1 + alpha;
        double a1 = -2 * cosw;
        double a2 = 1 - alpha;

        setNormalizedCoefficients(index, b0, b1, b2, a0, a1, a2);
    } else {
        // When cutoff is zero, nothing gets through the filter, so set
        // coefficients up correctly.
        setNormalizedCoefficients(index,
            0, 0, 0,
            1, 0, 0);
    }
}

void Biquad::setHighpassParams(int index, double cutoff, double resonance)
{
    // Limit cutoff to 0 to 1.
    cutoff = clampTo(cutoff, 0.0, 1.0);

    if (cutoff == 1) {
        // The z-transform is 0.
        setNormalizedCoefficients(index,
            0, 0, 0,
            1, 0, 0);
    } else if (cutoff > 0) {
        // Compute biquad coefficients for highpass filter

        resonance = pow(10, resonance / 20);
        double theta = piDouble * cutoff;
        double alpha = sin(theta) / (2 * resonance);
        double cosw = cos(theta);
        double beta = (1 + cosw) / 2;

        double b0 = beta;
        double b1 = -2 * beta;
        double b2 = beta;

        double a0 = 1 + alpha;
        double a1 = -2 * cosw;
        double a2 = 1 - alpha;

        setNormalizedCoefficients(index, b0, b1, b2, a0, a1, a2);
    } else {
        // When cutoff is zero, we need to be careful because the above
        // gives a quadratic divided by the same quadratic, with poles
        // and zeros on the unit circle in the same place. When cutoff
        // is zero, the z-transform is 1.
        setNormalizedCoefficients(index,
            1, 0, 0,
            1, 0, 0);
    }
}

void Biquad::setNormalizedCoefficients(int index, double b0, double b1, double b2, double a0, double a1, double a2)
{
    double a0Inverse = 1 / a0;

    m_b0[index] = b0 * a0Inverse;
    m_b1[index] = b1 * a0Inverse;
    m_b2[index] = b2 * a0Inverse;
    m_a1[index] = a1 * a0Inverse;
    m_a2[index] = a2 * a0Inverse;
}

void Biquad::setLowShelfParams(int index, double frequency, double dbGain)
{
    // Clip frequencies to between 0 and 1, inclusive.
    frequency = clampTo(frequency, 0.0, 1.0);

    double A = pow(10.0, dbGain / 40);

    if (frequency == 1) {
        // The z-transform is a constant gain.
        setNormalizedCoefficients(index,
            A * A, 0, 0,
            1, 0, 0);
    } else if (frequency > 0) {
        double w0 = piDouble * frequency;
        double S = 1; // filter slope (1 is max value)
        double alpha = 0.5 * sin(w0) * sqrt((A + 1 / A) * (1 / S - 1) + 2);
        double k = cos(w0);
        double k2 = 2 * sqrt(A) * alpha;
        double aPlusOne = A + 1;
        double aMinusOne = A - 1;

        double b0 = A * (aPlusOne - aMinusOne * k + k2);
        double b1 = 2 * A * (aMinusOne - aPlusOne * k);
        double b2 = A * (aPlusOne - aMinusOne * k - k2);
        double a0 = aPlusOne + aMinusOne * k + k2;
        double a1 = -2 * (aMinusOne + aPlusOne * k);
        double a2 = aPlusOne + aMinusOne * k - k2;

        setNormalizedCoefficients(index, b0, b1, b2, a0, a1, a2);
    } else {
        // When frequency is 0, the z-transform is 1.
        setNormalizedCoefficients(index,
            1, 0, 0,
            1, 0, 0);
    }
}

void Biquad::setHighShelfParams(int index, double frequency, double dbGain)
{
    // Clip frequencies to between 0 and 1, inclusive.
    frequency = clampTo(frequency, 0.0, 1.0);

    double A = pow(10.0, dbGain / 40);

    if (frequency == 1) {
        // The z-transform is 1.
        setNormalizedCoefficients(index,
            1, 0, 0,
            1, 0, 0);
    } else if (frequency > 0) {
        double w0 = piDouble * frequency;
        double S = 1; // filter slope (1 is max value)
        double alpha = 0.5 * sin(w0) * sqrt((A + 1 / A) * (1 / S - 1) + 2);
        double k = cos(w0);
        double k2 = 2 * sqrt(A) * alpha;
        double aPlusOne = A + 1;
        double aMinusOne = A - 1;

        double b0 = A * (aPlusOne + aMinusOne * k + k2);
        double b1 = -2 * A * (aMinusOne + aPlusOne * k);
        double b2 = A * (aPlusOne + aMinusOne * k - k2);
        double a0 = aPlusOne - aMinusOne * k + k2;
        double a1 = 2 * (aMinusOne - aPlusOne * k);
        double a2 = aPlusOne - aMinusOne * k - k2;

        setNormalizedCoefficients(index,
            b0, b1, b2,
            a0, a1, a2);
    } else {
        // When frequency = 0, the filter is just a gain, A^2.
        setNormalizedCoefficients(index,
            A * A, 0, 0,
            1, 0, 0);
    }
}

void Biquad::setPeakingParams(int index, double frequency, double Q, double dbGain)
{
    // Clip frequencies to between 0 and 1, inclusive.
    frequency = clampTo(frequency, 0.0, 1.0);

    // Don't let Q go negative, which causes an unstable filter.
    Q = std::max(0.0, Q);

    double A = pow(10.0, dbGain / 40);

    if (frequency > 0 && frequency < 1) {
        if (Q > 0) {
            double w0 = piDouble * frequency;
            double alpha = sin(w0) / (2 * Q);
            double k = cos(w0);

            double b0 = 1 + alpha * A;
            double b1 = -2 * k;
            double b2 = 1 - alpha * A;
            double a0 = 1 + alpha / A;
            double a1 = -2 * k;
            double a2 = 1 - alpha / A;

            setNormalizedCoefficients(index,
                b0, b1, b2,
                a0, a1, a2);
        } else {
            // When Q = 0, the above formulas have problems. If we look at
            // the z-transform, we can see that the limit as Q->0 is A^2, so
            // set the filter that way.
            setNormalizedCoefficients(index,
                A * A, 0, 0,
                1, 0, 0);
        }
    } else {
        // When frequency is 0 or 1, the z-transform is 1.
        setNormalizedCoefficients(index,
            1, 0, 0,
            1, 0, 0);
    }
}

void Biquad::setAllpassParams(int index, double frequency, double Q)
{
    // Clip frequencies to between 0 and 1, inclusive.
    frequency = clampTo(frequency, 0.0, 1.0);

    // Don't let Q go negative, which causes an unstable filter.
    Q = std::max(0.0, Q);

    if (frequency > 0 && frequency < 1) {
        if (Q > 0) {
            double w0 = piDouble * frequency;
            double alpha = sin(w0) / (2 * Q);
            double k = cos(w0);

            double b0 = 1 - alpha;
            double b1 = -2 * k;
            double b2 = 1 + alpha;
            double a0 = 1 + alpha;
            double a1 = -2 * k;
            double a2 = 1 - alpha;

            setNormalizedCoefficients(index,
                b0, b1, b2,
                a0, a1, a2);
        } else {
            // When Q = 0, the above formulas have problems. If we look at
            // the z-transform, we can see that the limit as Q->0 is -1, so
            // set the filter that way.
            setNormalizedCoefficients(index,
                -1, 0, 0,
                1, 0, 0);
        }
    } else {
        // When frequency is 0 or 1, the z-transform is 1.
        setNormalizedCoefficients(index,
            1, 0, 0,
            1, 0, 0);
    }
}

void Biquad::setNotchParams(int index, double frequency, double Q)
{
    // Clip frequencies to between 0 and 1, inclusive.
    frequency = clampTo(frequency, 0.0, 1.0);

    // Don't let Q go negative, which causes an unstable filter.
    Q = std::max(0.0, Q);

    if (frequency > 0 && frequency < 1) {
        if (Q > 0) {
            double w0 = piDouble * frequency;
            double alpha = sin(w0) / (2 * Q);
            double k = cos(w0);

            double b0 = 1;
            double b1 = -2 * k;
            double b2 = 1;
            double a0 = 1 + alpha;
            double a1 = -2 * k;
            double a2 = 1 - alpha;

            setNormalizedCoefficients(index,
                b0, b1, b2,
                a0, a1, a2);
        } else {
            // When Q = 0, the above formulas have problems. If we look at
            // the z-transform, we can see that the limit as Q->0 is 0, so
            // set the filter that way.
            setNormalizedCoefficients(index,
                0, 0, 0,
                1, 0, 0);
        }
    } else {
        // When frequency is 0 or 1, the z-transform is 1.
        setNormalizedCoefficients(index,
            1, 0, 0,
            1, 0, 0);
    }
}

void Biquad::setBandpassParams(int index, double frequency, double Q)
{
    // No negative frequencies allowed.
    frequency = std::max(0.0, frequency);

    // Don't let Q go negative, which causes an unstable filter.
    Q = std::max(0.0, Q);

    if (frequency > 0 && frequency < 1) {
        double w0 = piDouble * frequency;
        if (Q > 0) {
            double alpha = sin(w0) / (2 * Q);
            double k = cos(w0);

            double b0 = alpha;
            double b1 = 0;
            double b2 = -alpha;
            double a0 = 1 + alpha;
            double a1 = -2 * k;
            double a2 = 1 - alpha;

            setNormalizedCoefficients(index,
                b0, b1, b2,
                a0, a1, a2);
        } else {
            // When Q = 0, the above formulas have problems. If we look at
            // the z-transform, we can see that the limit as Q->0 is 1, so
            // set the filter that way.
            setNormalizedCoefficients(index,
                1, 0, 0,
                1, 0, 0);
        }
    } else {
        // When the cutoff is zero, the z-transform approaches 0, if Q
        // > 0. When both Q and cutoff are zero, the z-transform is
        // pretty much undefined. What should we do in this case?
        // For now, just make the filter 0. When the cutoff is 1, the
        // z-transform also approaches 0.
        setNormalizedCoefficients(index,
            0, 0, 0,
            1, 0, 0);
    }
}

void Biquad::getFrequencyResponse(int nFrequencies,
                                  const float* frequency,
                                  float* magResponse,
                                  float* phaseResponse)
{
    // Evaluate the Z-transform of the filter at given normalized
    // frequency from 0 to 1.  (1 corresponds to the Nyquist
    // frequency.)
    //
    // The z-transform of the filter is
    //
    // H(z) = (b0 + b1*z^(-1) + b2*z^(-2))/(1 + a1*z^(-1) + a2*z^(-2))
    //
    // Evaluate as
    //
    // b0 + (b1 + b2*z1)*z1
    // --------------------
    // 1 + (a1 + a2*z1)*z1
    //
    // with z1 = 1/z and z = exp(j*pi*frequency). Hence z1 = exp(-j*pi*frequency)

    // Make local copies of the coefficients as a micro-optimization.
    double b0 = m_b0[0];
    double b1 = m_b1[0];
    double b2 = m_b2[0];
    double a1 = m_a1[0];
    double a2 = m_a2[0];

    for (int k = 0; k < nFrequencies; ++k) {
        double omega = -piDouble * frequency[k];
        std::complex<double> z = std::complex<double> (cos(omega), sin(omega));
        std::complex<double> numerator = b0 + (b1 + b2 * z) * z;
        std::complex<double> denominator =
            std::complex<double>(1, 0) + (a1 + a2 * z) * z;
        std::complex<double> response = numerator / denominator;
        magResponse[k] = static_cast<float>(abs(response));
        phaseResponse[k] = static_cast<float>(atan2(imag(response), real(response)));
    }
}

} // namespace blink


text:
const char CloudPrintSetupSource::kInvalidPasswordHelpUrl[] =
  "https://www.google.com/support/accounts/bin/answer.py?ctx=ch&answer=27444";
const char CloudPrintSetupSource::kCanNotAccessAccountUrl[] =
  "https://www.google.com/support/accounts/bin/answer.py?answer=48598";
const char CloudPrintSetupSource::kCreateNewAccountUrl[] =
  "https://accounts.google.com/NewAccount?service=chromiumsync";

namespace {

// Utility method to keep dictionary population code streamlined.
void AddString(DictionaryValue* dictionary,
               const std::string& key,
               int resource_id) {
  dictionary->SetString(key, l10n_util::GetStringUTF16(resource_id));
}

}  // namespace

CloudPrintSetupSource::CloudPrintSetupSource() {
}

std::string CloudPrintSetupSource::GetSource() const {
  return chrome::kChromeUICloudPrintSetupHost;
}

void CloudPrintSetupSource::StartDataRequest(
    const std::string& path_raw,
    int render_process_id,
    int render_view_id,
    const content::URLDataSource::GotDataCallback& callback) {
  const char kCloudPrintSetupPath[] = "cloudprintsetup";
  const char kCloudPrintGaiaLoginPath[] = "gaialogin";
  const char kCloudPrintSetupFlowPath[] = "setupflow";
  const char kCloudPrintSetupDonePath[] = "setupdone";

  DictionaryValue localized_strings;
  DictionaryValue* dict = &localized_strings;

  std::string response;
  if (path_raw == kCloudPrintSetupPath) {
    dict->SetString("header",
        l10n_util::GetStringFUTF16(IDS_CLOUD_PRINT_SETUP_HEADER,
        l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT)));
    AddString(dict, "explain", IDS_CLOUD_PRINT_SETUP_EXPLAIN);
    AddString(dict, "anywhereheader", IDS_CLOUD_PRINT_SETUP_ANYWHERE_HEADER);
    AddString(dict, "anywhereexplain", IDS_CLOUD_PRINT_SETUP_ANYWHERE_EXPLAIN);
    AddString(dict, "printerheader", IDS_CLOUD_PRINT_SETUP_PRINTER_HEADER);
    AddString(dict, "printerexplain", IDS_CLOUD_PRINT_SETUP_PRINTER_EXPLAIN);
    AddString(dict, "sharingheader", IDS_CLOUD_PRINT_SETUP_SHARING_HEADER);
    AddString(dict, "sharingexplain", IDS_CLOUD_PRINT_SETUP_SHARING_EXPLAIN);

    static const base::StringPiece html(ResourceBundle::GetSharedInstance()
        .GetRawDataResource(IDR_CLOUD_PRINT_SETUP_LOGIN_HTML));
    webui::SetFontAndTextDirection(dict);
    response = webui::GetI18nTemplateHtml(html, dict);
  } else if (path_raw == kCloudPrintGaiaLoginPath) {
    // Start by setting the per-locale URLs we show on the setup wizard.
    dict->SetString("invalidpasswordhelpurl",
                   GetLocalizedUrl(kInvalidPasswordHelpUrl));
    dict->SetString("cannotaccessaccounturl",
                   GetLocalizedUrl(kCanNotAccessAccountUrl));
    dict->SetString("createnewaccounturl",
                   GetLocalizedUrl(kCreateNewAccountUrl));

    // None of the strings used here currently have sync-specific wording in
    // them.  There is a unit test to catch if that happens.
    dict->SetString("introduction", std::string());
    AddString(dict, "signinprefix", IDS_SYNC_LOGIN_SIGNIN_PREFIX);
    AddString(dict, "signinsuffix", IDS_SYNC_LOGIN_SIGNIN_SUFFIX);
    AddString(dict, "cannotbeblank", IDS_SYNC_CANNOT_BE_BLANK);
    AddString(dict, "emaillabel", IDS_SYNC_LOGIN_EMAIL_SAME_LINE);
    AddString(dict, "passwordlabel", IDS_SYNC_LOGIN_PASSWORD_SAME_LINE);
    AddString(dict, "invalidcredentials", IDS_SYNC_INVALID_USER_CREDENTIALS);
    AddString(dict, "signin", IDS_SYNC_SIGNIN);
    AddString(dict, "couldnotconnect", IDS_SYNC_LOGIN_COULD_NOT_CONNECT);
    AddString(dict, "cannotaccessaccount", IDS_SYNC_CANNOT_ACCESS_ACCOUNT);
    AddString(dict, "createaccount", IDS_SYNC_CREATE_ACCOUNT);
    AddString(dict, "cancel", IDS_CANCEL);
    AddString(dict, "settingup", IDS_SYNC_LOGIN_SETTING_UP);
    AddString(dict, "success", IDS_SYNC_SUCCESS);
    AddString(dict, "errorsigningin", IDS_SYNC_ERROR_SIGNING_IN);
    AddString(dict, "captchainstructions", IDS_SYNC_GAIA_CAPTCHA_INSTRUCTIONS);
    AddString(dict, "invalidaccesscode", IDS_SYNC_INVALID_ACCESS_CODE_LABEL);
    AddString(dict, "enteraccesscode", IDS_SYNC_ENTER_ACCESS_CODE_LABEL);
    AddString(dict, "getaccesscodehelp", IDS_SYNC_ACCESS_CODE_HELP_LABEL);
    AddString(dict, "getaccesscodeurl", IDS_SYNC_GET_ACCESS_CODE_URL);

    static const base::StringPiece html(ResourceBundle::GetSharedInstance()
        .GetRawDataResource(IDR_GAIA_LOGIN_HTML));
    webui::SetFontAndTextDirection(dict);
    response = webui::GetI18nTemplateHtml(html, dict);
  } else if (path_raw == kCloudPrintSetupDonePath) {
    AddString(dict, "testpage", IDS_CLOUD_PRINT_SETUP_TEST_PAGE);
    AddString(dict, "success", IDS_SYNC_SUCCESS);
    AddString(dict, "okay", IDS_SYNC_SETUP_OK_BUTTON_LABEL);
    static const base::StringPiece html(ResourceBundle::GetSharedInstance()
        .GetRawDataResource(IDR_CLOUD_PRINT_SETUP_DONE_HTML));
    webui::SetFontAndTextDirection(dict);
    response = webui::GetI18nTemplateHtml(html, dict);
  } else if (path_raw == kCloudPrintSetupFlowPath) {
    static const base::StringPiece html(
        ResourceBundle::GetSharedInstance()
        .GetRawDataResource(IDR_CLOUD_PRINT_SETUP_FLOW_HTML));
    response = html.as_string();
  }

  callback.Run(base::RefCountedString::TakeString(&response));
}

std::string CloudPrintSetupSource::GetMimeType(const std::string& path) const {
  return "text/html";
}

bool CloudPrintSetupSource::ShouldAddContentSecurityPolicy() const {
  return false;
}

std::string CloudPrintSetupSource::GetLocalizedUrl(
    const std::string& url) const {
  GURL original_url(url);
  DCHECK(original_url.is_valid());
  GURL localized_url = google_util::AppendGoogleLocaleParam(original_url);
  return localized_url.spec();
}

redpajama_set_name: RedPajamaGithub


text:
import typing

import mock
import pytest

from google.cloud.firestore_v1 import base_query
from google.cloud.firestore_v1 import collection
from google.cloud.firestore_v1 import query as query_mod
from tests.unit.v1 import _test_helpers

class _CollectionQueryMixin:

    # Path to each document where we don't specify custom collection names or
    # document Ids
    doc_key: str = "projects/project-project/databases/(default)/documents/col/doc"

    @staticmethod
    def build_results_iterable(items):
        raise NotImplementedError()

    @staticmethod
    def get_collection_class():
        raise NotImplementedError()

    @staticmethod
    def get_internal_client_mock():
        raise NotImplementedError()

    @staticmethod
    def get_client():
        raise NotImplementedError()

    def _bundled_collection_helper(
        self,
        document_ids: typing.Optional[typing.List[str]] = None,
        data: typing.Optional[typing.List[typing.Dict]] = None,
    ) -> collection.CollectionReference:
        """Builder of a mocked Query for the sake of testing Bundles.

        Bundling queries involves loading the actual documents for cold storage,
        and this method arranges all of the necessary mocks so that unit tests
        can think they are evaluating a live query.
        """
        from google.cloud.firestore_v1 import _helpers
        from google.cloud.firestore_v1.types.document import Document
        from google.cloud.firestore_v1.types.firestore import RunQueryResponse
        from google.protobuf.timestamp_pb2 import Timestamp  # type: ignore

        client = self.get_client()
        template = client._database_string + "/documents/col/{}"
        document_ids = document_ids or ["doc-1", "doc-2"]

        def _index_from_data(index: int):
            if data is None or len(data) < index + 1:
                return None
            return data[index]

        documents = [
            RunQueryResponse(
                transaction=b"",
                document=Document(
                    name=template.format(document_id),
                    fields=_helpers.encode_dict(
                        _index_from_data(index) or {"hello": "world"}
                    ),
                    create_time=Timestamp(seconds=1, nanos=1),
                    update_time=Timestamp(seconds=1, nanos=1),
                ),
                read_time=_test_helpers.build_timestamp(),
            )
            for index, document_id in enumerate(document_ids)
        ]
        iterator = self.build_results_iterable(documents)
        api_client = self.get_internal_client_mock()
        api_client.run_query.return_value = iterator
        client._firestore_api_internal = api_client
        return self.get_collection_class()("col", client=client)

    def _bundled_query_helper(
        self,
        document_ids: typing.Optional[typing.List[str]] = None,
        data: typing.Optional[typing.List[typing.Dict]] = None,
    ) -> base_query.BaseQuery:
        return self._bundled_collection_helper(
            document_ids=document_ids,
            data=data,
        )._query()

class TestBundle(_CollectionQueryMixin):
    @staticmethod
    def build_results_iterable(items):
        return iter(items)

    @staticmethod
    def get_client():
        return _test_helpers.make_client()

    @staticmethod
    def get_internal_client_mock():
        from google.cloud.firestore_v1.services.firestore import client

        return mock.create_autospec(client.FirestoreClient)

    @classmethod
    def get_collection_class(cls):
        return collection.CollectionReference

    def test_add_document(self):
        from google.cloud.firestore_bundle import FirestoreBundle

        bundle = FirestoreBundle("test")
        doc = _test_helpers.build_document_snapshot(client=_test_helpers.make_client())
        bundle.add_document(doc)
        assert bundle.documents[self.doc_key].snapshot == doc

    def test_add_newer_document(self):
        from google.protobuf.timestamp_pb2 import Timestamp  # type: ignore
        from google.cloud.firestore_bundle import FirestoreBundle

        bundle = FirestoreBundle("test")
        old_doc = _test_helpers.build_document_snapshot(
            data={"version": 1},
            client=_test_helpers.make_client(),
            read_time=Timestamp(seconds=1, nanos=1),
        )
        bundle.add_document(old_doc)
        assert bundle.documents[self.doc_key].snapshot._data["version"] == 1

        # Builds the same ID by default
        new_doc = _test_helpers.build_document_snapshot(
            data={"version": 2},
            client=_test_helpers.make_client(),
            read_time=Timestamp(seconds=1, nanos=2),
        )
        bundle.add_document(new_doc)
        assert bundle.documents[self.doc_key].snapshot._data["version"] == 2

    def test_add_older_document(self):
        from google.protobuf.timestamp_pb2 import Timestamp  # type: ignore
        from google.cloud.firestore_bundle import FirestoreBundle

        bundle = FirestoreBundle("test")
        new_doc = _test_helpers.build_document_snapshot(
            data={"version": 2},
            client=_test_helpers.make_client(),
            read_time=Timestamp(seconds=1, nanos=2),
        )
        bundle.add_document(new_doc)
        assert bundle.documents[self.doc_key].snapshot._data["version"] == 2

        # Builds the same ID by default
        old_doc = _test_helpers.build_document_snapshot(
            data={"version": 1},
            client=_test_helpers.make_client(),
            read_time=Timestamp(seconds=1, nanos=1),
        )
        bundle.add_document(old_doc)
        assert bundle.documents[self.doc_key].snapshot._data["version"] == 2

    def test_add_document_with_different_read_times(self):
        from google.cloud.firestore_bundle import FirestoreBundle

        bundle = FirestoreBundle("test")
        doc = _test_helpers.build_document_snapshot(
            client=_test_helpers.make_client(),
            data={"version": 1},
            read_time=_test_helpers.build_test_timestamp(second=1),
        )
        # Create another reference to the same document, but with new
        # data and a more recent `read_time`
        doc_refreshed = _test_helpers.build_document_snapshot(
            client=_test_helpers.make_client(),
            data={"version": 2},
            read_time=_test_helpers.build_test_timestamp(second=2),
        )

        bundle.add_document(doc)
        assert bundle.documents[self.doc_key].snapshot._data == {"version": 1}
        bundle.add_document(doc_refreshed)
        assert bundle.documents[self.doc_key].snapshot._data == {"version": 2}

    def test_add_query(self):
        from google.cloud.firestore_bundle import FirestoreBundle

        query = self._bundled_query_helper()
        bundle = FirestoreBundle("test")
        bundle.add_named_query("asdf", query)
        assert bundle.named_queries.get("asdf") is not None
        assert (
            bundle.documents[
                "projects/project-project/databases/(default)/documents/col/doc-1"
            ]
            is not None
        )
        assert (
            bundle.documents[
                "projects/project-project/databases/(default)/documents/col/doc-2"
            ]
            is not None
        )

    def test_add_query_twice(self):
        from google.cloud.firestore_bundle import FirestoreBundle

        query = self._bundled_query_helper()
        bundle = FirestoreBundle("test")
        bundle.add_named_query("asdf", query)
        with pytest.raises(ValueError):
            bundle.add_named_query("asdf", query)

    def test_adding_collection_raises_error(self):
        from google.cloud.firestore_bundle import FirestoreBundle

        col = self._bundled_collection_helper()
        bundle = FirestoreBundle("test")
        with pytest.raises(ValueError):
            bundle.add_named_query("asdf", col)

    def test_bundle_build(self):
        from google.cloud.firestore_bundle import FirestoreBundle

        bundle = FirestoreBundle("test")
        bundle.add_named_query("best name", self._bundled_query_helper())
        assert isinstance(bundle.build(), str)

    def test_get_documents(self):
        from google.cloud.firestore_v1 import _helpers
        from google.cloud.firestore_bundle import FirestoreBundle

        bundle = FirestoreBundle("test")
        query: query_mod.Query = self._bundled_query_helper()  # type: ignore
        bundle.add_named_query("sweet query", query)
        docs_iter = _helpers._get_documents_from_bundle(
            bundle, query_name="sweet query"
        )
        doc = next(docs_iter)
        assert doc.id == "doc-1"
        doc = next(docs_iter)
        assert doc.id == "doc-2"

        # Now an empty one
        docs_iter = _helpers._get_documents_from_bundle(
            bundle, query_name="wrong query"
        )
        doc = next(docs_iter, None)
        assert doc is None

    def test_get_documents_two_queries(self):
        from google.cloud.firestore_bundle import FirestoreBundle
        from google.cloud.firestore_v1 import _helpers

        bundle = FirestoreBundle("test")
        query: query_mod.Query = self._bundled_query_helper()  # type: ignore
        bundle.add_named_query("sweet query", query)

        query: query_mod.Query = self._bundled_query_helper(document_ids=["doc-3", "doc-4"])  # type: ignore
        bundle.add_named_query("second query", query)

        docs_iter = _helpers._get_documents_from_bundle(
            bundle, query_name="sweet query"
        )
        doc = next(docs_iter)
        assert doc.id == "doc-1"
        doc = next(docs_iter)
        assert doc.id == "doc-2"

        docs_iter = _helpers._get_documents_from_bundle(
            bundle, query_name="second query"
        )
        doc = next(docs_iter)
        assert doc.id == "doc-3"
        doc = next(docs_iter)
        assert doc.id == "doc-4"

    def test_get_document(self):
        from google.cloud.firestore_bundle import FirestoreBundle
        from google.cloud.firestore_v1 import _helpers

        bundle = FirestoreBundle("test")
        query: query_mod.Query = self._bundled_query_helper()  # type: ignore
        bundle.add_named_query("sweet query", query)

        assert (
            _helpers._get_document_from_bundle(
                bundle,
                document_id="projects/project-project/databases/(default)/documents/col/doc-1",
            )
            is not None
        )

        assert (
            _helpers._get_document_from_bundle(
                bundle,
                document_id="projects/project-project/databases/(default)/documents/col/doc-0",
            )
            is None
        )

class TestAsyncBundle(_CollectionQueryMixin):
    @staticmethod
    def get_client():
        return _test_helpers.make_async_client()

    @staticmethod
    def build_results_iterable(items):
        from tests.unit.v1 import test__helpers

        return test__helpers.AsyncIter(items)

    @staticmethod
    def get_internal_client_mock():
        from tests.unit.v1 import test__helpers

        return test__helpers.AsyncMock(spec=["run_query"])

    @classmethod
    def get_collection_class(cls):
        from google.cloud.firestore_v1 import async_collection

        return async_collection.AsyncCollectionReference

    def test_async_query(self):
        # Create an async query, but this test does not need to be
        # marked as async by pytest because `bundle.add_named_query()`
        # seemlessly handles accepting async iterables.
        from google.cloud.firestore_bundle import FirestoreBundle

        async_query = self._bundled_query_helper()
        bundle = FirestoreBundle("test")
        bundle.add_named_query("asdf", async_query)
        assert bundle.named_queries.get("asdf") is not None
        assert (
            bundle.documents[
                "projects/project-project/databases/(default)/documents/col/doc-1"
            ]
            is not None
        )
        assert (
            bundle.documents[
                "projects/project-project/databases/(default)/documents/col/doc-2"
            ]
            is not None
        )

class TestBundleBuilder(_CollectionQueryMixin):
    @staticmethod
    def build_results_iterable(items):
        return iter(items)

    @staticmethod
    def get_client():
        return _test_helpers.make_client()

    @staticmethod
    def get_internal_client_mock():
        from google.cloud.firestore_v1.services.firestore import client

        return mock.create_autospec(client.FirestoreClient)

    @classmethod
    def get_collection_class(cls):
        return collection.CollectionReference

    def test_build_round_trip(self):
        from google.cloud.firestore_bundle import FirestoreBundle
        from google.cloud.firestore_v1 import _helpers

        query = self._bundled_query_helper()
        bundle = FirestoreBundle("test")
        bundle.add_named_query("asdf", query)
        serialized = bundle.build()
        assert (
            serialized == _helpers.deserialize_bundle(serialized, query._client).build()
        )

    def test_build_round_trip_emojis(self):
        from google.cloud.firestore_bundle import FirestoreBundle
        from google.cloud.firestore_v1 import _helpers

        smile = "😂"
        mermaid = "🧜🏿♀"
        query = self._bundled_query_helper(
            data=[{"smile": smile}, {"compound": mermaid}],
        )
        bundle = FirestoreBundle("test")
        bundle.add_named_query("asdf", query)
        serialized = bundle.build()
        reserialized_bundle = _helpers.deserialize_bundle(serialized, query._client)

        assert (
            bundle.documents[
                "projects/project-project/databases/(default)/documents/col/doc-1"
            ].snapshot._data["smile"]
            == smile
        )
        assert (
            bundle.documents[
                "projects/project-project/databases/(default)/documents/col/doc-2"
            ].snapshot._data["compound"]
            == mermaid
        )
        assert serialized == reserialized_bundle.build()

    def test_build_round_trip_more_unicode(self):
        from google.cloud.firestore_bundle import FirestoreBundle
        from google.cloud.firestore_v1 import _helpers

        bano = "baño"
        chinese_characters = "殷周金文集成引得"
        query = self._bundled_query_helper(
            data=[{"bano": bano}, {"international": chinese_characters}],
        )
        bundle = FirestoreBundle("test")
        bundle.add_named_query("asdf", query)
        serialized = bundle.build()
        reserialized_bundle = _helpers.deserialize_bundle(serialized, query._client)

        assert (
            bundle.documents[
                "projects/project-project/databases/(default)/documents/col/doc-1"
            ].snapshot._data["bano"]
            == bano
        )
        assert (
            bundle.documents[
                "projects/project-project/databases/(default)/documents/col/doc-2"
            ].snapshot._data["international"]
            == chinese_characters
        )
        assert serialized == reserialized_bundle.build()

    def test_roundtrip_binary_data(self):
        import sys
        from google.cloud.firestore_bundle import FirestoreBundle
        from google.cloud.firestore_v1 import _helpers

        query = self._bundled_query_helper(
            data=[{"binary_data": b"\x0f"}],
        )
        bundle = FirestoreBundle("test")
        bundle.add_named_query("asdf", query)
        serialized = bundle.build()
        reserialized_bundle = _helpers.deserialize_bundle(serialized, query._client)
        gen = _helpers._get_documents_from_bundle(reserialized_bundle)
        snapshot = next(gen)
        assert (
            int.from_bytes(snapshot._data["binary_data"], byteorder=sys.byteorder) == 15
        )

    def test_deserialize_from_seconds_nanos(self):
        """Some SDKs (Node) serialize Timestamp values to
        '{"seconds": 123, "nanos": 456}', instead of an ISO-formatted string.
        This tests deserialization from that format."""
        from google.protobuf.json_format import ParseError
        from google.cloud.firestore_v1 import _helpers

        client = _test_helpers.make_client(project_name="fir-bundles-test")

        _serialized: str = (
            '139{"metadata":{"id":"test-bundle","createTime":'
            + '{"seconds":"1616434660","nanos":913764000},"version":1,"totalDocuments"'
            + ':1,"totalBytes":"829"}}224{"namedQuery":{"name":"self","bundledQuery":'
            + '{"parent":"projects/fir-bundles-test/databases/(default)/documents",'
            + '"structuredQuery":{"from":[{"collectionId":"bundles"}]}},"readTime":'
            + '{"seconds":"1616434660","nanos":913764000}}}194{"documentMetadata":'
            + '{"name":"projects/fir-bundles-test/databases/(default)/documents/'
            + 'bundles/test-bundle","readTime":{"seconds":"1616434660","nanos":'
            + '913764000},"exists":true,"queries":["self"]}}402{"document":{"name":'
            + '"projects/fir-bundles-test/databases/(default)/documents/bundles/'
            + 'test-bundle","fields":{"clientCache":{"stringValue":"1200"},'
            + '"serverCache":{"stringValue":"600"},"queries":{"mapValue":{"fields":'
            + '{"self":{"mapValue":{"fields":{"collection":{"stringValue":"bundles"'
            + '}}}}}}}},"createTime":{"seconds":"1615488796","nanos":163327000},'
            + '"updateTime":{"seconds":"1615492486","nanos":34157000}}}'
        )

        with pytest.raises(
            (ValueError, ParseError)
        ):  # protobuf 3.18.0 raises ParseError
            _helpers.deserialize_bundle(_serialized, client=client)

        # See https://github.com/googleapis/python-firestore/issues/505
        #
        # The following assertions would test deserialization of NodeJS bundles
        # were explicit handling of that edge case to be added.

        # First, deserialize that value into a Bundle instance. If this succeeds,
        # we're off to a good start.
        # bundle = _helpers.deserialize_bundle(_serialized, client=client)
        # Second, re-serialize it into a Python-centric format (aka, ISO timestamps)
        # instead of seconds/nanos.
        # re_serialized = bundle.build()
        # # Finally, confirm the round trip.
        # assert re_serialized == _helpers.deserialize_bundle(re_serialized, client=client).build()
        #

    def test_deserialized_bundle_cached_metadata(self):
        from google.cloud.firestore_bundle import FirestoreBundle
        from google.cloud.firestore_v1 import _helpers

        query = self._bundled_query_helper()
        bundle = FirestoreBundle("test")
        bundle.add_named_query("asdf", query)
        bundle_copy = _helpers.deserialize_bundle(bundle.build(), query._client)
        assert isinstance(bundle_copy, FirestoreBundle)
        assert bundle_copy._deserialized_metadata is not None
        bundle_copy.add_named_query("second query", query)
        assert bundle_copy._deserialized_metadata is None

    @mock.patch("google.cloud.firestore_v1._helpers._parse_bundle_elements_data")
    def test_invalid_json(self, fnc):
        from google.cloud.firestore_v1 import _helpers

        client = _test_helpers.make_client()
        fnc.return_value = iter([{}])
        with pytest.raises(ValueError):
            _helpers.deserialize_bundle("does not matter", client)

    @mock.patch("google.cloud.firestore_v1._helpers._parse_bundle_elements_data")
    def test_not_metadata_first(self, fnc):
        from google.cloud.firestore_v1 import _helpers

        client = _test_helpers.make_client()
        fnc.return_value = iter([{"document": {}}])
        with pytest.raises(ValueError):
            _helpers.deserialize_bundle("does not matter", client)

    @mock.patch("google.cloud.firestore_bundle.FirestoreBundle._add_bundle_element")
    @mock.patch("google.cloud.firestore_v1._helpers._parse_bundle_elements_data")
    def test_unexpected_termination(self, fnc, _):
        from google.cloud.firestore_v1 import _helpers

        client = _test_helpers.make_client()
        # invalid bc `document_metadata` must be followed by a `document`
        fnc.return_value = [{"metadata": {"id": "asdf"}}, {"documentMetadata": {}}]
        with pytest.raises(ValueError):
            _helpers.deserialize_bundle("does not matter", client)

    @mock.patch("google.cloud.firestore_bundle.FirestoreBundle._add_bundle_element")
    @mock.patch("google.cloud.firestore_v1._helpers._parse_bundle_elements_data")
    def test_valid_passes(self, fnc, _):
        from google.cloud.firestore_v1 import _helpers

        client = _test_helpers.make_client()
        fnc.return_value = [
            {"metadata": {"id": "asdf"}},
            {"documentMetadata": {}},
            {"document": {}},
        ]
        _helpers.deserialize_bundle("does not matter", client)

    @mock.patch("google.cloud.firestore_bundle.FirestoreBundle._add_bundle_element")
    @mock.patch("google.cloud.firestore_v1._helpers._parse_bundle_elements_data")
    def test_invalid_bundle(self, fnc, _):
        from google.cloud.firestore_v1 import _helpers

        client = _test_helpers.make_client()
        # invalid bc `document` must follow `document_metadata`
        fnc.return_value = [{"metadata": {"id": "asdf"}}, {"document": {}}]
        with pytest.raises(ValueError):
            _helpers.deserialize_bundle("does not matter", client)

    @mock.patch("google.cloud.firestore_bundle.FirestoreBundle._add_bundle_element")
    @mock.patch("google.cloud.firestore_v1._helpers._parse_bundle_elements_data")
    def test_invalid_bundle_element_type(self, fnc, _):
        from google.cloud.firestore_v1 import _helpers

        client = _test_helpers.make_client()
        # invalid bc `wtfisthis?` is obviously invalid
        fnc.return_value = [{"metadata": {"id": "asdf"}}, {"wtfisthis?": {}}]
        with pytest.raises(ValueError):
            _helpers.deserialize_bundle("does not matter", client)

    @mock.patch("google.cloud.firestore_bundle.FirestoreBundle._add_bundle_element")
    @mock.patch("google.cloud.firestore_v1._helpers._parse_bundle_elements_data")
    def test_invalid_bundle_start(self, fnc, _):
        from google.cloud.firestore_v1 import _helpers

        client = _test_helpers.make_client()
        # invalid bc first element must be of key `metadata`
        fnc.return_value = [{"document": {}}]
        with pytest.raises(ValueError):
            _helpers.deserialize_bundle("does not matter", client)

    def test_not_actually_a_bundle_at_all(self):
        from google.cloud.firestore_v1 import _helpers

        client = _test_helpers.make_client()
        with pytest.raises(ValueError):
            _helpers.deserialize_bundle("{}", client)

    def test_add_invalid_bundle_element_type(self):
        from google.cloud.firestore_bundle import FirestoreBundle
        from google.cloud.firestore_bundle import BundleElement

        client = _test_helpers.make_client()
        bundle = FirestoreBundle("asdf")
        with pytest.raises(ValueError):
            bundle._add_bundle_element(BundleElement(), client=client, type="asdf")


text:
'use strict';

import React from 'react';
import ReactNative, { View, TouchableHighlight, Text } from 'react-native';

class DeviceListItem extends React.Component {
  render() {
    return (
      <TouchableHighlight onPress={this.props.onPress}>
        <View>
          <Text>{this.props.item}</Text>
        </View>
      </TouchableHighlight>
    );
  }
}

module.exports = DeviceListItem;


text:
package govsw

import (
	"context"
	"fmt"
	"govsw/api/vswapi"
	"net"

	log "github.com/sirupsen/logrus"
	"google.golang.org/grpc"
)

const VSWAPI_PORT = 50099

type VswApiListener interface {
	VswAPISync(string)
	VswAPISaveConfig() error
}

type VswApiServer struct {
	DB       *DB
	Listener VswApiListener
	Addr     string

	log *log.Entry
}

func (s *VswApiServer) Serve(lis net.Listener) {
	s.log.Infof("Serve: started. %s", lis.Addr())

	server := grpc.NewServer()
	vswapi.RegisterVswApiServer(server, s)
	server.Serve(lis)

	s.log.Infof("Serve: exit.")
}

func (s *VswApiServer) Start() error {
	s.log = log.WithFields(log.Fields{"module": "vswapi"})

	lis, err := net.Listen("tcp", s.Addr)
	if err != nil {
		s.log.Errorf("Listen error. %s %s", s.Addr, err)
		return err
	}

	go s.Serve(lis)

	s.log.Infof("Start: success. %s", s.Addr)
	return nil
}

func (s *VswApiServer) ModIfname(ctxt context.Context, req *vswapi.ModIfnameRequest) (*vswapi.ModIfnameReply, error) {
	switch req.Cmd {
	case vswapi.ModIfnameRequest_ADD:
		s.DB.Ifname().RegisterIfname(req.Ifname)

	case vswapi.ModIfnameRequest_REG:
		s.DB.Ifname().RegisterPattern(req.Ifname)

	case vswapi.ModIfnameRequest_DELETE:
		s.DB.Ifname().Delete(req.Ifname)

	case vswapi.ModIfnameRequest_SYNC:
		s.Listener.VswAPISync(req.Ifname)

	default:
		return nil, fmt.Errorf("Invalid command. %s", req.Cmd)
	}

	return &vswapi.ModIfnameReply{}, nil
}

func (s *VswApiServer) GetIfnames(req *vswapi.GetIfnamesRequest, stream vswapi.VswApi_GetIfnamesServer) error {
	s.DB.Ifname().Range(func(kind, ifname string) {
		reply := vswapi.GetIfnamesReply{
			Ifname: ifname,
			Kind:   kind,
		}

		if err := stream.Send(&reply); err != nil {
			s.log.Errorf("send ifname error. %s", err)
		}
	})

	return nil
}

func (s *VswApiServer) ModLink(ctxt context.Context, req *vswapi.ModLinkRequest) (*vswapi.ModLinkReply, error) {
	operState, err := func() (bool, error) {
		switch req.Cmd {
		case vswapi.ModLinkRequest_UP:
			return true, nil

		case vswapi.ModLinkRequest_DOWN:
			return false, nil

		default:
			return false, fmt.Errorf("Invalid command. %s", req.Cmd)
		}
	}()
	if err != nil {
		s.log.Errorf("ModLink: %s", err)
		return nil, err
	}

	if err := s.DB.Link().GetByName(req.Ifname, func(link *Link) error {
		return link.SetOperStatus(operState)
	}); err != nil {
		s.log.Errorf("ModLink: %s", err)
		return nil, err
	}

	return &vswapi.ModLinkReply{}, nil
}

func (s *VswApiServer) GetLinks(req *vswapi.GetLinksRequest, stream vswapi.VswApi_GetLinksServer) error {
	s.DB.Link().Range(func(ifindex int, link *Link) {
		reply := vswapi.GetLinksReply{
			Index: int32(ifindex),
			Name:  link.Name(),
		}
		if err := stream.Send(&reply); err != nil {
			s.log.Errorf("send link error. %s", err)
		}
	})

	return nil
}

func (s *VswApiServer) GetStats(req *vswapi.GetStatsRequest, stream vswapi.VswApi_GetStatsServer) error {
	replies := []*vswapi.GetStatsReply{}
	s.DB.Link().Range(func(ifindex int, link *Link) {
		reply := &vswapi.GetStatsReply{
			Group:  fmt.Sprintf("link/%s", link.Name()),
			Values: map[string]uint64{},
		}

		link.Stats().Range(func(name string, value uint64) {
			reply.Values[name] = value
		})

		replies = append(replies, reply)
	})

	for _, reply := range replies {
		if err := stream.Send(reply); err != nil {
			return err
		}
	}

	return nil
}

func (s *VswApiServer) SaveConfig(ctxt context.Context, req *vswapi.SaveConfigRequest) (*vswapi.SaveConfigReply, error) {
	if err := s.Listener.VswAPISaveConfig(); err != nil {
		s.log.Errorf("SaveConfig: %s", err)
		return nil, err
	}

	return &vswapi.SaveConfigReply{}, nil
}


text:
namespace CircuitSimulation.Library.Data
{
    public class NorGateData : TwoInputGateData
    {
        public NorGateData()
        {
            Type = ElementType.Nor;
        }
    }
}


text:
title: "Landslide Exercise"
layout: post
category : Ask some Questions
tagline: ""
tags : [case study, landslide]
---

{% include JB/setup %}

# Landslide Susceptibility Model

----

#### Objectives:

----

### Overview

This case study has been chosen to demonstrate the concepts being highlighted by the bootcamp. We have chosen a landslide susceptibility analysis due to the diversity of inputs and a general curiousity into the methodology. The study area has been chosen in response to the Oso Mudslide[^1] which took place in Washington State on March 22nd, 2014. The methodology for this analysis is based off of work done by the California Geological Survey in Conjunction with the USGS[^2].

----

### Datasets

Using the iRODS plugin, download the following layers:

  - USA_states.shp
  - DEM.tif
  - WA_geology.shp

----

### Data Wrangling

Set project projection

Before starting any project in a GIS program, you should first set the project projection to make sure your data comes in with the same extent. If you don't set the project's projection, the program will use the projection of the first layer added or EPSG:4326.

 You can set the projection with the following steps:

 In the top navbar go  Project > Project Properties

  The following window should open up.

 Select CRS in the Left menu

 Check Enable On-the-fly CRS transformation

Select NAD83(HARN)/Washington South(ftUS) EPSG:2927 from the List of Projections

Add the US States shapefile

Since our project is directed at the state of Washington, we should use the state boundary as our study area. The Global Administrative Areas[^7] project provides high-quality boundary data on country,state and county levels. We can use the US-state level dataset to get the Washington boundary.

 Open the iRods Plugin and navigate to the Exercise_3 directory

Load the USA_states.shp layer

Create a layer for the state of Washington

SCreating a layer for the state of Washington will let us define the boundary for our study.

In the top toolbar, select Select Single Feature

 Click on the state of Washington to select it

 Right click on the USA_states layer and select Save Selection As...

Format: ESRI Shapefile

 Save as: washington.shp

 Encoding: UTF-8

CRS: Project CRS

Load the new washington layer

Select Add Vector Layer

 Browse to the new washington layer and click *Open*

Remove the USA_states layer from the project

Now that we have the Washington layer, we can get rid of the U.S. layer.

Right click the layer in the table of contents

 Select Remove

 Add the DEM layer from the iPlant data store

DEMs or Digital Elevation Models are very useful for establishing topological context in a map. DEMs generally come as a raster dataset that consists of elevation values. There are several different byproducts that can be created from DEMs.

  This DEM was taken from GTOPO30 satellite data.

 Open the iRods plugin and navigate to the directory Exercise_3

Select DEM.tif

 Click Load

Project the DEM

The DEM uses the WGS 84 coordinate system, which means it is measured in degrees. Since our project is in Washington State Plane which is measured in meters, we need to reproject the DEM to use it in our analysis.

In the top menu, go to Raster > Projections > Warp (Reproject)

Use the following options

Input File: DEM

 Output File: dem_project.tif

Source SRS: EPSG:4326

Resampling Method: Near

No data values: 0

 Clip the dem to the state of Washington

Clipping the dem will remove any values outside of the study area, which will make the analysis more efficient.

In the top menu, select Raster > Extraction > Clipper

 In the window, set the following options:

 Input file: dem_project.tif

 Output file: WA_dem.tif

 No data value: 0

 Clipping Mode: Mask layer > washington

 Load into canvas when finished

 Remove the DEM layer

 The project area should now look like this:

 Create a slope surface

In the top menu, select Raster > Analysis > DEM

Input file: WA_dem

Output file: WA_slope.tif

Mode: Slope

Scale: 0.30

Load into canvas when finished

Create a hillshade layer

In the top menu, select Raster > Analysis > DEM

Input file: WA_dem

Output file: WA_hillshade.tif

Mode: Hillshade

Z factor: 1.0

Scale: 0.30

Azimuth of light: 315.0

Altitude of light: 45.0

Load into canvas when finished

Load the Geology Layer

Open the iRods plugin

Load the WA_geology.shp file

Add Rock strength index

We are going to create a numeric field to represent the strength of the geologic unit

Open field calculator in Attribute Table:

Right-click WA_geology in Layers List > Open Attribute Table > Toggle editing mode (top left)

While in edit mode,click Open field calculator (top right)

Add and calculate new field

    Match your Field Calculator window to the one below for creating a new field strength with a range of values of 0-3. Be sure to match it exactly as it's displayed

Note: double-quotes are evaluated as a column whereas single-quotes are evaluated as column values. Save your changes once finished.

    Expression:

      case

          when "rock_type" = 'soft' then 1

          when "rock_type" = 'medium' then 2

          when "rock_type" = 'hard' then 3

      else 0

      done

Visualize the geology by strength

Right-click on WA_geology.shp in Layer List > Properties > Style

Change style type from Single Symbol to Categorized.

Categorize by strength and click Classify to add classes.

Match your colors with the example below or get fancy with your own styling.

Rasterize the rock strength layer

GDAL's rasterize is a prefered method. This can be accessed through Menu Bar > Raster > Conversion > Rasterize (Vector to raster). Notice how the parameters have been diabled in the example below. There's a specific reason for this. Complete the parameter inputs: Define your output file and location (in working directory); Attribute field = strength; Raster size in pixels = 1000 x 1000. Because GDAL is more powerful in the commandline, there are certain parameters that cannot be set within QGIS.

Click the edit icon (pencil) locate near the block of code. This enables you to add custom parameters.

Add the line of code
    -at -a_nodata 0 just after gdal_rasterize

    The -at flag enables the ALL_TOUCHED rasterization option so that all pixels touched by lines or polygons will be updated, not just those on the line render path, or whose center point is within the polygon. Defaults to disabled for normal rendering rules.[^3]

-a_nodata 0  The above snippet specifies that 0 should be recognized as a missing or null value, which prevents pixels with 0 value from being visualized or used in analysis in the output raster.[^3]

Style the new Rock Strength Raster

Open WA_geology.tif style properties. HINT: See step 4.

For Render type, select Singleband pseudocolor

On the right select:

Load min/max values: Min/max;

Extend: Actual (slower); then Load.

  This loads actual values into the classification. QGIS Approximates the Minimum and Maximum values by default.

Change Mode to Equal Interval with 3 classes. Remember, we only have three rock strength classes: soft, medium, hard. Change your color map if you'd like. The color maps are not stored into the raster, so the raster will load with the default color map (black to white) each time its opened in a new project.

Click Classify. Apply and OK.

Data Analysis

Reclassifying inputs:

Slope

  <col width="90" style="text-align:center;">
  <col width="50" style="text-align:center;">

    Category
    Slope

    1
    < 3°

    2
    3-5°

    3
    5-10°

    4
    10-15°

    5
    15-20°

    6
    20-30°

    7
    30-40°

    8
    > 40°

In order to reclass our slope layer into something useful, we will use the grass r.reclass tool

The r.reclass tool reads text files which define the classification rules(rule files). For this example, our rule fill will have the following contents:

slope-rule.txt

0 thru 2.99 = 1

3 thru 4.99 = 2

5 thru 9.99 = 3

10 thru 14.99 = 4

15 thru 19.99 = 5

20 thru 29.99 = 6

30 thru 39.99 = 7

40 thru 90 = 8

Once we have created the slope rule file. We can select the r.reclass tool from the Processing Toolbox.

In the processing toolbox, select GRASS commands > Raster > r.reclass

We will use the following settings for the reclassify tool:

Input Raster: WA_slope

File containing reclass rules: slope-rules.txt

Output raster layer: slope-reclass.tif (NOTE: select Save to file... or else QGIS will not create a permanent output)

Susceptibility

We will have to do some raster calculations to create the output data set. The classifications are taken from the California study[^2] and are as follows:

Since we need to cross reference these categories, we need to create a raster which represents each unique combination of the slope and rock strength classes. A method to create unique combinations is to promote the rock strength categories a decimal place. This would make the rock classes: 10,20, and 30.

To create these new classes, we can load the WA_geology.tif, and slope-reclass.tif

In the top menu, select Raster > Raster Calculator

Our raster calculator expression will be:

("geo_coded@1" * 10) + "slope-reclass@1"

Output layer: slope-geo-sect.tif

We can apply the landslide susceptibility classification using r.reclass and the following rule file:

landslide-rule.txt

11 12 13 21 31 = 0

14 = 3

22 23 = 5

15 = 6

16 32 33 = 7

17 18 24 = 8

25 thru 28 34 = 9

35 thru 38 = 10

Continue to SHOW YOUR RESULTS

[^1]: http://www.usgs.gov/blogs/features/usgs_top_story/landslide-in-washington-state
[^2]: http://www.conservation.ca.gov/cgs/information/publications/Documents/MS58.pdf
[^3]: http://www.spatialreference.org/ref/epsg/2927
[^4]: https://lta.cr.usgs.goc/GTOPO30
[^5]: http://www.dnr.wa.gov/ResearchScience/Topics/GeosciencesData/Pages/gis_data.aspx
[^6]: http://wdfw.wa.gov/conservation/gap/land_cover_data.html
[^7]: http://www.esrl.noaa.gov/thredds/catalog/Datasets/cpc_us_precip/catalog.xml#Datasets/cpc_us_precip/RT
[^8]: http://gadm.org/country


text:
/**
 *
 */
package com.vaadin.tests.components.table;

import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUI;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;
import com.vaadin.ui.Table.ColumnHeaderMode;
import com.vaadin.ui.VerticalLayout;

/**
 *
 * @since
 * @author Vaadin Ltd
 */
public class SetCurrentPageFirstItemIndex extends AbstractTestUI {

    private int index = 5;

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.tests.components.AbstractTestUI#setup(com.vaadin.server.
     * VaadinRequest)
     */
    @Override
    protected void setup(VaadinRequest request) {
        VerticalLayout vl = new VerticalLayout();
        setContent(vl);

        final Table imageTable = new Table();
        vl.addComponent(imageTable);

        imageTable.setColumnHeaderMode(ColumnHeaderMode.HIDDEN);
        imageTable.setPageLength(1);
        imageTable.addGeneratedColumn("image", new ImageGenerator());
        imageTable.setWidth(500, Unit.PIXELS);

        for (int i = 1; i <= 25; i++) {
            imageTable.addItem(new Integer(i));
        }

        imageTable.setCurrentPageFirstItemIndex(index);

        vl.addComponent(new Button("Click", new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
                if (index != 5) {
                    index = 5;
                    imageTable.setCurrentPageFirstItemIndex(index);
                } else {
                    index = 20;
                    imageTable.setCurrentPageFirstItemIndex(index);
                }
            }
        }));
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.tests.components.AbstractTestUI#getTestDescription()
     */
    @Override
    protected String getTestDescription() {
        return "Field lastRequestedFirstvisible should be updated out of timer.";
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.tests.components.AbstractTestUI#getTicketNumber()
     */
    @Override
    protected Integer getTicketNumber() {
        return 10666;
    }

    public class ImageGenerator implements ColumnGenerator {

        @Override
        public Object generateCell(Table source, Object itemId, Object columnId) {
            return "" + itemId;
        }
    }

}


text:
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<include file="struts2/struts-finance-component.xml"></include>
	<include file="struts2/struts-finance-charge.xml"></include>
	<include file="struts2/struts-finance-charge-single.xml"></include><!-- 将收入/支出分开的费用管理 -->
	<include file="struts2/struts-finance-invoice.xml"></include>
	<include file="struts2/struts-finance-account.xml"></include>
	<include file="struts2/struts-finance-profit.xml"></include>
	<include file="struts2/struts-finance-recordbill.xml"></include>
</struts>


text:
float * g_worldToCamMatrix = (float*)0x001B3EA10;
NiRect<float> * g_viewPort = (NiRect<float> *)0x001B3EA74;
const _WorldPtToScreenPt3_Internal WorldPtToScreenPt3_Internal = (_WorldPtToScreenPt3_Internal)0x00AB84C0;

void NiRefObject::IncRef(void)
{
	InterlockedIncrement(&m_uiRefCount);
}

bool NiRefObject::Release(void)
{
	return InterlockedDecrement(&m_uiRefCount) == 0;
}

void NiRefObject::DecRef(void)
{
	if(Release())
		DeleteThis();
}

// UNTESTED

int ExtraDataCompare(const void * ls, const void * rs)
{
	return (int)(((NiExtraData*)ls)->m_pcName - ((NiExtraData*)rs)->m_pcName);
}

void NiObjectNET::AddExtraData(NiExtraData * extraData)
{
	extraData->IncRef();

	// No capacity, allocate and grow
	UInt32 newSize = 0;
	if(m_extraDataCapacity == 0) {
		newSize = 1;
		NiExtraData ** extraDataList = (NiExtraData **)FormHeap_Allocate(newSize * sizeof(NiExtraData*));
		extraDataList[0] = extraData;
		m_extraData = extraDataList;
		m_extraDataCapacity = newSize;
		m_extraDataLen = m_extraDataCapacity;
		return;
	}

	// Reached capacity, reallocate and grow
	if(m_extraDataLen == m_extraDataCapacity) {
		newSize = (m_extraDataCapacity * 2) + 1;
		NiExtraData ** extraDataList = (NiExtraData **)FormHeap_Allocate(newSize * sizeof(NiExtraData*));
		// Copy the entries over
		memcpy_s(extraDataList, newSize * sizeof(NiExtraData*), m_extraData, m_extraDataLen * sizeof(NiExtraData*));
		// Zero the allocated entries
		for(UInt16 i = m_extraDataLen; i < newSize; i++)
			extraDataList[i] = NULL;

		FormHeap_Free(m_extraData);
		m_extraData = extraDataList;
		m_extraDataCapacity = newSize;
	}

	m_extraData[++m_extraDataLen] = extraData;
	qsort(m_extraData, m_extraDataLen, sizeof(NiExtraData*), ExtraDataCompare);
}

SInt32 NiObjectNET::GetIndexOf(NiExtraData * extraData)
{
	if(!extraData)
		return -1;
	if(!extraData->m_pcName)
		return -1;

	SInt16 min = 0;
	SInt16 max = (SInt16)m_extraDataLen - 1;
	SInt16 r = -1;
	while (max >= min) { // Iterative binary search
		SInt16 mid = (min + max) >> 1;
		if(m_extraData[mid]->m_pcName == extraData->m_pcName)
			r = mid; // Found entry
		else if (m_extraData[mid]->m_pcName < extraData->m_pcName)
			min = mid + 1;
		else
			max = mid - 1;
	}

	return r;
}

bool NiObjectNET::RemoveExtraData(NiExtraData * extraData)
{
	SInt32 index = GetIndexOf(extraData);
	if(index >= 0) { // Remove the entry
		extraData->DecRef();
		// Shift everything up
		for (UInt16 i = index; i < m_extraDataLen - 1; i++)
			m_extraData[i] = m_extraData[i + 1];
		// Remove the duplicate tail entry
		m_extraData[--m_extraDataLen] = NULL;
		return true;
	}

	return false;
}

// This should be a BSFixedString before passing to this
NiExtraData * NiObjectNET::GetExtraData(const char * name)
{
	SInt16 min = 0;
	SInt16 max = (SInt16)m_extraDataLen - 1;

	while (max >= min) { // Iterative binary search
		SInt16 mid = (min + max) >> 1;
		if(m_extraData[mid]->m_pcName == name)
			return m_extraData[mid];
		else if (m_extraData[mid]->m_pcName < name)
			min = mid + 1;
		else
			max = mid - 1;
	}

	return NULL;
}

bool NiCamera::WorldPtToScreenPt3(NiPoint3 * p_in, float * x_out, float * y_out, float * z_out, float zeroTolerance)
{
	return WorldPtToScreenPt3_Internal((float*)&this->m_aafWorldToCam, &this->m_kPort, p_in, x_out, y_out, z_out, zeroTolerance);
}


text:
#include <string>

#include "envoy/registry/registry.h"
#include "envoy/server/filter_config.h"

#include "extensions/filters/listener/original_dst/original_dst.h"
#include "extensions/filters/listener/well_known_names.h"

namespace Envoy {
namespace Extensions {
namespace ListenerFilters {
namespace OriginalDst {

/**
 * Config registration for the original dst filter. @see NamedNetworkFilterConfigFactory.
 */
class OriginalDstConfigFactory : public Server::Configuration::NamedListenerFilterConfigFactory {
public:
  // NamedListenerFilterConfigFactory
  Network::ListenerFilterFactoryCb
  createFilterFactoryFromProto(const Protobuf::Message&,
                               Server::Configuration::ListenerFactoryContext&) override {
    return [](Network::ListenerFilterManager& filter_manager) -> void {
      filter_manager.addAcceptFilter(std::make_unique<OriginalDstFilter>());
    };
  }

  ProtobufTypes::MessagePtr createEmptyConfigProto() override {
    return std::make_unique<Envoy::ProtobufWkt::Empty>();
  }

  std::string name() override { return ListenerFilterNames::get().OriginalDst; }
};

/**
 * Static registration for the original dst filter. @see RegisterFactory.
 */
REGISTER_FACTORY(OriginalDstConfigFactory, Server::Configuration::NamedListenerFilterConfigFactory);

} // namespace OriginalDst
} // namespace ListenerFilters
} // namespace Extensions
} // namespace Envoy


text:
/**
 * Autogenerated by Thrift for thrift/compiler/test/fixtures/basic/src/module.thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated @nocommit
 */
#pragma once

#include <thrift/lib/cpp2/gen/module_data_h.h>

#include "thrift/compiler/test/fixtures/basic/gen-cpp2/module_types.h"

namespace apache { namespace thrift {

template <> struct TEnumDataStorage<::test::fixtures::basic::MyEnum> {
  using type = ::test::fixtures::basic::MyEnum;
  static constexpr const std::size_t size = 2;
  static constexpr std::array<type, size> values = {{
      type::MyValue1,
      type::MyValue2,
  }};
  static constexpr std::array<folly::StringPiece, size> names = {{
      "MyValue1",
      "MyValue2",
  }};
};

template <> struct TEnumDataStorage<::test::fixtures::basic::HackEnum> {
  using type = ::test::fixtures::basic::HackEnum;
  static constexpr const std::size_t size = 2;
  static constexpr std::array<type, size> values = {{
      type::Value1,
      type::Value2,
  }};
  static constexpr std::array<folly::StringPiece, size> names = {{
      "Value1",
      "Value2",
  }};
};

template <> struct TEnumDataStorage<::test::fixtures::basic::MyUnion::Type> {
  using type = ::test::fixtures::basic::MyUnion::Type;
  static constexpr const std::size_t size = 4;
  static constexpr std::array<type, size> values = {{
      type::myEnum,
      type::myStruct,
      type::myDataItem,
      type::floatSet,
  }};
  static constexpr std::array<folly::StringPiece, size> names = {{
      "myEnum",
      "myStruct",
      "myDataItem",
      "floatSet",
  }};
};

template <> struct TEnumDataStorage<::test::fixtures::basic::UnionToBeRenamed::Type> {
  using type = ::test::fixtures::basic::UnionToBeRenamed::Type;
  static constexpr const std::size_t size = 1;
  static constexpr std::array<type, size> values = {{
      type::reserved_field,
  }};
  static constexpr std::array<folly::StringPiece, size> names = {{
      "reserved_field",
  }};
};

template <> struct TStructDataStorage<::test::fixtures::basic::MyStruct> {
  static constexpr const std::size_t fields_size = 9;
  static const std::array<folly::StringPiece, fields_size> fields_names;
  static const std::array<int16_t, fields_size> fields_ids;
  static const std::array<protocol::TType, fields_size> fields_types;

 private:
  // The following fields describe internal storage metadata, and are private to
  // prevent user logic from accessing them, but they can be inspected by
  // debuggers.
  static const std::array<folly::StringPiece, fields_size> storage_names;
  // -1 if the field has no isset.
  static const std::array<int, fields_size> isset_indexes;
};

template <> struct TStructDataStorage<::test::fixtures::basic::MyDataItem> {
  static constexpr const std::size_t fields_size = 0;
  static const std::array<folly::StringPiece, fields_size> fields_names;
  static const std::array<int16_t, fields_size> fields_ids;
  static const std::array<protocol::TType, fields_size> fields_types;

 private:
  // The following fields describe internal storage metadata, and are private to
  // prevent user logic from accessing them, but they can be inspected by
  // debuggers.
  static const std::array<folly::StringPiece, fields_size> storage_names;
  // -1 if the field has no isset.
  static const std::array<int, fields_size> isset_indexes;
};

template <> struct TStructDataStorage<::test::fixtures::basic::MyUnion> {
  static constexpr const std::size_t fields_size = 4;
  static const std::array<folly::StringPiece, fields_size> fields_names;
  static const std::array<int16_t, fields_size> fields_ids;
  static const std::array<protocol::TType, fields_size> fields_types;

 private:
  // The following fields describe internal storage metadata, and are private to
  // prevent user logic from accessing them, but they can be inspected by
  // debuggers.
  static const std::array<folly::StringPiece, fields_size> storage_names;
  // -1 if the field has no isset.
  static const std::array<int, fields_size> isset_indexes;
};

template <> struct TStructDataStorage<::test::fixtures::basic::ReservedKeyword> {
  static constexpr const std::size_t fields_size = 1;
  static const std::array<folly::StringPiece, fields_size> fields_names;
  static const std::array<int16_t, fields_size> fields_ids;
  static const std::array<protocol::TType, fields_size> fields_types;

 private:
  // The following fields describe internal storage metadata, and are private to
  // prevent user logic from accessing them, but they can be inspected by
  // debuggers.
  static const std::array<folly::StringPiece, fields_size> storage_names;
  // -1 if the field has no isset.
  static const std::array<int, fields_size> isset_indexes;
};

template <> struct TStructDataStorage<::test::fixtures::basic::UnionToBeRenamed> {
  static constexpr const std::size_t fields_size = 1;
  static const std::array<folly::StringPiece, fields_size> fields_names;
  static const std::array<int16_t, fields_size> fields_ids;
  static const std::array<protocol::TType, fields_size> fields_types;

 private:
  // The following fields describe internal storage metadata, and are private to
  // prevent user logic from accessing them, but they can be inspected by
  // debuggers.
  static const std::array<folly::StringPiece, fields_size> storage_names;
  // -1 if the field has no isset.
  static const std::array<int, fields_size> isset_indexes;
};

}} // apache::thrift


text:
(function () {
	'use strict'

	const suite = new Benchmark.Suite

	const imps = [
		bf.imp.functions,
		bf.imp.switch,
		bf.imp.transpiler,
		bf.imp.binarySearch
	]

	const options = {
		memorySize: 4,
		iterationsMax: 1000
	}

	const source = '++++++[>++++++[-]<-]'

	let phonyVar = 0

	imps.forEach(({ name, compile }) => {
		suite.add(`compile & run ${name}`, () => {
			const { memory } = compile(source, options)([])
			phonyVar += memory[0]
		})
	})

	imps.forEach(({ name, compile }) => {
		const compiled = compile(source, options)

		suite.add(`precompiled & run ${name}`, () => {
			const { memory } = compiled([])
			phonyVar += memory[0]
		})
	})

	suite.on('cycle', function (event) {
		console.log(String(event.target))
	})

	suite.on('complete', function () {
		console.log('Fastest is ', this.filter('fastest').map('name'));

		// have to use these values to make sure the functions don't get optimised away
		console.log('phonyVar', phonyVar)
	})

	suite.run({ async: true })
})()


text:
package com.karateca.ddescriber.model;

/**
 * @author Andres Dominguez.
 */
public class TestCounts {
  private final int testCount;
  private final int includedCount;
  private final int excludedCount;

  public TestCounts(int testCount, int includedCount, int excludedCount) {
    this.testCount = testCount;
    this.includedCount = includedCount;
    this.excludedCount = excludedCount;
  }

  public int getTestCount() {
    return testCount;
  }

  public int getIncludedCount() {
    return includedCount;
  }

  public int getExcludedCount() {
    return excludedCount;
  }
}


text:
ip addr flush dev $IFIN
ip addr flush dev $IFOUT

# bridge interfaces (layer 2) and let snort listen to bridge (IDS mode)
brctl addbr br0
brctl addif br0 $IFIN $IFOUT
ifconfig br0 up

sh restart_snort.sh


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.sql.models;

import com.azure.core.annotation.Immutable;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The target that a job execution is executed on. */
@Immutable
public final class JobExecutionTarget {
    /*
     * The type of the target.
     */
    @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY)
    private JobTargetType type;

    /*
     * The server name.
     */
    @JsonProperty(value = "serverName", access = JsonProperty.Access.WRITE_ONLY)
    private String serverName;

    /*
     * The database name.
     */
    @JsonProperty(value = "databaseName", access = JsonProperty.Access.WRITE_ONLY)
    private String databaseName;

    /**
     * Get the type property: The type of the target.
     *
     * @return the type value.
     */
    public JobTargetType type() {
        return this.type;
    }

    /**
     * Get the serverName property: The server name.
     *
     * @return the serverName value.
     */
    public String serverName() {
        return this.serverName;
    }

    /**
     * Get the databaseName property: The database name.
     *
     * @return the databaseName value.
     */
    public String databaseName() {
        return this.databaseName;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=VBXHBYFU44T5W&source=url)
[![GoDoc](https://img.shields.io/badge/godoc-reference-green.svg)](https://godoc.org/github.com/virtomize/i-doit-go-api)
[![Go Report Card](https://goreportcard.com/badge/github.com/virtomize/i-doit-go-api)](https://goreportcard.com/report/github.com/virtomize/i-doit-go-api)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/virtomize/i-doit-go-api/blob/master/LICENSE)
[![Build Status](https://travis-ci.com/virtomize/i-doit-go-api.svg?branch=master)](https://travis-ci.com/virtomize/i-doit-go-api)
[![Built with Mage](https://magefile.org/badge.svg)](https://magefile.org)
![Coverage](https://img.shields.io/badge/coverage-%3E80%25-brightgreen.svg)

is an [I-doit](https://www.i-doit.com/) API client implementation written in [GOLANG](https://golang.org).

Its focused on simplicity to create easy writable code for your projects.

the package supports:
- Login
- Requests
- Searching
- Getting object information by id, id slice, string or custom field
- creating, altering, deleting, archiving, quickpurging objects
- reports
- categories (only parts implemented) (wip)
- object\_type\_categories
- dialog

Other types of requests like
- object\_types (coming soon)
- object\_type\_groups (coming soon)
- objects\_by\_relation (coming soon)
- categories (category, category\_info) (wip)
- location\_tree
- workstation\_components
- logbook
- impact

are not implemented yet (and maybe never will) but can easily be implemented using the goidoit.Request function
there are some [advanced](https://github.com/virtomize/i-doit-go-api/blob/master/examples/advanced.go) [examples](https://github.com/virtomize/i-doit-go-api/blob/master/examples/advanced2.go) of how to do this.

There is also a second repo [i-doit-go-tools](https://github.com/virtomize/i-doit-go-tools) where you can find some more scripts for special use-cases that can be used as an
even more advanced example :P.

## Installation

If you already installed GO on your system and configured it properly than its simply:

```
go get github.com/virtomize/i-doit-go-api
```

If not follow [these instructions](https://golang.org/doc/install)

## Usage

### Simple example

```
package main

import (
	"fmt"
	"github.com/virtomize/i-doit-go-api"
)

func main() {
  // create api object
  a, _ := goidoit.NewAPI("https://example.com/src/jsonrpc.php", "yourapikey")

  // or login using X-RPC-Auth (recommended)
  // a, _ := goidoit.NewLogin("https://example.com/src/jsonrpc.php", "yourapikey", "username", "password")

  // search for sth like test
  s, _ := a.Search("test")

  // thats it
  fmt.Println(s)
}
```

### Advanced examples

There are more advanced [examples](https://github.com/virtomize/i-doit-go-api/tree/master/examples) documented in the repo for common use cases.

## Code Documentation

You find the full [code documentation here](https://godoc.org/github.com/virtomize/i-doit-go-api)

## Code Testing

This library uses [mage](https://magefile.org/) for testing and coverage.
After installing mage just run:

```
mage test
```

also code coverage in detail can be seen via browser by using

```
mage coverage
```

## Additional Informations

- [i-doit API documentation](https://kb.i-doit.com/pages/viewpage.action?pageId=37355644)
- [golang](https://golang.org/)
- [godoc](https://godoc.org/)
- [golang playground](https://play.golang.org/)

This project uses [sematic versioning](https://semver.org/).

## Other great client implementations

- Benjamin Heisigs [i-doit-api-client-php](https://github.com/bheisig/i-doit-api-client-php/)
- Dennis Stückens [i-doit-api-clients](https://bitbucket.org/dstuecken/i-doit-api-clients/)

Thanks for your code inspirations!

## Contribution

Thank you for participating to this project.
Please see our [Contribution Guidlines](https://github.com/virtomize/i-doit-go-api/blob/master/CONTRIBUTING.md) for more information.


text:
<?php

namespace Ctech\Configurator\Setup;

use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * Class InstallData
 * @package Ctech\Configurator\Setup
 */
class InstallData implements InstallDataInterface
{
    /**
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $installer = $setup;
        $installer->startSetup();

        $setup->endSetup();
    }

    /**
     * InstallData constructor.
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }
}


text:
<?php namespace CodeIgniter\Database\Live;

use CodeIgniter\Test\CIDatabaseTestCase;

/**
 * @group DatabaseLive
 */
class EmptyTest extends CIDatabaseTestCase
{
	protected $refresh = true;

	protected $seed = 'Tests\Support\Database\Seeds\CITestSeeder';

	public function testEmpty()
	{
		$this->db->table('misc')->emptyTable();

		$this->assertEquals(0, $this->db->table('misc')->countAll());
	}

	//--------------------------------------------------------------------

	public function testTruncate()
	{
		$this->db->table('misc')->truncate();

		$this->assertEquals(0, $this->db->table('misc')->countAll());
	}

	//--------------------------------------------------------------------
}


text:
package net.minidev.ovh.api.registry.image;

/**
 * The status of the image
 */
public enum OvhStatus {
	DELETING("DELETING"),
	DEPLOYING("DEPLOYING"),
	ERROR("ERROR"),
	OK("OK");

	final String value;

	OvhStatus(String s) {
		this.value = s;
	}

	public String toString() {
		return this.value;
	}
}


text:
export * from "./legacy-glTF";
export * from "./legacy-glTF1";


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <link href="../../CSS/perfiles.css" rel="stylesheet">
    <link href="../../CSS/fonts.css" rel="stylesheet">
    <link href="../../CSS/font-awesome.min.css" rel="stylesheet">
    <link href="../../CSS/meli.css" rel="stylesheet">
    <link rel="icon" type="image/png" href="../../IMG/favicon.ico" />

    <title>Angie M. Delgado - jointDeveloper</title>

jointDeveloper

Inicio

Info

Aptitudes

Educación

Cursos

Proyectos - Portafolio

Pasatiempos

Articulos

Contacto

Angie Melissa Delgado León

Soy estudiante de Ingeniería de Sistemas de la Universidad Francisco de Paula Santander. Apasionada por la Programación Competitiva, me gusta enseñar, compartir conocimiento y aprender cosas nuevas.

Aptitudes

        <canvas id="myChart" class="chart-aptitudes center"></canvas>

 Acerca de Mi

                Cosas que no me gustan

                 Injusticias

                 Arrogancia

                Peliculas de miedo

                Spoilers

                Cosas que Amo

                 Mi Familia y mis amigos

                 La programación competitiva

                Aprender

                Las sonrisas

                Perros y Gatos, ¿Quién no los ama?

                Una buena película, una buena canción y un buen libro

                Viajar

                Voleyball

                Dibujar

Educación

Ingeniería de Sistemas

Duración: 10 Semestres

Universidad Francisco de Paula Santander

Semestre: 9

Server-side Development with NodeJS

The Hong Kong University of Science and Technology

Coursera

Proyectos

Pasatiempos

Contacto

              info@jointDevelopers.co


text:
import os
import re
import time
import datetime
import hashlib
import string
import random

from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.api.labs import taskqueue

from v2ex.babel import Member
from v2ex.babel import Counter
from v2ex.babel import Section
from v2ex.babel import Node
from v2ex.babel import Topic
from v2ex.babel import Reply
from v2ex.babel import Note
from v2ex.babel import Notification

from v2ex.babel import SYSTEM_VERSION

from v2ex.babel.security import *
from v2ex.babel.ua import *
from v2ex.babel.da import *
from v2ex.babel.l10n import *
from v2ex.babel.ext.cookies import Cookies

from v2ex.babel.handlers import BaseHandler

import config

template.register_template_library('v2ex.templatetags.filters')

class MoneyDashboardHandler(BaseHandler):
    def get(self):
        if self.member:
            self.set_title(u'账户查询')
            self.finalize(template_name='money_dashboard')
        else:
            self.redirect('/signin')

application = webapp.WSGIApplication([
    ('/money/dashboard/?', MoneyDashboardHandler)
    ],
                                         debug=True)

def main():
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()


text:
#include <vector>
#include <algorithm>
#include <cstring>
#include "tasks/value_sort/value_sort_logical_task.hpp"
#include "tasks/physical_task_command_base.hpp"
#include "context/execution_context.hpp"
#include "scheduler/locality_option.hpp"
#include "memory/serialized_buffer.hpp"

namespace m3bp {

class ValueSortLogicalTask::ValueSortCommand
	: public PhysicalTaskCommandBase
{
private:
	ValueSortLogicalTask *m_logical_task;
	MemoryReference m_source;
	LockedMemoryReference m_locked_source;
	identifier_type m_partition;
public:
	ValueSortCommand(
		ValueSortLogicalTask *logical_task,
		MemoryReference source_buffer,
		identifier_type partition)
		: m_logical_task(logical_task)
		, m_source(std::move(source_buffer))
		, m_locked_source()
		, m_partition(partition)
	{ }
	virtual void prepare(
		ExecutionContext & /* context */,
		const Locality & /* locality */) override
	{
		m_locked_source = m_source.lock();
		m_source = MemoryReference();
	}
	virtual void run(
		ExecutionContext &context,
		const Locality & /* locality */) override
	{
		m_logical_task->run(
			context, std::move(m_locked_source), m_partition);
	}
};

ValueSortLogicalTask::ValueSortLogicalTask()
	: LogicalTaskBase()
	, m_comparator()
{ }

ValueSortLogicalTask::ValueSortLogicalTask(ComparatorType comparator)
	: LogicalTaskBase()
	, m_comparator(std::move(comparator))
{ }

void ValueSortLogicalTask::create_physical_tasks(ExecutionContext &context){
	auto &scheduler = context.scheduler();
	const auto entry_id = scheduler.create_physical_task(
		task_id(),
		std::unique_ptr<PhysicalTaskCommandBase>(
			new PhysicalTaskCommandBase()),
		LocalityOption());
	const auto terminal_id = scheduler.create_physical_task(
		task_id(),
		std::unique_ptr<PhysicalTaskCommandBase>(
			new PhysicalTaskCommandBase()),
		LocalityOption());
	scheduler.add_dependency(entry_id, terminal_id);
	entry_task(entry_id);
	barrier_task(entry_id);
	terminal_task(terminal_id);
}

void ValueSortLogicalTask::commit_physical_tasks(ExecutionContext &context){
	auto &scheduler = context.scheduler();
	scheduler.commit_task(entry_task());
	scheduler.commit_task(terminal_task());
}

void ValueSortLogicalTask::receive_fragment(
	ExecutionContext &context,
	identifier_type port,
	identifier_type partition,
	MemoryReference mobj)
{
	(void)(port);
	assert(port == 0);
	auto &scheduler = context.scheduler();
	auto &locality_manager = context.locality_manager();
	const auto mobj_loc = mobj.locality();
	const auto pid = scheduler.create_physical_task(
		task_id(),
		std::unique_ptr<PhysicalTaskCommandBase>(
			new ValueSortCommand(this, std::move(mobj), partition)),
		LocalityOption(
			locality_manager.random_worker_from_node(mobj_loc)));
	scheduler.add_dependency(entry_task(), pid);
	scheduler.add_dependency(pid, terminal_task());
	scheduler.commit_task(pid);
}

void ValueSortLogicalTask::run(
	ExecutionContext &context,
	LockedMemoryReference mobj,
	identifier_type partition)
{
	using PairType = std::pair<const void *, identifier_type>;
	auto &memory_manager = context.memory_manager();
	SerializedBuffer input_sb(std::move(mobj));
	const auto value_count = input_sb.record_count();
	const auto group_count = input_sb.group_count();
	const auto keys_size = input_sb.keys_data_size();
	const auto values_size = input_sb.values_data_size();

	auto output_sb = SerializedBuffer::allocate_grouped_buffer(
		memory_manager, value_count, group_count, keys_size, values_size);
	memcpy(output_sb.keys_data(), input_sb.keys_data(), keys_size);
	memcpy(
		output_sb.keys_offsets().data(), input_sb.keys_offsets().data(),
		(group_count + 1) * sizeof(size_type));
	memcpy(
		output_sb.value_group_offsets().data(),
		input_sb.value_group_offsets().data(),
		(group_count + 1) * sizeof(size_type));

	const auto in_values =
		static_cast<const uint8_t *>(input_sb.values_data());
	const auto in_group_offsets = input_sb.value_group_offsets();
	const auto in_value_offsets = input_sb.values_offsets();
	const auto out_values = static_cast<uint8_t *>(output_sb.values_data());
	auto out_value_offsets = output_sb.values_offsets();
	out_value_offsets[0] = 0;
	for(m3bp::identifier_type g = 0, v = 0; g < group_count; ++g){
		const auto values_head = v;
		std::vector<PairType> ptr_pairs;
		while(in_value_offsets[v] < in_group_offsets[g + 1]){
			ptr_pairs.emplace_back(in_values + in_value_offsets[v], v);
			++v;
		}
		std::sort(
			ptr_pairs.begin(), ptr_pairs.end(),
			[this](const PairType &a, const PairType &b) -> bool {
				return m_comparator(a.first, b.first);
			});
		auto w = values_head;
		for(const auto &p : ptr_pairs){
			const auto i = p.second;
			const auto len = in_value_offsets[i + 1] - in_value_offsets[i];
			memcpy(out_values + out_value_offsets[w], p.first, len);
			out_value_offsets[w + 1] = out_value_offsets[w] + len;
			++w;
		}
	}

	commit_fragment(
		context, 0, partition, MemoryReference(output_sb.raw_reference()));
}

}