问:
How can I run a command in a separate terminal using sudo without further user interaction
I am trying to automate the running of several tasks, but I need to run them as sudo.

I want to run them in separate terminals so I can watch the output of each.

Here is a sort of minimal example I have setup (because what I am trying to do is more complicated)

Setup two files - note that data is readable as root only and contains 3 lines of example text:

```<code>-rw------- 1 root    root      33 Nov 15 09:29 data
-rwxrwxrwx 1 root    root      11 Nov 15 09:30 test.sh*
</code>```

test.sh looks like:

```<code>#!/bin/bash
cat data
read -p "Press enter to continue"
</code>```

Also I have user level variable called "SESSION_MANAGER" that is setup in the bash startup... which seems to cause some issues (see later example)

So now I want to spawn various terminals running this script. I tried the following:

Attempt 1

```<code>xfce4-terminal -e './test.sh'
</code>```

output:

```<code>cat: data: Permission denied
Press enter to continue
</code>```

Attempt 2 - using sudo at the start

```<code>~/src/sandbox$ sudo xfce4-terminal -e './test.sh'
Failed to connect to session manager: Failed to connect to the session manager: SESSION_MANAGER environment variable not defined

(xfce4-terminal:6755): IBUS-WARNING **: The owner of /home/openbts/.config/ibus/bus is not root!
</code>```

output:

```<code>this is some data
more data
end
Press enter to continue
</code>```

here you can see that the output of the data file is print ok, but I had some issue with the session manager variable.

Attempt 3 - using sudo in the command

```<code>~/src/sandbox$ xfce4-terminal -e 'sudo ./test.sh'
</code>```

output:

[sudo] password for openbts:
this is some data
more data
end
Press enter to continue

here you can see that everything was well... but I had to enter my password again, which somewhat kills my automation :(

Attempt 4 - start as root

```<code>~/src/sandbox$ sudo su
root@openbts:/home/openbts/src/sandbox# xfce4-terminal -e './test.sh'
Failed to connect to session manager: Failed to connect to the session manager: SESSION_MANAGER environment variable not defined
</code>```

output:

```<code>this is some data
more data
end
Press enter to continue
</code>```

Here, again the output looks good, but I have this SESSION_MANAGER issue... Also the new xfce4-terminal comes out with messed up font/look - I guess this is the root users settings.

Questions

How can I run multiple instances of test.sh each in a new terminal and not have to enter passwords (or interact at all). I can enter the password once at the start of the process (in the original terminal)?

As you can see I got this sort-of working when going in a sudo su, but this issues here are the SESSION_MANAGER variable - not sure if that is an issue, but its very messy looking, but also the xcfe4-terminal looks bad (I guess I can change the root settings to the same as my user settings). So how can I avoid the SESSION_MANAGER issue when running as root?

答:
If you change user-id before you launch your separate terminal, you will see the session-manager issue. So the solution is to run the sudo in the terminal.

You do not want to type passwords in the sudo. You can do that by adding

```<code>yourname ALL=(ALL) NOPASSWD: ALL
</code>```

to /etc/sudoers (at least on slackware). You could also try to set the permissions on the files correct so you would not need root all the time.

Note that adding that line has security implications; you might want to allow just cat without password (in your example), or make even more elaborate rules for sudo. The line I gave is just an example. Personally, I would look at file-permissions.

Body:
I am trying to automate the running of several tasks, but I need to run them as sudo.

I want to run them in separate terminals so I can watch the output of each.

Here is a sort of minimal example I have setup (because what I am trying to do is more complicated)

Setup two files - note that data is readable as root only and contains 3 lines of example text:

-rw------- 1 root    root      33 Nov 15 09:29 data
-rwxrwxrwx 1 root    root      11 Nov 15 09:30 test.sh*

test.sh looks like:

#!/bin/bash
cat data
read -p "Press enter to continue"

Also I have user level variable called "SESSION_MANAGER" that is setup in the bash startup... which seems to cause some issues (see later example)

So now I want to spawn various terminals running this script. I tried the following:

Attempt 1

xfce4-terminal -e './test.sh'

output:

cat: data: Permission denied
Press enter to continue

Attempt 2 - using sudo at the start

~/src/sandbox$ sudo xfce4-terminal -e './test.sh'
Failed to connect to session manager: Failed to connect to the session manager: SESSION_MANAGER environment variable not defined

(xfce4-terminal:6755): IBUS-WARNING **: The owner of /home/openbts/.config/ibus/bus is not root!

output:

this is some data
more data
end
Press enter to continue

here you can see that the output of the data file is print ok, but I had some issue with the session manager variable.

Attempt 3 - using sudo in the command

~/src/sandbox$ xfce4-terminal -e 'sudo ./test.sh'

output:

[sudo] password for openbts:
this is some data
more data
end
Press enter to continue

here you can see that everything was well... but I had to enter my password again, which somewhat kills my automation :(

Attempt 4 - start as root

~/src/sandbox$ sudo su
root@openbts:/home/openbts/src/sandbox# xfce4-terminal -e './test.sh'
Failed to connect to session manager: Failed to connect to the session manager: SESSION_MANAGER environment variable not defined

output:

this is some data
more data
end
Press enter to continue

Here, again the output looks good, but I have this SESSION_MANAGER issue... Also the new xfce4-terminal comes out with messed up font/look - I guess this is the root users settings.

Questions

How can I run multiple instances of test.sh each in a new terminal and not have to enter passwords (or interact at all). I can enter the password once at the start of the process (in the original terminal)?

As you can see I got this sort-of working when going in a sudo su, but this issues here are the SESSION_MANAGER variable - not sure if that is an issue, but its very messy looking, but also the xcfe4-terminal looks bad (I guess I can change the root settings to the same as my user settings). So how can I avoid the SESSION_MANAGER issue when running as root?

Body:
If you change user-id before you launch your separate terminal, you will see the session-manager issue. So the solution is to run the sudo in the terminal.

You do not want to type passwords in the sudo. You can do that by adding

yourname ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers (at least on slackware). You could also try to set the permissions on the files correct so you would not need root all the time.

Note that adding that line has security implications; you might want to allow just cat without password (in your example), or make even more elaborate rules for sudo. The line I gave is just an example. Personally, I would look at file-permissions.


来源: stackexchange

问:
Transaction Management for Shared DB in Microservices
I have 2 Microservices that using same DB

First Microserivce for Balance Management .

Second Microserivce for Reservation Management.

And I have the following business scenario:

Need to check if the client have balance by calling REST Services from (Balance Management Microservice).

If he have balance , then I have to call another REST Services to reserved the balance from (Balance Management Microservice ) .

Then I have to do some kind of airline reservation also by calling another REST Service from (Reservation Management).

So the question is how to rollback the step 2 if the step 3 fail by using Transaction Management between REST Services by taking care that all Microservice using same DB

答: As usual when we have this kind of issues we should look into existing best practice. In this case, SAGAs design pattern is the answer to your question.</p>

ContentLicense: CC BY-SA 3.0


问:
How to use "Pull to refresh" in top and (at the same time) in bottom in a FlatList in React Native?
I need in my React-Native app to have a Pull to refresh on the top of my FlatList and at the same time a Pull to refresh in the bottom of that FlatList. I can use refreshControl to use it at the top but I don't know what to do to put it in both top and bottom.</p>

答:
The FlatList component has predefined functions for that. As i understand you want to be able to refresh via pull to refresh and when you are reaching the end of the list? If so, you can do the following: </p>

```<code>handleRefresh = () => {
//make api calls
};
</code>```

<p> </p>

```<code><FlatList
   data={yourData}
   onRefresh{this.handleRefresh} // handle pull to refresh
   onEndReached={this.handleRefresh} // handle refresh
   onEndReachedThreshold={1} // refresh as soon as the end of the list is reached. Probably you have to play around with this value
   ListFooterComponent={this.renderFooter(this.props.loading)} // show activity indicator
/>
</code>```

Body:
The FlatList component has predefined functions for that. As i understand you want to be able to refresh via pull to refresh and when you are reaching the end of the list? If so, you can do the following:

handleRefresh = () => {
//make api calls
};

<FlatList
   data={yourData}
   onRefresh{this.handleRefresh} // handle pull to refresh
   onEndReached={this.handleRefresh} // handle refresh
   onEndReachedThreshold={1} // refresh as soon as the end of the list is reached. Probably you have to play around with this value
   ListFooterComponent={this.renderFooter(this.props.loading)} // show activity indicator
/>


问:
CSS Sprites for Images of Zoomable Elements
I have an html portion of code that contain images. The images can be resized/zoomed in html by simply changing their size (width and height). I want to replace the images with CSS Sprites(to load a single file instead of many). The problem is that if I have a background to a div, if I change the div size the image in the background is not resized.

Do you know a way to achieve it? Is there a way that works on most browsers to load cropped images portions from an image and then to resize them as I would do with a simple image?

Later Edit: The image(s) should be loaded only once and the resize should be performed on client size to provide the user a better view when moves the mouse over image.

答:
In your specific use case pure CSS Sprites isn't going to work and building complex javascript to chop up the sprite image is going to cause more overhead than just loading the images individually.

Not really an answer but your use case goes way beyond what the CSS sprites technique can do.  If you can give some more context as to what your application does (ie. purpose of resizing, is resize happening serverside/clientside, ..etc.) there might be other solutions that will speed up the loading of the site.

ContentLicense: CC BY-SA 2.5


问:
How to test if a controller method forwards the requests to a specific URL?
In my Spring Boot application I have the following controller with a single method that redirects all HTML5 routes to the root URL**:

```<code>@Controller
public class RedirectController {

  @RequestMapping(value = "/**/{path:[^\\.]*}")
  public String redirect() {
    return "forward:/";
  }
}
</code>```

How should I properly test that it works as expected?

Calling the content() method of the MockMvcResultMatchers class doesn't work:

```<code>  @Test
  public void givenPathWithoutDotShouldReturnString() throws Exception {
    this.mockMvc.perform(get("/somePath"))
        .andExpect(content().string("forward:/"));
  }

>>> java.lang.AssertionError: Response content
>>> Expected :forward:/
>>> Actual   :
</code>```

** I found out about this solution from following this Spring tutorial.

答:
When I called the andDo(print()) of the mockMvc class I got the following result:

```<code>MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body =
    Forwarded URL = /
   Redirected URL = null
          Cookies = []
</code>```

Here I realized that Spring doesn't treat return "forward:/"; as a simple String result, but a URL forwarding (in a way it's pretty obvious), so the proper way to write the test is by calling the .andExpect() method with forwardedUrl("/") as an argument:

```<code>  @Test
  public void givenPathWithoutDotShouldReturnString() throws Exception {
    this.mockMvc.perform(get("/somePath"))
        .andExpect(forwardedUrl("/"));
  }
</code>```

The forwardedUrl() method comes from org.springframework.test.web.servlet.result.MockMvcResultMatchers.

Body:
In my Spring Boot application I have the following controller with a single method that redirects all HTML5 routes to the root URL**:

@Controller
public class RedirectController {

  @RequestMapping(value = "/**/{path:[^\\.]*}")
  public String redirect() {
    return "forward:/";
  }
}

How should I properly test that it works as expected?

Calling the content() method of the MockMvcResultMatchers class doesn't work:

  @Test
  public void givenPathWithoutDotShouldReturnString() throws Exception {
    this.mockMvc.perform(get("/somePath"))
        .andExpect(content().string("forward:/"));
  }

>>> java.lang.AssertionError: Response content
>>> Expected :forward:/
>>> Actual   :

** I found out about this solution from following this Spring tutorial.

Body:
When I called the andDo(print()) of the mockMvc class I got the following result:

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body =
    Forwarded URL = /
   Redirected URL = null
          Cookies = []

Here I realized that Spring doesn't treat return "forward:/"; as a simple String result, but a URL forwarding (in a way it's pretty obvious), so the proper way to write the test is by calling the .andExpect() method with forwardedUrl("/") as an argument:

  @Test
  public void givenPathWithoutDotShouldReturnString() throws Exception {
    this.mockMvc.perform(get("/somePath"))
        .andExpect(forwardedUrl("/"));
  }

