问:
Complete not getting called in Observable subscribe method
I am working on the angular application and I am trying to use RxObservable. Below is the sample code.

```<code>getMyData(){
 console.log('get my account data called');
  this.AccountService
    .getMyAccountData()
    .filter(_res => _res !== null)
    .takeUntil(this.ngUnsubscribe)
    .subscribe({
        next: _response => {console.log('call finished');}
        error: error => {
            console.log('had an error');
            handleHttpError(error);
       },
       complete: () => {
           console.log('account data loaded is being set');
           this.accountDataLoaded = true;
       }
    });
}
</code>```

Now this is an angular 2 app (Single page application). When I reload the page, the complete part of above function gets called and this.accountDataLoaded is true.

However, If I move to other component and come back to this one, the complete is not getting called and accountDataLoaded stays false.

I see there's no error on the console as well since I am logging the error as you can see above.

I am thinking either filter or takeUntil function on that observable are causing that but I am not sure.

答:
With RXjs behaviour complete is not been called if error is called.
In your case you need do the following thing.</p>

```<code>  getMyData(){
 console.log('get my account data called');
  this.AccountService
    .getMyAccountData()
    .filter(_res => _res !== null)
    .takeUntil(this.ngUnsubscribe)
    .subscribe({
        next: _response => {console.log('call finished');}
        error: error => {
            console.log('had an error');
            handleHttpError(error);
       },
       complete: () => {
           console.log('account data loaded is being set');
           this.accountDataLoaded = true;
       }
    }).add(() => {
         //Called when operation is complete (both success and error)
    });
}
</code>```

Body:
I am working on the angular application and I am trying to use RxObservable. Below is the sample code.

getMyData(){
 console.log('get my account data called');
  this.AccountService
    .getMyAccountData()
    .filter(_res => _res !== null)
    .takeUntil(this.ngUnsubscribe)
    .subscribe({
        next: _response => {console.log('call finished');}
        error: error => {
            console.log('had an error');
            handleHttpError(error);
       },
       complete: () => {
           console.log('account data loaded is being set');
           this.accountDataLoaded = true;
       }
    });
}

Now this is an angular 2 app (Single page application). When I reload the page, the complete part of above function gets called and this.accountDataLoaded is true.

However, If I move to other component and come back to this one, the complete is not getting called and accountDataLoaded stays false.

I see there's no error on the console as well since I am logging the error as you can see above.

I am thinking either filter or takeUntil function on that observable are causing that but I am not sure.

Body:
With RXjs behaviour complete is not been called if error is called.
In your case you need do the following thing.

  getMyData(){
 console.log('get my account data called');
  this.AccountService
    .getMyAccountData()
    .filter(_res => _res !== null)
    .takeUntil(this.ngUnsubscribe)
    .subscribe({
        next: _response => {console.log('call finished');}
        error: error => {
            console.log('had an error');
            handleHttpError(error);
       },
       complete: () => {
           console.log('account data loaded is being set');
           this.accountDataLoaded = true;
       }
    }).add(() => {
         //Called when operation is complete (both success and error)
    });
}


来源: stackexchange

问:
Text inside floated div not responsive
In the following code:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grid View</title>

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

```

The web page breaks at around 470px (checked through device toolbar using chrome inspect). This happens as the text inside the 4 floated divs in the second row is not responsive and gets out of the div at 470px. This is only happening when the text is inside a floated element, when I make the divs block element again, the text becomes responsive.

Can someone tell me why this happens ?

答:
Hope this help you. Added below mentioned CSS

```<code>    div#three div.col-3{
        width: 49%;
        margin: 0 0.5%;
        margin-bottom: 5px;}
</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grid View</title>

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

```

ContentLicense: CC BY-SA 4.0

Title: Text inside floated div not responsive

Body:
In the following code:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grid View</title>

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

The web page breaks at around 470px (checked through device toolbar using chrome inspect). This happens as the text inside the 4 floated divs in the second row is not responsive and gets out of the div at 470px. This is only happening when the text is inside a floated element, when I make the divs block element again, the text becomes responsive.

Can someone tell me why this happens ?

Body:
Hope this help you. Added below mentioned CSS

    div#three div.col-3{
        width: 49%;
        margin: 0 0.5%;
        margin-bottom: 5px;}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grid View</title>
  <style>
    * {
      box-sizing: border-box;
    }

    html {
      font-size: 1vw;
    }

    body {
      padding: 0 0;
      margin: 0;
      background-color: violet;
      font-size: 1.1rem;
    }

    .container {
      width: 80%;
      margin: 0 auto;
    }

    header {
      background-color: rgb(133, 76, 76);
      border: .01rem solid rgb(133, 76, 76);
      margin-bottom: 4%;
      position: fixed;
      top: 0;
      left: 10%;
      right: 10%;
      padding: 0;
    }

    header h1 {
      text-align: center;
    }

    .row {
      background-color: blueviolet;
      margin-bottom: 4%;
    }

    .row::after {
      content: "";
      clear: both;
      display: table;
    }

    [class*="col-"] {
      float: left;
      padding: 15px;
      background-color: whitesmoke;
    }

    .col-1 {
      width: 8.33%;
    }

    .col-2 {
      width: 16.66%;
    }

    .col-3 {
      width: 25%;
    }

    .col-4 {
      width: 33.33%;
    }

    .col-5 {
      width: 41.66%;
    }

    .col-6 {
      width: 50%;
    }

    .col-7 {
      width: 58.33%;
    }

    .col-8 {
      width: 66.66%;
    }

    .col-9 {
      width: 75%;
    }

    .col-10 {
      width: 83.33%;
    }

    .col-11 {
      width: 91.66%;
    }

    .col-12 {
      width: 100%;
    }

    div#three div.col-3 {
      width: 24%;
      margin-right: 1.33%;
    }

    div#three div.col-3:last-of-type {
      margin-right: 0;
    }

    @media only screen and (max-width: 780px) {
      html {
        font-size: 2.5vw;
      }
      body {
        padding-top: 17%;
      }
      div#three div.col-3 {
        width: 49%;
        margin: 0 0.5%;
        margin-bottom: 5px;
      }
    }

    @media only screen and (max-width: 480px) {
      html {
        font-size: 3vw;
      }
      body {
        padding-top: 17%;
      }
    }

    @media only screen and (max-width: 380px) {
      div#three div.col-3 {
        width: 99%;
        margin: 0 0.5%;
        margin-bottom: 5px;
      }
    }
  </style>
</head>

<body>
  <div class="container">
    <div id="one" class="row">
      <div class="col-12">
        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.</p>
      </div>
    </div>

    <div id="three" class="row">
      <div class="col-3">
        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.</p>
      </div>
      <div class="col-3">
        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.</p>
      </div>
      <div class="col-3">
        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.</p>
      </div>
      <div class="col-3">
        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.</p>
      </div>
    </div>
  </div>
</body>

</html>


问:
Why isn't "--comment" working when "-- comment" does?
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?</p>

```<code><?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>
</code>```

答: Per MySQL docs a space is required. Also, as stated on the previous linked page, MySQL deviates from the spec in this syntax (which is just 2 consecutive dashes [--this is a comment]).

ContentLicense: CC BY-SA 3.0

Body:
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?

<?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>


问:
Why the file.txt is not being deployed to my server?
In my existing aws pipeline I have the following buildspec.yml:

```<code>version: 0.2

phases:
  build:
    commands:
      - cd media/web/front_dev
      - echo "Hello" > ../web/txt/hello.txt

artifacts:
  files:
    - ./media/web/hello.txt
</code>```

And the appspec.yml has the following

```<code>version: 0.0
os: linux
files:
  - source: /
    destination: /webserver/src/public
</code>```

But the file hello.txt is not being deployed to the server on the deploy phase? Once I ssh into the machine I run the following commands:

```<code>/webserver/src/public/media/web/hello.txt
</code>```

But the file is not shown. Do you have any idea why?

My pipeline initially had only a source and a deployment step then I edited it in order to have a codebuild step as well.

答:
Check your pipeline. You may have added the build step but the deployment just fetches the code from the version control instead of the deployment. In order to solve that follow these steps:

Specify a name for the output artifact at the build step.

Select as input artifact the artifact you have placed into as output artifact at the build step.

Body:
In my existing aws pipeline I have the following buildspec.yml:

version: 0.2

phases:
  build:
    commands:
      - cd media/web/front_dev
      - echo "Hello" > ../web/txt/hello.txt

artifacts:
  files:
    - ./media/web/hello.txt

And the appspec.yml has the following

version: 0.0
os: linux
files:
  - source: /
    destination: /webserver/src/public

But the file hello.txt is not being deployed to the server on the deploy phase? Once I ssh into the machine I run the following commands:

/webserver/src/public/media/web/hello.txt

But the file is not shown. Do you have any idea why?

My pipeline initially had only a source and a deployment step then I edited it in order to have a codebuild step as well.


问:
How to code piecewise survival models in R (e.g. Kaplan-Meier curve with an extrapolated tail)
I would like to ask how to create piecewise survival models in R (e.g. a Kaplan-Meier curve with an extrapolated tail (regardless of the distribution), see attached figure as an example?

For example how to create a curve where I fit the exponential distribution when the time is 200 in the example below (so that I would get a similar looking curve like in the attached figure)?

```<code>library(survival)
library(flexsurv)
library(dplyr)

data <- survival::lung %>% filter(time < 300)

formula <- Surv(data$time, data$status) ~1

model <- flexsurvreg(formula = formula, dist = "exp", na.action = na.exclude)

plot(model, main = "plot",
     col.obs = "black",
     col = "blue")
</code>```

答:
The model has class "flexsurvreg", so the help page for plot.flexsurvreg should give you the answers, as well as the plot.survfit function, which accepts the ... argument. So, to get a plot similar to the one you show, the following may be a start:

```<code>plot(model, main = "plot",
     col.obs = "black",
     col = "blue",
     ci=FALSE,
     conf.int=FALSE,
     las=2,  # axis tick labels always perpendicular to axes
     xlab="Time (months)",
     ylab="Percentage alive")
