问:
How to get Flutter WebSocket working with spring-boot backend?
I have tried many combinations of the values below, I have no idea why it isn't working. I don't even know if the problem is with frontend or backend setup. I pasted the relevant code parts below.

FLutter says the following when I try to connect (MYIPADDRESS is a valid IP address, the IP address of the pc):

```<code>WebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'http://MYIPADDRESS:8080/topic/greetings#' was not upgraded to websocket
</code>```

Here is the backend/spring-boot controller part:

```<code>@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String send(final String message) throws Exception {
    return message;
}
</code>```

Here is the backend/spring-boot configuration part:

```<code>@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
         registry.addEndpoint("/websocket").withSockJS();
    }
}
</code>```

Here is the frontend/flutter part:

```<code>final channel = IOWebSocketChannel.connect(
  Uri(
    scheme: "ws",
    host: "MYIPADDRESS",
    port: 8080,
    path: "/topic/greetings",
  ),
);
</code>```

Body:
I have tried many combinations of the values below, I have no idea why it isn't working. I don't even know if the problem is with frontend or backend setup. I pasted the relevant code parts below.

FLutter says the following when I try to connect (MYIPADDRESS is a valid IP address, the IP address of the pc):

WebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'http://MYIPADDRESS:8080/topic/greetings#' was not upgraded to websocket

Here is the backend/spring-boot controller part:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String send(final String message) throws Exception {
    return message;
}

Here is the backend/spring-boot configuration part:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
         registry.addEndpoint("/websocket").withSockJS();
    }
}

Here is the frontend/flutter part:

final channel = IOWebSocketChannel.connect(
  Uri(
    scheme: "ws",
    host: "MYIPADDRESS",
    port: 8080,
    path: "/topic/greetings",
  ),
);


来源: stackexchange

问:
function to sample based on several conditions
I am trying to prepare a function/loop which would sample a number of rows based on conditions.
I have two dataframes, the first one is a dataframe with day dates, people and their roles.

```<code>library(bizdays)
library(tidyverse)
from_date <- "2023-01-01"
to_date <- "2023-12-31"
create.calendar(name = "cal23", holidays = integer(0), weekdays = c("saturday", "sunday"))
daty2023 <- bizseq(from_date, to_date, "cal23") %>% as.data.frame()
daty2023 <- daty2023 %>% mutate(resource = "Michael")
daty2023 <- daty2023 %>% mutate(role = "Manager")
daty20231 <- daty2023 %>% mutate(resource = "Jose", role = "Manager")
daty20232 <- daty2023 %>% mutate(resource = "Jakub", role = "Researcher")
daty2023 <- rbind(daty2023, daty20231, daty20232)
colnames(daty2023) <- c("date", "resource", "role")
daty2023$date <-as.Date(daty2023$date)
</code>```

The second dataframe is a tasklist with names of tasks, roles needed for these tasks, a period in which they should be performed and a number of mandays which should be assigned to each task in a given period.

```<code>tasklist <- data.frame(
  task = c("Task1", "Task2", "Task3", "Task4"),
  sdate = c("2023-01-12", "2023-04-18", "2023-08-25", "2023-11-03"),
  fdate = c("2023-01-12", "2023-04-25", "2023-09-26", "2023-12-29"),
  resource = c("Manager", "Manager", "Researcher", "Manager"))

tasklist <- tasklist %>% mutate(mandays = as.integer(c("1", "10", "20", "30")))
tasklist$sdate <- as.Date(tasklist$sdate)
tasklist$fdate <- as.Date(tasklist$fdate)
</code>```

What I am trying to do now is to sample dates in which people are available from the first data frame and assign them to tasks in the second data frame based on conditions. To do that I use the sample_n() function.

```<code>df = data.frame()
for (i in 1:nrow(tasklist)) {
output = daty2023 %>% filter(date >= tasklist$sdate[i] & date <= tasklist$fdate[i] & role == tasklist$resource[i]) %>% sample_n(., tasklist$mandays[i]) %>% mutate(Task = tasklist$task[i])
df = rbind(df, output)
}
</code>```

This loop allows me to match a person's availability with project task time slot and a role. However I started to wonder, whether it would be possible, and if yes how it would be possible, to add an additional condition which would assign a given amount of mandays to a person. The loop from above produces 61 mandays assigned to people. I am thinking how to make sure that i.e. 40 mandays at least are assigned to Michael, 11 to Jose and 10 to Jakub. I reckon I could probably play with the weight argument but I do not see how it could give me exactly the split I am looking for.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to prepare a function/loop which would sample a number of rows based on conditions.
I have two dataframes, the first one is a dataframe with day dates, people and their roles.

library(bizdays)
library(tidyverse)
from_date <- "2023-01-01"
to_date <- "2023-12-31"
create.calendar(name = "cal23", holidays = integer(0), weekdays = c("saturday", "sunday"))
daty2023 <- bizseq(from_date, to_date, "cal23") %>% as.data.frame()
daty2023 <- daty2023 %>% mutate(resource = "Michael")
daty2023 <- daty2023 %>% mutate(role = "Manager")
daty20231 <- daty2023 %>% mutate(resource = "Jose", role = "Manager")
daty20232 <- daty2023 %>% mutate(resource = "Jakub", role = "Researcher")
daty2023 <- rbind(daty2023, daty20231, daty20232)
colnames(daty2023) <- c("date", "resource", "role")
daty2023$date <-as.Date(daty2023$date)

The second dataframe is a tasklist with names of tasks, roles needed for these tasks, a period in which they should be performed and a number of mandays which should be assigned to each task in a given period.

tasklist <- data.frame(
  task = c("Task1", "Task2", "Task3", "Task4"),
  sdate = c("2023-01-12", "2023-04-18", "2023-08-25", "2023-11-03"),
  fdate = c("2023-01-12", "2023-04-25", "2023-09-26", "2023-12-29"),
  resource = c("Manager", "Manager", "Researcher", "Manager"))

tasklist <- tasklist %>% mutate(mandays = as.integer(c("1", "10", "20", "30")))
tasklist$sdate <- as.Date(tasklist$sdate)
tasklist$fdate <- as.Date(tasklist$fdate)

What I am trying to do now is to sample dates in which people are available from the first data frame and assign them to tasks in the second data frame based on conditions. To do that I use the sample_n() function.

df = data.frame()
for (i in 1:nrow(tasklist)) {
output = daty2023 %>% filter(date >= tasklist$sdate[i] & date <= tasklist$fdate[i] & role == tasklist$resource[i]) %>% sample_n(., tasklist$mandays[i]) %>% mutate(Task = tasklist$task[i])
df = rbind(df, output)
}

This loop allows me to match a person's availability with project task time slot and a role. However I started to wonder, whether it would be possible, and if yes how it would be possible, to add an additional condition which would assign a given amount of mandays to a person. The loop from above produces 61 mandays assigned to people. I am thinking how to make sure that i.e. 40 mandays at least are assigned to Michael, 11 to Jose and 10 to Jakub. I reckon I could probably play with the weight argument but I do not see how it could give me exactly the split I am looking for.


问:
Discord Bot - "403 Forbidden" error with purge and other administrator commands although 2FA was set up
When I try to execute my Python script, the terminal reports an error message:

403 Forbidden (error code: 60003): Two factor is required for this operation

But I have already a 2FA security in my Authentication App.

```<code>import discord
from discord.ext import commands

intents = discord.Intents().all()
client = commands.Bot(command_prefix='.', intents=intents)
print(client)

@client.command()
async def clear(ctx):
    try:
        await ctx.channel.purge(limit=5)
    except Exception as e:
        print(e)

client.run("token")
</code>```

I tried to search in my discord settings on Privacy & Setting, but I think there are no problems in here.

In my developer page of discord, I gave on my bot the Administrator Role.

Body:
When I try to execute my Python script, the terminal reports an error message:

403 Forbidden (error code: 60003): Two factor is required for this operation

But I have already a 2FA security in my Authentication App.

import discord
from discord.ext import commands

intents = discord.Intents().all()
client = commands.Bot(command_prefix='.', intents=intents)
print(client)

@client.command()
async def clear(ctx):
    try:
        await ctx.channel.purge(limit=5)
    except Exception as e:
        print(e)

client.run("token")

I tried to search in my discord settings on Privacy & Setting, but I think there are no problems in here.

In my developer page of discord, I gave on my bot the Administrator Role.


问:
How to configure Ftrace on kernel 5.15.0-56-generic (ubuntu 22.04)?
I'm trying to configure and enable ftrace on my ubuntu machine but its doesn't work. I also tried the instructions from the link here. I'm sure I'm missing something minor but I can't tell what.

Configuration:

$ cat /boot/config-5.15.0-56-generic | grep CONFIG_FUNCTION_TRACER
CONFIG_FUNCTION_TRACER=y
$ cat /boot/config-5.15.0-56-generic | grep CONFIG_FUNCTION_GRAPH_TRACER
CONFIG_FUNCTION_GRAPH_TRACER=y
$ cat /boot/config-5.15.0-56-generic | grep CONFIG_STACK_TRACER
CONFIG_STACK_TRACER=y
$ cat /boot/config-5.15.0-56-generic | grep CONFIG_DYNAMIC_FTRACE
CONFIG_DYNAMIC_FTRACE=y
```
<pre class="lang-bash prettyprint-override"><code>$ uname -a
Linux <redacted> 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
</code>```

Enable tracing (with root user)

$ echo function > /sys/kernel/debug/tracing/current_trace
$ echo do_sys_open > /sys/kernel/debug/tracing/set_ftrace_filter
$ echo 1 > tracing_on
```
<p>debugfs is already mounted:</p>
<pre class="lang-bash prettyprint-override"><code>$ mount
debugfs on /sys/kernel/debug type debugfs (rw,nosuid,nodev,noexec,relatime)
tracefs on /sys/kernel/tracing type tracefs (rw,nosuid,nodev,noexec,relatime)
tracefs on /sys/kernel/debug/tracing type tracefs (rw,nosuid,nodev,noexec,relatime)
</code>```

After enabling the tracing I was expecting to see the traces in  /sys/kernel/debug/tracing/trace or /sys/kernel/debug/tracing/trace_pipe files but I didn't see any traces.

Update: Instructions to generate the traces are working as expected. I was able to generate the traces successfully for do_sys_openat2 but with do_sys_open I don't see any traces.

Body:
I'm trying to configure and enable ftrace on my ubuntu machine but its doesn't work. I also tried the instructions from the link here. I'm sure I'm missing something minor but I can't tell what.

Configuration:

$ cat /boot/config-5.15.0-56-generic | grep CONFIG_FUNCTION_TRACER
CONFIG_FUNCTION_TRACER=y
$ cat /boot/config-5.15.0-56-generic | grep CONFIG_FUNCTION_GRAPH_TRACER
CONFIG_FUNCTION_GRAPH_TRACER=y
$ cat /boot/config-5.15.0-56-generic | grep CONFIG_STACK_TRACER
CONFIG_STACK_TRACER=y
$ cat /boot/config-5.15.0-56-generic | grep CONFIG_DYNAMIC_FTRACE
CONFIG_DYNAMIC_FTRACE=y

$ uname -a
Linux <redacted> 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

Enable tracing (with root user)

$ echo function > /sys/kernel/debug/tracing/current_trace
$ echo do_sys_open > /sys/kernel/debug/tracing/set_ftrace_filter
$ echo 1 > tracing_on

debugfs is already mounted:

$ mount
debugfs on /sys/kernel/debug type debugfs (rw,nosuid,nodev,noexec,relatime)
tracefs on /sys/kernel/tracing type tracefs (rw,nosuid,nodev,noexec,relatime)
tracefs on /sys/kernel/debug/tracing type tracefs (rw,nosuid,nodev,noexec,relatime)

After enabling the tracing I was expecting to see the traces in  /sys/kernel/debug/tracing/trace or /sys/kernel/debug/tracing/trace_pipe files but I didn't see any traces.

Update: Instructions to generate the traces are working as expected. I was able to generate the traces successfully for do_sys_openat2 but with do_sys_open I don't see any traces.


