问:
Multiple authentication providers for oauth2
I am using spring security to do OAuth2 authentication with request taking username and password as using in a normal flow. However, I want to add another method for authentication same OAuth but with different parameters in the request. (for example, id and clientToken - there is an authentication that is done before it reaches my service). At the end when both types of requests come to my auth service it must return an oauth token, which is further enhanced. Is it possible to have 2 different auth providers on oauth end point url?</p>

答:
Actually, there is the following line of code in spring oauth2 TokenEndpoint:

OAuth2AccessToken token = this.getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);

So spring uses TokenGranter abstraction to grant tokens.
When you search for a specific implementation, for example, ResourceOwnerPasswordTokenGranter, you can spot that it uses AuthentiacionManager which accommodates AuthenticationProviders.

So the answer is yes - it is possible.


来源: stackexchange

问:
macOS: Keep XPC Service (bundled) running after user quits main app
The bundled XPC Service in my macOS application need to do some post processing work with files dumped by the parent app, which most probably can't be completed within the usage time of the application. So, Is there a way to make the XPC service keep running even after the user quits the main app?</p>

答: You could install it as launch daemon (running in root context as long as computer is switched on) or as launch agent (running in user context as long as user is logged in).</p>

ContentLicense: CC BY-SA 4.0


问:
Nested UITableViews: a way to scroll both the outer vertical UITableView and a child horizontal UITableView at the same time?
When you're working with an atypical nested UITableViews setup - where you have an outer vertical UITableView that hosts 90° rotated UITableViews (see: Looking for a UI library to present Data horizontaly in iOS ):
is there a way to make iOS process vertical and horizontal touches at the same time?

I found that iOS is very clever in processing touches:
horizontal touches make the relevant horizontal UITableView scroll, while a vertical swipe makes the outer UITableView scroll. Perfect.

Only, I'd love to be able to move my finger diagonally and see the outer UITableView and the inner UITableView scroll at the same time.

I tried a few approaches (playing with canCancelContentTouches, delaysContentTouches, and touch messages) but I haven't found a way to make this happen.

EDIT:
Here's a XCode4 project that shows this behavior: http://marcanton.io/other/stackoverflow/nestedtableviews.zip

EDIT:
I submitted this issue to Apple Developer Technical Support, here's their reply:

Thank you for writing to Apple
  Worldwide Developer Technical Support.
  I am responding to your inquiry
  concerning touch events in embedded
  UITableViews.

Typically this is an approach that is
  not recommended. The issue is that
  UITableView inherits from UIScrollView
  and as stated in the documentation for
  UIScrollView:

"Important: You should not embed
  UIWebView or UITableView objects in
  UIScrollView objects. If you do so,
  unexpected behavior can result because
  touch events for the two objects can
  be mixed up and wrongly handled."

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIScrollView_Class/Reference/UIScrollView.html%23//apple_ref/occ/cl/UIScrollView

So that this time, there is not a
  workaround for getting both to scroll
  at the same time.

I recommend that you file an
  enhancement request at
  http://developer.apple.com/bugreporter/
  detailing what you would like to see
  us add in a future release.

Still, I think that there has to be a way to enable this functionality, although I understand that this is not recommended. In fact, Apple does not even recommend hosting UITableViews inside another UITableView, but with the exception made above, it works quite beautifully.
I'll keep this question updated with our collective findings.

EDIT: There actually is a way, detailed here: http://marcanton.io/blog/nested-orthogonal-tableviews/

答:
This would have to be a custom mirroring of intercepted touch events. Touch events follow the responder chain model, which means that if an object in the responder chain (the top most (outermost) view) cannot handle the event or action, it resends the message to the next responder (in this case the background UITableView in the chain). This is why you are seeing the horizontal events go to the horizontal UITableView and the vertical events going to the vertical UITableView. A diagonal touch event has applicable horizontal and vertical events, so the top-most view (the outer vertical UITableView) can respond to the vertical touches and swallows the event.

If you think about it, all vertical touches likely have a little bit of horizontal events (think about when you flick your finger), so there is likely some work done in the background to determine how to interpret the touch event (either as a vertical or horizontal).

I found this tread on passing events down to the next object in the responder chain. You might want to give this a try as a partial solution to your puzzle. The rest is to figure out how to capture the horizontal touch events and pass them along to the next responder.

ContentLicense: CC BY-SA 3.0


问:
How to terminate subscription to an actioncable channel from server?
Is there a way to terminate the subscription to a particular channel for any particular consumer from the server side (controller) so that disconnected callback in my coffee script file can be invoked?</p>

答:
Like Ollie's answer correctly pointed out, the other answers here are rejecting the ActionCable connection before it succeeds, but the question asks about disconnecting a subscription after it was already subscribed.