</code>```

I hope you didn't want the ugly x-axis breaks or the 3 significant digits for the y-axis tick labels. By the way, the y-axis label should really be Proportion alive.

Body:
I would like to ask how to create piecewise survival models in R (e.g. a Kaplan-Meier curve with an extrapolated tail (regardless of the distribution), see attached figure as an example?

For example how to create a curve where I fit the exponential distribution when the time is 200 in the example below (so that I would get a similar looking curve like in the attached figure)?

library(survival)
library(flexsurv)
library(dplyr)

data <- survival::lung %>% filter(time < 300)

formula <- Surv(data$time, data$status) ~1

model <- flexsurvreg(formula = formula, dist = "exp", na.action = na.exclude)

plot(model, main = "plot",
     col.obs = "black",
     col = "blue")

Body:
The model has class "flexsurvreg", so the help page for plot.flexsurvreg should give you the answers, as well as the plot.survfit function, which accepts the ... argument. So, to get a plot similar to the one you show, the following may be a start:

plot(model, main = "plot",
     col.obs = "black",
     col = "blue",
     ci=FALSE,
     conf.int=FALSE,
     las=2,  # axis tick labels always perpendicular to axes
     xlab="Time (months)",
     ylab="Percentage alive")

I hope you didn't want the ugly x-axis breaks or the 3 significant digits for the y-axis tick labels. By the way, the y-axis label should really be Proportion alive.


问:
SimpleMessageListenerContainer unable to call message handler correctly
I'm trying listen to a RabbitMq queue in my Spring Boot application. In my RabbitConfig.java file, I have the following beans:

```<code>// RabbitConfig.java
// ...Queue, exchange, binding beans, etc

@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setConcurrentConsumers(2);
    container.setPrefetchCount(100);
    container.setQueueNames(QUEUE_NAME);
    return container;
}

@Bean
public AmqpTemplate getTemplate(ConnectionFactory connectionFactory) {
    final RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.setMessageConverter(new Jackson2JsonMessageConverter(mapper));
    return template;
}
</code>```

I've created a listener container as I need to make some settings to it such as its prefetch count.

I've also created another class as the message listener which looks like this:

```<code>@Component
public class MyMessageListener {
    @RabbitListener(queues = QUEUE_NAME)
    public void messageHandler(MyMessageObj message, Channel channel) throws IOException {
        // process message...
}
</code>```

However, when I run the application, it throws an error of Error Handler converted exception to fatal. The error appears to occur because the container was expecting  messageHandler to have a different method signature.

I'm thinking I might have done something incorrect in the container because when I remove it, the application is able to run and listen to the queue except that I can't configure the settings in the container.

What have I done wrong and what should I do to have the container use the messageHandler correctly?

答:
Could you please try to implement a MessageListener class that implements org.springframework.amqp.core.MessageListener and implements the method "onMessage(Message message)"

Once you have a @Configuration class where you have defined the SimpleMessageListenerContainer, you need to have a corresponding Class that implements org.springframework.amqp.core.MessageListener and implements the method "onMessage(Message message)".

Let me know if this helps.

@Configuration
public class MessageConfig {

```<code>private static String queue = "ARRQueue";
@Bean
ConnectionFactory connectionFactory(){
    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory("localhost");
    cachingConnectionFactory.setUsername("guest");
    cachingConnectionFactory.setPassword("guest");
    return cachingConnectionFactory;
}

@Bean
MessageListenerContainer messageListenerContainer(){
    SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
    simpleMessageListenerContainer.setConnectionFactory(connectionFactory());
    simpleMessageListenerContainer.setQueues(new Queue(queue, true));
    simpleMessageListenerContainer.setMessageListener(new MessageListener());
    return simpleMessageListenerContainer;
}
</code>```

}

public class MessageListener implements org.springframework.amqp.core.MessageListener {
    @Override
    public void onMessage(Message message)
    {
        System.out.println("MessageListener.onMessage : " + new String(message.getBody()));
    }

Body:
I'm trying listen to a RabbitMq queue in my Spring Boot application. In my RabbitConfig.java file, I have the following beans:

// RabbitConfig.java
// ...Queue, exchange, binding beans, etc

@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setConcurrentConsumers(2);
    container.setPrefetchCount(100);
    container.setQueueNames(QUEUE_NAME);
    return container;
}

@Bean
public AmqpTemplate getTemplate(ConnectionFactory connectionFactory) {
    final RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.setMessageConverter(new Jackson2JsonMessageConverter(mapper));
    return template;
}

I've created a listener container as I need to make some settings to it such as its prefetch count.

I've also created another class as the message listener which looks like this:

@Component
public class MyMessageListener {
    @RabbitListener(queues = QUEUE_NAME)
    public void messageHandler(MyMessageObj message, Channel channel) throws IOException {
        // process message...
}

However, when I run the application, it throws an error of Error Handler converted exception to fatal. The error appears to occur because the container was expecting  messageHandler to have a different method signature.

I'm thinking I might have done something incorrect in the container because when I remove it, the application is able to run and listen to the queue except that I can't configure the settings in the container.

What have I done wrong and what should I do to have the container use the messageHandler correctly?

Body:
Could you please try to implement a MessageListener class that implements org.springframework.amqp.core.MessageListener and implements the method "onMessage(Message message)"

Once you have a @Configuration class where you have defined the SimpleMessageListenerContainer, you need to have a corresponding Class that implements org.springframework.amqp.core.MessageListener and implements the method "onMessage(Message message)".

Let me know if this helps.

@Configuration
public class MessageConfig {

private static String queue = "ARRQueue";
@Bean
ConnectionFactory connectionFactory(){
    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory("localhost");
    cachingConnectionFactory.setUsername("guest");
    cachingConnectionFactory.setPassword("guest");
    return cachingConnectionFactory;
}

@Bean
MessageListenerContainer messageListenerContainer(){
    SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
    simpleMessageListenerContainer.setConnectionFactory(connectionFactory());
    simpleMessageListenerContainer.setQueues(new Queue(queue, true));
    simpleMessageListenerContainer.setMessageListener(new MessageListener());
    return simpleMessageListenerContainer;
}

}

public class MessageListener implements org.springframework.amqp.core.MessageListener {
    @Override
    public void onMessage(Message message)
    {
        System.out.println("MessageListener.onMessage : " + new String(message.getBody()));
    }


问:
SQL query to get the latest price from the data?
I have this data in my Oracle table:

In this table, I have multiple products with having product_id and price at a particular time.

I want to write a SQL query to get latest price of each product based on the TIME column (Oracle - Long Type).

But here is the problem, for our table price monitoring for the product starts at 23:00 previous date.

Output required: when I passed 2-Dec-2019 as parameter into the SQL query

How can I do this with a SQL query? Or do I need to write a stored procedure for it, based on if and else condition?

Thanks in advance.

答:
Oh, I see.  You can use two parameters in the ORDER BY:

```<code>SELECT local_date, system_date, currency, product_id, time, current_price
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY product_id
                                ORDER BY local_date DESC, time DESC
                               ) as seqnum
      FROM t
      WHERE system_date = @parameter
     ) t
WHERE rn = 1;
</code>```

I'm not sure if you really want the filtering on date like that.  You might want:

```<code>      WHERE system_date <= @parameter
</code>```

or:

```<code>      WHERE system_date < @parameter + interval '1' day
</code>```

These would allow you to get data from earlier days, if there is no data on the date specified by the parameter.  The second version also works if system_date has a time component (which is allowed for date data types in Oracle).

Body:
Oh, I see.  You can use two parameters in the ORDER BY:

SELECT local_date, system_date, currency, product_id, time, current_price
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY product_id
                                ORDER BY local_date DESC, time DESC
                               ) as seqnum
      FROM t
      WHERE system_date = @parameter
     ) t
WHERE rn = 1;

I'm not sure if you really want the filtering on date like that.  You might want:

      WHERE system_date <= @parameter

or:

      WHERE system_date < @parameter + interval '1' day

These would allow you to get data from earlier days, if there is no data on the date specified by the parameter.  The second version also works if system_date has a time component (which is allowed for date data types in Oracle).


问:
jQuery $(this).data() returns undefined
I'm trying to fix the following code:

const $configuratorMenus = $('.configurators-menu ul li');

$configuratorMenus.click(() => {

    let panelID = $(this).data("id");
    let panelID2 = $(this).attr("data-id");

    console.log(panelID, panelID2);

    //$(`#${panelID}`).slideToggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
    <ul>
        <li data-id="shapes">

                Shape

        </li>
    </ul>
</div></code>```

It keeps consoling undefined, what am I doing wrong? I couldn't relate any other solution.

Note: I would like to solve this by using the arrow function.

答:
This one should resolve your problem -

const configuratorMenus = $('.configurators-menu ul li a');

configuratorMenus.click(function () {
    let panelID = $(this).parent().data("id");
    console.log(panelID);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
    <ul>
        <li data-id="shapes">

                Shape

        </li>
    </ul>
</div></code>```

Title: jQuery $(this).data() returns undefined

Body:
I'm trying to fix the following code:

const $configuratorMenus = $('.configurators-menu ul li');

$configuratorMenus.click(() => {

    let panelID = $(this).data("id");
    let panelID2 = $(this).attr("data-id");

    console.log(panelID, panelID2);

    //$(`#${panelID}`).slideToggle();
});

                Shape

It keeps consoling undefined, what am I doing wrong? I couldn't relate any other solution.

Note: I would like to solve this by using the arrow function.

Body:
This one should resolve your problem -

const configuratorMenus = $('.configurators-menu ul li a');