问:
Is there a hack/workaround to communicate from Firefox to a USB device without the Gamepad API?
I am developing the hard- & software for a keyboard, and I'd like to make a web-based configurator (something like the (chrome-only) Wootility for the Wooting keyboards). Support for Chromium browsers is really easy with WebUSB/HID/Serial etc., but Firefox makes it significantly harder. It should be user-friendly, but I'd gladly use messy JS code hacks. I am thinking about using the Gamepad API, but I'd like to avoid that if possible. Are there any APIs/hacks/workarounds I can use to transmit data to my USB device besides the Gamepad API?

I guess the Filesystem API would be a way, but with how restricted that is on Firefox it's not nice to use (which is my end goal, I hate having to download drivers for every goddamn device, a nice-to-use web configurator would be perfect). Implementing the Gamepad is a bit more complicated due to a few factors, but there has to be another hack that I'm not thinking of. Input to the website is pretty easy (it is a keyboard after all) but output seems pretty hard. Indicator LEDs also probably won't work via JS.

For reference, I am using an Arduino Uno (with a custom USB-capable bootloader) for prototyping, and will probably stick to an ATMEGA chip, but that won't be the issue - if I need to change my chip for that, I'd do it. If all other methods are worse/impossible I'd use the Gamepad API, but I'd like to avoid that if possible.


问:
How to synchronize my items from Etsy to Instagram Shop?
Is there a way to automatically synchronize my Item list from Etsy to Instagram Shop?
So each time a product is added, edited, deleted, it will be replicated to the other platform. Same when a sell has been done on a platform.

Thanks


问:
Using fulltext search in MYSQL with ngram parser enabled is it possible to search for 1 character words with ngram_token_size set to 2?
I am using Planetscale which has a pretty big limitation in that you can't edit the mysql configuration so I cannot set ngram_token_size which defaults to 2. The problem with this is I need to use this for logographic languages such as Chinese which requires I be able to search for singular characters e.g. 你

Any suggestions on how I can get around this limitation.

I have 11 million rows in my database.

My only thought is I could pad every character in my database with a useless unicode character and then in the app code I format the search in the same way and parse the results to remove the useless unicode character.

The only issue with this is I will double my current database size (only 1.8Gb at the moment).

Any other suggestions?


问:
HOW TO SOLVE: [The truth value of a GeoDataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().] => I am using iterrow and if lop
With this code I am creating new columns with secific values based on the magnitude of merge_c['Actual methane']. I need a for loop to iterate by each row and an if statement as a condition to determine the other values of the other columns.

This is how my code looks like:

```<code>merge_c = merge_c.sort_values(by="2019-CON", ascending=False)
merge_c.head(21)
merge_c['Actual methane'] = merge_c['2019-CON'] - merge_c['total_methane_mean_TWh']
for index, row in merge_c.iterrows():
    if merge_c[merge_c['Actual methane'] > 0]:
        merge_c['bio_met_min'] = 0
        merge_c['lower_bound_ng'] = merge_c['Actual methane'] *0.016
        merge_c['higher_bound_ng'] = merge_c['Actual methane'][i] *0.056
        merge_c['lower_bound_bio'] = merge_c['total_methane_mean_TWh'] *0.059
        merge_c['higher_bound_bio'] = merge_c['total_methane_mean_TWh'] *0.0604

        merge_c['lower_total'] = merge_c['lower_bound_ng'] + merge_c['lower_bound_bio']
        merge_c['higher_total'] = merge_c['higher_bound_ng'][i] + merge_c['higher_bound_bio']
        merge_c['lower_total_ng'] = merge_c['2019-CON'] *0.016
        merge_c['higher_total_ng'] = merge_c['2019-CON']*0.056
    else:
        merge_c['bio_met_min'] = merge_c['total_methane_mean_TWh'] + merge_c['Actual methane']

        merge_c['lower_bound_ng'] = 0
        merge_c['higher_bound_ng'] = 0
        merge_c['lower_bound_bio'] = 0
        merge_c['higher_bound_bio'] = 0
        merge_c['lower_total'] = merge_c['bio_met_min']*0.051
        merge_c['higher_total'] = merge_c['bio_met_min'] *0.053
        merge_c['lower_total_ng']= merge_c['2019-CON'] *0.008
        merge_c['higher_total_ng'] = merge_c['2019-CON'] *0.022

Error:

ValueError                                Traceback (most recent call last)
<ipython-input-19-65d61ab401ac> in <module>
      4 merge_c['Actual methane'] = merge_c['2019-CON'] - merge_c['total_methane_mean_TWh']
      5 for index, row in merge_c.iterrows():
----> 6     if merge_c[merge_c['Actual methane'] > 0]:

-> 1442         raise ValueError(
   1443             f"The truth value of a {type(self).__name__} is ambiguous. "
   1444             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a GeoDataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I believe it does not like that I am using interrows() and the if statement together. I am trying to pass it through a for loop and an if statement so I can change the value of specific rows and columns based on merge_c['Actual_methane']. By using interrows(), I can have the values I am looking for for each row. Not sure how to fix it. Thank you so much in advance
</code>```

Body:
With this code I am creating new columns with secific values based on the magnitude of merge_c['Actual methane']. I need a for loop to iterate by each row and an if statement as a condition to determine the other values of the other columns.

This is how my code looks like:

merge_c = merge_c.sort_values(by="2019-CON", ascending=False)
merge_c.head(21)
merge_c['Actual methane'] = merge_c['2019-CON'] - merge_c['total_methane_mean_TWh']
for index, row in merge_c.iterrows():
    if merge_c[merge_c['Actual methane'] > 0]:
        merge_c['bio_met_min'] = 0
        merge_c['lower_bound_ng'] = merge_c['Actual methane'] *0.016
        merge_c['higher_bound_ng'] = merge_c['Actual methane'][i] *0.056
        merge_c['lower_bound_bio'] = merge_c['total_methane_mean_TWh'] *0.059
        merge_c['higher_bound_bio'] = merge_c['total_methane_mean_TWh'] *0.0604

        merge_c['lower_total'] = merge_c['lower_bound_ng'] + merge_c['lower_bound_bio']
        merge_c['higher_total'] = merge_c['higher_bound_ng'][i] + merge_c['higher_bound_bio']
        merge_c['lower_total_ng'] = merge_c['2019-CON'] *0.016
        merge_c['higher_total_ng'] = merge_c['2019-CON']*0.056
    else:
        merge_c['bio_met_min'] = merge_c['total_methane_mean_TWh'] + merge_c['Actual methane']

        merge_c['lower_bound_ng'] = 0
        merge_c['higher_bound_ng'] = 0
        merge_c['lower_bound_bio'] = 0
        merge_c['higher_bound_bio'] = 0
        merge_c['lower_total'] = merge_c['bio_met_min']*0.051
        merge_c['higher_total'] = merge_c['bio_met_min'] *0.053
        merge_c['lower_total_ng']= merge_c['2019-CON'] *0.008
        merge_c['higher_total_ng'] = merge_c['2019-CON'] *0.022

Error:

ValueError                                Traceback (most recent call last)
<ipython-input-19-65d61ab401ac> in <module>
      4 merge_c['Actual methane'] = merge_c['2019-CON'] - merge_c['total_methane_mean_TWh']
      5 for index, row in merge_c.iterrows():
----> 6     if merge_c[merge_c['Actual methane'] > 0]:

-> 1442         raise ValueError(
   1443             f"The truth value of a {type(self).__name__} is ambiguous. "
   1444             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a GeoDataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I believe it does not like that I am using interrows() and the if statement together. I am trying to pass it through a for loop and an if statement so I can change the value of specific rows and columns based on merge_c['Actual_methane']. By using interrows(), I can have the values I am looking for for each row. Not sure how to fix it. Thank you so much in advance


问:
Invalid shape () for image data using matplotlib
I have the following two functions:

```<code>def Rs(n1,n2,o):
    numerador = n1*np.cos(o) - n2*np.sqrt(1-(n1*np.sin(o)/n2)**2)
    denominador = n1*np.cos(o) + n2*np.sqrt(1-(n1*np.sin(o)/n2)**2)
    return (np.abs(numerador/denominador))**2

def Rp(n1,n2,o):
    numerador = - n2*np.cos(o) + n1*np.sqrt(1-(n1*np.sin(o)/n2)**2)
    denominador = n2*np.cos(o) + n1*np.sqrt(1-(n1*np.sin(o)/n2)**2)
    return (np.abs(numerador/denominador))**2
</code>```

And I have the following code:

```<code>import numpy as np

o2 = np.linspace(0, np.pi/2, 90) # Array amb les thetes
n2 = np.linspace(1.5, 3.5, 90) # Array amb els index n2

O2, N2 = np.meshgrid(o2, n2) # Meshgrid per crear el pla on avaluar la funcio

  Imatge = Rs(n1, N2, O2)
  Imatge2 = Rp(n1, N2, O2)

#plt.imshow(Imatge, cmap = 'nipy_spectral')
#plt.colorbar()

  fig, axs = plt.subplots(2)
  fig.suptitle("Rp i Rs en funcio de theta i n2")
  axs[0].imshow(Imatge, cmap = 'nipy_spectral')
  axs[0].set_title(r'$R_s ( \theta _i )$')
  axs[0].set_xlabel(r'$\theta $')
  axs[0].set_ylabel('$n_2$')
  axs[1].imshow(Imatge2, cmap = 'nipy_spectral')
  axs[1].set_title(r'$R_p ( \theta _i )$')
  axs[1].set_xlabel(r'$\theta $')
  axs[1].set_ylabel('$n_2$')
  plt.tight_layout()
  plt.show()
</code>```

This code seems to be correctly and outputs the adjunted image:

enter image description here

My question is why it works if I am passing the matrix O2 and N2 as parameter to functions Rs and Rp, when I should pass integer values?

Instead of that, the following code represents that it should work, because I am passing to functions integer values of the matrix iteration over echa row and column, but it doesnt work. I dont understand the cause of the problem:

```<code>import numpy as np

o2 = np.linspace(0, np.pi/2, 90) # Array amb les thetes
n2 = np.linspace(1.5, 3.5, 90) # Array amb els index n2

O2, N2 = np.meshgrid(o2, n2) # Meshgrid per crear el pla on avaluar la funcio

for i,j in enumerate(O2):
  for k,l in enumerate(j):
    print (i,k)
    Imatge = Rs(n1, N2[i][k], O2[i][k])
    Imatge2 = Rp(n1, N2[i][k], O2[i][k])

    fig, axs = plt.subplots(2)
    fig.suptitle("Rp i Rs en funcio de theta i n2")
    axs[0].imshow(Imatge, cmap = 'nipy_spectral')
    axs[0].set_title(r'$R_s ( \theta _i )$')
    axs[0].set_xlabel(r'$\theta $')
    axs[0].set_ylabel('$n_2$')
    axs[1].imshow(Imatge2, cmap = 'nipy_spectral')
    axs[1].set_title(r'$R_p ( \theta _i )$')
    axs[1].set_xlabel(r'$\theta $')
    axs[1].set_ylabel('$n_2$')
    plt.tight_layout()
    plt.show()
</code>```

In this code the error is in the line "axs[0].imshow(Imatge, cmap = 'nipy_spectral')" and the error code is :Invalid shape () for image data

I tried to pass to function the values of the matrix instead of passing them all the matrix. The code that works is not seems to be logical for me.

Body:
I have the following two functions:

def Rs(n1,n2,o):
    numerador = n1*np.cos(o) - n2*np.sqrt(1-(n1*np.sin(o)/n2)**2)
    denominador = n1*np.cos(o) + n2*np.sqrt(1-(n1*np.sin(o)/n2)**2)
    return (np.abs(numerador/denominador))**2

def Rp(n1,n2,o):
    numerador = - n2*np.cos(o) + n1*np.sqrt(1-(n1*np.sin(o)/n2)**2)
    denominador = n2*np.cos(o) + n1*np.sqrt(1-(n1*np.sin(o)/n2)**2)
    return (np.abs(numerador/denominador))**2

And I have the following code:

import numpy as np

o2 = np.linspace(0, np.pi/2, 90) # Array amb les thetes
n2 = np.linspace(1.5, 3.5, 90) # Array amb els index n2

O2, N2 = np.meshgrid(o2, n2) # Meshgrid per crear el pla on avaluar la funcio

  Imatge = Rs(n1, N2, O2)
  Imatge2 = Rp(n1, N2, O2)

#plt.imshow(Imatge, cmap = 'nipy_spectral')
#plt.colorbar()

  fig, axs = plt.subplots(2)
  fig.suptitle("Rp i Rs en funcio de theta i n2")
  axs[0].imshow(Imatge, cmap = 'nipy_spectral')
  axs[0].set_title(r'$R_s ( \theta _i )$')
  axs[0].set_xlabel(r'$\theta $')
  axs[0].set_ylabel('$n_2$')
  axs[1].imshow(Imatge2, cmap = 'nipy_spectral')
  axs[1].set_title(r'$R_p ( \theta _i )$')
  axs[1].set_xlabel(r'$\theta $')
  axs[1].set_ylabel('$n_2$')
  plt.tight_layout()
  plt.show()

This code seems to be correctly and outputs the adjunted image:

enter image description here

My question is why it works if I am passing the matrix O2 and N2 as parameter to functions Rs and Rp, when I should pass integer values?

Instead of that, the following code represents that it should work, because I am passing to functions integer values of the matrix iteration over echa row and column, but it doesnt work. I dont understand the cause of the problem:

import numpy as np

o2 = np.linspace(0, np.pi/2, 90) # Array amb les thetes
n2 = np.linspace(1.5, 3.5, 90) # Array amb els index n2

O2, N2 = np.meshgrid(o2, n2) # Meshgrid per crear el pla on avaluar la funcio

for i,j in enumerate(O2):
  for k,l in enumerate(j):
    print (i,k)
    Imatge = Rs(n1, N2[i][k], O2[i][k])
    Imatge2 = Rp(n1, N2[i][k], O2[i][k])

    fig, axs = plt.subplots(2)
    fig.suptitle("Rp i Rs en funcio de theta i n2")
    axs[0].imshow(Imatge, cmap = 'nipy_spectral')
    axs[0].set_title(r'$R_s ( \theta _i )$')
    axs[0].set_xlabel(r'$\theta $')
    axs[0].set_ylabel('$n_2$')
    axs[1].imshow(Imatge2, cmap = 'nipy_spectral')
    axs[1].set_title(r'$R_p ( \theta _i )$')
    axs[1].set_xlabel(r'$\theta $')
    axs[1].set_ylabel('$n_2$')
    plt.tight_layout()
    plt.show()

In this code the error is in the line "axs[0].imshow(Imatge, cmap = 'nipy_spectral')" and the error code is :Invalid shape () for image data

I tried to pass to function the values of the matrix instead of passing them all the matrix. The code that works is not seems to be logical for me.


问:
ASP.NET: Save if the user is logged in
I just wanted to ask if it is possible to save a boolean to see if a user is currently logged in WITHOUT a cookie? I read about Identity in ASP.NET, but how does it save the whole data? In the database? And then I also ask myself if it would be good practice to just save the boolean in my own database to know if the user is logged in. Or is this bad practice?

I think it is obvious that this is my first time creating a login functionality. I already read a lot of articles of microsoft and other third party sites. They are all talking about Identity and Cookies, but I am just curious if it is possible otherwise. For instance with my own database.

Thank you for every answer.

Title: ASP.NET: Save if the user is logged in


问:
How to add requests success throughput to JMeter summariser output (stdout)
I need to add a number of successful requests per second into the JMeter output which is printed to stdout.

I checked summariser settings in .properties file, but it seems it does not allow to add a new property to the output.
I am also thinking about defining a listener which outputs to stdout (if possible) and where I would add the success rate column, but not sure how to provide it with the least effort.


问:
Cast IMap to Java Map
Is there any way to cast HazelCast IMap to java.util.map(HashMap)?

```<code>IMap<K, V> imap = ...;
Map<K, V> map;
</code>```

Didn't find any library method to do so. One way is forming the Map using entrySet of IMap but that includes iterating over complete entrySet and may slow down for huge IMaps.

Title: Cast IMap to Java Map

Body:
Is there any way to cast HazelCast IMap to java.util.map(HashMap)?

IMap<K, V> imap = ...;
Map<K, V> map;

Didn't find any library method to do so. One way is forming the Map using entrySet of IMap but that includes iterating over complete entrySet and may slow down for huge IMaps.


问:
How can I get the user's Facebook profile link with verification?
In my app, user can add their Facebook profile link. But I don't want to add the user's Facebook profile link without verifying it.

I can get the user's verified Facebook profile link from LoginManager.logInWithPermissions(["user_link"] using react-native-fbsdk-next package. But I don't want to log in using Facebook since the user already signed in using google or any other way in my app.


问:
cmake target_link_libraries to a shared library end up static link
I have a executable called exec and a shared library called A.

I've used add_library(A SHARED A.cpp) and target_link_libraries(exec PRIVATE A).

But after I use ldd on exec, it seems that there's no dependency on libA.

But I use the same code on macOS, it works.

I would like to ask what may cause this situation over here?

Thanks in advance!


问:
botocore.eventstream.EventStream returning response with very high latency
I am using AWS S3 select with boto3 to get the chunk of CSV from the S3 bucket. The response returned by the query is an object of botocore.eventstream.EventStream.
After looping on the EventStream, the actual JSON response is decoded and loaded to Python list. The issue is that, looping over EventStream is taking around 4-5 minutes. Is there any way to speed it up?

The minimal code to achieve this is given below:

```<code>    query="""SELECT * FROM s3object s WHERE "s"."xyz"='"""+num+"""' AND "s"."datestr">='"""+date_raw+"""' AND "s"."timestr">='"""+time_raw+"""' AND "s"."datestr"<='""" +date_raw_to+"""' AND "s"."timestr"<='"""+time_raw_to+"""'"""

print("query: ", query)
key="base/"+filepath

t1=time.time()
resp = s3_client.select_object_content(
    Bucket=bucket_name,
    Key=key, # file name or complete path with folder
    Expression=query, # query to execute on the CSV
    ExpressionType='SQL',
    InputSerialization={
        "CSV": {
            'FileHeaderInfo': 'USE',
        },
    },
    OutputSerialization={
        'JSON': {}
    },
)
print("resp: ", resp)
print("resp: ", type(resp)) # prints <class 'dict'>

print(type(resp['Payload'])) # prints <class 'botocore.eventstream.EventStream'>

t2=time.time()
print("time taken to get select response: ", t2-t1) # 2.6 seconds
all_records=[]
t1=time.time()
for event in resp['Payload']: # loop over to get each record
    try:
        raw=event['Records']['Payload']
        s=str(raw)[1:]

        records = ast.literal_eval(str(event['Records']['Payload'])[1:])
        print("-----------------")
        all_records.append(records)
    except:
        pass
t2=time.time()
print("time taken to loop: ", t2-t1) # prints 300 seconds (too much)
</code>```

Any help will be highly appreciated. Thanks!

Body:
I am using AWS S3 select with boto3 to get the chunk of CSV from the S3 bucket. The response returned by the query is an object of botocore.eventstream.EventStream.
After looping on the EventStream, the actual JSON response is decoded and loaded to Python list. The issue is that, looping over EventStream is taking around 4-5 minutes. Is there any way to speed it up?

The minimal code to achieve this is given below:

    query="""SELECT * FROM s3object s WHERE "s"."xyz"='"""+num+"""' AND "s"."datestr">='"""+date_raw+"""' AND "s"."timestr">='"""+time_raw+"""' AND "s"."datestr"<='""" +date_raw_to+"""' AND "s"."timestr"<='"""+time_raw_to+"""'"""

print("query: ", query)
key="base/"+filepath

t1=time.time()
resp = s3_client.select_object_content(
    Bucket=bucket_name,
    Key=key, # file name or complete path with folder
    Expression=query, # query to execute on the CSV
    ExpressionType='SQL',
    InputSerialization={
        "CSV": {
            'FileHeaderInfo': 'USE',
        },
    },
    OutputSerialization={
        'JSON': {}
    },
)
print("resp: ", resp)
print("resp: ", type(resp)) # prints <class 'dict'>

print(type(resp['Payload'])) # prints <class 'botocore.eventstream.EventStream'>

t2=time.time()
print("time taken to get select response: ", t2-t1) # 2.6 seconds
all_records=[]
t1=time.time()
for event in resp['Payload']: # loop over to get each record
    try:
        raw=event['Records']['Payload']
        s=str(raw)[1:]

        records = ast.literal_eval(str(event['Records']['Payload'])[1:])
        print("-----------------")
        all_records.append(records)
    except:
        pass
t2=time.time()
print("time taken to loop: ", t2-t1) # prints 300 seconds (too much)

Any help will be highly appreciated. Thanks!


问:
Does JS support multi-threading now?
I was perusing some answers but they were very old. Does somebody know about the latest development in this regard?

Also is there any chance that JS will become multi-threaded in the near future?

Related Question:-
link

Title: Does JS support multi-threading now?


问:
Flask WTForms 400 Bad Request on validation
I've created a Flask Form using flask-wtforms, which is used to overwrite a .cfg-file. This works totally fine until i started to implement custom validators from wtforms. I need the custom validator to check for non-ascii characters. The validator seems to work - if the form content is correct, everything works as usual but if i use a non-ascii character, instead of giving me the error code on the screen and not sending the form, flask gives me a 400 - Bad Request and crashes (the log is empty though)

Here's my form:

```<code>class WeatherForm(FlaskForm):
    apikey = StringField(validators=[
                           InputRequired()])

    lat = StringField(validators=[
                             InputRequired()])

    lon = StringField(validators=[
                             InputRequired()])

    submit = SubmitField('Aktualisieren')

    def validate_apikey(self, apikey):
        def is_ascii(s):
            return all(ord(c) < 128 for c in s)
        if not is_ascii(apikey.data):
            raise ValidationError("ASCII - Characters only")
</code>```

This is the relevant part of the app.route:

```<code>    weatherForm=WeatherForm(apikey=apikey,lat=lat,lon=lon)
    if weatherForm.validate_on_submit():
        config['weather']['lat'] = weatherForm.lat.data
        config['weather']['lon'] = weatherForm.lon.data
        config['weather']['openweatherapikey'] = weatherForm.apikey.data
        with open(os.path.join(app.root_path,'settings.cfg'), 'w') as configfile:
            config.write(configfile)
        return redirect('/settings')
# more stuff with other forms and more data happening after this
</code>```

This is the HTML Part:

```<code><form action="" method="post">
          {{ weatherForm.hidden_tag() }}
          <label for="OpenWeatherAPI">OpenWeatherAPI Key:</label><br>
          {{ weatherForm.apikey }}
          <br>
          <label for="lan">Latitute:</label><br>
          {{ weatherForm.lat }}
          <br>
          <label for="long">Longitute:</label><br>
          {{ weatherForm.lon }}<br>
          {{ weatherForm.submit }}
        </form>
</code>```

Any ideas how i can fix that?

I haven't found other approaches apart from this one

Body:
I've created a Flask Form using flask-wtforms, which is used to overwrite a .cfg-file. This works totally fine until i started to implement custom validators from wtforms. I need the custom validator to check for non-ascii characters. The validator seems to work - if the form content is correct, everything works as usual but if i use a non-ascii character, instead of giving me the error code on the screen and not sending the form, flask gives me a 400 - Bad Request and crashes (the log is empty though)

Here's my form:

class WeatherForm(FlaskForm):
    apikey = StringField(validators=[
                           InputRequired()])

    lat = StringField(validators=[
                             InputRequired()])

    lon = StringField(validators=[
                             InputRequired()])

    submit = SubmitField('Aktualisieren')

    def validate_apikey(self, apikey):
        def is_ascii(s):
            return all(ord(c) < 128 for c in s)
        if not is_ascii(apikey.data):
            raise ValidationError("ASCII - Characters only")

This is the relevant part of the app.route:

    weatherForm=WeatherForm(apikey=apikey,lat=lat,lon=lon)
    if weatherForm.validate_on_submit():
        config['weather']['lat'] = weatherForm.lat.data
        config['weather']['lon'] = weatherForm.lon.data
        config['weather']['openweatherapikey'] = weatherForm.apikey.data
        with open(os.path.join(app.root_path,'settings.cfg'), 'w') as configfile:
            config.write(configfile)
        return redirect('/settings')
# more stuff with other forms and more data happening after this

This is the HTML Part:

<form action="" method="post">
          {{ weatherForm.hidden_tag() }}
          OpenWeatherAPI Key:

          {{ weatherForm.apikey }}

          Latitute:

          {{ weatherForm.lat }}

          Longitute:

          {{ weatherForm.lon }}

          {{ weatherForm.submit }}
        </form>

Any ideas how i can fix that?

I haven't found other approaches apart from this one


问:
Why am I getting a type mismatch error 13?
Why am I getting a type mismatch error with this code?

"=COUNTIF($A$2:$H$301," * "&L2&" * ")"

I am trying to count the number of instances the name in cell "L2" shows up in the range "A2:H301". As you can see it needs to be a partial match. Image below for a helpful visual.


问:
rails 5 model validation with multiple conditions only works with : notation?
I am trying to validate that a user input field is not nil, is an integer, and is greater than or equal to 0. so initially I tried validates :badge_count, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } and this worked for ensuring input was not nil and that it was an integer, but I was able to save a value of -1. initially, I just then added a validate method that checked if value was greater than or equal to 0 if it was present and raised an error if this failed. I still felt like this wasn't ideal and I should be able to use validates to check this. then I implemented validates :badge_count, :presence => true, :numericality => {:only_integer => true, :greater_than_or_equal_to => 0} and it worked perfectly. I've looked at docs for validation methods and can't figure out why it works like this. most our validates checks use the presence: true and it works just fine. do I just need to use this hash notation if I am combining multiple things in one validation?


