问:
Continuous Delivery for React App using Docker in Jenkins in Windows
I followed (this)[https://hackernoon.com/continuous-delivery-of-react-app-with-jenkins-and-docker-8a1ae1511b86] tutorial for setting up Continuous Delivery for React App using Jenkins and Docker.I made all initial set up in Jenkins and when i try to build job it shows the following error : -

So i understood the docker installation is missing in Jenkins pipeline so i tried to add docker installation in pipeline and added Jenkins installation in tool configuration as well.But still it shows same error any help will be highly appreciated.

This is my Jenkisfile : -

```<code>pipeline{
agent any
stages{
stage('Checkout') {
    steps{
        script{
            checkout scm
        }
     }
    }
stage('Install dependencies') {
  steps {
    script {
      def dockerTool = tool name: 'docker', type: 'org.jenkinsci.plugins.docker.commons.tools.DockerTool'
               withEnv(["DOCKER=${dockerTool}/bin"]) {
                //stages
                //here we can trigger: sh "sudo ${DOCKER}/docker ..."
                }
            }
        }
      }
   stage('Environment') {
       steps{
           script{
            sh 'git --version'
            echo "Branch: ${env.BRANCH_NAME}"
            sh 'docker -v'
            sh 'printenv'
           }
       }
     }
    stage('Build Docker test'){
        steps{
        sh 'docker build -t react-test -f Dockerfile.test --no-cache .'
        }
    }
    stage('Docker test'){
      steps{
      sh 'docker run --rm react-test'
      }
    }
    stage('Clean Docker test'){
      steps{
      sh 'docker rmi react-test'
      }
    }
    stage('Deploy'){
    steps{
      if(env.BRANCH_NAME == 'master'){
        sh 'docker build -t reactapp --no-cache .'
        sh 'docker tag reactapp localhost:5000/reactapp'
        sh 'docker push localhost:5000/reactapp'
        sh 'docker rmi -f react-app localhost:5000/reactapp'
      }
    }
    }
  }
 }
</code>```

Dockerfile

```<code># Extending image
FROM node:carbon

RUN apt-get update && apt-get install -y --no-install-recommends apt-utils
RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get -y install autoconf automake libtool nasm make pkg-config git apt-utils

# Install Docker -y flag suppresses prompting from apt-get
RUN apt-get update && \
    apt-get -y install docker-ce docker-ce-cli containerd.io

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
....
</code>```

答:
If you are running Jenkins within a Docker container like in that article, you'll need to have Docker installed in that Docker image to run Docker commands.  If Docker is installed, it's likely a permission or PATH issue.

One way you can check if Docker is installed and able to be run is to login to the container Jenkins is running in and try to run a Docker command:

docker ps - run on the machine that is running Docker will tell you what containers are running. Grab the CONTAINER ID for the Jenkins Docker container.

docker exec -it <put container id here> bash - will get you a running shell into that container so you can run commands from within the container.

docker -v - from within the container will tell you if docker has been installed successfully. If you get docker: command not found it isn't able to be used by Jenkins.

exit - will close your shell.

You can install Docker within the Jenkins Docker image by adding RUN commands to your Dockerfile. For example:

```<code># Install Docker -y flag suppresses prompting from apt-get
RUN apt-get update && \
    apt-get -y install docker-ce docker-ce-cli containerd.io
</code>```

Docker documentation to install: https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-docker-ce-1

Body:
I followed (this)[https://hackernoon.com/continuous-delivery-of-react-app-with-jenkins-and-docker-8a1ae1511b86] tutorial for setting up Continuous Delivery for React App using Jenkins and Docker.I made all initial set up in Jenkins and when i try to build job it shows the following error : -

So i understood the docker installation is missing in Jenkins pipeline so i tried to add docker installation in pipeline and added Jenkins installation in tool configuration as well.But still it shows same error any help will be highly appreciated.

This is my Jenkisfile : -

pipeline{
agent any
stages{
stage('Checkout') {
    steps{
        script{
            checkout scm
        }
     }
    }
stage('Install dependencies') {
  steps {
    script {
      def dockerTool = tool name: 'docker', type: 'org.jenkinsci.plugins.docker.commons.tools.DockerTool'
               withEnv(["DOCKER=${dockerTool}/bin"]) {
                //stages
                //here we can trigger: sh "sudo ${DOCKER}/docker ..."
                }
            }
        }
      }
   stage('Environment') {
       steps{
           script{
            sh 'git --version'
            echo "Branch: ${env.BRANCH_NAME}"
            sh 'docker -v'
            sh 'printenv'
           }
       }
     }
    stage('Build Docker test'){
        steps{
        sh 'docker build -t react-test -f Dockerfile.test --no-cache .'
        }
    }
    stage('Docker test'){
      steps{
      sh 'docker run --rm react-test'
      }
    }
    stage('Clean Docker test'){
      steps{
      sh 'docker rmi react-test'
      }
    }
    stage('Deploy'){
    steps{
      if(env.BRANCH_NAME == 'master'){
        sh 'docker build -t reactapp --no-cache .'
        sh 'docker tag reactapp localhost:5000/reactapp'
        sh 'docker push localhost:5000/reactapp'
        sh 'docker rmi -f react-app localhost:5000/reactapp'
      }
    }
    }
  }
 }

Dockerfile

# Extending image
FROM node:carbon

RUN apt-get update && apt-get install -y --no-install-recommends apt-utils
RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get -y install autoconf automake libtool nasm make pkg-config git apt-utils

# Install Docker -y flag suppresses prompting from apt-get
RUN apt-get update && \
    apt-get -y install docker-ce docker-ce-cli containerd.io

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
....

Body:
If you are running Jenkins within a Docker container like in that article, you'll need to have Docker installed in that Docker image to run Docker commands.  If Docker is installed, it's likely a permission or PATH issue.

One way you can check if Docker is installed and able to be run is to login to the container Jenkins is running in and try to run a Docker command:

docker ps - run on the machine that is running Docker will tell you what containers are running. Grab the CONTAINER ID for the Jenkins Docker container.

docker exec -it <put container id here> bash - will get you a running shell into that container so you can run commands from within the container.

docker -v - from within the container will tell you if docker has been installed successfully. If you get docker: command not found it isn't able to be used by Jenkins.

exit - will close your shell.

You can install Docker within the Jenkins Docker image by adding RUN commands to your Dockerfile. For example:

# Install Docker -y flag suppresses prompting from apt-get
RUN apt-get update && \
    apt-get -y install docker-ce docker-ce-cli containerd.io

Docker documentation to install: https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-docker-ce-1


来源: stackexchange

问:
MongoDB findOneAndUpdate returns null
I have this and I cannot get it to work. Console.log logs null.
If I log before de update code it actually logs the item that im trying to edit. If I do it after the findOneAndUpdate() it returns null.

Edit 2:

I changed the mongoose method to findById and it worked. Still have one problem though. New code:

```<code>let promo = await Promo.findById(req.body._id)
      console.log('Promo findById(promoId) => ' + promo)
      console.log('Promo Fields => ' + JSON.stringify(promoFields))
      if (promo) {
        // Update
        const promo = await Promo.findOneAndUpdate(
          { promo: req.body_id },
          { $set: promoFields },
          { new: true },
          (err, doc) =>
            console.log(err + ' <--- err ///// ' + doc + ' <--- doc ')
        )
        return res.json(promo)
</code>```

Output:

```<code>[0] Promo findById(promoId) => { _id: 5cee8b0134349e1eec482053,
[0]   title: 'Dos',
[0]   subtitle: 'dos',
[0]   desc: 'dos',
[0]   __v: 0 }
[0] Promo Fields => {"title":"Dos","subtitle":"dos","desc":"dos"}
[0] null <--- err ///// { _id: 5cee6bcbcfd3f11d580aa715,
[0]   new: false,
[0]   desc: 'dos',
[0]   subtitle: 'dos',
[0]   title: 'Dos' } <--- doc
</code>```

The problem now is no matter what item from the list I edit it always updates de first one. Can it be an id mismatch? If I debug the id from req, I have the correct id from the item selected.. don't know why it behaves this way.
Last but not least here's the reducer:

```<code>const initialState = {
  promos: null
}

export default function(state = initialState, action) {
  const { type, payload } = action

  switch (type) {
    case POST_PROMOS:
      return {
        ...state,
        ...payload,
        loading: false
      }
    default:
      return state
  }
}
</code>```

I was wondering if I could in the reduce make something like

```<code>state.promos.filter(promo => promo._id !== payload)
</code>```

and then generate a new array with the payload item. I'm mixing concepts?

Thank you in advance

答:
Bingo!
It seems that req.body._id for some reason even though it was the Id from the desired editing item, it was not an ObjectId.

I let promoId = mongoDb.ObjectId(req.body._id) and then

```<code>promo = await Promo.findOneAndUpdate(
          { _id: promoId },
          { $set: promoFields },
          { new: true }
        )
</code>```

:)! Thanks

ContentLicense: CC BY-SA 4.0

Title: MongoDB findOneAndUpdate returns null

Body:
I have this and I cannot get it to work. Console.log logs null.
If I log before de update code it actually logs the item that im trying to edit. If I do it after the findOneAndUpdate() it returns null.

Edit 2:

I changed the mongoose method to findById and it worked. Still have one problem though. New code:

let promo = await Promo.findById(req.body._id)
      console.log('Promo findById(promoId) => ' + promo)
      console.log('Promo Fields => ' + JSON.stringify(promoFields))
      if (promo) {
        // Update
        const promo = await Promo.findOneAndUpdate(
          { promo: req.body_id },
          { $set: promoFields },
          { new: true },
          (err, doc) =>
            console.log(err + ' <--- err ///// ' + doc + ' <--- doc ')
        )
        return res.json(promo)

Output:

[0] Promo findById(promoId) => { _id: 5cee8b0134349e1eec482053,
[0]   title: 'Dos',
[0]   subtitle: 'dos',
[0]   desc: 'dos',
[0]   __v: 0 }
[0] Promo Fields => {"title":"Dos","subtitle":"dos","desc":"dos"}
[0] null <--- err ///// { _id: 5cee6bcbcfd3f11d580aa715,
[0]   new: false,
[0]   desc: 'dos',
[0]   subtitle: 'dos',
[0]   title: 'Dos' } <--- doc

The problem now is no matter what item from the list I edit it always updates de first one. Can it be an id mismatch? If I debug the id from req, I have the correct id from the item selected.. don't know why it behaves this way.
Last but not least here's the reducer:

const initialState = {
  promos: null
}

export default function(state = initialState, action) {
  const { type, payload } = action

  switch (type) {
    case POST_PROMOS:
      return {
        ...state,
        ...payload,
        loading: false
      }
    default:
      return state
  }
}

I was wondering if I could in the reduce make something like

state.promos.filter(promo => promo._id !== payload)

and then generate a new array with the payload item. I'm mixing concepts?

Thank you in advance

Body:
Bingo!
It seems that req.body._id for some reason even though it was the Id from the desired editing item, it was not an ObjectId.

I let promoId = mongoDb.ObjectId(req.body._id) and then

promo = await Promo.findOneAndUpdate(
          { _id: promoId },
          { $set: promoFields },
          { new: true }
        )

:)! Thanks


