问:
How to input words in for loops comprehension list
I would like to get the following for loops in comphrension list if that's possible.

```<code>for i in range(number_of_word):
    word = input()
</code>```

Thanks

答:
You can use:

words = [input() for i in range(number_of_word)]
```

Here you get a list words with all the values inputted by the user.

Body:
I would like to get the following for loops in comphrension list if that's possible.

for i in range(number_of_word):
    word = input()

Thanks

Body:
You can use:

words = [input() for i in range(number_of_word)]

Here you get a list words with all the values inputted by the user.


来源: stackexchange

问:
asp.net connection issues
This is my ASP.NET code:

```<code><html>
<body>

<%
Dim Conn
Conn = "Provider=xxxxxx; Server=xxxxxx; Database=xxxxxx; Trusted_Connection=xxx; "

sql="INSERT INTO xxxx"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "')"

on error resume next
Conn.Execute sql,recaffected
if err<>0 then
  Response.Write("Update Failed")
else
  Response.Write("<h3>"Record Added</h3>")
end if

%>

</body>
</html>
</code>```

I always get a result of "Update Failed"... Can you see from the code why this is?

答:
Suggest a major refactoring to eliminate your SQL injection vulnerability.

```<code>Dim  conn As New SqlConnection(SomeConnectionString)
Dim  cmd As SqlCommand = conn.CreateCommand()

conn.Open()
cmd.CommandText="INSERT INTO MyTable(Column1, Column2)  " & _
                     " VALUES (@Value1, @Value2)"
cmd.Parameters.AddWithValue("@Value1", Request.Form("xxxx"))
cmd.Parameters.AddWithValue("@Value2", Request.Form("xxxx"))
'add all your parameters as per above  '

cmd.ExecuteNonQuery()
</code>```

OwnerDisplayName: Gui

ContentLicense: CC BY-SA 3.0

Title: asp.net connection issues

Body:
This is my ASP.NET code:

<%
Dim Conn
Conn = "Provider=xxxxxx; Server=xxxxxx; Database=xxxxxx; Trusted_Connection=xxx; "

sql="INSERT INTO xxxx"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "',"
sql=sql & "'" & Request.Form("xxxx") & "')"

on error resume next
Conn.Execute sql,recaffected
if err<>0 then
  Response.Write("Update Failed")
else
  Response.Write("
"Record Added
")
end if

%>

I always get a result of "Update Failed"... Can you see from the code why this is?

Body:
Suggest a major refactoring to eliminate your SQL injection vulnerability.

Dim  conn As New SqlConnection(SomeConnectionString)
Dim  cmd As SqlCommand = conn.CreateCommand()

conn.Open()
cmd.CommandText="INSERT INTO MyTable(Column1, Column2)  " & _
                     " VALUES (@Value1, @Value2)"
cmd.Parameters.AddWithValue("@Value1", Request.Form("xxxx"))
cmd.Parameters.AddWithValue("@Value2", Request.Form("xxxx"))
'add all your parameters as per above  '

cmd.ExecuteNonQuery()


问:
Apache Camel AMQP with selector is consuming any message
I am trying to use selectors on an amqp with Azure Service Bus consumer. However, for some reason the route is also consuming messages that do not match the selector.

Here's an example:

This route generates messages and append a header:

```<code><route id="MessageGenerator">
    <from uri="timer:generator?delay=5000&period=5000"/>

    <setHeader headerName="INSTANCE_ID">
        <simple>{{env:INSTANCE_ID}}</simple>
    </setHeader>

    <to uri="amqp:queue:external_queue" />
</route>
</code>```

While this route should consume only those that contain INSTANCE_ID matching 2 possible values: env:INSTANCE_ID or Any.

```<code><route id="ExternalConsumer">
    <from uri="amqp:queue:external_queue?selector=INSTANCE_ID IN ('{{env:INSTANCE_ID}}', 'Any')"/>

    <log message="{{env:INSTANCE_ID}} consumed message with Instance ID: ${header.INSTANCE_ID}" logName="AMQP_TEST" loggingLevel="INFO"/>

</route>
</code>```

But the the log shows that it is consuming any message, regardless of the selector specifying which ones.

Am I missing something?

Thanks!

答: Issue here was that Azure Service Bus does NOT support selectors on queues. I switched to topics, which already have filters per subscription.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use selectors on an amqp with Azure Service Bus consumer. However, for some reason the route is also consuming messages that do not match the selector.

Here's an example:

This route generates messages and append a header:

<route id="MessageGenerator">
    <from uri="timer:generator?delay=5000&period=5000"/>

    <setHeader headerName="INSTANCE_ID">
        <simple>{{env:INSTANCE_ID}}</simple>
    </setHeader>

    <to uri="amqp:queue:external_queue" />
</route>

While this route should consume only those that contain INSTANCE_ID matching 2 possible values: env:INSTANCE_ID or Any.

<route id="ExternalConsumer">
    <from uri="amqp:queue:external_queue?selector=INSTANCE_ID IN ('{{env:INSTANCE_ID}}', 'Any')"/>

    <log message="{{env:INSTANCE_ID}} consumed message with Instance ID: ${header.INSTANCE_ID}" logName="AMQP_TEST" loggingLevel="INFO"/>

</route>

But the the log shows that it is consuming any message, regardless of the selector specifying which ones.

Am I missing something?

Thanks!


问:
How to statically link PROJ to pybind11
I'm interested in statically linking PROJ to a library created with pybind11.

but, I get error by cmake.

Why am I getting this error and how can I fix it?

My CMakeLists.txt is this.

```<code>cmake_minimum_required(VERSION 3.4)
project(myearth LANGUAGES CXX)

add_subdirectory(pybind11)
pybind11_add_module(myearth MyEarth.cpp)

include_directories(${CMAKE_SOURCE_DIR}/PROJ/include)
add_library(proj4 STATIC IMPORTED)
set_target_properties(proj4 PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/PROJ/lib/libproj.a)

target_link_libraries(myearth PRIVATE proj4)
</code>```

CMake Error.

I think fPIC option is for shared library. so, libproj.a is not necessary this option because this is static library.

```<code>(venv) ~/Projects/LinkLibTest/MySample/build$ make
[ 50%] Building CXX object CMakeFiles/myearth.dir/MyEarth.cpp.o
[100%] Linking CXX shared module myearth.cpython-36m-x86_64-linux-gnu.so
/usr/bin/ld: ../PROJ/lib/libproj.a(proj_4D_api.o): relocation R_X86_64_PC32 against symbol `pj_errno' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: bad value
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/myearth.dir/build.make:98: myearth.cpython-36m-x86_64-linux-gnu.so] Error 1
make[1]: *** [CMakeFiles/Makefile2:100: CMakeFiles/myearth.dir/all] Error 2
make: *** [Makefile:91: all] Error 2
(venv) ~/Projects/LinkLibTest/MySample/build$
</code>```

I created libproj.a by the following command.

```<code>$ ./configure --prefix=/output --disable-shared
$ sudo make
$ sudo make install
</code>```

Linux Mint 20.3 64bit

CMake v3.22.2

PROJ v5.2.0 (https://proj.org/)

Python v3.6.8

Thank you.

答:
Shared libraries must have position independent code, but your version of PROJ was built without it; you will have to rebuild PROJ with PIC.</p>
```<code>$ ./configure --prefix=/output --with-pic
</code>```

Title: How to statically link PROJ to pybind11

Body:
I'm interested in statically linking PROJ to a library created with pybind11.

but, I get error by cmake.

Why am I getting this error and how can I fix it?

My CMakeLists.txt is this.

cmake_minimum_required(VERSION 3.4)
project(myearth LANGUAGES CXX)

add_subdirectory(pybind11)
pybind11_add_module(myearth MyEarth.cpp)

include_directories(${CMAKE_SOURCE_DIR}/PROJ/include)
add_library(proj4 STATIC IMPORTED)
set_target_properties(proj4 PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/PROJ/lib/libproj.a)

target_link_libraries(myearth PRIVATE proj4)

CMake Error.

I think fPIC option is for shared library. so, libproj.a is not necessary this option because this is static library.

(venv) ~/Projects/LinkLibTest/MySample/build$ make
[ 50%] Building CXX object CMakeFiles/myearth.dir/MyEarth.cpp.o
[100%] Linking CXX shared module myearth.cpython-36m-x86_64-linux-gnu.so
/usr/bin/ld: ../PROJ/lib/libproj.a(proj_4D_api.o): relocation R_X86_64_PC32 against symbol `pj_errno' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: bad value
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/myearth.dir/build.make:98: myearth.cpython-36m-x86_64-linux-gnu.so] Error 1
make[1]: *** [CMakeFiles/Makefile2:100: CMakeFiles/myearth.dir/all] Error 2
make: *** [Makefile:91: all] Error 2
(venv) ~/Projects/LinkLibTest/MySample/build$

I created libproj.a by the following command.

$ ./configure --prefix=/output --disable-shared
$ sudo make
$ sudo make install

Linux Mint 20.3 64bit

CMake v3.22.2

PROJ v5.2.0 (https://proj.org/)

Python v3.6.8

Thank you.

Body:
Shared libraries must have position independent code, but your version of PROJ was built without it; you will have to rebuild PROJ with PIC.

$ ./configure --prefix=/output --with-pic


问:
R histogram plotting
I have a problem with my R double histogram.
I am adding two hist on the same plot, and for some reason the top part of the graph is cut off. I am simply trying to fit all the 'bars' within the plot.
Can anyone please help?
the graph currently looks like this, cut off at the top

```<code>mut <- subset(data_age, data_mutant =="Mutated")
notmut <- subset(data_age, data_mutant =="not mutated")

set.seed(100)
p1 <- hist(mut, plot=F)
p2 <- hist(notmut,plot=F)
plot( p1, col=rgb(0,0,1,1/4), xlim=range(c(mut,notmut)))
plot( p2, col=rgb(1,0,0,1/4), xlim=range(c(mut,notmut)), add=T)
</code>```

答:
Add a ylim as well.

```<code>p1 <- hist(mut, plot=F)
p2 <- hist(notmut,plot=F)
plot( p1, col=rgb(0,0,1,1/4), xlim=range(c(mut,notmut)), ylim=range(c(p1$counts,p2$counts)))
plot( p2, col=rgb(1,0,0,1/4), add=T)
</code>```

Title: R histogram plotting

Body:
I have a problem with my R double histogram.
I am adding two hist on the same plot, and for some reason the top part of the graph is cut off. I am simply trying to fit all the 'bars' within the plot.
Can anyone please help?
the graph currently looks like this, cut off at the top

mut <- subset(data_age, data_mutant =="Mutated")
notmut <- subset(data_age, data_mutant =="not mutated")

set.seed(100)
p1 <- hist(mut, plot=F)
p2 <- hist(notmut,plot=F)
plot( p1, col=rgb(0,0,1,1/4), xlim=range(c(mut,notmut)))
plot( p2, col=rgb(1,0,0,1/4), xlim=range(c(mut,notmut)), add=T)

Body:
Add a ylim as well.

p1 <- hist(mut, plot=F)
p2 <- hist(notmut,plot=F)
plot( p1, col=rgb(0,0,1,1/4), xlim=range(c(mut,notmut)), ylim=range(c(p1$counts,p2$counts)))
plot( p2, col=rgb(1,0,0,1/4), add=T)


问:
Which NET version takes priority when running an app System or Contained App
I am working on an app for NET 5 and because NET 5 isn’t released built into windows the main suggestion I have found is to create a contained app with the NET 5 runtimes. The issue with this as I understand it is that this can lead to security issues if new releases are not made and there are issues in NET 5.

So the question is which version would take priority.

A. The App contained NET5 runtimes.

Or

B. Newer Version NET5 runtimes installed in the Windows System separately.

答:
For apps with self contained deployment, the only runtime version being used is the one bundled with the app itself. In that way, the apps are well isolated and side by side (3.1 apps can live nicely with 6.0 apps without breaking each other).

If you want an app to use the common runtime installed, you have to publish it with framework dependent deployment.

If your goal is to resolve vulnerabilities in self contained deployment, make sure that,

Your app can auto update itself

You publish new releases of your app whenever (likely to be monthly) Microsoft publishes a new runtime version.


答:
Two ways here:

The spark-fast-tests library has two methods for making DataFrame comparisons:

The assertSmallDataFrameEquality method collects DataFrames on the driver node and makes the comparison

```<code>def assertSmallDataFrameEquality(actualDF: DataFrame, expectedDF: DataFrame): Unit = {
  if (!actualDF.schema.equals(expectedDF.schema)) {
    throw new DataFrameSchemaMismatch(schemaMismatchMessage(actualDF, expectedDF))
  }
  if (!actualDF.collect().sameElements(expectedDF.collect())) {
    throw new DataFrameContentMismatch(contentMismatchMessage(actualDF, expectedDF))
  }
}
</code>```

Using df2.except(df1)

For details of these 2 ways, you can refer DataFrame equality in Apache Spark
Compare two Spark dataframes

Title: Spark - compare 2 dataframes without using hardcoded column names

Body:
I need to create a way to compare 2 data frames and do not use any hardcoded data, so that I can upload at any time 2 files and compare them without changing anything.

df1
+--------------------+--------+----------------+----------+
|                  ID|colA.   |colB.           |colC      |
+--------------------+--------+----------------+----------+
|(122C8984ABF9F6EF...|       0|              10|     APPLE|
|(122C8984ABF9F6EF...|       0|              20|     APPLE|
|(122C8984ABF9F6EF...|       0|              10|    GOOGLE|
|(122C8984ABF9F6EF...|       0|              10|     APPLE|
|(122C8984ABF9F6EF...|       0|              15|   SAMSUNG|
|(122C8984ABF9F6EF...|       0|              10|     APPLE|
+--------------------+--------+----------------+----------+

df2
+--------------------+--------+----------------+----------+
|                  ID|colA.   |colB            |colC      |
+--------------------+--------+----------------+----------+
|(122C8984ABF9F6EF...|       0|              10|     APPLE|
|(122C8984ABF9F6EF...|       0|              20|     APPLE|
|(122C8984ABF9F6EF...|       0|              10|     APPLE|
|(122C8984ABF9F6EF...|       0|              30|     APPLE|
|(122C8984ABF9F6EF...|       0|              15|   SAMSUNG|
|(122C8984ABF9F6EF...|       0|              15|    GOOGLE|
+--------------------+--------+----------------+----------+

I need to compare these 2 data frames and count the differences from each column.
My output should look like this:|

+--------------+-------------+-----------------+------------+------+
|Attribute Name|Total Records|Number Miss Match|% Miss Match|Status|
+--------------+-------------+-----------------+------------+------+
|      colA|            6|                0|       0.0 %|  Pass|
colB.       |           6|                3|        50 %|  Fail|
|    colC. |            6|                2|      33.3 %|  Fail||
+--------------+-------------+-----------------+------------+------+

I know how to compare the columns when using hardcoded column names , by my requirement is to compare it dynamically.
What I did so far was to select a column from each data frame, but this doesn't seem the right way to do it.

 val columnsAll = df1.columns.map(m=>col(m))
 val df1_col1 = df1.select(df1.columns.slice(1,2).map(m=>col(m)):_*).as("Col1")
 val df2_col1 = df2.select(df2.columns.slice(1,2).map(m=>col(m)):_*).as("Col2")

Body:
Two ways here:

The spark-fast-tests library has two methods for making DataFrame comparisons:

The assertSmallDataFrameEquality method collects DataFrames on the driver node and makes the comparison

def assertSmallDataFrameEquality(actualDF: DataFrame, expectedDF: DataFrame): Unit = {
  if (!actualDF.schema.equals(expectedDF.schema)) {
    throw new DataFrameSchemaMismatch(schemaMismatchMessage(actualDF, expectedDF))
  }
  if (!actualDF.collect().sameElements(expectedDF.collect())) {
    throw new DataFrameContentMismatch(contentMismatchMessage(actualDF, expectedDF))
  }
}

Using df2.except(df1)

For details of these 2 ways, you can refer DataFrame equality in Apache Spark
Compare two Spark dataframes


问:
How can I pass multiple arguments from one dataframe to modify values in another dataframe in R?
I want to use manual inputs to a QAQC 'log file' to update an existing dataframe. The following log file would indicate date ranges (bounded by datetime_min and datetime_max) for particular variable (or 'all' of them) observations to be omitted from the dateframe (set to NA).

```<code>library(tidyverse)
library(lubridate)

QC_log <- tibble(
  variable = c("SpCond", "pH", "pH", "all"),
  datetime_min = ymd_hms(c("2021-06-01 18:00:00","2021-07-19 18:00:00","2021-08-19 18:00:00","2021-11-23 18:00:00")),
  datetime_max = ymd_hms(c("2021-06-02 18:00:00","2021-07-25 21:00:00","2021-08-19 20:00:00","2021-11-26 05:00:00"))
)
</code>```

The log should modify the following example of a dataframe, removing observations for each variable (for now I am not worried about 'all') that fall between the date min/max.

```<code>df <- tibble(
  Datetime = ymd_hms(c("2021-06-01 17:00:00","2021-06-01 18:00:00","2021-06-01 19:00:00","2021-11-23 16:00:00","2021-11-23 17:00:00","2021-11-23 18:00:00")),
  SpCond = c(220,225,224,230,231,235),
  pH = c(7.8,7.9,8.0,7.7,7.8,7.7)
)
</code>```

I have tried pmap like this:

```<code> df%>%
{pmap(QC_log, mutate(., ..1 = ifelse(Datetime > ..2 & Datetime < ..3, "NA", ..1)))}
</code>```

I assumed pmap was taking ..1,2,3 from QC_log where ..1 is 'variable', ..2 is datetime_min, and ..3 is datetime_max, passing those as arguments into mutate one QC_log row at a time, which then conditionally replaces observations with NA if they fall into the specified date range.

I think I am having a hard time understanding ideas about non-standard evaluation/how arguments get passed through functions, among other things. Hopefully this is simple for now - I would like for this functionality to eventually be more complicated (e.g., changing all observations to NA when variable = 'all'; adding in separate actions like adding a data flag rather than omitting; or using a specific criterion (e.g., "<10") to omit observations rather than a daterange.

答:
You can do the following

```<code>inner_join(
  df %>% pivot_longer(cols=c("SpCond","pH")),
  QC_log,
  by=c("name" = "variable")
  ) %>%
  filter((Datetime<datetime_min) | (Datetime>datetime_max)) %>%
  select(Datetime, name, value) %>%
  distinct() %>%
  pivot_wider(id_cols = Datetime)
</code>```

Output

```<code>  Datetime            SpCond    pH
  <dttm>               <dbl> <dbl>
1 2021-06-01 17:00:00    220   7.8
2 2021-06-01 18:00:00     NA   7.9
3 2021-06-01 19:00:00     NA   8
4 2021-11-23 16:00:00    230   7.7
5 2021-11-23 17:00:00    231   7.8
6 2021-11-23 18:00:00    235   7.7
</code>```

And here is a data.table approach

```<code>dcast(
  unique(melt(setDT(df), id="Datetime")[setDT(QC_log),on=.(variable),allow.cartesian=T,nomatch=0] %>%
  .[(Datetime<datetime_min) | (Datetime>datetime_max), .(Datetime,variable,value)]),
  Datetime~variable, value.var="value"
)
</code>```

Body:
I want to use manual inputs to a QAQC 'log file' to update an existing dataframe. The following log file would indicate date ranges (bounded by datetime_min and datetime_max) for particular variable (or 'all' of them) observations to be omitted from the dateframe (set to NA).

library(tidyverse)
library(lubridate)

QC_log <- tibble(
  variable = c("SpCond", "pH", "pH", "all"),
  datetime_min = ymd_hms(c("2021-06-01 18:00:00","2021-07-19 18:00:00","2021-08-19 18:00:00","2021-11-23 18:00:00")),
  datetime_max = ymd_hms(c("2021-06-02 18:00:00","2021-07-25 21:00:00","2021-08-19 20:00:00","2021-11-26 05:00:00"))
)

The log should modify the following example of a dataframe, removing observations for each variable (for now I am not worried about 'all') that fall between the date min/max.

df <- tibble(
  Datetime = ymd_hms(c("2021-06-01 17:00:00","2021-06-01 18:00:00","2021-06-01 19:00:00","2021-11-23 16:00:00","2021-11-23 17:00:00","2021-11-23 18:00:00")),
  SpCond = c(220,225,224,230,231,235),
  pH = c(7.8,7.9,8.0,7.7,7.8,7.7)
)

I have tried pmap like this:

 df%>%
{pmap(QC_log, mutate(., ..1 = ifelse(Datetime > ..2 & Datetime < ..3, "NA", ..1)))}

I assumed pmap was taking ..1,2,3 from QC_log where ..1 is 'variable', ..2 is datetime_min, and ..3 is datetime_max, passing those as arguments into mutate one QC_log row at a time, which then conditionally replaces observations with NA if they fall into the specified date range.

I think I am having a hard time understanding ideas about non-standard evaluation/how arguments get passed through functions, among other things. Hopefully this is simple for now - I would like for this functionality to eventually be more complicated (e.g., changing all observations to NA when variable = 'all'; adding in separate actions like adding a data flag rather than omitting; or using a specific criterion (e.g., "<10") to omit observations rather than a daterange.

Body:
You can do the following

inner_join(
  df %>% pivot_longer(cols=c("SpCond","pH")),
  QC_log,
  by=c("name" = "variable")
  ) %>%
  filter((Datetime<datetime_min) | (Datetime>datetime_max)) %>%
  select(Datetime, name, value) %>%
  distinct() %>%
  pivot_wider(id_cols = Datetime)

Output

  Datetime            SpCond    pH
  <dttm>               <dbl> <dbl>
1 2021-06-01 17:00:00    220   7.8
2 2021-06-01 18:00:00     NA   7.9
3 2021-06-01 19:00:00     NA   8
4 2021-11-23 16:00:00    230   7.7
5 2021-11-23 17:00:00    231   7.8
6 2021-11-23 18:00:00    235   7.7

And here is a data.table approach

dcast(
  unique(melt(setDT(df), id="Datetime")[setDT(QC_log),on=.(variable),allow.cartesian=T,nomatch=0] %>%
  .[(Datetime<datetime_min) | (Datetime>datetime_max), .(Datetime,variable,value)]),
  Datetime~variable, value.var="value"
)


问:
Unregister-Event not removing orphaned event subscriptions
I'm using this to subscribe to shutdown events for a particular computer:

```<code>Register-WMIEvent -ComputerName MyServer1 -Query "SELECT * FROM Win32_ComputerShutdownEvent” -SourceIdentifier "ShutdownWatcher" -Action {
    Write-Host "MyServer1 has been shutdown"
}
</code>```

This works find and I receive the shutdown text when the computer is shut down.

The problem is that once the event has fired if I try to use the following to remove the event subscription nothing happens and the subscription remains.

```<code>Unregister-Event -SourceIdentifier "ShutdownWatcher"
</code>```

It's as though the event subscription is orphaned and now can't be removed. It's orphaned and completely useless as it doesn't fire when another shutdown is performed. I'd like to remove the subscription once it has fired.

Anyone know how to remove orphaned event subscriptions ? One way is to shutdown the Powershell session but I don't really want to do that.

答:
I had the same issue.

I was able unregister the event subscription by finding the the specific subscriber, and then unregistering it:

```<code>Get-EventSubscriber -SourceIdentifier "ShutdownWatcher" | Unregister-Event
</code>```

This is similar to Mathias' answer, however this method targets the specific event subscription.

Body:
I'm using this to subscribe to shutdown events for a particular computer:

Register-WMIEvent -ComputerName MyServer1 -Query "SELECT * FROM Win32_ComputerShutdownEvent” -SourceIdentifier "ShutdownWatcher" -Action {
    Write-Host "MyServer1 has been shutdown"
}

This works find and I receive the shutdown text when the computer is shut down.

The problem is that once the event has fired if I try to use the following to remove the event subscription nothing happens and the subscription remains.

Unregister-Event -SourceIdentifier "ShutdownWatcher"

It's as though the event subscription is orphaned and now can't be removed. It's orphaned and completely useless as it doesn't fire when another shutdown is performed. I'd like to remove the subscription once it has fired.

Anyone know how to remove orphaned event subscriptions ? One way is to shutdown the Powershell session but I don't really want to do that.

Body:
I had the same issue.

I was able unregister the event subscription by finding the the specific subscriber, and then unregistering it:

Get-EventSubscriber -SourceIdentifier "ShutdownWatcher" | Unregister-Event

This is similar to Mathias' answer, however this method targets the specific event subscription.


问:
Passing ManagedObject collection from fetch result to closure up to ViewController
I want to perform a background fetch and pass the result to closure. Currently I'm using performBackgroundTask method from NSPersistentContainer which is giving a NSManagedObjectContext as a closure. Then using that context I'm executing fetch request. When fetch is done I'm, passing the result to the completion handler.

```<code>func getAllWorkspacesAsync(completion: @escaping ([Workspace]) -> Void) {
    CoreDataStack.shared.databaseContainer.performBackgroundTask { childContext in
        let workspacesFetchRequest: NSFetchRequest<Workspace> = NSFetchRequest(entityName: "Workspace")
        workspacesFetchRequest.predicate = NSPredicate(format: "remoteId == %@", "\(UserDefaults.lastSelectedWorkspaceId))")
        do {
            let workspaces: [Workspace] = try childContext.fetch(workspacesFetchRequest)
            completion(workspaces)
        } catch let error as NSError {
            // Handle error
        }
    }
}
</code>```

I'm going to call this method from ViewModel and use Combine PassthroughSubject to notify the ViewController about the event.

```<code>class WorkspaceViewModel {

    private var cancellables: Set<AnyCancellable> = []
    let resultPassthroughObject: PassthroughSubject<[Workspace], Error> = PassthroughSubject()

    private let cacheManager = WorkspaceCacheProvider.shared

    static public let shared: WorkspaceViewModel = {
        let instance = WorkspaceViewModel()
        return instance
    }()

    func fetchWorkspaces() {
        cacheManager.getAllWorkspacesAsync { [weak self] workspaces in
            guard let self = self else { return }
            self.resultPassthroughObject.send(workspaces)
        }
    }
}
</code>```

And the ViewController code:

```<code>class WorkspaceViewController: UIViewController {

    private var cancellables: Set<AnyCancellable> = []

    override func viewDidLoad() {
        super.viewDidLoad()

        WorkspaceViewModel.shared.resultPassthroughObject
            .receive(on: RunLoop.main)
            .sink { _ in } receiveValue: { workspaces in
            // update the UI
        }
        .store(in: &cancellables)

    }
}
</code>```

My question is: is it safe to pass NSManagedObject items?

答:
No, it is not

Do not pass NSManagedObject instances between queues. Doing so can result in corruption of the data and termination of the app. When it is necessary to hand off a managed object reference from one queue to another, use NSManagedObjectID instances.

You would want something like:

```<code>func getAllWorkspacesAsync(completion: @escaping ([NSManagedObjectID]) -> Void) {
    CoreDataStack.shared.databaseContainer.performBackgroundTask { childContext in
        let workspacesFetchRequest: NSFetchRequest<Workspace> = NSFetchRequest(entityName: "Workspace")
        workspacesFetchRequest.predicate = NSPredicate(format: "remoteId == %@", "\(UserDefaults.lastSelectedWorkspaceId))")
        do {
            let workspaces: [Workspace] = try childContext.fetch(workspacesFetchRequest)
            completion(workspaces.map { $0.objectID } )
        } catch let error as NSError {
            // Handle error
        }
    }
}
</code>```

You will need to make corresponding changes to your publisher so that it publishes [NSManagedObjectID].

Once you have received this array in your view controller you will need to call object(with:) on your view context to get the Workspace itself.  This will perform a fetch in the view context for the object anyway.

You may want to consider whether the time taken to fetch your workspaces warrants the use of a background context.  By default Core Data objects are retrieved as faults and the actual attribute values are only fetched when the fault is triggered by accessing an object's attributes.

Alternatively, if the purpose of the view controller is to present a list of workspaces that the user can select from, you could return an array of tuples or structs containing the workspace name and the object id.   However, this all sounds like pre-optimisation to me.

Body:
I want to perform a background fetch and pass the result to closure. Currently I'm using performBackgroundTask method from NSPersistentContainer which is giving a NSManagedObjectContext as a closure. Then using that context I'm executing fetch request. When fetch is done I'm, passing the result to the completion handler.

func getAllWorkspacesAsync(completion: @escaping ([Workspace]) -> Void) {
    CoreDataStack.shared.databaseContainer.performBackgroundTask { childContext in
        let workspacesFetchRequest: NSFetchRequest<Workspace> = NSFetchRequest(entityName: "Workspace")
        workspacesFetchRequest.predicate = NSPredicate(format: "remoteId == %@", "\(UserDefaults.lastSelectedWorkspaceId))")
        do {
            let workspaces: [Workspace] = try childContext.fetch(workspacesFetchRequest)
            completion(workspaces)
        } catch let error as NSError {
            // Handle error
        }
    }
}

I'm going to call this method from ViewModel and use Combine PassthroughSubject to notify the ViewController about the event.

class WorkspaceViewModel {

    private var cancellables: Set<AnyCancellable> = []
    let resultPassthroughObject: PassthroughSubject<[Workspace], Error> = PassthroughSubject()

    private let cacheManager = WorkspaceCacheProvider.shared

    static public let shared: WorkspaceViewModel = {
        let instance = WorkspaceViewModel()
        return instance
    }()

    func fetchWorkspaces() {
        cacheManager.getAllWorkspacesAsync { [weak self] workspaces in
            guard let self = self else { return }
            self.resultPassthroughObject.send(workspaces)
        }
    }
}

And the ViewController code:

class WorkspaceViewController: UIViewController {

    private var cancellables: Set<AnyCancellable> = []

    override func viewDidLoad() {
        super.viewDidLoad()

        WorkspaceViewModel.shared.resultPassthroughObject
            .receive(on: RunLoop.main)
            .sink { _ in } receiveValue: { workspaces in
            // update the UI
        }
        .store(in: &cancellables)

    }
}

My question is: is it safe to pass NSManagedObject items?

Body:
No, it is not

Do not pass NSManagedObject instances between queues. Doing so can result in corruption of the data and termination of the app. When it is necessary to hand off a managed object reference from one queue to another, use NSManagedObjectID instances.

You would want something like:

func getAllWorkspacesAsync(completion: @escaping ([NSManagedObjectID]) -> Void) {
    CoreDataStack.shared.databaseContainer.performBackgroundTask { childContext in
        let workspacesFetchRequest: NSFetchRequest<Workspace> = NSFetchRequest(entityName: "Workspace")
        workspacesFetchRequest.predicate = NSPredicate(format: "remoteId == %@", "\(UserDefaults.lastSelectedWorkspaceId))")
        do {
            let workspaces: [Workspace] = try childContext.fetch(workspacesFetchRequest)
            completion(workspaces.map { $0.objectID } )
        } catch let error as NSError {
            // Handle error
        }
    }
}

You will need to make corresponding changes to your publisher so that it publishes [NSManagedObjectID].

Once you have received this array in your view controller you will need to call object(with:) on your view context to get the Workspace itself.  This will perform a fetch in the view context for the object anyway.

You may want to consider whether the time taken to fetch your workspaces warrants the use of a background context.  By default Core Data objects are retrieved as faults and the actual attribute values are only fetched when the fault is triggered by accessing an object's attributes.

Alternatively, if the purpose of the view controller is to present a list of workspaces that the user can select from, you could return an array of tuples or structs containing the workspace name and the object id.   However, this all sounds like pre-optimisation to me.


问:
Returning partial view with a boolean value
I have an action method which returns a partial view to an ajax call. Whenever the partial view is received in success block of the ajax call, I am rendering it like this;

```<code> success: function (res) {
                $('#competitorTables').html(res);
            }
</code>```

But the action method has a condition within itself and it can result either true or false. I want to be able to return this boolean value with my return PartialView()block and then I want to be able to process it in my ajax call like this;

```<code> success: function (res, isConditionSatisfied) {
                if(isConditionSatisfied){
                   $('#competitorTables').html(res);
                   alert('Condition satisfied');
                }else{
                   $('#competitorTables').html(res);
                   alert('Condition did not satisfied');
                }
            }
</code>```

Is there a way that I can manage it? Thanks in advance.

Addition: Here is how I return from my action method;

```<code>return PartialView("_CompetitorTables", model);
</code>```

答:
I needed to do a similar thing; make an ajax call and render a partial view as well as return a decimal value to be used for another purpose.

Here's how approached the problem.

I added the value I needed to the partial view model

I created a hidden input somewhere in the partial view to hold this value

Then I made my ajax call and on success, I render the partial view and also used jQuery to fetch the value of that hidden field and voila!

Body:
I have an action method which returns a partial view to an ajax call. Whenever the partial view is received in success block of the ajax call, I am rendering it like this;

 success: function (res) {
                $('#competitorTables').html(res);
            }

But the action method has a condition within itself and it can result either true or false. I want to be able to return this boolean value with my return PartialView()block and then I want to be able to process it in my ajax call like this;

 success: function (res, isConditionSatisfied) {
                if(isConditionSatisfied){
                   $('#competitorTables').html(res);
                   alert('Condition satisfied');
                }else{
                   $('#competitorTables').html(res);
                   alert('Condition did not satisfied');
                }
            }

Is there a way that I can manage it? Thanks in advance.

Addition: Here is how I return from my action method;

return PartialView("_CompetitorTables", model);


问:
Question about #define statement in Objective-C project
I'm not experienced in C, so I'm not comfortable with this statement in this C / objective-C project.

```<code>#define CBLog(...) NSLog(@"%s [%ld]: %@", basename(__FILE__), __LINE__, [NSString stringWithFormat:__VA_ARGS__])
</code>```

Questions:

the 3 dots (...) are used to indicate CBLog() is a method with parameters ? What do they mean ?

%ld stands for line format ? what's the d in %ld for ?

FILE , LINE and VA_ARGS are default replacement tokens for the C debugger ?

thanks

答:
... means that any number of arguments can be given.

%ld means signed long, though it's a bit strange as I've never seen signed line numbers.

__FILE__ is the current source file's filename. __LINE__ is the current line number. __VA_ARGS__ are the arguments given to the macro.

Body:
I'm not experienced in C, so I'm not comfortable with this statement in this C / objective-C project.

#define CBLog(...) NSLog(@"%s [%ld]: %@", basename(__FILE__), __LINE__, [NSString stringWithFormat:__VA_ARGS__])

Questions:

the 3 dots (...) are used to indicate CBLog() is a method with parameters ? What do they mean ?

%ld stands for line format ? what's the d in %ld for ?

FILE , LINE and VA_ARGS are default replacement tokens for the C debugger ?

thanks


问:
Structuring Sidebar in React
Relatively new to React, and am wanting to recreate the design below

enter image description here

I have the base formatting down, but as you will notice, there are lines separating the logo blocks, from the login and signup blocks, with the signup and login buttons pushed to the bottom.

Below is my current code

CSS:

```<code>    width: 100vw;
    height: 100vh;
  }

  body {
    margin: 0;
    padding: 0;

  }