This question is very important because it deals with the scenario of an user being kicked out of a chatroom he was previously in. Unless you disconnect him from that subscription, he will continue to receive messages for that channel through the WebSocket until he closes his window/tab or reloads the page (because then a new subscription will be started and the server will not subscribe him to the chat he doesn't have permission anymore).

Ollie's answer points to a great pull request he made, because it allows to disconnect a specific stream, and not all open WebSockets connections a user has; the problem is it's not merged in Rails yet.

My solution is to use a documented API feature that already exists. Even tough it doesn't let you choose which stream you want to disconnect, you can disconnect all open websocket connects from a User.

In my tests this works fine because as soon as the disconnection happens, all tabs will try to resubscribe in a couple of seconds, and it will trigger the subscribed method in each ActionCable channel, thereby restarting the connections, but now based on the most up-to-date permissions from the server (which, of course, will not resubscribe him to the chat he was kicked out of).

The solution goes like this, assuming you have a join record ChatroomUser that is used to track if a specific user can read the chat in a specific chatroom:

```<code>class ChatroomUser < ApplicationRecord
  belongs_to :chatroom
  belongs_to :user

  after_destroy :disconnect_action_cable_connections

  private

    def disconnect_action_cable_connections

      ActionCable.server.remote_connections.where(current_user: self.user).disconnect

    end
end

</code>```

This uses this API (https://api.rubyonrails.org/classes/ActionCable/RemoteConnections.html), and assumes you have current_user set up in your ApplicationCable::Connection, as most people do (per tutorials).

Body:
Like Ollie's answer correctly pointed out, the other answers here are rejecting the ActionCable connection before it succeeds, but the question asks about disconnecting a subscription after it was already subscribed.

This question is very important because it deals with the scenario of an user being kicked out of a chatroom he was previously in. Unless you disconnect him from that subscription, he will continue to receive messages for that channel through the WebSocket until he closes his window/tab or reloads the page (because then a new subscription will be started and the server will not subscribe him to the chat he doesn't have permission anymore).

Ollie's answer points to a great pull request he made, because it allows to disconnect a specific stream, and not all open WebSockets connections a user has; the problem is it's not merged in Rails yet.

My solution is to use a documented API feature that already exists. Even tough it doesn't let you choose which stream you want to disconnect, you can disconnect all open websocket connects from a User.

In my tests this works fine because as soon as the disconnection happens, all tabs will try to resubscribe in a couple of seconds, and it will trigger the subscribed method in each ActionCable channel, thereby restarting the connections, but now based on the most up-to-date permissions from the server (which, of course, will not resubscribe him to the chat he was kicked out of).

The solution goes like this, assuming you have a join record ChatroomUser that is used to track if a specific user can read the chat in a specific chatroom:

class ChatroomUser < ApplicationRecord
  belongs_to :chatroom
  belongs_to :user

  after_destroy :disconnect_action_cable_connections

  private

    def disconnect_action_cable_connections

      ActionCable.server.remote_connections.where(current_user: self.user).disconnect

    end
end

This uses this API (https://api.rubyonrails.org/classes/ActionCable/RemoteConnections.html), and assumes you have current_user set up in your ApplicationCable::Connection, as most people do (per tutorials).


问:
Greedy/Non-Greedy pattern matching and optional suffixes in Lua
In Lua, I'm trying to pattern match and capture:

```<code>+384 Critical Strike (Reforged from Parry Chance)
</code>```

as

```<code>(+384) (Critical Strike)
</code>```

where the suffix (Reforged from %s) is optional.

Long version

I'm trying to match a string in Lua using patterns (i.e. strfind)

Note: In Lua they don't call them regular expressions, they call them patterns because they're not regular.

Example strings:

```<code>+384 Critical Strike
+1128 Hit
</code>```

This is broken down into two parts that I want to capture:

The number, with the leading positive or negative indicator; int his case is +384

The string, in this case is Critical Strike.

I can capture these using a fairly simple pattern:

And this pattern in lua works:

```<code>local text = "+384 Critical Strike";
local pattern = "([%+%-]%d+) (.+)";
local _, _, value, stat = strfind(text, pattern);
</code>```

value = +384

stat = Critical Strike

The Tricky Part

Now I need to expand that regular expression pattern to include an optional suffix:

```<code>+384 Critical Strike (Reforged from Parry Chance)
</code>```

Which is broken down into:

Note: I don't particularly care about the optional trailing suffix; meaning that I have no requirement to capture it, Although capturing it would be handy.

This is where I start to get into issues with greedy capturing. Right away the pattern I already have does what I don't want it to:

pattern = ([%+%-]%d+) (.+)

value = +384

stat = Critical Strike (Reforged from Parry Chance)

But let's try to include the suffix in the pattern:

with the pattern:

```<code>pattern = "([%+%-]%d+) (.+)( %(Reforged from .+%))?"
</code>```

And I'm using the ? operator to indicate 0 or 1 appearances of the suffix but that matches nothing.

I blindly tried changing the optional suffix group from parenthesis ( to brackets [:

```<code>pattern = "([%+%-]%d+) (.+)[ %(Reforged from .+%)]?"
</code>```

But now the match is greedy again:

value = +384

stat = Critical Strike (Reforged from Parry Chance)

Based on the Lua pattern reference):

x: (where x is not one of the magic characters ^$()%.[]*+-?) represents the character x itself.

.: (a dot) represents all characters.

%a: represents all letters.

%c: represents all control characters.

%d: represents all digits.

%l: represents all lowercase letters.

%p: represents all punctuation characters.

%s: represents all space characters.

%u: represents all uppercase letters.

%w: represents all alphanumeric characters.

%x: represents all hexadecimal digits.

%z: represents the character with representation 0.

%x: (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non-magic) can be preceded by a '%' when used to represent itself in a pattern.

[set]: represents the class which is the union of all characters in set. A range of characters can be specified by separating the end characters of the range with a '-'. All classes %x described above can also be used as components in set. All other characters in set represent themselves. For example, [%w_] (or [_%w]) represents all alphanumeric characters plus the underscore, [0-7] represents the octal digits, and [0-7%l%-] represents the octal digits plus the lowercase letters plus the '-' character.
  The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z] or [a-%%] have no meaning.

[^set]: represents the complement of set, where set is interpreted as above.

For all classes represented by single letters (%a, %c, etc.), the corresponding uppercase letter represents the complement of the class. For instance, %S represents all non-space characters.

The definitions of letter, space, and other character groups depend on the current locale. In particular, the class [a-z] may not be equivalent to %l.

and the magic matchers:

*, which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;

+, which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;

-, which also matches 0 or more repetitions of characters in the class. Unlike '*', these repetition items will always match the shortest possible sequence;

?, which matches 0 or 1 occurrence of a character in the class;

I noticed that there's a greedy *, and a non-greedy - modifier. Since my middle string matcher:

```<code>(%d) (%s) (%s)
</code>```

seems to be absorbing text until the end, perhaps i should try to make it non-greedy, by changing the * to a -:

```<code>oldPattern = "([%+%-]%d+) (.*)[ %(Reforged from .+%)]?"
newPattern = "([%+%-]%d+) (.-)[ %(Reforged from .+%)]?"
</code>```

Except now it fail to match:

value = +384

stat = nil

Rather than the middle group capturing "any" character (i.e. .), I tried a set that contains everything except (:

```<code>pattern = "([%+%-]%d+) ([^%(]*)( %(Reforged from .+%))?"
</code>```

and from there the wheels came off the wagon:

```<code>(+384) (Critical Strike)
</code>```0

I thought that I was close with:

```<code>(+384) (Critical Strike)
</code>```1

which captures

```<code>(+384) (Critical Strike)
</code>```2

So this is where I bang my head against the pillow and go to sleep; I can't believe I've spent four hours on this regex....pattern.

@NicolBolas The set of all possible strings, defined using a pseudo-regular expression language, are:

```<code>+%d %s (Reforged from %s)
</code>```

where

+ represents either the Plus Sign (+) or the "Minus Sign" (-)

%d represents any latin digit character (e.g. 0..9)

%s represents any latin uppercase or lowercase letters, or embedded spaces (e.g. A-Za-z)

the remaining characters are literals.

If i had to write a regular expression that obviously tries to do what i want:

```<code>\+\-\d+ [\w\s]+( \(Reforged from [\w\s]+\))?
</code>```

But I can give you near practically complete list of all values I'm likely to encounter in the wild if I didn't explain it well enough.

+123 Parry  positive number, single word

+123 Critical Strike  positive number, two words

-123 Parry  negative number, single word

-123 Critical Strike  negative number, two words

+123 Parry (Reforged from Dodge)  positive number, single word, optional suffix present with single word

+123 Critical Strike (Reforged from Dodge)  positive number, two words, optional suffix present with two words

-123 Parry (Reforged from Hit Chance)  negative number, single word, optional suffix present with two words

-123 Critical Strike (Reforged from Hit Chance)  negative number, two words, optional suffix present with two words

There are bonus patterns it would seem obvious that the patterns would also match:

+1234 Critical Strike Chance  four digit number, three words

+12345 Mount and run speed increase five digit number, five words

+123456 Mount and run speed increase six digit number, five words

-1 MoUnT aNd RuN sPeEd InCrEaSe one digit number, five words

-1 HiT (Reforged from CrItIcAl StRiKe ChAnCe) negative one digit number, one word, optional suffix present with 3 words

And while the ideal pattern should match the above bonus entries, it does not have to.

Localization

In reality all "numbers" i am attempting to parse out will be localized, e.g.:

+123,456 in English (en-US)

+123.456 in Germany (de-DE)

+123'456 in French (fr-CA)

+123 456 in Estonian (et-EE)

+1,23,456 in Assamese (as-IN)

Any answer must not attempt to account for these localization issues. You do not know the locale a number will be presented from, that is why the number localization has been removed from the question. You must strictly assume that numbers contain plus sign, hyphen minus, and latin digits 0 through 9. I already know how to parse localized numbers. This question is about trying to match the optional suffix with a greedy pattern parser.

Edit: You really didn't have to try to handle localized number. At some level trying to handle them, without knowing the locale, is wrong. For example, I didn't include all possible localizations of numbers. For another: I don't know what future localizations might exist in the future.

答:
It's much simpler, instead of just matching the pattern, you can look directly for the short output to the string you need, you can use it string.gsub

Example:

```<code>local testing = {"+123 Parry",
"+123 Critical Strike",
"-123 Parry",
"-123 Critical Strike",
"+123 Parry (Reforged from Dodge)",
"+123 Critical Strike (Reforged from Dodge)",
"-123 Parry (Reforged from Hit Chance)",
"-123 Critical Strike (Reforged from Hit Chance)",
"+122384    Critical    Strike      (Reforged from parry chance)",
"+384 Critical Strike ",
"+384Critical Strike (Reforged from parry chance)",
"+1234 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+12345 Mount and run speed increase (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123456 Mount and run speed increase (Reforged from CrItIcAl StRiKe ChAnCe)",
"-1 MoUnT aNd RuN sPeEd InCrEaSe (Reforged from CrItIcAl StRiKe ChAnCe)",
"-1 HiT (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123,456 +1234 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123.456 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123'456 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123 456 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+1,23,456 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+9 mana every 5 sec",
"-9 mana every 20 min (Does not occurr in data but gets captured if there)"}

for k,v in ipairs(testing) do
  local result = string.gsub(v, "([%+%-][',%.%d%s]-[%+%d]+)%s*([%a]+[^%(^%)]+[%a]+)%s*(%(?[%a%s]*%)?)", '(%1) (%2) %3')
  print(result)
end
</code>```

Output

```<code>(+123) (Parry)
(+123) (Critical Strike)
(-123) (Parry)
(-123) (Critical Strike)
(+123) (Parry) (Reforged from Dodge)
(+123) (Critical Strike) (Reforged from Dodge)
(-123) (Parry) (Reforged from Hit Chance)
(-123) (Critical Strike) (Reforged from Hit Chance)
(+122384) (Critical    Strike) (Reforged from parry chance)
(+384) (Critical Strike)
(+384) (Critical Strike) (Reforged from parry chance)
(+1234) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+12345) (Mount and run speed increase) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123456) (Mount and run speed increase) (Reforged from CrItIcAl StRiKe ChAnCe)
(-1) (MoUnT aNd RuN sPeEd InCrEaSe) (Reforged from CrItIcAl StRiKe ChAnCe)
(-1) (HiT) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123,456 +1234) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123.456) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123'456) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123 456) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+1,23,456) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+9) (mana every 5 sec)
(-9) (mana every 20 min) (Does not occurr in data but gets captured if there)
</code>```

Body:
In Lua, I'm trying to pattern match and capture:

+384 Critical Strike (Reforged from Parry Chance)

as

(+384) (Critical Strike)

where the suffix (Reforged from %s) is optional.

Long version

I'm trying to match a string in Lua using patterns (i.e. strfind)

Note: In Lua they don't call them regular expressions, they call them patterns because they're not regular.

Example strings:

+384 Critical Strike
+1128 Hit

This is broken down into two parts that I want to capture:

The number, with the leading positive or negative indicator; int his case is +384

The string, in this case is Critical Strike.

I can capture these using a fairly simple pattern:

And this pattern in lua works:

local text = "+384 Critical Strike";
local pattern = "([%+%-]%d+) (.+)";
local _, _, value, stat = strfind(text, pattern);

value = +384

stat = Critical Strike

The Tricky Part

Now I need to expand that regular expression pattern to include an optional suffix:

+384 Critical Strike (Reforged from Parry Chance)

Which is broken down into:

Note: I don't particularly care about the optional trailing suffix; meaning that I have no requirement to capture it, Although capturing it would be handy.

This is where I start to get into issues with greedy capturing. Right away the pattern I already have does what I don't want it to:

pattern = ([%+%-]%d+) (.+)

value = +384

stat = Critical Strike (Reforged from Parry Chance)

But let's try to include the suffix in the pattern:

with the pattern:

pattern = "([%+%-]%d+) (.+)( %(Reforged from .+%))?"

And I'm using the ? operator to indicate 0 or 1 appearances of the suffix but that matches nothing.

I blindly tried changing the optional suffix group from parenthesis ( to brackets [:

pattern = "([%+%-]%d+) (.+)[ %(Reforged from .+%)]?"

But now the match is greedy again:

value = +384

stat = Critical Strike (Reforged from Parry Chance)

Based on the Lua pattern reference):

x: (where x is not one of the magic characters ^$()%.[]*+-?) represents the character x itself.

.: (a dot) represents all characters.

%a: represents all letters.

%c: represents all control characters.

%d: represents all digits.

%l: represents all lowercase letters.

%p: represents all punctuation characters.

%s: represents all space characters.

%u: represents all uppercase letters.

%w: represents all alphanumeric characters.

%x: represents all hexadecimal digits.

%z: represents the character with representation 0.

%x: (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non-magic) can be preceded by a '%' when used to represent itself in a pattern.

[set]: represents the class which is the union of all characters in set. A range of characters can be specified by separating the end characters of the range with a '-'. All classes %x described above can also be used as components in set. All other characters in set represent themselves. For example, [%w_] (or [_%w]) represents all alphanumeric characters plus the underscore, [0-7] represents the octal digits, and [0-7%l%-] represents the octal digits plus the lowercase letters plus the '-' character.
  The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z] or [a-%%] have no meaning.

[^set]: represents the complement of set, where set is interpreted as above.

For all classes represented by single letters (%a, %c, etc.), the corresponding uppercase letter represents the complement of the class. For instance, %S represents all non-space characters.

The definitions of letter, space, and other character groups depend on the current locale. In particular, the class [a-z] may not be equivalent to %l.

and the magic matchers:

*, which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;

+, which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;

-, which also matches 0 or more repetitions of characters in the class. Unlike '*', these repetition items will always match the shortest possible sequence;

?, which matches 0 or 1 occurrence of a character in the class;

I noticed that there's a greedy *, and a non-greedy - modifier. Since my middle string matcher:

(%d) (%s) (%s)

seems to be absorbing text until the end, perhaps i should try to make it non-greedy, by changing the * to a -:

oldPattern = "([%+%-]%d+) (.*)[ %(Reforged from .+%)]?"
newPattern = "([%+%-]%d+) (.-)[ %(Reforged from .+%)]?"

Except now it fail to match:

value = +384

stat = nil

Rather than the middle group capturing "any" character (i.e. .), I tried a set that contains everything except (:

pattern = "([%+%-]%d+) ([^%(]*)( %(Reforged from .+%))?"

and from there the wheels came off the wagon:

local pattern = "([%+%-]%d+) ([^%(]*)( %(Reforged from .+%))?"
local pattern = "([%+%-]%d+) ((^%()*)( %(Reforged from .+%))?"
local pattern = "([%+%-]%d+) (%a )+)[ %(Reforged from .+%)]?"

I thought that I was close with:

local pattern = "([%+%-]%d+) ([%a ]+)[ %(Reforged from .+%)]?"

which captures

- value = "+385"
- stat = "Critical Strike "  (notice the trailing space)

So this is where I bang my head against the pillow and go to sleep; I can't believe I've spent four hours on this regex....pattern.

@NicolBolas The set of all possible strings, defined using a pseudo-regular expression language, are:

+%d %s (Reforged from %s)

where

+ represents either the Plus Sign (+) or the "Minus Sign" (-)

%d represents any latin digit character (e.g. 0..9)

%s represents any latin uppercase or lowercase letters, or embedded spaces (e.g. A-Za-z)

the remaining characters are literals.

If i had to write a regular expression that obviously tries to do what i want:

\+\-\d+ [\w\s]+( \(Reforged from [\w\s]+\))?

But I can give you near practically complete list of all values I'm likely to encounter in the wild if I didn't explain it well enough.

+123 Parry  positive number, single word

+123 Critical Strike  positive number, two words

-123 Parry  negative number, single word

-123 Critical Strike  negative number, two words

+123 Parry (Reforged from Dodge)  positive number, single word, optional suffix present with single word

+123 Critical Strike (Reforged from Dodge)  positive number, two words, optional suffix present with two words

-123 Parry (Reforged from Hit Chance)  negative number, single word, optional suffix present with two words

-123 Critical Strike (Reforged from Hit Chance)  negative number, two words, optional suffix present with two words

There are bonus patterns it would seem obvious that the patterns would also match:

+1234 Critical Strike Chance  four digit number, three words

+12345 Mount and run speed increase five digit number, five words

+123456 Mount and run speed increase six digit number, five words

-1 MoUnT aNd RuN sPeEd InCrEaSe one digit number, five words

-1 HiT (Reforged from CrItIcAl StRiKe ChAnCe) negative one digit number, one word, optional suffix present with 3 words

And while the ideal pattern should match the above bonus entries, it does not have to.

Localization

In reality all "numbers" i am attempting to parse out will be localized, e.g.:

+123,456 in English (en-US)

+123.456 in Germany (de-DE)

+123'456 in French (fr-CA)

+123 456 in Estonian (et-EE)

+1,23,456 in Assamese (as-IN)

Any answer must not attempt to account for these localization issues. You do not know the locale a number will be presented from, that is why the number localization has been removed from the question. You must strictly assume that numbers contain plus sign, hyphen minus, and latin digits 0 through 9. I already know how to parse localized numbers. This question is about trying to match the optional suffix with a greedy pattern parser.

Edit: You really didn't have to try to handle localized number. At some level trying to handle them, without knowing the locale, is wrong. For example, I didn't include all possible localizations of numbers. For another: I don't know what future localizations might exist in the future.

Body:
It's much simpler, instead of just matching the pattern, you can look directly for the short output to the string you need, you can use it string.gsub

Example:

local testing = {"+123 Parry",
"+123 Critical Strike",
"-123 Parry",
"-123 Critical Strike",
"+123 Parry (Reforged from Dodge)",
"+123 Critical Strike (Reforged from Dodge)",
"-123 Parry (Reforged from Hit Chance)",
"-123 Critical Strike (Reforged from Hit Chance)",
"+122384    Critical    Strike      (Reforged from parry chance)",
"+384 Critical Strike ",
"+384Critical Strike (Reforged from parry chance)",
"+1234 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+12345 Mount and run speed increase (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123456 Mount and run speed increase (Reforged from CrItIcAl StRiKe ChAnCe)",
"-1 MoUnT aNd RuN sPeEd InCrEaSe (Reforged from CrItIcAl StRiKe ChAnCe)",
"-1 HiT (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123,456 +1234 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123.456 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123'456 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+123 456 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+1,23,456 Critical Strike Chance (Reforged from CrItIcAl StRiKe ChAnCe)",
"+9 mana every 5 sec",
"-9 mana every 20 min (Does not occurr in data but gets captured if there)"}

for k,v in ipairs(testing) do
  local result = string.gsub(v, "([%+%-][',%.%d%s]-[%+%d]+)%s*([%a]+[^%(^%)]+[%a]+)%s*(%(?[%a%s]*%)?)", '(%1) (%2) %3')
  print(result)
end

Output

(+123) (Parry)
(+123) (Critical Strike)
(-123) (Parry)
(-123) (Critical Strike)
(+123) (Parry) (Reforged from Dodge)
(+123) (Critical Strike) (Reforged from Dodge)
(-123) (Parry) (Reforged from Hit Chance)
(-123) (Critical Strike) (Reforged from Hit Chance)
(+122384) (Critical    Strike) (Reforged from parry chance)
(+384) (Critical Strike)
(+384) (Critical Strike) (Reforged from parry chance)
(+1234) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+12345) (Mount and run speed increase) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123456) (Mount and run speed increase) (Reforged from CrItIcAl StRiKe ChAnCe)
(-1) (MoUnT aNd RuN sPeEd InCrEaSe) (Reforged from CrItIcAl StRiKe ChAnCe)
(-1) (HiT) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123,456 +1234) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123.456) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123'456) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+123 456) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+1,23,456) (Critical Strike Chance) (Reforged from CrItIcAl StRiKe ChAnCe)
(+9) (mana every 5 sec)
(-9) (mana every 20 min) (Does not occurr in data but gets captured if there)


问:
what schema permissions are entailed when a SQL Server 2005 database role owns a schema?
In SQL Server 2005, a user-defined database role can "own" a schema. You can see this in the properties window of the database role.  What exactly does this mean in terms of permissions/privileges against the tables in that schema?  What does owning a schema mean?

Or, to ask another way:  If I want a particular user-defined database role to have select/insert/update/delete privileges against every table in a schema, what is the best/smartest way to accomplish this?

I could go into the permissions of every individual table in the schema and grant the privs to the role, but this seems dumb.  How do I do it for the whole schema?

thanks
aj

答:
MSDN Documentation: db_owner

Making them members of the db_owner group for that a particular database will essentially do what you require - of course they have a few extra permissions - such as drop a database.

You could create a new user group/schema, of course as you pointed out you need to set appropriate permissions: SQL Server 2005 Permissions


问:
RegEx for an autocomplete feature
I am writing a search bar with an autocomplete feature that is hooked up to an endpoint. I am using regex to determine the "context" that I am in inside of the query I type in the search bar. The three contexts are "attribute," "value," and "operator." The two operators that are allowed are "AND" and "OR." Below is an example of an example query.

Color: Blue AND Size: "Women's Large" (<-- multi-word values or attribute names are surrounded by quotation marks)

I need my regex to match after you put a space after Blue, and if the user begins type "A/AN/AND/O/OR", I need it to match. Once they have put a space after the operator, I need it to stop matching.

This is the expression I have come up with.

```<code>const contextIsOperator = /[\w\d\s"]+: *[\w\s\d"]+ [\w]*$/
</code>```

It matches once I put a space after "Blue," but matches for everything I put after that. If I replace the last * in the expression with a +, it works when I put a space after "Blue" and start manually typing one of the operators, but not if I just have a space after "Blue."

The pattern I have in my head written in words is:

group of one or more characters/digits/spaces/quotation marks

followed by a colon

followed by an optional space

followed by another group of one or more characters/digits/space/quotation marks

followed by a space (after the value)

followed by one or more characters (this is the operator)

How do I solve this problem?

答:
Change [\w]* to something that just matches AND, OR, or one of their prefixes. Then you can make it optional with ?

```<code>[\w\s"]+: *[\w\s"]+ (A|AN|AND|O|OR)?$
</code>```

DEMO

Note that Size: Women's Large won't match this because the apostrophe isn't in \w; that only matches letters, digits, and underscore. You'll need to add any other punctuation characters that you want to allow in these fields to the character set.

Title: RegEx for an autocomplete feature

Body:
I am writing a search bar with an autocomplete feature that is hooked up to an endpoint. I am using regex to determine the "context" that I am in inside of the query I type in the search bar. The three contexts are "attribute," "value," and "operator." The two operators that are allowed are "AND" and "OR." Below is an example of an example query.

Color: Blue AND Size: "Women's Large" (<-- multi-word values or attribute names are surrounded by quotation marks)

I need my regex to match after you put a space after Blue, and if the user begins type "A/AN/AND/O/OR", I need it to match. Once they have put a space after the operator, I need it to stop matching.

This is the expression I have come up with.

const contextIsOperator = /[\w\d\s"]+: *[\w\s\d"]+ [\w]*$/

It matches once I put a space after "Blue," but matches for everything I put after that. If I replace the last * in the expression with a +, it works when I put a space after "Blue" and start manually typing one of the operators, but not if I just have a space after "Blue."

The pattern I have in my head written in words is:

group of one or more characters/digits/spaces/quotation marks

followed by a colon

followed by an optional space

followed by another group of one or more characters/digits/space/quotation marks

followed by a space (after the value)

followed by one or more characters (this is the operator)

How do I solve this problem?

Body:
Change [\w]* to something that just matches AND, OR, or one of their prefixes. Then you can make it optional with ?

[\w\s"]+: *[\w\s"]+ (A|AN|AND|O|OR)?$

DEMO

Note that Size: Women's Large won't match this because the apostrophe isn't in \w; that only matches letters, digits, and underscore. You'll need to add any other punctuation characters that you want to allow in these fields to the character set.


问:
Mapper fails to locate foreign keys on secondary table (Many to many relationship)
I'm trying to describe a simple  "many to many" relationship using flask-SQLAlchemy, however, the mapper does'nt seem to find the foreign keys on my secondary table, even though they are correctly defined.

I'm using the latest version os flask-SQLAlchemy (2.4) and SQLite. I've tried many code variations and still, nothing. Doumentation is not helping either =/

user_permit = db.table('userpermit',
    db.Column('permit_id', db.Integer, db.ForeignKey('permit.permit_id'), primary_key=True),
    db.Column('user_mail', db.String(128), db.ForeignKey('user.user_mail'), primary_key=True)
)

class User(db.Model):
    user_mail = db.Column(db.String(128), primary_key=True)

[...]
    permits = db.relationship('Permit', secondary=user_permit, backref='users_permitted')

class Permit(db.Model):
    permit_id = db.Column(db.Integer, primary_key=True)
```

I always get the same error message: NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.permits - there are no foreign keys linking these tables via secondary table ''.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions.

It seems it does not recognize my secondary table, since it says '', instead of 'userpermit'.

答:
Sorry, you guys. Too much time looking at the code lines. Turns out I was instantiating db.table('user permit'..... instead of db.Table (with capital T)

Thank you.

Body:
I'm trying to describe a simple  "many to many" relationship using flask-SQLAlchemy, however, the mapper does'nt seem to find the foreign keys on my secondary table, even though they are correctly defined.

I'm using the latest version os flask-SQLAlchemy (2.4) and SQLite. I've tried many code variations and still, nothing. Doumentation is not helping either =/

user_permit = db.table('userpermit',
    db.Column('permit_id', db.Integer, db.ForeignKey('permit.permit_id'), primary_key=True),
    db.Column('user_mail', db.String(128), db.ForeignKey('user.user_mail'), primary_key=True)
)

class User(db.Model):
    user_mail = db.Column(db.String(128), primary_key=True)

[...]
    permits = db.relationship('Permit', secondary=user_permit, backref='users_permitted')

class Permit(db.Model):
    permit_id = db.Column(db.Integer, primary_key=True)

I always get the same error message: NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.permits - there are no foreign keys linking these tables via secondary table ''.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions.

It seems it does not recognize my secondary table, since it says '', instead of 'userpermit'.


问:
How to set URL for Maven dependency
I have the following error after launch mvn clean install vagrant:up:

```<code>Downloading: https://oss.sonatype.org/content/repositories/snapshots/org/apache/avalon/framework/avalon-framework-api/4.2.0/avalon-framework-api-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-api:pom:4.2.0' in repository snapshot-repository (https://oss.sonatype.org/content/repositories/snapshots)
Downloading: http://central.maven.org/maven2/org/apache/avalon/framework/avalon-framework-api/4.2.0/avalon-framework-api-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-api:pom:4.2.0' in repository Avalon-repo (http://central.maven.org/maven2)
Downloading: http://repo1.maven.org/maven2/org/apache/avalon/framework/avalon-framework-api/4.2.0/avalon-framework-api-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-api:pom:4.2.0' in repository central (http://repo1.maven.org/maven2)
Downloading: https://oss.sonatype.org/content/repositories/snapshots/org/apache/avalon/framework/avalon-framework-impl/4.2.0/avalon-framework-impl-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-impl:pom:4.2.0' in repository snapshot-repository (https://oss.sonatype.org/content/repositories/snapshots)
Downloading: http://central.maven.org/maven2/org/apache/avalon/framework/avalon-framework-impl/4.2.0/avalon-framework-impl-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-impl:pom:4.2.0' in repository Avalon-repo (http://central.maven.org/maven2)
Downloading: http://repo1.maven.org/maven2/org/apache/avalon/framework/avalon-framework-impl/4.2.0/avalon-framework-impl-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-impl:pom:4.2.0' in repository central (http://repo1.maven.org/maven2)
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed to resolve artifact.

Unable to get dependency information: Error in metadata for artifact 'rubygems:vagrant:gem': Unable to parse version '[0.5.2,0.5.2.0.0.0.0.1)' for dependency 'rubygems:archive-tar-minitar:gem': Range defies version ordering: [0.5.2,0.5.2.0.0.0.0.1)
  rubygems:vagrant:gem:1.0.7

from the specified remote repositories:
  central (http://repo1.maven.org/maven2),
  rubygems (http://rubygems-proxy.torquebox.org/releases),
  snapshot-repository (https://oss.sonatype.org/content/repositories/snapshots),
  Avalon-repo (http://central.maven.org/maven2)

Path to dependency:
    1) downloader:downloader:jar:0.0.1-SNAPSHOT
    2) net.ju-n.maven.plugins:vagrant-maven-plugin:maven-plugin:1.0.1
</code>```

I have searched this dependency and I found it in another URL, but I don't know how to set it. I don't want to download the jar manually, because we are using Jenkins and I don't have access to that repository.

Anyone knows how to solve it?

Thanks!!

P.S. My pom.xml is (partial):

```<code><dependency>
  <groupId>net.ju-n.maven.plugins</groupId>
  <artifactId>vagrant-maven-plugin</artifactId>
  <version>1.0.1</version>
  <type>maven-plugin</type>
</dependency>
<dependency>
  <groupId>de.saumya.mojo</groupId>
  <artifactId>gem-maven-plugin</artifactId>
  <version>1.0.7</version>
</dependency>
<dependency>
  <groupId>avalon-framework</groupId>
  <artifactId>avalon-framework-impl</artifactId>
  <version>4.2.0</version>
  <optional>true</optional>
</dependency>
</code>```

Update1: I have the following repositories in my pom.xml:

```<code><repositories>
    <repository>
        <id>snapshot-repository</id>
        <name>Maven2 Snapshot Repository</name>
        <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </snapshots>
    </repository>

    <repository>
      <id>Avalon-repo</id>
      <url>http://central.maven.org/maven2</url>
    </repository>
  </repositories>
</code>```

Update2: The problem that Maven is looking for the dependency in http://repo1.maven.org/maven2/org/apache/avalon/framework/avalon-framework-impl/4.2.0/avalon-framework-impl-4.2.0.pom, but the correct URL is: https://repo1.maven.org/maven2/avalon-framework/avalon-framework-api/4.2.0/avalon-framework-api-4.2.0.pom

答:
I had this problem where my lookup for dependencies were failing. As it was kind of replacing org.xxx as org/xxx and none of the dependencies were pulled.

The url for default Central Maven repository is http://repo.maven.apache.org/maven2/.
Unless you want to fetch artifacts from different location (like local artifactory etc.,)  Remove  section or you can still have

```<code>       <repository>
           <id>central</id>
           <url>http://repo.maven.apache.org/maven2/</url>
       </repository>
</code>```

mvn clean install
it should download all repositories that you are looking for.

Title: How to set URL for Maven dependency

Body:
I have the following error after launch mvn clean install vagrant:up:

Downloading: https://oss.sonatype.org/content/repositories/snapshots/org/apache/avalon/framework/avalon-framework-api/4.2.0/avalon-framework-api-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-api:pom:4.2.0' in repository snapshot-repository (https://oss.sonatype.org/content/repositories/snapshots)
Downloading: http://central.maven.org/maven2/org/apache/avalon/framework/avalon-framework-api/4.2.0/avalon-framework-api-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-api:pom:4.2.0' in repository Avalon-repo (http://central.maven.org/maven2)
Downloading: http://repo1.maven.org/maven2/org/apache/avalon/framework/avalon-framework-api/4.2.0/avalon-framework-api-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-api:pom:4.2.0' in repository central (http://repo1.maven.org/maven2)
Downloading: https://oss.sonatype.org/content/repositories/snapshots/org/apache/avalon/framework/avalon-framework-impl/4.2.0/avalon-framework-impl-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-impl:pom:4.2.0' in repository snapshot-repository (https://oss.sonatype.org/content/repositories/snapshots)
Downloading: http://central.maven.org/maven2/org/apache/avalon/framework/avalon-framework-impl/4.2.0/avalon-framework-impl-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-impl:pom:4.2.0' in repository Avalon-repo (http://central.maven.org/maven2)
Downloading: http://repo1.maven.org/maven2/org/apache/avalon/framework/avalon-framework-impl/4.2.0/avalon-framework-impl-4.2.0.pom
[INFO] Unable to find resource 'org.apache.avalon.framework:avalon-framework-impl:pom:4.2.0' in repository central (http://repo1.maven.org/maven2)
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed to resolve artifact.

Unable to get dependency information: Error in metadata for artifact 'rubygems:vagrant:gem': Unable to parse version '[0.5.2,0.5.2.0.0.0.0.1)' for dependency 'rubygems:archive-tar-minitar:gem': Range defies version ordering: [0.5.2,0.5.2.0.0.0.0.1)
  rubygems:vagrant:gem:1.0.7

from the specified remote repositories:
  central (http://repo1.maven.org/maven2),
  rubygems (http://rubygems-proxy.torquebox.org/releases),
  snapshot-repository (https://oss.sonatype.org/content/repositories/snapshots),
  Avalon-repo (http://central.maven.org/maven2)

Path to dependency:
    1) downloader:downloader:jar:0.0.1-SNAPSHOT
    2) net.ju-n.maven.plugins:vagrant-maven-plugin:maven-plugin:1.0.1

I have searched this dependency and I found it in another URL, but I don't know how to set it. I don't want to download the jar manually, because we are using Jenkins and I don't have access to that repository.

Anyone knows how to solve it?

Thanks!!

P.S. My pom.xml is (partial):

<dependency>
  <groupId>net.ju-n.maven.plugins</groupId>
  <artifactId>vagrant-maven-plugin</artifactId>
  <version>1.0.1</version>
  <type>maven-plugin</type>
</dependency>
<dependency>
  <groupId>de.saumya.mojo</groupId>
  <artifactId>gem-maven-plugin</artifactId>
  <version>1.0.7</version>
</dependency>
<dependency>
  <groupId>avalon-framework</groupId>
  <artifactId>avalon-framework-impl</artifactId>
  <version>4.2.0</version>
  <optional>true</optional>
</dependency>

Update1: I have the following repositories in my pom.xml:

<repositories>
    <repository>
        <id>snapshot-repository</id>
        <name>Maven2 Snapshot Repository</name>
        <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </snapshots>
    </repository>

    <repository>
      <id>Avalon-repo</id>
      <url>http://central.maven.org/maven2</url>
    </repository>
  </repositories>

Update2: The problem that Maven is looking for the dependency in http://repo1.maven.org/maven2/org/apache/avalon/framework/avalon-framework-impl/4.2.0/avalon-framework-impl-4.2.0.pom, but the correct URL is: https://repo1.maven.org/maven2/avalon-framework/avalon-framework-api/4.2.0/avalon-framework-api-4.2.0.pom

Body:
I had this problem where my lookup for dependencies were failing. As it was kind of replacing org.xxx as org/xxx and none of the dependencies were pulled.

The url for default Central Maven repository is http://repo.maven.apache.org/maven2/.
Unless you want to fetch artifacts from different location (like local artifactory etc.,)  Remove  section or you can still have

       <repository>
           <id>central</id>
           <url>http://repo.maven.apache.org/maven2/</url>
       </repository>

mvn clean install
it should download all repositories that you are looking for.


问:
Heat map generation using coordinate points
I am new in Python. The answer to my question might be available in the StackOverflow, but honestly speaking, I tried almost all the codes and suggestions available in the StackOverflow.

My problem: Almost the same as it is described here. I have coordinate points (x and y) and the corresponding value (p) as a .csv file. I am reading that file using pandas.

```<code>df = pd.read_csv("example.csv")
</code>```

The example.csv file can be download from here. Let an image of size 2000 x 2000.

Task:

Based on the x and y coordinate points in the excel sheet, I have to locate the point in that image.

Lets, A is an image and A(x,y) is any point within A. Now I have to generate a heat map in such a way so that 50 pixels from x and 50 pixels fromy i.e., A(x,y), A(x+50, y), A(x, y+50) and A(x+50, y+50) contains p corresponding to that coordinate points.

I found this link which is very helpful and serves my issue, but the problem is some more modifications are necessary for my datasets.

The code which is available in the above link:

```<code>#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from skimage import io
from skimage.color import rgb2gray
import matplotlib as mpl
# Read original image
img = io.imread('img.jpg')

# Get the dimensions of the original image
x_dim, y_dim, z_dim = np.shape(img)

# Create heatmap
heatmap = np.zeros((x_dim, y_dim), dtype=float)

# Read CSV with a Pandas DataFrame
df = pd.read_csv("data.csv")

# Set probabilities values to specific indexes in the heatmap
for index, row in df.iterrows():
    x = np.int(row["x"])
    y = np.int(row["y"])
    x1 = np.int(row["x1"])
    y1 = np.int(row["y1"])
    p = row["Probability value"]
    heatmap[x:x1,y:y1] = p

# Plot images
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()

ax[0].imshow(img)
ax[0].set_title("Original")
fig.colorbar(ax[0].imshow(img), ax=ax[0])

ax[1].imshow(img, vmin=0, vmax=1)
ax[1].imshow(heatmap, alpha=.5, cmap='jet')
ax[1].set_title("Original + heatmap")

# Specific colorbar
norm = mpl.colors.Normalize(vmin=0,vmax=2)
N = 11
cmap = plt.get_cmap('jet',N)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
plt.colorbar(sm, ticks=np.linspace(0,1,N),
             boundaries=np.arange(0,1.1,0.1))

fig.tight_layout()
plt.show()
</code>```

Issues which I am facing when using this code:

This code is generating a heat map of square edges, but I am expecting a smooth edge. I know Gaussian distribution might solve this problem. But I am new in python and I don't know how to implement the Gaussian Distribution in my dataset.

The regions which don't belong to the coordinate points also generating a layer of color. As a result in an overlayed image those layer covering the background of original images. In one sentence I want the background of the heat map will be transparent so that overlays will not create any problem in showing the regions which are not covered by the coordinate points.

Any leads will be highly appreciated.

答:
The question you linked uses plotly. If you don't want to use that and want to simply smooth the way your data looks, I suggest just using a gaussian filter using scipy.

At the top, import:

```<code>import seaborn as sns
from scipy.ndimage.filters import gaussian_filter
</code>```

Then use it like this:

```<code>df_smooth = gaussian_filter(df, sigma=1)
sns.heatmap(df_smooth, vmin=-40, vmax=150, cmap ="coolwarm" , cbar=True , cbar_kws={"ticks":[-40,150,-20,0,25,50,75,100,125]})
</code>```

You can change the amount of smoothing, using e.g. sigma=3, or any other number that gives you the amount of smoothing you want.

Keep in mind that that will also "smooth out" any maximum data peaks you have, so your minimum and maximum data will not be the same that you specified in your normalization anymore. To still get good looking heatmaps I would suggest not using fixed values for your vmin and vmax, but:

```<code>sns.heatmap(df_smooth, vmin=np.min(df_smooth), vmax=np.max(df_smooth), cmap ="coolwarm" , cbar=True , cbar_kws={"ticks":[-40,150,-20,0,25,50,75,100,125]})
</code>```

In case that you Gaussian filter fulfill your expectations you mentioned  you can even implement Gaussian normalization on your data directly.

Body:
I am new in Python. The answer to my question might be available in the StackOverflow, but honestly speaking, I tried almost all the codes and suggestions available in the StackOverflow.

My problem: Almost the same as it is described here. I have coordinate points (x and y) and the corresponding value (p) as a .csv file. I am reading that file using pandas.

df = pd.read_csv("example.csv")

The example.csv file can be download from here. Let an image of size 2000 x 2000.

Task:

Based on the x and y coordinate points in the excel sheet, I have to locate the point in that image.

Lets, A is an image and A(x,y) is any point within A. Now I have to generate a heat map in such a way so that 50 pixels from x and 50 pixels fromy i.e., A(x,y), A(x+50, y), A(x, y+50) and A(x+50, y+50) contains p corresponding to that coordinate points.

I found this link which is very helpful and serves my issue, but the problem is some more modifications are necessary for my datasets.

The code which is available in the above link:

#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from skimage import io
from skimage.color import rgb2gray
import matplotlib as mpl
# Read original image
img = io.imread('img.jpg')

# Get the dimensions of the original image
x_dim, y_dim, z_dim = np.shape(img)

# Create heatmap
heatmap = np.zeros((x_dim, y_dim), dtype=float)

# Read CSV with a Pandas DataFrame
df = pd.read_csv("data.csv")

# Set probabilities values to specific indexes in the heatmap
for index, row in df.iterrows():
    x = np.int(row["x"])
    y = np.int(row["y"])
    x1 = np.int(row["x1"])
    y1 = np.int(row["y1"])
    p = row["Probability value"]
    heatmap[x:x1,y:y1] = p

# Plot images
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()

ax[0].imshow(img)
ax[0].set_title("Original")
fig.colorbar(ax[0].imshow(img), ax=ax[0])

ax[1].imshow(img, vmin=0, vmax=1)
ax[1].imshow(heatmap, alpha=.5, cmap='jet')
ax[1].set_title("Original + heatmap")

# Specific colorbar
norm = mpl.colors.Normalize(vmin=0,vmax=2)
N = 11
cmap = plt.get_cmap('jet',N)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
plt.colorbar(sm, ticks=np.linspace(0,1,N),
             boundaries=np.arange(0,1.1,0.1))

fig.tight_layout()
plt.show()

Issues which I am facing when using this code:

This code is generating a heat map of square edges, but I am expecting a smooth edge. I know Gaussian distribution might solve this problem. But I am new in python and I don't know how to implement the Gaussian Distribution in my dataset.

The regions which don't belong to the coordinate points also generating a layer of color. As a result in an overlayed image those layer covering the background of original images. In one sentence I want the background of the heat map will be transparent so that overlays will not create any problem in showing the regions which are not covered by the coordinate points.

Any leads will be highly appreciated.

Body:
The question you linked uses plotly. If you don't want to use that and want to simply smooth the way your data looks, I suggest just using a gaussian filter using scipy.

At the top, import:

import seaborn as sns
from scipy.ndimage.filters import gaussian_filter

Then use it like this:

df_smooth = gaussian_filter(df, sigma=1)
sns.heatmap(df_smooth, vmin=-40, vmax=150, cmap ="coolwarm" , cbar=True , cbar_kws={"ticks":[-40,150,-20,0,25,50,75,100,125]})

You can change the amount of smoothing, using e.g. sigma=3, or any other number that gives you the amount of smoothing you want.

Keep in mind that that will also "smooth out" any maximum data peaks you have, so your minimum and maximum data will not be the same that you specified in your normalization anymore. To still get good looking heatmaps I would suggest not using fixed values for your vmin and vmax, but:

sns.heatmap(df_smooth, vmin=np.min(df_smooth), vmax=np.max(df_smooth), cmap ="coolwarm" , cbar=True , cbar_kws={"ticks":[-40,150,-20,0,25,50,75,100,125]})

In case that you Gaussian filter fulfill your expectations you mentioned  you can even implement Gaussian normalization on your data directly.


问:
Setting extra bits in a bool makes it true and false at the same time
If I get a bool variable and set its second bit to 1, then variable evaluates to true and false at the same time. Compile the following code with gcc6.3 with -g option, (gcc-v6.3.0/Linux/RHEL6.0-2016-x86_64/bin/g++ -g main.cpp -o mytest_d)  and run the executable. You get the following.

How can T be equal to true and false at the same time?

```<code>       value   bits
       -----   ----
    T:   1     0001
after bit change
    T:   3     0011
T is true
T is false
</code>```

This can happen when you call a function in a different language (say fortran) where true and false definition is different than C++. For fortran if any bits are not 0 then the value is true, if all bits are zero then the value is false.

```<code>#include <iostream>
#include <bitset>

using namespace std;

void set_bits_to_1(void* val){
  char *x = static_cast<char *>(val);

  for (int i = 0; i<2; i++ ){
    *x |= (1UL << i);
  }
}

int main(int argc,char *argv[])
{

  bool T = 3;

  cout <<"       value   bits " <<endl;
  cout <<"       -----   ---- " <<endl;
  cout <<"    T:   "<< T <<"     "<< bitset<4>(T)<<endl;

  set_bits_to_1(&T);

  bitset<4> bit_T = bitset<4>(T);
  cout <<"after bit change"<<endl;
  cout <<"    T:   "<< T <<"     "<< bit_T<<endl;

  if (T ){
    cout <<"T is true" <<endl;
  }

  if ( T == false){
    cout <<"T is false" <<endl;
  }

}
</code>```

///////////////////////////////////
// Fortran function that is not compatible with C++ when compiled with ifort.

```<code>       logical*1 function return_true()
         implicit none

         return_true = 1;

       end function return_true
</code>```

答:
In C++ the bit representation (and even the size) of a bool is implementation defined; generally it's implemented as a char-sized type taking 1 or 0 as possible values.

If you set its value to anything different from the allowed ones (in this specific case by aliasing a bool through a char and modifying its bit representation), you are breaking the rules of the language, so anything can happen. In particular, it's explicitly specified in the standard that a "broken" bool may behave as both true and false (or neither true nor false) at the same time:

Using a bool value in ways described by this International Standard as “undefined,” such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neither true nor false

(C++11, [basic.fundamental], note 47)

In this particular case, you can see how it ended up in this bizarre situation: the first if gets compiled to

```<code>    movzx   eax, BYTE PTR [rbp-33]
    test    al, al
    je      .L22
</code>```

which loads T in eax (with zero extension), and skips the print if it's all zero; the next if instead is

```<code>    movzx   eax, BYTE PTR [rbp-33]
    xor     eax, 1
    test    al, al
    je      .L23
</code>```

The test if(T == false) is transformed to if(T^1), which flips just the low bit. This would be ok for a valid bool, but for your "broken" one it doesn't cut it.

Notice that this bizarre sequence is only generated at low optimization levels; at higher levels this is generally going to boil down to a zero/nonzero check, and a sequence like yours is likely to become a single test/conditional branch. You will get bizarre behavior anyway in other contexts, e.g. when summing bool values to other integers:

```<code>int foo(bool b, int i) {
    return i + b;
}
</code>```

becomes

```<code>foo(bool, int):
        movzx   edi, dil
        lea     eax, [rdi+rsi]
        ret
</code>```

where dil is "trusted" to be 0/1.

If your program is all C++, then the solution is simple: don't break bool values this way, avoid messing with their bit representation and everything will go well; in particular, even if you assign from an integer to a bool the compiler will emit the necessary code to make sure that the resulting value is a valid bool, so your bool T = 3 is indeed safe, and T will end up with a true in its guts.

If instead you need to interoperate with code written in other languages that may not share the same idea of what a bool is, just avoid bool for "boundary" code, and marshal it as an appropriately-sized integer. It will work in conditionals & co. just as fine.

Update about the Fortran/interoperability side of the issue

Disclaimer all I know of Fortran is what I read this morning on standard documents, and that I have some punched cards with Fortran listings that I use as bookmarks, so go easy on me.

First of all, this kind of language interoperability stuff isn't part of the language standards, but of the platform ABI. As we are talking about Linux x86-64, the relevant document is the System V x86-64 ABI.

First of all, nowhere is specified that the C _Bool type (which is defined to be the same as C++ bool at 3.1.2 note †) has any kind of compatibility with Fortran LOGICAL; in particular, at 9.2.2 table 9.2 specifies that "plain" LOGICAL is mapped to signed int. About TYPE*N types it says that

The “TYPE*N” notation specifies that variables or aggregate members of type TYPE shall occupy N bytes of storage.

(ibid.)

There's no equivalent type explicitly specified for LOGICAL*1, and it's understandable: it's not even standard; indeed if you try to compile a Fortran program containing a LOGICAL*1 in Fortran 95 compliant mode you get warnings about it, both by ifort

```<code>./example.f90(2): warning #6916: Fortran 95 does not allow this length specification.   [1]

    logical*1, intent(in) :: x

------------^
</code>```

and by gfort

```<code>./example.f90:2:13:
     logical*1, intent(in) :: x
             1
Error: GNU Extension: Nonstandard type declaration LOGICAL*1 at (1)
</code>```

so the waters are already muddled; so, combining the two rules above, I'd go for signed char to be safe.

However: the ABI also specifies:

The values for type LOGICAL are .TRUE. implemented as 1 and .FALSE.
implemented as 0.

So, if you have a program that stores anything besides 1 and 0 in a LOGICAL value, you are already out of spec on the Fortran side! You say:

A fortran logical*1 has same representation as bool, but in fortran if bits are 00000011 it is true, in C++ it is undefined.

This last statement is not true, the Fortran standard is representation-agnostic, and the ABI explicitly says the contrary. Indeed you can see this in action easily by checking the output of gfort for LOGICAL comparison:

```<code>integer function logical_compare(x, y)
    logical, intent(in) :: x
    logical, intent(in) :: y
    if (x .eqv. y) then
        logical_compare = 12
    else
        logical_compare = 24
    end if
end function logical_compare
</code>```

becomes

```<code>logical_compare_:
        mov     eax, DWORD PTR [rsi]
        mov     edx, 24
        cmp     DWORD PTR [rdi], eax
        mov     eax, 12
        cmovne  eax, edx
        ret
</code>```

You'll notice that there's a straight cmp between the two values, without normalizing them first (unlike ifort, that is more conservative in this regard).

Even more interesting: regardless of what the ABI says, ifort by default uses a nonstandard representation for LOGICAL; this is explained in the -fpscomp logicals switch documentation, which also specifies some interesting details about LOGICAL and cross-language compatibility:

Specifies that integers with a non-zero value are treated as true, integers with a zero value are treated as false. The literal constant .TRUE. has an integer value of 1, and the literal constant .FALSE. has an integer value of 0. This representation is used by Intel Fortran releases before Version 8.0 and by Fortran PowerStation.

The default is fpscomp nologicals, which specifies that odd integer values (low bit one) are treated as true and even integer values (low bit zero) are treated as false.

The literal constant .TRUE. has an integer value of -1, and the literal constant .FALSE. has an integer value of 0. This representation is used by Compaq Visual Fortran. The internal representation of LOGICAL values is not specified by the Fortran standard. Programs which use integer values in LOGICAL contexts, or which pass LOGICAL values to procedures written in other languages, are non-portable and may not execute correctly. Intel recommends that you avoid coding practices that depend on the internal representation of LOGICAL values.

(emphasis added)

Now, the internal representation of a LOGICAL normally shouldn't a problem, as, from what I gather, if you play "by the rules" and don't cross language boundaries you aren't going to notice. For a standard compliant program there's no "straight conversion" between INTEGER and LOGICAL; the only way I see you can shove an INTEGER into a LOGICAL seem to be TRANSFER, which is intrinsically non-portable and give no real guarantees, or the non-standard INTEGER <-> LOGICAL conversion on assignment.

The latter one is documented by gfort to always result in nonzero -> .TRUE., zero -> .FALSE., and you can see that in all cases code is generated to make this happen (even though it's convoluted code in case of ifort with the legacy representation), so you cannot seem to shove an arbitrary integer into a LOGICAL in this way.

```<code>logical*1 function integer_to_logical(x)
    integer, intent(in) :: x
    integer_to_logical = x
    return
end function integer_to_logical
</code>```
```<code>integer_to_logical_:
        mov     eax, DWORD PTR [rdi]
        test    eax, eax
        setne   al
        ret
</code>```

The reverse conversion for a LOGICAL*1 is a straight integer zero-extension (gfort), so, to be honoring the contract in the documentation linked above, it's clearly expecting the LOGICAL value to be 0 or 1.

But in general, the situation for these conversions is a bit of a mess, so I'd just stay away from them.

So, long story short: avoid putting INTEGER data into LOGICAL values, as it is bad even in Fortran, and make sure to use the correct compiler flag to get the ABI-compliant representation for booleans, and interoperability with C/C++ should be fine. But to be extra safe, I'd just use plain char on the C++ side.

Finally, from what I gather from the documentation, in ifort there is some builtin support for interoperability with C, including booleans; you may try to leverage it.

Body:
If I get a bool variable and set its second bit to 1, then variable evaluates to true and false at the same time. Compile the following code with gcc6.3 with -g option, (gcc-v6.3.0/Linux/RHEL6.0-2016-x86_64/bin/g++ -g main.cpp -o mytest_d)  and run the executable. You get the following.

How can T be equal to true and false at the same time?

       value   bits
       -----   ----
    T:   1     0001
after bit change
    T:   3     0011
T is true
T is false

This can happen when you call a function in a different language (say fortran) where true and false definition is different than C++. For fortran if any bits are not 0 then the value is true, if all bits are zero then the value is false.

#include <iostream>
#include <bitset>

using namespace std;

void set_bits_to_1(void* val){
  char *x = static_cast<char *>(val);

  for (int i = 0; i<2; i++ ){
    *x |= (1UL << i);
  }
}

int main(int argc,char *argv[])
{

  bool T = 3;

  cout <<"       value   bits " <<endl;
  cout <<"       -----   ---- " <<endl;
  cout <<"    T:   "<< T <<"     "<< bitset<4>(T)<<endl;

  set_bits_to_1(&T);

  bitset<4> bit_T = bitset<4>(T);
  cout <<"after bit change"<<endl;
  cout <<"    T:   "<< T <<"     "<< bit_T<<endl;

  if (T ){
    cout <<"T is true" <<endl;
  }

  if ( T == false){
    cout <<"T is false" <<endl;
  }

}

///////////////////////////////////
// Fortran function that is not compatible with C++ when compiled with ifort.

       logical*1 function return_true()
         implicit none

         return_true = 1;

       end function return_true

Body:
In C++ the bit representation (and even the size) of a bool is implementation defined; generally it's implemented as a char-sized type taking 1 or 0 as possible values.

If you set its value to anything different from the allowed ones (in this specific case by aliasing a bool through a char and modifying its bit representation), you are breaking the rules of the language, so anything can happen. In particular, it's explicitly specified in the standard that a "broken" bool may behave as both true and false (or neither true nor false) at the same time:

Using a bool value in ways described by this International Standard as “undefined,” such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neither true nor false

(C++11, [basic.fundamental], note 47)

In this particular case, you can see how it ended up in this bizarre situation: the first if gets compiled to

    movzx   eax, BYTE PTR [rbp-33]
    test    al, al
    je      .L22

which loads T in eax (with zero extension), and skips the print if it's all zero; the next if instead is

    movzx   eax, BYTE PTR [rbp-33]
    xor     eax, 1
    test    al, al
    je      .L23

The test if(T == false) is transformed to if(T^1), which flips just the low bit. This would be ok for a valid bool, but for your "broken" one it doesn't cut it.

Notice that this bizarre sequence is only generated at low optimization levels; at higher levels this is generally going to boil down to a zero/nonzero check, and a sequence like yours is likely to become a single test/conditional branch. You will get bizarre behavior anyway in other contexts, e.g. when summing bool values to other integers:

int foo(bool b, int i) {
    return i + b;
}

becomes

foo(bool, int):
        movzx   edi, dil
        lea     eax, [rdi+rsi]
        ret

where dil is "trusted" to be 0/1.

If your program is all C++, then the solution is simple: don't break bool values this way, avoid messing with their bit representation and everything will go well; in particular, even if you assign from an integer to a bool the compiler will emit the necessary code to make sure that the resulting value is a valid bool, so your bool T = 3 is indeed safe, and T will end up with a true in its guts.

If instead you need to interoperate with code written in other languages that may not share the same idea of what a bool is, just avoid bool for "boundary" code, and marshal it as an appropriately-sized integer. It will work in conditionals & co. just as fine.

Update about the Fortran/interoperability side of the issue

Disclaimer all I know of Fortran is what I read this morning on standard documents, and that I have some punched cards with Fortran listings that I use as bookmarks, so go easy on me.

First of all, this kind of language interoperability stuff isn't part of the language standards, but of the platform ABI. As we are talking about Linux x86-64, the relevant document is the System V x86-64 ABI.

First of all, nowhere is specified that the C _Bool type (which is defined to be the same as C++ bool at 3.1.2 note †) has any kind of compatibility with Fortran LOGICAL; in particular, at 9.2.2 table 9.2 specifies that "plain" LOGICAL is mapped to signed int. About TYPE*N types it says that

The “TYPE*N” notation specifies that variables or aggregate members of type TYPE shall occupy N bytes of storage.

(ibid.)

There's no equivalent type explicitly specified for LOGICAL*1, and it's understandable: it's not even standard; indeed if you try to compile a Fortran program containing a LOGICAL*1 in Fortran 95 compliant mode you get warnings about it, both by ifort

./example.f90(2): warning #6916: Fortran 95 does not allow this length specification.   [1]

    logical*1, intent(in) :: x

------------^

and by gfort

./example.f90:2:13:
     logical*1, intent(in) :: x
             1
Error: GNU Extension: Nonstandard type declaration LOGICAL*1 at (1)

so the waters are already muddled; so, combining the two rules above, I'd go for signed char to be safe.

However: the ABI also specifies:

The values for type LOGICAL are .TRUE. implemented as 1 and .FALSE.
implemented as 0.

So, if you have a program that stores anything besides 1 and 0 in a LOGICAL value, you are already out of spec on the Fortran side! You say:

A fortran logical*1 has same representation as bool, but in fortran if bits are 00000011 it is true, in C++ it is undefined.

This last statement is not true, the Fortran standard is representation-agnostic, and the ABI explicitly says the contrary. Indeed you can see this in action easily by checking the output of gfort for LOGICAL comparison:

integer function logical_compare(x, y)
    logical, intent(in) :: x
    logical, intent(in) :: y
    if (x .eqv. y) then
        logical_compare = 12
    else
        logical_compare = 24
    end if
end function logical_compare

becomes

logical_compare_:
        mov     eax, DWORD PTR [rsi]
        mov     edx, 24
        cmp     DWORD PTR [rdi], eax
        mov     eax, 12
        cmovne  eax, edx
        ret

You'll notice that there's a straight cmp between the two values, without normalizing them first (unlike ifort, that is more conservative in this regard).

Even more interesting: regardless of what the ABI says, ifort by default uses a nonstandard representation for LOGICAL; this is explained in the -fpscomp logicals switch documentation, which also specifies some interesting details about LOGICAL and cross-language compatibility:

Specifies that integers with a non-zero value are treated as true, integers with a zero value are treated as false. The literal constant .TRUE. has an integer value of 1, and the literal constant .FALSE. has an integer value of 0. This representation is used by Intel Fortran releases before Version 8.0 and by Fortran PowerStation.

The default is fpscomp nologicals, which specifies that odd integer values (low bit one) are treated as true and even integer values (low bit zero) are treated as false.

The literal constant .TRUE. has an integer value of -1, and the literal constant .FALSE. has an integer value of 0. This representation is used by Compaq Visual Fortran. The internal representation of LOGICAL values is not specified by the Fortran standard. Programs which use integer values in LOGICAL contexts, or which pass LOGICAL values to procedures written in other languages, are non-portable and may not execute correctly. Intel recommends that you avoid coding practices that depend on the internal representation of LOGICAL values.

(emphasis added)

Now, the internal representation of a LOGICAL normally shouldn't a problem, as, from what I gather, if you play "by the rules" and don't cross language boundaries you aren't going to notice. For a standard compliant program there's no "straight conversion" between INTEGER and LOGICAL; the only way I see you can shove an INTEGER into a LOGICAL seem to be TRANSFER, which is intrinsically non-portable and give no real guarantees, or the non-standard INTEGER <-> LOGICAL conversion on assignment.

The latter one is documented by gfort to always result in nonzero -> .TRUE., zero -> .FALSE., and you can see that in all cases code is generated to make this happen (even though it's convoluted code in case of ifort with the legacy representation), so you cannot seem to shove an arbitrary integer into a LOGICAL in this way.

logical*1 function integer_to_logical(x)
    integer, intent(in) :: x
    integer_to_logical = x
    return
end function integer_to_logical

integer_to_logical_:
        mov     eax, DWORD PTR [rdi]
        test    eax, eax
        setne   al
        ret

The reverse conversion for a LOGICAL*1 is a straight integer zero-extension (gfort), so, to be honoring the contract in the documentation linked above, it's clearly expecting the LOGICAL value to be 0 or 1.

But in general, the situation for these conversions is a bit of a mess, so I'd just stay away from them.

So, long story short: avoid putting INTEGER data into LOGICAL values, as it is bad even in Fortran, and make sure to use the correct compiler flag to get the ABI-compliant representation for booleans, and interoperability with C/C++ should be fine. But to be extra safe, I'd just use plain char on the C++ side.

Finally, from what I gather from the documentation, in ifort there is some builtin support for interoperability with C, including booleans; you may try to leverage it.


问:
How to Drag my view a little bit up when keyboard comes up?
In my app i have some textfields which gets filled through the keyboard. There are 6 of them and the last two are in very bottom of the screen and it gets hidden whenever keyboard comes up.
Any suggestions??</p>

答:
Use a UIScrollview so the user can scroll down. You can make use of the inputAccessoryView of a UITextField to show buttons like next and previous, on click let the input jump to the next textfield and scroll to it.

Have a look at this question and answers at SO, same problem, different solution.


问:
2 different Firestore interfaces
I've got 2 different firestore interfaces: both using the same firestore project.

I'm finding this abit confusing - which one am I meant to operate in?

How come the 2nd doesn't have access to other settings such as Rules?

答:
Cloud Firestore is available with, or without Firebase SDKs.

For Firebase users, the Firebase interface allows you to configure Firebase specific functionality (Rules).

For GCP users, the Google Cloud interface keeps you closer to other services and admin settings you'll likely be using, such as IAM, BigQuery, etc. It also gives you quick access to a shell (Just click the Cloud Shell icon) so you can quickly run commands like gcloud firestore export.

Both interfaces will show you the same data.

Title: 2 different Firestore interfaces


问:
Changing behavior of EditTextPreference when clicked
I'm trying to change the behavior of a EditTextPreference for my needs.
It hold a path i set using an intent.
My problem is it also open his own Fragment to modify his text.
I end up with 2 consecutives windows: the ACTION_OPEN_DOCUMENT_TREE which i wanted and the default windows to write a simple string in a box.

Here the SettingFragment.java:

```<code>@Override
public  void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    setPreferencesFromResource(R.xml.root_preferences, rootKey);

    Preference editTextPreference = getPreferenceManager().findPreference("path");
    if (editTextPreference != null) {
        editTextPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference arg0) {
                Intent secondActivity = new Intent(ACTION_OPEN_DOCUMENT_TREE);
                startActivityForResult(secondActivity, RQS_OPEN_DOCUMENT_TREE);

                return true;
            }
        });
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE) {
        Uri treeUri = data.getData();
        System.out.println(treeUri.toString());
        String path = FileUtil.getFullPathFromTreeUri(treeUri, getContext());

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        sharedPreferences.edit().putString("path",path).apply();
    }
}
</code>```

Here the associated xml:

```<code><androidx.preference.PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory>
    <EditTextPreference
        app:key="path"
        app:title="@string/path_title"
        app:useSimpleSummaryProvider="true"
    />