问:
Set right padding for LeftDrawable in EditText
How to define right padding for LeftDrawable in EditText?

```<code>editText.setCompoundDrawablePadding(10);
</code>```

This sets padding for all sides, but I want for just one side, something like:

```<code>editText.setCompoundDrawablePadding(10, 0, 0, 0);
</code>```

答:
you can create a drawable XML with the image you want and add there the paddings you want, then you can use this drawable at the EditText

Example

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

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:bottom="5px"
        android:drawable="@drawable/ic_arrow_back_black_24dp"
        android:left="10px"
        android:right="10px"
        android:top="5px" />

</layer-list>
</code>```

Body:
How to define right padding for LeftDrawable in EditText?

editText.setCompoundDrawablePadding(10);

This sets padding for all sides, but I want for just one side, something like:

editText.setCompoundDrawablePadding(10, 0, 0, 0);

Body:
you can create a drawable XML with the image you want and add there the paddings you want, then you can use this drawable at the EditText

Example

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

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:bottom="5px"
        android:drawable="@drawable/ic_arrow_back_black_24dp"
        android:left="10px"
        android:right="10px"
        android:top="5px" />

</layer-list>


问:
Cypress JS and ability to upload and append an image
So I'm working on uploading a file in Cypress. Now I have an issue of appending the image to the page. I'm trying to upload/append the image under the following:

```<code><label for="upload-137" class="field-upload>
 <div class="layout justify-center">
  <span class="v-btn">
   <div class="v-btn__content">
    <i class="v-icon">add</i>
   </div>
  </span>
 </div>
 <input id="upload-137" name="upload" type="file" accept=".jpg,.jpeg,.png" class="file-input">
</label>
</code>```

Specifically I'm looking to append it after layout as a sibling after the span.

So my thought would be:

```<code>   cy.fixture('/driver/jack.jpg', 'base64').then(fileContent => {
    const jack = cy.get('input[type="file"]').upload({
      fileContent,
      fileName: 'jack.jpg',
      mimeType: 'image/jpg'
    }, {
      subjectType: 'input'
    }, );
    cy.get('.field-upload > .layout').then(($div) => {
      function words(){
        var image = document.createElement("img");
        image.setAttribute("src", jack);
        var location = document.getElementsByClassName("layout");
        location.appendChild(image);
      }
      $div.append(words)
    })
  })
</code>```

My thinking was to use cypress upload package to pull in the file to assign it to the input field and upload. Then get the location, create the img, set the source including in the fixture that's been uploaded. Then append it to the location (based on class name).

I end up getting

TypeError: location.appendChild is not a function

Is there a way to append an image that was uploaded?

答:
Two issues with the code:

document in your test code will refer to the document being used to run your tests, you actually want to use cy.document() to obtain the document of the application under test (AUT)

document.getElementsByClassName returns an array of HTMLElements, so you'd need to get the first element from that array to use it.

The corrected code would look like this:

cy.fixture('/driver/jack.jpg', 'base64').then(fileContent => {
  cy.get('input[type="file"]').upload({
    fileContent,
    fileName: 'jack.jpg',
    mimeType: 'image/jpg'
  }, {
    subjectType: 'input'
  }, );

  cy.document().then($document => {
    cy.get('.field-upload > .layout').then(($div) => {
      function words(){
        var image = $document.createElement("img");
        image.setAttribute("src", "path/to/jack.jpg");
        return image
      }
      $div.append(words)
    })
  })
})
```

Body:
So I'm working on uploading a file in Cypress. Now I have an issue of appending the image to the page. I'm trying to upload/append the image under the following:

    add

 <input id="upload-137" name="upload" type="file" accept=".jpg,.jpeg,.png" class="file-input">

Specifically I'm looking to append it after layout as a sibling after the span.

So my thought would be:

   cy.fixture('/driver/jack.jpg', 'base64').then(fileContent => {
    const jack = cy.get('input[type="file"]').upload({
      fileContent,
      fileName: 'jack.jpg',
      mimeType: 'image/jpg'
    }, {
      subjectType: 'input'
    }, );
    cy.get('.field-upload > .layout').then(($div) => {
      function words(){
        var image = document.createElement("img");
        image.setAttribute("src", jack);
        var location = document.getElementsByClassName("layout");
        location.appendChild(image);
      }
      $div.append(words)
    })
  })

My thinking was to use cypress upload package to pull in the file to assign it to the input field and upload. Then get the location, create the img, set the source including in the fixture that's been uploaded. Then append it to the location (based on class name).

I end up getting

TypeError: location.appendChild is not a function

Is there a way to append an image that was uploaded?


问:
How can I move my application across spaces in Bluemix?
I have a couple of apps running in my own Bluemix space and I want to shift them into a different space that we use for integration purposes.

I can see no option in any part of the Bluemix UI to do this. Is there a recommended way to make the move or even to copy these apps to the new space?

Thanks.

答:
Due to a recent update, now you should use ibmcloud cf ... instead of plain cf ...

So this means

ibmcloud cf target -s <my space name>
ibmcloud cf push <my app name>

Also, you might need to change the route-path, with --route-path ....

ContentLicense: CC BY-SA 3.0


问:
how to perform login with complete validation using Rest Api in React native
I am trying to Build an Application in React native i have to perform Login User Authentication using Rest Api . Because i am new to React native i am not able to understand how to perform this action can any body help. Thanks

答:
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.

Making requests

In order to fetch content from an arbitrary URL, just pass the URL to fetch:

fetch('https://mywebsite.com/mydata.json');
```

<p>example.js</p>

<pre class="lang-js prettyprint-override"><code>// Example POST method implementation:

postData('http://example.com/answer', {answer: 42})
  .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
  .catch(error => console.error(error));

function postData(url = '', data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, cors, *same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
            'Content-Type': 'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrer: 'no-referrer', // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
}
</code>```

Body:
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.

Making requests

In order to fetch content from an arbitrary URL, just pass the URL to fetch:

fetch('https://mywebsite.com/mydata.json');

example.js

// Example POST method implementation:

postData('http://example.com/answer', {answer: 42})
  .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
  .catch(error => console.error(error));

function postData(url = '', data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, cors, *same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
            'Content-Type': 'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrer: 'no-referrer', // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
}


问:
BigQuery pricing when using gcloud
I'm using bq load... to insert a .json file into my BigQuery dataset.

The pricing at https://cloud.google.com/bigquery/pricing suggests that:

Loading data into BigQuery is free, with the exception of a small charge for streamed data

By using the CLI, I'm not sure exactly how the data is being inserted into the table, but I would imagine it's being added in bulk, not one at a time. Does anybody know for certain whether or not datafile insertion via the GC CLI would be considered streaming?

答: bq load means "load", so there is no cost associated with using it. You have to use bq insert to use the streaming API.

Title: BigQuery pricing when using gcloud


问:
Passing Data to a Stateful Widget in Flutter
I'm wondering what the recommended way of passing data to a stateful widget, while creating it, is.

The two styles I've seen are:

```<code>class ServerInfo extends StatefulWidget {

  Server _server;

  ServerInfo(Server server) {
    this._server = server;
  }

  @override
    State<StatefulWidget> createState() => new _ServerInfoState(_server);
}

class _ServerInfoState extends State<ServerInfo> {
  Server _server;

  _ServerInfoState(Server server) {
    this._server = server;
  }
}
</code>```

This method keeps a value both in ServerInfo and _ServerInfoState, which seems a bit wasteful.

The other method is to use widget._server:

```<code>class ServerInfo extends StatefulWidget {

  Server _server;

  ServerInfo(Server server) {
    this._server = server;
  }

  @override
    State<StatefulWidget> createState() => new _ServerInfoState();
}

class _ServerInfoState extends State<ServerInfo> {
  @override
    Widget build(BuildContext context) {
      widget._server = "10"; // Do something we the server value
      return null;
    }
}
</code>```

This seems a bit backwards as the state is no longer stored in _ServerInfoSate but instead in the widget.

Is there a best practice for this?

答:
Another answer, building on @RémiRousselet's anwser and for @user6638204's question, if you want to pass initial values and still be able to update them in the state later:</p>

```<code>class MyStateful extends StatefulWidget {
  final String foo;

  const MyStateful({Key key, this.foo}): super(key: key);

  @override
  _MyStatefulState createState() => _MyStatefulState(foo: this.foo);
}

class _MyStatefulState extends State<MyStateful> {
  String foo;

  _MyStatefulState({this.foo});

  @override
  Widget build(BuildContext context) {
    return Text(foo);
  }
}
</code>```

Body:
I'm wondering what the recommended way of passing data to a stateful widget, while creating it, is.

The two styles I've seen are:

class ServerInfo extends StatefulWidget {

  Server _server;

  ServerInfo(Server server) {
    this._server = server;
  }

  @override
    State<StatefulWidget> createState() => new _ServerInfoState(_server);
}

class _ServerInfoState extends State<ServerInfo> {
  Server _server;

  _ServerInfoState(Server server) {
    this._server = server;
  }
}

This method keeps a value both in ServerInfo and _ServerInfoState, which seems a bit wasteful.

The other method is to use widget._server:

class ServerInfo extends StatefulWidget {

  Server _server;

  ServerInfo(Server server) {
    this._server = server;
  }

  @override
    State<StatefulWidget> createState() => new _ServerInfoState();
}

class _ServerInfoState extends State<ServerInfo> {
  @override
    Widget build(BuildContext context) {
      widget._server = "10"; // Do something we the server value
      return null;
    }
}

This seems a bit backwards as the state is no longer stored in _ServerInfoSate but instead in the widget.

Is there a best practice for this?

Body:
Another answer, building on @RémiRousselet's anwser and for @user6638204's question, if you want to pass initial values and still be able to update them in the state later:

class MyStateful extends StatefulWidget {
  final String foo;