.Sidebar {
    height: 100%;
    width: 20%;
    background-color: white;
    border-right: 1px solid #F0F4FB;
    padding-left: 15px;
    box-sizing: border-box;

  }

  .SidebarList {
    height: auto;
    width: 100%;
    padding-left: 15px;
    font-size: 18px;
    border: 2px #FD954E;
    box-sizing: border-box

  }

  .SidebarList .row {
      width: 100%;
      height: 50px;
      background-color: white;
      list-style-type: none;
      margin: 0%;
      padding-bottom: 15px;
      display: flex;
      color: #A7ACB6;
      justify-content: center;
      align-items: center;
      font-family: Arial, Helvetica, sans-serif;

  }

.SidebarList .row:hover {
  cursor: pointer;
  background-color: #E7E7E7  ;
}

.SidebarList #active {
  background-color: white;
  color: #FD954E
}

.SidebarList .Login {
background-color: white;
color: #FD954E;
width: 279px;
height: 39px;
right: 1596px;
top: 958px;
border: 1px solid #FD954E;
box-sizing: border-box;
border-radius: 19.5px;
}

.SidebarList .SignUp {

  width: 279px;
  height: 39px;
  right: 1596px;
  top: 1011px;

  background: #FD954E;
  border-radius: 19.5px;
  border: none;
  }

  .row #icon {
    flex: 30%;
    display: grid;
    place-items: center;
    transform: scale(1.2)

  }

  .row #title {
    flex: 70%;
  }

