问:
How to check if multiple subscriptions reached onComplete()?
I have two subscriptions in an Angular 6 component.
Now I want to start a method as soon as these two subscriptions reached onComplete.

How can I do this the easiest way?

答:
We can use merge operator which allows us to subscribe multiple observables in parallel.</p>

```<code>const stream1$ = of (1,2,3);
    const stream2$ = of (4,5,6);
    const result$ = merge(stream1$, stream2$);
    result$.subscribe(
// value
      (val) => {console.log(val) },
// error
    (err) => { console.log(err) },
//on complete
    ()=>{console.log('completed') });
</code>```

Body:
We can use merge operator which allows us to subscribe multiple observables in parallel.

const stream1$ = of (1,2,3);
    const stream2$ = of (4,5,6);
    const result$ = merge(stream1$, stream2$);
    result$.subscribe(
// value
      (val) => {console.log(val) },
// error
    (err) => { console.log(err) },
//on complete
    ()=>{console.log('completed') });


来源: stackexchange

问:
Why is the XPath not valid?
The problem is that the XPath I get from Chrome is not correct or I do not know how to edit it so I can make it usable. I wanna parse it so i can get the results through a discord bot.

I did not try anything at all, I have no experience in using XPath so that is why I am here.

```<code>//*[@id="home"]/div/div/div[1]/div/table/tbody/tr[1]/td[2]
</code>```

What should happen is(if the xpath path would work) that I get a result through a discord bot but the path is not correct.

Could not store a value from path //*
   [@id="home"]/div/div/div[1]/div/table/tbody/tr[1]/td[2], Check that the path is valid!

答:
Use the following Xpath.</p>

```<code>//table[@class='table bb']//tr[1]/td[2]/@text
</code>```

ContentLicense: CC BY-SA 4.0

Title: Why is the XPath not valid?

Body:
The problem is that the XPath I get from Chrome is not correct or I do not know how to edit it so I can make it usable. I wanna parse it so i can get the results through a discord bot.

I did not try anything at all, I have no experience in using XPath so that is why I am here.

//*[@id="home"]/div/div/div[1]/div/table/tbody/tr[1]/td[2]

What should happen is(if the xpath path would work) that I get a result through a discord bot but the path is not correct.

Could not store a value from path //*
   [@id="home"]/div/div/div[1]/div/table/tbody/tr[1]/td[2], Check that the path is valid!

Body:
Use the following Xpath.

//table[@class='table bb']//tr[1]/td[2]/@text


问:
How to write a vlookup in vba in a sheet that contains 5000 rows of data?
```<code>Sub test
    Dim z As Long
    z = Range("A" & Rows.Count).End(xlUp).Row
    Range("C4").Formula ="=Vlookup(A4, '[EMP.txt]EMP'!$A$2:$C2,3,False)"
    Range("C4").Copy
    Range("C4:C" & z).pastspecial xlPasteAll
End sub
</code>```

My formula works in my code but it omits a couple rows so my totals don’t match. If I change the vlookup Formula to =Vlookup(A4,’[EMP.txt]EMP’!$A$2:$C176,3,False), it will pull over everything but the range will change on a week to week basis. How do I fix this?

答:
Becasue in your code you already have a variable named z where you store row of last non-blank cell in Column A, you can use that same row number to update your range in your Vlookup

So replace line:

```<code>Range("C4").Formula ="=Vlookup(A4, '[EMP.txt]EMP'!$A$2:$C2,3,False)"
</code>```

With

```<code>Range("C4").Formula ="=Vlookup(A4, '[EMP.txt]EMP'!$A$2:$C" & z & ",3,False)"
</code>```

Body:
Sub test
    Dim z As Long
    z = Range("A" & Rows.Count).End(xlUp).Row
    Range("C4").Formula ="=Vlookup(A4, '[EMP.txt]EMP'!$A$2:$C2,3,False)"
    Range("C4").Copy
    Range("C4:C" & z).pastspecial xlPasteAll
End sub

My formula works in my code but it omits a couple rows so my totals don’t match. If I change the vlookup Formula to =Vlookup(A4,’[EMP.txt]EMP’!$A$2:$C176,3,False), it will pull over everything but the range will change on a week to week basis. How do I fix this?

Body:
Becasue in your code you already have a variable named z where you store row of last non-blank cell in Column A, you can use that same row number to update your range in your Vlookup

So replace line:

Range("C4").Formula ="=Vlookup(A4, '[EMP.txt]EMP'!$A$2:$C2,3,False)"

With

Range("C4").Formula ="=Vlookup(A4, '[EMP.txt]EMP'!$A$2:$C" & z & ",3,False)"


问:
How can I disable the shadow dropping behind a sub-menu in GWT MenuBar?
I created a MenuBar with collapsing sub-menus using Googles GWT like in this example: GWT Showcase MenuBar

Hovering over a MenuItem opens a sub-menu if defined. The sub-menu drops a non-css3 shadow, which doesn't fit into my ui design, because I'm using a differently styled css3 box-shadow.

At first sight one doesn't seem to be able to disable this shadow in some property... does someone have an idea how to?

答:
The MenuBar popup is a 9-box - a table with 9 cells. The boxes in the table have style names matching the pattern .menuPopup[Position] and .menuPopup[Position]Inner, where Position is, for example, TopLeft, BottomRight, Left, etc.

If you copied the styles from the Showcase it should be sufficient to remove all references to the cells that are not .menuPopupMiddleCenter or .menuPopupMiddleCenterInner to remove the drop shadow you see.

ContentLicense: CC BY-SA 3.0


问:
How to search multiple keywords in paragraph and highlight the each keyword with different color in javascript using ReactJS?
I want to search one or multiple keywords from multiple bunch of texts, and trying to highlight each keyword with different color. I am using ReactJS redux.

I tried to do the same using Regex but i'm getting the same result what i want. It is working fine when i'm searching only one keyword. But when i'm searching more than one keywords, it display the same keyword multiple times.

And Please help to highlight different keyword with different colors. I am not able to achieve it.

```<code>export default class SolrSearchComponent extends Component {
render(){
      var allText = "Sea and Sky is your one-stop source for all things related. Sea and Sky is your one-stop source for all things related.";

      var KeywordsTosearch = ["Sea", "sky"];

      var parts = allText.split(new RegExp(`(${KeywordsTosearch.join("|")})`, "gi"));

      var tempKeyword=[];

        tempKeyword.push(
          <span>
            { parts.map((part, i) =>
              KeywordsTosearch.map((keyword,i) =>
             <span key={i} style={  part.toLowerCase() === keyword.toLowerCase() ?  { fontWeight: 'bold', color: 'red' } : {} }>
                { part }
              </span>)
            )
            }
          </span>
        );
        retrun(
        <div>
        {tempKeyword}
        </div>
        )
    }
}
</code>```

I'm expecting multiple keywords highlighted in different colors in result and also text should not print multiple times.

If i'm searching "Sea Sky" it show following in result :

Sea and Sky Sea and Sky is your one-stop source for all things related is your one-stop source for all things related. Sea and Sky Sea and Sky is your one-stop source for all things related is your one-stop source for all things related.

I want result like this:

Sea and Sky is your one-stop source for all things related. Sea and Sky is your one-stop source for all things related.

Note: Sea should be in red text and sky in blue text color.

答:
You can first define an object to hold the color for each of the keyword, then use it later

```<code>const styles = {
  "sea": {
    fontWeight: "bold", color: "red"
  },
  "sky": {
    fontWeight: "bold", color: "blue"
  }
}

// use it
<span style={styles[keyword] || {}}>...</span>
</code>```

Next nested looping of of both parts and KeywordsTosearch is causing the randomly repeated text

```<code>parts.map((part, i) => KeywordsTosearch.map((keyword,i) => { })
</code>```

Since 'KeywordsTosearch' had already done it's job in splitting the sentence, you just need to loop 'parts' to apply the styles

```<code>var tempKeyword = [];
tempKeyword = parts.map((part, i) =>
  <span
    key={i}
    style={this.getStyle(part)}>
    {part}
  </span>
)

</code>```

See working example https://codesandbox.io/s/recursing-turing-7m56b

Body:
I want to search one or multiple keywords from multiple bunch of texts, and trying to highlight each keyword with different color. I am using ReactJS redux.

I tried to do the same using Regex but i'm getting the same result what i want. It is working fine when i'm searching only one keyword. But when i'm searching more than one keywords, it display the same keyword multiple times.

And Please help to highlight different keyword with different colors. I am not able to achieve it.

export default class SolrSearchComponent extends Component {
render(){
      var allText = "Sea and Sky is your one-stop source for all things related. Sea and Sky is your one-stop source for all things related.";

      var KeywordsTosearch = ["Sea", "sky"];

      var parts = allText.split(new RegExp(`(${KeywordsTosearch.join("|")})`, "gi"));

      var tempKeyword=[];

        tempKeyword.push(

            { parts.map((part, i) =>
              KeywordsTosearch.map((keyword,i) =>

                { part }
              )
            )
            }

        );
        retrun(

        {tempKeyword}

        )
    }
}

I'm expecting multiple keywords highlighted in different colors in result and also text should not print multiple times.

If i'm searching "Sea Sky" it show following in result :

Sea and Sky Sea and Sky is your one-stop source for all things related is your one-stop source for all things related. Sea and Sky Sea and Sky is your one-stop source for all things related is your one-stop source for all things related.

I want result like this:

Sea and Sky is your one-stop source for all things related. Sea and Sky is your one-stop source for all things related.

Note: Sea should be in red text and sky in blue text color.

Body:
You can first define an object to hold the color for each of the keyword, then use it later

const styles = {
  "sea": {
    fontWeight: "bold", color: "red"
  },
  "sky": {
    fontWeight: "bold", color: "blue"
  }
}

// use it
<span style={styles[keyword] || {}}>...</span>

Next nested looping of of both parts and KeywordsTosearch is causing the randomly repeated text

