问:
How to improve performance in calculating greeks in DolphinDB?
I am using DolphinDB to calculate Greeks, I wrote it in vectorized way, and the performance is quite good. But I can't implement implied volatility in vectorized way which makes the performance very poor. How can I improve the performance of the following implementation?</p>

```<code>def GBlackScholes(future_price, strike, input_ttm, risk_rate, b_rate, input_vol, is_call) {
  ttm = input_ttm + 0.000000000000001;
  vol = input_vol + 0.000000000000001;

  d1 = (log(future_price/strike) + (b_rate + vol*vol/2) * ttm) / (vol * sqrt(ttm));
  d2 = d1 - vol * sqrt(ttm);

  if (is_call) {
    return future_price * exp((b_rate - risk_rate) * ttm) * cdfNormal(0, 1, d1) - strike * exp(-risk_rate*ttm) * cdfNormal(0, 1, d2);
  } else {
    return strike * exp(-risk_rate*ttm) * cdfNormal(0, 1, -d2) - future_price * exp((b_rate - risk_rate) * ttm) * cdfNormal(0, 1, -d1);
  }
}

def ImpliedVolatility(future_price, strike, ttm, risk_rate, b_rate, option_price, is_call) {
  high=5.0;
  low = 0.0;

  do {
    if (GBlackScholes(future_price, strike, ttm, risk_rate, b_rate, (high+low)/2, is_call) > option_price) {
      high = (high+low)/2;
    } else {
      low = (high + low) /2;
    }
  } while ((high-low) > 0.00001);

  return (high + low) /2;
}
</code>```

答:
Q : How can I improve the performance of the following implementation?

Vectorised processing ?

This part is a bit mysterious - forgive an old quant not to read this well enough - an information about which of the parameters was intended not to be a scalar was not present, so the analysis was based on the explicitly present pieces of information.

Disclaimer :
While I know that the DolphinDB has not published a ternary operator (...)?(...):(...) to be available in the public API, I feel the ideas expressed below are clear and sound.

Fighting Performance ?

If seriously talking about the performance, first let's review and principally avoid any repetitive re-calculations, that took place in the above proposed code :

```<code>def GBlackScholes( future_price,
                   strike,
                   input_ttm,
                   risk_rate,
                   b_rate,
                   input_vol,               // <------------[VAR]:: <-- ( high+low )/2
                   is_call                 //
                   ) {                    //
    ttm = input_ttm + 0.000000000000001; //-do-while-(CONST)
    vol = input_vol + 0.000000000000001;//--do-while--------[VAR]
                                       //
    d1  = ( log( future_price )       //----do-while-(CONST)
          - log( strike )            //-----do-while-(CONST)
          + b_rate                  //------do-while-(CONST)
          + vol*vol/2              //-------do-while--------[VAR]
          * ttm                   //--------do-while-(CONST)
            ) / ( vol            //---------do-while--------[VAR]
                * sqrt( ttm )   //----------do-while-(CONST)
                  );           //
    d2  = ( d1                //------------do-while--------[VAR]
          - vol              //-------------do-while--------[VAR]
          * sqrt( ttm )     //--------------do-while-(CONST)
            );             //              ++---------------[VAR]
                          //               ||     .________________________________________________.
 // -----------[VAR]-?-( cdfNormal(--------vv-) * [                                                ]--do-while-(CONST)
    return ( is_call ? ( cdfNormal( 0, 1,  d1 ) * future_price * exp( ( b_rate - risk_rate ) * ttm )
                       - cdfNormal( 0, 1,  d2 ) * strike       * exp(           -risk_rate   * ttm )
                         )
                     : ( cdfNormal( 0, 1, -d2 ) * strike       * exp(           -risk_rate   * ttm )
                       - cdfNormal( 0, 1, -d1 ) * future_price * exp( ( b_rate - risk_rate ) * ttm )
                         )
             );
}
</code>```

A slightly better formulated GBlackScholes_WHILEd() function - this saves ~ 22x float-OPs (some of which quite expensive) per each do{}while-LOOP :

```<code>def GBlackScholes_WHILEd( vol_,         // <--------------------------[VAR]:: ( high+low )/2 + 0.000000000000001;
                          V1,           // <--------------------------[VAR]:: vol_ * C3
                          is_call,
                          ttm_,         // do-while-(CONST)
                          C1, C2, C3,   // do-while-(CONST)
                          R1, R2        // do-while-(CONST)
                          ) {
  d1  = ( C1
        + C2
        * vol_*vol_ //--------------------do-while--------[VAR]
          )
        / V1;       //--------------------do-while--------[VAR]

  d2  = ( d1 //---------------------------do-while--------[VAR]
        - V1 //---------------------------do-while--------[VAR]
          );

  //    --[VAR]--- ? ( cdfNormal(------[VAR]) * <________________________________________________>--do-while-(CONST)
  return ( is_call ? ( cdfNormal( 0, 1,  d1 ) * R1
                     - cdfNormal( 0, 1,  d2 ) * R2
                       )
                   : ( cdfNormal( 0, 1, -d2 ) * R2
                     - cdfNormal( 0, 1, -d1 ) * R1
                       )
           );
}
</code>```

Finally :

The most efficiently formulated ImpliedVolatility() function avoids even all the call-signature per-loop processing at all, did some algebra and stays on the achievable performance edge :

```<code>def ImpliedVolatility( future_price,
                       strike,
                       ttm,
                       risk_rate,
                       b_rate,
                       option_price,
                       is_call
                       ) {
    high = 5.0;                                                 // IS THIS A UNIVERSALLY SAFE & TRUE SUPREME - i.e. SAFELY ABOVE ALL POSSIBLE OPTIONS ?
    low  = 0.0;

    ttm_ = ttm + 0.000000000000001;                             // do-while-(CONST)     1x fADD
    C1   = log(future_price ) - log( strike ) + b_rate;         // do-while-(CONST)     1x fADD  1x fDIV  1x fLOG  1x fNEG
    C2   =     ( ttm_ ) / 2;                                    // do-while-(CONST)              1x fDIV
    C3   = sqrt( ttm_ );                                        // do-while-(CONST)                       1x fSQRT
    R1   = future_price * exp( ( b_rate - risk_rate ) * ttm_ ); // do-while-(CONST)     1x fADD  2x fMUL  1x fEXP  1x fNEG
    R2   = strike       * exp(           -risk_rate   * ttm_ ); // do-while-(CONST)              2x fMUL  1x fEXP  1x fNEG
    U4   = C2   - ttm_;                                         // do-while-(CONST)     1x fADD                    1x fNEG
    U5   = ttm_ - C2;                                           // do-while-(CONST)     1x fADD                    1x fNEG
    U3inv= 1./ C3;                                              // do-while-(CONST)              1x fDIV

 // ------------------------------------------------------------// -----------------------------------------------------------------------------------------------
    if ( is_call ) {                                            // do-while-RE-TESTING: AVOIDED REPETITIVE per-loop COSTS of TESTING THE VERY THE SAME
                                                                // -----------------------------------------------------------------------------------------------
              do {
                    mid   = ( high + low ) / 2;       // cheapest  do-while per-loop-[VAR]-update
                    vol_  = mid + 0.000000000000001; //  cheapest  do-while per-loop-[VAR]-update
                    vol_2 = vol_ * vol_;            //   cheapest  do-while per-loop-[VAR]-update

                 /* ---------------------------------------------------------------------------------------------------------------------------------------------
                    HAS EVOLVED FROM THE ORIGINAL FORMULATION + AVOIDED REPETITIVE per-loop COSTS of 20+ expensive float OPs fully wasted,all in do-while-(CONST)
                                                              + AVOIDED REPETITIVE per-loop COSTS of all the CALL fun() STACK MANIPULATIONS AND RELATED OVERHEADS
                    ---------------------------------------------------------------------------------------------------------------------------------------------
                 */
                 // V4d1  =         ( C1 +   C2               * vol_2      ) / vol_ / C3;                            // [VAR]-dependent updates per loop
                 // V5d2  =         ( C1 + ( C2 - ttm_ )      * vol_2      ) / vol_ / C3;                            // [VAR]-dependent updates per loop
                 // Vmd2  =         (           ( ttm_ - C2 ) * vol_2 - C1 ) / vol_ / C3;                            // [VAR]-dependent updates per loop
                 //
                 // V4d1  = U3inv * ( C1 +                 C2 * vol_2      ) / vol_;                                 // fMUL faster than fDIV + a few more fUtilityCONSTs
                 // V5d2  = U3inv * ( C1 +                 U4 * vol_2      ) / vol_;                                 // fMUL faster than fDIV + a few more fUtilityCONSTs
                 // Vmd2  = U3inv * (                      U5 * vol_2 - C1 ) / vol_;                                 // fMUL faster than fDIV + a few more fUtilityCONSTs
                 //
                 // ---------------------------------------------------------------------------------------------------
                 // THIS AVOIDS RE-CALCULATION OF ALL do-while-(CONST)s BY THEIR RE-USE :
                 //
                 // if ( option_price < GBlackScholes_WHILEd( vol_,       // <----------[VAR] input_vol,             // GBlackScholes( future_price,
                 //                                           vol_ * C3,  // <----------[VAR] V1,                    //                strike,
                 //                                           is_call,    //                  is_call,               //                ttm,
                 //                                           ttm_,       // do-while-(CONST) ttm_,                  //                risk_rate,
                 //                                           C1, C2, C3, // do-while-(CONST) C1, C2, C3,            //                b_rate,
                 //                                           R1, R2      // do-while-(CONST) R1, R2                 //                mid,         // == (high+low)/2,
                 //                                           )           //                                         //                is_call
                 //      ) ...                                            //                                         //                )
                 //
                 // --------------------------------------------------------------------------------------------------
                 // EVEN BETTER :
                 //
                 // if ( option_price < ( is_call ? ( R1 * cdfNormal( 0, 1,  U3inv * ( C1 + C2 * vol_2      ) / vol_ )
                 //                                 - R2 * cdfNormal( 0, 1,  U3inv * ( C1 + U4 * vol_2      ) / vol_ )
                 //                                   )
                 //                               : ( R2 * cdfNormal( 0, 1,  U3inv * (      U5 * vol_2 - C1 ) / vol_ )
                 //                                 - R1 * cdfNormal( 0, 1, -U3inv * ( C1 + C2 * vol_2      ) / vol_ )
                 //                                   )
                 //                       )
                 //
                 //     ) ...
                 // ________________________________( CALL-OPTIONs )__________________________________________________

                    if ( option_price < (           ( R1 * cdfNormal( 0, 1,  U3inv * ( C1 + C2 * vol_2      ) / vol_ )
                                                    - R2 * cdfNormal( 0, 1,  U3inv * ( C1 + U4 * vol_2      ) / vol_ )
                                                      )
                                          )
                         ) {  high = mid;                             // == (high+low)/2;  // LOWER    HI-SIDE BRACKET
                    } else {   low = mid;                             // == (high+low)/2;  // HEIGHTEN LO-SIDE BRACKET
                    }
              } while ( ( high - low ) > 0.00001 );
              return    ( high + low ) / 2; // ________________________________________________________________ JIT/RET
    } else {
              do {  mid   = ( high + low ) / 2;       // cheapest  do-while per-loop-[VAR]-update
                    vol_  = mid + 0.000000000000001; //  cheapest  do-while per-loop-[VAR]-update
                    vol_2 = vol_ * vol_;            //   cheapest  do-while per-loop-[VAR]-update

                 // ________________________________( PUT-OPTIONs )___________________________________________________

                    if ( option_price < (           ( R2 * cdfNormal( 0, 1,  U3inv * (      U5 * vol_2 - C1 ) / vol_ )
                                                    - R1 * cdfNormal( 0, 1, -U3inv * ( C1 + C2 * vol_2      ) / vol_ )
                                                      )
                                          )
                         ) {  high = mid;                             // == (high+low)/2;  // LOWER    HI-SIDE BRACKET
                    } else {   low = mid;                             // == (high+low)/2;  // HEIGHTEN LO-SIDE BRACKET
                    }
              } while ( ( high - low ) > 0.00001 );
              return    ( high + low ) / 2; // ________________________________________________________________ JIT/RET
    }
}
</code>```

