问:
Create a custom theme that can inherit theme parameters
I wish to create a custom theme function, which can inherit all the arguments from theme.

So far, I have something like:

```<code>my_theme <- function(...){
  theme(axis.title = element_text(colour = "red"))
}
</code>```

If I want to change the plot background for example, I currently need to do:

```<code>ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  my_theme() +
  theme(panel.background = element_rect(fill = "blue",
                                        colour = "green"))
</code>```

While I wish I could do:

```<code>ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  my_theme(panel.background = element_rect(fill = "blue",
                                        colour = "green"))
</code>```

I guess I have to initialize all the theme's arguments inside the custom function, but is there another work around? Thanks!

答:
You could just pass on the ellipses to theme()?

library(ggplot2)

my_theme <- function(..., axis.title = NULL) {
  axis.title <- if (is.null(axis.title)) {
    element_text(colour = "red")
  } else {
    axis.title
  }
  theme(axis.title = axis.title, ...)
}

# Alternatively
my_theme <- function(..., axis.title = element_text(colour = "red")) {
  theme(axis.title = axis.title, ...)
}

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  my_theme(panel.background = element_rect(fill = "blue",
                                           colour = "green"))
```
<p><img src="https://i.imgur.com/RcVD5YX.png" alt="" /></p>
<p><sup>Created on 2022-02-09 by the reprex package (v2.0.1)</sup></p>
<p>Another option if you're writing scripts/notebooks for yourself with no intention to package up your code is to just use <code>theme_set()</code> at the beginning, which propagates to all subsequent plots. This is how most of my scripts start.</p>
<pre class="lang-r prettyprint-override"><code>library(ggplot2)

theme_set(theme_get() + theme(axis.title = element_text(colour = "red")))

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  theme(panel.background = element_rect(fill = "blue",
                                        colour = "green"))
</code>```

Body:
I wish to create a custom theme function, which can inherit all the arguments from theme.

So far, I have something like:

my_theme <- function(...){
  theme(axis.title = element_text(colour = "red"))
}

If I want to change the plot background for example, I currently need to do:

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  my_theme() +
  theme(panel.background = element_rect(fill = "blue",
                                        colour = "green"))

While I wish I could do:

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  my_theme(panel.background = element_rect(fill = "blue",
                                        colour = "green"))

I guess I have to initialize all the theme's arguments inside the custom function, but is there another work around? Thanks!

Body:
You could just pass on the ellipses to theme()?

library(ggplot2)

my_theme <- function(..., axis.title = NULL) {
  axis.title <- if (is.null(axis.title)) {
    element_text(colour = "red")
  } else {
    axis.title
  }
  theme(axis.title = axis.title, ...)
}

# Alternatively
my_theme <- function(..., axis.title = element_text(colour = "red")) {
  theme(axis.title = axis.title, ...)
}

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  my_theme(panel.background = element_rect(fill = "blue",
                                           colour = "green"))

Created on 2022-02-09 by the reprex package (v2.0.1)

Another option if you're writing scripts/notebooks for yourself with no intention to package up your code is to just use theme_set() at the beginning, which propagates to all subsequent plots. This is how most of my scripts start.

library(ggplot2)

theme_set(theme_get() + theme(axis.title = element_text(colour = "red")))

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  theme(panel.background = element_rect(fill = "blue",
                                        colour = "green"))


来源: stackexchange

问:
Confused between Ory Hydra and Ory Kratos for creating full-blown idp
I have a project where I want to build a full-blown IDP (using Golang). So technically, a user wants to SSO into another system using my service. I am looking to build this service from scratch. Upon researching for open-source IDP solutions, I came across ory/Hydra and ory/Kratos. I went through their documentation and did a quick-start tutorial. I am still confused about which of the above 2 libraries are suitable for the development of this service.

From a high-level standpoint, this is what I am trying to do.

There is an existing third-party web app X.

A user has already login credentials for my service Y.

A user wants to post some comments in app X.

He/She is redirected to my service Y login screen if not logged in.

After login, the Callback URL returns him back to app X comment section.

答:
ory/Kratos is not what you are looking for because it is designed to answer your user management basic needs.

The right tool for you is ory/Hydra. I have copied this from its documentation:

If you want apps and websites you don't own to use your application as
a potential sign in (e.g. be listed alongside "Sign in with Google",
"Sign in with Apple"), ORY Hydra is the right tool for you.

source: https://www.ory.sh/hydra/docs/concepts/before-oauth2

ContentLicense: CC BY-SA 4.0


问:
lighttpd service started with root privilege instead of the user set in the server.username
In my ubuntu box I created a user "lighttpd" and I modified the lighttpd.conf file with the created user, below are the lines modified.

server.username = "lighttpd"
server.groupname = "lighttpd"

I am a root user, and started the lighttpd service by executing with my conf file located in /run folder like below.
/usr/sbin/lighttpd -f /run/lighttpd.conf

On executing the above command, the lighttpd started with root user instead of lighttpd user.

My expectation was the service should start with lighttpd user (which was set server.username = "lighttpd" in conf file).

答:
Run lighttpd with the -p flag to print the configuration that lighttpd sees, and then verify that what lighttpd sees matches what you think lighttpd should see.  If lighttpd.conf contains server.username = "lighttpd", then lighttpd will exit with an error if lighttpd can not drop privileges to become user lighttpd.

In your case, review the output of: /usr/sbin/lighttpd -f /run/lighttpd.conf -p
Then, make sure that any other instance of lighttpd running on your machine has been shut down before you try manually starting lighttpd.  (You can run multiple instances of lighttpd on different ports, but for your experiment, it is simpler to ask you to make sure all other instances of lighttpd have been shut down.)


问:
VBA solution for very slow Countif formula
I have a solution that works in Excel with a countif formula (with the help of another Stackoverflow user).

Essentially what this countif formula does is count the first instance of an ID that exclusively exists with the classification type "DC". For example, as you can see in my snippet, 2232 is marked with as it is only exists with the classification "DC". Whilst in the case of 2240 it is marked as 0 as there are multiple classifications possible.

The formula in column D is the following:

=IF(IF(B2<>"DC",0,AND(COUNTIF(C$2:C$28,C2)=COUNTIF(A$2:A$28,A2),COUNTIF(A$2:A2,A2)=1)),1,0)

The problem that I am experiencing is that this is an extremely slow formula to process for Excel -- it takes roughly ~10-15 mins to complete. The database that I am running this on contains of roughly 150k~ lines.

I was wondering if it was possible to do this same process in VBA, but a lot faster and more efficient than the current processing time.

So I am using the following piece of VBA code to try to recreate the same results:

```<code>Sub MarkUniqueID()
   Dim Ary As Variant, Nary As Variant
   Dim r As Long

   With ThisWorkbook.Sheets("sheet1")
      Ary = .Range("A2", .Range("A" & Rows.Count).End(xlUp)).Value2
   End With
   ReDim Nary(1 To UBound(Ary), 1 To 1)
   With CreateObject("scripting.dictionary")
      For r = 1 To UBound(Ary)
         If Not .Exists(Ary(r, 1)) Then
            .Add Ary(r, 1), Nothing
            Nary(r, 1) = 1
         Else
            Nary(r, 1) = 0
         End If
      Next r
   End With
   ThisWorkbook.Sheets("sheet1").Range("E2").Resize(r).Value = Nary
End Sub
</code>```

Which runs the process much smoother it takes only a few ~seconds of my original time, however, I am not sure how I can add one more criteria into my array (i.e. only exclusively consider "DC"), as now the results are not what I want (see below).

Any pointers would be much appreciated!

答:
You can use another dictionary to track which ID's should be excluded:

Sub MarkUniqueID()
    Dim Ary As Variant, Nary() As Long, cls, id, k
    Dim r As Long, dictIn As Object, dictOut As Object
    Dim ws As Worksheet

    Set dictIn = CreateObject("scripting.dictionary")
    Set dictOut = CreateObject("scripting.dictionary")

    Set ws = ThisWorkbook.Sheets("sheet1")
    'pick up the classification and ID
    Ary = ws.Range("B2:C" & ws.Cells(ws.Rows.Count, "B").End(xlUp).Row).Value

    ReDim Nary(1 To UBound(Ary), 1 To 1)

    For r = 1 To UBound(Ary, 1)
        cls = Ary(r, 1)
        id = CStr(Ary(r, 2))

        If cls = "DC" Then
            If Not dictIn.exists(id) Then dictIn.Add id, r
        Else
            If Not dictOut.exists(id) Then dictOut.Add id, True
        End If
    Next r
    For Each k In dictIn
        If Not dictOut.exists(k) Then Nary(dictIn(k), 1) = 1
    Next k
    ws.Range("E2").Resize(UBound(Nary, 1)).Value = Nary
