问:
how to hide WSDL using CXF
i have developed a Java Web service using CXF, and Spring.
due to security reasons, i would like to hide the WSDL, though the WS will still be available.
is there a way to do that using CXF?</p>

答:
You could add a servlet filter in web.xml that stops ?wsdl requests from being processed:

```<code><filter>
    <filter-name>wsdlFilter</filter-name>
    <filter-class>com.mycompany.myWsdlFilterClass</filter-class>
</filter>

<filter-mapping>
  <filter-name>wsdlFilter</filter-name>
  <url-pattern>*?wsdl</url-pattern>
</filter-mapping>
</code>```

The doFilter() method would look like this:

```<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
    ServletException {

  String queryString = ((HttpServletRequest) request).getQueryString();
  if(queryString!=null && queryString.toLowerCase().startsWith("wsdl")){
    return; //the filter chain stops and request does not get processed
  }
  else{
    chain.doFilter(request, response);
  }

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: how to hide WSDL using CXF

Body:
You could add a servlet filter in web.xml that stops ?wsdl requests from being processed:

<filter>
    <filter-name>wsdlFilter</filter-name>
    <filter-class>com.mycompany.myWsdlFilterClass</filter-class>
</filter>

<filter-mapping>
  <filter-name>wsdlFilter</filter-name>
  <url-pattern>*?wsdl</url-pattern>
</filter-mapping>

The doFilter() method would look like this:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
    ServletException {

  String queryString = ((HttpServletRequest) request).getQueryString();
  if(queryString!=null && queryString.toLowerCase().startsWith("wsdl")){
    return; //the filter chain stops and request does not get processed
  }
  else{
    chain.doFilter(request, response);
  }

}


来源: stackexchange

问:
Prevent loading page when changing select value
I got this select tag in my form, which contains the name of a room

```<code><select class = 'form-control' id = 'room_select' name = 'room'>".$rooms."</select>
</code>```

I got 4 rooms so this select contains 4 options

```<code>$(document).ready(function(){
$("select").msDropDown();
$("#room_select").change(function(e){
    e.preventDefault();
    $("#room_select_form").submit();
});
$("#room_select option[value='<?php echo $room; ?>']").attr('selected', 'selected');
});
</code>```

Then I got this doc ready function first one .msDropDown(); is to be able to get images in the options. Then I got the change function which I googled around and put in a preventdDefault to not refresh page, (still refresh) I thought that I could use an ajax funciton to do this but I dont really know how to write it down or even if it works.

So currently the problem is that my function changes the room value as seen last in the code, but it refreshes the select tag and I see room nr 1 again,

答:
Your page is getting refreshed, because you are submitting the form in onchange listener. You need to put e.preventDefault(); in your form submit listener to prevent default form submit and then you can call ajax in you submit listener.

```<code>$(document).ready(function(){
$("select").msDropDown();
$("#room_select").change(function(e){
    $("#room_select_form").submit();
});
$("#room_select option[value='<?php echo $room; ?>']").attr('selected', 'selected');
$("#room_select_form").submit(function(e){
  e.preventDefault(); // to prevent page refresh
  // your Ajax call goes here....

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

ContentLicense: CC BY-SA 4.0

Body:
I got this select tag in my form, which contains the name of a room

<select class = 'form-control' id = 'room_select' name = 'room'>".$rooms."</select>

I got 4 rooms so this select contains 4 options

$(document).ready(function(){
$("select").msDropDown();
$("#room_select").change(function(e){
    e.preventDefault();
    $("#room_select_form").submit();
});
$("#room_select option[value='<?php echo $room; ?>']").attr('selected', 'selected');
});

Then I got this doc ready function first one .msDropDown(); is to be able to get images in the options. Then I got the change function which I googled around and put in a preventdDefault to not refresh page, (still refresh) I thought that I could use an ajax funciton to do this but I dont really know how to write it down or even if it works.

So currently the problem is that my function changes the room value as seen last in the code, but it refreshes the select tag and I see room nr 1 again,

Body:
Your page is getting refreshed, because you are submitting the form in onchange listener. You need to put e.preventDefault(); in your form submit listener to prevent default form submit and then you can call ajax in you submit listener.

$(document).ready(function(){
$("select").msDropDown();
$("#room_select").change(function(e){
    $("#room_select_form").submit();
});
$("#room_select option[value='<?php echo $room; ?>']").attr('selected', 'selected');
$("#room_select_form").submit(function(e){
  e.preventDefault(); // to prevent page refresh
  // your Ajax call goes here....

});
});


问:
Using AND inside abs(number) in Python
Trying to understand how AND statement works inside abs(numbers) function.

Calling print(abs(21-22 and 9-4 and 11-8))

This would always give me whatever the last expression is. In this case it calculates 11-8, so it prints 3.
Why other expressions are not in the output and no error as well?

答:
The fact that the expression is inside an abs call doesn't change the way that it's interpreted:

```<code>>>> 21-22 and 9-4 and 11-8
3
</code>```

which is of course the same as:

```<code>>>> -1 and 5 and 3
3
</code>```

An and evaluates the "truthiness" of each operand.  If either of them is "falsey", that one is returned; otherwise the last one is returned.

All int values except 0 are "truthy", so the only time you'll get something other than the last value from an and of ints is if one of them is zero:

```<code>>>> -1 and 0 and 3
0
</code>```

Title: Using AND inside abs(number) in Python

Body:
The fact that the expression is inside an abs call doesn't change the way that it's interpreted:

>>> 21-22 and 9-4 and 11-8
3

which is of course the same as:

>>> -1 and 5 and 3
3

An and evaluates the "truthiness" of each operand.  If either of them is "falsey", that one is returned; otherwise the last one is returned.

All int values except 0 are "truthy", so the only time you'll get something other than the last value from an and of ints is if one of them is zero:

>>> -1 and 0 and 3
0


问:
React Hooks, Conditionally change state inside onClick function, updates on the next click
Hello I have a single list component which render some <Card> components that has a prop isSelected . Because alot of things happens when a <Card> Component has isSelected === true I added the state on the <List> component, and I want when someone clicks a card to check:

1) If there are no previously selected items ( state===null to add that item's id to state )

2) If someone clicks the same item or another item while there is already an item selected in state, to just unselected the active item.

```<code>import {Card} from "./Card";
import cloneDeep from 'lodash/cloneDeep';

const List = () => {
    const [selectedCard, setSelectedCard] = useState(null);

    const onCardClick = id => {
        console.debug(selectedCard, id)
        const newSelectedCard = cloneDeep(selectedCard);
        // if he clicks another item while an item is active
        // or if he clicks the same item while active
        // should just make it inactive
        if (newSelectedCard !== null || newSelectedCard === id) {
            setSelectedCard(null)
        } else {
            setSelectedCard(id)
        }
        console.debug(selectedCard, id)
    }

    return (
        <ul className="card-list">
            {cardData.map(card => (
                <Card
                    onClick={() => onCardClick(card.id)}
                    key={card.id}
                    isSelected={selectedCard === card.id}
                    {...card}
                />
            ))}
        </ul>
    )
}

export const CardList = () => (
    <List/>
);
</code>```

The issue is that the 2 console.debugs print the same values which means that the state doesnt update imediately and Im experiencing some strange behaviours here and there. Am I missing something here?

答:
Not sure why you need to use cloneDeep.</p>

```<code>const onCardClick = id => {
   if (selectedCard === id) {
       setSelectedCard(null);
   } else {
       setSelectedCard(id);
   }
}
</code>```

Body:
Hello I have a single list component which render some <Card> components that has a prop isSelected . Because alot of things happens when a <Card> Component has isSelected === true I added the state on the <List> component, and I want when someone clicks a card to check:

1) If there are no previously selected items ( state===null to add that item's id to state )

2) If someone clicks the same item or another item while there is already an item selected in state, to just unselected the active item.

import {Card} from "./Card";
import cloneDeep from 'lodash/cloneDeep';

const List = () => {
    const [selectedCard, setSelectedCard] = useState(null);

    const onCardClick = id => {
        console.debug(selectedCard, id)
        const newSelectedCard = cloneDeep(selectedCard);
        // if he clicks another item while an item is active
        // or if he clicks the same item while active
        // should just make it inactive
        if (newSelectedCard !== null || newSelectedCard === id) {
            setSelectedCard(null)
        } else {
            setSelectedCard(id)
        }
        console.debug(selectedCard, id)
    }

    return (

            {cardData.map(card => (
                <Card
                    onClick={() => onCardClick(card.id)}
                    key={card.id}
                    isSelected={selectedCard === card.id}
                    {...card}
                />
            ))}

    )
}

export const CardList = () => (
    <List/>
);

The issue is that the 2 console.debugs print the same values which means that the state doesnt update imediately and Im experiencing some strange behaviours here and there. Am I missing something here?

Body:
Not sure why you need to use cloneDeep.

const onCardClick = id => {
   if (selectedCard === id) {
       setSelectedCard(null);
   } else {
       setSelectedCard(id);
   }
}


问:
Extracting first line from a file if condition matches in a block
I have the below file and I need to capture all the hostnames in a single file separated by "," which have Failed: 0 in them

file.txt:

```<code>host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 0
</code>```

So, the output should be host1, host4. I have tried the below code:

```<code>awk -F ':' '/:/{host=$1; getline; if($1 !~ /Failed:0/) NR==1{print host}}' file.txt > output.txt
</code>```

Can anyone, advice how to go about it, please? I would prefer to do it in one line command as I need to pass it via Jenkins pipeline.

========================Update===============================

Using grep - V Name: my input file looks as below:

host1:

Summary for host1

Succeeded: 36 (changed=10)

Failed:     0

host4:

Summary for host4

Succeeded: 36 (changed=10)

Failed:     0

Now, how can I just filter for Failed:  0 cases and get the hostnames?

答:
OP's input may contain carriage returns (\r) so this awk should work with both type of line endings (DOS or Unix):

```<code>awk -v ORS="," -F: '$2 ~ /^\r?$/{host=$1} /^[ \t]*Failed:[ \t]*0/{print host}' file
</code>```

Note that there will be a trailing comma instead of ending line break here. In case it matters use:

```<code>awk -v ORS="," -F: '$2 ~ /^\r?$/{host=$1} /^[ \t]*Failed:v0/{print host}' file |
sed 's/,$/\n/'
</code>```

Body:
I have the below file and I need to capture all the hostnames in a single file separated by "," which have Failed: 0 in them

file.txt:

host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 0

So, the output should be host1, host4. I have tried the below code:

awk -F ':' '/:/{host=$1; getline; if($1 !~ /Failed:0/) NR==1{print host}}' file.txt > output.txt

Can anyone, advice how to go about it, please? I would prefer to do it in one line command as I need to pass it via Jenkins pipeline.

========================Update===============================

Using grep - V Name: my input file looks as below:

host1:

Summary for host1

Succeeded: 36 (changed=10)

Failed:     0

host4:

Summary for host4

Succeeded: 36 (changed=10)

Failed:     0

Now, how can I just filter for Failed:  0 cases and get the hostnames?

Body:
OP's input may contain carriage returns (\r) so this awk should work with both type of line endings (DOS or Unix):

awk -v ORS="," -F: '$2 ~ /^\r?$/{host=$1} /^[ \t]*Failed:[ \t]*0/{print host}' file

Note that there will be a trailing comma instead of ending line break here. In case it matters use:

awk -v ORS="," -F: '$2 ~ /^\r?$/{host=$1} /^[ \t]*Failed:v0/{print host}' file |
sed 's/,$/\n/'


问:
Transform dataframe in specific way
I have a dataframe:

```<code>ID Name Value
1  A    5%
2  B    7%
3  C    mean - 14.1, variance - 1.16
4  D    mean - 7.15, variance - 1.62
5  E    mean - 8.32, variance - 2.56
</code>```

I want to transform that dataframe, so it looks like this:

```<code>ID Name Type        Value
1  A    value        5
2  B    value        7
3  C    mean        14.1
3  C    variance    1.16
4  D    mean        7.15
4  D    variance    1.62
5  E    mean        8.32
5  E    variance    2.56
</code>```

So as you see, i added a column type with type of value of the row. When it has value with percent it has type value, and when it has value mean and variance, it must be separated into two rows with type mean and type variance. How could i do that?

Data in dput format.

```<code>df1 <-
structure(list(ID = 1:5, Name = c("A", "B", "C", "D", "E"),
Value = c("5%", "7%", "mean - 14.1, variance - 1.16",
"mean - 7.15, variance - 1.62", "mean - 8.32, variance - 2.56")),
class = "data.frame", row.names = c(NA, -5L))
</code>```

答:
We can also use</p>

```<code>library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
  separate_rows(Value, sep = ',') %>%
  separate(Value, c('Type', 'Value'), sep = '\\s+-\\s+', fill = "left") %>%
  mutate(Type = replace(Type, is.na(Type), 'value'),
         Value = as.numeric(str_remove_all(Value, "\\D+"))))
</code>```

Title: Transform dataframe in specific way

Body:
I have a dataframe:

ID Name Value
1  A    5%
2  B    7%
3  C    mean - 14.1, variance - 1.16
4  D    mean - 7.15, variance - 1.62
5  E    mean - 8.32, variance - 2.56

I want to transform that dataframe, so it looks like this:

ID Name Type        Value
1  A    value        5
2  B    value        7
3  C    mean        14.1
3  C    variance    1.16
4  D    mean        7.15
4  D    variance    1.62
5  E    mean        8.32
5  E    variance    2.56

So as you see, i added a column type with type of value of the row. When it has value with percent it has type value, and when it has value mean and variance, it must be separated into two rows with type mean and type variance. How could i do that?

Data in dput format.

df1 <-
structure(list(ID = 1:5, Name = c("A", "B", "C", "D", "E"),
Value = c("5%", "7%", "mean - 14.1, variance - 1.16",
"mean - 7.15, variance - 1.62", "mean - 8.32, variance - 2.56")),
class = "data.frame", row.names = c(NA, -5L))

Body:
We can also use

library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
  separate_rows(Value, sep = ',') %>%
  separate(Value, c('Type', 'Value'), sep = '\\s+-\\s+', fill = "left") %>%
  mutate(Type = replace(Type, is.na(Type), 'value'),
         Value = as.numeric(str_remove_all(Value, "\\D+"))))


问:
asynchronous communication between server and webbowser
The server is monitoring the events in client web browser...If any events occured in client web browser,the server should be notified about that event and server should respond to that event (like invoking another java class in the server itself)...please help me with the code</p>

答: Construct an XMLHttpRequest for a URL that invokes the corresponding method on the appropriate Java class.

OwnerDisplayName: vishwa

OwnerDisplayName: Matthew


问:
Rails, gems, require, zsh and an error message! I can't load my app because of an issue related to "require"
So, I tried to repair something that was not working related to my ZSH file, which I managed to do, but ended up breaking some other stuff apparently :/
Anyway I am trying to run my app locally (actually all my apps run into the exact same problem) and it doesn't launch. I get a long list of script in the terminal which looks like this:

```<code>    122: from /home/olivier/code/OGsoundFX/rails-mister-cocktail/bin/spring:15:in `<top (required)>'
    121: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    120: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    119: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    118: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    117: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    116: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    115: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    114: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    113: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'

</code>```

I am not an expert, far from it, and I am a bit lost. It looks like this has something to do with "require". Everything was working this morning before I fixed the other issue, and broke this.
Any idea? Thanks!

答: OK I solved it, I just needed to 'bundle update' for some reason. I had tried 'bundle install' several times, because the problem did seem related to gems, but I didn't think of updating the gems.</p>

Body:
So, I tried to repair something that was not working related to my ZSH file, which I managed to do, but ended up breaking some other stuff apparently :/
Anyway I am trying to run my app locally (actually all my apps run into the exact same problem) and it doesn't launch. I get a long list of script in the terminal which looks like this:

    122: from /home/olivier/code/OGsoundFX/rails-mister-cocktail/bin/spring:15:in `<top (required)>'
    121: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    120: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    119: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    118: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    117: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    116: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    115: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    114: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    113: from /home/olivier/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'

I am not an expert, far from it, and I am a bit lost. It looks like this has something to do with "require". Everything was working this morning before I fixed the other issue, and broke this.
Any idea? Thanks!


问:
Sharing a TEXT alonsgide with a page text on FB and LINKEDIN?
I've just stumbled upon sharing a text (a hashtag) togeher with a text on Facebook / LinkedIn. Here is hwat I am trying to do (hashtag: #STUFF):

```<code><li class="facebook"><a target="_blank" href="http://www.facebook.com/share.php?u=<?php echo '#STUFF'. urlencode(get_the_permalink()); ?>">facebook</a></li>
</code>```

THIS, unfortunately doesn't work (no wonder!)
There is "Say Something about it" field on FB. Can I add a piece of code to the sharing button so that field will contain text (pretty much like with "subject" for email sending).

I am able to do that with Twitter. Like this:

```<code> <li class="twitter"><a target="_blank" href="https://twitter.com/intent/tweet?text=<?php echo urlencode(get_the_title() . ', #STUFF'); ?>&url=<?php echo urlencode(get_the_permalink()); ?>&original_referer=<?php ?>">twitter</a></li>
</code>```

答:
Facebook

Using sharer, you can only specify url, like so...

```<code>https://www.facebook.com/sharer.php?u={url}
</code>```

Source: Facebook Sharer Documentation.

BUT, if you register your app, get an app id, and install the Facebook share dialog plugin, then you have virtually unlimited access to specify sharing...

```<code>https://www.facebook.com/dialog/share?app_id={app_id}&display={page_type}&href={url}&redirect_uri={redirect_url}
</code>```

Source: Facebook Dialog Documentation.

LinkedIn

So, you cannot really specify any text when sharing on LinkedIn.  You can only set the url param.  But you can set the og: tags to show title, image, etc., as a preview in your share page:

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Verify that you did it right with: the LinkedIn Post Inspector.

BUT, similarly to Facebook, if you register your app, get an appid, etc., you can use this format fully to your heart's content...

```<code>"com.linkedin.ugc.ShareContent": {
        "shareCommentary": {
            "text": "Hello World! This is my first Share on LinkedIn!"
        },
        "shareMediaCategory": "NONE"
    }
</code>```

Source: Microsoft LinkedIn Documentation: Share on LinkedIn.

ContentLicense: CC BY-SA 3.0

Body:
I've just stumbled upon sharing a text (a hashtag) togeher with a text on Facebook / LinkedIn. Here is hwat I am trying to do (hashtag: #STUFF):

<a target="_blank" href="http://www.facebook.com/share.php?u=<?php echo '#STUFF'. urlencode(get_the_permalink()); ?>">facebook

THIS, unfortunately doesn't work (no wonder!)
There is "Say Something about it" field on FB. Can I add a piece of code to the sharing button so that field will contain text (pretty much like with "subject" for email sending).

I am able to do that with Twitter. Like this:

<a target="_blank" href="https://twitter.com/intent/tweet?text=<?php echo urlencode(get_the_title() . ', #STUFF'); ?>&url=<?php echo urlencode(get_the_permalink()); ?>&original_referer=<?php ?>">twitter

Body:
Facebook

Using sharer, you can only specify url, like so...

https://www.facebook.com/sharer.php?u={url}

Source: Facebook Sharer Documentation.

BUT, if you register your app, get an app id, and install the Facebook share dialog plugin, then you have virtually unlimited access to specify sharing...

https://www.facebook.com/dialog/share?app_id={app_id}&display={page_type}&href={url}&redirect_uri={redirect_url}

Source: Facebook Dialog Documentation.

LinkedIn

So, you cannot really specify any text when sharing on LinkedIn.  You can only set the url param.  But you can set the og: tags to show title, image, etc., as a preview in your share page:

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Verify that you did it right with: the LinkedIn Post Inspector.

BUT, similarly to Facebook, if you register your app, get an appid, etc., you can use this format fully to your heart's content...

"com.linkedin.ugc.ShareContent": {
        "shareCommentary": {
            "text": "Hello World! This is my first Share on LinkedIn!"
        },
        "shareMediaCategory": "NONE"
    }

Source: Microsoft LinkedIn Documentation: Share on LinkedIn.


问:
Copy If statement from single cell to all cells in a column
i have been able to use the below code in order to input either "Print Documents" or "E-Delivery" into cell K2 using an If/Else statement.  I am looking to try to extend this same statement for all of Column K (i.e K3 searching O3 and returning the correct value). Any help would be much appreciated.
many thanks,
Michael</p>

```<code>Sub InsertType()

Dim score As Integer, result As String
score = Range("O2").Value

If score > 0 Then
    result = "Print Documents"
Else
    result = "E-Delivery"
End If

Range("K2").Value = result

End Sub
</code>```

答:
You can loop your VBA code :)

