问:
Delete mapping doesn't work, I'm getting 405 error
I have this controller:

```<code>  @DeleteMapping("/delete/{id}")
  public String deleteWallet(@PathVariable("id") long id, Model model) {
    Wallet wallet = walletRepository.findById(id)
            .orElseThrow(() -> new IllegalArgumentException("Invalid wallet Id:" + id));
    walletRepository.delete(wallet);
    model.addAttribute("wallets", walletRepository.findAll());
    return "redirect:/";
}
</code>```

And this is HTML:

```<code><table class="table table-striped table-hover" id="productTable">
<thead>
<tr class="success">
    <th>Wallet Name</th>
    <th>Initial Balance</th>
</tr>
</thead>
<tbody>
<tr th:each="wallet : ${wallet}">
    <td th:text="${wallet.walletName}"></td>
    <td th:text="${wallet.initialBalance}"></td>
    <td>
        <a th:href="@{/api/wallet/delete/{id}(id = ${wallet.id})}">Delete</a>
    </td>
</tr>
</tbody>
</code>```

But when I press delete button its says:

Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]

I'm confused, my method is @DeleteMapping

Anyway, I found a way:

HTML:

```<code><form th:action="@{/api/wallet/delete/{id}(id=${wallet.id})}"
th:object="${wallet}" method="post">
            <input type="hidden" th:field="${wallet}">Delete</input>
            <button type="submit" onClick="return confirm('sure?')"/>
        </form>
</code>```

Controller:

```<code> @PostMapping("/delete/{id}")
 public String deleteWallet(@PathVariable("id") long id, Model model) {
    walletService.deleteWalletById(id);
    return "redirect:/";
}
</code>```

Body:
I have this controller:

  @DeleteMapping("/delete/{id}")
  public String deleteWallet(@PathVariable("id") long id, Model model) {
    Wallet wallet = walletRepository.findById(id)
            .orElseThrow(() -> new IllegalArgumentException("Invalid wallet Id:" + id));
    walletRepository.delete(wallet);
    model.addAttribute("wallets", walletRepository.findAll());
    return "redirect:/";
}

And this is HTML:

    Wallet Name
    Initial Balance

        Delete

But when I press delete button its says:

Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]

I'm confused, my method is @DeleteMapping

Anyway, I found a way:

HTML:

<form th:action="@{/api/wallet/delete/{id}(id=${wallet.id})}"
th:object="${wallet}" method="post">
            <input type="hidden" th:field="${wallet}">Delete</input>
            <button type="submit" onClick="return confirm('sure?')"/>
        </form>

Controller:

 @PostMapping("/delete/{id}")
 public String deleteWallet(@PathVariable("id") long id, Model model) {
    walletService.deleteWalletById(id);
    return "redirect:/";
}


来源: stackexchange

问:
Heroku Push rejected, Next.js
Next.js App, all work fine on localhost, when I push to Heroku, Push rejected, idk why. Please help my heroes.

Heroku Push logs:

```<code>remote: -----> Installing binaries
remote:        engines.node (package.json):  unspecified
remote:        engines.npm (package.json):   unspecified (use default)
remote:
remote:        Resolving node version 18.x...
remote:        Downloading and installing node 18.12.1...
remote:        Using default npm version: 8.19.2
remote:
remote: -----> Installing dependencies
remote:        Installing node modules
remote:        npm ERR! code ERESOLVE
remote:        npm ERR! ERESOLVE could not resolve
remote:        npm ERR!
remote:        npm ERR! While resolving: react-lightgallery@0.9.0
remote:        npm ERR! Found: react@18.2.0
remote:        npm ERR! node_modules/react
remote:        npm ERR!   react@"^18.2.0" from the root project
remote:        npm ERR!   peer react@"^17.0.2 || ^18.0.0-0" from next@12.2.6
remote:        npm ERR!   node_modules/next
remote:        npm ERR!     next@"12.2" from the root project
remote:        npm ERR!   9 more (react-circular-progressbar, react-dom, react-modal, ...)
remote:        npm ERR!
remote:        npm ERR! Could not resolve dependency:
remote:        npm ERR! peer react@"^16.13.1" from react-lightgallery@0.9.0
remote:        npm ERR! node_modules/react-lightgallery
remote:        npm ERR!   react-lightgallery@"^0.9.0" from the root project
remote:        npm ERR!
remote:        npm ERR! Conflicting peer dependency: react@16.14.0
remote:        npm ERR! node_modules/react
remote:        npm ERR!   peer react@"^16.13.1" from react-lightgallery@0.9.0
remote:        npm ERR!   node_modules/react-lightgallery
remote:        npm ERR!     react-lightgallery@"^0.9.0" from the root project
remote:        npm ERR!
remote:        npm ERR! Fix the upstream dependency conflict, or retry
remote:        npm ERR! this command with --force, or --legacy-peer-deps
remote:        npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
remote:        npm ERR!
remote:        npm ERR! See /tmp/npmcache.WP8R2/eresolve-report.txt for a full report.
remote:
remote:        npm ERR! A complete log of this run can be found in:
remote:        npm ERR!     /tmp/npmcache.WP8R2/_logs/2022-12-16T21_23_22_466Z-debug-0.log
remote:
remote: -----> Build failed

</code>```

package.json:

```<code>{
  "name": "test-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start -p $PORT",
    "lint": "next lint"
  },
  "dependencies": {
    "isotope-layout": "^3.0.6",
    "next": "12.2",
    "particles.js": "^2.0.0",
    "react": "^18.2.0",
    "react-circular-progressbar": "^2.1.0",
    "react-dom": "^18.2.0",
    "react-lightgallery": "^0.9.0",
    "react-modal": "^3.15.1",
    "react-modal-video": "^1.2.10",
    "react-tabs": "^5.1.0",
    "react-type-animation": "^1.1.3",
    "react-water-wave": "^2.0.1",
    "swiper": "^8.3.2"
  },
  "devDependencies": {
    "eslint": "8.23.0",
    "eslint-config-next": "12.2.5"
  }
}

</code>```

Next.js, all work fine on localhost, when I push to Heroku, Push rejected, idk why. Please help my heroes.

Thanks for your help.

Push Next.js app to Heroku, Push rejected.

ContentLicense: CC BY-SA 4.0

Title: Heroku Push rejected, Next.js

Body:
Next.js App, all work fine on localhost, when I push to Heroku, Push rejected, idk why. Please help my heroes.

Heroku Push logs:

remote: -----> Installing binaries
remote:        engines.node (package.json):  unspecified
remote:        engines.npm (package.json):   unspecified (use default)
remote:
remote:        Resolving node version 18.x...
remote:        Downloading and installing node 18.12.1...
remote:        Using default npm version: 8.19.2
remote:
remote: -----> Installing dependencies
remote:        Installing node modules
remote:        npm ERR! code ERESOLVE
remote:        npm ERR! ERESOLVE could not resolve
remote:        npm ERR!
remote:        npm ERR! While resolving: react-lightgallery@0.9.0
remote:        npm ERR! Found: react@18.2.0
remote:        npm ERR! node_modules/react
remote:        npm ERR!   react@"^18.2.0" from the root project
remote:        npm ERR!   peer react@"^17.0.2 || ^18.0.0-0" from next@12.2.6
remote:        npm ERR!   node_modules/next
remote:        npm ERR!     next@"12.2" from the root project
remote:        npm ERR!   9 more (react-circular-progressbar, react-dom, react-modal, ...)
remote:        npm ERR!
remote:        npm ERR! Could not resolve dependency:
remote:        npm ERR! peer react@"^16.13.1" from react-lightgallery@0.9.0
remote:        npm ERR! node_modules/react-lightgallery
remote:        npm ERR!   react-lightgallery@"^0.9.0" from the root project
remote:        npm ERR!
remote:        npm ERR! Conflicting peer dependency: react@16.14.0
remote:        npm ERR! node_modules/react
remote:        npm ERR!   peer react@"^16.13.1" from react-lightgallery@0.9.0
remote:        npm ERR!   node_modules/react-lightgallery
remote:        npm ERR!     react-lightgallery@"^0.9.0" from the root project
remote:        npm ERR!
remote:        npm ERR! Fix the upstream dependency conflict, or retry
remote:        npm ERR! this command with --force, or --legacy-peer-deps
remote:        npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
remote:        npm ERR!
remote:        npm ERR! See /tmp/npmcache.WP8R2/eresolve-report.txt for a full report.
remote:
remote:        npm ERR! A complete log of this run can be found in:
remote:        npm ERR!     /tmp/npmcache.WP8R2/_logs/2022-12-16T21_23_22_466Z-debug-0.log
remote:
remote: -----> Build failed

package.json:

{
  "name": "test-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start -p $PORT",
    "lint": "next lint"
  },
  "dependencies": {
    "isotope-layout": "^3.0.6",
    "next": "12.2",
    "particles.js": "^2.0.0",
    "react": "^18.2.0",
    "react-circular-progressbar": "^2.1.0",
    "react-dom": "^18.2.0",
    "react-lightgallery": "^0.9.0",
    "react-modal": "^3.15.1",
    "react-modal-video": "^1.2.10",
    "react-tabs": "^5.1.0",
    "react-type-animation": "^1.1.3",
    "react-water-wave": "^2.0.1",
    "swiper": "^8.3.2"
  },
  "devDependencies": {
    "eslint": "8.23.0",
    "eslint-config-next": "12.2.5"
  }
}

Next.js, all work fine on localhost, when I push to Heroku, Push rejected, idk why. Please help my heroes.

Thanks for your help.

Push Next.js app to Heroku, Push rejected.


问:
Parakimo asking password when try to send a scp file
I made this code and works fine. The only thing is that when scp starts to send the file to my kaly linux, it ask me the password but it is already set in my code:

```<code># importando as bibliotecas
import os
import paramiko

# criando o cliente ssh
client = paramiko.SSHClient()

# carregando as chaves de autenticação
client.load_system_host_keys()

# adicionando uma chave de autenticação
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

print('Enviando o arquivo de descriptografia')

# conectando ao servidor
client.connect('192.168.15.21', username='kali', password='kali')

# abrindo uma sessão
sess = client.get_transport().open_session()

# enviando o arquivo via scp
os.system('scp file.py kali@192.168.15.21:/home/kali')

# fechando a conexão
client.close()
</code>```