问:
PHP Xdebug "Launch currently open script" works but "Listen for XDebug" doesn't
I'm using Ubuntu 22.04, PHP 8.1, Xdebug 3, nginx & VSCode to debug local scripts and web things on localhost.

I've set up launch.json to run the scripts and web pages with Xdebug.
I can break on breakpoints when I 'Launch current script' but when I run 'Listen for Xdebug' the breakpoints are not hit.

```<code>echo 'PHP version: ' . PHP_VERSION:
   PHP version: 8.1.2-1ubuntu2.9
echo 'Loaded PHP configuration file: ' . php_ini_loaded_file():
   Loaded PHP configuration file: /etc/php/8.1/fpm/php.ini
get_loaded_extensions():
    returns an array that contains 'xdebug'
xdebug_info():
   Step Debugger    ✘ disabled
</code>```

This is the current xdebug.ini in mods-available:

zend_extension=/usr/lib/php/20210902/xdebug.so
xdebug.mode=debug
xdebug.client_host=localhost
xdebug.start_with_request=trigger
xdebug.log=/mnt/ramdisk/xdebug.log
```
<p>EDIT:</p>
<p>I've also tried this:</p>
<p>Installed the Chrome extension to create a cookie for Xdebug. Enabled it for that page. No change... I'm using the Brave browser. That cookie is <code>XDEBUG_SESSION</code> and the value is <code>XDEBUG_ECLIPSE</code>.</p>
<p>Does anyone know why the 'Listen for Xdebug' doesn't work?</p>
<p>launch.json:</p>
```{
    "name": "Listen for XDebug",
    "type": "php",
    "request": "launch",
    "port": 9003,
    // "log": true,
    "runtimeExecutable": "/usr/bin/php"
},
{
    "name": "Launch currently open script",
    "type": "php",
    "request": "launch",
    "program": "${file}",
    "cwd": "${fileDirname}",
    "port": 9003,
    "runtimeExecutable": "/usr/bin/php"
},
```
<p>output of xdebug_info() from command line:</p>
```\ \ / /  | |    | |
 \ V / __| | ___| |__  _   _  __ _
  > < / _` |/ _ \ '_ \| | | |/ _` |
 / . \ (_| |  __/ |_) | |_| | (_| |
/_/ \_\__,_|\___|_.__/ \__,_|\__, |
                              __/ |
                             |___/

Version => 3.1.2
Support Xdebug on Patreon, GitHub, or as a business: https://xdebug.org/support

             Enabled Features (through 'xdebug.mode' setting)
Feature => Enabled/Disabled
Development Helpers => ✘ disabled
Coverage => ✘ disabled
GC Stats => ✘ disabled
Profiler => ✘ disabled
Step Debugger => ✔ enabled
Tracing => ✘ disabled

                            Optional Features
Compressed File Support => no
Clock Source => clock_gettime

                              Diagnostic Log
[Step Debug] WARN: Creating socket for 'localhost:9003', poll success, but error: Operation now in progress (29).
[Step Debug] ERR: Could not connect to debugging client. Tried: localhost:9003 (through xdebug.client_host/xdebug.client_port) :-(

                              Step Debugging
Debugger is not active

                                   PHP
                           Build Configuration
Version (Run Time) => 8.1.2-1ubuntu2.9
Version (Compile Time) => 8.1.1
Debug Build => no
Thread Safety => disabled
                                 Settings
Configuration File (php.ini) Path => /etc/php/8.1/cli
Loaded Configuration File => /etc/php/8.1/cli/php.ini
Scan this dir for additional .ini files => /etc/php/8.1/cli/conf.d
Additional .ini files parsed => /etc/php/8.1/cli/conf.d/10-mysqlnd.ini,
/etc/php/8.1/cli/conf.d/10-opcache.ini,
/etc/php/8.1/cli/conf.d/10-pdo.ini,
/etc/php/8.1/cli/conf.d/20-calendar.ini,
/etc/php/8.1/cli/conf.d/20-ctype.ini,
/etc/php/8.1/cli/conf.d/20-exif.ini,
/etc/php/8.1/cli/conf.d/20-ffi.ini,
/etc/php/8.1/cli/conf.d/20-fileinfo.ini,
/etc/php/8.1/cli/conf.d/20-ftp.ini,
/etc/php/8.1/cli/conf.d/20-gettext.ini,
/etc/php/8.1/cli/conf.d/20-iconv.ini,
/etc/php/8.1/cli/conf.d/20-mysqli.ini,
/etc/php/8.1/cli/conf.d/20-pdo_mysql.ini,
/etc/php/8.1/cli/conf.d/20-pdo_sqlite.ini,
/etc/php/8.1/cli/conf.d/20-phar.ini,
/etc/php/8.1/cli/conf.d/20-posix.ini,
/etc/php/8.1/cli/conf.d/20-readline.ini,
/etc/php/8.1/cli/conf.d/20-shmop.ini,
/etc/php/8.1/cli/conf.d/20-sockets.ini,
/etc/php/8.1/cli/conf.d/20-sqlite3.ini,
/etc/php/8.1/cli/conf.d/20-sysvmsg.ini,
/etc/php/8.1/cli/conf.d/20-sysvsem.ini,
/etc/php/8.1/cli/conf.d/20-sysvshm.ini,
/etc/php/8.1/cli/conf.d/20-tokenizer.ini,
/etc/php/8.1/cli/conf.d/20-xdebug.ini

Directive => Local Value => Master Value
xdebug.mode => debug => debug
xdebug.start_with_request => default => default
xdebug.start_upon_error => default => default
xdebug.output_dir => /tmp => /tmp
xdebug.use_compression => 0 => 0
xdebug.trigger_value => no value => no value
xdebug.file_link_format => no value => no value
xdebug.filename_format => no value => no value
xdebug.log => /mnt/ramdisk/xdebug.log => /mnt/ramdisk/xdebug.log
xdebug.log_level => 7 => 7
xdebug.var_display_max_children => 128 => 128
xdebug.var_display_max_data => 512 => 512
xdebug.var_display_max_depth => 3 => 3
xdebug.max_nesting_level => 256 => 256
xdebug.cli_color => 0 => 0
xdebug.force_display_errors => Off => Off
xdebug.force_error_reporting => 0 => 0
xdebug.halt_level => 0 => 0
xdebug.max_stack_frames => -1 => -1
xdebug.show_error_trace => Off => Off
xdebug.show_exception_trace => Off => Off
xdebug.show_local_vars => Off => Off
xdebug.dump.COOKIE => no value => no value
xdebug.dump.ENV => no value => no value
xdebug.dump.FILES => no value => no value
xdebug.dump.GET => no value => no value
xdebug.dump.POST => no value => no value
xdebug.dump.REQUEST => no value => no value
xdebug.dump.SERVER => no value => no value
xdebug.dump.SESSION => no value => no value
xdebug.dump_globals => On => On
xdebug.dump_once => On => On
xdebug.dump_undefined => Off => Off
xdebug.profiler_output_name => cachegrind.out.%p => cachegrind.out.%p
xdebug.profiler_append => Off => Off
xdebug.cloud_id => no value => no value
xdebug.client_host => localhost => localhost
xdebug.client_port => 9003 => 9003
xdebug.discover_client_host => Off => Off
xdebug.client_discovery_header => no value => no value
xdebug.idekey => no value => no value
xdebug.connect_timeout_ms => 200 => 200
xdebug.scream => Off => Off
xdebug.gc_stats_output_name => gcstats.%p => gcstats.%p
xdebug.trace_output_name => trace.%c => trace.%c
xdebug.trace_format => 0 => 0
xdebug.trace_options => 0 => 0
xdebug.collect_assignments => Off => Off
xdebug.collect_return => Off => Off
```
<h2>output of xdebug_info from web page:</h2>
```Version 3.1.2
Support Xdebug on Patreon, GitHub, or as a business
Enabled Features
(through 'xdebug.mode' setting)
Feature Enabled/Disabled    Docs
Development Helpers ✘ disabled
Coverage    ✘ disabled
GC Stats    ✘ disabled
Profiler    ✘ disabled
Step Debugger   ✔ enabled
Tracing ✘ disabled
Optional Features
Compressed File Support no
Clock Source    clock_gettime
Diagnostic Log
Message Docs
  [Log Files] File '/mnt/ramdisk/xdebug.log' could not be opened.
⚠  [Step Debug] Creating socket for 'localhost:9003', poll success, but error: Operation now in progress (29).
  [Step Debug] Could not connect to debugging client. Tried: localhost:9003 (through xdebug.client_host/xdebug.client_port) :-(
Step Debugging  Docs
Debugger    Not Active
PHP
Build Configuration
Version (Run Time)  8.1.2-1ubuntu2.9
Version (Compile Time)  8.1.1
Debug Build no
Thread Safety   disabled
Settings
Configuration File (php.ini) Path   /etc/php/8.1/cli
Loaded Configuration File   /etc/php/8.1/fpm/php.ini
Scan this dir for additional .ini files /etc/php/8.1/fpm/conf.d
Additional .ini files parsed    /etc/php/8.1/fpm/conf.d/10-mysqlnd.ini, /etc/php/8.1/fpm/conf.d/10-opcache.ini, /etc/php/8.1/fpm/conf.d/10-pdo.ini, /etc/php/8.1/fpm/conf.d/20-calendar.ini, /etc/php/8.1/fpm/conf.d/20-ctype.ini, /etc/php/8.1/fpm/conf.d/20-exif.ini, /etc/php/8.1/fpm/conf.d/20-ffi.ini, /etc/php/8.1/fpm/conf.d/20-fileinfo.ini, /etc/php/8.1/fpm/conf.d/20-ftp.ini, /etc/php/8.1/fpm/conf.d/20-gettext.ini, /etc/php/8.1/fpm/conf.d/20-iconv.ini, /etc/php/8.1/fpm/conf.d/20-inotify.ini, /etc/php/8.1/fpm/conf.d/20-mysqli.ini, /etc/php/8.1/fpm/conf.d/20-pdo_mysql.ini, /etc/php/8.1/fpm/conf.d/20-pdo_sqlite.ini, /etc/php/8.1/fpm/conf.d/20-phar.ini, /etc/php/8.1/fpm/conf.d/20-posix.ini, /etc/php/8.1/fpm/conf.d/20-readline.ini, /etc/php/8.1/fpm/conf.d/20-shmop.ini, /etc/php/8.1/fpm/conf.d/20-sockets.ini, /etc/php/8.1/fpm/conf.d/20-sqlite3.ini, /etc/php/8.1/fpm/conf.d/20-sysvmsg.ini, /etc/php/8.1/fpm/conf.d/20-sysvsem.ini, /etc/php/8.1/fpm/conf.d/20-sysvshm.ini, /etc/php/8.1/fpm/conf.d/20-tokenizer.ini, /etc/php/8.1/fpm/conf.d/20-xdebug.ini
Directive   Local Value Master Value    Docs
xdebug.mode debug   debug
xdebug.start_with_request   trigger trigger
xdebug.start_upon_error default default
xdebug.output_dir   /tmp    /tmp
xdebug.use_compression  0   0
xdebug.trigger_value    no value    no value
xdebug.file_link_format no value    no value
xdebug.filename_format  no value    no value
xdebug.log  /mnt/ramdisk/xdebug.log /mnt/ramdisk/xdebug.log
xdebug.log_level    7   7
xdebug.var_display_max_children 128 128
xdebug.var_display_max_data 512 512
xdebug.var_display_max_depth    3   3
xdebug.max_nesting_level    256 256
xdebug.cli_color    0   0
xdebug.force_display_errors Off Off
xdebug.force_error_reporting    0   0
xdebug.halt_level   0   0
xdebug.max_stack_frames -1  -1
xdebug.show_error_trace Off Off
xdebug.show_exception_trace Off Off
xdebug.show_local_vars  Off Off
xdebug.dump.COOKIE  no value    no value
xdebug.dump.ENV no value    no value
xdebug.dump.FILES   no value    no value
xdebug.dump.GET no value    no value
xdebug.dump.POST    no value    no value
xdebug.dump.REQUEST no value    no value
xdebug.dump.SERVER  no value    no value
xdebug.dump.SESSION no value    no value
xdebug.dump_globals On  On
xdebug.dump_once    On  On
xdebug.dump_undefined   Off Off
xdebug.profiler_output_name cachegrind.out.%p   cachegrind.out.%p
xdebug.profiler_append  Off Off
xdebug.cloud_id no value    no value
xdebug.client_host  localhost   localhost
xdebug.client_port  9003    9003
xdebug.discover_client_host Off Off
xdebug.client_discovery_header  no value    no value
xdebug.idekey   no value    no value
xdebug.connect_timeout_ms   200 200
xdebug.scream   Off Off
xdebug.gc_stats_output_name gcstats.%p  gcstats.%p
xdebug.trace_output_name    trace.%c    trace.%c
xdebug.trace_format 0   0
xdebug.trace_options    0   0
xdebug.collect_assignments  Off Off
xdebug.collect_return   Off Off
```

Body:
I'm using Ubuntu 22.04, PHP 8.1, Xdebug 3, nginx & VSCode to debug local scripts and web things on localhost.

I've set up launch.json to run the scripts and web pages with Xdebug.
I can break on breakpoints when I 'Launch current script' but when I run 'Listen for Xdebug' the breakpoints are not hit.

echo 'PHP version: ' . PHP_VERSION:
   PHP version: 8.1.2-1ubuntu2.9
echo 'Loaded PHP configuration file: ' . php_ini_loaded_file():
   Loaded PHP configuration file: /etc/php/8.1/fpm/php.ini
get_loaded_extensions():
    returns an array that contains 'xdebug'
xdebug_info():
   Step Debugger    ✘ disabled

This is the current xdebug.ini in mods-available:

zend_extension=/usr/lib/php/20210902/xdebug.so
xdebug.mode=debug
xdebug.client_host=localhost
xdebug.start_with_request=trigger
xdebug.log=/mnt/ramdisk/xdebug.log

EDIT:

I've also tried this:

Installed the Chrome extension to create a cookie for Xdebug. Enabled it for that page. No change... I'm using the Brave browser. That cookie is XDEBUG_SESSION and the value is XDEBUG_ECLIPSE.

Does anyone know why the 'Listen for Xdebug' doesn't work?

launch.json:

{
    "name": "Listen for XDebug",
    "type": "php",
    "request": "launch",
    "port": 9003,
    // "log": true,
    "runtimeExecutable": "/usr/bin/php"
},
{
    "name": "Launch currently open script",
    "type": "php",
    "request": "launch",
    "program": "${file}",
    "cwd": "${fileDirname}",
    "port": 9003,
    "runtimeExecutable": "/usr/bin/php"
},

output of xdebug_info() from command line:

\ \ / /  | |    | |
 \ V / __| | ___| |__  _   _  __ _
  > < / _` |/ _ \ '_ \| | | |/ _` |
 / . \ (_| |  __/ |_) | |_| | (_| |
/_/ \_\__,_|\___|_.__/ \__,_|\__, |
                              __/ |
                             |___/

Version => 3.1.2
Support Xdebug on Patreon, GitHub, or as a business: https://xdebug.org/support

             Enabled Features (through 'xdebug.mode' setting)
Feature => Enabled/Disabled
Development Helpers => ✘ disabled
Coverage => ✘ disabled
GC Stats => ✘ disabled
Profiler => ✘ disabled
Step Debugger => ✔ enabled
Tracing => ✘ disabled

                            Optional Features
Compressed File Support => no
Clock Source => clock_gettime

                              Diagnostic Log
[Step Debug] WARN: Creating socket for 'localhost:9003', poll success, but error: Operation now in progress (29).
[Step Debug] ERR: Could not connect to debugging client. Tried: localhost:9003 (through xdebug.client_host/xdebug.client_port) :-(

                              Step Debugging
Debugger is not active

                                   PHP
                           Build Configuration
Version (Run Time) => 8.1.2-1ubuntu2.9
Version (Compile Time) => 8.1.1
Debug Build => no
Thread Safety => disabled
                                 Settings
Configuration File (php.ini) Path => /etc/php/8.1/cli
Loaded Configuration File => /etc/php/8.1/cli/php.ini
Scan this dir for additional .ini files => /etc/php/8.1/cli/conf.d
Additional .ini files parsed => /etc/php/8.1/cli/conf.d/10-mysqlnd.ini,
/etc/php/8.1/cli/conf.d/10-opcache.ini,
/etc/php/8.1/cli/conf.d/10-pdo.ini,
/etc/php/8.1/cli/conf.d/20-calendar.ini,
/etc/php/8.1/cli/conf.d/20-ctype.ini,
/etc/php/8.1/cli/conf.d/20-exif.ini,
/etc/php/8.1/cli/conf.d/20-ffi.ini,
/etc/php/8.1/cli/conf.d/20-fileinfo.ini,
/etc/php/8.1/cli/conf.d/20-ftp.ini,
/etc/php/8.1/cli/conf.d/20-gettext.ini,
/etc/php/8.1/cli/conf.d/20-iconv.ini,
/etc/php/8.1/cli/conf.d/20-mysqli.ini,
/etc/php/8.1/cli/conf.d/20-pdo_mysql.ini,
/etc/php/8.1/cli/conf.d/20-pdo_sqlite.ini,
/etc/php/8.1/cli/conf.d/20-phar.ini,
/etc/php/8.1/cli/conf.d/20-posix.ini,
/etc/php/8.1/cli/conf.d/20-readline.ini,
/etc/php/8.1/cli/conf.d/20-shmop.ini,
/etc/php/8.1/cli/conf.d/20-sockets.ini,
/etc/php/8.1/cli/conf.d/20-sqlite3.ini,
/etc/php/8.1/cli/conf.d/20-sysvmsg.ini,
/etc/php/8.1/cli/conf.d/20-sysvsem.ini,
/etc/php/8.1/cli/conf.d/20-sysvshm.ini,
/etc/php/8.1/cli/conf.d/20-tokenizer.ini,
/etc/php/8.1/cli/conf.d/20-xdebug.ini

Directive => Local Value => Master Value
xdebug.mode => debug => debug
xdebug.start_with_request => default => default
xdebug.start_upon_error => default => default
xdebug.output_dir => /tmp => /tmp
xdebug.use_compression => 0 => 0
xdebug.trigger_value => no value => no value
xdebug.file_link_format => no value => no value
xdebug.filename_format => no value => no value
xdebug.log => /mnt/ramdisk/xdebug.log => /mnt/ramdisk/xdebug.log
xdebug.log_level => 7 => 7
xdebug.var_display_max_children => 128 => 128
xdebug.var_display_max_data => 512 => 512
xdebug.var_display_max_depth => 3 => 3
xdebug.max_nesting_level => 256 => 256
xdebug.cli_color => 0 => 0
xdebug.force_display_errors => Off => Off
xdebug.force_error_reporting => 0 => 0
xdebug.halt_level => 0 => 0
xdebug.max_stack_frames => -1 => -1
xdebug.show_error_trace => Off => Off
xdebug.show_exception_trace => Off => Off
xdebug.show_local_vars => Off => Off
xdebug.dump.COOKIE => no value => no value
xdebug.dump.ENV => no value => no value
xdebug.dump.FILES => no value => no value
xdebug.dump.GET => no value => no value
xdebug.dump.POST => no value => no value
xdebug.dump.REQUEST => no value => no value
xdebug.dump.SERVER => no value => no value
xdebug.dump.SESSION => no value => no value
xdebug.dump_globals => On => On
xdebug.dump_once => On => On
xdebug.dump_undefined => Off => Off
xdebug.profiler_output_name => cachegrind.out.%p => cachegrind.out.%p
xdebug.profiler_append => Off => Off
xdebug.cloud_id => no value => no value
xdebug.client_host => localhost => localhost
xdebug.client_port => 9003 => 9003
xdebug.discover_client_host => Off => Off
xdebug.client_discovery_header => no value => no value
xdebug.idekey => no value => no value
xdebug.connect_timeout_ms => 200 => 200
xdebug.scream => Off => Off
xdebug.gc_stats_output_name => gcstats.%p => gcstats.%p
xdebug.trace_output_name => trace.%c => trace.%c
xdebug.trace_format => 0 => 0
xdebug.trace_options => 0 => 0
xdebug.collect_assignments => Off => Off
xdebug.collect_return => Off => Off

output of xdebug_info from web page:

Version 3.1.2
Support Xdebug on Patreon, GitHub, or as a business
Enabled Features
(through 'xdebug.mode' setting)
Feature Enabled/Disabled    Docs
Development Helpers ✘ disabled
Coverage    ✘ disabled
GC Stats    ✘ disabled
Profiler    ✘ disabled
Step Debugger   ✔ enabled
Tracing ✘ disabled
Optional Features
Compressed File Support no
Clock Source    clock_gettime
Diagnostic Log
Message Docs
  [Log Files] File '/mnt/ramdisk/xdebug.log' could not be opened.
⚠  [Step Debug] Creating socket for 'localhost:9003', poll success, but error: Operation now in progress (29).
  [Step Debug] Could not connect to debugging client. Tried: localhost:9003 (through xdebug.client_host/xdebug.client_port) :-(
Step Debugging  Docs
Debugger    Not Active
PHP
Build Configuration
Version (Run Time)  8.1.2-1ubuntu2.9
Version (Compile Time)  8.1.1
Debug Build no
Thread Safety   disabled
Settings
Configuration File (php.ini) Path   /etc/php/8.1/cli
Loaded Configuration File   /etc/php/8.1/fpm/php.ini
Scan this dir for additional .ini files /etc/php/8.1/fpm/conf.d
Additional .ini files parsed    /etc/php/8.1/fpm/conf.d/10-mysqlnd.ini, /etc/php/8.1/fpm/conf.d/10-opcache.ini, /etc/php/8.1/fpm/conf.d/10-pdo.ini, /etc/php/8.1/fpm/conf.d/20-calendar.ini, /etc/php/8.1/fpm/conf.d/20-ctype.ini, /etc/php/8.1/fpm/conf.d/20-exif.ini, /etc/php/8.1/fpm/conf.d/20-ffi.ini, /etc/php/8.1/fpm/conf.d/20-fileinfo.ini, /etc/php/8.1/fpm/conf.d/20-ftp.ini, /etc/php/8.1/fpm/conf.d/20-gettext.ini, /etc/php/8.1/fpm/conf.d/20-iconv.ini, /etc/php/8.1/fpm/conf.d/20-inotify.ini, /etc/php/8.1/fpm/conf.d/20-mysqli.ini, /etc/php/8.1/fpm/conf.d/20-pdo_mysql.ini, /etc/php/8.1/fpm/conf.d/20-pdo_sqlite.ini, /etc/php/8.1/fpm/conf.d/20-phar.ini, /etc/php/8.1/fpm/conf.d/20-posix.ini, /etc/php/8.1/fpm/conf.d/20-readline.ini, /etc/php/8.1/fpm/conf.d/20-shmop.ini, /etc/php/8.1/fpm/conf.d/20-sockets.ini, /etc/php/8.1/fpm/conf.d/20-sqlite3.ini, /etc/php/8.1/fpm/conf.d/20-sysvmsg.ini, /etc/php/8.1/fpm/conf.d/20-sysvsem.ini, /etc/php/8.1/fpm/conf.d/20-sysvshm.ini, /etc/php/8.1/fpm/conf.d/20-tokenizer.ini, /etc/php/8.1/fpm/conf.d/20-xdebug.ini
Directive   Local Value Master Value    Docs
xdebug.mode debug   debug
xdebug.start_with_request   trigger trigger
xdebug.start_upon_error default default
xdebug.output_dir   /tmp    /tmp
xdebug.use_compression  0   0
xdebug.trigger_value    no value    no value
xdebug.file_link_format no value    no value
xdebug.filename_format  no value    no value
xdebug.log  /mnt/ramdisk/xdebug.log /mnt/ramdisk/xdebug.log
xdebug.log_level    7   7
xdebug.var_display_max_children 128 128
xdebug.var_display_max_data 512 512
xdebug.var_display_max_depth    3   3
xdebug.max_nesting_level    256 256
xdebug.cli_color    0   0
xdebug.force_display_errors Off Off
xdebug.force_error_reporting    0   0
xdebug.halt_level   0   0
xdebug.max_stack_frames -1  -1
xdebug.show_error_trace Off Off
xdebug.show_exception_trace Off Off
xdebug.show_local_vars  Off Off
xdebug.dump.COOKIE  no value    no value
xdebug.dump.ENV no value    no value
xdebug.dump.FILES   no value    no value
xdebug.dump.GET no value    no value
xdebug.dump.POST    no value    no value
xdebug.dump.REQUEST no value    no value
xdebug.dump.SERVER  no value    no value
xdebug.dump.SESSION no value    no value
xdebug.dump_globals On  On
xdebug.dump_once    On  On
xdebug.dump_undefined   Off Off
xdebug.profiler_output_name cachegrind.out.%p   cachegrind.out.%p
xdebug.profiler_append  Off Off
xdebug.cloud_id no value    no value
xdebug.client_host  localhost   localhost
xdebug.client_port  9003    9003
xdebug.discover_client_host Off Off
xdebug.client_discovery_header  no value    no value
xdebug.idekey   no value    no value
xdebug.connect_timeout_ms   200 200
xdebug.scream   Off Off
xdebug.gc_stats_output_name gcstats.%p  gcstats.%p
xdebug.trace_output_name    trace.%c    trace.%c
xdebug.trace_format 0   0
xdebug.trace_options    0   0
xdebug.collect_assignments  Off Off
xdebug.collect_return   Off Off


问:
how can I solve 'datatype mismatch error'?
In flutter I use Sqflite.I want to add a data to sql lite.However I get an error and can not solve the problem.It says data type mismatch...For better understanding I attach a screenshot of the code.db_helper  file
great_places file
this shows an error

```<code>import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as path;
import 'package:sqflite/sql.dart';
import 'package:sqflite/sqlite_api.dart';

class DBhelper {
  static Future<Database> database() async {
    final dbPath =
        await sql.getDatabasesPath(); // Get a location using getDatabasesPath
    return sql.openDatabase(path.join(dbPath, 'places.db'), // open the database
        onCreate: (Database db, int version) {
      return db.execute(
          'CREATE TABLE user_places(id TEXT PRIMARY KEY,title Text,image Text)');
    }, version: 1);
  }

  static Future<void> insert(String table, Map<String, Object?> data) async {
    final db = await DBhelper.database();
    db.insert(table, data, conflictAlgorithm: ConflictAlgorithm.replace);
  }

  static Future<List<Map<String, dynamic>>> getData(String table) async {
    final db = await DBhelper.database();
    return db.query(table);
  }
}

</code>```
```<code>import 'package:flutter/foundation.dart';
import 'dart:io';
import '../helpers/db_helper.dart';
import '../models/place.dart';

class GreatPlaces with ChangeNotifier {
  List<Place> _items = [];

  List<Place> get items {
    return [..._items];
  }

  void addPlace(String pickedTitle, File pickedImage) {
    final newPlace = Place(
        id: DateTime.now().toString(),
        image: pickedImage,
        title: pickedTitle,
        location: null);
    _items.add(newPlace);
    notifyListeners();
    DBhelper.insert('user_places', {
      'id': newPlace.id,
      'title': newPlace.title,
      'image': newPlace.image.path
    });
  }

  Future<void> fetchAndSetPlaces() async {
    final dataList = await DBhelper.getData('user_places');
    _items = dataList
        .map((item) => Place(
            id: item['id'],
            title: item['title'],
            location: null,
            image: File(item['image'])))
        .toList();
    notifyListeners();
  }
}

</code>```

I had a look to pub dev sqflite article,but could not find a problem

Body:
In flutter I use Sqflite.I want to add a data to sql lite.However I get an error and can not solve the problem.It says data type mismatch...For better understanding I attach a screenshot of the code.db_helper  file
great_places file
this shows an error

import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as path;
import 'package:sqflite/sql.dart';
import 'package:sqflite/sqlite_api.dart';

class DBhelper {
  static Future<Database> database() async {
    final dbPath =
        await sql.getDatabasesPath(); // Get a location using getDatabasesPath
    return sql.openDatabase(path.join(dbPath, 'places.db'), // open the database
        onCreate: (Database db, int version) {
      return db.execute(
          'CREATE TABLE user_places(id TEXT PRIMARY KEY,title Text,image Text)');
    }, version: 1);
  }

  static Future<void> insert(String table, Map<String, Object?> data) async {
    final db = await DBhelper.database();
    db.insert(table, data, conflictAlgorithm: ConflictAlgorithm.replace);
  }

  static Future<List<Map<String, dynamic>>> getData(String table) async {
    final db = await DBhelper.database();
    return db.query(table);
  }
}

import 'package:flutter/foundation.dart';
import 'dart:io';
import '../helpers/db_helper.dart';
import '../models/place.dart';

class GreatPlaces with ChangeNotifier {
  List<Place> _items = [];

  List<Place> get items {
    return [..._items];
  }

  void addPlace(String pickedTitle, File pickedImage) {
    final newPlace = Place(
        id: DateTime.now().toString(),
        image: pickedImage,
        title: pickedTitle,
        location: null);
    _items.add(newPlace);
    notifyListeners();
    DBhelper.insert('user_places', {
      'id': newPlace.id,
      'title': newPlace.title,
      'image': newPlace.image.path
    });
  }

  Future<void> fetchAndSetPlaces() async {
    final dataList = await DBhelper.getData('user_places');
    _items = dataList
        .map((item) => Place(
            id: item['id'],
            title: item['title'],
            location: null,
            image: File(item['image'])))
        .toList();
    notifyListeners();
  }
}

I had a look to pub dev sqflite article,but could not find a problem


问:
how to call the backend api after successfull oauth login
i have used oauth to integrate github login in my application ,i have getting the github dilog box and i can able to login ,but i am trying call one api from node that will gave me access and refresh token but i am not sure how can i call that,i have attached my code below please let me know what did i made mistake on

const githubAuth = async () => {
    window.location.assign(
      `https://github.com/login/oauth/authorize?client_id=${githubclientid}`,
      '_self'
    );
  };
```

i am not sure how to call the api post login

Body:
i have used oauth to integrate github login in my application ,i have getting the github dilog box and i can able to login ,but i am trying call one api from node that will gave me access and refresh token but i am not sure how can i call that,i have attached my code below please let me know what did i made mistake on

const githubAuth = async () => {
    window.location.assign(
      `https://github.com/login/oauth/authorize?client_id=${githubclientid}`,
      '_self'
    );
  };

i am not sure how to call the api post login


问:
Directory API not working out of my domain
[google-admin-sdk] We are using the Directory API to retrieve users' contacts. However, when we test with a user (that has a domain) I'm facing "App is blocked"-message, when we tested that with Miro users, it works fine. How can we solve that?</p>


问:
How to process audio from Youtube live stream video using Python?
I have tried several methods to extract audio from live youtube stream video, but they didn't work. I have tried the following snippets.

```<code>import youtube_dl
import wave

def process_audio(chunk):
    # Process the audio data in the chunk
    pass

ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
    'on_progress_callback': process_audio,
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=sUKwTVAc0Vo'])
</code>```

Kindly guide if there is some other method to do this task.

Body:
I have tried several methods to extract audio from live youtube stream video, but they didn't work. I have tried the following snippets.

import youtube_dl
import wave

def process_audio(chunk):
    # Process the audio data in the chunk
    pass

ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
    'on_progress_callback': process_audio,
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=sUKwTVAc0Vo'])

Kindly guide if there is some other method to do this task.


问:
Can I create type template for nested json object with dynamic property key with Typescript?
I am new to typescript and new to javascript. I am required to create this type of structure with json objects inside array:

[
  {
    dynamic_proerty_name: {
      array_A: [],
      array_B: [],
    },
  },
  ...
];```
</div>
</div>
</p>
<p>There are one to many objects. All objects have different <code>dynamic_proerty_name</code> (they are unique).</p>
<p>The way i've implemented this now is creating type as such:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>type Lists = {
  "array_A": string[];
  "array_B": string[];
};

// Create one object
let lists = {
  "array_A": [];
  "array_B": [];
};
let obj = {
  [dynamic_property_name]: lists,
};</code>```

Problem raises when I want to pass this datatype into function as parameter. I can set:

function foo(data: any[]) {
  ...
}```
</div>
</div>
</p>
<p>but as I understand it is unwise to use <code>any[]</code> as a type. I would like to set the exact type, but cant seem to figure it out. I've tried to to print these at runtime:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>typeof data              // returns: object
data.constructor.name    // returns: Array
data[0].constructor.name // returns: Object
typeof data[0]           // returns: object</code>```

I've tried Object[] and object[] as type, but it gives me error everytime.

Now I would figure that possible solutions would be to define Lists type again so that it would contain also the dynamic property, but I am uncertain if:
a) that is possible
b) that would solve my primary problem.

Body:
I am new to typescript and new to javascript. I am required to create this type of structure with json objects inside array:

[
  {
    dynamic_proerty_name: {
      array_A: [],
      array_B: [],
    },
  },
  ...
];

There are one to many objects. All objects have different dynamic_proerty_name (they are unique).

The way i've implemented this now is creating type as such:

type Lists = {
  "array_A": string[];
  "array_B": string[];
};

// Create one object
let lists = {
  "array_A": [];
  "array_B": [];
};
let obj = {
  [dynamic_property_name]: lists,
};

Problem raises when I want to pass this datatype into function as parameter. I can set:

function foo(data: any[]) {
  ...
}

but as I understand it is unwise to use any[] as a type. I would like to set the exact type, but cant seem to figure it out. I've tried to to print these at runtime:

typeof data              // returns: object
data.constructor.name    // returns: Array
data[0].constructor.name // returns: Object
typeof data[0]           // returns: object

I've tried Object[] and object[] as type, but it gives me error everytime.

Now I would figure that possible solutions would be to define Lists type again so that it would contain also the dynamic property, but I am uncertain if:
a) that is possible
b) that would solve my primary problem.