The forwardedUrl() method comes from org.springframework.test.web.servlet.result.MockMvcResultMatchers.


问:
ImportError: No module named 'ruamel_yaml' after conda update --all
Ran

```<code>conda update --all
</code>```

which completed. Afterwards, when doing anything in conda it throws an error

```<code>ImportError: No module named 'ruamel_yaml'
</code>```

Output of echo $PATH

```<code>/opt/local/bin:/opt/local/bin:/Users/*username*/anaconda/bin:/usr/local/fsl/bin:/opt/spark/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Library/TeX/texbin
</code>```

and which conda outputs

```<code>/Users/*username*/anaconda/bin/conda
</code>```

If I do pip install ruamel.yaml i get

```<code>Requirement already satisfied: ruamel.yaml in /usr/local/lib/python2.7/site-packages
Requirement already satisfied: ruamel.ordereddict; platform_python_implementation == "CPython" and python_version <= "2.7" in /usr/local/lib/python2.7/site-packages (from ruamel.yaml)
</code>```

答:
Not really an answer, but for some reason several packages in anaconda had changed paths after running conda update --all to native OSx python. The damage was beyond manual correction, so I completely rewarped anaconda.

I can't reproduce this behaviour after having removed anaconda entirely, and run conda update --all again.

see @millimoose comments for a deeper explanation.

Body:
Ran

conda update --all

which completed. Afterwards, when doing anything in conda it throws an error

ImportError: No module named 'ruamel_yaml'

Output of echo $PATH

/opt/local/bin:/opt/local/bin:/Users/*username*/anaconda/bin:/usr/local/fsl/bin:/opt/spark/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Library/TeX/texbin

and which conda outputs

/Users/*username*/anaconda/bin/conda

If I do pip install ruamel.yaml i get

Requirement already satisfied: ruamel.yaml in /usr/local/lib/python2.7/site-packages
Requirement already satisfied: ruamel.ordereddict; platform_python_implementation == "CPython" and python_version <= "2.7" in /usr/local/lib/python2.7/site-packages (from ruamel.yaml)


问:
MicroService path /api/v1/ or /v1/api/
I'm building a MicroSerive and I was planning to publish services using this URI naming convention:

```<code>https://host:port/api/v1/service1
https://host:port/api/v1/service2
https://host:port/api/v2/service1
https://host:port/api/v2/service2
</code>```

But I've also seen URIs named like this (ie vx and api 'swapped'):

```<code>https://host:port/v1/api/service1
https://host:port/v1/api/service2
https://host:port/v2/api/service1
https://host:port/v2/api/service2
</code>```

In my opinion, the first approach is better. Are there any reasons to go for the second approach?

答:
Technically it doesn't matter

But within an overall REST approach the URL should be easily readable and comprehensible by a humain.

using your first approach is the correct form as it's easily readable as

```<code>The Api of Version 1 that exposes ...
</code>```

Title: MicroService path /api/v1/ or /v1/api/

Body:
I'm building a MicroSerive and I was planning to publish services using this URI naming convention:

https://host:port/api/v1/service1
https://host:port/api/v1/service2
https://host:port/api/v2/service1
https://host:port/api/v2/service2

But I've also seen URIs named like this (ie vx and api 'swapped'):

https://host:port/v1/api/service1
https://host:port/v1/api/service2
https://host:port/v2/api/service1
https://host:port/v2/api/service2

In my opinion, the first approach is better. Are there any reasons to go for the second approach?

Body:
Technically it doesn't matter

But within an overall REST approach the URL should be easily readable and comprehensible by a humain.

using your first approach is the correct form as it's easily readable as

The Api of Version 1 that exposes ...


问:
How to keep track of items with two values?
I am newbie to programming, so please bear with my question.

I often need to process data that has two or more components, for example name and age.

```<code>Alice 32
Bob 42
Terry 23
</code>```

I typically creates two lists name_list and age_list and make sure that the index number fits, so that name_list[2] (Terry) and age_list[2] (23) concerns the same person.

But I kind of have a feeling that this is not very smart once you have bigger amounts of data that you're adding and removing from the lists, as you have no way of knowing if data gets out of sync in case you make a mistake and only delete bob from name_list but not his age from the age_list.

Is there a better way to handle data set like these?

答:
Yes, there is. The easy way to save two or more items is a dictionary.

A dictionary has a key an a value, so following your example, you could build the dictonary like this:

```<code>age = dict() # or {}
age['Terry'] = 23
age['Bob'] = 42
age['Alice'] = 32
print age
{'Terry': 23, 'Bob': 42, 'Alice': 32}
</code>```

You should be familiar with python dictionarys, so you could check this link.

If, for example, you want to save the address, the phone number, etc. You could use a class instead.

Body:
I am newbie to programming, so please bear with my question.

I often need to process data that has two or more components, for example name and age.

Alice 32
Bob 42
Terry 23

I typically creates two lists name_list and age_list and make sure that the index number fits, so that name_list[2] (Terry) and age_list[2] (23) concerns the same person.

But I kind of have a feeling that this is not very smart once you have bigger amounts of data that you're adding and removing from the lists, as you have no way of knowing if data gets out of sync in case you make a mistake and only delete bob from name_list but not his age from the age_list.

Is there a better way to handle data set like these?

Body:
Yes, there is. The easy way to save two or more items is a dictionary.

A dictionary has a key an a value, so following your example, you could build the dictonary like this:

age = dict() # or {}
age['Terry'] = 23
age['Bob'] = 42
age['Alice'] = 32
print age
{'Terry': 23, 'Bob': 42, 'Alice': 32}

You should be familiar with python dictionarys, so you could check this link.

If, for example, you want to save the address, the phone number, etc. You could use a class instead.


问:
nginx configure Front and Backend
I have a backend running at localhost:8080. And the path /runFuction executes a certain command.

Now I would like to use nginx as web server for my front end and only sent certain request to my backend.

My nginx config looks as follows

```<code>server {
    listen       80;
    server_name  localhost;

    location / {
        root   <path to site>;
        index  index.html index.htm;
    }
    location /api {
     proxy_pass http://localhost:8080/;
    }
}
</code>```

In my index.html site I have a form that

```<code>...
 <form action="api/runFuction" method="post" enctype="multipart/form-data">
....
    <input type="submit" value="Do" />
</form>
</code>```

I assumed that this would be possible but somehow I am missing something. How can I reach the backend path since I alway get a 404 page not there?

答:
Could you try it?</p>

```<code>location /api/ {
    rewrite ^/api^/ /$1 break;
    proxy_pass http://localhost:8080;
}
</code>```

Title: nginx configure Front and Backend

Body:
I have a backend running at localhost:8080. And the path /runFuction executes a certain command.

Now I would like to use nginx as web server for my front end and only sent certain request to my backend.

My nginx config looks as follows

server {
    listen       80;
    server_name  localhost;

    location / {
        root   <path to site>;
        index  index.html index.htm;
    }
    location /api {
     proxy_pass http://localhost:8080/;
    }
}

In my index.html site I have a form that

...
 <form action="api/runFuction" method="post" enctype="multipart/form-data">
....
    <input type="submit" value="Do" />
</form>

I assumed that this would be possible but somehow I am missing something. How can I reach the backend path since I alway get a 404 page not there?

Body:
Could you try it?

location /api/ {
    rewrite ^/api^/ /$1 break;
    proxy_pass http://localhost:8080;
}


问:
How do I do simple user input in python?
I'm just playing with input and variables. I'm trying to run a simple function:

```<code>slope = (y2-y1)/(x2-x1)
</code>```

I'd like to prompt the user to enter y2, y1, x2 and x1. What is the simplest, cleanest way to do this?

答:
You can use:

```<code>foo=input('Please enter a value:')
</code>```

Where the string 'Please enter a value:' would be your message, and foo would be your variables.

Body:
I'm just playing with input and variables. I'm trying to run a simple function:

slope = (y2-y1)/(x2-x1)

I'd like to prompt the user to enter y2, y1, x2 and x1. What is the simplest, cleanest way to do this?

Body:
You can use:

foo=input('Please enter a value:')

Where the string 'Please enter a value:' would be your message, and foo would be your variables.


问:
Fail to decrease API
I'm working in an app. The app works in Android 7.x.x but when I try to run the app in the Android 5.x.x app crashed. I think this is happening because the compileSdkVersion is API 25. When I try to to change this to API 21 (ANDROID 5), I have some errors. What can I do to my app work in Android 5?

ps: I don't know if the app is working in Android 6, but probably is not working.

build.gradle:

```<code>android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
defaultConfig {
    applicationId "project.id"
    minSdkVersion 16
    targetSdkVersion 16
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
</code>```

When I try to change the compileSdkVersion to API 21, I have this errors:

```<code>Error:resource android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
Error:resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
Error:resource android:style/TextAppearance.Material.Widget.Button.Inverse not found.
Error:resource android:style/Widget.Material.Button.Colored not found.
Error:failed linking references.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:processDebugResources'.
</code>```