Any idea how to resolve that? (dont ask the password in terminal cmd)

Body:
I made this code and works fine. The only thing is that when scp starts to send the file to my kaly linux, it ask me the password but it is already set in my code:

# importando as bibliotecas
import os
import paramiko

# criando o cliente ssh
client = paramiko.SSHClient()

# carregando as chaves de autenticação
client.load_system_host_keys()

# adicionando uma chave de autenticação
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

print('Enviando o arquivo de descriptografia')

# conectando ao servidor
client.connect('192.168.15.21', username='kali', password='kali')

# abrindo uma sessão
sess = client.get_transport().open_session()

# enviando o arquivo via scp
os.system('scp file.py kali@192.168.15.21:/home/kali')

# fechando a conexão
client.close()

Any idea how to resolve that? (dont ask the password in terminal cmd)


问:
Python Rock, Paper, Scissors Loop Fail
I am a newer programmer. I am trying to build the infamous rock-paper-scissors game. I am working on making  infinite loops, break statements and making the game print out the winner and prompt the user to play again. However, I am having trouble with prompting the user to play again. No matter the answer the user inputs, the program will start again. I am not sure what I'm doing wrong.

Here is the code:

```<code>#defining the game function
def game():

    while True:
        p1=input("Player 1,Rock, Paper, or Scissors?: \n")
        p2= input("Player 2, what's your play?: \n")

        if p1 == "rock":
            if p2 == "scissors":
                print ("player 1 wins")
            elif p2 == "paper":
                print ("player 2 wins")

        elif p1== "paper":
            if p2 == "rock":
                print ("player 2 wins")
            elif p2 == "scissors":
                print ("player 1 wins")

        elif p1 == "scissors":
            if p2 =="rock":
                print ("player 2 wins")
            elif p2 == "paper":
                print ("player 1 wins")

        else:
                p1 == p2
                print ("its a tie")
#ask the user if they'd like to play again
#the issue is in this section of code
#no mater what the input is, the program will always prompt and start the function again

        ask= input("do you want to play again?: \n")
        if ask == 'y' or 'yes':
                game()
        else:
                ask == 'n' or 'no'
                print ("game over")
                break

#run program
game()

#output
#Player 1,Rock, Paper, or Scissors?:
#rock
#Player 2, what's your play?:
#paper
#player 2 wins
#do you want to play again?:
#n
#Player 1,Rock, Paper, or Scissors?:

</code>```

I've tried reversing the y and n prompts but this just reverses the problem (makes the game end regardless of the input). I've tried to change the formatting as well, but that always results in an error. Any help would be greatly appreciated.

Title: Python Rock, Paper, Scissors Loop Fail

Body:
I am a newer programmer. I am trying to build the infamous rock-paper-scissors game. I am working on making  infinite loops, break statements and making the game print out the winner and prompt the user to play again. However, I am having trouble with prompting the user to play again. No matter the answer the user inputs, the program will start again. I am not sure what I'm doing wrong.

Here is the code:

#defining the game function
def game():

    while True:
        p1=input("Player 1,Rock, Paper, or Scissors?: \n")
        p2= input("Player 2, what's your play?: \n")

        if p1 == "rock":
            if p2 == "scissors":
                print ("player 1 wins")
            elif p2 == "paper":
                print ("player 2 wins")

        elif p1== "paper":
            if p2 == "rock":
                print ("player 2 wins")
            elif p2 == "scissors":
                print ("player 1 wins")

        elif p1 == "scissors":
            if p2 =="rock":
                print ("player 2 wins")
            elif p2 == "paper":
                print ("player 1 wins")

        else:
                p1 == p2
                print ("its a tie")
#ask the user if they'd like to play again
#the issue is in this section of code
#no mater what the input is, the program will always prompt and start the function again

        ask= input("do you want to play again?: \n")
        if ask == 'y' or 'yes':
                game()
        else:
                ask == 'n' or 'no'
                print ("game over")
                break

#run program
game()

#output
#Player 1,Rock, Paper, or Scissors?:
#rock
#Player 2, what's your play?:
#paper
#player 2 wins
#do you want to play again?:
#n
#Player 1,Rock, Paper, or Scissors?:

I've tried reversing the y and n prompts but this just reverses the problem (makes the game end regardless of the input). I've tried to change the formatting as well, but that always results in an error. Any help would be greatly appreciated.


问:
Ads-script prints "Invalid Date"
I'm trying to print the current time for a google-ads user, but the ads-script shows "invalid date".

Should I print this differently?

It's JS based, but not 100%.

```<code>const DateUtils = {
  /**
   * Set timezone to a given date.
   * @param {!Date} date A given date.
   * @param {!TimeZone} timeZone A given timezone.
   * @return {!Date} Day with the new timezone.
   */
  changeTimeZone: function(date, timeZone) {
    if (typeof date === 'string') {
      return new Date(
          new Date(date).toLocaleString('en-US', {
            timeZone,
          }),
      );
    }
    return new Date(
        date.toLocaleString('en-US', {
          timeZone,
        }),
    );
  }
};

/**
 * Main entry point
 */
function main() {

  // The current account's timezone.
const TIMEZONE = AdsApp.currentAccount().getTimeZone();

// The current time for the current account.
const NOW = DateUtils.changeTimeZone(new Date(), TIMEZONE);

 console.log(JSON.stringify(NOW));
 console.log(NOW.toLocaleString());
}
</code>```

Title: Ads-script prints "Invalid Date"

Body:
I'm trying to print the current time for a google-ads user, but the ads-script shows "invalid date".

Should I print this differently?

It's JS based, but not 100%.

const DateUtils = {
  /**
   * Set timezone to a given date.
   * @param {!Date} date A given date.
   * @param {!TimeZone} timeZone A given timezone.
   * @return {!Date} Day with the new timezone.
   */
  changeTimeZone: function(date, timeZone) {
    if (typeof date === 'string') {
      return new Date(
          new Date(date).toLocaleString('en-US', {
            timeZone,
          }),
      );
    }
    return new Date(
        date.toLocaleString('en-US', {
          timeZone,
        }),
    );
  }
};

/**
 * Main entry point
 */
function main() {

  // The current account's timezone.
const TIMEZONE = AdsApp.currentAccount().getTimeZone();

// The current time for the current account.
const NOW = DateUtils.changeTimeZone(new Date(), TIMEZONE);

 console.log(JSON.stringify(NOW));
 console.log(NOW.toLocaleString());
}


问:
Is there a way to persist an entity with a set of childrens, if those childres are both persisted, and unpersisted (With ids and without ids)
I have an Entity with children, with a ManyToMany relationship, and read that it's better to not set a CascadeType, and I'm working on a way to save "Versions" of that entity, so the user can add or remove children and then save a new version of that.

What I do is create a new object with the same values, and just add a different revision number, but if the user adds more children I get an error: object references an unsaved transient instance - save the transient instance before flushing

so I tried with every other CascadeType

```<code>`@ManyToMany(cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE,
            CascadeType.DETACH,
            CascadeType.REFRESH,
        }`
</code>```

but with this im getting.

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.atms.dao.domain.ExternalToolEntity}

So my guess is that with a set of children with both assigned and unassigned Ids JPA does not know what strategy to follow, is there a way to achieve this? or this should be done in two parts, one for copying and one for updating.

Body:
I have an Entity with children, with a ManyToMany relationship, and read that it's better to not set a CascadeType, and I'm working on a way to save "Versions" of that entity, so the user can add or remove children and then save a new version of that.

What I do is create a new object with the same values, and just add a different revision number, but if the user adds more children I get an error: object references an unsaved transient instance - save the transient instance before flushing

so I tried with every other CascadeType

`@ManyToMany(cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE,
            CascadeType.DETACH,
            CascadeType.REFRESH,
        }`

but with this im getting.

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.atms.dao.domain.ExternalToolEntity}

So my guess is that with a set of children with both assigned and unassigned Ids JPA does not know what strategy to follow, is there a way to achieve this? or this should be done in two parts, one for copying and one for updating.


问:
Why is plotting envfit result in ggplot result in disproportionate arrows compared to sites?
The title of my question might seem very obvious as there are many tuto and already solved questions about plotting metaMDS and envfit result in ggplot here. But actually I followed these previous posts/tuto and I am still getting weirdly very 'long' variable arrows, such long that my sites plot is totally 'masked' (see plot). I tried running this several time with scaling the arrows using ordiArrowMul() or without and still coming to the same. Can anyone help me spot where I did a mistake somewhere or what's the problem?

here is what I have as data and the code:

My dataframe is very large and using dput makes a very large code so I upload it to a drive here: https://drive.google.com/drive/folders/1wupRAxS9Q5Ht0IplbstY7-MrF_FoVolo?usp=share_link

