问:
can arduino send repeated http requests and get and parse the the data from response
I want to use an Arduino for a project. What i want is arduino should send repeated http request (say every minute) with some data (most probably the IP address) to the server. And server will return a response with some data in JSON format and arduino should parse the data and write it to a text file. The data is some configuration parameters from the database. Can I do it with Arduino? I saw some posts saying that the repeated http request is not possible? any kind of help? A sample code will be really helpful. I am using Arduino mega with Ethernet shield.

```<code>#include <SPI.h>
#include <Ethernet.h>
#include <HttpClient.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup(){
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
 // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
// try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }

// give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.print("connecting... ");
}

void loop(){

  if (Ethernet.begin(mac) !=0){
    HttpClient http;
    http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL
    int httpCode = http.GET();                                        //Make the request
    if (httpCode > 0) { //Check for the returning code
        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
      }
    else {
      Serial.println("Error on HTTP request");
    }
    http.end(); //Free the resources
  }
  delay(10000);

    }
</code>```

I tried the above code to send an http request. But getting an error
no matching function for call to 'HttpClient::HttpClient()'

any suggestions would be really helpful.

答:
You don't have any limitation for sending repeated requests except the timing for each request. Your code is fine except the part that making an HTTP request. The default Arduino library is a little complicated for handling HTTP requests (e.g there is no HttpClient.GET).

There are many high-level API out there that handles the requests for you and also can set various header types.

For example ArduinoHTTPClient is a good one. Just grab the library and check out examples. I rewrite your code based on that and you will get your JSON response body. Then you can simply use one of the JSON parsers like ArduinoJSON to parse results.

```<code>#include <ArduinoHttpClient.h>
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);

char serverAddress[] = "http://jsonplaceholder.typicode.com"; // server address
int port = 80;

EthernetClient EthClient;
HttpClient client = HttpClient(EthClient, serverAddress, port);

void setup()
{
    Serial.begin(9600);

    // start the Ethernet connection:
    Serial.println("Initialize Ethernet with DHCP:");
    if (Ethernet.begin(mac) == 0)
    {
        Serial.println("Failed to configure Ethernet using DHCP");
        // Check for Ethernet hardware present
        if (Ethernet.hardwareStatus() == EthernetNoHardware)
        {
            Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
            while (true)
            {
                delay(1); // do nothing, no point running without Ethernet hardware
            }
        }
        if (Ethernet.linkStatus() == LinkOFF)
        {
            Serial.println("Ethernet cable is not connected.");
        }
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip, myDns);
    }
    else
    {
        Serial.print("  DHCP assigned IP ");
        Serial.println(Ethernet.localIP());
    }
}
void loop()
{
    Serial.println("making GET request");
    client.get("/comments?id=10");

    // read the status code and body of the response
    int statusCode = client.responseStatusCode();
    String response = client.responseBody();

    Serial.print("Status code: ");
    Serial.println(statusCode);
    Serial.print("Response: ");
    Serial.println(response);
    Serial.println("Wait five seconds");
    delay(5000);
}
</code>```

Body:
I want to use an Arduino for a project. What i want is arduino should send repeated http request (say every minute) with some data (most probably the IP address) to the server. And server will return a response with some data in JSON format and arduino should parse the data and write it to a text file. The data is some configuration parameters from the database. Can I do it with Arduino? I saw some posts saying that the repeated http request is not possible? any kind of help? A sample code will be really helpful. I am using Arduino mega with Ethernet shield.

#include <SPI.h>
#include <Ethernet.h>
#include <HttpClient.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup(){
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
 // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
// try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }

// give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.print("connecting... ");
}

void loop(){

  if (Ethernet.begin(mac) !=0){
    HttpClient http;
    http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL
    int httpCode = http.GET();                                        //Make the request
    if (httpCode > 0) { //Check for the returning code
        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
      }
    else {
      Serial.println("Error on HTTP request");
    }
    http.end(); //Free the resources
  }
  delay(10000);

    }

I tried the above code to send an http request. But getting an error
no matching function for call to 'HttpClient::HttpClient()'

any suggestions would be really helpful.

Body:
You don't have any limitation for sending repeated requests except the timing for each request. Your code is fine except the part that making an HTTP request. The default Arduino library is a little complicated for handling HTTP requests (e.g there is no HttpClient.GET).

There are many high-level API out there that handles the requests for you and also can set various header types.

For example ArduinoHTTPClient is a good one. Just grab the library and check out examples. I rewrite your code based on that and you will get your JSON response body. Then you can simply use one of the JSON parsers like ArduinoJSON to parse results.

#include <ArduinoHttpClient.h>
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);

char serverAddress[] = "http://jsonplaceholder.typicode.com"; // server address
int port = 80;

EthernetClient EthClient;
HttpClient client = HttpClient(EthClient, serverAddress, port);

void setup()
{
    Serial.begin(9600);

    // start the Ethernet connection:
    Serial.println("Initialize Ethernet with DHCP:");
    if (Ethernet.begin(mac) == 0)
    {
        Serial.println("Failed to configure Ethernet using DHCP");
        // Check for Ethernet hardware present
        if (Ethernet.hardwareStatus() == EthernetNoHardware)
        {
            Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
            while (true)
            {
                delay(1); // do nothing, no point running without Ethernet hardware
            }
        }
        if (Ethernet.linkStatus() == LinkOFF)
        {
            Serial.println("Ethernet cable is not connected.");
        }
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip, myDns);
    }
    else
    {
        Serial.print("  DHCP assigned IP ");
        Serial.println(Ethernet.localIP());
    }
}
void loop()
{
    Serial.println("making GET request");
    client.get("/comments?id=10");

    // read the status code and body of the response
    int statusCode = client.responseStatusCode();
    String response = client.responseBody();

    Serial.print("Status code: ");
    Serial.println(statusCode);
    Serial.print("Response: ");
    Serial.println(response);
    Serial.println("Wait five seconds");
    delay(5000);
}


来源: stackexchange

问:
Where is the basic Control-TAB (MRU) behavior in Xcode?
In most multi-document editors for windowing environments, Control-TAB will utilize an MRU list to bring the user back to the last visible file.  What is the appropriate command to accomplish this in Xcode 3.x?

I currently have Ctrl-TAB mapped to "View|Previous File", however this does not appear to be an MRU. Worse yet, if it hits the "beginning" of the list (should be a circular buffer), it falls back on inserting an actual TAB character into the text editor.

答:
In Xcode 3 (or any Mac application) you can use Command-Tilde (⌘~) to switch between open windows.

