问:
how to click the multiple checkboxes in selenium webdriver?
As i want to click the multiple checkboxes in selenium webdriver, so that im using the 'id' webelement to click but what problem i'm facing means all the checkboxes id's are same in my HTML
so is there anyway to click multiple checkboxes?

Here im posting my HTML code:
first check box:

```<code><tbody role="rowgroup">
<tr data-uid="6adb7eb4-7169-4ab8-aef4-cc8b2774beac" role="row" class="k-state-selected" aria-selected="true"><td style="text-align:left" role="gridcell">Order</td><td style="text-align:left" role="gridcell">55</td><td style="text-align:left" role="gridcell">ORD55</td><td style="text-align:right" role="gridcell">2,400.00</td><td style="text-align:right" role="gridcell">2,400.00</td><td style="text-align:center" role="gridcell" id="GridPayRecp_active_cell" class="" aria-describedby="c7c68ce1-edc3-4958-a6c1-2611999356b0 GridPayRecp_active_cell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;" checked=""></td><td style="text-align:right" role="gridcell">2,400.00</td></tr><tr class="k-alt" data-uid="3f3d1588-6f42-4c22-bdda-28c090ece58b" role="row"><td style="text-align:left" role="gridcell">Order</td><td style="text-align:left" role="gridcell">57</td><td style="text-align:left" role="gridcell">ORD57</td><td style="text-align:right" role="gridcell">3,600.00</td><td style="text-align:right" role="gridcell">3,597.00</td><td style="text-align:center" role="gridcell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;"></td><td style="text-align:right" role="gridcell">0.00</td></tr><tr data-uid="1ab110de-fbe6-4954-b612-39c3cb7fc8ba" role="row"><td style="text-align:left" role="gridcell">Proforma</td><td style="text-align:left" role="gridcell">90</td><td style="text-align:left" role="gridcell">PRO90</td><td style="text-align:right" role="gridcell">3,600.00</td><td style="text-align:right" role="gridcell">3,366.00</td><td style="text-align:center" role="gridcell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;"></td><td style="text-align:right" role="gridcell">0.00</td></tr>
</tbody>
</code>```

second checkbox:

```<code><tbody role="rowgroup">
<tr data-uid="6adb7eb4-7169-4ab8-aef4-cc8b2774beac" role="row" class="k-state-selected" aria-selected="true"><td style="text-align:left" role="gridcell">Order</td><td style="text-align:left" role="gridcell">55</td><td style="text-align:left" role="gridcell">ORD55</td><td style="text-align:right" role="gridcell">2,400.00</td><td style="text-align:right" role="gridcell">2,400.00</td><td style="text-align:center" role="gridcell" id="GridPayRecp_active_cell" class="" aria-describedby="c7c68ce1-edc3-4958-a6c1-2611999356b0 GridPayRecp_active_cell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;" checked=""></td><td style="text-align:right" role="gridcell">2,400.00</td></tr><tr class="k-alt" data-uid="3f3d1588-6f42-4c22-bdda-28c090ece58b" role="row"><td style="text-align:left" role="gridcell">Order</td><td style="text-align:left" role="gridcell">57</td><td style="text-align:left" role="gridcell">ORD57</td><td style="text-align:right" role="gridcell">3,600.00</td><td style="text-align:right" role="gridcell">3,597.00</td><td style="text-align:center" role="gridcell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;"></td><td style="text-align:right" role="gridcell">0.00</td></tr><tr data-uid="1ab110de-fbe6-4954-b612-39c3cb7fc8ba" role="row"><td style="text-align:left" role="gridcell">Proforma</td><td style="text-align:left" role="gridcell">90</td><td style="text-align:left" role="gridcell">PRO90</td><td style="text-align:right" role="gridcell">3,600.00</td><td style="text-align:right" role="gridcell">3,366.00</td><td style="text-align:center" role="gridcell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;"></td><td style="text-align:right" role="gridcell">0.00</td></tr></tbody>
</code>```

third checkbox:

```<code></tbody>
</code>```

答:
How to click on all checkboxes with the same ID, (Java example):

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);

List<WebElement> checkboxes = wait.until(ExpectedConditions
        .presenceOfAllElementsLocatedBy(By.cssSelector("tr[role=row] input#chkSelect[type=checkBox]")));

for (WebElement checkbox : checkboxes) {
    wait.until(ExpectedConditions.elementToBeClickable(checkbox)).click();
}
</code>```

Click first and second checkboxes for each row:

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);

List<WebElement> rows = wait.until(ExpectedConditions
        .presenceOfAllElementsLocatedBy(By.cssSelector("tr[role=row]")));

for (WebElement row : rows) {
    List<WebElement> checkboxes = driver.findElements(By.cssSelector("input#chkSelect[type=checkBox]"));
    wait.until(ExpectedConditions.elementToBeClickable(checkboxes.get(0))).click();
    wait.until(ExpectedConditions.elementToBeClickable(checkboxes.get(1))).click();

}
</code>```

Body:
As i want to click the multiple checkboxes in selenium webdriver, so that im using the 'id' webelement to click but what problem i'm facing means all the checkboxes id's are same in my HTML
so is there anyway to click multiple checkboxes?

Here im posting my HTML code:
first check box:

Order	55	ORD55	2,400.00	2,400.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;" checked="">	2,400.00

Order	57	ORD57	3,600.00	3,597.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;">	0.00

Proforma	90	PRO90	3,600.00	3,366.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;">	0.00

second checkbox:

Order	55	ORD55	2,400.00	2,400.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;" checked="">	2,400.00

Order	57	ORD57	3,600.00	3,597.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;">	0.00

Proforma	90	PRO90	3,600.00	3,366.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;">	0.00

third checkbox:

Body:
How to click on all checkboxes with the same ID, (Java example):

WebDriverWait wait = new WebDriverWait(driver, 10);

List<WebElement> checkboxes = wait.until(ExpectedConditions
        .presenceOfAllElementsLocatedBy(By.cssSelector("tr[role=row] input#chkSelect[type=checkBox]")));

for (WebElement checkbox : checkboxes) {
    wait.until(ExpectedConditions.elementToBeClickable(checkbox)).click();
}

Click first and second checkboxes for each row:

WebDriverWait wait = new WebDriverWait(driver, 10);

List<WebElement> rows = wait.until(ExpectedConditions
        .presenceOfAllElementsLocatedBy(By.cssSelector("tr[role=row]")));

for (WebElement row : rows) {
    List<WebElement> checkboxes = driver.findElements(By.cssSelector("input#chkSelect[type=checkBox]"));
    wait.until(ExpectedConditions.elementToBeClickable(checkboxes.get(0))).click();
    wait.until(ExpectedConditions.elementToBeClickable(checkboxes.get(1))).click();

}


来源: stackexchange

问:
Why am I getting an error when I runspider?
I am currently working through an exercise where I put Amazon Reviews for a specific product into a csv file. I have put together my code to extract the data but I am getting a syntax error when I go to runspider to put into the csv. This part I copied directly from the practice module I am looking at so I wasn't quite sure what the issue could be. All of the resources I have found on runspider indicate that the code should be correct but clearly I've done something wrong here.

Here is my code. I am getting an error on the very last line:

```<code>import scrapy

# Implementing Spider
class ReviewspiderSpider(scrapy.Spider):

    # Name of Spider
    name = 'reviewspider'

    allowed_domains = ["amazon.com"]
    start_urls = ['https://www.amazon.com/product-reviews/B07N49F51N/ref=cm_cr_arp_d_viewpnt_lft?pageNumber=']

    def parse(self, response):
        names = response.xpath('//span[@class="a-profile-name"]/text()').extract()
        reviewTitles = response.xpath('//a[@data-hook="review-title"]/span/text()').extract()
        starRatings = response.xpath('//span[@class="a-icon-alt"]/text()').extract()
        reviews = response.xpath('//span[@data-hook="review-body"]/span/text()').extract()
        noOfComments = response.xpath('//span[@class="a-size-base"]/text()').extract()
        for (name, title, rating, review, comments) in zip(names, reviewTitles, starRatings, reviews, noOfComments):
            yield {'Name': name, 'Title': title, 'Rating': rating, 'Review': review, 'No of Comments': comments }

scrapy runspider spiders/reviewspider.py -t csv -o - > amazonreviews.csv
</code>```

Here is the Error Message:

```<code>  File "<ipython-input-35-6e8796e727d9>", line 22
    scrapy runspider <reviewspider.py> -t csv -o - > amazonreviews.csv
                   ^
SyntaxError: invalid syntax
</code>```

What am I missing here? I am very new to Python, webscraping and scrapy so any and all breakdown/insight is useful.

答:
The line

```<code>scrapy runspider spiders/reviewspider.py -t csv -o - > amazonreviews.csv
</code>```

is not part of your code. It is just command how to run your spider.

Go to your project location via cmd or anaconda prompt. And try

