问:
React Router 4 + history.push firing PUSH and POP
So I have set up the following route in my app:

```<code><Router history={history}>
    <div>
      <Route path={'/'} exact component={Home} />
      <Route path={'/cachaca/:bottle'} component={BottlePage} />
      <PublicRoute authed={this.state.authed} exact path={'/login'} component={Login} />
      <PublicRoute authed={this.state.authed} exact path={'/register'} component={Register} />
      <PrivateRoute authed={this.state.authed} path={'/dashboard'} component={Dashboard} />
    </div>
</Router>
</code>```

In different parts of the app, I programatically navigate around the app with history.push like so:

```<code>history.push({
  pathname: '/',
  search: '?startRange='+ startRange + '&endRange='+ endRange + '&maker=0'
})
</code>```

The odd thing is that when that code runs, it triggers two actions - a PUSH and a POP causing the app to navigate twice. This is what we get from the history listener log after a single push:

```<code>The current URL is /?startRange=0&endRange=31&maker=0
The last navigation action was PUSH
The current URL is /?startRange=0&endRange=31&maker=0
The last navigation action was POP
</code>```

The query params are getting properly stored and everything else seems to be working fine, but I was wondering what could be creating this problem so that my user doesn't have to back twice to go to where he actually was supposed to.

Incidentally, here is how I conjure up the history 'plugin':

```<code>import createHistory from 'history/createBrowserHistory'

const history = createHistory()

history.listen((location, action) => {
  console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

export default history
</code>```

There is also another instance where the push changes the url location bar but doesn't actually navigate anywhere but I'll save that for another question.

Am I doing something wrong? Appreciate any help!
Thanks!

答: It looks like you're trying to mix and match react-router v2 and v4, which are very different. See the comments here.</p>

Body:
So I have set up the following route in my app:

<Router history={history}>

      <Route path={'/'} exact component={Home} />
      <Route path={'/cachaca/:bottle'} component={BottlePage} />
      <PublicRoute authed={this.state.authed} exact path={'/login'} component={Login} />
      <PublicRoute authed={this.state.authed} exact path={'/register'} component={Register} />
      <PrivateRoute authed={this.state.authed} path={'/dashboard'} component={Dashboard} />

</Router>

In different parts of the app, I programatically navigate around the app with history.push like so:

history.push({
  pathname: '/',
  search: '?startRange='+ startRange + '&endRange='+ endRange + '&maker=0'
})

The odd thing is that when that code runs, it triggers two actions - a PUSH and a POP causing the app to navigate twice. This is what we get from the history listener log after a single push:

The current URL is /?startRange=0&endRange=31&maker=0
The last navigation action was PUSH
The current URL is /?startRange=0&endRange=31&maker=0
The last navigation action was POP

The query params are getting properly stored and everything else seems to be working fine, but I was wondering what could be creating this problem so that my user doesn't have to back twice to go to where he actually was supposed to.

Incidentally, here is how I conjure up the history 'plugin':

import createHistory from 'history/createBrowserHistory'

const history = createHistory()