Code:

```<code>Sub InsertType()

Dim ws As Worksheet
Dim score As Integer, result As String
Dim i As Long
Dim lRow As Long

Set ws = ActiveWorkbook.Worksheets("Sheet1") 'Name of worksheet

lRow = ws.Cells(Rows.Count, "O").End(xlUp).Row 'Find the last row in column O

For i = 1 To lRow 'Loop from row 1 to last row
score = ws.Range(ws.Cells(i, "O"), ws.Cells(i, "O")).Value 'Take value from row i and column O

If score > 0 Then
    result = "Print Documents"
Else
    result = "E-Delivery"
End If

ws.Range(ws.Cells(i, "K"), ws.Cells(i, "K")).Value = result 'Print Result in Row i and column K
Next i

End Sub
</code>```

Result:

Body:
i have been able to use the below code in order to input either "Print Documents" or "E-Delivery" into cell K2 using an If/Else statement.  I am looking to try to extend this same statement for all of Column K (i.e K3 searching O3 and returning the correct value). Any help would be much appreciated.
many thanks,
Michael

Sub InsertType()

Dim score As Integer, result As String
score = Range("O2").Value

If score > 0 Then
    result = "Print Documents"
Else
    result = "E-Delivery"
End If

Range("K2").Value = result

End Sub