</PreferenceCategory>
</code>```

I tried changing EditTextPreference for Preference but the value woulnd't show anymore. I've found out that useSimpleSummaryProvider could only be applied to ListPreference and EditTextPreference.
I also tried to disable it but it would no longer fire onPreferenceClick().
Is there a way to only execute onPreferenceClick rather than the default fragment or a better way to handle this?

答:
try this </p>

```<code>@Override
    public boolean setOnPreferenceClickListener(Preference preference) {
        if(preference.getKey().equals("path")){
           Intent secondActivity = new Intent(ACTION_OPEN_DOCUMENT_TREE);
           startActivityForResult(secondActivity, RQS_OPEN_DOCUMENT_TREE);
            return true;
        }
        return false;
    }
</code>```

Body:
I'm trying to change the behavior of a EditTextPreference for my needs.
It hold a path i set using an intent.
My problem is it also open his own Fragment to modify his text.
I end up with 2 consecutives windows: the ACTION_OPEN_DOCUMENT_TREE which i wanted and the default windows to write a simple string in a box.

Here the SettingFragment.java:

@Override
public  void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    setPreferencesFromResource(R.xml.root_preferences, rootKey);

    Preference editTextPreference = getPreferenceManager().findPreference("path");
    if (editTextPreference != null) {
        editTextPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference arg0) {
                Intent secondActivity = new Intent(ACTION_OPEN_DOCUMENT_TREE);
                startActivityForResult(secondActivity, RQS_OPEN_DOCUMENT_TREE);

                return true;
            }
        });
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE) {
        Uri treeUri = data.getData();
        System.out.println(treeUri.toString());
        String path = FileUtil.getFullPathFromTreeUri(treeUri, getContext());

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        sharedPreferences.edit().putString("path",path).apply();
    }
}

Here the associated xml:

<androidx.preference.PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory>
    <EditTextPreference
        app:key="path"
        app:title="@string/path_title"
        app:useSimpleSummaryProvider="true"
    />
</PreferenceCategory>

I tried changing EditTextPreference for Preference but the value woulnd't show anymore. I've found out that useSimpleSummaryProvider could only be applied to ListPreference and EditTextPreference.
I also tried to disable it but it would no longer fire onPreferenceClick().
Is there a way to only execute onPreferenceClick rather than the default fragment or a better way to handle this?

Body:
try this

@Override
    public boolean setOnPreferenceClickListener(Preference preference) {
        if(preference.getKey().equals("path")){
           Intent secondActivity = new Intent(ACTION_OPEN_DOCUMENT_TREE);
           startActivityForResult(secondActivity, RQS_OPEN_DOCUMENT_TREE);
            return true;
        }
        return false;
    }


问:
How to check if element is clicked when click event is bounded to document
I want to detect the click on the button, but event target is the image instead of the button. So, how can I detect the click on a specific element when one of its children is clicked.

```<code>$(document).on('click', function(event){
    var $this=$('#menu');
    var $that=$('#menu-body');
    if($this.is(event.target)) { // this line does not work correctly
        if($that.is(':hidden')){
            $that.show();
        } else {
            $that.hide();
        }
    } else {
        if(!$(event.target).is($that)){
            $that.hide();
        }
    }
});
</code>```

This code works when the button has no children, but ain't working when an image is inside:

```<code><button id="menu"><img src="pics/menu.png"></button>
</code>```

答:
This is what I would do using plain vanilla Javascript.

Simply check if the element has id="menu", or closest('#menu') finds an element. If either is true, you have a click on #menu or a descendant.

document.addEventListener('click', function(event) {
  if (event.target.id === 'menu' || event.target.closest('#menu')) {
    console.log('clicked #menu or descendant');
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="menu"><img src="pics/menu.png"></button></code>```