  const MyStateful({Key key, this.foo}): super(key: key);

  @override
  _MyStatefulState createState() => _MyStatefulState(foo: this.foo);
}

class _MyStatefulState extends State<MyStateful> {
  String foo;

  _MyStatefulState({this.foo});

  @override
  Widget build(BuildContext context) {
    return Text(foo);
  }
}


问:
how to iterate a function over multiple lists?
I have the following function:

```<code>def calc(X: float, Y: float, z: float) -> dict:
    n1 = X*Y
    n2 = Y*z
    n3 = z**2
    return {"c": n1, "d" : n2, "e" : n3}
</code>```

I can take a list such as [10,10,20] and input it into the function using the *args approach:

```<code>list_1 = [10,10,20]
calc(*list_1)

#results
{'c' : 100, 'd': 200, 'e': 400}
</code>```

However, let's assume I want to pass an array or multiple lists into the function, such as:

```<code>list_2 = [[10,10,20],
          [20,25,30],
          [35,40,45]]
</code>```

where I want the function to iterate over each individual list.

I have thought about using a loop, but cannot get how to iterate over each aspect of the multi-dimensional list.

I have tried potentially using the index by doing the following:

```<code>for x in len(list_2):
      call(*list_2[x])
</code>```

but I get the following error:

```<code>'int' object is not ierable
</code>```

Ideally, I would like this to be vectorized and avoid using loops, but any input or direction is much appreciated!

答:
Note that you cannot avoid looping over the list, since you have to extract each sublist and pass it to the function as argument.

Now you can iterate over the 2D list, and pass each sublist as an argument, and then collect the results in a list

```<code>def calc(X: float, Y: float, z: float) -> dict:
    n1 = X*Y
    n2 = Y*z
    n3 = z**2
    return {"c": n1, "d" : n2, "e" : n3}

list_2 = [[10,10,20],
          [20,25,30],
          [35,40,45]]

#Iterate over the sublists, pass each sublist to the function, and collect its result
res = [calc(*li) for li in list_2]

print(res)
</code>```

Or you can use a map which is equivalent to the list-comprehension defined above

```<code>#Pass each sublist to the function by unpacking the list of lists, and collect its result
res = list(map(calc, *list_2))
</code>```

The output will be same in both cases

```<code>[{'c': 100, 'd': 200, 'e': 400},
{'c': 500, 'd': 750, 'e': 900},
{'c': 1400, 'd': 1800, 'e': 2025}]
</code>```

Body:
I have the following function:

def calc(X: float, Y: float, z: float) -> dict:
    n1 = X*Y
    n2 = Y*z
    n3 = z**2
    return {"c": n1, "d" : n2, "e" : n3}

I can take a list such as [10,10,20] and input it into the function using the *args approach:

list_1 = [10,10,20]
calc(*list_1)

#results
{'c' : 100, 'd': 200, 'e': 400}

However, let's assume I want to pass an array or multiple lists into the function, such as:

list_2 = [[10,10,20],
          [20,25,30],
          [35,40,45]]

where I want the function to iterate over each individual list.

I have thought about using a loop, but cannot get how to iterate over each aspect of the multi-dimensional list.

I have tried potentially using the index by doing the following:

for x in len(list_2):
      call(*list_2[x])

but I get the following error:

'int' object is not ierable

Ideally, I would like this to be vectorized and avoid using loops, but any input or direction is much appreciated!

Body:
Note that you cannot avoid looping over the list, since you have to extract each sublist and pass it to the function as argument.

Now you can iterate over the 2D list, and pass each sublist as an argument, and then collect the results in a list

def calc(X: float, Y: float, z: float) -> dict:
    n1 = X*Y
    n2 = Y*z
    n3 = z**2
    return {"c": n1, "d" : n2, "e" : n3}

list_2 = [[10,10,20],
          [20,25,30],
          [35,40,45]]

#Iterate over the sublists, pass each sublist to the function, and collect its result
res = [calc(*li) for li in list_2]

print(res)

Or you can use a map which is equivalent to the list-comprehension defined above

#Pass each sublist to the function by unpacking the list of lists, and collect its result
res = list(map(calc, *list_2))

The output will be same in both cases

[{'c': 100, 'd': 200, 'e': 400},
{'c': 500, 'd': 750, 'e': 900},
{'c': 1400, 'd': 1800, 'e': 2025}]


问:
Promise don't resolve in catchError typescript
I need resolve(false) in catchError, but this dosn't work.

In my loin.page.ts

async login() {
      if (this.signin.valid) {
        const controls = this.signin.controls;
        const valid = await this.authService.signin(controls.email.value, controls.password.value);
        if (valid) {
            this.navCtrl.navigateRoot('/user', { animated: true});
        } else {
            console.log('Bad credentials');
        }
    }
  }
```

<p><strong>authService.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';

constructor(private http: HttpClient) {}

signin(email, password) {

        const headers = new HttpHeaders({
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        });
        const data = {
            email,
            password
        };
        const url = URL_SERVICIOS + 'xxx';
        return new Promise ((resolve) => {

            this.http.post(url, data).pipe(
                map( (result: any) => {
                    this.credentials = result;
                    resolve(true);
                }),
                catchError(() => {
                    return Promise.resolve(false);
                })
            ).subscribe();
        });
     }
</code>```

This code ends in 'return Promise.resolve(false);' and does not continue in loin.page.ts

答:
You could try like below, just annotated with type and used resolve() in both success and catch block</p>

```<code>...
 return new Promise<boolean>((resolve) => {
     this.http.post(url, data).pipe(
         map( (result: any) => {
             this.credentials = result;
             resolve(true);
         }),
         catchError(() => {
             resolve(false);
         })
         ).subscribe();
     });
...
</code>```

Body:
I need resolve(false) in catchError, but this dosn't work.

In my loin.page.ts

async login() {
      if (this.signin.valid) {
        const controls = this.signin.controls;
        const valid = await this.authService.signin(controls.email.value, controls.password.value);
        if (valid) {
            this.navCtrl.navigateRoot('/user', { animated: true});
        } else {
            console.log('Bad credentials');
        }
    }
  }

authService.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';

constructor(private http: HttpClient) {}

signin(email, password) {

        const headers = new HttpHeaders({
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        });
        const data = {
            email,
            password
        };
        const url = URL_SERVICIOS + 'xxx';
        return new Promise ((resolve) => {

            this.http.post(url, data).pipe(
                map( (result: any) => {
                    this.credentials = result;
                    resolve(true);
                }),
                catchError(() => {
                    return Promise.resolve(false);
                })
            ).subscribe();
        });
     }

This code ends in 'return Promise.resolve(false);' and does not continue in loin.page.ts

Body:
You could try like below, just annotated with type and used resolve() in both success and catch block

...
 return new Promise<boolean>((resolve) => {
     this.http.post(url, data).pipe(
         map( (result: any) => {
             this.credentials = result;
             resolve(true);
         }),
         catchError(() => {
             resolve(false);
         })
         ).subscribe();
     });
...


问:
How does etcd propagate writes to non-leader members?
From both the visualisation on the raft.github.io page and The Secret Lives of Data shows that write requests in Raft must be sent through the leader.

When I am running etcd, which uses Raft, I can send a etcdctl put request to any of the etcd members, even if they are not the leader, and the write would still be propagated across the cluster.

What is the mechanism behind this? Is it part of Raft? Is it specific to etcd or etcdctl?

答:
In the Raft paper, chapter 5.1.,

The leader handles all client requests (if
  a client contacts a follower, the follower redirects it to the
  leader).

They suggest that you contact any peer, and that peer either is the leader and does the work or it responds to the client with the information about the current leader, and then the client retries the request. This allows the client to know only one peer, and eventually the client finds out who the leader is.

Since all peers inside a cluster know about other peers, one can implement request redirection on the peer itself. This way, the client doesn't know about the redirection layer and can also only know for one peer.

Another option would be to broadcast the request to all peers, and checking that only one peer responds with success, (or none if an election is in progress and then you can retry the request). This would mean that the client needs to know about all the peers, and if you have a dynamic Raft cluster, you would need to keep track of the cluster configuration changes on the client also.

The mechanism behind this is specific to etcd and their implementation.
From the docs available at github:

'MsgProp' proposes to append data to its log entries. This is a special
      type to redirect proposals to leader. Therefore, send method overwrites
      raftpb.Message's term with its HardState's term to avoid attaching its
      local term to 'MsgProp'. When 'MsgProp' is passed to the leader's 'Step'
      method, the leader first calls the 'appendEntry' method to append entries
      to its log, and then calls 'bcastAppend' method to send those entries to
      its peers. When passed to candidate, 'MsgProp' is dropped. When passed to
      follower, 'MsgProp' is stored in follower's mailbox(msgs) by the send
      method. It is stored with sender's ID and later forwarded to leader by
      rafthttp package.


问:
How can I use ComponentName.js instead of index.js when importing React component (from Atomic design structure directory)
I am using Gatsby (React) for my project. I am using Atomic design folder structure e.g:

```<code>src/components/Organisms/Header
</code>```

In this folder I like to have:

```<code>src/components/Organisms/Header/header.js
src/components/Organisms/Header/header.module.scss
</code>```

How can I import header.js from within src/components/layout.js like:

```<code>import Header from '@components/Organisms/Header'
</code>```

instead of:

```<code>import Header from '@components/Organisms/Header/header'
</code>```

Update:

I managed to do it by:

adding an index.js file to src/components/Organisms/Header/

and export { default } from './header'; in index.js

But are this best practices?

答:
You have a few options here. With all of these you would import src/components/Header.

1. Flat with no component directory (my preference):

```<code>src
└── components
    ├── Header.js
    └── header.module.css
</code>```

Benefits

Less meaningless nesting

No conflicting/confusing filenames open in your editor (e.g. index)

Easy to follow the imports and exports

Drawbacks

Nowhere for one-off resources and sub-components to go

2. Adjacent component and resources-directory (Ruby-style):

```<code>src
└── components
    ├── Header
    │   ├── header.module.css
    │   └── logo.png
    └── Header.js
</code>```

Benefits

Resources and sub-components are kept together

No conflicting/confusing filenames open in your editor (e.g. index)

Easy to follow the imports and exports

Drawbacks

The component isn't adjacent to resources, so imports require a ./Header/ prefix

Depending on the sorting, the resources directory may not be listed immediately adjacent to the component

3. With a directory index that exports Header:

```<code>src
└── components
    └── Header
        ├── Header.js
        ├── header.module.css
        ├── index.js
        └── logo.png
</code>```