```<code>#read data
data <- read.csv('~/data.csv',row.names = 1)

envi <- read.csv('~/env.csv',row.names = 1)

meta <- structure(list(SAMPLE_ID = c("MOLA_1-1_A", "MOLA_1-1_A", "MOLA_1-1_A", "MOLA_10-1_A", "MOLA_10-1_A", "MOLA_10-1_A", "MOLA_12-1_A", "MOLA_12-1_A", "MOLA_12-1_A", "MOLA_13-1_A", "MOLA_13-1_A", "MOLA_15-1_A", "MOLA_15-1_A", "MOLA_15-1_A", "MOLA_18-1_A", "MOLA_18-1_A", "MOLA_18-1_A", "MOLA_19-1_A", "MOLA_19-1_A", "MOLA_19-1_A", "MOLA_21-1_B", "MOLA_21-1_B", "MOLA_22-1_A", "MOLA_22-1_A", "MOLA_22-1_A", "MOLA_23-1_B", "MOLA_23-1_B", "MOLA_23-1_B", "MOLA_25-1_A", "MOLA_25-1_A", "MOLA_25-1_A", "MOLA_4-1_A", "MOLA_4-1_A", "MOLA_4-1_A", "MOLA_7-1_A", "MOLA_7-1_A", "MOLA_7-1_A", "MOLA_9-1_A", "MOLA_9-1_A", "MOLA_9-1_A"), `Month-Year` = structure(c(1556668800, 1556668800, 1556668800, 1590969600, 1590969600, 1590969600, 1593561600, 1593561600, 1593561600, 1596240000, 1596240000, 1604188800, 1604188800, 1604188800, 1612137600, 1612137600, 1612137600, 1614556800, 1614556800, 1614556800, 1617235200, 1617235200, 1619827200, 1619827200, 1619827200, 1625097600, 1625097600, 1625097600, 1564617600, 1564617600, 1564617600, 1559347200, 1559347200, 1559347200, 1569888000, 1569888000, 1569888000, 1577836800, 1577836800, 1577836800), tzone = "UTC", class = c("POSIXct", "POSIXt")), season = c("Spring", "Spring", "Spring", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Autumn", "Autumn", "Autumn", "Winter", "Winter", "Winter", "Spring", "Spring", "Spring", "Spring", "Spring", "Spring", "Spring", "Spring", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Autumn", "Autumn", "Autumn", "Winter", "Winter", "Winter"), Depth = c("5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m"), month = c("May", "May", "May", "Jun", "Jun", "Jun", "Jul", "Jul", "Jul", "Aug", "Aug", "Nov", "Nov", "Nov", "Feb", "Feb", "Feb", "Mar", "Mar", "Mar", "Apr", "Apr", "May", "May", "May", "Jul", "Jul", "Jul", "Aug", "Aug", "Aug", "Jun", "Jun", "Jun", "Oct", "Oct", "Oct", "Jan", "Jan", "Jan")), class = "data.frame", row.names = c(NA, -40L))

#nmds
set.seed(123)
nmds = metaMDS(as.matrix(data), distance = "bray")

#envfit
set.seed(123)
ef <- envfit(nmds, envi, permu = 999)
ef

#plot
plot(nmds, type = "t", display = "sites")
plot(ef, p.max = 0.05)
</code>```

so far, so good, the output is this and it is fine
enter image description here

now trying to do a nice ggplot does not give the same result

```<code>#extract envfit arrows data and filter out non significant one
en_coord_cont = as.data.frame(scores(ef, "vectors")) * ordiArrowMul(ef)
en_coord_cont$pval <- ef[["vectors"]][["pvals"]]
en_coord_cont <- filter(en_coord_cont,pval<=0.05)

#extract nmds scores and associate to metadata
data.scores = as.data.frame(scores(nmds))
temp <- cbind(data.scores,meta)
temp$month <-  factor(temp$month, levels = month.abb)

#ggplot
xx = ggplot(temp, aes(x = NMDS1, y = NMDS2)) + geom_point(size = 4, aes( shape = Depth,colour=month))+ coord_fixed() + theme(axis.text.y = element_text(colour = "black", size = 12, face = "bold"), axis.text.x = element_text(colour = "black", face = "bold", size = 12), legend.text = element_text(size = 12, face ="bold", colour ="black"), legend.position = "right", axis.title.y = element_text(face = "bold", size = 14), axis.title.x = element_text(face = "bold", size = 14, colour = "black"), legend.title = element_text(size = 14, colour = "black", face = "bold"), panel.background = element_blank(), panel.border = element_rect(colour = "black", fill = NA, size = 1.2), legend.key=element_blank()) + scale_colour_manual(values = c('blue4','blue','green4','green3','green'  ,'red4' ,'orangered','orange','yellow3','yellow')) +geom_vline(xintercept = 0,linetype = "dashed")+ geom_hline(yintercept = 0,linetype = "dashed")+geom_segment(aes(x = 0, y = 0, xend =NMDS1, yend = NMDS2), data = en_coord_cont, size =1, alpha = 0.5, colour = "grey30") +geom_text(data = en_coord_cont, aes(x = NMDS1, y = NMDS2), colour = "grey30", fontface = "bold", label = row.names(en_coord_cont))

xx
</code>```

enter image description here

Body:
The title of my question might seem very obvious as there are many tuto and already solved questions about plotting metaMDS and envfit result in ggplot here. But actually I followed these previous posts/tuto and I am still getting weirdly very 'long' variable arrows, such long that my sites plot is totally 'masked' (see plot). I tried running this several time with scaling the arrows using ordiArrowMul() or without and still coming to the same. Can anyone help me spot where I did a mistake somewhere or what's the problem?

here is what I have as data and the code:

My dataframe is very large and using dput makes a very large code so I upload it to a drive here: https://drive.google.com/drive/folders/1wupRAxS9Q5Ht0IplbstY7-MrF_FoVolo?usp=share_link

#read data
data <- read.csv('~/data.csv',row.names = 1)

envi <- read.csv('~/env.csv',row.names = 1)

meta <- structure(list(SAMPLE_ID = c("MOLA_1-1_A", "MOLA_1-1_A", "MOLA_1-1_A", "MOLA_10-1_A", "MOLA_10-1_A", "MOLA_10-1_A", "MOLA_12-1_A", "MOLA_12-1_A", "MOLA_12-1_A", "MOLA_13-1_A", "MOLA_13-1_A", "MOLA_15-1_A", "MOLA_15-1_A", "MOLA_15-1_A", "MOLA_18-1_A", "MOLA_18-1_A", "MOLA_18-1_A", "MOLA_19-1_A", "MOLA_19-1_A", "MOLA_19-1_A", "MOLA_21-1_B", "MOLA_21-1_B", "MOLA_22-1_A", "MOLA_22-1_A", "MOLA_22-1_A", "MOLA_23-1_B", "MOLA_23-1_B", "MOLA_23-1_B", "MOLA_25-1_A", "MOLA_25-1_A", "MOLA_25-1_A", "MOLA_4-1_A", "MOLA_4-1_A", "MOLA_4-1_A", "MOLA_7-1_A", "MOLA_7-1_A", "MOLA_7-1_A", "MOLA_9-1_A", "MOLA_9-1_A", "MOLA_9-1_A"), `Month-Year` = structure(c(1556668800, 1556668800, 1556668800, 1590969600, 1590969600, 1590969600, 1593561600, 1593561600, 1593561600, 1596240000, 1596240000, 1604188800, 1604188800, 1604188800, 1612137600, 1612137600, 1612137600, 1614556800, 1614556800, 1614556800, 1617235200, 1617235200, 1619827200, 1619827200, 1619827200, 1625097600, 1625097600, 1625097600, 1564617600, 1564617600, 1564617600, 1559347200, 1559347200, 1559347200, 1569888000, 1569888000, 1569888000, 1577836800, 1577836800, 1577836800), tzone = "UTC", class = c("POSIXct", "POSIXt")), season = c("Spring", "Spring", "Spring", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Autumn", "Autumn", "Autumn", "Winter", "Winter", "Winter", "Spring", "Spring", "Spring", "Spring", "Spring", "Spring", "Spring", "Spring", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Summer", "Autumn", "Autumn", "Autumn", "Winter", "Winter", "Winter"), Depth = c("5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m", "5 m"), month = c("May", "May", "May", "Jun", "Jun", "Jun", "Jul", "Jul", "Jul", "Aug", "Aug", "Nov", "Nov", "Nov", "Feb", "Feb", "Feb", "Mar", "Mar", "Mar", "Apr", "Apr", "May", "May", "May", "Jul", "Jul", "Jul", "Aug", "Aug", "Aug", "Jun", "Jun", "Jun", "Oct", "Oct", "Oct", "Jan", "Jan", "Jan")), class = "data.frame", row.names = c(NA, -40L))

#nmds
set.seed(123)
nmds = metaMDS(as.matrix(data), distance = "bray")

#envfit
set.seed(123)
ef <- envfit(nmds, envi, permu = 999)
ef

#plot
plot(nmds, type = "t", display = "sites")
plot(ef, p.max = 0.05)

so far, so good, the output is this and it is fine
enter image description here

now trying to do a nice ggplot does not give the same result

#extract envfit arrows data and filter out non significant one
en_coord_cont = as.data.frame(scores(ef, "vectors")) * ordiArrowMul(ef)
en_coord_cont$pval <- ef[["vectors"]][["pvals"]]
en_coord_cont <- filter(en_coord_cont,pval<=0.05)

#extract nmds scores and associate to metadata
data.scores = as.data.frame(scores(nmds))
temp <- cbind(data.scores,meta)
temp$month <-  factor(temp$month, levels = month.abb)

#ggplot
xx = ggplot(temp, aes(x = NMDS1, y = NMDS2)) + geom_point(size = 4, aes( shape = Depth,colour=month))+ coord_fixed() + theme(axis.text.y = element_text(colour = "black", size = 12, face = "bold"), axis.text.x = element_text(colour = "black", face = "bold", size = 12), legend.text = element_text(size = 12, face ="bold", colour ="black"), legend.position = "right", axis.title.y = element_text(face = "bold", size = 14), axis.title.x = element_text(face = "bold", size = 14, colour = "black"), legend.title = element_text(size = 14, colour = "black", face = "bold"), panel.background = element_blank(), panel.border = element_rect(colour = "black", fill = NA, size = 1.2), legend.key=element_blank()) + scale_colour_manual(values = c('blue4','blue','green4','green3','green'  ,'red4' ,'orangered','orange','yellow3','yellow')) +geom_vline(xintercept = 0,linetype = "dashed")+ geom_hline(yintercept = 0,linetype = "dashed")+geom_segment(aes(x = 0, y = 0, xend =NMDS1, yend = NMDS2), data = en_coord_cont, size =1, alpha = 0.5, colour = "grey30") +geom_text(data = en_coord_cont, aes(x = NMDS1, y = NMDS2), colour = "grey30", fontface = "bold", label = row.names(en_coord_cont))

xx

enter image description here


问:
spring-boot-starter-actuator set the configuration management.metrics.export.datadog.apiKey from the code
I'm using spring-boot-starter-actuator to export metrics to datadog. everything is working fine where I have set management.metrics.export.datadog.apiKey in the application.properties file,
But I want to set the configuration management.metrics.export.datadog.apiKey reading from the secret manager in the code.