parts.map((part, i) => KeywordsTosearch.map((keyword,i) => { })

Since 'KeywordsTosearch' had already done it's job in splitting the sentence, you just need to loop 'parts' to apply the styles

var tempKeyword = [];
tempKeyword = parts.map((part, i) =>
  <span
    key={i}
    style={this.getStyle(part)}>
    {part}
  </span>
)

See working example https://codesandbox.io/s/recursing-turing-7m56b


问:
How to make a loop that successively includes one more element of a numpy array in order to calculate the running variance?
I have numbers stored in an array like [1, 6, 12, 4...].  I want to do a calculation where each new iteration will use one more element of the array.

For example, the first iteration will use only the number 1.

The second iteration will use 1 and 6.

The third will use 1, 6, and 12, and so on.

More detail for anyone interested in statistics/variance in Python:

I want to calculate running variance on the data in the array. It seems straightforward to get variance on a whole array in Python. So I'll put my array up to element i inside the loop.  I will calculate variance on the array as looping progresses and the array "grows."  If anyone knows a better way to do this, I would be grateful to know.

答:
For the purpose of calculating the running variance on a numpy array, you can use slices in a list comprehension as follows:

```<code>import numpy as np
a = [1, 6, 12, 4]
running_var = [np.var(a[:i+1]) for i in range(len(a))]
print(running_var)
#[0.0, 6.25, 20.222222222222225, 16.1875]
</code>```

But as your list grows big, you're going to be wasting computations. A more efficient way would be to keep track of the running sum of the values in a and the running sum of the squares of a.

```<code>running_sum = 0.
running_sum_of_squares = 0.
running_var = []
for i,x in enumerate(a):
    running_sum += x
    running_sum_of_squares += x*x
    n = i+1.
    running_var.append((running_sum_of_squares - running_sum*running_sum/n)/n)
print(running_var)
#[0.0, 6.25, 20.222222222222225, 16.1875]
</code>```

This computation is for the population variance, but you can easily adjust it for the sample variance.

Timing results

Just to demonstrate the vast speed improvement of the second method, here is a timing comparison:

Create large random sample

```<code>np.random.seed(0)
N = 100000
a = np.random.randn(N)
</code>```

Method 1: List comprehension

```<code>%%timeit
running_var = [np.var(a[:i+1]) for i in range(len(a))]
# 1 loop, best of 3: 11.1 s per loop
</code>```

Method 2: Incremental variance calculation

```<code>def get_running_var(a):
    running_sum = 0.
    running_sum_of_squares = 0.
    running_var = []
    for i,x in enumerate(a):
        running_sum += x
        running_sum_of_squares += x*x
        n = i+1.
        running_var.append((running_sum_of_squares - running_sum*running_sum/n)/n)
    return running_var

%%timeit
get_running_var(a)
# 10 loops, best of 3: 60.5 ms per loop
</code>```

For an array of size 100,000, the incremental calculation is over 180 times faster!

I couldn't run the speed test on the @user3483203's answer with N = 100000 due to a MemoryError, so I repeated the tests for an array of size 10,000.

The results were the following:

List comprehension: 100 loops, best of 3: 268 ms per loop

Incremental Variance: 100 loops, best of 3: 6.09 ms per loop

user3483203's method: 1 loop, best of 3: 5.73 s per loop

Body:
For the purpose of calculating the running variance on a numpy array, you can use slices in a list comprehension as follows:

import numpy as np
a = [1, 6, 12, 4]
running_var = [np.var(a[:i+1]) for i in range(len(a))]
print(running_var)
#[0.0, 6.25, 20.222222222222225, 16.1875]

But as your list grows big, you're going to be wasting computations. A more efficient way would be to keep track of the running sum of the values in a and the running sum of the squares of a.

running_sum = 0.
running_sum_of_squares = 0.
running_var = []
for i,x in enumerate(a):
    running_sum += x
    running_sum_of_squares += x*x
    n = i+1.
    running_var.append((running_sum_of_squares - running_sum*running_sum/n)/n)
print(running_var)
#[0.0, 6.25, 20.222222222222225, 16.1875]

This computation is for the population variance, but you can easily adjust it for the sample variance.

Timing results

Just to demonstrate the vast speed improvement of the second method, here is a timing comparison:

Create large random sample

np.random.seed(0)
N = 100000
a = np.random.randn(N)

Method 1: List comprehension

%%timeit
running_var = [np.var(a[:i+1]) for i in range(len(a))]
# 1 loop, best of 3: 11.1 s per loop

Method 2: Incremental variance calculation

def get_running_var(a):
    running_sum = 0.
    running_sum_of_squares = 0.
    running_var = []
    for i,x in enumerate(a):
        running_sum += x
        running_sum_of_squares += x*x
        n = i+1.
        running_var.append((running_sum_of_squares - running_sum*running_sum/n)/n)
    return running_var

%%timeit
get_running_var(a)
# 10 loops, best of 3: 60.5 ms per loop

For an array of size 100,000, the incremental calculation is over 180 times faster!

I couldn't run the speed test on the @user3483203's answer with N = 100000 due to a MemoryError, so I repeated the tests for an array of size 10,000.

The results were the following:

List comprehension: 100 loops, best of 3: 268 ms per loop

Incremental Variance: 100 loops, best of 3: 6.09 ms per loop

user3483203's method: 1 loop, best of 3: 5.73 s per loop


问:
Found average of one variable per value of other variable, but how to use the result?
I have to extract some meaning from a dataset of age, weight, and exercise time.

I was able to find the average weight for each age, but now I don't now what to do with that data because it is not a column or an array. I can I turn this into something useful if I want to plot it or use it in a function.

```<code>person_data_url = 'url'
df = pd.read_csv(persons_data_url, ...)

avg = df.groupby('age')['weight'].aggregate(np.mean)
</code>```

looks like this

```<code>age
18    148.000000
19    125.086957
20    161.000000
21    171.500000
22    119.368421
23    139.285714
24    149.411765
25    167.789474
26    186.400000
27    161.500000
</code>```

Is it possible to make a plot or graph where each average weight was on the y-axis and the age on the x-axis?

答:
You can use matplotlib and reset_index() on your calculated dataframe and then just simply plot the columns vs one another:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'age': np.random.randint(18,27,size=100),
    'weight': np.random.randint(120,240,size=100)
})

avg = df.groupby('age').agg('mean').reset_index()

plt.figure(1)
plt.plot(avg['age'], avg['weight'])
plt.xlabel('Age')
plt.ylabel('Weight')
plt.title('Weight vs Age')
plt.show()
</code>```

Body:
I have to extract some meaning from a dataset of age, weight, and exercise time.

I was able to find the average weight for each age, but now I don't now what to do with that data because it is not a column or an array. I can I turn this into something useful if I want to plot it or use it in a function.

person_data_url = 'url'
df = pd.read_csv(persons_data_url, ...)

avg = df.groupby('age')['weight'].aggregate(np.mean)

looks like this

age
18    148.000000
19    125.086957
20    161.000000
21    171.500000
22    119.368421
23    139.285714
24    149.411765
25    167.789474
26    186.400000
27    161.500000

Is it possible to make a plot or graph where each average weight was on the y-axis and the age on the x-axis?

Body:
You can use matplotlib and reset_index() on your calculated dataframe and then just simply plot the columns vs one another:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'age': np.random.randint(18,27,size=100),
    'weight': np.random.randint(120,240,size=100)
})

avg = df.groupby('age').agg('mean').reset_index()

plt.figure(1)
plt.plot(avg['age'], avg['weight'])
plt.xlabel('Age')
plt.ylabel('Weight')
plt.title('Weight vs Age')
plt.show()


问:
Is there a way to filter using both 'AND' and 'OR' for a python data frame?
I am trying to filter a Pandas data frame using a series of conditions in python.

```<code>filtered_df = data[(data['Dependant'].isnull())|(data['cust2_status']=='closed'), (data['cust1_status']== 'active')]
</code>```

I was hoping to get a subset of rows were dependant = null OR customer 2 = 'closed' AND customer 1 = 'active'. The error I am receiving is "'Series' objects are mutable, thus they cannot be hashed".

答:
Yes.

Docs: loc

```<code>filtered_df = data.loc[(((data['Dependant'].isnull()|(data['cust2_status']=='closed')) & (data['cust1_status']== 'active'))]

</code>```

Body:
I am trying to filter a Pandas data frame using a series of conditions in python.

filtered_df = data[(data['Dependant'].isnull())|(data['cust2_status']=='closed'), (data['cust1_status']== 'active')]

I was hoping to get a subset of rows were dependant = null OR customer 2 = 'closed' AND customer 1 = 'active'. The error I am receiving is "'Series' objects are mutable, thus they cannot be hashed".

Body:
Yes.

Docs: loc

filtered_df = data.loc[(((data['Dependant'].isnull()|(data['cust2_status']=='closed')) & (data['cust1_status']== 'active'))]


问:
I can upload images to specific directory but can't view them in template (Page not found (404))
I am trying to add upload image to admin form in my Django project I found on GitHub. I can upload image to folder my_app(catalog)/media/images/image.png but when I try to call it in the template I can only see that image icon that appears when there is no picture.

settings.py

```<code>STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT  = os.path.join(BASE_DIR, 'catalog/media')
</code>```

model.py

```<code>class Book(models.Model):
    image = models.ImageField(blank=True, null = True, upload_to='images')
</code>```

book_detail.html

```<code>img src="{{ book.image.url}}" width="250"
</code>```

views.py

```<code>class BookDetailView(generic.DetailView):
    model = Book
</code>```

urls.py

```<code>from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('', views.index, name='index'),
    path('book/create/', views.BookCreate.as_view(), name='book_create'),
    path('books/', views.BookListView.as_view(), name='books'),
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

This is how it looks like (I print {{ book.image }} next to the picture (images/screenshot_4.png):

This is the error I get:

答: You may have dropped a ']' at the end of your urlpatterns or maybe I am mistaken</p>

Body:
I am trying to add upload image to admin form in my Django project I found on GitHub. I can upload image to folder my_app(catalog)/media/images/image.png but when I try to call it in the template I can only see that image icon that appears when there is no picture.

settings.py

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT  = os.path.join(BASE_DIR, 'catalog/media')

model.py

class Book(models.Model):
    image = models.ImageField(blank=True, null = True, upload_to='images')

book_detail.html

img src="{{ book.image.url}}" width="250"

views.py

class BookDetailView(generic.DetailView):
    model = Book

urls.py

from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('', views.index, name='index'),
    path('book/create/', views.BookCreate.as_view(), name='book_create'),
    path('books/', views.BookListView.as_view(), name='books'),
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This is how it looks like (I print {{ book.image }} next to the picture (images/screenshot_4.png):

This is the error I get:


问:
Use Ansible inventory IP in Playbook
I have an inventory file called inventory.ini which contains exactly just:

```<code>10.0.0.4
10.0.0.5
</code>```

I would like to use the IPs listed here in the my Playbook under the variable ip_address:

```<code>- name: Import & load configuration file into PAN-OS
  hosts: localhost
  connection: local
  gather_facts: False

  vars:
    ip_address: "{{ SOMETHING-GOES-HERE }}"
    username: "#{PALOS_USERNAME}#"
    password: "#{PALOS_PASSWORD}#"
    config_file: ""
    load_file: ""

  roles:
  - role: PaloAltoNetworks.paloaltonetworks

  tasks:
  - name: wait for reboot
    panos_check:
      ip_address: "{{ ip_address }}"
      username: "{{ username }}"
      password: "{{ password }}"
      interval: 5
      timeout: 900

  - name: import configuration file into PAN-OS
    panos_import:
      ip_address: "{{ ip_address }}"
      username: "{{ username }}"
      password: "{{ password }}"
      file: "{{ config_file }}"
      category: "configuration"
</code>```

I have tried using {{ inventory_hostname }}, but that brings back localhost instead. I have also tried using {{ ansible_host }}, but that brings back 127.0.0.1

Does anyone know how I can use the IPs listed in the inventory in place of the variable as it loops through each deployment?

Just to note, I run the playbook as such:

```<code>ansible-playbook panos-config.yml -i inventory.ini --extra-vars "config_file=./xml-config/asdf.xml load_file=asdf.xml" -vvv
</code>```

Ansible version is 2.8.0

答:
Turns out I needed to change the hosts to all, and leave {{ ansible_host }} in the ip_address variable field. The IPs get pulled from the inventory file and deploys fine. Like so:

```<code>- name: Import & load configuration file into PAN-OS
  hosts: all
  connection: local
  gather_facts: False

  vars:
    ip_address: "{{ ansible_host }}"
    username: "#{PALOS_USERNAME}#"
    password: "#{PALOS_PASSWORD}#"
    config_file: ""
    load_file: ""

  roles:
  - role: PaloAltoNetworks.paloaltonetworks

  tasks:
  - name: wait for reboot
    panos_check:
      ip_address: "{{ ip_address }}"
      username: "{{ username }}"
      password: "{{ password }}"
      interval: 5
      timeout: 900

  - name: import configuration file into PAN-OS
    panos_import:
      ip_address: "{{ ip_address }}"
      username: "{{ username }}"
      password: "{{ password }}"
      file: "{{ config_file }}"
      category: "configuration"
</code>```

Title: Use Ansible inventory IP in Playbook

Body:
I have an inventory file called inventory.ini which contains exactly just:

10.0.0.4
10.0.0.5

I would like to use the IPs listed here in the my Playbook under the variable ip_address:

- name: Import & load configuration file into PAN-OS
  hosts: localhost
  connection: local
  gather_facts: False

  vars:
    ip_address: "{{ SOMETHING-GOES-HERE }}"
    username: "#{PALOS_USERNAME}#"
    password: "#{PALOS_PASSWORD}#"
    config_file: ""
    load_file: ""

  roles:
  - role: PaloAltoNetworks.paloaltonetworks

  tasks:
  - name: wait for reboot
    panos_check:
      ip_address: "{{ ip_address }}"
      username: "{{ username }}"
      password: "{{ password }}"
      interval: 5
      timeout: 900

  - name: import configuration file into PAN-OS
    panos_import:
      ip_address: "{{ ip_address }}"
      username: "{{ username }}"
      password: "{{ password }}"
      file: "{{ config_file }}"
      category: "configuration"

I have tried using {{ inventory_hostname }}, but that brings back localhost instead. I have also tried using {{ ansible_host }}, but that brings back 127.0.0.1

Does anyone know how I can use the IPs listed in the inventory in place of the variable as it loops through each deployment?

Just to note, I run the playbook as such:

ansible-playbook panos-config.yml -i inventory.ini --extra-vars "config_file=./xml-config/asdf.xml load_file=asdf.xml" -vvv

Ansible version is 2.8.0

Body:
Turns out I needed to change the hosts to all, and leave {{ ansible_host }} in the ip_address variable field. The IPs get pulled from the inventory file and deploys fine. Like so:

- name: Import & load configuration file into PAN-OS
  hosts: all
  connection: local
  gather_facts: False

  vars:
    ip_address: "{{ ansible_host }}"
    username: "#{PALOS_USERNAME}#"
    password: "#{PALOS_PASSWORD}#"
    config_file: ""
    load_file: ""

  roles:
  - role: PaloAltoNetworks.paloaltonetworks

  tasks:
  - name: wait for reboot
    panos_check:
      ip_address: "{{ ip_address }}"
      username: "{{ username }}"
      password: "{{ password }}"
      interval: 5
      timeout: 900

  - name: import configuration file into PAN-OS
    panos_import:
      ip_address: "{{ ip_address }}"
      username: "{{ username }}"
      password: "{{ password }}"
      file: "{{ config_file }}"
      category: "configuration"


问:
How to build reactive architecture that will avoid nested Flux blocks (Flux<Flux <T>>)?
I am trying to build an application A (like an adaptor) that will:

1) Receive POST requests with some key (JSON format)

2) It should modify that key somehow and create POST request to another system B.

3) Application A should parse the response from application B and modify that response.