history.listen((location, action) => {
  console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

export default history

There is also another instance where the push changes the url location bar but doesn't actually navigate anywhere but I'll save that for another question.

Am I doing something wrong? Appreciate any help!
Thanks!


来源: stackexchange

问:
Delphi 7 GIF in picture Dialog
I am using Delphi 7 and the OpenPictureDialog to open / preview various images. This works fine when opening a bmp, jpg, etc.; however, if I try to do the same with a gif I get the following error. Anyone got any idea why or have a fix for it?

thanks

Colin

答: Just use the GraphicEx library by Mike Lischke. Just add a couple files to your uses list and your application natively supports GIF, TIFF, PNG and many many others. The standard TImage will work with them and also the TPictureDialog (along with all others standard components that use TGraphic - take note that some features will only work at runtime).</p>

ContentLicense: CC BY-SA 2.5

Title: Delphi 7 GIF in picture Dialog


问:
Aspose.Words - Format a single word in a paragraph
I'm new to Aspose.Words for .Net, and working on recreating some documents for a customer. I need to make a single word in a paragraph bold and underlined.  I'm trying to achieve this by creating separate paragraph runs for the text before the bold word, the bold word itself, and the text after.  Then I'm formatting the bold word's run and appending everything to the paragraph.  This seems overly complicated.  Is there a simple way to achieve this from within DocumentBuilder.WriteLn("some text")?</p>

答:
I kept working at it, and achieved the desired result by using DocumentBuilder.Write() instead of DocumentBuilder.Writeln():</p>

```<code>builder.Write("The start of the paragraph ");
builder.Font.Bold = true;
builder.Font.Underline = Underline.Single;
builder.Write("underlined bolded text");
builder.Font.Bold = false;
builder.Font.Underline = Underline.None;
builder.Write(" the end of the paragraph.");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I kept working at it, and achieved the desired result by using DocumentBuilder.Write() instead of DocumentBuilder.Writeln():

builder.Write("The start of the paragraph ");
builder.Font.Bold = true;
builder.Font.Underline = Underline.Single;
builder.Write("underlined bolded text");
builder.Font.Bold = false;
builder.Font.Underline = Underline.None;
builder.Write(" the end of the paragraph.");


问:
Why HM-10 doesn't send an OK if i send AT from an MSP430 Launchpad?
I'm trying to set up an UART communication with a HM-10 chip on a Texas Instruments MSP430 Launchpad, but I ran into a very elementary problem.

What I want to achieve is to send an "AT" through UART to HM-10, and receive an answer for that. By the way this is a code I found here and I slightly modified for my purposes.

```<code>#include "msp430g2553.h"

const char string[] = { "AT" };
unsigned int i;

void main(void)
{
  WDTCTL = WDTPW + WDTHOLD; // Stop the Watch dog

  //------------------- Configure the Clocks -------------------//

  if (CALBC1_1MHZ==0xFF)   // If calibration constant erased
     {
        while(1);          // do not load, trap CPU!!
     }

   DCOCTL  = 0;             // Select lowest DCOx and MODx settings
   BCSCTL1 = CALBC1_1MHZ;   // Set range
   DCOCTL  = CALDCO_1MHZ;   // Set DCO step + modulation

  //---------------- Configuring the LED's ----------------------//

   P1DIR  |=  BIT0 + BIT6;  // P1.0 and P1.6 output
   P1OUT  &= ~BIT0 + BIT6;  // P1.0 and P1.6 = 0

  //--------- Setting the UART function for P1.1 & P1.2 --------//

   P1SEL  |=  BIT1 + BIT2;  // P1.1 UCA0RXD input
   P1SEL2 |=  BIT1 + BIT2;  // P1.2 UCA0TXD output

  //------------ Configuring the UART(USCI_A0) ----------------//

   UCA0CTL1 |=  UCSSEL_2 + UCSWRST;  // USCI Clock = SMCLK,USCI_A0 disabled
   UCA0BR0   =  104;                 // 104 From datasheet table-
   UCA0BR1   =  0;                   // -selects baudrate =9600,clk = SMCLK
   UCA0MCTL  =  UCBRS_1;             // Modulation value = 1 from datasheet
   //UCA0STAT |=  UCLISTEN;            // loop back mode enabled
   UCA0CTL1 &= ~UCSWRST;             // Clear UCSWRST to enable USCI_A0

  //---------------- Enabling the interrupts ------------------//

   IE2 |= UCA0TXIE;                  // Enable the Transmit interrupt
   IE2 |= UCA0RXIE;                  // Enable the Receive  interrupt
   _BIS_SR(GIE);                     // Enable the global interrupt

   i = 0;
   UCA0TXBUF = string[i];                  // Transmit a byte

   _BIS_SR(LPM0_bits + GIE);         // Going to LPM0
}

  //-----------------------------------------------------------------------//
  //                Transmit and Receive interrupts                        //
  //-----------------------------------------------------------------------//

  #pragma vector = USCIAB0TX_VECTOR
  __interrupt void TransmitInterrupt(void)
  {
    P1OUT  ^= BIT0;//light up P1.0 Led on Tx
    if (i == sizeof string - 1)
    {
    UC0IE &= ~UCA0TXIE;
    }
    UCA0TXBUF = string[i++];
  }

  #pragma vector = USCIAB0RX_VECTOR
  __interrupt void ReceiveInterrupt(void)
  {
    // light up P1.6 LED on RX
    if (UCA0RXBUF == 'O')
    {
        P1OUT  ^= BIT6;
    }
    IFG2 &= ~UCA0RXIFG; // Clear RX flag
  }
</code>```

According to the datasheet I should receive an OK answer for this command.

If there was an 'O' in the RX buffer, I would expect the LED to light up on my board, but that doesn't happen.

Using Code Composer, I also verified with adding a breakpoint to the RX interrupt that there is indeed no RX answer.

I believe this is entirely a software question, that's why I put it here. I'm using the correct rotation of jumpers(http://xanthium.in/Serial-Communication-MSP430-UART-USCI_A) and RX is wired to TX and vica versa.

I would appreciate if you could point out if I was doing anything conceptionally wrong or if I just made a mistake. Thank you!

答:
I think for everyone  who is working with HM-10 devices in the future I want to answer this question, because it has I think its own sort of mini-literature, which was first frustrating, but then I kind of liked the challenges it posed to me.

Some of the problems are hardware related, so this post might need to be moved to an embedded engineering section. (Great consequence - you cannot be 100% sure before checking it with a scope)

Know your hardware - HM-10 has tons of versions, and it turned our one needed an extra potential divider because it has a 3.3V logic level high instead of 5V. This website is a fantastic place to start. Though, ours turned out to be an MLT-BT05 which is a clone of a clone. It doesn't have iBeacon capability on its firmware, so if you don't want to power cycling, then you should probably avoid this one.

About the coding bit the most important thing is to check with \n, \r and \n\r, as linuxfan briefly mentioned its importance above, because some of the devices need it. The best place to start is AT and if it works, then use AT+HELP and find the version, usually AT+VERSION command so you can identify with 100% certainty which chip you have.

Currenetly it is prototyped on an Arduino, but I will include working code as soon as its finished on MSP430.

The Arduino code:

```<code>#include <SoftwareSerial.h>
SoftwareSerial bluetooth(9, 10); // RX, TX
  char commandbuffer[50];
      int j = 0;
void setup()
{

  memset(commandbuffer, 0, sizeof(commandbuffer));
  analogWrite(12, 255);
  analogWrite(11, 0);
  // Start the hardware serial port
  Serial.begin(19200);
  bluetooth.begin(9600);
  // un REM this to set up a Master and connect to a Slave

  Serial.println("BLE CC41A Bluetooth");
  Serial.println("----------------------------------");
  Serial.println("");
  Serial.println("Trying to connect to Slave Bluetooth");
  delay(1000);
  bluetooth.println("AT"); // just a check
  delay(2000);

  bluetooth.println("AT+NAMEHIST");
  delay(2000);
  bluetooth.println("AT+ROLE0");
  delay(2000);
    bluetooth.println("AT+INQ"); // look for nearby Slave
    delay(5000);
    bluetooth.println("AT+CONN1"); // connect to it */
}
void loop()
{
  bluetooth.listen();
  // while there is data coming in, read it
  // and send to the hardware serial port:
  while (bluetooth.available() > 0) {
    char inByte = bluetooth.read();
    Serial.write(inByte);
  }
  // Read user input if available.
  if (Serial.available()) {
    delay(10); // The DELAY!
    char temp = Serial.read();
    if (temp == '\n')
    {
      bluetooth.println(commandbuffer);
      Serial.println(commandbuffer);
      memset(commandbuffer, 0, sizeof(commandbuffer));
      j = 0; // Reset
    }
    else
    {
      commandbuffer[j++] = temp;
    }
    delay(500);
  }
</code>```

Body:
I'm trying to set up an UART communication with a HM-10 chip on a Texas Instruments MSP430 Launchpad, but I ran into a very elementary problem.

What I want to achieve is to send an "AT" through UART to HM-10, and receive an answer for that. By the way this is a code I found here and I slightly modified for my purposes.

#include "msp430g2553.h"

const char string[] = { "AT" };
unsigned int i;

void main(void)
{
  WDTCTL = WDTPW + WDTHOLD; // Stop the Watch dog

  //------------------- Configure the Clocks -------------------//

  if (CALBC1_1MHZ==0xFF)   // If calibration constant erased
     {
        while(1);          // do not load, trap CPU!!
     }

   DCOCTL  = 0;             // Select lowest DCOx and MODx settings
   BCSCTL1 = CALBC1_1MHZ;   // Set range
   DCOCTL  = CALDCO_1MHZ;   // Set DCO step + modulation

  //---------------- Configuring the LED's ----------------------//

   P1DIR  |=  BIT0 + BIT6;  // P1.0 and P1.6 output
   P1OUT  &= ~BIT0 + BIT6;  // P1.0 and P1.6 = 0

  //--------- Setting the UART function for P1.1 & P1.2 --------//

   P1SEL  |=  BIT1 + BIT2;  // P1.1 UCA0RXD input
   P1SEL2 |=  BIT1 + BIT2;  // P1.2 UCA0TXD output

  //------------ Configuring the UART(USCI_A0) ----------------//

   UCA0CTL1 |=  UCSSEL_2 + UCSWRST;  // USCI Clock = SMCLK,USCI_A0 disabled
   UCA0BR0   =  104;                 // 104 From datasheet table-
   UCA0BR1   =  0;                   // -selects baudrate =9600,clk = SMCLK
   UCA0MCTL  =  UCBRS_1;             // Modulation value = 1 from datasheet
   //UCA0STAT |=  UCLISTEN;            // loop back mode enabled
   UCA0CTL1 &= ~UCSWRST;             // Clear UCSWRST to enable USCI_A0

  //---------------- Enabling the interrupts ------------------//

   IE2 |= UCA0TXIE;                  // Enable the Transmit interrupt
   IE2 |= UCA0RXIE;                  // Enable the Receive  interrupt
   _BIS_SR(GIE);                     // Enable the global interrupt

   i = 0;
   UCA0TXBUF = string[i];                  // Transmit a byte

   _BIS_SR(LPM0_bits + GIE);         // Going to LPM0
}

  //-----------------------------------------------------------------------//
  //                Transmit and Receive interrupts                        //
  //-----------------------------------------------------------------------//

  #pragma vector = USCIAB0TX_VECTOR
  __interrupt void TransmitInterrupt(void)
  {
    P1OUT  ^= BIT0;//light up P1.0 Led on Tx
    if (i == sizeof string - 1)
    {
    UC0IE &= ~UCA0TXIE;
    }
    UCA0TXBUF = string[i++];
  }

  #pragma vector = USCIAB0RX_VECTOR
  __interrupt void ReceiveInterrupt(void)
  {
    // light up P1.6 LED on RX
    if (UCA0RXBUF == 'O')
    {
        P1OUT  ^= BIT6;
    }
    IFG2 &= ~UCA0RXIFG; // Clear RX flag
  }

According to the datasheet I should receive an OK answer for this command.

If there was an 'O' in the RX buffer, I would expect the LED to light up on my board, but that doesn't happen.

Using Code Composer, I also verified with adding a breakpoint to the RX interrupt that there is indeed no RX answer.

I believe this is entirely a software question, that's why I put it here. I'm using the correct rotation of jumpers(http://xanthium.in/Serial-Communication-MSP430-UART-USCI_A) and RX is wired to TX and vica versa.

I would appreciate if you could point out if I was doing anything conceptionally wrong or if I just made a mistake. Thank you!

Body:
I think for everyone  who is working with HM-10 devices in the future I want to answer this question, because it has I think its own sort of mini-literature, which was first frustrating, but then I kind of liked the challenges it posed to me.

Some of the problems are hardware related, so this post might need to be moved to an embedded engineering section. (Great consequence - you cannot be 100% sure before checking it with a scope)

Know your hardware - HM-10 has tons of versions, and it turned our one needed an extra potential divider because it has a 3.3V logic level high instead of 5V. This website is a fantastic place to start. Though, ours turned out to be an MLT-BT05 which is a clone of a clone. It doesn't have iBeacon capability on its firmware, so if you don't want to power cycling, then you should probably avoid this one.

About the coding bit the most important thing is to check with \n, \r and \n\r, as linuxfan briefly mentioned its importance above, because some of the devices need it. The best place to start is AT and if it works, then use AT+HELP and find the version, usually AT+VERSION command so you can identify with 100% certainty which chip you have.

Currenetly it is prototyped on an Arduino, but I will include working code as soon as its finished on MSP430.

The Arduino code:

#include <SoftwareSerial.h>
SoftwareSerial bluetooth(9, 10); // RX, TX
  char commandbuffer[50];
      int j = 0;
void setup()
{

  memset(commandbuffer, 0, sizeof(commandbuffer));
  analogWrite(12, 255);
  analogWrite(11, 0);
  // Start the hardware serial port
  Serial.begin(19200);
  bluetooth.begin(9600);
  // un REM this to set up a Master and connect to a Slave

  Serial.println("BLE CC41A Bluetooth");
  Serial.println("----------------------------------");
  Serial.println("");
  Serial.println("Trying to connect to Slave Bluetooth");
  delay(1000);
  bluetooth.println("AT"); // just a check
  delay(2000);

  bluetooth.println("AT+NAMEHIST");
  delay(2000);
  bluetooth.println("AT+ROLE0");
  delay(2000);
    bluetooth.println("AT+INQ"); // look for nearby Slave
    delay(5000);
    bluetooth.println("AT+CONN1"); // connect to it */
}
void loop()
{
  bluetooth.listen();
  // while there is data coming in, read it
  // and send to the hardware serial port:
  while (bluetooth.available() > 0) {
    char inByte = bluetooth.read();
    Serial.write(inByte);
  }
  // Read user input if available.
  if (Serial.available()) {
    delay(10); // The DELAY!
    char temp = Serial.read();
    if (temp == '\n')
    {
      bluetooth.println(commandbuffer);
      Serial.println(commandbuffer);
      memset(commandbuffer, 0, sizeof(commandbuffer));
      j = 0; // Reset
    }
    else
    {
      commandbuffer[j++] = temp;
    }
    delay(500);
  }


问:
How do I create a doPost(e) function in Apps Script project to capture HTTP POST data from web service?
I'm trying to create a script to capture data via HTTP POST from Ejunkie. When someone makes a purchase on ejunkie, they can transmit all the order data via HTTP POST to a common notification url (documentation). I want to capture that data so I can get it into a Google Sheet.

So I've setup a sheet with a doPost(e) function like so:

```<code>// attempt 1
function doPost(e) {
  if(typeof e !== 'undefined')
  Logger.log(e.parameters);
}

// attempt 2
function doPost(e) {
  var data = JSON.stringify(e);
  Logger.log(data);
}
</code>```

which I've published as a Web App with access to anyone, and then entered this script URL as the common notification URL in ejunkie.

I've tried a couple of test transactions, but I'm getting nothing in the Logs.

Any ideas? Thanks in advance for any help.

Here's the ejunkie documentation on this subject.

答:
This is the code I used to post the data to my sheet:

```<code>function doPost(e) {
  Logger.log("I was called")
  if(typeof e !== 'undefined')
  Logger.log(e.parameter);
  var ss= SpreadsheetApp.openById("ID here")
  var sheet = ss.getSheetByName("Sheet2")
  sheet.getRange(1, 1).setValue(JSON.stringify(e))
  return ContentService.createTextOutput(JSON.stringify(e))
}
</code>```

Used curl to make a post request and got echo of the data sent!

Body:
I'm trying to create a script to capture data via HTTP POST from Ejunkie. When someone makes a purchase on ejunkie, they can transmit all the order data via HTTP POST to a common notification url (documentation). I want to capture that data so I can get it into a Google Sheet.

So I've setup a sheet with a doPost(e) function like so:

// attempt 1
function doPost(e) {
  if(typeof e !== 'undefined')
  Logger.log(e.parameters);
}

// attempt 2
function doPost(e) {
  var data = JSON.stringify(e);
  Logger.log(data);
}

which I've published as a Web App with access to anyone, and then entered this script URL as the common notification URL in ejunkie.

I've tried a couple of test transactions, but I'm getting nothing in the Logs.

Any ideas? Thanks in advance for any help.

Here's the ejunkie documentation on this subject.

Body:
This is the code I used to post the data to my sheet:

function doPost(e) {
  Logger.log("I was called")
  if(typeof e !== 'undefined')
  Logger.log(e.parameter);
  var ss= SpreadsheetApp.openById("ID here")
  var sheet = ss.getSheetByName("Sheet2")
  sheet.getRange(1, 1).setValue(JSON.stringify(e))
  return ContentService.createTextOutput(JSON.stringify(e))
}

Used curl to make a post request and got echo of the data sent!

ContentLicense: CC BY-SA 4.0


问:
Android orientation change losing data solution not working
I have been looking for an solution on how to make my app not to loose data when orientation of phone changes. I have found one and it is adding this line of code

```<code>android:configChanges="orientation|keyboardHidden">
</code>```

to android manifest. So i did it:

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:configChanges="orientation|keyboardHidden">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

And my data still get lost when orientation changes, could anyone please help me ? Thank you very much.

My java code:

```<code>public class MainActivity extends AppCompatActivity {
int scoreofShooter1 = 0;
int scoreofShooter2 = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void addOneForShooter1(View view) {
    scoreofShooter1 = scoreofShooter1 + 1;
    displayForShooter1(scoreofShooter1);
}

public void addTwoForShooter1(View view) {
    scoreofShooter1 = scoreofShooter1 + 2;
    displayForShooter1(scoreofShooter1);
}
public void addThreeForShooter1(View view) {
    scoreofShooter1 = scoreofShooter1 + 3;
    displayForShooter1(scoreofShooter1);
}

public void addFourForShooter1(View view) {
    scoreofShooter1 = scoreofShooter1 + 4;
    displayForShooter1(scoreofShooter1);
}

public void addOneForShooter2(View view) {
    scoreofShooter2 = scoreofShooter2 + 1;
    displayForShooter2(scoreofShooter2);
}

public void addTwoForShooter2(View view) {
    scoreofShooter2 = scoreofShooter2 + 2;
    displayForShooter2(scoreofShooter2);
}
public void addThreeForShooter2(View view) {
    scoreofShooter2 = scoreofShooter2 + 3;
    displayForShooter2(scoreofShooter2);
}

public void addFourForShooter2(View view) {
    scoreofShooter2 = scoreofShooter2 + 4;
    displayForShooter2(scoreofShooter2);
}

public void resetScoreOfShooter1(View view) {
    scoreofShooter1 = 0;
    displayForShooter1(scoreofShooter1);
}

public void resetScoreOfShooter2(View view) {
    scoreofShooter2 = 0;
    displayForShooter2(scoreofShooter2);
}

public void displayForShooter1(int score) {
    TextView scoreView = (TextView) findViewById(R.id.shooter_1_score);
    scoreView.setText(String.valueOf(score));
}

public void displayForShooter2(int score) {
    TextView scoreView = (TextView) findViewById(R.id.shooter_2_score);
    scoreView.setText(String.valueOf(score));
}
</code>```

}

答:
Your solution is bad practice as stated in this great article

Perhaps the hackiest and most widely abused workaround is to disable the default destroy-and-recreate behavior by setting the android:configChanges attribute in your Android manifest. The apparent simplicity of this approach makes it extremely attractive to developers; Google engineers, however, discourage its use. The primary concern is that it requires you to handle device configuration changes manually in code. Handling configuration changes require you to take many additional steps to ensure that each and every string, layout, drawable, dimension, etc. remains in sync with the device’s current configuration, and if you aren’t careful, your application can easily have a whole series of resource-specific bugs as a result.

Another reason why Google discourages its use is because many
  developers incorrectly assume that setting
  android:configChanges="orientation" (for example) will magically
  protect their application from unpredictable scenarios in which the
  underlying Activity will be destroyed and recreated. This is not the
  case. Configuration changes can occur for a number of reasons—not just
  screen orientation changes. Inserting your device into a display dock,
  changing the default language, and modifying the device’s default font
  scaling factor are just three examples of events that can trigger a
  device configuration change, all of which signal the system to destroy
  and recreate all currently running Activities the next time they are
  resumed. As a result, setting the android:configChanges attribute is
  generally not good practice.

there are two scenarios:
1- if you just need to save some attributes just use onSavedInstanceState and onRestoreInstanceState

2- If you have a more complicated scenario where you have running Threads, AsyncTasks, Sockets.
you could:

1- Manage the Object Inside a Retained Fragment as described here

2- the better solution is to use loaders which are created to solve this exact problem.

from android docs:

If you fetch the data directly in the activity or fragment, your users will suffer from lack of responsiveness due to performing potentially slow queries from the UI thread.

If you fetch the data from another thread, perhaps with AsyncTask, then you're responsible for managing both the thread and the UI thread
  through various activity or fragment lifecycle events, such as
  onDestroy() and configurations changes.

Loaders solve these problems and includes other benefits. For example:

Loaders run on separate threads to prevent janky or unresponsive UI.
  Loaders simplify thread management by providing callback methods when
  events occur. Loaders persist and cache results across configuration
  changes to prevent duplicate queries. Loaders can implement an
  observer to monitor for changes in the underlying data source. For
  example, CursorLoader automatically registers a ContentObserver to
  trigger a reload when data changes.

for your particular situation

use the following code:

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        scoreofShooter1 = savedInstanceState.getInt("scoreofShooter1");
        scoreofShooter2 = savedInstanceState.getInt("scoreofShooter2");
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("scoreofShooter1", scoreofShooter1);
    outState.putInt("scoreofShooter2", scoreofShooter2);
}
</code>```

Body:
I have been looking for an solution on how to make my app not to loose data when orientation of phone changes. I have found one and it is adding this line of code

android:configChanges="orientation|keyboardHidden">

to android manifest. So i did it:

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:configChanges="orientation|keyboardHidden">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And my data still get lost when orientation changes, could anyone please help me ? Thank you very much.

My java code:

public class MainActivity extends AppCompatActivity {
int scoreofShooter1 = 0;
int scoreofShooter2 = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void addOneForShooter1(View view) {
    scoreofShooter1 = scoreofShooter1 + 1;
    displayForShooter1(scoreofShooter1);
}

public void addTwoForShooter1(View view) {
    scoreofShooter1 = scoreofShooter1 + 2;
    displayForShooter1(scoreofShooter1);
}
public void addThreeForShooter1(View view) {
    scoreofShooter1 = scoreofShooter1 + 3;
    displayForShooter1(scoreofShooter1);
}

public void addFourForShooter1(View view) {
    scoreofShooter1 = scoreofShooter1 + 4;
    displayForShooter1(scoreofShooter1);
}

public void addOneForShooter2(View view) {
    scoreofShooter2 = scoreofShooter2 + 1;
    displayForShooter2(scoreofShooter2);
}

public void addTwoForShooter2(View view) {
    scoreofShooter2 = scoreofShooter2 + 2;
    displayForShooter2(scoreofShooter2);
}
public void addThreeForShooter2(View view) {
    scoreofShooter2 = scoreofShooter2 + 3;
    displayForShooter2(scoreofShooter2);
}

public void addFourForShooter2(View view) {
    scoreofShooter2 = scoreofShooter2 + 4;
    displayForShooter2(scoreofShooter2);
}

public void resetScoreOfShooter1(View view) {
    scoreofShooter1 = 0;
    displayForShooter1(scoreofShooter1);
}

public void resetScoreOfShooter2(View view) {
    scoreofShooter2 = 0;
    displayForShooter2(scoreofShooter2);
}

public void displayForShooter1(int score) {
    TextView scoreView = (TextView) findViewById(R.id.shooter_1_score);
    scoreView.setText(String.valueOf(score));
}

public void displayForShooter2(int score) {
    TextView scoreView = (TextView) findViewById(R.id.shooter_2_score);
    scoreView.setText(String.valueOf(score));
}

}

Body:
Your solution is bad practice as stated in this great article

Perhaps the hackiest and most widely abused workaround is to disable the default destroy-and-recreate behavior by setting the android:configChanges attribute in your Android manifest. The apparent simplicity of this approach makes it extremely attractive to developers; Google engineers, however, discourage its use. The primary concern is that it requires you to handle device configuration changes manually in code. Handling configuration changes require you to take many additional steps to ensure that each and every string, layout, drawable, dimension, etc. remains in sync with the device’s current configuration, and if you aren’t careful, your application can easily have a whole series of resource-specific bugs as a result.

Another reason why Google discourages its use is because many
  developers incorrectly assume that setting
  android:configChanges="orientation" (for example) will magically
  protect their application from unpredictable scenarios in which the
  underlying Activity will be destroyed and recreated. This is not the
  case. Configuration changes can occur for a number of reasons—not just
  screen orientation changes. Inserting your device into a display dock,
  changing the default language, and modifying the device’s default font
  scaling factor are just three examples of events that can trigger a
  device configuration change, all of which signal the system to destroy
  and recreate all currently running Activities the next time they are
  resumed. As a result, setting the android:configChanges attribute is
  generally not good practice.

there are two scenarios:
1- if you just need to save some attributes just use onSavedInstanceState and onRestoreInstanceState

2- If you have a more complicated scenario where you have running Threads, AsyncTasks, Sockets.
you could:

1- Manage the Object Inside a Retained Fragment as described here

2- the better solution is to use loaders which are created to solve this exact problem.

from android docs:

If you fetch the data directly in the activity or fragment, your users will suffer from lack of responsiveness due to performing potentially slow queries from the UI thread.

If you fetch the data from another thread, perhaps with AsyncTask, then you're responsible for managing both the thread and the UI thread
  through various activity or fragment lifecycle events, such as
  onDestroy() and configurations changes.

Loaders solve these problems and includes other benefits. For example:

Loaders run on separate threads to prevent janky or unresponsive UI.
  Loaders simplify thread management by providing callback methods when
  events occur. Loaders persist and cache results across configuration
  changes to prevent duplicate queries. Loaders can implement an
  observer to monitor for changes in the underlying data source. For
  example, CursorLoader automatically registers a ContentObserver to
  trigger a reload when data changes.

for your particular situation

use the following code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        scoreofShooter1 = savedInstanceState.getInt("scoreofShooter1");
        scoreofShooter2 = savedInstanceState.getInt("scoreofShooter2");
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("scoreofShooter1", scoreofShooter1);
    outState.putInt("scoreofShooter2", scoreofShooter2);
}


问:
Rails4: collection_check_boxes from array
There is some way to serialize a collection_check_boxes from one constant?
Something like this:

```<code># model
class tutorial < ActiveRecord::Base
  serialize :option
  TYPES = ["Option 1", "Option 2", "Option 3"]
end

# view
<%= form_for(@tutorial) do |b| %>
  <%= f.collection_check_boxes(:option, Tutorial::TYPES, :id, :name) do |b| %>
         <%= b.label class:"label-checkbox" do%>
         <%=b.check_box + b.text%>
      <%end%>
   <% end %>
<% end %>
</code>```

Or just:

```<code><%= f.collection_check_boxes :option, Tutorial::TYPES, :id, :name %>
</code>```

When I try both it I get the error:

```<code>undefined method `id' for "Option\t1":String
</code>```

My permit parameters are already set with option: []

Someone did something like that before?

Thanks!

答:
The definition is:

```<code>collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)`
</code>```

The first one is a method to send, the second is a collection, the third is a method which is called to set an option value property, and the fourth is a method that is called to get a text and place it as a label for an option.

```<code><%= f.collection_check_boxes :option, Tutorial::TYPES, :id, :name %>
</code>```

There you are using Tutorial::TYPES (which is an array if strings) as a collection, and call id and name methods on each string.

Your collection should be Tutorial.all, and to get a label, you should implement a method on a Tutorial object for that, for example:

```<code>enum type: [
  :type1,
  :type2,
  :type3,
]
</code>```

And use it like this:

```<code><%= f.collection_check_boxes :option, Tutorial.all, :id, :type %>
</code>```

Body:
There is some way to serialize a collection_check_boxes from one constant?
Something like this:

# model
class tutorial < ActiveRecord::Base
  serialize :option
  TYPES = ["Option 1", "Option 2", "Option 3"]
end

# view
<%= form_for(@tutorial) do |b| %>
  <%= f.collection_check_boxes(:option, Tutorial::TYPES, :id, :name) do |b| %>
         <%= b.label class:"label-checkbox" do%>
         <%=b.check_box + b.text%>
      <%end%>
   <% end %>
<% end %>

Or just:

<%= f.collection_check_boxes :option, Tutorial::TYPES, :id, :name %>

When I try both it I get the error:

undefined method `id' for "Option\t1":String

My permit parameters are already set with option: []

Someone did something like that before?

Thanks!

Body:
The definition is:

collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)`

The first one is a method to send, the second is a collection, the third is a method which is called to set an option value property, and the fourth is a method that is called to get a text and place it as a label for an option.

<%= f.collection_check_boxes :option, Tutorial::TYPES, :id, :name %>

There you are using Tutorial::TYPES (which is an array if strings) as a collection, and call id and name methods on each string.

Your collection should be Tutorial.all, and to get a label, you should implement a method on a Tutorial object for that, for example:

enum type: [
  :type1,
  :type2,
  :type3,
]

And use it like this:

<%= f.collection_check_boxes :option, Tutorial.all, :id, :type %>


问:
How to get the student id where student got grade A but not C
table
.......

```<code>student_id   Grade
1              A
1              B
1              D
2              B
2              C
2              A
</code>```

Desired Output
.............

```<code>student_id
1
</code>```

i have tried
............

```<code>select student_id from student where grade='A' and not grade='c';
</code>```

but i am getting wrong output

答:
Select by grades of A, left join to grades again by student_id and grade C, and exclude matches.

```<code>select distinct
 a.student_id
from grades as a
  left join grades as c
  on c.student_id = a.student_id
  and c.Grade = 'C'
where a.Grade = 'A'
and c.student_id is null -- exclude students with C's
</code>```

Here's a demo.

Body:
table
.......

student_id   Grade
1              A
1              B
1              D
2              B
2              C
2              A

Desired Output
.............

student_id
1

i have tried
............

select student_id from student where grade='A' and not grade='c';

but i am getting wrong output

Body:
Select by grades of A, left join to grades again by student_id and grade C, and exclude matches.

select distinct
 a.student_id
from grades as a
  left join grades as c
  on c.student_id = a.student_id
  and c.Grade = 'C'
where a.Grade = 'A'
and c.student_id is null -- exclude students with C's

Here's a demo.


问:
RSpec: Controller not updating record in test env
This is kind of a weird question so I'll probably be editing this to fill in some context as needed. I have an RSpec test:

```<code>    it "should update object paramaters" do
      put :update, params: {id: test_project, project: valid_params}
      test_project.reload
      expect(test_project.title).to eql valid_params[:title]
      expect(test_project.created_at).to_not eql test_project.updated_at
    end
</code>```

Relevant controller action:

```<code>  # @project is defined in a before_action
  def update
    if @project.update_attributes(project_params)
      redirect_to @project, flash: { success: "Project successfully updated!" }
    else
      render :edit
    end
  end
</code>```

This request returns a 200 OK (I would expect a redirect code, but this is not the case) response code, however when I reload test_project the title remains unchanged and the test fails. This EXACT same request works to update the Project in the development and production environments. Any clues as to why this isn't working?

答: I don't actually see a reload in the test (you should do one there). The 200 would suggest either (a) there's a user authentication step that you've not handled in your tests or (b) there's a validation issue. You can test for either / both by using gem 'pry' and binding.pry in your update method. If the pry doesn't execute in update, then update isn't executing (perhaps user authentication issue) and if it does execute, you can look at @project.errors.full_messages to see what the issue is.

Body:
This is kind of a weird question so I'll probably be editing this to fill in some context as needed. I have an RSpec test:

    it "should update object paramaters" do
      put :update, params: {id: test_project, project: valid_params}
      test_project.reload
      expect(test_project.title).to eql valid_params[:title]
      expect(test_project.created_at).to_not eql test_project.updated_at
    end

Relevant controller action:

  # @project is defined in a before_action
  def update
    if @project.update_attributes(project_params)
      redirect_to @project, flash: { success: "Project successfully updated!" }
    else
      render :edit
    end
  end

This request returns a 200 OK (I would expect a redirect code, but this is not the case) response code, however when I reload test_project the title remains unchanged and the test fails. This EXACT same request works to update the Project in the development and production environments. Any clues as to why this isn't working?


问:
How to assign values from array to buttons in Swift
Hi I'm a beginner in Swift and I would like to know how I can make string values, stored in an array, the title of buttons.

Specific to my case: I have 24 buttons in my storyboard, all put into one action in the controller view. In my model I have an array with 24 emoji's and I would like to know how I can (randomly) assign these emoji's to my buttons.

```<code>var emoji : [String] = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]
</code>```

Thank you in advance.

答:
Assuming you've added buttons to a view e.g. via interface builder you can do something like this. There are a lot of examples on how to sort the emoji array elsewhere.</p>

```<code>class ViewController: UIViewController {

    let emoji = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]

    override func viewDidLoad() {
        super.viewDidLoad()
        let buttons: [UIButton] = view.subviews.flatMap { $0 as? UIButton }
        guard buttons.count <= emoji.count else {
            fatalError("Not enough emoji for buttons")
        }
        // sort emoji here
        _ = buttons.enumerated().map {  (index, element) in
            element.setTitle(emoji[index], for: .normal)
        }
    }
}
</code>```

Body:
Hi I'm a beginner in Swift and I would like to know how I can make string values, stored in an array, the title of buttons.

Specific to my case: I have 24 buttons in my storyboard, all put into one action in the controller view. In my model I have an array with 24 emoji's and I would like to know how I can (randomly) assign these emoji's to my buttons.

var emoji : [String] = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]

Thank you in advance.

Body:
Assuming you've added buttons to a view e.g. via interface builder you can do something like this. There are a lot of examples on how to sort the emoji array elsewhere.

class ViewController: UIViewController {

    let emoji = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]

    override func viewDidLoad() {
        super.viewDidLoad()
        let buttons: [UIButton] = view.subviews.flatMap { $0 as? UIButton }
        guard buttons.count <= emoji.count else {
            fatalError("Not enough emoji for buttons")
        }
        // sort emoji here
        _ = buttons.enumerated().map {  (index, element) in
            element.setTitle(emoji[index], for: .normal)
        }
    }
}