configuratorMenus.click(function () {
    let panelID = $(this).parent().data("id");
    console.log(panelID);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
    <ul>
        <li data-id="shapes">
            <a href="#">
                Shape
            </a>
        </li>
    </ul>
</div>


问:
type 'MethodChannelDocumentReference' is not a subtype of type 'DocumentReference' in type cast
I'm updating my project using firestore and its the first time that I has this type of error.
Its very stange for me, I use firestore how the documentation saids and in other parts of my app Firestore don't had any error,
but in this part I use cloud functions to create a document and insert its reference in other. After I need to obtain the DocumentId but its said me this error "type 'MethodChannelDocumentReference' is not a subtype of type 'DocumentReference' in type cast"
I leave some screenshots.

coupon=>reference as reference">

This is my code in cloud functions:

```<code>exports.generateUserCode = functions.https.onCall(async (data, context) => {
  const { uid } = data;
  let coupon = shortid.generate();
  let user = firestore.doc(`users/${uid}`);
  try {
    await firestore
      .collection("coupons")
      .doc(coupon)
      .set({
        owner: user,
        type: 0,
        value: 10,
        isPercentage: false,
        usersUsedIt: 0
      });
    await user.update({
      coupon: {
        reference: firestore.doc(`coupons/${coupon}`),
        uses: 0
      }
    });
    return {
      status: true,
      message: "codigo de invitacion generado",
      code: coupon
    };
  } catch (e) {
    console.log("error", e);
    return {
      status: false,
      message: "algo salio mal",
      code: null
    };
  }
});
</code>```

This is the flutter code:

```<code>@override
  Future<UserModel> getUser() async {
    try {
      final authUser = await _auth.currentUser();
      if (authUser != null) {
        final user = await _firestore.document('users/${authUser.uid}').get();
        if (!user.data.containsKey('coupon') || user.data['coupon'] == null) {
          final couponCode = await _generateCode(authUser.uid);
          return UserModel.fromData(authUser, couponCode);
        } else {
          final coupon = Map<String, dynamic>.from(user.data['coupon']);
          final couponRef = coupon['reference'] as DocumentReference;
          return UserModel.fromData(authUser, couponRef.documentID);
        }
      }
      return null;
    } catch (e) {
      log(e.toString(), error: e);
      throw ServerException();
    }
  }
</code>```

And this appears when I try to debug the code:

```<code>type 'MethodChannelDocumentReference' is not a subtype of type 'DocumentReference' in type cast
</code>```

答: there is the solution thanks for your help.</p>

Body:
I'm updating my project using firestore and its the first time that I has this type of error.
Its very stange for me, I use firestore how the documentation saids and in other parts of my app Firestore don't had any error,
but in this part I use cloud functions to create a document and insert its reference in other. After I need to obtain the DocumentId but its said me this error "type 'MethodChannelDocumentReference' is not a subtype of type 'DocumentReference' in type cast"
I leave some screenshots.

coupon=>reference as reference">

This is my code in cloud functions:

exports.generateUserCode = functions.https.onCall(async (data, context) => {
  const { uid } = data;
  let coupon = shortid.generate();
  let user = firestore.doc(`users/${uid}`);
  try {
    await firestore
      .collection("coupons")
      .doc(coupon)
      .set({
        owner: user,
        type: 0,
        value: 10,
        isPercentage: false,
        usersUsedIt: 0
      });
    await user.update({
      coupon: {
        reference: firestore.doc(`coupons/${coupon}`),
        uses: 0
      }
    });
    return {
      status: true,
      message: "codigo de invitacion generado",
      code: coupon
    };
  } catch (e) {
    console.log("error", e);
    return {
      status: false,
      message: "algo salio mal",
      code: null
    };
  }
});

This is the flutter code:

@override
  Future<UserModel> getUser() async {
    try {
      final authUser = await _auth.currentUser();
      if (authUser != null) {
        final user = await _firestore.document('users/${authUser.uid}').get();
        if (!user.data.containsKey('coupon') || user.data['coupon'] == null) {
          final couponCode = await _generateCode(authUser.uid);
          return UserModel.fromData(authUser, couponCode);
        } else {
          final coupon = Map<String, dynamic>.from(user.data['coupon']);
          final couponRef = coupon['reference'] as DocumentReference;
          return UserModel.fromData(authUser, couponRef.documentID);
        }
      }
      return null;
    } catch (e) {
      log(e.toString(), error: e);
      throw ServerException();
    }
  }

And this appears when I try to debug the code:

type 'MethodChannelDocumentReference' is not a subtype of type 'DocumentReference' in type cast


问:
Python __init__ setattr on arguments?
It seems that often __init__ methods are similar to this:

```<code>def __init__(self, ivar1, ivar2, ivar3):
    self.ivar1 = ivar1
    self.ivar2 = ivar2
    self.ivar3 = ivar3
</code>```

Is there someway to turn the arguments into a list (without resorting to *args or **kwargs) and then using setattr to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g.  you'd need to at least slice it to [1:] because you don't want self.self.

(actually I guess it would need to be a dictionary to hold the name and value)

like this:

```<code>def __init__(self, ivar1, ivar2, ivar3, optional=False):
    for k, v in makedict(self.__class__.__init__.__args__): # made up __args__
        setattr(self, k, v)
</code>```

Thanks!

Responding to Unknown's answer, I found this to work:

```<code>Class A(object):
    def __init__(self, length, width, x):
        self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self']))
</code>```

or

```<code>Class A(object):
    def __init__(self, length, width, x):
        self.__dict__.update(locals())
        del self.__dict__['self']
</code>```

Not too bad..

答:
If you want to declare class variables dynamically from given paramater, there is a short and clean way to do this while initializing a class:</p>

```<code>class Foo():

    def __init__(self, **content):
        if isinstance(content, dict):
            self.hello = 'world' # normal declaration instance variable
            for key, value in content.items():
                self.__setattr__(key, value)

    test = "test" # class variable

>>> content = {'foo':'bar'}
>>> instance = Foo(**content)
>>> instance.foo
>>> 'bar'
</code>```

Title: Python __init__ setattr on arguments?

Body:
It seems that often __init__ methods are similar to this:

def __init__(self, ivar1, ivar2, ivar3):
    self.ivar1 = ivar1
    self.ivar2 = ivar2
    self.ivar3 = ivar3

Is there someway to turn the arguments into a list (without resorting to *args or **kwargs) and then using setattr to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g.  you'd need to at least slice it to [1:] because you don't want self.self.

(actually I guess it would need to be a dictionary to hold the name and value)

like this:

def __init__(self, ivar1, ivar2, ivar3, optional=False):
    for k, v in makedict(self.__class__.__init__.__args__): # made up __args__
        setattr(self, k, v)

Thanks!

Responding to Unknown's answer, I found this to work:

Class A(object):
    def __init__(self, length, width, x):
        self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self']))

or

Class A(object):
    def __init__(self, length, width, x):
        self.__dict__.update(locals())
        del self.__dict__['self']

Not too bad..

Body:
If you want to declare class variables dynamically from given paramater, there is a short and clean way to do this while initializing a class:

class Foo():

    def __init__(self, **content):
        if isinstance(content, dict):
            self.hello = 'world' # normal declaration instance variable
            for key, value in content.items():
                self.__setattr__(key, value)

    test = "test" # class variable

>>> content = {'foo':'bar'}
>>> instance = Foo(**content)
>>> instance.foo
>>> 'bar'


答:
Since you are using arrow function , this will refer window object in this case. You can use e.target.Where e is event object. Also the data attribute is on li but the event is originating from a. So change $configuratorMenus to $('.configurators-menu ul li a')

const $configuratorMenus = $('.configurators-menu ul li a');

$configuratorMenus.click((e) => {
  // get the parent element from the target
  let panelID = $(e.target).parent().data('id');
  console.log(panelID);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
  <ul>
    <li data-id="shapes">

                Shape

    </li>
  </ul>
</div></code>```

Title: jQuery $(this).data() returns undefined

Body:
Since you are using arrow function , this will refer window object in this case. You can use e.target.Where e is event object. Also the data attribute is on li but the event is originating from a. So change $configuratorMenus to $('.configurators-menu ul li a')

const $configuratorMenus = $('.configurators-menu ul li a');

$configuratorMenus.click((e) => {
  // get the parent element from the target
  let panelID = $(e.target).parent().data('id');
  console.log(panelID);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
  <ul>
    <li data-id="shapes">
      <a href="#">
                Shape
            </a>
    </li>
  </ul>
</div>


问:
POST Request in node.js
guys.

I've task: X company has created Z school, in school there is only one class.
School needs: 1. to create students' list:
a. id
b. name
c. surname
d. birth date
e. addresses
f. scores

how can I post request in node.js to get all these above information? I'm using firebase and get request is already done. maybe I'm asking question wrongly, cause im an amateur and sorry for that.

Thank you in advance.

this is my code:

```<code>const { admin } = require('../firebase');
const app = express();

app.get('/', (req, res) => {
    const reference = admin.database().ref('/students')

    reference.on('value', (snapshot) => {
        res.json(snapshot.val())
        reference.off('value')
    }, (errorObject) => {
        res.send(`somethig wrong: ${errorObject.code}`)
    })
})

app.post('/', (req, res) => {

})

module.exports = app

</code>```

答:
You could use axios to send POST requests through your web application like the following example:

```<code>axios.post( '/student', { name: 'John', sname: 'Cage' })
     .then( function( resp ) {
       console.log( resp )
     })
     .catch( function( err ) {
       console.error( err )
     })
</code>```

Now you can listen "/student" (the POST request) from your NodeJS server:

```<code>app.post( '/student', (req, res) => {
  // Your new student data
  console.log( 'Name:', req.body.name )
  console.log( 'Surname:', req.body.sname )
})
</code>```

Title: POST Request in node.js

Body:
guys.

I've task: X company has created Z school, in school there is only one class.
School needs: 1. to create students' list:
a. id
b. name
c. surname
d. birth date
e. addresses
f. scores

how can I post request in node.js to get all these above information? I'm using firebase and get request is already done. maybe I'm asking question wrongly, cause im an amateur and sorry for that.

Thank you in advance.

this is my code:

const { admin } = require('../firebase');
const app = express();

app.get('/', (req, res) => {
    const reference = admin.database().ref('/students')

    reference.on('value', (snapshot) => {
        res.json(snapshot.val())
        reference.off('value')
    }, (errorObject) => {
        res.send(`somethig wrong: ${errorObject.code}`)
    })
})

app.post('/', (req, res) => {

})

module.exports = app

Body:
You could use axios to send POST requests through your web application like the following example:

axios.post( '/student', { name: 'John', sname: 'Cage' })
     .then( function( resp ) {
       console.log( resp )
     })
     .catch( function( err ) {
       console.error( err )
     })

Now you can listen "/student" (the POST request) from your NodeJS server:

app.post( '/student', (req, res) => {
  // Your new student data
  console.log( 'Name:', req.body.name )
  console.log( 'Surname:', req.body.sname )
})


问:
How can I perform LiveData transformations on a background thread?
I have a need to transform one type of data, returned by a LiveData object, into another form on a background thread to prevent UI lag.

In my specific case, I have:

MyDBRow objects (POJOs consisting of primitive longs and Strings);

a Room DAO instance emitting these via a LiveData<List<MyDBRow>>; and

a UI expecting richer MyRichObject objects (POJOs with the primitives inflated into e.g. date/time objects)

so I need to transform my LiveData<List<MyDBRow>> into a LiveData<List<MyRichObject>>, but not on the UI thread.

The Transformations.map(LiveData<X>, Function<X, Y>) method does this needed transformation, but I can't use this because it executes the transformation on the main thread:

Applies the given function on the main thread to each value emitted by source LiveData and returns LiveData, which emits resulting values.

The given function func will be executed on the main thread.

What is a clean way to make LiveData transformations occur:

somewhere off the main thread, and

only as needed (i.e. only when something is observing the intended transformation)?

答:
How about like this:</p>

```<code>@Query("SELECT * FROM " + PeriodicElement.TABLE_NAME)
abstract fun getAll(): LiveData<List<PeriodicElement>>

fun getAllElements(): LiveData<HashMap<String, PeriodicElement>> {
    return Transformations.switchMap(getAll(), ::transform)
}

private fun transform(list: List<PeriodicElement>): LiveData<HashMap<String, PeriodicElement>> {
    val map = HashMap<String, PeriodicElement>()
    val liveData = MutableLiveData(map)

    AsyncTask.execute {
        for (p in list) {
            map[p.symbol] = p

            if (!liveData.hasObservers()) {
                //prevent memory leak
                break
            }
        }
        liveData.postValue(map)
    }
    return liveData
}
</code>```

Body:
How about like this:

@Query("SELECT * FROM " + PeriodicElement.TABLE_NAME)
abstract fun getAll(): LiveData<List<PeriodicElement>>

fun getAllElements(): LiveData<HashMap<String, PeriodicElement>> {
    return Transformations.switchMap(getAll(), ::transform)
}

private fun transform(list: List<PeriodicElement>): LiveData<HashMap<String, PeriodicElement>> {
    val map = HashMap<String, PeriodicElement>()
    val liveData = MutableLiveData(map)

    AsyncTask.execute {
        for (p in list) {
            map[p.symbol] = p

            if (!liveData.hasObservers()) {
                //prevent memory leak
                break
            }
        }
        liveData.postValue(map)
    }
    return liveData
}


问:
Angular `<router-outlet>` displays template twice
I'm using angular4 and trying to create a router link. The router link works but displays the template twice.

Below is my code in the component:

import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  template: `

Contacts App

Contact List

    <router-outlet></router-outlet>
    `
})
export class AppComponent {
    constructor(
        private route: ActivatedRoute,
        private router: Router,
    ){ }

    gotoDetail(): void {
        this.router.navigate(['facebook/top']);
    }
}
```

<p>my routes:</p>

<pre class="lang-js prettyprint-override"><code>const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'facebook/top',  component: CommentComponent },
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}
</code>```

答:
In your app-routing.module.ts file try to use:

```<code>{path: '' , redirectTo: 'AppComponent', pathMatch: 'full'}
</code>```

instead of:

```<code>{ path: '', component: AppComponent, pathMatch: 'full' }
</code>```

Body:
I'm using angular4 and trying to create a router link. The router link works but displays the template twice.

Below is my code in the component:

import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  template: `

Contacts App

Contact List

    <router-outlet></router-outlet>
    `
})
export class AppComponent {
    constructor(
        private route: ActivatedRoute,
        private router: Router,
    ){ }

    gotoDetail(): void {
        this.router.navigate(['facebook/top']);
    }
}

my routes:

const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'facebook/top',  component: CommentComponent },
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

Body:
In your app-routing.module.ts file try to use:

{path: '' , redirectTo: 'AppComponent', pathMatch: 'full'}

instead of:

{ path: '', component: AppComponent, pathMatch: 'full' }


问:
Ordering Grep Output With Multiple Patterns
The file I'm searching (fruit.text) looks something like the below snippet, the data appears in random order that I cannot control.

....fruit=apple,...qty=3,...condition=bad,....

...qty=4,...condition=great,...fruit=orange,...

...condition=ok,...qty=2,...fruit=banana,...

My Grep command is: grep -Eo 'fruit.[^,]*'\|'qty.[^,]*'\|'condition.[^,]*' fruit.txt

This results in output like:

fruit=apple

qty=3

condition=bad

qty=4

condition=great

fruit=orange

condition=ok

qty=2

fruit=banana

Which is correct, however, I'm looking for the output to be ordered as I specified in the grep cmd. ie, exactly like the below:

fruit=apple

qty=3

condition=bad

fruit=orange

qty=4

condition=great

fruit=banana

qty=2

condition=ok

答:
A solution with gawk:

first i added some extra ',' to the input:

```<code>....,fruit=apple,...,qty=3,...,condition=bad,....
...,qty=4,...,condition=great,...,fruit=orange,...
...,condition=ok,...,qty=2,...,fruit=banana,...
</code>```

Then i wrote this awk script (fruit.awk):

```<code>{ fruit ="";
  qty="";
  condition="";
  for (i = 1;i <= NF; i++){
        delete a;
        split($i,a,"=");
        if (a[1]=="fruit" ) { fruit=a[2]; }
        if (a[1]=="qty") { qty=a[2] }
        if (a[1]=="condition") { condition=a[2] }
   }
}
{ print "fruit=" fruit;
  print "qty=" qty;
  print "condition=" condition;
}
</code>```

output of: gawk -F , -f fruit.awk fruit.txt:

```<code>fruit=apple
qty=3
condition=bad
fruit=orange
qty=4
condition=great
fruit=banana
qty=2
condition=ok
</code>```

Body:
A solution with gawk:

first i added some extra ',' to the input:

....,fruit=apple,...,qty=3,...,condition=bad,....
...,qty=4,...,condition=great,...,fruit=orange,...
...,condition=ok,...,qty=2,...,fruit=banana,...

Then i wrote this awk script (fruit.awk):

{ fruit ="";
  qty="";
  condition="";
  for (i = 1;i <= NF; i++){
        delete a;
        split($i,a,"=");
        if (a[1]=="fruit" ) { fruit=a[2]; }
        if (a[1]=="qty") { qty=a[2] }
        if (a[1]=="condition") { condition=a[2] }
   }
}
{ print "fruit=" fruit;
  print "qty=" qty;
  print "condition=" condition;
}

output of: gawk -F , -f fruit.awk fruit.txt:

fruit=apple
qty=3
condition=bad
fruit=orange
qty=4
condition=great
fruit=banana
qty=2
condition=ok


问:
Not able to show RTSP stream with Angular
i'm working on a web application with angular where i need to show an rtsp stream inside my window.
I'm using JSMpeg player related to this topic : Not able to Show live camera RTSP streaming with Angular.

For my websocket i used the node websocket library and i runned it like this in my cmd : node websocket-relay.js supersecret 8081 8082

It detect each connection i make on it.

Then for the conversion part i used FFMPEG where I convert a h264 format to mpegts (mpegvideo1 gave me an error)
I run it like this :

ffmpeg -i "rtsp://myurl/media.smp" -vcodec h264 -f mpegts -max_muxing_queue_size 9999 -b 800k -r 30 http://localhost:8081/supersecret/640/480/

For the angular part I have this :

```<code>@ViewChild('streaming', {static: true}) streamingcanvas: ElementRef;

constructor( ... ) { }

ngOnInit() {
    ....
    let player = new JSMpeg.Player('ws://localhost:8081/supersecret', {
        canvas: this.streamingcanvas, autoplay: true, audio: false, loop: true
      })
}

</code>```

Result in my window :

What did i missed to make it works and get a real video stream?

Thanks for help

EDIT : My first ffmpeg command was wrong, only the audio was sent, now i got this :

```<code>ffmpeg -i "rtsp://myurl/media.smp" -vcodec h264 -f mpegts -codec:v mpeg1video -s 640x360 -b: 700k -r 25 -bf 0 -codec:a mp2 -ar 44100 -ac 1 -b:a 64k -max_muxing_queue_size 9999 http://localhost:8081/supersecret/640/360/
</code>```

It still doesnt work but the canvas is not black anymore

答:
```<code>Usage:
node websocket-relay.js <secret> [<stream-port> <websocket-port>]
</code>```

Try ws://localhost:8082/supersecret

Body:
i'm working on a web application with angular where i need to show an rtsp stream inside my window.
I'm using JSMpeg player related to this topic : Not able to Show live camera RTSP streaming with Angular.

For my websocket i used the node websocket library and i runned it like this in my cmd : node websocket-relay.js supersecret 8081 8082

It detect each connection i make on it.

Then for the conversion part i used FFMPEG where I convert a h264 format to mpegts (mpegvideo1 gave me an error)
I run it like this :

ffmpeg -i "rtsp://myurl/media.smp" -vcodec h264 -f mpegts -max_muxing_queue_size 9999 -b 800k -r 30 http://localhost:8081/supersecret/640/480/

For the angular part I have this :

@ViewChild('streaming', {static: true}) streamingcanvas: ElementRef;

constructor( ... ) { }

ngOnInit() {
    ....
    let player = new JSMpeg.Player('ws://localhost:8081/supersecret', {
        canvas: this.streamingcanvas, autoplay: true, audio: false, loop: true
      })
}

Result in my window :

What did i missed to make it works and get a real video stream?

Thanks for help

EDIT : My first ffmpeg command was wrong, only the audio was sent, now i got this :

ffmpeg -i "rtsp://myurl/media.smp" -vcodec h264 -f mpegts -codec:v mpeg1video -s 640x360 -b: 700k -r 25 -bf 0 -codec:a mp2 -ar 44100 -ac 1 -b:a 64k -max_muxing_queue_size 9999 http://localhost:8081/supersecret/640/360/

It still doesnt work but the canvas is not black anymore

Body:
Usage:
node websocket-relay.js <secret> [<stream-port> <websocket-port>]

Try ws://localhost:8082/supersecret


问:
How to create database and user in H2 DB in IDEA via script file?
I don't understand how to create user and database via H2 embedded DB in Intelij Idea

Can u write example of creation Database and User please with h2 syntax?

When I am trying to run this script :

```<code>CREATE USER GUEST PASSWORD 'abc';
</code>```

in this file createDatabaseAndUser.sql

in this program :

```<code>  Class.forName(JDBC_DRIVER);

        //STEP 2: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        //STEP 3: Execute a query
        ScriptRunner sr = new ScriptRunner(conn);
        //Creating a reader object
        Reader reader = new BufferedReader(new FileReader("C:\\PROJECTS\\src\\main\\resources\\createDatabaseAndUser.sql"));
        //Running the script
        sr.runScript(reader);
</code>```

I gained an error :
Error executing: CREATE USER GUEST PASSWORD 'abc'
.  Cause: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "CREATE[*] USER GUEST PASSWORD 'abc'
"; SQL statement:
CREATE USER GUEST PASSWORD 'abc'
 [42000-199]

答:
CREATE USER GUEST PASSWORD 'abc'; is really Syntax error in SQL statement. Because you write command in h2 syntax, but you have .sql extension in your migration file.

I don't exactly know how to solve this problem with H2 syntax. But you can solve it just by making your migration with SQL command.

Try to write this in your createDatabaseAndUser.sql file:

```<code>CREATE USER Guest WITH PASSWORD = 'abc';
</code>```

Body:
I don't understand how to create user and database via H2 embedded DB in Intelij Idea

Can u write example of creation Database and User please with h2 syntax?

When I am trying to run this script :

CREATE USER GUEST PASSWORD 'abc';

in this file createDatabaseAndUser.sql

in this program :

  Class.forName(JDBC_DRIVER);

        //STEP 2: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        //STEP 3: Execute a query
        ScriptRunner sr = new ScriptRunner(conn);
        //Creating a reader object
        Reader reader = new BufferedReader(new FileReader("C:\\PROJECTS\\src\\main\\resources\\createDatabaseAndUser.sql"));
        //Running the script
        sr.runScript(reader);

I gained an error :
Error executing: CREATE USER GUEST PASSWORD 'abc'
.  Cause: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "CREATE[*] USER GUEST PASSWORD 'abc'
"; SQL statement:
CREATE USER GUEST PASSWORD 'abc'
 [42000-199]

Body:
CREATE USER GUEST PASSWORD 'abc'; is really Syntax error in SQL statement. Because you write command in h2 syntax, but you have .sql extension in your migration file.

I don't exactly know how to solve this problem with H2 syntax. But you can solve it just by making your migration with SQL command.

Try to write this in your createDatabaseAndUser.sql file:

CREATE USER Guest WITH PASSWORD = 'abc';


问:
Keras/Tensorflow - Generate predictions in batch for imagenet (I get only one result back)
I am generating imagenet tags for all keyframes in a video with a single call and have this code:

```<code> # all keras/tf/mobilenet imports
model_imagenet = MobileNetV2(weights='imagenet')

frames_list = []
for frame in frame_set:
    frame_img = frame.to_image()
    frame_pil = frame_img.resize((224,224), Image.ANTIALIAS)
    ts = int(frame.pts)
    x = image.img_to_array(frame_pil)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    frames_list.append(x)

print(len(frames_list))

preds_list = model_imagenet.predict_on_batch(frames_list)
print("[*]",preds_list)
</code>```

The result appears thus:

```<code>frames_list count: 125
</code>```

and the predictions thus, one row of 1000 dimensions (imagenet classes), shouldn't it be 125 rows?:

```<code>[[1.15425530e-04 1.83317825e-04 4.28701424e-05 2.87547664e-05
                    :
  7.91769926e-05 1.30803732e-04 4.81895368e-05 3.06891889e-04]]
</code>```

This is generating prediction for a single row in the batch. I have tried both predict and predict_on_batch with the same result.

How can I get a bulk prediction for say 200 frames at one go with Keras/Tensorflow/Mobilenet?

答:
OK, here is how I solved it, hope this helps someone else:

```<code>preds_list = model_imagenet.predict(np.vstack(frames_list),batch_size=32)
print("[*]",preds_list)
</code>```

Please note the np.vstack and adjust the batch_size to whatever your computer is capable of.

Body:
I am generating imagenet tags for all keyframes in a video with a single call and have this code:

 # all keras/tf/mobilenet imports
model_imagenet = MobileNetV2(weights='imagenet')

frames_list = []
for frame in frame_set:
    frame_img = frame.to_image()
    frame_pil = frame_img.resize((224,224), Image.ANTIALIAS)
    ts = int(frame.pts)
    x = image.img_to_array(frame_pil)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    frames_list.append(x)

print(len(frames_list))

preds_list = model_imagenet.predict_on_batch(frames_list)
print("[*]",preds_list)

The result appears thus:

frames_list count: 125

and the predictions thus, one row of 1000 dimensions (imagenet classes), shouldn't it be 125 rows?:

[[1.15425530e-04 1.83317825e-04 4.28701424e-05 2.87547664e-05
                    :
  7.91769926e-05 1.30803732e-04 4.81895368e-05 3.06891889e-04]]

This is generating prediction for a single row in the batch. I have tried both predict and predict_on_batch with the same result.

How can I get a bulk prediction for say 200 frames at one go with Keras/Tensorflow/Mobilenet?

Body:
OK, here is how I solved it, hope this helps someone else:

preds_list = model_imagenet.predict(np.vstack(frames_list),batch_size=32)
print("[*]",preds_list)

Please note the np.vstack and adjust the batch_size to whatever your computer is capable of.


问:
Should I check the types of constructor arguments (and at other places too)?
Python discourages checking the types. But in many cases this may be useful:

Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.

Checking functions arguments.

In properties. If someone sets a wrong value or different type, I should respond quickly.

答:
"If I don't and set the object's members to the arguments it will cause problems later."

Please be very clear on the exact list of "problems" which will be caused later.

Will it not work at all?  That what try/except blocks are for.

Will it behave "oddly"?  This is really rare, and is limited to "near-miss" types and operators.  The standard example is division.  If you expected integers, but got floating-point, then division may not do what you wanted.  But that's fixed with the //, vs. / division operators.

Will it be simply wrong, but still appear to complete?  This is really rare, and would require a pretty-carefully crafted type that used standard names, but did non-standard things.  For example

```<code>class MyMaliciousList( list ):
    def append( self, value ):
        super( MyMaliciousList, self ).remove( value )
</code>```

Other than that, it's hard to have things "cause problems later".  Please update your question with specific examples of "problems".

OwnerDisplayName: Xolve

ContentLicense: CC BY-SA 2.5

Body:
"If I don't and set the object's members to the arguments it will cause problems later."

Please be very clear on the exact list of "problems" which will be caused later.

Will it not work at all?  That what try/except blocks are for.

Will it behave "oddly"?  This is really rare, and is limited to "near-miss" types and operators.  The standard example is division.  If you expected integers, but got floating-point, then division may not do what you wanted.  But that's fixed with the //, vs. / division operators.

Will it be simply wrong, but still appear to complete?  This is really rare, and would require a pretty-carefully crafted type that used standard names, but did non-standard things.  For example

class MyMaliciousList( list ):
    def append( self, value ):
        super( MyMaliciousList, self ).remove( value )

Other than that, it's hard to have things "cause problems later".  Please update your question with specific examples of "problems".


问:
Build fails with validation failed in Localizable.strings
I made Localizable.string files and compiled my project (my source code uses NSLocalizedString macro function) but my project doesn't compile because of the Localizable.string file. If I comment all the lines in the Localizable.string file, my project compiles successfully.

As result, the problem is related with the Localizable.string files. I searched about it on Google, I found that UTF-8 files (Localizable.string) has changed to UTF-16. And though I tried this... this way didn't work, too.

===============================================================

My Localizable.string file contains:

"LOCAL_APP_GRADE" = "Basic"

"LOCAL_APP_LAST_UPDATED_DATE" =
"2011/04/20"

"LOCAL_MAIN_MENU_TITLE" = "Main Menu"

In my source code:

```<code>NSLocalizedString( @"LOCAL_MAIN_MENU_TITLE", @"" );
</code>```

Error message:

Copy .strings file Error Validation failed: The data couldn't be read because it has been corrupted.

答:
I've been struggling with this same error, and ended up having a couple similar issues, but with different details. First off, even though it appears that Xcode's internal "builtin-copyStrings" tool should be able to handle either little-endian or big-endian UTF-16 files, it really only handles big endian. My theory is it's running some extra validation step (perhaps using the plutil command line utility) that didn't used to happen in Xcode 3, and that tool barfs on anything but big-endian UTF-16. Not entirely sure though.

The second trick is that you need to make sure your strings files are saved with no BOM (Byte Order Marker). I did some editing of my .strings files in BBEdit, which ended up saving a BOM to the file, and that also appears to make Xcode 4 have a conniption fit. Xcode itself doesn't appear to have any way to remove the BOM from the file, so this has to be done in a text editor such as BBEdit or TextWrangler which can do that for you.

Body:
I made Localizable.string files and compiled my project (my source code uses NSLocalizedString macro function) but my project doesn't compile because of the Localizable.string file. If I comment all the lines in the Localizable.string file, my project compiles successfully.

As result, the problem is related with the Localizable.string files. I searched about it on Google, I found that UTF-8 files (Localizable.string) has changed to UTF-16. And though I tried this... this way didn't work, too.

===============================================================

My Localizable.string file contains:

"LOCAL_APP_GRADE" = "Basic"

"LOCAL_APP_LAST_UPDATED_DATE" =
"2011/04/20"

"LOCAL_MAIN_MENU_TITLE" = "Main Menu"

In my source code:

NSLocalizedString( @"LOCAL_MAIN_MENU_TITLE", @"" );

Error message:

Copy .strings file Error Validation failed: The data couldn't be read because it has been corrupted.


问:
django base.html doesnt exist
This is my file tree

this is my error

this is views.py

```<code>def signup(request):
    proj = project.objects.all()
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'Homepage/Projects.html', {'form': form,"project":proj})
</code>```

urls.py

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    path('projects/', Homepage.views.signup, name='projects')
]
</code>```

my settings.py

html

did i miss something?

in my venv folder

答:
You are referring to the base.html of django admin site.

You need to create a base.html file inside your Homepage>templates folder so that you can use that as {% extends 'base.html' %}

Title: django base.html doesnt exist

Body:
This is my file tree

this is my error

this is views.py

def signup(request):
    proj = project.objects.all()
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'Homepage/Projects.html', {'form': form,"project":proj})

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('projects/', Homepage.views.signup, name='projects')
]