Body:
You can loop your VBA code :)

Code:

Sub InsertType()

Dim ws As Worksheet
Dim score As Integer, result As String
Dim i As Long
Dim lRow As Long

Set ws = ActiveWorkbook.Worksheets("Sheet1") 'Name of worksheet

lRow = ws.Cells(Rows.Count, "O").End(xlUp).Row 'Find the last row in column O

For i = 1 To lRow 'Loop from row 1 to last row
score = ws.Range(ws.Cells(i, "O"), ws.Cells(i, "O")).Value 'Take value from row i and column O

If score > 0 Then
    result = "Print Documents"
Else
    result = "E-Delivery"
End If

ws.Range(ws.Cells(i, "K"), ws.Cells(i, "K")).Value = result 'Print Result in Row i and column K
Next i

End Sub

Result:


问:
Application only runs if you run as administrator?
Edit: This problem only occurs on windows 7 and vista from what I've heard.

I have a very simple app developed with an external graphics library. If I install this app into a program files directory and run it, it will crash immediately but it works fine normally, with exactly the same files. I have realised it is because you need to run the application as administrator for it to work.

I appreciate if this is a problem directly related to the graphics engine I am using, but I don't really think so (but I'm clueless). Can anyone help me?

Edit for more detail:

The application executable and files that are needed to run it are installed into the default program directory - for me, C:\Program Files (x86). If you try and run with without clicking run as administrator, it will simple freeze and say "App has stopped working. Windows is checking for a solution to the problem..." My question is basically, how can I make it so run as administrator isn't necessary?

答: If you right-click on the EXE and go to Properties -> Compatibility there are some options that might help. You could try running the app in compatibility mode for a previous Windows version or if that doesn't work at least mark the EXE to run as administrator by default.


问:
How to break service call with huge list of account numbers
For example if list has 40 account numbers how to break it to two request of 20 each and add reponse back to list   </p>

```<code> public async Task<ListInformation> RetrieveInformation(List<long> AccountNumber)
    {
        ListInformationreturn Val = new ListInformation();
        var keys = new List_Type();
        AccountNumber.ForEach(x => { keys.Add(x.ToString()); });
        var response = await AccountRequestAsync(keys);

        });
    }
</code>```

答:
try something like this this:

```<code>public async Task<ListInformation> RetrieveInformation(List<long> AccountNumber)
    {
        ListInformationreturn Val = new ListInformation();

        int skip = 0; //default
        const int take = 20;
        do
        {
            var keys = new List_Type();
            AccountNumber.Skip(skip).Take(take).ForEach(x => { keys.Add(x.ToString()); });
            var response = await AccountRequestAsync(keys);

            });
            skip += keys.Count();

        }
        while (AccountNumber.Count() != skip);
    }
</code>```

Or you can make a property with number of elements that you want to take, instead of

```<code>const int take = 20;
</code>```

And important thing we have here:

```<code>skip += keys.Count();
</code>```

We always have to add to a skip property the count of handled keys, instead of take count.

And add your response to result like this:

```<code>ListInformationReturn result = new ListInformation();
result.Add(response)
</code>```

But actually i don't know you response type, so this is just an example

Body:
For example if list has 40 account numbers how to break it to two request of 20 each and add reponse back to list

 public async Task<ListInformation> RetrieveInformation(List<long> AccountNumber)
    {
        ListInformationreturn Val = new ListInformation();
        var keys = new List_Type();
        AccountNumber.ForEach(x => { keys.Add(x.ToString()); });
        var response = await AccountRequestAsync(keys);

        });
    }

Body:
try something like this this:

public async Task<ListInformation> RetrieveInformation(List<long> AccountNumber)
    {
        ListInformationreturn Val = new ListInformation();

        int skip = 0; //default
        const int take = 20;
        do
        {
            var keys = new List_Type();
            AccountNumber.Skip(skip).Take(take).ForEach(x => { keys.Add(x.ToString()); });
            var response = await AccountRequestAsync(keys);

            });
            skip += keys.Count();

        }
        while (AccountNumber.Count() != skip);
    }

Or you can make a property with number of elements that you want to take, instead of

const int take = 20;

And important thing we have here:

skip += keys.Count();

We always have to add to a skip property the count of handled keys, instead of take count.

And add your response to result like this:

ListInformationReturn result = new ListInformation();
result.Add(response)

But actually i don't know you response type, so this is just an example


问:
TypeError: can't convert np.ndarray of type numpy.str_. The only supported types are: float64, float32
I am working on a RNN algo to predict user's next location and I train it using torch but i get this error.

and i get this error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

--> 203         total_loss += run(batch_user, batch_td, batch_ld, batch_loc, batch_dst, step=1)

<ipython-input-34-3a623cd33ef9> in run(user, td, ld, loc, dst, step)

--> 159     user = Variable(torch.from_numpy(np.asarray([user],dtype='<U32'))).type(ltype)

TypeError: can't convert np.ndarray of type numpy.str_. The only supported types are: float64, float32, float16, int64, int32, int16, int8, uint8, and bool.
</code>```

my code is:

```<code>###############################################################################################
def run(user, td, ld, loc, dst, step):

    optimizer.zero_grad()

    seqlen = len(td)

    user = Variable(torch.from_numpy(np.asarray([user],dtype='<U32'))).type(ltype)

    #neg_loc = Variable(torch.FloatTensor(1).uniform_(0, len(poi2pos)-1).long()).type(ltype)
    #(neg_lati, neg_longi) = poi2pos.get(neg_loc.data.cpu().numpy()[0])
    rnn_output = h_0
    for idx in xrange(seqlen-1):
        td_upper = Variable(torch.from_numpy(np.asarray(up_time-td[idx],dtype='<U32'))).type(ftype)
        td_lower = Variable(torch.from_numpy(np.asarray(td[idx]-lw_time,dtype='<U32'))).type(ftype)
        ld_upper = Variable(torch.from_numpy(np.asarray(up_dist-ld[idx],dtype='<U32'))).type(ftype)
        ld_lower = Variable(torch.from_numpy(np.asarray(ld[idx]-lw_dist,dtype='<U32'))).type(ftype)
        location = Variable(torch.from_numpy(np.asarray(loc[idx],dtype='<U32'))).type(ltype)
        rnn_output = strnn_model(td_upper, td_lower, ld_upper, ld_lower, location, rnn_output)#, neg_lati, neg_longi, neg_loc, step)
</code>```

答:
Maybe that user is of type object .
So try to convert it as numerical using something like  user.dtype("category").cat.codes

Body:
I am working on a RNN algo to predict user's next location and I train it using torch but i get this error.

and i get this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

--> 203         total_loss += run(batch_user, batch_td, batch_ld, batch_loc, batch_dst, step=1)

<ipython-input-34-3a623cd33ef9> in run(user, td, ld, loc, dst, step)

--> 159     user = Variable(torch.from_numpy(np.asarray([user],dtype='<U32'))).type(ltype)

TypeError: can't convert np.ndarray of type numpy.str_. The only supported types are: float64, float32, float16, int64, int32, int16, int8, uint8, and bool.

my code is:

###############################################################################################
def run(user, td, ld, loc, dst, step):

    optimizer.zero_grad()

    seqlen = len(td)

    user = Variable(torch.from_numpy(np.asarray([user],dtype='<U32'))).type(ltype)

    #neg_loc = Variable(torch.FloatTensor(1).uniform_(0, len(poi2pos)-1).long()).type(ltype)
    #(neg_lati, neg_longi) = poi2pos.get(neg_loc.data.cpu().numpy()[0])
    rnn_output = h_0
    for idx in xrange(seqlen-1):
        td_upper = Variable(torch.from_numpy(np.asarray(up_time-td[idx],dtype='<U32'))).type(ftype)
        td_lower = Variable(torch.from_numpy(np.asarray(td[idx]-lw_time,dtype='<U32'))).type(ftype)
        ld_upper = Variable(torch.from_numpy(np.asarray(up_dist-ld[idx],dtype='<U32'))).type(ftype)
        ld_lower = Variable(torch.from_numpy(np.asarray(ld[idx]-lw_dist,dtype='<U32'))).type(ftype)
        location = Variable(torch.from_numpy(np.asarray(loc[idx],dtype='<U32'))).type(ltype)
        rnn_output = strnn_model(td_upper, td_lower, ld_upper, ld_lower, location, rnn_output)#, neg_lati, neg_longi, neg_loc, step)


问:
How to convert Values in a Hashmap to a List<String>
I have a Hashmap of type

```<code>Map<String, List<String>> adminErrorMap = new HashMap<>();
</code>```

I want to be able to iterate thru the entire hashmap and get all the values to a single List<String>. The Keys are irrelevant.

I have done something like this:

```<code>List<String> adminValues = new ArrayList<>();

