问:
Loop though JSON images from Tumblr API using Gatsby
I'm trying to connect to use Tumblr's API to create a image array using a Graphql request.

```<code>import React from 'react';
import { graphql } from 'gatsby';
import "../styles/index.scss";

const Portfolio = ( props ) => {
  const name=props.data.allTumblrPost.edges[0].node.blog_name;
  const image=props.data.allTumblrPost.edges;
  const test=props.data.allTumblrPost.edges[6].node.photos[0].alt_sizes[0].url;

    return (
        <div>
      <h1>{name}'s Portfolio</h1>

      <img src={test} />

      {image.map(({ node }, i) => {
          return (
            <div>
                <img src={node.photos} alt={`image_${node.photos}`} />
            </div>
          )
        })}
        </div>
    )
}

export default Portfolio;

export const pageQuery = graphql`
    query PostQuery {
    allTumblrPost {
      edges {
        node {
          blog_name
          post_url
          photos {
            caption
            alt_sizes {
              url
            }
          }
          id
          type
          date
        }
      }
    }
  }
`
</code>```

So far, I have managed to output one single test image as shown above.
I can change the edge array value and everything works fine.
My question is how do I loop though the edge array to output all the images and pipe that data through photos[0].alt_sizes[0].url?

答:
I suggest reading up on Array.prototype.map(). Arguably the MDN docs aren't the most beginner-friendly, so I'll also recommend Tania Rascia's Examples of Map, Filter and Reduce in JavaScript.

As for your question:

import React from "react";
import { graphql } from "gatsby";
import "../styles/index.scss";

const Portfolio = (props) => {
  /**
   * Note: you will probably also want to map through the different posts.
   * Optimally this should be done in the parent component, and you'll pass
   * the `post` down as a prop.
   */
  const post = props.data.allTumblrPost.edges[0]; // only handle the first post
  const { blog_name, photos } = post.node; // destructure the photos and name

  return (

{blog_name}'s Portfolio

      {
        // this is where you map through the post's photos
        photos.map((photo, index) => (

        ))
      }

  );
};

export default Portfolio;

export const pageQuery = graphql`
  query PostQuery {
    allTumblrPost {
      edges {
        node {
          blog_name
          post_url
          photos {
            caption
            alt_sizes {
              url
            }
          }
          id
          type
          date
        }
      }
    }
  }
`;
```

Body:
I'm trying to connect to use Tumblr's API to create a image array using a Graphql request.

import React from 'react';
import { graphql } from 'gatsby';
import "../styles/index.scss";

const Portfolio = ( props ) => {
  const name=props.data.allTumblrPost.edges[0].node.blog_name;
  const image=props.data.allTumblrPost.edges;
  const test=props.data.allTumblrPost.edges[6].node.photos[0].alt_sizes[0].url;

    return (

{name}'s Portfolio

      {image.map(({ node }, i) => {
          return (

                <img src={node.photos} alt={`image_${node.photos}`} />

          )
        })}

    )
}

export default Portfolio;

export const pageQuery = graphql`
    query PostQuery {
    allTumblrPost {
      edges {
        node {
          blog_name
          post_url
          photos {
            caption
            alt_sizes {
              url
            }
          }
          id
          type
          date
        }
      }
    }
  }
`

So far, I have managed to output one single test image as shown above.
I can change the edge array value and everything works fine.
My question is how do I loop though the edge array to output all the images and pipe that data through photos[0].alt_sizes[0].url?

Body:
I suggest reading up on Array.prototype.map(). Arguably the MDN docs aren't the most beginner-friendly, so I'll also recommend Tania Rascia's Examples of Map, Filter and Reduce in JavaScript.

As for your question:

import React from "react";
import { graphql } from "gatsby";
import "../styles/index.scss";

const Portfolio = (props) => {
  /**
   * Note: you will probably also want to map through the different posts.
   * Optimally this should be done in the parent component, and you'll pass
   * the `post` down as a prop.
   */
  const post = props.data.allTumblrPost.edges[0]; // only handle the first post
  const { blog_name, photos } = post.node; // destructure the photos and name

  return (
    <div>
      <h1>{blog_name}'s Portfolio</h1>

      {
        // this is where you map through the post's photos
        photos.map((photo, index) => (
          <img key={index} src={photo.alt_sizes[0].url} alt={photo.caption} />
        ))
      }
    </div>
  );
};

export default Portfolio;

export const pageQuery = graphql`
  query PostQuery {
    allTumblrPost {
      edges {
        node {
          blog_name
          post_url
          photos {
            caption
            alt_sizes {
              url
            }
          }
          id
          type
          date
        }
      }
    }
  }
`;


来源: stackexchange

问:
send forward slash "\" in http post
hello i am using a very basic html form :

```<code><!DOCTYPE html>
<html>
<body>

<h1>The form method="post" attribute</h1>

<form action="http://123.123.123.123" method="post" target="_blank">
<label for="key1">First name:</label>
  <input type="text" id="key1" name="key1"><br><br>
  <label for="key2">Last name:</label>
  <input type="text" id="key2" name="key2"><br><br>

    <label for="key3">First name:</label>
  <input type="text" id="key3" name="key3"><br><br>
  <label for="key4">Last name:</label>
 <input type="text" id="key4" name="key4"><br><br>

  <input type="submit" value="Submit">
</form>
</body>
</html>
</code>```

i am using this form to receive http post request to my python http server, the problem is ,in the last field , i need the the 1\ in the request that i receive on the server to save it into a variable and use it in os.path.join, but when i try to send request containing "\" i receive : 1%5C instead of, how can i send \
thanks in advance

答:
%5C is a \ in the standard form encoding.

You need to decode it on the server. You could do it manually, but you should be using an HTTP server library that does it for you automatically. e.g. Django.

ContentLicense: CC BY-SA 4.0

Title: send forward slash "\" in http post

Body:
hello i am using a very basic html form :

<!DOCTYPE html>

The form method="post" attribute

<form action="http://123.123.123.123" method="post" target="_blank">
First name:
  <input type="text" id="key1" name="key1">

  Last name:
  <input type="text" id="key2" name="key2">

    First name:
  <input type="text" id="key3" name="key3">

  Last name:
 <input type="text" id="key4" name="key4">

  <input type="submit" value="Submit">
</form>

i am using this form to receive http post request to my python http server, the problem is ,in the last field , i need the the 1\ in the request that i receive on the server to save it into a variable and use it in os.path.join, but when i try to send request containing "\" i receive : 1%5C instead of, how can i send \
thanks in advance


问:
How to make a strings array by using dynamic memory allocation in C?
I tried to do this:

```<code>char** arr_from_num(int num)
{
    char** strings = (char**)malloc(num*sizeof(char*));
    if (strings == NULL)
        return 0;
    for (int i = 1; i <= num; i++) {
            strings[i-1] = (char*)malloc(9 * sizeof(char));
            strings[i-1] = "FizzBuzz";
    }
    return strings;
}
</code>```

But the function has a failure in doing this line:  char** strings = (char**)malloc(num*sizeof(char*));

How can I do it in other way?

答:
An array of strings is basically a 2D array where the first [] in the array syntax shows "how many strings" you have and the 2nd [] shows the length of each.

```<code>    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    void main()
    {
        char **arr = (char**)malloc(3);
        for (int i = 0;i < 3;i++)
        {
            arr[i] = malloc(sizeof("Fizzbuzz"));
            strcpy(arr[i], "Fizzbuzz");
        }
        //printing
        for (int i = 0;i < 3;i++)
        {
            printf("\n%s", arr[i]);
        }
        free(arr);
     }
</code>```

You have to allocate memory twice. Once for the number of strings and 2nd for the number of characters in the string. At the end of program you must free memory which you created using malloc function.

Body:
I tried to do this:

char** arr_from_num(int num)
{
    char** strings = (char**)malloc(num*sizeof(char*));
    if (strings == NULL)
        return 0;
    for (int i = 1; i <= num; i++) {
            strings[i-1] = (char*)malloc(9 * sizeof(char));
            strings[i-1] = "FizzBuzz";
    }
    return strings;
}

But the function has a failure in doing this line:  char** strings = (char**)malloc(num*sizeof(char*));

How can I do it in other way?

Body:
An array of strings is basically a 2D array where the first [] in the array syntax shows "how many strings" you have and the 2nd [] shows the length of each.

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    void main()
    {
        char **arr = (char**)malloc(3);
        for (int i = 0;i < 3;i++)
        {
            arr[i] = malloc(sizeof("Fizzbuzz"));
            strcpy(arr[i], "Fizzbuzz");
        }
        //printing
        for (int i = 0;i < 3;i++)
        {
            printf("\n%s", arr[i]);
        }
        free(arr);
     }

You have to allocate memory twice. Once for the number of strings and 2nd for the number of characters in the string. At the end of program you must free memory which you created using malloc function.


问:
User logged out of firebase server when different page loads
I'm new to firebase, and I can't figure out how to keep the user logged in after going to a different page.  I'm able to successfully log in and post user data to the console on the log in page, but when I go to a different page and try to get the user information using firebase.auth().currentUser.  I initially had it immediately redirect to another page after the log in was completed, and turned it off to see if I was leaving the page before the information was relayed to the server, but that did not fix it.  I also tried to manually set the persistence to no avail.  I've looked around here and haven't found anything that fixes the problem.

Here is my sign in method (which is basically the same thing as what's on firebase docs), which is called when the sign in button on the form is clicked:

```<code>function signIn(){
    //getting credential input from form
    var email = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    console.log(email, password)
    //calling firebase to sign in user
    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(cred => {
        //confirmation that user signed in
        console.log("signed in");
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMsg = error.message;
        if(errorCode === 'auth/wrong-password') {
            alert('Wrong Password');
        }
        else {
            alert(errorMsg);
        }
        console.log(error);
    });
};
</code>```

答:
firebase.auth().currentUser takes time to get data once a page is loaded. If you try to get it instantly, it will be null.

```<code>firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});
</code>```

This code will do whatever is in the function once Firebase has retrieved all the necessary data. @CanUver's answer did mention this code.

I show a loading page on my website until this is complete. This code snippet was from the Firebase Docs.

I'm not sure if this is your issue, but I remember having this problem.

Body:
I'm new to firebase, and I can't figure out how to keep the user logged in after going to a different page.  I'm able to successfully log in and post user data to the console on the log in page, but when I go to a different page and try to get the user information using firebase.auth().currentUser.  I initially had it immediately redirect to another page after the log in was completed, and turned it off to see if I was leaving the page before the information was relayed to the server, but that did not fix it.  I also tried to manually set the persistence to no avail.  I've looked around here and haven't found anything that fixes the problem.

Here is my sign in method (which is basically the same thing as what's on firebase docs), which is called when the sign in button on the form is clicked:

function signIn(){
    //getting credential input from form
    var email = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    console.log(email, password)
    //calling firebase to sign in user
    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(cred => {
        //confirmation that user signed in
        console.log("signed in");
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMsg = error.message;
        if(errorCode === 'auth/wrong-password') {
            alert('Wrong Password');
        }
        else {
            alert(errorMsg);
        }
        console.log(error);
    });
};

Body:
firebase.auth().currentUser takes time to get data once a page is loaded. If you try to get it instantly, it will be null.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

This code will do whatever is in the function once Firebase has retrieved all the necessary data. @CanUver's answer did mention this code.

I show a loading page on my website until this is complete. This code snippet was from the Firebase Docs.

I'm not sure if this is your issue, but I remember having this problem.


问:
Data JPA Test with reactive spring
I want to test the repository layer and I'm using spring webflux. My test class is as follows

```<code>@RunWith(SpringRunner.class)
@DataJpaTest
public class DataTester {
    @Autowired
    private MyRepository repository;