End Sub
```

Body:
I have a solution that works in Excel with a countif formula (with the help of another Stackoverflow user).

Essentially what this countif formula does is count the first instance of an ID that exclusively exists with the classification type "DC". For example, as you can see in my snippet, 2232 is marked with as it is only exists with the classification "DC". Whilst in the case of 2240 it is marked as 0 as there are multiple classifications possible.

The formula in column D is the following:

=IF(IF(B2<>"DC",0,AND(COUNTIF(C$2:C$28,C2)=COUNTIF(A$2:A$28,A2),COUNTIF(A$2:A2,A2)=1)),1,0)

The problem that I am experiencing is that this is an extremely slow formula to process for Excel -- it takes roughly ~10-15 mins to complete. The database that I am running this on contains of roughly 150k~ lines.

I was wondering if it was possible to do this same process in VBA, but a lot faster and more efficient than the current processing time.

So I am using the following piece of VBA code to try to recreate the same results:

Sub MarkUniqueID()
   Dim Ary As Variant, Nary As Variant
   Dim r As Long

   With ThisWorkbook.Sheets("sheet1")
      Ary = .Range("A2", .Range("A" & Rows.Count).End(xlUp)).Value2
   End With
   ReDim Nary(1 To UBound(Ary), 1 To 1)
   With CreateObject("scripting.dictionary")
      For r = 1 To UBound(Ary)
         If Not .Exists(Ary(r, 1)) Then
            .Add Ary(r, 1), Nothing
            Nary(r, 1) = 1
         Else
            Nary(r, 1) = 0
         End If
      Next r
   End With
   ThisWorkbook.Sheets("sheet1").Range("E2").Resize(r).Value = Nary
End Sub

Which runs the process much smoother it takes only a few ~seconds of my original time, however, I am not sure how I can add one more criteria into my array (i.e. only exclusively consider "DC"), as now the results are not what I want (see below).

Any pointers would be much appreciated!


问:
How to convert an object into an array of objects with named properties?
How do you go from a single object like this:

```<code>{
    item001: '200',
    item002: '350',
    ...
}
</code>```

to an array of objects with named properties like this:

```<code>[
    {
        product: 'item001',
        price: 200
    },
    {
        product: 'item002',
        price: 350
    },
    ...
]
</code>```

答:
You can use entries and map methods to iterate over and map key/value pairs of an object:

const items = { item001: '200', item002: '350' };

const new_items = Object.entries(items).map((item)=>({ product:item[0], price:item[1]}));
console.log(new_items)```

Body:
How do you go from a single object like this:

{
    item001: '200',
    item002: '350',
    ...
}

to an array of objects with named properties like this:

[
    {
        product: 'item001',
        price: 200
    },
    {
        product: 'item002',
        price: 350
    },
    ...
]


问:
How to handle multiple sessions for same website using same browser with different tabs. ASP.net C#
How to handle multiple sessions for same website using same browser with different tabs. ASP.net C#.
example like google if we open 2 account in same browser  it will not effect user details.</p>

答:
Well, as noted, session() is global to the user. In fact, they can launch two different browsers, say FireFox, and Edge - and they will BOTH continue to use the same session values!

What this REALLY means is that from day one, your designs HAVE to make this assumption. If you don't make this simple assumption, then you can be in for a world of BIG hurt if you "just out of the blue" wrote code without the above concept in mind.

In other words, for global things, then session() is fine. However, if you start writing BOATLOADS of code based on using session() to persist values on a SINGLE page? DON'T!!!

And it takes a few seconds in 99% of cases to flip code from session[] to ViewState[] for a given page.

So, now then the ONLY issue is when we use session[] to pass values around from page to page.

Using session() for passing values is ok, but NOT for such information like PK row values such as booking a hotel room, or say selecting a house to buy.

However, like a lot of people, the problem is we don't really think about this issue, or don't know about this issue until it is too late.

So, this is a problem. You want the "easy" of session(), but we need a way to pass around values from page to page.

As noted, one way is to pass values around using parameters in the URL. But then again, that's rather ugly. Sure, for some things like to filter a grid by a given city, then that can be really nice, since then users can save such a URL, or often modify the URL to their liking.

However, for a simple pick of a house or say a hotel room to book, then you can't of course allow or risk doing that (since you would be exposing primary row keys and selection in plain view. Worse yet, it can be a huge security risk. (some very early credit card and other types of sites would actually let you type in values that would let you get and see OTHER USERS information!!!

So, here is how you can handle this issue:

First up, we have these simple choices:

```<code>Parameters in URL - they are ugly, high risk, but GREAT for things like city filters etc.

Session() - this is global to the user - includes separate browsers launched.

ViewState - this is per web page - ideal for what we need, and PER PAGE!!!

HiddenFields (in markup) - again, per page - ideal for what we need, but PER PAGE!!!
</code>```

So, in regards the per page options, only URL parameters can work for passing.
(sans the session() option).

ViewState is great for per page, but you can't use ViewState for passing values between pages. Keep in mind that viewstate is client side, and while encrypted?

Well, for not super high security, then it ok to use. Just remember, ViewState should be kept small, since it goes with EACH button click and PostBack, ViewState becomes part of that "package" and post.

ViewState is part of the page post-back. This is certainly ok, and even better then hidden fields which appear in plain view client side. Just keep in mind ViewState increases the size of each and every post back for a page. So, keep it light, small, and don't persist LARGE amounts of data like say some large dataset.
(unlike Session() which is 100% server side).

So, we need:
Easy approach - per page, but NOT have to re-write a lot of code.

So, while you could say munge up the URL, then they start to look really ugly, and while that might get you a session for the given page, your session() code has to be changed - and it gets messy.

so, just limit using session() to pass values, but NOT persist per page - and you then quite much home free.

In effect? I am saying NEVER use Session to persist values in a page unless you have no other reasonable choice. (use ViewState).

The other issue? What good is to suggest some approach in which you have to re-write a boatload of existing code?

I find that even a page with quite a bit of Session() stuff can in less then a minute be changed over to use ViewState. In fact, you can in most cases use search + replace Session to Viewstate.

So, the only issue left is now the passing of values from page to page.

Use session freely to pass values to the next page. However, for any values that are say PK values, or row identification values, or values that will "break" or "damage" the operations of that page if MORE then one page were to be open? Then simple transfer the values in session to next page AND THEN ALWAYS on FIRST PAGE load (IsPostBack = false), you simple transfer the values to ViewState.

This works really nice, and is BOATLOADS of less work then trying to adopt some silly parameter in the URL or what ever other junk people propose. In other words, we want the LEAST DAMAGE to existing code.

And also, because session() is global? Then it starts to get REALLY messy. I want to say pass 4 values to the next page. And then on that page I might have some more values - all of sudden, while writing code, you can't even remember what session() name to use - and it piles up into a BIG MESS REALLY fast. You wind up with a boatload of session values - ever more growing in your application. It just a mess, and global values tend to be a HUGE mess in any applcation - including that of using session().

And, often, 4-5 values are for the SPECIFIC page - so do NOT create 4-5 session() values, but add a typedef or simple class to the project. And use that for passing of the values. It MUCH LESS clutter in session(), and as you about to see, it also MUCH nicer for transferring these values to Viewstate.

So, we now have this:

```<code>we adopt and use View Sate for each page.
we ONLY use session to pass values to next page.
</code>```

Lets give a simple example.

We say have a grid of hotels - you pick one. As noted, for buying things, picking  hotel etc, then passing that value with session is OK AS LONG as you adopt the above rule (that we transfer values to Viewstate in the target page).

The goal here is to allow multiple working tabs or copies of the browser running, and of course minimal code changes.

So, say we have a GridView, and a Hotel to book.

So, note the values we pass (hotel ID, room type, nightly rate).

As noted, we then navigate to the next page (probably additional room details, etc.) - confirm booking etc.

But, as we noted, we can't use session() anymore, since they might have two browsers open. Heck they might have the page open on both their desktop and their smartphone.

So, when we land on the 2nd page, if two pages land using session, we in huge trouble? No, not with our above approach.

So we can still use session() to pass values, BUT we do NOT persist values on that target page. In other words, we break down the two issues:

```<code>a) - we using session() to pass values to the next page
b) - we now are NOT using session() to persist values on CURRENT page <<--- this we fix!!!
</code>```

So, by making our goal here CRYSTAL CLEAR then you as a developer can deal with the above with a SIMPLE change to your existing code. As I stated, you the developer have to code, build, and design your web pages with the above concepts in mind.

So, for persisting values on a given page, just start using ViewState in place of session() - such code will work un-changed in most cases, and all and any values you save ONLY BELONG to the current page.

Only major difference is a user refresh of the page can re-set the ViewState for that page (but session() would and did persist - so some caution is required here - but not much).

So do this:

Pass values by session(), but on FIRST PAGE load (IsPostBack = False), transfer the value(s) to view state, and you are done!!

So, while session() can and is and will be shared between even two browsers running? Well, you click on some row, get PK into session(). Now, say you jump to the next page, on page load (IsPostBack = false), you transfer session value(s) to ViewState, and now you have full operational page - not dependent on Session().

The above is the best solution I have found, and you don't in most cases have to change your code, or introduced some mucked up URL which I find is even more of mess.

Body:
Well, as noted, session() is global to the user. In fact, they can launch two different browsers, say FireFox, and Edge - and they will BOTH continue to use the same session values!

What this REALLY means is that from day one, your designs HAVE to make this assumption. If you don't make this simple assumption, then you can be in for a world of BIG hurt if you "just out of the blue" wrote code without the above concept in mind.

In other words, for global things, then session() is fine. However, if you start writing BOATLOADS of code based on using session() to persist values on a SINGLE page? DON'T!!!

And it takes a few seconds in 99% of cases to flip code from session[] to ViewState[] for a given page.

So, now then the ONLY issue is when we use session[] to pass values around from page to page.

Using session() for passing values is ok, but NOT for such information like PK row values such as booking a hotel room, or say selecting a house to buy.

However, like a lot of people, the problem is we don't really think about this issue, or don't know about this issue until it is too late.

So, this is a problem. You want the "easy" of session(), but we need a way to pass around values from page to page.

As noted, one way is to pass values around using parameters in the URL. But then again, that's rather ugly. Sure, for some things like to filter a grid by a given city, then that can be really nice, since then users can save such a URL, or often modify the URL to their liking.