问:
urllib: Get name of file from direct download link
Python 3. Probably need to use urllib to do this,

I need to know how to send a request to a direct download link, and get the name of the file it attempts to save.

(As an example, a KSP mod from CurseForge: https://kerbal.curseforge.com/projects/mechjeb/files/2355387/download)

Of course, the file ID (2355387) will be changed. It could be from any project, but always on CurseForge. (If that makes a difference on the way it's downloaded.)

That example link results in the file:

How can I return that file name in Python?

Edit: I should note that I want to avoid saving the file, reading the name, then deleting it if possible. That seems like the worst way to do this.

答:
Using urllib.request, when you request a response from a url, the response contains a reference to the url you are downloading.

```<code>>>> from urllib.request import urlopen
>>> url = 'https://kerbal.curseforge.com/projects/mechjeb/files/2355387/download'
>>> response = urlopen(url)
>>> response.url
'https://addons-origin.cursecdn.com/files/2355/387/MechJeb2-2.6.0.0.zip'
</code>```

You can use os.path.basename to get the filename:

```<code>>>> from os.path import basename
>>> basename(response.url)
'MechJeb2-2.6.0.0.zip'
</code>```

Body:
Using urllib.request, when you request a response from a url, the response contains a reference to the url you are downloading.

>>> from urllib.request import urlopen
>>> url = 'https://kerbal.curseforge.com/projects/mechjeb/files/2355387/download'
>>> response = urlopen(url)
>>> response.url
'https://addons-origin.cursecdn.com/files/2355/387/MechJeb2-2.6.0.0.zip'

You can use os.path.basename to get the filename:

>>> from os.path import basename
>>> basename(response.url)
'MechJeb2-2.6.0.0.zip'


问:
Ionic2 menuToggle hide dynamically
I am using Ionic2, and would like to show/hide the menuToggle on a user event. This is how it's done in Ionic1. Does anyone know how to do it in Ionic2 please?

Thanks

答:
Assuming that your using Menu, ToggleMenu components and here is your solution

Menu bar content

```<code><ion-menu [content]="mycontent" [enabled]="customVariable">
  <ion-content>
    <ion-list>
      <ion-item menuClose detail-none>Close Menu</ion-item>
    </ion-list>
  </ion-content>
</ion-menu>

userEvent(){
    this.customVariable=false;
}
</code>```

Title: Ionic2 menuToggle hide dynamically

Body:
Assuming that your using Menu, ToggleMenu components and here is your solution

Menu bar content

<ion-menu [content]="mycontent" [enabled]="customVariable">
  <ion-content>
    <ion-list>
      <ion-item menuClose detail-none>Close Menu</ion-item>
    </ion-list>
  </ion-content>
</ion-menu>

userEvent(){
    this.customVariable=false;
}


问:
Update shared styles with JavaScript application wide in Polymer 2.0
I have a shared-styles element that keeps most of my applications colors.  I can easily change the colors manually in shared-styles.html, and all of my other components can inherit from there if I use the CSS variables.

My problem is I need to update the CSS variables in shared-styles.html and have all the other components that inherit the CSS variables to update their colors accordingly.  Below is my shared-styles.html.  For brevity, I removed all the variables except --app-primary-color.

```<code><link rel="import" href="../bower_components/polymer/polymer-element.html">

<!-- shared styles for all views -->
<dom-module id="shared-styles">
  <template>
    <style is="custom-style">
      :host {
        --app-primary-color:#2196F3;
      }
    </style>
  </template>
  <script>
    class SharedStyles extends Polymer.Element {

      static get is() { return 'shared-styles'; }

      ready(){
        super.ready();
        console.log('update css');
        this.updateStyles({'--app-primary-color': 'red'});
      }
    }
    window.customElements.define(SharedStyles.is, SharedStyles);
  </script>
</dom-module>
</code>```

This is how I am including them in the other components.  For example:

```<code><dom-module id="test-element">
  <template>
    <style include="shared-styles">
</code>```

Body:
I have a shared-styles element that keeps most of my applications colors.  I can easily change the colors manually in shared-styles.html, and all of my other components can inherit from there if I use the CSS variables.

My problem is I need to update the CSS variables in shared-styles.html and have all the other components that inherit the CSS variables to update their colors accordingly.  Below is my shared-styles.html.  For brevity, I removed all the variables except --app-primary-color.

<link rel="import" href="../bower_components/polymer/polymer-element.html">

<dom-module id="shared-styles">
  <template>

  </template>

</dom-module>

This is how I am including them in the other components.  For example:

<dom-module id="test-element">
  <template>

Body:
The shared style is not a Polymer element, so it should not extend Polymer.Element and should not have a <script> tag. It should be defined like this:

shared-styles.html

<link rel="import" href="../bower_components/polymer/polymer-element.html">

<!-- shared styles for all views -->
<dom-module id="shared-styles">
  <template>
    <style>
      :host {
        --app-primary-color: #2196F3;
      }
    </style>
  </template>
</dom-module>

Then, call this.updateStyles in the root element (e.g., <my-app>) to apply a global style in Polymer 2.0. Note that all elements under <my-app> would inherit the newly specified styles.

Example

Here are instructions using Polymer CLI's polymer-2-starter-kit template:

Install the bleeding edge Polymer CLI (npm install polymer-cli@next), required for the polymer-2-starter-kit template.

Run:

mkdir polymer-2-shared-styles-demo
cd polymer-2-shared-styles-demo
polymer init polymer-2-starter-kit

In src/my-app.html, add a <button> to the menu, which will change the value of --app-primary-color:

<template>
  <app-drawer-layout fullbleed>
    <!-- Drawer content -->
    <app-drawer id="drawer" slot="drawer">
      <app-toolbar>Menu</app-toolbar>

      <!-- ****     LINE 77: Add button below      **** -->
      <button on-click="_changeAppColor">Change app color</button>

<script>
  class MyApp extends Polymer.Element {

    /* ***    LINE 130: Define button-click handler below     **** */
    _changeAppColor() {
      this.updateStyles({'--app-primary-color': 'red'});
    }

In src/shared-styles.html, change .circle's background to use --app-primary-color:

.circle {

  /* ***    LINE 33: Use --app-primary-color below     **** */
  background: var(--app-primary-color, #ddd);

Run polymer serve -o to open the starter kit in the default browser.

Click the button in the menu to change the color of the toolbar and the circles in each page. It should look like this:

GitHub project


问:
Performance of a trimming function
My old Trimming function:

```<code>string TailTrimString (const string & sSource, const char *chars) {
  size_t End = sSource.find_last_not_of(chars);
  if (End == string::npos) {
    // only "*chars"
    return "";
  }
  if (End == sSource.size() - 1) {
    // noting to trim
    return sSource;
  }
  return sSource.substr(0, End + 1);
}
</code>```

Instead of it I've decided to use boost, and wrote the trivial:

```<code>string TailTrimString (const string & sSource, const char *chars) {
    return boost::algorithm::trim_right_copy_if(sSource,boost::algorithm::is_any_of(chars));
}
</code>```

And I was amazed to find out that the new function works much slower.
I've done some profiling, and I see that the function is_any_of is very slow.

Is it possible that boost's implementation works slower than my quite straightforward implementation? Is there anything I should use instead of is_any_of in order to improve the performance?

I also found a discussion on this matter in the boost's mailing list, but I am still not sure on how can I improve the performance of my code.

The boost version that I use is 1.38, which is quite old, but I guess this code didn't change too much since then.

Thank you.

答:
In answer to your question about the relative performance, the std::string::find_last_not_of, will wrap C string routines (such as strcspan), and these are very fast, however boost::algorithm::is_any_of uses (probably used to use, I'd hazard that in the later versions this has changed!) a std::set for the set of characters to look for and does a check in this set for each character - which will not be anywhere near as fast!

EDIT: just to add an echo, your function works, it's not broken, it's not slow, so don't bother changing it...

Title: Performance of a trimming function

Body:
My old Trimming function:

string TailTrimString (const string & sSource, const char *chars) {
  size_t End = sSource.find_last_not_of(chars);
  if (End == string::npos) {
    // only "*chars"
    return "";
  }
  if (End == sSource.size() - 1) {
    // noting to trim
    return sSource;
  }
  return sSource.substr(0, End + 1);
}

Instead of it I've decided to use boost, and wrote the trivial:

string TailTrimString (const string & sSource, const char *chars) {
    return boost::algorithm::trim_right_copy_if(sSource,boost::algorithm::is_any_of(chars));
}

And I was amazed to find out that the new function works much slower.
I've done some profiling, and I see that the function is_any_of is very slow.

Is it possible that boost's implementation works slower than my quite straightforward implementation? Is there anything I should use instead of is_any_of in order to improve the performance?

I also found a discussion on this matter in the boost's mailing list, but I am still not sure on how can I improve the performance of my code.

The boost version that I use is 1.38, which is quite old, but I guess this code didn't change too much since then.

Thank you.


问:
How do I return the smallest value using a for loop?
I am given a limit, and I have to return the smallest value for n to make it true: 1+2+3+4+...+n >= limit. I feel like there's one thing missing, but I can't tell.

```<code>public int whenToReachLimit(int limit) {
 int sum = 0;

 for (int i = 1; sum < limit; i++) {
   sum = sum + i;
  }
 return sum;
}
</code>```

The output would be:

1 : 1

4 : 3

10 : 4

答:
I've found the answer. Turns out it doesn't work with a for loop which I find odd. But this is the answer to my own question.

```<code>public int whenToReachLimit(int limit) {
int n = 0;
int sum = 0;

while (sum < limit) {
   sum += n;
   n++;
  }
 return n-1;
}
</code>```

Body:
I am given a limit, and I have to return the smallest value for n to make it true: 1+2+3+4+...+n >= limit. I feel like there's one thing missing, but I can't tell.

public int whenToReachLimit(int limit) {
 int sum = 0;

 for (int i = 1; sum < limit; i++) {
   sum = sum + i;
  }
 return sum;
}

The output would be:

1 : 1

4 : 3

10 : 4

Body:
I've found the answer. Turns out it doesn't work with a for loop which I find odd. But this is the answer to my own question.

public int whenToReachLimit(int limit) {
int n = 0;
int sum = 0;

while (sum < limit) {
   sum += n;
   n++;
  }
 return n-1;
}


问:
How to JsonPost to a WebService target in Nlog
With Nlog 4.4.5 am trying to use protocol JsonPost of WebService target to post logs to slack. Slack webhooks need Json data over https post (https://api.slack.com/incoming-webhooks)

<target xsi:type="WebService"
            name="slack"
            url="https://hooks.slack.com/services/T*****/B4T****/7F********XDv9h/"
            protocol="JsonPost"
            encoding="utf-8"
            >

    <parameter name="text" type="System.String" layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fff}: ${level} - ${message}"/>

</target>
```

It does not post anything to my slack channel created for the webhook whereas I see the other targets in my Nlog.config are called and log files are populated with new data.

Any idea where I should look into to sort it out?

答:
Maybe something like this answer:

https://github.com/NLog/NLog/issues/1958

While waiting for this issue to be resolved (Using JSON-Layout directly):

https://github.com/NLog/NLog/issues/1905

Body:
With Nlog 4.4.5 am trying to use protocol JsonPost of WebService target to post logs to slack. Slack webhooks need Json data over https post (https://api.slack.com/incoming-webhooks)

<target xsi:type="WebService"
            name="slack"
            url="https://hooks.slack.com/services/T*****/B4T****/7F********XDv9h/"
            protocol="JsonPost"
            encoding="utf-8"
            >

    <parameter name="text" type="System.String" layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fff}: ${level} - ${message}"/>

</target>

It does not post anything to my slack channel created for the webhook whereas I see the other targets in my Nlog.config are called and log files are populated with new data.

Any idea where I should look into to sort it out?


问:
How to add +1 value on the entire column of my database table?
Just new in programming I created a database using XAMPP with 3 columns (f_name, l_name, age).

I created a index.php page where I have only 1 button present, what I am expecting to happen is that if I click that button the entire column age will commit +1 to all current values inside the age. Is it possible?

But unfortunately I don't know how to create the code. I would like to see a simple example of code that will add +1 to the entire column of age. At lease a base logic that will help me figure it out how to do it.

答:
i was able to add +1 to the entire column of age

enter image description here
Query:

enter image description here
Ajax:

Thank you everyone.


问:
Django url pattern
This should be an easy question.  I have two url patterns in Django:

```<code>url(r'^wiki/page/(?P<page_title>.*)', views.wiki_view, name = 'wiki_view'),
url(r'^wiki/page/$', views.wiki_page_index, name = 'wiki_page_index'),
</code>```

When I visit /wiki/page/test, it takes me to views.wiki_view.  This is correct.  I need the first pattern to capture all characters after the "page/", which is why I used .*

When I visit /wiki/page/, it also takes me to views.wiki_view.  This is incorrect.

I could alter the second url pattern to read:

```<code>url(r'^wiki/page/$', views.wiki_page_index, name = 'wiki_page_index'),
</code>```

Thus, when I visit /wiki/page, it will take me to views.wiki_page_index.  But I'd rather fix the problem instead of avoiding it.

How do I format the first url pattern so that it won't pick up the instance of /wiki/page/?

答:
Place the second one before the current first one.

http://docs.djangoproject.com/en/dev/topics/http/urls/
("Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.")

Title: Django url pattern

Body:
This should be an easy question.  I have two url patterns in Django:

url(r'^wiki/page/(?P<page_title>.*)', views.wiki_view, name = 'wiki_view'),
url(r'^wiki/page/$', views.wiki_page_index, name = 'wiki_page_index'),

When I visit /wiki/page/test, it takes me to views.wiki_view.  This is correct.  I need the first pattern to capture all characters after the "page/", which is why I used .*

When I visit /wiki/page/, it also takes me to views.wiki_view.  This is incorrect.

I could alter the second url pattern to read:

url(r'^wiki/page/$', views.wiki_page_index, name = 'wiki_page_index'),

Thus, when I visit /wiki/page, it will take me to views.wiki_page_index.  But I'd rather fix the problem instead of avoiding it.

How do I format the first url pattern so that it won't pick up the instance of /wiki/page/?


问:
Is it possible to have multiple configurable app icons for a mobile app (iOS + Android)?
I'm designing an app that serves a bunch of different instances. Each user belongs to an instance of the platform and when they authenticate I'd like to change the styling of the app icon to reflect their instance.

Ideally, there would be a generic icon when they download from the app store then once they authenticate we'd show their team-specific icon.

Is this possible?
..on both iOS and Android or either?

The development team is building the app in React Native and exporting to iOS and Android. I'm drawing the icons.

答:
For previous versions of iOS I believe it is not possible but as of iOS 10.3 you can do this using:

```<code>setAlternateIconName(_:completionHandler:)
</code>```

and for android check this: How to change an application icon programmatically in android

Body:
For previous versions of iOS I believe it is not possible but as of iOS 10.3 you can do this using:

setAlternateIconName(_:completionHandler:)

and for android check this: How to change an application icon programmatically in android


问:
User Agent Stylesheet - css property for strong is disabled?

In my codepen I placed  tags within a paragraph, but I noticed no emphasis being displayed.  Chrome developer tools shows the user agent stylesheet for strong has a line through it.  What could possibly be disabling this setting as I do not override strong myself or change any font-weight within my code?

I am using chrome version 56.

```<code><p id="p10">offset() - Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document. <strong>[returns: object]</strong>
</p>
</code>```

答:
Your codepen calls this reset stylesheet (the classic "Eric Meyer Reset"):

```<code>https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css
</code>```

This resets all internal browser styles (i.e. it overwrites them), so you have (among many others) to add your own CSS for the strong tag with a rule like

```<code>strong {
  font-weight: bold;
}
</code>```

Or you just erase the reference to that reset style sheet...

Just as a reaction to the downvote: what do you think this is:

Body:
In my codepen I placed  tags within a paragraph, but I noticed no emphasis being displayed.  Chrome developer tools shows the user agent stylesheet for strong has a line through it.  What could possibly be disabling this setting as I do not override strong myself or change any font-weight within my code?

I am using chrome version 56.

offset() - Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document. [returns: object]

Body:
Your codepen calls this reset stylesheet (the classic "Eric Meyer Reset"):

https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css

This resets all internal browser styles (i.e. it overwrites them), so you have (among many others) to add your own CSS for the strong tag with a rule like

strong {
  font-weight: bold;
}

Or you just erase the reference to that reset style sheet...

Just as a reaction to the downvote: what do you think this is:


问:
How does Awk's pattern matching for strings works?
I am trying to understand how the range pattern matching work in Awk
Here is the full data that I am practicing with

```<code>Raw Data
-----------------------------------------
    USSR    8649    275     Asia
    Canada  3852    25      North America
    China   3705    1032    Asia
    USA     3615    237     North America
    Brazil  3286    134     South America
    India   1267    746     Asia
    Mexico  762     78      North America
    France  211     55      Europe
    Japan   144     120     Asia
    Germany 96      61      Europe
    England 94      56      Europe
</code>```

If I write this code

```<code>$ awk '/Asia/, /Europe/' countries.awk
</code>```

I get

```<code>USSR    8649    275     Asia
Canada  3852    25      North America
China   3705    1032    Asia
USA     3615    237     North America
Brazil  3286    134     South America
India   1267    746     Asia
Mexico  762     78      North America
France  211     55      Europe
Japan   144     120     Asia
Germany 96      61      Europe
</code>```

It doesn't output England.

And If I write this

```<code>$ awk '/Europe/, /Asia/' countries.awk
</code>```

I get

```<code>France  211     55      Europe
Japan   144     120     Asia
Germany 96      61      Europe
England 94      56      Europe
</code>```

What is the behavior here? Why do I not get England on the first one?

答:
Never use range expressions as they make trivial tasks very slightly briefer but then need a complete rewrite or duplicate conditions when your requirements change. Always use a flag instead:

```<code>awk '/Asia/{f=1} f{print} /Europe/{f=0}' countries.awk
</code>```

I bet if you started with that you wouldn't even have had to ask this question as the logic is clear and explicit.

Body:
I am trying to understand how the range pattern matching work in Awk
Here is the full data that I am practicing with

Raw Data
-----------------------------------------
    USSR    8649    275     Asia
    Canada  3852    25      North America
    China   3705    1032    Asia
    USA     3615    237     North America
    Brazil  3286    134     South America
    India   1267    746     Asia
    Mexico  762     78      North America
    France  211     55      Europe
    Japan   144     120     Asia
    Germany 96      61      Europe
    England 94      56      Europe

If I write this code

$ awk '/Asia/, /Europe/' countries.awk

I get

USSR    8649    275     Asia
Canada  3852    25      North America
China   3705    1032    Asia
USA     3615    237     North America
Brazil  3286    134     South America
India   1267    746     Asia
Mexico  762     78      North America
France  211     55      Europe
Japan   144     120     Asia
Germany 96      61      Europe

It doesn't output England.

And If I write this

$ awk '/Europe/, /Asia/' countries.awk

I get

France  211     55      Europe
Japan   144     120     Asia
Germany 96      61      Europe
England 94      56      Europe

What is the behavior here? Why do I not get England on the first one?

Body:
Never use range expressions as they make trivial tasks very slightly briefer but then need a complete rewrite or duplicate conditions when your requirements change. Always use a flag instead:

awk '/Asia/{f=1} f{print} /Europe/{f=0}' countries.awk

I bet if you started with that you wouldn't even have had to ask this question as the logic is clear and explicit.


问:
Jquery parent child selectors
I have the html structure below and I'm trying to select the row containing the text 'Related list item:'.

My Jquery is below:
$('#WebPartWPQ3 > table(eq:2) > tbody > tr > td > table > tbody > tr:last').remove();
 but not working...

```<code> <DIV id="WebPartWPQ3" fixed_bound allowDelete="false" OnlyForMePart="true" HasPers="true" WebPartID="00000000-0000-0000-0000-000000000000" width="100%">
  <TABLE cellSpacing="0" cellPadding="4" width="100%" border="0" fixed_bound xmlns:ddwrt2="urn:frontpage:internal" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:dsp="http://schemas.microsoft.com/sharepoint/dsp" xmlns:x="http://www.w3.org/2001/XMLSchema">
    <TBODY fixed_bound>
      <TR fixed_bound>
        <TD class="ms-vb" fixed_bound>
        </TD>
      </TR>
    </TBODY>
  </TABLE>
  <TABLE width="100%" border="0" fixed_bound xmlns:ddwrt2="urn:frontpage:internal" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:dsp="http://schemas.microsoft.com/sharepoint/dsp" xmlns:x="http://www.w3.org/2001/XMLSchema">
    <TBODY fixed_bound>
      <TR fixed_bound>
        <TD fixed_bound>
          <TABLE cellSpacing="0" width="100%" border="0" fixed_bound>
            <TBODY fixed_bound>
              <TR fixed_bound>
                <TD class="ms-formlabel" vAlign="top" noWrap width="25%" fixed_bound>
                  <B fixed_bound>Title:
                  </B>
                </TD>
                <TD class="ms-formbody" vAlign="top" width="75%" fixed_bound>Employee annual leave approval
                  <BR fixed_bound/>
                  <BR fixed_bound/>
                </TD>
              </TR>
              <TR fixed_bound>
                <TD class="ms-formlabel" width="25%" fixed_bound>
                  <B fixed_bound>Approved Carry Forward days
                    <SPAN class="ms-formvalidation" fixed_bound> *
                    </SPAN>:
                  </B>
                </TD>
                <TD class="ms-formbody" width="75%" fixed_bound>
                  <SPAN fixed_bound>
                    <INPUT class="ms-input" id="ctl00_PlaceHolderMain_TaskForm_ff1_1_ctl00_ctl00_TextField" title="Approved Carry Forward days" style="IME-MODE: inactive" size="11" name="ctl00$PlaceHolderMain$TaskForm$ff1_1$ctl00$ctl00$TextField" fixed_bound value=""/>
                    <BR fixed_bound/>
                  </SPAN>
                </TD>
              </TR>
              <TR fixed_bound>
                <TD class="ms-formlabel" width="25%" fixed_bound>
                  <B fixed_bound>Review Comments:
                  </B>
                </TD>
                <TD class="ms-formbody" width="75%" fixed_bound>
                  <SPAN fixed_bound>
                    <TEXTAREA class="ms-long" id="ctl00_PlaceHolderMain_TaskForm_ff2_1_ctl00_ctl00_TextField" title="Review Comments" name="ctl00$PlaceHolderMain$TaskForm$ff2_1$ctl00$ctl00$TextField" rows="5" fixed_bound>
                    </TEXTAREA>
                    <BR fixed_bound/>
                  </SPAN>
                </TD>
              </TR>
              <TR fixed_bound>
                <TD class="ms-formlabel" vAlign="top" noWrap width="25%" fixed_bound>
                  <B fixed_bound>Related list item:
                  </B>
                </TD>
                <TD class="ms-formbody" vAlign="top" width="75%" fixed_bound>
                  <A href="http://orange.extra.net/people/hr/Workflows/Expire%20the%20employee%20year%20in%20a%20year/" fixed_bound>
                  </A>
                </TD>
              </TR>
            </TBODY>
          </TABLE>
        </TD>
      </TR>
    </TBODY>
  </TABLE>
  <TABLE cellSpacing="0" cellPadding="4" width="100%" border="0" fixed_bound xmlns:ddwrt2="urn:frontpage:internal" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:dsp="http://schemas.microsoft.com/sharepoint/dsp" xmlns:x="http://www.w3.org/2001/XMLSchema">
    <TBODY fixed_bound>
      <TR fixed_bound>
        <TD class="ms-vb" noWrap fixed_bound>
          <INPUT style="DISPLAY: none" onclick="javascript: __doPostBack('ctl00$PlaceHolderMain$TaskForm','__update;__commit;__redirectsource;__redirectToList={};')" type="button" name="btnSave" fixed_bound jQuery1291028280448="3" value="Save Draft"/>
        </TD>
        <TD fixed_bound>
          <INPUT onclick="javascript: __doPostBack('ctl00$PlaceHolderMain$TaskForm','__update;__workflowTaskComplete={0*};__commit;__redirectsource;__redirectToList={};')" type="button" name="btnMarkSubmited" fixed_bound value="Complete Task"/>
        </TD>
        <TD class="ms-vb" noWrap width="99%" fixed_bound>
          <INPUT onclick="javascript: __doPostBack('ctl00$PlaceHolderMain$TaskForm','__cancel;__redirectsource;__redirectToList={};')" type="button" name="btnCancel" fixed_bound value="Cancel"/>
        </TD>
      </TR>
    </TBODY>
  </TABLE>
</DIV>
</code>```

答:
```<code>$('#WebPartWPQ3').find('Related list item').closest('tr').remove();
</code>```

Title: Jquery parent child selectors

Body:
I have the html structure below and I'm trying to select the row containing the text 'Related list item:'.

My Jquery is below:
$('#WebPartWPQ3 > table(eq:2) > tbody > tr > td > table > tbody > tr:last').remove();
 but not working...

                  Title:

                Employee annual leave approval

                  Approved Carry Forward days
                     *
                    :

                    <INPUT class="ms-input" id="ctl00_PlaceHolderMain_TaskForm_ff1_1_ctl00_ctl00_TextField" title="Approved Carry Forward days" style="IME-MODE: inactive" size="11" name="ctl00$PlaceHolderMain$TaskForm$ff1_1$ctl00$ctl00$TextField" fixed_bound value=""/>

                  Review Comments:

                    <TEXTAREA class="ms-long" id="ctl00_PlaceHolderMain_TaskForm_ff2_1_ctl00_ctl00_TextField" title="Review Comments" name="ctl00$PlaceHolderMain$TaskForm$ff2_1$ctl00$ctl00$TextField" rows="5" fixed_bound>
                    </TEXTAREA>

                  Related list item:

          <INPUT style="DISPLAY: none" onclick="javascript: __doPostBack('ctl00$PlaceHolderMain$TaskForm','__update;__commit;__redirectsource;__redirectToList={};')" type="button" name="btnSave" fixed_bound jQuery1291028280448="3" value="Save Draft"/>

          <INPUT onclick="javascript: __doPostBack('ctl00$PlaceHolderMain$TaskForm','__update;__workflowTaskComplete={0*};__commit;__redirectsource;__redirectToList={};')" type="button" name="btnMarkSubmited" fixed_bound value="Complete Task"/>

          <INPUT onclick="javascript: __doPostBack('ctl00$PlaceHolderMain$TaskForm','__cancel;__redirectsource;__redirectToList={};')" type="button" name="btnCancel" fixed_bound value="Cancel"/>


问:
How can I use twitter for sign in to my Codename one application
I am trying to sign in with twitter in my Codename one application, but when I am clicking on login button it will redirect to twitter, but not asking for credentials, It just throws a following error:

Whoa there!
There is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.

below is my code:

```<code>twitter.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {

                Oauth2 Tauth = new Oauth2("https://api.twitter.com/oauth/authenticate?oauth_token", "XXXXXXXXXXXXXXXXXX", "https://www.codenameone.com");
                Tauth.showAuthentication(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                    AccessToken token = (AccessToken) evt.getSource();
                    Log.p(token.toString());
                    }
                });

            }
        });
</code>```

So anyone know whats wrong with this code?

答:
I haven't used twitter's API myself, but your URL looks incorrect.  This docs page indicates that you should be using "https://api.twitter.com/oauth2/token".

And don't include a query string as part of the URL.  Just the base URL "https://api.twitter.com/oauth2/token".

The Oauth2 class will add necessary query parameters.

Body:
I am trying to sign in with twitter in my Codename one application, but when I am clicking on login button it will redirect to twitter, but not asking for credentials, It just throws a following error:

Whoa there!
There is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.

below is my code:

twitter.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {

                Oauth2 Tauth = new Oauth2("https://api.twitter.com/oauth/authenticate?oauth_token", "XXXXXXXXXXXXXXXXXX", "https://www.codenameone.com");
                Tauth.showAuthentication(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                    AccessToken token = (AccessToken) evt.getSource();
                    Log.p(token.toString());
                    }
                });

            }
        });

So anyone know whats wrong with this code?


问:
HTTP POST with Basic Auth and Fields (libcurl c++)
I am trying to make an HTTP POST using libcurl. The HTTP POST needs to perform a Basic Authentication, include a field and send a file in multi part. What I am using at the moment is the following:

```<code>FILE* fo = nullptr;
std::string fullErrPath(errPath);
fullErrPath.append("debug.txt");
fo = fopen(fullErrPath.c_str(), "wb");

CURL *curl;
CURLcode res;

struct curl_httppost* formpost = nullptr;
struct curl_httppost* lastptr = nullptr;

struct curl_slist* headerlist = nullptr;
static const char buf[] = "Expect:";

const char* imgPath = "/path/to/image.jpg";

curl_global_init(CURL_GLOBAL_ALL);

curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "jpgdata",
             CURLFORM_FILE, imgPath,
             CURLFORM_CONTENTTYPE, "image/jpeg",
             CURLFORM_END);

curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "submit",
             CURLFORM_COPYCONTENTS, "send"
             CURLFORM_END);