问:
ImageJ Macro script to batch process with color thresholding fails to save output tif files
I've written a script in ImageJ Macro in order to batch process a large number of images with color thresholding and particle analysis, modified from this tutorial. Most of the time the thresholding works automatically, but sometimes has to be done manually, so I've created a partly automated "human-in-the-loop" script, which pauses for user input in several places. The most important of these follows an if/else statement in which user input determines whether the automatic color thresholding is acceptable. If yes, then the particles are analyzed, and if no then the color threshold is re-set to be done manually. To make this possible, I duplicate the imagefile at the beginning of the script, and revert to the original in order to process it manually. The majority of the script works, but the .tif files are not saved when the thresholding is done automatically (interestingly, the files are saved when the else portion of the script is run, i.e. when the thresholding is done manually).

In troubleshooting this issue, I've tried saving the .tif file outside the if/else statement, but still inside the processImage function. With this modification, the output file is not saved even when the images are thresholded manually. I've also tried modifying the output directory - I wonder whether the issue results from some issue with which directory the images are being saved to. My other guess is that my process for generating the filenames is failing, but I've gone through a troubleshooting process to print the generated names, and this suggests that the names are being generated correctly.

This is my first time writing a script in ImageJ macro, and I don't know what else to try! Any ImageJ Macro wizards out there who can spot my problem? Gratitude in advance for many tedious hours of repetitive clicking avoided.