Body:
I want to detect the click on the button, but event target is the image instead of the button. So, how can I detect the click on a specific element when one of its children is clicked.

$(document).on('click', function(event){
    var $this=$('#menu');
    var $that=$('#menu-body');
    if($this.is(event.target)) { // this line does not work correctly
        if($that.is(':hidden')){
            $that.show();
        } else {
            $that.hide();
        }
    } else {
        if(!$(event.target).is($that)){
            $that.hide();
        }
    }
});

This code works when the button has no children, but ain't working when an image is inside:

<button id="menu"></button>

Body:
This is what I would do using plain vanilla Javascript.

Simply check if the element has id="menu", or closest('#menu') finds an element. If either is true, you have a click on #menu or a descendant.

document.addEventListener('click', function(event) {
  if (event.target.id === 'menu' || event.target.closest('#menu')) {
    console.log('clicked #menu or descendant');
  }
})

<button id="menu"><img src="pics/menu.png"></button>


问:
How can i change "oe_chatter" log comments in Odoo 10?
I've created a custom module for uploading some documents against an employee in Odoo 10. And now i am trying to use "oe_chatter" for logs purpose.

When i click on save, log is coming as :

Note by Administrator - 2 minutes ago

hr.documents created

How can i change this to "Employee Document is created" ?