Benefits

Component and resources are kept together

Sorting doesn't matter

Drawbacks

Conflicting/confusing filenames open in your editor (e.g. index)

Confusing imports and exports, may cause hard-to-diagnose errors

Extra work for every component

Body:
I am using Gatsby (React) for my project. I am using Atomic design folder structure e.g:

src/components/Organisms/Header

In this folder I like to have:

src/components/Organisms/Header/header.js
src/components/Organisms/Header/header.module.scss

How can I import header.js from within src/components/layout.js like:

import Header from '@components/Organisms/Header'

instead of:

import Header from '@components/Organisms/Header/header'

Update:

I managed to do it by:

adding an index.js file to src/components/Organisms/Header/

and export { default } from './header'; in index.js

But are this best practices?

Body:
You have a few options here. With all of these you would import src/components/Header.

1. Flat with no component directory (my preference):

src
└── components
    ├── Header.js
    └── header.module.css

Benefits

Less meaningless nesting

No conflicting/confusing filenames open in your editor (e.g. index)

Easy to follow the imports and exports

Drawbacks

Nowhere for one-off resources and sub-components to go

2. Adjacent component and resources-directory (Ruby-style):

src
└── components
    ├── Header
    │   ├── header.module.css
    │   └── logo.png
    └── Header.js

Benefits

Resources and sub-components are kept together

No conflicting/confusing filenames open in your editor (e.g. index)

Easy to follow the imports and exports

Drawbacks

The component isn't adjacent to resources, so imports require a ./Header/ prefix

Depending on the sorting, the resources directory may not be listed immediately adjacent to the component

3. With a directory index that exports Header:

src
└── components
    └── Header
        ├── Header.js
        ├── header.module.css
        ├── index.js
        └── logo.png

Benefits

Component and resources are kept together

Sorting doesn't matter

Drawbacks

Conflicting/confusing filenames open in your editor (e.g. index)

Confusing imports and exports, may cause hard-to-diagnose errors

Extra work for every component


问:
SQL Check if value in Table is in range of 2 columns in another Table
I'm trying to check whether a value in TABLE_1 is in a range based on 2 columns in TABLE_2. I am able to accomplish based on the answer provided in question SQL: Checking if a number within range of multiple ranges however when I used this method with a large dataset (~40K rows in both tables) it is maxing out CPU on my SQL server and the query takes an excess of 3 minutes. Is there a way to optimize this query and to limit the CPU that the query uses? If not, is there an alternate query that might be more efficient.

TABLE_1:

```<code>mysql> SELECT * FROM TABLE_1;
+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  1 | Apples  |  2314 |
|  2 | Oranges |  3412 |
|  3 | Oranges |  1296 |
|  4 | Apples  |  2230 |
|  5 | Apples  |  5293 |
|  6 | Oranges |  1994 |
+----+---------+-------+
6 rows in set (0.00 sec)
</code>```

TABLE_2:

```<code>mysql> SELECT * FROM TABLE_2;
+----+---------+-------------+-----------+
| ID | FRUIT   | START_RANGE | END_RANGE |
+----+---------+-------------+-----------+
|  1 | Apples  |        2300 |      2400 |
|  2 | Apples  |        7000 |      8000 |
|  3 | Oranges |        1296 |      1296 |
|  4 | Apples  |        5000 |      6000 |
|  5 | Oranges |        9000 |      9999 |
|  6 | Oranges |        8000 |      9000 |
+----+---------+-------------+-----------+
</code>```

Query:

```<code>SELECT *
FROM TABLE_1
WHERE NOT EXISTS (SELECT 1 FROM TABLE_2
                  WHERE TABLE_1.FRUIT = TABLE_2.FRUIT
                  AND TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE);
</code>```

Output:

```<code>+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  2 | Oranges |  3412 |
|  4 | Apples  |  2230 |
|  6 | Oranges |  1994 |
+----+---------+-------+
3 rows in set (0.00 sec)
</code>```

答:
Besides adding an index on table_2.fruit (as @Gordon already suggested), you might try the following:

```<code>SELECT *
FROM   table_1
WHERE  id NOT IN (SELECT tab1.id
                  FROM   table_1 tab1
                  JOIN   table_2 tab2
                    ON   tab1.fruit = tab2.fruit
                   AND   tab1.count BETWEEN tab2.start_range AND tab2.end_range);
</code>```

This of course supposes that ID if the primary key.

Body:
I'm trying to check whether a value in TABLE_1 is in a range based on 2 columns in TABLE_2. I am able to accomplish based on the answer provided in question SQL: Checking if a number within range of multiple ranges however when I used this method with a large dataset (~40K rows in both tables) it is maxing out CPU on my SQL server and the query takes an excess of 3 minutes. Is there a way to optimize this query and to limit the CPU that the query uses? If not, is there an alternate query that might be more efficient.

TABLE_1:

mysql> SELECT * FROM TABLE_1;
+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  1 | Apples  |  2314 |
|  2 | Oranges |  3412 |
|  3 | Oranges |  1296 |
|  4 | Apples  |  2230 |
|  5 | Apples  |  5293 |
|  6 | Oranges |  1994 |
+----+---------+-------+
6 rows in set (0.00 sec)

TABLE_2:

mysql> SELECT * FROM TABLE_2;
+----+---------+-------------+-----------+
| ID | FRUIT   | START_RANGE | END_RANGE |
+----+---------+-------------+-----------+
|  1 | Apples  |        2300 |      2400 |
|  2 | Apples  |        7000 |      8000 |
|  3 | Oranges |        1296 |      1296 |
|  4 | Apples  |        5000 |      6000 |
|  5 | Oranges |        9000 |      9999 |
|  6 | Oranges |        8000 |      9000 |
+----+---------+-------------+-----------+

Query:

SELECT *
FROM TABLE_1
WHERE NOT EXISTS (SELECT 1 FROM TABLE_2
                  WHERE TABLE_1.FRUIT = TABLE_2.FRUIT
                  AND TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE);

Output:

+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  2 | Oranges |  3412 |
|  4 | Apples  |  2230 |
|  6 | Oranges |  1994 |
+----+---------+-------+
3 rows in set (0.00 sec)

Body:
Besides adding an index on table_2.fruit (as @Gordon already suggested), you might try the following:

SELECT *
FROM   table_1
WHERE  id NOT IN (SELECT tab1.id
                  FROM   table_1 tab1
                  JOIN   table_2 tab2
                    ON   tab1.fruit = tab2.fruit
                   AND   tab1.count BETWEEN tab2.start_range AND tab2.end_range);

This of course supposes that ID if the primary key.


问:
How to get applescript to compare application version against a Variable
I have a line in my applescript that will not read a variable set for the name of an Application

```<code>set ReadAppVersion to value of version of application TheApp
</code>```

but if I use this below it works.

```<code>set ReadAppVersion to value of version of application "OsiriX"
</code>```

For some reason, I cannot read the version of the application if I have it as a variable name.

But if I use this below it works.

```<code>set ReadAppVersion to value of version of application "OsiriX"
</code>```

```<code>on AppOsirixChecks(TheApp)
  delay 1
  tell application "Finder"
    close every window
  end tell
  do shell script "defaults write com.apple.finder AppleShowAllFiles FALSE"
  tell application "Dock"
    tell application "System Events"
      tell process "Dock"
        click UI element "Finder" of list 1
      end tell
    end tell
  end tell
  menu_click({"Finder", "Go", "Applications"})
  delay 1
  set ReadAppName to 0
  set ReadAppVersion to 0
  set TheRow to 2
  tell application "System Events"
    tell process "Finder"
      repeat until ReadAppName is equal to TheApp
        set ReadAppVersion to value of version of application "osirix"
        set ReadAppName to value of text field 1 of UI element 1 of row TheRow of outline 1 of scroll area 1 of splitter group 1 of splitter group 1 of window "Applications"
        set TheRow to TheRow + 1
        if ReadAppVersion doesn't equal AppVersionOsiriX then
          log "TEST FAILURE !: The current version is: " & ReadAppVersion
        end if
      end repeat
    end tell
  end tell
  log ">>>                 Current Application Name is: " & ReadAppName
  log ">>>              Current Application version is: " & ReadAppVersion
  --return TheRow  -- this line does not seem necessary
  tell application "Finder"
    activate
    delay 2
    close every window
    do shell script "defaults write com.apple.finder AppleShowAllFiles TRUE"
  end tell
end AppOsirixChecks
</code>```

<filepath>/upgrade_test_validation_checklist.scpt:10612:10617: execution error: OsiriX got an error: Can’t make «class valL» of version into type specifier. (-1700)

答:
There is no value of version.

To get the version of an application omit value of

```<code>set ReadAppVersion to version of application "OsiriX"
</code>```

and move the line to before the System Events tell block as you need to get the value only once.

Honestly I have no idea what the script is supposed to do. Why do you GUI script a Finder window ?

Body:
I have a line in my applescript that will not read a variable set for the name of an Application

set ReadAppVersion to value of version of application TheApp

but if I use this below it works.

set ReadAppVersion to value of version of application "OsiriX"

For some reason, I cannot read the version of the application if I have it as a variable name.

But if I use this below it works.

set ReadAppVersion to value of version of application "OsiriX"

on AppOsirixChecks(TheApp)
  delay 1
  tell application "Finder"
    close every window
  end tell
  do shell script "defaults write com.apple.finder AppleShowAllFiles FALSE"
  tell application "Dock"
    tell application "System Events"
      tell process "Dock"
        click UI element "Finder" of list 1
      end tell
    end tell
  end tell
  menu_click({"Finder", "Go", "Applications"})
  delay 1
  set ReadAppName to 0
  set ReadAppVersion to 0
  set TheRow to 2
  tell application "System Events"
    tell process "Finder"
      repeat until ReadAppName is equal to TheApp
        set ReadAppVersion to value of version of application "osirix"
        set ReadAppName to value of text field 1 of UI element 1 of row TheRow of outline 1 of scroll area 1 of splitter group 1 of splitter group 1 of window "Applications"
        set TheRow to TheRow + 1
        if ReadAppVersion doesn't equal AppVersionOsiriX then
          log "TEST FAILURE !: The current version is: " & ReadAppVersion
        end if
      end repeat
    end tell
  end tell
  log ">>>                 Current Application Name is: " & ReadAppName
  log ">>>              Current Application version is: " & ReadAppVersion
  --return TheRow  -- this line does not seem necessary
  tell application "Finder"
    activate
    delay 2
    close every window
    do shell script "defaults write com.apple.finder AppleShowAllFiles TRUE"
  end tell