4) After that my application A should answer to the initial POST request.

```<code>@RestController
@RequestMapping("/A")
public class Controller {
    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "B", consumes = APPLICATION_JSON_VALUE)
    // to return nested Flux is a bad idea here
    private Flux<Flux<Map<String, ResultClass>>> testUpdAcc(@RequestBody Flux<Map<String, SomeClass>> keys) {
        return someMethod(keys);
    }

    // the problem comes here when I will get Flux<Flux<T>> in the return
    public Flux<Flux<Map<String, ResultClass>>> someMethod(Flux<Map<String, SomeClass>> keysFlux) {
        return keysFlux.map(keysMap -> {
                                // do something with keys and create URL
                                // also will batch keys here
                                <...>

                                // for each batch of keys:
                                WebClient.create(hostAndPort)
                                .method(HttpMethod.POST)
                                .uri(url)
                                .body(BodyInserters.fromObject(body))
                                .header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                                .accept(MediaType.APPLICATION_JSON)
                                .retrieve()
                                .bodyToMono(schema) // response will be parsed into some schema here
                                .retryWhen (// will make a retry mechanism here)

                                // ===== will join all Mono batches into single Flux
                                Flux.concat(...);
                                }
                             );
    }

}
</code>```

Of course this can be fixed by not reading keysFlux as Flux and read that as Map. But that should make everything less reactive, no? :)

```<code>    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "B", consumes = APPLICATION_JSON_VALUE)
    // to return nested Flux is a bad idea here
    private Flux<Map<String, ResultClass>> testUpdAcc(@RequestBody Map<String, SomeClass> keys) {
        return someMethod(keys);
    }
</code>```

Also I have tried to use block()/blockFirst() in the last moment before returning the request, but I have got an error:

```<code>block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor...
</code>```

Thank you for your ideas!

答:
Forget about my question - we can easily use "flatMap" instead of "map".
That will solve a problem with Flux inside Flux.</p>

Body:
I am trying to build an application A (like an adaptor) that will:

1) Receive POST requests with some key (JSON format)

2) It should modify that key somehow and create POST request to another system B.

3) Application A should parse the response from application B and modify that response.

4) After that my application A should answer to the initial POST request.

@RestController
@RequestMapping("/A")
public class Controller {
    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "B", consumes = APPLICATION_JSON_VALUE)
    // to return nested Flux is a bad idea here
    private Flux<Flux<Map<String, ResultClass>>> testUpdAcc(@RequestBody Flux<Map<String, SomeClass>> keys) {
        return someMethod(keys);
    }

    // the problem comes here when I will get Flux<Flux<T>> in the return
    public Flux<Flux<Map<String, ResultClass>>> someMethod(Flux<Map<String, SomeClass>> keysFlux) {
        return keysFlux.map(keysMap -> {
                                // do something with keys and create URL
                                // also will batch keys here
                                <...>

                                // for each batch of keys:
                                WebClient.create(hostAndPort)
                                .method(HttpMethod.POST)
                                .uri(url)
                                .body(BodyInserters.fromObject(body))
                                .header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                                .accept(MediaType.APPLICATION_JSON)
                                .retrieve()
                                .bodyToMono(schema) // response will be parsed into some schema here
                                .retryWhen (// will make a retry mechanism here)

                                // ===== will join all Mono batches into single Flux
                                Flux.concat(...);
                                }
                             );
    }

}

Of course this can be fixed by not reading keysFlux as Flux and read that as Map. But that should make everything less reactive, no? :)

    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "B", consumes = APPLICATION_JSON_VALUE)
    // to return nested Flux is a bad idea here
    private Flux<Map<String, ResultClass>> testUpdAcc(@RequestBody Map<String, SomeClass> keys) {
        return someMethod(keys);
    }

Also I have tried to use block()/blockFirst() in the last moment before returning the request, but I have got an error:

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor...

Thank you for your ideas!


问:
Rename a jar file removing the version number
I am trying to rename a jar file name with a version embedded in it like
test-java-1.0.0.jar to test-java.jar

Tried below approach but this will not workout if the version is changed to something like

test-java-11.0.0.jar or test-compile-1.0.12.jar

```<code>Set test=test-java-1.0.0.jar
set test1=%test:~0,-10%
rename %test% %test1%.jar
</code>```

Looking for something like:

Input string: test-java-1.0.0.jar

Expected output: test-java.jar

答:
This should be enough</p>

```<code>ren test-java*.jar test-java.jar
</code>```

Body:
I am trying to rename a jar file name with a version embedded in it like
test-java-1.0.0.jar to test-java.jar

Tried below approach but this will not workout if the version is changed to something like

test-java-11.0.0.jar or test-compile-1.0.12.jar

Set test=test-java-1.0.0.jar
set test1=%test:~0,-10%
rename %test% %test1%.jar

Looking for something like:

Input string: test-java-1.0.0.jar

Expected output: test-java.jar

Body:
This should be enough

ren test-java*.jar test-java.jar


问:
Convert financial year and financial quarter into year month
I've got 2 columns in a table, Financial_Year and Financial_Quarter.  An example of the data is as follows:

```<code>Financial_Year  Financial_Quarter
2018/2019         2
</code>```

I want to produce a third column called 'Year_month' which is the last month of the quarter within each financial year, so in the above example I want the year_month column to read 201809.

Has anyone got any hints how to do this in Oracle SQL?

答:
I guess there are many ways to skin this cat, here is one

```<code>SELECT CASE WHEN financial_quarter = '4' THEN SUBSTR(financial_year, 6, 4) || '03'
       ELSE SUBSTR(financial_year, 1, 4) || LPAD((financial_quarter + 1) * 3, 2, '0')
       END
FROM some_table
</code>```

Of course '4' needs to be replaced with 4 if financial_quarter is numeric

Body:
I've got 2 columns in a table, Financial_Year and Financial_Quarter.  An example of the data is as follows:

Financial_Year  Financial_Quarter
2018/2019         2

I want to produce a third column called 'Year_month' which is the last month of the quarter within each financial year, so in the above example I want the year_month column to read 201809.

Has anyone got any hints how to do this in Oracle SQL?

Body:
I guess there are many ways to skin this cat, here is one

SELECT CASE WHEN financial_quarter = '4' THEN SUBSTR(financial_year, 6, 4) || '03'
       ELSE SUBSTR(financial_year, 1, 4) || LPAD((financial_quarter + 1) * 3, 2, '0')
       END
FROM some_table

Of course '4' needs to be replaced with 4 if financial_quarter is numeric


问:
How can I set up a simple CGAL + Qt program
I would like to set up a simple CGAL + Qt program. In a nutshell, I would like to take the following:

https://github.com/CGAL/cgal/blob/master/Arrangement_on_surface_2/examples/Arrangement_on_surface_2/conics.cpp

and print out a visualization of it using Qt. I have no problems compiling the above:

```<code>cgal_create_CMakeLists -c Core
cmake -DCGAL_DIR=/usr/share/CGAL/ .
make
</code>```

and have been able to compile various Qt programs using qmake, but I'm having a hard time using Qt inside the conics.cpp file.

My questions are:

what Qt libraries do I need to include

how do I use the inserter to insert arr into the Qt widget stream

how do I set up and run using cmake

UPDATE

I've been trying to figure out how to compile a program with Qt headers. Following the Polygon demo, I added:

```<code>// Qt headers
#include <QtGui>
#include <QString>
#include <QFileDialog>
#include <QInputDialog>
#include <QGraphicsLineItem>
</code>```

to conics.cpp. I had no luck with either:

```<code>cgal_create_cmake_script
</code>```

or:

```<code>cgal_create_CMakeLists -c Core:Qt5
</code>```

what is working so far is to modify the CMakeLists.txt found in the Polygon demo as so:

```<code>project (Qt_Demo)

cmake_minimum_required(VERSION 3.1)
if(NOT POLICY CMP0070 AND POLICY CMP0053)
  # Only set CMP0053 to OLD with CMake<3.10, otherwise there is a warning.
  cmake_policy(SET CMP0053 OLD)
endif()

find_package(CGAL COMPONENTS Qt5 Core)

include(${CGAL_USE_FILE})

find_package(Qt5 QUIET COMPONENTS Xml Script OpenGL Svg)

include_directories (BEFORE ../../include)

if ( CGAL_FOUND AND CGAL_Qt5_FOUND AND Qt5_FOUND )

  add_definitions(-DQT_NO_KEYWORDS)

  if( CGAL_Core_FOUND)
    add_definitions(-DCGAL_USE_CORE)
  endif()

  #--------------------------------
  # Demo: Polygon_2
  #--------------------------------
  # UI files (Qt Designer files)
  #qt5_wrap_ui( DT_UI_FILES Polygon_2.ui )

  # qrc files (resources files, that contain icons, at least)
  #qt5_add_resources ( CGAL_Qt5_RESOURCE_FILES ./Polygon_2.qrc )

  # use the Qt MOC preprocessor on classes that derives from QObject
  qt5_generate_moc( conics.cpp "${CMAKE_CURRENT_BINARY_DIR}/conics.moc" )

#  add_library( CGAL SHARED IMPORTED )
#  SET_PROPERTY(TARGET CGAL PROPERTY IMPORTED_LOCATION ${CGAL_LIBRARY} )

  # The executable itself.
  add_executable  ( conics conics.cpp conics.moc ${DT_UI_FILES} ${DT_RESOURCE_FILES} ${CGAL_Qt5_RESOURCE_FILES} ${CGAL_Qt5_MOC_FILES} )

  qt5_use_modules(conics Xml Script OpenGL Svg)

  add_to_cached_list( CGAL_EXECUTABLE_TARGETS conics )

  # Link with Qt libraries
  target_link_libraries( conics ${QT_LIBRARIES} )
  # And with CGAL libraries
  target_link_libraries( conics ${CGAL_LIBRARIES} ${CGAL_3RD_PARTY_LIBRARIES} )

else()

  message(STATUS "NOTICE: This demo requires CGAL, CGAL_Core, and Qt5, and will not be compiled.")

endif()
</code>```

Really, there should be a simpler approach!

答:
"What Qt libraries do I need to include?"
You need the following libraries from Qt

#include <QtGui>
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
```

<p>In addition to those, you'll need some CGAL::Qt libraries to support CGAL data structures</p>

<pre class="lang-cpp prettyprint-override"><code>#include <CGAL/Qt/GraphicsViewNavigation.h>
</code>```

You'll also need a custom graphics item to represent Arrangement_2
instead of QGraphicsLineItem.

An Arrangement_2 item in CGAL is represented by combination of Vertices, Edges and Faces. Hence, you need a custom QGraphicsItem for displaying Arrangement_2 on to a scene in Qt.

In CGAL Demo, you can find a predefined graphics item in Arrangement_2GraphicsItem.h which can be used to display arr of conics.

How do I use the inserter to insert arr into the Qt widget stream?

Once you have a Arrangement_2GraphicsItem, you can pass the reference to arr into the graphics item and add the graphics item to the Qt scene.

arr_gi = new CGAL::Qt::ArrangementGraphicsItem<Arrangement_2>(&arr);
scene.addItem(arr_gi);
```

<ul>
<li>How do I set up and run using CMake?</li>
</ul>

<p>Your CMakeLists.txt should look like this:</p>

```cmake_minimum_required (VERSION 3.8)
project(conics)

find_package(Boost COMPONENTS thread system REQUIRED)
find_package(CGAL REQUIRED COMPONENTS Core Qt5)
find_package(Qt5 QUIET COMPONENTS Qt5 Core)

# Add source to this project's executable.
add_executable (conics
conics.cpp
ArrangementGraphicsItem.h
ArrangementPainterOstream.h #ArrangementGraphicsItem dependencies
ArrangementTypes.h
Utils.h
${CGAL_Qt5_RESOURCE_FILES} ${CGAL_Qt5_MOC_FILES})

qt5_use_modules(conics Xml Script OpenGL Svg)

include_directories(${Boost_INCLUDE_DIR})
target_link_libraries(conics CGAL::CGAL_Core CGAL::CGAL CGAL::CGAL_Qt5 ${Boost_LIBRARIES})

```

Body:
I would like to set up a simple CGAL + Qt program. In a nutshell, I would like to take the following:

https://github.com/CGAL/cgal/blob/master/Arrangement_on_surface_2/examples/Arrangement_on_surface_2/conics.cpp

and print out a visualization of it using Qt. I have no problems compiling the above:

cgal_create_CMakeLists -c Core
cmake -DCGAL_DIR=/usr/share/CGAL/ .
make

and have been able to compile various Qt programs using qmake, but I'm having a hard time using Qt inside the conics.cpp file.

My questions are:

what Qt libraries do I need to include

how do I use the inserter to insert arr into the Qt widget stream

how do I set up and run using cmake

UPDATE

I've been trying to figure out how to compile a program with Qt headers. Following the Polygon demo, I added:

// Qt headers
#include <QtGui>
#include <QString>
#include <QFileDialog>
#include <QInputDialog>
#include <QGraphicsLineItem>

to conics.cpp. I had no luck with either:

cgal_create_cmake_script

or:

cgal_create_CMakeLists -c Core:Qt5

what is working so far is to modify the CMakeLists.txt found in the Polygon demo as so:

project (Qt_Demo)

cmake_minimum_required(VERSION 3.1)
if(NOT POLICY CMP0070 AND POLICY CMP0053)
  # Only set CMP0053 to OLD with CMake<3.10, otherwise there is a warning.
  cmake_policy(SET CMP0053 OLD)
endif()

find_package(CGAL COMPONENTS Qt5 Core)

include(${CGAL_USE_FILE})

find_package(Qt5 QUIET COMPONENTS Xml Script OpenGL Svg)

include_directories (BEFORE ../../include)

if ( CGAL_FOUND AND CGAL_Qt5_FOUND AND Qt5_FOUND )

  add_definitions(-DQT_NO_KEYWORDS)

  if( CGAL_Core_FOUND)
    add_definitions(-DCGAL_USE_CORE)
  endif()

  #--------------------------------
  # Demo: Polygon_2
  #--------------------------------
  # UI files (Qt Designer files)
  #qt5_wrap_ui( DT_UI_FILES Polygon_2.ui )

  # qrc files (resources files, that contain icons, at least)
  #qt5_add_resources ( CGAL_Qt5_RESOURCE_FILES ./Polygon_2.qrc )

  # use the Qt MOC preprocessor on classes that derives from QObject
  qt5_generate_moc( conics.cpp "${CMAKE_CURRENT_BINARY_DIR}/conics.moc" )

#  add_library( CGAL SHARED IMPORTED )
#  SET_PROPERTY(TARGET CGAL PROPERTY IMPORTED_LOCATION ${CGAL_LIBRARY} )

  # The executable itself.
  add_executable  ( conics conics.cpp conics.moc ${DT_UI_FILES} ${DT_RESOURCE_FILES} ${CGAL_Qt5_RESOURCE_FILES} ${CGAL_Qt5_MOC_FILES} )

  qt5_use_modules(conics Xml Script OpenGL Svg)

  add_to_cached_list( CGAL_EXECUTABLE_TARGETS conics )

  # Link with Qt libraries
  target_link_libraries( conics ${QT_LIBRARIES} )
  # And with CGAL libraries
  target_link_libraries( conics ${CGAL_LIBRARIES} ${CGAL_3RD_PARTY_LIBRARIES} )

else()

  message(STATUS "NOTICE: This demo requires CGAL, CGAL_Core, and Qt5, and will not be compiled.")

endif()

Really, there should be a simpler approach!

Body:
"What Qt libraries do I need to include?"
You need the following libraries from Qt

#include <QtGui>
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>

In addition to those, you'll need some CGAL::Qt libraries to support CGAL data structures

#include <CGAL/Qt/GraphicsViewNavigation.h>

You'll also need a custom graphics item to represent Arrangement_2
instead of QGraphicsLineItem.

An Arrangement_2 item in CGAL is represented by combination of Vertices, Edges and Faces. Hence, you need a custom QGraphicsItem for displaying Arrangement_2 on to a scene in Qt.

In CGAL Demo, you can find a predefined graphics item in Arrangement_2GraphicsItem.h which can be used to display arr of conics.

How do I use the inserter to insert arr into the Qt widget stream?

Once you have a Arrangement_2GraphicsItem, you can pass the reference to arr into the graphics item and add the graphics item to the Qt scene.

arr_gi = new CGAL::Qt::ArrangementGraphicsItem<Arrangement_2>(&arr);
scene.addItem(arr_gi);

How do I set up and run using CMake?

Your CMakeLists.txt should look like this:

cmake_minimum_required (VERSION 3.8)
project(conics)

find_package(Boost COMPONENTS thread system REQUIRED)
find_package(CGAL REQUIRED COMPONENTS Core Qt5)
find_package(Qt5 QUIET COMPONENTS Qt5 Core)

# Add source to this project's executable.
add_executable (conics
conics.cpp
ArrangementGraphicsItem.h
ArrangementPainterOstream.h #ArrangementGraphicsItem dependencies
ArrangementTypes.h
Utils.h
${CGAL_Qt5_RESOURCE_FILES} ${CGAL_Qt5_MOC_FILES})

qt5_use_modules(conics Xml Script OpenGL Svg)

include_directories(${Boost_INCLUDE_DIR})
target_link_libraries(conics CGAL::CGAL_Core CGAL::CGAL CGAL::CGAL_Qt5 ${Boost_LIBRARIES})


Title: Select all rows by group with condition

Body:
I have this data frame:

`dat <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-15", "2017-02-05","2018-05-23", "2018-02-22"), grp = c(1,1,6,7,7,7),
var2 = c(1,3,18,15,25,5))`

I would like to have all the rows of each group (grp) when value of var2>=14

Expected results:

    dat <- data.frame(date = c("2017-02-15", "2017-02-05","2018-05-23",
"2018-02-22"), grp = c(6,7,7,7), var2 = c(18,15,25,5))

Body:
Maybe without groupby , with base R

dat[dat$grp %in% dat$grp [dat$var2 >= 14],]
        date grp var2
3 2017-02-15   6   18
4 2017-02-05   7   15
5 2018-05-23   7   25
6 2018-02-22   7    5


问:
Unable to enter Text in a input TextBox using Javascriptexecutor
Running into a peculiar problem where I am unable to enter text into a TextBox using Selenium.

I have tried the below approaches till now but unable to achieve the result with anyone of them :

SendKeys

Actions class

javascriptexecutor

Details About Page Section under Test:

Page section has two radio buttons which gives the option to user to follow different path for verification.

The Xpath of the field on which I am facing the issue remains same even when user selects any of the two Checkboxes which I think is possibly the issue.

This is not an issue related to frame switching as other fields in the section are working fine.

Result :

Code is able to Click on the field but not enter text.

Even if it enters the text 2 out of 5 times through javascriptexecutor, the page fails to recognize the text. As it is a mandatory field, error is thrown later even if text is populated through javascript.

Expectation :

Need a Robust way to make it work. Any approach would work.

Approach 1 : SendKeys

```<code>wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@class='cPATCHEDOmniScriptCommunity']")));
    driver.findElement(By.xpath("//div[@ng-show='creditCheckDetails && !successCreditBoolVal']/div[2]/div[1]/input[1]")).sendKeys("TestData");
</code>```

Approach 2 : Actions Class

```<code>wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@class='cPATCHEDOmniScriptCommunity']")));
    Actions action = new Actions(driver);
    action.moveToElement(driver.findElement(By.xpath("//div[@ng-show='creditCheckDetails && !successCreditBoolVal']/div[2]/div[1]/input[1]"))).sendKeys("TestData").build().perform();