This is my code :

```<code>class HrDocuments(models.Model):
    _name = 'hr.documents'
    _inherit = ['mail.thread', 'ir.needaction_mixin']

<div class="oe_chatter">
                        <field name="message_follower_ids" widget="mail_followers" groups="base.group_user"/>
                        <field name="message_ids" widget="mail_thread"/>
</div>
</code>```

答: Just add _description = "Employee Document is created" after _inherit

Body:
I've created a custom module for uploading some documents against an employee in Odoo 10. And now i am trying to use "oe_chatter" for logs purpose.

When i click on save, log is coming as :

Note by Administrator - 2 minutes ago

hr.documents created

How can i change this to "Employee Document is created" ?

This is my code :

class HrDocuments(models.Model):
    _name = 'hr.documents'
    _inherit = ['mail.thread', 'ir.needaction_mixin']

                        <field name="message_follower_ids" widget="mail_followers" groups="base.group_user"/>
                        <field name="message_ids" widget="mail_thread"/>


问:
azure iothub device stops sending messages
I've recently started working with the Azure-Iot-SDK and wonder how to investigate this behaviour.
My application is ok with sending messages to the IoT hub for some time, but suddenly just stops sending. Without an error or anything else that helps me find the rootcause for this. Just restarting the application (a service to be precise) is enough to get it working again.

