问:
Rails 7 How to import pinned js modules in action's views / partial layouts?
i tried to import a pinned js module in an action view, but got the error related to es-module-shims

# config/importmap.rb
...
pin_all_from "app/javascript/zzz", under: "zzz"

# layouts/application.html.erb
...
<%= javascript_importmap_tags %>

# zzz/show.html.erb
...
<%= javascript_importmap_tags("zzz") %>
...
```
<p>then when load the show action page, sometime i got the bellow error:</p>
```Error: Unable to resolve specifier 'application' from ... es-module-shims.js:769

Error: Unable to resolve specifier 'zzz' from ... es-module-shims.js:769
```

It looks like the async loading es-module-shims.js file be broken. If i change to javascript_importmap_tags("zzz", shim: false), it'll be ok, but we need es-module-shims for support non-Chromium browsers, right ?

so How could i import pinned js modules in action's views (or partial layouts) ?

Thanks !!!

答:
According to the javascript_importmap_tags method code, this method will setup all script tags needed to use an importmap-powered entrypoint (which defaults to application.js) which include es-module-shims.js loading script, so if i call it again on action's view then there're duplicate scripts and this leads to unstable loading es-module-shims.js.

# https://github.com/rails/importmap-rails../importmap_tags_helper.rb
  def javascript_importmap_tags(entry_point = "application", shim: true)
    safe_join [
      javascript_inline_importmap_tag,
      javascript_importmap_module_preload_tags,
      (javascript_importmap_shim_nonce_configuration_tag if shim),
      (javascript_importmap_shim_tag if shim),
      javascript_import_module_tag(entry_point)
    ].compact, "\n"
  end
```
<p>Actually i just only need call the method <code>javascript_import_module_tag</code> which will generate a script import my module:</p>
<pre class="lang-rb prettyprint-override"><code># layouts/application.html.erb
...
<%= javascript_importmap_tags %> # Set up needed script and import `application`

# zzz/show.html.erb
...
<%= javascript_import_module_tag("zzz") %> # only import `zzz` module
</code>```

Now i don't get loading es-module-shims.js errors anymore.

Body:
i tried to import a pinned js module in an action view, but got the error related to es-module-shims

# config/importmap.rb
...
pin_all_from "app/javascript/zzz", under: "zzz"

# layouts/application.html.erb
...
<%= javascript_importmap_tags %>

# zzz/show.html.erb
...
<%= javascript_importmap_tags("zzz") %>
...

then when load the show action page, sometime i got the bellow error:

Error: Unable to resolve specifier 'application' from ... es-module-shims.js:769

Error: Unable to resolve specifier 'zzz' from ... es-module-shims.js:769

It looks like the async loading es-module-shims.js file be broken. If i change to javascript_importmap_tags("zzz", shim: false), it'll be ok, but we need es-module-shims for support non-Chromium browsers, right ?

so How could i import pinned js modules in action's views (or partial layouts) ?

Thanks !!!

Body:
According to the javascript_importmap_tags method code, this method will setup all script tags needed to use an importmap-powered entrypoint (which defaults to application.js) which include es-module-shims.js loading script, so if i call it again on action's view then there're duplicate scripts and this leads to unstable loading es-module-shims.js.

# https://github.com/rails/importmap-rails../importmap_tags_helper.rb
  def javascript_importmap_tags(entry_point = "application", shim: true)
    safe_join [
      javascript_inline_importmap_tag,
      javascript_importmap_module_preload_tags,
      (javascript_importmap_shim_nonce_configuration_tag if shim),
      (javascript_importmap_shim_tag if shim),
      javascript_import_module_tag(entry_point)
    ].compact, "\n"
  end

Actually i just only need call the method javascript_import_module_tag which will generate a script import my module:

# layouts/application.html.erb
...
<%= javascript_importmap_tags %> # Set up needed script and import `application`

# zzz/show.html.erb
...
<%= javascript_import_module_tag("zzz") %> # only import `zzz` module

Now i don't get loading es-module-shims.js errors anymore.


来源: stackexchange

问:
Embed a web browser in a cross platform Gtk application
I need to embed a very simple browser ( can parse HTML, and JS Ext ) in a Gtk Widget hopefully in gtkmm. I looked into gtkmozembed, but the c++ wrapper is very out dated, so I tried to just write it in C, but I'm already committed to Gtk+ 3.0, and gtkmozembed doesn't work with Gtk+ 3.0. Is there a way to just extend Gtk::Widget and put a gecko parser in it? Can't really find any gecko documentation, I keep getting redirected to gtkmozembed.

Any ideas/suggestions would be greatly appreciated.

Edit:
@Mark After I tried using Webkitgtk, I get the following output and the application crashes.

```<code>** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_foreach: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_insert_internal: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed
*** NSPlugin Wrapper *** ERROR: no valid NPP -> PluginInstance mapping found

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed
*** NSPlugin Wrapper *** ERROR: no valid NPP -> PluginInstance mapping found

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_insert_internal: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_insert_internal: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_find: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_insert_internal: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed
*** NSPlugin Wrapper *** ERROR: no valid NPP -> PluginInstance mapping found

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed
ttocui_gtk: /build/buildd/nspluginwrapper-1.2.2/src/npw-rpc.c:1225: do_recv_NPObject: Assertion `npobj != ((void *)0)' failed.
*** NSPlugin Viewer  *** ERROR: NPN_GetProperty() wait for reply: Connection reset by peer
*** NSPlugin Viewer  *** WARNING:(/build/buildd/nspluginwrapper-1.2.2/src/npw-viewer.c:898):invoke_NPN_GetValue: assertion failed: (rpc_method_invoke_possible(g_rpc_connection))
Aborted
*** NSPlugin Viewer  *** WARNING: unhandled variable 18 (<unknown variable>) in NPN_GetValue()
*** NSPlugin Viewer  *** WARNING:(/build/buildd/nspluginwrapper-1.2.2/src/npw-viewer.c:898):invoke_NPN_GetValue: assertion failed: (rpc_method_invoke_possible(g_rpc_connection))
</code>```

The .js file is included in the head tag of my html pages...

```<code><link rel="stylesheet" type="text/css" href="/ext3.2.1/resources/css/ext-all.css">
<link rel="stylesheet" type="text/css" href="/ext3.2.1/resources/css/xtheme-access.css"/>

<script type="text/javascript" src="/ext3.2.1/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="/ext3.2.1/ext-all-debug.js"></script>
</code>```

答:
As an addendum to @ptomato's answer.  WebKitGTK is the way to go.  I do not know of a gtkmm/C++ wrapper for it, but I am currently using it from a gtkmm project quite successfully (luckily, gtkmm/C++ allows you to mix in the C gtk quite easily):

```<code>WebKitWebView* pWebKitView = WEBKIT_WEB_VIEW (webkit_web_view_new ());
gtk_container_add (GTK_CONTAINER (pSomeContainer->gobj()), GTK_WIDGET (pWebKitView));
</code>```

And off you go...

ContentLicense: CC BY-SA 3.0

Body:
I need to embed a very simple browser ( can parse HTML, and JS Ext ) in a Gtk Widget hopefully in gtkmm. I looked into gtkmozembed, but the c++ wrapper is very out dated, so I tried to just write it in C, but I'm already committed to Gtk+ 3.0, and gtkmozembed doesn't work with Gtk+ 3.0. Is there a way to just extend Gtk::Widget and put a gecko parser in it? Can't really find any gecko documentation, I keep getting redirected to gtkmozembed.

Any ideas/suggestions would be greatly appreciated.

Edit:
@Mark After I tried using Webkitgtk, I get the following output and the application crashes.

** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16360): DEBUG: NP_Initialize succeeded

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_foreach: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_insert_internal: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed
*** NSPlugin Wrapper *** ERROR: no valid NPP -> PluginInstance mapping found

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed
*** NSPlugin Wrapper *** ERROR: no valid NPP -> PluginInstance mapping found

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_insert_internal: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_insert_internal: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_find: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_insert_internal: assertion `hash_table != NULL' failed

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed
*** NSPlugin Wrapper *** ERROR: no valid NPP -> PluginInstance mapping found

(ttocui_gtk:16360): GLib-CRITICAL **: g_hash_table_lookup: assertion `hash_table != NULL' failed
ttocui_gtk: /build/buildd/nspluginwrapper-1.2.2/src/npw-rpc.c:1225: do_recv_NPObject: Assertion `npobj != ((void *)0)' failed.
*** NSPlugin Viewer  *** ERROR: NPN_GetProperty() wait for reply: Connection reset by peer
*** NSPlugin Viewer  *** WARNING:(/build/buildd/nspluginwrapper-1.2.2/src/npw-viewer.c:898):invoke_NPN_GetValue: assertion failed: (rpc_method_invoke_possible(g_rpc_connection))
Aborted
*** NSPlugin Viewer  *** WARNING: unhandled variable 18 (<unknown variable>) in NPN_GetValue()
*** NSPlugin Viewer  *** WARNING:(/build/buildd/nspluginwrapper-1.2.2/src/npw-viewer.c:898):invoke_NPN_GetValue: assertion failed: (rpc_method_invoke_possible(g_rpc_connection))

The .js file is included in the head tag of my html pages...

<link rel="stylesheet" type="text/css" href="/ext3.2.1/resources/css/ext-all.css">
<link rel="stylesheet" type="text/css" href="/ext3.2.1/resources/css/xtheme-access.css"/>

Body:
As an addendum to @ptomato's answer.  WebKitGTK is the way to go.  I do not know of a gtkmm/C++ wrapper for it, but I am currently using it from a gtkmm project quite successfully (luckily, gtkmm/C++ allows you to mix in the C gtk quite easily):

WebKitWebView* pWebKitView = WEBKIT_WEB_VIEW (webkit_web_view_new ());
gtk_container_add (GTK_CONTAINER (pSomeContainer->gobj()), GTK_WIDGET (pWebKitView));

And off you go...


问:
How can i fetch thumbnail or cover art from audio files in flutter?
Thumbnail or cover art of an music player is an important part. I try many audio packages from the pub.dev  but these packages do not support the thumbnail extraction or meta extraction from music files. In asset_audio_player package we can add metas externally but we could not fetch the meta from music files. My question is there is any way that i can extract the thumbnail or meta from music files.</p>

答: You could try flutter_media_metada for this, try to restrict the null, sometimes songs has no artwork.</p>

ContentLicense: CC BY-SA 4.0


问:
Detect http only cookie cleared or expired
In my application authentication done by a third party service, that service generate a token cookie and save it on client side.

Problem: When user accessing the application, during accessing some user clear the site specific cookies in chrome browser and sometimes cookie session expired but there is no way to identify this in application. please suggest me how can I identify this that cookie is removed or expired.

Tried approach: I tried to get cookie by document.cookie but it's not returning that authentication cookie.

答:
Your token cookie is httpOnly due to security reasons, because this kind of cookies are hidden to the code to prevent any third party lib to steal sessions in your application.

So you should not check if the cookie exists or not as a regular one, instead your identity service should provide you an endpoint where you could do a call (that will contain your httpOnly token cookie), and which will responde accordingly depending on the state of your token/session.


问:
Find one character in a string of any number of characters and return True or False
I'm having trouble returning the correct Boolean value back after checking for all occurrences of a single letter in a string of any length. If the single letter is in the string, I want it to return True. If the single letter is not in the string, I want it to return False. However, when I run it in python, it is just returning back only True or only False and is not accurately checking if the single letter is in the word.</p>
```<code>def contains_char(any_length: str, single_character: str) -> bool:
    """A way to find one character in a word of any length."""
    assert len(single_character) == 1
    any_length = ""
    single_character = ""
    check_character: bool = False
    i: int = 0
    while i < len(any_length):
        if any_length[i] == single_character[0]:
            check_character is True
        else:
            i += 1
            alternative_char: int = 0
            while check_character is not True and i < len(any_length):
                if any_length[alternative_char] == single_character[0]:
                    check_character == True
                else:
                    alternative_char += 1
    if check_character is not False:
        return False
    else:
        return True