Is there a way I can do this?


问:
CSS animation z-index not working right on IOS
I have a simple reactJS module with css animation where an envelope opens, a paper pops up, the paper goes back down, and the envelope closes.

On desktop (chrome, opera and firefox) it works great. On my Samsung (Chrome and Firefox) it works great. On iPadOS it gets wonky.

On Safari, Firefox, and Chrome, the envelope top spreads to the entire width of the screen, and to the top of the screen when it's closing and about to open. On Chrome on ipad, it also puts the envelope top in front of the 'letter' that slides up, when the letter is at the top. I have played with z-index changes, setting translateX values in the animation, and with opacity. I can't seem to figure out what is causing the problem, nor how to fix it.

I have been beating my head against the wall for this stupid little animation for 2 hours. Any ideas where I went wrong?

.js file

```<code>import React from "react";
import './EmailOpen.scss';

const contactEmail = 'email@email.com';

const EmailOpen = () => {
    return (
        <>
            <a href={ contactEmail } >
                <div className="wrapper">
                    <div className="mail">
                        <div className="cover"></div>
                        <div className="letter"><h1>@</h1></div>
                    </div>
                </div>
            </a>
        </>
    );
}

export default EmailOpen;
</code>```

.scss file

```<code>
$envelopeWidth: 90px;
$envelopeHeight: calc($envelopeWidth * .6667);
$duration: 4s;
$borderRad: calc(0.0333 * $envelopeWidth);
$halfWidth: calc($envelopeWidth / 2);
$halfHeight: calc($envelopeHeight / 2);
$letterMove: calc(-0.67 * $envelopeHeight);

body {
    background-color: #000;
}

.wrapper {
    position: relative;
    top: calc(2vh);
    left: calc(50% - $halfWidth);
}

.mail {
    background: #aaa;
    position: relative;
    transform-style: preserve-3d;
    cursor: pointer;
    width: $envelopeWidth;
    height: $envelopeHeight;
    border-bottom-left-radius: $borderRad;
    border-bottom-right-radius: $borderRad;

    &:before {
        content:"";
        position: absolute;
        top: 0;
        right: 0;
        z-index: 5000;
        border-right: $halfWidth solid #fed;
        border-left: $halfWidth solid transparent;
        border-top: $halfHeight solid transparent;
        border-bottom: $halfHeight solid #fed;
        border-bottom-left-radius: $borderRad;
        border-bottom-right-radius: $borderRad;
    }

    &:after {
        content:"";
        position: absolute;
        top: 0;
        left: 0;
        z-index: 4000;
        border-left: $halfWidth solid #cba;
        border-right: $halfWidth solid transparent;
        border-top: $halfHeight solid transparent;
        border-bottom: $halfHeight solid #cba;
        border-bottom-left-radius: $borderRad;
        border-bottom-right-radius: $borderRad;
    }
}

.cover {
    &::before {
        content:"";
        position: absolute;
        top: 0;
        left: 0;
        z-index: 6000;
        transform-origin: top;
        transform: rotateX(0deg);
        animation: open $duration linear infinite;
        opacity: 1;
        border-left: $halfWidth solid transparent;
        border-right: $halfWidth solid transparent;
        border-bottom: $halfHeight solid transparent;
        border-top: $halfHeight solid #a98;
        border-bottom-left-radius: $borderRad;
        border-bottom-right-radius: $borderRad;
    }
}

@keyframes open {
    0%, 5% {
        transform: rotateX(0deg);
        z-index: 6000;
    }
    15%, 85% {
        transform: rotateX(180deg);
        z-index: 0;
    }
    95%, 100% {
        transform: rotateX(0deg);
        z-index: 6000;
    }
}

.letter {
    position: absolute;
    top: 0;
    background: #eee;
    left: calc($envelopeWidth * 0.05);
    width: calc($envelopeWidth * 0.9);
    height: calc($envelopeHeight * 0.95);
    border-radius: $borderRad;
    animation: letter $duration linear infinite;
    z-index: 2000;

    h1 {
        position: absolute;
        top: 10%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: green;
    }

    @keyframes letter {
        0%, 15% {
            transform: translateY(0);
        }
        25%, 75%  {
            transform: translateY($letterMove);
        }
        85%, 100% {
            transform: translateY(0);
        }
    }
}
</code>```

Body:
I have a simple reactJS module with css animation where an envelope opens, a paper pops up, the paper goes back down, and the envelope closes.

On desktop (chrome, opera and firefox) it works great. On my Samsung (Chrome and Firefox) it works great. On iPadOS it gets wonky.

On Safari, Firefox, and Chrome, the envelope top spreads to the entire width of the screen, and to the top of the screen when it's closing and about to open. On Chrome on ipad, it also puts the envelope top in front of the 'letter' that slides up, when the letter is at the top. I have played with z-index changes, setting translateX values in the animation, and with opacity. I can't seem to figure out what is causing the problem, nor how to fix it.

I have been beating my head against the wall for this stupid little animation for 2 hours. Any ideas where I went wrong?

.js file

import React from "react";
import './EmailOpen.scss';

const contactEmail = 'email@email.com';

const EmailOpen = () => {
    return (
        <>

@

        </>
    );
}

export default EmailOpen;

.scss file

$envelopeWidth: 90px;
$envelopeHeight: calc($envelopeWidth * .6667);
$duration: 4s;
$borderRad: calc(0.0333 * $envelopeWidth);
$halfWidth: calc($envelopeWidth / 2);
$halfHeight: calc($envelopeHeight / 2);
$letterMove: calc(-0.67 * $envelopeHeight);

body {
    background-color: #000;
}

.wrapper {
    position: relative;
    top: calc(2vh);
    left: calc(50% - $halfWidth);
}

.mail {
    background: #aaa;
    position: relative;
    transform-style: preserve-3d;
    cursor: pointer;
    width: $envelopeWidth;
    height: $envelopeHeight;
    border-bottom-left-radius: $borderRad;
    border-bottom-right-radius: $borderRad;

    &:before {
        content:"";
        position: absolute;
        top: 0;
        right: 0;
        z-index: 5000;
        border-right: $halfWidth solid #fed;
        border-left: $halfWidth solid transparent;
        border-top: $halfHeight solid transparent;
        border-bottom: $halfHeight solid #fed;
        border-bottom-left-radius: $borderRad;
        border-bottom-right-radius: $borderRad;
    }

    &:after {
        content:"";
        position: absolute;
        top: 0;
        left: 0;
        z-index: 4000;
        border-left: $halfWidth solid #cba;
        border-right: $halfWidth solid transparent;
        border-top: $halfHeight solid transparent;
        border-bottom: $halfHeight solid #cba;
        border-bottom-left-radius: $borderRad;
        border-bottom-right-radius: $borderRad;
    }
}

.cover {
    &::before {
        content:"";
        position: absolute;
        top: 0;
        left: 0;
        z-index: 6000;
        transform-origin: top;
        transform: rotateX(0deg);
        animation: open $duration linear infinite;
        opacity: 1;
        border-left: $halfWidth solid transparent;
        border-right: $halfWidth solid transparent;
        border-bottom: $halfHeight solid transparent;
        border-top: $halfHeight solid #a98;
        border-bottom-left-radius: $borderRad;
        border-bottom-right-radius: $borderRad;
    }
}

@keyframes open {
    0%, 5% {
        transform: rotateX(0deg);
        z-index: 6000;
    }
    15%, 85% {
        transform: rotateX(180deg);
        z-index: 0;
    }
    95%, 100% {
        transform: rotateX(0deg);
        z-index: 6000;
    }
}

.letter {
    position: absolute;
    top: 0;
    background: #eee;
    left: calc($envelopeWidth * 0.05);
    width: calc($envelopeWidth * 0.9);
    height: calc($envelopeHeight * 0.95);
    border-radius: $borderRad;
    animation: letter $duration linear infinite;
    z-index: 2000;

    h1 {
        position: absolute;
        top: 10%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: green;
    }

    @keyframes letter {
        0%, 15% {
            transform: translateY(0);
        }
        25%, 75%  {
            transform: translateY($letterMove);
        }
        85%, 100% {
            transform: translateY(0);
        }
    }
}


问:
gclod dataflow run ignore certificate
I have an Elasticsearch instance on premise on our GCP k8s, and I am trying to run a dataflow template (Bq to Elasticsearch, specifically). The problem is that it gives me the following error:

```<code>Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

since the Elasticsearch have self-signed auth certificate I am not really sure where and how to find this certificate.

Is there any flag or option or parameter to disable the certificate validation?

In python when you connect to Elasticsearch you can use:

```<code>Elasticsearch(hosts=[address], basic_auth=[user, password], verify_certs=False)
</code>```

and with curl you can use the -k parameter:

```<code>curl -k https://<elasticsearch_url>:9200
</code>```

Is there a way to reach the same trick with Dataflow run ?

I tried to disable the certification for the environment I was running it with the following command:

```<code>gcloud config set auth/disable_ssl_validation True
</code>```

but apart giving me this warning:

```<code>/Users/salvob/google-cloud-sdk/lib/third_party/urllib3/connectionpool.py:1050: InsecureRequestWarning: Unverified HTTPS request is being made to host 'oauth2.googleapis.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  InsecureRequestWarning,
/Users/salvob/google-cloud-sdk/lib/third_party/urllib3/connectionpool.py:1050: InsecureRequestWarning: Unverified HTTPS request is being made to host 'dataflow.googleapis.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  InsecureRequestWarning,
</code>```

it still gives me the security failed error :(

Title: gclod dataflow run ignore certificate

Body:
I have an Elasticsearch instance on premise on our GCP k8s, and I am trying to run a dataflow template (Bq to Elasticsearch, specifically). The problem is that it gives me the following error:

Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

since the Elasticsearch have self-signed auth certificate I am not really sure where and how to find this certificate.

Is there any flag or option or parameter to disable the certificate validation?

In python when you connect to Elasticsearch you can use:

Elasticsearch(hosts=[address], basic_auth=[user, password], verify_certs=False)

and with curl you can use the -k parameter:

curl -k https://<elasticsearch_url>:9200

Is there a way to reach the same trick with Dataflow run ?

I tried to disable the certification for the environment I was running it with the following command:

gcloud config set auth/disable_ssl_validation True

but apart giving me this warning:

/Users/salvob/google-cloud-sdk/lib/third_party/urllib3/connectionpool.py:1050: InsecureRequestWarning: Unverified HTTPS request is being made to host 'oauth2.googleapis.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  InsecureRequestWarning,
/Users/salvob/google-cloud-sdk/lib/third_party/urllib3/connectionpool.py:1050: InsecureRequestWarning: Unverified HTTPS request is being made to host 'dataflow.googleapis.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  InsecureRequestWarning,

it still gives me the security failed error :(


问:
How to close the docker container after logstash pipelines worked?
I have two pipelines in my Logstash docker container. First pipeline runs mysql database query and writes it to elasticsearch. And other writes logs from log file to elasticsearch.

I want to close the docker container after the processes are finished. How can I do this?


问:
sass calc function unary negation returns error
sass calc function  unary negation returns error

"sass": "^1.56.1",
"sass-loader": "^13.0.2",
"webpack": "^5.74.0",

Why is error presented?

code:

```<code>      margin-left: calc(-($map-width - 100%) / 2);