Failed to execute aapt

答:
Your compileSdkVersion MUST match the support library. So change it into 26 in your build.gradle

```<code>compileSdkVersion 26
buildToolsVersion '26.0.2'
compile 'com.android.support:appcompat-v7:26.0.2'
</code>```

targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. Optional, but it SHOULD be 26 too.

It could also error about support library that can cause app to force close. See: InflateException with FloatingActionButton from Official Design Library

Title: Fail to decrease API

Body:
I'm working in an app. The app works in Android 7.x.x but when I try to run the app in the Android 5.x.x app crashed. I think this is happening because the compileSdkVersion is API 25. When I try to to change this to API 21 (ANDROID 5), I have some errors. What can I do to my app work in Android 5?

ps: I don't know if the app is working in Android 6, but probably is not working.

build.gradle:

android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
defaultConfig {
    applicationId "project.id"
    minSdkVersion 16
    targetSdkVersion 16
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

When I try to change the compileSdkVersion to API 21, I have this errors:

Error:resource android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
Error:resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
Error:resource android:style/TextAppearance.Material.Widget.Button.Inverse not found.
Error:resource android:style/Widget.Material.Button.Colored not found.
Error:failed linking references.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:processDebugResources'.

Failed to execute aapt

Body:
Your compileSdkVersion MUST match the support library. So change it into 26 in your build.gradle

compileSdkVersion 26
buildToolsVersion '26.0.2'
compile 'com.android.support:appcompat-v7:26.0.2'

targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. Optional, but it SHOULD be 26 too.

It could also error about support library that can cause app to force close. See: InflateException with FloatingActionButton from Official Design Library


问:
Should you use a function for only one line of code?
I'm relatively new to python and I was wondering if it's always better to never write something twice. I'm currently making a program where at two points in the program the same sentence may need to be saved to a file (consisting only of that sentence). </p>

<p>Is it worth it to make a function for that? I was wondering since it now takes up 2 lines of code, but making a function would make it 4 (2 to define the function and 2 to call it). </p>

答:
Wrap even a one-liner in a function if

Calling the function looks simpler than the code it wraps;

It is likely to be repeated several times in your code;

It is likely to change (then you change only the body of the function and not every place where it is used).

AFAIK, unlike in languages like C where simple functions can get inlined by the compiler, in Python there will be a (sometimes important) performance overhead in calling a wrapper function.

Body:
I'm relatively new to python and I was wondering if it's always better to never write something twice. I'm currently making a program where at two points in the program the same sentence may need to be saved to a file (consisting only of that sentence).

Is it worth it to make a function for that? I was wondering since it now takes up 2 lines of code, but making a function would make it 4 (2 to define the function and 2 to call it).


问:
Extracting URLs from wikipedia tables
I am using the code below, taken from here, to scrape a wikipedia table. In addition to the test information, I would like to visit each hyperlink for each cite/country, and copy the text from each of those pages. Is there a way to do that with BeautifulSoup?

```<code># -*- coding: utf-8 -*-
"""
Scrape a table from wikipedia using python. Allows for cells spanning multiple rows and/or columns. Outputs csv files for
each table
"""

from bs4 import BeautifulSoup
import urllib.request
import os
import codecs

# wiki = "https://en.wikipedia.org/wiki/International_Phonetic_Alphabet_chart_for_English_dialects"
wiki = 'https://en.wikipedia.org/wiki/List_of_national_capitals_in_alphabetical_order'
header = {'User-Agent': 'Mozilla/5.0'}  # Needed to prevent 403 error on Wikipedia
req = urllib.request.Request(wiki, headers=header)
page = urllib.request.urlopen(req)
soup = BeautifulSoup(page, "html.parser")

tables = soup.findAll("table", {"class": "wikitable"})

# show tables
# for table in tables:
#     print("###############")
#     print(table)#.text)#[:100])

for tn in range(len(tables)):
    table = tables[tn]

    # preinit list of lists
    rows = table.findAll("tr")
    row_lengths = [len(r.findAll(['th', 'td'])) for r in rows]
    ncols = max(row_lengths)
    nrows = len(rows)
    data = []
    for i in range(nrows):
        rowD = []
        for j in range(ncols):
            rowD.append('')
        data.append(rowD)

    # process html
    for i in range(len(rows)):
        row = rows[i]
        rowD = []
        cells = row.findAll(["td", "th"])
        for j in range(len(cells)):
            cell = cells[j]

            # lots of cells span cols and rows so lets deal with that
            cspan = int(cell.get('colspan', 1))
            rspan = int(cell.get('rowspan', 1))
            for k in range(rspan):
                for l in range(cspan):
                    data[i + k][j + l] += cell.text

        data.append(rowD)

        # write data out

        page = os.path.split(wiki)[1]
    fname = 'output_{}_t{}.csv'.format(page, tn)
    f = codecs.open(fname, 'w')  # ,encoding='utf-8')
    for i in range(nrows):
        rowStr = ','.join(data[i])
        rowStr = rowStr.replace('\n', '')
        # print(rowStr)
        rowStr = rowStr  # .encode('unicode_escape')
        f.write(rowStr + '\n')

    f.close()
</code>```

答:
```<code>from bs4 import BeautifulSoup
import requests
wiki_url = 'https://en.wikipedia.org/wiki/List_of_national_capitals_in_alphabetical_order'
print('Fetching main wiki article: %s' % wiki_url)
page = requests.get(wiki_url).text
print('Done. Extracting table links..')
html = BeautifulSoup(page)
table = html.find('table', 'wikitable')
links = table.findAll('a')
links_content = {}
print('Done extracting links. About to fetch: %s links..' % len(links))
for link in links:
    print('Fetching: %s' % link)
    links_content[link] = requests.get(link).text
</code>```

Title: Extracting URLs from wikipedia tables

Body:
I am using the code below, taken from here, to scrape a wikipedia table. In addition to the test information, I would like to visit each hyperlink for each cite/country, and copy the text from each of those pages. Is there a way to do that with BeautifulSoup?

# -*- coding: utf-8 -*-
"""
Scrape a table from wikipedia using python. Allows for cells spanning multiple rows and/or columns. Outputs csv files for
each table
"""

from bs4 import BeautifulSoup
import urllib.request
import os
import codecs

# wiki = "https://en.wikipedia.org/wiki/International_Phonetic_Alphabet_chart_for_English_dialects"
wiki = 'https://en.wikipedia.org/wiki/List_of_national_capitals_in_alphabetical_order'
header = {'User-Agent': 'Mozilla/5.0'}  # Needed to prevent 403 error on Wikipedia
req = urllib.request.Request(wiki, headers=header)
page = urllib.request.urlopen(req)
soup = BeautifulSoup(page, "html.parser")

tables = soup.findAll("table", {"class": "wikitable"})

# show tables
# for table in tables:
#     print("###############")
#     print(table)#.text)#[:100])

for tn in range(len(tables)):
    table = tables[tn]

    # preinit list of lists
    rows = table.findAll("tr")
    row_lengths = [len(r.findAll(['th', 'td'])) for r in rows]
    ncols = max(row_lengths)
    nrows = len(rows)
    data = []
    for i in range(nrows):
        rowD = []
        for j in range(ncols):
            rowD.append('')
        data.append(rowD)

    # process html
    for i in range(len(rows)):
        row = rows[i]
        rowD = []
        cells = row.findAll(["td", "th"])
        for j in range(len(cells)):
            cell = cells[j]

            # lots of cells span cols and rows so lets deal with that
            cspan = int(cell.get('colspan', 1))
            rspan = int(cell.get('rowspan', 1))
            for k in range(rspan):
                for l in range(cspan):
                    data[i + k][j + l] += cell.text

        data.append(rowD)

        # write data out

        page = os.path.split(wiki)[1]
    fname = 'output_{}_t{}.csv'.format(page, tn)
    f = codecs.open(fname, 'w')  # ,encoding='utf-8')
    for i in range(nrows):
        rowStr = ','.join(data[i])
        rowStr = rowStr.replace('\n', '')
        # print(rowStr)
        rowStr = rowStr  # .encode('unicode_escape')
        f.write(rowStr + '\n')

    f.close()


问:
MDI Single Instance C#.. how to achieve that?
I found the following code in codeproject for single instance.

```<code>frmSChild objfrmSChild = frmSChild.GetChildInstance();
objfrmSChild.MdiParent = this;
objfrmSChild.Show();
objfrmSChild.BringToFront();
</code>```

It is working fine. But it only works once.

I open the that frmSChild for 2 or 3 times. it will bring forwards that form.

But if I close that form and open again. there is an error stating cannot detect an exposed ojbect.

How to modify the code to get it done?

答: Check the form's IsDisposed property, and, if it's true, make a new instance.

Body:
I found the following code in codeproject for single instance.

frmSChild objfrmSChild = frmSChild.GetChildInstance();
objfrmSChild.MdiParent = this;
objfrmSChild.Show();
objfrmSChild.BringToFront();

It is working fine. But it only works once.

I open the that frmSChild for 2 or 3 times. it will bring forwards that form.

But if I close that form and open again. there is an error stating cannot detect an exposed ojbect.

How to modify the code to get it done?


问:
FOSUserBundle - perform function upon initial login
I have a Symfony 3 application with user management via FOSUserBundle. I want to implement a Listener class that checks for an initial user login, by checking the user's "last_login" value. While I did read the article on event subscribers, I struggle to find out when exactly the last_login value is updated.
Is there anyone with such knowledge, or does anyone know a better approach regarding a user's initial login?</p>

答:
I just had a look at this and it seems you can use an eventSubscriber to subscribe to the SecurityEvents::INTERACTIVE_LOGIN event to get where you need to be.

```<code>class RegistrationSubscriber implements EventSubscriberInterface
{
private $tokenStorage;

public function __construct(TokenStorage $tokenStorage)
{
    $this->tokenStorage = $tokenStorage;
}
 public static function getSubscribedEvents()
{
    return [
        SecurityEvents::INTERACTIVE_LOGIN => [
            ['lastLogin', 150],
        ],
    ];
}
public function lastLogin(InteractiveLoginEvent $event){
    $user = $this->tokenStorage->getToken()->getUser();
    if($user->getLastLogin() == null){
     //Do something
    }
}
</code>```

In my testing on the first login $user->getLastLogin() is null so you can put any logic you need here.

Body:
I just had a look at this and it seems you can use an eventSubscriber to subscribe to the SecurityEvents::INTERACTIVE_LOGIN event to get where you need to be.

class RegistrationSubscriber implements EventSubscriberInterface
{
private $tokenStorage;

public function __construct(TokenStorage $tokenStorage)
{
    $this->tokenStorage = $tokenStorage;
}
 public static function getSubscribedEvents()
{
    return [
        SecurityEvents::INTERACTIVE_LOGIN => [
            ['lastLogin', 150],
        ],
    ];
}
public function lastLogin(InteractiveLoginEvent $event){
    $user = $this->tokenStorage->getToken()->getUser();
    if($user->getLastLogin() == null){
     //Do something
    }
}

In my testing on the first login $user->getLastLogin() is null so you can put any logic you need here.


问:
How can use Microsoft Oslo Library for solve stiff equations?
which phrase in Microsoft Oslo Library can solve the Stiff ordinary differential Equations?
is there another way to solve them at all?</p>

答: Any method that invites you to provide the Jacobian is an implicit method and thus (better) suited for stiff equations. Here that is the BDF method.</p>


问:
how to scrape data using dt tags
I am scraping data from a url, mostly I have experienced ul li and so on.

This time I have found dl tags, and when I use scrape_between function it doesn't show me anything my code is :

```<code><div id='gallery-1' class='gallery galleryid-273 gallery-columns-2 gallery-size-full'><dl class='gallery-item'>
        <dt class='gallery-icon portrait'>
            <a href='https://example.com/wp-content/uploads/2013/11/gf-1.jpg?fit=650%2C976' data-rel="lightbox-gallery-1"><img  width="650" height="976"  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="https://example.com/wp-content/uploads/2013/11/gf-1.jpg?fit=650%2C976"  class="attachment-full size-full" alt="" aria-describedby="gallery-1-16311" data-srcset="https://example.com/wp-content/uploads/2013/11/gf-1.jpg?w=650 650w, https://example.com/wp-content/uploads/2013/11/gf-1.jpg?resize=200%2C300 200w" data-sizes="(max-width: 650px) 100vw, 650px" /></a>
        </dt>
            <dd class='wp-caption-text gallery-caption' id='gallery-1-16311'>
            Ground Floor Plan
            </dd></dl><dl class='gallery-item'>
        <dt class='gallery-icon portrait'>
            <a href='https://example.com/wp-content/uploads/2013/11/ff.jpg?fit=649%2C1024' data-rel="lightbox-gallery-1"><img  width="649" height="1024"  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="https://example.com/wp-content/uploads/2013/11/ff.jpg?fit=649%2C1024"  class="attachment-full size-full" alt="" aria-describedby="gallery-1-16312" data-srcset="https://example.com/wp-content/uploads/2013/11/ff.jpg?w=649 649w, https://example.com/wp-content/uploads/2013/11/ff.jpg?resize=190%2C300 190w" data-sizes="(max-width: 649px) 100vw, 649px" /></a>
        </dt>
            <dd class='wp-caption-text gallery-caption' id='gallery-1-16312'>
            First Floor pLan
            </dd></dl><br style="clear: both" />
    </div>
</code>```

Can anybody help me out ?

scrap_between function is

```<code>function scrape_between($data, $start, $end){
    $data = stristr($data, $start);
    $data = substr($data, strlen($start));
    $stop = stripos($data, $end);
    $data = substr($data, 0, $stop);
    return $data;
}
</code>```

I need to scrape images that are place in dt tags

I am trying this code

```<code>$project_images = scrape_between($data, '<dl class="gallery-item', '<br style="clear: both">');
</code>```

Please suggest

答:
You could use a loop in your function and make it return an array:

```<code>//returns array with found elements
function scrape_between($data, $start, $end) {

    $html_array = explode($start, $data);

    $clean_html_arr = [];

    foreach ($html_array as $position => $html_array_element) {
      if ($position > 0) {
        $html_exploded = explode($end, $html_array_element);
        $clean_html_arr[] = $start . $html_exploded[0] . $end;
      }
    }

    return $clean_html_arr;
}
</code>```

And use it like this:

```<code>//Test function
foreach(scrape_between($str, "<dl class='gallery-item'>", "</dl>") as $key => $htmlBlock) {
    echo htmlspecialchars($htmlBlock) . '<br><br>';
}
</code>```

Title: how to scrape data using dt tags

Body:
I am scraping data from a url, mostly I have experienced ul li and so on.

This time I have found dl tags, and when I use scrape_between function it doesn't show me anything my code is :

            Ground Floor Plan

            First Floor pLan

Can anybody help me out ?

scrap_between function is

function scrape_between($data, $start, $end){
    $data = stristr($data, $start);
    $data = substr($data, strlen($start));
    $stop = stripos($data, $end);
    $data = substr($data, 0, $stop);
    return $data;
}

I need to scrape images that are place in dt tags

I am trying this code

$project_images = scrape_between($data, '<dl class="gallery-item', '
');

Please suggest

Body:
You could use a loop in your function and make it return an array:

//returns array with found elements
function scrape_between($data, $start, $end) {

    $html_array = explode($start, $data);

    $clean_html_arr = [];

    foreach ($html_array as $position => $html_array_element) {
      if ($position > 0) {
        $html_exploded = explode($end, $html_array_element);
        $clean_html_arr[] = $start . $html_exploded[0] . $end;
      }
    }

    return $clean_html_arr;
}

And use it like this:

//Test function
foreach(scrape_between($str, "<dl class='gallery-item'>", "</dl>") as $key => $htmlBlock) {
    echo htmlspecialchars($htmlBlock) . '<br><br>';
}


问:
Selenium working only for few pages -- Element is not clickable at point
I tried to automate Amazon/novels list page using selenium. It is working sometimes and not working sometimes. I am unable to understand the mistake in the code. It worked fine for some time and scrolled 13 pages out of 20. But from next time, it is not working properly. Till now it didn't scroll complete 20 pages.

```<code>from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup

class App:

    def __init__(self,path='F:\Imaging'):

        self.path=path
        self.driver = webdriver.Chrome('F:\chromedriver')
        self.driver.get('https://www.amazon.in/s/ref=sr_pg_1?rh=i%3Aaps%2Ck%3Anovels&keywords=novels&ie=UTF8&qid=1510727563')
        sleep(1)
        self.scroll_down()
        self.driver.close()

    def scroll_down(self):

        self.driver.execute_script("window.scrollTo(0,5500);")
        sleep(1)
        load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
        load_more.click()
        sleep(2)

        for value in range(2,19):

            print(self.driver.current_url)
            sleep(3)
            self.driver.execute_script("window.scrollTo(0,5500);")
            sleep(2)
            load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
            load_more.click()

        sleep(3)

if __name__=='__main__':
    app=App()
</code>```

The output for this code which i am getting is:

```<code>    C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Akhil/Scrape/amazon.py
https://www.amazon.in/s/ref=sr_pg_2/257-8503487-3570721?rh=i%3Aaps%2Ck%3Anovels&page=2&keywords=novels&ie=UTF8&qid=1510744188
https://www.amazon.in/s/ref=sr_pg_3?rh=i%3Aaps%2Ck%3Anovels&page=3&keywords=novels&ie=UTF8&qid=1510744197
https://www.amazon.in/s/ref=sr_pg_4?rh=i%3Aaps%2Ck%3Anovels&page=4&keywords=novels&ie=UTF8&qid=1510744204
Traceback (most recent call last):
  File "C:/Users/Akhil/Scrape/amazon.py", line 31, in <module>
    app=App()
  File "C:/Users/Akhil/Scrape/amazon.py", line 11, in __init__
    self.scroll_down()
  File "C:/Users/Akhil/Scrape/amazon.py", line 26, in scroll_down
    load_more.click()
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a title="Next Page" id="pagnNextLink" class="pagnNext" href="/gp/search/ref=sr_pg_5?rh=i%3Aaps%2Ck%3Anovels&page=5&keywords=novels&ie=UTF8&qid=1510744210">...</a> is not clickable at point (809, 8). Other element would receive the click: <a href="/gp/prime/ref=nav_prime_try_btn/257-8503487-3570721" class="nav-a nav-a-2" data-ux-mouseover="true" id="nav-link-prime" tabindex="26">...</a>
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Process finished with exit code 1
</code>```

How to solve this problem?

答:
I finally got the correct result using small modifications to the answer given by @RatmirAsanov.

Please see this code. This will scroll all pages without fail.

```<code>from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

class App:
    def __init__(self,path='F:\Imaging'):
        self.path=path
        self.driver = webdriver.Chrome('F:\chromedriver')
        self.driver.get('https://www.amazon.in/s/ref=sr_pg_1?rh=i%3Aaps%2Ck%3Anovels&keywords=novels&ie=UTF8&qid=1510727563')
        sleep(1)
        self.scroll_down()
        self.driver.close()

    def scroll_down(self):
        sleep(3)
        self.driver.execute_script("window.scrollTo(0,5450);")
        sleep(3)
        load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
        load_more.click()
        sleep(3)
        for value in range(2,19):
            print(self.driver.current_url)
            sleep(5)
            self.driver.execute_script("window.scrollTo(0,5500);")
            sleep(3)
            load_more = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='pagnRA']/a[@title='Next Page']")))
            self.driver.execute_script("arguments[0].click();", load_more)
            #load_more.click()
            sleep(3)
        sleep(3)

if __name__=='__main__':
    APP=App()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried to automate Amazon/novels list page using selenium. It is working sometimes and not working sometimes. I am unable to understand the mistake in the code. It worked fine for some time and scrolled 13 pages out of 20. But from next time, it is not working properly. Till now it didn't scroll complete 20 pages.

from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup

class App:

    def __init__(self,path='F:\Imaging'):

        self.path=path
        self.driver = webdriver.Chrome('F:\chromedriver')
        self.driver.get('https://www.amazon.in/s/ref=sr_pg_1?rh=i%3Aaps%2Ck%3Anovels&keywords=novels&ie=UTF8&qid=1510727563')
        sleep(1)
        self.scroll_down()
        self.driver.close()

    def scroll_down(self):

        self.driver.execute_script("window.scrollTo(0,5500);")
        sleep(1)
        load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
        load_more.click()
        sleep(2)

        for value in range(2,19):

            print(self.driver.current_url)
            sleep(3)
            self.driver.execute_script("window.scrollTo(0,5500);")
            sleep(2)
            load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
            load_more.click()

        sleep(3)

if __name__=='__main__':
    app=App()

The output for this code which i am getting is:

    C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Akhil/Scrape/amazon.py
https://www.amazon.in/s/ref=sr_pg_2/257-8503487-3570721?rh=i%3Aaps%2Ck%3Anovels&page=2&keywords=novels&ie=UTF8&qid=1510744188
https://www.amazon.in/s/ref=sr_pg_3?rh=i%3Aaps%2Ck%3Anovels&page=3&keywords=novels&ie=UTF8&qid=1510744197
https://www.amazon.in/s/ref=sr_pg_4?rh=i%3Aaps%2Ck%3Anovels&page=4&keywords=novels&ie=UTF8&qid=1510744204
Traceback (most recent call last):
  File "C:/Users/Akhil/Scrape/amazon.py", line 31, in <module>
    app=App()
  File "C:/Users/Akhil/Scrape/amazon.py", line 11, in __init__
    self.scroll_down()
  File "C:/Users/Akhil/Scrape/amazon.py", line 26, in scroll_down
    load_more.click()
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (809, 8). Other element would receive the click: ...
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Process finished with exit code 1

How to solve this problem?

Body:
I finally got the correct result using small modifications to the answer given by @RatmirAsanov.

Please see this code. This will scroll all pages without fail.

from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

class App:
    def __init__(self,path='F:\Imaging'):
        self.path=path
        self.driver = webdriver.Chrome('F:\chromedriver')
        self.driver.get('https://www.amazon.in/s/ref=sr_pg_1?rh=i%3Aaps%2Ck%3Anovels&keywords=novels&ie=UTF8&qid=1510727563')
        sleep(1)
        self.scroll_down()
        self.driver.close()

    def scroll_down(self):
        sleep(3)
        self.driver.execute_script("window.scrollTo(0,5450);")
        sleep(3)
        load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
        load_more.click()
        sleep(3)
        for value in range(2,19):
            print(self.driver.current_url)
            sleep(5)
            self.driver.execute_script("window.scrollTo(0,5500);")
            sleep(3)
            load_more = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='pagnRA']/a[@title='Next Page']")))
            self.driver.execute_script("arguments[0].click();", load_more)
            #load_more.click()
            sleep(3)
        sleep(3)

if __name__=='__main__':
    APP=App()


问:
Angular: Form fields read-only mode
I have some forms that should be editable only by some users. Other users should only be able to view it.

Currently, for each form control in a form, I'm checking condition and displaying either a form control or a text. Something like,

```<code><div>
    <input type="text" *ngIf="editable">
    <p *ngIf="!editable">{{value}}</p>
</div>
</code>```

This doesn't seem to be an elegant way. Please suggest a cleaner way to achieve this, like doing something at the top level.

答:
I think you should take a look to the ng-disabled directive.
This should do the trick here!</p>

Title: Angular: Form fields read-only mode

Body:
I have some forms that should be editable only by some users. Other users should only be able to view it.

Currently, for each form control in a form, I'm checking condition and displaying either a form control or a text. Something like,

    <input type="text" *ngIf="editable">

{{value}}

This doesn't seem to be an elegant way. Please suggest a cleaner way to achieve this, like doing something at the top level.


问:
How to compute grads_and_vars with GradientDescentOptimizer
I have the following CNN code implementation.

```<code>optimizer = tf.train.GradientDescentOptimizer(cnn.learning_rate).minimize(loss = cnn.loss, global_step=global_step)
grads_and_vars = optimizer.compute_gradients(cnn.loss)
train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)
</code>```

Using it, I get the following error:

```<code>grads_and_vars = optimizer.compute_gradients(cnn.loss)
AttributeError: 'Operation' object has no attribute 'compute_gradients'
</code>```

I noticed that using the above GradientDescentOptimizer implementation with tf.train.exponential_decay does not provide the attribute 'compute_gradients'
 for the optimizer.

Can someone help me with this?

答:
Both compute_gradients and apply_gradients are methods of the tf.train.GradientDescentOptimizer class.

The problem is that you are defining your optimizer as the step. You should remove the minimize call, like this:

```<code>optimizer = tf.train.GradientDescentOptimizer(cnn.learning_rate)
grads_and_vars = optimizer.compute_gradients(cnn.loss)
train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)
</code>```

and it should work.

However, if you are not doing any specific use of the gradients, you can indeed use .minimize(...) to directly define a training step, similarly to your train_op:

```<code>optimizer = tf.train.GradientDescentOptimizer(cnn.learning_rate)
train_op = optimizer.minimize(loss=cnn.loss, global_step=global_step)
</code>```

Further explanation on how apply_gradients works here.

Body:
I have the following CNN code implementation.

optimizer = tf.train.GradientDescentOptimizer(cnn.learning_rate).minimize(loss = cnn.loss, global_step=global_step)
grads_and_vars = optimizer.compute_gradients(cnn.loss)
train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)

Using it, I get the following error:

grads_and_vars = optimizer.compute_gradients(cnn.loss)
AttributeError: 'Operation' object has no attribute 'compute_gradients'

I noticed that using the above GradientDescentOptimizer implementation with tf.train.exponential_decay does not provide the attribute 'compute_gradients'
 for the optimizer.

Can someone help me with this?

Body:
Both compute_gradients and apply_gradients are methods of the tf.train.GradientDescentOptimizer class.

The problem is that you are defining your optimizer as the step. You should remove the minimize call, like this:

optimizer = tf.train.GradientDescentOptimizer(cnn.learning_rate)
grads_and_vars = optimizer.compute_gradients(cnn.loss)
train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)

and it should work.

However, if you are not doing any specific use of the gradients, you can indeed use .minimize(...) to directly define a training step, similarly to your train_op:

optimizer = tf.train.GradientDescentOptimizer(cnn.learning_rate)
train_op = optimizer.minimize(loss=cnn.loss, global_step=global_step)

Further explanation on how apply_gradients works here.


问:
reactjs componentWillMount not calling every time when i open modal
i am displaying table data inside modal dialog, when i click table row to edit data it will open another modal dialog, here i am getting row data by using clicked row id inside componentWillMount(). but when i close edit modal dialog and try to edit other table row componentWillMount() will not called. so edit modal dialog is empty. why componentWillMount not calling every time?

答:
I used following steps to fix it.

i used {(this.state.open) ? <Dialog open={true} ></Dialog> : null

second step by unmounting the component componentWillUnmount() { }


问:
Use of GetGuiResources
Is it a good idea to use GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS) at the start of WinMain, and before the last return to detect GDI leaks or, more specifically, objects I forgot to release?
Also I'm currently wondering why the first call in my program returns 4 when there's no window yet.

答:
In most situations, it's enough to use process explorer. Keep the window open showing the GDI handles of your process (right-click on the columns, choose "Select Columns" and then check the "GDI Objects" checkbox in the "Process Memory" tab).

While running your application, watch the number of GDI handles - if it increases and never goes back, you know you have a leak.

OwnerDisplayName: Zub

Title: Use of GetGuiResources

OwnerDisplayName: Stefan


问:
How do I remove all events of a type from an element
I want to remove ALL click events from a certain DOM element. How? There is removeEventListener, but that requires the attached function.

Is there a way to remove ALL attached events of one type (or just ALL, that's fine too)?

答:
You didn't mention whether or not you were using a library to assist in DOM manipulation, but if you're using jQuery, its as simple as $(domelement).unbind('click');
Documented here: http://api.jquery.com/unbind/</p>


问:
IntelliTrace stand-alone collector
I would like to set up min winforms app to use the IntelliTrace stand-alone collector.

Iv downloaded the application but I cant seem to find how I set it up to winforms.

It should be in this link I guess, but I dont quite understand: https://msdn.microsoft.com/en-us/library/hh398365(v=vs.110).aspx

Does anyone have any advice? Im trying to google to find examples without luck.

Best regards
Rob

答:
Download Intellitrace standalone collector

Double click on the .exe file

Put the IntelliTraceCollectio.cab file in a folder.
For example D:\Intellitrace

Open command prompt as an administrator
Go to specified path of IntelliTraceCollectio.cab
and enter the command

expand /f:* IntelliTraceCollection.cab .

(Don't forget to put . at end)

Using command prompt,
enter

icacls "D:\IntelliTrace" /grant

(D:\Intellitrace is the path of your folder as specified above)

Create one more folder as D:\IntelliTraceLog (To store the collected intellitrace log file)

To collect data from an application, enter command

D:\Intellitrace\IntelliTraceSC.exe launch /cp:"D:\Intellitrace\collection_plan.ASP.NET.default.xml" /f: "C:IntelliTraceLog\MyApp.itrace" "D:\xyz\abc.exe"

(D:\xyz\abc.exe is the actual path of your file you want to run)

Now you will get an itrace file in D:\IntelliTraceLog. Open it in visual studio enterprise. Select any exception and click on Run Debugging.

Title: IntelliTrace stand-alone collector


问:
MySql select table dynamically
Is there any way to select all data form one of those tables based on the condition ?</p>

```
SELECT * FROM
CASE WHEN (another query which will return integer)>0 THEN products ELSE sub_products END
LIMIT 0, 25
```

答:
Modify IntResultQuery below to contain your query which returns a scalar value.

Modify a.Rslt to be the name of the column with the scalar value.

```<code>SELECT *
FROM (IntResultQuery) A
LEFT JOIN Products
 on 1=1 and A.Rslt>0
LEFT JOIN Sub_products
 on 1=1 and A.Rslt<=0
</code>```

Though I agree this design is strange; and you'll get column names from both tables so maybe not what you need.

```<code>SELECT *
FROM (IntResultQuery) A
LEFT JOIN Products
 on A.Rslt > 0
LEFT JOIN Sub_products
 on A.Rslt <= 0
</code>```

This union approach assumes both tables have the same table structure.  By unioning the tables and creating a column which tells us the source of the data, we can take the scalar result from your query and pick the right rows from the unioned tables.

```<code>SELECT *
FROM (SELECT 0 as src, P.*
      FROM Products P
      UNION ALL
      SELECT -1 as src, SP.*
      FROM Sub_products SP) Z
CROSS JOIN (IntResultQuery) A
WHERE Z.src > A.Rslt
</code>```

This approach avoids the multiple columns for the two tables; but suffers if the tables structures are not identical.  You could specify the specific columns from each table desired assuming at least some match; and left join in the columns that don't match.  But this type of design gets challenging to maintain the data as it complicates which table needs to be updated when a change is needed.

Title: MySql select table dynamically

Body:
Is there any way to select all data form one of those tables based on the condition ?

SELECT * FROM
CASE WHEN (another query which will return integer)>0 THEN products ELSE sub_products END
LIMIT 0, 25

Body:
Modify IntResultQuery below to contain your query which returns a scalar value.

Modify a.Rslt to be the name of the column with the scalar value.

SELECT *
FROM (IntResultQuery) A
LEFT JOIN Products
 on 1=1 and A.Rslt>0
LEFT JOIN Sub_products
 on 1=1 and A.Rslt<=0

Though I agree this design is strange; and you'll get column names from both tables so maybe not what you need.

SELECT *
FROM (IntResultQuery) A
LEFT JOIN Products
 on A.Rslt > 0
LEFT JOIN Sub_products
 on A.Rslt <= 0

This union approach assumes both tables have the same table structure.  By unioning the tables and creating a column which tells us the source of the data, we can take the scalar result from your query and pick the right rows from the unioned tables.

SELECT *
FROM (SELECT 0 as src, P.*
      FROM Products P
      UNION ALL
      SELECT -1 as src, SP.*
      FROM Sub_products SP) Z
CROSS JOIN (IntResultQuery) A
WHERE Z.src > A.Rslt

This approach avoids the multiple columns for the two tables; but suffers if the tables structures are not identical.  You could specify the specific columns from each table desired assuming at least some match; and left join in the columns that don't match.  But this type of design gets challenging to maintain the data as it complicates which table needs to be updated when a change is needed.


问:
How to use custom models in Django?
Followed the Django Quickstart tutorial here and it all worked wo/ problems.

Now when I added a custom APIView I started having trouble. Namely the custom models I created.

Here is my views.py

```<code>class ValuationDetails(APIView):

   def get(self, request, format=None):
       serializer = ValuationRequestSerializer(data=request.data)
       if serializer.is_valid():
           return Response('Valuation report', status=status.HTTP_201_CREATED)
</code>```

Here is my ValuationRequestSerializer:

```<code>class ValuationRequestSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ValuationRequest
        fields = ('street', 'number', 'latitude', 'longitude')
</code>```

Here is my ValuationRequest:

```<code>from django.db import models

class ValuationRequest(models.Model):
    def __init__(self, street, number, latitude, longitude):
        self.street = street
        self.number = number
        self.latitude = latitude
        self.longitude = longitude
</code>```

The first exception was:

RuntimeError: Model class valuationservice.valproperty.model.val_models.ValuationRequest doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

Then I added in the setting.py INSTALLED_APPS a line

```<code>'valuationservice.valproperty.model.val_models'
</code>```

The second exception after that was:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I guess there are two questions:

How can I use custom models in Django?

What is missing that the Django doesn't like by throwing the first exception?

Python version 2.7.12

Thanks!

答:
You should not define an __init__ method in your model class.

(If you did, you should always be sure to call the superclass method using super(); but you shouldn't do it at all in this case.)

Title: How to use custom models in Django?

Body:
Followed the Django Quickstart tutorial here and it all worked wo/ problems.

Now when I added a custom APIView I started having trouble. Namely the custom models I created.

Here is my views.py

class ValuationDetails(APIView):

   def get(self, request, format=None):
       serializer = ValuationRequestSerializer(data=request.data)
       if serializer.is_valid():
           return Response('Valuation report', status=status.HTTP_201_CREATED)

Here is my ValuationRequestSerializer:

class ValuationRequestSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ValuationRequest
        fields = ('street', 'number', 'latitude', 'longitude')

Here is my ValuationRequest:

from django.db import models

class ValuationRequest(models.Model):
    def __init__(self, street, number, latitude, longitude):
        self.street = street
        self.number = number
        self.latitude = latitude
        self.longitude = longitude

The first exception was:

RuntimeError: Model class valuationservice.valproperty.model.val_models.ValuationRequest doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

Then I added in the setting.py INSTALLED_APPS a line

'valuationservice.valproperty.model.val_models'

The second exception after that was:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I guess there are two questions:

How can I use custom models in Django?

What is missing that the Django doesn't like by throwing the first exception?

Python version 2.7.12

Thanks!


问:
How can I run something Async in OncreateView?
I have a problem with my app. Firstly, I made two Tabs using fragments which inflates an activity. The tabs implemented is working fine. Secondly i have  displayed the XAML right.

However, I now need to run something asynchronously in
OnCreateView in the Fragment. How can i manage this without getting errors?

Any help is greatly appreciated! Thanks

Here is my Fragment:

```<code>public class FragmentSettings : SupportFragment
{
    private Button mBtnOk;

    public FragmentSettings(Context context)
    {
        mContext = context;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Inflate the fragment XML
        View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

        //Grab the butten from the inflated fragment
        mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
        mBtnOk.Click += (object sender, EventArgs e) =>
        {
            //DO stuff
        };
        //=====================================
        //Want to do something async stuff here
        //=====================================

        return view;
    }
}
</code>```

答:
This did the trick for me, thanks for all the answers!</p>

```<code>    public override async void OnActivityCreated(Bundle savedInstanceState)
    {
        base.OnActivityCreated(savedInstanceState);

        await LoadData();
    }
    private async Task LoadData()
    {
     //My async method
    }
</code>```

Body:
I have a problem with my app. Firstly, I made two Tabs using fragments which inflates an activity. The tabs implemented is working fine. Secondly i have  displayed the XAML right.

However, I now need to run something asynchronously in
OnCreateView in the Fragment. How can i manage this without getting errors?

Any help is greatly appreciated! Thanks

Here is my Fragment:

public class FragmentSettings : SupportFragment
{
    private Button mBtnOk;

    public FragmentSettings(Context context)
    {
        mContext = context;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Inflate the fragment XML
        View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

        //Grab the butten from the inflated fragment
        mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
        mBtnOk.Click += (object sender, EventArgs e) =>
        {
            //DO stuff
        };
        //=====================================
        //Want to do something async stuff here
        //=====================================

        return view;
    }
}

Body:
This did the trick for me, thanks for all the answers!

    public override async void OnActivityCreated(Bundle savedInstanceState)
    {
        base.OnActivityCreated(savedInstanceState);

        await LoadData();
    }
    private async Task LoadData()
    {
     //My async method
    }


问:
Counting relationships size in Neo4j
I have a Neo4j Graph database which stores Twitter data.
Each Tweet is about a Topic and has got this kind of relationship:

```<code>(t:Tweet)-[:ABOUT]->(t1:Topic)
</code>```

A User can be mentioned by a Tweet due to this relationship
(t:Tweet)-[:MENTIONS]->(u:User)

I'd like to know how many users are mentioned in tweets regarding a specific topic.

My query is:

```<code>match (n:Topic)<--()-[r:MENTIONS]->(u:User)
where n.name='politics'
return count(r)
</code>```

Is this query right? Because I've got unexpected results.

Thanks a lot.

答:
You can try using the following query.</p>

```<code>match (n:Topic{name:'politics'})
RETURN size((n)<--()-[:MENTIONS]->(:User)) as count
</code>```

Title: Counting relationships size in Neo4j

Body:
I have a Neo4j Graph database which stores Twitter data.
Each Tweet is about a Topic and has got this kind of relationship:

(t:Tweet)-[:ABOUT]->(t1:Topic)

A User can be mentioned by a Tweet due to this relationship
(t:Tweet)-[:MENTIONS]->(u:User)

I'd like to know how many users are mentioned in tweets regarding a specific topic.

My query is:

match (n:Topic)<--()-[r:MENTIONS]->(u:User)
where n.name='politics'
return count(r)

Is this query right? Because I've got unexpected results.

Thanks a lot.

Body:
You can try using the following query.

match (n:Topic{name:'politics'})
RETURN size((n)<--()-[:MENTIONS]->(:User)) as count


问:
Can I upload CSV files to Android firebase?
I am using Android firebase for the first time so please let me know can I upload CSV files from my mobile to firebase? if yes then how ? </p>

答: You totally can. You can use Firebase Storage to store your files - csv, images, videos, etc.</p>


问:
No module named externals in mplot3d
I am trying to visualize the 3d plot using mpl_toolkits.mplot3d.Axes3D with matplotlib

I am using python 3 with matplot version '2.1.0' and scikit-learn verison 0.19.0. When i run the code it is producing the following error,

```<code>from matplotlib.externals import six
ImportError: No module named 'matplotlib.externals'
</code>```

I tried to solve this issue by removing existing matplotlib and installing again, without any luck.

i am trying to run this code

```<code>import numpy as np
import mglearn
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from mpl_toolkits.mplot3d import Axes3D, axes3d

X, y = make_blobs(centers=4, random_state=8)
y = y % 2

X_new = np.hstack([X, X[:, 1:] ** 2])

figure = plt.figure()
ax = Axes3D(figure, elev=-152, azim=-26)
# plot first all the points with y == 0, then all with y == 1
mask = y == 0
ax.scatter(X_new[mask, 0], X_new[mask, 1], X_new[mask, 2], c='b', cmap=mglearn.cm2, s=60)
ax.scatter(X_new[mask, 0], X_new[mask, 1], X_new[mask, 2], c='r', marker='^', cmap=mglearn.cm2, s=60)
ax.set_xlabel("feature0")
ax.set_ylabel("feature1")
ax.set_zlabel("feature1 ** 2")

plt.show()

Error log after installing sabron package
The minimum supported version is 2.4.6

  ver=ver, min_ver=_MIN_NUMEXPR_VERSION), UserWarning)