Body:
I am using DolphinDB to calculate Greeks, I wrote it in vectorized way, and the performance is quite good. But I can't implement implied volatility in vectorized way which makes the performance very poor. How can I improve the performance of the following implementation?

def GBlackScholes(future_price, strike, input_ttm, risk_rate, b_rate, input_vol, is_call) {
  ttm = input_ttm + 0.000000000000001;
  vol = input_vol + 0.000000000000001;

  d1 = (log(future_price/strike) + (b_rate + vol*vol/2) * ttm) / (vol * sqrt(ttm));
  d2 = d1 - vol * sqrt(ttm);

  if (is_call) {
    return future_price * exp((b_rate - risk_rate) * ttm) * cdfNormal(0, 1, d1) - strike * exp(-risk_rate*ttm) * cdfNormal(0, 1, d2);
  } else {
    return strike * exp(-risk_rate*ttm) * cdfNormal(0, 1, -d2) - future_price * exp((b_rate - risk_rate) * ttm) * cdfNormal(0, 1, -d1);
  }
}

def ImpliedVolatility(future_price, strike, ttm, risk_rate, b_rate, option_price, is_call) {
  high=5.0;
  low = 0.0;

  do {
    if (GBlackScholes(future_price, strike, ttm, risk_rate, b_rate, (high+low)/2, is_call) > option_price) {
      high = (high+low)/2;
    } else {
      low = (high + low) /2;
    }
  } while ((high-low) > 0.00001);

  return (high + low) /2;
}

Body:
Q : How can I improve the performance of the following implementation?

Vectorised processing ?

This part is a bit mysterious - forgive an old quant not to read this well enough - an information about which of the parameters was intended not to be a scalar was not present, so the analysis was based on the explicitly present pieces of information.

Disclaimer :
While I know that the DolphinDB has not published a ternary operator (...)?(...):(...) to be available in the public API, I feel the ideas expressed below are clear and sound.

Fighting Performance ?

If seriously talking about the performance, first let's review and principally avoid any repetitive re-calculations, that took place in the above proposed code :

def GBlackScholes( future_price,
                   strike,
                   input_ttm,
                   risk_rate,
                   b_rate,
                   input_vol,               // <------------[VAR]:: <-- ( high+low )/2
                   is_call                 //
                   ) {                    //
    ttm = input_ttm + 0.000000000000001; //-do-while-(CONST)
    vol = input_vol + 0.000000000000001;//--do-while--------[VAR]
                                       //
    d1  = ( log( future_price )       //----do-while-(CONST)
          - log( strike )            //-----do-while-(CONST)
          + b_rate                  //------do-while-(CONST)
          + vol*vol/2              //-------do-while--------[VAR]
          * ttm                   //--------do-while-(CONST)
            ) / ( vol            //---------do-while--------[VAR]
                * sqrt( ttm )   //----------do-while-(CONST)
                  );           //
    d2  = ( d1                //------------do-while--------[VAR]
          - vol              //-------------do-while--------[VAR]
          * sqrt( ttm )     //--------------do-while-(CONST)
            );             //              ++---------------[VAR]
                          //               ||     .________________________________________________.
 // -----------[VAR]-?-( cdfNormal(--------vv-) * [                                                ]--do-while-(CONST)
    return ( is_call ? ( cdfNormal( 0, 1,  d1 ) * future_price * exp( ( b_rate - risk_rate ) * ttm )
                       - cdfNormal( 0, 1,  d2 ) * strike       * exp(           -risk_rate   * ttm )
                         )
                     : ( cdfNormal( 0, 1, -d2 ) * strike       * exp(           -risk_rate   * ttm )
                       - cdfNormal( 0, 1, -d1 ) * future_price * exp( ( b_rate - risk_rate ) * ttm )
                         )
             );
}

A slightly better formulated GBlackScholes_WHILEd() function - this saves ~ 22x float-OPs (some of which quite expensive) per each do{}while-LOOP :

def GBlackScholes_WHILEd( vol_,         // <--------------------------[VAR]:: ( high+low )/2 + 0.000000000000001;
                          V1,           // <--------------------------[VAR]:: vol_ * C3
                          is_call,
                          ttm_,         // do-while-(CONST)
                          C1, C2, C3,   // do-while-(CONST)
                          R1, R2        // do-while-(CONST)
                          ) {
  d1  = ( C1
        + C2
        * vol_*vol_ //--------------------do-while--------[VAR]
          )
        / V1;       //--------------------do-while--------[VAR]

  d2  = ( d1 //---------------------------do-while--------[VAR]
        - V1 //---------------------------do-while--------[VAR]
          );

  //    --[VAR]--- ? ( cdfNormal(------[VAR]) * <________________________________________________>--do-while-(CONST)
  return ( is_call ? ( cdfNormal( 0, 1,  d1 ) * R1
                     - cdfNormal( 0, 1,  d2 ) * R2
                       )
                   : ( cdfNormal( 0, 1, -d2 ) * R2
                     - cdfNormal( 0, 1, -d1 ) * R1
                       )
           );
}

Finally :

The most efficiently formulated ImpliedVolatility() function avoids even all the call-signature per-loop processing at all, did some algebra and stays on the achievable performance edge :

def ImpliedVolatility( future_price,
                       strike,
                       ttm,
                       risk_rate,
                       b_rate,
                       option_price,
                       is_call
                       ) {
    high = 5.0;                                                 // IS THIS A UNIVERSALLY SAFE & TRUE SUPREME - i.e. SAFELY ABOVE ALL POSSIBLE OPTIONS ?
    low  = 0.0;

    ttm_ = ttm + 0.000000000000001;                             // do-while-(CONST)     1x fADD
    C1   = log(future_price ) - log( strike ) + b_rate;         // do-while-(CONST)     1x fADD  1x fDIV  1x fLOG  1x fNEG
    C2   =     ( ttm_ ) / 2;                                    // do-while-(CONST)              1x fDIV
    C3   = sqrt( ttm_ );                                        // do-while-(CONST)                       1x fSQRT
    R1   = future_price * exp( ( b_rate - risk_rate ) * ttm_ ); // do-while-(CONST)     1x fADD  2x fMUL  1x fEXP  1x fNEG
    R2   = strike       * exp(           -risk_rate   * ttm_ ); // do-while-(CONST)              2x fMUL  1x fEXP  1x fNEG
    U4   = C2   - ttm_;                                         // do-while-(CONST)     1x fADD                    1x fNEG
    U5   = ttm_ - C2;                                           // do-while-(CONST)     1x fADD                    1x fNEG
    U3inv= 1./ C3;                                              // do-while-(CONST)              1x fDIV

 // ------------------------------------------------------------// -----------------------------------------------------------------------------------------------
    if ( is_call ) {                                            // do-while-RE-TESTING: AVOIDED REPETITIVE per-loop COSTS of TESTING THE VERY THE SAME
                                                                // -----------------------------------------------------------------------------------------------
              do {
                    mid   = ( high + low ) / 2;       // cheapest  do-while per-loop-[VAR]-update
                    vol_  = mid + 0.000000000000001; //  cheapest  do-while per-loop-[VAR]-update
                    vol_2 = vol_ * vol_;            //   cheapest  do-while per-loop-[VAR]-update

                 /* ---------------------------------------------------------------------------------------------------------------------------------------------
                    HAS EVOLVED FROM THE ORIGINAL FORMULATION + AVOIDED REPETITIVE per-loop COSTS of 20+ expensive float OPs fully wasted,all in do-while-(CONST)
                                                              + AVOIDED REPETITIVE per-loop COSTS of all the CALL fun() STACK MANIPULATIONS AND RELATED OVERHEADS
                    ---------------------------------------------------------------------------------------------------------------------------------------------
                 */
                 // V4d1  =         ( C1 +   C2               * vol_2      ) / vol_ / C3;                            // [VAR]-dependent updates per loop
                 // V5d2  =         ( C1 + ( C2 - ttm_ )      * vol_2      ) / vol_ / C3;                            // [VAR]-dependent updates per loop
                 // Vmd2  =         (           ( ttm_ - C2 ) * vol_2 - C1 ) / vol_ / C3;                            // [VAR]-dependent updates per loop
                 //
                 // V4d1  = U3inv * ( C1 +                 C2 * vol_2      ) / vol_;                                 // fMUL faster than fDIV + a few more fUtilityCONSTs
                 // V5d2  = U3inv * ( C1 +                 U4 * vol_2      ) / vol_;                                 // fMUL faster than fDIV + a few more fUtilityCONSTs
                 // Vmd2  = U3inv * (                      U5 * vol_2 - C1 ) / vol_;                                 // fMUL faster than fDIV + a few more fUtilityCONSTs
                 //
                 // ---------------------------------------------------------------------------------------------------
                 // THIS AVOIDS RE-CALCULATION OF ALL do-while-(CONST)s BY THEIR RE-USE :
                 //
                 // if ( option_price < GBlackScholes_WHILEd( vol_,       // <----------[VAR] input_vol,             // GBlackScholes( future_price,
                 //                                           vol_ * C3,  // <----------[VAR] V1,                    //                strike,
                 //                                           is_call,    //                  is_call,               //                ttm,
                 //                                           ttm_,       // do-while-(CONST) ttm_,                  //                risk_rate,
                 //                                           C1, C2, C3, // do-while-(CONST) C1, C2, C3,            //                b_rate,
                 //                                           R1, R2      // do-while-(CONST) R1, R2                 //                mid,         // == (high+low)/2,
                 //                                           )           //                                         //                is_call
                 //      ) ...                                            //                                         //                )
                 //
                 // --------------------------------------------------------------------------------------------------
                 // EVEN BETTER :
                 //
                 // if ( option_price < ( is_call ? ( R1 * cdfNormal( 0, 1,  U3inv * ( C1 + C2 * vol_2      ) / vol_ )
                 //                                 - R2 * cdfNormal( 0, 1,  U3inv * ( C1 + U4 * vol_2      ) / vol_ )
                 //                                   )
                 //                               : ( R2 * cdfNormal( 0, 1,  U3inv * (      U5 * vol_2 - C1 ) / vol_ )
                 //                                 - R1 * cdfNormal( 0, 1, -U3inv * ( C1 + C2 * vol_2      ) / vol_ )
                 //                                   )
                 //                       )
                 //
                 //     ) ...
                 // ________________________________( CALL-OPTIONs )__________________________________________________

                    if ( option_price < (           ( R1 * cdfNormal( 0, 1,  U3inv * ( C1 + C2 * vol_2      ) / vol_ )
                                                    - R2 * cdfNormal( 0, 1,  U3inv * ( C1 + U4 * vol_2      ) / vol_ )
                                                      )
                                          )
                         ) {  high = mid;                             // == (high+low)/2;  // LOWER    HI-SIDE BRACKET
                    } else {   low = mid;                             // == (high+low)/2;  // HEIGHTEN LO-SIDE BRACKET
                    }
              } while ( ( high - low ) > 0.00001 );
              return    ( high + low ) / 2; // ________________________________________________________________ JIT/RET
    } else {
              do {  mid   = ( high + low ) / 2;       // cheapest  do-while per-loop-[VAR]-update
                    vol_  = mid + 0.000000000000001; //  cheapest  do-while per-loop-[VAR]-update
                    vol_2 = vol_ * vol_;            //   cheapest  do-while per-loop-[VAR]-update

                 // ________________________________( PUT-OPTIONs )___________________________________________________

                    if ( option_price < (           ( R2 * cdfNormal( 0, 1,  U3inv * (      U5 * vol_2 - C1 ) / vol_ )
                                                    - R1 * cdfNormal( 0, 1, -U3inv * ( C1 + C2 * vol_2      ) / vol_ )
                                                      )
                                          )
                         ) {  high = mid;                             // == (high+low)/2;  // LOWER    HI-SIDE BRACKET
                    } else {   low = mid;                             // == (high+low)/2;  // HEIGHTEN LO-SIDE BRACKET
                    }
              } while ( ( high - low ) > 0.00001 );
              return    ( high + low ) / 2; // ________________________________________________________________ JIT/RET
    }
}