Code is like this (on DataChangedEvent) :

```<code>try {
    deviceClient = DeviceClient.Create(connectionString, x509Certificate, tType);
    Log("Start sending message")
    await deviceClient.SendEventAsync(message);
    DoLogging("Done sending!");
}
catch (Exception e)
{
    moreLogging("Error occurred");
}
</code>```

Somehow the "Done sending!" message stops appearing in the logs, but the "Start sending message" keeps coming.
Does anyone have any suggestions how to proceed?

答: If you haven't fixed the timeouts, here's a tip for you: try re-creating your IoT Hub in another region ("West US" works stably for me).</p>

Body:
I've recently started working with the Azure-Iot-SDK and wonder how to investigate this behaviour.
My application is ok with sending messages to the IoT hub for some time, but suddenly just stops sending. Without an error or anything else that helps me find the rootcause for this. Just restarting the application (a service to be precise) is enough to get it working again.

Code is like this (on DataChangedEvent) :

try {
    deviceClient = DeviceClient.Create(connectionString, x509Certificate, tType);
    Log("Start sending message")
    await deviceClient.SendEventAsync(message);
    DoLogging("Done sending!");
}
catch (Exception e)
{
    moreLogging("Error occurred");
}

Somehow the "Done sending!" message stops appearing in the logs, but the "Start sending message" keeps coming.
Does anyone have any suggestions how to proceed?