Traceback (most recent call last):
  File "/home/asif/ml-codes/matpolitlib-tutorials/example-two.py", line 5, in <module>
    from mpl_toolkits.mplot3d import Axes3D, axes3d
  File "/usr/lib/python3/dist-packages/mpl_toolkits/mplot3d/__init__.py", line 4, in <module>
    from matplotlib.externals import six
ImportError: No module named 'matplotlib.externals'
</code>```

答:
Execute:

```<code>sudo apt-get remove python3-matplotlib
</code>```

This will remove the version that is located in /usr/lib/python3/dist-packages/ according to your error log.

Title: No module named externals in mplot3d

Body:
I am trying to visualize the 3d plot using mpl_toolkits.mplot3d.Axes3D with matplotlib

I am using python 3 with matplot version '2.1.0' and scikit-learn verison 0.19.0. When i run the code it is producing the following error,

from matplotlib.externals import six
ImportError: No module named 'matplotlib.externals'

I tried to solve this issue by removing existing matplotlib and installing again, without any luck.

i am trying to run this code

import numpy as np
import mglearn
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from mpl_toolkits.mplot3d import Axes3D, axes3d

X, y = make_blobs(centers=4, random_state=8)
y = y % 2

X_new = np.hstack([X, X[:, 1:] ** 2])

figure = plt.figure()
ax = Axes3D(figure, elev=-152, azim=-26)
# plot first all the points with y == 0, then all with y == 1
mask = y == 0
ax.scatter(X_new[mask, 0], X_new[mask, 1], X_new[mask, 2], c='b', cmap=mglearn.cm2, s=60)
ax.scatter(X_new[mask, 0], X_new[mask, 1], X_new[mask, 2], c='r', marker='^', cmap=mglearn.cm2, s=60)
ax.set_xlabel("feature0")
ax.set_ylabel("feature1")
ax.set_zlabel("feature1 ** 2")

plt.show()

Error log after installing sabron package
The minimum supported version is 2.4.6

  ver=ver, min_ver=_MIN_NUMEXPR_VERSION), UserWarning)
Traceback (most recent call last):
  File "/home/asif/ml-codes/matpolitlib-tutorials/example-two.py", line 5, in <module>
    from mpl_toolkits.mplot3d import Axes3D, axes3d
  File "/usr/lib/python3/dist-packages/mpl_toolkits/mplot3d/__init__.py", line 4, in <module>
    from matplotlib.externals import six
ImportError: No module named 'matplotlib.externals'

Body:
Execute:

sudo apt-get remove python3-matplotlib

This will remove the version that is located in /usr/lib/python3/dist-packages/ according to your error log.


问:
Threads(PThreads) stopping execution and going into wait state
I have been having this problem wherein my threads stop execution and go into a wait state(reason : unknown). Pseudo code is posted below followed by some explanation

```<code>int arr[1000];
T1
{
tmp = arr[i];
}
T2
{
tmp=arr[i];
}
T3
{
arr[i] = value;
}
Main()
{
spawns of threads and waits for them to finish;
}
</code>```

So the only thing that is shared across these threads is the array, T3 writes into this array and T1,T2 read from it and use it for some purpose.
When I execute the program all three threads work fine and do what is required of them but when I try to run it for longer periods, after a while they stop execution and go into a wait state. The threads are still in the process mix but in less idle state. I do not know why this is happening and would greatly appreciate if someone can provide any useful pointers as to how I can find a resolution to this problem.

答:
I was going to say, check your mutex locking and unlocking, especially when using conditions, but you found your problem.

By the way....you don't necessarily need to use a mutex to read or write values to a shared array.  Check out gcc atomic operations if you need more speed!

Body:
I have been having this problem wherein my threads stop execution and go into a wait state(reason : unknown). Pseudo code is posted below followed by some explanation

int arr[1000];
T1
{
tmp = arr[i];
}
T2
{
tmp=arr[i];
}
T3
{
arr[i] = value;
}
Main()
{
spawns of threads and waits for them to finish;
}

So the only thing that is shared across these threads is the array, T3 writes into this array and T1,T2 read from it and use it for some purpose.
When I execute the program all three threads work fine and do what is required of them but when I try to run it for longer periods, after a while they stop execution and go into a wait state. The threads are still in the process mix but in less idle state. I do not know why this is happening and would greatly appreciate if someone can provide any useful pointers as to how I can find a resolution to this problem.


问:
currentregion.copy and destination stopper
I have a snippet of code

```<code>For Each wkSht In Sheets

    If Sheet6.Range("E3").Value = wkSht.Name Then
    wkSht.Range("A1").CurrentRegion.Copy Destination:=Sheet6.Range("A12")
    End If