end AppOsirixChecks

<filepath>/upgrade_test_validation_checklist.scpt:10612:10617: execution error: OsiriX got an error: Can’t make «class valL» of version into type specifier. (-1700)

Body:
There is no value of version.

To get the version of an application omit value of

set ReadAppVersion to version of application "OsiriX"

and move the line to before the System Events tell block as you need to get the value only once.

Honestly I have no idea what the script is supposed to do. Why do you GUI script a Finder window ?


问:
Why does the compiler prevent me from using push on a Vec created using collect()?
The following compiles:

```<code>pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>();
    result.push(format!("And all for the want of a {}.", list[0]));
    result.join("\n")
}
</code>```

The following does not (see Playground):

```<code>pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>()
        .push(format!("And all for the want of a {}.", list[0]))
        .join("\n");
    result
}
</code>```

The compiler tells me

error[E0599]: no method named `join` found for type `()` in the current scope
 --> src/lib.rs:9:10
  |
9 |         .join("\n");
  |          ^^^^
```

I get the same type of error if I try to compose just with push.

What I would expect is that collect returns B, aka Vec<String>.  Vec is not (), and Vec of course has the methods I want to include in the list of composed functions.

Why can't I compose these functions? The explanation might include describing the "magic" of terminating the expression after collect() to get the compiler to instantiate the Vec in a way that does not happen when I compose with push etc.

答:
If you read the documentation for Vec::push and look at the signature of the method, you will learn that it does not return the Vec:

```<code>pub fn push(&mut self, value: T)
</code>```

Since there is no explicit return type, the return type is the unit type (). There is no method called join on (). You will need to write your code in multiple lines.

See also:

What is the purpose of the unit type in Rust?

I'd write this more functionally:

```<code>use itertools::Itertools; // 0.8.0

pub fn build_proverb(list: &[&str]) -> String {
    let last = list
        .get(0)
        .map(|d| format!("And all for the want of a {}.", d));

    list.windows(2)
        .map(|d| format!("For want of a {} the {} was lost.", d[0], d[1]))
        .chain(last)
        .join("\n")
}

fn main() {
    println!("{}", build_proverb(&["nail", "shoe"]));
}
</code>```

See also:

What's an idiomatic way to print an iterator separated by spaces in Rust?

Body:
The following compiles:

pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>();
    result.push(format!("And all for the want of a {}.", list[0]));
    result.join("\n")
}

The following does not (see Playground):

pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>()
        .push(format!("And all for the want of a {}.", list[0]))
        .join("\n");
    result
}

The compiler tells me

error[E0599]: no method named `join` found for type `()` in the current scope
 --> src/lib.rs:9:10
  |
9 |         .join("\n");
  |          ^^^^

I get the same type of error if I try to compose just with push.

What I would expect is that collect returns B, aka Vec<String>.  Vec is not (), and Vec of course has the methods I want to include in the list of composed functions.

Why can't I compose these functions? The explanation might include describing the "magic" of terminating the expression after collect() to get the compiler to instantiate the Vec in a way that does not happen when I compose with push etc.

Body:
If you read the documentation for Vec::push and look at the signature of the method, you will learn that it does not return the Vec:

pub fn push(&mut self, value: T)

Since there is no explicit return type, the return type is the unit type (). There is no method called join on (). You will need to write your code in multiple lines.

See also:

What is the purpose of the unit type in Rust?

I'd write this more functionally:

use itertools::Itertools; // 0.8.0

pub fn build_proverb(list: &[&str]) -> String {
    let last = list
        .get(0)
        .map(|d| format!("And all for the want of a {}.", d));

    list.windows(2)
        .map(|d| format!("For want of a {} the {} was lost.", d[0], d[1]))
        .chain(last)
        .join("\n")
}

fn main() {
    println!("{}", build_proverb(&["nail", "shoe"]));
}

See also:

What's an idiomatic way to print an iterator separated by spaces in Rust?


问:
How do you convert epoch time in C#?
How do you convert Unix epoch time into real time in C#? (Epoch beginning 1/1/1970)</p>

答:
The Unix epoch is the number of seconds that have elapsed since January 1, 1970 at midnight UTC time minus the leap seconds. This means that at midnight of January 1, 1970, Unix time was 0. The Unix epoch is also called Unix time, POSIX time, or Unix timestamp.

With .Net Framework 4.6 or higher Use the method DateTimeOffset.ToUnixTimeMilliseconds()  It returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z.

var EPOCH = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
```
<p>It's well documented here DateTimeOffset.ToUnixTimeMilliseconds</p>
<p>To get the <strong>EPOCH</strong> with seconds only you may use</p>
<pre class="lang-cs prettyprint-override"><code> var Epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
</code>```

and convert the Epoch to DateTime with the following method

private DateTime Epoch2UTCNow(int epoch)
{
    return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch);
}
```
<p>But Since</p>
<blockquote>
<p>On systems where the representation of Unix time is as a signed 32-bit number, the representation will end after 231 - 1 seconds which will happen at 3:14:08 on 19 January 2038 UTC. This is called the Year 2038 problem where the 32-bit signed Unix time will overflow.</p>
</blockquote>
<p>I suggest to save it as long not <code>int</code> as <strong>EPOCH_2038_SAFE</strong></p>
<pre class="lang-cs prettyprint-override"><code>long EPOCH_2038_SAFE =
(long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
</code>```

If you are looking for more, use the following with more ticks precision

long EPOCH = DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1,0,0,0,0).Ticks;
```

ContentLicense: CC BY-SA 2.5

Title: How do you convert epoch time in C#?

Body:
The Unix epoch is the number of seconds that have elapsed since January 1, 1970 at midnight UTC time minus the leap seconds. This means that at midnight of January 1, 1970, Unix time was 0. The Unix epoch is also called Unix time, POSIX time, or Unix timestamp.

With .Net Framework 4.6 or higher Use the method DateTimeOffset.ToUnixTimeMilliseconds()  It returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z.

var EPOCH = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

It's well documented here DateTimeOffset.ToUnixTimeMilliseconds

To get the EPOCH with seconds only you may use

 var Epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;

and convert the Epoch to DateTime with the following method

private DateTime Epoch2UTCNow(int epoch)
{
    return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch);
}

But Since

On systems where the representation of Unix time is as a signed 32-bit number, the representation will end after 231 - 1 seconds which will happen at 3:14:08 on 19 January 2038 UTC. This is called the Year 2038 problem where the 32-bit signed Unix time will overflow.

I suggest to save it as long not int as EPOCH_2038_SAFE

long EPOCH_2038_SAFE =
(long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;

If you are looking for more, use the following with more ticks precision

long EPOCH = DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1,0,0,0,0).Ticks;


问:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created
I get the following exception thrown:

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

This is my code:

```<code>if (InvokeRequired)
{
    BeginInvoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);
}
else
    Invoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);
</code>```

I found pages about this topic on this site but I don't know what is wrong.

答:
What about this :

```
public static bool SafeInvoke( this Control control, MethodInvoker method )
{
    if( control != null && ! control.IsDisposed && control.IsHandleCreated && control.FindForm().IsHandleCreated )
    {
        if( control.InvokeRequired )
        {
            control.Invoke( method );
        }
        else
        {
            method();
        }
        return true;
    }
    return false;
}
```

Use it like that :

```
this.label.SafeInvoke(new MethodInvoker( () => { this.label.Text = yourText; }));
```

Body:
I get the following exception thrown:

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

This is my code:

if (InvokeRequired)
{
    BeginInvoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);
}
else
    Invoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);

I found pages about this topic on this site but I don't know what is wrong.

Body:
What about this :

public static bool SafeInvoke( this Control control, MethodInvoker method )
{
    if( control != null && ! control.IsDisposed && control.IsHandleCreated && control.FindForm().IsHandleCreated )
    {
        if( control.InvokeRequired )
        {
            control.Invoke( method );
        }
        else
        {
            method();
        }
        return true;
    }
    return false;
}

Use it like that :

this.label.SafeInvoke(new MethodInvoker( () => { this.label.Text = yourText; }));


问:
Angular 8, I use and old webpack systen (back when there was no angular cli)
I try to upgrade a old grunt webpack based builder (been using since Angular 2 to 7), but now with Angular 8, I cannot upgrade to Ivy.

I have only a cryptic error:

```<code>ERROR in bundle.4c959b202dbdca8012b0.js from UglifyJs
Unexpected token: keyword «const» [./node_modules/@angular/forms/__ivy_ngcc__/fesm5/forms.js:29,0][bundle.4c959b202dbdca8012b0.js:69647,0]
</code>```

My tsconfig.aot.json looks like this:

```<code>{
  "compilerOptions": {
    "skipLibCheck": true,
    "outDir": "build/aot",
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "lib": [
      "es5",
      "es6",
      "dom",
      "es2015.collection",
      "es2015.promise",
      "es2015.core",
      "es2016",
      "es2017"
    ]
  },
  "include": [
    "src/angular/**/*",
    "test/angular-webpack/**/*"
  ],
  "exclude": [
    "node_modules",
    "src/angular/bundle.ts",
    "test/angular-webpack/angular/bundle.ts",
    "test/angular-karma",
    "build/browser"
  ],
  "angularCompilerOptions": {
    "enableIvy": true,
    "annotationsAs": "decorators",
    "preserveWhitespaces": false
  }
}
</code>```

答: actually, it was my problem, i switched to terser-webpack-plugin and now it works.</p>

Body:
I try to upgrade a old grunt webpack based builder (been using since Angular 2 to 7), but now with Angular 8, I cannot upgrade to Ivy.

I have only a cryptic error:

ERROR in bundle.4c959b202dbdca8012b0.js from UglifyJs
Unexpected token: keyword «const» [./node_modules/@angular/forms/__ivy_ngcc__/fesm5/forms.js:29,0][bundle.4c959b202dbdca8012b0.js:69647,0]

My tsconfig.aot.json looks like this:

{
  "compilerOptions": {
    "skipLibCheck": true,
    "outDir": "build/aot",
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "lib": [
      "es5",
      "es6",
      "dom",
      "es2015.collection",
      "es2015.promise",
      "es2015.core",
      "es2016",
      "es2017"
    ]
  },
  "include": [
    "src/angular/**/*",
    "test/angular-webpack/**/*"
  ],
  "exclude": [
    "node_modules",
    "src/angular/bundle.ts",
    "test/angular-webpack/angular/bundle.ts",
    "test/angular-karma",
    "build/browser"
  ],
  "angularCompilerOptions": {
    "enableIvy": true,
    "annotationsAs": "decorators",
    "preserveWhitespaces": false
  }
}


