问:
How to get user id from IdentityServer in client app when including access token?
I have implemented an authentication service based on IdentityServer3 and a simple MVC client app and a Shopper API secured by the authentication service. I've implemented a IdentityServer custom UserService so that the authentication service authenticates against our existing user data store. My Shopper API expects a userid in the Shopper Get request. Currently the response from authentication service includes the identity token and the access token, but no user id. I tried adding a user_id claim in the AuthenticationResult from my custom UserService.AuthenticateLocalAsync method, but I'm not seeing it in my client app code.
UserService.AuthenticateLocalAsync looks like this:

```<code>try
{
    var user = new shopper(_dbConnLib, context.UserName, context.Password);
    var claims = new List<Claim> { new Claim("user_id", user.shopperid) };
    context.AuthenticateResult = new AuthenticateResult(user.shopperid, user.MemberDetail.billToAddress.FirstName, claims);
}
catch(shopperInitFromException ex)
{
    context.AuthenticateResult = null;  // Indicates username/password failure
}
return Task.FromResult(0);
</code>```

And my client app SecurityTokenValidated handler looks like this:

```<code>SecurityTokenValidated = async n =>
{
    var nid = new ClaimsIdentity(
        n.AuthenticationTicket.Identity.AuthenticationType,
        Constants.ClaimTypes.GivenName,
        Constants.ClaimTypes.Role);

    var userInfoClient = new UserInfoClient(
        new Uri(n.Options.Authority + "/connect/userinfo").ToString());

    var userInfo = await userInfoClient.GetAsync(n.ProtocolMessage.AccessToken);
    userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Type, ui.Value)));

    nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

    nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

    //nid.AddClaim(new Claim("user_id", n.ProtocolMessage.UserId));

    nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

    n.AuthenticationTicket = new AuthenticationTicket(
        nid,
        n.AuthenticationTicket.Properties);
}
</code>```

If I step through that in the debugger, userInfo.Claims always has a count of 0. How can I get back a claim with the unique identifier of the user? Or can I get it from the identity or access token? Or should I just pass the tokens to the Shopper API and let it determine the id from the tokens?

答:
I think I may have the answer. So far, as far as I can tell, the claims I include in the AuthenticateResult constructor in my override of AuthenticateLocalAsync don't seem to go anywhere. But the claims I include in my override of GetProfileDataAsync appear in the token. My GetProfileDataAsync code, which appears to set the claims properly, looks like this: </p>

```<code>public override Task GetProfileDataAsync(ProfileDataRequestContext context)
{
    var user = new shopper(_dbConnLib, context.Subject.FindFirst("sub").Value);
    var claims = new List<Claim> { new Claim("sub", user.shopperid), new Claim("acr_level", "level 0"), new Claim("amr", "anonymous") };
    context.IssuedClaims = claims;
    return Task.FromResult(0);
}
</code>```

<p>My AuthenticateLocalAsync code that sets claims in the AuthenticateResult that I never see in my client app code looks like this: </p>

```<code>public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
{
    // TODO: Handle AddshopperToBasketException in UserService.AuthenticateLocalAsync
    try
    {
        var user = new shopper(_dbConnLib, context.UserName, context.Password);
        var claims = new List<Claim> { new Claim("acr_level", "level 0"), new Claim("amr", "anonymous") };
        context.AuthenticateResult = new AuthenticateResult(user.shopperid, user.MemberDetail.billToAddress.FirstName, claims);
    }
    catch(shopperInitFromException ex)
    {
        context.AuthenticateResult = null;  // Indicates username/password failure
    }
    return Task.FromResult(0);
}
</code>```

Body:
I have implemented an authentication service based on IdentityServer3 and a simple MVC client app and a Shopper API secured by the authentication service. I've implemented a IdentityServer custom UserService so that the authentication service authenticates against our existing user data store. My Shopper API expects a userid in the Shopper Get request. Currently the response from authentication service includes the identity token and the access token, but no user id. I tried adding a user_id claim in the AuthenticationResult from my custom UserService.AuthenticateLocalAsync method, but I'm not seeing it in my client app code.
UserService.AuthenticateLocalAsync looks like this:

try
{
    var user = new shopper(_dbConnLib, context.UserName, context.Password);
    var claims = new List<Claim> { new Claim("user_id", user.shopperid) };
    context.AuthenticateResult = new AuthenticateResult(user.shopperid, user.MemberDetail.billToAddress.FirstName, claims);
}
catch(shopperInitFromException ex)
{
    context.AuthenticateResult = null;  // Indicates username/password failure
}
return Task.FromResult(0);

And my client app SecurityTokenValidated handler looks like this:

SecurityTokenValidated = async n =>
{
    var nid = new ClaimsIdentity(
        n.AuthenticationTicket.Identity.AuthenticationType,
        Constants.ClaimTypes.GivenName,
        Constants.ClaimTypes.Role);

    var userInfoClient = new UserInfoClient(
        new Uri(n.Options.Authority + "/connect/userinfo").ToString());

    var userInfo = await userInfoClient.GetAsync(n.ProtocolMessage.AccessToken);
    userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Type, ui.Value)));

    nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

    nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

    //nid.AddClaim(new Claim("user_id", n.ProtocolMessage.UserId));

    nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

    n.AuthenticationTicket = new AuthenticationTicket(
        nid,
        n.AuthenticationTicket.Properties);
}

If I step through that in the debugger, userInfo.Claims always has a count of 0. How can I get back a claim with the unique identifier of the user? Or can I get it from the identity or access token? Or should I just pass the tokens to the Shopper API and let it determine the id from the tokens?

Body:
I think I may have the answer. So far, as far as I can tell, the claims I include in the AuthenticateResult constructor in my override of AuthenticateLocalAsync don't seem to go anywhere. But the claims I include in my override of GetProfileDataAsync appear in the token. My GetProfileDataAsync code, which appears to set the claims properly, looks like this:

public override Task GetProfileDataAsync(ProfileDataRequestContext context)
{
    var user = new shopper(_dbConnLib, context.Subject.FindFirst("sub").Value);
    var claims = new List<Claim> { new Claim("sub", user.shopperid), new Claim("acr_level", "level 0"), new Claim("amr", "anonymous") };
    context.IssuedClaims = claims;
    return Task.FromResult(0);
}

My AuthenticateLocalAsync code that sets claims in the AuthenticateResult that I never see in my client app code looks like this:

public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
{
    // TODO: Handle AddshopperToBasketException in UserService.AuthenticateLocalAsync
    try
    {
        var user = new shopper(_dbConnLib, context.UserName, context.Password);
        var claims = new List<Claim> { new Claim("acr_level", "level 0"), new Claim("amr", "anonymous") };
        context.AuthenticateResult = new AuthenticateResult(user.shopperid, user.MemberDetail.billToAddress.FirstName, claims);
    }
    catch(shopperInitFromException ex)
    {
        context.AuthenticateResult = null;  // Indicates username/password failure
    }
    return Task.FromResult(0);
}


来源: stackexchange

问:
Pass index of apply function to FUN in R or should I do something different?
I am currently trying to loop through my data frame called "test" and get the sum of each of the numbers in each column. ex. sum(test$colname1 = 4) would return 1 because of only one 4 occurrence in the first column. I cannot use count because I have 7 specific numbers I want saved (1-7) even if there were 0 occurrences for a number. Count only returns numbers that have occurred and doesn't show 0 values. My plan is to use the apply function to loop through my columns and do the sum of each of the 7 numbers and save the sums into a value and then return those combined values into a data frame where I can do further calculations. Apply requires a function so I decided to do something like this:

```<code>final_results <- cbind(final_results, apply(test, 2, applyFunction(indexOfApply))

applyFunction <- function(indexofApply) {
temp <- c(sum(indexofApply == 1), sum(indexofApply == 2),
sum(indexofApply == 3), sum(indexofApply == 4),
sum(indexofApply == 5), sum(indexofApply == 6), sum(indexofApply == 7))

return(temp)
}
</code>```

I want my result to look something like this:

 My original data frame looks like this
(column names are confidential)

Is there a way to pass the index of the apply function to my own function like I want to do or is there some much easier way to do this? I am new at R and it feels like there should be a better way to do this. Please explain any answers you give so I can learn. Thank you.