</code>```

Approach 3 : Javascriptexecutor

```<code>wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@class='cPATCHEDOmniScriptCommunity']")));
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    jse.executeScript("arguments[0].value='testdata';", driver.findElement(By.xpath("//div[@ng-show='creditCheckDetails && !successCreditBoolVal']/div[2]/div[1]/input[1]")));
</code>```

Approach 4 : Javascriptexecutor

```<code>wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@class='cPATCHEDOmniScriptCommunity']")));
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    jse.executeScript("document.evaluate(//div[@ng-show='creditCheckDetails && !successCreditBoolVal']/div[2]/div[1]/input[1], document, null, 9, null).singleNodeValue.innerHTML="+ BusinessName);
</code>```

Page HTML :

```<code><div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center tileContainer b-t-4" ng-class="{'b-t-4': creditCheckDetails, 'b-t-1': !creditCheckDetails}" ng-show="showCreditSectionForAgent" style="">
            <h2 class="titleHeader ng-binding">Business verification</h2>

            <div class="arrow_padding isMobile"><img src="/resource/vz_images/images/arrow.svg" class="tileIcon isMobile ng-hide" ng-click="completePlaceOrder = false; creditCheckDetailsMobile = true;scrollToTopOfPage();" ng-show="!creditCheckDetails && !successCreditBoolVal && showPlus" style=""></div>

            <img src="/resource/BuyflowImages/BuyflowImages/plus-large.svg" class="tileIcon isNotMobile ng-hide" ng-click="insatllationDetails = false; contactDetails = false; shippingAddressDetails = false; billingAddressDetails = false; termsAndConditionDetails = false; cardMessageCheck(); creditCardDetails = false; creditCheckDetails = !creditCheckDetails" ng-show="!creditCheckDetails && !successCreditBoolVal && showPlus" style="">

            <img src="/resource/BuyflowImages/BuyflowImages/minus-large.svg" class="tileIcon isNotMobile" ng-click="insatllationDetails = false; contactDetails = false; shippingAddressDetails = false; billingAddressDetails = false; termsAndConditionDetails = false; cardMessageCheck(); creditCheckDetails = !creditCheckDetails" ng-show="creditCheckDetails && !successCreditBoolVal" style="">

            <div class="slds-size--1-of-1 ng-hide" ng-show="!creditCheckDetails && !showHelpMessage" style="">

                <p class="Body warn-state" ng-show="!successCreditBoolVal">Please complete credit check.</p>
                <p class="Body warn-state ng-binding ng-hide" ng-show="creditCheckError"></p>
                <p class="Body success-state ng-hide" ng-show="successCreditBoolVal">Credit approval complete</p>
            </div>
            <div class="slds-size--1-of-1 vz_alert-warn helpMessage ng-binding ng-hide" ng-show="showHelpMessage && !successCreditBoolVal" ng-bind-html="helpMessage"></div>
            <div class="slds-size--1-of-1" ng-show="creditCheckDetails && !successCreditBoolVal" style="">
                <p class="Body">As part of your new service request, we need to do a standard business verification using your Federal Tax ID. If you do not have a Tax ID, we can use your personal information as well.</p>
                <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center creditCheckSolePCorpLLC" style="padding-top: 2%;">
                    <div class="slds-size--1-of-1">
                        <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--8-of-12 slds-grid_vertical-align-center slds-grid_align-center">

                            <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--6-of-12 slds-grid_vertical-align-center slds-grid_align-center" style="padding-right: 10px;">
                                <label class="container-radio">
                                   <input type="radio" name="soleOrCorp" value="corporationLLC" ng-model="soleOrCorp" style="-webkit-appearance: radio;" class="ng-pristine ng-untouched ng-valid ng-not-empty">
                                <span class="checkmark"></span>
                                <span for="contactChoice2" style="font-family: 'NeueHaasGroteskText'; font-size: 14px; color: black;">My Business uses a Federal Tax ID</span>
                                </label>
                            </div>
                            <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--6-of-12 slds-grid_vertical-align-center slds-grid_align-center">
                                <label class="container-radio">
                                    <input type="radio" name="soleOrCorp" value="soleproprietorship" ng-model="soleOrCorp" style="-webkit-appearance: radio;" class="ng-pristine ng-untouched ng-valid ng-not-empty">
                                <span class="checkmark"></span>
                                <span style="font-family: 'NeueHaasGroteskText'; font-size: 14px; color: black;">My Business does not have a Federal Tax ID</span>
                                </label>
                            </div>

                            <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-large-size--6-of-12"></div>
                        </div>
                    </div>

                </div>
                <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center corpLLCSoleContainer" style="padding-top:1%;" ng-show="soleOrCorp === 'corporationLLC'">
                    <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--6-of-12 slds-grid_vertical-align-center slds-grid_align-center" style="display: block;padding-right: 30px;">
                        <label class="labelAboveTextBox">Business name*</label>
                        <input type="text" class="businessName ng-pristine ng-valid ng-empty ng-valid-maxlength ng-touched" ng-model="businessName" ng-keyup="setBusinessName(businessName)" maxlength="30" style="width: 100%;">
                        <!-- ngIf: reqForBusinessName -->
                        <!-- ngIf: reqForBusinessNamesalphabets -->
                    </div>
                    <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--6-of-12 slds-grid_vertical-align-center slds-grid_align-center" style="display: block;padding-right: 30px;">

                        <label class="labelAboveTextBox">Federal Tax ID*</label>
                        <input type="password" ng-required="businessTaxId" class="businessTaxId ng-pristine ng-empty ng-valid ng-valid-required ng-touched" ng-model="businessTaxId" ng-change="Check(businessTaxId, 'tId', 'businessTaxId')" ng-blur="PIEEncryptionTax()" ng-class="{'vz_error': businessTaxId.length > 0 && businessTaxId.length !== 9, 'noredBorder': businessTaxId.length === 9}" style="width: 100%;">
                        <!-- ngIf: reqForBusinessTaxIDForLength -->
                        <!-- ngIf: reqForBusinessTaxIDFornozero -->

                        <!-- ngIf: reqForBusinessTaxID -->
                    </div>
                    <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--6-of-12 slds-grid_vertical-align-center slds-grid_align-center" style="display: block;padding-right: 30px;margin-top: 15px;">

                            <label class="labelAboveTextBox">Responsible Party First Name*</label>
                            <input type="text" class="businessName afname ng-pristine ng-untouched ng-valid ng-not-empty" id="responsibeFirstName" ng-keyup="responsibeFirstName();" ng-model="afname" style="width: 100%;">
                            <!-- ngIf: reqafname -->
                    </div>
                    <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--6-of-12 slds-grid_vertical-align-center slds-grid_align-center" style="display: block;margin-top: 15px;padding-right: 30px;">

                            <label class="labelAboveTextBox">Responsible Party Last Name*</label>
                            <input type="text" class="businessName alname ng-pristine ng-untouched ng-valid ng-not-empty" id="responsibeLastName" ng-keyup="responsibeLastName();" ng-model="alname" style="width: 100%;">
                            <!-- ngIf: reqalname -->
                    </div>
                </div>
                <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center corpLLCSoleContainer ng-hide" style="" ng-show="soleOrCorp === 'soleproprietorship' ">
                    <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center">
                        <p class="Body ng-binding"></p>
                        <div ng-hide="hideForAgent" class="slds-m-top--medium" style="width: 100%;">
                            <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center soleProprietorInputDiv" style="padding-bottom: 5px;padding-top:5px;">
                                <div class="slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--6-of-12" style="padding-right: 30px;">
                                    <label class="labelAboveTextBox">Business name*</label>
                                    <input type="text" class="sBusinessName ng-pristine ng-untouched ng-empty ng-valid-maxlength ng-valid ng-valid-required" ng-model="businessName" ng-required="businessName" ng-keyup="setBusinessName(businessName)" maxlength="30" style="width: 100%;>
                                     <span ng-if=" reqsbusinessname"="">This is required
                                </div>
                                <div class="slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--6-of-12" style="padding-right: 30px;">
                                    <label class="labelAboveTextBox">SSN*</label>
                                    <input type="password" class="ssn ng-pristine ng-untouched ng-empty ng-valid ng-valid-required" ng-required="ssnId" ng-model="ssnId" ng-blur="PIEEncryptionSsn()" ng-change="Check(ssnId, 'ssn', 'ssn')" ng-class="{'vz_error': ssnId.length > 0 && ssnId.length !== 9, 'noredBorder': ssnId.length === 9}" style="width: 100%;>
                                    <span ng-if=" reqssnidlen"="">SSN Length should be 9
                                    <!-- ngIf: reqssnIdlpatternDups -->
                                    <!-- ngIf: reqssnIdlpattern -->
                                    <!-- ngIf: reqssnId -->                            </div>
                            </div>

                            <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center" style="padding-top: 25px; padding-bottom: 10px;">
                                <div class="slds-size--1-of-1" style="font-size: 14px; font-weight: bold; font-family: 'NeueHaasGroteskDisplayBold'; color: black;">
                                    Please provide the name of person responsible for the account
                                </div>
                            </div>

                            <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center ssnHolderNameDiv" style="padding-bottom: 5px;">
                                <div class="slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--3-of-12" style="padding-right: 30px;">
                                    <label class="labelAboveTextBox">Responsible Party First Name*</label>
                                    <input type="text" class="fname ng-pristine ng-untouched ng-valid ng-not-empty" ng-model="fname" style="width: 100%;" reqfname"="">This is required
                                </div>
                                <div class="slds-size--1-of-1 slds-medium-size--3-of-6 slds-large-size--3-of-12" style="padding-right: 30px;">
                                    <label class="labelAboveTextBox">Responsible Party Last Name*</label>
                                    <input type="text" class="lname ng-pristine ng-untouched ng-valid ng-not-empty" ng-model="lname" style="width: 100%;" reqlname"="">This is required
                                </div>
                                <div class="slds-large-size--6-of-12"></div>
                            </div>
                            <div class="slds-grid slds-wrap slds-gr id_vertical-align-center slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center" style="margin-bottom: 0px;padding-top: 15px;">
                               <label class=" labelAboveTextBox">Date of Birth*</label>
                            </div>

                             <div class="slds-grid slds-wrap slds-grid_vertical-align-center slds-medium-size--6-of-6 slds-large-size--12-of-12 slds-grid_vertical-align-center slds-grid_align-center" id="ssnDOBdiv" style="padding-bottom: 5px;margin-top: 0.3%;">
                                <div class="slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--4-of-12">
                                    <label class="labelAboveTextBox">MM/DD/YYYY</label>
                                    <input type="text" datepicker-credit-section="" class="yYYY ng-pristine ng-untouched ng-valid ng-empty" ng-model="ssnDOB" readonly="" id="creditCheckDOBY" ng-blur="PIEEncryptionDOB()" style="width: 100%;>
                                </div>
                                <div class=" slds-large-size--6-of-12"=""></div>
                            </div>
                             <div><!-- ngIf: reqDOB --></div>
                        </div>
                    </div>
                </div>
                <div class="slds-size--1-of-1 slds-medium-size--6-of-6 slds-large-size--12-of-12">
                    <button class="btn-buyF btn-primary-buyF btn-md-buyF save-btn ng-binding" ng-class="{'confirm-btn-disabled': (successCredit || hideForAgent)}" ng-click="scrollToTop(); validateCreditCheckData();" style="height: 42px;border-radius: 21px;">Proceed</button>
                </div>
            </div>
        </div>