for (Map.Entry<String, List<String>> entry : adminErrorMap.entrySet()) {
         adminValues.add(entry.getValue().toString());
    }
System.out.println(adminValues);
</code>```

Output

[[{description=File Path, value=PurchaseOrder.plsql},
  {description=Component, value=PURCH}, {description=Commit Date,
  value=Thu May 05 00:32:01 IST 2016}],[{description=File Path,
  value=CustomerOrder.plsql}, {description=Component, value=COMP},
  {description=Commit Date, value=Thu June 05 00:32:01 IST 2016}]]

As you can see, there are [] inside a main [].

How to have all values inside one []. Like shown below;

Or is there any other way to implement this?

[{description=File Path, value=PurchaseOrder.plsql},
  {description=Component, value=PURCH}, {description=Commit Date,
  value=Thu May 05 00:32:01 IST 2016},{description=File Path,
  value=CustomerOrder.plsql}, {description=Component, value=COMP},
  {description=Commit Date, value=Thu June 05 00:32:01 IST 2016}]

答:
A simple way would be:

```<code>new ArrayList<>(map.values());
</code>```

For JDK 8 and above this can also be done as:

```<code>map.values().stream().collect(Collectors.toList());
</code>```

Body:
I have a Hashmap of type

Map<String, List<String>> adminErrorMap = new HashMap<>();

I want to be able to iterate thru the entire hashmap and get all the values to a single List<String>. The Keys are irrelevant.

I have done something like this:

List<String> adminValues = new ArrayList<>();

for (Map.Entry<String, List<String>> entry : adminErrorMap.entrySet()) {
         adminValues.add(entry.getValue().toString());
    }
System.out.println(adminValues);

Output

[[{description=File Path, value=PurchaseOrder.plsql},
  {description=Component, value=PURCH}, {description=Commit Date,
  value=Thu May 05 00:32:01 IST 2016}],[{description=File Path,
  value=CustomerOrder.plsql}, {description=Component, value=COMP},
  {description=Commit Date, value=Thu June 05 00:32:01 IST 2016}]]

As you can see, there are [] inside a main [].

How to have all values inside one []. Like shown below;

Or is there any other way to implement this?

[{description=File Path, value=PurchaseOrder.plsql},
  {description=Component, value=PURCH}, {description=Commit Date,
  value=Thu May 05 00:32:01 IST 2016},{description=File Path,
  value=CustomerOrder.plsql}, {description=Component, value=COMP},
  {description=Commit Date, value=Thu June 05 00:32:01 IST 2016}]

Body:
A simple way would be:

new ArrayList<>(map.values());

For JDK 8 and above this can also be done as:

map.values().stream().collect(Collectors.toList());


问:
Generate Ansible fact once (per host)
I would like to generate a password and some other values when they do not exist yet.

Something like this:

```<code>- name: Retrieve or generate my_password
  generated_fact:
    shell: some shell command
    name: my_password
</code>```

I have a working approach but am really unhappy with it since it is very verbose and error prone:

```<code>- name: Generate my_password
  shell: some shell command
  register: generate_password_task
  when: ansible_local.convoluted.bs.my_password is not defined

- name: Store my_password as local fact
  ini_file:
    path: "/etc/ansible/facts.d/convoluted.fact"
    section: bs
    option: my_password
    value: "{{ generate_password_task.stdout }}"
  when: generate_password_task.changed

- name: Reload Ansible local facts
  setup: filter=ansible_local
  when: generate_password_task.changed
</code>```

Is there a high level abstraction for this task along the lines of the first code snippet? Or some other approach more sane than what I currently have?

答:
Here would be my approach, in two tasks.

Note that this has been checked when:

The ini file does not exists

The ini file is present but there is no bs section

The ini file is present, have a bs section, but the section does not include a my_password option

The ini file is present, have a bs section, but the option my_password is empty

The ini file is present, have a bs section and have a value for the option my_password

The cases 1 to 4 does end in a change of the ini file with a newly generated password, when the last case ends in a skipped task.

And here are the two tasks doing this:

- set_fact:
    actual_password: "{{ lookup('ini', 'my_password section=bs file=/etc/ansible/facts.d/convoluted.fact', errors='ignore') }}"

- ini_file:
    path: /etc/ansible/facts.d/convoluted.fact
    section: bs
    option: my_password
    value: "{{ lookup('password', '/dev/null chars=ascii_letters,digits,hexdigits,punctuation') }}"
  when: actual_password|length == 0
```

<p>Those are using</p>

<ul>
<li>the <code>ini</code> lookup in order to confirm that the ini and value are not yet set</li>
<li>the <code>password</code> plugin to generate a password</li>
</ul>

<p>The condition (<code>when: actual_password|length == 0</code>) to write the <code>ini</code> is based on experimentation</p>

<ul>
<li>Thanks to the <code>errors='ignore'</code> syntax in the <code>ini</code> lookup, the variable <code>actual_password</code> ends up being an empty string if the file or section does not exists, because both those cases are causing the lookup to return an error</li>
<li>If the section exists but does not contains the option then the lookup ends up returning an empty array <code>[]</code></li>
<li>If the option is there but empty, the lookup return that empty string</li>
</ul>

<p>Knowing all that is making the test relevant: <code>[]|length == 0</code> and <code>''|length == 0</code> are both true.</p>

<p>A last note on the <code>password</code> plugin, yes it does write a file on your controller host, but you are not forced to consider it, use it, or even, well, store it.<br>
The plugin return the password, so you can easily use it as you would for any other variable in the <code>value</code> attribute of your <code>ini_file</code> module.<br>
And then, if you don't want to store it on the controller host, do as you would do for anything you don't care about in linux, redirect it to <code>/dev/null</code>, either way, the password is in your <code>ini</code> file now.</p>

<p>And if you need to re-use that same password later in the playbook, just store it via an extra <code>set_fact</code></p>

<pre class="lang-yaml prettyprint-override"><code>- set_fact:
    actual_password: "{{ lookup('ini', 'my_password section=bs file=/etc/ansible/facts.d/convoluted.fact', errors='ignore') }}"

- block:
  - set_fact:
      new_password: "{{ lookup('password', '/dev/null chars=ascii_letters,digits,hexdigits,punctuation') }}"

  - ini_file:
      path: /etc/ansible/facts.d/convoluted.fact
      section: bs
      option: my_password
      value: "{{ new_password }}"
  when: actual_password|length == 0
</code>```

Given this playbook:

- hosts: local
  gather_facts: no

  tasks:
    - set_fact:
        actual_password: "{{ lookup('ini', 'my_password section=bs file=/etc/ansible/facts.d/convoluted.fact', errors='ignore') }}"

    - ini_file:
        path: /etc/ansible/facts.d/convoluted.fact
        section: bs
        option: my_password
        value: "{{ lookup('password', '/dev/null chars=ascii_letters,digits,hexdigits,punctuation') }}"
      when: actual_password|length == 0
```

<p>Here is a double run of it:</p>

```/ansible # cat /etc/ansible/facts.d/convoluted.fact
cat: can't open '/etc/ansible/facts.d/convoluted.fact': No such file or directory
/ansible # ansible-playbook play.yml

PLAY [local] ***********************************************************************************************************************************************************************************************

TASK [set_fact] ********************************************************************************************************************************************************************************************
[WARNING]: Unable to find '/etc/ansible/facts.d/convoluted.fact' in expected paths (use -vvvvv to see paths)
ok: [local]

TASK [ini_file] ********************************************************************************************************************************************************************************************
changed: [local]

PLAY RECAP *************************************************************************************************************************************************************************************************
local                      : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

/ansible # cat /etc/ansible/facts.d/convoluted.fact
[bs]
my_password = fnI;L3FpR5207,8,jxGP
/ansible # ansible-playbook play.yml

PLAY [local] ***********************************************************************************************************************************************************************************************

TASK [set_fact] ********************************************************************************************************************************************************************************************
ok: [local]

TASK [ini_file] ********************************************************************************************************************************************************************************************
skipping: [local]

PLAY RECAP *************************************************************************************************************************************************************************************************
local                      : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
```

Title: Generate Ansible fact once (per host)

Body:
I would like to generate a password and some other values when they do not exist yet.

Something like this:

- name: Retrieve or generate my_password
  generated_fact:
    shell: some shell command
    name: my_password

I have a working approach but am really unhappy with it since it is very verbose and error prone:

- name: Generate my_password
  shell: some shell command
  register: generate_password_task
  when: ansible_local.convoluted.bs.my_password is not defined

- name: Store my_password as local fact
  ini_file:
    path: "/etc/ansible/facts.d/convoluted.fact"
    section: bs
    option: my_password
    value: "{{ generate_password_task.stdout }}"
  when: generate_password_task.changed

- name: Reload Ansible local facts
  setup: filter=ansible_local
  when: generate_password_task.changed

Is there a high level abstraction for this task along the lines of the first code snippet? Or some other approach more sane than what I currently have?

Body:
Here would be my approach, in two tasks.

Note that this has been checked when:

The ini file does not exists

The ini file is present but there is no bs section

The ini file is present, have a bs section, but the section does not include a my_password option

The ini file is present, have a bs section, but the option my_password is empty

The ini file is present, have a bs section and have a value for the option my_password

The cases 1 to 4 does end in a change of the ini file with a newly generated password, when the last case ends in a skipped task.

And here are the two tasks doing this:

- set_fact:
    actual_password: "{{ lookup('ini', 'my_password section=bs file=/etc/ansible/facts.d/convoluted.fact', errors='ignore') }}"

- ini_file:
    path: /etc/ansible/facts.d/convoluted.fact
    section: bs
    option: my_password
    value: "{{ lookup('password', '/dev/null chars=ascii_letters,digits,hexdigits,punctuation') }}"
  when: actual_password|length == 0

Those are using

the ini lookup in order to confirm that the ini and value are not yet set