However, for a simple pick of a house or say a hotel room to book, then you can't of course allow or risk doing that (since you would be exposing primary row keys and selection in plain view. Worse yet, it can be a huge security risk. (some very early credit card and other types of sites would actually let you type in values that would let you get and see OTHER USERS information!!!

So, here is how you can handle this issue:

First up, we have these simple choices:

Parameters in URL - they are ugly, high risk, but GREAT for things like city filters etc.

Session() - this is global to the user - includes separate browsers launched.

ViewState - this is per web page - ideal for what we need, and PER PAGE!!!

HiddenFields (in markup) - again, per page - ideal for what we need, but PER PAGE!!!

So, in regards the per page options, only URL parameters can work for passing.
(sans the session() option).

ViewState is great for per page, but you can't use ViewState for passing values between pages. Keep in mind that viewstate is client side, and while encrypted?

Well, for not super high security, then it ok to use. Just remember, ViewState should be kept small, since it goes with EACH button click and PostBack, ViewState becomes part of that "package" and post.

ViewState is part of the page post-back. This is certainly ok, and even better then hidden fields which appear in plain view client side. Just keep in mind ViewState increases the size of each and every post back for a page. So, keep it light, small, and don't persist LARGE amounts of data like say some large dataset.
(unlike Session() which is 100% server side).

So, we need:
Easy approach - per page, but NOT have to re-write a lot of code.

So, while you could say munge up the URL, then they start to look really ugly, and while that might get you a session for the given page, your session() code has to be changed - and it gets messy.

so, just limit using session() to pass values, but NOT persist per page - and you then quite much home free.

In effect? I am saying NEVER use Session to persist values in a page unless you have no other reasonable choice. (use ViewState).

The other issue? What good is to suggest some approach in which you have to re-write a boatload of existing code?

I find that even a page with quite a bit of Session() stuff can in less then a minute be changed over to use ViewState. In fact, you can in most cases use search + replace Session to Viewstate.

So, the only issue left is now the passing of values from page to page.

Use session freely to pass values to the next page. However, for any values that are say PK values, or row identification values, or values that will "break" or "damage" the operations of that page if MORE then one page were to be open? Then simple transfer the values in session to next page AND THEN ALWAYS on FIRST PAGE load (IsPostBack = false), you simple transfer the values to ViewState.

This works really nice, and is BOATLOADS of less work then trying to adopt some silly parameter in the URL or what ever other junk people propose. In other words, we want the LEAST DAMAGE to existing code.

And also, because session() is global? Then it starts to get REALLY messy. I want to say pass 4 values to the next page. And then on that page I might have some more values - all of sudden, while writing code, you can't even remember what session() name to use - and it piles up into a BIG MESS REALLY fast. You wind up with a boatload of session values - ever more growing in your application. It just a mess, and global values tend to be a HUGE mess in any applcation - including that of using session().

And, often, 4-5 values are for the SPECIFIC page - so do NOT create 4-5 session() values, but add a typedef or simple class to the project. And use that for passing of the values. It MUCH LESS clutter in session(), and as you about to see, it also MUCH nicer for transferring these values to Viewstate.

So, we now have this:

we adopt and use View Sate for each page.
we ONLY use session to pass values to next page.

Lets give a simple example.

We say have a grid of hotels - you pick one. As noted, for buying things, picking  hotel etc, then passing that value with session is OK AS LONG as you adopt the above rule (that we transfer values to Viewstate in the target page).

The goal here is to allow multiple working tabs or copies of the browser running, and of course minimal code changes.

So, say we have a GridView, and a Hotel to book.

So, note the values we pass (hotel ID, room type, nightly rate).

As noted, we then navigate to the next page (probably additional room details, etc.) - confirm booking etc.

But, as we noted, we can't use session() anymore, since they might have two browsers open. Heck they might have the page open on both their desktop and their smartphone.

So, when we land on the 2nd page, if two pages land using session, we in huge trouble? No, not with our above approach.

So we can still use session() to pass values, BUT we do NOT persist values on that target page. In other words, we break down the two issues:

a) - we using session() to pass values to the next page
b) - we now are NOT using session() to persist values on CURRENT page <<--- this we fix!!!

So, by making our goal here CRYSTAL CLEAR then you as a developer can deal with the above with a SIMPLE change to your existing code. As I stated, you the developer have to code, build, and design your web pages with the above concepts in mind.

So, for persisting values on a given page, just start using ViewState in place of session() - such code will work un-changed in most cases, and all and any values you save ONLY BELONG to the current page.

Only major difference is a user refresh of the page can re-set the ViewState for that page (but session() would and did persist - so some caution is required here - but not much).

So do this:

Pass values by session(), but on FIRST PAGE load (IsPostBack = False), transfer the value(s) to view state, and you are done!!

So, while session() can and is and will be shared between even two browsers running? Well, you click on some row, get PK into session(). Now, say you jump to the next page, on page load (IsPostBack = false), you transfer session value(s) to ViewState, and now you have full operational page - not dependent on Session().

The above is the best solution I have found, and you don't in most cases have to change your code, or introduced some mucked up URL which I find is even more of mess.


问:
Can't add project from local Maven repository as a dependency
I've written a new Maven project and for now let's call it Utils. I've installed it successfully in my local Maven repository. At least the targets clean install print BUILD SUCCESSFUL in the end. I can also find the jar when I navigate to it manually through the Windows Explorer.

Now there's another project called Import I've written that should have Utils as a dependency. When I now add it to the pom with the scope compile and run the goals eclipse:eclipse I'm again getting the message BUILD SUCCESSFUL. But unfortunately, the Utils project isn't in the referenced libraries of Import.

When I want to add it in the POM view of the Maven Eclipse plugin, Utils is also not found. Interestingly, when I specify an erroneous version of Utils, I'm getting a warning when I want to install Import with Maven.

Do you know where I'm wrong?

答:
In order to make the maven eclipse plugin ignore projects in your workspace, you can also set the property useProjectReferences to false.
For example by adding this section to your pom.xml:

```<code><plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-eclipse-plugin</artifactId>
  <version>2.8</version>
  <configuration>
    <useProjectReferences>false</useProjectReferences>
  </configuration>
</plugin>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In order to make the maven eclipse plugin ignore projects in your workspace, you can also set the property useProjectReferences to false.
For example by adding this section to your pom.xml:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-eclipse-plugin</artifactId>
  <version>2.8</version>
  <configuration>
    <useProjectReferences>false</useProjectReferences>
  </configuration>
</plugin>

ContentLicense: CC BY-SA 3.0


问:
Tkinter window not displaying until after program is run
```<code>global window
window = Tk()
window.geometry('300x200')
window.minsize(300,200)
window.maxsize(300,200)
window.configure(bg='black')
window.title("testupdate")

global outputtext
outputtext = tk.StringVar()
outputtext.set("starting window...")

my_label = tk.Label(window, textvariable = outputtext, bg = 'black', fg = 'white', font = 'terminal')
my_label.pack()

class ChangeLabel():
    def __init__(self, text):
        outputtext = tk.StringVar()
        outputtext.set(text)
        my_label.config(textvariable = outputtext)
</code>```

Here's the main code: https://replit.com/@YourPetFinch/textadventure#main.py

I've been trying to make a text adventure game with Tkinter so I can package it all nicely as an app. I created a function that I can call from another file to update a label as the game output so I can keep the GUI setup simple, but I've been having a problem where the window won't show up until the code has finished running. I'm new to tkinter (and honestly not very good at Python in general) so this is probably a stupid question.

答:
That's not how global is used.  The global statement is only used inside a function, to state that you're going to modify a global.  You can't actually make a global that crosses files, but your from gui import * will handle that.

The issue here is understanding event-driven programming.  When you create a window, nothing gets drawn.  All that does is send a number of messages to signal the core.  The messages will not get fetched and dispatched until it gets into the .mainloop().  The main loop processes all the messages and does the drawing, which might queue up more messages.

So, you cannot use time.sleep(2) like that.  As you saw, that will interrupt the process and prevent any drawing from being done.  Instead, you will have to use window.after to request a callback after some number of seconds.  The .mainloop monitors the timers, and will give you a call when time runs out.  You cannot use time.sleep inside an event handler either, for the same reason; your GUI will freeze until your event handler returns.

Body:
global window
window = Tk()
window.geometry('300x200')
window.minsize(300,200)
window.maxsize(300,200)
window.configure(bg='black')
window.title("testupdate")

global outputtext
outputtext = tk.StringVar()
outputtext.set("starting window...")

my_label = tk.Label(window, textvariable = outputtext, bg = 'black', fg = 'white', font = 'terminal')
my_label.pack()

class ChangeLabel():
    def __init__(self, text):
        outputtext = tk.StringVar()
        outputtext.set(text)
        my_label.config(textvariable = outputtext)

Here's the main code: https://replit.com/@YourPetFinch/textadventure#main.py

I've been trying to make a text adventure game with Tkinter so I can package it all nicely as an app. I created a function that I can call from another file to update a label as the game output so I can keep the GUI setup simple, but I've been having a problem where the window won't show up until the code has finished running. I'm new to tkinter (and honestly not very good at Python in general) so this is probably a stupid question.


问:
GLIBC_2.33 not found in raspberry pi python
Error Trace:

ImportError: /lib/arm-linux-gnueabihf/libc.so.6: version `GLIBC_2.33' not found (required by /home/pi/.local/lib/python3.7/site-packages/grpc/_cython/cygrpc.cpython-37m-arm-linux-gnueabihf.so)

Scenario:

I'm using google cloud vision api to detect text in images. The program works fine on laptop but gives the above mentioned error when ran in raspberry pi. I've searched a lot but couldn't find any working solution. I'd really appreciate if any one could let me know how to solve this.