```<code>// ask user to select a folder (should be parent folder)
home_dir = getDirectory("select home folder");

//// prepare a folder to output the images
output_dir = home_dir + "output" + File.separator;
File.makeDirectory(output_dir);

input_dir = getDirectory("select process folder");

// Get the list of files from that directory
// ****NOTE: if there are non-image files in this directory, it may cause the macro to crash****
fileList = getFileList(input_dir);

for (i = 0; i < fileList.length; i++)
{
    processImage(fileList[i]);
}

updateResults();  // Update the results table so it shows the filenames

// Show a dialog to allow user to save the results file
outputFile = File.openDialog("Save results file");

// Save the results data
saveAs("results",outputFile);

function processImage(imageFile)
{
    // Store the number of results before executing the commands,
    // so we can add the filename just to the new results
    prevNumResults = nResults;

  //set working directory

    open(imageFile);
    // Get the filename from the title of the image that's open for adding to the results table
    // We do this instead of using the imageFile parameter so that the
    // directory path is not included on the table
    filename = getTitle();

    //***** my macro script*****

    //select line tool, measure, and set scale
    setTool("line");
    waitForUser("Click OK when done");
    run("Set Scale...");

    //duplicate image in case automated thresholding needs adjustment
    run("Duplicate...", " ");

    // Color Thresholder 1.52a
    // Autogenerated macro, single images only!
    min=newArray(3);
    max=newArray(3);
    filter=newArray(3);
    a=getTitle();
    run("HSB Stack");
    run("Convert Stack to Images");
    selectWindow("Hue");
    rename("0");
    selectWindow("Saturation");
    rename("1");
    selectWindow("Brightness");
    rename("2");
    min[0]=43;  // lower bound for Hue
    max[0]=132;  //upper bound for Hue
    filter[0]="pass";
    min[1]=25;   //lower bound for Saturation
    max[1]=255;   //upper bound for Saturation
    filter[1]="pass";
    min[2]=45;   //lower bound for Brightness
    max[2]=255;   //upper bound for Brightness
    filter[2]="pass";
    for (i=0;i<3;i++){
      selectWindow(""+i);
      setThreshold(min[i], max[i]);
      run("Convert to Mask");
      if (filter[i]=="stop")  run("Invert");
    }
    imageCalculator("AND create", "0","1");
    imageCalculator("AND create", "Result of 0","2");
    for (i=0;i<3;i++){
      selectWindow(""+i);
      close();
    }
    selectWindow("Result of 0");
    close();
    selectWindow("Result of Result of 0");
    rename(a);

    ans=getBoolean("good threshold?");

    if(ans==1){
        run("Analyze Particles...", "size=100000-Infinity pixel show=[Overlay Masks] display include");  //increase "size = 40000"
        waitForUser("check result");
        filename=getInfo("image.filename");
        image_out = output_dir + filename;
        saveAs("Tiff",image_out);
        print(image_out);

    } else{
        close();
        run("Out [-]");
        run("Out [-]");
        run("Out [-]");
        run("Color Threshold...");
        waitForUser("Click OK when done");
        run("Analyze Particles...", "size=70000-Infinity pixel show=[Overlay Masks] display include"); //have to increase it here too
        waitForUser("check result");
        filename=getInfo("image.filename");
        image_out = output_dir + filename;
        saveAs("Tiff",image_out);
        print(image_out);
    }

    // Now loop through each of the new results, and add the filename to the "Filename" column
     for (row = prevNumResults; row < nResults; row++)
        {
            setResult("Filename", row, filename);
        }

       close("*");  // Closes all images

}

</code>```