the password plugin to generate a password

The condition (when: actual_password|length == 0) to write the ini is based on experimentation

Thanks to the errors='ignore' syntax in the ini lookup, the variable actual_password ends up being an empty string if the file or section does not exists, because both those cases are causing the lookup to return an error

If the section exists but does not contains the option then the lookup ends up returning an empty array []

If the option is there but empty, the lookup return that empty string

Knowing all that is making the test relevant: []|length == 0 and ''|length == 0 are both true.

A last note on the password plugin, yes it does write a file on your controller host, but you are not forced to consider it, use it, or even, well, store it.

The plugin return the password, so you can easily use it as you would for any other variable in the value attribute of your ini_file module.

And then, if you don't want to store it on the controller host, do as you would do for anything you don't care about in linux, redirect it to /dev/null, either way, the password is in your ini file now.

And if you need to re-use that same password later in the playbook, just store it via an extra set_fact

- set_fact:
    actual_password: "{{ lookup('ini', 'my_password section=bs file=/etc/ansible/facts.d/convoluted.fact', errors='ignore') }}"

- block:
  - set_fact:
      new_password: "{{ lookup('password', '/dev/null chars=ascii_letters,digits,hexdigits,punctuation') }}"

  - ini_file:
      path: /etc/ansible/facts.d/convoluted.fact
      section: bs
      option: my_password
      value: "{{ new_password }}"
  when: actual_password|length == 0

Given this playbook:

- hosts: local
  gather_facts: no

  tasks:
    - set_fact:
        actual_password: "{{ lookup('ini', 'my_password section=bs file=/etc/ansible/facts.d/convoluted.fact', errors='ignore') }}"

    - ini_file:
        path: /etc/ansible/facts.d/convoluted.fact
        section: bs
        option: my_password
        value: "{{ lookup('password', '/dev/null chars=ascii_letters,digits,hexdigits,punctuation') }}"
      when: actual_password|length == 0

Here is a double run of it:

/ansible # cat /etc/ansible/facts.d/convoluted.fact
cat: can't open '/etc/ansible/facts.d/convoluted.fact': No such file or directory
/ansible # ansible-playbook play.yml

PLAY [local] ***********************************************************************************************************************************************************************************************

TASK [set_fact] ********************************************************************************************************************************************************************************************
[WARNING]: Unable to find '/etc/ansible/facts.d/convoluted.fact' in expected paths (use -vvvvv to see paths)
ok: [local]

TASK [ini_file] ********************************************************************************************************************************************************************************************
changed: [local]

PLAY RECAP *************************************************************************************************************************************************************************************************
local                      : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

/ansible # cat /etc/ansible/facts.d/convoluted.fact
[bs]
my_password = fnI;L3FpR5207,8,jxGP
/ansible # ansible-playbook play.yml

PLAY [local] ***********************************************************************************************************************************************************************************************

TASK [set_fact] ********************************************************************************************************************************************************************************************
ok: [local]

TASK [ini_file] ********************************************************************************************************************************************************************************************
skipping: [local]

PLAY RECAP *************************************************************************************************************************************************************************************************
local                      : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0


问:
yet another clearInterval in javascript not working
Belive me i ve seen many solutions i still dont know why this doesnt work.

```<code>timerId = 0;
    $("#dumpStartId").click(function(){
        var proId = $("#curProfileId").val();
        timerId = setInterval(function(){
        showact();
        showactdat();
        },1000);
    });
    $("#dumpStopId").click(function(){
        clearInterval(timerId);
        document.getElementById('curSeqId').value = "";
        if(timerId)
        {
            clearInterval(timerId);
        }
    });
</code>```

dumpstartid and dumpstopid are the ids of the two buttons. Even after clicking stop the intervals are executing continuosly. Im not sure whats wrong with this code. No errors in the console too.

Update: I can observer that sometimes after insanely pressing the button for around 5 or 6 times it comes to a complete halt. Cant this thing stop instantaneously (or is too much to ask??)

答: It was because the function the setInterval is calling was problematic which polls a rest service at a varied interval from the setIntervals interval causing it to conflict. I ve corrected it and that fixed it.</p>

Body:
Belive me i ve seen many solutions i still dont know why this doesnt work.

timerId = 0;
    $("#dumpStartId").click(function(){
        var proId = $("#curProfileId").val();
        timerId = setInterval(function(){
        showact();
        showactdat();
        },1000);
    });
    $("#dumpStopId").click(function(){
        clearInterval(timerId);
        document.getElementById('curSeqId').value = "";
        if(timerId)
        {
            clearInterval(timerId);
        }
    });

dumpstartid and dumpstopid are the ids of the two buttons. Even after clicking stop the intervals are executing continuosly. Im not sure whats wrong with this code. No errors in the console too.

Update: I can observer that sometimes after insanely pressing the button for around 5 or 6 times it comes to a complete halt. Cant this thing stop instantaneously (or is too much to ask??)


问:
Why when handling exceptions from multiprocess.Process KeyboardInterrupt exception can be catched only if you throw it yourself?
Let's say I've got a bunch of Processes, I want to run those and check if they are OK:

```<code>procs = [fetcher_process, checker_process, publisher_process, manager_process]
try:
    for p in procs:
        p.run()
except Exception as e:
    print("Oopsie")
    exit()

for p in procs:
    p.join()
</code>```

Such a code works flawlassly, unless you hit Ctrl+C. Then you get unhandled KeyboardInterrupt in p.run() even though it is definitely handled in the try/except.

```<code>Traceback (most recent call last):
  File "/home/keddad/Documents/thevyshka-news-fetcher/main.py", line 39, in <module>
    p.run()
  File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/home/keddad/Documents/thevyshka-news-fetcher/fetchuler.py", line 19, in fetch_news
    time.sleep(5)
KeyboardInterrupt
</code>```

But, if I create custom SIGINT handler which throws the same KeyboardInterrupt, like this:

```<code>def raise_keyboards_ex():
    raise KeyboardInterrupt()
signal.signal(signal.SIGINT, raise_keyboards_ex)
</code>```

Then the try/except starts working as expected. So, why one KeyboardInterrupt is being caught here while other don't?

答:
So, as @jasonharper said, the reason why it wasn't catched was not some kind of magic - it is just because KeyboardInterrupt is not a subclass of Exception. The only reason it catched it now was that instead of rising KeyboardInterrupt I actually caused another exception:

```<code>try:
    for p in procs:
        p.run()
except Exception as e:
    print("Oopsie")
    print(e) # prints "raise_keyboards_ex() takes 0 positional arguments but 2 were given"
    exit()
</code>```

Body:
Let's say I've got a bunch of Processes, I want to run those and check if they are OK:

procs = [fetcher_process, checker_process, publisher_process, manager_process]
try:
    for p in procs:
        p.run()
except Exception as e:
    print("Oopsie")
    exit()

for p in procs:
    p.join()

Such a code works flawlassly, unless you hit Ctrl+C. Then you get unhandled KeyboardInterrupt in p.run() even though it is definitely handled in the try/except.

Traceback (most recent call last):
  File "/home/keddad/Documents/thevyshka-news-fetcher/main.py", line 39, in <module>
    p.run()
  File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/home/keddad/Documents/thevyshka-news-fetcher/fetchuler.py", line 19, in fetch_news
    time.sleep(5)
KeyboardInterrupt

But, if I create custom SIGINT handler which throws the same KeyboardInterrupt, like this:

def raise_keyboards_ex():
    raise KeyboardInterrupt()
signal.signal(signal.SIGINT, raise_keyboards_ex)

Then the try/except starts working as expected. So, why one KeyboardInterrupt is being caught here while other don't?

Body:
So, as @jasonharper said, the reason why it wasn't catched was not some kind of magic - it is just because KeyboardInterrupt is not a subclass of Exception. The only reason it catched it now was that instead of rising KeyboardInterrupt I actually caused another exception:

try:
    for p in procs:
        p.run()
except Exception as e:
    print("Oopsie")
    print(e) # prints "raise_keyboards_ex() takes 0 positional arguments but 2 were given"
    exit()


问:
Generic Repository with Paging For GetAll Method to include Item Count
I am using a generic repository something like Repo which has a method

```<code> public IEmerable<TEntity> GetAll(
 Expression<Func<TEntity, bool>> filter = null,
 Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
 IList<Expression<Func<TEntity, object>>> includes = null,
 int? page = null,
 int? pageSize = null)
 {
        var query = context.Set<TEntity>().AsQueryable();

        if (includes != null)
        {
            query = includes.Aggregate(query, (current, include) => current.Include(include));
        }
        if (orderBy != null)
        {
            query = orderBy(query);
        }
        if (filter != null)
        {
            query = query.AsExpandable().Where(filter);
        }
        if (page != null && pageSize != null)
        {
            query = query.Skip((page.Value - 1)*pageSize.Value).Take(pageSize.Value);
        }
        return query.ToList();
 }
</code>```

The problem lies here I am trying to DDD so 'TEntity' is actually entity class for EF. I need to return the total records count of the total database record as well. How shall I do it following best practises for an API?

答:
If it  is possible you can change you generic repository interface to use value tuples:

```<code>public (int count, IEnumerable<TEntity> records) GetAll(...){}
</code>```

Or introduce generic DTO:

```<code>public class CountedResult<TEntity>
{
    public int Count { get; set;}
    public IEnumerable<TEntity> Records { get; set;}
}
</code>```

And return it:

```<code>public CountedResult<TEntity> GetAll(...){}
</code>```

P.S.

Would not it make sense to order stuff after filtering?

Body:
I am using a generic repository something like Repo which has a method

 public IEmerable<TEntity> GetAll(
 Expression<Func<TEntity, bool>> filter = null,
 Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
 IList<Expression<Func<TEntity, object>>> includes = null,
 int? page = null,
 int? pageSize = null)
 {
        var query = context.Set<TEntity>().AsQueryable();

        if (includes != null)
        {
            query = includes.Aggregate(query, (current, include) => current.Include(include));
        }
        if (orderBy != null)
        {
            query = orderBy(query);
        }
        if (filter != null)
        {
            query = query.AsExpandable().Where(filter);
        }
        if (page != null && pageSize != null)
        {
            query = query.Skip((page.Value - 1)*pageSize.Value).Take(pageSize.Value);
        }
        return query.ToList();
 }