    @Test
    .....

}

</code>```

Even though this would work in spring-mvc when using spring-weblux I get the following error.

```<code>Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
...

Caused by: org.springframework.context.ApplicationContextException: Unable to start ReactiveWebApplicationContext due to missing ReactiveWebServerFactory bean.
</code>```

How to resolve this? If I am to start the whole application context with @SpringBootApplication it works. Any other options without using that?

答:
The reason for this was that in the application.properties the application type was set as reactive.

spring.main.web-application-type=reactive

This tries to auto configure a web server in this case a reactive web server. As @DataJpaTest does not provide a bean for that, this fails. This can be fixed in either two ways.

One is by Adding an application.properties file in the resources directory of the test package and setting the value as,sprig.main-web-application-type=none solves this issue.

Or we can simple pass a property value to the annotation as follows. @DataJpaTest(properties = "spring.main.web-application-type=none")

Title: Data JPA Test with reactive spring

Body:
I want to test the repository layer and I'm using spring webflux. My test class is as follows

@RunWith(SpringRunner.class)
@DataJpaTest
public class DataTester {
    @Autowired
    private MyRepository repository;

    @Test
    .....

}

Even though this would work in spring-mvc when using spring-weblux I get the following error.

Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
...

Caused by: org.springframework.context.ApplicationContextException: Unable to start ReactiveWebApplicationContext due to missing ReactiveWebServerFactory bean.

How to resolve this? If I am to start the whole application context with @SpringBootApplication it works. Any other options without using that?


问:
Import strings from .txt and searching for first numeric character - python
I am a total noob with python (programming in fact) but I hope you can help :)

I have a .txt file with a list of strings containing addresses.

I want to import it to Python and then search for the first numberic character and then create a new column for it...like

input

```<code>'Elm Street 12'
'Baker Street 143'
</code>```

and output

```<code>'Elm Street 12' , 12
'Baker Street 143' , 14
</code>```

and save it to .txt.

I am trying to do if from the windows cmd.

Thank you in advance.

答:
You probably want to use a dict. Loop through and use re to find your numeric characters, use that as a key in the dict to each string. If you expect to have duplicates.

```<code>import re
results = {}
for s in ['Elm Street 12', 'Baker Street 143']:
    match = re.search(r'\d+', s)
    if match:
        results[match.group()] = s

>>> results
<<< {'12': 'Elm Street 12', '143': 'Baker Street 143'}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am a total noob with python (programming in fact) but I hope you can help :)

I have a .txt file with a list of strings containing addresses.

I want to import it to Python and then search for the first numberic character and then create a new column for it...like

input

'Elm Street 12'
'Baker Street 143'

and output

'Elm Street 12' , 12
'Baker Street 143' , 14

and save it to .txt.

I am trying to do if from the windows cmd.

Thank you in advance.

Body:
You probably want to use a dict. Loop through and use re to find your numeric characters, use that as a key in the dict to each string. If you expect to have duplicates.

import re
results = {}
for s in ['Elm Street 12', 'Baker Street 143']:
    match = re.search(r'\d+', s)
    if match:
        results[match.group()] = s

>>> results
<<< {'12': 'Elm Street 12', '143': 'Baker Street 143'}


问:
Syntax error - typescript - unexpected token :?
I am new to Angular, and as you know to be a good Angular developer you have to be good in typescript, so I wrote my simple program as you can see :

```<code>function loge(messag){
    console.log(messag);
}

var message:string;

message = "Hi";

loge(message);
</code>```

There is no Syntax error I believe But I get this in my Terminal :

```<code>SyntaxError: Unexpected token :
  at createScript (vm.js:80:10)
  at Object.runInThisContext (vm.js:139:10)
  at Module._compile (module.js:607:28)
  at Object.Module._extensions..js (module.js:654:10)
  at Module.load (module.js:556:32)
  at tryModuleLoad (module.js:499:12)
  at Function.Module._load (module.js:491:3)
  at Function.Module.runMain (module.js:684:10)
  at startup (bootstrap_node.js:187:16)
  at bootstrap_node.js:608:3
</code>```

I don't know why I get this, I need to help so I can move on.
I am using the version 2.5.3 of typescript and PhpStrom as an IDE.

Any help would be much appreciated.

答:
I also was getting the same problem because I was trying to compile the .ts file and then trying to run the same .ts file using node file_name.ts command.

But it should be like first compile .ts file using tsc file_name.ts
then run the generated js file using node file_name.js.

Body:
I am new to Angular, and as you know to be a good Angular developer you have to be good in typescript, so I wrote my simple program as you can see :

function loge(messag){
    console.log(messag);
}

var message:string;

message = "Hi";

loge(message);

There is no Syntax error I believe But I get this in my Terminal :

SyntaxError: Unexpected token :
  at createScript (vm.js:80:10)
  at Object.runInThisContext (vm.js:139:10)
  at Module._compile (module.js:607:28)
  at Object.Module._extensions..js (module.js:654:10)
  at Module.load (module.js:556:32)
  at tryModuleLoad (module.js:499:12)
  at Function.Module._load (module.js:491:3)
  at Function.Module.runMain (module.js:684:10)
  at startup (bootstrap_node.js:187:16)
  at bootstrap_node.js:608:3

I don't know why I get this, I need to help so I can move on.
I am using the version 2.5.3 of typescript and PhpStrom as an IDE.

Any help would be much appreciated.


问:
Can't catch mocked exception because it doesn't inherit BaseException
I'm working on a project that involves connecting to a remote server, waiting for a response, and then performing actions based on that response.  We catch a couple of different exceptions, and behave differently depending on which exception is caught.  For example:

```<code>def myMethod(address, timeout=20):
    try:
        response = requests.head(address, timeout=timeout)
    except requests.exceptions.Timeout:
        # do something special
    except requests.exceptions.ConnectionError:
        # do something special
    except requests.exceptions.HTTPError:
        # do something special
    else:
        if response.status_code != requests.codes.ok:
            # do something special
        return successfulConnection.SUCCESS
</code>```

To test this, we've written a test like the following

```<code>class TestMyMethod(unittest.TestCase):

    def test_good_connection(self):
        config = {
            'head.return_value': type('MockResponse', (), {'status_code': requests.codes.ok}),
            'codes.ok': requests.codes.ok
        }
        with mock.patch('path.to.my.package.requests', **config):
            self.assertEqual(
                mypackage.myMethod('some_address',
                mypackage.successfulConnection.SUCCESS
            )

    def test_bad_connection(self):
        config = {
            'head.side_effect': requests.exceptions.ConnectionError,
            'requests.exceptions.ConnectionError': requests.exceptions.ConnectionError
        }
        with mock.patch('path.to.my.package.requests', **config):
            self.assertEqual(
                mypackage.myMethod('some_address',
                mypackage.successfulConnection.FAILURE
            )
</code>```

If I run the function directly, everything happens as expected.  I even tested by adding raise requests.exceptions.ConnectionError to the try clause of the function.  But when I run my unit tests, I get

ERROR: test_bad_connection (test.test_file.TestMyMethod)
----------------------------------------------------------------
Traceback (most recent call last):
  File "path/to/sourcefile", line ###, in myMethod
    respone = requests.head(address, timeout=timeout)
  File "path/to/unittest/mock", line 846, in __call__
    return _mock_self.mock_call(*args, **kwargs)
  File "path/to/unittest/mock", line 901, in _mock_call
    raise effect