.Logo {
  padding-left: 25px;
  padding-top: 25px;
  padding-bottom: 30px;
  border-bottom: 1px solid #F0F4FB;
  width: 55%;

}
</code>```

Sidebar.js

```<code>import React from "react";
import "../App.css";
import { SidebarData } from './SidebarData'
import Logo from './Logo.svg'

function Sidebar() {
    return (
    <div className="Sidebar">
        <div>
        <img src = {Logo} alt='Logo’ className=‘Logo’ />

        </div>
           <ul className="SidebarList">
               {SidebarData.map((val, key) => {
                 return (
                  <li
                    key={key}
                    className="row"
                    id={window.location.pathname == val.link ? "active" : ""}
                    onClick={() => {
                        window.location.pathname = val.link;
                        }}
                    >
                      <div id="icon">{val.icon}</div> <div id="title">{val.title}</div>
                      </li>
               );
               })}

            </ul>
<div className= "SidebarList">
            <button className="Login">
                Login
            </button>
            </div>
            <div className= "SidebarList">
            <button className="SignUp">
                Sign Up
            </button>
    </div>
    </div>
    );
}

export default Sidebar;
</code>```

How should I structure my code in order to acheive my desired result? Ex: with the logo at the top with the seperator, the list of navigation elements, and then the login and signup buttons at the bottom with the seperator?

Currently, my sidebar looks as follows, with the seperator not full width between the logo and navigation elements, and the buttons extending beyond the sidebar.

enter image description here

答:
It would be easier to simplify the problem with just HTML and CSS as that's much easier to troubleshoot. Part of your problem is that you are defining the width of the sidebar as a percentage of the screen width but elements within the sidebar are defined with a width in pixels. When the browser window is too small, your buttons will appear outside the full width of the sidebar. You could either code all your values as percentages or in pixels. Alternatively, you could use a mix and just set a min-width for the sidebar so that you don't end up with elements out of place.

The reason that your line break is not the full width of your sidebar is because you are defining it with the border-bottom property of the logo. Your logo is not 100% the width of the sidebar so your line break will only be the width of the logo. A better solution would be to define a div that is set to width: 100%. This way, you will have more control.

Here is a simplified solution to your sidebar problem using pixels to define the widths.

HTML:

```<code><div class="sidebar">
  <div class="header">
    <div class="logo">Logo</div>
  </div>
  <div class="line-break" />
  <div class="content">
    <ul class="nav">
      <li>Home</li>
      <li>Blog</li>
    </ul>
  </div>
  <div class="line-break" />
  <div class="footer">
    <button class="login">Login</button>
    <button class="sign-up">Sign up</button>
  </div>