curl = curl_easy_init();

if (curl) {

    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_URL, urlupload);

    headerlist = curl_slist_append(headerlist, buf);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);

    //curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "field=1");

    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

    curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
    curl_easy_setopt(curl, CURLOPT_USERPWD, credentials);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);

    curl_easy_setopt(curl, CURLOPT_STDERR, fo);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    // Response information
    int httpCode(0);
    static std::string httpData;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &httpData);

    res = curl_easy_perform(curl);

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);

    curl_easy_cleanup(curl);
    curl_formfree(formpost);
    curl_slist_free_all(headerlist);
    fclose(fo);
}
</code>```

I left on purpose this part "//curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "field=1");" commented because I found online that it does not make sense to use it with CURLOPT_HTTPPOST. This is the post. But code above does not work.
First, the http response code I get from the server is 400 and by checking "debug.txt", in fact, there is no data. I see only the header.
Second, I need to include the POST field "field=1", but I do not know how to do it without using the command "curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "field=1");".

Thanks.

答:
First, you want to set CURLOPT_USERPWD for the Basic auth.

Then, you need to decide which format of the data you want to POST. Do you want it to be multipart formpost or "regular" - you cannot mix them as that's just how HTTP works. The curl_formadd() you're doing so far is multipart formpost, and CURLOPT_POSTFIELDS is the regular one ("application/x-www-form-urlencoded").

So you say you want to add a "field=1" to the post, and to do that and keep this a multipart formpost you can insert the following snippet after your second call to curl_formadd. It adds another "part" to the post with the name and contents you asked for:

```<code>curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "field",
             CURLFORM_COPYCONTENTS, "1"
             CURLFORM_END);