来源: stackexchange

问:
Moving a Local mySQL database from Laravel/Homestead to live site database
I'm new here so sorry if this is posted in the wrong place >.<

I recently started using CraftCMS and decided to make a site with it. After looking at multiple forums about development I decided to use Laravel/Homestead to develop the site locally. It's working great! Everything is working fine, all the data is being saved and it works every time I boot up homestead.

The one question I have is how to move all this data from my local database to a live site. I have Bluehost and I know it's capable of mySQL and hosting a CraftCMS site. I just need to know how to transfer all the data.

I've been using Sequel Pro to monitor everything locally. So I feel like it's possible. Not really experienced with databases in this way. Just need a nudge in the right direction. Thanks!

答:
It's definitely possible.

If you can export your craft db with sequel pro (or the command line)

Assuming your local database env is root with

mysqldump -u root -p password mycraftdb > dump.sql

You'll need to import this sql file in phpmyadmin on bluehost
Here's a help doc. https://my.bluehost.com/hosting/help/256

Start a new database unless you're using the old tables in your new local craft site.  Definitely back up your old one.

Whenever you work with a host like Bluehost, godaddy, etc. You're going to have an obnoxious time trying to get everything configured to pass the system report for craftcms.  Sometimes you'll even have to reach out to the host to do something simple like upping a memory_limit.

Here's an article my friend wrote about his experiences using craftcms with these hosting environments. It could be helpful.

https://medium.com/@importantcoding/craftcms-how-i-hate-to-love-you-e0d26722a1d2

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Trouble with C# console code. Trying to get a while loop to average 3 test scores. Final product is only using the first number entered in while loop
Struggling with understanding the while loop. I'm just starting to learn programming. While testing the code, it appears as if only the second number entered gets processed into the final answer. </p>

```<code>  static void Main(string[] args)
    {
        Console.WriteLine("Enter test score");

        string input = Console.ReadLine();
        double value = Double.Parse(input);

        double sum = 0.0;
        int counter = 1;
        int total = 3;

        while (counter < total)
        {
            sum = sum + value;
            counter = counter + 1;

            Console.WriteLine("Enter another test score");
            input = Console.ReadLine();
            value = Double.Parse(input);

        }
        Console.WriteLine("Test score average is: {0:N2}", sum / total);
        Console.Read();
    }
</code>```

答:
You need your while loop to run three times so start the counter from 0 instead of 1.

Within the loop you can ask for the test scores and add them to the sum and then increment the counter.

double sum = 0.0;
int counter = 0;
int total = 3;
while (counter < total)
{
   Console.WriteLine("Enter test score");
   string input = Console.ReadLine();
   double value = double.Parse(input);
   sum += value;
   counter++;
}

Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
```

<p>Or like this if you need the question to be different, you can ask the question outside of the loop and save the result to the <code>sum</code> variable. Since we have already asked the question once we can make the <code>counter</code> start at 1 instead of 0.</p>

<pre class="lang-cs prettyprint-override"><code>double sum = 0.0;
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = double.Parse(input);

sum = sum + value;

int counter = 1;
int total = 3;
while (counter < total)
{
    Console.WriteLine("Enter another test score");
     input = Console.ReadLine();
     value = double.Parse(input);
    sum += value;
    counter++;
}

Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
</code>```

Body:
Struggling with understanding the while loop. I'm just starting to learn programming. While testing the code, it appears as if only the second number entered gets processed into the final answer.

  static void Main(string[] args)
    {
        Console.WriteLine("Enter test score");

        string input = Console.ReadLine();
        double value = Double.Parse(input);

        double sum = 0.0;
        int counter = 1;
        int total = 3;

        while (counter < total)
        {
            sum = sum + value;
            counter = counter + 1;

            Console.WriteLine("Enter another test score");
            input = Console.ReadLine();
            value = Double.Parse(input);

        }
        Console.WriteLine("Test score average is: {0:N2}", sum / total);
        Console.Read();
    }

Body:
You need your while loop to run three times so start the counter from 0 instead of 1.

Within the loop you can ask for the test scores and add them to the sum and then increment the counter.

double sum = 0.0;
int counter = 0;
int total = 3;
while (counter < total)
{
   Console.WriteLine("Enter test score");
   string input = Console.ReadLine();
   double value = double.Parse(input);
   sum += value;
   counter++;
}

Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();

Or like this if you need the question to be different, you can ask the question outside of the loop and save the result to the sum variable. Since we have already asked the question once we can make the counter start at 1 instead of 0.

double sum = 0.0;
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = double.Parse(input);

sum = sum + value;

int counter = 1;
int total = 3;
while (counter < total)
{
    Console.WriteLine("Enter another test score");
     input = Console.ReadLine();
     value = double.Parse(input);
    sum += value;
    counter++;
}

Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();


问:
Breakpoints Not Highlighting Line
I'm suddenly running into an odd problem with breakpoints in Visual Studio 2019 (this is for a C# solution).

Yesterday setting a breakpoint highlighted the entire source code line in the editor.

Today it only sets the red circle in the left-hand margin.

Something has changed but I have no idea what. How do I revert to the earlier behavior?

答:
I still don't know what happened but running the VS Installer and telling it to Modify the setup -- and then not making any changes -- fixed the problem.

Obviously something got messed up somewhere and I'd still love to know what happened. But the problem is gone...for now.

Title: Breakpoints Not Highlighting Line


问:
Creating a dataframe using declared variables
I'm trying to create a dataframe to assist in downstream calculations. All "MineralVars" need an NA value in this 1-row dataframe. MineralVars will always change in length and variable names, so I can't create the dataframe by inputting each Mineral one at a time. I need to create it using the string 'MineralVars'.

```<code># Declare variables
MineralVars <- c("Al", "Cu", "Pb")

# Create helper dataframe
Placeholder_df <- data.frame(make = "Placeholder", modelid = "Placeholder",
                             unitno = "Placeholder", compart = "Placeholder",
                             MineralVars = NA, meterread = NA, order = NA)
</code>```

My desired dataframe would look like this;

```<code>Desired_df <- data.frame(sampledate = NA, make = "Placeholder", modelid = "Placeholder",
                            unitno = "Placeholder", compart = "Placeholder", oilchanged = "Placeholder",
                            Cu = NA, Pb = NA, Al = NA, meterread = NA, order = NA)
</code>```

答:
We can just do an assignment

```<code>Placeholder_df[MineralVars] <- NA
</code>```

and remove the "MineralVars"

```<code>Placeholder_df["MineralVars"] <- NULL
</code>```

Or use add_column

```<code>library(tibble)
library(dplyr)
add_column(Placeholder_df,.before = "MineralVars",
    !!!setNames(rep(NA,length(MineralVars)), MineralVars))  %>%
      mutate(MineralVars = NULL)
 #      make     modelid      unitno     compart Al Cu Pb meterread order
#1 Placeholder Placeholder Placeholder Placeholder NA NA NA        NA    NA
</code>```

and assign (<-) it either 'Placeholder_df' or a new object

Body:
I'm trying to create a dataframe to assist in downstream calculations. All "MineralVars" need an NA value in this 1-row dataframe. MineralVars will always change in length and variable names, so I can't create the dataframe by inputting each Mineral one at a time. I need to create it using the string 'MineralVars'.

# Declare variables
MineralVars <- c("Al", "Cu", "Pb")

# Create helper dataframe
Placeholder_df <- data.frame(make = "Placeholder", modelid = "Placeholder",
                             unitno = "Placeholder", compart = "Placeholder",
                             MineralVars = NA, meterread = NA, order = NA)

My desired dataframe would look like this;