my.package.requests.exceptions.ConnectionError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Path/to/my/test", line ##, in test_bad_connection
    mypackage.myMethod('some_address',
  File "Path/to/package", line ##, in myMethod
    except requests.exceptions.ConnectionError:
TypeError: catching classes that do not inherit from BaseException is not allowed
```

I tried to change the exception I was patching in to BaseException and I got a more or less identical error.

I've read https://stackoverflow.com/a/18163759/3076272 already, so I think it must be a bad __del__ hook somewhere, but I'm not sure where to look for it or what I can even do in the mean time.  I'm also relatively new to unittest.mock.patch() so it's very possible that I'm doing something wrong there as well.

This is a Fusion360 add-in so it is using Fusion 360's packaged version of Python 3.3 - as far as I know it's a vanilla version (i.e. they don't roll their own) but I'm not positive of that.

答:
Use patch.object to partially mock a class.

My use case:

import unittest
from unittest import mock
import requests

def test_my_function(self):
    response = mock.MagicMock()
    response.raise_for_status.side_effect = requests.HTTPError

    with mock.patch.object(requests, 'get', return_value=response):
        my_function()
```

Body:
I'm working on a project that involves connecting to a remote server, waiting for a response, and then performing actions based on that response.  We catch a couple of different exceptions, and behave differently depending on which exception is caught.  For example:

def myMethod(address, timeout=20):
    try:
        response = requests.head(address, timeout=timeout)
    except requests.exceptions.Timeout:
        # do something special
    except requests.exceptions.ConnectionError:
        # do something special
    except requests.exceptions.HTTPError:
        # do something special
    else:
        if response.status_code != requests.codes.ok:
            # do something special
        return successfulConnection.SUCCESS

To test this, we've written a test like the following

class TestMyMethod(unittest.TestCase):

    def test_good_connection(self):
        config = {
            'head.return_value': type('MockResponse', (), {'status_code': requests.codes.ok}),
            'codes.ok': requests.codes.ok
        }
        with mock.patch('path.to.my.package.requests', **config):
            self.assertEqual(
                mypackage.myMethod('some_address',
                mypackage.successfulConnection.SUCCESS
            )

    def test_bad_connection(self):
        config = {
            'head.side_effect': requests.exceptions.ConnectionError,
            'requests.exceptions.ConnectionError': requests.exceptions.ConnectionError
        }
        with mock.patch('path.to.my.package.requests', **config):
            self.assertEqual(
                mypackage.myMethod('some_address',
                mypackage.successfulConnection.FAILURE
            )

If I run the function directly, everything happens as expected.  I even tested by adding raise requests.exceptions.ConnectionError to the try clause of the function.  But when I run my unit tests, I get

ERROR: test_bad_connection (test.test_file.TestMyMethod)
----------------------------------------------------------------
Traceback (most recent call last):
  File "path/to/sourcefile", line ###, in myMethod
    respone = requests.head(address, timeout=timeout)
  File "path/to/unittest/mock", line 846, in __call__
    return _mock_self.mock_call(*args, **kwargs)
  File "path/to/unittest/mock", line 901, in _mock_call
    raise effect
my.package.requests.exceptions.ConnectionError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Path/to/my/test", line ##, in test_bad_connection
    mypackage.myMethod('some_address',
  File "Path/to/package", line ##, in myMethod
    except requests.exceptions.ConnectionError:
TypeError: catching classes that do not inherit from BaseException is not allowed

I tried to change the exception I was patching in to BaseException and I got a more or less identical error.

I've read https://stackoverflow.com/a/18163759/3076272 already, so I think it must be a bad __del__ hook somewhere, but I'm not sure where to look for it or what I can even do in the mean time.  I'm also relatively new to unittest.mock.patch() so it's very possible that I'm doing something wrong there as well.

This is a Fusion360 add-in so it is using Fusion 360's packaged version of Python 3.3 - as far as I know it's a vanilla version (i.e. they don't roll their own) but I'm not positive of that.


问:
Different redirects on form submit in a Django view
Is it possible to redirect to a page or another when sending a request.POST in a Django view, depending on which button has been used?

Example:

```<code><form id="myForm" action='?'>
    <submit button1>
    <submit button2>
</form>
</code>```

and then in my view:

```<code>if request.method == "POST":
    if form.is_valid() and button1:
        form.save()
        return redirect('page1')
    if form.is_valid() and button2:
        form.save()
        return redirect('page2')
</code>```

答:
You may try this:

html

```<code><form>
    <input type="submit" name="button1">
    <input type="submit" name="button2">
</form>
</code>```

Views.py

```<code>if request.method == "POST":
    if form.is_valid() and 'button1' in request.POST:
        form.save()
        return redirect('page1')
    if form.is_valid() and 'button2' in request.POST:
        form.save()
        return redirect('page2')
</code>```

Body:
Is it possible to redirect to a page or another when sending a request.POST in a Django view, depending on which button has been used?

Example:

<form id="myForm" action='?'>
    <submit button1>
    <submit button2>
</form>

and then in my view:

if request.method == "POST":
    if form.is_valid() and button1:
        form.save()
        return redirect('page1')
    if form.is_valid() and button2:
        form.save()
        return redirect('page2')

Body:
You may try this:

html

<form>
    <input type="submit" name="button1">
    <input type="submit" name="button2">
</form>

Views.py

if request.method == "POST":
    if form.is_valid() and 'button1' in request.POST:
        form.save()
        return redirect('page1')
    if form.is_valid() and 'button2' in request.POST:
        form.save()
        return redirect('page2')


问:
Python SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escap
Does anyone know why I am getting this unicode error. I am trying to remove duplicates from a csv file. </p>

```<code>import pandas as pd
df = pd.read_csv('new.csv', usecols=['minzoom', 'maxzoom']).drop_duplicates(keep='first').reset_index()
file_name = "C:\Users\kziaj\Desktop\Python Test\newno.csv"
df.to_csv("newno.csv", index=False) # you don't need to set sep in this because to_csv makes it comma delimited.
</code>```

答:
The error indicates the path of your file is not valid.
Specifically, python treats single backslash as escape character, not a path separator, which is a common mistake in python programming on Windows. To avoid this, use double backslash or raw string.

Double Backslash

```<code>file_name = "C:\\Users\\kziaj\\Desktop\\Python Test\\newno.csv"
</code>```

Raw String

```<code>file_name = r"C:\Users\kziaj\Desktop\Python Test\newno.csv"
</code>```

Body:
Does anyone know why I am getting this unicode error. I am trying to remove duplicates from a csv file.

import pandas as pd
df = pd.read_csv('new.csv', usecols=['minzoom', 'maxzoom']).drop_duplicates(keep='first').reset_index()
file_name = "C:\Users\kziaj\Desktop\Python Test\newno.csv"
df.to_csv("newno.csv", index=False) # you don't need to set sep in this because to_csv makes it comma delimited.

Body:
The error indicates the path of your file is not valid.
Specifically, python treats single backslash as escape character, not a path separator, which is a common mistake in python programming on Windows. To avoid this, use double backslash or raw string.

Double Backslash

file_name = "C:\\Users\\kziaj\\Desktop\\Python Test\\newno.csv"

Raw String

file_name = r"C:\Users\kziaj\Desktop\Python Test\newno.csv"


问:
Making an API call using fetch
I am trying to make a Fetch API call using a free code snippet from and I am unable to recieve the json response. I would have thought it was just a question of placing the code snippet between the script tags on the index.html page,

fetch("https://currency-converter5.p.rapidapi.com/currency/list?format=json", {
  "method": "GET",
  "headers": {
    "x-rapidapi-host": "currency-converter5.p.rapidapi.com",
    "x-rapidapi-key": "**redacted**"
  }
})
.then(response => {
  console.log(response);
})
.catch(err => {
  console.log(err);
});```

答:
You're close.  But there's a second asynchronous operation that needs to be chained into the promise.  Your response contains JSON, which can be read (asynchronously) with response.json().  Return that and chain another .then() to log the result of that operation:

```<code>fetch("https://currency-converter5.p.rapidapi.com/currency/list?format=json",
{
  "method": "GET",
  "headers": {
    "x-rapidapi-host": "currency-converter5.p.rapidapi.com",
    "x-rapidapi-key": "**redacted**"
  }
})
.then(response => response.json())
.then(result => {
  console.log(result);
})
.catch(err => {
  console.log(err);
});
</code>```

Title: Making an API call using fetch

Body:
You're close.  But there's a second asynchronous operation that needs to be chained into the promise.  Your response contains JSON, which can be read (asynchronously) with response.json().  Return that and chain another .then() to log the result of that operation:

fetch("https://currency-converter5.p.rapidapi.com/currency/list?format=json",
{
  "method": "GET",
  "headers": {
    "x-rapidapi-host": "currency-converter5.p.rapidapi.com",
    "x-rapidapi-key": "**redacted**"
  }
})
.then(response => response.json())
.then(result => {
  console.log(result);
})
.catch(err => {
  console.log(err);
});


问:
How to stop a while loop containing two inherited for loops
```<code>import time
stop_time = time.time() + 5 #5 seconds
while time.time() < stop_time:
    for i in range(1000000):
        print(i)
        for x in range(654165):
            print(x)
</code>```

How to stop this loop after 5 seconds?

答:
You can use the perf_counter() method:</p>

```<code>import time

while time.perf_counter() <= 5:
    for i in range(1000000):
        if time.perf_counter() <= 5:
            print(i)
            for x in range(654165):
                if time.perf_counter() <= 5:
                    print(x)
</code>```

Body:
import time
stop_time = time.time() + 5 #5 seconds
while time.time() < stop_time:
    for i in range(1000000):
        print(i)
        for x in range(654165):
            print(x)

How to stop this loop after 5 seconds?

Body:
You can use the perf_counter() method:

import time

while time.perf_counter() <= 5:
    for i in range(1000000):
        if time.perf_counter() <= 5:
            print(i)
            for x in range(654165):
                if time.perf_counter() <= 5:
                    print(x)


答:
I've solved it like so:

```<code>    <input class="button" value='update' type="submit" name="action" form="eventForm"/>
    <input class="button" value='submit' type="submit" name="action" form="eventForm"/>
</code>```

And then in the view:

```<code>if request.POST['action'] == 'submit':
[...]
elif request.POST['action'] == 'update'
</code>```

Title: Different redirects on form submit in a Django view

Body:
I've solved it like so:

    <input class="button" value='update' type="submit" name="action" form="eventForm"/>
    <input class="button" value='submit' type="submit" name="action" form="eventForm"/>

And then in the view:

if request.POST['action'] == 'submit':
[...]
elif request.POST['action'] == 'update'


问:
Dynamic Dates SQL Server
I have the below data in SQL.

I need to figure out a way dynamically to get the next dates based the 2 values below. The remaining doses tells me how many dates I will need to find and RXDAYS tells me the increments in which to look for the dates

```<code>Date Shipped    Remaining Doses RXDAYS
2019-06-05      2               30
</code>```

So based on the above I would find the date 30 days after 2019-06-05 and get 2019-07-05 and 30 days after that I would get 2019-08-04.

Is there a way to do this?

答:
Use dateadd(). This gives you the final date:

```<code>dateadd(day, doses * rxdays, date_shipped)
</code>```

On the other hand if you want to generate new rows, then you could use a recursive query:

```<code>with cte as (
    select date_shipped mydate, doses, rxdays from mytable
    union all
    select (dateadd(day, rxdays, date_shipped), doses - 1, rxdays
    from cte
    where doses > 0
)
select mydate from cte
</code>```

For the sample data row showned in your question, this would generate three rows, with dates 2019-06-05, 2019-07-05 and 2019-08-04.

If doses has values greater than 100, then you need to add option(maxrecursion 0) at the very end of the query.

Title: Dynamic Dates SQL Server

Body:
I have the below data in SQL.

I need to figure out a way dynamically to get the next dates based the 2 values below. The remaining doses tells me how many dates I will need to find and RXDAYS tells me the increments in which to look for the dates

Date Shipped    Remaining Doses RXDAYS
2019-06-05      2               30

So based on the above I would find the date 30 days after 2019-06-05 and get 2019-07-05 and 30 days after that I would get 2019-08-04.

Is there a way to do this?

Body:
Use dateadd(). This gives you the final date:

dateadd(day, doses * rxdays, date_shipped)

On the other hand if you want to generate new rows, then you could use a recursive query:

with cte as (
    select date_shipped mydate, doses, rxdays from mytable
    union all
    select (dateadd(day, rxdays, date_shipped), doses - 1, rxdays
    from cte
    where doses > 0
)
select mydate from cte

For the sample data row showned in your question, this would generate three rows, with dates 2019-06-05, 2019-07-05 and 2019-08-04.

If doses has values greater than 100, then you need to add option(maxrecursion 0) at the very end of the query.


问:
Persist store with Redux Toolkit in React-native
I am using redux-persist with redux toolkit.
here is my store configuration.

I haven't implemented or configured store before.
I intend to persist user state after login.
Currently after login, if I reload app in emulator it always goes back to login screen.

is my store configured properly?

updated store file:

```<code>import {configureStore} from '@reduxjs/toolkit';
import authReducer from '../features/login/authSlice';
import AsyncStorage from '@react-native-community/async-storage';
import {persistReducer, persistStore} from 'redux-persist';
import {combineReducers} from 'redux';
import hardSet from 'redux-persist/lib/stateReconciler/hardSet';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';

const reducers = combineReducers({
  auth: authReducer,
  // other reducers goes here...
});

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
//  stateReconciler: hardSet,
};

const _persistedReducer = persistReducer(persistConfig, reducers);

export const store = configureStore({
  reducer: _persistedReducer,
});
export const persistor = persistStore(store);
</code>```

My index.js file where i wrap my root component with PersistGate

```<code>   import React from 'react';
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import {store, persistor} from './src/stores/store';
import {Provider} from 'react-redux';
import {storeUser, storeRefreshToken} from './src/features/login/authSlice';
import {PersistGate} from 'redux-persist/lib/integration/react';

const RNRedux = () => (
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
);

AppRegistry.registerComponent(appName, () => RNRedux);
</code>```

Error I get currently:

答:
I think you need to use persistStore. You should store your app store in persistStore and then use persistGate.
PersistGate delays the rendering of your app's UI until your persisted state has been retrieved and saved to redux.

So, your store file can be :

```<code>import { persistStore } from 'redux-persist';
const persistor = persistStore(store);
export { persistor, store };
</code>```

And your app.js will be :

```<code>import { store, persistor } from 'path_to_your_store/store';
<Provider store={store}>
          <PersistGate persistor={persistor}>
             </App>
          </PersistGate>
</Provider>
</code>```

Body:
I am using redux-persist with redux toolkit.
here is my store configuration.

I haven't implemented or configured store before.
I intend to persist user state after login.
Currently after login, if I reload app in emulator it always goes back to login screen.

is my store configured properly?

updated store file:

import {configureStore} from '@reduxjs/toolkit';
import authReducer from '../features/login/authSlice';
import AsyncStorage from '@react-native-community/async-storage';
import {persistReducer, persistStore} from 'redux-persist';
import {combineReducers} from 'redux';
import hardSet from 'redux-persist/lib/stateReconciler/hardSet';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';

const reducers = combineReducers({
  auth: authReducer,
  // other reducers goes here...
});

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
//  stateReconciler: hardSet,
};

const _persistedReducer = persistReducer(persistConfig, reducers);

export const store = configureStore({
  reducer: _persistedReducer,
});
export const persistor = persistStore(store);

My index.js file where i wrap my root component with PersistGate

   import React from 'react';
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import {store, persistor} from './src/stores/store';
import {Provider} from 'react-redux';
import {storeUser, storeRefreshToken} from './src/features/login/authSlice';
import {PersistGate} from 'redux-persist/lib/integration/react';

const RNRedux = () => (
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
);

AppRegistry.registerComponent(appName, () => RNRedux);

Error I get currently:

Body:
I think you need to use persistStore. You should store your app store in persistStore and then use persistGate.
PersistGate delays the rendering of your app's UI until your persisted state has been retrieved and saved to redux.

So, your store file can be :

import { persistStore } from 'redux-persist';
const persistor = persistStore(store);
export { persistor, store };

And your app.js will be :

import { store, persistor } from 'path_to_your_store/store';
<Provider store={store}>
          <PersistGate persistor={persistor}>
             </App>
          </PersistGate>
</Provider>


问:
How to eliminate spaces in list containing numbers in python?
I have a list, which is to be passed as part of params to URL.

```<code>params={"some_value":[1234, 5678]}
</code>```

Observe the space before 5678
As a number wise, it doesn't make any difference.
But when passed as parameter, it looks like http://some_url/abcd?some_value=[1234,%205678]

```<code>%20 gets added to space.
</code>```

Any way, how can i eliminate this kind of space existing in list ?

```<code>response = requests_session.get(url=url, headers=headers, params=params, json=None,verify=False, timeout=1000)
</code>```

Should look like params={"some_value":[1234,5678]} and http://some_url/abcd?some_value=[1234,5678]

答:
An easy solution is this. Before you pass it as a parameter,

```<code>params["some_value"] = str(params["some_value"]).replace(" ", "")
</code>```

```<code>>>> params
{'some_value': '[1234,5678]'}
>>>
</code>```

On the front-end side:

```<code>JSON.parse('[1234,5678]')
</code>```

Returns

```<code>> (2) [1234, 5678]
</code>```

Body:
I have a list, which is to be passed as part of params to URL.

params={"some_value":[1234, 5678]}

Observe the space before 5678
As a number wise, it doesn't make any difference.
But when passed as parameter, it looks like http://some_url/abcd?some_value=[1234,%205678]

%20 gets added to space.

Any way, how can i eliminate this kind of space existing in list ?

response = requests_session.get(url=url, headers=headers, params=params, json=None,verify=False, timeout=1000)

Should look like params={"some_value":[1234,5678]} and http://some_url/abcd?some_value=[1234,5678]

Body:
An easy solution is this. Before you pass it as a parameter,

params["some_value"] = str(params["some_value"]).replace(" ", "")

>>> params
{'some_value': '[1234,5678]'}
>>>

On the front-end side:

JSON.parse('[1234,5678]')

Returns

> (2) [1234, 5678]


答:
Yes. Give your submit buttons the same name but different values

```<code><button type="submit" name="submit" value="button1">Button 1</button>
<button type="submit" name="submit" value="button2">Button 2</button>
</code>```

Which button was clicked will then be available in request.POST

```<code>if request.method == "POST" and form.is_valid():
    form.save()
    if request.POST['submit'] == 'button1':
        return redirect('page1')
    elif request.POST['submit'] == 'button2':
        return redirect('page2')
</code>```

Body:
Yes. Give your submit buttons the same name but different values

<button type="submit" name="submit" value="button1">Button 1</button>
<button type="submit" name="submit" value="button2">Button 2</button>

Which button was clicked will then be available in request.POST

if request.method == "POST" and form.is_valid():
    form.save()
    if request.POST['submit'] == 'button1':
        return redirect('page1')
    elif request.POST['submit'] == 'button2':
        return redirect('page2')


问:
Foreach - How to print a only the third and 4th value
I have form with the option to add more fields.
I'd like to know if i could print the individual values of a foreach loop.
eg. if the person added to forms and i want to print the second value how would i do that ?
So Far what i have tried only printed the first Character.

HTML

```<code><form action="careerHistoryCon.php" method="post" enctype="multipart/form-data">
<label for="industry[]">Industry Segmentation</label>
<input type="text" name="industry[]" id="" placeholder="Finance / Insurance ...."><br>
<p>To add another feild <a href="#" id="addMore">Click here</a> </p> <br><br>
</form>
</code>```

JQ

```<code>  $("#addMore").click(function(){
$(".form-group:last").clone().appendTo(".wrapper");
});
</code>```

PHP - Problem here

```<code>if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (isset($_POST['submit'])){

    $industry= $_POST['industry'];
    foreach ($industry as $key => $value) {

        echo $value[0]. '<BR>';
        echo $value[1]. '<BR>';

    }
}
</code>```

答:
You are pretty near to the solution. Using foreach on an array gives you the index as key.

```<code>foreach ($industry as $key => $value) {
    if($key == 1) echo $value; // array starts with 0, so 1 is the second element.
}
</code>```

or you can use an iterator

```<code>// using foreach
$i = 0;
foreach ($industry as $key => $value) {
    if($i == 1) echo $value;
    $i++;
}

//using for
for($i = 0; $i < count($industry); $i++) {
    if($i == 1) echo $industry[$i];
}
</code>```

btw. since $value is the input string of the user, $value[0] would just be the first letter the user entered. Because a string is just an array of chars.

Body:
I have form with the option to add more fields.
I'd like to know if i could print the individual values of a foreach loop.
eg. if the person added to forms and i want to print the second value how would i do that ?
So Far what i have tried only printed the first Character.

HTML

<form action="careerHistoryCon.php" method="post" enctype="multipart/form-data">
Industry Segmentation
<input type="text" name="industry[]" id="" placeholder="Finance / Insurance ....">

To add another feild Click here

</form>

JQ

  $("#addMore").click(function(){
$(".form-group:last").clone().appendTo(".wrapper");
});

PHP - Problem here

if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (isset($_POST['submit'])){

    $industry= $_POST['industry'];
    foreach ($industry as $key => $value) {

        echo $value[0]. '
';
        echo $value[1]. '
';

    }
}

Body:
You are pretty near to the solution. Using foreach on an array gives you the index as key.

foreach ($industry as $key => $value) {
    if($key == 1) echo $value; // array starts with 0, so 1 is the second element.
}

or you can use an iterator

// using foreach
$i = 0;
foreach ($industry as $key => $value) {
    if($i == 1) echo $value;
    $i++;
}

//using for
for($i = 0; $i < count($industry); $i++) {
    if($i == 1) echo $industry[$i];
}

btw. since $value is the input string of the user, $value[0] would just be the first letter the user entered. Because a string is just an array of chars.


问:
Make DIV fixed inside a scrollable DIV
Does anyone now how to make a DIV inside another DIV that is scroll-able fixed, so that no matter how much I scroll by, the DIV always stays in the same place?

Any help would be greatly appreciated.

答: I would recommend absolutely positioning the div over the scrollable div. It wont be in the scrollable div, because it doesn't need to be.

Title: Make DIV fixed inside a scrollable DIV


问:
Disable checkbox on certain lines on a JTable
I have a JTable on a Netbeans 8.2 project which shows the data of a list a class (let's call it Client) and a checkbox on the first column of each line. I've setup this way changing the data type of the column in the object's properties menu. How can I not show this checkbox in case that a client's attribute is false?</p>

答:
I assume the first column is not editable. If you want to hide the JCheckBox when cell value is false, you can use a customer cell renderer:

```<code>private class MyCellRenderer extends DefaultTableCellRenderer
{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
    {
        Component c;
        if (((Boolean)value).equals(true))
        {
            // Use the default renderer for Boolean which is JCheckBox based
            c = myTable.getDefaultRenderer(table.getColumnClass(col)).getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        } else
        {
            // Use the standard default renderer which is a JLabel
            c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
            if (c instanceof JLabel)
            {
                ((JLabel) c).setText(null);
            }
        }
        return c;
    }
}
</code>```

And apply it on the first boolean column:

```<code>myTable.getColumnModel().getColumn(0).setCellRenderer(new MyCellRenderer());
</code>```

Body:
I assume the first column is not editable. If you want to hide the JCheckBox when cell value is false, you can use a customer cell renderer:

private class MyCellRenderer extends DefaultTableCellRenderer
{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
    {
        Component c;
        if (((Boolean)value).equals(true))
        {
            // Use the default renderer for Boolean which is JCheckBox based
            c = myTable.getDefaultRenderer(table.getColumnClass(col)).getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        } else
        {
            // Use the standard default renderer which is a JLabel
            c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
            if (c instanceof JLabel)
            {
                ((JLabel) c).setText(null);
            }
        }
        return c;
    }
}

And apply it on the first boolean column:

myTable.getColumnModel().getColumn(0).setCellRenderer(new MyCellRenderer());


问:
Creating Lexicon and Scanner in Python
I'm new here in the world of coding and I haven't received a very warm welcome.  I've been trying to learn python via the online tutorial http://learnpythonthehardway.org/book/. I've been able to struggle my way through the book up until exercise 48 & 49.  That's where he turns students loose and says "You figure it out."  But I simply can't.  I understand that I need to create a Lexicon of possible words and that I need to scan the user input to see if it matches anything in the Lexicon but that's about it!  From what I can tell, I need to create a list called lexicon:

```<code>lexicon = [
    ('directions', 'north'),
    ('directions', 'south'),
    ('directions', 'east'),
    ('directions', 'west'),
    ('verbs', 'go'),
    ('verbs', 'stop'),
    ('verbs', 'look'),
    ('verbs', 'give'),
    ('stops', 'the'),
    ('stops', 'in'),
    ('stops', 'of'),
    ('stops', 'from'),
    ('stops', 'at')
]
</code>```

Is that right?  I don't know what to do next?  I know that each item in the list is called a tuple, but that doesn't really mean anything to me.  How do I take raw input and assign it to the tuple?  You know what I mean?  So in exercise 49 he imports the lexicon and just inside python prints lexicon.scan("input") and it returns the list of tuples so for example:

```<code>from ex48 import lexicon
>>> print lexicon.scan("go north")
[('verb', 'go'), ('direction', 'north')]
</code>```

Is 'scan()' a predefined function or did he create the function within the lexicon module?  I know that if you use 'split()' it creates a list with all of the words from the input but then how does it assign 'go' to the tuple ('verb', 'go')?

Am I just way off?  I know I'm asking a lot but I searched around everywhere for hours and I can't figure this one out on my own.  Please help!  I will love you forever!

答:
Like the most here I am new to the world of coding and I though I attach my solution below as it might help other students.

I already saw a few more efficient approaches that I could implement. However, the code handles every use case of the exercise and since I am wrote it on my own with my beginners mind it does not take complicated shortcuts and should be very easy to understand for other beginners.

I therefore thought it might beneficial for someone else learning. Let me know what you think. Cheers!

```<code>class Lexicon(object):

def __init__(self):
    self.sentence = []
    self.dictionary = {
        'north' : ('direction','north'),
        'south' : ('direction','south'),
        'east' : ('direction','east'),
        'west' : ('direction','west'),
        'down' : ('direction','down'),
        'up' : ('direction','up'),
        'left' : ('direction','left'),
        'right' : ('direction','right'),
        'back' : ('direction','back'),
        'go' : ('verb','go'),
        'stop' : ('verb','stop'),
        'kill' : ('verb','kill'),
        'eat' : ('verb', 'eat'),
        'the' : ('stop','the'),
        'in' : ('stop','in'),
        'of' : ('stop','of'),
        'from' : ('stop','from'),
        'at' : ('stop','at'),
        'it' : ('stop','it'),
        'door' : ('noun','door'),
        'bear' : ('noun','bear'),
        'princess' : ('noun','princess'),
        'cabinet' : ('noun','cabinet'),
    }

def scan(self, input):
    loaded_imput = input.split()
    self.sentence.clear()

    for item in loaded_imput:
        try:
            int(item)
            number = ('number', int(item))
            self.sentence.append(number)
        except ValueError:
            word = self.dictionary.get(item.lower(), ('error', item))
            self.sentence.append(word)

    return self.sentence
lexicon = Lexicon()
</code>```

Title: Creating Lexicon and Scanner in Python

Body:
I'm new here in the world of coding and I haven't received a very warm welcome.  I've been trying to learn python via the online tutorial http://learnpythonthehardway.org/book/. I've been able to struggle my way through the book up until exercise 48 & 49.  That's where he turns students loose and says "You figure it out."  But I simply can't.  I understand that I need to create a Lexicon of possible words and that I need to scan the user input to see if it matches anything in the Lexicon but that's about it!  From what I can tell, I need to create a list called lexicon:

lexicon = [
    ('directions', 'north'),
    ('directions', 'south'),
    ('directions', 'east'),
    ('directions', 'west'),
    ('verbs', 'go'),
    ('verbs', 'stop'),
    ('verbs', 'look'),
    ('verbs', 'give'),
    ('stops', 'the'),
    ('stops', 'in'),
    ('stops', 'of'),
    ('stops', 'from'),
    ('stops', 'at')
]

Is that right?  I don't know what to do next?  I know that each item in the list is called a tuple, but that doesn't really mean anything to me.  How do I take raw input and assign it to the tuple?  You know what I mean?  So in exercise 49 he imports the lexicon and just inside python prints lexicon.scan("input") and it returns the list of tuples so for example:

from ex48 import lexicon
>>> print lexicon.scan("go north")
[('verb', 'go'), ('direction', 'north')]

Is 'scan()' a predefined function or did he create the function within the lexicon module?  I know that if you use 'split()' it creates a list with all of the words from the input but then how does it assign 'go' to the tuple ('verb', 'go')?

Am I just way off?  I know I'm asking a lot but I searched around everywhere for hours and I can't figure this one out on my own.  Please help!  I will love you forever!

Body:
Like the most here I am new to the world of coding and I though I attach my solution below as it might help other students.

I already saw a few more efficient approaches that I could implement. However, the code handles every use case of the exercise and since I am wrote it on my own with my beginners mind it does not take complicated shortcuts and should be very easy to understand for other beginners.

I therefore thought it might beneficial for someone else learning. Let me know what you think. Cheers!

class Lexicon(object):

def __init__(self):
    self.sentence = []
    self.dictionary = {
        'north' : ('direction','north'),
        'south' : ('direction','south'),
        'east' : ('direction','east'),
        'west' : ('direction','west'),
        'down' : ('direction','down'),
        'up' : ('direction','up'),
        'left' : ('direction','left'),
        'right' : ('direction','right'),
        'back' : ('direction','back'),
        'go' : ('verb','go'),
        'stop' : ('verb','stop'),
        'kill' : ('verb','kill'),
        'eat' : ('verb', 'eat'),
        'the' : ('stop','the'),
        'in' : ('stop','in'),
        'of' : ('stop','of'),
        'from' : ('stop','from'),
        'at' : ('stop','at'),
        'it' : ('stop','it'),
        'door' : ('noun','door'),
        'bear' : ('noun','bear'),
        'princess' : ('noun','princess'),
        'cabinet' : ('noun','cabinet'),
    }

def scan(self, input):
    loaded_imput = input.split()
    self.sentence.clear()

    for item in loaded_imput:
        try:
            int(item)
            number = ('number', int(item))
            self.sentence.append(number)
        except ValueError:
            word = self.dictionary.get(item.lower(), ('error', item))
            self.sentence.append(word)

    return self.sentence
lexicon = Lexicon()


问:
Scraping using selenium
Hi I am trying to scrape this website I originally was using Bs4 and that was fine to get certain elements. Sector, name etc. But I am not able to use it to get the financial data. Below I have copied some of the page_source the "-" should be in this case 0.0663. I believe I am trying to scrape javascript and I have looked around and none of the solutions I have seen have worked for me. I was wondering if someone could help me crack this.

Although I will be grateful if someone can post some working code I would also really appreciate if you can point me in the right direction as well to understand what to look for in the html which shows me what I need to do and how to get it kinda thing.

URL: https://www.tradingview.com/symbols/LSE-TSCO/

HTML:

    Return on Equity (TTM)

    —

```

<p>Python Code:</p>

<pre class="lang-py prettyprint-override"><code>url = "https://www.tradingview.com/symbols/LSE-TSCO/"
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(url)
html = driver.page_source
</code>```

答:
To get the equity value.Induce WebDriverWait() and wait for visibility_of_element_located() and below xpath.

```<code>driver.get(url)
print(WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,"//span[contains(.,'Return on Equity (TTM)')]/following-sibling::span[1]"))).text)
</code>```

You need to import below libraries.

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
</code>```

Title: Scraping using selenium

Body:
Hi I am trying to scrape this website I originally was using Bs4 and that was fine to get certain elements. Sector, name etc. But I am not able to use it to get the financial data. Below I have copied some of the page_source the "-" should be in this case 0.0663. I believe I am trying to scrape javascript and I have looked around and none of the solutions I have seen have worked for me. I was wondering if someone could help me crack this.

Although I will be grateful if someone can post some working code I would also really appreciate if you can point me in the right direction as well to understand what to look for in the html which shows me what I need to do and how to get it kinda thing.

URL: https://www.tradingview.com/symbols/LSE-TSCO/

HTML:

    Return on Equity (TTM)

    —

Python Code:

url = "https://www.tradingview.com/symbols/LSE-TSCO/"
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(url)
html = driver.page_source

Body:
To get the equity value.Induce WebDriverWait() and wait for visibility_of_element_located() and below xpath.

driver.get(url)
print(WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,"//span[contains(.,'Return on Equity (TTM)')]/following-sibling::span[1]"))).text)