</code>```

console output:

```<code>Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Expected digit.
    ╷
598 │       margin-left: calc(-(#{$map-width} - 100%) / 2);
    │                           ^
    ╵
</code>```

wrapping in in brackets like so will result the same error

```<code>      margin-left: calc((-(#{$map-width} - 100%)) / 2);

</code>```

Expected: no error

Body:
sass calc function  unary negation returns error

"sass": "^1.56.1",
"sass-loader": "^13.0.2",
"webpack": "^5.74.0",

Why is error presented?

code:

      margin-left: calc(-($map-width - 100%) / 2);

console output:

Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Expected digit.
    ╷
598 │       margin-left: calc(-(#{$map-width} - 100%) / 2);
    │                           ^
    ╵

wrapping in in brackets like so will result the same error

      margin-left: calc((-(#{$map-width} - 100%)) / 2);

Expected: no error


问:
NoMethodError in Posts#show
Hi I am new to rails and am adding comments to a post, I want to add the username of the commenter in the comment but I am getting this error, comment.user displays a bunch of jibberish and comment.user.username gives me an error

posts_controller.rb

```<code>   class PostsController < ApplicationController

before_action :authenticate_user!

def new
    @post = Post.new
end

def create

    @post = current_user.posts.build(post_params)
    @post.user = current_user

    respond_to do |format|
    if @post.save

        format.html { redirect_to root_path, notice: 'Post was successfully created.'
     }
        format.json { render :show, status: :created, location: @post }

      else

        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
        end
      end
  end

  def index
    @posts = Post.all.order(created_at: :desc)
   end

def show
    @post = Post.find(params[:id])
end

def like

    @post = Post.all.find(params[:id])

    Like.create(user_id: current_user.id, post_id: @post.id)
    redirect_to post_path(@post)
end

private

def post_params
    params.require(:post).permit(:body)
end

end
</code>```

comments_controller.rb

```<code>  class CommentsController < ApplicationController

 def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(comment_params)

    @comment.save
    redirect_to post_path(@post)
  end

  private
    def comment_params
      params.require(:comment).permit(:body).merge(user_id: current_user.id)
    end

 end
</code>```

comment.rb

```<code> class Comment < ApplicationRecord
 belongs_to :user
 belongs_to :post
 end
</code>```

user.rb

```<code>class User < ApplicationRecord
 # Include default devise modules. Others available are:
 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable

 devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :validatable

 followability

 has_many :notifications, as: :recipient, dependent: :destroy
 has_many :posts, foreign_key: :user_id, dependent: :destroy
 has_many :likes, dependent: :destroy
 has_many :comments
  def unfollow(user)
  followerable_relationships.where(followable_id: user.id).destroy_all
  end

  end
</code>```

show.html.erb

```<code> <div>
 <div>
 <% if user_signed_in? %>

 By <%= @post.user.username%></h1>
 <% end %>
 </div>
 <div>
 <p> <%= @post.body %> </p>
 </div>

 <%= @post.likes.count %> Likes
 <% pre_like = @post.likes.find { |like| like.user_id == current_user.id} %>
 <% if pre_like %>
  <%= button_to 'Unlike', post_like_path(@post, pre_like), method: :delete %>
 <% else %>
  <%= button_to 'Like', post_likes_path(@post), method: :post %>
  <% end %>

 <br>

 <h2>Add a comment:</h2>
 <%= form_with model: [ @post, @post.comments.build ] do |form| %>

  <p>

  <%= form.label :body %><br>
  <%= form.text_area :body %>
  </p>
 <p>
<%= form.submit %>
</p>
<% end %>

 <br>

<h2>Comments</h2>
 <% @post.comments.each do |comment| %>
 <p>
<strong>Commenter:</strong>
 <%= comment.user.username %>
 </p>

 <p>
<strong>Comment:</strong>
<%= comment.body %>
  </p>
 <% end %>

 </div>

</code>```

Title: NoMethodError in Posts#show

Body:
Hi I am new to rails and am adding comments to a post, I want to add the username of the commenter in the comment but I am getting this error, comment.user displays a bunch of jibberish and comment.user.username gives me an error

posts_controller.rb

   class PostsController < ApplicationController

before_action :authenticate_user!

def new
    @post = Post.new
end

def create

    @post = current_user.posts.build(post_params)
    @post.user = current_user

    respond_to do |format|
    if @post.save

        format.html { redirect_to root_path, notice: 'Post was successfully created.'
     }
        format.json { render :show, status: :created, location: @post }

      else

        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
        end
      end
  end

  def index
    @posts = Post.all.order(created_at: :desc)
   end

def show
    @post = Post.find(params[:id])
end

def like

    @post = Post.all.find(params[:id])

    Like.create(user_id: current_user.id, post_id: @post.id)
    redirect_to post_path(@post)
end

private

def post_params
    params.require(:post).permit(:body)
end

end

comments_controller.rb

  class CommentsController < ApplicationController

 def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(comment_params)

    @comment.save
    redirect_to post_path(@post)
  end

  private
    def comment_params
      params.require(:comment).permit(:body).merge(user_id: current_user.id)
    end

 end

comment.rb

 class Comment < ApplicationRecord
 belongs_to :user
 belongs_to :post
 end

user.rb

class User < ApplicationRecord
 # Include default devise modules. Others available are:
 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable

 devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :validatable

 followability

 has_many :notifications, as: :recipient, dependent: :destroy
 has_many :posts, foreign_key: :user_id, dependent: :destroy
 has_many :likes, dependent: :destroy
 has_many :comments
  def unfollow(user)
  followerable_relationships.where(followable_id: user.id).destroy_all
  end

  end

show.html.erb

 <% if user_signed_in? %>

 By <%= @post.user.username%>

 <% end %>

 <%= @post.body %>

 <%= @post.likes.count %> Likes
 <% pre_like = @post.likes.find { |like| like.user_id == current_user.id} %>
 <% if pre_like %>
  <%= button_to 'Unlike', post_like_path(@post, pre_like), method: :delete %>
 <% else %>
  <%= button_to 'Like', post_likes_path(@post), method: :post %>
  <% end %>

Add a comment:

 <%= form_with model: [ @post, @post.comments.build ] do |form| %>

  <%= form.label :body %>

  <%= form.text_area :body %>

<%= form.submit %>

<% end %>

Comments

 <% @post.comments.each do |comment| %>

Commenter:
 <%= comment.user.username %>

Comment:
<%= comment.body %>

 <% end %>


问:
Can't get how to apply Implicit Symmetric QR Step and symmetric QR to small matrices

The main issue is that I don't understand how to apply this algorithm to, for instance, matrix 3x3. Should all matrices of size 2x2 be treated as Hessenberg unreduced? How should I apply algorithm 8.3.2(Implicit Symmetric QR Step with Wilkinson Shift) to 2x2 matrix?

P.S.
It's Goulub and Van Loan book "Matrix computations"


问:
Elasticsearch - Flattened field - Aggregating topics/subtopics
The data I'm storing is coming from an external source that may change over time, so I'm using a 'flattened' field to hold the data.  The data will be following a 'Set' --> 'Topics' --> 'Subtopics' (three tiered) structure.

Sample Index and Data:

```<code>{
  "so_DemoIndex": {
    "aliases": {},
    "mappings": {
      "properties": {
        "item": {
          "type": "keyword"
        },
        "metadata": {
          "type": "flattened"
        }
      }
    }
  }
}

POST /_bulk
{"create":{"_index":"so_DemoIndex"}}
{"item":"Item 1","metadata":[{"name":"setA","topics":[{"name":"topic1","subtopics":[{"name":"subtopic_a"},{"name":"subtopic_b"}]},{"name":"topic2","subtopics":[]}]},{"name":"setB","topics":[{"name":"topic3","subtopics":[{"name":"subtopic_d"}]}]}]}
{"create":{"_index":"so_DemoIndex"}}
{"item":"Item 2","metadata":[{"name":"setA","topics":[{"name":"topic1","subtopics":[{"name":"subtopic_a"}]}]}]}
{"create":{"_index":"so_DemoIndex"}}
{"item":"Item 3","metadata":[{"name":"setA","topics":[{"name":"topic2","subtopics":[{"name":"subtopic_c"}]}]},{"name":"setB","topics":[{"name":"topic3","subtopics":[{"name":"subtopic_d"}]}]}]}
</code>```

Example of the Data:

```<code>[
    {
      "name":"setA",
      "topics": [
        {
          "name": "topic1",
          "subtopics": [
            {"name": "subtopic_a"},
            {"name": "subtopic_b"}
          ]
        },
        {
          "name": "topic2",
          "subtopics": [
            {"name": "subtopic_c"}
          ]
        }
      ]
    },
    {
      "name":"setB",
      "topics": [
        {
          "name": "topic3",
          "subtopics": [
            {"name": "subtopic_d"}
          ]
        },
        {
          "name": "topic4",
          "subtopics": []
        }
      ]
    }
  ]
</code>```

I am trying to get aggregates reporting out like:

```<code>"aggregations": {
  "set": {
    "key": "setA",
    "buckets": [
      {
        "key": "topic1",
        "doc_count": 15,
        "buckets": [
          {
            "key": "subtopic_a",
            "doc_count": 10
          },
          {
            "key": "subtopic_b",
            "doc_count": 5
          }
        ]
      },
      {
        "key": "topic2",
        "doc_count": 2,
        "buckets": [
          {
            "key": "subtopic_c",
            "doc_count": 2
          }
        ]
      }
   ]
 }
}
</code>```

The closest I think I've gotten is using 'sub-aggregations' like so:

```<code>{
  "from": 0,
  "size": 20,
  "query": {
    "match_all": {}
  },
  "aggs": {
    "Set": {
      "terms": {
        "field": "metadata.name"
      },
      "aggs":{
        "Topics": {
          "terms": {
            "field": "metadata.topics.name"
          },
          "aggs": {
            "SubTopics": {
              "terms": {
                "field": "metadata.topics.subtopics.name"
              }
            }
          }
        }
      }
    }
  }
}
</code>```

This seems to return the totals at each 'tier' regardless of the 'parent' aggregate.  i.e. It gives the total count for Topics, not just for the topics under 'Set A'.  e.g.  A related issue is that the different 'Sets' may have different 'tier' names - i.e. if Set A is 'Categories --> Topics --> Subtopics', Set B might be 'Region --> State --> City'.  I'm trying to figure out if there is any way to get these aggregations to be 'dynamic' in any way.

```<code>"aggregations": {
  "Set": {
    "doc_count_error_upper_bound": 0,
    "sum_other_doc_count": 0,
    "buckets": [
      {
        "key": "setA",
        "doc_count": 3,
        "Topics": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "topic1",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_a",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_d",
                    "doc_count": 1
                  }
                ]
              }
            },
            {
              "key": "topic2",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_d",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_c",
                    "doc_count": 1
                  }
                ]
              }
            },
            {
              "key": "topic3",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_d",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_c",
                    "doc_count": 1
                  }
                ]
              }
            }
          ]
        }
      },
      {
        "key": "setB",
        "doc_count": 2,
        "Topics": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "topic2",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_d",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_c",
                    "doc_count": 1
                  }
                ]
              }
            },
            {
              "key": "topic3",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_d",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_c",
                    "doc_count": 1
                  }
                ]
              }
            },
            {
              "key": "topic1",
              "doc_count": 1,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_d",
                    "doc_count": 1
                  }
                ]
              }
            }
          ]
        }
      }
    ]
  }
}
</code>```

Body:
The data I'm storing is coming from an external source that may change over time, so I'm using a 'flattened' field to hold the data.  The data will be following a 'Set' --> 'Topics' --> 'Subtopics' (three tiered) structure.

Sample Index and Data:

{
  "so_DemoIndex": {
    "aliases": {},
    "mappings": {
      "properties": {
        "item": {
          "type": "keyword"
        },
        "metadata": {
          "type": "flattened"
        }
      }
    }
  }
}

POST /_bulk
{"create":{"_index":"so_DemoIndex"}}
{"item":"Item 1","metadata":[{"name":"setA","topics":[{"name":"topic1","subtopics":[{"name":"subtopic_a"},{"name":"subtopic_b"}]},{"name":"topic2","subtopics":[]}]},{"name":"setB","topics":[{"name":"topic3","subtopics":[{"name":"subtopic_d"}]}]}]}
{"create":{"_index":"so_DemoIndex"}}
{"item":"Item 2","metadata":[{"name":"setA","topics":[{"name":"topic1","subtopics":[{"name":"subtopic_a"}]}]}]}
{"create":{"_index":"so_DemoIndex"}}
{"item":"Item 3","metadata":[{"name":"setA","topics":[{"name":"topic2","subtopics":[{"name":"subtopic_c"}]}]},{"name":"setB","topics":[{"name":"topic3","subtopics":[{"name":"subtopic_d"}]}]}]}

Example of the Data:

[
    {
      "name":"setA",
      "topics": [
        {
          "name": "topic1",
          "subtopics": [
            {"name": "subtopic_a"},
            {"name": "subtopic_b"}
          ]
        },
        {
          "name": "topic2",
          "subtopics": [
            {"name": "subtopic_c"}
          ]
        }
      ]
    },
    {
      "name":"setB",
      "topics": [
        {
          "name": "topic3",
          "subtopics": [
            {"name": "subtopic_d"}
          ]
        },
        {
          "name": "topic4",
          "subtopics": []
        }
      ]
    }
  ]

I am trying to get aggregates reporting out like:

"aggregations": {
  "set": {
    "key": "setA",
    "buckets": [
      {
        "key": "topic1",
        "doc_count": 15,
        "buckets": [
          {
            "key": "subtopic_a",
            "doc_count": 10
          },
          {
            "key": "subtopic_b",
            "doc_count": 5
          }
        ]
      },
      {
        "key": "topic2",
        "doc_count": 2,
        "buckets": [
          {
            "key": "subtopic_c",
            "doc_count": 2
          }
        ]
      }
   ]
 }
}

The closest I think I've gotten is using 'sub-aggregations' like so:

{
  "from": 0,
  "size": 20,
  "query": {
    "match_all": {}
  },
  "aggs": {
    "Set": {
      "terms": {
        "field": "metadata.name"
      },
      "aggs":{
        "Topics": {
          "terms": {
            "field": "metadata.topics.name"
          },
          "aggs": {
            "SubTopics": {
              "terms": {
                "field": "metadata.topics.subtopics.name"
              }
            }
          }
        }
      }
    }
  }
}

This seems to return the totals at each 'tier' regardless of the 'parent' aggregate.  i.e. It gives the total count for Topics, not just for the topics under 'Set A'.  e.g.  A related issue is that the different 'Sets' may have different 'tier' names - i.e. if Set A is 'Categories --> Topics --> Subtopics', Set B might be 'Region --> State --> City'.  I'm trying to figure out if there is any way to get these aggregations to be 'dynamic' in any way.

"aggregations": {
  "Set": {
    "doc_count_error_upper_bound": 0,
    "sum_other_doc_count": 0,
    "buckets": [
      {
        "key": "setA",
        "doc_count": 3,
        "Topics": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "topic1",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_a",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_d",
                    "doc_count": 1
                  }
                ]
              }
            },
            {
              "key": "topic2",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_d",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_c",
                    "doc_count": 1
                  }
                ]
              }
            },
            {
              "key": "topic3",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_d",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_c",
                    "doc_count": 1
                  }
                ]
              }
            }
          ]
        }
      },
      {
        "key": "setB",
        "doc_count": 2,
        "Topics": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "topic2",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_d",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_c",
                    "doc_count": 1
                  }
                ]
              }
            },
            {
              "key": "topic3",
              "doc_count": 2,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_d",
                    "doc_count": 2
                  },
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_c",
                    "doc_count": 1
                  }
                ]
              }
            },
            {
              "key": "topic1",
              "doc_count": 1,
              "SubTopics": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "subtopic_a",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_b",
                    "doc_count": 1
                  },
                  {
                    "key": "subtopic_d",
                    "doc_count": 1
                  }
                ]
              }
            }
          ]
        }
      }
    ]
  }
}


问:
Submitting form to Ajax Post type
I have multiple Ajax calls (Get and Post) on a single page of Laravel Application, I want to post a form using AJAX Post but the form is using the first Ajax on the page which has the Get type. How can I make the form use the second Ajax with the Post type?

This is a snippet for the problem as the application is very large to show its code.

```<code>  $.ajax({  //First Ajax
          type: "GET",
          url: "/course/digital-marketing/facebook/fetch",
          success: function (data) {

               function createOrUpdate(){
                document.getElementById("testForm").submit();// Form submission

                $.ajax({//Second Ajax
                    data: $('#testForm').serialize(),
                    url: "/course/digital-marketing/facebook",
                    type: "POST",
                    dataType: 'json',
                    success: function (data) {
                        console.log('Success:', data);

                    },
                    error: function (data) {
                        console.log('Error:', data);
                    }

                });

            }

              createOrUpdate()

          }

</code>```

Title: Submitting form to Ajax Post type

Body:
I have multiple Ajax calls (Get and Post) on a single page of Laravel Application, I want to post a form using AJAX Post but the form is using the first Ajax on the page which has the Get type. How can I make the form use the second Ajax with the Post type?

This is a snippet for the problem as the application is very large to show its code.

  $.ajax({  //First Ajax
          type: "GET",
          url: "/course/digital-marketing/facebook/fetch",
          success: function (data) {

               function createOrUpdate(){
                document.getElementById("testForm").submit();// Form submission

                $.ajax({//Second Ajax
                    data: $('#testForm').serialize(),
                    url: "/course/digital-marketing/facebook",
                    type: "POST",
                    dataType: 'json',
                    success: function (data) {
                        console.log('Success:', data);

                    },
                    error: function (data) {
                        console.log('Error:', data);
                    }

                });

            }

              createOrUpdate()

          }


问:
Do something when local notification is triggered in swift
Im trying to run a code (here I print in console) when the notification appears on screen even if user is not interacting with it, but nothing happens, what am I missing?

```<code>import SwiftUI
import UserNotifications

class MyUserNotificationCenterDelegate : NSObject, UNUserNotificationCenterDelegate
{
    func userNotificationCenter( center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {

    }

    func userNotificationCenter( center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    {
        print("notification arrived")
        completionHandler()
    }
}

struct ContentView: View
{
    var body: some View
    {
        VStack
        {
            Button("Permission")
            {
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
                    if success {
                        print("Done!")
                    } else if let error = error {
                        print(error.localizedDescription)
                    }
                }
            }

            Button("Schedule")
            {
                let content = UNMutableNotificationContent()
                content.title = "notification"
                content.subtitle = "subtitle"
                content.sound = UNNotificationSound.defaultCritical

                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)

                let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                UNUserNotificationCenter.current().add(request)

            }
            Button("Stop")
            {                UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

I tried conforming the notification delegate UNUserNotificationCenterDelegate as you can see, but maybe I did forget something here, or this is not what is called when notification just shows up

Body:
Im trying to run a code (here I print in console) when the notification appears on screen even if user is not interacting with it, but nothing happens, what am I missing?

import SwiftUI
import UserNotifications

class MyUserNotificationCenterDelegate : NSObject, UNUserNotificationCenterDelegate
{
    func userNotificationCenter( center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {

    }

    func userNotificationCenter( center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    {
        print("notification arrived")
        completionHandler()
    }
}

struct ContentView: View
{
    var body: some View
    {
        VStack
        {
            Button("Permission")
            {
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
                    if success {
                        print("Done!")
                    } else if let error = error {
                        print(error.localizedDescription)
                    }
                }
            }

            Button("Schedule")
            {
                let content = UNMutableNotificationContent()
                content.title = "notification"
                content.subtitle = "subtitle"
                content.sound = UNNotificationSound.defaultCritical

                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)

                let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                UNUserNotificationCenter.current().add(request)

            }
            Button("Stop")
            {                UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I tried conforming the notification delegate UNUserNotificationCenterDelegate as you can see, but maybe I did forget something here, or this is not what is called when notification just shows up


问:
I have a question with react native and nodejs with the multer library and GCP
I need to upload 2 fields, one for image and the other for video, but when I try to upload both, it doesn't work.
When I upload an input it works fine for me, as I show below, but I don't know how to modify it to receive 2 files and upload it with multer to gcs

In the front

```<code>  let formdata = new FormData();
  formdata.append("name", name)
  formdata.append("price", price)
  formdata.append("desc", desc)
  formdata.append("type", type)
  formdata.append("image", {uri: image, name: 'image.jpg', type: 'image/jpeg'})
  formdata.append("user_id", user.uid)
  formdata.append("video", {uri: video})
</code>```

In the Back

```<code>router.post('/addService',  multer.single('image'),  imgUpload.uploadToGcs,  async (req, res, next) =>  {
try {
    const data = req.body;
    if (req.file && req.file.cloudStoragePublicUrl) {
         data.imageUrl = req.file.cloudStoragePublicUrl;
    }
     let user_id = data.user_id;
     delete data.user_id
     const newService = new Services( {service_data:data, photo_gallery:"", video_galery:"", user_id:user_id});
     await newService.save();
     return res.status(201).json({
        result: "200",
    })
} catch (error) {
    console.log(error)
    return res.status(400).json({
        result: error,
    })
}

</code>```

I tried to make the following change but it didn't work for me, I

```<code>router.post('/addService',  multer.single('image'),multer.single('video'),  imgUpload.uploadToGcs,  async (req, res, next) =>  {
try {
    const data = req.body;
    if (req.file && req.file.cloudStoragePublicUrl) {
         data.imageUrl = req.file.cloudStoragePublicUrl;
    }
     let user_id = data.user_id;
     delete data.user_id
     const newService = new Services( {service_data:data, photo_gallery:"", video_galery:"", user_id:user_id});
     await newService.save();
     return res.status(201).json({
        result: "200",
    })
} catch (error) {
    console.log(error)
    return res.status(400).json({
        result: error,
    })
}

</code>```

also tried to use multer.fields and it didn't work either

```<code>router.post('/addService',  multer.fields[{image},{video}],  imgUpload.uploadToGcs,  async (req, res, next) =>  {
try {
    const data = req.body;
    if (req.file && req.file.cloudStoragePublicUrl) {
         data.imageUrl = req.file.cloudStoragePublicUrl;
    }
     let user_id = data.user_id;
     delete data.user_id
     const newService = new Services( {service_data:data, photo_gallery:"", video_galery:"", user_id:user_id});
     await newService.save();
     return res.status(201).json({
        result: "200",
    })
} catch (error) {
    console.log(error)
    return res.status(400).json({
        result: error,
    })
}

</code>```

Body:
I need to upload 2 fields, one for image and the other for video, but when I try to upload both, it doesn't work.
When I upload an input it works fine for me, as I show below, but I don't know how to modify it to receive 2 files and upload it with multer to gcs

In the front

  let formdata = new FormData();
  formdata.append("name", name)
  formdata.append("price", price)
  formdata.append("desc", desc)
  formdata.append("type", type)
  formdata.append("image", {uri: image, name: 'image.jpg', type: 'image/jpeg'})
  formdata.append("user_id", user.uid)
  formdata.append("video", {uri: video})

In the Back

router.post('/addService',  multer.single('image'),  imgUpload.uploadToGcs,  async (req, res, next) =>  {
try {
    const data = req.body;
    if (req.file && req.file.cloudStoragePublicUrl) {
         data.imageUrl = req.file.cloudStoragePublicUrl;
    }
     let user_id = data.user_id;
     delete data.user_id
     const newService = new Services( {service_data:data, photo_gallery:"", video_galery:"", user_id:user_id});
     await newService.save();
     return res.status(201).json({
        result: "200",
    })
} catch (error) {
    console.log(error)
    return res.status(400).json({
        result: error,
    })
}

I tried to make the following change but it didn't work for me, I

router.post('/addService',  multer.single('image'),multer.single('video'),  imgUpload.uploadToGcs,  async (req, res, next) =>  {
try {
    const data = req.body;
    if (req.file && req.file.cloudStoragePublicUrl) {
         data.imageUrl = req.file.cloudStoragePublicUrl;
    }
     let user_id = data.user_id;
     delete data.user_id
     const newService = new Services( {service_data:data, photo_gallery:"", video_galery:"", user_id:user_id});
     await newService.save();
     return res.status(201).json({
        result: "200",
    })
} catch (error) {
    console.log(error)
    return res.status(400).json({
        result: error,
    })
}

also tried to use multer.fields and it didn't work either

router.post('/addService',  multer.fields[{image},{video}],  imgUpload.uploadToGcs,  async (req, res, next) =>  {
try {
    const data = req.body;
    if (req.file && req.file.cloudStoragePublicUrl) {
         data.imageUrl = req.file.cloudStoragePublicUrl;
    }
     let user_id = data.user_id;
     delete data.user_id
     const newService = new Services( {service_data:data, photo_gallery:"", video_galery:"", user_id:user_id});
     await newService.save();
     return res.status(201).json({
        result: "200",
    })
} catch (error) {
    console.log(error)
    return res.status(400).json({
        result: error,
    })
}


问:
Apache POI docx to pdf SAXParseException: Premature End of File
I'm attempting to convert a docx file made in Apache POI to a pdf file. I've run into a couple of errors I haven't been able to resolve.

I'm using org.apache.poi:poi-ooxml:5.2.3 and fr.opensages.xdocreport:org.apache.poi.xwpf.converter.pdf:1.0.6

The code so far is as follows:

@GetMapping ("pdf")
fun getPdf (aResponse: HttpServletResponse) {

   val myDoc = XWPFDocument ()
   val myParagraph = myDoc.createParagraph ()
   val myRun = myParagraph.createRun ()
   myRun.setText ("Hello, world!")

   val myPdfOptions = PdfOptions.create ()

   aResponse.contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE
   aResponse.addHeader ("Content-disposition", "attachment; filename=\"hello-world.pdf\"")

   aResponse.outputStream.use {
      PdfConverter.getInstance ().convert (myDoc, it, myPdfOptions)
   }
}

```
<p>When I run this I get the following error:</p>
```java.lang.IllegalStateException: Expecting one Styles document part, but found 0
   at org.apache.poi.xwpf.usermodel.XWPFDocument.getStyle(XWPFDocument.java:587)
   at org.apache.poi.xwpf.converter.core.styles.XWPFStylesDocument.<init>(XWPFStylesDocument.java:190)
   at org.apache.poi.xwpf.converter.core.styles.XWPFStylesDocument.<init>(XWPFStylesDocument.java:184)
   at org.apache.poi.xwpf.converter.core.XWPFDocumentVisitor.createStylesDocument(XWPFDocumentVisitor.java:166)
   at org.apache.poi.xwpf.converter.core.XWPFDocumentVisitor.<init>(XWPFDocumentVisitor.java:159)
   at org.apache.poi.xwpf.converter.pdf.internal.PdfMapper.<init>(PdfMapper.java:149)
   at org.apache.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:55)
   at org.apache.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:38)
   at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)

```
<p>So next I added in an empty document styles into the document</p>
<pre class="lang-kotlin prettyprint-override"><code>   myDoc.createStyles ()
</code>```

This errors with the following:

```<code>org.xml.sax.SAXParseException: Premature end of file.
   at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
   at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:178)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1471)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1013)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:605)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:534)
   at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:888)
   at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:824)
   at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
   at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1216)
   at java.xml/com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:635)
   at org.apache.xmlbeans.impl.store.Locale$SaxLoader.load(Locale.java:2532)
   at org.apache.xmlbeans.impl.store.Locale.lambda$parseToXmlObject$3(Locale.java:717)
   at org.apache.xmlbeans.impl.store.Locale.syncWrap(Locale.java:490)
   at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:716)
   at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.parse(SchemaTypeLoaderBase.java:233)
   at org.apache.xmlbeans.impl.schema.AbstractDocumentFactory.parse(AbstractDocumentFactory.java:71)
   at org.apache.poi.xwpf.usermodel.XWPFDocument.getStyle(XWPFDocument.java:591)
... continues same as above error
</code>```

So far I haven't discovered a way around this last error. Maybe I am missing something in the Styles? It doesn't seem to like something with it's own createStyles() method.

Body:
I'm attempting to convert a docx file made in Apache POI to a pdf file. I've run into a couple of errors I haven't been able to resolve.

I'm using org.apache.poi:poi-ooxml:5.2.3 and fr.opensages.xdocreport:org.apache.poi.xwpf.converter.pdf:1.0.6

The code so far is as follows:

@GetMapping ("pdf")
fun getPdf (aResponse: HttpServletResponse) {

   val myDoc = XWPFDocument ()
   val myParagraph = myDoc.createParagraph ()
   val myRun = myParagraph.createRun ()
   myRun.setText ("Hello, world!")

   val myPdfOptions = PdfOptions.create ()

   aResponse.contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE
   aResponse.addHeader ("Content-disposition", "attachment; filename=\"hello-world.pdf\"")

   aResponse.outputStream.use {
      PdfConverter.getInstance ().convert (myDoc, it, myPdfOptions)
   }
}

When I run this I get the following error:

java.lang.IllegalStateException: Expecting one Styles document part, but found 0
   at org.apache.poi.xwpf.usermodel.XWPFDocument.getStyle(XWPFDocument.java:587)
   at org.apache.poi.xwpf.converter.core.styles.XWPFStylesDocument.<init>(XWPFStylesDocument.java:190)
   at org.apache.poi.xwpf.converter.core.styles.XWPFStylesDocument.<init>(XWPFStylesDocument.java:184)
   at org.apache.poi.xwpf.converter.core.XWPFDocumentVisitor.createStylesDocument(XWPFDocumentVisitor.java:166)
   at org.apache.poi.xwpf.converter.core.XWPFDocumentVisitor.<init>(XWPFDocumentVisitor.java:159)
   at org.apache.poi.xwpf.converter.pdf.internal.PdfMapper.<init>(PdfMapper.java:149)
   at org.apache.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:55)
   at org.apache.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:38)
   at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)

So next I added in an empty document styles into the document

   myDoc.createStyles ()

This errors with the following:

org.xml.sax.SAXParseException: Premature end of file.
   at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
   at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:178)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1471)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1013)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:605)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
   at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:534)
   at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:888)
   at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:824)
   at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
   at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1216)
   at java.xml/com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:635)
   at org.apache.xmlbeans.impl.store.Locale$SaxLoader.load(Locale.java:2532)
   at org.apache.xmlbeans.impl.store.Locale.lambda$parseToXmlObject$3(Locale.java:717)
   at org.apache.xmlbeans.impl.store.Locale.syncWrap(Locale.java:490)
   at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:716)
   at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.parse(SchemaTypeLoaderBase.java:233)
   at org.apache.xmlbeans.impl.schema.AbstractDocumentFactory.parse(AbstractDocumentFactory.java:71)
   at org.apache.poi.xwpf.usermodel.XWPFDocument.getStyle(XWPFDocument.java:591)