```<code>scrapy runspider reviewspider.py -t csv -o amazonreviews.csv
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am currently working through an exercise where I put Amazon Reviews for a specific product into a csv file. I have put together my code to extract the data but I am getting a syntax error when I go to runspider to put into the csv. This part I copied directly from the practice module I am looking at so I wasn't quite sure what the issue could be. All of the resources I have found on runspider indicate that the code should be correct but clearly I've done something wrong here.

Here is my code. I am getting an error on the very last line:

import scrapy

# Implementing Spider
class ReviewspiderSpider(scrapy.Spider):

    # Name of Spider
    name = 'reviewspider'

    allowed_domains = ["amazon.com"]
    start_urls = ['https://www.amazon.com/product-reviews/B07N49F51N/ref=cm_cr_arp_d_viewpnt_lft?pageNumber=']

    def parse(self, response):
        names = response.xpath('//span[@class="a-profile-name"]/text()').extract()
        reviewTitles = response.xpath('//a[@data-hook="review-title"]/span/text()').extract()
        starRatings = response.xpath('//span[@class="a-icon-alt"]/text()').extract()
        reviews = response.xpath('//span[@data-hook="review-body"]/span/text()').extract()
        noOfComments = response.xpath('//span[@class="a-size-base"]/text()').extract()
        for (name, title, rating, review, comments) in zip(names, reviewTitles, starRatings, reviews, noOfComments):
            yield {'Name': name, 'Title': title, 'Rating': rating, 'Review': review, 'No of Comments': comments }

scrapy runspider spiders/reviewspider.py -t csv -o - > amazonreviews.csv

Here is the Error Message:

  File "<ipython-input-35-6e8796e727d9>", line 22
    scrapy runspider <reviewspider.py> -t csv -o - > amazonreviews.csv
                   ^
SyntaxError: invalid syntax

What am I missing here? I am very new to Python, webscraping and scrapy so any and all breakdown/insight is useful.

Body:
The line

scrapy runspider spiders/reviewspider.py -t csv -o - > amazonreviews.csv

is not part of your code. It is just command how to run your spider.

Go to your project location via cmd or anaconda prompt. And try

scrapy runspider reviewspider.py -t csv -o amazonreviews.csv


问:
Custom CSS/JS for Google Sites
The new Google Sites service is amazing, a website (mostly static with some Google services) can be created with just 1 file in Google Drive.

However, it has no direct UI to customise CSS or to add additional JS.

Anyone with a work-around for this?

答:
As far as I can see, this is not possible. I gave it a spin, but no Luck.

There are multiple questions on SO about this, and they all lead to the documentation, which doesn't give us any more information:

Create my own Google site template Using my own CSS

https://support.google.com/sites/answer/98216?hl=en&visit_id=637177843384493895-752760820&rd=2

Title: Custom CSS/JS for Google Sites


问:
Spring data Derived Queries with Multiple Condition and one parameter
How can I create a derived query methods in Spring data which select result based on multiple conditions but with only one parameter.

```<code>List<Entity> findById1OrId2OrId3(String id1OrId2OrId3);
</code>```

Something like this example.

答: You can use "In" and make list of Ids then make a new derived query to achieve this</p>

Body:
How can I create a derived query methods in Spring data which select result based on multiple conditions but with only one parameter.

List<Entity> findById1OrId2OrId3(String id1OrId2OrId3);

Something like this example.


问:
Strange interaction between print and the ternary conditional operator
Ran into a strange interaction between print and the ternary conditional operator that I don't understand. If we do...:

print 'foo, ' . (1 ? 'yes' : 'no') . ' bar';

...then we get the output...:

foo, yes bar

...as we would expect. However, if we do...:

print (1 ? 'yes' : 'no') . ' bar';

...then we just get the output...:

yes

Why isn't " bar" getting appended to the output in the second case?

答:
If the first non-whitespace character after a function name is an opening parenthesis, then Perl will interpret that as the start of the function's parameter list and the matching closing parenthesis will be used as the end of the parameter list. This is one of the things that use warnings will tell you about.

The usual fix is to insert a + before the opening parenthesis.

```<code>$ perl -e "print (1 ? 'yes' : 'no') . ' bar'"
yes
$ perl -e "print +(1 ? 'yes' : 'no') . ' bar'"
yes bar
</code>```

Body:
If the first non-whitespace character after a function name is an opening parenthesis, then Perl will interpret that as the start of the function's parameter list and the matching closing parenthesis will be used as the end of the parameter list. This is one of the things that use warnings will tell you about.

The usual fix is to insert a + before the opening parenthesis.

$ perl -e "print (1 ? 'yes' : 'no') . ' bar'"
yes
$ perl -e "print +(1 ? 'yes' : 'no') . ' bar'"
yes bar


问:
How to check if an array contains any undefined value in javascript
I want to know whether my array contains any undefined value. My array is like this,

How to find it?
I tried this method but it doesn't read 'undefined'

```<code> let newValues = []
 if(values.length === selectedCertifiedList.length){
   values && values.filter(v => v === (undefined ||  0 || null)).map(val => {
        newValues.push(val);
   })
 }
</code>```

答:
Try this,</p>

```<code>const data = ['one', 0, 'two',  undefined, 'three'];
const checker = [null, undefined, 0]; //filtering conditions
const x = data.filter((item) => !checker.includes(item) )
console.log(data)
console.log(x)

//Output looks ["one","two","three"]
</code>```

Body:
I want to know whether my array contains any undefined value. My array is like this,

How to find it?
I tried this method but it doesn't read 'undefined'

 let newValues = []
 if(values.length === selectedCertifiedList.length){
   values && values.filter(v => v === (undefined ||  0 || null)).map(val => {
        newValues.push(val);
   })
 }

Body:
Try this,

const data = ['one', 0, 'two',  undefined, 'three'];
const checker = [null, undefined, 0]; //filtering conditions
const x = data.filter((item) => !checker.includes(item) )
console.log(data)
console.log(x)

//Output looks ["one","two","three"]


问:
Multiple substring searches in numpy array with few unique values
Inspired by this question: suppose that I have a list of multiple 1D numpy arrays xs and I would like to know how many occur as "substrings" of another larger 1D numpy array y.

We can assume that arrays contain integers and that a is a substring of b if a == b[p:q] for some integers p and q.

My proposed solution uses the in operator of Python's bytes object, but I suppose that it is inefficient if xs has many elements:

```<code>import numpy as np

N = 10_000    # number of arrays to search
M = 3         # "alphabet" size
K = 1_000_000 # size of the target array

xs = [np.random.randint(0, M, size=7) for _ in range(N)]
y = np.random.randint(0, M, size=K)

y_bytes = y.tobytes()
%time num_matches = sum(1 for x in xs if x.tobytes() in y_bytes)
# CPU times: user 1.03 s, sys: 17 µs, total: 1.03 s
# Wall time: 1.03 s
</code>```

If M is large (number of possible values in y of any of the xs's) is large, then I imagine that little can be done to speed this up. However, for small M I imagine that using a trie or something of the sort could be helpful. Is there an efficient way to implement this in Python, possibly using numpy/numba?

答:
For small M's, we can assign each of the xs a unique label based on the combination of integers in it. For the same we can leverage convolution with an scaling array and hence, reduce each of xs to a scalar. Finally, we use matching-method to detect and hence, the count.

The only over-head would be the conversion to array from the list of arrays. So, if the list-creation itself is optimized before-hand to have an array rather, it would help a lot on final performance numbers.

The implementation would look something like this -

```<code>x = np.asarray(xs) # convert to array, if not already done

s = M**np.arange(x.shape[1])
yr = np.convolve(y,s[::-1])
xr = x.dot(s)

# Final step : Match and get count
N = np.maximum(xr.max(),yr.max())+1 # or use s[-1]*M if M is small enough
l = np.zeros(N, dtype=bool)
l[yr] = True
count = l[xr].sum()
</code>```

Alternatives to perform Final step

Alternative #1 :

```<code>sidx = yr.argsort()
idx = np.searchsorted(yr,xr,sorter=sidx)
idx[idx==len(yr)] = 0
count = (yr[sidx[idx]] == xr).sum()
</code>```

Alternative #2 :

```<code>from scipy.sparse import csr_matrix

ly = len(yr)
y_extent = yr.max()+1  # or use s[-1]*M if M is small enough
r = np.zeros(ly, dtype=np.uint64)
val = np.ones(ly, dtype=np.bool)
sp_mat = csr_matrix((val, (r,yr)), shape=(1,y_extent))
count = sp_mat[:,xr].sum()
</code>```

Alternative #3 :

For bigger M number, we can use empty arrays instead -

```<code>l = np.empty(N, dtype=bool)
l[xr] = False
l[yr] = True
count = l[xr].sum()
</code>```

Digging further (Leveraging numba on convolution)

Profiling on the main proposed solution reveals that the 1D convolution part was the time-consuming part. Going further, we see that the 1D convolution code has a specific kernel that is geometric  in nature. This could be implemented in O(n) upon re-using boundary elements per iteration. Note that this would be basically an inverted kernel as compared to the one proposed earlier. So, putting all of those changes, we end up with something like this -

```<code>from numba import njit

@njit
def numba1(y, conv_out, M, L, N):
    A = M**L
    for i in range(1,N):
        conv_out[i] = conv_out[i-1]*M + y[i+L-1] - y[i-1]*A
    return conv_out

def numba_convolve(y, M, L):
        N = len(y)-L+1
        conv_out = np.empty(N, dtype=int)
        conv_out[0] = y[:L].dot(M**np.arange(L-1,-1,-1))
        return numba1(y, conv_out, M, L, N)

def intersection_count(xs, y):
    x = np.asarray(xs) # convert to array, if not already done

    L = x.shape[1]
    s = M**np.arange(L-1,-1,-1)
    xr = x.dot(s)

    yr_numba = numba_convolve(y, M=M, L=L)

    # Final step : Match and get count
    N = s[0]*M
    l = np.zeros(N, dtype=bool)
    l[yr_numba] = True
    count = l[xr].sum()
    return count
</code>```

Benchmarking

We will re-use the setup from the question.

```<code>In [42]: %%timeit
    ...: y_bytes = y.tobytes()
    ...: p = sum(1 for x in xs if x.tobytes() in y_bytes)
927 ms ± 3.57 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [43]: %timeit intersection_count(xs, y)
7.55 ms ± 71.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

As noted earlier conversion to array could be the bottleneck. So, let's time that part too -

```<code>In [44]: %timeit np.asarray(xs)
3.41 ms ± 10.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

So, the array-conversion part is around 45% of total runtime and that's a substantial one. Hence, the suggestion to work with 2D array as opposed to list of 1D arrays becomes crucial at this point. The upside is array data gives us vectorized capability and hence improved performance overall. Just to emphasis on the 2D array availibility, here are the speedups with and without -

```<code>In [45]: 927/7.55
Out[45]: 122.78145695364239