</code>```

答:
```<code>def contains_char(string,character):
    if character in string:
        return True
    return False
</code>```

Body:
I'm having trouble returning the correct Boolean value back after checking for all occurrences of a single letter in a string of any length. If the single letter is in the string, I want it to return True. If the single letter is not in the string, I want it to return False. However, when I run it in python, it is just returning back only True or only False and is not accurately checking if the single letter is in the word.

def contains_char(any_length: str, single_character: str) -> bool:
    """A way to find one character in a word of any length."""
    assert len(single_character) == 1
    any_length = ""
    single_character = ""
    check_character: bool = False
    i: int = 0
    while i < len(any_length):
        if any_length[i] == single_character[0]:
            check_character is True
        else:
            i += 1
            alternative_char: int = 0
            while check_character is not True and i < len(any_length):
                if any_length[alternative_char] == single_character[0]:
                    check_character == True
                else:
                    alternative_char += 1
    if check_character is not False:
        return False
    else:
        return True


问:
Calculate pairwise similarity of strings in column using tidyverse
If I have a df with the following columns and rows:

row
text

1
This sentence is very similar to the next sentence

2
This sentence is not very similar to the next sentence

3
You can't sneeze with your eyes opened

...
...

How can I apply a function that check for every value in the text column whether there is a similar sentence in another row of that column? What I want to do is to then remove rows in which the value of the text column is too similar. For example, how can I ensure that no cell in the column is more than 30, 40, or 80% similar to another string in that same column?

What I want to end up with is the following:

row
text

1
This sentence is very similar to the next sentence

3
You can't sneeze with your eyes opened

...
...

答:
Here's a solution based on calculating the Levenshtein distance between strings using the levenshteinSim function from the RecordLinkage package, which is reasonably fast:

library(RecordLinkage)

exclude_similar <- function(text, similarity = 0.8) {

 sim_mat <- asplit(outer(text, text, levenshteinSim), 1)
 exclude <- unlist(lapply(seq_along(sim_mat), function(x) {
         y <- which(sim_mat[[x]] > similarity)
         y[y > x]
         }
        ))
 answer <- rep(TRUE, length(text))
 answer[exclude] <- FALSE
 return(answer)
}
```
<p>You would use the function like this:</p>
<pre class="lang-r prettyprint-override"><code>df[exclude_similar(df$text, similarity = 0.8), ]
#>   row                                               text
#> 1   1 This sentence is very similar to the next sentence
#> 3   3             You can't sneeze with your eyes opened

df[exclude_similar(df$text, similarity = 0.1), ]
#>   row                                               text
#> 1   1 This sentence is very similar to the next sentence

df[exclude_similar(df$text, similarity = 0.95), ]
#>   row                                                   text
#> 1   1     This sentence is very similar to the next sentence
#> 2   2 This sentence is not very similar to the next sentence
#> 3   3                 You can't sneeze with your eyes opened
</code>```

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

Data used

df <- read.table(text = "row    text
1   \"This sentence is very similar to the next sentence\"
2   \"This sentence is not very similar to the next sentence\"
3   \"You can't sneeze with your eyes opened\"", header = TRUE)
```

Body:
Here's a solution based on calculating the Levenshtein distance between strings using the levenshteinSim function from the RecordLinkage package, which is reasonably fast:

library(RecordLinkage)

exclude_similar <- function(text, similarity = 0.8) {

 sim_mat <- asplit(outer(text, text, levenshteinSim), 1)
 exclude <- unlist(lapply(seq_along(sim_mat), function(x) {
         y <- which(sim_mat[[x]] > similarity)
         y[y > x]
         }
        ))
 answer <- rep(TRUE, length(text))
 answer[exclude] <- FALSE
 return(answer)
}

You would use the function like this:

df[exclude_similar(df$text, similarity = 0.8), ]
#>   row                                               text
#> 1   1 This sentence is very similar to the next sentence
#> 3   3             You can't sneeze with your eyes opened

df[exclude_similar(df$text, similarity = 0.1), ]
#>   row                                               text
#> 1   1 This sentence is very similar to the next sentence

df[exclude_similar(df$text, similarity = 0.95), ]
#>   row                                                   text
#> 1   1     This sentence is very similar to the next sentence
#> 2   2 This sentence is not very similar to the next sentence
#> 3   3                 You can't sneeze with your eyes opened

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

Data used

df <- read.table(text = "row    text
1   \"This sentence is very similar to the next sentence\"
2   \"This sentence is not very similar to the next sentence\"
3   \"You can't sneeze with your eyes opened\"", header = TRUE)


问:
Vert.x - How to get POST Value passed between Verticles?
This the class that runs verticles :

```<code>public class RequestResponseExample {
    public static void main(String[] args) throws InterruptedException {
        Logger LOG = LoggerFactory.getLogger(RequestResponseExample.class);

        final Vertx vertx = Vertx.vertx();
        final Handler<AsyncResult<String>> RequestHandler = dar-> vertx.deployVerticle(new ResponseVerticle());

        vertx.deployVerticle(new ResponseVerticle(), RequestHandler);
    }
}
</code>```

This is The Request verticle Class :

```<code>public class RequestVerticle extends AbstractVerticle{
    public static final Logger LOG = LoggerFactory.getLogger(RequestVerticle.class);
    static final String ADDRESS = "my.request.address";

    @Override
    public void start() throws Exception {

        Router router = Router.router(vertx);
        router.get("/Test").handler(rc -> rc.response().sendFile("index.html"));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }
}
</code>```

This is The Response verticle Class: Here Im having a difficulty getting The Inserted value in the HTML file

```<code>public class ResponseVerticle extends AbstractVerticle{
    public static final Logger LOG = LoggerFactory.getLogger(RequestVerticle.class);
    @Override
    public void start() throws Exception {

    Router router = Router.router(vertx);

    // How to handle the POST value ?
    router.post("/Test/Result").handler(rc -> rc.end("The Post Value"));

    vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
}
</code>```

答:
When the user invokes POST /Test/Result and sends some POST value, you receive it in your Response verticle class (third snippet). If you want to share that method with other verticles, you should store it somewhere inside the handler method so other verticles access it or immediately forward it to other verticle via the event bus.

One possible solution would be to create a third verticle (e.g. StorageVerticle) which has get and set methods. That way, ResponseVerticle invokes the set method to store the value it got, and the RequestVerticle invokes the get method to fetch the value the user sent on calling POST method.

The other solution of direct communication between verticles involves the Event Bus message exchange - one verticle publishes/sends a message and all other verticles can register as a consumer to get that message. More on this you can find here: https://vertx.io/docs/vertx-core/java/#_the_event_bus_api.

It is hard to say which approach is better because it is case-to-case basis and I have limited information here about the scope of the project.

Body:
This the class that runs verticles :

public class RequestResponseExample {
    public static void main(String[] args) throws InterruptedException {
        Logger LOG = LoggerFactory.getLogger(RequestResponseExample.class);

        final Vertx vertx = Vertx.vertx();
        final Handler<AsyncResult<String>> RequestHandler = dar-> vertx.deployVerticle(new ResponseVerticle());

        vertx.deployVerticle(new ResponseVerticle(), RequestHandler);
    }
}

This is The Request verticle Class :

public class RequestVerticle extends AbstractVerticle{
    public static final Logger LOG = LoggerFactory.getLogger(RequestVerticle.class);
    static final String ADDRESS = "my.request.address";

    @Override
    public void start() throws Exception {

        Router router = Router.router(vertx);
        router.get("/Test").handler(rc -> rc.response().sendFile("index.html"));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }
}

This is The Response verticle Class: Here Im having a difficulty getting The Inserted value in the HTML file