问:
Populate markers and polylines independent of the base tile map used. (An alternative to Leaflet for android)
I want to create a maps application and want the base tile map be changable (google maps, map box, etc). What I want to do is have a transparent layer on top of tile map and draw all markers and paths on that top layer so that no matter which base tile map the user selects, markers and paths remains the same.

I am looking for an alternative to leaflet for android.

答:
Since nearly all of the map programs you will use: Maps, Mapzen, etc all use similar logic of defining your map within the XML Sample 1 or Sample 2 (Below):

```<code><com.google.android.gms.maps.MapView android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />
</code>```

The approach you could use would be to have multiple maps defined in your layout, show or hide them depending upon whatever factors you need, and then utilize data stored within your Activity to populate them.

For example, say you wanted to use Markers like in your question, when you place the marker, grab the latitude (double), longitude (double), and markerId (String), store them into a List / Set of objects in your Activity and then when the map is swapped, you can 'place' the markers again as you have the same required values to draw said markers.

If you want to pull the Latitude and Longitude from Markers clicked, this code has an example of how to do it.

With regards to your paths, you could record start and end latitude / longitude points and re-draw / place them on whichever map is in the visible front.

The same applies to your zoom level and any other misc item you want to store; you just need to find common denominators and use them stored in your dataset to place and re-draw on whichever map is in the foreground.