Next
</code>```

need to modify this so that when copied to sheet6, it will not copy anything over row 200 and below. so in the event the currentregion is >= 187 rows, it will not copy/paste anything past that. Done some googling and can't find any solution to this

答:
You can simplify the code to what is below. Your post is a bit confusing because first you say below 200, then 187. Whatever you need can be placed in the rows argument of the Resize method.

```<code>Dim CopySheet as Worksheet
CopySheet = Worksheets(Sheet6.Range("E3").Value))

With CopySheet.Range("A1").CurrentRegion
    .Resize(186,.Columns.Count).Copy Destination:=Sheet6.Range("A12")
End With
</code>```

Body:
I have a snippet of code

For Each wkSht In Sheets

    If Sheet6.Range("E3").Value = wkSht.Name Then
    wkSht.Range("A1").CurrentRegion.Copy Destination:=Sheet6.Range("A12")
    End If
Next

need to modify this so that when copied to sheet6, it will not copy anything over row 200 and below. so in the event the currentregion is >= 187 rows, it will not copy/paste anything past that. Done some googling and can't find any solution to this

Body:
You can simplify the code to what is below. Your post is a bit confusing because first you say below 200, then 187. Whatever you need can be placed in the rows argument of the Resize method.

Dim CopySheet as Worksheet
CopySheet = Worksheets(Sheet6.Range("E3").Value))

With CopySheet.Range("A1").CurrentRegion
    .Resize(186,.Columns.Count).Copy Destination:=Sheet6.Range("A12")
End With


问:
onchange form input grabs value and submits form
click to see the toggle input

I have a form input for item quantity, it's formatted to have toggles for increasing and decreasing the value

```<code><input name="quantity" type="text" class="form-control text-center" id="quantity" value="<?php echo $crow[ 'quantity' ];?>" />
</code>```

How could I use javascript to run a function on change or on click and grab it's value and submit a form?

Thanks for your help

I now have

```<code>function changeQuant(){
     var x = document.getElementById("quantity").value;
     document.getElementById('fquant').submit();
}
</code>```

and the form submits on change

```<code><form action="cartplusone.php" method="post" id="fquant" >
   <td class="input-qty"><input name="quantity" type="text" class="form-control text-center" id="quantity" onchange="changeQuant()" value="<?php echo $crow[ 'quantity' ];?>" /></td>
   <input name="newqval" type="hidden" id="newqval" value="">