public class ResponseVerticle extends AbstractVerticle{
    public static final Logger LOG = LoggerFactory.getLogger(RequestVerticle.class);
    @Override
    public void start() throws Exception {

    Router router = Router.router(vertx);

    // How to handle the POST value ?
    router.post("/Test/Result").handler(rc -> rc.end("The Post Value"));

    vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
}


问:
Questions about addresses in SAE J1939 bus
I am developing a program to read and request parameters from a bus with J1939. I know that in order to request PGNs I need to have an address, which is claimed in the address claim procedure. I have some questions about this.

First, do the node addresses change often or are they static?

Second, does my program, as an external test equipment application, need to do the address claim procedure every time the bus is turned on, or can I store the ID that I get from the address claim procedure for my application forever?

As for the address claim procedure, what is a suitable NAME field for my application? What I'm trying to do is setup a monitoring system of different parameters of the bus, like speed, fuel, pedal position, etc. My guess is that there wont be enough ECUs to fill all the 255 available addresses, but I can't confirm how many there are so I may need a NAME. It is not a product, hence wont be mass produced and will only work in our facilities.

答:
Alex

First, what variables do you want to read? I mean, if you are trying to broadcast vehicle Speed, fuel, pedals... these are generical messages which are available on the bus without a request. Appling a digital filter (mask) on CAN might solve your problem in an efficient way. The request method is more for special ID (see more here J1939-71 ).

Applying filters n Python:

```<code>import can

# CAN Setting
can_interface = 'can0'
bus.set_filters([{"can_id":0xCF00400, "can_mask": 0xFFFFFFF, "extended": True},
                 {"can_id":0x18fee927, "can_mask": 0xFFFFFFF, "extended": True}])
bus = can.interface.Bus(can_interface, bustype='socketcan',can_filters=can_filters)

while True:
     message = bus.recv()
     print(message)
</code>```

How filters/masks works:

```<code># The following just equals zero
0xCF00400 & 0 == 0 # True

# The following equals 0xCF00400 (217056256 in decimal) exactly
0xCF00400 & 0xFFFFFFF == 0xCF00400 # True
0xCF00400 & 0xFFFFFFF == 217056256 # True

# The following can_id would not get through the filter + mask:
0x18fee500 & 0xFFFFFFF == 0xCF00400 & 0xFFFFFFF # False

# The following obviously would get through the filter + mask:
0xCF00400 & 0xFFFFFFF == 0xCF00400 & 0xFFFFFFF # True
</code>```

Anyways, to be honest I never used the request method but maybe I can help.

First, do the node addresses change often or are they static?

Second, does my program, as an external test equipment application,
need to do the address claim procedure every time the bus is turned
on, or can I store the ID that I get from the address claim procedure
for my application forever?

The nodes work as a bridge ecu-ccu, so they will be always the same. But you need to always request the data again because they are not 'on line'.

As for the address claim procedure, what is a suitable NAME field for
my aplication?

I truly didn't understand that question XD. But I think you mean you're developing a data J1939 reader/logger.

Body:
Alex

First, what variables do you want to read? I mean, if you are trying to broadcast vehicle Speed, fuel, pedals... these are generical messages which are available on the bus without a request. Appling a digital filter (mask) on CAN might solve your problem in an efficient way. The request method is more for special ID (see more here J1939-71 ).

Applying filters n Python:

import can

# CAN Setting
can_interface = 'can0'
bus.set_filters([{"can_id":0xCF00400, "can_mask": 0xFFFFFFF, "extended": True},
                 {"can_id":0x18fee927, "can_mask": 0xFFFFFFF, "extended": True}])
bus = can.interface.Bus(can_interface, bustype='socketcan',can_filters=can_filters)

while True:
     message = bus.recv()
     print(message)

How filters/masks works:

# The following just equals zero
0xCF00400 & 0 == 0 # True

# The following equals 0xCF00400 (217056256 in decimal) exactly
0xCF00400 & 0xFFFFFFF == 0xCF00400 # True
0xCF00400 & 0xFFFFFFF == 217056256 # True

# The following can_id would not get through the filter + mask:
0x18fee500 & 0xFFFFFFF == 0xCF00400 & 0xFFFFFFF # False

# The following obviously would get through the filter + mask:
0xCF00400 & 0xFFFFFFF == 0xCF00400 & 0xFFFFFFF # True

Anyways, to be honest I never used the request method but maybe I can help.

First, do the node addresses change often or are they static?

Second, does my program, as an external test equipment application,
need to do the address claim procedure every time the bus is turned
on, or can I store the ID that I get from the address claim procedure
for my application forever?

The nodes work as a bridge ecu-ccu, so they will be always the same. But you need to always request the data again because they are not 'on line'.

As for the address claim procedure, what is a suitable NAME field for
my aplication?

I truly didn't understand that question XD. But I think you mean you're developing a data J1939 reader/logger.


问:
Initializing Flutter. This may take a few minutes on vs code
Initializing Flutter. This may take a few minutes takes forever and stops all other processes. any idea on how to solve this?

答:
I was able to resolve this by killing all dart processes by running the command

```<code>killall -9 dart
</code>```

delete the pod files

run flutter clean

Body:
I was able to resolve this by killing all dart processes by running the command

killall -9 dart

delete the pod files

run flutter clean


问:
Looping through an array in SwiftUI
I have an array of strings I want to loop through and create a view for each element. To achieve that, I tried using ForEach(), the output of the code below are the following errors:

Cannot convert value of type '[String]' to expected argument type 'Binding<C>'

Generic parameter 'C' could not be inferred

Code:

struct HomeView: View {
    let array: [String] = ["A", "B", "C", "D", "E", "F", "G"]

    var body: some View {
        VStack {
            ForEach(array, id: \.self) { letter in
                Text(array[letter])
            }
        }
    }
}
```

PS: The code is simplified

Desired output:

VStack of all letters from the array

答:
You can try this (just use the letter parameter from the for loop):

let array: [String] = ["A", "B", "C", "D", "E", "F", "G"]

var body: some View {
    VStack {
        ForEach(array, id: \.self) { letter in
            Text(letter)
        }
    }
}
```

Title: Looping through an array in SwiftUI

Body:
I have an array of strings I want to loop through and create a view for each element. To achieve that, I tried using ForEach(), the output of the code below are the following errors:

Cannot convert value of type '[String]' to expected argument type 'Binding<C>'

Generic parameter 'C' could not be inferred

Code:

struct HomeView: View {
    let array: [String] = ["A", "B", "C", "D", "E", "F", "G"]