You need to import below libraries.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


问:
node js express, req.body returns nothing
I have this web server setup with express, everything works fine except the req.body returns nothing it seems. I don't get any error it just doesn't do anything. The console.log(req.body) doesn't do anything. When I check the console I see nothing. But the rest of the application works ok.

What am I missing?

server.js file is below

```<code>if (process.env.NODE_ENV !== "production") {
    require("dotenv").config();
}

const clientId = process.env.client_id;
const clientSecret = process.env.client_secret;
const refreshToken = process.env.refresh_token;

const date = new Date();
date.setDate(date.getDate() - 2);

const express = require("express");
const app = express();

app.use(express.json());
app.use(express.static("public"));

app.post("/alerts", async (req, res) => {
    console.log(req.body)
    const alertsUrl = `https://www.g2smart.com/g2smart/api/alert?range=last7Days&cpo=${req.body.selection}&status=Opened&limit=100&page=1`
    const axios = require("axios");
    const oauth = require("axios-oauth-client");

    const getRefreshToken = oauth.client(axios.create(), {
        url: "https://www.g2smart.com/g2smart/api/oauth2/token",
        grant_type: "refresh_token",
        client_id: `${clientId}`,
        client_secret: `${clientSecret}`,
        refresh_token: `${refreshToken}`,
    });

    const auth = await getRefreshToken();

    axios({
        url: alertsUrl
            ,
        headers: {
            accept: "application/json, text/plain, */*",
            authorization: `Bearer ${auth["access_token"]}`,
        },
        responseType: "json",
    }).then((data) => res.json(data.data.items));
});