my settings.py

html

did i miss something?

in my venv folder


问:
Check whether any of the strings from one column match any of the strings from another column
I have a situation like this:

```<code>lst = ["Apple", "Apple", "Apple small", "Orange", "FruitX", "FruitY"]
lst2 = ["Apple", "Orange", "Fruit1", "Fruit2"]
</code>```

Where lst and lst2 are pandas series (or columns in a dataframe I should say).

I need to find which of the values from lst2 are in lst and in the end create a dataframe with the results as follows (ideally with the number of matched values and with the ability to also add other columns from lst ():

```<code>lst2     lst        match_count    other_colum_from_lstDF    other_colum_from_lstDF
Apple    Apple      2              info1                     info2
Apple    Apple      2              info1                     info2
Orange   Orange     1              info1                     info2
Fruit1   nan        0              nan                       nan
Fruit2   nan        0              nan                       nan
</code>```

So you can match multiple values from lst to one value from lst2, so I would need the results duplicated as per above, ideally with the number of matched values.

I think the right way would be to use isin but wasn't able to figure out how.

答:
Use pd.merge:

```<code>df_merge = pd.merge(df2, df1, how = 'left', left_on = 'lst2', right_on = 'lst')
df_merge['match_count'] = df_merge.groupby(['lst'])['lst'].transform('count').fillna(0)
df_merge = df_merge[['lst2','lst','match_count','info1']]
</code>```

Output is:

```<code>    lst2    lst match_count info1
0   Apple   Apple   2.0     info1
1   Apple   Apple   2.0     info1
2   Orange  Orange  1.0     info1
3   Fruit1  NaN     0.0      NaN
4   Fruit2  NaN     0.0      NaN

</code>```

Body:
I have a situation like this:

lst = ["Apple", "Apple", "Apple small", "Orange", "FruitX", "FruitY"]
lst2 = ["Apple", "Orange", "Fruit1", "Fruit2"]

Where lst and lst2 are pandas series (or columns in a dataframe I should say).

I need to find which of the values from lst2 are in lst and in the end create a dataframe with the results as follows (ideally with the number of matched values and with the ability to also add other columns from lst ():

lst2     lst        match_count    other_colum_from_lstDF    other_colum_from_lstDF
Apple    Apple      2              info1                     info2
Apple    Apple      2              info1                     info2
Orange   Orange     1              info1                     info2
Fruit1   nan        0              nan                       nan
Fruit2   nan        0              nan                       nan

So you can match multiple values from lst to one value from lst2, so I would need the results duplicated as per above, ideally with the number of matched values.

I think the right way would be to use isin but wasn't able to figure out how.

Body:
Use pd.merge:

df_merge = pd.merge(df2, df1, how = 'left', left_on = 'lst2', right_on = 'lst')
df_merge['match_count'] = df_merge.groupby(['lst'])['lst'].transform('count').fillna(0)
df_merge = df_merge[['lst2','lst','match_count','info1']]

Output is:

    lst2    lst match_count info1
0   Apple   Apple   2.0     info1
1   Apple   Apple   2.0     info1
2   Orange  Orange  1.0     info1
3   Fruit1  NaN     0.0      NaN
4   Fruit2  NaN     0.0      NaN


问:
Is it a bad idea to construct http ETag headers using database primary keys?

Can I use a database key (from an immutable object) as an ETag?

I am trying to get browser and/or proxy caching to work for my web application (happens to be python/flask, but I don't think that's particularly relevant).  In everything I've read about ETags, they are usually discussed as being a hash of the (presumably static) resource.

In my case, I have a class of objects in my database that are not editable. Several different views can be generated for each one of these objects.  Generating the views, at least some of them, requires some work on the server, but in general the resulting output is lightweight.  So doing the work to generate the whole page, then taking the hash, would be inefficient, and I may as well just send the response at that point.

My thinking is, because each view is built on an immutable database object, that object's key (plus the URL of the request) is enough to know whether the client's cache is good or not.  But that would mean using the same ETag for lots of different resources.  As far as I can tell it seems like this should work, but

Is it against an official spec for how ETags are supposed to be used? E.g. is there always supposed to be a unique ETag for different resources?

Is it going to be a bad idea for some other reason?

A bit more context

My application has URLs of the form:

 example.com/view/<name>/<version>/<view>/<additional view args>

The DB has a unique index on the combination of <name> and <version>. But there is a special keyword latest for version, which causes the server to find the most recent entry with <name>.  No matter what view is requested, it is fully defined by the object found by name and version.  So if a client sends a request header with If-none-match: <key>, I would always return 304 regardless of the view requested unless (a) they requested the latest version and (b) the primary key of the latest version in the DB does not match the If-none-match header.

答:
I suggest reading RFC 7232, which is fairly straightforward and will give you an excellent understanding of conditional validation.

Your desire to avoid computing the response before knowing if there's a match is both sensible and allowable. As the standard makes clear, it's up to you to choose the opaque value. Hashes are just one special case of that. (In fact they require special mention because collisions are theoretically possible.) The standard specifically gives the example of using a version number for the ETag:

For example, a resource that has implementation-specific versioning
applied to all changes might use an internal revision number, perhaps
combined with a variance identifier for content negotiation, to
accurately differentiate between representations.

You also ask if the ETag needs to be different for each resource. The answer is no:

There is
no implication of uniqueness across representations of different
resources (i.e., the same strong validator might be in use for
representations of multiple resources at the same time and does not
imply that those representations are equivalent).

Some would be concerned about exposing database IDs to the client. I don't have a strong feeling about that, but of course that's easily avoided by hashing or otherwise obscuring the ID.

Looking at your specific design, though, it appears that simply using the version for your ETag would be sufficient. In fact, for all resources other than latest it appears that there's only one possible representation. If so, you should set those entries to be cached forever, and it doesn't really matter what the ETag is. Then for latest use a short cache time and use the version (or primary key, if you prefer) for the ETag.


问:
I'm having these error's in my Android Studio, I'm unable to even start the project

ERROR: Unable to resolve dependency for ':app@debug/compileClasspath':
  Could not resolve com.android.support:appcompat-v7:29.+. Show Details
  Affected Modules: app

ERROR: Unable to resolve dependency for
  ':app@debugAndroidTest/compileClasspath': Could not resolve
  com.android.support:appcompat-v7:29.+. Show Details Affected Modules:
  app

ERROR: Unable to resolve dependency for
  ':app@debugUnitTest/compileClasspath': Could not resolve
  com.android.support:appcompat-v7:29.+. Show Details Affected Modules:
  app

答:
```<code>android {
    compileSdkVersion 28
    buildToolsVersion "28.0.2"
    defaultConfig {
        applicationId "com.example.example"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.android.support:support-v4:28.0.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.material:material:1.0.0'

}
</code>```


问:
np.outer output changes when stored in an array
I have a NxN matrix which I am interested in its eigenvalue decomposition in order to obtain P=exp(tA). In order to evaluate the P_ij(t) functions, I want to prepare a E=NxNxN matrix where E is the outer product of v[i] and np.linalg.inv(v)[i] and v[i] is one of the eigenvectors.

The sample code with my 3x3 toy matrix is as

def eig_trial(A,n):
        v,w=np.linalg.eig(A)
        w_inv=np.linalg.inv(
        eigs=np.array([[[0 for k in xrange(len(v))] for j in xrange(n)] for i in xrange(n)])
        for i in range(len(v)):
            q=np.outer(np.array(w[:,i]),np.array(w_inv[i]))
            eigs[i]=q
        pprint.pprint(eigs)

A=np.asarray([[6,3,-2],[-4, -1, 2],[13,9,-3]])
eig_trial(A,3)
```

The problem is, q=np.outer(...), which is the correct value, is not equal to eigs[i].

Is there a reason why I can't store this into a matrix? If it helps, I am using Canopy Version: 2.1.9.3717 (64 bit) and Python 2.7.13.

Thanks!

答:
I literally have no idea but I found a weird workaround. The problem is due to eigs being an array. It works if it is a list of lists.

def eig_trial(A,n):
        v,w=np.linalg.eig(A)
        w_inv=np.linalg.inv(
        eigs=[[[0 for k in xrange(len(v))] for j in xrange(n)] for i in xrange(n)] #np.array dropped
        for i in range(len(v)):
            q=np.outer(np.array(w[:,i]),np.array(w_inv[i]))
            eigs[i]=q
        eigs=np.asarray(eigs) #now convert it to an np array
        pprint.pprint(eigs)

A=np.asarray([[6,3,-2],[-4, -1, 2],[13,9,-3]])
eig_trial(A,3)
```

I would be very happy if someone explains why, but this is at least a solution.

Body:
I have a NxN matrix which I am interested in its eigenvalue decomposition in order to obtain P=exp(tA). In order to evaluate the P_ij(t) functions, I want to prepare a E=NxNxN matrix where E is the outer product of v[i] and np.linalg.inv(v)[i] and v[i] is one of the eigenvectors.

The sample code with my 3x3 toy matrix is as

def eig_trial(A,n):
        v,w=np.linalg.eig(A)
        w_inv=np.linalg.inv(
        eigs=np.array([[[0 for k in xrange(len(v))] for j in xrange(n)] for i in xrange(n)])
        for i in range(len(v)):
            q=np.outer(np.array(w[:,i]),np.array(w_inv[i]))
            eigs[i]=q
        pprint.pprint(eigs)

A=np.asarray([[6,3,-2],[-4, -1, 2],[13,9,-3]])
eig_trial(A,3)

The problem is, q=np.outer(...), which is the correct value, is not equal to eigs[i].

Is there a reason why I can't store this into a matrix? If it helps, I am using Canopy Version: 2.1.9.3717 (64 bit) and Python 2.7.13.

Thanks!

Body:
I literally have no idea but I found a weird workaround. The problem is due to eigs being an array. It works if it is a list of lists.

def eig_trial(A,n):
        v,w=np.linalg.eig(A)
        w_inv=np.linalg.inv(
        eigs=[[[0 for k in xrange(len(v))] for j in xrange(n)] for i in xrange(n)] #np.array dropped
        for i in range(len(v)):
            q=np.outer(np.array(w[:,i]),np.array(w_inv[i]))
            eigs[i]=q
        eigs=np.asarray(eigs) #now convert it to an np array
        pprint.pprint(eigs)

A=np.asarray([[6,3,-2],[-4, -1, 2],[13,9,-3]])
eig_trial(A,3)

I would be very happy if someone explains why, but this is at least a solution.


问:
Nativescript Greensock issue - Module not found: Error: Can't resolve 'TweenLite'
I would love to use webview with PixiJS and Greensock (GSAP) in my Nativescript app. I have no problem to add TweenMax.min.js but when I have more GSAP files like for instance plugins/PixiPlugin.min.js - on $ tns run ios I have something like this:

```<code>ERROR in ./assets/game/js/gsap/plugins/PixiPlugin.min.js
Module not found: Error: Can't resolve 'TweenLite' in '/systemfolder/app/assets/game/js/gsap/plugins'
 @ ./assets/game/js/gsap/plugins/PixiPlugin.min.js 287:153-177
 @ . sync (?<!\bApp_Resources\b.*)(?<!\.\/\btests\b\/.*?)\.(xml|css|js|(?<!\.d\.)ts|(?<!\b_[\w-]*\.)scss)$
 @ ./app.js
</code>```

and I stuck at this point so app does not run. Any clue?

答: Migration from Greensock 2 to GSAP 3 resolved my issue. https://greensock.com/</p>

Body:
I would love to use webview with PixiJS and Greensock (GSAP) in my Nativescript app. I have no problem to add TweenMax.min.js but when I have more GSAP files like for instance plugins/PixiPlugin.min.js - on $ tns run ios I have something like this:

ERROR in ./assets/game/js/gsap/plugins/PixiPlugin.min.js
Module not found: Error: Can't resolve 'TweenLite' in '/systemfolder/app/assets/game/js/gsap/plugins'
 @ ./assets/game/js/gsap/plugins/PixiPlugin.min.js 287:153-177
 @ . sync (?<!\bApp_Resources\b.*)(?<!\.\/\btests\b\/.*?)\.(xml|css|js|(?<!\.d\.)ts|(?<!\b_[\w-]*\.)scss)$
 @ ./app.js

and I stuck at this point so app does not run. Any clue?


问:
How to set default avatar to user in rails?
I would like my users to have a default avatar. So I try this in a helper.

```<code>  def show_avatar(user)
    if File.exist?("/public/uploads/users/#{user.id}/avatar.jpg")
        image_tag ("accueil/profile_default.png"), class: 'rounded-circle', alt: "#{user.username}"
    else
      image_tag user.avatar_url, class: 'rounded-circle', alt: "#{user.username}"
    end
  end
</code>```

But I don't understand why it doesn't work. I also tried with Dir.empty? but also without result.
Thank you for your help.

答:
File.exist?("/public/uploads/users/#{user.id}/avatar.jpg") will check the path from the root of your file system - not the root of your Rails app. Your logic is also backwards.

```<code>def show_avatar(user)
  if File.exist?(Rails.root.join("/public/uploads/users/#{user.id}/avatar.jpg"))
    image_tag user.avatar_url, class: 'rounded-circle', alt: user.username
  else
    image_tag "accueil/profile_default.png", class: 'rounded-circle', alt: user.username
   nd
end
</code>```

Body:
I would like my users to have a default avatar. So I try this in a helper.

  def show_avatar(user)
    if File.exist?("/public/uploads/users/#{user.id}/avatar.jpg")
        image_tag ("accueil/profile_default.png"), class: 'rounded-circle', alt: "#{user.username}"
    else
      image_tag user.avatar_url, class: 'rounded-circle', alt: "#{user.username}"
    end
  end

But I don't understand why it doesn't work. I also tried with Dir.empty? but also without result.
Thank you for your help.

Body:
File.exist?("/public/uploads/users/#{user.id}/avatar.jpg") will check the path from the root of your file system - not the root of your Rails app. Your logic is also backwards.

def show_avatar(user)
  if File.exist?(Rails.root.join("/public/uploads/users/#{user.id}/avatar.jpg"))
    image_tag user.avatar_url, class: 'rounded-circle', alt: user.username
  else
    image_tag "accueil/profile_default.png", class: 'rounded-circle', alt: user.username
   nd
end


问:
Change in the Dimension (shape) because of np.hstack on tf.keras.preprocessing.text.Tokenizer.texts_to_sequences
I have applied np.hstack on tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences for both Training Labels and for Validation (Testing) Labels.

Surprisingly and mystically, the Size of the Output, after I applied on Training Labels is different that of before I have applied np.hstack. However, there is no Change in the Shape for Validation Labels, before and after the application of tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences and np.hstack.

This is the Link of the Google Colab, to reproduce the error easily.

Complete Code to reproduce the Error is given below (just in case if the link doesn't work):

```<code>!pip install tensorflow==2.1

# For Preprocessing the Text => To Tokenize the Text
from tensorflow.keras.preprocessing.text import Tokenizer
# If the Two Articles are of different length, pad_sequences will make the length equal
from tensorflow.keras.preprocessing.sequence import pad_sequences

# Package for performing Numerical Operations
import numpy as np

Unique_Labels_List = ['India', 'USA', 'Australia', 'Germany', 'Bhutan', 'Nepal', 'New Zealand', 'Israel', 'Canada', 'France', 'Ireland', 'Poland', 'Egypt', 'Greece', 'China', 'Spain', 'Mexico']

Train_Labels = Unique_Labels_List[0:14]
#print('Train Labels = {}'.format(Train_Labels))

Val_Labels =  Unique_Labels_List[14:]
#print('Val_Labels = {}'.format(Val_Labels))

No_Of_Train_Items = [248, 200, 200, 218, 248, 248, 249, 247, 220, 200, 200, 211, 224, 209]
No_Val_Items = [212, 200, 219]

T_L = []
for Each_Label, Item in zip(Train_Labels, No_Of_Train_Items):
    T_L.append([Each_Label] * Item)

T_L = [item for sublist in T_L for item in sublist]

V_L = []
for Each_Label, Item in zip(Val_Labels, No_Val_Items):
    V_L.append([Each_Label] * Item)

V_L = [item for sublist in V_L for item in sublist]

len(T_L)

len(V_L)

label_tokenizer = Tokenizer()

label_tokenizer.fit_on_texts(Unique_Labels_List)

# Since it should be a Numpy Array, we should Convert the Sequences to Numpy Array, for both Training and
# Test Labels

training_label_list = label_tokenizer.texts_to_sequences(T_L)

validation_label_list = label_tokenizer.texts_to_sequences(V_L)

training_label_seq = np.hstack(training_label_list)

validation_label_seq = np.hstack(validation_label_list)

print('Actual Number of Train Labels before np.hstack are {}'.format(len(training_label_list)))
print('Change in the Number of Train Labels because of np.hstack are {}'.format(len(training_label_seq)))

print('-------------------------------------------------------------------------------------------------------')

print('Actual Number of Validation Labels before np.hstack are {}'.format(len(validation_label_list)))
print('However, there is no change in the Number of Validation Labels because of np.hstack {}'.format(len(validation_label_seq)))
</code>```

Thank you in advance.

答:
It's because you have lists with multiple values in training_label_list. You can verify by sorted(training_label_list, key=lambda x: len(x), reverse = True).

It happened because label_tokenizer considering New Zealand in the below manner.

>>>label_tokenizer.index_word
{1: 'india',
 2: 'usa',
 3: 'australia',
 4: 'germany',
 5: 'bhutan',
 6: 'nepal',
 7: 'new',
 8: 'zealand',
 9: 'israel',
 10: 'canada',
 11: 'france',
 12: 'ireland',
 13: 'poland',
 14: 'egypt',
 15: 'greece',
 16: 'china',
 17: 'spain',
 18: 'mexico'}
```

Checkout the indexes 7 & 8.

Body:
I have applied np.hstack on tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences for both Training Labels and for Validation (Testing) Labels.

Surprisingly and mystically, the Size of the Output, after I applied on Training Labels is different that of before I have applied np.hstack. However, there is no Change in the Shape for Validation Labels, before and after the application of tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences and np.hstack.

This is the Link of the Google Colab, to reproduce the error easily.

Complete Code to reproduce the Error is given below (just in case if the link doesn't work):

!pip install tensorflow==2.1

# For Preprocessing the Text => To Tokenize the Text
from tensorflow.keras.preprocessing.text import Tokenizer
# If the Two Articles are of different length, pad_sequences will make the length equal
from tensorflow.keras.preprocessing.sequence import pad_sequences

# Package for performing Numerical Operations
import numpy as np

Unique_Labels_List = ['India', 'USA', 'Australia', 'Germany', 'Bhutan', 'Nepal', 'New Zealand', 'Israel', 'Canada', 'France', 'Ireland', 'Poland', 'Egypt', 'Greece', 'China', 'Spain', 'Mexico']

Train_Labels = Unique_Labels_List[0:14]
#print('Train Labels = {}'.format(Train_Labels))

Val_Labels =  Unique_Labels_List[14:]
#print('Val_Labels = {}'.format(Val_Labels))

No_Of_Train_Items = [248, 200, 200, 218, 248, 248, 249, 247, 220, 200, 200, 211, 224, 209]
No_Val_Items = [212, 200, 219]

T_L = []
for Each_Label, Item in zip(Train_Labels, No_Of_Train_Items):
    T_L.append([Each_Label] * Item)

T_L = [item for sublist in T_L for item in sublist]

V_L = []
for Each_Label, Item in zip(Val_Labels, No_Val_Items):
    V_L.append([Each_Label] * Item)

V_L = [item for sublist in V_L for item in sublist]

len(T_L)

len(V_L)

label_tokenizer = Tokenizer()

label_tokenizer.fit_on_texts(Unique_Labels_List)

# Since it should be a Numpy Array, we should Convert the Sequences to Numpy Array, for both Training and
# Test Labels

training_label_list = label_tokenizer.texts_to_sequences(T_L)

validation_label_list = label_tokenizer.texts_to_sequences(V_L)

training_label_seq = np.hstack(training_label_list)

validation_label_seq = np.hstack(validation_label_list)

print('Actual Number of Train Labels before np.hstack are {}'.format(len(training_label_list)))
print('Change in the Number of Train Labels because of np.hstack are {}'.format(len(training_label_seq)))

print('-------------------------------------------------------------------------------------------------------')

print('Actual Number of Validation Labels before np.hstack are {}'.format(len(validation_label_list)))
print('However, there is no change in the Number of Validation Labels because of np.hstack {}'.format(len(validation_label_seq)))

Thank you in advance.

Body:
It's because you have lists with multiple values in training_label_list. You can verify by sorted(training_label_list, key=lambda x: len(x), reverse = True).

It happened because label_tokenizer considering New Zealand in the below manner.

>>>label_tokenizer.index_word
{1: 'india',
 2: 'usa',
 3: 'australia',
 4: 'germany',
 5: 'bhutan',
 6: 'nepal',
 7: 'new',
 8: 'zealand',
 9: 'israel',
 10: 'canada',
 11: 'france',
 12: 'ireland',
 13: 'poland',
 14: 'egypt',
 15: 'greece',
 16: 'china',
 17: 'spain',
 18: 'mexico'}

Checkout the indexes 7 & 8.


问:
How to create a python exception with multiple causes?
How do I raise a python exception with multiple causes, similar to Java's addSuppressed() feature? For example I have list of multiple methods to try and if none of them work I want to raise an exception that includes the exceptions from all the methods that were tried. I.e.:

exceptions = []
for method in methods_to_try:
  try:
    method()
  except Exception as e:
    exceptions.append(e)
if exceptions:
  raise Exception("All methods failed") from exceptions
```

But this code fails because the raise ... from ... statement expects a single exception and not a list. Python 2 or 3 solutions are acceptable. All back traces and exception messages must be preserved.

答:
Once could raise each exception from the other to chain it. The only issue is with the cause order which may be misleading.</p>

```<code>def combine_exc(exceptions):
   c_exc = None
   for ex in reversed(exceptions):
      try:
         if c_exc is None:
            raise ex
         else:
            raise ex from c_exc
      except Exception as ex1:
         c_exc = ex1

   return c_exc
</code>```

Body:
How do I raise a python exception with multiple causes, similar to Java's addSuppressed() feature? For example I have list of multiple methods to try and if none of them work I want to raise an exception that includes the exceptions from all the methods that were tried. I.e.:

exceptions = []
for method in methods_to_try:
  try:
    method()
  except Exception as e:
    exceptions.append(e)
if exceptions:
  raise Exception("All methods failed") from exceptions

But this code fails because the raise ... from ... statement expects a single exception and not a list. Python 2 or 3 solutions are acceptable. All back traces and exception messages must be preserved.

Body:
Once could raise each exception from the other to chain it. The only issue is with the cause order which may be misleading.

def combine_exc(exceptions):
   c_exc = None
   for ex in reversed(exceptions):
      try:
         if c_exc is None:
            raise ex
         else:
            raise ex from c_exc
      except Exception as ex1:
         c_exc = ex1

   return c_exc


问:
Mysql if else with multiple conditions
Can anyone of you help me out to build a Select query for the following table like Data.

I have a similar table, from what i need to select query is with the following conditions

Get all records where

1. delete is '0'

2. AND If delete is '1' then the year should be > 2019

3. AND If delete is '1' and Year is = 2019 then the month should be > 2

```<code>------------------------------------
id , name , delete , year , month
------------------------------------
1 , apple ,     0 , 0000 , 0
2 , orange ,    1 , 2019 , 3
3 , grapes ,    1 , 2018 , 4
4 , Banana ,    1 , 2019 , 1
5 , Pears ,     0 , 0000 , 0
6 , Pineapple , 1 , 2020 , 3
7 , watermelon ,1 , 2019 , 2
</code>```

The Results should be

```<code>1 , apple ,     0 , 0000 , 0
2 , orange ,    1 , 2019 , 3
5 , Pears ,     0 , 0000 , 0
6 , Pineapple , 1 , 2020 , 3
</code>```

答:
Use

```<code>SELECT
  *
FROM
  Table1
  Where
     `delete` = 0
     OR (`delete` = 1 AND `year` > 2019)
     OR (`delete` = 1 AND `year` = 2019 AND `month` > 2)
</code>```

The result http://sqlfiddle.com/#!9/c7ae8f/1

Title: Mysql if else with multiple conditions

Body:
Can anyone of you help me out to build a Select query for the following table like Data.

I have a similar table, from what i need to select query is with the following conditions

Get all records where

1. delete is '0'

2. AND If delete is '1' then the year should be > 2019

3. AND If delete is '1' and Year is = 2019 then the month should be > 2

------------------------------------
id , name , delete , year , month
------------------------------------
1 , apple ,     0 , 0000 , 0
2 , orange ,    1 , 2019 , 3
3 , grapes ,    1 , 2018 , 4
4 , Banana ,    1 , 2019 , 1
5 , Pears ,     0 , 0000 , 0
6 , Pineapple , 1 , 2020 , 3
7 , watermelon ,1 , 2019 , 2

The Results should be

1 , apple ,     0 , 0000 , 0
2 , orange ,    1 , 2019 , 3
5 , Pears ,     0 , 0000 , 0
6 , Pineapple , 1 , 2020 , 3

Body:
Use

SELECT
  *
FROM
  Table1
  Where
     `delete` = 0
     OR (`delete` = 1 AND `year` > 2019)
     OR (`delete` = 1 AND `year` = 2019 AND `month` > 2)

The result http://sqlfiddle.com/#!9/c7ae8f/1


问:
Mixed Date formats in R data frame
how do you work with a column of mixed date types, for example 8/2/2020,2/7/2020, and all are reflecting February,
I have tried zoo::as.Date(mixeddatescolumn,"%d/%m/%Y").The first one is right but the second is wrong.

i have tried solutions here too
Fixing mixed date formats in data frame? but the questions seems different from what i am handling.

答:
Since we know that every month is in February search for /2/ or /02/ and if found the middle number is the month; otherwise, the first number is the month. In either case set the format appropriately and use as.Date.  No packages are used.

```<code>dates <- c("8/2/2020", "2/7/2020", "2/28/2000", "28/2/2000") # test data

as.Date(dates, ifelse(grepl("/0?2/", dates), "%d/%m/%Y", "%m/%d/%Y"))
## [1] "2020-02-08" "2020-02-07" "2000-02-28" "2000-02-28"
</code>```

Title: Mixed Date formats in R data frame

Body:
Since we know that every month is in February search for /2/ or /02/ and if found the middle number is the month; otherwise, the first number is the month. In either case set the format appropriately and use as.Date.  No packages are used.

dates <- c("8/2/2020", "2/7/2020", "2/28/2000", "28/2/2000") # test data

as.Date(dates, ifelse(grepl("/0?2/", dates), "%d/%m/%Y", "%m/%d/%Y"))
## [1] "2020-02-08" "2020-02-07" "2000-02-28" "2000-02-28"


问:
An empty
 tag is automatically getting inserted, how do I get rid of it?
An empty

 tag is getting inserted automatically when the page is rendered, I'm not sure, how to get rid of it. Which is adding unwanted space on the webpage.

I'm not sure how I can get rid of it. I'm trying to set the margin-bottom for the
 to 0px, even that isn't getting applied as well.

I would be really thankful to anyone who could help me with fixing this issue.

Thanks in advance!

Here is the code which renders the HTML block:
The

 tag gets generated dynamically, but not sure, how it is getting generated from the code.

```<code>{% if job_detail.type != '' and job_detail.type is not None or job_detail.age_limit != '' and job_detail.age_limit is not None %}
     <hr />
     <div class="row">
     {% if job_detail.type != '' and job_detail.type is not None %}
       <div class="col-md-6">
         <h3 class="card-title topic-title">JOB TYPE</h3>
         <p class="card-text topic-text last-child">{{ job_detail.type|linebreaks }}</p>
       </div>
     {% endif %}
     {% if job_detail.age_limit != '' and job_detail.age_limit is not None %}
       <div class="col-md-6 mt-4 mt-sm-4 mt-md-0">
         <h3 class="card-title topic-title">AGE LIMIT</h3>
         <p class="card-text topic-text last-child">{{ job_detail.age_limit|linebreaks }}</p>
       </div>
     {% endif %}
     </div>
   {% endif %}
</code>```

答:
I was able to fix this issue by adding the following style to the paragraph tag ```margin-bottom: 0!important

Thanks everyone for your time and assistance!

Title: An empty <p> tag is automatically getting inserted, how do I get rid of it?

Body:
An empty

 tag is getting inserted automatically when the page is rendered, I'm not sure, how to get rid of it. Which is adding unwanted space on the webpage.

I'm not sure how I can get rid of it. I'm trying to set the margin-bottom for the
 to 0px, even that isn't getting applied as well.

I would be really thankful to anyone who could help me with fixing this issue.

Thanks in advance!

Here is the code which renders the HTML block:
The

 tag gets generated dynamically, but not sure, how it is getting generated from the code.

{% if job_detail.type != '' and job_detail.type is not None or job_detail.age_limit != '' and job_detail.age_limit is not None %}

     {% if job_detail.type != '' and job_detail.type is not None %}

JOB TYPE

{{ job_detail.type|linebreaks }}

     {% endif %}
     {% if job_detail.age_limit != '' and job_detail.age_limit is not None %}

AGE LIMIT

{{ job_detail.age_limit|linebreaks }}

     {% endif %}

   {% endif %}