In Xcode 4 you use ⌘} for next tab and ⌘{ for previous tab - command shift bracket.

As a side note, for some reason Xcode 4 won't let me set the key binding for previous/next tab to the standard Control-Tab.  When I try it puts in Command-Control-Tab.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
cannot import yaml on mac
The software I have requires yaml, based on the import yaml at the top. I installed pyyaml on the mac I am using and it still threw the import error. I tried to change the code in the program to import pyyaml but that still didn't help. Any idea what the module is called to import it? If you need more information just ask.

答:
For python2:
sudo yum install python-yaml

For python3:
sudo yum install python3-yaml

Title: cannot import yaml on mac


问:
Getting properties of keys in Javascript
I have a key/value array that I defined by doing something similar to:

```<code>var arr;

function assign(iSize, jSize)
{
    arr = {};

    for (var i = 0; i < iSize; i++) {
        for (var j = 0; j < jSize; j++) {
            var pt = new Point(i, j);
            arr[pt] = [1, 2, 3];
        }
    }
}
</code>```

Where my Point function is

```<code>function Point(x, y) {
    this.x = x;
    this.y = y;
}
</code>```

and now I would like to iterate through all the values of the array but I also need to know the keys as well. I've tried

```<code>function iterate() {
    for(var e in arr) {
        console.log(e.x);
    }
}
</code>```

but it just prints out undefined. Also, if I try

```<code>function iterate() {
    console.log(Object.keys(arr));
}
</code>```

I just get [object Object] as output.

I've tried printing out the Point at the moment of creation and I can access the x and y values just fine.

As a side note, in my actual implementation I'm not just assigning the array [1, 2, 3] to each index of my array. I am assigning an array generated by another function that has nothing to do with accessing the keys in arr

答:
The main problem is that you use an object (Point) as key. If you save a reference to this object and then use it as a key you get your property (last property in code introduced by me). Do you really need Point object as key?</p>

```<code>var arr;
var ptRef;
function assign(iSize, jSize) {
  arr = {};
  ptRef = {};
  for (var i = 0; i < iSize; i++) {
    for (var j = 0; j < jSize; j++) {
      var pt = new Point(i, j);
      console.log(pt);
      arr[pt] = [1, 2, 3];
      ptRef = pt;
    }
  }
  console.log(arr[ptRef]);
}
</code>```

Body:
I have a key/value array that I defined by doing something similar to:

var arr;

function assign(iSize, jSize)
{
    arr = {};

    for (var i = 0; i < iSize; i++) {
        for (var j = 0; j < jSize; j++) {
            var pt = new Point(i, j);
            arr[pt] = [1, 2, 3];
        }
    }
}

Where my Point function is

function Point(x, y) {
    this.x = x;
    this.y = y;
}

and now I would like to iterate through all the values of the array but I also need to know the keys as well. I've tried

function iterate() {
    for(var e in arr) {
        console.log(e.x);
    }
}

but it just prints out undefined. Also, if I try

function iterate() {
    console.log(Object.keys(arr));
}

I just get [object Object] as output.

I've tried printing out the Point at the moment of creation and I can access the x and y values just fine.

As a side note, in my actual implementation I'm not just assigning the array [1, 2, 3] to each index of my array. I am assigning an array generated by another function that has nothing to do with accessing the keys in arr

Body:
The main problem is that you use an object (Point) as key. If you save a reference to this object and then use it as a key you get your property (last property in code introduced by me). Do you really need Point object as key?

var arr;
var ptRef;
function assign(iSize, jSize) {
  arr = {};
  ptRef = {};
  for (var i = 0; i < iSize; i++) {
    for (var j = 0; j < jSize; j++) {
      var pt = new Point(i, j);
      console.log(pt);
      arr[pt] = [1, 2, 3];
      ptRef = pt;
    }
  }
  console.log(arr[ptRef]);
}


问:
How do I switch my theme based on data from local storage
My theme settings always revert to the default theme on page refresh despite reading the theme settings from local storage

Here is my code for the theme implementation:

```<code>green.addEventListener('click', () => {
  if (localStorage.getItem('theme') != 'green') {
    localStorage.setItem('theme', 'green');
  }
  main.classList.add(localStorage.getItem('theme'));
});
yellow.addEventListener('click', () => {
  if (localStorage.getItem('theme') !== 'yellow') {
    localStorage.setItem('theme', 'yellow');
  }
  main.className = localStorage.getItem('theme');
});
purple.addEventListener('click', () => {
  if (localStorage.getItem('theme') !== '') {
    localStorage.setItem('theme', '');
  }
  main.className = localStorage.getItem('theme');
});
</code>```

I've checked the localStorage and the theme values are stored

答: In your Initial class instead of setting it to empty, set the local storage to the default theme and read the theme value from local storage in your initial class. So that on page reload also you will be reading the theme from the local storage and it will be set already with the custom theme.</p>

Body:
My theme settings always revert to the default theme on page refresh despite reading the theme settings from local storage

Here is my code for the theme implementation:

green.addEventListener('click', () => {
  if (localStorage.getItem('theme') != 'green') {
    localStorage.setItem('theme', 'green');
  }
  main.classList.add(localStorage.getItem('theme'));
});
yellow.addEventListener('click', () => {
  if (localStorage.getItem('theme') !== 'yellow') {
    localStorage.setItem('theme', 'yellow');
  }
  main.className = localStorage.getItem('theme');
});
purple.addEventListener('click', () => {
  if (localStorage.getItem('theme') !== '') {
    localStorage.setItem('theme', '');
  }
  main.className = localStorage.getItem('theme');
});

I've checked the localStorage and the theme values are stored


问:
MacOS "configure: error: cannot run C compiled programs"
I am pretty new to the MacOS environment and I previously had some issue compiling C scripts. I had the following issue:

```<code>fatal error: stdio.h: No such file or directory
 #include <stdio.h>
                   ^
compilation terminated.
</code>```

I tried to re-install xcode-select --install but keep telling me

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

I updated everything and nothing.  Apparently it is because I don't have the /usr/includes file. I found a way to compile my software by using

/Library/Developer/CommandLineTools/usr/bin/g++ XXXX.cpp

However, now I am trying to ./compile and make another software but I don't know how to use this gcc interpreter by default. When I try to ./configure I got this error

configure: error: cannot run C compiled programs. If you meant to
  cross compile, use  '--host'. See 'config.log' for more details

So when I do look into config.log :

```<code>configure:3224: checking for gcc
configure:3240: found /usr/local/bin/gcc
configure:3251: result: gcc
configure:3282: checking for C compiler version
configure:3291: gcc --version >&5
gcc (GCC) 4.9.2 20141029 (prerelease)
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

configure:3302: $? = 0
configure:3291: gcc -v >&5
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/x86_64-apple-darwin14.0.0/4.9.2/lto-wrapper
Target: x86_64-apple-darwin14.0.0
Configured with: ../gcc-4.9-20141029/configure --enable-languages=c++,fortran
Thread model: posix
gcc version 4.9.2 20141029 (prerelease) (GCC)
configure:3302: $? = 0
configure:3291: gcc -V >&5
gcc: error: unrecognized command line option '-V'
gcc: fatal error: no input files
compilation terminated.
configure:3302: $? = 1
configure:3291: gcc -qversion >&5
gcc: error: unrecognized command line option '-qversion'
gcc: fatal error: no input files
compilation terminated.
configure:3302: $? = 1
configure:3322: checking whether the C compiler works
configure:3344: gcc    conftest.c  >&5
configure:3348: $? = 0
configure:3396: result: yes
configure:3399: checking for C compiler default output file name
configure:3401: result: a.out
configure:3407: checking for suffix of executables
configure:3414: gcc -o conftest    conftest.c  >&5
configure:3418: $? = 0
configure:3440: result:
configure:3462: checking whether we are cross compiling
configure:3470: gcc -o conftest    conftest.c  >&5
conftest.c:15:19: fatal error: stdio.h: No such file or directory
 #include <stdio.h>
                   ^
compilation terminated.
configure:3474: $? = 1
configure:3481: ./conftest
./configure: line 3483: ./conftest: No such file or directory
configure:3485: $? = 127
configure:3492: error: in `/Users/XXXX/phyml':
configure:3494: error: cannot run C compiled programs.
If you meant to cross compile, use `--host'.
See `config.log' for more details
</code>```

Do you have any ideas of how I can fix it ?

Thanks a lot !

答:
It's really easy to miss the answer from melpomene in the small comments to this question so let me post this here for everyone to see. This error usually means you're missing compiler tools (headers actually) that have been removed from Xcode.

You can find them in /Library/Developer/CommandLineTools/Packages/ since their name might be different depending on your version of macOS in the future.

Assuming you're running macOS Mojave (10.14), you need to run:

```<code>open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
</code>```

And an macOS-style package installer will start, asking you for your adminstrator password. This is an official Apple package and although it might be weird to install something out of a random directory, you can trust it. You don't have to take my word for it though. Apple buried this change in the Xcode 10 release notes and you can find their explanation here: https://developer.apple.com/documentation/xcode_release_notes/xcode_10_release_notes#3035623

I'll reproduce this here in case this link ever goes away or gets changed:

The Command Line Tools package installs the macOS system headers inside the macOS SDK. Software that compiles with the installed tools will search for headers within the macOS SDK provided by either Xcode at:

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk

or the Command Line Tools at:

/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk

depending on which is selected using xcode-select.

The command line tools will search the SDK for system headers by default. However, some software may fail to build correctly against the SDK and require macOS headers to be installed in the base system under /usr/include. If you are the maintainer of such software, we encourage you to update your project to work with the SDK or file a bug report for issues that are preventing you from doing so. As a workaround, an extra package is provided which will install the headers to the base system. In a future release, this package will no longer be provided. You can find this package at:

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

> To make sure that you're using the intended version of the command line tools, run xcode-select -s  or xcode select -s /Library/Developer/CommandLineTools after installing.

Body:
I am pretty new to the MacOS environment and I previously had some issue compiling C scripts. I had the following issue:

fatal error: stdio.h: No such file or directory
 #include <stdio.h>
                   ^
compilation terminated.

I tried to re-install xcode-select --install but keep telling me

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

I updated everything and nothing.  Apparently it is because I don't have the /usr/includes file. I found a way to compile my software by using

/Library/Developer/CommandLineTools/usr/bin/g++ XXXX.cpp

However, now I am trying to ./compile and make another software but I don't know how to use this gcc interpreter by default. When I try to ./configure I got this error

configure: error: cannot run C compiled programs. If you meant to
  cross compile, use  '--host'. See 'config.log' for more details

So when I do look into config.log :

configure:3224: checking for gcc
configure:3240: found /usr/local/bin/gcc
configure:3251: result: gcc
configure:3282: checking for C compiler version
configure:3291: gcc --version >&5
gcc (GCC) 4.9.2 20141029 (prerelease)
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

configure:3302: $? = 0
configure:3291: gcc -v >&5
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/x86_64-apple-darwin14.0.0/4.9.2/lto-wrapper
Target: x86_64-apple-darwin14.0.0
Configured with: ../gcc-4.9-20141029/configure --enable-languages=c++,fortran
Thread model: posix
gcc version 4.9.2 20141029 (prerelease) (GCC)
configure:3302: $? = 0
configure:3291: gcc -V >&5
gcc: error: unrecognized command line option '-V'
gcc: fatal error: no input files
compilation terminated.
configure:3302: $? = 1
configure:3291: gcc -qversion >&5
gcc: error: unrecognized command line option '-qversion'
gcc: fatal error: no input files
compilation terminated.
configure:3302: $? = 1
configure:3322: checking whether the C compiler works
configure:3344: gcc    conftest.c  >&5
configure:3348: $? = 0
configure:3396: result: yes
configure:3399: checking for C compiler default output file name
configure:3401: result: a.out
configure:3407: checking for suffix of executables
configure:3414: gcc -o conftest    conftest.c  >&5
configure:3418: $? = 0
configure:3440: result:
configure:3462: checking whether we are cross compiling
configure:3470: gcc -o conftest    conftest.c  >&5
conftest.c:15:19: fatal error: stdio.h: No such file or directory
 #include <stdio.h>
                   ^
compilation terminated.
configure:3474: $? = 1
configure:3481: ./conftest
./configure: line 3483: ./conftest: No such file or directory
configure:3485: $? = 127
configure:3492: error: in `/Users/XXXX/phyml':
configure:3494: error: cannot run C compiled programs.
If you meant to cross compile, use `--host'.
See `config.log' for more details

Do you have any ideas of how I can fix it ?

Thanks a lot !

Body:
It's really easy to miss the answer from melpomene in the small comments to this question so let me post this here for everyone to see. This error usually means you're missing compiler tools (headers actually) that have been removed from Xcode.

You can find them in /Library/Developer/CommandLineTools/Packages/ since their name might be different depending on your version of macOS in the future.

Assuming you're running macOS Mojave (10.14), you need to run:

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

And an macOS-style package installer will start, asking you for your adminstrator password. This is an official Apple package and although it might be weird to install something out of a random directory, you can trust it. You don't have to take my word for it though. Apple buried this change in the Xcode 10 release notes and you can find their explanation here: https://developer.apple.com/documentation/xcode_release_notes/xcode_10_release_notes#3035623

I'll reproduce this here in case this link ever goes away or gets changed:

The Command Line Tools package installs the macOS system headers inside the macOS SDK. Software that compiles with the installed tools will search for headers within the macOS SDK provided by either Xcode at:

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk

or the Command Line Tools at:

/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk

depending on which is selected using xcode-select.

The command line tools will search the SDK for system headers by default. However, some software may fail to build correctly against the SDK and require macOS headers to be installed in the base system under /usr/include. If you are the maintainer of such software, we encourage you to update your project to work with the SDK or file a bug report for issues that are preventing you from doing so. As a workaround, an extra package is provided which will install the headers to the base system. In a future release, this package will no longer be provided. You can find this package at:

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

> To make sure that you're using the intended version of the command line tools, run xcode-select -s  or xcode select -s /Library/Developer/CommandLineTools after installing.


问:
Access to the path (path name) is denied using File.Open
Debugging locally on Windows 10 machine, VS2015.

I need to open a file with Read access only. That file exists in a sub-folder of the web application.

This throws an exception:

System.UnauthorizedAccessException: Access to the path 'F:\webroot\subfolder' is denied.

I have tried adding Everyone with Full Permissions, adding every user with Full Permissions, turning on security policy auditing and checking the Security log to uncover the requesting user but nothing appears in there as if it is not actually a security error, a different folder name, and everything else I can find online including adding the ASPNET user - there is no such user to add.

The calculated path is the correct physical disk path. The path is inside the webroot.

```<code>string FilePath = HttpContext.Current.Server.MapPath("\\Upload");
string PathToFile = FilePath + "\\" + idFileName;
Stream fs = File.Open(FilePath, FileMode.Open, FileAccess.Read);
</code>```

The final line of code throws the exception.

ASP.NET web page output:
Access to the path 'F:\webrootname\Upload' is denied.

Application Event Log:

Event code: 4011
Event message: An unhandled access exception has occurred.

答:
Maybe it's because you're calling FileOpen with FilePath instead of PathToFile that you calculated, so :

Stream fs = File.Open(PathToFile, FileMode.Open, FileAccess.Read);
```

<p>Also, you can go further and test if the file exists before opening it :</p>

<pre class="lang-cs prettyprint-override"><code>string FilePath = HttpContext.Current.Server.MapPath("\\Upload");
string PathToFile = FilePath + "\\" + idFileName;
if(System.IO.File.Exists(PathToFile))
{
    Stream fs = File.Open(PathToFile, FileMode.Open, FileAccess.Read);
}
else
{
    // use whatever logger to trace your application
    log.Error("The file : + PathToFile + " does not exist");
}
</code>```

Body:
Debugging locally on Windows 10 machine, VS2015.

I need to open a file with Read access only. That file exists in a sub-folder of the web application.

This throws an exception:

System.UnauthorizedAccessException: Access to the path 'F:\webroot\subfolder' is denied.

I have tried adding Everyone with Full Permissions, adding every user with Full Permissions, turning on security policy auditing and checking the Security log to uncover the requesting user but nothing appears in there as if it is not actually a security error, a different folder name, and everything else I can find online including adding the ASPNET user - there is no such user to add.

The calculated path is the correct physical disk path. The path is inside the webroot.

string FilePath = HttpContext.Current.Server.MapPath("\\Upload");
string PathToFile = FilePath + "\\" + idFileName;
Stream fs = File.Open(FilePath, FileMode.Open, FileAccess.Read);

The final line of code throws the exception.

ASP.NET web page output:
Access to the path 'F:\webrootname\Upload' is denied.

Application Event Log:

Event code: 4011
Event message: An unhandled access exception has occurred.

Body:
Maybe it's because you're calling FileOpen with FilePath instead of PathToFile that you calculated, so :

Stream fs = File.Open(PathToFile, FileMode.Open, FileAccess.Read);

Also, you can go further and test if the file exists before opening it :

string FilePath = HttpContext.Current.Server.MapPath("\\Upload");
string PathToFile = FilePath + "\\" + idFileName;
if(System.IO.File.Exists(PathToFile))
{
    Stream fs = File.Open(PathToFile, FileMode.Open, FileAccess.Read);
}
else
{
    // use whatever logger to trace your application
    log.Error("The file : + PathToFile + " does not exist");
}


问:
SignalR hub resolves to null inside RabbitMQ subscription handler in ASP.NET Core
I have an ASP.NET Core MVC project with RabbitMQ (by means of EasyNetQ) and SignalR.

Next, I have a subscription on a RabbitMQ message that should send a notification to the client via SignalR.

But sadly, the hub always resolves to null.

An interesting observation is that when the application is still starting and there are still unacknowledged messages in the queue, the service actually resolves just fine.

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.RegisterEasyNetQ("host=localhost;virtualHost=/");
}

public void Configure(IApplicationBuilder app)
{
    app.UseSignalR(route =>
    {
        route.MapHub<MyHub>("/mypath");
    });

    app.Use(async (context, next) =>
    {
        var bus = context.RequestServices.GetRequiredService<IBus>();

        bus.SubscribeAsync<MyMessage>("MySubscription", async message =>
        {
            var hubContext = context.RequestServices
                .GetRequiredService<IHubContext<MyHub>>();

            // hubContext is null
            await hubContext.Clients.All.SendAsync("MyNotification");
        });

        await next.Invoke();
    });
}
</code>```

I suspect that perhaps I'm doing something wrong with regards to registering the subscription inside an app.Use but I can't seem to find any useful examples so this was the best I could figure.

I'm on ASP.NET Core 3 preview 5, I don't know if that has anything to do with my problem.

So the question is: how do I get the hub context inside the message subscription handler?

UPDATE

I've checked the GetRequiredService docs and the call should actuall throw an InvalidOperationException if the service couldn't be resolved, but it doesn't. It returns null, which as far as I can tell, shouldn't be possible (unless the default container supports registration of null-valued instances).

答:
I've managed to solve the issue with help from this issue by implementing an IHostedService instead.

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.RegisterEasyNetQ("host=localhost;virtualHost=/");
    services.AddHostedService<MyHostedService>();
}

public void Configure(IApplicationBuilder app)
{
    app.UseSignalR(route =>
    {
        route.MapHub<MyHub>("/mypath");
    });
}

public class MyHostedService : BackgroundService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public ServiceBusHostedService(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var scope = _serviceScopeFactory.CreateScope();
        var bus = scope.ServiceProvider.GetRequiredService<IBus>();

        bus.SubscribeAsync<MyMessage>("MySubscription", async message =>
        {
            var hubContext = scope.ServiceProvider.GetRequiredService<IHubContext<MyHub>>();

            await hubContext.Clients
                .All
                .SendAsync("MyNotification", cancellationToken: stoppingToken);
        });

        return Task.CompletedTask;
    }
}
</code>```

Body:
I have an ASP.NET Core MVC project with RabbitMQ (by means of EasyNetQ) and SignalR.

Next, I have a subscription on a RabbitMQ message that should send a notification to the client via SignalR.

But sadly, the hub always resolves to null.

An interesting observation is that when the application is still starting and there are still unacknowledged messages in the queue, the service actually resolves just fine.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.RegisterEasyNetQ("host=localhost;virtualHost=/");
}