... continues same as above error

So far I haven't discovered a way around this last error. Maybe I am missing something in the Styles? It doesn't seem to like something with it's own createStyles() method.


问:
Create a new AWS project in PhpStorm
To create an AWS::Lambda that I can test locally.

I was following this tutorial until this part: https://youtu.be/31Wih42FqTM?t=249 (timecode set).

I have AWS Toolkit plugin:

Problem:

I don't have AWS option in New Project

I'm working on PhpStorm, it's because of that?

Answer: Finaly, I need Intellij idea:

Title: Create a new AWS project in PhpStorm


问:
How to check with Win32 API if an app is installed from Windows store?
I am trying to write a C++ program to check if an app is downloaded from Microsoft Store or not. This app can be natively installed using setup.exe file, which I can detect by reading the registry path that it initializes to.

Unfortunately when it is installed from App Store the registry path is different.

Can someone suggest me any Winn32 api for this to check if an app is installed from MS Store or reliable work arounds?


问:
Amplify multiple env
I have two environments for my Amplify backend and two branches Git Dev and Prod. Dev contains the Amplify environment Dev and Prod contains Prod. How can I update the (amplify) prod environment with dev content

git checkout dev
amplify env add dev
git checkout prod
amplify pull envName dev (error no dev env)

Title: Amplify multiple env