答:
```<code>   # simulating a data set
 df <- data.frame(col1 = sample(1:10, 10, replace = T),
             col2 = sample(1:10, 10, replace = T),
             col3 = sample(1:10, 10, replace = T))

my_vals = 1:7

 # a shell for the results

df2 <- as.data.frame(matrix(rep(0,21), ncol = 3))

for (i in 1:length(my_vals))
{ for (j in 1:ncol(df))
   { df2[i,j] <- sum(df[,j] == my_vals [i])}
}

names(df2) <- names(df)

df2

col1 col2 col3
1    2    0    1
2    0    1    0
3    0    2    1
4    0    0    0
5    1    1    3
6    2    2    2
7    1    3    1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently trying to loop through my data frame called "test" and get the sum of each of the numbers in each column. ex. sum(test$colname1 = 4) would return 1 because of only one 4 occurrence in the first column. I cannot use count because I have 7 specific numbers I want saved (1-7) even if there were 0 occurrences for a number. Count only returns numbers that have occurred and doesn't show 0 values. My plan is to use the apply function to loop through my columns and do the sum of each of the 7 numbers and save the sums into a value and then return those combined values into a data frame where I can do further calculations. Apply requires a function so I decided to do something like this:

final_results <- cbind(final_results, apply(test, 2, applyFunction(indexOfApply))

applyFunction <- function(indexofApply) {
temp <- c(sum(indexofApply == 1), sum(indexofApply == 2),
sum(indexofApply == 3), sum(indexofApply == 4),
sum(indexofApply == 5), sum(indexofApply == 6), sum(indexofApply == 7))

return(temp)
}

I want my result to look something like this:

 My original data frame looks like this
(column names are confidential)

Is there a way to pass the index of the apply function to my own function like I want to do or is there some much easier way to do this? I am new at R and it feels like there should be a better way to do this. Please explain any answers you give so I can learn. Thank you.


问:
Unable to trigger Mention in teams when creating a new group conversation
I can create a new group conversation and have teams recognize my mention (it creates the popup div containing the correct user info for the user's name in the message), but it does not actually trigger a notification activity on mobile or desktop platforms - which is the part I actually need to work.

```<code>var channelData = new Dictionary<string, string>();
channelData["teamsChannelId"] = yourTeamsChannelID;
IMessageActivity newMessage = Activity.CreateMessageActivity();
newMessage.Type = ActivityTypes.Message;
newMessage.Text = "Hello <at>Guy</at>.  This is a newly created reply chain.";

var mention = new Mention();
mention.Mentioned = new ChannelAccount("correctIdGoesHere", "Guy");
mention.Text = "<at>Guy</at>";

newMessage.Entities = new List<Entity>();
newMessage.Entities.Add(mention);

ConversationParameters conversationParams = new ConversationParameters(
    isGroup: true,
    bot: null,
    members: null,
    topicName: "Test Conversation",
    activity: (Activity)newMessage,
    channelData: channelData);
var result = await connector.Conversations.CreateConversationAsync(conversationParams);
</code>```

答: This is indeed a bug and has been entered in our bug database.</p>

Body:
I can create a new group conversation and have teams recognize my mention (it creates the popup div containing the correct user info for the user's name in the message), but it does not actually trigger a notification activity on mobile or desktop platforms - which is the part I actually need to work.

var channelData = new Dictionary<string, string>();
channelData["teamsChannelId"] = yourTeamsChannelID;
IMessageActivity newMessage = Activity.CreateMessageActivity();
newMessage.Type = ActivityTypes.Message;
newMessage.Text = "Hello <at>Guy</at>.  This is a newly created reply chain.";

var mention = new Mention();
mention.Mentioned = new ChannelAccount("correctIdGoesHere", "Guy");
mention.Text = "<at>Guy</at>";

newMessage.Entities = new List<Entity>();
newMessage.Entities.Add(mention);

ConversationParameters conversationParams = new ConversationParameters(
    isGroup: true,
    bot: null,
    members: null,
    topicName: "Test Conversation",
    activity: (Activity)newMessage,
    channelData: channelData);
var result = await connector.Conversations.CreateConversationAsync(conversationParams);


问:
MYSQL delete all records except first and last for a given date
This gives me all the records for a particular switch and port. I would like to delete all except the first and last one for each day.</p>

```<code>/mysql -sN --user=root --password=notmypassword -e
"SELECT * FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  AND (time > '2016-05-31 00:00:00' AND time < '2016-05-31 23:59:59') "
</code>```

答:
Give this a try:</p>

```<code>DELETE
FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
AND port = '0'
AND datatype = 'TxElements'
AND time BETWEEN '2016-05-31 00:00:00' AND '2016-05-31 23:59:59'
AND time NOT IN (
    SELECT MIN(time), MAX(time)
    FROM collector.fibre
    WHERE fabric_switch_name = 'switch-1'
    AND port = '0'
    AND datatype = 'TxElements'
    AND time BETWEEN '2016-05-31 00:00:00' AND '2016-05-31 23:59:59'
)
</code>```

Body:
This gives me all the records for a particular switch and port. I would like to delete all except the first and last one for each day.

/mysql -sN --user=root --password=notmypassword -e
"SELECT * FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  AND (time > '2016-05-31 00:00:00' AND time < '2016-05-31 23:59:59') "

Body:
Give this a try:

DELETE
FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
AND port = '0'
AND datatype = 'TxElements'
AND time BETWEEN '2016-05-31 00:00:00' AND '2016-05-31 23:59:59'
AND time NOT IN (
    SELECT MIN(time), MAX(time)
    FROM collector.fibre
    WHERE fabric_switch_name = 'switch-1'
    AND port = '0'
    AND datatype = 'TxElements'
    AND time BETWEEN '2016-05-31 00:00:00' AND '2016-05-31 23:59:59'
)


问:
ui-router child view being multiple named views or unnamed views
How to configure in ui-router a parent/children relationship where siblings coexist in parent page? I can't make child state multiple named views working.

This is my parent page:parent.html:

```<code><div> I have two child pages:
  child page1 detail: <ui-view /> and
  child page2 detail:<ui-view />.
  I need both pages
</div>
</code>```

I don't know how to or if I should use multiple-named views since multiple named views seem parallel and separable rather than wrapped around by other text like in the code above.

My ui router config:

```<code> $stateProvider
  .state('parent', {
    url: '/parent',
    templateUrl: 'parent.html'

  })
  .state('parent.children', {
    url: '/children',
    views: {
      'child1': {
        templateUrl: 'child1.html'
      },
      'child2': {
        templateUrl: 'child2.html'
      }
    }
  });
</code>```

The unnamed ui-view only allows one child to be plugged in.

See code in
Plunker

答:
The <ui-view>s in your example are incorrect. It's not a self-closing tag and when ui-view is used as the element instead of an attribute directive you need a name attribute to use named views. If you change your parent.html to the following it should work.

```<code><div> I have two child pages:
  child page1 detail: <ui-view name="child1"></ui-view> and
  child page2 detail:<ui-view name="child2"></ui-view>.
  I need both pages
</div>
</code>```

Body:
How to configure in ui-router a parent/children relationship where siblings coexist in parent page? I can't make child state multiple named views working.

This is my parent page:parent.html:

 I have two child pages:
  child page1 detail: <ui-view /> and
  child page2 detail:<ui-view />.
  I need both pages

I don't know how to or if I should use multiple-named views since multiple named views seem parallel and separable rather than wrapped around by other text like in the code above.

My ui router config:

 $stateProvider
  .state('parent', {
    url: '/parent',
    templateUrl: 'parent.html'

  })
  .state('parent.children', {
    url: '/children',
    views: {
      'child1': {
        templateUrl: 'child1.html'
      },
      'child2': {
        templateUrl: 'child2.html'
      }
    }
  });

The unnamed ui-view only allows one child to be plugged in.

See code in
Plunker

Body:
The <ui-view>s in your example are incorrect. It's not a self-closing tag and when ui-view is used as the element instead of an attribute directive you need a name attribute to use named views. If you change your parent.html to the following it should work.

<div> I have two child pages:
  child page1 detail: <ui-view name="child1"></ui-view> and
  child page2 detail:<ui-view name="child2"></ui-view>.
  I need both pages
</div>


问:
A way to extract certain
 tag using BeautifulSoup?
I'm stuck on a current problem extracting the text from a p tag using BS4.

For reference purposes, linked is a screenshot of the HTML.

What I need to extract is specifically the p tag that contains the text, but there are other p tags that exist.

What I currently have is:

```<code>soup2 = BeautifulSoup(response2, 'html.parser')
div = soup2.find("div", {"id": "body"}).find_all('p')
print (div[5])
</code>```

I understand that the find_all creates a list of all p tags, and I could potentially find the list index of the p tag I'm looking for.  However, that presents a problem since I'm performing this extraction multiple times on other pages with a similar HTML layout as in the picture.  As in, not every find_all list will have the p tag text I'm looking for as the 5th index.

Any suggestions?

答:
find_all accepts many arguments.

you can use them to better filter the results.

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all

you can also iterate over all the elements and find the most likely one.

create a sample of 100 html pages, and find a method/mix of strategies that works for all of them.

Title: A way to extract certain <p> tag using BeautifulSoup?

Body:
I'm stuck on a current problem extracting the text from a p tag using BS4.

For reference purposes, linked is a screenshot of the HTML.

What I need to extract is specifically the p tag that contains the text, but there are other p tags that exist.

What I currently have is:

soup2 = BeautifulSoup(response2, 'html.parser')
div = soup2.find("div", {"id": "body"}).find_all('p')
print (div[5])

I understand that the find_all creates a list of all p tags, and I could potentially find the list index of the p tag I'm looking for.  However, that presents a problem since I'm performing this extraction multiple times on other pages with a similar HTML layout as in the picture.  As in, not every find_all list will have the p tag text I'm looking for as the 5th index.

Any suggestions?


问:
Python palindrome code doesn't return anything
Why?
It returns:

```<code>  if word[0] != word[-1]:
IndexError: list index out of range
</code>```

If I change "print "Palindrome"" to "return True" and "return False" it returns nothing at all.

```<code>import sys