    var body: some View {
        VStack {
            ForEach(array, id: \.self) { letter in
                Text(array[letter])
            }
        }
    }
}

PS: The code is simplified

Desired output:

VStack of all letters from the array


问:
How to tell if two strings of any length are anagrams using bash, awk or any using command or script?
The string or word can be of any length.

Eg "William Shakespeare" = "I am a weakish speller"  both are anagrams

E.g.  "Madam Curie" = "Radium came"

答:
```<code>#!/bin/bash

#set -x

i=0
for letter in {A..Z}
do
alphabet[$i]="$letter"
((i++))
done

i=0
for digits in {0..25}
do
array[$i]=0
((i++))
done

read -p "Enter first word: " word1
read -p "Enter second word: " word2

while read -n 1 letter
do

if [ -z "$letter" ]
then continue
fi
for b in "${!alphabet[@]}"
do
if [ "$letter" = "${alphabet[$b]}" ]
then
((array[$b]+=1))
break
fi
done
done < <(echo "${word1^^}")

while read -n 1 letter
do
if [ -z "$letter" ]
then continue
fi
for b in "${!alphabet[@]}"
do
if [ "$letter" = "${alphabet[$b]}" ]
then
((array[$b]-=1))
break
fi
done
done < <(echo "${word2^^}")

echo -n "Words are "
for element in "${array[@]}"
do
if [ "$element" -ne 0 ]
then echo -n "not "
fi
done

echo "anagrams"

echo
exit

</code>```

And in functions

```<code>#!/bin/bash

set -x

i=0
for letter in {A..Z}
do
alphabet[$i]="$letter"
((i++))
done

read_word(){
local array=()
local i=0
for digits in {0..25}
do
array[$i]=0
((i++))
done
local sentence="$1"
while read -n 1 letter
do
if [ -z "$letter" ]
then continue
fi
for b in "${!alphabet[@]}"
do
if [ "$letter" = "${alphabet[$b]}" ]
then
((array[$b]+=1))
break
fi
done
done < <(echo "${sentence^^}")
echo "${array[@]}"
}

equal_array(){
if [ "$1" = "$2" ]
then echo "anagrams"
else echo " not anagrams"
fi
}

read -p "Enter first word: " word1
read -p "Enter second word: " word2

word1=($(read_word "$word1"))
word2=($(read_word "$word2"))

equal_array "${word1[*]}" "${word2[*]}"

exit

</code>```

Body:
#!/bin/bash

#set -x

i=0
for letter in {A..Z}
do
alphabet[$i]="$letter"
((i++))
done

i=0
for digits in {0..25}
do
array[$i]=0
((i++))
done

read -p "Enter first word: " word1
read -p "Enter second word: " word2

while read -n 1 letter
do

if [ -z "$letter" ]
then continue
fi
for b in "${!alphabet[@]}"
do
if [ "$letter" = "${alphabet[$b]}" ]
then
((array[$b]+=1))
break
fi
done
done < <(echo "${word1^^}")

while read -n 1 letter
do
if [ -z "$letter" ]
then continue
fi
for b in "${!alphabet[@]}"
do
if [ "$letter" = "${alphabet[$b]}" ]
then
((array[$b]-=1))
break
fi
done
done < <(echo "${word2^^}")

echo -n "Words are "
for element in "${array[@]}"
do
if [ "$element" -ne 0 ]
then echo -n "not "
fi
done

echo "anagrams"

echo
exit

And in functions

#!/bin/bash

set -x

i=0
for letter in {A..Z}
do
alphabet[$i]="$letter"
((i++))
done

read_word(){
local array=()
local i=0
for digits in {0..25}
do
array[$i]=0
((i++))
done
local sentence="$1"
while read -n 1 letter
do
if [ -z "$letter" ]
then continue
fi
for b in "${!alphabet[@]}"
do
if [ "$letter" = "${alphabet[$b]}" ]
then
((array[$b]+=1))
break
fi
done
done < <(echo "${sentence^^}")
echo "${array[@]}"
}

equal_array(){
if [ "$1" = "$2" ]
then echo "anagrams"
else echo " not anagrams"
fi
}

read -p "Enter first word: " word1
read -p "Enter second word: " word2

word1=($(read_word "$word1"))
word2=($(read_word "$word2"))

equal_array "${word1[*]}" "${word2[*]}"

exit


问:
create public folder and allow user to create files into the particular folder
I am creating an application using asp.net mvc and javascript in which I am creating folders and creating document inside those folders,

below is my code to create folders and docs

```<code>function createFolder() {
    loadClient('https://www.googleapis.com/discovery/v1/apis/drive/v3/rest', function () {
        var body = {
            'name': document.getElementById('txtFolderName').value,
            'mimeType': "application/vnd.google-apps.folder",
            'parents': ['1R7c6lCV_qRxSTVHnbefLN4vJY0ZTMFUW']
        };

        return gapi.client.drive.files.create({
            'resource': body
        }).then(function (response) {
            console.log("Response", response);
        }, function (err) { console.error("Execute error", err); });
    })
}

function execute() {
    loadClient('https://docs.googleapis.com/$discovery/rest?version=v1', function () {
        return gapi.client.docs.documents.create({
            "resource": {
                "title": document.getElementById('txtTitle').value
            }
        })
            .then(function (response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
            },
                function (err) { console.error("Execute error", err); });
    })
}
</code>```

now I want to create folders which will be accessible to everyone of my organization and insert the file in those folder

for example I have folder Named as "My company" and when I create a file, the file should be created inside "My company" folder

thanks for your time

答:
I believe your goal is as follows.

You want to create a new folder and want to publicly share the created folder as the writer.

You want to achieve this using googleapis for Javascript.

In this case, how about the following modification?

Modified script:

From:

return gapi.client.drive.files.create({
    'resource': body
}).then(function (response) {
    console.log("Response", response);
}, function (err) { console.error("Execute error", err); });
```
<h4>To:</h4>
<pre class="lang-js prettyprint-override"><code>gapi.client.drive.files.create({ 'resource': body })
.then(function (response) {
  console.log("Response", response);

  // Created folder is publicly shared.
  var folderId = response.result.id;
  gapi.client.drive.permissions.create({
    "fileId": folderId,
    "resource": {"role": "writer", "type": "anyone" }
  })
  .then(function (res) {
    console.log(res);
  }, function (err) {
    console.log(err.result.error.message);
  });

  // Create new Google Document to the created folder.
  var body = {
    'name': "sample filename",
    'mimeType': "application/vnd.google-apps.document",
    'parents': [folderId]
  };
  gapi.client.drive.files.create({ 'resource': body })
  .then(function (res) {
    console.log(res);
  }, function (err) {
    console.log(err.result.error.message);
  });

}, function (err) {
  console.error("Execute error", err);
});
</code>```

I added the script for one more thing I want to achieve is that I want to create document in those a particular folder of my google drive.

Reference:

Permissions: create

Body:
I am creating an application using asp.net mvc and javascript in which I am creating folders and creating document inside those folders,

below is my code to create folders and docs

function createFolder() {
    loadClient('https://www.googleapis.com/discovery/v1/apis/drive/v3/rest', function () {
        var body = {
            'name': document.getElementById('txtFolderName').value,
            'mimeType': "application/vnd.google-apps.folder",
            'parents': ['1R7c6lCV_qRxSTVHnbefLN4vJY0ZTMFUW']
        };

        return gapi.client.drive.files.create({
            'resource': body
        }).then(function (response) {
            console.log("Response", response);
        }, function (err) { console.error("Execute error", err); });
    })
}

function execute() {
    loadClient('https://docs.googleapis.com/$discovery/rest?version=v1', function () {
        return gapi.client.docs.documents.create({
            "resource": {
                "title": document.getElementById('txtTitle').value
            }
        })
            .then(function (response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
            },
                function (err) { console.error("Execute error", err); });
    })
}

now I want to create folders which will be accessible to everyone of my organization and insert the file in those folder

for example I have folder Named as "My company" and when I create a file, the file should be created inside "My company" folder

thanks for your time

Body:
I believe your goal is as follows.

You want to create a new folder and want to publicly share the created folder as the writer.

You want to achieve this using googleapis for Javascript.

In this case, how about the following modification?

Modified script:

From:

return gapi.client.drive.files.create({
    'resource': body
}).then(function (response) {
    console.log("Response", response);
}, function (err) { console.error("Execute error", err); });

To:

gapi.client.drive.files.create({ 'resource': body })
.then(function (response) {
  console.log("Response", response);

  // Created folder is publicly shared.
  var folderId = response.result.id;
  gapi.client.drive.permissions.create({
    "fileId": folderId,
    "resource": {"role": "writer", "type": "anyone" }
  })
  .then(function (res) {
    console.log(res);
  }, function (err) {
    console.log(err.result.error.message);
  });

  // Create new Google Document to the created folder.
  var body = {
    'name': "sample filename",
    'mimeType': "application/vnd.google-apps.document",
    'parents': [folderId]
  };
  gapi.client.drive.files.create({ 'resource': body })
  .then(function (res) {
    console.log(res);
  }, function (err) {
    console.log(err.result.error.message);
  });

}, function (err) {
  console.error("Execute error", err);
});

I added the script for one more thing I want to achieve is that I want to create document in those a particular folder of my google drive.

Reference:

Permissions: create


问:
Special characters (german umlauts) are displayed as ASCII
In our database german umlauts are displayed as ASCII.
Here some examples

```<code>Ü is displayed as "š"
ä is displayed as "„"
Ä is displayed as "Ž"
ö is displayed as "”"
Ö is displayed as "™"
</code>```

Here some Oracle enviroment variables:

```<code>SELECT distinct client_charset FROM v$session_connect_info
WHERE sid = sys_context('USERENV','SID');
retuns Unknown

select * from v$NLS_PARAMETERS;
NLS_LANGUAGE    GERMAN
NLS_CHARACTERSET    WE8MSWIN1252
</code>```

I have also noticed, that there is no NLS_LANG setted up.
Can someone give me any clue how to check if this is a problem of env variable or character-encoding itself? Or how to fix it so that the umlauts would be displayed correctly?
Thanks in advance!

答:
The first sentence is already wrong, it must be "my client application displays german umlauts as ..." Characters like Ž are not ASCII either. The Oracle environment variables have nothing to do how your client displays any characters.

There could be two reasons:

Characters like š „ Ž ” ™ are really stored in your database because they are inserted wrong, and you just think it should be Ü ä Ä ö Ö

Your client uses the wrong character set.

NLS_LANG is used to tell the database "my client uses character set XYZ" - no more, no less! Well, some clients inherit the NLS_LANG value for own character set setting but that is not always the case.

Actual answer:

You have wrong data in your database! When you inserted the data then your client was using CP437 (Oracle Character Set US8PC437) but you did not tell this the database.

Most likely data was inserted by sqlplus which inherits the codepage from cmd.exe which is by default 437 on English Windows machines. NLS_LANG character set was set to WE8MSWIN1252. When character set of client and database is the same then data is transferred byte-by-byte without any conversion - there is the mismatch!

Solutions:

Before you run your sqlplus script Set NLS_LANG accordingly, e.g.

```<code>SET NLS_LANG=.US8PC437
sqlplus ...
</code>```

Language and Territory are optional and thus can be skipped.

Your database uses character set WE8MSWIN1252, then it would be beneficial to use it also by your client. By this you can insert and display any character which is supported by the database (no less but also no more)

```<code>chcp 1252
SET NLS_LANG=.WE8MSWIN1252
sqlplus ...
</code>```

Correction of wrong data:

In order to correct the wrong data try this:

```<code>UPDATE table_name SET column_name = CONVERT(column_name, 'WE8MSWIN1252', 'US8PC437');
</code>```

Note, this should be a one-time correction only. Do not put such update as part of your application code!

Update

For correction of PL/SQL code, try this one (not tested):

Create a SQL script like this:

```<code>SET HEADING OFF
SET FEEDBACK OFF
SET NEWPAGE NONE
SET VERIFY OFF
SET TRIMSPOOL ON
SET DEFINE OFF
SET ECHO OFF
SET TERMOUT OFF
SET PAGESIZE 0
SET LINESIZE 32767
SET LONG 2000000000
SET LONGCHUNKSIZE 32767

spool PACKAGE_NAME.sql;
SELECT DBMS_METADATA.GET_DDL('PACKAGE', 'PACKAGE_NAME', USER) FROM DUAL t;

spool OFF;
EXIT
</code>```

And the run it like this

```<code>c:\> chcp 437
c:\> SET NLS_LANG=.WE8MSWIN1252
c:\> sqlplus -s ... @<above script>

c:\> SET NLS_LANG=.US8PC437
c:\> sqlplus ... @PACKAGE_NAME.sql
</code>```

Body:
In our database german umlauts are displayed as ASCII.
Here some examples

Ü is displayed as "š"
ä is displayed as "„"
Ä is displayed as "Ž"
ö is displayed as "”"
Ö is displayed as "™"

Here some Oracle enviroment variables:

SELECT distinct client_charset FROM v$session_connect_info
WHERE sid = sys_context('USERENV','SID');
retuns Unknown

select * from v$NLS_PARAMETERS;
NLS_LANGUAGE    GERMAN
NLS_CHARACTERSET    WE8MSWIN1252

I have also noticed, that there is no NLS_LANG setted up.
Can someone give me any clue how to check if this is a problem of env variable or character-encoding itself? Or how to fix it so that the umlauts would be displayed correctly?
Thanks in advance!

Body:
The first sentence is already wrong, it must be "my client application displays german umlauts as ..." Characters like Ž are not ASCII either. The Oracle environment variables have nothing to do how your client displays any characters.

There could be two reasons:

Characters like š „ Ž ” ™ are really stored in your database because they are inserted wrong, and you just think it should be Ü ä Ä ö Ö

Your client uses the wrong character set.

NLS_LANG is used to tell the database "my client uses character set XYZ" - no more, no less! Well, some clients inherit the NLS_LANG value for own character set setting but that is not always the case.

Actual answer:

You have wrong data in your database! When you inserted the data then your client was using CP437 (Oracle Character Set US8PC437) but you did not tell this the database.

Most likely data was inserted by sqlplus which inherits the codepage from cmd.exe which is by default 437 on English Windows machines. NLS_LANG character set was set to WE8MSWIN1252. When character set of client and database is the same then data is transferred byte-by-byte without any conversion - there is the mismatch!

Solutions:

Before you run your sqlplus script Set NLS_LANG accordingly, e.g.

SET NLS_LANG=.US8PC437
sqlplus ...

Language and Territory are optional and thus can be skipped.

Your database uses character set WE8MSWIN1252, then it would be beneficial to use it also by your client. By this you can insert and display any character which is supported by the database (no less but also no more)

chcp 1252
SET NLS_LANG=.WE8MSWIN1252
sqlplus ...

Correction of wrong data:

In order to correct the wrong data try this:

UPDATE table_name SET column_name = CONVERT(column_name, 'WE8MSWIN1252', 'US8PC437');

Note, this should be a one-time correction only. Do not put such update as part of your application code!

Update

For correction of PL/SQL code, try this one (not tested):

Create a SQL script like this:

SET HEADING OFF
SET FEEDBACK OFF
SET NEWPAGE NONE
SET VERIFY OFF
SET TRIMSPOOL ON
SET DEFINE OFF
SET ECHO OFF
SET TERMOUT OFF
SET PAGESIZE 0
SET LINESIZE 32767
SET LONG 2000000000
SET LONGCHUNKSIZE 32767

spool PACKAGE_NAME.sql;
SELECT DBMS_METADATA.GET_DDL('PACKAGE', 'PACKAGE_NAME', USER) FROM DUAL t;

spool OFF;
EXIT

And the run it like this

c:\> chcp 437
c:\> SET NLS_LANG=.WE8MSWIN1252
c:\> sqlplus -s ... @<above script>

c:\> SET NLS_LANG=.US8PC437
c:\> sqlplus ... @PACKAGE_NAME.sql


问:
Android app code coverage for manual testing
I am looking for a way to get EMMA code coverage with manual test. I mean, i don't want to write any unit test cases using the android test framework, instead i am looking for a way to instrument my android app source code and test manually and at the end i should be able to see my EMMA coverage. Any help would be much appreciated.</p>

答:
Nearly a month and you have no responses.

You might consider using a test coverage tool that isn't tied to the infrastructure in the way Emma is.  This avoids the problems with incompatabilities with said infrastructure.

Our Java Test Coverage tool instruments your source code, making it independent of the compiler and runtime system.  You compile your code and execute/test it however your like (system tests, unit tests, manual interaction), and it collects test coverage data in a Java array in a TestCoverage class, as the tests run.   At the end of execution (you define that, although exit from main is a common definition), that test coverage data is written somehow to a file, eventually to be displayed by the test coverage tool.   While the Java Test Coverage tool provides a default class implementation that writes the array to a disk file using Java file primitives, you can easily override the implementation with any code you like, and store the array in any place where it can be eventually retrieved by another mechanism to be turned into a file, and then displayed.

This will work with your manual exercising of code.


问:
Using Ani Library on Objects (Processing)
I am currently working with the Ani Library in Processing.
I'm trying to fade in some rectangles one by one (on a PGraphics). To let the rectangles appear I use a loop - whose size I can control with MouseX. So one rectangle appears after the other. But I also want to fade in each one individually using the Ani Library. Currently I can only get the fade in to affect all of them at once.

So I tried to make an object out of the rectangle and put the FadeIn inside the object. But it behaves similar here – all fade in at once.
How can I solve this? Do I need an Array or an Array List for this?

This is my Code without an object:

```<code>import de.looksgood.ani.*;
PGraphics pg;
float alpha;

void setup() {
  size(1920, 1920);
  rectMode(CENTER);
  Ani.init(this);
  pg = createGraphics(width, height);
}

void draw() {
  drawPG();
  image(pg, 0,0);
}

void drawPG () {
  pg.beginDraw();
  pg.pushMatrix();
  pg.translate(100, height/4.75);
  pg.background(255);
  pg.noStroke();
  Ani.to(this, 10, "alpha", 255, Ani.EXPO_OUT);
  color black = color(0, 0, 0, alpha);
  pg.fill(black);
  int blocks = int(map(mouseX, 0, width, 0, 7));
  for (int i = 0; i < blocks; i++) {
    pg.pushMatrix();
    pg.translate(i * 200 + i*100, 0);
    pg.rect(0, 0, 200, 200);
    pg.popMatrix();
  }
  pg.popMatrix();
  pg.endDraw();
}
</code>```

And this is my tried out version with an Object:

```<code>import de.looksgood.ani.*;

PGraphics pg;
Rectangle myRect;

void setup() {
  size(1920, 1920);
  rectMode(CENTER);
  myRect = new Rectangle();
  Ani.init(this);
  pg = createGraphics(width, height);

}

void draw() {
  drawPG();
  image(pg, 0,0);
}

void drawPG () {
  pg.beginDraw();
  pg.pushMatrix();
  pg.translate(100, height/4.75);
  pg.background(255);
  pg.noStroke();
  int blocks = int(map(mouseX, 0, width, 0, 7));
  for (int i = 0; i < blocks; i++) {
    pg.pushMatrix();
    pg.translate(i * 200 + i*100, 0);
    myRect.display(pg);
    pg.popMatrix();
  }
  pg.popMatrix();
  pg.endDraw();
}

class Rectangle {
  float alpha;

  Rectangle() {
  }

  void display(PGraphics pg) {
    Ani.to(this, 10, "alpha", 255, Ani.EXPO_OUT);
    color black = color(0, 0, 0, alpha);
    pg.fill(black);
    pg.rect(0, 0, 200, 200);
  }
}
</code>```

答:
+++ EDIT +++

Found a solution here:
https://processing.org/tutorials/objects

And this gave me the hint to really work with an array. And then it says for the PGraphic:

```<code>  void drawPG () {
  pg.beginDraw();
  pg.pushMatrix();
  pg.translate(100, height/4.75);
  pg.background(255);
  pg.noStroke();
  int blocks = int(map(mouseX, 0, width, 0, rectangles.length));
  for (int i = 0; i < blocks; i++) {
    pg.pushMatrix();
    pg.translate(i * 200 + i*100, 0);
    rectangles[i].display(pg);
    pg.popMatrix();
  }
  pg.popMatrix();
  pg.endDraw();
}
</code>```

Above setup();

```<code>   Rectangle[] rectangles = new Rectangle[7];
</code>```

And in setup();

```<code>   for (int i = 0; i < rectangles.length; i++) {
    rectangles[i] = new Rectangle();
  }
</code>```

Body:
I am currently working with the Ani Library in Processing.
I'm trying to fade in some rectangles one by one (on a PGraphics). To let the rectangles appear I use a loop - whose size I can control with MouseX. So one rectangle appears after the other. But I also want to fade in each one individually using the Ani Library. Currently I can only get the fade in to affect all of them at once.

So I tried to make an object out of the rectangle and put the FadeIn inside the object. But it behaves similar here – all fade in at once.
How can I solve this? Do I need an Array or an Array List for this?

This is my Code without an object:

import de.looksgood.ani.*;
PGraphics pg;
float alpha;

void setup() {
  size(1920, 1920);
  rectMode(CENTER);
  Ani.init(this);
  pg = createGraphics(width, height);
}

void draw() {
  drawPG();
  image(pg, 0,0);
}

void drawPG () {
  pg.beginDraw();
  pg.pushMatrix();
  pg.translate(100, height/4.75);
  pg.background(255);
  pg.noStroke();
  Ani.to(this, 10, "alpha", 255, Ani.EXPO_OUT);
  color black = color(0, 0, 0, alpha);
  pg.fill(black);
  int blocks = int(map(mouseX, 0, width, 0, 7));
  for (int i = 0; i < blocks; i++) {
    pg.pushMatrix();
    pg.translate(i * 200 + i*100, 0);
    pg.rect(0, 0, 200, 200);
    pg.popMatrix();
  }
  pg.popMatrix();
  pg.endDraw();
}

And this is my tried out version with an Object:

import de.looksgood.ani.*;

PGraphics pg;
Rectangle myRect;

void setup() {
  size(1920, 1920);
  rectMode(CENTER);
  myRect = new Rectangle();
  Ani.init(this);
  pg = createGraphics(width, height);

}

void draw() {
  drawPG();
  image(pg, 0,0);
}

void drawPG () {
  pg.beginDraw();
  pg.pushMatrix();
  pg.translate(100, height/4.75);
  pg.background(255);
  pg.noStroke();
  int blocks = int(map(mouseX, 0, width, 0, 7));
  for (int i = 0; i < blocks; i++) {
    pg.pushMatrix();
    pg.translate(i * 200 + i*100, 0);
    myRect.display(pg);
    pg.popMatrix();
  }
  pg.popMatrix();
  pg.endDraw();
}

class Rectangle {
  float alpha;