</div>
</code>```

CSS:

```<code>html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.sidebar {
  width: 300px;
  height: 100%;
  border-right: 1px solid grey;
}

.line-break {
  height: 1px;
  width: 100%;
  background-color: grey;
}

.header .logo {
  height: 40px;
  width: 200px;
  background-color: grey;
  margin: 20px;
}

ul.nav {
  list-style-type: none;
  padding: 20px 0 0 40px;
}

ul.nav li {
  margin-bottom: 14px;
}

ul.nav li:last-child {
  margin-bottom: 0;
}

.footer {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.footer button {
  padding: 6px 0;
  width: 80%;
  margin-bottom: 14px;
}

.footer button:last-child {
  margin-bottom: 0;
}
</code>```

And here is a link to a CodePen
where you can see this in action.

Title: Structuring Sidebar in React

Body:
Relatively new to React, and am wanting to recreate the design below

enter image description here

I have the base formatting down, but as you will notice, there are lines separating the logo blocks, from the login and signup blocks, with the signup and login buttons pushed to the bottom.

Below is my current code

CSS:

    width: 100vw;
    height: 100vh;
  }

  body {
    margin: 0;
    padding: 0;

  }

.Sidebar {
    height: 100%;
    width: 20%;
    background-color: white;
    border-right: 1px solid #F0F4FB;
    padding-left: 15px;
    box-sizing: border-box;

  }

  .SidebarList {
    height: auto;
    width: 100%;
    padding-left: 15px;
    font-size: 18px;
    border: 2px #FD954E;
    box-sizing: border-box

  }

  .SidebarList .row {
      width: 100%;
      height: 50px;
      background-color: white;
      list-style-type: none;
      margin: 0%;
      padding-bottom: 15px;
      display: flex;
      color: #A7ACB6;
      justify-content: center;
      align-items: center;
      font-family: Arial, Helvetica, sans-serif;

  }

.SidebarList .row:hover {
  cursor: pointer;
  background-color: #E7E7E7  ;
}

.SidebarList #active {
  background-color: white;
  color: #FD954E
}

.SidebarList .Login {
background-color: white;
color: #FD954E;
width: 279px;
height: 39px;
right: 1596px;
top: 958px;
border: 1px solid #FD954E;
box-sizing: border-box;
border-radius: 19.5px;
}

.SidebarList .SignUp {

  width: 279px;
  height: 39px;
  right: 1596px;
  top: 1011px;

  background: #FD954E;
  border-radius: 19.5px;
  border: none;
  }

  .row #icon {
    flex: 30%;
    display: grid;
    place-items: center;
    transform: scale(1.2)

  }

  .row #title {
    flex: 70%;
  }

.Logo {
  padding-left: 25px;
  padding-top: 25px;
  padding-bottom: 30px;
  border-bottom: 1px solid #F0F4FB;
  width: 55%;

}

Sidebar.js

import React from "react";
import "../App.css";
import { SidebarData } from './SidebarData'
import Logo from './Logo.svg'

function Sidebar() {
    return (

               {SidebarData.map((val, key) => {
                 return (

 {
                        window.location.pathname = val.link;
                        }}
                    >

{val.icon}

{val.title}

               );
               })}

            <button className="Login">
                Login
            </button>

            <button className="SignUp">
                Sign Up
            </button>

    );
}

export default Sidebar;

How should I structure my code in order to acheive my desired result? Ex: with the logo at the top with the seperator, the list of navigation elements, and then the login and signup buttons at the bottom with the seperator?

Currently, my sidebar looks as follows, with the seperator not full width between the logo and navigation elements, and the buttons extending beyond the sidebar.

enter image description here

Body:
It would be easier to simplify the problem with just HTML and CSS as that's much easier to troubleshoot. Part of your problem is that you are defining the width of the sidebar as a percentage of the screen width but elements within the sidebar are defined with a width in pixels. When the browser window is too small, your buttons will appear outside the full width of the sidebar. You could either code all your values as percentages or in pixels. Alternatively, you could use a mix and just set a min-width for the sidebar so that you don't end up with elements out of place.

The reason that your line break is not the full width of your sidebar is because you are defining it with the border-bottom property of the logo. Your logo is not 100% the width of the sidebar so your line break will only be the width of the logo. A better solution would be to define a div that is set to width: 100%. This way, you will have more control.

Here is a simplified solution to your sidebar problem using pixels to define the widths.

HTML:

<div class="sidebar">
  <div class="header">
    <div class="logo">Logo</div>
  </div>
  <div class="line-break" />
  <div class="content">
    <ul class="nav">
      <li>Home</li>
      <li>Blog</li>
    </ul>
  </div>
  <div class="line-break" />
  <div class="footer">
    <button class="login">Login</button>
    <button class="sign-up">Sign up</button>
  </div>
</div>

CSS:

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.sidebar {
  width: 300px;
  height: 100%;
  border-right: 1px solid grey;
}

.line-break {
  height: 1px;
  width: 100%;
  background-color: grey;
}

.header .logo {
  height: 40px;
  width: 200px;
  background-color: grey;
  margin: 20px;
}

ul.nav {
  list-style-type: none;
  padding: 20px 0 0 40px;
}

ul.nav li {
  margin-bottom: 14px;
}

ul.nav li:last-child {
  margin-bottom: 0;
}

.footer {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.footer button {
  padding: 6px 0;
  width: 80%;
  margin-bottom: 14px;
}

.footer button:last-child {
  margin-bottom: 0;
}

And here is a link to a CodePen
where you can see this in action.


问:
"Argument of type 'string' is not assignable to parameter of type never" in the parameter of the function call to get a value from an object key
I need to render a list of products from the data stored in an object with a react router v6. I typed the object and created the typed function to get the value of a key following what is taught in this github answer. This eliminated the previous error of Argument of type 'string' is not assignable to parameter of type 'never' ts(2345), but a new error appeared: Argument of type 'string' is not assignable to parameter of type ' never' ts(2345), which is pointed to the slug parameter of the getKeyValue call in the constant in the line const shoe = getKeyValue(slug)(shoes);.

```<code>const shoes: { [key: string]: { name: string; img: string } } = {
  'air-jordan-3-valor-blue': {
    name: 'VALOUR BLUE',
    img: 'https://secure-images.nike.com/is/image/DotCom/CT8532_104_A_PREM?$SNKRS_COVER_WD$&align=0,1',
  },
  'jordan-mars-270-london': {
    name: 'JORDAN MARS 270 LONDON',
    img: 'https://secure-images.nike.com/is/image/DotCom/CV3042_001_A_PREM?$SNKRS_COVER_WD$&align=0,1',
  },
  'air-jordan-1-zoom-racer-blue': {
    name: 'RACER BLUE',
    img: 'https://secure-images.nike.com/is/image/DotCom/CK6637_104_A_PREM?$SNKRS_COVER_WD$&align=0,1',
  },
};

const getKeyValue =
  <T extends object, U extends keyof T>(key: U) =>
  (obj: T): T[U] =>
    obj[key];

function LaunchIndex() {
  return (
    <ul>
      {Object.entries(shoes).map(([slug, { name, img }]) => (
        <li key={slug}>
          <Link to={`/launch/products/${slug}`}>
            <h2>{name}</h2>
            <img src={img} alt={name} />
          </Link>
        </li>
      ))}
    </ul>
  );
}

function LaunchShoe() {
  const { slug } = useParams();
  const shoe = getKeyValue(slug)(shoes); // error here

  if (!shoe) {
    return <h2>Not found!</h2>;
  }

  const { name, img } = shoe;

  return (
    <div>
      <h2>{name}</h2>
      <img src={img} alt={name} />
    </div>
  );
}
</code>```

To resolve this error I followed what is in this github answer, I changed the line to const shoe = getKeyValue(slug as never)(shoes);. So it worked, the application worked as expected, but I can't understand what's happening...

答:
Your implementation of getKeyValue is different from the Github post you linked. Here's the linked version:

const getKeyValue = <T extends object, U extends keyof T>(obj: T) => (key: U) =>
  obj[key];
```
<p>and here's your version:</p>
<pre class="lang-js prettyprint-override"><code>const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T): T[U] =>
  obj[key];