Body:
I've written a script in ImageJ Macro in order to batch process a large number of images with color thresholding and particle analysis, modified from this tutorial. Most of the time the thresholding works automatically, but sometimes has to be done manually, so I've created a partly automated "human-in-the-loop" script, which pauses for user input in several places. The most important of these follows an if/else statement in which user input determines whether the automatic color thresholding is acceptable. If yes, then the particles are analyzed, and if no then the color threshold is re-set to be done manually. To make this possible, I duplicate the imagefile at the beginning of the script, and revert to the original in order to process it manually. The majority of the script works, but the .tif files are not saved when the thresholding is done automatically (interestingly, the files are saved when the else portion of the script is run, i.e. when the thresholding is done manually).

In troubleshooting this issue, I've tried saving the .tif file outside the if/else statement, but still inside the processImage function. With this modification, the output file is not saved even when the images are thresholded manually. I've also tried modifying the output directory - I wonder whether the issue results from some issue with which directory the images are being saved to. My other guess is that my process for generating the filenames is failing, but I've gone through a troubleshooting process to print the generated names, and this suggests that the names are being generated correctly.

This is my first time writing a script in ImageJ macro, and I don't know what else to try! Any ImageJ Macro wizards out there who can spot my problem? Gratitude in advance for many tedious hours of repetitive clicking avoided.

// ask user to select a folder (should be parent folder)
home_dir = getDirectory("select home folder");

//// prepare a folder to output the images
output_dir = home_dir + "output" + File.separator;
File.makeDirectory(output_dir);

input_dir = getDirectory("select process folder");

// Get the list of files from that directory
// ****NOTE: if there are non-image files in this directory, it may cause the macro to crash****
fileList = getFileList(input_dir);

for (i = 0; i < fileList.length; i++)
{
    processImage(fileList[i]);
}

updateResults();  // Update the results table so it shows the filenames

// Show a dialog to allow user to save the results file
outputFile = File.openDialog("Save results file");

// Save the results data
saveAs("results",outputFile);

function processImage(imageFile)
{
    // Store the number of results before executing the commands,
    // so we can add the filename just to the new results
    prevNumResults = nResults;

  //set working directory

    open(imageFile);
    // Get the filename from the title of the image that's open for adding to the results table
    // We do this instead of using the imageFile parameter so that the
    // directory path is not included on the table
    filename = getTitle();

    //***** my macro script*****

    //select line tool, measure, and set scale
    setTool("line");
    waitForUser("Click OK when done");
    run("Set Scale...");

    //duplicate image in case automated thresholding needs adjustment
    run("Duplicate...", " ");

    // Color Thresholder 1.52a
    // Autogenerated macro, single images only!
    min=newArray(3);
    max=newArray(3);
    filter=newArray(3);
    a=getTitle();
    run("HSB Stack");
    run("Convert Stack to Images");
    selectWindow("Hue");
    rename("0");
    selectWindow("Saturation");
    rename("1");
    selectWindow("Brightness");
    rename("2");
    min[0]=43;  // lower bound for Hue
    max[0]=132;  //upper bound for Hue
    filter[0]="pass";
    min[1]=25;   //lower bound for Saturation
    max[1]=255;   //upper bound for Saturation
    filter[1]="pass";
    min[2]=45;   //lower bound for Brightness
    max[2]=255;   //upper bound for Brightness
    filter[2]="pass";
    for (i=0;i<3;i++){
      selectWindow(""+i);
      setThreshold(min[i], max[i]);
      run("Convert to Mask");
      if (filter[i]=="stop")  run("Invert");
    }
    imageCalculator("AND create", "0","1");
    imageCalculator("AND create", "Result of 0","2");
    for (i=0;i<3;i++){
      selectWindow(""+i);
      close();
    }
    selectWindow("Result of 0");
    close();
    selectWindow("Result of Result of 0");
    rename(a);

    ans=getBoolean("good threshold?");

    if(ans==1){
        run("Analyze Particles...", "size=100000-Infinity pixel show=[Overlay Masks] display include");  //increase "size = 40000"
        waitForUser("check result");
        filename=getInfo("image.filename");
        image_out = output_dir + filename;
        saveAs("Tiff",image_out);
        print(image_out);

    } else{
        close();
        run("Out [-]");
        run("Out [-]");
        run("Out [-]");
        run("Color Threshold...");
        waitForUser("Click OK when done");
        run("Analyze Particles...", "size=70000-Infinity pixel show=[Overlay Masks] display include"); //have to increase it here too
        waitForUser("check result");
        filename=getInfo("image.filename");
        image_out = output_dir + filename;
        saveAs("Tiff",image_out);
        print(image_out);
    }

    // Now loop through each of the new results, and add the filename to the "Filename" column
     for (row = prevNumResults; row < nResults; row++)
        {
            setResult("Filename", row, filename);
        }

       close("*");  // Closes all images

}


问:
What level of parallel safety avoids "cannot assign XIDs during a parallel operation"?
I recently ran into this error message while executing a query that called one of my PL/pgSQL functions:

```<code>ERROR:  cannot assign XIDs during a parallel operation
CONTEXT:  SQL statement [redacted]
PL/pgSQL function [redacted]
</code>```

The function is marked PARALLEL SAFE, and I assume this error is telling me that it should actually be marked PARALLEL RESTRICTED or PARALLEL UNSAFE. Given that I don't understand what in the code is parallel unsafe, does the above error give me any hint about what I'm doing wrong and what level of safety it requires?

Body:
I recently ran into this error message while executing a query that called one of my PL/pgSQL functions:

ERROR:  cannot assign XIDs during a parallel operation
CONTEXT:  SQL statement [redacted]
PL/pgSQL function [redacted]

The function is marked PARALLEL SAFE, and I assume this error is telling me that it should actually be marked PARALLEL RESTRICTED or PARALLEL UNSAFE. Given that I don't understand what in the code is parallel unsafe, does the above error give me any hint about what I'm doing wrong and what level of safety it requires?


问:
Mongoose DocumentArray Types (with autogenerated mongoose typescript types with mongoose-tsgen)
I am having issues trying to create a new Document in ts (it works fine in js).

"mongoose": "^5.11.10",
"mongoose-tsgen": "7.1.3",
node: v16.15.1
npm: v8.11.0
tsc: Version 4.9.3

Also it is a problem in the latest version of mongoose (6.1.5) and mongoose-tsgen (9.0.10)

Schema user.ts:

```<code>...
tikTokAdvertiserAccounts: [
    {
      id: String,
      name: String,
    },
  ],
...
</code>```

I get this in my types.gen.ts:

```<code>...
export interface UserTikTokAdvertiserAccount {
  id?: string;
  name?: string;
  _id: mongoose.Types.ObjectId;
}
...
</code>```

I want to create it in my router:

```<code>...
let advertiserAccounts: UserTikTokAdvertiserAccount[] = [];
advertiserAccounts.push({id:'testid', name:'testname'});

user.tikTokAdvertiserAccounts = advertiserAccounts; // problem line

await user.save();
...
</code>```

This throws an error:
Type 'UserTikTokAdvertiserAccount[]' is missing the following properties from type 'DocumentArray<UserTikTokAdvertiserAccountDocument>': isMongooseDocumentArray, create, id, $pop, and 8 more.

So my question is how do I create this DocumentArray?

Interestingly if I try:

```<code>...
user.tikTokAdvertiserAccounts = new mongoose.Types.DocumentArray(
    advertiserAccounts
);
...
</code>```