答: Have you tried building glibc 2.33+ alongside the glibc that come in raspberry pi? Something along this answer and comments to use buildroot


问:
Merging datasets based on date column
Hello Stack Community,

I am trying to merge two datasets based on the date column in each.
Below are the snapshots of each dataset, in which, you can clearly see that date column only is formatted as year-month-day, with no specification for hour:minute:second.

dataset 1; snapshot of date column

dataset 2; snapshot of date column

I am merging the two datasets using the following code:

final <- merge(dataset1, dataset2, by.x="close_date", by.y = "date",all.x = TRUE, all.y = TRUE)

Below is another snapshot which shows the result of the code above. As you can see, somehow the hour:minute:second appears in date column which dirsputs the merge.

result of the merge

Is there a way to merge the two columns properly? Maybe someone could suggest the function that would set hh:mm:ss to 00:00:00? Btw, beforehand in the script I have both columns "close_date" from dataset1 and "date" from dataset2 formatted in the same way using the as.POSIXct function.

You can check the R output for head() below:

```<code> head(dataset1) %>%
   select(close_date)

 A tibble: 6 x 1
  close_date
  <dttm>
1 2020-03-01 00:00:00
2 2020-03-02 00:00:00
3 2020-03-03 00:00:00
4 2020-03-04 00:00:00
5 2020-03-05 00:00:00
6 2020-03-06 00:00:00

 head(dataset2) %>%
   select(date)

 A tibble: 6 x 1
  date
  <dttm>
 1 2020-03-01 00:00:00
 2 2020-03-02 00:00:00
 3 2020-03-03 00:00:00
 4 2020-03-04 00:00:00
 5 2020-03-05 00:00:00
 6 2020-03-06 00:00:00
</code>```