public void Configure(IApplicationBuilder app)
{
    app.UseSignalR(route =>
    {
        route.MapHub<MyHub>("/mypath");
    });

    app.Use(async (context, next) =>
    {
        var bus = context.RequestServices.GetRequiredService<IBus>();

        bus.SubscribeAsync<MyMessage>("MySubscription", async message =>
        {
            var hubContext = context.RequestServices
                .GetRequiredService<IHubContext<MyHub>>();

            // hubContext is null
            await hubContext.Clients.All.SendAsync("MyNotification");
        });

        await next.Invoke();
    });
}

I suspect that perhaps I'm doing something wrong with regards to registering the subscription inside an app.Use but I can't seem to find any useful examples so this was the best I could figure.

I'm on ASP.NET Core 3 preview 5, I don't know if that has anything to do with my problem.

So the question is: how do I get the hub context inside the message subscription handler?

UPDATE

I've checked the GetRequiredService docs and the call should actuall throw an InvalidOperationException if the service couldn't be resolved, but it doesn't. It returns null, which as far as I can tell, shouldn't be possible (unless the default container supports registration of null-valued instances).

Body:
I've managed to solve the issue with help from this issue by implementing an IHostedService instead.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.RegisterEasyNetQ("host=localhost;virtualHost=/");
    services.AddHostedService<MyHostedService>();
}