exstring = "f"
data = list(exstring)

def palindrome(word):
    if len(word) < 2:
        print "Palindrome"
    if word[0] != word[-1]:
        print "Not Palindrome"
    return palindrome(word[1:-1])

palindrome(data)
</code>```

答:
What you want to do is this:

```<code>def palindrome(word):
    if len(word) < 2:
        return True
    if word[0] != word[-1]:
        return False
    return palindrome(word[1:-1])
</code>```

You do not need elif in this case. It's just good practice. The second if statement will not be reached unless the first is false anyway. More "correct" (but still completely equivalent) is:

```<code>def palindrome(word):
    if len(word) < 2:
        return True
    elif word[0] != word[-1]:
        return False
    else
        return palindrome(word[1:-1])
</code>```

Furthermore, it's good practice to only let the function decide if it's a palindrome or not, and not print it. Instead, you should use it like this:

```<code>if palindrome(word):
    print "Palindrome"
else
    print "Not palindrome"
</code>```

Don't mix functionality unless you have a good reason.

Body:
Why?
It returns:

  if word[0] != word[-1]:
IndexError: list index out of range

If I change "print "Palindrome"" to "return True" and "return False" it returns nothing at all.

import sys

exstring = "f"
data = list(exstring)

def palindrome(word):
    if len(word) < 2:
        print "Palindrome"
    if word[0] != word[-1]:
        print "Not Palindrome"
    return palindrome(word[1:-1])

palindrome(data)

Body:
What you want to do is this:

def palindrome(word):
    if len(word) < 2:
        return True
    if word[0] != word[-1]:
        return False
    return palindrome(word[1:-1])

You do not need elif in this case. It's just good practice. The second if statement will not be reached unless the first is false anyway. More "correct" (but still completely equivalent) is:

def palindrome(word):
    if len(word) < 2:
        return True
    elif word[0] != word[-1]:
        return False
    else
        return palindrome(word[1:-1])

Furthermore, it's good practice to only let the function decide if it's a palindrome or not, and not print it. Instead, you should use it like this:

if palindrome(word):
    print "Palindrome"
else
    print "Not palindrome"

Don't mix functionality unless you have a good reason.


问:
How to create a Spring Reactor Flux from a ActiveMQ queue?
I am experimenting with the Spring Reactor 3 components and Spring Integration to create a reactive stream (Flux) from a JMS queue.

I am attempting to create a reactive stream (Spring Reactor 3 Flux) from a JMS queue (ActiveMQ using Spring Integration) for clients to get the JMS messages asynchronously. I believe that I have everything hooked up correctly but the client does not receive any of the JMS messages until the server is stopped. Then all of the messages get "pushed" to the client a once.

Any help would be appreciated.

Here is the configuration file that I am using to configure the JMS, Integration components and the reactive publisher:

```<code>@Configuration
@EnableJms
@EnableIntegration
public class JmsConfiguration {

    @Value("${spring.activemq.broker-url:tcp://localhost:61616}")
    private String defaultBrokerUrl;

    @Value("${queues.patient:patient}")
    private String patientQueue;

    @Autowired
    MessageListenerAdapter messageListenerAdapter;

    @Bean
    public DefaultJmsListenerContainerFactory myFactory(
            DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory =
                new DefaultJmsListenerContainerFactory();
        configurer.configure(factory, jmsConnectionFactory());
        return factory;
    }

    @Bean
    public Queue patientQueue() {
        return new ActiveMQQueue(patientQueue);

    }

    @Bean
    public ActiveMQConnectionFactory jmsConnectionFactory() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL(defaultBrokerUrl);
        connectionFactory.setTrustedPackages(Arrays.asList("com.sapinero"));
        return connectionFactory;
    }

    // Set the jackson message converter
    @Bean
    public JmsTemplate jmsTemplate() {
        JmsTemplate template = new JmsTemplate();
        template.setConnectionFactory(jmsConnectionFactory());
        template.setDefaultDestinationName(patientQueue);
        template.setMessageConverter(jacksonJmsMessageConverter());
        return template;
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter() {
        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter();
        messageListenerAdapter.setMessageConverter(jacksonJmsMessageConverter());
        return messageListenerAdapter;
    }

    @Bean
    public AbstractMessageListenerContainer messageListenerContainer() {
        DefaultMessageListenerContainer defaultMessageListenerContainer = new DefaultMessageListenerContainer();
        defaultMessageListenerContainer.setMessageConverter(jacksonJmsMessageConverter());
        defaultMessageListenerContainer.setConnectionFactory(jmsConnectionFactory());
        defaultMessageListenerContainer.setDestinationName(patientQueue);
        defaultMessageListenerContainer.setMessageListener(messageListenerAdapter());
        defaultMessageListenerContainer.setCacheLevel(100);
        defaultMessageListenerContainer.setErrorHandler(new ErrorHandler() {
            @Override
            public void handleError(Throwable t) {
                t.printStackTrace();
            }
        });

        return defaultMessageListenerContainer;
    }

    @Bean // Serialize message content to json using TextMessage
    public MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");
        return converter;
    }

    @Bean
    public MessageChannel jmsOutboundInboundReplyChannel() {
        return MessageChannels.queue().get();
    }

    @Bean
    public Publisher<Message<String>> pollableReactiveFlow() {
        return IntegrationFlows
                .from(Jms.messageDrivenChannelAdapter(messageListenerContainer()).get())
                .channel(MessageChannels.queue())
                .log(LoggingHandler.Level.DEBUG)
                .log()
                .toReactivePublisher();
    }

    @Bean
    public MessageChannel jmsChannel() {
        return new DirectChannel();
    }
</code>```

The controller that creates the Flux is:

```<code>@RestController
@RequestMapping("patients")
public class PatientChangePushController {
    private LocalDateTime lastTimePatientDataRetrieved = LocalDateTime.now();
    private int durationInSeconds = 30;
    private Patient patient;
    AtomicReference<SignalType> checkFinally = new AtomicReference<>();

    @Autowired
    PatientService patientService;

    @Autowired
    @Qualifier("pollableReactiveFlow")
    private
    Publisher<Message<String>> pollableReactiveFlow;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private Queue patientQueue;