</form>
</code>```

How do I now best get the var x value into the hidden form field?

答:
Maybe you're searching this:

```<code><script>
$('#quantity').on('change', function() {
  alert($(this).val());
})
</script>
</code>```

Note: This solution requires JQuery!

Body:
click to see the toggle input

I have a form input for item quantity, it's formatted to have toggles for increasing and decreasing the value

<input name="quantity" type="text" class="form-control text-center" id="quantity" value="<?php echo $crow[ 'quantity' ];?>" />

How could I use javascript to run a function on change or on click and grab it's value and submit a form?

Thanks for your help

I now have

function changeQuant(){
     var x = document.getElementById("quantity").value;
     document.getElementById('fquant').submit();
}

and the form submits on change

<form action="cartplusone.php" method="post" id="fquant" >
   <input name="quantity" type="text" class="form-control text-center" id="quantity" onchange="changeQuant()" value="<?php echo $crow[ 'quantity' ];?>" />
   <input name="newqval" type="hidden" id="newqval" value="">
</form>

How do I now best get the var x value into the hidden form field?

Body:
Maybe you're searching this:

<script>
$('#quantity').on('change', function() {
  alert($(this).val());
})
</script>

Note: This solution requires JQuery!


问:
Custom Tooltip in Google Chart Timeline using php
Starting off, I want to say everything is working here, I am just wondering how can I attach a custom tooltip for the results.

I tried to add a new column type string and role tooltip and set the row v as a tooltip but it didn't worked

PHP Generator

```<code>$table['cols'] = array(

            array('label' => 'str1', 'type' => 'string'),
            array('label' => 'str1', 'type' => 'string'),
            array('label' => 'data1', 'type' => 'date'),
            array('label' => 'data2', 'type' => 'date')
        );

        foreach ($query as $r) {
            $date1 = new DateTime($r['data_zakupu']);
            $date2 = "Date(" . date_format($date1, 'Y') . ", " . ((int)date_format($date1, 'm') - 1) . ", " . date_format($date1, 'j') . ")";

            $date3 = new DateTime($r['data_zakupu']);
            $date3->modify("+ 1 day");
            $date4 = "Date(" . date_format($date3, 'Y') . ", " . ((int)date_format($date3, 'm') - 1) . ", " . date_format($date3, 'j') . ")";

            $temp = array();
            if (!isset($pojazd)) {
                $temp[] = array('v' => (string)$r['nr_rej']);
            } else {
                $temp[] = array('v' => (string)$r['kat']);
            }

            if ($r['kat'] === "Paliwo") {
                $alias = $r['litry'] . " L";
            } else {
                $alias = $r['kat']." - ".$r['brutto'] . " zł";
            }
            $temp[] = array('v' => (string)$alias);
            $temp[] = array('v' => (string)$date2);
            $temp[] = array('v' => (string)$date4);

            $rows[] = array('c' => $temp);
        }
        $table['rows'] = $rows;
 echo json_encode($table);