public void Configure(IApplicationBuilder app)
{
    app.UseSignalR(route =>
    {
        route.MapHub<MyHub>("/mypath");
    });
}

public class MyHostedService : BackgroundService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public ServiceBusHostedService(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var scope = _serviceScopeFactory.CreateScope();
        var bus = scope.ServiceProvider.GetRequiredService<IBus>();

        bus.SubscribeAsync<MyMessage>("MySubscription", async message =>
        {
            var hubContext = scope.ServiceProvider.GetRequiredService<IHubContext<MyHub>>();

            await hubContext.Clients
                .All
                .SendAsync("MyNotification", cancellationToken: stoppingToken);
        });

        return Task.CompletedTask;
    }
}


问:
Migrate Error: Django/Postrgres: DataError Numeric Precision 10000 must be between 1 and 1000
When trying to migrate changes for the first time into my Postgresql DB, I encounter this error.

I can successfully migrate and start my app when using the standard SQLite db that DJango comes with. However, when trying to connect to my Postgresql I've been having trouble. I have my Postgresql open with pgAdmin and the databases connected with no data in them. I also have deleted all entries in my django app in case an import error was causing the error.

$ docker-compose run web python manage.py migrate
Starting src_db_1 ... done
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, courses, products, sessions
Running migrations:
  Applying products.0001_initial...Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
    return self.cursor.execute(sql)