问:
How to use Array_agg without returning the same values in different Order?
When using Array_agg, it returns the same values in different orders. I tried using distinct in a few places and it didn't work. I tried using an order before and after the array and it would fail or not properly exclude results.

I am trying to find all fields in the field column that share the same time and same ID and put them into an array.

Columns are Fieldname, ID, Time

```<code>select b.Field, count(*)
from (select Time, ID, array_agg(fieldname) as Field
  from a
  group by 1,2
  order by 3) b
group by b.field
order by 1 desc
</code>```

This produces duplicate results
For example I will have:

```<code>Field Name    Count
Ghost,Mark    1234
Mark,Ghost    1234
</code>```

I also tried this below where I add a subquery where I first order the fields alphabetically when grouping time and ID but it failed to execute. I think due to array_agg not being the root query?

```<code>select a.Field, count(*)
from
  (select Time, ID, array_agg(fieldname) as field
  from
    (select Time, ID, fieldname
    from a
    group by 1,2
    order by 3 desc) a
  group by 1,2 ) b
group by 1
order by 2 desc
</code>```

Body:
When using Array_agg, it returns the same values in different orders. I tried using distinct in a few places and it didn't work. I tried using an order before and after the array and it would fail or not properly exclude results.

I am trying to find all fields in the field column that share the same time and same ID and put them into an array.