    /**
     * Subscribe to a Flux of a patient that has been updated.
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}/alerts", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Message<String>> getPatientAlerts(@PathVariable Long id) {

        Flux<Message<String>> messageFlux = Flux.from(pollableReactiveFlow);
        return messageFlux;
    }

    @GetMapping(value = "/generate")
    public void generateJmsMessage() {
        for (long i = 0L; i < 100; i++) {
            Patient patient = new Patient();
            patient.setId(i);
            send(patient);
            System.out.println("Message was sent to the Queue");
        }

    }

    void send(Patient patient) {
        this.jmsTemplate.convertAndSend(this.patientQueue, patient);
    }

}
</code>```

If anyone can tell me why the messages do not get sent to the client until after the server is killed, I would appreciate it.

答:
Works well for me:

```<code>@SpringBootApplication
@RestController
public class SpringIntegrationSseDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringIntegrationSseDemoApplication.class, args);
    }

    @Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Bean
    public Publisher<Message<String>> jmsReactiveSource() {
        return IntegrationFlows
                .from(Jms.messageDrivenChannelAdapter(this.connectionFactory)
                        .destination("testQueue"))
                .channel(MessageChannels.queue())
                .log(LoggingHandler.Level.DEBUG)
                .log()
                .toReactivePublisher();
    }

    @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> getPatientAlerts() {
        return Flux.from(jmsReactiveSource())
                .map(Message::getPayload);
    }

    @GetMapping(value = "/generate")
    public void generateJmsMessage() {
        for (int i = 0; i < 100; i++) {
            this.jmsTemplate.convertAndSend("testQueue", "testMessage #" + (i + 1));
        }
    }

}
</code>```

In one terminal I have curl http://localhost:8080/events which waits for SSEs from that Flux.

In other terminal I perform curl http://localhost:8080/generate and see in the first one:

```<code>data:testMessage #1

data:testMessage #2

data:testMessage #3

data:testMessage #4
</code>```

I use Spring Boot 2.0.0.BUILD-SNAPSHOT.

Also see here: https://spring.io/blog/2017/03/08/spring-tips-server-sent-events-sse

Body:
I am experimenting with the Spring Reactor 3 components and Spring Integration to create a reactive stream (Flux) from a JMS queue.

I am attempting to create a reactive stream (Spring Reactor 3 Flux) from a JMS queue (ActiveMQ using Spring Integration) for clients to get the JMS messages asynchronously. I believe that I have everything hooked up correctly but the client does not receive any of the JMS messages until the server is stopped. Then all of the messages get "pushed" to the client a once.

Any help would be appreciated.

Here is the configuration file that I am using to configure the JMS, Integration components and the reactive publisher:

@Configuration
@EnableJms
@EnableIntegration
public class JmsConfiguration {

    @Value("${spring.activemq.broker-url:tcp://localhost:61616}")
    private String defaultBrokerUrl;

    @Value("${queues.patient:patient}")
    private String patientQueue;

    @Autowired
    MessageListenerAdapter messageListenerAdapter;

    @Bean
    public DefaultJmsListenerContainerFactory myFactory(
            DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory =
                new DefaultJmsListenerContainerFactory();
        configurer.configure(factory, jmsConnectionFactory());
        return factory;
    }

    @Bean
    public Queue patientQueue() {
        return new ActiveMQQueue(patientQueue);

    }

    @Bean
    public ActiveMQConnectionFactory jmsConnectionFactory() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL(defaultBrokerUrl);
        connectionFactory.setTrustedPackages(Arrays.asList("com.sapinero"));
        return connectionFactory;
    }

    // Set the jackson message converter
    @Bean
    public JmsTemplate jmsTemplate() {
        JmsTemplate template = new JmsTemplate();
        template.setConnectionFactory(jmsConnectionFactory());
        template.setDefaultDestinationName(patientQueue);
        template.setMessageConverter(jacksonJmsMessageConverter());
        return template;
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter() {
        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter();
        messageListenerAdapter.setMessageConverter(jacksonJmsMessageConverter());
        return messageListenerAdapter;
    }

    @Bean
    public AbstractMessageListenerContainer messageListenerContainer() {
        DefaultMessageListenerContainer defaultMessageListenerContainer = new DefaultMessageListenerContainer();
        defaultMessageListenerContainer.setMessageConverter(jacksonJmsMessageConverter());
        defaultMessageListenerContainer.setConnectionFactory(jmsConnectionFactory());
        defaultMessageListenerContainer.setDestinationName(patientQueue);
        defaultMessageListenerContainer.setMessageListener(messageListenerAdapter());
        defaultMessageListenerContainer.setCacheLevel(100);
        defaultMessageListenerContainer.setErrorHandler(new ErrorHandler() {
            @Override
            public void handleError(Throwable t) {
                t.printStackTrace();
            }
        });

        return defaultMessageListenerContainer;
    }

    @Bean // Serialize message content to json using TextMessage
    public MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");
        return converter;
    }

    @Bean
    public MessageChannel jmsOutboundInboundReplyChannel() {
        return MessageChannels.queue().get();
    }

    @Bean
    public Publisher<Message<String>> pollableReactiveFlow() {
        return IntegrationFlows
                .from(Jms.messageDrivenChannelAdapter(messageListenerContainer()).get())
                .channel(MessageChannels.queue())
                .log(LoggingHandler.Level.DEBUG)
                .log()
                .toReactivePublisher();
    }

    @Bean
    public MessageChannel jmsChannel() {
        return new DirectChannel();
    }

The controller that creates the Flux is:

@RestController
@RequestMapping("patients")
public class PatientChangePushController {
    private LocalDateTime lastTimePatientDataRetrieved = LocalDateTime.now();
    private int durationInSeconds = 30;
    private Patient patient;
    AtomicReference<SignalType> checkFinally = new AtomicReference<>();

    @Autowired
    PatientService patientService;

    @Autowired
    @Qualifier("pollableReactiveFlow")
    private
    Publisher<Message<String>> pollableReactiveFlow;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private Queue patientQueue;

    /**
     * Subscribe to a Flux of a patient that has been updated.
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}/alerts", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Message<String>> getPatientAlerts(@PathVariable Long id) {

        Flux<Message<String>> messageFlux = Flux.from(pollableReactiveFlow);
        return messageFlux;
    }

    @GetMapping(value = "/generate")
    public void generateJmsMessage() {
        for (long i = 0L; i < 100; i++) {
            Patient patient = new Patient();
            patient.setId(i);
            send(patient);
            System.out.println("Message was sent to the Queue");
        }

    }

    void send(Patient patient) {
        this.jmsTemplate.convertAndSend(this.patientQueue, patient);
    }

}

If anyone can tell me why the messages do not get sent to the client until after the server is killed, I would appreciate it.

Body:
Works well for me:

@SpringBootApplication
@RestController
public class SpringIntegrationSseDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringIntegrationSseDemoApplication.class, args);
    }

    @Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Bean
    public Publisher<Message<String>> jmsReactiveSource() {
        return IntegrationFlows
                .from(Jms.messageDrivenChannelAdapter(this.connectionFactory)
                        .destination("testQueue"))
                .channel(MessageChannels.queue())
                .log(LoggingHandler.Level.DEBUG)
                .log()
                .toReactivePublisher();
    }

    @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> getPatientAlerts() {
        return Flux.from(jmsReactiveSource())
                .map(Message::getPayload);
    }

    @GetMapping(value = "/generate")
    public void generateJmsMessage() {
        for (int i = 0; i < 100; i++) {
            this.jmsTemplate.convertAndSend("testQueue", "testMessage #" + (i + 1));
        }
    }

}

In one terminal I have curl http://localhost:8080/events which waits for SSEs from that Flux.

In other terminal I perform curl http://localhost:8080/generate and see in the first one:

data:testMessage #1

data:testMessage #2

data:testMessage #3

data:testMessage #4

I use Spring Boot 2.0.0.BUILD-SNAPSHOT.

Also see here: https://spring.io/blog/2017/03/08/spring-tips-server-sent-events-sse


问:
HttpClient in an NLog target
I need to create a Target that uses HttpClient. HttpClient does not contain any synchronous methods, they are all Task returning Async calls. What is the best way to use this in an NLog target, seeing as the api does not seem to be async/await aware?</p>

答:
Update NLog 4.6

NLog 4.6 introduces AsyncTaskTarget that ensures correct ordering, and also makes it easy to perform batching.

Old answer:

Maybe something like this should work:

```<code>public class CustomTarget : Target
{

protected override async void Write(NLog.Common.AsyncLogEventInfo logEvent)
{
    try
    {
           await WriteAsync(logEvent.LogEvent).ConfigureAwait(false);
           logEvent.Continuation(null);
    }
    catch (Exception ex)
    {
          InternalLogger.Error(ex, "Failed to sent message");
          logEvent.Continuation(ex);
    }
}

}
</code>```

Or steal the code from this PR: https://github.com/NLog/NLog/pull/2006

Title: HttpClient in an NLog target

Body:
Update NLog 4.6

NLog 4.6 introduces AsyncTaskTarget that ensures correct ordering, and also makes it easy to perform batching.

Old answer:

Maybe something like this should work:

public class CustomTarget : Target
{

protected override async void Write(NLog.Common.AsyncLogEventInfo logEvent)
{
    try
    {
           await WriteAsync(logEvent.LogEvent).ConfigureAwait(false);
           logEvent.Continuation(null);
    }
    catch (Exception ex)
    {
          InternalLogger.Error(ex, "Failed to sent message");
          logEvent.Continuation(ex);
    }
}

}

Or steal the code from this PR: https://github.com/NLog/NLog/pull/2006

ContentLicense: CC BY-SA 4.0


问:
Eclipse: how to launch URL with fragment?
In Eclipse, is there a way to launch a URL that contains fragment (C:\...\something.html#fragment)? Eclipse returns this error:

```<code>An internal error occurred during: "Launching MyApplication".
URI has a fragment component
</code>```

答: The only way that seems to work is to start a local web server and launch the URL as http://... It is a bit a of a hassle but fragments don't seem to work for local files although they are fully supported in browsers.</p>

ContentLicense: CC BY-SA 2.5

Body:
In Eclipse, is there a way to launch a URL that contains fragment (C:\...\something.html#fragment)? Eclipse returns this error:

An internal error occurred during: "Launching MyApplication".
URI has a fragment component


问:
Writing a const and non-const variant of a function
I implemented a rather complex functions, but for the sake of a minimal example, let's stick with this:

```<code>(const) char * my_function((const) char *input) {
  return input;
}
</code>```

The problem arises when I need to call the function one time with a const and once with a non-const value:

```<code>const char *a = "ABC";
char b[3];

// The following fails without using const in the declaration of my_function
const char *result_a = my_function(a);

// The following fails when using const in the declaration of my_function
char *result_b = my_function(b);
</code>```

Can this problem be solved in plain C without repeating the same function with different names?

I know this can be done with a second file or an incredibly long #define, but is there an elegant solution?

答:
If within the function the string pointed to by the parameter is not being changed then the function definition can look like

```<code>char * my_function( const char *input )
{
    // ...
    return ( char * )input;
}
</code>```

Thus you can write

```<code>const char *a = "ABC";
char b[3];

const char *result_a = my_function(a);
char *result_b = my_function(b);
</code>```

That is it is the responsibility of the user of the function to process correctly the returned object.

This approach is used in most standard C string functions.

For example

```<code>char *strstr(const char *s1, const char *s2);
</code>```

Body:
I implemented a rather complex functions, but for the sake of a minimal example, let's stick with this:

(const) char * my_function((const) char *input) {
  return input;
}

The problem arises when I need to call the function one time with a const and once with a non-const value:

const char *a = "ABC";
char b[3];

// The following fails without using const in the declaration of my_function
const char *result_a = my_function(a);

// The following fails when using const in the declaration of my_function
char *result_b = my_function(b);

Can this problem be solved in plain C without repeating the same function with different names?

I know this can be done with a second file or an incredibly long #define, but is there an elegant solution?

Body:
If within the function the string pointed to by the parameter is not being changed then the function definition can look like

char * my_function( const char *input )
{
    // ...
    return ( char * )input;
}

Thus you can write

const char *a = "ABC";
char b[3];

const char *result_a = my_function(a);
char *result_b = my_function(b);

That is it is the responsibility of the user of the function to process correctly the returned object.

This approach is used in most standard C string functions.

For example

char *strstr(const char *s1, const char *s2);


问:
IndexOutOfBoundsException while updating a ListView in JavaFX
I got a problem with an IndexOutOfBoundsException while I want to update a ListView in JavaFX.

What I need to do

I have a ListView with elements that correspond to a small simulation. With a click on one list-element the graphical simulation updates based on the click a element of the ListView. Afterwards the ListView needs a update and other elements will be shown. That means all old elements will be removed and only the new ones will be shown.

My code looks like that:

```<code>public void init() {
    // simCont.initSimulation() returns ArrayList
    ObservableList<Default> obsDefaultList = FXCollections
            .observableArrayList(simCont.initSimulation());
    listTest.getItems().addAll(obsDefaultList);
    listTest.getSelectionModel().selectedItemProperty()
            .addListener(new ChangeListener<Default>() {

                @Override
                public void changed(
                        ObservableValue<? extends Default> observable,
                        Default oldValue, Default newValue) {
                    updateList(newValue);
                }
            });
}

private void updateList(Default chosen) {
    ObservableList<Default> list = FXCollections
            .observableArrayList(simCont.doSimulationStep(chosen.getId()));
    listTest.getItems().clear();
    listTest.getItems().addAll(list);
}
</code>```

At first there are two elements shown. When I click on one of them the ListView updates but I get an IndexOutOfBoundsException.

```<code>Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException
at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.subList(ReadOnlyUnbackedObservableList.java:136)
at javafx.collections.ListChangeListener$Change.getAddedSubList(ListChangeListener.java:242)
at com.sun.javafx.scene.control.behavior.ListViewBehavior.lambda$new$174(ListViewBehavior.java:258)
at com.sun.javafx.scene.control.behavior.ListViewBehavior$$Lambda$145/442103778.onChanged(Unknown Source)
at javafx.collections.WeakListChangeListener.onChanged(WeakListChangeListener.java:88)
at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.callObservers(ReadOnlyUnbackedObservableList.java:75)
at javafx.scene.control.MultipleSelectionModelBase.clearAndSelect(MultipleSelectionModelBase.java:331)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.simpleSelect(CellBehaviorBase.java:242)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.doSelect(CellBehaviorBase.java:206)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.mousePressed(CellBehaviorBase.java:132)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:95)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3724)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
at com.sun.glass.ui.View.notifyMouse(View.java:925)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/1109371569.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)

Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at de.hhn.unitylab.controller.SimulationController.doSimulationStep(SimulationController.java:65)
at de.hhn.unitylab.ui.SimulatorViewController.updateList(SimulatorViewController.java:107)
at de.hhn.unitylab.ui.SimulatorViewController.access$0(SimulatorViewController.java:105)
at de.hhn.unitylab.ui.SimulatorViewController$1.changed(SimulatorViewController.java:94)
at de.hhn.unitylab.ui.SimulatorViewController$1.changed(SimulatorViewController.java:1)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyObjectWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyObjectWrapper.java:176)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:142)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:145)
at javafx.scene.control.SelectionModel.setSelectedItem(SelectionModel.java:102)
at javafx.scene.control.MultipleSelectionModelBase.lambda$new$34(MultipleSelectionModelBase.java:67)
at javafx.scene.control.MultipleSelectionModelBase$$Lambda$127/2138925075.invalidated(Unknown Source)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyIntegerWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:176)
at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:142)
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:113)
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:146)
at javafx.scene.control.SelectionModel.setSelectedIndex(SelectionModel.java:68)
at javafx.scene.control.MultipleSelectionModelBase.select(MultipleSelectionModelBase.java:357)
at javafx.scene.control.ListView.lambda$new$156(ListView.java:374)
at javafx.scene.control.ListView$$Lambda$126/1092624378.invalidated(Unknown Source)
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:349)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyBooleanPropertyBase.fireValueChangedEvent(ReadOnlyBooleanPropertyBase.java:72)
at javafx.scene.Node$FocusedProperty.notifyListeners(Node.java:7526)
at javafx.scene.Scene$13.invalidated(Scene.java:2046)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:111)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:145)
at javafx.scene.Scene$KeyHandler.setFocusOwner(Scene.java:3891)
at javafx.scene.Scene$KeyHandler.requestFocus(Scene.java:3938)
at javafx.scene.Scene$KeyHandler.access$1900(Scene.java:3877)
at javafx.scene.Scene.requestFocus(Scene.java:2010)
at javafx.scene.Node.requestFocus(Node.java:7687)
at com.sun.javafx.scene.control.behavior.ListViewBehavior.mousePressed(ListViewBehavior.java:360)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:95)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3724)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
at com.sun.glass.ui.View.notifyMouse(View.java:925)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/1109371569.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
</code>```

Debugging was confusing because I found no reason for the exception.
I searched the web but found nothing that worked for me. Hopefully somebody can help me with that issue.

答:
I think you are in the similar situation of this answer:JavaFX ComboBox change value causes IndexOutOfBoundsException

try

```<code>Platform.runLater(() -> updateList(newValue) )
</code>```

instead of updateList(newValue)

Body:
I got a problem with an IndexOutOfBoundsException while I want to update a ListView in JavaFX.

What I need to do

I have a ListView with elements that correspond to a small simulation. With a click on one list-element the graphical simulation updates based on the click a element of the ListView. Afterwards the ListView needs a update and other elements will be shown. That means all old elements will be removed and only the new ones will be shown.

My code looks like that:

public void init() {
    // simCont.initSimulation() returns ArrayList
    ObservableList<Default> obsDefaultList = FXCollections
            .observableArrayList(simCont.initSimulation());
    listTest.getItems().addAll(obsDefaultList);
    listTest.getSelectionModel().selectedItemProperty()
            .addListener(new ChangeListener<Default>() {

                @Override
                public void changed(
                        ObservableValue<? extends Default> observable,
                        Default oldValue, Default newValue) {
                    updateList(newValue);
                }
            });
}

private void updateList(Default chosen) {
    ObservableList<Default> list = FXCollections
            .observableArrayList(simCont.doSimulationStep(chosen.getId()));
    listTest.getItems().clear();
    listTest.getItems().addAll(list);
}

At first there are two elements shown. When I click on one of them the ListView updates but I get an IndexOutOfBoundsException.

Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException
at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.subList(ReadOnlyUnbackedObservableList.java:136)
at javafx.collections.ListChangeListener$Change.getAddedSubList(ListChangeListener.java:242)
at com.sun.javafx.scene.control.behavior.ListViewBehavior.lambda$new$174(ListViewBehavior.java:258)
at com.sun.javafx.scene.control.behavior.ListViewBehavior$$Lambda$145/442103778.onChanged(Unknown Source)
at javafx.collections.WeakListChangeListener.onChanged(WeakListChangeListener.java:88)
at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.callObservers(ReadOnlyUnbackedObservableList.java:75)
at javafx.scene.control.MultipleSelectionModelBase.clearAndSelect(MultipleSelectionModelBase.java:331)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.simpleSelect(CellBehaviorBase.java:242)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.doSelect(CellBehaviorBase.java:206)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.mousePressed(CellBehaviorBase.java:132)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:95)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3724)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
at com.sun.glass.ui.View.notifyMouse(View.java:925)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/1109371569.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)

Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at de.hhn.unitylab.controller.SimulationController.doSimulationStep(SimulationController.java:65)
at de.hhn.unitylab.ui.SimulatorViewController.updateList(SimulatorViewController.java:107)
at de.hhn.unitylab.ui.SimulatorViewController.access$0(SimulatorViewController.java:105)
at de.hhn.unitylab.ui.SimulatorViewController$1.changed(SimulatorViewController.java:94)
at de.hhn.unitylab.ui.SimulatorViewController$1.changed(SimulatorViewController.java:1)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyObjectWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyObjectWrapper.java:176)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:142)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:145)
at javafx.scene.control.SelectionModel.setSelectedItem(SelectionModel.java:102)
at javafx.scene.control.MultipleSelectionModelBase.lambda$new$34(MultipleSelectionModelBase.java:67)
at javafx.scene.control.MultipleSelectionModelBase$$Lambda$127/2138925075.invalidated(Unknown Source)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyIntegerWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:176)
at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:142)
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:113)
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:146)
at javafx.scene.control.SelectionModel.setSelectedIndex(SelectionModel.java:68)
at javafx.scene.control.MultipleSelectionModelBase.select(MultipleSelectionModelBase.java:357)
at javafx.scene.control.ListView.lambda$new$156(ListView.java:374)
at javafx.scene.control.ListView$$Lambda$126/1092624378.invalidated(Unknown Source)
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:349)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyBooleanPropertyBase.fireValueChangedEvent(ReadOnlyBooleanPropertyBase.java:72)
at javafx.scene.Node$FocusedProperty.notifyListeners(Node.java:7526)
at javafx.scene.Scene$13.invalidated(Scene.java:2046)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:111)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:145)
at javafx.scene.Scene$KeyHandler.setFocusOwner(Scene.java:3891)
at javafx.scene.Scene$KeyHandler.requestFocus(Scene.java:3938)
at javafx.scene.Scene$KeyHandler.access$1900(Scene.java:3877)
at javafx.scene.Scene.requestFocus(Scene.java:2010)
at javafx.scene.Node.requestFocus(Node.java:7687)
at com.sun.javafx.scene.control.behavior.ListViewBehavior.mousePressed(ListViewBehavior.java:360)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:95)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3724)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
at com.sun.glass.ui.View.notifyMouse(View.java:925)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/1109371569.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)

Debugging was confusing because I found no reason for the exception.
I searched the web but found nothing that worked for me. Hopefully somebody can help me with that issue.

Body:
I think you are in the similar situation of this answer:JavaFX ComboBox change value causes IndexOutOfBoundsException

try

Platform.runLater(() -> updateList(newValue) )

instead of updateList(newValue)


问:
Hibernate program still running
My small program terminates properly if i do not <s>begin a transaction</s> save to a transaction.

```<code>public static void main(String[] args){
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction t = null;

    try{
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        session = sessionFactory.openSession();

        session.beginTransaction();
        session.save(new UserInfo("garb@junkHeap.com", "password2", "erical garb"));
        t = session.getTransaction();
        t.commit();
    }
    catch (Exception e){
        System.out.println("Could not create connection!");
        e.printStackTrace();
    }
    finally{

        DAOUtilities.closeResource(session, "Session");
        DAOUtilities.closeResource(sessionFactory, "sessionFactory");
        StandardServiceRegistryBuilder.destroy(registry);

        System.out.println("Session open: " + session.isOpen());
        System.out.println("Factory open: " + sessionFactory.isOpen());
        System.out.println("Transaction active: " + t.isActive());
    }
}
</code>```

The print statements confirm that session and sessionFactory were successfully closed and the transaction is no longer active. To my knowledge there is no way to check if registry was successfully destroyed. Here is the output...

```<code>Hibernate: insert into UserInfo (loggedIn, name, password, email) values (?, ?, ?, ?)
Mar 24, 2017 12:37:49 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:postgresql://localhost:5432/hibernatedb]
Session open: false
Factory open: false
Transaction active: false
</code>```

What am I missing? Any suggestions would be appriciated, Thank you.

NOTE: My database gui is detecting a one session leak per execution and changes are accurately reflected in database.

答:
I found the problem it existed in a database verification function I implemented a long time ago. Since open postgres sessions did not prevent my program from terminating I overlooked the error.

I implemented a session leak detector I found at https://vladmihalcea.com/the-best-way-to-detect-database-connection-leaks/

The confidence it gave me in issue allowed me to find the culprit. I highly recommend implementing such a test in all programs utilizing a database. I wish I had known about this tool when I began the project, It would have saved me a lot of time. Hopefully this post will save others the time I have lost.

Title: Hibernate program still running

Body:
My small program terminates properly if i do not <s>begin a transaction</s> save to a transaction.

public static void main(String[] args){
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction t = null;

    try{
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        session = sessionFactory.openSession();

        session.beginTransaction();
        session.save(new UserInfo("garb@junkHeap.com", "password2", "erical garb"));
        t = session.getTransaction();
        t.commit();
    }
    catch (Exception e){
        System.out.println("Could not create connection!");
        e.printStackTrace();
    }
    finally{

        DAOUtilities.closeResource(session, "Session");
        DAOUtilities.closeResource(sessionFactory, "sessionFactory");
        StandardServiceRegistryBuilder.destroy(registry);

        System.out.println("Session open: " + session.isOpen());
        System.out.println("Factory open: " + sessionFactory.isOpen());
        System.out.println("Transaction active: " + t.isActive());
    }
}

The print statements confirm that session and sessionFactory were successfully closed and the transaction is no longer active. To my knowledge there is no way to check if registry was successfully destroyed. Here is the output...

Hibernate: insert into UserInfo (loggedIn, name, password, email) values (?, ?, ?, ?)
Mar 24, 2017 12:37:49 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:postgresql://localhost:5432/hibernatedb]
Session open: false
Factory open: false
Transaction active: false

What am I missing? Any suggestions would be appriciated, Thank you.

NOTE: My database gui is detecting a one session leak per execution and changes are accurately reflected in database.


问:
unregister ejabbered user with fabiang php
i use fabiang php example (https://github.com/fabiang/xmpp/blob/master/example.php) to successfully register new user. but when I try remove command it fails with

```<code><error code='405' type='cancel'><not-allowed xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/><text xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'>The query is only allowed from local users</text></error>
</code>```

I noticed I can register new user even if Im not logged in, so I suspect my authentication is not working as expected for remove. How to use fabiang to authenticate with sha1?

I can unregister from android app with sha1 auth without problem.

答:
I figured it out, in order to unregister user, you have to be logged in as that user (while for register you have to be logged in as admin).

```<code>$this->implementation = new Implementation($withAuthentication);
$this->options = new \Fabiang\Xmpp\Options('tcp://...');
$this->options->setImplementation($this->implementation);
$this->options->setLogger($this->logger)
  ->setUsername($xmppuser)
  ->setPassword($xmpppass)
  ->setTimeout(self::XMPP_TIMEOUT);

$this->client = new \Fabiang\Xmpp\Client($this->options);

$listener = new UnRegistrationListener();
$unRegistrationObj = new UnRegistration();

$this->client->connect();
$this->implementation->registerListener($listener);
$this->client->send($unRegistrationObj);
$this->client->disconnect();
</code>```

and unregister message from ProtocolImplementationInterface looks like this:

```<code>public function toString()
{
return \Fabiang\Xmpp\Util\XML::quoteMessage(
  "<iq id='%s' type='set'><query xmlns='jabber:iq:register'><remove></remove></query></iq>",
  \Fabiang\Xmpp\Util\XML::generateId()
);
}
</code>```

Body:
i use fabiang php example (https://github.com/fabiang/xmpp/blob/master/example.php) to successfully register new user. but when I try remove command it fails with

<error code='405' type='cancel'><not-allowed xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/><text xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'>The query is only allowed from local users</text></error>

I noticed I can register new user even if Im not logged in, so I suspect my authentication is not working as expected for remove. How to use fabiang to authenticate with sha1?

I can unregister from android app with sha1 auth without problem.

Body:
I figured it out, in order to unregister user, you have to be logged in as that user (while for register you have to be logged in as admin).

$this->implementation = new Implementation($withAuthentication);
$this->options = new \Fabiang\Xmpp\Options('tcp://...');
$this->options->setImplementation($this->implementation);
$this->options->setLogger($this->logger)
  ->setUsername($xmppuser)
  ->setPassword($xmpppass)
  ->setTimeout(self::XMPP_TIMEOUT);

$this->client = new \Fabiang\Xmpp\Client($this->options);

$listener = new UnRegistrationListener();
$unRegistrationObj = new UnRegistration();

$this->client->connect();
$this->implementation->registerListener($listener);
$this->client->send($unRegistrationObj);
$this->client->disconnect();

and unregister message from ProtocolImplementationInterface looks like this:

public function toString()
{
return \Fabiang\Xmpp\Util\XML::quoteMessage(
  "<iq id='%s' type='set'><query xmlns='jabber:iq:register'><remove></remove></query></iq>",
  \Fabiang\Xmpp\Util\XML::generateId()
);
}


问:
Common results of two MySQL queries
I am looking to combine two MySQL queries so it returns the common results so I know I am not looking to use UNION on this one. I tried writing a subselect statement but that didn't work out

First query:

```<code>SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 4 and m.answer = 3 and h.page = 4
</code>```

Second query:

```<code>SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 114 and m.answer = 1 and h.page = 114
</code>```

Failed merge query:

```<code>SELECT s.ses_id FROM session s, multiple, history h
JOIN (
    SELECT session.ses_id
    FROM session, history, multiple
    WHERE multiple.question = 114 and multiple.answer = 1 and history.page = 114 and history.ses_id = session.ses_id and multiple.ses_id=session.ses_id
    ) q1 ON q1.ses_id = s.ses_id
WHERE s.interview = 'lifestyle' and s.finished = 'y' and multiple.page=4 and multiple.answer = 3 and h.page = 4 and h.ses_id = s.ses_id and multiple.ses_id=s.ses_id
</code>```

The multiple table contains questions and answers and I am looking to find the ids of those who have answered the two questions with those specific answers.

I realize this should be easy and I am most likely overthinking and/or missing something.

答:
Below simply altered query may be useful.,

```<code>SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE
( m.question = 4 and m.answer = 3 and h.page = 4 )
OR
( m.question = 114 and m.answer = 1 and h.page = 114 )
</code>```

Merge operation is not needed.

Title: Common results of two MySQL queries

Body:
I am looking to combine two MySQL queries so it returns the common results so I know I am not looking to use UNION on this one. I tried writing a subselect statement but that didn't work out

First query:

SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 4 and m.answer = 3 and h.page = 4

Second query:

SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 114 and m.answer = 1 and h.page = 114

Failed merge query:

SELECT s.ses_id FROM session s, multiple, history h
JOIN (
    SELECT session.ses_id
    FROM session, history, multiple
    WHERE multiple.question = 114 and multiple.answer = 1 and history.page = 114 and history.ses_id = session.ses_id and multiple.ses_id=session.ses_id
    ) q1 ON q1.ses_id = s.ses_id
WHERE s.interview = 'lifestyle' and s.finished = 'y' and multiple.page=4 and multiple.answer = 3 and h.page = 4 and h.ses_id = s.ses_id and multiple.ses_id=s.ses_id

The multiple table contains questions and answers and I am looking to find the ids of those who have answered the two questions with those specific answers.

I realize this should be easy and I am most likely overthinking and/or missing something.

Body:
Below simply altered query may be useful.,

SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE
( m.question = 4 and m.answer = 3 and h.page = 4 )
OR
( m.question = 114 and m.answer = 1 and h.page = 114 )

Merge operation is not needed.


问:
How to use --init parameter in docker run
There are --init and --init-path options for docker run, but it's not clear how to use it.

At first, I thought it's something like dumb-init, but included in docker core (kind of "native"). But --init key demands --init-path to be set as well, pointing to docker-init binary, and gives no clue on where to take it. Google is silent about docker-init.

Okay, maybe I'm supposed to use yelp/dumb-init or 'phusion/baseimage-docker', but those solutions don't seem to use docker run's --init option.

So, I'm curious where do I take this "docker-init binary" to set the --init-path to?

答:
I've found this in documentation:

You can use the --init flag to indicate that an init process should be
  used as the PID 1 in the container. Specifying an init process ensures
  the usual responsibilities of an init system, such as reaping zombie
  processes, are performed inside the created container. The default
  init process used is the first docker-init executable found in the
  system path of the Docker daemon process. This docker-init binary,
  included in the default installation, is backed by
  tini.

I couldn't find docker-init on a macOS Docker installation, but on Linux it's here:

/usr/bin/docker-init


问:
Object propagation
I have a collection of objects, lets say QVector<ApplicationStates>, which registers the most important operations done in my software. Basically, this object is meant to process redo/undo operations.The application is built using a lot of delegated objects. Operations which have to be registered lie in a lot of these objects. As such, I am always passing  my collection of objects, in each delegate under the form:

```<code>class AWidget : public QWidget{
    AWidget(QVector<ApplicationStates>* states, QWidget* parent = nullptr);
    ...
</code>```

It seems ugly to me. I think about two solutions:

Singleton;

Simply declare the QVector as a static global variable (I read that global variables are evil).

Does someone have a suggestion?
Thanks for your answers.

答:
I get into a similar situation from time to time, and I have found simply wrapping your vector in a class called something like "ApplicationContext" then passing a shared pointer or reference to an instance of that around saves the day. It has many benefits:

You avoid the global / singleton, and you are free to in fact have several instances concurrently in the future

If you suddenly have more than just that vector of objects that you need to pass arround, simply extend your context class to add whatever you need

If your vector suddenly becomes a map or changes in other ways, you need not change any interfaces that pass it along such as the signals/slots. (You will need to change the implementation where the vector is used of course).

BONUS: The code becomes easily testable! You can now make test cases for this class.

This might not be the best solution in all cases, but I think it comes pretty close in this case!

Title: Object propagation

Body:
I have a collection of objects, lets say QVector<ApplicationStates>, which registers the most important operations done in my software. Basically, this object is meant to process redo/undo operations.The application is built using a lot of delegated objects. Operations which have to be registered lie in a lot of these objects. As such, I am always passing  my collection of objects, in each delegate under the form:

class AWidget : public QWidget{
    AWidget(QVector<ApplicationStates>* states, QWidget* parent = nullptr);
    ...

It seems ugly to me. I think about two solutions:

Singleton;

Simply declare the QVector as a static global variable (I read that global variables are evil).

Does someone have a suggestion?
Thanks for your answers.


问:
Azure Function with serviceBusTrigger stops receiving messages
I have am Azure Function configured with a servieBusTrigger to receive messages from a topic subscription on Azure Serivce Bus. The function have been running fine for days, but this morning I noticed a lot of messages on the subscription. It turns out, that my Function no longer receives messages from the queue.

I've checked the queue to ensure that the messages are not in the dead letter queue. They are not. I have logging in place in my Function and no log statements are found (which I didn't expect since the messages are never processed). I've checked the log files on Kudu (`LogFiles\Application\Functions\Function\MyFunction). It is empty and I did enable application logging through the Portal.

Here's my function.json:

```<code>{
  "disabled": false,
  "bindings": [
    {
      "name": "mySbMsg",
      "type": "serviceBusTrigger",
      "direction": "in",
      "topicName": "tasks-v1",
      "subscriptionName": "errormail-v1",
      "connection": "connection",
      "accessRights": "Manage"
    }
  ]
}
</code>```

As I wrote earlier, the Function did work fine for days. I'm running on the consumption plan, why always on shouldn't be an issue.

Any ideas to how to debug this?

UPDATE: For future reference, we updated to compiled functions which fixes the problem (which makes sense since the bug are in Roslyn).

答:
It appears your function ran into this bug with roslyn compilation which is solved via restart: https://github.com/Azure/azure-webjobs-sdk-script/issues/999

I saw this error in your function app logs:

2017-03-28 23:14:11.6306121 Cannot enqueue data after PromiseNotToEnqueue.

This is a sporadic issue, but if you want a workaround you can use precompiled functions.

Body:
I have am Azure Function configured with a servieBusTrigger to receive messages from a topic subscription on Azure Serivce Bus. The function have been running fine for days, but this morning I noticed a lot of messages on the subscription. It turns out, that my Function no longer receives messages from the queue.

I've checked the queue to ensure that the messages are not in the dead letter queue. They are not. I have logging in place in my Function and no log statements are found (which I didn't expect since the messages are never processed). I've checked the log files on Kudu (`LogFiles\Application\Functions\Function\MyFunction). It is empty and I did enable application logging through the Portal.

Here's my function.json:

{
  "disabled": false,
  "bindings": [
    {
      "name": "mySbMsg",
      "type": "serviceBusTrigger",
      "direction": "in",
      "topicName": "tasks-v1",
      "subscriptionName": "errormail-v1",
      "connection": "connection",
      "accessRights": "Manage"
    }
  ]
}

As I wrote earlier, the Function did work fine for days. I'm running on the consumption plan, why always on shouldn't be an issue.

Any ideas to how to debug this?

UPDATE: For future reference, we updated to compiled functions which fixes the problem (which makes sense since the bug are in Roslyn).


问:
TIME_FORMAT Returns NULL
I have a time stored in mysql, the column is set as time, so it reads 13:16:00. When I try to run

```<code>SELECT TIME_FORMAT ('alarm_time', '%H:%i) FROM `Alarm`;
</code>```

I get a NULL, I am trying to get a result of 13:06.

答:
Why don't you simply use left(value,position).

select left(alarm_time,5) from Alarm; with correct schema name and backticks where ever required should suffice.

The function is self explanatory in its syntax :)

Title: TIME_FORMAT Returns NULL

Body:
I have a time stored in mysql, the column is set as time, so it reads 13:16:00. When I try to run

SELECT TIME_FORMAT ('alarm_time', '%H:%i) FROM `Alarm`;

I get a NULL, I am trying to get a result of 13:06.


问:
Convert object function to function pointer
I'm trying convert a object function to function pointer but can't get it, i've done something like this, simple example:

```<code>typedef struct
{
    int v1;

    int DoSome(int a)
    {
        return v1 * a;
    }
} strx;

int main()
{
    strx a; // instance...
    a.v1 = 2;

    std::function<int(strx* instance, int value)> DoSome = std::mem_fn(&strx::DoSome);

    cout << DoSome(&a, 4) << endl; // 16 ok

    int(*pDoSome)(strx* instance, int value) = (int(*)(strx*, int))std::mem_fn(&strx::DoSome); // syntax error

    // ptr method...
    pDoSome(&a ,4);

    return 0;
}
</code>```

and i have obtained something like:

main.cpp [Error] invalid cast from type 'std::_Mem_fn' to type 'int ()(strx, int)'

How i can do correctly the casting?

答: You can't.  This is why std::function is more flexible than pointers to functions.

Body:
I'm trying convert a object function to function pointer but can't get it, i've done something like this, simple example:

typedef struct
{
    int v1;

    int DoSome(int a)
    {
        return v1 * a;
    }
} strx;

int main()
{
    strx a; // instance...
    a.v1 = 2;

    std::function<int(strx* instance, int value)> DoSome = std::mem_fn(&strx::DoSome);

    cout << DoSome(&a, 4) << endl; // 16 ok

    int(*pDoSome)(strx* instance, int value) = (int(*)(strx*, int))std::mem_fn(&strx::DoSome); // syntax error

    // ptr method...
    pDoSome(&a ,4);

    return 0;
}

and i have obtained something like:

main.cpp [Error] invalid cast from type 'std::_Mem_fn' to type 'int ()(strx, int)'

How i can do correctly the casting?


问:
Why the list is always empty?
in this code i am searching the wifi access points and showing the results in text view.... it works fine on samsung phone but for some reason the list is always empty in case of other phones....

can you help me understand why the list is always empty? I ll be very grateful.

```<code>public class MainActivity extends AppCompatActivity {

    Switch aswitch;
    int n=1;
    TextView text;
    WifiManager wifi;
    String message;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        aswitch=(Switch)findViewById(R.id.myswitch);
        wifi=(WifiManager)getSystemService(WIFI_SERVICE);
        text=(TextView)findViewById(R.id.mytv);

        aswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // do something, the isChecked will be
                // true if the switch is in the On position
                if (isChecked && !wifi.isWifiEnabled()) {
                    wifi.setWifiEnabled(true);
                    message="enabled";
                    text.setText(message);

                } else if (!isChecked && wifi.isWifiEnabled()){
                    wifi.setWifiEnabled(false);
                    message="disabled";
                    text.setText(message);
                }
            }
        });

            MyBroadcastReceiver broadcast=new MyBroadcastReceiver();
            registerReceiver(broadcast, new IntentFilter(wifi.SCAN_RESULTS_AVAILABLE_ACTION));

    }
    class MyBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuffer stringBuffer=new StringBuffer();
            List<ScanResult> list=wifi.getScanResults();

            for(ScanResult scanResult:list){
                String ssid0 = scanResult.SSID;
                int rssi0 = scanResult.level;
                String rssiString0 = String.valueOf(rssi0);
                stringBuffer.append("\n SSID:" + ssid0 + "   RSSI:" + rssiString0 +"dBm");
                text.setText("yes");
            }
            text.setText(stringBuffer);
            if(wifi.isWifiEnabled()){
                wifi.startScan();
            }

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

答: As strange as it looks You must declare a fine or coarse location permission in manifest. Had this problem myself some time ago. </p>

Title: Why the list is always empty?

Body:
in this code i am searching the wifi access points and showing the results in text view.... it works fine on samsung phone but for some reason the list is always empty in case of other phones....

can you help me understand why the list is always empty? I ll be very grateful.

public class MainActivity extends AppCompatActivity {

    Switch aswitch;
    int n=1;
    TextView text;
    WifiManager wifi;
    String message;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        aswitch=(Switch)findViewById(R.id.myswitch);
        wifi=(WifiManager)getSystemService(WIFI_SERVICE);
        text=(TextView)findViewById(R.id.mytv);

        aswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // do something, the isChecked will be
                // true if the switch is in the On position
                if (isChecked && !wifi.isWifiEnabled()) {
                    wifi.setWifiEnabled(true);
                    message="enabled";
                    text.setText(message);

                } else if (!isChecked && wifi.isWifiEnabled()){
                    wifi.setWifiEnabled(false);
                    message="disabled";
                    text.setText(message);
                }
            }
        });

            MyBroadcastReceiver broadcast=new MyBroadcastReceiver();
            registerReceiver(broadcast, new IntentFilter(wifi.SCAN_RESULTS_AVAILABLE_ACTION));

    }
    class MyBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuffer stringBuffer=new StringBuffer();
            List<ScanResult> list=wifi.getScanResults();

            for(ScanResult scanResult:list){
                String ssid0 = scanResult.SSID;
                int rssi0 = scanResult.level;
                String rssiString0 = String.valueOf(rssi0);
                stringBuffer.append("\n SSID:" + ssid0 + "   RSSI:" + rssiString0 +"dBm");
                text.setText("yes");
            }
            text.setText(stringBuffer);
            if(wifi.isWifiEnabled()){
                wifi.startScan();
            }

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}