it seems to work out fine without Typescript complaining.

But if I try something on multiple lines then typescript gets confused:

```<code>const explicitAccounts = new mongoose.Types.DocumentArray(
    advertiserAccounts
);
user.tikTokAdvertiserAccounts = explicitAccounts;
</code>```

Type 'DocumentArray<Document<any, any, any>>' is not assignable to type 'DocumentArray<UserTikTokAdvertiserAccountDocument>'. Type 'Document<any, any, any>' is missing the following properties from type 'UserTikTokAdvertiserAccountDocument': ownerDocument, parent, parentArray

So my question is how should I create these sub document arrays on this user document? Or is there something wrong with the mongoose-tsgen library that should be different?

I was suggested by the author of this library to cast to any, but I don't particularly like that!

Body:
I am having issues trying to create a new Document in ts (it works fine in js).

"mongoose": "^5.11.10",
"mongoose-tsgen": "7.1.3",
node: v16.15.1
npm: v8.11.0
tsc: Version 4.9.3

Also it is a problem in the latest version of mongoose (6.1.5) and mongoose-tsgen (9.0.10)

Schema user.ts:

...
tikTokAdvertiserAccounts: [
    {
      id: String,
      name: String,
    },
  ],
...

I get this in my types.gen.ts:

...
export interface UserTikTokAdvertiserAccount {
  id?: string;
  name?: string;
  _id: mongoose.Types.ObjectId;
}
...

I want to create it in my router:

...
let advertiserAccounts: UserTikTokAdvertiserAccount[] = [];
advertiserAccounts.push({id:'testid', name:'testname'});

user.tikTokAdvertiserAccounts = advertiserAccounts; // problem line

await user.save();
...

This throws an error:
Type 'UserTikTokAdvertiserAccount[]' is missing the following properties from type 'DocumentArray<UserTikTokAdvertiserAccountDocument>': isMongooseDocumentArray, create, id, $pop, and 8 more.

So my question is how do I create this DocumentArray?

Interestingly if I try:

...
user.tikTokAdvertiserAccounts = new mongoose.Types.DocumentArray(
    advertiserAccounts
);
...

it seems to work out fine without Typescript complaining.

But if I try something on multiple lines then typescript gets confused:

const explicitAccounts = new mongoose.Types.DocumentArray(
    advertiserAccounts
);
user.tikTokAdvertiserAccounts = explicitAccounts;

Type 'DocumentArray<Document<any, any, any>>' is not assignable to type 'DocumentArray<UserTikTokAdvertiserAccountDocument>'. Type 'Document<any, any, any>' is missing the following properties from type 'UserTikTokAdvertiserAccountDocument': ownerDocument, parent, parentArray

So my question is how should I create these sub document arrays on this user document? Or is there something wrong with the mongoose-tsgen library that should be different?

I was suggested by the author of this library to cast to any, but I don't particularly like that!


问:
Fetching files with Even minutes from aws using boto3 and python3 on local machine?
I have some CSV files over the AWS s3 bucket where the file format is Year_Month_Date_Hour_Minute.csv

I have to fetch those files on my local machine which contains even minutes in it's name

I have already tried it using the for loop but It is calling the

```<code>pages = paginator.paginate(Bucket=self.bucket, Prefix=prefix)
</code>```

30 times for each hour, which takes a lot of time to return the output
refer the below piece of code to see what I have already done and share the best approach we can implement here

```<code>paginator = self.s3.get_paginator('list_objects')
            files = set()
            for i in range(0, 60, 2):
                pages = []
                prefix = '{:%Y_%m_%d_%H_}'.format(self.date) + '{}'.format(i)
                pages = paginator.paginate(Bucket=self.bucket, Prefix=prefix)
                items = []
                for page in pages:
                    if page.get('Contents') == None:
                        continue
                    else:
                        for item in page['Contents']:
                            items = set([item['Key']])
                            files = files.union(items)
</code>```

Thanks

Body:
I have some CSV files over the AWS s3 bucket where the file format is Year_Month_Date_Hour_Minute.csv

I have to fetch those files on my local machine which contains even minutes in it's name

I have already tried it using the for loop but It is calling the

pages = paginator.paginate(Bucket=self.bucket, Prefix=prefix)

30 times for each hour, which takes a lot of time to return the output
refer the below piece of code to see what I have already done and share the best approach we can implement here

paginator = self.s3.get_paginator('list_objects')
            files = set()
            for i in range(0, 60, 2):
                pages = []
                prefix = '{:%Y_%m_%d_%H_}'.format(self.date) + '{}'.format(i)
                pages = paginator.paginate(Bucket=self.bucket, Prefix=prefix)
                items = []
                for page in pages:
                    if page.get('Contents') == None:
                        continue
                    else:
                        for item in page['Contents']:
                            items = set([item['Key']])
                            files = files.union(items)

Thanks


问:
How can I toggle the tree data in ag-grid using a button (simplified and grouped)?
I am using ag-grid in my application with the Client-Side Row Model and I want to add a button that allows the user to toggle the tree data on and off. How can I do this using vanilla JavaScript?</p>


问:
Falied When i Tried to Deploy My React-App on Vercel
I'm having multiples error's while tryng to deploy my react website on vercel, i only know that's something about the dependecies that i'm using. on localhost the site work just fine.

My React.APP GitHub Repositorie

Here's my package.json("at the beginning i didn't have that bunch of thing, but i just installed all trying to resolve")

[Heres the error's that i'm having]       [

I tried run build locally, it opens but does not fetch the items that come from the API(commerce.js)
and when a click on something the page goes to my disk C:

And as i said a tried to re install all my dependencies, i use --force and --legacy-peer-deps as i saw and some tutorials, but no success


问:
CSS grid-template-areas issues
I am very new to CSS/HTML and am having issues with getting grid-template-areas to work.

I'm trying to get the layout to look similar to the Google homepage, but get this instead

The top 2 left buttons correspond to Projects1 and Projects2 in the grid, the top 3 to the right are Resume, square and Contact respectively. The blue logo image is logo in the grid, SB is the search bar.

Any help is appreciated! I had difficulty finding a similar question, but if there is an existing duplicate please let me know.

CSS:

```<code>.Resume { grid-area: Resume}
.Contact { grid-area: Contact}
.dropdown {grid-area: square}
.logo {grid-area: logo}
.SB {grid-area: Search-Bar}
.Projects {grid-area: Projects}
.Lucky {grid-area: Lucky}

.container {
  display: grid;
  grid-template-areas:
    " . . . . . Resume square Contact "
    ". . . . . . . ."
    ". . . . . . . ."
    ". . . . . . . ."
    ". . . . logo . . ."
    ". . . . SB  . . ."
    ". . . . Projects1 . Projects2 ."
    ". . . . . . . ."
    ". . . . . . . ."
    ". . . . . . . .";

  }

.Resume a {
  color: black;
  font: Arial;
  text-decoration: none;
}

.Resume a:hover {
  color: black;
  font: Arial;
  text-decoration: underline;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  justify-content: left;
}

.Contact button {
  background-color: rgb(0, 134, 248);
  border: none;
  color: white;
  font-weight: bold;
  height: 30px;
  text-decoration: none;
  font: Futura;
  cursor: pointer;
}

.SB input {
  width: 500px;
  height: 30px;
  border-radius: 15px;
  position: relative;
  border: 1px solid rgb(0, 134, 248);
}

.Projects1 button {
  background-color: rgb(242, 242, 242);
  border: none;
  color: rgb(117, 117, 117);
  font-weight: bold;
  text-decoration: none;
  font: Futura;
  cursor: pointer;
  height: 30px;
  justify-content: left;
}

.Projects2 button {
  background-color: rgb(242, 242, 242);
  border: none;
  color: rgb(117, 117, 117);
  font-weight: bold;
  text-decoration: none;
  font: Futura;
  cursor: pointer;
  height: 30px;
  justify-content: left;
}
</code>```

HTML:

```<code>
<!DOCTYPE html>
<html>
<head>
  <title>Page Name</title>
  <link rel="shortcut icon" href="images/"/>
    <link rel="stylesheet" href="css/HPstylesheet.css">
<style>
  .search {
    background-image: url(./search.jpg);
    position: left;
    background-size: 25px;
  }
</style>
</head>
<body>

<div class = "container">

    <div class = "Resume">
     <a  href = "www.example.com"> Resume </a>
    </div>

  <div class = "dropdown">
    <span>
      <img data-toggle="dropdown" src="images/square.jpg">
    </span>

  <div class="dropdown-content">
        <a target="_blank" href="#"> <img src="images/linkedin.jpg", width = "50px", heigth = "50px">
          <p >LinkedIn</p>
        </a>

        <a target="_blank" href="mailto: #"><img src="images/email.jpg", width = "50px", heigth = "50px">
          <p >Email</p>
        </a>

        <a target="_blank" href="#"><img src="images/github.jpg", width = "50px", heigth = "50px">
          <p >Github</p>
        </a>
  </div>
  </div>

  <div class = "Contact">
    <button> Contact </button>
  </div>

  <div class = "logo">
    <img src = "images/logo.jpg", height = "200px", width = "500px">
  </div>

 <div class = "SB">
    <form action="http://www.example.com/login.php">
  <input type="text" id = "search" placeholder="Hello... :)">
</form>
  </div>

  <div class = "Projects1">
    <button> Projects </button>
  </div>

<div class = "Projects2">
    <button> I'm Feeling Lucky </button>
  </div>

</div>

    </body>
</html>

</code>```

Title: CSS grid-template-areas issues

Body:
I am very new to CSS/HTML and am having issues with getting grid-template-areas to work.

I'm trying to get the layout to look similar to the Google homepage, but get this instead

The top 2 left buttons correspond to Projects1 and Projects2 in the grid, the top 3 to the right are Resume, square and Contact respectively. The blue logo image is logo in the grid, SB is the search bar.

Any help is appreciated! I had difficulty finding a similar question, but if there is an existing duplicate please let me know.

CSS:

.Resume { grid-area: Resume}
.Contact { grid-area: Contact}
.dropdown {grid-area: square}
.logo {grid-area: logo}
.SB {grid-area: Search-Bar}
.Projects {grid-area: Projects}
.Lucky {grid-area: Lucky}

.container {
  display: grid;
  grid-template-areas:
    " . . . . . Resume square Contact "
    ". . . . . . . ."
    ". . . . . . . ."
    ". . . . . . . ."
    ". . . . logo . . ."
    ". . . . SB  . . ."
    ". . . . Projects1 . Projects2 ."
    ". . . . . . . ."
    ". . . . . . . ."
    ". . . . . . . .";

  }

.Resume a {
  color: black;
  font: Arial;
  text-decoration: none;
}

.Resume a:hover {
  color: black;
  font: Arial;
  text-decoration: underline;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  justify-content: left;
}

.Contact button {
  background-color: rgb(0, 134, 248);
  border: none;
  color: white;
  font-weight: bold;
  height: 30px;
  text-decoration: none;
  font: Futura;
  cursor: pointer;
}

.SB input {
  width: 500px;
  height: 30px;
  border-radius: 15px;
  position: relative;
  border: 1px solid rgb(0, 134, 248);
}

.Projects1 button {
  background-color: rgb(242, 242, 242);
  border: none;
  color: rgb(117, 117, 117);
  font-weight: bold;
  text-decoration: none;
  font: Futura;
  cursor: pointer;
  height: 30px;
  justify-content: left;
}

.Projects2 button {
  background-color: rgb(242, 242, 242);
  border: none;
  color: rgb(117, 117, 117);
  font-weight: bold;
  text-decoration: none;
  font: Futura;
  cursor: pointer;
  height: 30px;
  justify-content: left;
}

HTML:

<!DOCTYPE html>

  <title>Page Name</title>
  <link rel="shortcut icon" href="images/"/>
    <link rel="stylesheet" href="css/HPstylesheet.css">

      Resume

LinkedIn

Email

Github

    <button> Contact </button>

    <form action="http://www.example.com/login.php">
  <input type="text" id = "search" placeholder="Hello... :)">
</form>

    <button> Projects </button>

    <button> I'm Feeling Lucky </button>