Columns are Fieldname, ID, Time

select b.Field, count(*)
from (select Time, ID, array_agg(fieldname) as Field
  from a
  group by 1,2
  order by 3) b
group by b.field
order by 1 desc

This produces duplicate results
For example I will have:

Field Name    Count
Ghost,Mark    1234
Mark,Ghost    1234

I also tried this below where I add a subquery where I first order the fields alphabetically when grouping time and ID but it failed to execute. I think due to array_agg not being the root query?

select a.Field, count(*)
from
  (select Time, ID, array_agg(fieldname) as field
  from
    (select Time, ID, fieldname
    from a
    group by 1,2
    order by 3 desc) a
  group by 1,2 ) b
group by 1
order by 2 desc


问:
i need change time from 24h to 12AM/PM
I need change time from 24h to 12AM/PM .. I select time am/pm but result 24h

```<code> foreach ($bookings as $booking) {
                $b_date = DateTime::createFromFormat('Y-m-d H:i:s', $booking->b_date . ' 00:00:00');
                $booking->b_date = $b_date->format($date_format);
                $b_date->modify("+{$booking->b_time} minutes");

                $b_create_date = DateTime::createFromFormat('Y-m-d H:i:s', $booking->b_create_date);
                $booking->b_create_date = $b_create_date->format($date_format .' H:i');
</code>```
```<code>    foreach ($bookings as $booking) {
                $start = DateTime::createFromFormat('Y-m-d H:i:s', $booking->b_date . ' 00:00:00');
                $start->modify("+{$booking->b_time} minutes");
                if ($start >= $start_date_time && $start <= $end_date_time) {
                    $end = clone $start;
                    $end->modify("+{$booking->b_service_duration} minutes");
                    $booking->start = $start->format('Y-m-d H:i');
                    $booking->end = $end->format('Y-m-d H:i');
                    $booking->b_service_duration_display = $hours[$booking->b_service_duration];
                    $bookings_filter[] = $booking;
                }

            }
</code>```

I change 'H:i:s' to "g:iA" but not work

Title: i need change time from 24h to 12AM/PM

Body:
I need change time from 24h to 12AM/PM .. I select time am/pm but result 24h

 foreach ($bookings as $booking) {
                $b_date = DateTime::createFromFormat('Y-m-d H:i:s', $booking->b_date . ' 00:00:00');
                $booking->b_date = $b_date->format($date_format);
                $b_date->modify("+{$booking->b_time} minutes");

                $b_create_date = DateTime::createFromFormat('Y-m-d H:i:s', $booking->b_create_date);
                $booking->b_create_date = $b_create_date->format($date_format .' H:i');

    foreach ($bookings as $booking) {
                $start = DateTime::createFromFormat('Y-m-d H:i:s', $booking->b_date . ' 00:00:00');
                $start->modify("+{$booking->b_time} minutes");
                if ($start >= $start_date_time && $start <= $end_date_time) {
                    $end = clone $start;
                    $end->modify("+{$booking->b_service_duration} minutes");
                    $booking->start = $start->format('Y-m-d H:i');
                    $booking->end = $end->format('Y-m-d H:i');
                    $booking->b_service_duration_display = $hours[$booking->b_service_duration];
                    $bookings_filter[] = $booking;
                }

            }

I change 'H:i:s' to "g:iA" but not work


问:
Event on element not firing with custom directive but firing on element that doesn't have the directive in Vue 3
For some reason my custom directive doesn't fire on any events except beforeMount. But they do fire on elements that don't even have the custom directive. What am I doing wrong?</p>
```<code><style>
    [v-cloak] {
        display: none;
    }
</style>
<script type="importmap">
    {
      "imports": {
        "vue": "https://unpkg.com/vue@3.2.45/dist/vue.esm-browser.js"
      }
    }
</script>
<script type="module">
    import { createApp } from 'vue'

    const sampledir = {

        beforeMount (el, binding) {
            el.value = binding.value;
        },

        beforeUpdate (el, binding) {
            alert("before updated");
        },

        updated (el, binding) {
            alert("updated");
        }

    }

    const app = createApp({
        data() {
            return {
                message: 'Hello World!',
                othermsg: "hey"
            }
        }
    }).directive("sampledir",sampledir).mount('#app');
</script>

<div id="app" v-cloak>
    <h1>{{ message }}</h1>
    <input v-sampledir="message" type="text" />
    <input v-model="othermsg" type="text" />
</div>
</code>```

Body:
For some reason my custom directive doesn't fire on any events except beforeMount. But they do fire on elements that don't even have the custom directive. What am I doing wrong?

{{ message }}

    <input v-sampledir="message" type="text" />
    <input v-model="othermsg" type="text" />


问:
a scrollbar solution/any solution to navigate in the window of tkinter lib
Im currently struggling with finding a solution to a project im working on.
so far I've reached to this point:
GUI so far
Basically Im loading a csv file and plotting graphs according to any variable I choose and I can plot
multiple graphs BUT, once I've plotted 4 graphs the 5th will no longer be visible since it will go out of the frame....
I've tried methods I saw online and came to the conclusion that the widgets I used just dont have the scrollbar option/implementation.
any suggestions on how to deal with that?</p>