psycopg2.DataError: NUMERIC precision 10000 must be between 1 and 1000
LINE 1: ...r(120) NOT NULL, "description" text NULL, "price" numeric(10...
                                                             ^

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  ...
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
    return self.cursor.execute(sql)
django.db.utils.DataError: NUMERIC precision 10000 must be between 1 and 1000
LINE 1: ...r(120) NOT NULL, "description" text NULL, "price" numeric(10...
```

<h1>This is my models.py where I created the price DecimalField.</h1>

<pre class="lang-py prettyprint-override"><code>from django.db import models
from django.urls import reverse

class Product(models.Model):
    title       = models.CharField(max_length=120) # max_length = required
    description = models.TextField(blank=True, null=True)
    price       = models.DecimalField(decimal_places=2, max_digits=100,blank=True)
    summary     = models.TextField(blank=True, null=True)
    featured    = models.BooleanField(default=False) # null=True, default=True

    def get_absolute_url(self):
        return reverse("products:product-detail", kwargs={"id": self.id}) #f"/products/{self.id}/"
</code>```

This is my manage.py

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trydjango.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)
```

```                                 ^
```

答:
According to the documentation, max_digits is the maximum number of digits allowed meanwhile decimal_places is the number of decimal places to store.

For example, if max_digits = 6 and decimal_places = 2 means that you will 4 numbers for the digits and 2 for the decimal places (for a total of 6 digits max). Allowing us to store up to 9999,99.

Having said that, I think the error is related to specifying max_digits = 100. Try a lower number of digits.

Body:
When trying to migrate changes for the first time into my Postgresql DB, I encounter this error.

I can successfully migrate and start my app when using the standard SQLite db that DJango comes with. However, when trying to connect to my Postgresql I've been having trouble. I have my Postgresql open with pgAdmin and the databases connected with no data in them. I also have deleted all entries in my django app in case an import error was causing the error.

$ docker-compose run web python manage.py migrate
Starting src_db_1 ... done
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, courses, products, sessions
Running migrations:
  Applying products.0001_initial...Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
    return self.cursor.execute(sql)
psycopg2.DataError: NUMERIC precision 10000 must be between 1 and 1000
LINE 1: ...r(120) NOT NULL, "description" text NULL, "price" numeric(10...
                                                             ^

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  ...
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
    return self.cursor.execute(sql)
django.db.utils.DataError: NUMERIC precision 10000 must be between 1 and 1000
LINE 1: ...r(120) NOT NULL, "description" text NULL, "price" numeric(10...

This is my models.py where I created the price DecimalField.

from django.db import models
from django.urls import reverse

class Product(models.Model):
    title       = models.CharField(max_length=120) # max_length = required
    description = models.TextField(blank=True, null=True)
    price       = models.DecimalField(decimal_places=2, max_digits=100,blank=True)
    summary     = models.TextField(blank=True, null=True)
    featured    = models.BooleanField(default=False) # null=True, default=True

    def get_absolute_url(self):
        return reverse("products:product-detail", kwargs={"id": self.id}) #f"/products/{self.id}/"

This is my manage.py

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trydjango.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

                                 ^


问:
Is there a way to find text with spaces before and after string in excel?
I am trying to update some addresses and fix case sensitive errors for example "123 Nw Apple St" should be "123 NW Apple St" I would like to be able to find all "Ne","Nw","Se" and "Sw." and if possible replace them with the correct version. However, I have yet to figure out how to even find these.

I have tried a couple different methods using search and find. The problem I am running into is Nw is not always at the end of address.

A couple things I have tried;

```<code>=SEARCH(" "&"Nw"&" ",A2,1)
</code>```

and

```<code>=SEARCH(" Nw ",A2,1)
</code>```

I just need some identifier that Nw is found. If it could replace it with "NW"
that would be even better.

答:
If you wish to capitalize all two-character directions without changing a word like:

kitchenware

then consider the following User Defined Function:

```<code>Public Function TidyUp(sin As String) As String
    Dim i As Long
    arr = Split(sin, " ")
    For i = LBound(arr) To UBound(arr)
        If UCase(arr(i)) = "NE" Then arr(i) = "NE"
        If UCase(arr(i)) = "NW" Then arr(i) = "NW"
        If UCase(arr(i)) = "SE" Then arr(i) = "SE"
        If UCase(arr(i)) = "SW" Then arr(i) = "SW"
    Next i
    TidyUp = Join(arr, " ")
End Function
</code>```

User Defined Functions (UDFs) are very easy to install and use:

ALT-F11  brings up the VBE window

ALT-I
ALT-M opens a fresh module

paste the stuff in and close the VBE window

If you save the workbook, the UDF will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx

To remove the UDF:

bring up the VBE window as above

clear the code out

close the VBE window

To use the UDF from Excel:

=myfunction(A1)

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

and for specifics on UDFs, see:

http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx

Macros must be enabled for this to work!

Body:
I am trying to update some addresses and fix case sensitive errors for example "123 Nw Apple St" should be "123 NW Apple St" I would like to be able to find all "Ne","Nw","Se" and "Sw." and if possible replace them with the correct version. However, I have yet to figure out how to even find these.

I have tried a couple different methods using search and find. The problem I am running into is Nw is not always at the end of address.

A couple things I have tried;

=SEARCH(" "&"Nw"&" ",A2,1)

and

=SEARCH(" Nw ",A2,1)

I just need some identifier that Nw is found. If it could replace it with "NW"
that would be even better.

Body:
If you wish to capitalize all two-character directions without changing a word like:

kitchenware

then consider the following User Defined Function:

Public Function TidyUp(sin As String) As String
    Dim i As Long
    arr = Split(sin, " ")
    For i = LBound(arr) To UBound(arr)
        If UCase(arr(i)) = "NE" Then arr(i) = "NE"
        If UCase(arr(i)) = "NW" Then arr(i) = "NW"
        If UCase(arr(i)) = "SE" Then arr(i) = "SE"
        If UCase(arr(i)) = "SW" Then arr(i) = "SW"
    Next i
    TidyUp = Join(arr, " ")
End Function

User Defined Functions (UDFs) are very easy to install and use:

ALT-F11  brings up the VBE window

ALT-I
ALT-M opens a fresh module

paste the stuff in and close the VBE window

If you save the workbook, the UDF will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx

To remove the UDF:

bring up the VBE window as above

clear the code out

close the VBE window

To use the UDF from Excel:

=myfunction(A1)

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

and for specifics on UDFs, see:

http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx

Macros must be enabled for this to work!


问:
How to customize data provider request call?
I'm new to react and react-admin.

I'm, using jsonServerProvider (in my App.js I have the following):

```<code>import jsonServerProvider from 'ra-data-json-server';
</code>```

I'd like to create a custom bulk action. In a list, select many items and click a button to "connect" them. I tried to use UPDATE_MANY, but this calls my endpoint multiple times, so it's not suitable. Ideally I need the request to call my endpoint like so: url.to.myendpoint?ids=1,2,3 or even better pass an array of IDs in the body and use a PUT request.

Just to understand how things work and debug network calls, I tried also the GET_MANY, in the dataproviders page, the request seems to get the IDs like so: { ids: {mixed[]}, data: {Object} }

But the request is sent to the server like so: url.to.myendpoint?id=1&id=2&id=3 which in my python/flask backend is not nice to parse.

I've spent a bunch of time reading the docs, e.g.:

https://github.com/marmelab/react-admin/blob/master/docs/Actions.md

https://react-admin.com/docs/en/actions.html

https://marmelab.com/react-admin/Actions.html

I tried different approaches and I could not achieve what I want. So again please help me to make my custom bulk button work.

My bulk button is called ConnectItemsButton and the code looks like this:

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button, crudUpdateMany } from 'react-admin';
import { showNotification, GET_MANY } from 'react-admin';
import dataProvider from './dataProvider';

class ConnectItemsButton extends Component {
  handleClick = () => {
    const { selectedIds } = this.props;
    dataProvider(GET_MANY, 'items/connect', { ids: selectedIds })
      .then(() => {
        showNotification('Connected!');
      })
      .catch((e) => {
        showNotification('Error.', 'warning')
      });
  };

  render() {
    return (
      <Button label="Associate" onClick={this.handleClick} />
    );
  }
}

export default connect(undefined, { crudUpdateMany })(ConnectItemsButton);

</code>```

Note that the contents of ./dataProvider (it's the same provider used in the App.js file and passed to the <Admin> in the props):

```<code>import jsonServerProvider from 'ra-data-json-server';
export default jsonServerProvider('http://127.0.0.1:5000/api');
</code>```

In my list I created it, the button is displayed properly, so here I share the code snippet:

```<code>const PostBulkActionButtons = props => (
  <Fragment>
    <ConnectItemsButton {...props} />
  </Fragment>
);

...

export const ItemsList = props => (
  <List {...props} bulkActionButtons={<PostBulkActionButtons />}>

...

</code>```

In my backend endpoint items/connect I simply need to get a comma separated list of IDs to parse, that's it.

A simple working solution would be awesome, or at least point me in the right direction. Thanks for your help.

答:
The way I would do this is by using react-admin's dataActions. Your action would be something like this:

```<code>crudCreate('items/connect', { selectedIds: selectedIds }, basePath , redirectUrl)
</code>```

I recommend using a custom dataProvider (e.g. if you use jsonDataProvider, in your App.js import where you see ra-data-json-server: if you use WebStorm Ctrl + click on it and copy the code e.g. to customJsonDataProvider.js and fix eventual warnings, e.g. import lines should be moved at the top) and pass it as props to your Admin component. In your customJsonDataProvider you will have a convertDataRequestToHTTP, or something similar, which manages the CRUD actions and returns the url and HTTP method that you want to use.

An example of what you want to do would be:

```<code>const convertDataRequestToHTTP = (type, resource, params) => {
let url = '';
const options = {};

switch (type) {
    ...
    case CREATE: {
      ...
      if (type === 'items/connect') {
        const { data: { selectedIds } } = params;
        url = `${apiUrl}?${selectedIds.reduce((acc, id) => `${acc};${id}`)}`
        options.method = 'GET';
      }
      ...
      break;
    }
    ...
}
return { url, options };
</code>```

}

In your dataProvider.js, modify the import to use the custom provider you created, e.g.:

```<code>import jsonServerProvider from './customJsonServer';
</code>```

The code in your AssociateTradesButton.js should work fine as is.

You can find the documentation for creating you own dataProvider here.

Body:
I'm new to react and react-admin.

I'm, using jsonServerProvider (in my App.js I have the following):

import jsonServerProvider from 'ra-data-json-server';

I'd like to create a custom bulk action. In a list, select many items and click a button to "connect" them. I tried to use UPDATE_MANY, but this calls my endpoint multiple times, so it's not suitable. Ideally I need the request to call my endpoint like so: url.to.myendpoint?ids=1,2,3 or even better pass an array of IDs in the body and use a PUT request.

Just to understand how things work and debug network calls, I tried also the GET_MANY, in the dataproviders page, the request seems to get the IDs like so: { ids: {mixed[]}, data: {Object} }

But the request is sent to the server like so: url.to.myendpoint?id=1&id=2&id=3 which in my python/flask backend is not nice to parse.

I've spent a bunch of time reading the docs, e.g.:

https://github.com/marmelab/react-admin/blob/master/docs/Actions.md

https://react-admin.com/docs/en/actions.html

https://marmelab.com/react-admin/Actions.html

I tried different approaches and I could not achieve what I want. So again please help me to make my custom bulk button work.

My bulk button is called ConnectItemsButton and the code looks like this:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button, crudUpdateMany } from 'react-admin';
import { showNotification, GET_MANY } from 'react-admin';
import dataProvider from './dataProvider';

class ConnectItemsButton extends Component {
  handleClick = () => {
    const { selectedIds } = this.props;
    dataProvider(GET_MANY, 'items/connect', { ids: selectedIds })
      .then(() => {
        showNotification('Connected!');
      })
      .catch((e) => {
        showNotification('Error.', 'warning')
      });
  };

  render() {
    return (
      <Button label="Associate" onClick={this.handleClick} />
    );
  }
}

export default connect(undefined, { crudUpdateMany })(ConnectItemsButton);