</code>```

The problem is that you reversed the arguments. When you pass in the key parameter first, Typescript checks the constraint U extends keyof T and has no idea what to do because it has no idea what T is... the object hasn't been passed in yet! The result is the error message you saw.

If you reverse the arguments to match the implementation from the Github post, your code should work correctly.

Body:
I need to render a list of products from the data stored in an object with a react router v6. I typed the object and created the typed function to get the value of a key following what is taught in this github answer. This eliminated the previous error of Argument of type 'string' is not assignable to parameter of type 'never' ts(2345), but a new error appeared: Argument of type 'string' is not assignable to parameter of type ' never' ts(2345), which is pointed to the slug parameter of the getKeyValue call in the constant in the line const shoe = getKeyValue(slug)(shoes);.

const shoes: { [key: string]: { name: string; img: string } } = {
  'air-jordan-3-valor-blue': {
    name: 'VALOUR BLUE',
    img: 'https://secure-images.nike.com/is/image/DotCom/CT8532_104_A_PREM?$SNKRS_COVER_WD$&align=0,1',
  },
  'jordan-mars-270-london': {
    name: 'JORDAN MARS 270 LONDON',
    img: 'https://secure-images.nike.com/is/image/DotCom/CV3042_001_A_PREM?$SNKRS_COVER_WD$&align=0,1',
  },
  'air-jordan-1-zoom-racer-blue': {
    name: 'RACER BLUE',
    img: 'https://secure-images.nike.com/is/image/DotCom/CK6637_104_A_PREM?$SNKRS_COVER_WD$&align=0,1',
  },
};

const getKeyValue =
  <T extends object, U extends keyof T>(key: U) =>
  (obj: T): T[U] =>
    obj[key];

function LaunchIndex() {
  return (

      {Object.entries(shoes).map(([slug, { name, img }]) => (

          <Link to={`/launch/products/${slug}`}>

{name}

          </Link>

      ))}

  );
}

function LaunchShoe() {
  const { slug } = useParams();
  const shoe = getKeyValue(slug)(shoes); // error here

  if (!shoe) {
    return
Not found!
;
  }

  const { name, img } = shoe;

  return (

{name}

  );
}

To resolve this error I followed what is in this github answer, I changed the line to const shoe = getKeyValue(slug as never)(shoes);. So it worked, the application worked as expected, but I can't understand what's happening...

Body:
Your implementation of getKeyValue is different from the Github post you linked. Here's the linked version:

const getKeyValue = <T extends object, U extends keyof T>(obj: T) => (key: U) =>
  obj[key];

and here's your version:

const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T): T[U] =>
  obj[key];

The problem is that you reversed the arguments. When you pass in the key parameter first, Typescript checks the constraint U extends keyof T and has no idea what to do because it has no idea what T is... the object hasn't been passed in yet! The result is the error message you saw.

If you reverse the arguments to match the implementation from the Github post, your code should work correctly.


问:
How do I skip or ignore not defined errors in javascript Line
I have javascript/Jquery files like this that is suppose to store javascript and Jquery functions for my entire website.

Issue: All the functions ID are not present in all the pages, so the script doesn't work and it stops at the line where it can't find ID reference and throw this error "Cannot set properties of null (setting 'innerHTML')"

This is an example that represents what the script flow

```<code>  //Code for page 1
  var page1redirect = document.getElementById("page1redirectafter").value;
  document.getElementById("page1redirectID").value = page1redirect;

  //Code for page 2
  var page2redirect = document.getElementById("page2redirectafter").value;
  document.getElementById("page2redirectID").value = page2redirect;

  //Code for page 3
  var page3redirect = document.getElementById("page3redirectafter").value;
  document.getElementById("page3redirectID").value = page3redirect;
</code>```

Is there any way I can skip or ignore any error that doesn't run and continue the next function?

答:
If the ids are correct and included in the HTML, those objects are probably null since by the time the script runs the DOM has still not been fully loaded. So you might want to delay the script, try more than once or ask the browser to inform you of any changes made to the DOM.

If you just want to ignore it when an object is null and do nothing, just check if it's null:

Instead of e.g.

```<code>var page3redirect = document.getElementById("page3redirectafter").value;
document.getElementById("page3redirectID").value = page3redirect;
</code>```

Do

```<code>var page3redirect = document.getElementById("page3redirectafter");
if (page3redirect != null) {
    var page3redirectID = document.getElementById("page3redirectID");
    if (page3redirectID != null) {
        page3redirectID.value = page3redirect.value;
    };
};
</code>```

Body:
I have javascript/Jquery files like this that is suppose to store javascript and Jquery functions for my entire website.

Issue: All the functions ID are not present in all the pages, so the script doesn't work and it stops at the line where it can't find ID reference and throw this error "Cannot set properties of null (setting 'innerHTML')"

This is an example that represents what the script flow

  //Code for page 1
  var page1redirect = document.getElementById("page1redirectafter").value;
  document.getElementById("page1redirectID").value = page1redirect;

  //Code for page 2
  var page2redirect = document.getElementById("page2redirectafter").value;
  document.getElementById("page2redirectID").value = page2redirect;

  //Code for page 3
  var page3redirect = document.getElementById("page3redirectafter").value;
  document.getElementById("page3redirectID").value = page3redirect;

Is there any way I can skip or ignore any error that doesn't run and continue the next function?

Body:
If the ids are correct and included in the HTML, those objects are probably null since by the time the script runs the DOM has still not been fully loaded. So you might want to delay the script, try more than once or ask the browser to inform you of any changes made to the DOM.

If you just want to ignore it when an object is null and do nothing, just check if it's null:

Instead of e.g.

var page3redirect = document.getElementById("page3redirectafter").value;
document.getElementById("page3redirectID").value = page3redirect;

Do

var page3redirect = document.getElementById("page3redirectafter");
if (page3redirect != null) {
    var page3redirectID = document.getElementById("page3redirectID");
    if (page3redirectID != null) {
        page3redirectID.value = page3redirect.value;
    };
};


问:
How can I stop isNaN from returning an error for a blank field?
EDIT:

Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,

When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?

I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!

答:
How about use short-circuit evaluation with jsFiddle example

EDIT for parseFloat:

```<code>function checkNumber()
{
    var sInput = parseFloat(document.getElementById('sInput').value || 0);
    var dInput = parseFloat(document.getElementById('dInput').value || 0);
    var pInput = parseFloat(document.getElementById('pInput').value || 0);
    if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
        alert("You entered an invalid character. Please press 'Reset' and enter a number.");
    }
}
</code>```

So if pInput is undefined just use 0, but if the input has value then use that value.

SIDE NOTE: white space is actually a number, +'            '; // 0

Body:
How about use short-circuit evaluation with jsFiddle example

EDIT for parseFloat:

function checkNumber()
{
    var sInput = parseFloat(document.getElementById('sInput').value || 0);
    var dInput = parseFloat(document.getElementById('dInput').value || 0);
    var pInput = parseFloat(document.getElementById('pInput').value || 0);
    if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
        alert("You entered an invalid character. Please press 'Reset' and enter a number.");
    }
}

So if pInput is undefined just use 0, but if the input has value then use that value.

SIDE NOTE: white space is actually a number, +'            '; // 0


问:
Filter date as character
Im trying to filter a new frame by the date. But my dtf shows the "date" variable as character. This is what I have when run str function:

str(banco_4$dt_inic_tr)

Console shows: **chr [1:505057] "07 May 15" "26 May 15" "05 Sep 16" "21 Aug 15" "29 Apr 16"** ...

What I want to do is : filter the variable dt_inic_tr between "01 Jan 15" to "31 Dec 20".

```<code>banco_5 <-banco_4%>%
filter((as.character(dt_inic_tr)>=as.character("01 Jan 15"))&
            (as.character(dt_inic_tr)<=as.character("31 Dec 20")))
</code>```

答:
Maybe it might be easier to transform the dates, e.g.

```<code>as.Date("01 Jan 15",format="%d %B %y")
</code>```

This yields

```<code>"2015-01-01"
</code>```

which makes the filtering a bit easier.

Title: Filter date as character

Body:
Im trying to filter a new frame by the date. But my dtf shows the "date" variable as character. This is what I have when run str function:

str(banco_4$dt_inic_tr)

Console shows: **chr [1:505057] "07 May 15" "26 May 15" "05 Sep 16" "21 Aug 15" "29 Apr 16"** ...

What I want to do is : filter the variable dt_inic_tr between "01 Jan 15" to "31 Dec 20".

banco_5 <-banco_4%>%
filter((as.character(dt_inic_tr)>=as.character("01 Jan 15"))&
            (as.character(dt_inic_tr)<=as.character("31 Dec 20")))

Body:
Maybe it might be easier to transform the dates, e.g.

as.Date("01 Jan 15",format="%d %B %y")

This yields

"2015-01-01"

which makes the filtering a bit easier.


问:
Python: whats does comma mean in in [ : ,1 ]
guys I am new to python and learning machine learning.I have trouble understanding what does this line of code mean:-

```<code>y_scores_knn = y_probas_knn[:,1]
</code>```

I didnt get what  ,1 mean inside an array box [] and what it does

答: That is how you access the column with index 1. This functionality is only if y_scores_knn is part of certain classes that deal with 2-d arrays. One class I'm most familiar with is a numpy array, which allows the accessing of columns, along with many other helpful methods.</p>

Body:
guys I am new to python and learning machine learning.I have trouble understanding what does this line of code mean:-

y_scores_knn = y_probas_knn[:,1]

I didnt get what  ,1 mean inside an array box [] and what it does


问:
How to implement a "GetTypeByPath" type in TypeScript?
My requirement is that the type alias can be passed in two parameters, the first one is the object type, the second one is a dot expression that indicates the path of the field.

For example:

```<code>type Obj = {
  a: {
    b: string[]
  }
  c: number[]
}