</code>```

Body:
I am trying to make an HTTP POST using libcurl. The HTTP POST needs to perform a Basic Authentication, include a field and send a file in multi part. What I am using at the moment is the following:

FILE* fo = nullptr;
std::string fullErrPath(errPath);
fullErrPath.append("debug.txt");
fo = fopen(fullErrPath.c_str(), "wb");

CURL *curl;
CURLcode res;

struct curl_httppost* formpost = nullptr;
struct curl_httppost* lastptr = nullptr;

struct curl_slist* headerlist = nullptr;
static const char buf[] = "Expect:";

const char* imgPath = "/path/to/image.jpg";

curl_global_init(CURL_GLOBAL_ALL);

curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "jpgdata",
             CURLFORM_FILE, imgPath,
             CURLFORM_CONTENTTYPE, "image/jpeg",
             CURLFORM_END);

curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "submit",
             CURLFORM_COPYCONTENTS, "send"
             CURLFORM_END);

curl = curl_easy_init();

if (curl) {

    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_URL, urlupload);

    headerlist = curl_slist_append(headerlist, buf);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);

    //curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "field=1");

    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

    curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
    curl_easy_setopt(curl, CURLOPT_USERPWD, credentials);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);

    curl_easy_setopt(curl, CURLOPT_STDERR, fo);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    // Response information
    int httpCode(0);
    static std::string httpData;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &httpData);

    res = curl_easy_perform(curl);

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);

    curl_easy_cleanup(curl);
    curl_formfree(formpost);
    curl_slist_free_all(headerlist);
    fclose(fo);
}

I left on purpose this part "//curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "field=1");" commented because I found online that it does not make sense to use it with CURLOPT_HTTPPOST. This is the post. But code above does not work.
First, the http response code I get from the server is 400 and by checking "debug.txt", in fact, there is no data. I see only the header.
Second, I need to include the POST field "field=1", but I do not know how to do it without using the command "curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "field=1");".

Thanks.

Body:
First, you want to set CURLOPT_USERPWD for the Basic auth.

Then, you need to decide which format of the data you want to POST. Do you want it to be multipart formpost or "regular" - you cannot mix them as that's just how HTTP works. The curl_formadd() you're doing so far is multipart formpost, and CURLOPT_POSTFIELDS is the regular one ("application/x-www-form-urlencoded").

So you say you want to add a "field=1" to the post, and to do that and keep this a multipart formpost you can insert the following snippet after your second call to curl_formadd. It adds another "part" to the post with the name and contents you asked for:

curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "field",
             CURLFORM_COPYCONTENTS, "1"
             CURLFORM_END);


问:
succes function in ajax call depends on echo from PDO
i need to customize the success message in an ajax call based on the result after inserting data into mysql table,

```<code> $.ajax({
             data: dataString,
             type: 'POST',
             url: 'mypage.php',
             success: function(data)
             {
                 if (data === 'success') {
                    alert("New record created successfull");
                 }else{alert("something goes wrong"); }
             }
            });