</code>```

HTML + JS

```<code><script type="text/javascript"
                        src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    var d = new Date();
    var n = d.getMonth() + 1;
    var y = d.getFullYear();

    $('#month_picker').val(n);
    $('#year_picker').val(y);

    google.charts.load("current", {packages: ["timeline"], 'language': 'pl'});
    google.charts.setOnLoadCallback(drawChart);
    $("#users").change(drawChart);

    $('#month_picker').on('change', function () {
        drawChart();
    });

    $(window).on("throttledresize", function (event) {
        drawChart();
    });

    function drawChart() {
        $.ajax({
            url: '',
            type: "POST",
            data: {
                customMonth: $('#month_picker').val(),
                customYear: $('#year_picker').val(),
            },
            dataType: 'json',
            success: function (responseText) {
                var container = document.getElementById('visualization');
                var chart = new google.visualization.Timeline(container);
                var dataTable = new google.visualization.DataTable(responseText);

                var options = {
                    timeline: {colorByRowLabel: true}
                };
                $(window).trigger('resize');
                chart.draw(dataTable, options);
            },
            error: function (jqXHR, textStatus, errorThrown) {
            }
        });
    }
    $(window).resize(function() {
        $('#visualization').height('500px');// need autoheight

    });
</script>
<div id="visualization" style="width: 100%;"></div>
</code>```

JSON generated by php : https://jsonblob.com/17856337-ca0e-11e7-9220-89c8556cdc82

答:
according to the data format for a Timeline,

the tooltip should be in Column 2

as such, the column definitions would be as follows...

```<code>$table['cols'] = array(
  array('label' => 'str1', 'type' => 'string'),
  array('label' => 'str1', 'type' => 'string'),
  array('role' => 'tooltip', 'type' => 'string'),
  array('label' => 'data1', 'type' => 'date'),
  array('label' => 'data2', 'type' => 'date')
);
</code>```

then add the tooltip content to each row...

```<code>...
$temp[] = array('v' => (string)$alias);
$temp[] = array('v' => (string)$tooltip);
$temp[] = array('v' => (string)$date2);
$temp[] = array('v' => (string)$date4);