GetTypeByPath<Obj, 'a.b'>  // => string[]
GetTypeByPath<Obj, 'c.5'>  // => number
</code>```

So how the GetTypeByPath type would be look like?

答:
I've answered this sort of "deep indexing" question before, but it seems like there are always slightly different use cases.  The basic approach is to use template literal types to split the path string at dot characters "." and use a recursive conditional type to walk down through the nested properties.  I'll refer to your GetTypeByPath<T, K> as DeepIndex<T, K> to be consistent with prior instances of this question.

Anyway, the implementation looks something like:

```<code>type DeepIndex<T, K extends string> = T extends object ? (
  K extends `${infer F}.${infer R}` ? DeepIndex<Idx<T, F>, R> : Idx<T, K>
) : never;
</code>```

where Idx<T, K> represents the "shallow" indexed access operation normally written as just T[K].  We'll come to how to implement Idx<T, K> (and why we don't just write T[K]) in a bit.

For now, let's just convince ourselves that DeepIndex<T, K> does what we expect.  First, we won't try indexing into primitives, so the whole thing is wrapped in T extends object ? ( ... ) : never.  We could index into primitives, but then we'd be supporting things like DeepIndex<Obj, 'a.b.5.length.toPrecision'> evaluating to (precision?: number | undefined) => string.  If you remove that wrapper then that's what you'd get.

The heart of the type is just: try to split the path at the first dot into the first part of the string F and the rest of the string R.  If you can do that, then you want to DeepIndex into the T[F] property at the path R.  If you can't, then there are no more dots and we'll just treat the path K as a single key and return T[K].

So how do we implement Idx<T, K>?  One fairly universal complication is that there's no simple way to express to the compiler that the path fragment at K will definitely be one of the keys of T. So one thing we'd need to do is check for that.  We can try it as:

```<code>type Idx<T, K extends string> = K extends keyof T ? T[K] : never;
</code>```

And this kind of works:

```<code>type X = DeepIndex<Obj, 'a.b'>  // string[]
</code>```

Until it doesn't:

```<code>type Y = DeepIndex<Obj, 'c.5'>  // never
</code>```

And this is the place where your use case differs from others I've seen.  You are indexing into a number[] with the string value "5".  But the Array<T> type definition has a number index signature, and "5" is not a number.  It's a "numeric string", so you should be able to index into an array with it (since object keys in JavaScript are actually strings and not really numbers), but the compiler doesn't see "5" extends keyof (number[]) as being true.

So we need to account for such numeric string keys.  Let's try this:

```<code>type Idx<T, K extends string> =
  K extends keyof T ? T[K] :
  K extends `${number}` ? number extends keyof T ? T[number] : never : never;
</code>```

Here we're saying that if K is a string version of a number (the "pattern template literal" `${number}` syntax was introduced in microsoft/TypeScript#40598), and if the type T has a numeric index signature, then we should index into T with number instead of K.   Let's test it out again:

```<code>type X = DeepIndex<Obj, 'a.b'>  // string[]
type Y = DeepIndex<Obj, 'c.5'>  // number
</code>```

Looks good!

Of course there are tons of edge cases.  For those come come later, even if this meets the needs of the original person asking the question, there's no guarantee it will do what you expect... so you should really test against all your use cases.

For example: it's quite hard to check if K is a valid path before you do the indexing.  Instead of a compiler warning if you write DeepIndex<Obj, "something.that.is.definitely.not.a.path">, you'll just get the never type out, which may or may not be acceptable:

```<code>type Z = DeepIndex<Obj, 'oopsieDaisy'> // never
</code>```

So test carefully!

Playground link to code

Body:
My requirement is that the type alias can be passed in two parameters, the first one is the object type, the second one is a dot expression that indicates the path of the field.

For example:

type Obj = {
  a: {
    b: string[]
  }
  c: number[]
}

GetTypeByPath<Obj, 'a.b'>  // => string[]
GetTypeByPath<Obj, 'c.5'>  // => number

So how the GetTypeByPath type would be look like?

Body:
I've answered this sort of "deep indexing" question before, but it seems like there are always slightly different use cases.  The basic approach is to use template literal types to split the path string at dot characters "." and use a recursive conditional type to walk down through the nested properties.  I'll refer to your GetTypeByPath<T, K> as DeepIndex<T, K> to be consistent with prior instances of this question.

Anyway, the implementation looks something like:

type DeepIndex<T, K extends string> = T extends object ? (
  K extends `${infer F}.${infer R}` ? DeepIndex<Idx<T, F>, R> : Idx<T, K>
) : never;

where Idx<T, K> represents the "shallow" indexed access operation normally written as just T[K].  We'll come to how to implement Idx<T, K> (and why we don't just write T[K]) in a bit.

For now, let's just convince ourselves that DeepIndex<T, K> does what we expect.  First, we won't try indexing into primitives, so the whole thing is wrapped in T extends object ? ( ... ) : never.  We could index into primitives, but then we'd be supporting things like DeepIndex<Obj, 'a.b.5.length.toPrecision'> evaluating to (precision?: number | undefined) => string.  If you remove that wrapper then that's what you'd get.

The heart of the type is just: try to split the path at the first dot into the first part of the string F and the rest of the string R.  If you can do that, then you want to DeepIndex into the T[F] property at the path R.  If you can't, then there are no more dots and we'll just treat the path K as a single key and return T[K].

So how do we implement Idx<T, K>?  One fairly universal complication is that there's no simple way to express to the compiler that the path fragment at K will definitely be one of the keys of T. So one thing we'd need to do is check for that.  We can try it as:

type Idx<T, K extends string> = K extends keyof T ? T[K] : never;

And this kind of works:

type X = DeepIndex<Obj, 'a.b'>  // string[]

Until it doesn't:

type Y = DeepIndex<Obj, 'c.5'>  // never

And this is the place where your use case differs from others I've seen.  You are indexing into a number[] with the string value "5".  But the Array<T> type definition has a number index signature, and "5" is not a number.  It's a "numeric string", so you should be able to index into an array with it (since object keys in JavaScript are actually strings and not really numbers), but the compiler doesn't see "5" extends keyof (number[]) as being true.

So we need to account for such numeric string keys.  Let's try this:

type Idx<T, K extends string> =
  K extends keyof T ? T[K] :
  K extends `${number}` ? number extends keyof T ? T[number] : never : never;

Here we're saying that if K is a string version of a number (the "pattern template literal" `${number}` syntax was introduced in microsoft/TypeScript#40598), and if the type T has a numeric index signature, then we should index into T with number instead of K.   Let's test it out again:

type X = DeepIndex<Obj, 'a.b'>  // string[]
type Y = DeepIndex<Obj, 'c.5'>  // number

Looks good!

Of course there are tons of edge cases.  For those come come later, even if this meets the needs of the original person asking the question, there's no guarantee it will do what you expect... so you should really test against all your use cases.

For example: it's quite hard to check if K is a valid path before you do the indexing.  Instead of a compiler warning if you write DeepIndex<Obj, "something.that.is.definitely.not.a.path">, you'll just get the never type out, which may or may not be acceptable:

type Z = DeepIndex<Obj, 'oopsieDaisy'> // never

So test carefully!

<a href="https://www.typescriptlang.org/play?ts=4.5.4#code/HYQwtgpgzgDiDGEAEB5A9jKSDeBYAUAUkgC4CeMyAkgCYAeAPACoA0SA0khHSRMDVigkATgEtgAcwB8SALwcuPPgKQBrCGTQAzJEyQB+XQG12AXSQAuJMAgA3CMIDcBIqQrIAIhAgwq-bsxsnNy8-IIi4tJyuoqhKmgARgBWEPAkBkgAFK7EwUphSAAGACTY4loOSABiAL4AdKXllQBKNYUZXj5+NAG0jKzVUmzNMlZ9gRxSrgCUltZ2Ds6E+MTklKjJ0XgrxEggVtu7uwlWQmKSRqY5SDXX8FbAAK5gCQ6XrrfLq+5IABrRnV8-kYKGSbAA5CA6glwTIkAB6eFIM6RS5IQC8G4BgPdca2QAE0Ad4gT0QWCkOD4HUAKyw4iI+b2YQYwCMey58J8CKBILAEMgqqI6Dg2d91uMBnk4uFzlFZNcJcosOpNDo9IYmCZzBY5bEFUVSk8Xg42hkDa8mSFdUrtDE1UZTQ5NQzKg8Fk5hW51oDugFxTqCijJDJ5HoLQVEik0hlsjtcn6VCUysAKkzag1E8mkK12oYvcCGGK2FUhpnRkgC5MZnMbIylq56bikAAJMBgQldPOgpIQqEJal1AA2fAkJAAFnUSGgAArCVKiKCiNDAWF1pEN5ut+SZGAz+BzhfAfQPZ5mpAAHyQj38WnEEBos1kMgDEndDc7W2u+yFMeOpwiFyu36fEc9zWMebwAcQHI7A2-zyLmJIMJ23bQrSCJIk+aJYjiPwEnBRLeqSXbkvAqH0vaTJYdBPwAFptsSARIeSaAYPOEAeCAc5kLSZGumyBBQQQQA" rel="nofollow noreferrer">Playground link to code


问:
How to make dynamic link in Vue JS?
I have:

```<code><b-dropdown text="Select Factory" block variant="primary" class="m-2" menu-class="w-100">
<b-dropdown-item @click="selectedFactory='China'">China</b-dropdown-item>
<b-dropdown-item @click="selectedFactory='Europe'">Europe</b-dropdown-item>
</b-dropdown>

<b-dropdown text="Select Toy" block variant="primary" class="m-2" menu-class="w-100">
<b-dropdown-item @click="selectedToy='Marvel'">Marvel</b-dropdown-item>
<b-dropdown-item @click="selectedToy='Toy Story'">Toy Story</b-dropdown-item>
</b-dropdown>
</code>```

How can I make this line of code work, such that the source link is dynamic? Currently it does work with the dropdown selection when embeded into an iframe. I am guessing probably something to do with the compute function, am not very sure

```<code>export default {

el: '#apps',
  data () {
     return {

        source:'http://127.0.0.1:5503/src/html/`{{this.selectedFactory}}`_{{this.selectedToy}}.html',
        selectedFactory: '',
        selectedToy:'',
     }
  },
  computed:{

  }

}
</code>```

答:
I have figured out the answer:</p>
```<code>   export default {
    el: '#apps',
      data () {
         return {
            selectedFactory: '',
            selectedToy:'',
         }
      },
      computed:{
         source: function(){ return'http://127.0.0.1:5503/src/html/'+this.selectedFactory+'_'+this.selectedToy+'.html',
}

      }

    }