Desired_df <- data.frame(sampledate = NA, make = "Placeholder", modelid = "Placeholder",
                            unitno = "Placeholder", compart = "Placeholder", oilchanged = "Placeholder",
                            Cu = NA, Pb = NA, Al = NA, meterread = NA, order = NA)

Body:
We can just do an assignment

Placeholder_df[MineralVars] <- NA

and remove the "MineralVars"

Placeholder_df["MineralVars"] <- NULL

Or use add_column

library(tibble)
library(dplyr)
add_column(Placeholder_df,.before = "MineralVars",
    !!!setNames(rep(NA,length(MineralVars)), MineralVars))  %>%
      mutate(MineralVars = NULL)
 #      make     modelid      unitno     compart Al Cu Pb meterread order
#1 Placeholder Placeholder Placeholder Placeholder NA NA NA        NA    NA

and assign (<-) it either 'Placeholder_df' or a new object


问:
trying to use a function that return a button component but nothing get rendered
I am trying to use a function that return a button component but when calling this function, the button component didn't render. Everything rendered except this function. I have no errors no warnings and i have tried to separate this function in a separate file but still no rendering for that function.
I am using react-bootstrap. the function i am trying to call is activeProcessingBtn</p>

```<code>const activeProcessingBtn = () => {
  return (
    <div>
      <Button variant="primary" disabled>
        <Spinner
          as="span"
          animation="grow"
          size="sm"
          role="status"
          aria-hidden="true"
        />
        processing...
      </Button>
    </div>
  );
};
function Machines() {
  const [machineInfo, setMachineInfo] = useState({
    id: 0,
    name: "Choose Machine"
  });
  const [isProcessing, setIsProcessing] = useState(true);

  const Machiness = [
    { id: 1, name: "Machine1" },
    { id: 2, name: "Machine2" },
    { id: 3, name: "Machine3" }
  ];

  const selectHandler = (NewName, NewID) => {
    setMachineInfo({ id: NewID, name: NewName });
  };

  const AddMachinesToDropDownItem = Machiness.map(({ id, name }) => {
    return (
      <Dropdown.Item
        eventKey={id}
        value={name}
        className="DropdownItem"
        onClick={() => selectHandler(name, id)}
      >
        {name}
      </Dropdown.Item>
    );
  });

  return (
    <div>
      <h6> Get attendance Manually </h6>
      <DropdownButton id="DropDownMenu" title={machineInfo.name}>
        {AddMachinesToDropDownItem}
      </DropdownButton>

      <activeProcessingBtn />

    </div>
  );
}

export default Machines;

</code>```

答:
Instead of trying to treat it like a component (<activeProcessingBtn />), call it as a function.

```<code>return (
  <div>
    <h6> Get attendance Manually </h6>
    <DropdownButton id="DropDownMenu" title={machineInfo.name}>
      {AddMachinesToDropDownItem}
    </DropdownButton>

    // See here
    {activeProcessingBtn()}

  </div>
);
</code>```

Body:
I am trying to use a function that return a button component but when calling this function, the button component didn't render. Everything rendered except this function. I have no errors no warnings and i have tried to separate this function in a separate file but still no rendering for that function.
I am using react-bootstrap. the function i am trying to call is activeProcessingBtn

const activeProcessingBtn = () => {
  return (

      <Button variant="primary" disabled>
        <Spinner
          as="span"
          animation="grow"
          size="sm"
          role="status"
          aria-hidden="true"
        />
        processing...
      </Button>

  );
};
function Machines() {
  const [machineInfo, setMachineInfo] = useState({
    id: 0,
    name: "Choose Machine"
  });
  const [isProcessing, setIsProcessing] = useState(true);

  const Machiness = [
    { id: 1, name: "Machine1" },
    { id: 2, name: "Machine2" },
    { id: 3, name: "Machine3" }
  ];

  const selectHandler = (NewName, NewID) => {
    setMachineInfo({ id: NewID, name: NewName });
  };

  const AddMachinesToDropDownItem = Machiness.map(({ id, name }) => {
    return (
      <Dropdown.Item
        eventKey={id}
        value={name}
        className="DropdownItem"
        onClick={() => selectHandler(name, id)}
      >
        {name}
      </Dropdown.Item>
    );
  });

  return (

 Get attendance Manually

      <DropdownButton id="DropDownMenu" title={machineInfo.name}>
        {AddMachinesToDropDownItem}
      </DropdownButton>

      <activeProcessingBtn />

  );
}

export default Machines;

Body:
Instead of trying to treat it like a component (<activeProcessingBtn />), call it as a function.

return (
  <div>
    <h6> Get attendance Manually </h6>
    <DropdownButton id="DropDownMenu" title={machineInfo.name}>
      {AddMachinesToDropDownItem}
    </DropdownButton>

    // See here
    {activeProcessingBtn()}

  </div>
);


问:
Angular component inside angular component? `<comp0><comp1></comp1></comp0>`
I've tried with ng-template and with ng-container, but I can't figure out how to include a component inside a component…

import { Component } from '@angular/core';