app.listen(process.env.port || 3000);

console.log("Running at Port 3000");
</code>```

and here is the script.js below, where i have my fetch function.

```<code>const selectElement = document.querySelector('[data-cpo-select]')
const cpo = {
    france: "total_fr_hpc",
    netherlands: "total_nl_hpc",
    te61: "te61"}

selectElement.addEventListener("change", (event) => {
    const selection = event.target.value
    fetch("/alerts", {
        method: "POST",
        headers: {
            "Content-Type": "application",
            "Accept": "application/json",
        },
        body: JSON.stringify({
            selection: cpo[selection]
        })
    })
        .then((res) => res.json())
        .then((data) => {
            setAlertsData(data);
        });

    const alertTypeElement = document.querySelector("[data-alert-type]");
    const locationElement = document.querySelector("[data-location]");
    const statusElement = document.querySelector("[data-status]");
    const severityElement = document.querySelector("[data-severity]");
    const chargePointElement = document.querySelector("[data-charge-point]");

    function setAlertsData(data) {
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        const today = new Date();
        locationElement.textContent = data["0"]["locationName"];
        severityElement.textContent = `${new Date(data["0"]["openDate"]).toLocaleString()} ${data["0"]["severity"]}`
        alertTypeElement.textContent = data["0"]["alertType"];
        chargePointElement.textContent = data["0"]["equipmentId"].slice(9,);
        statusElement.textContent = data["0"]["status"];

        console.log(new Date(data["0"]["openDate"]).toLocaleString(options))
    }
})
</code>```

答: The Content-Type header in your request needs to be application/json not application

Body:
I have this web server setup with express, everything works fine except the req.body returns nothing it seems. I don't get any error it just doesn't do anything. The console.log(req.body) doesn't do anything. When I check the console I see nothing. But the rest of the application works ok.

What am I missing?

server.js file is below

if (process.env.NODE_ENV !== "production") {
    require("dotenv").config();
}

const clientId = process.env.client_id;
const clientSecret = process.env.client_secret;
const refreshToken = process.env.refresh_token;

const date = new Date();
date.setDate(date.getDate() - 2);

const express = require("express");
const app = express();

app.use(express.json());
app.use(express.static("public"));

app.post("/alerts", async (req, res) => {
    console.log(req.body)
    const alertsUrl = `https://www.g2smart.com/g2smart/api/alert?range=last7Days&cpo=${req.body.selection}&status=Opened&limit=100&page=1`
    const axios = require("axios");
    const oauth = require("axios-oauth-client");

    const getRefreshToken = oauth.client(axios.create(), {
        url: "https://www.g2smart.com/g2smart/api/oauth2/token",
        grant_type: "refresh_token",
        client_id: `${clientId}`,
        client_secret: `${clientSecret}`,
        refresh_token: `${refreshToken}`,
    });

    const auth = await getRefreshToken();

    axios({
        url: alertsUrl
            ,
        headers: {
            accept: "application/json, text/plain, */*",
            authorization: `Bearer ${auth["access_token"]}`,
        },
        responseType: "json",
    }).then((data) => res.json(data.data.items));
});