It really comes down to how you want to manage the data and how you will 'swap' between maps.

Bear in mind that this approach can be fairly CPU intensive if the maps all maintain their data in the background while non-visible. You should likely remove the markers and drawn paths whenever you move the map to invisible or gone.

Body:
Since nearly all of the map programs you will use: Maps, Mapzen, etc all use similar logic of defining your map within the XML Sample 1 or Sample 2 (Below):

<com.google.android.gms.maps.MapView android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

The approach you could use would be to have multiple maps defined in your layout, show or hide them depending upon whatever factors you need, and then utilize data stored within your Activity to populate them.

For example, say you wanted to use Markers like in your question, when you place the marker, grab the latitude (double), longitude (double), and markerId (String), store them into a List / Set of objects in your Activity and then when the map is swapped, you can 'place' the markers again as you have the same required values to draw said markers.

If you want to pull the Latitude and Longitude from Markers clicked, this code has an example of how to do it.

With regards to your paths, you could record start and end latitude / longitude points and re-draw / place them on whichever map is in the visible front.

The same applies to your zoom level and any other misc item you want to store; you just need to find common denominators and use them stored in your dataset to place and re-draw on whichever map is in the foreground.

It really comes down to how you want to manage the data and how you will 'swap' between maps.

Bear in mind that this approach can be fairly CPU intensive if the maps all maintain their data in the background while non-visible. You should likely remove the markers and drawn paths whenever you move the map to invisible or gone.


问:
Problem uploading code to ESP8266: esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for package header
I'm trying to upload the example Blink code to my ESP8266 modules, 1 of which is an ESP8266-07, the other a WeMos D1 mini PRO. I've installed the library for the ESPs according to online instructions. I'm uploading from Ubuntu 16.04, Arduino 1.8.9. I've also made sure to use sudo chmod 666 /dev/ttyUSB0.

I've tried uploading both through a normal USB cable and through a USB-TTL board, both of which made no difference. My Tools > Board settings are "Generic ESP8266 module" for the ESP8266-07 and "LOLIN(WEMOS) D1 mini Pro" for my mini Pro. In all 4 cases (2 different boards, 2 uploading cables/gateways), I've got the same error message.

```<code>raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for package header
</code>```

I've also tried uploading the code to my Node MCU, in which case, I got a different error:

```<code>esptools.FatalError: Invalid head of package (0x46)
</code>```

答:
There are a few different things to check for troubleshooting:

Check what your serial devices are enumerating as. They may be showing up as /dev/ttyACM* rather than /dev/ttyUSB0

Add your user to the  dialout group

```<code>sudo usermod -a -G tty yourUserName
sudo usermod -a -G dialout yourUserName
</code>```

Are you attempting to program through a USB hub? Those sometimes cause strange  power issues that interfere with programming devices. If so, try plugging in directly to a primary USB port.

Body:
I'm trying to upload the example Blink code to my ESP8266 modules, 1 of which is an ESP8266-07, the other a WeMos D1 mini PRO. I've installed the library for the ESPs according to online instructions. I'm uploading from Ubuntu 16.04, Arduino 1.8.9. I've also made sure to use sudo chmod 666 /dev/ttyUSB0.

I've tried uploading both through a normal USB cable and through a USB-TTL board, both of which made no difference. My Tools > Board settings are "Generic ESP8266 module" for the ESP8266-07 and "LOLIN(WEMOS) D1 mini Pro" for my mini Pro. In all 4 cases (2 different boards, 2 uploading cables/gateways), I've got the same error message.

raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for package header

I've also tried uploading the code to my Node MCU, in which case, I got a different error:

esptools.FatalError: Invalid head of package (0x46)

Body:
There are a few different things to check for troubleshooting:

Check what your serial devices are enumerating as. They may be showing up as /dev/ttyACM* rather than /dev/ttyUSB0

Add your user to the  dialout group

sudo usermod -a -G tty yourUserName
sudo usermod -a -G dialout yourUserName

Are you attempting to program through a USB hub? Those sometimes cause strange  power issues that interfere with programming devices. If so, try plugging in directly to a primary USB port.