  Rectangle() {
  }

  void display(PGraphics pg) {
    Ani.to(this, 10, "alpha", 255, Ani.EXPO_OUT);
    color black = color(0, 0, 0, alpha);
    pg.fill(black);
    pg.rect(0, 0, 200, 200);
  }
}

Body:
+++ EDIT +++

Found a solution here:
https://processing.org/tutorials/objects

And this gave me the hint to really work with an array. And then it says for the PGraphic:

  void drawPG () {
  pg.beginDraw();
  pg.pushMatrix();
  pg.translate(100, height/4.75);
  pg.background(255);
  pg.noStroke();
  int blocks = int(map(mouseX, 0, width, 0, rectangles.length));
  for (int i = 0; i < blocks; i++) {
    pg.pushMatrix();
    pg.translate(i * 200 + i*100, 0);
    rectangles[i].display(pg);
    pg.popMatrix();
  }
  pg.popMatrix();
  pg.endDraw();
}

Above setup();

   Rectangle[] rectangles = new Rectangle[7];

And in setup();

   for (int i = 0; i < rectangles.length; i++) {
    rectangles[i] = new Rectangle();
  }


问:
Git isn't working as expected with vscode remote ssh
I recently tried out vscode's remote SSH feature. It was super easy to setup and connect to a remote server.

I opened the editor to a directory that is a git repo and expected to have the default git features working like normal. But if I edit a file, vscode isn't showing the visual indication that there is a modification in the file. And the git tab doesn't show the change. I can open the terminal in vscode and run git status and I do in fact see the change so I know that's actually editing the file.

If I ssh into the server and run git status I do notice that vscode updates and now shows the change in the git tab. But there's still no visual indication next to the line number in the actual file that is changed.

答:
What solved it for me: use the -A option (forward your ssh-agent) when ssh-ing to your remote server. This will allow you to connect to git using your git credentials from the client.

Example:

```<code>ssh username@servername -A
</code>```

Or just enter

```<code>ForwardAgent yes
</code>```

Into your ssh-config (~/.ssh/config on ubuntu).

Body:
What solved it for me: use the -A option (forward your ssh-agent) when ssh-ing to your remote server. This will allow you to connect to git using your git credentials from the client.

Example:

ssh username@servername -A

Or just enter

ForwardAgent yes

Into your ssh-config (~/.ssh/config on ubuntu).


问:
Problem with calling method from another class for use
So I have these two .java files, one that defines a Dice and another that is going to use the Dice.
I need to implement the roll method from the Dice.java file in the Yahtzee.java file but I'm not sure how to go about doing so.</p>
```<code>public class Dice {
    private int value;

    public Dice() {
        value = -1;
    }

    public Dice(int j) {
        value = j;
    }

    public void roll() {
        value = RandomNumber.getRandomNumber(1, 6);

    }
    public int getValue() {
        return value;
    }

}
</code>```
```<code>public class Yahtzee {

    private Dice[] dice;

    public Yahtzee() {

    }
}
</code>```

答:
In your constructor you will want to instantiate the array of Dice (6 for Yahtzee if memory holds).

```<code>public class Yahtzee {

  private Dice[] dice = new Dice[6];

  public Yahtzee() {
    for (int index = 0 ; index < dice.length ; ++index) {
      dice[index] = new Dice();
    }
  }
}
</code>```

Now a given instance of Yahtzee owns 6 instances of Dice and can invoke public methods on those instances.  So you can add a method that iterates over those Dice and invokes the roll() method on each as follows:

```<code>public void roll() {
  for (Dice d : dice) {
    d.roll();
  }
}
</code>```

You will need to implement another method (or modify this one) to handle the re-roll of specific Dice.  This example should be enough to get your started however.

Body:
So I have these two .java files, one that defines a Dice and another that is going to use the Dice.
I need to implement the roll method from the Dice.java file in the Yahtzee.java file but I'm not sure how to go about doing so.

public class Dice {
    private int value;