app.listen(process.env.port || 3000);

console.log("Running at Port 3000");

and here is the script.js below, where i have my fetch function.

const selectElement = document.querySelector('[data-cpo-select]')
const cpo = {
    france: "total_fr_hpc",
    netherlands: "total_nl_hpc",
    te61: "te61"}

selectElement.addEventListener("change", (event) => {
    const selection = event.target.value
    fetch("/alerts", {
        method: "POST",
        headers: {
            "Content-Type": "application",
            "Accept": "application/json",
        },
        body: JSON.stringify({
            selection: cpo[selection]
        })
    })
        .then((res) => res.json())
        .then((data) => {
            setAlertsData(data);
        });

    const alertTypeElement = document.querySelector("[data-alert-type]");
    const locationElement = document.querySelector("[data-location]");
    const statusElement = document.querySelector("[data-status]");
    const severityElement = document.querySelector("[data-severity]");
    const chargePointElement = document.querySelector("[data-charge-point]");

    function setAlertsData(data) {
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        const today = new Date();
        locationElement.textContent = data["0"]["locationName"];
        severityElement.textContent = `${new Date(data["0"]["openDate"]).toLocaleString()} ${data["0"]["severity"]}`
        alertTypeElement.textContent = data["0"]["alertType"];
        chargePointElement.textContent = data["0"]["equipmentId"].slice(9,);
        statusElement.textContent = data["0"]["status"];

        console.log(new Date(data["0"]["openDate"]).toLocaleString(options))
    }
})


问:
HLA recursive division errors with corresponding C code
Here is my errored hla program:
it always print nothing...
it should prompt user for two int8 integers and print the integer quotient after calling divideRec, increment the result with properly pushing and popping in stack aligns...cannot figure out where should I fix..

```<code>program prog1;

#include( "stdlib.hhf" );

static

n : int8 := 0;

d : int8 := 0;

procedure divideRec( numerator: int8; denominator : int8 ); @nodisplay; @noframe;
static

iReturnAddress : dword;

iResult : int8;

temp : int16;

iRegisterValue : dword;

begin divideRec;

mov( EBX, iRegisterValue );

pop( iReturnAddress );

pop( temp);

//junk

//this is denominator
pop( temp);
mov(temp,BX);
mov(BL, denominator);

//this is numerator

pop(temp);
mov(temp,BX);
mov(BL, numerator);

push(iReturnAddress);
push(iRegisterValue);

//subtask

mov(0,DH);

mov(numerator,AL);
cmp(AL,denominator);
jge recursiveCall;

recursiveCall:
mov(numerator,BL);
sub(denominator,BL);
mov(BL, numerator);
push(BX);
push(temp);
call divideRec;
inc(DH);

jmp ExitSequence;

ExitSequence:
pop(EBX);
ret();
end divideRec;

begin prog1;

stdout.put("Provide a numerator: ");
stdin.get(n);
stdout.put("Provide a denominator: ");
stdin.get(d);

//16-bits
//n
mov(0,BX);
mov(n,BL);
push(BX);
//d
mov(0,BX);
mov(d,BL);
push(BX);

mov(0,BX);
push(BX);
call divideRec;
stdout.put("divide( ",n,", ",d, ") = ");
stdout.puti8(DH);

end prog1;
</code>```

here is the corresponding c code:

```<code>

int main(){

int n, d;
printf("gimme a numerator:");
scanf("%d",&n);
 printf("gimme a denominator:");
scanf("%d",&d);
int result = divideRec(n,d);
printf("the quotient is %d", result);
return(0);
}

int divideRec(int numerator, int denominator){

int result = 0;
if(numerator>=denominator){
result = 1+(divideRec(numerator-denominator, denominator));

}
return(result);

}

</code>```

This program always ends up outputting with zeros or nothing. I believe there are something wrong with the stack align, pushes and pops that I can't figure out. please kindly offer some helps.

答:
ENVIRONMENT

HLA (High Level Assembler - HLABE back end, POLINK linker)
Version 2.16 build 4413 (prototype)

Windows 10

NOTE

There are several ways to go about correcting this problem and these examples could be improved.

Outside of learning and practice a recursive procedure is probably not the optimal solution for this problem. I recommend a more minimal solution utilizing idiv.

EXAMPLES

Minimal

```<code>program minimal;
#include("stdlib.hhf");

static
numerator : int8 := 0;
denominator : int8 := 0;

begin minimal;
    stdout.put("Provide a numerator: ");
    stdin.get(numerator);
    stdout.put("Provide a denominator: ");
    stdin.get(denominator);

    mov(0, EAX);        // Clear numerator
    mov(numerator, AL); // Set numerator
    idiv(denominator);  // Divide AX by denominator
    stdout.put("divide(", numerator, ", ", denominator, ") = ");
    stdout.puti8(AL);   // Quotient is in AL
end minimal;
</code>```

Procedure

```<code>program function;
#include("stdlib.hhf");

static
numerator : int8 := 0;
denominator : int8 := 0;

procedure divide(numerator: int8; denominator: int8);
begin divide;
    mov(0, EAX);        // Clear numerator
    mov(numerator, AL); // Set numerator
    idiv(denominator);  // Divide AX by denominator
end divide;

begin function;
    stdout.put("Provide a numerator: ");
    stdin.get(numerator);
    stdout.put("Provide a denominator: ");
    stdin.get(denominator);

    mov(0, EBX);
    mov(numerator, BL);
    push(EBX);

    mov(0, EBX);
    mov(denominator, BL);
    push(EBX);

    call divide;
    stdout.put("divide(", numerator, ", ", denominator, ") = ");
    stdout.puti8(AL); // Quotient is in AL
end function;
</code>```

Recursive

```<code>program recursive;
#include("stdlib.hhf");

static
numerator : int8 := 0;
denominator : int8 := 0;
value : int8 := 0;

procedure divideRec(numerator: int8; denominator : int8; value : int8);
begin divideRec;
    mov(0, EAX);
    mov(numerator, AL);
    cmp(AL, denominator);
    je ret_val_plus_1;
    jl ret_val;
    mov(0, EDX);
    sub(denominator, AL);
    cmp(AL, DL);
    jg recurse;
    jmp done;

    ret_val_plus_1:
        inc(value);
        jmp done;

    ret_val:
        jmp done;

    recurse:
        inc(value);

        mov(0, EBX);
        mov(AL, BL);
        push(EBX);

        mov(0, EBX);
        mov(denominator, BL);
        push(EBX);

        mov(0, EBX);
        mov(value, BL);
        push(EBX);

        call divideRec;
        mov(AL, value);
        jmp done;

    done:
        mov(0, EAX);
        mov(value, AL);
end divideRec;

begin recursive;
    stdout.put("Provide a numerator: ");
    stdin.get(numerator);
    stdout.put("Provide a denominator: ");
    stdin.get(denominator);

    mov(0, EBX);
    mov(numerator,BL);
    push(EBX);

    mov(0, EBX);
    mov(denominator,BL);
    push(EBX);

    mov(0, EBX);
    push(EBX);

    call divideRec;

    stdout.put("divide(", numerator, ", ", denominator, ") = ");
    stdout.puti8(AL);
end recursive;
</code>```

Error Handling

```<code>program error_handling;
#include("stdlib.hhf");

static
    numerator : int8 := 0;
    denominator : int8 := 0;

begin error_handling;
    forever
        try
            stdout.put("Provide a numerator: ");
            stdin.get(numerator);
            stdout.put("Provide a denominator: ");
            stdin.get(denominator);

            xor(EAX, EAX);        // Clear numerator
            mov(numerator, AL);       // Set numerator
            idiv(denominator);  // Divide AX by denominator
            stdout.put("divide(", numerator, ", ", denominator, ") = ");
            stdout.puti8(AL);

        unprotected
            break;

        exception(ex.ValueOutOfRange)
            stdout.put("Number entered is out of range: -128 to 127", nl);

        exception(ex.ConversionError)
            stdout.put("Input contained illegal characters.", nl);

        exception(ex.DivideError)
            stdout.put("Attempted illegal division: e.g. Divide by Zero", nl);

        anyexception
            stdout.put("An unknown error occurred with code: ", EAX, nl);

        endtry;
    endfor;
end error_handling;
</code>```

Body:
Here is my errored hla program:
it always print nothing...
it should prompt user for two int8 integers and print the integer quotient after calling divideRec, increment the result with properly pushing and popping in stack aligns...cannot figure out where should I fix..

program prog1;

#include( "stdlib.hhf" );

static

n : int8 := 0;

d : int8 := 0;

procedure divideRec( numerator: int8; denominator : int8 ); @nodisplay; @noframe;
static

iReturnAddress : dword;

iResult : int8;

temp : int16;

iRegisterValue : dword;

begin divideRec;

mov( EBX, iRegisterValue );

pop( iReturnAddress );

pop( temp);

//junk

//this is denominator
pop( temp);
mov(temp,BX);
mov(BL, denominator);

//this is numerator

pop(temp);
mov(temp,BX);
mov(BL, numerator);