The problem lies here I am trying to DDD so 'TEntity' is actually entity class for EF. I need to return the total records count of the total database record as well. How shall I do it following best practises for an API?

Body:
If it  is possible you can change you generic repository interface to use value tuples:

public (int count, IEnumerable<TEntity> records) GetAll(...){}

Or introduce generic DTO:

public class CountedResult<TEntity>
{
    public int Count { get; set;}
    public IEnumerable<TEntity> Records { get; set;}
}

And return it:

public CountedResult<TEntity> GetAll(...){}

P.S.

Would not it make sense to order stuff after filtering?


问:
Update all slide master's and layout's footers
Trying to create a macro to quickly enter in project names to ppt footers. I can only get the top level slide master to accept the input title. I've tried looping through the other slide master layouts with the new footer info but I keep getting errors at the line to write text to the footer in the For loop</p>

```<code>
    Sub footchange()

    Dim myValue As Variant
    Dim sld As Slide

    myValue = InputBox("Enter Presentation Name")

    Set mySlidesHF = ActivePresentation.SlideMaster.HeadersFooters

    'Add name to slide master footer
    With mySlidesHF
        .Footer.Visible = True
        .Footer.Text = myValue + "    |   Confidential © 2020"
        .SlideNumber.Visible = True
    End With

    'Add name to slide master layouts footers
    For Each sld In ActivePresentation.Slides
       With sld.HeadersFooters
            .Footer.Visible = True
            .Footer.Text = myValue + "    |   Confidential © 2020"
            .SlideNumber.Visible = True
        End With
    Next

</code>```

答:
I was able to update all the master slides/layouts by adding a 2nd nested loop for the layouts in each master slide:</p>

```<code>Sub footchange()

Dim myValue As Variant
Dim sld As Slide

'Add design and layout variables
Dim oMaster As Design
Dim cLay As CustomLayout

myValue = InputBox("Enter Presentation Name")

'Just to show you how many Masters you have
Debug.Print ActivePresentation.Designs.Count

'Loop through them
For Each oMaster In ActivePresentation.Designs

'Use actual Design
Set mySlidesHF = oMaster.SlideMaster
Set myLayoutsHF = oMaster.SlideMaster.CustomLayouts

'Add name to slide master footer
With mySlidesHF.HeadersFooters
    .Footer.Visible = True
    .Footer.Text = myValue + "    |   Confidential © 2020"
    .SlideNumber.Visible = True
End With

'Add name to layouts
For Each cLay In myLayoutsHF
    With cLay.HeadersFooters
        .Footer.Visible = True
        .Footer.Text = myValue + "    |   Confidential © 2020"
        .SlideNumber.Visible = True
    End With
Next cLay

Next oMaster

End Sub
</code>```

Body:
Trying to create a macro to quickly enter in project names to ppt footers. I can only get the top level slide master to accept the input title. I've tried looping through the other slide master layouts with the new footer info but I keep getting errors at the line to write text to the footer in the For loop

    Sub footchange()

    Dim myValue As Variant
    Dim sld As Slide

    myValue = InputBox("Enter Presentation Name")

    Set mySlidesHF = ActivePresentation.SlideMaster.HeadersFooters

    'Add name to slide master footer
    With mySlidesHF
        .Footer.Visible = True
        .Footer.Text = myValue + "    |   Confidential © 2020"
        .SlideNumber.Visible = True
    End With

    'Add name to slide master layouts footers
    For Each sld In ActivePresentation.Slides
       With sld.HeadersFooters
            .Footer.Visible = True
            .Footer.Text = myValue + "    |   Confidential © 2020"
            .SlideNumber.Visible = True
        End With
    Next

Body:
I was able to update all the master slides/layouts by adding a 2nd nested loop for the layouts in each master slide:

Sub footchange()

Dim myValue As Variant
Dim sld As Slide

'Add design and layout variables
Dim oMaster As Design
Dim cLay As CustomLayout

myValue = InputBox("Enter Presentation Name")

'Just to show you how many Masters you have
Debug.Print ActivePresentation.Designs.Count

'Loop through them
For Each oMaster In ActivePresentation.Designs

'Use actual Design
Set mySlidesHF = oMaster.SlideMaster
Set myLayoutsHF = oMaster.SlideMaster.CustomLayouts

'Add name to slide master footer
With mySlidesHF.HeadersFooters
    .Footer.Visible = True
    .Footer.Text = myValue + "    |   Confidential © 2020"
    .SlideNumber.Visible = True
End With

'Add name to layouts
For Each cLay In myLayoutsHF
    With cLay.HeadersFooters
        .Footer.Visible = True
        .Footer.Text = myValue + "    |   Confidential © 2020"
        .SlideNumber.Visible = True
    End With
Next cLay

Next oMaster

End Sub


问:
More pythonic way to test for is none
Which way to test for a variable == None is the more pythonic?

if var:

or

if var is not None

?

I personally would favor the primer. But the latter is more explicit.
https://www.python.org/dev/peps/pep-0020/

But for what benefit? Beginner programmers - should this be assumed in production grade software?

答:
If None-ness is important, and it's possible you'd receive a falsy value that should not be treated equivalently, you have to use is not None. But if you're just testing None vs. "some other value guaranteed to be truthy", then it's really personal preference.

For example, when testing the result of a regex .match call, if matchobj: and if matchobj is not None: are both fine; match returns either None for a failed match or a guaranteed truthy match object, so it's mostly a matter of personal style. if matchobj: is microscopically faster, but not enough to weight the decision meaningfully.

Title: More pythonic way to test for is none


问:
How to set new properties, or push to array with async and await, within callback function?
When I use async/await with rawCollection and get data inside a loop, and then set new properties (poTmp), it works as expected. But after I set new properties and console.log outside it doesn't set new props. Why?    </p>

```<code>let items = await Items.rawCollection()
    .aggregate([
      {
        $match: match,
      },
    ])
    .toArray()

  let data = items
  data.forEach(async item => {
    let po = await PurchaseOrderDetails.rawCollection()
      .aggregate([
        {
          $match: {
            itemId: item._id,
            tranDate: { $lte: tDate },
          },
        },
        {
          $group: {
            _id: '$itemId',
            itemDoc: { $last: item },
            onHandPO: { $sum: '$qtyBase' },
          },
        },
        {
          $group: {
            _id: '$itemId',
            itemDoc: { $last: '$itemDoc' },
            lastOnHandPO: { $last: '$onHandPO' },
          },
        },
      ])
      .toArray()
    //==================
    //set new properties
    //==================
    item.poTmp = po[0]

  })
  console.log(data)
  return data
</code>```

答:
Here is a working example anyone who needs it:</p>

```<code>  public async updateBatch(req:any,res:any){

        body = [1,3,4,5,6]

        var rfinal:number[] = [];

        await Promise.all(body.map(async items=>{

            let newStatus = 'MJ';

                inputParameters = [
                { name: 'PID', dataType: sql.Int, value: items },
                { name: 'Status', dataType: sql.VarChar, value: newStatus }
            ];

            let CustomQuery = `UPDATE MYTable
                SET Status= @Status
                WHERE PID= @PID`;

            const result = await provider.executeQuery(CustomQuery, inputParameters).catch(err => {
                    LogErrors.logErrors(err);
            });
            if(result.rowsAffected[0]>0){
                    rfinal.push(result.rowsAffected[0]);
            }else{
                throw new console.error('Un expected error, updating newsfeed');
            }

        })
        );

  }
</code>```

Body:
When I use async/await with rawCollection and get data inside a loop, and then set new properties (poTmp), it works as expected. But after I set new properties and console.log outside it doesn't set new props. Why?

let items = await Items.rawCollection()
    .aggregate([
      {
        $match: match,
      },
    ])
    .toArray()

  let data = items
  data.forEach(async item => {
    let po = await PurchaseOrderDetails.rawCollection()
      .aggregate([
        {
          $match: {
            itemId: item._id,
            tranDate: { $lte: tDate },
          },
        },
        {
          $group: {
            _id: '$itemId',
            itemDoc: { $last: item },
            onHandPO: { $sum: '$qtyBase' },
          },
        },
        {
          $group: {
            _id: '$itemId',
            itemDoc: { $last: '$itemDoc' },
            lastOnHandPO: { $last: '$onHandPO' },
          },
        },
      ])
      .toArray()
    //==================
    //set new properties
    //==================
    item.poTmp = po[0]

  })
  console.log(data)
  return data

Body:
Here is a working example anyone who needs it:

  public async updateBatch(req:any,res:any){

        body = [1,3,4,5,6]

        var rfinal:number[] = [];

        await Promise.all(body.map(async items=>{

            let newStatus = 'MJ';

                inputParameters = [
                { name: 'PID', dataType: sql.Int, value: items },
                { name: 'Status', dataType: sql.VarChar, value: newStatus }
            ];

            let CustomQuery = `UPDATE MYTable
                SET Status= @Status
                WHERE PID= @PID`;

            const result = await provider.executeQuery(CustomQuery, inputParameters).catch(err => {
                    LogErrors.logErrors(err);
            });
            if(result.rowsAffected[0]>0){
                    rfinal.push(result.rowsAffected[0]);
            }else{
                throw new console.error('Un expected error, updating newsfeed');
            }

        })
        );

  }


问:
Logical OR ( || ) working different in 2 versions of MariaDB
When used in where clause

select * from tableA where col like 'value' || col = val ;

select * from tableA where col like 'value' or col = val ;

I experience two different behaviors:

Both 1 & 2 work the same in version ( 10.2.14 )

Only 2 works as expected in version ( 10.3.22 )

I tried to look at release log for 10.3.22 but nothing was mentioned regarding the change to logical OR. Has anyone faced the issue if so just want to confirm there are changes between different versions of Maria DB ?

or its somethign else i shuld be looking at ?

答: Check that if you have the PIPES_AS_CONCAT SQL_MODE set in the 10.3.22. If not, show the data that is giving you trouble.