$rows[] = array('c' => $temp);
</code>```

Body:
Starting off, I want to say everything is working here, I am just wondering how can I attach a custom tooltip for the results.

I tried to add a new column type string and role tooltip and set the row v as a tooltip but it didn't worked

PHP Generator

$table['cols'] = array(

            array('label' => 'str1', 'type' => 'string'),
            array('label' => 'str1', 'type' => 'string'),
            array('label' => 'data1', 'type' => 'date'),
            array('label' => 'data2', 'type' => 'date')
        );

        foreach ($query as $r) {
            $date1 = new DateTime($r['data_zakupu']);
            $date2 = "Date(" . date_format($date1, 'Y') . ", " . ((int)date_format($date1, 'm') - 1) . ", " . date_format($date1, 'j') . ")";

            $date3 = new DateTime($r['data_zakupu']);
            $date3->modify("+ 1 day");
            $date4 = "Date(" . date_format($date3, 'Y') . ", " . ((int)date_format($date3, 'm') - 1) . ", " . date_format($date3, 'j') . ")";

            $temp = array();
            if (!isset($pojazd)) {
                $temp[] = array('v' => (string)$r['nr_rej']);
            } else {
                $temp[] = array('v' => (string)$r['kat']);
            }

            if ($r['kat'] === "Paliwo") {
                $alias = $r['litry'] . " L";
            } else {
                $alias = $r['kat']." - ".$r['brutto'] . " zł";
            }
            $temp[] = array('v' => (string)$alias);
            $temp[] = array('v' => (string)$date2);
            $temp[] = array('v' => (string)$date4);

            $rows[] = array('c' => $temp);
        }
        $table['rows'] = $rows;
 echo json_encode($table);

HTML + JS

JSON generated by php : https://jsonblob.com/17856337-ca0e-11e7-9220-89c8556cdc82

Body:
according to the data format for a Timeline,

the tooltip should be in Column 2

as such, the column definitions would be as follows...

$table['cols'] = array(
  array('label' => 'str1', 'type' => 'string'),
  array('label' => 'str1', 'type' => 'string'),
  array('role' => 'tooltip', 'type' => 'string'),
  array('label' => 'data1', 'type' => 'date'),
  array('label' => 'data2', 'type' => 'date')
);

then add the tooltip content to each row...

...
$temp[] = array('v' => (string)$alias);
$temp[] = array('v' => (string)$tooltip);
$temp[] = array('v' => (string)$date2);
$temp[] = array('v' => (string)$date4);

$rows[] = array('c' => $temp);


问:
Promise resolves to null when resolving this
I have a function that connects to a API. That function returns a Promise. I can't figure out why Promise.resolve returns null when I'm resolving with a constant containing the this context.

```<code>const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      console.log(platform) // Object that I want
      resolve(platform)
    });
  });
}

connect()
  .then(platform => {
    console.log(platform) // null
  })
</code>```

I don't know if it is any help but I know there is a method on the resolve object (platform) called datastore. If I resolve that method, ie resolve(platform.datastore) I get the method, instead of null

I have tried to resolve static values, resolve(25) or resolve('hello') and that works fine.

How do I return/resolve the object?

答:
Turns out that platform, the object to resolve, also has a then method. If you resolve the original promise with a new promise then it will try to resolve the new one as well. In this case the new promise resolves to null.

```<code>const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      delete platform.this;
      resolve(platform);
    });
  });
}
</code>```

The next question is how to do this in a better way than deleting every obsolete then method.

Body:
I have a function that connects to a API. That function returns a Promise. I can't figure out why Promise.resolve returns null when I'm resolving with a constant containing the this context.

const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      console.log(platform) // Object that I want
      resolve(platform)
    });
  });
}

connect()
  .then(platform => {
    console.log(platform) // null
  })

I don't know if it is any help but I know there is a method on the resolve object (platform) called datastore. If I resolve that method, ie resolve(platform.datastore) I get the method, instead of null

I have tried to resolve static values, resolve(25) or resolve('hello') and that works fine.

How do I return/resolve the object?

Body:
Turns out that platform, the object to resolve, also has a then method. If you resolve the original promise with a new promise then it will try to resolve the new one as well. In this case the new promise resolves to null.

const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      delete platform.this;
      resolve(platform);
    });
  });
}

The next question is how to do this in a better way than deleting every obsolete then method.


问:
Font sizes on different pages
Ok so I'm not sure if questions like this are allowed on here so if not please tell me and I will remove it. My question is about whether font sizes should be the same on all pages.

Here's my situation. I have several headings spread across multiple pages on a website which I am creating. They all use the same styles but as they all have different character lengths when the screen gets smaller some of the headings start breaking at points which just make the website look rubbish. To make a couple of these heading look good I have had to use a font size of 16px, which isn't ideal as the the body text is 16px but still it looks better than what it did look like.

So what would you usually do in this situation? Would you keep all the headings the same size to keep in theme with the other pages? or is it ok to have some smaller than others? will the user even notice?

答:
As Albert mentioned in previous response, you should totally keep the headlines in the same size.

As a part of best practises "always use ems to set font sizes". You can update/ modify the size of body text with respect to your header font size.

For example: keep header size as 2em and make body text size as 1em or 1.2em as per your design requirements.

For further readings on this you can refer: W3S guidelines for font sizes

Title: Font sizes on different pages


问:
Python Scipy interpolate warning message
I am trying to fit a spline surface to some 2D data using scipy interpolate

```<code>from scipy import interpolate
</code>```

Using

```<code> # fit spline to surface
 xnew, ynew = np.mgrid[x[0]:x[-1]:100j, y[0]:y[-1]:100j]
 tck = interpolate.bisplrep(X, Z, array)
 znew = interpolate.bisplev(xnew[:,0], ynew[0,:], tck)
</code>```

But I'm getting the following warning messages:

C:\Users...\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\interpolate_fitpack_impl.py:975:
  RuntimeWarning: A theoretically impossible result when finding a
  smoothing spline with fp = s. Probable causes: s too small or badly
  chosen eps. (abs(fp-s)/s>0.001)
          kx,ky=3,3 nx,ny=16,18 m=610 fp=18417275715.663498 s=575.071502   warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess))
  C:\Users...\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\interpolate_fitpack_impl.py:975:
  RuntimeWarning: The required storage space exceeds the available
  storage space. Probable causes: nxest or nyest too small or s is too
  small. (fp>s)
          kx,ky=3,3 nx,ny=20,20 m=610 fp=661.198585 s=575.071502   warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess))
  C:\Users...\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\interpolate_fitpack_impl.py:975:
  RuntimeWarning: The required storage space exceeds the available
  storage space. Probable causes: nxest or nyest too small or s is too
  small. (fp>s)
          kx,ky=3,3 nx,ny=20,20 m=610 fp=1013.605606 s=575.071502   warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess))

And instead of getting something similar to my data:

I'm getting this:

I admit I don't know what the warning messages mean and haven't found anything on the internet.

答:
Seems like your input data contains too few data points? Another issue might be that your x and y axes have very different order of magnitude. I don't know if that is a problem for bisplrep, but other interpolation algorithms do not like that.

I had more success with scipy.interpolate.Rbf, which also gives a very smooth result.

Body:
I am trying to fit a spline surface to some 2D data using scipy interpolate

from scipy import interpolate

Using

 # fit spline to surface
 xnew, ynew = np.mgrid[x[0]:x[-1]:100j, y[0]:y[-1]:100j]
 tck = interpolate.bisplrep(X, Z, array)
 znew = interpolate.bisplev(xnew[:,0], ynew[0,:], tck)

But I'm getting the following warning messages:

C:\Users...\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\interpolate_fitpack_impl.py:975:
  RuntimeWarning: A theoretically impossible result when finding a
  smoothing spline with fp = s. Probable causes: s too small or badly
  chosen eps. (abs(fp-s)/s>0.001)
          kx,ky=3,3 nx,ny=16,18 m=610 fp=18417275715.663498 s=575.071502   warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess))
  C:\Users...\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\interpolate_fitpack_impl.py:975:
  RuntimeWarning: The required storage space exceeds the available
  storage space. Probable causes: nxest or nyest too small or s is too
  small. (fp>s)
          kx,ky=3,3 nx,ny=20,20 m=610 fp=661.198585 s=575.071502   warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess))
  C:\Users...\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\interpolate_fitpack_impl.py:975:
  RuntimeWarning: The required storage space exceeds the available
  storage space. Probable causes: nxest or nyest too small or s is too
  small. (fp>s)
          kx,ky=3,3 nx,ny=20,20 m=610 fp=1013.605606 s=575.071502   warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess))

And instead of getting something similar to my data:

I'm getting this:

I admit I don't know what the warning messages mean and haven't found anything on the internet.


问:
How an output of Windows application executed on remote SSH server gets to a local SSH client
I'm using PuTTY to connect to an SSH server running on Windoes 7.

When I issue powershell in PuTTY terminal does it mean that the powershell command window opens on the remote machine?

If so how does the output from remotely running powershell window gets routed to PuTTY client?

Sorry if this is lame question but it's not so obvious to me.

答:
While the PowerShell is executed on the remote machine, no window opens on the server.

powershell.exe is a console application. Console applications have a standard IO (input and output). If you run a Windows console application locally, Windows GUI creates a console window and binds the application IO to the window. While if you run a console application via an SSH server, the SSH server binds the application IO to the SSH shell session. So anything that the PowerShell prints, gets routed to the SSH shell session output, which ultimately renders in your local SSH client window (PuTTY).

In other words, a local PowerShell window is rendered by Windows GUI (the system that executes the PowerShell), not by the PowerShell process itself (contrary to windows of GUI applications). Another system, like the SSH server, can choose a completely different "rendering" of the IO, like routing the IO to the SSH shell session.

It's the same process like, if you use ls command on a *nix server. The ls is also a console application. (Afaik, all *nix applications are actually console applications, what is not true on Windows.)


问:
Making my own haarcascade
I know how to use already made haarcascades for face,eyes detection etc. But I wanted to create a haarcascade to recognize a ceiling fan(both when it is turned ON or OFF). Can anyone give me some good suggestions on how can I make such a haarcascade?Thanks in advance!

答:
I followed this video and made Haarcascades for bikes and heavy vehicle detection and it was helpful

SentDex Making our own HaarCascades

Title: Making my own haarcascade