push(iReturnAddress);
push(iRegisterValue);

//subtask

mov(0,DH);

mov(numerator,AL);
cmp(AL,denominator);
jge recursiveCall;

recursiveCall:
mov(numerator,BL);
sub(denominator,BL);
mov(BL, numerator);
push(BX);
push(temp);
call divideRec;
inc(DH);

jmp ExitSequence;

ExitSequence:
pop(EBX);
ret();
end divideRec;

begin prog1;

stdout.put("Provide a numerator: ");
stdin.get(n);
stdout.put("Provide a denominator: ");
stdin.get(d);

//16-bits
//n
mov(0,BX);
mov(n,BL);
push(BX);
//d
mov(0,BX);
mov(d,BL);
push(BX);

mov(0,BX);
push(BX);
call divideRec;
stdout.put("divide( ",n,", ",d, ") = ");
stdout.puti8(DH);

end prog1;

here is the corresponding c code:

int main(){

int n, d;
printf("gimme a numerator:");
scanf("%d",&n);
 printf("gimme a denominator:");
scanf("%d",&d);
int result = divideRec(n,d);
printf("the quotient is %d", result);
return(0);
}

int divideRec(int numerator, int denominator){

int result = 0;
if(numerator>=denominator){
result = 1+(divideRec(numerator-denominator, denominator));

}
return(result);

}

This program always ends up outputting with zeros or nothing. I believe there are something wrong with the stack align, pushes and pops that I can't figure out. please kindly offer some helps.

Body:
ENVIRONMENT

HLA (High Level Assembler - HLABE back end, POLINK linker)
Version 2.16 build 4413 (prototype)

Windows 10

NOTE

There are several ways to go about correcting this problem and these examples could be improved.

Outside of learning and practice a recursive procedure is probably not the optimal solution for this problem. I recommend a more minimal solution utilizing idiv.

EXAMPLES

Minimal

program minimal;
#include("stdlib.hhf");

static
numerator : int8 := 0;
denominator : int8 := 0;

begin minimal;
    stdout.put("Provide a numerator: ");
    stdin.get(numerator);
    stdout.put("Provide a denominator: ");
    stdin.get(denominator);

    mov(0, EAX);        // Clear numerator
    mov(numerator, AL); // Set numerator
    idiv(denominator);  // Divide AX by denominator
    stdout.put("divide(", numerator, ", ", denominator, ") = ");
    stdout.puti8(AL);   // Quotient is in AL
end minimal;

Procedure

program function;
#include("stdlib.hhf");

static
numerator : int8 := 0;
denominator : int8 := 0;

procedure divide(numerator: int8; denominator: int8);
begin divide;
    mov(0, EAX);        // Clear numerator
    mov(numerator, AL); // Set numerator
    idiv(denominator);  // Divide AX by denominator
end divide;

begin function;
    stdout.put("Provide a numerator: ");
    stdin.get(numerator);
    stdout.put("Provide a denominator: ");
    stdin.get(denominator);

    mov(0, EBX);
    mov(numerator, BL);
    push(EBX);

    mov(0, EBX);
    mov(denominator, BL);
    push(EBX);

    call divide;
    stdout.put("divide(", numerator, ", ", denominator, ") = ");
    stdout.puti8(AL); // Quotient is in AL
end function;

Recursive

program recursive;
#include("stdlib.hhf");

static
numerator : int8 := 0;
denominator : int8 := 0;
value : int8 := 0;

procedure divideRec(numerator: int8; denominator : int8; value : int8);
begin divideRec;
    mov(0, EAX);
    mov(numerator, AL);
    cmp(AL, denominator);
    je ret_val_plus_1;
    jl ret_val;
    mov(0, EDX);
    sub(denominator, AL);
    cmp(AL, DL);
    jg recurse;
    jmp done;

    ret_val_plus_1:
        inc(value);
        jmp done;

    ret_val:
        jmp done;

    recurse:
        inc(value);

        mov(0, EBX);
        mov(AL, BL);
        push(EBX);

        mov(0, EBX);
        mov(denominator, BL);
        push(EBX);

        mov(0, EBX);
        mov(value, BL);
        push(EBX);

        call divideRec;
        mov(AL, value);
        jmp done;

    done:
        mov(0, EAX);
        mov(value, AL);
end divideRec;

begin recursive;
    stdout.put("Provide a numerator: ");
    stdin.get(numerator);
    stdout.put("Provide a denominator: ");
    stdin.get(denominator);

    mov(0, EBX);
    mov(numerator,BL);
    push(EBX);

    mov(0, EBX);
    mov(denominator,BL);
    push(EBX);

    mov(0, EBX);
    push(EBX);

    call divideRec;

    stdout.put("divide(", numerator, ", ", denominator, ") = ");
    stdout.puti8(AL);
end recursive;

Error Handling

program error_handling;
#include("stdlib.hhf");

static
    numerator : int8 := 0;
    denominator : int8 := 0;

begin error_handling;
    forever
        try
            stdout.put("Provide a numerator: ");
            stdin.get(numerator);
            stdout.put("Provide a denominator: ");
            stdin.get(denominator);

            xor(EAX, EAX);        // Clear numerator
            mov(numerator, AL);       // Set numerator
            idiv(denominator);  // Divide AX by denominator
            stdout.put("divide(", numerator, ", ", denominator, ") = ");
            stdout.puti8(AL);

        unprotected
            break;

        exception(ex.ValueOutOfRange)
            stdout.put("Number entered is out of range: -128 to 127", nl);

        exception(ex.ConversionError)
            stdout.put("Input contained illegal characters.", nl);

        exception(ex.DivideError)
            stdout.put("Attempted illegal division: e.g. Divide by Zero", nl);

        anyexception
            stdout.put("An unknown error occurred with code: ", EAX, nl);

        endtry;
    endfor;
end error_handling;


问:
how can i extract this value from a website, with python, selenium and chromedriver
```<code><div class="flexible row ng-scope">
    <!-- ngRepeat: graph in graphs track by $index --><figure class="figure-gauge flexible column ng-scope" data-ng-repeat="graph in graphs track by $index">
        <figcaption class="rigid">
            <div class="data-value">
                <b class="ng-binding">
                    334
                </b>
            </div>
</code>```

I need to extract the value (334) that appears, i take this from Chrome Web Inspector . I am using python and selenium, I have tried with many codes but none has worked for me, I appreciate any help.

I try whit this:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options

DRIVER_PATH = r'C:\chromedriver.exe'
options = Options()
options.headless = True
options.add_argument("--window-size=1920,1200")

driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH)
driver.get("https://iot.app.initialstate.com/embed/#/tiles/bkt_kb448kawjvmhe")
data = driver.find_element_by_class_name('ng-binding')
print
driver.quit()
</code>```

Error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".ng-binding"}
(Session info: headless chrome=83.0.4103.61)

Selenium 3.141.0
Python 3.8

答:
You can extract it using xpath</p>

```<code>val = driver.find_element_by_xpath('/html/body/div[1]/article/div[2]/div/div/div[1]/article/div/figure/figcaption/div/b').text
print(val)
</code>```

Body:
                    334

I need to extract the value (334) that appears, i take this from Chrome Web Inspector . I am using python and selenium, I have tried with many codes but none has worked for me, I appreciate any help.

I try whit this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

DRIVER_PATH = r'C:\chromedriver.exe'
options = Options()
options.headless = True
options.add_argument("--window-size=1920,1200")

driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH)
driver.get("https://iot.app.initialstate.com/embed/#/tiles/bkt_kb448kawjvmhe")
data = driver.find_element_by_class_name('ng-binding')
print
driver.quit()

Error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".ng-binding"}
(Session info: headless chrome=83.0.4103.61)

Selenium 3.141.0
Python 3.8

Body:
You can extract it using xpath

val = driver.find_element_by_xpath('/html/body/div[1]/article/div[2]/div/div/div[1]/article/div/figure/figcaption/div/b').text
print(val)


问:
How to replace those entries in a column which have parenthesis or numbers included with them in a pandas dataframe?
```<code>I have a dataframe like this:
    Country                  Energy Supply      Energy Supply per Capita
16  Afghanistan              3.210000e+08       10.0
17  Albania                  1.020000e+08       35.0
18  Algeria                  1.959000e+09       51.0
19  American Samoa           NaN
40  Bolivia
   (Plurinational State of)  3.360000e+08       32.0
... ... ... ...
213 Switzerland17            1.113000e+09       136.0
214 Syrian Arab Republic     5.420000e+08       28.0
215 Tajikistan               1.060000e+08       13.0
216 Thailand                 5.336000e+09       79.0
228 Ukraine18                4.844000e+09       107.0
232 United States of
    America20                9.083800e+10       286.0