In [46]: 927/(7.55-3.41)
Out[46]: 223.91304347826087
</code>```

Body:
Inspired by this question: suppose that I have a list of multiple 1D numpy arrays xs and I would like to know how many occur as "substrings" of another larger 1D numpy array y.

We can assume that arrays contain integers and that a is a substring of b if a == b[p:q] for some integers p and q.

My proposed solution uses the in operator of Python's bytes object, but I suppose that it is inefficient if xs has many elements:

import numpy as np

N = 10_000    # number of arrays to search
M = 3         # "alphabet" size
K = 1_000_000 # size of the target array

xs = [np.random.randint(0, M, size=7) for _ in range(N)]
y = np.random.randint(0, M, size=K)

y_bytes = y.tobytes()
%time num_matches = sum(1 for x in xs if x.tobytes() in y_bytes)
# CPU times: user 1.03 s, sys: 17 µs, total: 1.03 s
# Wall time: 1.03 s

If M is large (number of possible values in y of any of the xs's) is large, then I imagine that little can be done to speed this up. However, for small M I imagine that using a trie or something of the sort could be helpful. Is there an efficient way to implement this in Python, possibly using numpy/numba?

Body:
For small M's, we can assign each of the xs a unique label based on the combination of integers in it. For the same we can leverage convolution with an scaling array and hence, reduce each of xs to a scalar. Finally, we use matching-method to detect and hence, the count.

The only over-head would be the conversion to array from the list of arrays. So, if the list-creation itself is optimized before-hand to have an array rather, it would help a lot on final performance numbers.

The implementation would look something like this -

x = np.asarray(xs) # convert to array, if not already done

s = M**np.arange(x.shape[1])
yr = np.convolve(y,s[::-1])
xr = x.dot(s)

# Final step : Match and get count
N = np.maximum(xr.max(),yr.max())+1 # or use s[-1]*M if M is small enough
l = np.zeros(N, dtype=bool)
l[yr] = True
count = l[xr].sum()

Alternatives to perform Final step

Alternative #1 :

sidx = yr.argsort()
idx = np.searchsorted(yr,xr,sorter=sidx)
idx[idx==len(yr)] = 0
count = (yr[sidx[idx]] == xr).sum()

Alternative #2 :

from scipy.sparse import csr_matrix

ly = len(yr)
y_extent = yr.max()+1  # or use s[-1]*M if M is small enough
r = np.zeros(ly, dtype=np.uint64)
val = np.ones(ly, dtype=np.bool)
sp_mat = csr_matrix((val, (r,yr)), shape=(1,y_extent))
count = sp_mat[:,xr].sum()

Alternative #3 :

For bigger M number, we can use empty arrays instead -

l = np.empty(N, dtype=bool)
l[xr] = False
l[yr] = True
count = l[xr].sum()

Digging further (Leveraging numba on convolution)

Profiling on the main proposed solution reveals that the 1D convolution part was the time-consuming part. Going further, we see that the 1D convolution code has a specific kernel that is geometric  in nature. This could be implemented in O(n) upon re-using boundary elements per iteration. Note that this would be basically an inverted kernel as compared to the one proposed earlier. So, putting all of those changes, we end up with something like this -

from numba import njit

@njit
def numba1(y, conv_out, M, L, N):
    A = M**L
    for i in range(1,N):
        conv_out[i] = conv_out[i-1]*M + y[i+L-1] - y[i-1]*A
    return conv_out

def numba_convolve(y, M, L):
        N = len(y)-L+1
        conv_out = np.empty(N, dtype=int)
        conv_out[0] = y[:L].dot(M**np.arange(L-1,-1,-1))
        return numba1(y, conv_out, M, L, N)

def intersection_count(xs, y):
    x = np.asarray(xs) # convert to array, if not already done

    L = x.shape[1]
    s = M**np.arange(L-1,-1,-1)
    xr = x.dot(s)

    yr_numba = numba_convolve(y, M=M, L=L)

    # Final step : Match and get count
    N = s[0]*M
    l = np.zeros(N, dtype=bool)
    l[yr_numba] = True
    count = l[xr].sum()
    return count

Benchmarking

We will re-use the setup from the question.

In [42]: %%timeit
    ...: y_bytes = y.tobytes()
    ...: p = sum(1 for x in xs if x.tobytes() in y_bytes)
927 ms ± 3.57 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [43]: %timeit intersection_count(xs, y)
7.55 ms ± 71.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

As noted earlier conversion to array could be the bottleneck. So, let's time that part too -

In [44]: %timeit np.asarray(xs)
3.41 ms ± 10.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

So, the array-conversion part is around 45% of total runtime and that's a substantial one. Hence, the suggestion to work with 2D array as opposed to list of 1D arrays becomes crucial at this point. The upside is array data gives us vectorized capability and hence improved performance overall. Just to emphasis on the 2D array availibility, here are the speedups with and without -

In [45]: 927/7.55
Out[45]: 122.78145695364239

In [46]: 927/(7.55-3.41)
Out[46]: 223.91304347826087


问:
Can I change the appearance of an html image during hover without a second image?
Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?</p>

答:
You don't use an img tag, but an element with a background-image css attribute and set the background-position on hover.  IE requires an 'a' tag as a parent element for the :hover selector.  They are called css sprites.

A great article explaining how to use CSS sprites.

OwnerDisplayName: Brent Nesbitt

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Brent Nesbitt

OwnerDisplayName: Mike Schall

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Mike Schall


问:
What does the "?:^" regular expression mean?
I am looking at this sub-expression (this is in JavaScript):

```<code>(?:^|.....)
</code>```

I know that ? means "zero or one times" when it follows a character, but not sure what it means in this context.

答:
When working with groups, you often have several options that modify the behavior of the group:

```<code>(foo)     // default behavior, matches "foo" and stores a back-reference
(?:foo)   // non-capturing group: matches "foo", but doesn't store a back-ref
(?i:foo)  // matches "foo" case-insensitively
(?=foo)   // matches "foo", but does not advance the current position
          // ("positive zero-width look-ahead assertion")
(?!foo)   // matches anything but "foo", and does not advance the position
          // ("negative zero-width look-ahead assertion")
</code>```

to name a few.

They all begin with "?", which is the way to indicate a group modifier. The question mark has nothing to do with optionality in this case.

It simply says:

```<code>(?:^foo)  // match "foo" at the start of the line, but do not store a back-ref
</code>```

Sometimes it's just overkill to store a back-reference to some part of the match that you are not going to use anyway. When the group is there only to make a complex expression atomic (e.g. it should either match or fail as a whole), storing a back-reference is an unnecessary waste of resources that can even slow down the regex a bit. And sometimes, you just want to be group 1 the first group relevant to you, instead of the first group in the regex.

OwnerDisplayName: levik

Body:
I am looking at this sub-expression (this is in JavaScript):

(?:^|.....)

I know that ? means "zero or one times" when it follows a character, but not sure what it means in this context.

LastEditorDisplayName: levik

Body:
When working with groups, you often have several options that modify the behavior of the group:

(foo)     // default behavior, matches "foo" and stores a back-reference
(?:foo)   // non-capturing group: matches "foo", but doesn't store a back-ref
(?i:foo)  // matches "foo" case-insensitively
(?=foo)   // matches "foo", but does not advance the current position
          // ("positive zero-width look-ahead assertion")
(?!foo)   // matches anything but "foo", and does not advance the position
          // ("negative zero-width look-ahead assertion")

to name a few.

They all begin with "?", which is the way to indicate a group modifier. The question mark has nothing to do with optionality in this case.

It simply says:

(?:^foo)  // match "foo" at the start of the line, but do not store a back-ref

Sometimes it's just overkill to store a back-reference to some part of the match that you are not going to use anyway. When the group is there only to make a complex expression atomic (e.g. it should either match or fail as a whole), storing a back-reference is an unnecessary waste of resources that can even slow down the regex a bit. And sometimes, you just want to be group 1 the first group relevant to you, instead of the first group in the regex.

OwnerDisplayName: Tomalak

LastEditorDisplayName: Tomalak


问:
How to connect Flask API endpoints to React app
I have an API made on Flask that has several endpoints. I am trying to use data from these end points to display a chart on my front end that shows the data to the user.

The following are my exact requirements:

Implement one or more types of charts that can be used to effectively visualize data supplied from the API endpoints. Users should be able to pick different metrics to visualize and compare with others.

My Flask API:

```<code>import os
from flask import Flask, jsonify, session, request
import sqlalchemy
import time
from functools import wraps

# web app
app = Flask(__name__)
app.secret_key = 'super_secure_key_that_should_be_in_.env'

# database engine
engine = sqlalchemy.create_engine(os.getenv('SQL_URI'))

def rate_limit(**limit_kwargs):
    def decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            limit = limit_kwargs['limit'] if 'limit' in limit_kwargs else 5
            seconds = limit_kwargs['window'] if 'window' in limit_kwargs else 60
            session_key = 'rate_limit_' + str(request.url_rule)
            if session_key not in session:
                session[session_key] = []

            window: list = session[session_key]
            if len(window) < limit:
                window.append(int(time.time()))
                session[session_key] = window
                return function(*args, **kwargs)

            if time.time() - window[0] < seconds:
                return jsonify(error='Rate limit exceeded'), 429

            window.pop(0)
            window.append(int(time.time()))
            session[session_key] = window
            return function(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/')
@rate_limit()
def index():
    return 'Welcome '

@app.route('/events/hourly')
@rate_limit(limit=3, window=20)
def events_hourly():
    return queryHelper('''
        SELECT date, hour, events
        FROM public.hourly_events
        ORDER BY date, hour
        LIMIT 168;
    ''')

@app.route('/events/daily')
@rate_limit(limit=2)
def events_daily():
    return queryHelper('''
        SELECT date, SUM(events) AS events
        FROM public.hourly_events
        GROUP BY date
        ORDER BY date
        LIMIT 7;
    ''')

@app.route('/stats/hourly')
@rate_limit(limit=3, window=20)
def stats_hourly():
    return queryHelper('''
        SELECT date, hour, impressions, clicks, revenue
        FROM public.hourly_stats
        ORDER BY date, hour
        LIMIT 168;
    ''')

@app.route('/stats/daily')
@rate_limit(limit=2)
def stats_daily():
    return queryHelper('''
        SELECT date,
            SUM(impressions) AS impressions,
            SUM(clicks) AS clicks,
            SUM(revenue) AS revenue
        FROM public.hourly_stats
        GROUP BY date
        ORDER BY date
        LIMIT 7;
    ''')

@app.route('/poi')
@rate_limit(limit=3)
def poi():
    return queryHelper('''
        SELECT *
        FROM public.poi;
    ''')

def queryHelper(query):
    with engine.connect() as conn:
        result = conn.execute(query).fetchall()
        return jsonify([dict(row.items()) for row in result])
</code>```

My React App.js:

```<code>import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

import DailyEvents from "./Components/DailyEvents";

class App extends Component {
    render() {
        return (
            <div className="App">
                <header className= "App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title"> Welcome to React</h1>
                </header>
                <DailyEvents />
            </div>
        );
    }
}

export default App;
</code>```

My Components/DailyEvents.js:

```<code>import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
  state = {
    dates: []
  }
    componentDidMount() {
    axios.get('api_url_or_localhost/events/daily')
    .then(res => res.json())
    .then((data) => {
      this.setState({ dates: data })
    })
    .catch(console.log)
  }
}