答:
With the provided data (in future please provide data directly with dput(head(dataset1)). See here How to make a great R reproducible example

We could define the date format in each dataset before merging using ymd function of lubridate package:

```<code>library(lubridate)

dataset1$close_date <- ymd(dataset1$close_date)
dataset2$date <- ymd(dataset2$date)

final <- merge(dataset1, dataset2, by.x="close_date", by.y = "date",all.x = TRUE, all.y = TRUE)
final
</code>```
```<code>  close_date    coin case_count_world_
1 2020-03-01 BTCUSDT
2 2020-03-02 BTCUSDT
3 2020-03-03 BTCUSDT
4 2020-03-04 BTCUSDT
5 2020-03-05 BTCUSDT
6 2020-03-06    <NA>
7 2020-03-07    <NA>
8 2020-03-08    <NA>
</code>```

data:

```<code>dataset1 <- structure(list(close_date = structure(c(18322, 18323, 18324,
18325, 18326), class = "Date"), coin = c("BTCUSDT", "BTCUSDT",
"BTCUSDT", "BTCUSDT", "BTCUSDT")), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))

dataset2 <- structure(list(date = structure(c(18322, 18323, 18324, 18325,
18326, 18327, 18328, 18329), class = "Date"), case_count_world_ = c("",
"", "", "", "", "", "", "")), row.names = c(NA, -8L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

Title: Merging datasets based on date column

Body:
Hello Stack Community,

I am trying to merge two datasets based on the date column in each.
Below are the snapshots of each dataset, in which, you can clearly see that date column only is formatted as year-month-day, with no specification for hour:minute:second.

dataset 1; snapshot of date column

dataset 2; snapshot of date column

I am merging the two datasets using the following code:

final <- merge(dataset1, dataset2, by.x="close_date", by.y = "date",all.x = TRUE, all.y = TRUE)

Below is another snapshot which shows the result of the code above. As you can see, somehow the hour:minute:second appears in date column which dirsputs the merge.

result of the merge

Is there a way to merge the two columns properly? Maybe someone could suggest the function that would set hh:mm:ss to 00:00:00? Btw, beforehand in the script I have both columns "close_date" from dataset1 and "date" from dataset2 formatted in the same way using the as.POSIXct function.

You can check the R output for head() below:

 head(dataset1) %>%
   select(close_date)

 A tibble: 6 x 1
  close_date
  <dttm>
1 2020-03-01 00:00:00
2 2020-03-02 00:00:00
3 2020-03-03 00:00:00
4 2020-03-04 00:00:00
5 2020-03-05 00:00:00
6 2020-03-06 00:00:00

 head(dataset2) %>%
   select(date)

 A tibble: 6 x 1
  date
  <dttm>
 1 2020-03-01 00:00:00
 2 2020-03-02 00:00:00
 3 2020-03-03 00:00:00
 4 2020-03-04 00:00:00
 5 2020-03-05 00:00:00
 6 2020-03-06 00:00:00

Body:
With the provided data (in future please provide data directly with dput(head(dataset1)). See here How to make a great R reproducible example

We could define the date format in each dataset before merging using ymd function of lubridate package:

library(lubridate)

dataset1$close_date <- ymd(dataset1$close_date)
dataset2$date <- ymd(dataset2$date)

final <- merge(dataset1, dataset2, by.x="close_date", by.y = "date",all.x = TRUE, all.y = TRUE)
final

  close_date    coin case_count_world_
1 2020-03-01 BTCUSDT
2 2020-03-02 BTCUSDT
3 2020-03-03 BTCUSDT
4 2020-03-04 BTCUSDT
5 2020-03-05 BTCUSDT
6 2020-03-06    <NA>
7 2020-03-07    <NA>
8 2020-03-08    <NA>

data:

dataset1 <- structure(list(close_date = structure(c(18322, 18323, 18324,
18325, 18326), class = "Date"), coin = c("BTCUSDT", "BTCUSDT",
"BTCUSDT", "BTCUSDT", "BTCUSDT")), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))

dataset2 <- structure(list(date = structure(c(18322, 18323, 18324, 18325,
18326, 18327, 18328, 18329), class = "Date"), case_count_world_ = c("",
"", "", "", "", "", "", "")), row.names = c(NA, -8L), class = c("tbl_df",
"tbl", "data.frame"))


问:
Bootstrap Dynamically Appended Button Group Not De-Selecting Properly
When I have a Bootstrap 5 button group, the code looks as follows:

  <input id="a" type="radio" class="btn-check" name="btnradio" autocomplete="off">
  Option A
  <input id="b" type="radio" class="btn-check" name="btnradio" autocomplete="off">
  Option B
  <input id="c" type="radio" class="btn-check" name="btnradio" autocomplete="off">
  Option C

```
<p>This works fine if the group is on the page during pageload. However, if I dynamically append the elements after pageload, the buttons stay "active" once clicked and don't toggle properly.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let options = ["D", "E", "F"];

let group = document.createElement('div');
group.className = 'btn-group d-flex justify-content-between m-4';
for (let type of options) {
  let button = document.createElement('input');
  button.id = type;
  button.name = type;
  button.type = 'radio';
  button.className = 'btn-check';
  button.autocomplete = 'off';
  group.append(button);
  let label = document.createElement('label');
  label.htmlFor = type;
  label.className = 'btn btn-outline-primary';
  label.innerHTML = 'Option ' + type;
  group.append(label);
}
document.body.append(group);</code>```

<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css" />

On Pageload

    <input id="a" type="radio" class="btn-check" name="btnradio" autocomplete="off">
    Option A
    <input id="b" type="radio" class="btn-check" name="btnradio" autocomplete="off">
    Option B
    <input id="c" type="radio" class="btn-check" name="btnradio" autocomplete="off">
    Option C

Dynamically Appended

```

Any idea why this might be?

答:
You need the dynamically added buttons to share a name attribute.

If you notice in your onload group they all have the same name attribute: name="btnradio"

Whereas in your dynamically added group, they all have different name attributes:  button.name = type;

Since they all have different names, they're seen as different button groups, so selecting another won't deselect the others.

Body:
When I have a Bootstrap 5 button group, the code looks as follows:

  <input id="a" type="radio" class="btn-check" name="btnradio" autocomplete="off">
  Option A
  <input id="b" type="radio" class="btn-check" name="btnradio" autocomplete="off">
  Option B
  <input id="c" type="radio" class="btn-check" name="btnradio" autocomplete="off">
  Option C

This works fine if the group is on the page during pageload. However, if I dynamically append the elements after pageload, the buttons stay "active" once clicked and don't toggle properly.

let options = ["D", "E", "F"];

let group = document.createElement('div');
group.className = 'btn-group d-flex justify-content-between m-4';
for (let type of options) {
  let button = document.createElement('input');
  button.id = type;
  button.name = type;
  button.type = 'radio';
  button.className = 'btn-check';
  button.autocomplete = 'off';
  group.append(button);
  let label = document.createElement('label');
  label.htmlFor = type;
  label.className = 'btn btn-outline-primary';
  label.innerHTML = 'Option ' + type;
  group.append(label);
}
document.body.append(group);

<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css" />

On Pageload

    <input id="a" type="radio" class="btn-check" name="btnradio" autocomplete="off">
    Option A
    <input id="b" type="radio" class="btn-check" name="btnradio" autocomplete="off">
    Option B
    <input id="c" type="radio" class="btn-check" name="btnradio" autocomplete="off">
    Option C

Dynamically Appended

Any idea why this might be?


问:
How to make an arrayformula count values by row?
I have tried many approaches but I can't seem to figure out a solution to a fairly simple problem with an array formula it seems:

I have a sheet where I get results of individual results of runs of a certain scientific experiment by row.
Next, I'd like to count the occurrence of each output value. Output values can be a number from 1 to 10 so I'd like to individually count how many times the output has been per value.

Also, I'd be then summing up how many individual outputs have been generated in total. So I'd be counting the number of unique outputs within a row.

Now my issue is that when using Arrayformula the way I normally use it it doesn't work because it would count and sum up everything for the whole Matrix specified. However, I just want the current row to be counted. I tried using ROW to get there, but i failed.
I also tried some things like =ARRAYFORMULA(SUMIF(IF(COLUMN(B1:F1),ROW(B2:F5)),ROW(B2:F5),B2:F5)) to understand how to apply the logic, but I fail to get it working as COUNTIF version if itself.

Test Sheet

Any help and ideas would be highly appreciated!

答:
Just an afterthought to this, I think the accepted answer is optimal but I did wonder if you could solve it using only countifs. The answer is yes, but you have to force the array arguments to be the same size and shape otherwise you get the 'array arguments different sizes' error so in J2:

```<code>=ArrayFormula(countifs(B2:F6,mod(sequence(5,10,0),10)+1,row(B2:F6)+B2:F6-B2:F6,int(sequence(5,10,0)/10)+2))
</code>```

Note the the total number of outcomes column gives the number of different outcomes using the formula below in H2:

```<code>=ArrayFormula(mmult(sign(J2:S6),sequence(10,1,1,0)))
</code>```

Body:
Just an afterthought to this, I think the accepted answer is optimal but I did wonder if you could solve it using only countifs. The answer is yes, but you have to force the array arguments to be the same size and shape otherwise you get the 'array arguments different sizes' error so in J2:

=ArrayFormula(countifs(B2:F6,mod(sequence(5,10,0),10)+1,row(B2:F6)+B2:F6-B2:F6,int(sequence(5,10,0)/10)+2))

Note the the total number of outcomes column gives the number of different outcomes using the formula below in H2:

=ArrayFormula(mmult(sign(J2:S6),sequence(10,1,1,0)))


问:
Execute DB2 iSeries Stored Procedure from a SQL 2005 Linked Server
I am trying to execute a stored procedured from a linked database in MS SQL 2005.  The linked database is a db2 database on a iseries server.  I am using the iSeries IBMDASQL service provider.  I am able to query the stored procedure without problems using a simple vbscript and ado.  When I try to execute the same stored procedure in query analyzer on the SQL Server, I never see any results.  Query analyzer always show 'command executed' and when I execute the select * on the temp table, no values appear.  What am I doing wrong?????
Thanks!

--code from query analyzer below--

```<code>DECLARE @emailToAddress         char(50)
DECLARE @emailFromAddress       char(50)

set @emailToAddress = 'customer.service@company.com'
set @emailFromAddress = 'customer@gmail.com'

If Object_ID('tempdb..#tmpResultTbl') Is Not Null
    Drop Table #tmpResultTbl

Create Table #tmpResultTbl
(
OUTPGMID Char(150))

--SET FMTONLY Off
Set NoCount On
Insert Into #tmpResultTbl
EXEC ('CALL abicqual.VP_GETCCEPGMID(?, ?) ', @emailToAddress, @emailFromAddress) AT MAM400

Select * From #tmpResultTbl
</code>```

UPDATED:
Here is the updated code to use openquery... still no luck :(

DECLARE @TSQL varchar(8000)
DECLARE @emailToAddress         varchar(50)
DECLARE @emailFromAddress       varchar(50)
SET @emailToAddress = 'customer.service@company.com'
SET @emailFromAddress = 'customer@gmail.com'
SET @TSQL = 'SELECT * FROM OPENQUERY(MAM400,''CALL abicqual.VP_GETCCEPGMID(''''' + @emailToAddress + ''''', ''''' + @emailFromAddress + '''''' + ')''' + ')'
Print @TSQL
EXEC (@TSQL)

--output below--
SELECT * FROM OPENQUERY(MAM400,'CALL abicqual.VP_GETCCEPGMID(''customer.service@company.com'', ''customer@gmail.com'')')
Msg 7357, Level 16, State 2, Line 1
Cannot process the object "CALL abicqual.VP_GETCCEPGMID('customer.service@company.com', 'customer@gmail.com')". The OLE DB provider "IBMDASQL" for linked server "MAM400" indicates that either the object has no columns or the current user does not have permissions on that object.

答:
I'm using the Microsoft DB2OLEDB provider which is available as part of the Feature Pack for SQL 2005 - April 2006.  It's also part of Host Integration Services.  It hooks into the AS/400 using the DRDA (Oracle style) protocol.

You can download it seperately but it will only install on SQL standard, enterprise or developer (not express).

I also find that building the complete query that I want to run on the DB2/400 box and then wrapping it in a VARCHAR(MAX) string which also includes the "SELECT * FROM OPENQUERY (--linkedservername--,--DB2/400 query with params--)" and then using the sp_execute or EXEC commands returns the best results.

It's even possible to wrap up RPG code within DB2/400 SQL procedures and then call them (with params) from the MS SQL Server and return any result set as a MS SQL table.

Body:
I am trying to execute a stored procedured from a linked database in MS SQL 2005.  The linked database is a db2 database on a iseries server.  I am using the iSeries IBMDASQL service provider.  I am able to query the stored procedure without problems using a simple vbscript and ado.  When I try to execute the same stored procedure in query analyzer on the SQL Server, I never see any results.  Query analyzer always show 'command executed' and when I execute the select * on the temp table, no values appear.  What am I doing wrong?????
Thanks!

--code from query analyzer below--

DECLARE @emailToAddress         char(50)
DECLARE @emailFromAddress       char(50)

set @emailToAddress = 'customer.service@company.com'
set @emailFromAddress = 'customer@gmail.com'

If Object_ID('tempdb..#tmpResultTbl') Is Not Null
    Drop Table #tmpResultTbl

Create Table #tmpResultTbl
(
OUTPGMID Char(150))

--SET FMTONLY Off
Set NoCount On
Insert Into #tmpResultTbl
EXEC ('CALL abicqual.VP_GETCCEPGMID(?, ?) ', @emailToAddress, @emailFromAddress) AT MAM400

Select * From #tmpResultTbl

UPDATED:
Here is the updated code to use openquery... still no luck :(

DECLARE @TSQL varchar(8000)
DECLARE @emailToAddress         varchar(50)
DECLARE @emailFromAddress       varchar(50)
SET @emailToAddress = 'customer.service@company.com'
SET @emailFromAddress = 'customer@gmail.com'
SET @TSQL = 'SELECT * FROM OPENQUERY(MAM400,''CALL abicqual.VP_GETCCEPGMID(''''' + @emailToAddress + ''''', ''''' + @emailFromAddress + '''''' + ')''' + ')'
Print @TSQL
EXEC (@TSQL)

--output below--
SELECT * FROM OPENQUERY(MAM400,'CALL abicqual.VP_GETCCEPGMID(''customer.service@company.com'', ''customer@gmail.com'')')
Msg 7357, Level 16, State 2, Line 1
Cannot process the object "CALL abicqual.VP_GETCCEPGMID('customer.service@company.com', 'customer@gmail.com')". The OLE DB provider "IBMDASQL" for linked server "MAM400" indicates that either the object has no columns or the current user does not have permissions on that object.


问:
Is it necessary to assign null to a local variable at the end of a method, such as List<Student> in Java?
I have define a method to deal with a scheduled task every hour.In my method I have a local variable,Is it necessary to assign null to a local variable at the end of a method? The IDEA tell me:

stuentList=null;

The value null assigned to 'stuentList' is never used, remove redundant assignment.

So I think it is not necessary, is that right?

```<code>private void dealWithStudent(){
  List<Student> stuentList=new  new ArrayList<Student>();
  //query condition and assign to stuentList
  //use stuentList to insert to db
  stuentList=null;
}
</code>```

答: No, once you leave the method the variables defined within that block are descoped and marked for garbage collection.</p>

Body:
I have define a method to deal with a scheduled task every hour.In my method I have a local variable,Is it necessary to assign null to a local variable at the end of a method? The IDEA tell me:

stuentList=null;

The value null assigned to 'stuentList' is never used, remove redundant assignment.

So I think it is not necessary, is that right?

private void dealWithStudent(){
  List<Student> stuentList=new  new ArrayList<Student>();
  //query condition and assign to stuentList
  //use stuentList to insert to db
  stuentList=null;
}


问:
type operator for removing from a tagged union
Is it possible to remove a specific type literal from a tagged union / discriminated union? How would I write such a type?

Given this type:

```<code>type MyUnion = {
  kind: "foo"
  foo: number
} | {
  kind: "bar"
  bar: string
} | {
  kind: "baz"
  baz: boolean
}
</code>```

I want to remove the {kind: "baz", baz: boolean} type literal. Is it possible to write a type RemoveTag<T, K, V> such that:

```<code>type MyUnionWithoutBaz = RemoveTag<MyUnion, "kind", "baz">
</code>```

yields:

```<code>type MyUnionWithoutBaz = {
  kind: "foo"
  foo: number
} | {
  kind: "bar"
  bar: string
}
</code>```

?

答:
You can use the Exclude<T, U> utility type to filter members from out a union T which are not assignable to another type U.  Your RemoveTag type could therefore be written as

```<code>type RemoveTag<T, K extends keyof T, V> =
  Exclude<T, Record<K, V>>
</code>```

depending on your use cases (if the discriminant property is optional then it wouldn't work as is).  For your example, it produces:

```<code>type MyUnionWithoutBaz = RemoveTag<MyUnion, "kind", "baz">
/* type TWithoutBaz = {
    kind: "foo";
    foo: number;
} | {
    kind: "bar";
    bar: string;
} */
</code>```

as desired.

Playground link to code

Body:
Is it possible to remove a specific type literal from a tagged union / discriminated union? How would I write such a type?

Given this type:

type MyUnion = {
  kind: "foo"
  foo: number
} | {
  kind: "bar"
  bar: string
} | {
  kind: "baz"
  baz: boolean
}

I want to remove the {kind: "baz", baz: boolean} type literal. Is it possible to write a type RemoveTag<T, K, V> such that:

type MyUnionWithoutBaz = RemoveTag<MyUnion, "kind", "baz">

yields:

type MyUnionWithoutBaz = {
  kind: "foo"
  foo: number
} | {
  kind: "bar"
  bar: string
}

?

Body:
You can use the Exclude<T, U> utility type to filter members from out a union T which are not assignable to another type U.  Your RemoveTag type could therefore be written as

type RemoveTag<T, K extends keyof T, V> =
  Exclude<T, Record<K, V>>

depending on your use cases (if the discriminant property is optional then it wouldn't work as is).  For your example, it produces:

type MyUnionWithoutBaz = RemoveTag<MyUnion, "kind", "baz">
/* type TWithoutBaz = {
    kind: "foo";
    foo: number;
} | {
    kind: "bar";
    bar: string;
} */

as desired.

Playground link to code


问:
python - convert curl command
I have this curl command.

This works

```<code>curl -O -H "X-Api:3433432" -X GET "https://website.com/file.zip"
</code>```

Trying to figure it out how to convert it to something python understands.

```<code>curl -O -H "X-Api:3433432" -X GET "https://website/file.zip"
</code>```

答:
try using module requests:

```<code>import requests

headers = {
    'X-Api': '3433432',
}

response = requests.get('https://website.com/file.zip', headers=headers)
</code>```

Title: python - convert curl command

Body:
I have this curl command.

This works

curl -O -H "X-Api:3433432" -X GET "https://website.com/file.zip"

Trying to figure it out how to convert it to something python understands.

curl -O -H "X-Api:3433432" -X GET "https://website/file.zip"

Body:
try using module requests:

import requests

headers = {
    'X-Api': '3433432',
}

response = requests.get('https://website.com/file.zip', headers=headers)


问:
Extract boost log attribute values of arbitrary type
There is a logging system with the number of attributes of arbitrary types. The attributes are added by external program(s) using public API (function template). The types aren't known beforehand. The typical way to print out an attribute's value looks like (simplified):

```<code>void print(logging::attribute_value const& attr)
{
    auto val = logging::extract<int>(attr);
    if (val) {
        std::cout << "value: " << val.get() << std::endl;
    }
}
</code>```

In the example above it's already known that the attribute value type is int. What if the expected type isn't known? Of cource, I could write it like:

```<code>typedef boost::mpl::vector<int, std::string> types; // Expected types
logging::value_ref<types> val = logging::extract<types>(attr);
[..]
</code>```

however in that case I have to define all possible types and handle them separately.

Is there a way to print out (or convert to strings) all values regardless of their types, assuming the types overload streaming operator?

UPDATE

Here are some more details:

```<code>// Add new attributes with arbitrary types
template<typename T>
void addProperty(const std::string &key, T && value)
{
    auto attrs = boost::log::core::get()->get_thread_attributes();
    attrs.erase(key);
    attrs.insert(key, boost::log::attributes::make_constant(std::move(value)));
    boost::log::core::get()->set_thread_attributes(attrs);
}
</code>```

and another function that should print the properties' values

```<code>void printProperties()
{
    const auto &attrs = boost::log::core::get()->get_thread_attributes();
    for (auto const &a : attrs) {
        // Print all values. Types aren't known.
    }
}
</code>```

答:
Is there a way to print out (or convert to strings) all values regardless of their types, assuming the types overload streaming operator?

No, Boost.Log doesn't support that, you must know the name and type of the attribute value in order to be able to extract or visit it.

What you could do is maintain your own mapping between attribute names and formatting routines, such as this:

```<code>std::map<
    logging::attribute_name,
    std::function< void(std::ostream&, logging::attribute_value const&) >
> formatters;

template< typename T >
void formatter(std::ostream& strm, logging::attribute_value const& attr)
{
    auto val = logging::extract< T >(attr);
    if (val)
        strm << val.get();
}

template<typename T>
void addProperty(const std::string &key, T && value)
{
    typedef std::remove_cv_t< std::remove_reference_t< T > > value_type;
    logging::attribute_name name(key);
    formatters[name] = &formatter< value_type >;
    boost::log::core::get()->add_thread_attribute(name,
        boost::log::attributes::make_constant(std::forward< T >(value)));
}

void printProperties()
{
    const auto &attrs = boost::log::core::get()->get_thread_attributes();
    for (auto const &a : attrs) {
        auto it = formatters.find(a.first);
        if (it != formatters.end()) {
            std::cout << "value: ";
            it->second(std::cout, a.second.get_value());
            std::cout << std::endl;
        }
    }
}
</code>```

Body:
There is a logging system with the number of attributes of arbitrary types. The attributes are added by external program(s) using public API (function template). The types aren't known beforehand. The typical way to print out an attribute's value looks like (simplified):

void print(logging::attribute_value const& attr)
{
    auto val = logging::extract<int>(attr);
    if (val) {
        std::cout << "value: " << val.get() << std::endl;
    }
}

In the example above it's already known that the attribute value type is int. What if the expected type isn't known? Of cource, I could write it like:

typedef boost::mpl::vector<int, std::string> types; // Expected types
logging::value_ref<types> val = logging::extract<types>(attr);
[..]

however in that case I have to define all possible types and handle them separately.

Is there a way to print out (or convert to strings) all values regardless of their types, assuming the types overload streaming operator?

UPDATE

Here are some more details:

// Add new attributes with arbitrary types
template<typename T>
void addProperty(const std::string &key, T && value)
{
    auto attrs = boost::log::core::get()->get_thread_attributes();
    attrs.erase(key);
    attrs.insert(key, boost::log::attributes::make_constant(std::move(value)));
    boost::log::core::get()->set_thread_attributes(attrs);
}

and another function that should print the properties' values

void printProperties()
{
    const auto &attrs = boost::log::core::get()->get_thread_attributes();
    for (auto const &a : attrs) {
        // Print all values. Types aren't known.
    }
}

Body:
Is there a way to print out (or convert to strings) all values regardless of their types, assuming the types overload streaming operator?

No, Boost.Log doesn't support that, you must know the name and type of the attribute value in order to be able to extract or visit it.

What you could do is maintain your own mapping between attribute names and formatting routines, such as this:

std::map<
    logging::attribute_name,
    std::function< void(std::ostream&, logging::attribute_value const&) >
> formatters;

template< typename T >
void formatter(std::ostream& strm, logging::attribute_value const& attr)
{
    auto val = logging::extract< T >(attr);
    if (val)
        strm << val.get();
}

template<typename T>
void addProperty(const std::string &key, T && value)
{
    typedef std::remove_cv_t< std::remove_reference_t< T > > value_type;
    logging::attribute_name name(key);
    formatters[name] = &formatter< value_type >;
    boost::log::core::get()->add_thread_attribute(name,
        boost::log::attributes::make_constant(std::forward< T >(value)));
}

void printProperties()
{
    const auto &attrs = boost::log::core::get()->get_thread_attributes();
    for (auto const &a : attrs) {
        auto it = formatters.find(a.first);
        if (it != formatters.end()) {
            std::cout << "value: ";
            it->second(std::cout, a.second.get_value());
            std::cout << std::endl;
        }
    }
}


问:
Is it possible for run NUnit against a specific (long) list of tests
I have a list of several thousand NUnit tests that I want to run (generated automatically by another tool). (This is a subset of all of the tests, and changes frequently)

I'd like to be able to run these via NUnit-Console.exe. Unfortunately the /run option only takes a direct list of files which in my case would not fit on a single command line. I'd like it to pickup the list from a filename.

I appreciate that I could use categories, but the list I want to run changes frequently and so I'd prefer not to have to start changing source code.

Does anyone know if there is a clean way to get NUnit to run my specified tests?
(I could break it down into a series of smaller calls to NUnit-console with a full command line, but that's not very elegant)

(If it's not possible, maybe I should add it as an NUnit feature request.)

答:
I see what you're saying, but like you say you can run a single fixture from the command line.

```<code>nunit-console /fixture:namespace.fixture tests.dll
</code>```

How about generating all the tests in the same fixture? Or place them all in the same assembly?

```<code>nunit-console tests.dll
</code>```

Body:
I see what you're saying, but like you say you can run a single fixture from the command line.

nunit-console /fixture:namespace.fixture tests.dll

How about generating all the tests in the same fixture? Or place them all in the same assembly?

nunit-console tests.dll


问:
Execute command with multiple layers of quoting via ssh
I want to execute a docker command on a remote server. The problem is I don't know to escape multiple quotes.

```<code>ret=$(ssh root@server "docker exec nginx bash -c 'cat /etc/nginx/nginx.conf | grep 'ServerName' | cut -d '|' -f1'")
</code>```

I get

```<code>bash:  -f1: command not found
</code>```

答:
Wrap your parameter string with N calls to "$(printf "%q" ...)", for N recursive calls .

```<code>ssh root@server "docker exec nginx bash -c 'cat /etc/nginx/nginx.conf | grep ServerName | cut -d | -f1'"
</code>```

How may recursive calls the above line has? I don't wish to set up docker just for the test, so I may have one of the following wrong:

ssh  - certainly counts

docker - ??

ngix  - ??

bash  - certainly counts

If there are four, then you need four calls to "$(printf "%q "str")", don't forget to add all those " marks

```<code>ssh root@server docker exec nginx bash -c "$(printf "%q" "$(printf "%q" "$(printf "%q" "$(printf "%q" "cat /etc/nginx/nginx.conf | grep ServerName | cut -d | -f1")")")")"
</code>```

Explanation: ssh parses the string like bash -c does, stripping one level of quotes. docker and nginx may also each parse the string (or not). Finally, bash -c parses whatever the previous levels have parsed, and removes the final level of quotes. exec does not parse the strings, it simply passes them verbatim to the next level.

Another solution is to put the line, that you want bash to execute, into a script. Then you can simply invoke the script without all this quoting insanity.

```<code>#!/bin/bash
< /etc/nginx/nginx.conf grep ServerName | cut -d | -f1
</code>```

Body:
I want to execute a docker command on a remote server. The problem is I don't know to escape multiple quotes.

ret=$(ssh root@server "docker exec nginx bash -c 'cat /etc/nginx/nginx.conf | grep 'ServerName' | cut -d '|' -f1'")

I get

bash:  -f1: command not found

Body:
Wrap your parameter string with N calls to "$(printf "%q" ...)", for N recursive calls .

ssh root@server "docker exec nginx bash -c 'cat /etc/nginx/nginx.conf | grep ServerName | cut -d | -f1'"

How may recursive calls the above line has? I don't wish to set up docker just for the test, so I may have one of the following wrong:

ssh  - certainly counts

docker - ??

ngix  - ??

bash  - certainly counts

If there are four, then you need four calls to "$(printf "%q "str")", don't forget to add all those " marks

ssh root@server docker exec nginx bash -c "$(printf "%q" "$(printf "%q" "$(printf "%q" "$(printf "%q" "cat /etc/nginx/nginx.conf | grep ServerName | cut -d | -f1")")")")"

Explanation: ssh parses the string like bash -c does, stripping one level of quotes. docker and nginx may also each parse the string (or not). Finally, bash -c parses whatever the previous levels have parsed, and removes the final level of quotes. exec does not parse the strings, it simply passes them verbatim to the next level.

Another solution is to put the line, that you want bash to execute, into a script. Then you can simply invoke the script without all this quoting insanity.

#!/bin/bash
< /etc/nginx/nginx.conf grep ServerName | cut -d | -f1


问:
Android Emulator Not clickable on Top
I'm using:

```<code>Mac OS High Sierra 10.13.4
Android Studio 3.1.1
Nexus 5X emulator with API level 27
</code>```

On its top, the emulator is not clickable or draggable, I just cannot drop down the notification bar or click the back button in app. This is not happening at the bottom of the emulator...anyone experiencing the same issue? I don't know if this could be useful, but I'm using a double monitor (macbook + led panel).

EDIT: I think there's a problem with smaller devices. same problem with Pixel 2 (NOT XL).
Works fine with Pixel 2 XL.

EDIT 2: Pixel 2 works fine on API level 25 (Nougat).

答:
I thought that experienced exactly this issue with the Pixel 4 API 31 emulator running in AndroidStudio 2021.1.1 on Ubuntu today; however, it turned out to be user expectations of older APIs combined with a barely-readable notification icon in the bar.

I wanted to open the device settings; my own devices are older Android 9 and to do this, I just tap the notification bar, it expands, and I click on the gear icon which immediately appears in the notification bar area once the pane expands to show quick settings.

The API 31 UI acts differently - first of all, I thought there was a permanent settings gear already in the notification bar.  I thought that was odd, but, okay, I'll click it to open... turns out that this is not the case: it's an actual notification icon that looks like a settings gear from the Google Setup program trying to complete the initial setup on the phone (this was a new emulator).  Tapping it did nothing, of course, but was frustrating because I thought it was a setting gear.  Strike one, and had me googling for "Emulator top bar not responsive" leading me here.

Secondly, clicking to "tap" on the notification bar in API 31 doesn't immediately expand it like it does on my API 28-based Note 8: I had to "click and swipe" down (awkward with the mouse) to open notifications.  And in API 31, even this is not sufficient to see the actual phone settings gear either!  You have to swipe down one more time to further expand the notification pane and finally you can see the gear to open settings.

These two things combined to make me believe that the emulator was non-responsive when clicking the notification bar at the top.

I hope this helps someone else realize what might be happening - took me more time to write this up than the actual "problem" cost me, but I was so annoyed at this "broken" emulator which wasn't opening the settings for me that I had to write it up!

Title: Android Emulator Not clickable on Top

Body:
I'm using:

Mac OS High Sierra 10.13.4
Android Studio 3.1.1
Nexus 5X emulator with API level 27

On its top, the emulator is not clickable or draggable, I just cannot drop down the notification bar or click the back button in app. This is not happening at the bottom of the emulator...anyone experiencing the same issue? I don't know if this could be useful, but I'm using a double monitor (macbook + led panel).

EDIT: I think there's a problem with smaller devices. same problem with Pixel 2 (NOT XL).
Works fine with Pixel 2 XL.

EDIT 2: Pixel 2 works fine on API level 25 (Nougat).


问:
Offline services in mapbox react native
Is mapbox library in react native can do some offline services for routing or navigation in react native or not?
Please Help me, Thanks</p>

答:
I am having a similar issue at the moment too. So far I have learned that, yes React Native supports Mapbox (although tricky to set up)

I am unsure about Navigation but it does offline manager for static maps and mapbox studio projects.

https://github.com/nitaliano/react-native-mapbox-gl/blob/master/docs/OfflineManager.md

Title: Offline services in mapbox react native


问:
R: How to repeatedly subtract specific columns from different series of columns, and output to a new dataframe?
I have a dataframe in wide format, and I want to subtract specific columns from different series of columns. Ideally I'd like the results to be in a new dataframe.

For example:
From this sample dataframe (dfOld), I would like columns A, B and C to each subtract D,  and columns E, F and G to each subtract column H. In the real dataset, this keeps going and needs to be iterated.

image of dfOld as table

Sample Data:

```<code>dfOld <- data.frame(ID = c(1,2,3,4,5,6,7,8,9,10), A = c(2, 3, 4,5,4,6,7,1,9,12), B = c(3, 4, 5,2,4,5,1,7,0,8), C = c(5, 6, 7,2,4,1,5,4,6,13), D = c(68, 7, 8,2,1,5,7,9,78,7), E = c(2, 3, 42,5,4,6,7,1,9,12), F = c(37, 4, 5,2,48,5,1,7,60,8), G = c(5, 6, 7,2,4,1,5,4,6,13), H = c(35, 7, 8,2,1,5,7,9,78,7))
</code>```

The results would ideally be in a new dataframe, with columns that have values and names for A-D, B-D, C-D, E-H, F-H, G-H, and look like this:

image of dfNew as table

In Excel, the formula would be "=B2-$E2" dragged down the rows, and across 3 columns, and then repeated again for "F2-$I2" etc, using the "$" sign to lock the column

In R, I've only been able to do this manually, kind of like the answer previously posted for a similar question (Subtracting two columns to give a new column in R)

```<code>dfOld$A-D<-(dfOld$A-dfOld$D)
dfOld$B-D<-(dfOld$B-dfOld$D)
dfOld$C-D<-(dfOld$C-dfOld$D)
dfOld$E-H<-(dfOld$E-dfOld$H)
dfOld$F-H<-(dfOld$F-dfOld$H)
dfOld$G-H<-(dfOld$G-dfOld$H)
</code>```

And then separated the new columns out into a new dataset.

However, this obviously isn't scalable for my much larger dataset, and I'd really like to learn how else to do this kind of operation that's so easy in Excel(although still not scalable for large datasets).

Part of the answer may already be here: Subtract a column in a dataframe from many columns in R
But this answer (an several other similar ones) changes the values in the same dataframe, and the columns keep the same names.
I haven't been able to adapt it so that the new values have new columns, with new names (and ideally in a new dataframe)

Another part of the answer may be here:
Iterative function to subtract columns from a specific column in a dataframe and have the values appear in a new column
These answers put the subtracted results in new columns with new names, but every column in this dataframe subtracts values of every other column (A,B,C,D,E,F,G,H each minus C). And I can't seem to adapt it so that it works over specific series of columns (A, B, C each minus D, then E, F, G each minus H, etc.)

Thanks in advance for your help.

答:
Probably others have better ways - but here is one possibility.

load two libraries and set dfOld to data.table

```<code>library(data.table)
library(magrittr)
setDT(dfOld)
</code>```

get information about the columns, and make into a list.

```<code>lv = names(dfOld)[-1][seq(1,ncol(dfOld)-1)%%4>0]
lv = split(lv, ceiling(seq_along(lv)/3))
names(lv) = names(dfOld)[-1][seq(1,ncol(dfOld)-1)%%4==0]
</code>```

lv looks like this:

```<code>> lv
$D
[1] "A" "B" "C"

$H
[1] "E" "F" "G"
</code>```

This is a bit convoluted, but basically, I'm taking each of the elements of the lv list, and I'm reshaping columns from dfOld, so I can do all subtractions at once. Then I'm retaining only the variables I need, and binding each of the resulting list of data.tables into a single datatable using rbindlist

```<code>res =rbindlist(lapply(names(lv), function(x)  {
  melt(dfOld,id=c("ID", x),measure.vars = lv[[x]]) %>%
    .[,`:=`(nc=value-get(x),variable=paste0(variable,"-",x))] %>%
    .[,.(ID,variable,nc)]
}))
</code>```

Last step is simple - just dcast back

```<code>dcast(res,ID~variable, value.var="nc")
</code>```

Output

```<code>    ID A-D B-D C-D E-H F-H G-H
 1:  1 -66 -65 -63 -33   2 -30
 2:  2  -4  -3  -1  -4  -3  -1
 3:  3  -4  -3  -1  34  -3  -1
 4:  4   3   0   0   3   0   0
 5:  5   3   3   3   3  47   3
 6:  6   1   0  -4   1   0  -4
 7:  7   0  -6  -2   0  -6  -2
 8:  8  -8  -2  -5  -8  -2  -5
 9:  9 -69 -78 -72 -69 -18 -72
10: 10   5   1   6   5   1   6
</code>```

Body:
I have a dataframe in wide format, and I want to subtract specific columns from different series of columns. Ideally I'd like the results to be in a new dataframe.

For example:
From this sample dataframe (dfOld), I would like columns A, B and C to each subtract D,  and columns E, F and G to each subtract column H. In the real dataset, this keeps going and needs to be iterated.

image of dfOld as table

Sample Data:

dfOld <- data.frame(ID = c(1,2,3,4,5,6,7,8,9,10), A = c(2, 3, 4,5,4,6,7,1,9,12), B = c(3, 4, 5,2,4,5,1,7,0,8), C = c(5, 6, 7,2,4,1,5,4,6,13), D = c(68, 7, 8,2,1,5,7,9,78,7), E = c(2, 3, 42,5,4,6,7,1,9,12), F = c(37, 4, 5,2,48,5,1,7,60,8), G = c(5, 6, 7,2,4,1,5,4,6,13), H = c(35, 7, 8,2,1,5,7,9,78,7))

The results would ideally be in a new dataframe, with columns that have values and names for A-D, B-D, C-D, E-H, F-H, G-H, and look like this:

image of dfNew as table

In Excel, the formula would be "=B2-$E2" dragged down the rows, and across 3 columns, and then repeated again for "F2-$I2" etc, using the "$" sign to lock the column

In R, I've only been able to do this manually, kind of like the answer previously posted for a similar question (Subtracting two columns to give a new column in R)

dfOld$A-D<-(dfOld$A-dfOld$D)
dfOld$B-D<-(dfOld$B-dfOld$D)
dfOld$C-D<-(dfOld$C-dfOld$D)
dfOld$E-H<-(dfOld$E-dfOld$H)
dfOld$F-H<-(dfOld$F-dfOld$H)
dfOld$G-H<-(dfOld$G-dfOld$H)

And then separated the new columns out into a new dataset.

However, this obviously isn't scalable for my much larger dataset, and I'd really like to learn how else to do this kind of operation that's so easy in Excel(although still not scalable for large datasets).

Part of the answer may already be here: Subtract a column in a dataframe from many columns in R
But this answer (an several other similar ones) changes the values in the same dataframe, and the columns keep the same names.
I haven't been able to adapt it so that the new values have new columns, with new names (and ideally in a new dataframe)

Another part of the answer may be here:
Iterative function to subtract columns from a specific column in a dataframe and have the values appear in a new column
These answers put the subtracted results in new columns with new names, but every column in this dataframe subtracts values of every other column (A,B,C,D,E,F,G,H each minus C). And I can't seem to adapt it so that it works over specific series of columns (A, B, C each minus D, then E, F, G each minus H, etc.)

Thanks in advance for your help.

Body:
Probably others have better ways - but here is one possibility.

load two libraries and set dfOld to data.table

library(data.table)
library(magrittr)
setDT(dfOld)

get information about the columns, and make into a list.

lv = names(dfOld)[-1][seq(1,ncol(dfOld)-1)%%4>0]
lv = split(lv, ceiling(seq_along(lv)/3))
names(lv) = names(dfOld)[-1][seq(1,ncol(dfOld)-1)%%4==0]

lv looks like this:

> lv
$D
[1] "A" "B" "C"

$H
[1] "E" "F" "G"

This is a bit convoluted, but basically, I'm taking each of the elements of the lv list, and I'm reshaping columns from dfOld, so I can do all subtractions at once. Then I'm retaining only the variables I need, and binding each of the resulting list of data.tables into a single datatable using rbindlist

res =rbindlist(lapply(names(lv), function(x)  {
  melt(dfOld,id=c("ID", x),measure.vars = lv[[x]]) %>%
    .[,`:=`(nc=value-get(x),variable=paste0(variable,"-",x))] %>%
    .[,.(ID,variable,nc)]
}))

Last step is simple - just dcast back

dcast(res,ID~variable, value.var="nc")

Output

    ID A-D B-D C-D E-H F-H G-H
 1:  1 -66 -65 -63 -33   2 -30
 2:  2  -4  -3  -1  -4  -3  -1
 3:  3  -4  -3  -1  34  -3  -1
 4:  4   3   0   0   3   0   0
 5:  5   3   3   3   3  47   3
 6:  6   1   0  -4   1   0  -4
 7:  7   0  -6  -2   0  -6  -2
 8:  8  -8  -2  -5  -8  -2  -5
 9:  9 -69 -78 -72 -69 -18 -72
10: 10   5   1   6   5   1   6


问:
How to prevent CKEditor replacing spaces with  ?
I'm facing an issue with CKEditor 4, I need to have an output without any html entity so I added config.entities = false; in my config, but some   appear when

an inline tag is inserted: the space before is replaced with

text is pasted: every space is replaced with   even with config.forcePasteAsPlainText = true;

You can check that on any demo by typing

test test

eg.

Do you know how I can prevent this behaviour?

Thanks!

答:
Remove all   but not <tag> </tag> with Javascript Regexp

This is especially helpful with CKEditor as it creates lines like

, which you might want to keep.

Background: I first tried to make a one-liner Javascript using lookaround assertions. It seems you can't chain them, at least not yet. My first approach was unsuccesful:

return text.replace(/(?<!\>) (?!<\/)/gi, " ")

// Removes   but not

// It works, but does not remove `<p>  blah  </p>`.
```
<p><strong>Here is my updated working one-liner code:</strong></p>
<pre class="lang-js prettyprint-override"><code>return text.replace(/(?<!\>\s.)( (?!<\/)|(?<!\>) <\/p>)/gi, " ")
</code>```

This works as intended. You can test it here.

However, this is a shady practise as lookarounds are not fully supported by some browsers.

Read more about Assertions.

What I ended up using in my production code:
I ended up doing a bit hacky approach with multiple replace(). This should work on all browsers.

.trim()                                                            // Remove whitespaces
.replace(/\u00a0/g, " ")                                           // Remove unicode non-breaking space
.replace(/((<\w+>)\s*( )\s*(<\/\w+>))/gi, "$2$4")  // Replace empty nbsp tags with BOOM
.replace(/ /gi, " ")                                          // remove all
.replace(/((<\w+>)\s*()\s*(<\/\w+>))/gi, "$2 $4")  // Replace BOOM back to empty tags
```

If you have a better suggestion, I would be happy to hear .

Body:
Remove all &nbsp; but not <tag>&nbsp;</tag> with Javascript Regexp

This is especially helpful with CKEditor as it creates lines like <p>&nbsp;</p>, which you might want to keep.

Background: I first tried to make a one-liner Javascript using lookaround assertions. It seems you can't chain them, at least not yet. My first approach was unsuccesful:

return text.replace(/(?<!\>)&nbsp;(?!<\/)/gi, " ")

// Removes &nbsp; but not <p>&nbsp;</p>
// It works, but does not remove `<p>&nbsp; blah &nbsp;</p>`.

Here is my updated working one-liner code:

return text.replace(/(?<!\>\s.)(&nbsp;(?!<\/)|(?<!\>)&nbsp;<\/p>)/gi, " ")

This works as intended. You can test it here.

However, this is a shady practise as lookarounds are not fully supported by some browsers.

Read more about Assertions.

What I ended up using in my production code:
I ended up doing a bit hacky approach with multiple replace(). This should work on all browsers.

.trim()                                                            // Remove whitespaces
.replace(/\u00a0/g, " ")                                           // Remove unicode non-breaking space
.replace(/((<\w+>)\s*(&nbsp;)\s*(<\/\w+>))/gi, "$2<!--BOOM-->$4")  // Replace empty nbsp tags with BOOM
.replace(/&nbsp;/gi, " ")                                          // remove all &nbsp;
.replace(/((<\w+>)\s*(<!--BOOM-->)\s*(<\/\w+>))/gi, "$2&nbsp;$4")  // Replace BOOM back to empty tags

If you have a better suggestion, I would be happy to hear .


问:
Is there a way to GET lists of course work for ALL courses in one request (Method: courses.courseWork.list Google Classroom API)
Is there a way to GET lists of course work for ALL courses in one request (Method: courses.courseWork.list Google Classroom API).
Right now, it works only by one single courseId per request
Thank you

```<code>function execute() {
return gapi.client.classroom.courses.courseWork.list({
"courseId": "7777777777777",
"courseWorkStates": [
"PUBLISHED"
]
})
</code>```

答:
It is not possible, it needs the 'courseId' parameter to return the data. A workaround would be listing all the courses with 'Method: courses.list' [1], get the Id's for all courses and create a cycle so it gets the course work for all courses.

[1] https://developers.google.com/classroom/reference/rest/v1/courses/list

Body:
Is there a way to GET lists of course work for ALL courses in one request (Method: courses.courseWork.list Google Classroom API).
Right now, it works only by one single courseId per request
Thank you

function execute() {
return gapi.client.classroom.courses.courseWork.list({
"courseId": "7777777777777",
"courseWorkStates": [
"PUBLISHED"
]
})