问:
curl: (60) SSL certificate problem: unable to get local issuer certificate
```<code>root@sclrdev:/home/sclr/certs/FreshCerts# curl --ftp-ssl --verbose ftp://{abc}/ -u trup:trup --cacert /etc/ssl/certs/ca-certificates.crt
* About to connect() to {abc} port 21 (#0)
*   Trying {abc}...
* Connected to {abc} ({abc}) port 21 (#0)
< 220-Cerberus FTP Server - Home Edition
< 220-This is the UNLICENSED Home Edition and may be used for home, personal use only
< 220-Welcome to Cerberus FTP Server
< 220 Created by Cerberus, LLC
> AUTH SSL
< 234 Authentication method accepted
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS alert, Server hello (2):
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
</code>```

答:
I had this problem with Digicert of all CAs.  I created a digicertca.pem file that was just both intermediate and root pasted together into one file.

```<code>curl https://cacerts.digicert.com/DigiCertGlobalRootCA.crt.pem
curl https://cacerts.digicert.com/DigiCertSHA2SecureServerCA.crt.pem

curl -v https://mydigisite.com/sign_on --cacert DigiCertCA.pem
...
*  subjectAltName: host "mydigisite.com" matched cert's "mydigisite.com"
*  issuer: C=US; O=DigiCert Inc; CN=DigiCert SHA2 Secure Server CA
*  SSL certificate verify ok.
> GET /users/sign_in HTTP/1.1
> Host: mydigisite.com
> User-Agent: curl/7.65.1
> Accept: */*
...
</code>```

Eorekan had the answer but only got myself and one other to up vote his answer.

Body:
I had this problem with Digicert of all CAs.  I created a digicertca.pem file that was just both intermediate and root pasted together into one file.

curl https://cacerts.digicert.com/DigiCertGlobalRootCA.crt.pem
curl https://cacerts.digicert.com/DigiCertSHA2SecureServerCA.crt.pem