export default App;
</code>```

I keep getting a TypeError that instance.render is not a function.

What I am trying to do is use my Flask API endpoints to visualize the data on the front-end.

答:
Can / Should you make changes to the Flask API, or is that code part of the requirements? Because I'm pretty sure you won't be able to return those Date objects straight from the DB without serializing them first.

I suggest you use Postman (or just a browser, for get requests) to test the routes locally and basically have a look at the data first.
React can use Axios or fetch to get this data and visualize it.

```<code>import React, { Component } from 'react'

class App extends Component {
  state = {
    dates: []
  }
    componentDidMount() {
    fetch('api_url_or_localhost/events/daily'))
    .then(res => res.json())
    .then((data) => {
      this.setState({ dates: data })
    })
    .catch(console.log)
  }
  ...
}
</code>```

see this https://pusher.com/tutorials/consume-restful-api-react for more details

Body:
I have an API made on Flask that has several endpoints. I am trying to use data from these end points to display a chart on my front end that shows the data to the user.

The following are my exact requirements:

Implement one or more types of charts that can be used to effectively visualize data supplied from the API endpoints. Users should be able to pick different metrics to visualize and compare with others.

My Flask API:

import os
from flask import Flask, jsonify, session, request
import sqlalchemy
import time
from functools import wraps

# web app
app = Flask(__name__)
app.secret_key = 'super_secure_key_that_should_be_in_.env'

# database engine
engine = sqlalchemy.create_engine(os.getenv('SQL_URI'))

def rate_limit(**limit_kwargs):
    def decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            limit = limit_kwargs['limit'] if 'limit' in limit_kwargs else 5
            seconds = limit_kwargs['window'] if 'window' in limit_kwargs else 60
            session_key = 'rate_limit_' + str(request.url_rule)
            if session_key not in session:
                session[session_key] = []

            window: list = session[session_key]
            if len(window) < limit:
                window.append(int(time.time()))
                session[session_key] = window
                return function(*args, **kwargs)

            if time.time() - window[0] < seconds:
                return jsonify(error='Rate limit exceeded'), 429

            window.pop(0)
            window.append(int(time.time()))
            session[session_key] = window
            return function(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/')
@rate_limit()
def index():
    return 'Welcome '

@app.route('/events/hourly')
@rate_limit(limit=3, window=20)
def events_hourly():
    return queryHelper('''
        SELECT date, hour, events
        FROM public.hourly_events
        ORDER BY date, hour
        LIMIT 168;
    ''')

@app.route('/events/daily')
@rate_limit(limit=2)
def events_daily():
    return queryHelper('''
        SELECT date, SUM(events) AS events
        FROM public.hourly_events
        GROUP BY date
        ORDER BY date
        LIMIT 7;
    ''')

@app.route('/stats/hourly')
@rate_limit(limit=3, window=20)
def stats_hourly():
    return queryHelper('''
        SELECT date, hour, impressions, clicks, revenue
        FROM public.hourly_stats
        ORDER BY date, hour
        LIMIT 168;
    ''')

@app.route('/stats/daily')
@rate_limit(limit=2)
def stats_daily():
    return queryHelper('''
        SELECT date,
            SUM(impressions) AS impressions,
            SUM(clicks) AS clicks,
            SUM(revenue) AS revenue
        FROM public.hourly_stats
        GROUP BY date
        ORDER BY date
        LIMIT 7;
    ''')

@app.route('/poi')
@rate_limit(limit=3)
def poi():
    return queryHelper('''
        SELECT *
        FROM public.poi;
    ''')

def queryHelper(query):
    with engine.connect() as conn:
        result = conn.execute(query).fetchall()
        return jsonify([dict(row.items()) for row in result])

My React App.js:

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

import DailyEvents from "./Components/DailyEvents";

class App extends Component {
    render() {
        return (

 Welcome to React

                <DailyEvents />

        );
    }
}

export default App;

My Components/DailyEvents.js:

import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
  state = {
    dates: []
  }
    componentDidMount() {
    axios.get('api_url_or_localhost/events/daily')
    .then(res => res.json())
    .then((data) => {
      this.setState({ dates: data })
    })
    .catch(console.log)
  }
}

export default App;

I keep getting a TypeError that instance.render is not a function.

What I am trying to do is use my Flask API endpoints to visualize the data on the front-end.

Body:
Can / Should you make changes to the Flask API, or is that code part of the requirements? Because I'm pretty sure you won't be able to return those Date objects straight from the DB without serializing them first.

I suggest you use Postman (or just a browser, for get requests) to test the routes locally and basically have a look at the data first.
React can use Axios or fetch to get this data and visualize it.

import React, { Component } from 'react'

class App extends Component {
  state = {
    dates: []
  }
    componentDidMount() {
    fetch('api_url_or_localhost/events/daily'))
    .then(res => res.json())
    .then((data) => {
      this.setState({ dates: data })
    })
    .catch(console.log)
  }
  ...
}

see this https://pusher.com/tutorials/consume-restful-api-react for more details


问:
How to change site title on scroll
I want to change the site title's h1(.site-h1) to another text when down scrolling with jquery. For example, "my site" changes "welcome" when scrolling.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

my title

   MENU

          <button type="button" name="button">CONTACTME</button>

```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navbar {
  background-color: #F4F7F6;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}

.navbar .site-h1 h1 {
  text-align: center;
  font-family: 'Oleo Script', cursive;
  color: #202221;
  font-size: 2rem;
  margin-top: 1rem;
}

.navbar .menu-title {
  cursor: pointer;
}

.navbar .menu-title h2 {
  margin-top: -65px ;
  padding: .7rem 1.2rem;
  font-family: 'Roboto Slab', serif;
  font-size: .8rem;
  font-weight: lighter;
  transition: 1s;
}

.navbar .menu-title h2:hover {
  color: #A6ABAB;
}

.navbar .contactme {
  text-align: right;
  margin-top: -50px;
  padding-right: 1rem;
  font-family: 'Roboto Slab', serif;
  padding-bottom: 1rem;
}

.navbar .contactme button {
  background-color: #DF3E7B;
  color: #F4F7F6;
  border: none;
  border-radius: 1rem;
  padding: .7rem;
  font-weight: bold;
  font-size: .8rem;
  cursor: pointer;
}

.navbar .contactme button:hover {
  background-color: #dd85a5;
}</code>```

答:
Try this

$(window).one('scroll', function() {
    $('.title').text('Welcome');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<h1 class="title">Hello welcome </h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br></code>```

Title: How to change site title on scroll

Body:
I want to change the site title's h1(.site-h1) to another text when down scrolling with jquery. For example, "my site" changes "welcome" when scrolling.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

my title

   MENU

          <button type="button" name="button">CONTACTME</button>

.navbar {
  background-color: #F4F7F6;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}

.navbar .site-h1 h1 {
  text-align: center;
  font-family: 'Oleo Script', cursive;
  color: #202221;
  font-size: 2rem;
  margin-top: 1rem;
}

.navbar .menu-title {
  cursor: pointer;
}

.navbar .menu-title h2 {
  margin-top: -65px ;
  padding: .7rem 1.2rem;
  font-family: 'Roboto Slab', serif;
  font-size: .8rem;
  font-weight: lighter;
  transition: 1s;
}

.navbar .menu-title h2:hover {
  color: #A6ABAB;
}

.navbar .contactme {
  text-align: right;
  margin-top: -50px;
  padding-right: 1rem;
  font-family: 'Roboto Slab', serif;
  padding-bottom: 1rem;
}

.navbar .contactme button {
  background-color: #DF3E7B;
  color: #F4F7F6;
  border: none;
  border-radius: 1rem;
  padding: .7rem;
  font-weight: bold;
  font-size: .8rem;
  cursor: pointer;
}

.navbar .contactme button:hover {
  background-color: #dd85a5;
}

Body:
Try this

$(window).one('scroll', function() {
    $('.title').text('Welcome');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<h1 class="title">Hello welcome </h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>


问:
How can I check whether a double has a fractional part?
Basically I have two variables:

```<code>double halfWidth = Width / 2;
double halfHeight = Height / 2;
</code>```

As they are being divided by 2, they will either be a whole number or a decimal. How can I check whether they are a whole number or a .5?

答:
You may discard a fractional part and compare the result with the original value using floor():

```<code>if (floor(halfWidth) == halfWidth) {
    // halfWidth is a whole number
} else {
    // halfWidth has a non-zero fractional part
}
</code>```

As rightly pointed out by @Dávid Laczkó, it's a better solution than modf() because there's no need for an additional variable.

And according to my benchmarks (Linux, gcc 8.3.0, optimizations -O0...-O3), the floor() call consumes less CPU time than modf() on the modern notebook and server processors. The difference even growing with compiler optimizations enabled. Probably it's because the modf() has two arguments when the floor() has only one argument.

Body:
Basically I have two variables:

double halfWidth = Width / 2;
double halfHeight = Height / 2;

As they are being divided by 2, they will either be a whole number or a decimal. How can I check whether they are a whole number or a .5?

Body:
You may discard a fractional part and compare the result with the original value using floor():

if (floor(halfWidth) == halfWidth) {
    // halfWidth is a whole number
} else {
    // halfWidth has a non-zero fractional part
}

As rightly pointed out by @Dávid Laczkó, it's a better solution than modf() because there's no need for an additional variable.

And according to my benchmarks (Linux, gcc 8.3.0, optimizations -O0...-O3), the floor() call consumes less CPU time than modf() on the modern notebook and server processors. The difference even growing with compiler optimizations enabled. Probably it's because the modf() has two arguments when the floor() has only one argument.


问:
Logging GPS locations to file in Android
I have an Android application that periodically gets GPS updates. If I wanted to store the lat, lon, speed, altitude etc. in a file, what is the best practice for doing this?</p>

答:
Every time you receive a geo fix, store the location into a file. In the method onLocationChanged call something like

```<code>protected void storeLastKnownLocation(Location lastKnownLocation) {
    //save last known location
    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
    editor.putFloat(LAST_KNOWN_LNG_KEY, (float) lastKnownLocation..getLongitude());
    editor.putFloat(LAST_KNOWN_LAT_KEY, (float) lastKnownLocation.getLatitude());
    editor.commit();
}
</code>```

When the Activity starts, in the onCreate method you'll retrieve those values as

```<code>float lastKnownLng = getPreferences(MODE_PRIVATE).getFloat(LAST_KNOWN_LNG_KEY, 0f);
float lastKnownLat = getPreferences(MODE_PRIVATE).getFloat(LAST_KNOWN_LAT_KEY, 0f);
...
</code>```

Body:
Every time you receive a geo fix, store the location into a file. In the method onLocationChanged call something like

protected void storeLastKnownLocation(Location lastKnownLocation) {
    //save last known location
    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
    editor.putFloat(LAST_KNOWN_LNG_KEY, (float) lastKnownLocation..getLongitude());
    editor.putFloat(LAST_KNOWN_LAT_KEY, (float) lastKnownLocation.getLatitude());
    editor.commit();
}

When the Activity starts, in the onCreate method you'll retrieve those values as

float lastKnownLng = getPreferences(MODE_PRIVATE).getFloat(LAST_KNOWN_LNG_KEY, 0f);
float lastKnownLat = getPreferences(MODE_PRIVATE).getFloat(LAST_KNOWN_LAT_KEY, 0f);
...


问:
IE or Edge Print dialog box send request to server without session (because SameSite=Lax on session cookie)
I have a asp.net site, which users can login and members can get report or print page by Ctrl+P.

Recently when my members open my site in IE and try to print, they are logged out!

why?
because IE print dialog send some request to server without session cookie, so StateServer release new session for this client and then user logged out.

Why print dialog sent request?
I don't know, but i guess IE print dialog try to renders page and ready it for print.

Why print dialog don't sent current session cookie?
because new update of .net set SameSite=lax for session cookie, so requests from print dialog can't send current session cookie.
https://support.microsoft.com/en-us/help/4524419/kb4524419

How can i prevent IE print dialog from send request?
or how can i force IE print dialog to send same session cookie?

Any idea?

Edited:
I create a sample project to show this problem. you can download my project and host on IIS, then open Default.Aspx and try to print that page in IE(or edge).
You'll seen my problem.
https://easyupload.io/w6vvpy

答:
Found the fix:

You have to set the cookieSameSite= "None" in the session state tag to avoid this issue. I've tried this and working well in all browsers.

```<code><sessionState cookieSameSite="None" cookieless="false" timeout="360">
</sessionState>
</code>```

Body:
Found the fix:

You have to set the cookieSameSite= "None" in the session state tag to avoid this issue. I've tried this and working well in all browsers.

<sessionState cookieSameSite="None" cookieless="false" timeout="360">
</sessionState>


问:
Can I hash two strings into one hash?
I am pretty new to Python and wanted to create some code which hashed together two strings. In particular for my case I wanted to hash the hash of a file and a Bitcoins Blocks hash. The code bellow obviously doesn't work as sha256() takes only one argument. Do you guys know anyway around this?

Thanks,

```<code>from __future__ import print_function
import blocktrail, time, csv, hashlib, sys

client = blocktrail.APIClient(api_key="x", api_secret="x", network="BTC", testnet=False)
address = client.address('x')

latest_block = client.block_latest()
hash_list = []
h = latest_block['hash']
sha256 = hashlib.sha256()
BUF_SIZE = 65536
print("test")

with open('entries#x.csv', 'rb') as entriesfile:
    buf = entriesfile.read(BUF_SIZE)
    while len(buf) > 0:
        sha256.update(buf)
        buf = entriesfile.read(BUF_SIZE)
    print(sha256.hexdigest())

entryhash = sha256.hexdigest()

hashofhe = hashlib.sha256(b'entryhash', 'h')
</code>```

答:
Just a comment on this as I was looking for advice on the same subject:

Concatenating the two strings and hashing is not necessarily a good idea as you can have easy collisions: "hello", "world" will have the same hash as "hel", "loworld".

If you know your strings well, you can find a neat separator to avoid this.

Another option could be to prepend the size of each string before concatenation, so you would end up hashing "5hello5world" and "3hel8loworld" and is much less likely to generate collisions.

If all you want is to implement __hash__, you could do hash(hash(a) + hash(b)).

Title: Can I hash two strings into one hash?

Body:
I am pretty new to Python and wanted to create some code which hashed together two strings. In particular for my case I wanted to hash the hash of a file and a Bitcoins Blocks hash. The code bellow obviously doesn't work as sha256() takes only one argument. Do you guys know anyway around this?

Thanks,

from __future__ import print_function
import blocktrail, time, csv, hashlib, sys

client = blocktrail.APIClient(api_key="x", api_secret="x", network="BTC", testnet=False)
address = client.address('x')

latest_block = client.block_latest()
hash_list = []
h = latest_block['hash']
sha256 = hashlib.sha256()
BUF_SIZE = 65536
print("test")

with open('entries#x.csv', 'rb') as entriesfile:
    buf = entriesfile.read(BUF_SIZE)
    while len(buf) > 0:
        sha256.update(buf)
        buf = entriesfile.read(BUF_SIZE)
    print(sha256.hexdigest())

entryhash = sha256.hexdigest()

hashofhe = hashlib.sha256(b'entryhash', 'h')


问:
iOS 11 disable password autofill accessory view option?
As of now I would like to opt out of the new option iOS 11 gives, that is to suggest passwords in the app. When I run the app on iOS 11 I get the autofill option on top of the keyboard and my username and password textfield don't even show up.

So, my question is, how can I disable the new password autofill feature all together so the key on the keyboard is not shown at all and the overall behavior is the same as pre iOS 11?

答:
I have attached the screenshot. you can change the content Type as Username in the storyboard or you can do programatically.
you may create an extension for UITextfield .

```<code>func diableAutofill() {
        self.autocorrectionType = .no
        if #available(iOS 11.0, *) {
            self.textContentType = .username
        } else {
            self.textContentType = .init("")
        }
    }
</code>```

Body:
I have attached the screenshot. you can change the content Type as Username in the storyboard or you can do programatically.
you may create an extension for UITextfield .

func diableAutofill() {
        self.autocorrectionType = .no
        if #available(iOS 11.0, *) {
            self.textContentType = .username
        } else {
            self.textContentType = .init("")
        }
    }


问:
jQuery DataTable : Individual column searching on table header
I have followed the steps on Individual column searching (text inputs) and  Individual column searching (select inputs) to use multiple filters on jQuery DataTable and there are multiple filters on the footer. On the other hand, I want to move these filters to the header of the DataTable, but cannot align them horizontally as displayed on the image below. There are some examples as Custom filtering - range search, but they are not aligned as well. Is it possible to do this?

```<code>$(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );

    // DataTable
    var table = $('#example').DataTable();

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );
</code>```

答:
In your code use this.header() instead of this.footer()

like:

```<code>$( 'input', this.header() ).on( 'keyup change', function () {

        // your code
});
</code>```

Hope it will work for you.

Body:
I have followed the steps on Individual column searching (text inputs) and  Individual column searching (select inputs) to use multiple filters on jQuery DataTable and there are multiple filters on the footer. On the other hand, I want to move these filters to the header of the DataTable, but cannot align them horizontally as displayed on the image below. There are some examples as Custom filtering - range search, but they are not aligned as well. Is it possible to do this?

$(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );

    // DataTable
    var table = $('#example').DataTable();

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );

Body:
In your code use this.header() instead of this.footer()

like:

$( 'input', this.header() ).on( 'keyup change', function () {

        // your code
});

Hope it will work for you.


问:
Encoding 20-bit number across bytes in Go
I have the following layout I am trying to achieve in Go.

At the moment I can work out how to encode/set bits 6 & 7 from Byte 0

```<code>// Element ID flag
bytesToSend[0] |= (1 << 7)

//N/S Flag
bytesToSend[0] |= (1 << 6)
</code>```

I cannot work out however how to encode the 20-bit "Block Number" in Go.

I do think that to read it I will be doing...

```<code>block_num_out := ((int(bytesToSend[0]) & 0x0f) << 16) | (int(bytesToSend[1]) << 8) | (int(bytesToSend[2]))
</code>```

My encoding I have tried...

```<code>block_num_in := 343348
bytesToSend[0] |= block_num_in << 16
</code>```

But this gives an error of...

invalid operation: bytesToSend[0] |= block_num_in << 16 (mismatched types byte and int)

I have also tried

```<code>block_num_in := 343348
bytesToSend[0] |= (byte(block_num_in) << 16) & 0x0f
bytesToSend[1] |= byte(block_num_in) << 8
bytesToSend[2] |= byte(block_num_in)
</code>```

Any ideas?  Thanks!

答:
When writing, you have to use the opposite shifting direction. And since block_num_in is of type int, you have to convert the result to byte:

```<code>bytesToSend[0] |= byte(block_num_in >> 16 & 0x0f)
bytesToSend[1] = byte(block_num_in >> 8 & 0xff)
bytesToSend[2] = byte(block_num_in)
</code>```

Also if you have to do a lot of bit kung fu involving stepping byte boundaries, consider using github.com/icza/bitio (disclosure: I'm the author).

Body:
I have the following layout I am trying to achieve in Go.

At the moment I can work out how to encode/set bits 6 & 7 from Byte 0

// Element ID flag
bytesToSend[0] |= (1 << 7)

//N/S Flag
bytesToSend[0] |= (1 << 6)

I cannot work out however how to encode the 20-bit "Block Number" in Go.

I do think that to read it I will be doing...

block_num_out := ((int(bytesToSend[0]) & 0x0f) << 16) | (int(bytesToSend[1]) << 8) | (int(bytesToSend[2]))

My encoding I have tried...

block_num_in := 343348
bytesToSend[0] |= block_num_in << 16

But this gives an error of...

invalid operation: bytesToSend[0] |= block_num_in << 16 (mismatched types byte and int)

I have also tried

block_num_in := 343348
bytesToSend[0] |= (byte(block_num_in) << 16) & 0x0f
bytesToSend[1] |= byte(block_num_in) << 8
bytesToSend[2] |= byte(block_num_in)

Any ideas?  Thanks!

Body:
When writing, you have to use the opposite shifting direction. And since block_num_in is of type int, you have to convert the result to byte:

bytesToSend[0] |= byte(block_num_in >> 16 & 0x0f)
bytesToSend[1] = byte(block_num_in >> 8 & 0xff)
bytesToSend[2] = byte(block_num_in)

Also if you have to do a lot of bit kung fu involving stepping byte boundaries, consider using github.com/icza/bitio (disclosure: I'm the author).


问:
Ext.container.Container / ExtJS: How to jump to the element by id?
I am using a page which is extended Ext.container.Container. How to jump to element by id with ExtJS script? </p>

答:
I will try to give you an answer that fits your needs. But maybe you can make an example or be a bit more specific in your question.

You can use the ComponentQuery to navigate to specific components in your ExtJS application. (https://docs.sencha.com/extjs/7.0.0/modern/Ext.ComponentQuery.html)

There is also an up (https://docs.sencha.com/extjs/7.0.0/modern/Ext.Container.html#method-up) and down (https://docs.sencha.com/extjs/7.0.0/modern/Ext.Container.html#method-down) selector method which can be used to find components by id like this:

```<code>let myComponent = myContainer.down('#myComponentID');
</code>```

or

```<code>let myContainer = containerChild.up('container');
</code>```

You should definitly check out the ComponentQuery documentation to learn more about selector other than id.

And last but not least: Don't use the @cfg id to set an id to your component. Use the @cfg itemId (https://docs.sencha.com/extjs/7.0.0/modern/Ext.Widget.html#cfg-itemId).

I hope this will help you.

Body:
I will try to give you an answer that fits your needs. But maybe you can make an example or be a bit more specific in your question.

You can use the ComponentQuery to navigate to specific components in your ExtJS application. (https://docs.sencha.com/extjs/7.0.0/modern/Ext.ComponentQuery.html)

There is also an up (https://docs.sencha.com/extjs/7.0.0/modern/Ext.Container.html#method-up) and down (https://docs.sencha.com/extjs/7.0.0/modern/Ext.Container.html#method-down) selector method which can be used to find components by id like this:

let myComponent = myContainer.down('#myComponentID');

or

let myContainer = containerChild.up('container');

You should definitly check out the ComponentQuery documentation to learn more about selector other than id.

And last but not least: Don't use the @cfg id to set an id to your component. Use the @cfg itemId (https://docs.sencha.com/extjs/7.0.0/modern/Ext.Widget.html#cfg-itemId).

I hope this will help you.


问:
Pyinstaller write method crash on executable
After create the executable file with pyinstaller, crash application in write method.
Anyone know how solved this problem?

MacOS Catalina

Python 3.6

```<code>fw = open("/Users/user/Desktop/samplefolder/sample.csv", "wt")
fw.write("Hello")
fw.close()
</code>```

答:
please use the below code if you are trying to write data into a .csv file using python

```<code>import csv
with open('sample.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["Hello"])
</code>```

Body:
After create the executable file with pyinstaller, crash application in write method.
Anyone know how solved this problem?

MacOS Catalina

Python 3.6

fw = open("/Users/user/Desktop/samplefolder/sample.csv", "wt")
fw.write("Hello")
fw.close()

Body:
please use the below code if you are trying to write data into a .csv file using python

import csv
with open('sample.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["Hello"])


问:
SSH Key - Still asking for password and passphrase
I've been somewhat 'putting up' with Github always asking for my username and password when I clone a repository.  I want to bypass this step because it is an annoyance within my workflow.

I tried setting up an SSH key (which I successfully did) using this guide. https://help.github.com/articles/generating-ssh-keys and I was successful.

My problem is that I am still asked for my github password and passphrase when cloning a repository (using SSH).  My understanding was that after I set up this SSH key, I would no longer have to do that.

I am a little unsure what to ask, so I will just state my goal.

I want to be able to clone repositories without having to put in my Github information all the time.

What am I missing with my SSH key? If anyone can provide some guidance or resources I would appreciate it, because I've always felt a little lost when it came to SSH authentication in GitHub.

From my knowledge, this is a command that tests if things are working properly, here are the output from my console:

```<code>~ $ ssh -T git@github.com
Saving password to keychain failed
Enter passphrase for key '/Users/MYNAME/.ssh/id_rsa':
Hi MYNAME! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

When I input my password, should that fail first? Then, when I enter my passphrase, it passes.

答:
As explained in Cloning a Git repo from VSTS over SSH asks a password! Unexpected

The problem may be because of public key authentication failing, so it then asks for mycompany account's password.

This would not happen if the public key authentication succeeded.

So you might check id_rsa.pub and even create a new one.

Body:
I've been somewhat 'putting up' with Github always asking for my username and password when I clone a repository.  I want to bypass this step because it is an annoyance within my workflow.

I tried setting up an SSH key (which I successfully did) using this guide. https://help.github.com/articles/generating-ssh-keys and I was successful.

My problem is that I am still asked for my github password and passphrase when cloning a repository (using SSH).  My understanding was that after I set up this SSH key, I would no longer have to do that.

I am a little unsure what to ask, so I will just state my goal.

I want to be able to clone repositories without having to put in my Github information all the time.

What am I missing with my SSH key? If anyone can provide some guidance or resources I would appreciate it, because I've always felt a little lost when it came to SSH authentication in GitHub.

From my knowledge, this is a command that tests if things are working properly, here are the output from my console:

~ $ ssh -T git@github.com
Saving password to keychain failed
Enter passphrase for key '/Users/MYNAME/.ssh/id_rsa':
Hi MYNAME! You've successfully authenticated, but GitHub does not provide shell access.

When I input my password, should that fail first? Then, when I enter my passphrase, it passes.


问:
Using XSL to move from one node to another
So I want to convert the following using XSL

```<code><doc>
    <data id="priority" level="2" include="true">
        <name>Priority</name>
    </data>
    <data id="cost" level="1" leveltype="number">
        <name>Cost</name>
    </data>
    <data id="date" level="3" include="true">
        <name>Date</name>
    </data>
</doc>
</code>```

To this

```<code><doc>
    <data id="priority">
        <name>Priority</name>
    </data>
    <data id="cost">
        <name>Cost</name>
    </data>
    <data id="date">
        <name>Date</name>
    </data>

    <!-- ordering matters, though if necessary I can reorder this manually via the DOM instead of XSL -->
    <levels>
        <level id="cost" include="false" type="number"/>
        <level id="priority" include="true"/>
        <level id="date" include="true"/>
    </level>
</doc>
</code>```

Basically I want to take the level attributes and make them their own thing. A huge bonus would be if there were some way to remove the level number and use the order of the node instead to represent that.

答:
This is a shorter and simpler solution using only templates (no <xsl:for-each>):

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="/*">
  <doc>
   <xsl:apply-templates select="*"/>
   <levels>
    <xsl:apply-templates select="data" mode="level">
     <xsl:sort select="@level" data-type="number"/>
    </xsl:apply-templates>
   </levels>
  </doc>
 </xsl:template>
 <xsl:template match="data/@*[not(name()='id')]"/>

 <xsl:template match="data" mode="level">
  <level id="{@id}" include="{boolean(@include)}">
   <xsl:if test="@leveltype">
    <xsl:attribute name="type"><xsl:value-of select="@leveltype"/></xsl:attribute>
   </xsl:if>
  </level>
 </xsl:template>
</xsl:stylesheet>
</code>```

When applied on the provided XML document:

```<code><doc>
    <data id="priority" level="2" include="true">
        <name>Priority</name>
    </data>
    <data id="cost" level="1" leveltype="number">
        <name>Cost</name>
    </data>
    <data id="date" level="3" include="true">
        <name>Date</name>
    </data>
</doc>
</code>```

the wanted, correct result is produced:

```<code><doc>
   <data id="priority">
      <name>Priority</name>
   </data>
   <data id="cost">
      <name>Cost</name>
   </data>
   <data id="date">
      <name>Date</name>
   </data>
   <levels>
      <level id="cost" include="false" type="number"/>
      <level id="priority" include="true"/>
      <level id="date" include="true"/>
   </levels>
</doc>
</code>```

Explanation:

Using and overriding the identity rule/template.

Using mode="level" to generate the second part of the result-document.

Body:
So I want to convert the following using XSL

<doc>
    <data id="priority" level="2" include="true">
        <name>Priority</name>
    </data>
    <data id="cost" level="1" leveltype="number">
        <name>Cost</name>
    </data>
    <data id="date" level="3" include="true">
        <name>Date</name>
    </data>
</doc>

To this

<doc>
    <data id="priority">
        <name>Priority</name>
    </data>
    <data id="cost">
        <name>Cost</name>
    </data>
    <data id="date">
        <name>Date</name>
    </data>

    <levels>
        <level id="cost" include="false" type="number"/>
        <level id="priority" include="true"/>
        <level id="date" include="true"/>
    </level>
</doc>

Basically I want to take the level attributes and make them their own thing. A huge bonus would be if there were some way to remove the level number and use the order of the node instead to represent that.

Body:
This is a shorter and simpler solution using only templates (no <xsl:for-each>):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="/*">
  <doc>
   <xsl:apply-templates select="*"/>
   <levels>
    <xsl:apply-templates select="data" mode="level">
     <xsl:sort select="@level" data-type="number"/>
    </xsl:apply-templates>
   </levels>
  </doc>
 </xsl:template>
 <xsl:template match="data/@*[not(name()='id')]"/>

 <xsl:template match="data" mode="level">
  <level id="{@id}" include="{boolean(@include)}">
   <xsl:if test="@leveltype">
    <xsl:attribute name="type"><xsl:value-of select="@leveltype"/></xsl:attribute>
   </xsl:if>
  </level>
 </xsl:template>
</xsl:stylesheet>

When applied on the provided XML document:

<doc>
    <data id="priority" level="2" include="true">
        <name>Priority</name>
    </data>
    <data id="cost" level="1" leveltype="number">
        <name>Cost</name>
    </data>
    <data id="date" level="3" include="true">
        <name>Date</name>
    </data>
</doc>

the wanted, correct result is produced:

<doc>
   <data id="priority">
      <name>Priority</name>
   </data>
   <data id="cost">
      <name>Cost</name>
   </data>
   <data id="date">
      <name>Date</name>
   </data>
   <levels>
      <level id="cost" include="false" type="number"/>
      <level id="priority" include="true"/>
      <level id="date" include="true"/>
   </levels>
</doc>

Explanation:

Using and overriding the identity rule/template.

Using mode="level" to generate the second part of the result-document.


问:
Encode UTF8 text to Unicode C#
How to encode UTF8 text to Unicode?

```<code>string text_txt = "Ð¿ÑÐ¸Ð²ÐµÑ";
byte[] bytesUtf8 = Encoding.Default.GetBytes(text_txt);
text_txt = Encoding.UTF8.GetString(bytesUtf8);
</code>```

The problem is output: п�?иве�

I need output: привет

Using that site: https://www.branah.com/unicode-converter enter text in "UTF-8 text (Example: a ä¸ Ð¯)" to "Ð¿ÑÐ¸Ð²ÐµÑ" it will show you "привет" on Unicode text

Please give some advice thanks

答:
```<code>   byte[] utf8Bytes = new byte[text_txt.Length];
                for (int i = 0; i < text_txt.Length; ++i)
                {
                    //Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
                    utf8Bytes[i] = (byte)text_txt[i];
                }
                text_txt= Encoding.UTF8.GetString(utf8Bytes, 0, text_txt.Length);
</code>```

from answer: How to convert a UTF-8 string into Unicode?

Title: Encode UTF8 text to Unicode C#

Body:
How to encode UTF8 text to Unicode?

string text_txt = "Ð¿ÑÐ¸Ð²ÐµÑ";
byte[] bytesUtf8 = Encoding.Default.GetBytes(text_txt);
text_txt = Encoding.UTF8.GetString(bytesUtf8);

The problem is output: п�?иве�

I need output: привет

Using that site: https://www.branah.com/unicode-converter enter text in "UTF-8 text (Example: a ä¸ Ð¯)" to "Ð¿ÑÐ¸Ð²ÐµÑ" it will show you "привет" on Unicode text

Please give some advice thanks

Body:
   byte[] utf8Bytes = new byte[text_txt.Length];
                for (int i = 0; i < text_txt.Length; ++i)
                {
                    //Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
                    utf8Bytes[i] = (byte)text_txt[i];
                }
                text_txt= Encoding.UTF8.GetString(utf8Bytes, 0, text_txt.Length);

from answer: How to convert a UTF-8 string into Unicode?


问:
How to set item position to bottomcenter launchbackground.xml
I tried to add to my app splash screen an image but I don't know how to set the gravity of it to bottom center. There is my code :

```<code><item
    android:width="265dp"
    android:height="160dp"
    android:drawable="@mipmap/bottomsplash"
    android:gravity="bottom" />
</code>```

The bottom gravity set it at the bottom left but I want it to bottom center.

答:
Try this : </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:width="265dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:height="160dp"
        android:drawable="@mipmap/bottomsplash"
        android:layout_marginBottom="50dp" />

</RelativeLayout>
</code>```

Body:
I tried to add to my app splash screen an image but I don't know how to set the gravity of it to bottom center. There is my code :

<item
    android:width="265dp"
    android:height="160dp"
    android:drawable="@mipmap/bottomsplash"
    android:gravity="bottom" />

The bottom gravity set it at the bottom left but I want it to bottom center.

Body:
Try this :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:width="265dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:height="160dp"
        android:drawable="@mipmap/bottomsplash"
        android:layout_marginBottom="50dp" />

</RelativeLayout>


问:
How to Select Last three Characters in XSLT
I need to select the last three characters of a string in xslt.

Example# if the string has "IAMFINE" I need the output as "INE"
         if String has "MYNAMEIS" I need the out as "EIS"

答:
check it</p>

```<code><xsl:value-of select="substring(., string-length(.) -2)" />
</code>```

Body:
check it

<xsl:value-of select="substring(., string-length(.) -2)" />


问:
How to manipulate data by Symfony Form (with JS, AJAX)?
I've got a short question. Let's say I have the data from database in my Symfony app and on the same page I have a form which is responsible for manipulate these data. Saying "manipulate" I mean: displaying or hiding some data and sorting them. I think the best way to achieve this would be use a JavaScript/AJAX. The thing is I never wrote even JavaScript in my Symfony apps and I completly don't know how to go about it.

Have you got some link to documentation, tutorial or article which will show me how to manipulate data by JavaScript/AJAX in Symfony? Or could you please explain me it in a few words?

Thank you in advance for helping!

答:
In Symfony, we use and compile JS files as assets in order to use them on pages. You might want to use JQuery when performing AJAX-requests. Using JQuery, AJAX can be coded by the following way:

```<code>$.ajax({
   url: <insert url here>,
   type: <insert type here, for example, GET>,
   dataType: <insert data type here, for example, json>,
   success:function(data) {
      <Implement a function which is applied after a successful request. Variable "data" is the result of the request.>
   }
   error:function(data) {
      <Optionally, implement a function which shows information when request was not successful.>
   }
});
</code>```

For example, you have the class .cl on page and want to change HTML code of it. Then use $('.cl').replaceWith($(data).find('.cl')) in the success function.

Body:
In Symfony, we use and compile JS files as assets in order to use them on pages. You might want to use JQuery when performing AJAX-requests. Using JQuery, AJAX can be coded by the following way:

$.ajax({
   url: <insert url here>,
   type: <insert type here, for example, GET>,
   dataType: <insert data type here, for example, json>,
   success:function(data) {
      <Implement a function which is applied after a successful request. Variable "data" is the result of the request.>
   }
   error:function(data) {
      <Optionally, implement a function which shows information when request was not successful.>
   }
});

For example, you have the class .cl on page and want to change HTML code of it. Then use $('.cl').replaceWith($(data).find('.cl')) in the success function.


问:
Sphinx documentation and hover text
Is it possible, using sphinx, to have hover-boxes for words that appear inside code snippets, similar to what the hover-boxes in the code samples in the angular.js landing page look and behave like?</p>

答:
(For those who landed here while looking for hover tooltips in regular RsT text)

The :abbr: inline markup produces tooltips in HTML,
like that:

```<code>:abbr:`linkified text (tooltip text)`
</code>```

An alternative, fully functional solution is the sphinx-hoverxref extension, which retrofits a :ref:-like role that fetches tooltip content from the referenced section, figure, etc:

Title: Sphinx documentation and hover text

Body:
(For those who landed here while looking for hover tooltips in regular RsT text)

The :abbr: inline markup produces tooltips in HTML,
like that:

:abbr:`linkified text (tooltip text)`

An alternative, fully functional solution is the sphinx-hoverxref extension, which retrofits a :ref:-like role that fetches tooltip content from the referenced section, figure, etc:


问:
Find arguments for an EXE and make it run programmatically
Ten years ago, a previous developer of my company has created a software that let a user accomplish some repetitive tasks faster.
That developer splitted up the software in several exe files, based on specific functions, so we have a "main.exe" file that runs other exe (let's say "tasA.exe", "taskB.exe" and so on) depending on which task the user want to do.

Now my company would like to go further and automate some of that tasks, without the requirement of human action, and planned to replace one by one the "taskX.exe" files. Meanwhile, the "taskX.exe" files should be scheduled and runned in unattended mode, without have to pass from "main.exe", until the new version will be released.

Unfortunately, the company has no more the source code and the previous developer has not included any hint so calling the exe with "/?" "--help" has no effect: the exe simply exits, does not crash nor print anything, neither a log. Even its creator doesn't remember the exact params that could let it run in "unattended" mode, but he is certain that it is definitely possible.

The only thing I know, based on the dll surrounding the file, is that the exe was built with Python and QT library and when running it show a UI that let the user accomplish some operations.

Is there a way to know such arguments?

Can the arguments be desumed when the exe is running in attended mode?

Is there anything that I could try, maybe create a software that simulate the human action?

Thanks

答:
You have to reverse engineer it.

Extract the bytecode from the exe

Use a python decompiler to translate bytecode back to python


问:
How to get display this javascript returned value in html input field?
I want the result of JavaScript in my input field so that it will push the value to my server while clicking submit.

In this code I am able to get the Javascript result in HTML but I don't know how to display it in the input field.

My code is below. It will return the local LAN IP.

I am creating this page to fetch the local IPs from our office pc. Now the IP is displayed in the web page but I want it to be displayed in input box so that when user clicks on submit, the result is pushed to the server / database.

This when used in HTML body will display in  web page. This class='ipAdd' should be displayed in input field by setting its value.

$(document).ready(function ubsrt() {
  window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var pc = new RTCPeerConnection({
      iceServers: []
    }),
    noop = function() {};

  pc.createDataChannel("");
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);
  pc.onicecandidate = function(ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate) return;

    var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];

    console.log('my IP: ', myIP);
    $('.ipAdd').text(myIP);

    pc.onicecandidate = noop;

  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="formGroup">
  <label for="address">IP Address</label> <br>
  <input type="text" class="one" id="address" name="address" size="50px" id="" Value="id=" list "">
</div>

<h3 class='ipAdd'>
  <h3></code>```

答:
Try below code for help.

```<code>$('.ipAdd').html(myIP);  // this value display in html
$('#address').val(myIP); // this value store in input
</code>```

Body:
I want the result of JavaScript in my input field so that it will push the value to my server while clicking submit.

In this code I am able to get the Javascript result in HTML but I don't know how to display it in the input field.

My code is below. It will return the local LAN IP.

I am creating this page to fetch the local IPs from our office pc. Now the IP is displayed in the web page but I want it to be displayed in input box so that when user clicks on submit, the result is pushed to the server / database.

This when used in HTML body will display in  web page. This class='ipAdd' should be displayed in input field by setting its value.

$(document).ready(function ubsrt() {
  window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var pc = new RTCPeerConnection({
      iceServers: []
    }),
    noop = function() {};

  pc.createDataChannel("");
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);
  pc.onicecandidate = function(ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate) return;

    var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];

    console.log('my IP: ', myIP);
    $('.ipAdd').text(myIP);

    pc.onicecandidate = noop;

  };
});

  IP Address

  <input type="text" class="one" id="address" name="address" size="50px" id="" Value="id=" list "">

Body:
Try below code for help.

$('.ipAdd').html(myIP);  // this value display in html
$('#address').val(myIP); // this value store in input


问:
Android Execution failed for task ':app:compileDebugJavaWithJavac'. - React Native
I am working on a react native application. when I try to build the applications using react-native run-android the build fails. Here is the output of the error that occurs.

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 8s
253 actionable tasks: 5 executed, 248 up-to-date
error Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
error Command failed: ./gradlew app:installDebug
debug Error: Command failed: ./gradlew app:installDebug
    at checkExecSyncError (child_process.js:607:13)
    at execFileSync (child_process.js:627:13)
    at runOnAllDevices (/Users/FaisalHussain/mobile/node_modules/@react-native-community/cli/build/commands/runAndroid/runOnAllDevices.js:58:39)
    at buildAndRun (/Users/FaisalHussain/mobile/node_modules/@react-native-community/cli/build/commands/runAndroid/runAndroid.js:142:41)
    at then.result (/Users/FaisalHussain/mobile/node_modules/@react-native-community/cli/build/commands/runAndroid/runAndroid.js:104:12)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
</code>```

The application was on a old version of react native (0.48.x) I have updated it to 0.59.10.

What I have done so far:

used jetifier to resolve issues with the plugins.

checked that the build tools version matches the compile sdk version

checked if the emulator is running.

Hence I have tried everything I could to resolve this but had no luck. Please do guide me on how to resolve this issue. Looking forward to your answers.

答:
make sure you have followed all the necessary steps from the upgrade helper https://react-native-community.github.io/upgrade-helper/?from=0.48.0&to=0.59.10

also i would suggest you to upgrade to v0.60+ because there are breaking changes after v0.59.10.

having said that

before you run the app make sure your gradle is clean
run the following command to clean your gradle cd android && ./gradle clean
then later you can navigate back to your app folder cd ..  and try and run again react-native run-android

Body:
I am working on a react native application. when I try to build the applications using react-native run-android the build fails. Here is the output of the error that occurs.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 8s
253 actionable tasks: 5 executed, 248 up-to-date
error Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
error Command failed: ./gradlew app:installDebug
debug Error: Command failed: ./gradlew app:installDebug
    at checkExecSyncError (child_process.js:607:13)
    at execFileSync (child_process.js:627:13)
    at runOnAllDevices (/Users/FaisalHussain/mobile/node_modules/@react-native-community/cli/build/commands/runAndroid/runOnAllDevices.js:58:39)
    at buildAndRun (/Users/FaisalHussain/mobile/node_modules/@react-native-community/cli/build/commands/runAndroid/runAndroid.js:142:41)
    at then.result (/Users/FaisalHussain/mobile/node_modules/@react-native-community/cli/build/commands/runAndroid/runAndroid.js:104:12)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)

The application was on a old version of react native (0.48.x) I have updated it to 0.59.10.

What I have done so far:

used jetifier to resolve issues with the plugins.

checked that the build tools version matches the compile sdk version

checked if the emulator is running.

Hence I have tried everything I could to resolve this but had no luck. Please do guide me on how to resolve this issue. Looking forward to your answers.


答:
Looks like your packages not working stable with Android side. It's better be update all packages and react native version to their last stable versions.

If you face with too much error while update, you can create fresh new react native project (with same package name with your current project), install all packages (and their dependencies) and copy your current project's source code to your new project.

Title: Android Execution failed for task ':app:compileDebugJavaWithJavac'. - React Native


问:
Django converting year to a full date
In my book aplication I have a date field in model, but as an input from REST request sometimes I am getting just a year, or even full date but as a string format. I wanted to create at first a manual form to add a books where i don't know exact date of publication despite a year.

So what I am trying to do is in case of getting just a year add "01/01" and convert is to a date with
".strptime(s, "%Y-%m-%d").date()".  But that's not working, datefield default validator is preventing me from passing anything else than "yyyy-mm-dd" format input. Can i somehow overwrite a default validaotr or stop launching it by a form ? Any suggestion how to handle that problem?

Models:

```<code>class Book(models.Model):

title = models.CharField(max_length=100)
publication_date = models.DateField()
authors = models.ManyToManyField("Author", related_name="author")
ISBN = ISBNField() #validators=[book_unique_validator,]
pages = models.IntegerField(validators=[page_validator,], blank=True)
language = models.CharField(max_length=4)

def __str__(self):
    return self.title
</code>```

views:

```<code>class BookAddView(FormView):
    model = Book
    template_name = "Books/create_book.html"
    form_class = BookForm
    success_url = reverse_lazy("book_list")

    def form_valid(self, form):
        if Book.objects.filter(ISBN=form.cleaned_data["ISBN"]).count() > 0:
            messages.warning(self.request, f'Book "{form.cleaned_data["ISBN"]}" already exist in database.')
            return redirect("book_details", pk=Book.objects.get(ISBN=form.cleaned_data["ISBN"]).pk)
        else:
            if len(publication_date=form.cleaned_data['publication_date']) == 4:
                book_date = (form.cleaned_data['publication_date'] + "01/01").strptime(s, "%Y-%m-%d").date()
            else:
                book_date = publication_date=form.cleaned_data['publication_date']
        new_book = Book(
                    title=form.cleaned_data["title"].lower(),
                    publication_date=book_date,
                    ISBN=form.cleaned_data["ISBN"],
                    pages=form.cleaned_data["pages"],
                    language=form.cleaned_data["language"]
                )
            authors = Author.objects.filter(pk__in=form.cleaned_data["authors"])
            new_book.save()
            for author in authors:
                new_book.authors.add(author)
            new_book.save()
            pk = new_book.pk
            return redirect("covers_add", pk=pk)
</code>```

forms:

```<code>class BookForm(forms.ModelForm):
    title = forms.CharField()
    publication_date = forms.CharField()
    authors = forms.ModelMultipleChoiceField(Author.objects.all())
    ISBN = ISBNField()
    pages = forms.IntegerField()
    language = forms.CharField()

    class Meta:
        model = Book
        fields = ["title", "publication_date", "authors", "ISBN", "pages", "language"]
</code>```

答:
You can pass year, month and day to datetime.datetime class when only year is provided.

```<code>import datetime

if len(publication_date=form.cleaned_data['publication_date']) == 4:
    book_date = <b>datetime.datetime(int(form.cleaned_data['publication_date']), month=1, day=1).date()</b>
</code>```

datetime.datetime(int(form.cleaned_data['publication_date']), month=1, day=1) will return a datetime.datetime object. So you can easily get the date() from that.

Further read datetime Objects

Title: Django converting year to a full date

Body:
In my book aplication I have a date field in model, but as an input from REST request sometimes I am getting just a year, or even full date but as a string format. I wanted to create at first a manual form to add a books where i don't know exact date of publication despite a year.

So what I am trying to do is in case of getting just a year add "01/01" and convert is to a date with
".strptime(s, "%Y-%m-%d").date()".  But that's not working, datefield default validator is preventing me from passing anything else than "yyyy-mm-dd" format input. Can i somehow overwrite a default validaotr or stop launching it by a form ? Any suggestion how to handle that problem?

Models:

class Book(models.Model):

title = models.CharField(max_length=100)
publication_date = models.DateField()
authors = models.ManyToManyField("Author", related_name="author")
ISBN = ISBNField() #validators=[book_unique_validator,]
pages = models.IntegerField(validators=[page_validator,], blank=True)
language = models.CharField(max_length=4)

def __str__(self):
    return self.title

views:

class BookAddView(FormView):
    model = Book
    template_name = "Books/create_book.html"
    form_class = BookForm
    success_url = reverse_lazy("book_list")

    def form_valid(self, form):
        if Book.objects.filter(ISBN=form.cleaned_data["ISBN"]).count() > 0:
            messages.warning(self.request, f'Book "{form.cleaned_data["ISBN"]}" already exist in database.')
            return redirect("book_details", pk=Book.objects.get(ISBN=form.cleaned_data["ISBN"]).pk)
        else:
            if len(publication_date=form.cleaned_data['publication_date']) == 4:
                book_date = (form.cleaned_data['publication_date'] + "01/01").strptime(s, "%Y-%m-%d").date()
            else:
                book_date = publication_date=form.cleaned_data['publication_date']
        new_book = Book(
                    title=form.cleaned_data["title"].lower(),
                    publication_date=book_date,
                    ISBN=form.cleaned_data["ISBN"],
                    pages=form.cleaned_data["pages"],
                    language=form.cleaned_data["language"]
                )
            authors = Author.objects.filter(pk__in=form.cleaned_data["authors"])
            new_book.save()
            for author in authors:
                new_book.authors.add(author)
            new_book.save()
            pk = new_book.pk
            return redirect("covers_add", pk=pk)

forms:

class BookForm(forms.ModelForm):
    title = forms.CharField()
    publication_date = forms.CharField()
    authors = forms.ModelMultipleChoiceField(Author.objects.all())
    ISBN = ISBNField()
    pages = forms.IntegerField()
    language = forms.CharField()

    class Meta:
        model = Book
        fields = ["title", "publication_date", "authors", "ISBN", "pages", "language"]

Body:
You can pass year, month and day to datetime.datetime class when only year is provided.

import datetime

if len(publication_date=form.cleaned_data['publication_date']) == 4:
    book_date = datetime.datetime(int(form.cleaned_data['publication_date']), month=1, day=1).date()

datetime.datetime(int(form.cleaned_data['publication_date']), month=1, day=1) will return a datetime.datetime object. So you can easily get the date() from that.

Further read datetime Objects


问:
marklogic xdmp:http-post options parameter issue
Trying to build options parameter from another config XML to pass in the xdmp:http-post function.

```<code>let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$db-config/user-name/text()}</username>
                <password>{$db-config/password/text()}</password>
            </authentication>
        </options>
return $options
</code>```

output of the above code is:

```<code><options xmlns="xdmp:http">
  <authentication method="digest">
    <username>
    </username>
    <password>
    </password>
 </authentication>
</options>
</code>```

No able to understand why the xpath is returning blank.
On removing the xmlns="xdmp:http" namespace getting the correct output.

答:
That's because you are trying to fetch values from an xml without namespace and putting it in an xml with namespace. You can modify your code to this -

```<code>xquery version "1.0-ml";
let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$db-config/*:user-name/text()}</username>
                <password>{$db-config/*:password/text()}</password>
            </authentication>
        </options>
return $options
</code>```

For more understanding on how namespace work go through https://docs.marklogic.com/guide/xquery/namespaces#chapter

Body:
Trying to build options parameter from another config XML to pass in the xdmp:http-post function.

let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$db-config/user-name/text()}</username>
                <password>{$db-config/password/text()}</password>
            </authentication>
        </options>
return $options

output of the above code is:

<options xmlns="xdmp:http">
  <authentication method="digest">
    <username>
    </username>
    <password>
    </password>
 </authentication>
</options>

No able to understand why the xpath is returning blank.
On removing the xmlns="xdmp:http" namespace getting the correct output.

Body:
That's because you are trying to fetch values from an xml without namespace and putting it in an xml with namespace. You can modify your code to this -

xquery version "1.0-ml";
let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$db-config/*:user-name/text()}</username>
                <password>{$db-config/*:password/text()}</password>
            </authentication>
        </options>
return $options

For more understanding on how namespace work go through https://docs.marklogic.com/guide/xquery/namespaces#chapter