</code>```

I needed to replace name of all those countries which are having parenthesis or numbers in their name. For example: 'Bolivia (Plurinational State of)' should be 'Bolivia','Switzerland17' should be 'Switzerland' and 'United States of America20' should be 'United States of America'.
I tried this using replace() and split() but nothing worked out for me.

Can somebody please help me with this.

答:
```<code>df.Country = df.Country.str.extract(r"([^(\d]+)")
</code>```

<blockquote>
```<code>      Country              Energy Supply     Energy Supply per Capita
16   Afghanistan           3.210000e+08     10.0
17   Albania               1.020000e+08     35.0
18   Algeria               1.959000e+09     51.0
19   American Samoa                 NaN     NaN
40   Bolivia               3.360000e+08     32.0
213  Switzerland           1.113000e+09     136.0
214  Syrian Arab Republic  5.420000e+08     28.0
215  Tajikistan            1.060000e+08     13.0
216  Thailand              5.336000e+09     79.0
228  Ukraine               4.844000e+09     107.0
</code>```
</blockquote>

Body:
I have a dataframe like this:
    Country                  Energy Supply      Energy Supply per Capita
16  Afghanistan              3.210000e+08       10.0
17  Albania                  1.020000e+08       35.0
18  Algeria                  1.959000e+09       51.0
19  American Samoa           NaN
40  Bolivia
   (Plurinational State of)  3.360000e+08       32.0
... ... ... ...
213 Switzerland17            1.113000e+09       136.0
214 Syrian Arab Republic     5.420000e+08       28.0
215 Tajikistan               1.060000e+08       13.0
216 Thailand                 5.336000e+09       79.0
228 Ukraine18                4.844000e+09       107.0
232 United States of
    America20                9.083800e+10       286.0

I needed to replace name of all those countries which are having parenthesis or numbers in their name. For example: 'Bolivia (Plurinational State of)' should be 'Bolivia','Switzerland17' should be 'Switzerland' and 'United States of America20' should be 'United States of America'.
I tried this using replace() and split() but nothing worked out for me.

Can somebody please help me with this.

Body:
df.Country = df.Country.str.extract(r"([^(\d]+)")

      Country              Energy Supply     Energy Supply per Capita
16   Afghanistan           3.210000e+08     10.0
17   Albania               1.020000e+08     35.0
18   Algeria               1.959000e+09     51.0
19   American Samoa                 NaN     NaN
40   Bolivia               3.360000e+08     32.0
213  Switzerland           1.113000e+09     136.0
214  Syrian Arab Republic  5.420000e+08     28.0
215  Tajikistan            1.060000e+08     13.0
216  Thailand              5.336000e+09     79.0
228  Ukraine               4.844000e+09     107.0


问:
IBM Websphere portlet classloader issue
I am currently working on a portlet that is using the commons-collections jar file and am getting a NoSuchMethodError. To resolve this issue I need to change the classloader of my WAR file from PARENT_FIRST to PARENT_LAST (in the application.xml file).

However, when I do this my portlet will not launch and when I log into the console it displays the message "The portlet is temporarily disabled". If I change the classloader back to PARENT_FIRST then it will launch again but then I get the NoSuchMethodError.

Does anybody have any suggestions on how to fix this issue ?

答: I am not sure how, but today I started getting error messages in the logs when I was getting "The portlet is temporarily disabled". I was getting a java.lang.LinkageError which was down to the fact that I had the servlet-api-2.5.jar and a jaxb jar which was conflicting with webshpere j2ee.jar. Once I removed these dependencies and set the classloader to PARENT_LAST, it seems to work properly. It seems that a lot of people face similar issues. The link below is also useful http://forum.springsource.org/showthread.php?33663-dispatcher-servlet-quot-not-a-servlet-class-quot-in-websphere</p>

Title: IBM Websphere portlet classloader issue


问:
How do i remove blue color from selected rows in aggrid

I'm trying to remove the blue color to the selected rows.

答:
you can do it easily in CSS

The selected row has class .ag-row-selected and you should override native style

Use the next style:

```<code>.ag-row-selected {
    background-color: unset !important;
}
</code>```

I just added style in index.html

here result:

WORKING EXAMPLE: https://plnkr.co/edit/JOKkg1LcjihbCZSi

Body:
you can do it easily in CSS

The selected row has class .ag-row-selected and you should override native style

Use the next style:

.ag-row-selected {
    background-color: unset !important;
}

I just added style in index.html

here result:

WORKING EXAMPLE: https://plnkr.co/edit/JOKkg1LcjihbCZSi


问:
Wrong use of GROUP BY
i'm having a real problem with a query. The database entity are:

```<code>Paziente (Codice_Fiscale, Nome_Paziente, Cognome_Paziente, Data_Nascita, Luogo_Nascita)
Appuntamento (Codice_Appuntamento, Data_Appuntamento, Ora_Appuntamento, Codice_Fiscale)
Intervento (Codice_Intervento, Tipo_Intervento, Sala_Intervento, Data_Intervento, Ora_Intervento, Codice_Fiscale_Paziente, ID_Dentista)
Dentista (ID_Dentista, Nome_Dentista, Cognome_Dentista)
</code>```

I need to do a query that shows a list of appointment grouped by type of intervention.
It should be something like:

```<code>Tipo_Intervento       COUNT(*)
Chirurgia dentale      1
Cura carie             2
Estrazione dentale     1
Pulizia dentale        3
</code>```

I can do this correctly when i use this query:

```<code>SELECT intervento.Tipo_Intervento, COUNT(*)
FROM intervento
GROUP BY intervento.Tipo_Intervento
</code>```

But i need to link the database "intervento" to "appuntamento" ('cause it's an exercise) and when i use this:

```<code>SELECT COUNT(DISTINCT appuntamento.Codice_Appuntamento) AS Numero_Appuntamenti, intervento.Tipo_Intervento AS Tipologia_intervento
FROM appuntamento, intervento
WHERE appuntamento.Codice_Fiscale = intervento.Codice_Fiscale_Paziente
GROUP BY intervento.Tipo_Intervento
</code>```

I obtain the wrong value:

```<code>Numero_Appuntamenti      Tipologia_intervento
2                        Chirurgia dentale
4                        Cura carie
2                        Estrazione dentale
3                        Pulizia dentale
</code>```

The problem is in the GROUP BY intervento.Tipo_Intervento, that increase the number of appointments, in fact if i use GROUP BY appuntamento.Codice_Appuntamento i obtain:

```<code>Numero_Appuntamenti  Tipologia_intervento
1                    Pulizia dentale
1                    Estrazione dentale
1                    Pulizia dentale
1                    Cura carie
1                    Cura carie
1                    Pulizia dentale
1                    Estrazione dentale
</code>```

That is right, but i need it to be grouped.

Does someone can help me? (forgive my bad english, as you can see it's not my language)

EDIT: This is the table "appuntamento":

```<code>Codice_Appuntamento Data_Appuntamento   Ora_Appuntamento    Codice_Fiscale
        001           2020-05-05    16:00:00.000000     RSSMRA80A01H501U
        002           2020-07-03    16:30:00.000000     VRDGPP85E02F205P
        003          2020-06-05     16:00:00.000000     RSSMRA80A01H501U
        004          2020-08-14     17:15:00.000000     BNCGNN83D03L219B
        005           2020-08-27    17:45:00.000000     BNCGNN83D03L219B
        006          2020-07-05     16:00:00.000000     RSSMRA80A01H501U
        007          2020-09-13     17:20:00.000000     VRDGPP85E02F205P
</code>```

And this the table "intervento"

```<code>Codice_Intervento Tipo_Intervento   Sala_Intervento    Data_Intervento   Ora_Intervento   Codice_Fiscale_Paziente   ID_Dentista
    A_001          Pulizia dentale        1             2020-05-05       16:00:00.000000    RSSMRA80A01H501U            D_001
    A_002          Estrazione dentale     2             2020-07-03        16:30:00.000000   VRDGPP85E02F205P            D_003
    A_003          Pulizia dentale        1             2020-06-05        16:00:00.000000   RSSMRA80A01H501U            D_001
    A_004          Cura carie             3             2020-08-14        17:15:00.000000   BNCGNN83D03L219B            D_001
    A_005          Chirurgia dentale      5             2020-08-27        17:45:00.000000   BNCGNN83D03L219B            D_002
    A_006          Pulizia dentale        1             2020-07-05        16:00:00.000000   RSSMRA80A01H501U            D_001
    A_007          Cura carie             3             2020-09-13         17:20:00.000000  VRDGPP85E02F205P            D_002
</code>```

"Codice fiscale" and "ID_Dentista" are the foreing key, thery are the primary key of "paziente" and "dentista"

答:
COUNT(DISTINCT field) returns how many unique [appuntamento].[Codice_Appuntamento] are found for each [intervento].[Tipo_Intervento]. If I read your question right, you just want to remove the DISTINCT.

That should work if you use a LEFT JOIN. Your way of putting together tables rule out any [appuntamento] without a [intervento]

SELECT COUNT(appuntamento.Codice_Appuntamento) AS Numero_Appuntamenti, intervento.Tipo_Intervento AS Tipologia_intervento
FROM appuntamento
LEFT JOIN intervento ON appuntamento.Codice_Fiscale = intervento.Codice_Fiscale_Paziente
GROUP BY intervento.Tipo_Intervento
```

Title: Wrong use of GROUP BY

Body:
i'm having a real problem with a query. The database entity are:

Paziente (Codice_Fiscale, Nome_Paziente, Cognome_Paziente, Data_Nascita, Luogo_Nascita)
Appuntamento (Codice_Appuntamento, Data_Appuntamento, Ora_Appuntamento, Codice_Fiscale)
Intervento (Codice_Intervento, Tipo_Intervento, Sala_Intervento, Data_Intervento, Ora_Intervento, Codice_Fiscale_Paziente, ID_Dentista)
Dentista (ID_Dentista, Nome_Dentista, Cognome_Dentista)

I need to do a query that shows a list of appointment grouped by type of intervention.
It should be something like:

Tipo_Intervento       COUNT(*)
Chirurgia dentale      1
Cura carie             2
Estrazione dentale     1
Pulizia dentale        3

I can do this correctly when i use this query:

SELECT intervento.Tipo_Intervento, COUNT(*)
FROM intervento
GROUP BY intervento.Tipo_Intervento

But i need to link the database "intervento" to "appuntamento" ('cause it's an exercise) and when i use this:

SELECT COUNT(DISTINCT appuntamento.Codice_Appuntamento) AS Numero_Appuntamenti, intervento.Tipo_Intervento AS Tipologia_intervento
FROM appuntamento, intervento
WHERE appuntamento.Codice_Fiscale = intervento.Codice_Fiscale_Paziente
GROUP BY intervento.Tipo_Intervento

I obtain the wrong value:

Numero_Appuntamenti      Tipologia_intervento
2                        Chirurgia dentale
4                        Cura carie
2                        Estrazione dentale
3                        Pulizia dentale

The problem is in the GROUP BY intervento.Tipo_Intervento, that increase the number of appointments, in fact if i use GROUP BY appuntamento.Codice_Appuntamento i obtain:

Numero_Appuntamenti  Tipologia_intervento
1                    Pulizia dentale
1                    Estrazione dentale
1                    Pulizia dentale
1                    Cura carie
1                    Cura carie
1                    Pulizia dentale
1                    Estrazione dentale

That is right, but i need it to be grouped.

Does someone can help me? (forgive my bad english, as you can see it's not my language)

EDIT: This is the table "appuntamento":

Codice_Appuntamento Data_Appuntamento   Ora_Appuntamento    Codice_Fiscale
        001           2020-05-05    16:00:00.000000     RSSMRA80A01H501U
        002           2020-07-03    16:30:00.000000     VRDGPP85E02F205P
        003          2020-06-05     16:00:00.000000     RSSMRA80A01H501U
        004          2020-08-14     17:15:00.000000     BNCGNN83D03L219B
        005           2020-08-27    17:45:00.000000     BNCGNN83D03L219B
        006          2020-07-05     16:00:00.000000     RSSMRA80A01H501U
        007          2020-09-13     17:20:00.000000     VRDGPP85E02F205P

And this the table "intervento"

Codice_Intervento Tipo_Intervento   Sala_Intervento    Data_Intervento   Ora_Intervento   Codice_Fiscale_Paziente   ID_Dentista
    A_001          Pulizia dentale        1             2020-05-05       16:00:00.000000    RSSMRA80A01H501U            D_001
    A_002          Estrazione dentale     2             2020-07-03        16:30:00.000000   VRDGPP85E02F205P            D_003
    A_003          Pulizia dentale        1             2020-06-05        16:00:00.000000   RSSMRA80A01H501U            D_001
    A_004          Cura carie             3             2020-08-14        17:15:00.000000   BNCGNN83D03L219B            D_001
    A_005          Chirurgia dentale      5             2020-08-27        17:45:00.000000   BNCGNN83D03L219B            D_002
    A_006          Pulizia dentale        1             2020-07-05        16:00:00.000000   RSSMRA80A01H501U            D_001
    A_007          Cura carie             3             2020-09-13         17:20:00.000000  VRDGPP85E02F205P            D_002

"Codice fiscale" and "ID_Dentista" are the foreing key, thery are the primary key of "paziente" and "dentista"