    public Dice() {
        value = -1;
    }

    public Dice(int j) {
        value = j;
    }

    public void roll() {
        value = RandomNumber.getRandomNumber(1, 6);

    }
    public int getValue() {
        return value;
    }

}

public class Yahtzee {

    private Dice[] dice;

    public Yahtzee() {

    }
}

Body:
In your constructor you will want to instantiate the array of Dice (6 for Yahtzee if memory holds).

public class Yahtzee {

  private Dice[] dice = new Dice[6];

  public Yahtzee() {
    for (int index = 0 ; index < dice.length ; ++index) {
      dice[index] = new Dice();
    }
  }
}

Now a given instance of Yahtzee owns 6 instances of Dice and can invoke public methods on those instances.  So you can add a method that iterates over those Dice and invokes the roll() method on each as follows:

public void roll() {
  for (Dice d : dice) {
    d.roll();
  }
}

You will need to implement another method (or modify this one) to handle the re-roll of specific Dice.  This example should be enough to get your started however.


问:
Android MapView in a RecyclerView - caching for performance
I have a RecyclerView with multiple item types, one of which has a MapView in it.

My problem is that I want to show multiple MapViews and the loading of the maps can be quite slow as a scroll happens; more over the map has to be loaded again even if the same place shows several times or the view has been recycled.

According to the Google maps API Terms of Service it is allowed to cache maps for performance reasons:

10.5.d: No caching or storage. You will not pre-fetch, cache, index, or store any Content to be used outside the Service, except that you
  may store limited amounts of Content solely for the purpose of
  improving the performance of your Maps API Implementation due to
  network latency (and not for the purpose of preventing Google from
  accurately tracking usage), and only if such storage:

  i. is temporary (and in no event more than 30 calendar days);

  ii. is secure;

  iii. does not manipulate or aggregate any part of the Content or Service; and

  iv. does not modify attribution in any way.

How do I go about and cache\restore the maps from and to the MapView? - I do not see anything that seems relevant in the MapView's API

答:
You can reach some performance improvements by applying the following:

```<code>recyclerView.setHasFixedSize(true);
recyclerView.setDrawingCacheEnabled(true);
</code>```

..in combination with lite mode of MapsView:

```<code><com.google.android.gms.maps.MapView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        app:liteMode="true"
        app:mapType="normal" />
</code>```

@MikeL I summarized your answer here, so others will find the answer quicker.

Body:
You can reach some performance improvements by applying the following:

recyclerView.setHasFixedSize(true);
recyclerView.setDrawingCacheEnabled(true);

..in combination with lite mode of MapsView:

<com.google.android.gms.maps.MapView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        app:liteMode="true"
        app:mapType="normal" />

@MikeL I summarized your answer here, so others will find the answer quicker.


问:
JPA/Hibernate @OrderBy annotation with boolean row
I want to order by a row "pk" in attributes. But it has a boolean data. The attributes that has pk=true should go first. I just can't write @OrderBy("pk=true"). How can I make it to order by this row?</p>
```<code>public class Entity {

//here are some rows;

@OneToMany
    @JoinColumn(name = "id")
    @OrderBy("pk", "firstName")
    private Collection<Attributes> attributes;
}

public class Attributes {

    @Id
    private Long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "pk")
    private Boolean pk;
}
</code>```

答:
Ok, from the example you gave you already know how to sort by the field pk. It is just that you want the reverse order.

For that you would write

@OrderBy("pk desc")

See also https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/order-by-annotation.html

Body:
I want to order by a row "pk" in attributes. But it has a boolean data. The attributes that has pk=true should go first. I just can't write @OrderBy("pk=true"). How can I make it to order by this row?

public class Entity {

//here are some rows;

@OneToMany
    @JoinColumn(name = "id")
    @OrderBy("pk", "firstName")
    private Collection<Attributes> attributes;
}

public class Attributes {

    @Id
    private Long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "pk")
    private Boolean pk;
}


问:
The main difference between SharedFlow and StateFlow
What are the differences between SharedFlow and StateFlow?

And how to use these in MVI architecture? is it better to use simple Flow or these as states and events?

答:
Flow is cold!, means it emits data only when it is collected.
Also Flow cannot hold data, take it as a pipe in which water is flowing , data in flow only flows , not stored(no .value function).

Unlike flow , stateflow and sharedflow are hot streams means they emit data even when there is no collector. Also if there are multiple collectors ,a new flow will be run for each collector, completely independent from each other.
SharedFlow and StateFlow are Flows that allows for sharing itself between multiple collectors, so that only one flow is effectively run for all of the simultaneous collectors. If you define a SharedFlow that accesses databases and it is collected by multiple collectors, the database access will only run once, and the resulting data will be shared to all collectors.

What are the differences between SharedFlow and StateFlow?

StateFlow

Stateflow takes an initial value through constructor and emits it immediately
when someone starts collecting.
Stateflow is identical to LiveData.
LiveData automatically unregisters the consumer when the view goes to the STOPPED
state. When collecting a StateFlow this is not handled automatically , you can
use repeatOnLifeCyCle scope if you want to unregister the consumer on STOPPED
state.
If you want current state use stateflow(.value).

SharedFlow

StateFlow only emits last known value , whereas sharedflow can configure how many
previous values to be emitted.
If you want emitting and collecting repeated values , use sharedflow.


问:
Equivalent of JObject in System.Text.Json
I have DTO class that has a property of type JObject. This DTO class is send/receive over HTTP between multiple services. JObject is used because the ExtractedData does not have predefined properties

```<code>public class MyDTO
{
    public JObject ExtractedData {get;set;}
}
</code>```

I am converting this project to .NET 5. What is equivalent to JObject in .NET 5? I am trying to avoid JsonDocument because (from the docs):

JsonDocument builds an in-memory view of the data into a pooled
buffer. Therefore, unlike JObject or JArray from Newtonsoft.Json, the
JsonDocument type implements IDisposable and needs to be used inside a
using block.

I am planing to use JsonElement.  Is this the most appropriate choice or is there any other type available to hold JSON as an object?

答:
As of Nov 2021, .NET 6 introduces the System.Text.Json.Nodes namespace which:

Provides types for handling an in-memory writeable document object
model (DOM) for random access of the JSON elements within a structured
view of the data

The four new types are JsonArray, JsonObject, JsonNode and JsonValue.
The closest type to JObject is JsonObject which offers similar functionality.

See below for some examples:

```<code>// create object manually using initializer syntax
JsonObject obj = new JsonObject
{
    ["Id"] = 3,
    ["Name"] = "Bob",
    ["DOB"] = new DateTime(2001, 02, 03),
    ["Friends"] = new JsonArray
    {
        new JsonObject
        {
            ["Id"] = 2,
            ["Name"] = "Smith"
        },
        new JsonObject
        {
            ["Id"] = 4,
            ["Name"] = "Jones"
        }
    }
};

// random access to values
int id = (int)obj["Id"];
DateTime dob = (DateTime)obj["DOB"];
string firstFriendName = (string)obj["Friends"][0]["Name"];
</code>```