</code>```

答:
Try the following Xpath.

```<code>//input[@class='businessName ng-pristine ng-valid ng-empty ng-valid-maxlength ng-touched'][@ng-model='businessName']
</code>```

*Edited Answer**

```<code>//label[@class='labelAboveTextBox'][contains(.,'Business name')]/following-sibling::input
</code>```

Updated

Use WebdriverWait and elementtobeclickable and use following xpath.Since You have two similar element present and you have said class names are getting change in each automation run i have provided index option for the 1st element.

```<code>WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//label[@class='labelAboveTextBox'][contains(.,'Business name')]/following-sibling::input)[1]")));
element.sendKeys("TestData");
</code>```

Body:
Running into a peculiar problem where I am unable to enter text into a TextBox using Selenium.

I have tried the below approaches till now but unable to achieve the result with anyone of them :

SendKeys

Actions class

javascriptexecutor

Details About Page Section under Test:

Page section has two radio buttons which gives the option to user to follow different path for verification.

The Xpath of the field on which I am facing the issue remains same even when user selects any of the two Checkboxes which I think is possibly the issue.

This is not an issue related to frame switching as other fields in the section are working fine.

Result :

Code is able to Click on the field but not enter text.

Even if it enters the text 2 out of 5 times through javascriptexecutor, the page fails to recognize the text. As it is a mandatory field, error is thrown later even if text is populated through javascript.

Expectation :

Need a Robust way to make it work. Any approach would work.

Approach 1 : SendKeys

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@class='cPATCHEDOmniScriptCommunity']")));
    driver.findElement(By.xpath("//div[@ng-show='creditCheckDetails && !successCreditBoolVal']/div[2]/div[1]/input[1]")).sendKeys("TestData");

Approach 2 : Actions Class

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@class='cPATCHEDOmniScriptCommunity']")));
    Actions action = new Actions(driver);
    action.moveToElement(driver.findElement(By.xpath("//div[@ng-show='creditCheckDetails && !successCreditBoolVal']/div[2]/div[1]/input[1]"))).sendKeys("TestData").build().perform();

Approach 3 : Javascriptexecutor

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@class='cPATCHEDOmniScriptCommunity']")));
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    jse.executeScript("arguments[0].value='testdata';", driver.findElement(By.xpath("//div[@ng-show='creditCheckDetails && !successCreditBoolVal']/div[2]/div[1]/input[1]")));

Approach 4 : Javascriptexecutor

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@class='cPATCHEDOmniScriptCommunity']")));
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    jse.executeScript("document.evaluate(//div[@ng-show='creditCheckDetails && !successCreditBoolVal']/div[2]/div[1]/input[1], document, null, 9, null).singleNodeValue.innerHTML="+ BusinessName);

Page HTML :

Business verification

Please complete credit check.

Credit approval complete

As part of your new service request, we need to do a standard business verification using your Federal Tax ID. If you do not have a Tax ID, we can use your personal information as well.

                                   <input type="radio" name="soleOrCorp" value="corporationLLC" ng-model="soleOrCorp" style="-webkit-appearance: radio;" class="ng-pristine ng-untouched ng-valid ng-not-empty">

                                My Business uses a Federal Tax ID

                                    <input type="radio" name="soleOrCorp" value="soleproprietorship" ng-model="soleOrCorp" style="-webkit-appearance: radio;" class="ng-pristine ng-untouched ng-valid ng-not-empty">

                                My Business does not have a Federal Tax ID

                        Business name*
                        <input type="text" class="businessName ng-pristine ng-valid ng-empty ng-valid-maxlength ng-touched" ng-model="businessName" ng-keyup="setBusinessName(businessName)" maxlength="30" style="width: 100%;">

                        Federal Tax ID*
                        <input type="password" ng-required="businessTaxId" class="businessTaxId ng-pristine ng-empty ng-valid ng-valid-required ng-touched" ng-model="businessTaxId" ng-change="Check(businessTaxId, 'tId', 'businessTaxId')" ng-blur="PIEEncryptionTax()" ng-class="{'vz_error': businessTaxId.length > 0 && businessTaxId.length !== 9, 'noredBorder': businessTaxId.length === 9}" style="width: 100%;">

                            Responsible Party First Name*
                            <input type="text" class="businessName afname ng-pristine ng-untouched ng-valid ng-not-empty" id="responsibeFirstName" ng-keyup="responsibeFirstName();" ng-model="afname" style="width: 100%;">

                            Responsible Party Last Name*
                            <input type="text" class="businessName alname ng-pristine ng-untouched ng-valid ng-not-empty" id="responsibeLastName" ng-keyup="responsibeLastName();" ng-model="alname" style="width: 100%;">

                                    Business name*
                                    <input type="text" class="sBusinessName ng-pristine ng-untouched ng-empty ng-valid-maxlength ng-valid ng-valid-required" ng-model="businessName" ng-required="businessName" ng-keyup="setBusinessName(businessName)" maxlength="30" style="width: 100%;>
                                     This is required

                                    SSN*
                                    <input type="password" class="ssn ng-pristine ng-untouched ng-empty ng-valid ng-valid-required" ng-required="ssnId" ng-model="ssnId" ng-blur="PIEEncryptionSsn()" ng-change="Check(ssnId, 'ssn', 'ssn')" ng-class="{'vz_error': ssnId.length > 0 && ssnId.length !== 9, 'noredBorder': ssnId.length === 9}" style="width: 100%;>
                                    SSN Length should be 9

                                    Please provide the name of person responsible for the account

                                    Responsible Party First Name*
                                    <input type="text" class="fname ng-pristine ng-untouched ng-valid ng-not-empty" ng-model="fname" style="width: 100%;" reqfname"="">This is required

                                    Responsible Party Last Name*
                                    <input type="text" class="lname ng-pristine ng-untouched ng-valid ng-not-empty" ng-model="lname" style="width: 100%;" reqlname"="">This is required

                               Date of Birth*

                                    MM/DD/YYYY
                                    <input type="text" datepicker-credit-section="" class="yYYY ng-pristine ng-untouched ng-valid ng-empty" ng-model="ssnDOB" readonly="" id="creditCheckDOBY" ng-blur="PIEEncryptionDOB()" style="width: 100%;>

                    <button class="btn-buyF btn-primary-buyF btn-md-buyF save-btn ng-binding" ng-class="{'confirm-btn-disabled': (successCredit || hideForAgent)}" ng-click="scrollToTop(); validateCreditCheckData();" style="height: 42px;border-radius: 21px;">Proceed</button>

Body:
Try the following Xpath.

//input[@class='businessName ng-pristine ng-valid ng-empty ng-valid-maxlength ng-touched'][@ng-model='businessName']

*Edited Answer**

//label[@class='labelAboveTextBox'][contains(.,'Business name')]/following-sibling::input

Updated

Use WebdriverWait and elementtobeclickable and use following xpath.Since You have two similar element present and you have said class names are getting change in each automation run i have provided index option for the 1st element.

WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//label[@class='labelAboveTextBox'][contains(.,'Business name')]/following-sibling::input)[1]")));
element.sendKeys("TestData");


问:
Express sendFile function
I am trying to write some API using node.js. I have a pdf file stored in Temp folder, and I want to send it using res.sendFile(). But when i try so, it just sends back empty file (not even pdf file), with no error.

I have already tried using both relative and absolute path.

```<code>res.sendFile(`${os.tmpdir}/download/something.pdf`);
</code>```

答:
You will need to provide the path via the options parameter.  Example code:

```<code>app.get('/file', function (req, res, next) {
  var options = {
    root: `${os.tmpdir}`,
    dotfiles: 'deny',
    headers: {
      'x-timestamp': Date.now(),
      'x-sent': true
    }
  }

  var filename = 'somefile.pdf'

  res.sendFile(filename, options, function (err) {
    if (err) {
      next(err)
    } else {
      console.log('Sent:', fileName)
    }
  })
})
</code>```

Code based on: https://expressjs.com/en/api.html#res.sendFile

Title: Express sendFile function

Body:
I am trying to write some API using node.js. I have a pdf file stored in Temp folder, and I want to send it using res.sendFile(). But when i try so, it just sends back empty file (not even pdf file), with no error.

I have already tried using both relative and absolute path.

res.sendFile(`${os.tmpdir}/download/something.pdf`);

Body:
You will need to provide the path via the options parameter.  Example code:

app.get('/file', function (req, res, next) {
  var options = {
    root: `${os.tmpdir}`,
    dotfiles: 'deny',
    headers: {
      'x-timestamp': Date.now(),
      'x-sent': true
    }
  }

  var filename = 'somefile.pdf'

  res.sendFile(filename, options, function (err) {
    if (err) {
      next(err)
    } else {
      console.log('Sent:', fileName)
    }
  })
})

Code based on: https://expressjs.com/en/api.html#res.sendFile


问:
Sql Server: Linked server to Informix database
I have a Linked Server pointing to Informix DB. Using this linked server, I am writing a SQL query to fetch the data and load it into a SQL table.

But there are some tables exist which is throwing datatype overflow error. For a table I identified the column and the record which is causing the issue.
Could not convert the data value due to reason other than sign mismatch or overflow.

If I exclude this column or the specific record, my SELECT statement returns the result without any issue. I analyzed this column which is Char datatype; I obtain an error when there are certain characters (€ or š character) in the field.

Below is the script that I used to create the Linked Server:

```<code>DECLARE @provider NVARCHAR(4000);

SET @provider = N'Driver={IBM INFORMIX ODBC DRIVER};'

`+` N'SERVICE=1526 ;' --Informix service name

`+` N'PROTOCOL=onsoctcp ;' --Informix protocol

--+ N'DB_LOCALE=en_US.819; CLIENT_LOCALE=en_US.819;';

EXEC master.dbo.sp_addlinkedserver

@server =N'LS_INFORMIX', --Linked Server system name

@srvproduct=N'Ifxoledbc',

@provider=N'Ifxoledbc',

@datasrc=N'xxx@yyyyyy', --Informix Database

@provstr= @provider;
</code>```

I tried to remove the commentLine on 5th row, but I receive error 7303 (cannot inizializate Ifxoledbc).

Can someone help me?

答:
In theory you could avoid the faulty codeset conversion using ODBC instead of OLEDB for the linked server and setting CLIENT_LOCALE to en_US.819.

Create the linked server using the ODBC driver with:

```<code>EXEC sp_dropserver 'ids1210_odbc', @droplogins='droplogins';;

EXEC master.dbo.sp_addlinkedserver @server = N'ids1210_odbc',
 @srvproduct=N'MSDASQL',
 @provider=N'MSDASQL',
 @datasrc=N'ids1210',
 @provstr=N'Provider=MSDASQL'

exec sp_addlinkedsrvlogin 'ids1210_odbc',false,'sa','informix','mypass'

select * from OPENQUERY(ids1210_odbc,'select * from systables')