</code>```

here is the php code

```<code> <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "success";
}
catch(PDOException $e)
{
echo "fail";
}

$conn = null;
?>
</code>```

and when i try to check the message returned from the php page i get the right alert with this ajax call

```<code>$.ajax({
             data: dataString,
             type: 'POST',
             url: 'mypage.php',
             success: function(data)
             {
                 alert(data);
             }
            });
</code>```

i tried many things but i cannot find where is the problem exactly, any help will be appreciated.

答:
This will work I used same code in another case:</p>

```<code>if ($.trim(data) === 'success') {
   alert("New record created successfull");
}else{alert("something goes wrong"); }
</code>```

Body:
i need to customize the success message in an ajax call based on the result after inserting data into mysql table,

 $.ajax({
             data: dataString,
             type: 'POST',
             url: 'mypage.php',
             success: function(data)
             {
                 if (data === 'success') {
                    alert("New record created successfull");
                 }else{alert("something goes wrong"); }
             }
            });

here is the php code

 <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "success";
}
catch(PDOException $e)
{
echo "fail";
}

$conn = null;
?>

and when i try to check the message returned from the php page i get the right alert with this ajax call

$.ajax({
             data: dataString,
             type: 'POST',
             url: 'mypage.php',
             success: function(data)
             {
                 alert(data);
             }
            });

i tried many things but i cannot find where is the problem exactly, any help will be appreciated.

Body:
This will work I used same code in another case:

if ($.trim(data) === 'success') {
   alert("New record created successfull");
}else{alert("something goes wrong"); }


问:
dynamic vs object type
I have used the dynamic and the object type interchangeably. Is there any difference between these two types? Is there any performance implications of using one over the other? Which one of these is more flexible?</p>

答:
With the advancement in C# language, we have seen the dynamic and object types.  Here are the two types, as I learned by comparing these 7 points:

Object

Microsoft introduced the Object type in C# 1.0.

It can store any value because "object" is the base class of all types in the .NET framework.

Compiler has little information about the type.

We can pass the object type as a method argument, and the method also can return the object type.

We need to cast object variables to the original type to use it and to perform desired operations.

Object can cause problems at run time if the stored value is not converted or cast to the underlying data type.

Useful when we don't have more information about the data type.

Dynamic

Dynamic was introduced with C# 4.0

It can store any type of variable, similar to how Visual Basic handles a variable.

It is not type-safe, i.e., the compiler doesn't have any information about the type of variable.

A method can both accept a Dynamic type as an argument and return it.

Casting is not required, but you need to know the properties and methods related to stored type.

The Dynamic type can cause problems if the wrong properties or methods are accessed because all the information about the stored value is resolved at run time, compared to at compilation.

Useful when we need to code using reflection or dynamic languages or with the COM objects due to writing less code.

Hopefully, this would help somebody.

Title: dynamic vs object type


问:
Entity Framework 6.1.3 initialize existing, but empty database from code-first model
I've got some Problems while preparing an Application for the release on production systems.

The situation:

Entity Framework 6.1.3 Code-First Model with several migrations

A windows service with dedicated serviceuser (not Local System)

The configuration (handled by a WPF-App) allows to paste a connectionstring pointing to the desired MS-SQL DB

The DB should be prepared by the installing admin, so that the serviceuser has dbowner, dbwriter and dbreader rights. (should be enough for future migrations)

The serviceuser should not have rights on the SQL-Servers masterdb. That's why the desired DB for the windows service must be created by the admin before starting the service

What i'm trying to do:

Writing an  IDatabaseInitializer<MyDbContext>, which initializes the existing, but empty database upon detection AND updates the database in case of an outdated model

What I tried:

Using the MigrateDatabaseToLatestVersion initializer => This one fails since there is no __MigrationHistory table in the prepared, but empty database

Using the CreateDatabaseIfNotExists initializer => This one fails, since the database is already existing, whicht leeds this initializer to do ... nothing

Writing my own IDbInitializer with the following InitializeDatabase-method:

```<code>public void InitializeDatabase(RapasiDbContext context)
{
    if (!context.Database.Exists()) //Shouldn't happen
    {
      ... // Throw Execption: No prepared DB found
    }
    try //Initialize the existing database, but only if not already done (force:false)
    {
        context.Database.InitializeDatabase(false);
    }
    catch (Exception ex)
    {
        Log.Fatal("Error while initializing the database", ex);
    }
    try //Update the databse, if model is outdated
    {
        var dbMigrationConfig = new Configuration();
        if (dbMigrationConfig.AutomaticMigrationsEnabled && !context.Database.CompatibleWithModel(true))
        {
            Log.Info("database schame outdated, starting migration!");
            try
            {
                var migrator = new DbMigrator(dbMigrationConfig);
                migrator.Update();
            }
            catch (Exception ex)
            {
                Log.Fatal("Error while migrating the database", ex);
            }
        }
    }
    catch (Exception ex)
    {
        Log.Fatal("No Migration-Histroy found!", ex);
    }
}
</code>```

The problem(s)

In the way I'm trying it now, the Initializer it not called at all

Switching to InitializeDatabase(force:true) leeds to recursivly calling my own InitializeDatabase method :(

The question:

How is it possible, to initialize an exsiting database with the InitialCommit-Up() script from my migrations?

Or am I missing some really obvious point, why this kind of DB initialization is not meant to happen? Are there any best practices for my situation I just don't know?

答:
MigrateDatabaseToLatestVersion initializer should work, even if there is no __MigrationHistory table. It is supposed to be created when the migrations are run for the first time.

As you say in your comment in the original question, you need to provide the right values for the constructor parameters of MigrateDatabaseToLatestVersion when calling SetInitializer method:

```<code>Database.SetInitializer(new MigrateDatabaseToLatestVersion<RapasiDbContext, Configuration>(true, new Configuration()));
</code>```

As the reference page says, the boolean parameter in the constructor specifies whether to use the connection information from the context that triggered initialization to perform the migration. If this parameter is missing the connection information will be obtained from a context constructed using the default constructor or registered factory (this may not be what you need).

Also, I think you may be interpreting the AutomaticMigrations configuration incorrectly. It does not mean that your migrations will be APPLIED automatically, it means they will be GENERATED automatically if you didn't manually run Add-Migration after your model changed. I guess you want your pending migrations to be executed when your database is not up to date, even if AutomaticMigrations are disabled.

Body:
I've got some Problems while preparing an Application for the release on production systems.

The situation:

Entity Framework 6.1.3 Code-First Model with several migrations

A windows service with dedicated serviceuser (not Local System)

The configuration (handled by a WPF-App) allows to paste a connectionstring pointing to the desired MS-SQL DB

The DB should be prepared by the installing admin, so that the serviceuser has dbowner, dbwriter and dbreader rights. (should be enough for future migrations)

The serviceuser should not have rights on the SQL-Servers masterdb. That's why the desired DB for the windows service must be created by the admin before starting the service

What i'm trying to do:

Writing an  IDatabaseInitializer<MyDbContext>, which initializes the existing, but empty database upon detection AND updates the database in case of an outdated model

What I tried:

Using the MigrateDatabaseToLatestVersion initializer => This one fails since there is no __MigrationHistory table in the prepared, but empty database

Using the CreateDatabaseIfNotExists initializer => This one fails, since the database is already existing, whicht leeds this initializer to do ... nothing

Writing my own IDbInitializer with the following InitializeDatabase-method:

public void InitializeDatabase(RapasiDbContext context)
{
    if (!context.Database.Exists()) //Shouldn't happen
    {
      ... // Throw Execption: No prepared DB found
    }
    try //Initialize the existing database, but only if not already done (force:false)
    {
        context.Database.InitializeDatabase(false);
    }
    catch (Exception ex)
    {
        Log.Fatal("Error while initializing the database", ex);
    }
    try //Update the databse, if model is outdated
    {
        var dbMigrationConfig = new Configuration();
        if (dbMigrationConfig.AutomaticMigrationsEnabled && !context.Database.CompatibleWithModel(true))
        {
            Log.Info("database schame outdated, starting migration!");
            try
            {
                var migrator = new DbMigrator(dbMigrationConfig);
                migrator.Update();
            }
            catch (Exception ex)
            {
                Log.Fatal("Error while migrating the database", ex);
            }
        }
    }
    catch (Exception ex)
    {
        Log.Fatal("No Migration-Histroy found!", ex);
    }
}

The problem(s)

In the way I'm trying it now, the Initializer it not called at all

Switching to InitializeDatabase(force:true) leeds to recursivly calling my own InitializeDatabase method :(

The question:

How is it possible, to initialize an exsiting database with the InitialCommit-Up() script from my migrations?

Or am I missing some really obvious point, why this kind of DB initialization is not meant to happen? Are there any best practices for my situation I just don't know?

Body:
MigrateDatabaseToLatestVersion initializer should work, even if there is no __MigrationHistory table. It is supposed to be created when the migrations are run for the first time.

As you say in your comment in the original question, you need to provide the right values for the constructor parameters of MigrateDatabaseToLatestVersion when calling SetInitializer method:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<RapasiDbContext, Configuration>(true, new Configuration()));

As the reference page says, the boolean parameter in the constructor specifies whether to use the connection information from the context that triggered initialization to perform the migration. If this parameter is missing the connection information will be obtained from a context constructed using the default constructor or registered factory (this may not be what you need).

Also, I think you may be interpreting the AutomaticMigrations configuration incorrectly. It does not mean that your migrations will be APPLIED automatically, it means they will be GENERATED automatically if you didn't manually run Add-Migration after your model changed. I guess you want your pending migrations to be executed when your database is not up to date, even if AutomaticMigrations are disabled.