Note that the contents of ./dataProvider (it's the same provider used in the App.js file and passed to the <Admin> in the props):

import jsonServerProvider from 'ra-data-json-server';
export default jsonServerProvider('http://127.0.0.1:5000/api');

In my list I created it, the button is displayed properly, so here I share the code snippet:

const PostBulkActionButtons = props => (
  <Fragment>
    <ConnectItemsButton {...props} />
  </Fragment>
);

...

export const ItemsList = props => (
  <List {...props} bulkActionButtons={<PostBulkActionButtons />}>

...

In my backend endpoint items/connect I simply need to get a comma separated list of IDs to parse, that's it.

A simple working solution would be awesome, or at least point me in the right direction. Thanks for your help.

Body:
The way I would do this is by using react-admin's dataActions. Your action would be something like this:

crudCreate('items/connect', { selectedIds: selectedIds }, basePath , redirectUrl)

I recommend using a custom dataProvider (e.g. if you use jsonDataProvider, in your App.js import where you see ra-data-json-server: if you use WebStorm Ctrl + click on it and copy the code e.g. to customJsonDataProvider.js and fix eventual warnings, e.g. import lines should be moved at the top) and pass it as props to your Admin component. In your customJsonDataProvider you will have a convertDataRequestToHTTP, or something similar, which manages the CRUD actions and returns the url and HTTP method that you want to use.

An example of what you want to do would be:

const convertDataRequestToHTTP = (type, resource, params) => {
let url = '';
const options = {};

switch (type) {
    ...
    case CREATE: {
      ...
      if (type === 'items/connect') {
        const { data: { selectedIds } } = params;
        url = `${apiUrl}?${selectedIds.reduce((acc, id) => `${acc};${id}`)}`
        options.method = 'GET';
      }
      ...
      break;
    }
    ...
}
return { url, options };

}

In your dataProvider.js, modify the import to use the custom provider you created, e.g.:

import jsonServerProvider from './customJsonServer';

The code in your AssociateTradesButton.js should work fine as is.

You can find the documentation for creating you own dataProvider here.


问:
FParsec: how to omit `many` parser failures from error messages
Consider this parser that converts digit strings to ints:

```<code>let toInt (s:string) =
    match Int32.TryParse(s) with
    | (true, n) -> preturn n
    | _         -> fail "Number must be below 2147483648"

let naturalNum = many1Chars digit >>= toInt <?> "natural number"
</code>```

When I run it on non-numeric strings like "abc" it shows the correct error message:

Error in Ln: 1 Col: 1
abc
^
Expecting: natural number
```

<p>But when I give it a numeric string exceeding the <code>int</code> range it gives the following counter-productive message:</p>

<pre class="lang-none prettyprint-override"><code>Error in Ln: 1 Col: 17
9999999999999999
                ^
Note: The error occurred at the end of the input stream.
Expecting: decimal digit
Other error messages:
  Number must be below 2147483648
</code>```

The primary message "Expecting: decimal digit" makes no sense, because we have to many digits already.

Is there a way to get rid of it and only show "Number must be below 2147483648"?

Full example:

```<code>open System
open FParsec

[<EntryPoint>]
let main argv =
    let toInt (s:string) =
        match Int32.TryParse(s) with
        | (true, n) -> preturn n
        | _         -> fail "Number must be below 2147483648"

    let naturalNum = many1Chars digit >>= toInt <?> "natural number"

    match run naturalNum "9999999999999999" with
    | Failure (msg, _, _) -> printfn "%s" msg
    | Success (a, _, _)   -> printfn "%A" a

    0
</code>```

答:
The effect you see ist that the first parser of your sequence succeeds, but also generates an error message (because it could consume even more digits). Your second parser consumes no further input and if it fails FParsec will therefore merge the error messages of the two sequenced parsers (Manual on merging of error messages).

A solution would be to create a small wrapper for a parser, that removes error messages from a result in the Ok case. Then when sequenced with a second parser only the message of the second parser remain.

Untested code from the top of my head:

```<code>let purify p =
    fun stream ->
        let res = p stream
        match res.Status with
            | Ok -> Reply(res.Result)
            | _ -> res

let naturalNum = purify (many1Chars digit) >>= toInt <?> "natural number"
</code>```

Body:
Consider this parser that converts digit strings to ints:

let toInt (s:string) =
    match Int32.TryParse(s) with
    | (true, n) -> preturn n
    | _         -> fail "Number must be below 2147483648"

let naturalNum = many1Chars digit >>= toInt <?> "natural number"

When I run it on non-numeric strings like "abc" it shows the correct error message:

Error in Ln: 1 Col: 1
abc
^
Expecting: natural number

But when I give it a numeric string exceeding the int range it gives the following counter-productive message:

Error in Ln: 1 Col: 17
9999999999999999
                ^
Note: The error occurred at the end of the input stream.
Expecting: decimal digit
Other error messages:
  Number must be below 2147483648

The primary message "Expecting: decimal digit" makes no sense, because we have to many digits already.

Is there a way to get rid of it and only show "Number must be below 2147483648"?

Full example:

open System
open FParsec

[<EntryPoint>]
let main argv =
    let toInt (s:string) =
        match Int32.TryParse(s) with
        | (true, n) -> preturn n
        | _         -> fail "Number must be below 2147483648"

    let naturalNum = many1Chars digit >>= toInt <?> "natural number"

    match run naturalNum "9999999999999999" with
    | Failure (msg, _, _) -> printfn "%s" msg
    | Success (a, _, _)   -> printfn "%A" a

    0

Body:
The effect you see ist that the first parser of your sequence succeeds, but also generates an error message (because it could consume even more digits). Your second parser consumes no further input and if it fails FParsec will therefore merge the error messages of the two sequenced parsers (Manual on merging of error messages).

A solution would be to create a small wrapper for a parser, that removes error messages from a result in the Ok case. Then when sequenced with a second parser only the message of the second parser remain.

Untested code from the top of my head:

let purify p =
    fun stream ->
        let res = p stream
        match res.Status with
            | Ok -> Reply(res.Result)
            | _ -> res

let naturalNum = purify (many1Chars digit) >>= toInt <?> "natural number"


问:
Hosting for a medium sized Python/Django App
I'm planning to build an app with Python/Django with a web interface and web services providing data feeds for mobile apps.

The solution should be scaleable.
Since there is obviously no guarantee that a lot of people will use the service I can't really tell how big the project gonna become. But it should be at least designed to scale quite a bit.

The data being served will mostly be text and pictures, so no need for the real heavy stuff for things like video or audio streaming, real time search and so on.

My question is, what host (best based in Europe) would you recommend?
I'm not so confident using Appengine due to evental lock-in effects and its data base restrictions. But if anyone can share good experiences with it, let me hear them.

答:
I've heard good things about DjangoEurope.

They have servers located in Germany, France and Switzerland.


问:
How can I implement a dynamic count within R without using a for loop?
I want to distinctly count the number of customers who have purchased from the company between each SKU's first and last purchase date. This is after I have distinctly counted the number of customers for each SKU given in SQL (as well as finding the first and last purchase date),

I have code that successfully solves this problem; however, it uses a for loop and it is taking far too long because there are tens of thousands of SKUs. This is short example of what my SKU table looks like:

```<code>SKUID <- c('123', '456', '789')
NumberOfCustomers <- c(204543, 92703, 305727)
SKUFirstPurchase <- c('2014-05-02', '2014-02-03', '2016-05-13')
SKULastPurchase <- c('2017-09-30', '2018-07-01', '2019-01-09')

SKUCount <- data.frame(SKUID, NumberOfCustomers,
                       SKUFirstPurchase, SKULastPurchase)
colnames(SKUCount) <- c('SKU', 'NumberOfCustomers',
                        'FirstPurchase', 'LastPurchase')
</code>```

Then I have another table that is about 6 million rows long, a select distinct of the sales date and the CustomerID that I call OrderTable. I can't summarize the distinct count on a day-to-day basis and sum them together because this would double count customers who have purchased on separate days. I have to re-calculate the distinct count with every FirstPurchase/LastPurchase permutation that I see in my SKUCount table. From there, I use the following code to calculate the distinct number of customers in the given time frame:

```<code>library(dplyr)

for (i in 1:nrow(SKUCount))
{
  SKUCount[i, c('DateCustomers')] <-
    sapply(OrderTable %>%
              filter(Date >= SKUCount[i,'FirstPurchase'],
                     Date <= SKUCount[i,'LastPurchase']) %>%
              select(CustomerID),
           function(x) length(unique(x)))
}
</code>```

As I previously noted, this piece of code DOES work, but it's very slow (~0.5 second for each row). Is there a quicker way to calculate the distinct counts, or is there a more clever solution to my problem?

答:
Try this one:

```<code>    library("purrrlyr")
    library("dplyr")

#First creating the datasets including OrderTable (please correct me if I got it wrong!):
    SKUID <- c('123', '456', '789')
    NumberOfCustomers <- c(204543, 92703, 305727)
    SKUFirstPurchase <- c('2014-05-02', '2014-02-03', '2016-05-13')
    SKULastPurchase <- c('2017-09-30', '2018-07-01', '2019-01-09')

    SKUCount <- data.frame(SKUID, NumberOfCustomers,
                           SKUFirstPurchase, SKULastPurchase)
    colnames(SKUCount) <- c('SKU', 'NumberOfCustomers',
                            'FirstPurchase', 'LastPurchase')

    OrderTable <- data.frame(Date=c('2014-06-02', '2014-08-02', '2015-02-03', '2017-05-13'
    ,'2015-05-02', '2014-06-03', '2016-07-13', '2017-09-30', '2018-07-01', '2019-01-09'),
    CustomerID=c('121','212','3434','24232','121','124','212','131','412','3634'))

#changing factors to date
    SKUCount$FirstPurchase<-as.Date(SKUCount$FirstPurchase,format = "%Y-%m-%d")
    SKUCount$LastPurchase<-as.Date(SKUCount$LastPurchase,format = "%Y-%m-%d")
    OrderTable$Date<-as.Date(OrderTable$Date,format = "%Y-%m-%d")

#defining a function, named FUN, which limit the Date from OrderTable between
#the two date arguments (FirstPurchase and LastPurchase) and returns the
#distinct count of CustomerID's from OrderTable:
FUN <- function(FirstPurchase,LastPurchase){
              Rtrn<-OrderTable %>%
              filter(Date >= FirstPurchase,
              Date <= LastPurchase)  %>%
              summarize(n_distinct(CustomerID))
              as.numeric(Rtrn)
              }
</code>```

Next you want to take your dataset, SKUCount, and create a variable called DateCustomers by applying the function, FUN, to every row of it:

```<code>    SKUCount %>%
      rowwise() %>%
       mutate(DateCustomers= FUN(FirstPurchase,LastPurchase))
      # Source: local data frame [3 x 5]
      # Groups: <by row>
      #
      #   # A tibble: 3 x 5
      #   SKU   NumberOfCustomers FirstPurchase LastPurchase DateCustomers
      # <fct>             <dbl> <date>        <date>               <dbl>
      #   1 123              204543 2014-05-02    2017-09-30          6
      # 2 456               92703 2014-02-03    2018-07-01            7
      # 3 789              305727 2016-05-13    2019-01-09            5
</code>```

Body:
I want to distinctly count the number of customers who have purchased from the company between each SKU's first and last purchase date. This is after I have distinctly counted the number of customers for each SKU given in SQL (as well as finding the first and last purchase date),

I have code that successfully solves this problem; however, it uses a for loop and it is taking far too long because there are tens of thousands of SKUs. This is short example of what my SKU table looks like:

SKUID <- c('123', '456', '789')
NumberOfCustomers <- c(204543, 92703, 305727)
SKUFirstPurchase <- c('2014-05-02', '2014-02-03', '2016-05-13')
SKULastPurchase <- c('2017-09-30', '2018-07-01', '2019-01-09')

SKUCount <- data.frame(SKUID, NumberOfCustomers,
                       SKUFirstPurchase, SKULastPurchase)
colnames(SKUCount) <- c('SKU', 'NumberOfCustomers',
                        'FirstPurchase', 'LastPurchase')

Then I have another table that is about 6 million rows long, a select distinct of the sales date and the CustomerID that I call OrderTable. I can't summarize the distinct count on a day-to-day basis and sum them together because this would double count customers who have purchased on separate days. I have to re-calculate the distinct count with every FirstPurchase/LastPurchase permutation that I see in my SKUCount table. From there, I use the following code to calculate the distinct number of customers in the given time frame:

library(dplyr)

for (i in 1:nrow(SKUCount))
{
  SKUCount[i, c('DateCustomers')] <-
    sapply(OrderTable %>%
              filter(Date >= SKUCount[i,'FirstPurchase'],
                     Date <= SKUCount[i,'LastPurchase']) %>%
              select(CustomerID),
           function(x) length(unique(x)))
}

As I previously noted, this piece of code DOES work, but it's very slow (~0.5 second for each row). Is there a quicker way to calculate the distinct counts, or is there a more clever solution to my problem?

Body:
Try this one:

    library("purrrlyr")
    library("dplyr")

#First creating the datasets including OrderTable (please correct me if I got it wrong!):
    SKUID <- c('123', '456', '789')
    NumberOfCustomers <- c(204543, 92703, 305727)
    SKUFirstPurchase <- c('2014-05-02', '2014-02-03', '2016-05-13')
    SKULastPurchase <- c('2017-09-30', '2018-07-01', '2019-01-09')

    SKUCount <- data.frame(SKUID, NumberOfCustomers,
                           SKUFirstPurchase, SKULastPurchase)
    colnames(SKUCount) <- c('SKU', 'NumberOfCustomers',
                            'FirstPurchase', 'LastPurchase')

    OrderTable <- data.frame(Date=c('2014-06-02', '2014-08-02', '2015-02-03', '2017-05-13'
    ,'2015-05-02', '2014-06-03', '2016-07-13', '2017-09-30', '2018-07-01', '2019-01-09'),
    CustomerID=c('121','212','3434','24232','121','124','212','131','412','3634'))

#changing factors to date
    SKUCount$FirstPurchase<-as.Date(SKUCount$FirstPurchase,format = "%Y-%m-%d")
    SKUCount$LastPurchase<-as.Date(SKUCount$LastPurchase,format = "%Y-%m-%d")
    OrderTable$Date<-as.Date(OrderTable$Date,format = "%Y-%m-%d")

#defining a function, named FUN, which limit the Date from OrderTable between
#the two date arguments (FirstPurchase and LastPurchase) and returns the
#distinct count of CustomerID's from OrderTable:
FUN <- function(FirstPurchase,LastPurchase){
              Rtrn<-OrderTable %>%
              filter(Date >= FirstPurchase,
              Date <= LastPurchase)  %>%
              summarize(n_distinct(CustomerID))
              as.numeric(Rtrn)
              }

Next you want to take your dataset, SKUCount, and create a variable called DateCustomers by applying the function, FUN, to every row of it:

    SKUCount %>%
      rowwise() %>%
       mutate(DateCustomers= FUN(FirstPurchase,LastPurchase))
      # Source: local data frame [3 x 5]
      # Groups: <by row>
      #
      #   # A tibble: 3 x 5
      #   SKU   NumberOfCustomers FirstPurchase LastPurchase DateCustomers
      # <fct>             <dbl> <date>        <date>               <dbl>
      #   1 123              204543 2014-05-02    2017-09-30          6
      # 2 456               92703 2014-02-03    2018-07-01            7
      # 3 789              305727 2016-05-13    2019-01-09            5


问:
Word wrapping in xml node content with lxml
I'm writing an XML file using lxml and in one of the nodes, the content to write is a very long string.
I'm looking for a way to wrap these strings in the XML nodes.

For now, I tried as below :

from lxml import etree

def lines_lenght(string, width):
    words = string.split()
    for i in range(0, len(words), width):
        yield " ".join(words[i:i+width])

s = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in enim at arcu tincidunt tristique. Ut commodo dui hendrerit lobortis egestas. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed laoreet interdum enim ut cursus. Fusce condimentum dictum dictum. Morbi feugiat bibendum enim, ut mollis turpis tincidunt vitae. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce libero ante, consectetur at sollicitudin at, eleifend lacinia ipsum. In hac habitasse platea dictumst. Sed laoreet mi eu nisi condimentum, sit amet vestibulum purus elementum. Nam a eros mi.
"""

root = etree.Element("corpus")

doc = etree.ElementTree(root)

article_node = etree.SubElement(root, "article")

final_content = "\n".join(lines_lenght(s, 10))
article_node.text = final_content

doc.write("corpus.xml", xml_declaration=True, encoding="utf-8")
```

<p>But in the generated XML file, the line breaks do not seem to be preserved. According this answer I tried with <code>\n</code> instead of \n, but the result is the same.</p>

<p>Any hint to help me?</p>

<p>Edit: Here is a preview of what I try to achieve:</p>

<pre class="lang-xml prettyprint-override"><code><corpus>
<article>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in
enim at arcu tincidunt tristique. Ut commodo dui hendrerit lobortis
egestas. Orci varius natoque penatibus et magnis dis parturient   montes</article>
</corpus>
</code>```

Instead of:

<corpus>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in enim at arcu tincidunt tristique. Ut commodo dui hendrerit lobortis egestas. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

</corpus>
```

答:
Well, it took a while to get there, and on the way I had to enlist the help of this answer here, and move out of lxml (which, as others have said, is a great library but has many limitations), to a python built in.

Is starts like yours, but stops right after article_node.text = final_content (before doc.write()). And adds from the answer linked above:

```<code>def indent(elem, level=0):
i = "\n" + level*"  "
if len(elem):
    #print(len(elem))
    if not elem.text or not elem.text.strip():
        elem.text = i + "  "
    if not elem.tail or not elem.tail.strip():
        elem.tail = i
    for elem in elem:
        indent(elem, level+1)
    if not elem.tail or not elem.tail.strip():
        elem.tail = i

else:
    if level and (not elem.tail or not elem.tail.strip()):
        elem.tail = i
</code>```

Then on to:

```<code>import xml.etree.ElementTree as ET
root2 = ET.fromstring(etree.tostring(doc))
tree = ET.ElementTree(root2)

indent(root2)
tree.write("corpus.xml", encoding="utf-8", xml_declaration=True)
</code>```

To test it:

```<code>with open("corpus.xml") as f:
    print(f.read())
</code>```

Output:

```<code><?xml version='1.0' encoding='utf-8'?>
<corpus>
  <article>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in
enim at arcu tincidunt tristique. Ut commodo dui hendrerit lobortis
egestas. Orci varius natoque penatibus et magnis dis parturient montes,
nascetur ridiculus mus. Sed laoreet interdum enim ut cursus. Fusce
condimentum dictum dictum. Morbi feugiat bibendum enim, ut mollis turpis
tincidunt vitae. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce libero ante, consectetur at sollicitudin at, eleifend lacinia ipsum.
In hac habitasse platea dictumst. Sed laoreet mi eu nisi
condimentum, sit amet vestibulum purus elementum. Nam a eros mi.</article>
</corpus>
</code>```

Those more familiar with the xml library may be able to make this shorter, but that's the best I could do...

Body:
I'm writing an XML file using lxml and in one of the nodes, the content to write is a very long string.
I'm looking for a way to wrap these strings in the XML nodes.

For now, I tried as below :

from lxml import etree

def lines_lenght(string, width):
    words = string.split()
    for i in range(0, len(words), width):
        yield " ".join(words[i:i+width])

s = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in enim at arcu tincidunt tristique. Ut commodo dui hendrerit lobortis egestas. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed laoreet interdum enim ut cursus. Fusce condimentum dictum dictum. Morbi feugiat bibendum enim, ut mollis turpis tincidunt vitae. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce libero ante, consectetur at sollicitudin at, eleifend lacinia ipsum. In hac habitasse platea dictumst. Sed laoreet mi eu nisi condimentum, sit amet vestibulum purus elementum. Nam a eros mi.
"""

root = etree.Element("corpus")

doc = etree.ElementTree(root)

article_node = etree.SubElement(root, "article")

final_content = "\n".join(lines_lenght(s, 10))
article_node.text = final_content

doc.write("corpus.xml", xml_declaration=True, encoding="utf-8")

But in the generated XML file, the line breaks do not seem to be preserved. According this answer I tried with
 instead of \n, but the result is the same.

Any hint to help me?

Edit: Here is a preview of what I try to achieve:

<corpus>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in
enim at arcu tincidunt tristique. Ut commodo dui hendrerit lobortis
egestas. Orci varius natoque penatibus et magnis dis parturient   montes

</corpus>

Instead of:

<corpus>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in enim at arcu tincidunt tristique. Ut commodo dui hendrerit lobortis egestas. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

</corpus>

Body:
Well, it took a while to get there, and on the way I had to enlist the help of this answer here, and move out of lxml (which, as others have said, is a great library but has many limitations), to a python built in.

Is starts like yours, but stops right after article_node.text = final_content (before doc.write()). And adds from the answer linked above:

def indent(elem, level=0):
i = "\n" + level*"  "
if len(elem):
    #print(len(elem))
    if not elem.text or not elem.text.strip():
        elem.text = i + "  "
    if not elem.tail or not elem.tail.strip():
        elem.tail = i
    for elem in elem:
        indent(elem, level+1)
    if not elem.tail or not elem.tail.strip():
        elem.tail = i

else:
    if level and (not elem.tail or not elem.tail.strip()):
        elem.tail = i

Then on to:

import xml.etree.ElementTree as ET
root2 = ET.fromstring(etree.tostring(doc))
tree = ET.ElementTree(root2)

indent(root2)
tree.write("corpus.xml", encoding="utf-8", xml_declaration=True)

To test it:

with open("corpus.xml") as f:
    print(f.read())

Output:

<?xml version='1.0' encoding='utf-8'?>
<corpus>
  <article>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in
enim at arcu tincidunt tristique. Ut commodo dui hendrerit lobortis
egestas. Orci varius natoque penatibus et magnis dis parturient montes,
nascetur ridiculus mus. Sed laoreet interdum enim ut cursus. Fusce
condimentum dictum dictum. Morbi feugiat bibendum enim, ut mollis turpis
tincidunt vitae. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce libero ante, consectetur at sollicitudin at, eleifend lacinia ipsum.
In hac habitasse platea dictumst. Sed laoreet mi eu nisi
condimentum, sit amet vestibulum purus elementum. Nam a eros mi.</article>
</corpus>

Those more familiar with the xml library may be able to make this shorter, but that's the best I could do...


问:
How to using open and .write to write string + variables value into a file on the same line?
I want to take input from the user containing a string, store that string into a variable and write it inside another strings line into a file.

I've tried using open and .write and using (%s) to add the input to the wrote line.

```<code>outF = open("file.txt", "w")
string = raw_input("enter string to add!")
outF.write('string data to write (%s)', % string)
outF.close()
</code>```

答:
Try This:

outF = open("file.txt", "a") #append mode if u wish to add more data to the file later
string = raw_input("enter string to add!")
string_new="string u want to add before"+string #add strings wherever u need
outF.write(string_new)
outF.close()
```

Body:
I want to take input from the user containing a string, store that string into a variable and write it inside another strings line into a file.

I've tried using open and .write and using (%s) to add the input to the wrote line.

outF = open("file.txt", "w")
string = raw_input("enter string to add!")
outF.write('string data to write (%s)', % string)
outF.close()


问:
How to generate a shuffled number series query with id in postgresql?
I would like to generate unique 'random' numbers in posgresql.

```<code>select s
from generate_series(1, 5) as s
order by random();
</code>```

This query results the following:

```<code>| s |
|---|
| 2 |
| 5 |
| 1 |
| 3 |
| 4 |
</code>```

But I would like to append it with an id, like this:

```<code>| id | s |
|----|---|
|  1 | 2 |
|  2 | 5 |
|  3 | 1 |
|  4 | 3 |
|  5 | 4 |
</code>```

答:
You could try using your resuly as a FROM (subquery) and ROW_NUMBER () OVER ()</p>

```<code>select  t.s,  ROW_NUMBER () OVER ()
from  (
  select s
  from generate_series(1, 5) as s
  order by random();
) t
</code>```

Body:
I would like to generate unique 'random' numbers in posgresql.

select s
from generate_series(1, 5) as s
order by random();

This query results the following:

| s |
|---|
| 2 |
| 5 |
| 1 |
| 3 |
| 4 |

But I would like to append it with an id, like this:

| id | s |
|----|---|
|  1 | 2 |
|  2 | 5 |
|  3 | 1 |
|  4 | 3 |
|  5 | 4 |

Body:
You could try using your resuly as a FROM (subquery) and ROW_NUMBER () OVER ()

select  t.s,  ROW_NUMBER () OVER ()
from  (
  select s
  from generate_series(1, 5) as s
  order by random();
) t