</code>```

Title: How to make dynamic link in Vue JS?

Body:
I have:

China
Europe

Marvel
Toy Story

How can I make this line of code work, such that the source link is dynamic? Currently it does work with the dropdown selection when embeded into an iframe. I am guessing probably something to do with the compute function, am not very sure

export default {

el: '#apps',
  data () {
     return {

        source:'http://127.0.0.1:5503/src/html/`{{this.selectedFactory}}`_{{this.selectedToy}}.html',
        selectedFactory: '',
        selectedToy:'',
     }
  },
  computed:{

  }

}

Body:
I have figured out the answer:

   export default {
    el: '#apps',
      data () {
         return {
            selectedFactory: '',
            selectedToy:'',
         }
      },
      computed:{
         source: function(){ return'http://127.0.0.1:5503/src/html/'+this.selectedFactory+'_'+this.selectedToy+'.html',
}

      }

    }


问:
HuggingFace 'TFEmbeddings' object has no attribute 'word_embeddings'
Trying to run this TextualHeatmap example, we encounter 'TFEmbeddings' object has no attribute 'word_embeddings' error in the following code snippet from the HuggingFace transformers library. Any help is appreciated.

```<code>from transformers import TFDistilBertForMaskedLM, DistilBertTokenizer
dbert_model = TFDistilBertForMaskedLM.from_pretrained('distilbert-base-uncased')
dbert_tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
dbert_embmat = dbert_model.distilbert.embeddings.word_embeddings
</code>```

答: Try to use '.weight' instead of '.word_embeddings' as per hugging face latest implementation. It works for me.</p>

Body:
Trying to run this TextualHeatmap example, we encounter 'TFEmbeddings' object has no attribute 'word_embeddings' error in the following code snippet from the HuggingFace transformers library. Any help is appreciated.

from transformers import TFDistilBertForMaskedLM, DistilBertTokenizer
dbert_model = TFDistilBertForMaskedLM.from_pretrained('distilbert-base-uncased')
dbert_tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
dbert_embmat = dbert_model.distilbert.embeddings.word_embeddings


问:
Automated facebook post to wall with Javascript
I have a facebook application in which the user is authenticated with PHP and grants permissions to the app, including publish_stream.

During the application, the user is going through several screens.

On the last screen, the is user chooses if they want to share a post on their wall.

If they do, an automated and formatted post should be posted on their wall.

I've tried to do it with Javascript but it didn't work.  Can you see what's wrong?

Thanks!
Here's my code:

```<code><div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId  : 'MY APP ID',
          status : true,
          cookie : true,
          xfbml  : true
        });
      };

      (function() {
        var e = document.createElement('script');
        e.src = 'http://connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>

<script>
    function postToFacebook() {
        var body = '';
        var params = {};
        params['message'] = 'MESSAGE';
        params['name'] = 'NAME';
        params['description'] = '';
        params['link'] = '';
        params['picture'] = 'https://www.URL.com/pic.jpg';
        params['caption'] = 'CAPTION';
        FB.api('/me/feed', 'post', params, function(response) {
          if (!response || response.error) {
           // alert('Error occured');
          } else {
           // alert('Post ID: ' + response);
          }
        });
    }
    </script>
</code>```

答:
You are not calling the function postToFacebook()!

```<code>window.fbAsyncInit = function() {
    FB.init({
      appId  : 'MY APP ID',
      status : true,
      cookie : true,
      xfbml  : true
    });
    postToFacebook();
  };
</code>```

Body:
You are not calling the function postToFacebook()!

window.fbAsyncInit = function() {
    FB.init({
      appId  : 'MY APP ID',
      status : true,
      cookie : true,
      xfbml  : true
    });
    postToFacebook();
  };


问:
Python Multiply Matrix by Vector of Matrices
Does anybody know of a way (preferably using numpy or something similar) to multiply a matrix by a vector of matrices and obtain the desired product shown below? Basically the idea is to follow the normal rules of matrix multplication of a matrix and a vector, only the elements of the vector are matrices themselves and not numbers.

Body:
If I understand the question correctly, you can try this:

import numpy as np

A = np.arange(3*3*3).reshape(3, 3, 3)
b = np.arange(9).reshape(3, 3)
print(f"A=\n{A}\n\nb=\n{b}")

It gives:

A=
[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]
  [24 25 26]]]

b=
[[0 1 2]
 [3 4 5]
 [6 7 8]]

Then:

out = (b@A.transpose(2, 0, 1)).transpose(1, 2, 0)
print(out)

which gives:

[[[ 45  48  51]
  [ 54  57  60]
  [ 63  66  69]]

 [[126 138 150]
  [162 174 186]
  [198 210 222]]

 [[207 228 249]
  [270 291 312]
  [333 354 375]]]

The matrix out[0] is equal to 0*A[0] + 1*A[1] + 2*A[2], out[1] is equal to 3*A[0] + 4*A[1] + 5*A[2] etc.


问:
HERE Search parameter 'r' not functioning
I am calling the public transit v8 like this

```<code>    https://transit.hereapi.com/v8/stations?in=51.492597,-0.156927;r=1000&return=transport&apiKey=my_key
</code>```

However, no matter what i change the r value to it continues search the default distance, whether i put it higher or lower than 500, it returns the same.

Documentation states - {lat},{lng}[;r={radius}] and all example show lat,long;r=x

I am sure I am using the correct formatting

Does anyone know why this may be?

答:
The delimiter between query params is an ampersand (&) not a semicolon (;).

Maybe change ;r=1000 to &r=1000

Body:
I am calling the public transit v8 like this

    https://transit.hereapi.com/v8/stations?in=51.492597,-0.156927;r=1000&return=transport&apiKey=my_key

However, no matter what i change the r value to it continues search the default distance, whether i put it higher or lower than 500, it returns the same.

Documentation states - {lat},{lng}[;r={radius}] and all example show lat,long;r=x

I am sure I am using the correct formatting

Does anyone know why this may be?


问:
Process communication in Python
What is the best way to establish communication between two processes in python? After some googling, I tried to do so:

```<code>parent_pipe, child_pipe = Pipe()
p = Process(target = instance_tuple.instance.run(), \
    args = (parent_pipe, child_pipe,))
p.start()
</code>```

Sending data to the child process:

```<code>command = Command(command_name, args)
parent_pipe.send(command)
</code>```

Process target function:

```<code>while True:
    if (self.parent_pipe.poll()):
        command = parent_pipe.recv()
        if (command.name == 'init_model'):
            self.init_model()
        elif (command.name == 'get_tree'):
            tree = self.get_fidesys_tree(*command.args)
            result = CommandResult(command.name, tree)
            self.child_pipe.send(result)
        elif(command.name == 'set_variable'):
            name = command.args[0]
            value = command.args[1]
            self.config[name] = value
</code>```

But it doesn't seem to work (child process doesn't receive anything through parent_pipe). How can I fix it?

Thanks in advance.

答:
You can have a look here : http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes
The solution is close to yours but seems easier.</p>

Title: Process communication in Python

Body:
What is the best way to establish communication between two processes in python? After some googling, I tried to do so:

parent_pipe, child_pipe = Pipe()
p = Process(target = instance_tuple.instance.run(), \
    args = (parent_pipe, child_pipe,))
p.start()

Sending data to the child process:

command = Command(command_name, args)
parent_pipe.send(command)

Process target function:

while True:
    if (self.parent_pipe.poll()):
        command = parent_pipe.recv()
        if (command.name == 'init_model'):
            self.init_model()
        elif (command.name == 'get_tree'):
            tree = self.get_fidesys_tree(*command.args)
            result = CommandResult(command.name, tree)
            self.child_pipe.send(result)
        elif(command.name == 'set_variable'):
            name = command.args[0]
            value = command.args[1]
            self.config[name] = value

But it doesn't seem to work (child process doesn't receive anything through parent_pipe). How can I fix it?

Thanks in advance.


问:
How to merge a table?
Inbound table:

Date
P_ID
S_ID
Measure1
Measure2

2022-02-12
01
03
100
NULL

2022-02-12
01
03
NULL
200

2022-02-13
01
02
300
NULL

2022-02-13
01
02
NULL
400

There are some more measure fields in this table.
In each row is only one measure field <> NULL.

I want to transfer/merge this table into another one, which is empty at the beginning:

Outbound table

Date
P_ID
S_ID
Measure1
Measure2

2022-02-12
01
03
100
200

2022-02-13
01
02
300
400

I've tried that with merge:

```<code>MERGE @OutboundTable AS TARGET
USING @InboundTable AS SOURCE
        ON  TARGET.[Date]   = SOURCE.[Date]
        AND TARGET.[P_ID]   = SOURCE.[P_ID]
        AND TARGET.[S_ID]   = SOURCE.[S_ID]
WHEN MATCHED THEN UPDATE SET
         TARGET.[Measure1] = ISNULL(SOURCE.[Measure1],TARGET.[Measure1]),
         TARGET.[Measure2] = ISNULL(SOURCE.[Measure2],TARGET.[Measure2])
    WHEN NOT MATCHED THEN
    INSERT
    (
          [Date]
        , [P_D]
        , [S_ID]
        , [Measure1]
        , [Measure2]
    )
    VALUES
    (
          SOURCE.[Date]
        , SOURCE.[P_ID]
        , SOURCE.[S_ID]
        , SOURCE.[Measure1]
        , SOURCE.[Measure2]
    )
    ;
</code>```

But it did not work. The outbound table contained the same rows as the inbound table.

How can I perform this transformation?

答:
Query:

```<code>INSERT INTO outbound (date, P_ID, S_ID, Measure1, Measure2)
SELECT date, P_ID, S_ID, MAX(Measure1) AS Measure1, MAX(Measure2) AS Measure2
  FROM inbound_table
  GROUP BY date, P_ID, S_ID;
</code>```

Title: How to merge a table?

Body:
Inbound table:

Date
P_ID
S_ID
Measure1
Measure2

2022-02-12
01
03
100
NULL

2022-02-12
01
03
NULL
200

2022-02-13
01
02
300
NULL

2022-02-13
01
02
NULL
400

There are some more measure fields in this table.
In each row is only one measure field <> NULL.

I want to transfer/merge this table into another one, which is empty at the beginning:

Outbound table

Date
P_ID
S_ID
Measure1
Measure2

2022-02-12
01
03
100
200

2022-02-13
01
02
300
400

I've tried that with merge:

MERGE @OutboundTable AS TARGET
USING @InboundTable AS SOURCE
        ON  TARGET.[Date]   = SOURCE.[Date]
        AND TARGET.[P_ID]   = SOURCE.[P_ID]
        AND TARGET.[S_ID]   = SOURCE.[S_ID]
WHEN MATCHED THEN UPDATE SET
         TARGET.[Measure1] = ISNULL(SOURCE.[Measure1],TARGET.[Measure1]),
         TARGET.[Measure2] = ISNULL(SOURCE.[Measure2],TARGET.[Measure2])
    WHEN NOT MATCHED THEN
    INSERT
    (
          [Date]
        , [P_D]
        , [S_ID]
        , [Measure1]
        , [Measure2]
    )
    VALUES
    (
          SOURCE.[Date]
        , SOURCE.[P_ID]
        , SOURCE.[S_ID]
        , SOURCE.[Measure1]
        , SOURCE.[Measure2]
    )
    ;

But it did not work. The outbound table contained the same rows as the inbound table.

How can I perform this transformation?

Body:
Query:

INSERT INTO outbound (date, P_ID, S_ID, Measure1, Measure2)
SELECT date, P_ID, S_ID, MAX(Measure1) AS Measure1, MAX(Measure2) AS Measure2
  FROM inbound_table
  GROUP BY date, P_ID, S_ID;


问:
What are the proper typescript types for addEventListener mousemove and it's event argument?
Question: Without using any, What is the proper typing for my onMouseMove function?

```<code>export class Main {
  private dTimer: number;

  constructor() {
    this.init();
  }

  private init() {
    this.mouseHandlers();
  }

  private mouseHandlers() {
    document.addEventListener('mousemove', this.onMouseMove)
  }

  private onMouseMove: EventListener = (event: MouseEvent) => {
    clearTimeout(this.dTimer);
    this.dTimer = setTimeout(() => {
      console.log(event.pageX, event.pageY)
    }, 500);
  }
}
</code>```

Typescript is complaining about my types and I dunno how to make it happy w/o using any.

```<code>main.ts(38,3): error TS2322: Type '(event: MouseEvent) => void' is not assignable to type 'EventListener'.
  Types of parameters 'event' and 'evt' are incompatible.
    Type 'Event' is not assignable to type 'MouseEvent'.
      Property 'altKey' is missing in type 'Event'.
</code>```

答:
I've found that using MouseEventInit as the event type solves the problem.  This type comes from TypeScript lib.dom.ts. I'm using TypeScript 4.5.5.
i.e.

```<code>private onMouseMove: EventListener = (event: MouseEventInit) => {
clearTimeout(this.dTimer);
this.dTimer = setTimeout(() => {
    console.log(event.pageX, event.pageY)
}, 500);}
</code>```

Body:
Question: Without using any, What is the proper typing for my onMouseMove function?

export class Main {
  private dTimer: number;

  constructor() {
    this.init();
  }

  private init() {
    this.mouseHandlers();
  }

  private mouseHandlers() {
    document.addEventListener('mousemove', this.onMouseMove)
  }

  private onMouseMove: EventListener = (event: MouseEvent) => {
    clearTimeout(this.dTimer);
    this.dTimer = setTimeout(() => {
      console.log(event.pageX, event.pageY)
    }, 500);
  }
}

Typescript is complaining about my types and I dunno how to make it happy w/o using any.

main.ts(38,3): error TS2322: Type '(event: MouseEvent) => void' is not assignable to type 'EventListener'.
  Types of parameters 'event' and 'evt' are incompatible.
    Type 'Event' is not assignable to type 'MouseEvent'.
      Property 'altKey' is missing in type 'Event'.

Body:
I've found that using MouseEventInit as the event type solves the problem.  This type comes from TypeScript lib.dom.ts. I'm using TypeScript 4.5.5.
i.e.

private onMouseMove: EventListener = (event: MouseEventInit) => {
clearTimeout(this.dTimer);
this.dTimer = setTimeout(() => {
    console.log(event.pageX, event.pageY)
}, 500);}


问:
Does Array.map() use an iterator as constructor?
This is normally a detail that is hidden from the programmer, but as a test I made a new class Vector extending Array that changed the constructor to unpack an input array and now Vector.map() stopped working:

class Vector extends Array {
    constructor(array) {
        console.assert(Array.isArray(array),
            `Vector constructor expected Array, got ${array}`);
        // ignore special case of length 1 array
        super(...array);
    }

    add(other) {
        return this.map((e, i) => e + other[i]);
    }
}

let a = new Vector([1,2,3]);
console.log(a.add(a));```

I assume what happened based on my Python experience is that Array.map() internally constructs a new Array with an iterator, like that of Array.prototype[@@iterator](), but my Vector constructor instead takes an Array object. Is this correct? Maybe map is a primitive of the JS implementation.

答:
This has nothing to do with iterators, it's because of the way that Array.prototype.map() creates the result.

The result will be the same subclass as the object it's being called on, so it calls your constructor to create the result. It expects any subclasses of Array to support the same parameters as Array itself: either the argument is a single integer which is the size of the array to create, or it's multiple arguments to provide the initial contents of the array.

Since the array you're mapping over is 3 elements long, it wants to create a Vector with 3 elements, so it calls Vector(3) to create this.

You need to redefine your class to accept arguments like Array:

class Vector extends Array {
  constructor(...args) {
    // Allow it to be called with an Array argument and convert it to Vector.
    if (args.length == 1 && Array.isArray(args[0])) {
      if (args[0].length == 1) {
        // need to handle 1 element specially so it's not used as the length
        super(1);
        self[0] = args[0];
      } else {
        super(...args[0]);
      }
    } else {
      super(...args);
    }
  }

  add(other) {
    return this.map((e, i) => e + other[i]);
  }
}

let a = new Vector([1, 2, 3]);
console.log(a.add(a));```

This implementation accepts all the Array arguments, and additionally accepts an array as the sole argument in order to convert it to a vector.

Body:
This is normally a detail that is hidden from the programmer, but as a test I made a new class Vector extending Array that changed the constructor to unpack an input array and now Vector.map() stopped working:

class Vector extends Array {
    constructor(array) {
        console.assert(Array.isArray(array),
            `Vector constructor expected Array, got ${array}`);
        // ignore special case of length 1 array
        super(...array);
    }

    add(other) {
        return this.map((e, i) => e + other[i]);
    }
}

let a = new Vector([1,2,3]);
console.log(a.add(a));

I assume what happened based on my Python experience is that Array.map() internally constructs a new Array with an iterator, like that of Array.prototype[@@iterator](), but my Vector constructor instead takes an Array object. Is this correct? Maybe map is a primitive of the JS implementation.

Body:
This has nothing to do with iterators, it's because of the way that Array.prototype.map() creates the result.

The result will be the same subclass as the object it's being called on, so it calls your constructor to create the result. It expects any subclasses of Array to support the same parameters as Array itself: either the argument is a single integer which is the size of the array to create, or it's multiple arguments to provide the initial contents of the array.

Since the array you're mapping over is 3 elements long, it wants to create a Vector with 3 elements, so it calls Vector(3) to create this.

You need to redefine your class to accept arguments like Array:

class Vector extends Array {
  constructor(...args) {
    // Allow it to be called with an Array argument and convert it to Vector.
    if (args.length == 1 && Array.isArray(args[0])) {
      if (args[0].length == 1) {
        // need to handle 1 element specially so it's not used as the length
        super(1);
        self[0] = args[0];
      } else {
        super(...args[0]);
      }
    } else {
      super(...args);
    }
  }

  add(other) {
    return this.map((e, i) => e + other[i]);
  }
}

let a = new Vector([1, 2, 3]);
console.log(a.add(a));

This implementation accepts all the Array arguments, and additionally accepts an array as the sole argument in order to convert it to a vector.


问:
If else statement not outputting correctly?
I'm a beginner to Python and am struggling with a project I am working on. The program takes monthly income, fixed monthly expenses, asks for any additional expenses, and then outputs with an if else statement. My issue is in this function:

```<code>def spending(income, totals):

  finalTotal = income - totals

  if income > finalTotal:

    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif finalTotal > income:

    print("You overspent by $", "%.2f"%finalTotal, "this month!")

  else:

    print("You broke even this month!")
</code>```

It is printing:

```<code>You saved $ -805.00 this month!
</code>```

When I'd like it to print:

```<code>You overspent by $ 805.00 this month!
</code>```

Any feedback would be greatly appreciated!!

Here is my code:
https://replit.com/@ashleyshubin/BudgetProgram#main.py

答:
If totals is your monthly expenses, then subtracting totals from income gives you how much money you made this month. The first if statement should be

```<code>if finalTotal > 0:
</code>```

The second if statement would be

```<code>if finalTotal < 0:
</code>```

And you would want to use abs(finalTotal) when printing finalTotal so it does not display a negative number

Body:
I'm a beginner to Python and am struggling with a project I am working on. The program takes monthly income, fixed monthly expenses, asks for any additional expenses, and then outputs with an if else statement. My issue is in this function:

def spending(income, totals):

  finalTotal = income - totals

  if income > finalTotal:

    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif finalTotal > income:

    print("You overspent by $", "%.2f"%finalTotal, "this month!")

  else:

    print("You broke even this month!")

It is printing:

You saved $ -805.00 this month!

When I'd like it to print:

You overspent by $ 805.00 this month!

Any feedback would be greatly appreciated!!

Here is my code:
https://replit.com/@ashleyshubin/BudgetProgram#main.py

Body:
If totals is your monthly expenses, then subtracting totals from income gives you how much money you made this month. The first if statement should be

if finalTotal > 0:

The second if statement would be

if finalTotal < 0:

And you would want to use abs(finalTotal) when printing finalTotal so it does not display a negative number


问:
Angular2 wait for @Input object to be fully initialized
I have a .ts class with a variable decorated as @Input

I would like to make a copy of this object but i cant figure out the right place to do this is, my current code:

```<code>@Input() myObj: MyObj;
public copy: MyObj;

 ngOnInit() {
    this.copy = JSON.parse(JSON.stringify(myObj));
}
</code>```

The call within the ngOnInit method breaks because the ngOnInit is called before the myObj variable is fully created.

I have also tried to create the copy within the ngAfterContentInit method but that is also called before myObj variable is fully created.

I have seen other questions similar to mine, but they all wait for an observable, my object is not an observable, is simply an object passed from parent to child through the view:

```<code><child-view [myObj]="myObjInParent"/>
</code>```

答:
If you want copy to be initialized only once at the time of component initialization then Akmal's solution works: https://stackoverflow.com/a/71093779/904375

But in case you want the copy to be updated every time the @Input() is updated, then you have to create a getter/setter. For eg.:

```<code>  private _copy: any;

  private _employee: Employee;

  get employee() { return this._employee; }

  @Input() set employee(value: Employee) {
    this._employee = value;
    this._copy = {...value};
  };

</code>```

Body:
I have a .ts class with a variable decorated as @Input

I would like to make a copy of this object but i cant figure out the right place to do this is, my current code:

@Input() myObj: MyObj;
public copy: MyObj;

 ngOnInit() {
    this.copy = JSON.parse(JSON.stringify(myObj));
}

The call within the ngOnInit method breaks because the ngOnInit is called before the myObj variable is fully created.

I have also tried to create the copy within the ngAfterContentInit method but that is also called before myObj variable is fully created.

I have seen other questions similar to mine, but they all wait for an observable, my object is not an observable, is simply an object passed from parent to child through the view:

<child-view [myObj]="myObjInParent"/>

Body:
If you want copy to be initialized only once at the time of component initialization then Akmal's solution works: https://stackoverflow.com/a/71093779/904375

But in case you want the copy to be updated every time the @Input() is updated, then you have to create a getter/setter. For eg.:

  private _copy: any;

  private _employee: Employee;

  get employee() { return this._employee; }

  @Input() set employee(value: Employee) {
    this._employee = value;
    this._copy = {...value};
  };