@Component({
  selector: 'hello',
  //  template: `<h1>Hello</h1><div>I am in a div<ng-container></ng-container>; now this is end</div>`,
  template: `<h1>Hello</h1><div>I am in a div<ng-template></ng-template>; now this is end</div>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {}

@Component({
  selector: 'intestines',
  template: 'Eww',
  styles: []
})
export class IntestinesComponent  {}

@Component({
  selector: 'my-app',
  template: `<hello><intestines></intestines></hello>`,
  styles: [ 'p { font-family: Lato; }' ]
})
export class AppComponent  {}
```

https://stackblitz.com/edit/angular-2b2yl3

答:
Use ng-content

```<code>@Component({
  selector: 'hello',
  template: `<h1>Hello</h1><div>I am in a div<ng-content></ng-content>; now this is end</div>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {}
</code>```

Also check this article may be useful for you.

Body:
I've tried with ng-template and with ng-container, but I can't figure out how to include a component inside a component…

import { Component } from '@angular/core';

@Component({
  selector: 'hello',
  //  template: `<h1>Hello</h1><div>I am in a div<ng-container></ng-container>; now this is end</div>`,
  template: `<h1>Hello</h1><div>I am in a div<ng-template></ng-template>; now this is end</div>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {}

@Component({
  selector: 'intestines',
  template: 'Eww',
  styles: []
})
export class IntestinesComponent  {}

@Component({
  selector: 'my-app',
  template: `<hello><intestines></intestines></hello>`,
  styles: [ 'p { font-family: Lato; }' ]
})
export class AppComponent  {}

https://stackblitz.com/edit/angular-2b2yl3

Body:
Use ng-content

@Component({
  selector: 'hello',
  template: `<h1>Hello</h1><div>I am in a div<ng-content></ng-content>; now this is end</div>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {}

Also check this article may be useful for you.


问:
Eclipse: Android not adding id class to R.java
I am currently writing a program for an android app and I keep running into a problem where I get an error "id cannot be resolved or is not a field". For example I have a line of code:

```<code>mBodyText = (EditText) findViewById(R.id.body);
</code>```

After viewing the R.java class there is no id class. I previously copied and pasted an example online and it also implemented a line of code that was similar and it added the id class to R.java.

I'm just wondering how to correct this problem. I have researched it and some people suggested to others to import android.R and this corrects some errors but then creates new ones saying that the part after is not in that category.

答: Sometimes cleaning the project resolves problems like this.  (Select clean from the project menu.)</p>

Body:
I am currently writing a program for an android app and I keep running into a problem where I get an error "id cannot be resolved or is not a field". For example I have a line of code:

mBodyText = (EditText) findViewById(R.id.body);

After viewing the R.java class there is no id class. I previously copied and pasted an example online and it also implemented a line of code that was similar and it added the id class to R.java.

I'm just wondering how to correct this problem. I have researched it and some people suggested to others to import android.R and this corrects some errors but then creates new ones saying that the part after is not in that category.


答: All component names should start with an uppercase letter. This is what React uses to figure out whether it should consider an element a native HTML element and pass it over to the browser or further resolve what it renders. So your best option would be to rename the function to ActiveProcessingBtn or ActiveProcessingButton.

Title: trying to use a function that return a button component but nothing get rendered


问:
How to get group statistics in Pandas
I have a dataset looking like this for simplication:

```<code>lst = [
       ["2015", "A"],
       ["2015", "B"],
       ["2015", "C"],
       ["2016", "A"],
       ["2016", "A"],
       ["2016", "B"],
       ["2016", "D"]

      ]

df = pd.DataFrame(lst, columns =["Year", "Item"])
</code>```

I want to generate some stats like the following. How can I do this using Pandas? My actual dataset has tens of thousands of observations, and many different items.

Thank you!

答:
Consider running inline aggregates with transform and merge on a data frame of all possible values. Finally, clean up with fillna procedures:

```<code>from itertools import product
...
years_items_df = pd.DataFrame(product(["2015", "2016"], list("ABCD")),
                              columns = ["Year", "Item"])

df = (df.assign(Count = lambda x: x.groupby(["Year", "Item"])["Year"].transform("count"),
                AnnualCount = lambda x: x.groupby(["Year"])["Year"].transform("count"))
        .drop_duplicates()
        .merge(years_items_df, on=["Year", "Item"], how="right")
        .sort_values(["Year", "Item"])
        .assign(Count = lambda x: x['Count'].fillna(0),
                AnnualCount = lambda x: x['AnnualCount'].ffill(),
                Percent = lambda x: x["Count"].div(x["AnnualCount"]))
        .reset_index(drop=True)
      )

df
#    Year Item  Count  AnnualCount   Percent
# 0  2015    A    1.0          3.0  0.333333
# 1  2015    B    1.0          3.0  0.333333
# 2  2015    C    1.0          3.0  0.333333
# 3  2015    D    0.0          3.0  0.000000
# 4  2016    A    2.0          4.0  0.500000
# 5  2016    B    1.0          4.0  0.250000
# 6  2016    C    0.0          4.0  0.000000
# 7  2016    D    1.0          4.0  0.250000
</code>```

Title: How to get group statistics in Pandas

Body:
I have a dataset looking like this for simplication:

lst = [
       ["2015", "A"],
       ["2015", "B"],
       ["2015", "C"],
       ["2016", "A"],
       ["2016", "A"],
       ["2016", "B"],
       ["2016", "D"]

      ]

df = pd.DataFrame(lst, columns =["Year", "Item"])

I want to generate some stats like the following. How can I do this using Pandas? My actual dataset has tens of thousands of observations, and many different items.

Thank you!

Body:
Consider running inline aggregates with transform and merge on a data frame of all possible values. Finally, clean up with fillna procedures:

from itertools import product
...
years_items_df = pd.DataFrame(product(["2015", "2016"], list("ABCD")),
                              columns = ["Year", "Item"])

df = (df.assign(Count = lambda x: x.groupby(["Year", "Item"])["Year"].transform("count"),
                AnnualCount = lambda x: x.groupby(["Year"])["Year"].transform("count"))
        .drop_duplicates()
        .merge(years_items_df, on=["Year", "Item"], how="right")
        .sort_values(["Year", "Item"])
        .assign(Count = lambda x: x['Count'].fillna(0),
                AnnualCount = lambda x: x['AnnualCount'].ffill(),
                Percent = lambda x: x["Count"].div(x["AnnualCount"]))
        .reset_index(drop=True)
      )

df
#    Year Item  Count  AnnualCount   Percent
# 0  2015    A    1.0          3.0  0.333333
# 1  2015    B    1.0          3.0  0.333333
# 2  2015    C    1.0          3.0  0.333333
# 3  2015    D    0.0          3.0  0.000000
# 4  2016    A    2.0          4.0  0.500000
# 5  2016    B    1.0          4.0  0.250000
# 6  2016    C    0.0          4.0  0.000000
# 7  2016    D    1.0          4.0  0.250000


问:
Python multiprocessing slowed down even in mono-thread
I want to run the same code in parallel using multiprocess.

My process code run in 8 minutes alone. In 10 minutes when using the "force mono-thread" thing. But when I run 24 of them in parallel, each instance takes approximately 1 hour.

Before, when each process spanned threads furiously like a mad man, I had context switches of 1.6M.
I then used the following env. variables to force Numpy to only use one thread per process:

os.environ["NUMEXPR_NUM_THREADS"] = '1'
os.environ["OMP_NUM_THREADS"] = '1'
os.environ["MKL_THREADING_LAYER"] = "sequential"  # Better than setting MKL_NUM_THREADS=1 (source: https://software.intel.com/en-us/node/528380)
```

Even after that, my problem remains. I have runtime around 1 hour per process.
Using glances, apart from the CPU that is used at 95-100% (red in glances) the rest is green, memory, bandwith, even context switches is back to normal at around 5K.

Do you have an idea of why this happens? I don't get why this is 6 times slower in parallel when no obvious indicator pop up in glances

Here is in attachement a screen capture of glances

答:
Without a "minimal code example", it is indeed difficult to answer, so instead of a straight answer, I'll provide some code. I've experimented with:

```<code>import os
os.environ['OMP_NUM_THREADS'] = '1'
import numpy as np
import time
def tns(): return time.time_ns() / 1e9

def nps(vec, its=100):
    return min(np.linalg.norm(vec - np.random.randn(len(vec))) for _ in range(its))

start = tns()
s = nps(np.random.randn(100_000))
end = tns()
print("{} took {}".format(s, end - start))
</code>```

On my machine, setting OMP_NUM_THREADS=1 yields a ~2.5 times speed-up. The explanation I received from #numpy on freenode was that my code is memory-bound and thus multi-threading won't help.

Body:
I want to run the same code in parallel using multiprocess.

My process code run in 8 minutes alone. In 10 minutes when using the "force mono-thread" thing. But when I run 24 of them in parallel, each instance takes approximately 1 hour.

Before, when each process spanned threads furiously like a mad man, I had context switches of 1.6M.
I then used the following env. variables to force Numpy to only use one thread per process:

os.environ["NUMEXPR_NUM_THREADS"] = '1'
os.environ["OMP_NUM_THREADS"] = '1'
os.environ["MKL_THREADING_LAYER"] = "sequential"  # Better than setting MKL_NUM_THREADS=1 (source: https://software.intel.com/en-us/node/528380)

Even after that, my problem remains. I have runtime around 1 hour per process.
Using glances, apart from the CPU that is used at 95-100% (red in glances) the rest is green, memory, bandwith, even context switches is back to normal at around 5K.

Do you have an idea of why this happens? I don't get why this is 6 times slower in parallel when no obvious indicator pop up in glances

Here is in attachement a screen capture of glances

Body:
Without a "minimal code example", it is indeed difficult to answer, so instead of a straight answer, I'll provide some code. I've experimented with:

import os
os.environ['OMP_NUM_THREADS'] = '1'
import numpy as np
import time
def tns(): return time.time_ns() / 1e9

def nps(vec, its=100):
    return min(np.linalg.norm(vec - np.random.randn(len(vec))) for _ in range(its))

start = tns()
s = nps(np.random.randn(100_000))
end = tns()
print("{} took {}".format(s, end - start))

On my machine, setting OMP_NUM_THREADS=1 yields a ~2.5 times speed-up. The explanation I received from #numpy on freenode was that my code is memory-bound and thus multi-threading won't help.


问:
Performance issues with applications deployed on Tomcat
Recently we have migrated all our companies applications from Websphere to Tomcat application server. As part of this process we had performance testing done.

We found that couple of applications are having over 100% performance degradation in Tomcat. We increased the number of threads, we configured datasource settings to accommodate our test, we have also increased the read and write buffer sizes in the Tomcat server.

```<code>Application Background:

-> Spring Framework
-> Hibernate
-> Oracle 12c
-> JSPs
-> OpenJDK 8
</code>```

We already checked the database and found no issues with performance in DB.

The CPU utilization while running the test is always less than 10%.

Heap settings are -xms = 1.5G to -xmx = 2G, and it never utilizes more than 1.2G.

We also have two nodes and HAProxy on top to balance the load. (We don't have a web server in place).

Despite our best efforts we couldn't pinpoint the issue that is causing the performance degradation. I am aware that this information isn't enough to provide a solution for our problem, however, any suggestion on how to proceed will be very helpful as we hit a dead-end and are unable to proceed.

Appreciate it if you can share any points that will be helpful in finding the issue.

Thanks.

答:
Take Thread Dumps and analyze which part of application is having issues and start troubleshoot from there.

Follow this article for detailed explanation about Thread Dumps analysis - https://dzone.com/articles/how-analyze-java-thread-dumps

Body:
Recently we have migrated all our companies applications from Websphere to Tomcat application server. As part of this process we had performance testing done.

We found that couple of applications are having over 100% performance degradation in Tomcat. We increased the number of threads, we configured datasource settings to accommodate our test, we have also increased the read and write buffer sizes in the Tomcat server.

Application Background:

-> Spring Framework
-> Hibernate
-> Oracle 12c
-> JSPs
-> OpenJDK 8

We already checked the database and found no issues with performance in DB.

The CPU utilization while running the test is always less than 10%.

Heap settings are -xms = 1.5G to -xmx = 2G, and it never utilizes more than 1.2G.

We also have two nodes and HAProxy on top to balance the load. (We don't have a web server in place).

Despite our best efforts we couldn't pinpoint the issue that is causing the performance degradation. I am aware that this information isn't enough to provide a solution for our problem, however, any suggestion on how to proceed will be very helpful as we hit a dead-end and are unable to proceed.

Appreciate it if you can share any points that will be helpful in finding the issue.

Thanks.


问:
Close or redirect tab window through using Google Apps script
I am trying to run a script that when a if() statement returns false it closes the current tab window of the google sheet or it redirects to another URL (as long as one of these work, thats ok for me).

I understand that this may be possible through using HTML but i don't know HTML well enough to do this.

I have found the below code which is meant to redirect to a different page which I tried but this does not work:

```<code>      return HtmlService.createHtmlOutput(
        "<form action='http://www.google.com' method='get' id='foo'></form>" +
        "<script>document.getElementById('foo').submit();</script>");
</code>```

Does anyone have any ideas?

See code that this is in below below:

```<code>  if (name == password)
  {
    Browser.msgBox('You have succesfully logged in');
    sortOutSheets();
  }
  else (name != password)
  {
    var response = Browser.msgBox('Login Failed - do you want to login again?', Browser.Buttons.YES_NO);
    if(response == "yes")
      enterPassword();
    else(response == "no")
    HtmlService.createHtmlOutputFromFile('Close Window');
  }
}
</code>```

I have now turned to writing the HTML in another HTML file but still no luck

答:
Here are the steps that I would program.

Show Dialog box in spreadsheet asking for a password

User enters password

User clicks Submit button

Client side code calls the server and sends the password to code in GS file

Server code tests the password

If password is good, build new HTML and open another dialog box

The opening of a new dialog box will automatically close the first dialog box

The new dialog box will have a  tag link in it, built with a new url on the server

When the new dialog box opens, automatically run code with window.onload = function() {var aTagElement; aTagElement = document.getElementById('idOfLinkTag');aTagElement.click() }

The client code will automatically run when the dialog box opens, and programmatically click the link, which will open a new file in the same browser tab

Body:
I am trying to run a script that when a if() statement returns false it closes the current tab window of the google sheet or it redirects to another URL (as long as one of these work, thats ok for me).

I understand that this may be possible through using HTML but i don't know HTML well enough to do this.

I have found the below code which is meant to redirect to a different page which I tried but this does not work:

      return HtmlService.createHtmlOutput(
        "<form action='http://www.google.com' method='get' id='foo'></form>" +
        "");

Does anyone have any ideas?

See code that this is in below below:

  if (name == password)
  {
    Browser.msgBox('You have succesfully logged in');
    sortOutSheets();
  }
  else (name != password)
  {
    var response = Browser.msgBox('Login Failed - do you want to login again?', Browser.Buttons.YES_NO);
    if(response == "yes")
      enterPassword();
    else(response == "no")
    HtmlService.createHtmlOutputFromFile('Close Window');
  }
}

I have now turned to writing the HTML in another HTML file but still no luck

Body:
Here are the steps that I would program.

Show Dialog box in spreadsheet asking for a password

User enters password

User clicks Submit button

Client side code calls the server and sends the password to code in GS file

Server code tests the password

If password is good, build new HTML and open another dialog box

The opening of a new dialog box will automatically close the first dialog box

The new dialog box will have a <a> tag link in it, built with a new url on the server

When the new dialog box opens, automatically run code with window.onload = function() {var aTagElement; aTagElement = document.getElementById('idOfLinkTag');aTagElement.click() }

The client code will automatically run when the dialog box opens, and programmatically click the link, which will open a new file in the same browser tab


问:
Multiple Gatsby wrapRootElement (implementing Auth0 and Redux)
Im trying to implement Gatsby with both Auth0 and Redux

As both Auth0 and Redux needs to use wrapRootElement in gatsby-browser.js, how can I merge the two in order to use them successfully in gatsby? Thanks in advance

gatsby-browser.js

```<code>// used by Auth0
export const wrapRootElement = ({ element }) => {
  return <SessionCheck>{element}</SessionCheck>
}

// used by Redux
export { default as wrapRootElement } from "./src/state/ReduxWrapper"
</code>```

gatsby-ssr.js

Take note Im also importing then exporting ReduxWrapper in gatsby-ssr.js

```<code>// export { default as wrapRootElement } from "./src/store/ReduxWrapper"
</code>```

ReduxWrapper.js

```<code>import React from "react"
import { Provider } from "react-redux"
import { createStore as reduxCreateStore } from "redux"
import rootReducer from "."

const createStore = () => reduxCreateStore(rootReducer)

export default ({ element }) => (
  <Provider store={createStore()}>{element}</Provider>
)
</code>```

I tried doing the following in gatsby-browser.js but it returns a blank page

```<code>export const wrapRootElement = ({ element }) => {
  return (
    <SessionCheck>
      <ReduxWrapper>{element}</ReduxWrapper>
    </SessionCheck>
  )
}
</code>```

答:
Thanks to Jeremy Albright, here's the solution to above issue. Happy coding

Basically, element should be passed as a prop to ReduxWrapper and NOT as a children

gatsby-browser.js

```<code>export const wrapRootElement = props => {
  return (
    <SessionCheck>
      <ReduxWrapper {...props} />
    </SessionCheck>
  )
}
</code>```

Body:
Im trying to implement Gatsby with both Auth0 and Redux

As both Auth0 and Redux needs to use wrapRootElement in gatsby-browser.js, how can I merge the two in order to use them successfully in gatsby? Thanks in advance

gatsby-browser.js

// used by Auth0
export const wrapRootElement = ({ element }) => {
  return <SessionCheck>{element}</SessionCheck>
}

// used by Redux
export { default as wrapRootElement } from "./src/state/ReduxWrapper"

gatsby-ssr.js

Take note Im also importing then exporting ReduxWrapper in gatsby-ssr.js

// export { default as wrapRootElement } from "./src/store/ReduxWrapper"

ReduxWrapper.js

import React from "react"
import { Provider } from "react-redux"
import { createStore as reduxCreateStore } from "redux"
import rootReducer from "."

const createStore = () => reduxCreateStore(rootReducer)

export default ({ element }) => (
  <Provider store={createStore()}>{element}</Provider>
)

I tried doing the following in gatsby-browser.js but it returns a blank page

export const wrapRootElement = ({ element }) => {
  return (
    <SessionCheck>
      <ReduxWrapper>{element}</ReduxWrapper>
    </SessionCheck>
  )
}

Body:
Thanks to Jeremy Albright, here's the solution to above issue. Happy coding

Basically, element should be passed as a prop to ReduxWrapper and NOT as a children

gatsby-browser.js

export const wrapRootElement = props => {
  return (
    <SessionCheck>
      <ReduxWrapper {...props} />
    </SessionCheck>
  )
}


问:
ng help - 'ng' is not recognized as an internal or external command
ng command is not getting recognized when used. I have already tried installing angular at global level and did the settings as per

Angular's - 'ng' is not recognized as an internal or external command, operable program or batch file

angularjs/cli- Ng is command is not working as globle

but no luck.

Can you please let me know what specific settings are required to achieve this.

Error: ng' is not recognized as an internal or external command,
  operable program or batch file.

Adding project structure as needed

答: Install Node.js and angular as an administrator or give your user an administrator role. </p>


问:
react-chartjs2 manage max value

There is my chartjs2 horizontal bar chart.
I want to manage max value.

If you see second chart, max value is 14, and min value is 13.
I want to manage the max and min gap.
I mean, I want the second chart to display   x-coordinate's min value is 10 and max is more 14.(probably 15 or 16)
Also I don't want to show cut the data label.
The max value label is cut. 14

I tried to max value plus some rest value, but it was not good.
;(

Pleas give your ideas.

Thanks.

答:
I changed option which is align property.</p>

```<code>plugins: {
        datalabels: {
          align: 'top',
          anchor: 'end',
          color: 'rgb(16,0,0)'
        }
      }
</code>```

Title: react-chartjs2 manage max value

Body:
I changed option which is align property.

plugins: {
        datalabels: {
          align: 'top',
          anchor: 'end',
          color: 'rgb(16,0,0)'
        }
      }


问:
How to base64 encode and decode a column in python pandas?
I read this post

encoding a dataframe

but I do not want to encrypt the dataframe, just convert it to base 64. I import a carriage return delimited list of words into a dataframe with:

```<code>words = pd.read_table("sampleText.txt",names=['word'], header=None)
words.head()
</code>```

that gives

```<code>    word
0   difference
1   where
2   mc
3   is
4   the
</code>```

then

```<code>words['words_encoded'] = map(lambda x: x.encode('base64','strict'), words['word'])
print (words)
</code>```

gave

```<code>                word                   words_encoded
0         difference  <map object at 0x7fad3e89e410>
1              where  <map object at 0x7fad3e89e410>
2                 mc  <map object at 0x7fad3e89e410>
3                 is  <map object at 0x7fad3e89e410>
4                the  <map object at 0x7fad3e89e410>
...              ...                             ...
999995  distribution  <map object at 0x7fad3e89e410>
999996            in  <map object at 0x7fad3e89e410>
999997      scenario  <map object at 0x7fad3e89e410>
999998          less  <map object at 0x7fad3e89e410>
999999          land  <map object at 0x7fad3e89e410>

[1000000 rows x 2 columns]
</code>```

I dont understand why my encoded column refers to a map object and not the actual data so I tried:

```<code>b64words = words.word.str.encode('base64')
print(b64words)
</code>```

gives

```<code>0        NaN
1        NaN
2        NaN
3        NaN
4        NaN
          ..
999995   NaN
999996   NaN
999997   NaN
999998   NaN
999999   NaN
Name: word, Length: 1000000, dtype: float64
</code>```

Well,

That threw me so I read the linked answer above and tried

```<code>import base64
def encode(text):
    return base64.b64encode(text)
words['Encoded_Column'] = [encode(x) for x in words]
</code>```

but got

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-8cf5a6f1f3a9> in <module>
      2 def encode(text):
      3     return base64.b64encode(text)
----> 4 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-89-8cf5a6f1f3a9> in <listcomp>(.0)
      2 def encode(text):
      3     return base64.b64encode(text)
----> 4 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-89-8cf5a6f1f3a9> in encode(text)
      1 import base64
      2 def encode(text):
----> 3     return base64.b64encode(text)
      4 words['Encoded_Column'] = [encode(x) for x in words]

~/miniconda3/envs/p37cu10.2PyTo/lib/python3.7/base64.py in b64encode(s, altchars)
     56     application to e.g. generate url or filesystem safe Base64 strings.
     57     """
---> 58     encoded = binascii.b2a_base64(s, newline=False)
     59     if altchars is not None:
     60         assert len(altchars) == 2, repr(altchars)

TypeError: a bytes-like object is required, not 'str'
</code>```

so I tried converting to a bytes like object like so:

```<code>import base64
def encode(text):
    btext = text.str.encode('utf-8')
    return base64.b64encode(btext)
words['Encoded_Column'] = [encode(x) for x in words]
</code>```

but got

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-90-46db6d3688ba> in <module>
      3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
----> 5 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-90-46db6d3688ba> in <listcomp>(.0)
      3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
----> 5 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-90-46db6d3688ba> in encode(text)
      1 import base64
      2 def encode(text):
----> 3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
      5 words['Encoded_Column'] = [encode(x) for x in words]

AttributeError: 'str' object has no attribute 'str'
</code>```

in this C example they are also converting first to byte strings and then to base64 like but I cannot do this simple task in Python.I am falling down this rabbit hole and every attempt just gets me deeper. I really appreciate any help that a clear minded person can give.

答:
map returns an iterator, not a list, so pandas simply assigned it to all of the slots in the newly formed "words_encoded" column. Similarly, if you did words['all_ones'] = 1, pandas would assign a 1 down that column.

Secondly, "base64" isn't a codec for strings, it works on bytes. You have to choose a text encoding and then encode that. So,

```<code>words['word_encoded'] = words.word.str.encode(
    'utf-8', 'strict').str.encode('base64')
</code>```

works except that this encoder puts a "\n" on the end of the base64 string, which I find odd. Instead, you can do one of the following

```<code>words['word_encoded'] = words.word.str.encode(
    'utf-8', 'strict').apply(
         base64.b64encode)

# or

words['word_encoded'] = [base64.b64encode(x.encode('utf-8', 'strict'))
    for x in words.word]
</code>```

Personally I think the first one is a bit more "pandas" as it generates the Series directly without an intermediate list.

The solution in action

```<code>>>> import base64
>>> import pandas as pd
>>> words = pd.read_table("sampleText.txt",names=['word'], header=None)
__main__:1: FutureWarning: read_table is deprecated, use read_csv instead, passing sep='\t'.
>>> words['word_encoded'] = words.word.str.encode(
...     'utf-8', 'strict').str.encode('base64')
>>>
>>> words
         word           word_encoded
0  difference  b'ZGlmZmVyZW5jZQ==\n'
1       where          b'd2hlcmU=\n'
2          mc              b'bWM=\n'
3          is              b'aXM=\n'
4         the              b'dGhl\n'
>>>
>>> words['word_encoded'] = words.word.str.encode(
...     'utf-8', 'strict').apply(
...          base64.b64encode)
>>>
>>> words
         word         word_encoded
0  difference  b'ZGlmZmVyZW5jZQ=='
1       where          b'd2hlcmU='
2          mc              b'bWM='
3          is              b'aXM='
4         the              b'dGhl'
>>>
>>> words['word_encoded'] = [base64.b64encode(x.encode('utf-8', 'strict'))
...     for x in words.word]
>>>
>>> words
         word         word_encoded
0  difference  b'ZGlmZmVyZW5jZQ=='
1       where          b'd2hlcmU='
2          mc              b'bWM='
3          is              b'aXM='
4         the              b'dGhl'
</code>```

Body:
I read this post

encoding a dataframe

but I do not want to encrypt the dataframe, just convert it to base 64. I import a carriage return delimited list of words into a dataframe with:

words = pd.read_table("sampleText.txt",names=['word'], header=None)
words.head()

that gives

    word
0   difference
1   where
2   mc
3   is
4   the

then

words['words_encoded'] = map(lambda x: x.encode('base64','strict'), words['word'])
print (words)

gave

                word                   words_encoded
0         difference  <map object at 0x7fad3e89e410>
1              where  <map object at 0x7fad3e89e410>
2                 mc  <map object at 0x7fad3e89e410>
3                 is  <map object at 0x7fad3e89e410>
4                the  <map object at 0x7fad3e89e410>
...              ...                             ...
999995  distribution  <map object at 0x7fad3e89e410>
999996            in  <map object at 0x7fad3e89e410>
999997      scenario  <map object at 0x7fad3e89e410>
999998          less  <map object at 0x7fad3e89e410>
999999          land  <map object at 0x7fad3e89e410>

[1000000 rows x 2 columns]

I dont understand why my encoded column refers to a map object and not the actual data so I tried:

b64words = words.word.str.encode('base64')
print(b64words)

gives

0        NaN
1        NaN
2        NaN
3        NaN
4        NaN
          ..
999995   NaN
999996   NaN
999997   NaN
999998   NaN
999999   NaN
Name: word, Length: 1000000, dtype: float64

Well,

That threw me so I read the linked answer above and tried

import base64
def encode(text):
    return base64.b64encode(text)
words['Encoded_Column'] = [encode(x) for x in words]

but got

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-8cf5a6f1f3a9> in <module>
      2 def encode(text):
      3     return base64.b64encode(text)
----> 4 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-89-8cf5a6f1f3a9> in <listcomp>(.0)
      2 def encode(text):
      3     return base64.b64encode(text)
----> 4 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-89-8cf5a6f1f3a9> in encode(text)
      1 import base64
      2 def encode(text):
----> 3     return base64.b64encode(text)
      4 words['Encoded_Column'] = [encode(x) for x in words]

~/miniconda3/envs/p37cu10.2PyTo/lib/python3.7/base64.py in b64encode(s, altchars)
     56     application to e.g. generate url or filesystem safe Base64 strings.
     57     """
---> 58     encoded = binascii.b2a_base64(s, newline=False)
     59     if altchars is not None:
     60         assert len(altchars) == 2, repr(altchars)

TypeError: a bytes-like object is required, not 'str'

so I tried converting to a bytes like object like so:

import base64
def encode(text):
    btext = text.str.encode('utf-8')
    return base64.b64encode(btext)
words['Encoded_Column'] = [encode(x) for x in words]

but got

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-90-46db6d3688ba> in <module>
      3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
----> 5 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-90-46db6d3688ba> in <listcomp>(.0)
      3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
----> 5 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-90-46db6d3688ba> in encode(text)
      1 import base64
      2 def encode(text):
----> 3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
      5 words['Encoded_Column'] = [encode(x) for x in words]

AttributeError: 'str' object has no attribute 'str'

in this C example they are also converting first to byte strings and then to base64 like but I cannot do this simple task in Python.I am falling down this rabbit hole and every attempt just gets me deeper. I really appreciate any help that a clear minded person can give.

Body:
map returns an iterator, not a list, so pandas simply assigned it to all of the slots in the newly formed "words_encoded" column. Similarly, if you did words['all_ones'] = 1, pandas would assign a 1 down that column.

Secondly, "base64" isn't a codec for strings, it works on bytes. You have to choose a text encoding and then encode that. So,

words['word_encoded'] = words.word.str.encode(
    'utf-8', 'strict').str.encode('base64')

works except that this encoder puts a "\n" on the end of the base64 string, which I find odd. Instead, you can do one of the following

words['word_encoded'] = words.word.str.encode(
    'utf-8', 'strict').apply(
         base64.b64encode)

# or

words['word_encoded'] = [base64.b64encode(x.encode('utf-8', 'strict'))
    for x in words.word]

Personally I think the first one is a bit more "pandas" as it generates the Series directly without an intermediate list.

The solution in action

>>> import base64
>>> import pandas as pd
>>> words = pd.read_table("sampleText.txt",names=['word'], header=None)
__main__:1: FutureWarning: read_table is deprecated, use read_csv instead, passing sep='\t'.
>>> words['word_encoded'] = words.word.str.encode(
...     'utf-8', 'strict').str.encode('base64')
>>>
>>> words
         word           word_encoded
0  difference  b'ZGlmZmVyZW5jZQ==\n'
1       where          b'd2hlcmU=\n'
2          mc              b'bWM=\n'
3          is              b'aXM=\n'
4         the              b'dGhl\n'
>>>
>>> words['word_encoded'] = words.word.str.encode(
...     'utf-8', 'strict').apply(
...          base64.b64encode)
>>>
>>> words
         word         word_encoded
0  difference  b'ZGlmZmVyZW5jZQ=='
1       where          b'd2hlcmU='
2          mc              b'bWM='
3          is              b'aXM='
4         the              b'dGhl'
>>>
>>> words['word_encoded'] = [base64.b64encode(x.encode('utf-8', 'strict'))
...     for x in words.word]
>>>
>>> words
         word         word_encoded
0  difference  b'ZGlmZmVyZW5jZQ=='
1       where          b'd2hlcmU='
2          mc              b'bWM='
3          is              b'aXM='
4         the              b'dGhl'


问:
Prevent from submiting form several times by clicking fast in laravel
So I ran into issue, that If i click fast enough subnmit button, my form is submited several times. How can I prevent this? Token is added automatically, but it doesnt help at all I guess.
Form example:

```<code>  <div class="row padding-10">
    {!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}
    <div class="form-group">
      {!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}
      <div class="col-md-offset-0 col-md-11">
      {!! Form::text('title', null, ['class' => 'form-control']) !!}
      </div>
    </div>
    <div class="form-group">
      {!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}
      <div class="col-md-offset-0 col-md-11">
      {!! Form::textarea('body', null, ['class' => 'form-control']) !!}
      </div>
    </div>
    <div class="col-md-offset-5 col-md-3">
      {!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control']) !!}
    </div>
    {!! Form::close() !!}
  </div>
</code>```

My NewsController store method:

```<code>    public function store()
{
$validator = Validator::make($data = Input::all(), array(
  'title' => 'required|min:8',
  'body' => 'required|min:8',
));

if ($validator->fails())
{
  return Redirect::back()->withErrors($validator)->withInput();
}

News::create($data);

return Redirect::to('/news');
}
</code>```

答:
Want to submit value of button as well and prevent double form submit?

If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.

```<code>// Add class disableonsubmit to your form
    $(document).ready(function () {
        $('form.disableonsubmit').submit(function(e) {
            if ($(this).data('submitted') === true) {
                // Form is already submitted
                console.log('Form is already submitted, waiting response.');
                // Stop form from submitting again
                e.preventDefault();
            } else {
                // Set the data-submitted attribute to true for record
                $(this).data('submitted', true);
            }
        });
    });
</code>```

Body:
So I ran into issue, that If i click fast enough subnmit button, my form is submited several times. How can I prevent this? Token is added automatically, but it doesnt help at all I guess.
Form example:

    {!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}

      {!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}

      {!! Form::text('title', null, ['class' => 'form-control']) !!}

      {!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}

      {!! Form::textarea('body', null, ['class' => 'form-control']) !!}

      {!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control']) !!}

    {!! Form::close() !!}

My NewsController store method:

    public function store()
{
$validator = Validator::make($data = Input::all(), array(
  'title' => 'required|min:8',
  'body' => 'required|min:8',
));

if ($validator->fails())
{
  return Redirect::back()->withErrors($validator)->withInput();
}

News::create($data);

return Redirect::to('/news');
}

Body:
Want to submit value of button as well and prevent double form submit?

If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.

// Add class disableonsubmit to your form
    $(document).ready(function () {
        $('form.disableonsubmit').submit(function(e) {
            if ($(this).data('submitted') === true) {
                // Form is already submitted
                console.log('Form is already submitted, waiting response.');
                // Stop form from submitting again
                e.preventDefault();
            } else {
                // Set the data-submitted attribute to true for record
                $(this).data('submitted', true);
            }
        });
    });


问:
Flatten JUnit tests in static member classes
For one of my projects I'm using JUnit 5 to test reflection code, which requires a large number of classes for test cases. Throwing them all in one scope and trying to name them intelligently is nearly impossible, so I'm hoping to put both the test methods and the types being tested inside a static member class. Doing this would allow me to reuse names such as X or Y in each test, and would keep the types being tested near the code that tests them. (The member classes have to be static so I can add interfaces)

If I just add static classes the tests run fine out of the box, but in the final report I end up with all the member classes listed separately, so I'd like to be able to "flatten" them all into the single class in the report.

Here's an example of what I would like to achieve: (I'm actually writing the tests in Kotlin, but this is the equivalent Java code)

class MethodTests {
    static class WhateverName {
        interface X {}
        class Y implements X {}

        @Test
        void something_withInterfaceSupertype_shouldReturnThing() {
            // ...
        }

        @Test
        void other_withInterfaceSupertype_shouldReturnThing() {
            // ...
        }
    }
    static class WhateverOtherName {
        interface X {
            void m();
        }
        class Y implements X {
            void m() {}
        }

        @Test
        void something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing() {
            // ...
        }
    }

    // This might actually be even better, since I wouldn't need `WhateverName`
    @Test // not valid, but maybe I could annotate the class instead of the method?
    static class something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo {
        interface X {}
        class Y implements X {}

        @Test
        void runTest() {
            // ...
        }
    }

}
```

<p>At the moment the test report in IDEA ends up being structured like this:</p>

```- MethodTests
  - someRoot_testHere
- MethodTests$WhateverName
  - something_withInterfaceSupertype_shouldReturnThing
  - other_withInterfaceSupertype_shouldReturnThing
- MethodTests$WhateverOtherName
  - something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
- MethodTests$something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo
  - runTest
```

<p>But I'd like the test report to be structured like this:</p>

```- MethodTests
  - someRoot_testHere
  - something_withInterfaceSupertype_shouldReturnThing
  - other_withInterfaceSupertype_shouldReturnThing
  - something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
  - something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo
```

I tried using @DisplayName on the member classes but it just resulted in a duplicate name in the report. So far I think I might want to use an extension, but after doing a bit of research I haven't found any way to change the class a test is listed under in the report using them.

答: Maybe you can reorganize the output files and indices or fool around with them using xsl/xslt or some other form of post processing. Also, this article may be of interest.</p>

Body:
For one of my projects I'm using JUnit 5 to test reflection code, which requires a large number of classes for test cases. Throwing them all in one scope and trying to name them intelligently is nearly impossible, so I'm hoping to put both the test methods and the types being tested inside a static member class. Doing this would allow me to reuse names such as X or Y in each test, and would keep the types being tested near the code that tests them. (The member classes have to be static so I can add interfaces)

If I just add static classes the tests run fine out of the box, but in the final report I end up with all the member classes listed separately, so I'd like to be able to "flatten" them all into the single class in the report.

Here's an example of what I would like to achieve: (I'm actually writing the tests in Kotlin, but this is the equivalent Java code)

class MethodTests {
    static class WhateverName {
        interface X {}
        class Y implements X {}

        @Test
        void something_withInterfaceSupertype_shouldReturnThing() {
            // ...
        }

        @Test
        void other_withInterfaceSupertype_shouldReturnThing() {
            // ...
        }
    }
    static class WhateverOtherName {
        interface X {
            void m();
        }
        class Y implements X {
            void m() {}
        }

        @Test
        void something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing() {
            // ...
        }
    }

    // This might actually be even better, since I wouldn't need `WhateverName`
    @Test // not valid, but maybe I could annotate the class instead of the method?
    static class something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo {
        interface X {}
        class Y implements X {}

        @Test
        void runTest() {
            // ...
        }
    }

}

At the moment the test report in IDEA ends up being structured like this:

- MethodTests
  - someRoot_testHere
- MethodTests$WhateverName
  - something_withInterfaceSupertype_shouldReturnThing
  - other_withInterfaceSupertype_shouldReturnThing
- MethodTests$WhateverOtherName
  - something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
- MethodTests$something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo
  - runTest

But I'd like the test report to be structured like this:

- MethodTests
  - someRoot_testHere
  - something_withInterfaceSupertype_shouldReturnThing
  - other_withInterfaceSupertype_shouldReturnThing
  - something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
  - something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo

I tried using @DisplayName on the member classes but it just resulted in a duplicate name in the report. So far I think I might want to use an extension, but after doing a bit of research I haven't found any way to change the class a test is listed under in the report using them.


问:
Position DIV under Background Image, regardless of viewport (responsive)
I have a big background image of 1920x550px and I want to place a div directly under it.
Since I don't know how to display the full image, I used a dirty trick and actually filled the image with a transparent part so it is a 1920x1080 image, then I display it with this:

```<code>.bg-image-big{
    background: url(../images/header-bg-big.png) no-repeat center center fixed;
    background-color: #f7f7f7;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
</code>```

This stretches it to be always full screen.
Two problems now: That does not work on mobile (cuts the image) and I have no idea how to place the inner div exactly below the "end" of the actual banner. In theory and a 1920x1080 screen it is a 550px margin-top.

```<code><div class="section bg-light-gray bg-image-big">
   <div class="inner">
      <!-- placed right under the end of the banner -->
   </div>
</div>
</code>```

Any better approach to that (pretty sure there is). Any hint appreciated!

For the matter of it, I am using Bootstrap3 and FullPage.js

//EDIT:

Visualization as per request:

What I want:

What I have:
Full Desktop

Responsive

This is not about the 6/8/12 wide but about the position of those elements.
hope this helps a little more...

答:
I had the same problem. Here's how I solved it.

The background image was attached to the body element. The original image size was 1920px by 1080px.

I calculated the ratio of the height to width, which came to 56.25.

For the element that I wanted to position below the image, I used this:

```<code>#page-area {
    margin-top: 56.25vw;
}
</code>```

As the viewport width changes, the image height does too. So I set the margin-top to be the same height as the image.

Body:
I have a big background image of 1920x550px and I want to place a div directly under it.
Since I don't know how to display the full image, I used a dirty trick and actually filled the image with a transparent part so it is a 1920x1080 image, then I display it with this:

.bg-image-big{
    background: url(../images/header-bg-big.png) no-repeat center center fixed;
    background-color: #f7f7f7;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

This stretches it to be always full screen.
Two problems now: That does not work on mobile (cuts the image) and I have no idea how to place the inner div exactly below the "end" of the actual banner. In theory and a 1920x1080 screen it is a 550px margin-top.

Any better approach to that (pretty sure there is). Any hint appreciated!

For the matter of it, I am using Bootstrap3 and FullPage.js

//EDIT:

Visualization as per request:

What I want:

What I have:
Full Desktop

Responsive

This is not about the 6/8/12 wide but about the position of those elements.
hope this helps a little more...

Body:
I had the same problem. Here's how I solved it.

The background image was attached to the body element. The original image size was 1920px by 1080px.

I calculated the ratio of the height to width, which came to 56.25.

For the element that I wanted to position below the image, I used this:

#page-area {
    margin-top: 56.25vw;
}

As the viewport width changes, the image height does too. So I set the margin-top to be the same height as the image.


问:
Error while updating property 'fill' of a view managed by: RNSVGReact
I try to render a qrcode using this library: react-native-qrcode-svg but I have this error:

Error while updating property 'fill' of a view managed by: RNSVGReact

I install the required package react-native-svg but the problem persist. I'm using the latest version of all packages.

This is the full code:

```<code>import React, { Component } from 'react';
import QRCode from 'react-native-qrcode-svg';

export default class MyQRCode extends Component {
  render() {
    return (
      <QRCode
        value="http://awesome.link.qr"
      />
    );
  };
}
</code>```

答:
As of 17 February 2020, installing the version 9.13.3 of react-native-svg is going to solve your problem.

Apparently, using expo install CLI is going to install the latest version of this package, but that's going to give you an error when you're starting the project(you'll see there specified what version of the package is supported by expo).

Just do something like:

```<code>yarn add react-native-svg@9.13.3
</code>```

or

```<code>npm install react-native-svg@9.13.3
</code>```

And you should be good to go.

See this link for more info.

Body:
I try to render a qrcode using this library: react-native-qrcode-svg but I have this error:

Error while updating property 'fill' of a view managed by: RNSVGReact

I install the required package react-native-svg but the problem persist. I'm using the latest version of all packages.

This is the full code:

import React, { Component } from 'react';
import QRCode from 'react-native-qrcode-svg';

export default class MyQRCode extends Component {
  render() {
    return (
      <QRCode
        value="http://awesome.link.qr"
      />
    );
  };
}

Body:
As of 17 February 2020, installing the version 9.13.3 of react-native-svg is going to solve your problem.

Apparently, using expo install CLI is going to install the latest version of this package, but that's going to give you an error when you're starting the project(you'll see there specified what version of the package is supported by expo).

Just do something like:

yarn add react-native-svg@9.13.3

or

npm install react-native-svg@9.13.3

And you should be good to go.

See this link for more info.


问:
Change Visual Order of Overlapping Factor Values in geom_sf in R
(Load libraries)

```<code>library(tidyverse)
library(sf)
</code>```

Let's say we have two points at the same position (x,y) but with different values (z):

```<code>x<-c(1,1)
y<-c(1,1)
z<-c(0,1)
</code>```

I know that geom_point will change the order of the displayed values (which is on top), based on the ordering of the dataset:

```<code>ggplot(data=points, aes(x=x,y=y))+geom_point(aes(color=z),size=20)
ggplot(data=points%>%arrange(desc(z)), aes(x=x,y=y))+geom_point(aes(color=z),size=20)
</code>```

order 1
order 2

And this still works if "z" is a factor.

If I make the points into sf objects and plot them using geom_sf, it works if "z" is numeric.

```<code>ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) )+geom_sf(aes(color=z),size=20)

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%arrange(desc(z)))+geom_sf(aes(color=z),size=20)
</code>```

sf num order 1
sf num order 2

However, using geom_sf with factor(z), nothing changes when I reorder the dataset.

```<code>ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%mutate(z=factor(z)))+geom_sf(aes(color=z),size=20)

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%mutate(z=factor(z))%>%
arrange(desc(z)))+geom_sf(aes(color=z),size=20)
</code>```

sf factor order 1
sf factor order 2

How can I force the reordering in the last example?

Thanks so much!

答:
In your last example, you can force the re-ordering by re-arranging the order of z before setting z as a factor and attributing unique values of z as factor levels as follow:

library(tidyverse)
library(sf)

points%>%
  st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%
  arrange(desc(z)) %>%
  mutate(z=factor(z, levels = unique(z))) %>% str()

Classes ‘sf’ and 'data.frame':  2 obs. of  2 variables:
 $ z       : Factor w/ 2 levels "1","0": 1 2
 $ geometry:sfc_POINT of length 2; first list element:  'XY' num  1 1
 - attr(*, "sf_column")= chr "geometry"
 - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA
  ..- attr(*, "names")= chr "z"
```
<p>In the <code>str</code> output, you can see that now factor levels are well organized (1 before 0) And if we plot it, you get the expected plot:</p>
<pre class="lang-r prettyprint-override"><code>library(tidyverse)
library(sf)
ggplot(data=points%>%
         st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%
         arrange(desc(z)) %>%
         mutate(z=factor(z, levels = unique(z))))+
  geom_sf(aes(color=z),size=20)
</code>```

Does it answer your question ?

Body:
(Load libraries)

library(tidyverse)
library(sf)

Let's say we have two points at the same position (x,y) but with different values (z):

x<-c(1,1)
y<-c(1,1)
z<-c(0,1)

I know that geom_point will change the order of the displayed values (which is on top), based on the ordering of the dataset:

ggplot(data=points, aes(x=x,y=y))+geom_point(aes(color=z),size=20)
ggplot(data=points%>%arrange(desc(z)), aes(x=x,y=y))+geom_point(aes(color=z),size=20)

order 1
order 2

And this still works if "z" is a factor.

If I make the points into sf objects and plot them using geom_sf, it works if "z" is numeric.

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) )+geom_sf(aes(color=z),size=20)

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%arrange(desc(z)))+geom_sf(aes(color=z),size=20)

sf num order 1
sf num order 2

However, using geom_sf with factor(z), nothing changes when I reorder the dataset.

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%mutate(z=factor(z)))+geom_sf(aes(color=z),size=20)

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%mutate(z=factor(z))%>%
arrange(desc(z)))+geom_sf(aes(color=z),size=20)

sf factor order 1
sf factor order 2

How can I force the reordering in the last example?

Thanks so much!

Body:
In your last example, you can force the re-ordering by re-arranging the order of z before setting z as a factor and attributing unique values of z as factor levels as follow:

library(tidyverse)
library(sf)

points%>%
  st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%
  arrange(desc(z)) %>%
  mutate(z=factor(z, levels = unique(z))) %>% str()

Classes ‘sf’ and 'data.frame':  2 obs. of  2 variables:
 $ z       : Factor w/ 2 levels "1","0": 1 2
 $ geometry:sfc_POINT of length 2; first list element:  'XY' num  1 1
 - attr(*, "sf_column")= chr "geometry"
 - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA
  ..- attr(*, "names")= chr "z"

In the str output, you can see that now factor levels are well organized (1 before 0) And if we plot it, you get the expected plot:

library(tidyverse)
library(sf)
ggplot(data=points%>%
         st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%
         arrange(desc(z)) %>%
         mutate(z=factor(z, levels = unique(z))))+
  geom_sf(aes(color=z),size=20)

Does it answer your question ?