Some other cool things which now make using System.Text.Json much easier in .NET6 are listed below.

Parse, Create, and DOM Manipulation

```<code>// parse
var jsonObj = JsonNode.Parse(jsonString).AsObject();
</code>```

If you have a JsonElement (perhaps after deserializing into dynamic, object, or JsonElement) you can call Create, now you have a navigable and writable DOM object:

```<code>// create
JsonObject obj = JsonObject.Create(jsonElement);
</code>```

You can Add/Remove properties:

```<code>obj.Add("FullName", "Bob Smith");
bool successfullyRemoved = obj.Remove("Name");
</code>```

Safely interrogate object for particular key using ContainsKey and TryGetPropertyValue (which returns a JsonNode):

```<code>if (obj.ContainsKey("Hobbies"))
    // do stuff

if (obj.TryGetPropertyValue("Hobbies", out JsonNode? node))
    // do stuff with node
</code>```

Project and Filter data

It's possible to use Linq to project and filter the JsonObject:

```<code>// select Keys
List<string> keys = obj.Select(node => node.Key).ToList();
// filter friends
var friends = obj["Friends"].AsArray()
             .Where(n => (int)n.AsObject()["Id"] > 2);
</code>```

Deserialize Json

It's now easy to deserialize the Json or deserialize a portion of the Json.  This is useful when we only want to deserialize partial Json from the main object.  For the example above we can deserialize the list of friends into a generic List<Friend> easily:

```<code>List<Friend> friends = obj["Friends"].AsArray().Deserialize<List<Friend>>();
</code>```

where Deserilize<T>() is an extension method on JsonNode.

Serialize

It's easy to serialize the JsonObject by using ToJsonString():

```<code>string s = obj.ToJsonString();

// write pretty json with WriteIndented
string s = obj.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
</code>```

In your particular case you could define JsonObject in your DTO:

```<code>public class MyDTO
{
    public JsonObject ExtractedData {get;set;}
}
</code>```

Body:
I have DTO class that has a property of type JObject. This DTO class is send/receive over HTTP between multiple services. JObject is used because the ExtractedData does not have predefined properties

public class MyDTO
{
    public JObject ExtractedData {get;set;}
}

I am converting this project to .NET 5. What is equivalent to JObject in .NET 5? I am trying to avoid JsonDocument because (from the docs):

JsonDocument builds an in-memory view of the data into a pooled
buffer. Therefore, unlike JObject or JArray from Newtonsoft.Json, the
JsonDocument type implements IDisposable and needs to be used inside a
using block.

I am planing to use JsonElement.  Is this the most appropriate choice or is there any other type available to hold JSON as an object?

Body:
As of Nov 2021, .NET 6 introduces the System.Text.Json.Nodes namespace which:

Provides types for handling an in-memory writeable document object
model (DOM) for random access of the JSON elements within a structured
view of the data

The four new types are JsonArray, JsonObject, JsonNode and JsonValue.
The closest type to JObject is JsonObject which offers similar functionality.

See below for some examples:

// create object manually using initializer syntax
JsonObject obj = new JsonObject
{
    ["Id"] = 3,
    ["Name"] = "Bob",
    ["DOB"] = new DateTime(2001, 02, 03),
    ["Friends"] = new JsonArray
    {
        new JsonObject
        {
            ["Id"] = 2,
            ["Name"] = "Smith"
        },
        new JsonObject
        {
            ["Id"] = 4,
            ["Name"] = "Jones"
        }
    }
};

// random access to values
int id = (int)obj["Id"];
DateTime dob = (DateTime)obj["DOB"];
string firstFriendName = (string)obj["Friends"][0]["Name"];

Some other cool things which now make using System.Text.Json much easier in .NET6 are listed below.

Parse, Create, and DOM Manipulation

// parse
var jsonObj = JsonNode.Parse(jsonString).AsObject();

If you have a JsonElement (perhaps after deserializing into dynamic, object, or JsonElement) you can call Create, now you have a navigable and writable DOM object:

// create
JsonObject obj = JsonObject.Create(jsonElement);

You can Add/Remove properties:

obj.Add("FullName", "Bob Smith");
bool successfullyRemoved = obj.Remove("Name");

Safely interrogate object for particular key using ContainsKey and TryGetPropertyValue (which returns a JsonNode):

if (obj.ContainsKey("Hobbies"))
    // do stuff

if (obj.TryGetPropertyValue("Hobbies", out JsonNode? node))
    // do stuff with node

Project and Filter data

It's possible to use Linq to project and filter the JsonObject:

// select Keys
List<string> keys = obj.Select(node => node.Key).ToList();
// filter friends
var friends = obj["Friends"].AsArray()
             .Where(n => (int)n.AsObject()["Id"] > 2);

Deserialize Json

It's now easy to deserialize the Json or deserialize a portion of the Json.  This is useful when we only want to deserialize partial Json from the main object.  For the example above we can deserialize the list of friends into a generic List<Friend> easily:

List<Friend> friends = obj["Friends"].AsArray().Deserialize<List<Friend>>();

where Deserilize<T>() is an extension method on JsonNode.

Serialize

It's easy to serialize the JsonObject by using ToJsonString():

string s = obj.ToJsonString();

// write pretty json with WriteIndented
string s = obj.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));

In your particular case you could define JsonObject in your DTO:

public class MyDTO
{
    public JsonObject ExtractedData {get;set;}
}


问:
how can i source last N lines of a shell script
for example

a=1;b=2;c=3;d=4;e=5

the file is 1.sh

cat 1.sh

```<code>echo $a
echo $b
echo $c
echo $d
echo $e
</code>```

i use the command

source 1.sh

i get

```<code>1
2
3
4
5
</code>```

how can i source the last 3 line of 1.sh?

tail -n 3 1.sh|xargs -0 sh -c

can not work because the variable can not pass to sh

答:
tail -n 3 1.sh > tmp.sh ; source ./tmp.sh ; rm tmp.sh

If necessary, choose or generate a name that's unlikely to collide with anything else, like /tmp/tmp$$.sh.

Body:
for example

a=1;b=2;c=3;d=4;e=5

the file is 1.sh

cat 1.sh

echo $a
echo $b
echo $c
echo $d
echo $e

i use the command

source 1.sh

i get

1
2
3
4
5

how can i source the last 3 line of 1.sh?

tail -n 3 1.sh|xargs -0 sh -c

can not work because the variable can not pass to sh


问:
How to get total number of nodes in an XML in MarkLogic Database
I have an XML like below in my database:

```<code><PersonalData>
  <Person>
    <Name></Name>
    <Age></Age>
    <AccountNo>
      <Number>123<Number>
      <SwiftCode>1235<SwiftCode>
    </AccountNo>
    <AccountNo>
      <Number>15523<Number>
      <SwiftCode>188235<SwiftCode>
    </AccountNo>
  </Person>
</PersonalData>
</code>```

in this XML, I have multiple AccountNo nodes and I have around 1M similar records in my database. I want to identify the count of AccountNo nodes in my entire database.

答:
One way in which you can report the count of AccountNo elements would be to   use an XPath and count:

```<code>count(//AccountNo)
</code>```

You can also use cts:search and specify the AccountNo in the $expression XPath, and then count() the results:

```<code>count(cts:search(//AccountNo, cts:true-query()))
</code>```

Another way to get a count of all the distinct AccountNo elements would be to run a CoRB job to select the docs that have those elements, and then in the process module return a line for every element in the doc and write the results to a text file. Below is an example OPTIONS-FILE that could be used to achieve that:

```<code>URIS-MODULE=INLINE-XQUERY|let $uris := cts:uris('',(),cts:element-query(xs:QName("AccountNo"), cts:true-query())) return (count($uris), $uris)
PROCESS-MODULE=INLINE-XQUERY|declare variable $URI external; doc($URI)//AccountNo ! 1
PROCESS-TASK=com.marklogic.developer.corb.ExportBatchToFileTask
EXPORT-FILE-NAME=AccountNoCounts.txt
DISK-QUEUE=true
</code>```

Then you could get the line count from the result file, which would tell you have many elements there are: wc -l AccountNoCounts.txt

If you need to be able to get this count often, and need the response to be fast, you could create a TDE that projects rows for each of the AccountNo elements and then could and could select the count with SQL (e.g. SELECT count(1) FROM Person.AccountNo) or use the Optic API against that TDE and op.count().

Body:
I have an XML like below in my database:

<PersonalData>
  <Person>
    <Name></Name>
    <Age></Age>
    <AccountNo>
      <Number>123<Number>
      <SwiftCode>1235<SwiftCode>
    </AccountNo>
    <AccountNo>
      <Number>15523<Number>
      <SwiftCode>188235<SwiftCode>
    </AccountNo>
  </Person>
</PersonalData>

in this XML, I have multiple AccountNo nodes and I have around 1M similar records in my database. I want to identify the count of AccountNo nodes in my entire database.

Body:
One way in which you can report the count of AccountNo elements would be to   use an XPath and count:

count(//AccountNo)

You can also use cts:search and specify the AccountNo in the $expression XPath, and then count() the results:

count(cts:search(//AccountNo, cts:true-query()))

Another way to get a count of all the distinct AccountNo elements would be to run a CoRB job to select the docs that have those elements, and then in the process module return a line for every element in the doc and write the results to a text file. Below is an example OPTIONS-FILE that could be used to achieve that:

URIS-MODULE=INLINE-XQUERY|let $uris := cts:uris('',(),cts:element-query(xs:QName("AccountNo"), cts:true-query())) return (count($uris), $uris)
PROCESS-MODULE=INLINE-XQUERY|declare variable $URI external; doc($URI)//AccountNo ! 1
PROCESS-TASK=com.marklogic.developer.corb.ExportBatchToFileTask
EXPORT-FILE-NAME=AccountNoCounts.txt
DISK-QUEUE=true

Then you could get the line count from the result file, which would tell you have many elements there are: wc -l AccountNoCounts.txt

If you need to be able to get this count often, and need the response to be fast, you could create a TDE that projects rows for each of the AccountNo elements and then could and could select the count with SQL (e.g. SELECT count(1) FROM Person.AccountNo) or use the Optic API against that TDE and op.count().


问:
How to define a component as default value for a prop in React?
How can I do something like this correctly in React?

import Bar from './Bar.jsx'

const Foo = ({ icon = <Bar />}) => {
  // ...
}

export default Foo
```

Right now using icon = <Bar /> will simple give parsing error.

答:
Use capitalized Icon prop to be able to use it as a component:

```<code>const Bar = ({}) => {
  return <div>Bar</div>;
};

const Foo = ({ Icon = Bar }) => {
  return (
    <div>
      <Icon />
    </div>
  );
};
</code>```

Live

Body:
How can I do something like this correctly in React?

import Bar from './Bar.jsx'

const Foo = ({ icon = <Bar />}) => {
  // ...
}

export default Foo

Right now using icon = <Bar /> will simple give parsing error.

Body:
Use capitalized Icon prop to be able to use it as a component:

const Bar = ({}) => {
  return <div>Bar</div>;
};

const Foo = ({ Icon = Bar }) => {
  return (
    <div>
      <Icon />
    </div>
  );
};

Live


问:
php null replacement function
there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.

i try to write the same function in php, which looks like below:

```<code>function replace_null($value, $replace) {
    if (!isset($value)) {
        return $replace;
    } else {
        return $value;
    }
}

$address = replace_null($data['address'], 'Address is not available.');
</code>```

of course, if $data['address'] is found null, php will stop executing the code and replace_null won't be called.

i'm currently using ternary

```<code>(isset(data['address']) ? data['address'] : 'Address is not available.');
</code>```

but i think replace_null, if it works, will offer a more convenient way.

is there a function in php that provide the same functionality as vba's Nz()?
any suggestion will be appreciated.

thanks in advance.

答:
```<code><?
function replace_null($value, $replace) {
    if(empty($value) && $value !== '0') {
        return $replace;
    } else {
        return $value;
    }
}

$address = replace_null("0", "replacing null");
echo $address;
?>
</code>```

Title: php null replacement function

Body:
there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.

i try to write the same function in php, which looks like below:

function replace_null($value, $replace) {
    if (!isset($value)) {
        return $replace;
    } else {
        return $value;
    }
}

$address = replace_null($data['address'], 'Address is not available.');

of course, if $data['address'] is found null, php will stop executing the code and replace_null won't be called.

i'm currently using ternary

(isset(data['address']) ? data['address'] : 'Address is not available.');

but i think replace_null, if it works, will offer a more convenient way.

is there a function in php that provide the same functionality as vba's Nz()?
any suggestion will be appreciated.

thanks in advance.


问:
Moving average Python using for loop
My code tries to calculate a moving average of a list, but it computes it incorrectly. Here is the code:</p>
```<code>import numpy as np
import matplotlib.pyplot as plt

for i in a:
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)
    display(Mov_Avg)

plt.plot(Mov_Avg)
</code>```

答:
I see two issues here:

Since you're doing a moving average, once you get to the indices which are less than window_size away from the end of the array a, you'll be out of bound.

for i in a doesn't give you indices to access the array a but the actual values inside the array.

What you want to do is something like this:

import numpy as np

a = np.array([5,3,8,10,2,1,5,1,0,2])
window_size = 2

Mov_Avg = []

for i in range(a.size - window_size + 1):
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)
```
<p>Which gives:</p>
```>>> print(a)
[ 5  3  8 10  2  1  5  1  0  2]
>>> print(Mov_Avg)
[4.0, 5.5, 9.0, 6.0, 1.5, 3.0, 3.0, 0.5, 1.0]
```
<p>Note that since here <code>window_size == 2</code>, you get <code>len(Mov_Avg) == a.size - 1</code>. The general case is in the <code>range</code> above. What you can do to get something a bit cleaner when plotting is this:</p>
<pre class="lang-py prettyprint-override"><code>x_a = np.arange(a.size)
x_Mov_Avg = (x_a + (window_size-1)/2)[:-(window_size-1)]
plt.plot(x_a, a)
plt.plot(x_Mov_Avg, Mov_Avg)
plt.show()
</code>```

This will show the moving average data points at the center of their windows along the x axis.

Title: Moving average Python using for loop

Body:
My code tries to calculate a moving average of a list, but it computes it incorrectly. Here is the code:

import numpy as np
import matplotlib.pyplot as plt

for i in a:
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)
    display(Mov_Avg)

plt.plot(Mov_Avg)

Body:
I see two issues here:

Since you're doing a moving average, once you get to the indices which are less than window_size away from the end of the array a, you'll be out of bound.

for i in a doesn't give you indices to access the array a but the actual values inside the array.

What you want to do is something like this:

import numpy as np

a = np.array([5,3,8,10,2,1,5,1,0,2])
window_size = 2

Mov_Avg = []

for i in range(a.size - window_size + 1):
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)

Which gives:

>>> print(a)
[ 5  3  8 10  2  1  5  1  0  2]
>>> print(Mov_Avg)
[4.0, 5.5, 9.0, 6.0, 1.5, 3.0, 3.0, 0.5, 1.0]

Note that since here window_size == 2, you get len(Mov_Avg) == a.size - 1. The general case is in the range above. What you can do to get something a bit cleaner when plotting is this:

x_a = np.arange(a.size)
x_Mov_Avg = (x_a + (window_size-1)/2)[:-(window_size-1)]
plt.plot(x_a, a)
plt.plot(x_Mov_Avg, Mov_Avg)
plt.show()

This will show the moving average data points at the center of their windows along the x axis.


问:
I cannot understand the results of these simple additions in Javascript. Is there something like rounding affecting?
In Javascript when I do the following additions:

```<code>console.log(42.458333333333336+21)
console.log(42.458333333333336+22)
</code>```

I expected this to output:

```<code>63.458333333333336
64.458333333333336
</code>```

But it does not, it outputs:

```<code>63.458333333333336
64.45833333333334
</code>```

What's going on with that then?

答:
The difference in display is caused by JavaScript’s default formatting of floating-point numbers. JavaScript uses just enough digits to uniquely distinguish the number from adjacent representable values.

When 42.458333333333336 appears in source code, it is converted to the nearest value representable in the Number format, which is 42.45833333333333570180911920033395290374755859375.

Adding 21 to this produces 63.45833333333333570180911920033395290374755859375.  The next higher Number is 63.458333333333342807236476801335811614990234375. If these were rounded to 16 significant decimal digits, they would have the same result, 63.4583333333333. So JavaScript rounds your result to 17 digits to distinguish it, producing “63.458333333333336”.

When 22 is added to 42.45833333333333570180911920033395290374755859375, the result is 64.458333333333342807236476801335811614990234375. Note that this went past 64, so the exponent used to represent it in base-two floating-point has increased. That means it loses some absolute precision. The result was rounded to fit in the floating-point format, so the fraction portion changed.  The next lower Number is 64.4583333333333285963817615993320941925048828125.  For these two numbers, only 16 significant digits are needed to distinguish them, because they round to 64.45833333333334 and 64.45833333333333. So JavaScript produces “64.45833333333334”.

Body:
In Javascript when I do the following additions:

console.log(42.458333333333336+21)
console.log(42.458333333333336+22)

I expected this to output:

63.458333333333336
64.458333333333336

But it does not, it outputs:

63.458333333333336
64.45833333333334

What's going on with that then?


问:
How to redirect user to notFound Page in getServerSideProps whenever an invalid params.id is entered in Next.JS
```<code>export const getServerSideProps = async ({ params }) => {
  const res = await fetch(
    `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${params.id}`
  );

  const { hits } = await res.json();

  if (!hits) {
    return {
      notFound: true,
    };
  }

  return {
    props: { pic: hits[0] },
    notFound: true,
  };
};
</code>```

I keep getting this error whenever a user enter an invalid params.id=====>

Server Error
FetchError: invalid json response body at https://pixabay.com/api/?key=*************************************&id=**xzk** reason: Unexpected token E in JSON at position 1

I used "xzk" as the id value which is invalid and instead of redirecting user to notFoundPage, it keeps showing this error, and the error is even revealing my api-keys. Please what am  I doing wrong? Ideas is also welcome. Thanks in advance.

答:
I've found a solution to this, which is checking if the response is OK. And if it is not Ok then it should redirect the user to notFound page which was set to true in the if statement.</p>
```<code>export const getServerSideProps = async ({ params }) => {
  const { id } = params;

  const res = await fetch(
    `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${id}`
  );

  if (!res.ok) {
    return {
      notFound: true,
    };
  }

  const { hits } = await res.json();

  return {
    props: { pic: hits[0] },
  };
};
</code>```

Body:
export const getServerSideProps = async ({ params }) => {
  const res = await fetch(
    `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${params.id}`
  );

  const { hits } = await res.json();

  if (!hits) {
    return {
      notFound: true,
    };
  }

  return {
    props: { pic: hits[0] },
    notFound: true,
  };
};

I keep getting this error whenever a user enter an invalid params.id=====>

Server Error
FetchError: invalid json response body at https://pixabay.com/api/?key=*************************************&id=**xzk** reason: Unexpected token E in JSON at position 1

I used "xzk" as the id value which is invalid and instead of redirecting user to notFoundPage, it keeps showing this error, and the error is even revealing my api-keys. Please what am  I doing wrong? Ideas is also welcome. Thanks in advance.

Body:
I've found a solution to this, which is checking if the response is OK. And if it is not Ok then it should redirect the user to notFound page which was set to true in the if statement.

export const getServerSideProps = async ({ params }) => {
  const { id } = params;

  const res = await fetch(
    `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${id}`
  );

  if (!res.ok) {
    return {
      notFound: true,
    };
  }

  const { hits } = await res.json();

  return {
    props: { pic: hits[0] },
  };
};