curl -v https://mydigisite.com/sign_on --cacert DigiCertCA.pem
...
*  subjectAltName: host "mydigisite.com" matched cert's "mydigisite.com"
*  issuer: C=US; O=DigiCert Inc; CN=DigiCert SHA2 Secure Server CA
*  SSL certificate verify ok.
> GET /users/sign_in HTTP/1.1
> Host: mydigisite.com
> User-Agent: curl/7.65.1
> Accept: */*
...

Eorekan had the answer but only got myself and one other to up vote his answer.


问:
How to extract value from selected TextBlock element in a ListBox?
I'm using a ListBox to display all values contained in Dictionary<> object:

```<code><ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
                    <TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>
</code>```

Content is filled by the following code:

```<code>Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;
</code>```

Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.

I tried doing something like that, but obviosly it doesn't work:

```<code>private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
</code>```

I would really appreciate your help!

答:
```<code>private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    this.Test_SomeOtherTextBlock.Text = lb.ToString();
}```
will go something like this..
```<code>
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    DataTemplate template=lb.ContentTemplate;
    //Now here you have to extract the content of the data template
      and then you need to extract the TextBlock from that content.</p>

<p>}
```
This is just an overview of the functionality.Sorry not able to post complete code.

Body:
I'm using a ListBox to display all values contained in Dictionary<> object:

<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
                    <TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

Content is filled by the following code:

Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;

Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.

I tried doing something like that, but obviosly it doesn't work:

private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    this.Test_SomeOtherTextBlock.Text = lb.ToString();
}

I would really appreciate your help!

Body:
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    this.Test_SomeOtherTextBlock.Text = lb.ToString();
}

will go something like this..

private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    DataTemplate template=lb.ContentTemplate;
    //Now here you have to extract the content of the data template
      and then you need to extract the TextBlock from that content.

}

This is just an overview of the functionality.Sorry not able to post complete code.


问:
Get neighboring values from an element in 2D array
I'm trying to extract the neighbors of an element in a 2D array. This seems like a simple function but I was unable to find one in numpy. My current solution is this but I wonder if there is a better way?

```<code>import numpy as np
import itertools
import operator

def get_neighbors(a, coord):
  # exclude element itself
  indices = [p for p in itertools.product([-1,0,1],[-1,0,1]) if p != (0,0)]

  x = []
  y = []
  for i in indices:
    c = tuple(map(operator.add, coord, i))
    if c[0] >= 0 and c[0] < a.shape[0] and c[1] >= 0 and c[1] < a.shape[1]:
      x.append(c[0])
      y.append(c[1])

  # fancy indexing
  return a[x,y]

a = np.arange(9).reshape(3,3)
print(get_neighbors(a, (2,2)))
</code>```

After some time I got a good solution with:

```<code>import numpy as np
import scipy.ndimage as ndimage

def test_func(values):
  print(values, type(values))
  return 1

x = np.array([[1,2,3],[4,5,6],[7,8,9]])

footprint = np.array([[1,1,1],
                      [1,0,1],
                      [1,1,1]])

results = ndimage.generic_filter(x, test_func, footprint=footprint,
  mode='constant', cval=np.nan)
print(x)
print(results)
</code>```

答:
Perhaps you could use a mask.

```<code>def get_neighbors(a, r, c):
    mask = np.zeros(a.shape,dtype=bool)
    mask[r-1 if r!=0 else r:r+2,c-1 if c!=0 else c:c+2] = True
    mask[r,c] = False
    return a[mask]
</code>```

A more efficient answer without any masks can be done if you define a simple constant. There are at most 9 pixels, whenever we slice the center pixel and the neighbors, and it's trivial to determine which one is the center pixel among the sliced indices.

```<code>POSITION_CONST = np.array([[0,1,1],[2,3,4]])

def get_neighbors(a, r, c):
    C = POSITION_CONST[int(r!=0), (c!=0)*(1+int(c!=(a.shape[1]-1)))]
    N = a[max(r-1,0):r+2,max(c-1,0):c+2].ravel()
    return N[np.where(np.arange(len(N))!=C)[0]]
</code>```

Body:
I'm trying to extract the neighbors of an element in a 2D array. This seems like a simple function but I was unable to find one in numpy. My current solution is this but I wonder if there is a better way?

import numpy as np
import itertools
import operator

def get_neighbors(a, coord):
  # exclude element itself
  indices = [p for p in itertools.product([-1,0,1],[-1,0,1]) if p != (0,0)]

  x = []
  y = []
  for i in indices:
    c = tuple(map(operator.add, coord, i))
    if c[0] >= 0 and c[0] = 0 and c[1] < a.shape[1]:
      x.append(c[0])
      y.append(c[1])

  # fancy indexing
  return a[x,y]

a = np.arange(9).reshape(3,3)
print(get_neighbors(a, (2,2)))

After some time I got a good solution with:

import numpy as np
import scipy.ndimage as ndimage

def test_func(values):
  print(values, type(values))
  return 1

x = np.array([[1,2,3],[4,5,6],[7,8,9]])

footprint = np.array([[1,1,1],
                      [1,0,1],
                      [1,1,1]])

results = ndimage.generic_filter(x, test_func, footprint=footprint,
  mode='constant', cval=np.nan)
print(x)
print(results)

Body:
Perhaps you could use a mask.

def get_neighbors(a, r, c):
    mask = np.zeros(a.shape,dtype=bool)
    mask[r-1 if r!=0 else r:r+2,c-1 if c!=0 else c:c+2] = True
    mask[r,c] = False
    return a[mask]

A more efficient answer without any masks can be done if you define a simple constant. There are at most 9 pixels, whenever we slice the center pixel and the neighbors, and it's trivial to determine which one is the center pixel among the sliced indices.

POSITION_CONST = np.array([[0,1,1],[2,3,4]])

def get_neighbors(a, r, c):
    C = POSITION_CONST[int(r!=0), (c!=0)*(1+int(c!=(a.shape[1]-1)))]
    N = a[max(r-1,0):r+2,max(c-1,0):c+2].ravel()
    return N[np.where(np.arange(len(N))!=C)[0]]


问:
File not found when trying to use etag
I am trying to use etag when i update my bucket S3, but i get this error:

```<code>Error: Error in function call
   on config.tf line 48, in resource "aws_s3_bucket_object" "bucket_app":
   48:   etag = filemd5("${path.module}/${var.env}/app-config.json")
     |----------------
     | path.module is "."
     | var.env is "develop"
 Call to function "filemd5" failed: no file exists at develop/app-config.json.
</code>```

However, this works fine:

```<code>resource "aws_s3_bucket_object" "bucket_app" {
  bucket = "${var.app}-${var.env}-app-assets"
  key    = "config.json"
  source = "${path.module}/${var.env}/app-config.json"

  // etag = filemd5("${path.module}/${var.env}/app-config.json")

  depends_on = [
    local_file.app_config_json
  ]
}
</code>```

I am genereting the file this way:

```<code>resource "local_file" "app_config_json" {
  content  = local.app_config_json
  filename = "${path.module}/${var.env}/app-config.json"
}
</code>```

I really don't get what i am doing wrong...

答:
All functions in Terraform run during the initial configuration processing, not during the graph walk. For all of the functions that read files on disk, that means that the files must be present on disk prior to running Terraform as part of the configuration itself -- usually, checked in to version control -- rather than being generated dynamically during the Terraform operation.

The documentation for [file], which filemd5 builds on, has the following to say about it:

This function can be used only with files that already exist on disk at the beginning of a Terraform run. Functions do not participate in the dependency graph, so this function cannot be used with files that are generated dynamically during a Terraform operation. We do not recommend using dynamic local files in Terraform configurations, but in rare situations where this is necessary you can use the local_file data source to read files while respecting resource dependencies.

As the documentation there suggests, the local_file data source provides a way to read a file into memory as a resource during the graph walk, although its result would still need to be passed to md5 to get the result you needed here.

Because you're creating the file with a local_file resource anyway, you can skip the need for the additional data resource and derive the MD5 hash directly from your local_file.app_config_json resource:

```<code>resource "aws_s3_bucket_object" "bucket_app" {
  bucket = "${var.app}-${var.env}-app-assets"
  key    = "config.json"
  source = local_file.app_config_json.filename
  etag   = md5(local_file.app_config_json.content)
}
</code>```

Note that we don't need to use depends_on if we derive the configuration from attributes of the local_file.app_config_json resource, because Terraform can therefore already see that the dependency relationship exists.

Title: File not found when trying to use etag

Body:
I am trying to use etag when i update my bucket S3, but i get this error:

Error: Error in function call
   on config.tf line 48, in resource "aws_s3_bucket_object" "bucket_app":
   48:   etag = filemd5("${path.module}/${var.env}/app-config.json")
     |----------------
     | path.module is "."
     | var.env is "develop"
 Call to function "filemd5" failed: no file exists at develop/app-config.json.

However, this works fine:

resource "aws_s3_bucket_object" "bucket_app" {
  bucket = "${var.app}-${var.env}-app-assets"
  key    = "config.json"
  source = "${path.module}/${var.env}/app-config.json"

  // etag = filemd5("${path.module}/${var.env}/app-config.json")

  depends_on = [
    local_file.app_config_json
  ]
}

I am genereting the file this way:

resource "local_file" "app_config_json" {
  content  = local.app_config_json
  filename = "${path.module}/${var.env}/app-config.json"
}

I really don't get what i am doing wrong...

Body:
All functions in Terraform run during the initial configuration processing, not during the graph walk. For all of the functions that read files on disk, that means that the files must be present on disk prior to running Terraform as part of the configuration itself -- usually, checked in to version control -- rather than being generated dynamically during the Terraform operation.

The documentation for [file], which filemd5 builds on, has the following to say about it:

This function can be used only with files that already exist on disk at the beginning of a Terraform run. Functions do not participate in the dependency graph, so this function cannot be used with files that are generated dynamically during a Terraform operation. We do not recommend using dynamic local files in Terraform configurations, but in rare situations where this is necessary you can use the local_file data source to read files while respecting resource dependencies.

As the documentation there suggests, the local_file data source provides a way to read a file into memory as a resource during the graph walk, although its result would still need to be passed to md5 to get the result you needed here.

Because you're creating the file with a local_file resource anyway, you can skip the need for the additional data resource and derive the MD5 hash directly from your local_file.app_config_json resource:

resource "aws_s3_bucket_object" "bucket_app" {
  bucket = "${var.app}-${var.env}-app-assets"
  key    = "config.json"
  source = local_file.app_config_json.filename
  etag   = md5(local_file.app_config_json.content)
}

Note that we don't need to use depends_on if we derive the configuration from attributes of the local_file.app_config_json resource, because Terraform can therefore already see that the dependency relationship exists.


问:
Item in RecyclerView not filling it's width match_parent
I have a problem with my RecyclerView and its child items. They do not extend through the whole android:layout_width="match_parent" nor fill_parent. I've tried both. The thing is, this work perfectly and with no changes, it got ruined somehow.

I am showing this in a FragmentDialog and the child items only expand like wrap_content when I scroll the view up and down, they are fully expanded but as soon as I click on them (I call notifyDataSetChanged()) they shrink again.

Here is a picture of a properly filled item and below it's how they are when they load or when I notifyData. Also the StickHeaderAdapter that I use, does not show headers until I click on one of the items (this work previously and I changed nothing on that part either).

Here is the code for the child row:

```<code><?xml version="1.0" encoding="utf-8"?>
<carbon.widget.LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    app:carbon_rippleColor="@color/green"
    app:carbon_rippleStyle="background">

<carbon.widget.TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/block_name"
    android:padding="@dimen/block_row_padding"
    android:layout_weight="1"
    android:textSize="@dimen/block_row_text_size"
    android:textColor="@color/black"
    app:carbon_rippleColor="@color/green"
    app:carbon_rippleStyle="background"/>

<RelativeLayout
    android:id="@+id/download_layout"
    android:layout_width="64dp"
    android:layout_height="match_parent"
    android:layout_marginRight="24dp"
    android:layout_marginEnd="24dp"
    android:visibility="gone">

    <carbon.widget.ProgressBar
        android:id="@+id/downloading_bar"
        app:carbon_progressStyle="circular_indeterminate"
        app:carbon_barWidth="5dp"
        app:carbon_tint="@color/green"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:layout_margin="8dp"
        android:visibility="invisible"/>

    <carbon.widget.TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/block_progress_download"
        android:textSize="12sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:visibility="invisible" />

</RelativeLayout>
</code>```

And here is the part of the adapter code where I create ViewHolder:

```<code>@Override
public BlockAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.block_row, parent, false);
    return new ViewHolder(view);
}
</code>```

This is the binding code if it helps:

```<code>@Override
public void onBindViewHolder(BlockAdapter.ViewHolder holder, int position) {
    if (blockData.isDownloading()) {
        holder.download_layout.setVisibility(View.VISIBLE);
        holder.download_bar.setVisibility(View.VISIBLE);
        if (blockData.getProgress() != null) {
            holder.download_progress.setVisibility(View.VISIBLE);
            holder.download_progress.setText(String.format("%d%%", blockData.getProgress()));
        }
    } else {
        holder.download_layout.setVisibility(View.GONE);
        holder.download_bar.setVisibility(View.GONE);
        holder.download_progress.setVisibility(View.GONE);
    }

    if (selected) {
        holder.itemView.setBackgroundColor(mContext.getResources().getColor(R.color.green));
        holder.block_name.setTextColor(mContext.getResources().getColor(R.color.white));
    } else {
        holder.itemView.setBackgroundColor(mContext.getResources().getColor(R.color.white));
        holder.block_name.setTextColor(mContext.getResources().getColor(R.color.black));
    }

}
</code>```

I don't know why this work in the morning and changed later...

Things I tried:

Change match_parent for fill_parent

Set RecyclerView.LayoutParams to LayoutParams.MATCH_PARENT

Change width programatically

Change createViewHolder from ..., parent, false); to ..., null); and add Params seperatelly

Logged the width (sometimes it's like 390, when I scroll it gets to 990 and when I click back to 390)

Setup StickHeaders sooner, but they are all set when they get created and header is there, it's just invisible.

ANY HELP IS APPRECIATED!

答:
I had the same problem. It happens only to some view, and it is reproducible.

Overriding setAutoMeasureEnabled to return false didn't work, for whatever reason.

I use androidx.recyclerview:recyclerview:1.1.0

I worked around this issue by resetting the view's width to match the parent's width, i.e.,

```<code>this.itemView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
this.itemView.requestLayout();
</code>```

at the end of binding the ViewHolder. this.itemView is the ViewHolder's root view in this case, i.e. androidx.recyclerview.widget.RecyclerView.ViewHolder.itemView.

Body:
I have a problem with my RecyclerView and its child items. They do not extend through the whole android:layout_width="match_parent" nor fill_parent. I've tried both. The thing is, this work perfectly and with no changes, it got ruined somehow.

I am showing this in a FragmentDialog and the child items only expand like wrap_content when I scroll the view up and down, they are fully expanded but as soon as I click on them (I call notifyDataSetChanged()) they shrink again.

Here is a picture of a properly filled item and below it's how they are when they load or when I notifyData. Also the StickHeaderAdapter that I use, does not show headers until I click on one of the items (this work previously and I changed nothing on that part either).

Here is the code for the child row:

<?xml version="1.0" encoding="utf-8"?>
<carbon.widget.LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    app:carbon_rippleColor="@color/green"
    app:carbon_rippleStyle="background">

<carbon.widget.TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/block_name"
    android:padding="@dimen/block_row_padding"
    android:layout_weight="1"
    android:textSize="@dimen/block_row_text_size"
    android:textColor="@color/black"
    app:carbon_rippleColor="@color/green"
    app:carbon_rippleStyle="background"/>

<RelativeLayout
    android:id="@+id/download_layout"
    android:layout_width="64dp"
    android:layout_height="match_parent"
    android:layout_marginRight="24dp"
    android:layout_marginEnd="24dp"
    android:visibility="gone">

    <carbon.widget.ProgressBar
        android:id="@+id/downloading_bar"
        app:carbon_progressStyle="circular_indeterminate"
        app:carbon_barWidth="5dp"
        app:carbon_tint="@color/green"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:layout_margin="8dp"
        android:visibility="invisible"/>

    <carbon.widget.TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/block_progress_download"
        android:textSize="12sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:visibility="invisible" />

</RelativeLayout>

And here is the part of the adapter code where I create ViewHolder:

@Override
public BlockAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.block_row, parent, false);
    return new ViewHolder(view);
}

This is the binding code if it helps:

@Override
public void onBindViewHolder(BlockAdapter.ViewHolder holder, int position) {
    if (blockData.isDownloading()) {
        holder.download_layout.setVisibility(View.VISIBLE);
        holder.download_bar.setVisibility(View.VISIBLE);
        if (blockData.getProgress() != null) {
            holder.download_progress.setVisibility(View.VISIBLE);
            holder.download_progress.setText(String.format("%d%%", blockData.getProgress()));
        }
    } else {
        holder.download_layout.setVisibility(View.GONE);
        holder.download_bar.setVisibility(View.GONE);
        holder.download_progress.setVisibility(View.GONE);
    }

    if (selected) {
        holder.itemView.setBackgroundColor(mContext.getResources().getColor(R.color.green));
        holder.block_name.setTextColor(mContext.getResources().getColor(R.color.white));
    } else {
        holder.itemView.setBackgroundColor(mContext.getResources().getColor(R.color.white));
        holder.block_name.setTextColor(mContext.getResources().getColor(R.color.black));
    }

}

I don't know why this work in the morning and changed later...

Things I tried:

Change match_parent for fill_parent

Set RecyclerView.LayoutParams to LayoutParams.MATCH_PARENT

Change width programatically

Change createViewHolder from ..., parent, false); to ..., null); and add Params seperatelly

Logged the width (sometimes it's like 390, when I scroll it gets to 990 and when I click back to 390)

Setup StickHeaders sooner, but they are all set when they get created and header is there, it's just invisible.

ANY HELP IS APPRECIATED!

Body:
I had the same problem. It happens only to some view, and it is reproducible.

Overriding setAutoMeasureEnabled to return false didn't work, for whatever reason.

I use androidx.recyclerview:recyclerview:1.1.0

I worked around this issue by resetting the view's width to match the parent's width, i.e.,

this.itemView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
this.itemView.requestLayout();

at the end of binding the ViewHolder. this.itemView is the ViewHolder's root view in this case, i.e. androidx.recyclerview.widget.RecyclerView.ViewHolder.itemView.