问:
how to sum amount for each user?
I have data like this:

```<code> USER_ID   NUM   num_id
1   47641   800    1
2   47641   100    2
3   47641   250    3
4   70919   200    1
5   70919   200    2
6   70919   200    3
7   70919   200    4
</code>```

...

I have no idea what to try, result that i want is this:

```<code> USER_ID   NUM   num_id
1   47641   800    1
2   47641   100    2
3   47641   100    3
4   70919   200    1
5   70919   200    2
6   70919   200    3
7   70919   200    4
...
</code>```

so if for each user, sum of num < 1000 than all num must be same, but if sum of num for each user > 1000 for example for 47641 user we have 800 100 and 250 so we have to sum 800 and 100 and from 250 we need only 100 because 800+100+100=1000 so for num_id=3 we need only 100

I have not written some code...

I only want some ways what to try.
hope you will get idea of problem

答:
You seem to want the amounts for the first n records that sum to 1000.  You want a cumulative sum:

```<code>select t.*,
       (case when running_sum <= 1000 then num
             when running_sum - num < 1000 then 1000 - (running_sum - num)
             else 0
         end) as new_num
from (select t.*, sum(num) over (partition by user_id order by num_id) as running_sum
      from t
     ) t;
</code>```

Title: how to sum amount for each user?

Body:
I have data like this:

 USER_ID   NUM   num_id
1   47641   800    1
2   47641   100    2
3   47641   250    3
4   70919   200    1
5   70919   200    2
6   70919   200    3
7   70919   200    4

...

I have no idea what to try, result that i want is this:

 USER_ID   NUM   num_id
1   47641   800    1
2   47641   100    2
3   47641   100    3
4   70919   200    1
5   70919   200    2
6   70919   200    3
7   70919   200    4
...

so if for each user, sum of num < 1000 than all num must be same, but if sum of num for each user > 1000 for example for 47641 user we have 800 100 and 250 so we have to sum 800 and 100 and from 250 we need only 100 because 800+100+100=1000 so for num_id=3 we need only 100

I have not written some code...

I only want some ways what to try.
hope you will get idea of problem

Body:
You seem to want the amounts for the first n records that sum to 1000.  You want a cumulative sum:

select t.*,
       (case when running_sum <= 1000 then num
             when running_sum - num < 1000 then 1000 - (running_sum - num)
             else 0
         end) as new_num
from (select t.*, sum(num) over (partition by user_id order by num_id) as running_sum
      from t
     ) t;


问:
Most elegant and fastest way to remove all leading zeroes in perl string
I wrote rmlz function for trimming all leading zeroes from string.

```<code># remove all leading zeroes from string
use strict;
use warnings;
use feature 'say';

sub rmlz {
  my ( $str ) = @_;
  if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
  }
  return $str;
}

say rmlz('0050625'); # must return 50625
</code>```

Is there most elegant and clear way to rewrite this code ? Or regexp+length+substr is best option ?

答:
A simple substitution will remove leading zeros:

```<code>$str =~ s/^0+(?=[0-9])//;
</code>```

This removes as many zeros as possible while still leaving at least one digit.
The latter constraint is needed to prevent "0" becoming "".

Body:
I wrote rmlz function for trimming all leading zeroes from string.

# remove all leading zeroes from string
use strict;
use warnings;
use feature 'say';

sub rmlz {
  my ( $str ) = @_;
  if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
  }
  return $str;
}

say rmlz('0050625'); # must return 50625

Is there most elegant and clear way to rewrite this code ? Or regexp+length+substr is best option ?

Body:
A simple substitution will remove leading zeros:

$str =~ s/^0+(?=[0-9])//;

This removes as many zeros as possible while still leaving at least one digit.
The latter constraint is needed to prevent "0" becoming "".


问:
Building SQL "where in" statement from list of strings in one line?
I have a List(Of String) which corresponds to "types" on our database table.

We are using the DB2 ADO.NET provider and my final query needs to look something like this:

```<code>select * from table where type in (@type1, @type2, @type3, @type4)
</code>```

In the past, I've built the list of query parameters / host variables using a ForEach loop, but I would really like to figure out a way to build them in one line. Of course, I can join all of the strings, but adding the "@" and the incrementing digit is giving me headaches.

Anyone have any ideas  on how to do this?

答:
A simple way could be to use :</p>

```<code>"'" + string.Join("','", myListOfNames) + "'")
</code>```

Body:
I have a List(Of String) which corresponds to "types" on our database table.

We are using the DB2 ADO.NET provider and my final query needs to look something like this:

select * from table where type in (@type1, @type2, @type3, @type4)

In the past, I've built the list of query parameters / host variables using a ForEach loop, but I would really like to figure out a way to build them in one line. Of course, I can join all of the strings, but adding the "@" and the incrementing digit is giving me headaches.

Anyone have any ideas  on how to do this?

Body:
A simple way could be to use :

"'" + string.Join("','", myListOfNames) + "'")


问:
How to convert encoding of text file (which contains text of language other than English) from "UTF-16 LE" to "UTF-8" in Python?
I have few text files which contain text in Hindi language in a folder. But those text files are in UTF-16 LE Encoding. I want to change the encoding to UTF-8 without changing text in it. How can I do that?

I wrote two python files but none of them are working proprely. When I run any of them, along with changing the encoding, they clear the file content. These are code in my Python files:

File 1:

```<code>import os
for root, dirs, files in os.walk("."):
    for filename in files:
        #print(filename[-4:])
        if(filename[-3:] == "txt"):
            f= open(filename,"w+")
            x = f.read()
            print(x)
            f.close()
            f1= open(filename, "w+", encoding="utf-8")
            f1.write(x)
            f1.close()
</code>```

File 2:

```<code>import codecs
BLOCKSIZE = 1048576
with codecs.open("ee.txt", "r", "utf-16-le") as sourceFile:
    with codecs.open("ee.txt", "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            print(contents)
            if not contents:
                break
            targetFile.write(contents)
</code>```

答:
Before to explain you what it is wrong two useful tips:

I think you should remove the print. It will just confuse you, and it depends on the operating system and environment what encoding it will print.

Try with a very short file (few character) and check the input and output of both files either as text and as bytes.

Now the solution:

On the first example: you should open the first file as read (r).

On second example: you open the same file, first step to read but before you read the file you open it to write, so you truncate the file, and you will have no characters to read.

Use a ee.txt.tmp file to write, and at the end, if there are no error, you can move the tmp file removing the .tmp prefix.

In general: never read and write on the same file.

Body:
I have few text files which contain text in Hindi language in a folder. But those text files are in UTF-16 LE Encoding. I want to change the encoding to UTF-8 without changing text in it. How can I do that?

I wrote two python files but none of them are working proprely. When I run any of them, along with changing the encoding, they clear the file content. These are code in my Python files:

File 1:

import os
for root, dirs, files in os.walk("."):
    for filename in files:
        #print(filename[-4:])
        if(filename[-3:] == "txt"):
            f= open(filename,"w+")
            x = f.read()
            print(x)
            f.close()
            f1= open(filename, "w+", encoding="utf-8")
            f1.write(x)
            f1.close()

File 2:

import codecs
BLOCKSIZE = 1048576
with codecs.open("ee.txt", "r", "utf-16-le") as sourceFile:
    with codecs.open("ee.txt", "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            print(contents)
            if not contents:
                break
            targetFile.write(contents)


问:
Cannot close stream until all bytes are written c#
This is my first c# attempt in a while, but I have gotten myself to this point and maybe I think I need some expert eyes on it.

I keep getting the error mentioned in the title. I am guessing there is something obvious I am missing?

```<code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace API_Call
{
    class Program
    {
        static void Main(string[] args)
        {
            var watch = new Stopwatch();
            HttpWebRequest request = HttpWebRequest.Create("http://bk-pim/Perfion/GetData.asmx") as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.Headers.Add("SOAPAction","http://perfion.com/ExecuteQuery");
            //FileInfo info = new FileInfo(@"C:\Users\dcoats\Desktop\mytestfile.txt");
            //long size = info.Length;
            //request.ContentLength = size;

            using (var stream = request.GetRequestStream())
            using (var writer = new StreamWriter(stream))
            {
                var body = WebUtility.HtmlEncode(File.ReadAllText(@"C:\Users\dcoats\Desktop\mytestfile.txt"));
                body = "<?xml version=\"1.0\" encoding=\"utf - 8\"?>< soap:Envelope xmlns:soap = \"http://schemas.xmlsoap.org/soap/envelope/\" xmlns: xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xmlns: xsd = \"http://www.w3.org/2001/XMLSchema\" >< soap:Body >< ExecuteQueryResponse xmlns = \"http://perfion.com/\" >< ExecuteQueryResult >" + body + "</ExecuteQueryResult></ ExecuteQueryResponse ></ soap:Body ></ soap:Envelope > ";

            }

            watch.Start();
            var response = request.GetResponse(); //bombs here
            watch.Stop();
            response.GetResponseStream();

            Console.WriteLine();
            Console.ReadLine();
            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.ReadLine();
        }
    }
}
</code>```

答:
You asked for a better way to interact with a webservice:

Right click REFERENCES in SOLUTION EXPLORER

Choose ADD SERVICE REFERENCE

Enter the URL where your service is located - example http://bk-pim/Perfion/GetData.asmx or http://www.dneonline.com/calculator.asmx

Choose a namespace/set other options

Click OK

Create a client (I couldn't use your webservice, so this answer now switches to using DNEOnline's calculator, with a chosen namespace of "Calc" ):

Calc.CalculatorSoapClient sc = new Calc.CalculatorSoapClient();

Call methods on the client:

int result = sc.Add(1,2);

That's it - no sockets, no building XML etc - the service reference creates a set of objects and classes that do all of that

Body:
This is my first c# attempt in a while, but I have gotten myself to this point and maybe I think I need some expert eyes on it.

I keep getting the error mentioned in the title. I am guessing there is something obvious I am missing?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace API_Call
{
    class Program
    {
        static void Main(string[] args)
        {
            var watch = new Stopwatch();
            HttpWebRequest request = HttpWebRequest.Create("http://bk-pim/Perfion/GetData.asmx") as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.Headers.Add("SOAPAction","http://perfion.com/ExecuteQuery");
            //FileInfo info = new FileInfo(@"C:\Users\dcoats\Desktop\mytestfile.txt");
            //long size = info.Length;
            //request.ContentLength = size;

            using (var stream = request.GetRequestStream())
            using (var writer = new StreamWriter(stream))
            {
                var body = WebUtility.HtmlEncode(File.ReadAllText(@"C:\Users\dcoats\Desktop\mytestfile.txt"));
                body = "<?xml version=\"1.0\" encoding=\"utf - 8\"?>< soap:Envelope xmlns:soap = \"http://schemas.xmlsoap.org/soap/envelope/\" xmlns: xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xmlns: xsd = \"http://www.w3.org/2001/XMLSchema\" >< soap:Body >< ExecuteQueryResponse xmlns = \"http://perfion.com/\" >< ExecuteQueryResult >" + body + "</ExecuteQueryResult></ ExecuteQueryResponse ></ soap:Body ></ soap:Envelope > ";

            }

            watch.Start();
            var response = request.GetResponse(); //bombs here
            watch.Stop();
            response.GetResponseStream();

            Console.WriteLine();
            Console.ReadLine();
            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.ReadLine();
        }
    }
}


问:
Convert serialize() to array of objects to post to controller
I am using Datatables. I have a table with multiple inputs and I want to post array of objects to controller via ajax.

```<code>var data = table.$('input, select').serialize();
</code>```

The result:

```<code>row-1-location=123&row-1-lot=231545&row-2-location=2323&row-2-lot=5523&row-3-location=23232&row-3-lot=23235
</code>```

I am assuming I need to split the string at every second '&', then split again.
The question is, is this the only way to convert it to array of objects?

The result I want is array of objects:

```<code>[{location : 123, lot: 231545}, {location: 2323, lot: 5523}......]
</code>```

HTML:

```<code><tbody>
    <tr role="row" class="odd">
        <td><input type="text" id="row-5-location" name="row-5-location" value=""></td>
        <td><input type="text" id="row-5-lot" name="row-5-lot" value=""></td>
    </tr>
    <tr role="row" class="even">
        <td><input type="text" id="row-6-location" name="row-5-location" value=""></td>
        <td><input type="text" id="row-6-lot" name="row-5-lot" value=""></td>
    </tr>
</tbody>
</code>```

Thanks!

答:
To create the array of objects you require it would make more sense to just build the structure from the DOM directly instead of serialising it, then picking apart the resulting string.

To achieve this you can select the parent tr elements then use map() to build the objects. The only HTML change which would make it simpler still would be to put common classes on the input elements. Something like this:

var arr = $('table tr').map(function() {
  var $tr = $(this);
  return {
    location: $tr.find('.location').val(),
    lot: $tr.find('.lot').val()
  }
}).get();

console.log(arr);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr role="row" class="odd">
      <td><input type="text" class="location" id="row-5-location" name="row-5-location" value="123"></td>
      <td><input type="text" class="lot" id="row-5-lot" name="row-5-lot" value="231545"></td>
    </tr>
    <tr role="row" class="even">
      <td><input type="text" class="location" id="row-6-location" name="row-5-location" value="2323"></td>
      <td><input type="text" class="lot" id="row-6-lot" name="row-5-lot" value="5523"></td>
    </tr>
  </tbody>
</table></code>```

Body:
I am using Datatables. I have a table with multiple inputs and I want to post array of objects to controller via ajax.

var data = table.$('input, select').serialize();

The result:

row-1-location=123&row-1-lot=231545&row-2-location=2323&row-2-lot=5523&row-3-location=23232&row-3-lot=23235

I am assuming I need to split the string at every second '&', then split again.
The question is, is this the only way to convert it to array of objects?

The result I want is array of objects:

[{location : 123, lot: 231545}, {location: 2323, lot: 5523}......]

HTML:

        <input type="text" id="row-5-location" name="row-5-location" value="">
        <input type="text" id="row-5-lot" name="row-5-lot" value="">

        <input type="text" id="row-6-location" name="row-5-location" value="">
        <input type="text" id="row-6-lot" name="row-5-lot" value="">

Thanks!

Body:
To create the array of objects you require it would make more sense to just build the structure from the DOM directly instead of serialising it, then picking apart the resulting string.

To achieve this you can select the parent tr elements then use map() to build the objects. The only HTML change which would make it simpler still would be to put common classes on the input elements. Something like this:

var arr = $('table tr').map(function() {
  var $tr = $(this);
  return {
    location: $tr.find('.location').val(),
    lot: $tr.find('.lot').val()
  }
}).get();

console.log(arr);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr role="row" class="odd">
      <td><input type="text" class="location" id="row-5-location" name="row-5-location" value="123"></td>
      <td><input type="text" class="lot" id="row-5-lot" name="row-5-lot" value="231545"></td>
    </tr>
    <tr role="row" class="even">
      <td><input type="text" class="location" id="row-6-location" name="row-5-location" value="2323"></td>
      <td><input type="text" class="lot" id="row-6-lot" name="row-5-lot" value="5523"></td>
    </tr>
  </tbody>
</table>


问:
Returning a file in a HTTP response
I'm very new to Node JS and would appreciate any help/advice.

Using NodeJS, I have created a local server run this link (it's simply a hello world)

From there, I have used this stack overflow snippet , which responds by the request type made.

I'd like to take this a step further, and when the reponse.method is get/post/etc. - I'd like the response to be a file.

In other words, I'd like to return a file from a HTTP response.

In theory, something along the lines of:

```<code>if(request.method == "GET")
{
    response.end("C:\[file path]\test.txt");
}
</code>```

I've tried simply copying/pasting the file directory after response.end('file directory') but was not opening the file that I wanted it to.

```<code>const http = require("http");
const hostname = '127.0.0.1';
const port = 8091;

var server = http.createServer ( function(request,response){

response.writeHead(200,{"Content-Type":"text\plain"});
if(request.method == "GET")
    {
        response.end("received GET request.")
    }
else if(request.method == "POST")
    {
        response.end("received POST request.");
    }
else
    {
        response.end("Undefined request .");
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
</code>```

答:
You can send file data by first reading the file using the fs module's readFile method, and then sending it via res.write() followed by res.end(), or just res.end() as you have done. Here's an example:

```<code>var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function(req, res) {
    if (req.method === 'GET' && req.url === '/') {
        fs.readFile('./index.html', function(err, data) {
            if (err){
                throw err;
            }
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(data);
            return;
        });
    }
}).listen(3000);
</code>```

I answered a similar question to this here: https://stackoverflow.com/a/56285824/4882724

Title: Returning a file in a HTTP response

Body:
I'm very new to Node JS and would appreciate any help/advice.

Using NodeJS, I have created a local server run this link (it's simply a hello world)

From there, I have used this stack overflow snippet , which responds by the request type made.

I'd like to take this a step further, and when the reponse.method is get/post/etc. - I'd like the response to be a file.

In other words, I'd like to return a file from a HTTP response.

In theory, something along the lines of:

if(request.method == "GET")
{
    response.end("C:\[file path]\test.txt");
}

I've tried simply copying/pasting the file directory after response.end('file directory') but was not opening the file that I wanted it to.

const http = require("http");
const hostname = '127.0.0.1';
const port = 8091;

var server = http.createServer ( function(request,response){

response.writeHead(200,{"Content-Type":"text\plain"});
if(request.method == "GET")
    {
        response.end("received GET request.")
    }
else if(request.method == "POST")
    {
        response.end("received POST request.");
    }
else
    {
        response.end("Undefined request .");
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

Body:
You can send file data by first reading the file using the fs module's readFile method, and then sending it via res.write() followed by res.end(), or just res.end() as you have done. Here's an example:

var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function(req, res) {
    if (req.method === 'GET' && req.url === '/') {
        fs.readFile('./index.html', function(err, data) {
            if (err){
                throw err;
            }
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(data);
            return;
        });
    }
}).listen(3000);

I answered a similar question to this here: https://stackoverflow.com/a/56285824/4882724


问:
ADB: missing port in specification
I've recently upgraded to Android SDK Platform-Tools version 28.0.2. Version information:

```<code>$ adb version
Android Debug Bridge version 1.0.40
Version 28.0.2-5303910
</code>```

When using the adb connect command I now get the following error:

```<code>$ adb connect 192.168.1.20
missing port in specification: tcp:192.168.1.20
</code>```

ADB previously connected to devices using TCP port 5555 by default. I am still able to connect to my device by specifying this port number:

```<code>$ adb connect 192.168.1.20:5555
connected to 192.168.1.20:5555
</code>```

However, this is a minor inconvenience to me as I'm used to typing in just the IP address. Is there any way of telling this version of ADB to use TCP port 5555 by default?

答:
Just flagged this on an AndroidThings device,

had to swap

```<code> adb connect Android.local
</code>```

with

```<code> adb connect Android.local:5555
</code>```

Title: ADB: missing port in specification

Body:
I've recently upgraded to Android SDK Platform-Tools version 28.0.2. Version information:

$ adb version
Android Debug Bridge version 1.0.40
Version 28.0.2-5303910

When using the adb connect command I now get the following error:

$ adb connect 192.168.1.20
missing port in specification: tcp:192.168.1.20

ADB previously connected to devices using TCP port 5555 by default. I am still able to connect to my device by specifying this port number:

$ adb connect 192.168.1.20:5555
connected to 192.168.1.20:5555

However, this is a minor inconvenience to me as I'm used to typing in just the IP address. Is there any way of telling this version of ADB to use TCP port 5555 by default?

Body:
Just flagged this on an AndroidThings device,

had to swap

 adb connect Android.local

with

 adb connect Android.local:5555


问:
Execute method after all promises inside of a given method resolved
In a Vue.js component, I have some methods that use axios to call an API.

In different cases, I need to execute some code once the call in this method has resolved, but I don't want to add a bunch of if statements in the .then() chained to the axios call.

```<code>methods: {
  callApi() {
    axios.get('/api')
     .then(() => {
       // call has resolved, request is done
     })
  },
  firstMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something
  },
  secondMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something else
  }
}
</code>```

As you can see, firstMethod and secondMethod both rely on callApi but are supposed to do a different thing once the request is done. I prefer to split this logic in different functions instead of using conditions in the callApi method.
Is there a way to do this without having to add this logic inside of the
callApi ?

答:
Have callApi return the promise chain, then use and return that in firstMethod and secondMethod.

```<code>methods: {
  callApi() {
    return axios.get('/api')
     .then(() => {
       // call has resolved, request is done
     })
  },
  firstMethod() {
    return this.callApi()
    .then(() => {
      // Need to wait for the call to resolve
      // Do something
    })
  },
  secondMethod() {
    return this.callApi()
    .then(() => {
      // Need to wait for the call to resolve
      // Do something else
    })
  }
}
</code>```

Whatever calls callApi, firstMethod, or secondMethod should check for failure and handle/report it.

Your original code was breaking one of the rules of promises: The function should always either return the chain, or handle rejection. (And yes, that's or [99.9% of the time], not and.)

Body:
In a Vue.js component, I have some methods that use axios to call an API.

In different cases, I need to execute some code once the call in this method has resolved, but I don't want to add a bunch of if statements in the .then() chained to the axios call.

methods: {
  callApi() {
    axios.get('/api')
     .then(() => {
       // call has resolved, request is done
     })
  },
  firstMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something
  },
  secondMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something else
  }
}

As you can see, firstMethod and secondMethod both rely on callApi but are supposed to do a different thing once the request is done. I prefer to split this logic in different functions instead of using conditions in the callApi method.
Is there a way to do this without having to add this logic inside of the
callApi ?

Body:
Have callApi return the promise chain, then use and return that in firstMethod and secondMethod.

methods: {
  callApi() {
    return axios.get('/api')
     .then(() => {
       // call has resolved, request is done
     })
  },
  firstMethod() {
    return this.callApi()
    .then(() => {
      // Need to wait for the call to resolve
      // Do something
    })
  },
  secondMethod() {
    return this.callApi()
    .then(() => {
      // Need to wait for the call to resolve
      // Do something else
    })
  }
}

Whatever calls callApi, firstMethod, or secondMethod should check for failure and handle/report it.

Your original code was breaking one of the rules of promises: The function should always either return the chain, or handle rejection. (And yes, that's or [99.9% of the time], not and.)


问:
PyCharm asks for python interpreter every time project is loaded
Rather frustratingly, every time I load up an existing project or create a new one - it complains there is no interpreter selected and I have to provide the path to it.

There is nothing unusual about my python installation, it's sat in C:/Python27/ as you would expect. It always used to work, but the last few weeks something has changed.

I'm running Win7. PATH system variable points to C:/Python27/ as it ought to.

If I crack open commandline, the python command opens as it ought to.

Any ideas?

答: On Mac: File > Preferences for New Projects.


问:
Filter top n largest groups in data.frame
For the example data:

```<code>set.seed(2222)
example_data <- data.frame(col1 = 1:15,
                           col2 = 16:30,
                           group = sample(1:3, 15, replace = TRUE))

   col1 col2 group
1     1   16     2
2     2   17     1
3     3   18     3
4     4   19     2
5     5   20     3
6     6   21     1
7     7   22     3
8     8   23     1
9     9   24     3
10   10   25     1
11   11   26     2
12   12   27     2
13   13   28     2
14   14   29     3
15   15   30     3
</code>```

I want to find the top n groups with the most number of records.

Let's say I want to get the top 2 groups with the most number of records. In the data, this would be group 3 and 2:

```<code>example_data %>%
  group_by(group) %>%
  summarise(n = n())

# A tibble: 3 x 2
  group     n
  <int> <int>
1     1     4
2     2     5
3     3     6
</code>```

The expected output is:

```<code>   col1 col2 group
1     1   16     2
2     3   18     3
3     4   19     2
4     5   20     3
5     7   22     3
6     9   24     3
7    11   26     2
8    12   27     2
9    13   28     2
10   14   29     3
11   15   30     3
</code>```

Body:
For the example data:

set.seed(2222)
example_data <- data.frame(col1 = 1:15,
                           col2 = 16:30,
                           group = sample(1:3, 15, replace = TRUE))

   col1 col2 group
1     1   16     2
2     2   17     1
3     3   18     3
4     4   19     2
5     5   20     3
6     6   21     1
7     7   22     3
8     8   23     1
9     9   24     3
10   10   25     1
11   11   26     2
12   12   27     2
13   13   28     2
14   14   29     3
15   15   30     3

I want to find the top n groups with the most number of records.

Let's say I want to get the top 2 groups with the most number of records. In the data, this would be group 3 and 2:

example_data %>%
  group_by(group) %>%
  summarise(n = n())

# A tibble: 3 x 2
  group     n
  <int> <int>
1     1     4
2     2     5
3     3     6

The expected output is:

   col1 col2 group
1     1   16     2
2     3   18     3
3     4   19     2
4     5   20     3
5     7   22     3
6     9   24     3
7    11   26     2
8    12   27     2
9    13   28     2
10   14   29     3
11   15   30     3

Body:
Yet another solution (similar to @OTStats):

library(dplyr)

example_data %>%
  inner_join(
    count(., group) %>% top_n(2, n) %>% dplyr::select(group)
    )

#    col1 col2 group
# 1     1   16     2
# 2     3   18     3
# 3     4   19     2
# 4     5   20     3
# 5     7   22     3
# 6     9   24     3
# 7    11   26     2
# 8    12   27     2
# 9    13   28     2
# 10   14   29     3
# 11   15   30     3


问:
How to create a circular Alphabet in Python so that the letter after z is a and the letter before a is z
Is there a Function in Python to easily create a circular Alphabet, so that the letter after z is a and the letter before a is z?

I tried something with chr() and .join(Alphabet), but that didn't worked because i got the error message an integer is required (got type str).

for character in word:
    if chr(Alphabet[Alphabet.find(character)) >= "z":
        new_Alphabet = Alphabet.join(Alphabet)
    elif chr(Alphabet[Alphabet.find(character)) <= "a":
        new_Alphabet = Alphabet.join(Alphabet[:-1])
```

答:
Alternative (old fashion?) solution:</p>

```<code>def cycle_letter(ch,up=True):
  upper = 'A' <= ch <= 'Z'
  ch = ch.lower()
  letters = 'abcdefghijklmnopqrstuvwxyz'
  pos = letters.find(ch)
  if pos < 0: return ch
  length = len(letters)
  pos += 1 if up else length-1
  ans = letters[pos%length]
  if upper: ans = ans.upper()
  return ans

################################################################################

def cycle_string(s,up=True):
  return ''.join(cycle_letter(ch,up) for ch in s)

################################################################################

if __name__ == '__main__':    #Test
  s = cycle_string('Hello, World!')
  print(s)
  s = cycle_string(s,False)
  print(s)
</code>```

Body:
Alternative (old fashion?) solution:

def cycle_letter(ch,up=True):
  upper = 'A' <= ch <= 'Z'
  ch = ch.lower()
  letters = 'abcdefghijklmnopqrstuvwxyz'
  pos = letters.find(ch)
  if pos < 0: return ch
  length = len(letters)
  pos += 1 if up else length-1
  ans = letters[pos%length]
  if upper: ans = ans.upper()
  return ans

################################################################################

def cycle_string(s,up=True):
  return ''.join(cycle_letter(ch,up) for ch in s)

################################################################################

if __name__ == '__main__':    #Test
  s = cycle_string('Hello, World!')
  print(s)
  s = cycle_string(s,False)
  print(s)


问:
Fill missing dates-hours on dataframe with empty values
I have a dataframe with data from several supermarkets, with the following structure:

```<code>       MARKET_ID  SECTOR  DATE        HOUR      REVENUE  COUPONS  ITEMS
328    21         Fruits  2019-02-24  15:00:00  808.60   19       29
329    21         Fruits  2019-02-24  22:00:00  267.54   8        8
330    21         Fruits  2019-02-26  17:00:00  350.89   10       14
331    21         Dairy   2019-02-26  07:00:00  72.89    2        2
332    21         Dairy   2019-03-03  15:00:00  122.69   4        4
</code>```

Some notes:

[HOUR] goes from "00:00:00" to "23:00:00" (24 entries per date).

My "composite key" would be a combination of [MARKET_ID],
[SECTOR], [DATE] and [HOUR], but I do not use MultiIndex in that dataframe.

Hours with no sales (revenue, coupons or items) do not appear as
lines in the data I receive.

I would like to fill those missing lines in my dataframe, such as below:

```<code>       MARKET_ID  SECTOR  DATE        HOUR      REVENUE  COUPONS  ITEMS
328    21         Fruits  2019-02-24  14:00:00  0        0        0
</code>```

While searching I came across solutions using reindex or grouper, but I'm not sure if those will fit my problem. Any suggestions?

Thanks for the attention.

答:
Create a combined column for date and time:

```<code>df['DATETIME'] = pd.to_datetime(df['DATE'] + ' ' + df['HOUR'])
</code>```

Drop redundant information:

```<code>df.drop(['DATE','HOUR'], inplace=True, axis = 1)
</code>```

Now group by MARKET_ID and SECTOR and use resample with Hours option and fill missing values with 0:

```<code>df.groupby(['MARKET_ID', 'SECTOR']).\
    apply(lambda x : x.set_index('DATETIME').resample('H').mean().fillna(0))
</code>```

Body:
I have a dataframe with data from several supermarkets, with the following structure:

       MARKET_ID  SECTOR  DATE        HOUR      REVENUE  COUPONS  ITEMS
328    21         Fruits  2019-02-24  15:00:00  808.60   19       29
329    21         Fruits  2019-02-24  22:00:00  267.54   8        8
330    21         Fruits  2019-02-26  17:00:00  350.89   10       14
331    21         Dairy   2019-02-26  07:00:00  72.89    2        2
332    21         Dairy   2019-03-03  15:00:00  122.69   4        4

Some notes:

[HOUR] goes from "00:00:00" to "23:00:00" (24 entries per date).

My "composite key" would be a combination of [MARKET_ID],
[SECTOR], [DATE] and [HOUR], but I do not use MultiIndex in that dataframe.

Hours with no sales (revenue, coupons or items) do not appear as
lines in the data I receive.

I would like to fill those missing lines in my dataframe, such as below:

       MARKET_ID  SECTOR  DATE        HOUR      REVENUE  COUPONS  ITEMS
328    21         Fruits  2019-02-24  14:00:00  0        0        0

While searching I came across solutions using reindex or grouper, but I'm not sure if those will fit my problem. Any suggestions?

Thanks for the attention.

Body:
Create a combined column for date and time:

df['DATETIME'] = pd.to_datetime(df['DATE'] + ' ' + df['HOUR'])

Drop redundant information:

df.drop(['DATE','HOUR'], inplace=True, axis = 1)

Now group by MARKET_ID and SECTOR and use resample with Hours option and fill missing values with 0:

df.groupby(['MARKET_ID', 'SECTOR']).\
    apply(lambda x : x.set_index('DATETIME').resample('H').mean().fillna(0))