select * from ids1210_odbc.stores7.informix.systables
</code>```

"ids1210" is the name of the ODBC System DSN. Use the Windows ODBC Data Source Administrator to create it.
Both CLIENT_LOCALE and DB_LOCALE in the Environment DSN should be set to "en_US.819".

It should work and allow you to retrieve the "fancy" characters from the database but, at some point, you should fix the problem and change the locale of the database to suit the data you have inside.

Body:
I have a Linked Server pointing to Informix DB. Using this linked server, I am writing a SQL query to fetch the data and load it into a SQL table.

But there are some tables exist which is throwing datatype overflow error. For a table I identified the column and the record which is causing the issue.
Could not convert the data value due to reason other than sign mismatch or overflow.

If I exclude this column or the specific record, my SELECT statement returns the result without any issue. I analyzed this column which is Char datatype; I obtain an error when there are certain characters (€ or š character) in the field.

Below is the script that I used to create the Linked Server:

DECLARE @provider NVARCHAR(4000);

SET @provider = N'Driver={IBM INFORMIX ODBC DRIVER};'

`+` N'SERVICE=1526 ;' --Informix service name

`+` N'PROTOCOL=onsoctcp ;' --Informix protocol

--+ N'DB_LOCALE=en_US.819; CLIENT_LOCALE=en_US.819;';

EXEC master.dbo.sp_addlinkedserver

@server =N'LS_INFORMIX', --Linked Server system name

@srvproduct=N'Ifxoledbc',

@provider=N'Ifxoledbc',

@datasrc=N'xxx@yyyyyy', --Informix Database

@provstr= @provider;

I tried to remove the commentLine on 5th row, but I receive error 7303 (cannot inizializate Ifxoledbc).

Can someone help me?

Body:
In theory you could avoid the faulty codeset conversion using ODBC instead of OLEDB for the linked server and setting CLIENT_LOCALE to en_US.819.

Create the linked server using the ODBC driver with:

EXEC sp_dropserver 'ids1210_odbc', @droplogins='droplogins';;

EXEC master.dbo.sp_addlinkedserver @server = N'ids1210_odbc',
 @srvproduct=N'MSDASQL',
 @provider=N'MSDASQL',
 @datasrc=N'ids1210',
 @provstr=N'Provider=MSDASQL'

exec sp_addlinkedsrvlogin 'ids1210_odbc',false,'sa','informix','mypass'

select * from OPENQUERY(ids1210_odbc,'select * from systables')

select * from ids1210_odbc.stores7.informix.systables

"ids1210" is the name of the ODBC System DSN. Use the Windows ODBC Data Source Administrator to create it.
Both CLIENT_LOCALE and DB_LOCALE in the Environment DSN should be set to "en_US.819".

It should work and allow you to retrieve the "fancy" characters from the database but, at some point, you should fix the problem and change the locale of the database to suit the data you have inside.


问:
How to return a model back (or anything for that matter) on an update mutation in Sequelize?
I am using the update model method to update an entry in Sequelize using the mysql2 dialect. It seems as if with MySQL you can only return a count of rows affected. I would like to pass it back as a boolean.

It should be noted that I am fairly new to JS/ES6, Node, pretty much all of this, I am more versed in PHP so I apologize in advance if the answer is obvious or a fundamental misunderstanding of JS, but I promise I have worked on this for hours. The online documentation and online examples for the update method are fairly light.

The closest answer I can find is at: Sequelize on GraphQL update not return anything

I have removed irrelevant bits of this code for brevity.

Model:

export default (sequelize, DataTypes) => {
    const Payment = sequelize.define('payment', {
        ...
        processed: {
            type: DataTypes.INTEGER(1).UNSIGNED,
            allowNull: false,
            defaultValue: '0'
        },
        ...
    return Payment;
```

<p>Schema:</p>

<pre class="lang-js prettyprint-override"><code>...
type Payment {
id: Int!
amount: Float!
processedTime: Int
processed: Int!
dueDate: Int!
status: PaymentStatuses

Employee: Employee
Client: Client!
Merchant: Merchant
PaymentType: PaymentType
}

type Query {
getPayment(id: Int!): Payment
}
type Mutation {

updatePaymentStatus(id: Int!, processed: Int!): Boolean

}
</code>```

What I was originally trying to do was:

updatePaymentStatus(id: Int!, processed: Int!): Payment!
```

<p>Resolver:</p>

<pre class="lang-js prettyprint-override"><code>Mutation {
updatePaymentStatus: async (parent, {id, processed}, {models}) =>
{await models.Payment.update({processed}, {where: {id}})
.then((datareturned) => {return datareturned[0]})}
}
</code>```

If I check my database, the update is actually working correctly. If I console.log(datareturned[0]) I get a 1 (or 0 if no rows were updated).

I would like to be able to return at least a Boolean as described in my schema but no matter what I try, I get null or some other error because the returned value is null. I realize I may be incorrectly assuming returning 1 will be assumed as true but I have also tried:

```<code>.then((datareturned) => {if (datareturned[0] === 1) {return true}})}
</code>```

In GraphiQL:

```<code>mutation{
  updatePaymentStatus(id:1, processed:0)
}
</code>```

Response:

```<code>{
  "data": {
    "updatePaymentStatus": null
  }
}
</code>```

I am not sure if the problem is with my lack of JS knowledge, or that Sequelize does not return much using the MySQL dialect, or somewhere in between.

答:
Hey i just ran into this last night... i did it like this in my resolver

```<code>addUserProfileCertification: async (_, args, { models }) => {
      try {
        await models.ProfileCompanyCertification.create(args.input);
        return true;
      } catch (err) {
        logger.error(err);
      }
      return false;
    },
</code>```

and my mutation

```<code>addUserProfileCertification(input: ProfileCertificationInput!): Boolean
</code>```

GraphiQL result looks like

```<code>{
  "data": {
    "addUserProfileCertification": true
  }
}
</code>```

You can easily return the whole model if you want though by return a findOne with the id from your args at the bottom of your resolver like...

```<code>updateUserProfileContact: async (_, args, { models }) => {

      let returnValue = null;
      const { id, input } = args;
      try {
        await models.ProfileContact.update(input, { where: { id } });
        returnValue = await models.ProfileContact.findOne({ where: { id } });
      } catch (err) {
        logger.error(err);
      }
      return returnValue;
    },
</code>```

You just need to tell your mutation to expect a Payment type rather than a Boolean, and you can refine what you want to pass back to the client by selecting only certain fields from payment as part of the mutation that you enter into GraphiQL

Body:
I am using the update model method to update an entry in Sequelize using the mysql2 dialect. It seems as if with MySQL you can only return a count of rows affected. I would like to pass it back as a boolean.

It should be noted that I am fairly new to JS/ES6, Node, pretty much all of this, I am more versed in PHP so I apologize in advance if the answer is obvious or a fundamental misunderstanding of JS, but I promise I have worked on this for hours. The online documentation and online examples for the update method are fairly light.

The closest answer I can find is at: Sequelize on GraphQL update not return anything

I have removed irrelevant bits of this code for brevity.

Model:

export default (sequelize, DataTypes) => {
    const Payment = sequelize.define('payment', {
        ...
        processed: {
            type: DataTypes.INTEGER(1).UNSIGNED,
            allowNull: false,
            defaultValue: '0'
        },
        ...
    return Payment;

Schema:

...
type Payment {
id: Int!
amount: Float!
processedTime: Int
processed: Int!
dueDate: Int!
status: PaymentStatuses

Employee: Employee
Client: Client!
Merchant: Merchant
PaymentType: PaymentType
}

type Query {
getPayment(id: Int!): Payment
}
type Mutation {

updatePaymentStatus(id: Int!, processed: Int!): Boolean

}

What I was originally trying to do was:

updatePaymentStatus(id: Int!, processed: Int!): Payment!

Resolver:

Mutation {
updatePaymentStatus: async (parent, {id, processed}, {models}) =>
{await models.Payment.update({processed}, {where: {id}})
.then((datareturned) => {return datareturned[0]})}
}

If I check my database, the update is actually working correctly. If I console.log(datareturned[0]) I get a 1 (or 0 if no rows were updated).

I would like to be able to return at least a Boolean as described in my schema but no matter what I try, I get null or some other error because the returned value is null. I realize I may be incorrectly assuming returning 1 will be assumed as true but I have also tried:

.then((datareturned) => {if (datareturned[0] === 1) {return true}})}

In GraphiQL:

mutation{
  updatePaymentStatus(id:1, processed:0)
}

Response:

{
  "data": {
    "updatePaymentStatus": null
  }
}

I am not sure if the problem is with my lack of JS knowledge, or that Sequelize does not return much using the MySQL dialect, or somewhere in between.

Body:
Hey i just ran into this last night... i did it like this in my resolver

addUserProfileCertification: async (_, args, { models }) => {
      try {
        await models.ProfileCompanyCertification.create(args.input);
        return true;
      } catch (err) {
        logger.error(err);
      }
      return false;
    },

and my mutation

addUserProfileCertification(input: ProfileCertificationInput!): Boolean

GraphiQL result looks like

{
  "data": {
    "addUserProfileCertification": true
  }
}

You can easily return the whole model if you want though by return a findOne with the id from your args at the bottom of your resolver like...

updateUserProfileContact: async (_, args, { models }) => {

      let returnValue = null;
      const { id, input } = args;
      try {
        await models.ProfileContact.update(input, { where: { id } });
        returnValue = await models.ProfileContact.findOne({ where: { id } });
      } catch (err) {
        logger.error(err);
      }
      return returnValue;
    },

You just need to tell your mutation to expect a Payment type rather than a Boolean, and you can refine what you want to pass back to the client by selecting only certain fields from payment as part of the mutation that you enter into GraphiQL


问:
How to start bare X server (X -retro &) in Linux OS using Python script?
I am a newbie and trying to automate a Linux-based Test in Python. Please help me.

This is what I have tried. But It does not work. No errors but display shows blank black screen.

subprocess.Popen(['pkill', 'X'])
time.sleep(5)
subprocess.Popen(['X', '-retro', '&']).communicate()
subprocess.Popen(['export', 'DISPLAY=:0']).communicate()
subprocess.Popen(['openbox', '--replace', '&']).communicate()
```

答:
The export will have no effect as each command is evaluated in an separate shell if a shell is required otherwise only fork and exec will be involved. Pass the environmental variables via the dictionary keyword argument.

Communicate will wait until the program exits. Also & is pointless as Popen does not wait for the program to finish and there is no sense in backgrounding a job in what is not a shell and has no concept or status of such distinction.

```<code>subprocess.Popen(['pkill', 'X'])
time.sleep(5)
subprocess.Popen(['X', '-retro'])
import sys
env = dict(sys.environ)
env['DISPLAY']=':0'
subprocess.Popen(['openbox', '--replace'], env=env)
</code>```

If there is a problem with this it lies with the commands involved and not the Python code.

Body:
The export will have no effect as each command is evaluated in an separate shell if a shell is required otherwise only fork and exec will be involved. Pass the environmental variables via the dictionary keyword argument.

Communicate will wait until the program exits. Also & is pointless as Popen does not wait for the program to finish and there is no sense in backgrounding a job in what is not a shell and has no concept or status of such distinction.

subprocess.Popen(['pkill', 'X'])
time.sleep(5)
subprocess.Popen(['X', '-retro'])
import sys
env = dict(sys.environ)
env['DISPLAY']=':0'
subprocess.Popen(['openbox', '--replace'], env=env)

If there is a problem with this it lies with the commands involved and not the Python code.


问:
How to add empty rows in excel sheet data table using c#
How to add empty rows in my data table and then loop through the column heading and split by- Then year insert to the empty row and
After that merge the year row

Here is my data table code:

```<code>       private void button1_Click(object sender, EventArgs e)
       {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            Excel.Range chartRange;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        xlWorkSheet.Cells[2, 1] = "Retailer";

        xlWorkSheet.Cells[2, 2] = "Brand";
        xlWorkSheet.Cells[2, 3] = "2019_WK1";

        xlWorkSheet.Cells[2, 4] = "2019_WK2";

            xlWorkSheet.Cells[2, 5] = "2019_WK3";

            xlWorkSheet.Cells[3, 1] = "LuLu";
            xlWorkSheet.Cells[3, 2] = "Perisil";
            xlWorkSheet.Cells[3, 3] = "25";
            xlWorkSheet.Cells[3, 4] = "26";
            xlWorkSheet.Cells[3, 5] = "23";

            xlWorkSheet.Cells[4, 1] = "Lulu";
            xlWorkSheet.Cells[4, 2] = "Ariel";
            xlWorkSheet.Cells[4, 3] = "26";
            xlWorkSheet.Cells[4, 4] = "28";
            xlWorkSheet.Cells[4, 5] = "29";

            xlWorkSheet.Cells[5, 1] = "Danube";
            xlWorkSheet.Cells[5, 2] = "Omo";
            xlWorkSheet.Cells[5, 3] = "27";
            xlWorkSheet.Cells[5, 4] = "28";
            xlWorkSheet.Cells[5, 5] = "30";

            xlWorkSheet.Cells[6, 1] = "Danube";
            xlWorkSheet.Cells[6, 2] = "Tide";
            xlWorkSheet.Cells[6, 3] = "24";
            xlWorkSheet.Cells[6, 4] = "23";
            xlWorkSheet.Cells[6, 5] = "29";

            xlWorkSheet.Cells[7, 1] = "Bin Dawood";
            xlWorkSheet.Cells[7, 2] = "Persil";
            xlWorkSheet.Cells[7, 3] = "26";
            xlWorkSheet.Cells[7, 4] = "27";
            xlWorkSheet.Cells[7, 5] = "28";

        xlWorkBook.SaveAs("F:\\CTR_Data", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlApp);
            releaseObject(xlWorkBook);
            releaseObject(xlWorkSheet);

            MessageBox.Show("File created !");
        }
</code>```

I want to add five empty rows in ("A1" to "E1" cells) and loop through the column heading and split by-

I want a excel output like above picture

答:
You must use the merge method (xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[2, 1]].Merge();)

```<code>Application xlApp;
        Workbook xlWorkBook;
        Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        Range chartRange;

        xlApp = new Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

        xlWorkSheet.Cells[1, 1] = "Retailer";
        xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[2, 1]].Merge();

        xlWorkSheet.Cells[2, 2] = "Brand";
        xlWorkSheet.Range[xlWorkSheet.Cells[1, 2], xlWorkSheet.Cells[2, 2]].Merge();

        xlWorkSheet.Cells[2, 3] = "2019_WK1";

        xlWorkSheet.Cells[2, 4] = "2019_WK2";

        xlWorkSheet.Cells[2, 5] = "2019_WK3";

        xlWorkSheet.Cells[3, 1] = "LuLu";
        xlWorkSheet.Cells[3, 2] = "Perisil";
        xlWorkSheet.Cells[3, 3] = "25";
        xlWorkSheet.Cells[3, 4] = "26";
        xlWorkSheet.Cells[3, 5] = "23";

        xlWorkSheet.Cells[4, 1] = "Lulu";
        xlWorkSheet.Cells[4, 2] = "Ariel";
        xlWorkSheet.Cells[4, 3] = "26";
        xlWorkSheet.Cells[4, 4] = "28";
        xlWorkSheet.Cells[4, 5] = "29";

        xlWorkSheet.Cells[5, 1] = "Danube";
        xlWorkSheet.Cells[5, 2] = "Omo";
        xlWorkSheet.Cells[5, 3] = "27";
        xlWorkSheet.Cells[5, 4] = "28";
        xlWorkSheet.Cells[5, 5] = "30";

        xlWorkSheet.Cells[6, 1] = "Danube";
        xlWorkSheet.Cells[6, 2] = "Tide";
        xlWorkSheet.Cells[6, 3] = "24";
        xlWorkSheet.Cells[6, 4] = "23";
        xlWorkSheet.Cells[6, 5] = "29";

        xlWorkSheet.Cells[7, 1] = "Bin Dawood";
        xlWorkSheet.Cells[7, 2] = "Persil";
        xlWorkSheet.Cells[7, 3] = "26";
        xlWorkSheet.Cells[7, 4] = "27";
        xlWorkSheet.Cells[7, 5] = "28";

        xlWorkSheet.Cells[1, 3] = "Year";
        xlWorkSheet.Range[xlWorkSheet.Cells[1, 3], xlWorkSheet.Cells[1, 5]].Merge();

        xlWorkBook.SaveAs("test", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();
</code>```

Body:
How to add empty rows in my data table and then loop through the column heading and split by- Then year insert to the empty row and
After that merge the year row

Here is my data table code:

       private void button1_Click(object sender, EventArgs e)
       {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            Excel.Range chartRange;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        xlWorkSheet.Cells[2, 1] = "Retailer";

        xlWorkSheet.Cells[2, 2] = "Brand";
        xlWorkSheet.Cells[2, 3] = "2019_WK1";

        xlWorkSheet.Cells[2, 4] = "2019_WK2";

            xlWorkSheet.Cells[2, 5] = "2019_WK3";

            xlWorkSheet.Cells[3, 1] = "LuLu";
            xlWorkSheet.Cells[3, 2] = "Perisil";
            xlWorkSheet.Cells[3, 3] = "25";
            xlWorkSheet.Cells[3, 4] = "26";
            xlWorkSheet.Cells[3, 5] = "23";

            xlWorkSheet.Cells[4, 1] = "Lulu";
            xlWorkSheet.Cells[4, 2] = "Ariel";
            xlWorkSheet.Cells[4, 3] = "26";
            xlWorkSheet.Cells[4, 4] = "28";
            xlWorkSheet.Cells[4, 5] = "29";

            xlWorkSheet.Cells[5, 1] = "Danube";
            xlWorkSheet.Cells[5, 2] = "Omo";
            xlWorkSheet.Cells[5, 3] = "27";
            xlWorkSheet.Cells[5, 4] = "28";
            xlWorkSheet.Cells[5, 5] = "30";

            xlWorkSheet.Cells[6, 1] = "Danube";
            xlWorkSheet.Cells[6, 2] = "Tide";
            xlWorkSheet.Cells[6, 3] = "24";
            xlWorkSheet.Cells[6, 4] = "23";
            xlWorkSheet.Cells[6, 5] = "29";

            xlWorkSheet.Cells[7, 1] = "Bin Dawood";
            xlWorkSheet.Cells[7, 2] = "Persil";
            xlWorkSheet.Cells[7, 3] = "26";
            xlWorkSheet.Cells[7, 4] = "27";
            xlWorkSheet.Cells[7, 5] = "28";

        xlWorkBook.SaveAs("F:\\CTR_Data", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlApp);
            releaseObject(xlWorkBook);
            releaseObject(xlWorkSheet);

            MessageBox.Show("File created !");
        }

I want to add five empty rows in ("A1" to "E1" cells) and loop through the column heading and split by-

I want a excel output like above picture

Body:
You must use the merge method (xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[2, 1]].Merge();)

Application xlApp;
        Workbook xlWorkBook;
        Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        Range chartRange;

        xlApp = new Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

        xlWorkSheet.Cells[1, 1] = "Retailer";
        xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[2, 1]].Merge();

        xlWorkSheet.Cells[2, 2] = "Brand";
        xlWorkSheet.Range[xlWorkSheet.Cells[1, 2], xlWorkSheet.Cells[2, 2]].Merge();

        xlWorkSheet.Cells[2, 3] = "2019_WK1";

        xlWorkSheet.Cells[2, 4] = "2019_WK2";

        xlWorkSheet.Cells[2, 5] = "2019_WK3";

        xlWorkSheet.Cells[3, 1] = "LuLu";
        xlWorkSheet.Cells[3, 2] = "Perisil";
        xlWorkSheet.Cells[3, 3] = "25";
        xlWorkSheet.Cells[3, 4] = "26";
        xlWorkSheet.Cells[3, 5] = "23";

        xlWorkSheet.Cells[4, 1] = "Lulu";
        xlWorkSheet.Cells[4, 2] = "Ariel";
        xlWorkSheet.Cells[4, 3] = "26";
        xlWorkSheet.Cells[4, 4] = "28";
        xlWorkSheet.Cells[4, 5] = "29";

        xlWorkSheet.Cells[5, 1] = "Danube";
        xlWorkSheet.Cells[5, 2] = "Omo";
        xlWorkSheet.Cells[5, 3] = "27";
        xlWorkSheet.Cells[5, 4] = "28";
        xlWorkSheet.Cells[5, 5] = "30";

        xlWorkSheet.Cells[6, 1] = "Danube";
        xlWorkSheet.Cells[6, 2] = "Tide";
        xlWorkSheet.Cells[6, 3] = "24";
        xlWorkSheet.Cells[6, 4] = "23";
        xlWorkSheet.Cells[6, 5] = "29";

        xlWorkSheet.Cells[7, 1] = "Bin Dawood";
        xlWorkSheet.Cells[7, 2] = "Persil";
        xlWorkSheet.Cells[7, 3] = "26";
        xlWorkSheet.Cells[7, 4] = "27";
        xlWorkSheet.Cells[7, 5] = "28";

        xlWorkSheet.Cells[1, 3] = "Year";
        xlWorkSheet.Range[xlWorkSheet.Cells[1, 3], xlWorkSheet.Cells[1, 5]].Merge();

        xlWorkBook.SaveAs("test", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();


问:
Can a trait have a supertrait that is parameterized by a generic?
Can you do something like this in Rust?

```<code>trait A : forall<T> B<T> { ... }
</code>```

That is, if we want:

```<code>impl A for D { ... }
</code>```

We must first implement:

```<code>impl<T> B<T> for D { ... }
</code>```

答:
While the language is unable to specify such a higher kinded constraint, it is often possible to rethink the trait B so that its implementation is universal over this parameter type T.

Considering this example of B:

trait B<T> {
    fn foo(bar: T) -> u32;
}
```

<p>A type that implements <code>B</code> for any <code>T</code> would be practically equivalent to the type implementing the trait below:</p>

<pre class="lang-rust prettyprint-override"><code>trait UniversalB {
    fn foo<T>(bar: T) -> u32;
}
</code>```

This one declares the type parameters at method call level. While this trait is no longer object safe, it can still be used as a supertrait:

trait A: UniversalB {}
```

The implementations may need to be adjusted accordingly.

See also:

The Rust Programming Language, Chapter 10, Section 1 on Generic Data Types In Method Definitions

Body:
Can you do something like this in Rust?

trait A : forall<T> B<T> { ... }

That is, if we want:

impl A for D { ... }

We must first implement:

impl<T> B<T> for D { ... }

Body:
While the language is unable to specify such a higher kinded constraint, it is often possible to rethink the trait B so that its implementation is universal over this parameter type T.

Considering this example of B:

trait B<T> {
    fn foo(bar: T) -> u32;
}

A type that implements B for any T would be practically equivalent to the type implementing the trait below:

trait UniversalB {
    fn foo<T>(bar: T) -> u32;
}

This one declares the type parameters at method call level. While this trait is no longer object safe, it can still be used as a supertrait:

trait A: UniversalB {}

The implementations may need to be adjusted accordingly.

See also:

The Rust Programming Language, Chapter 10, Section 1 on Generic Data Types In Method Definitions