问:
CSS: how to add background but not only in the text
I'm making a copy of the page of Google as a school project and i'm trying to set up the background color of the last part of the footer but it's only filling the color around the letters, how I can fill the whole part of background there?

p {
  padding: 15px 30px;
  font-size: 15px;
  border-bottom: 1px solid #f2f2f2;
  background-color: #f2f2f2;
  color: #70757a;
  display: block;
}

.izq,
.der {
  font-size: 14px;
  color: #70757a;
  margin-block-end: 10px;
  background-color: #f2f2f2;
}

.izq {
  margin-left: 40px;
  float: left;
}

.der {
  margin-right: 40px;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div>
    <p>México</p>
  </div>
  <div id="abajo">Sobre Google
    Publicidad
    Negocios
    Cómo funciona la Búsqueda
    Privacidad
    Condiciones
    Preferencias </div>
</footer></code>```

答:
Use inline-block with background-color to footer

```<code>footer {
      display: inline-block;
      width:100%;
      background: #bbb;
    }
</code>```

This one makes it responsive to fill all background of content,even if it stacks below,as no specific height is gave

p {
  padding: 15px 30px;
  font-size: 15px;
  background-color: #bbb;
  color: #70757a;
  display: block;
  margin-block-end: 0px;
}
.izq, .der {
  font-size: 14px;
  color: #70757a;
  margin-block-end: 10px;
}
.izq {
  margin-left: 40px;
  float:left;
}
.der {
  margin-right: 40px;
  float: right;
}
footer {
  display: inline-block;
  width:100%;
  background: #bbb;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div id="asdf"><p>México</p></div>
  <div id="abajo">
    Sobre Google
    Publicidad
    Negocios
    Cómo funciona la Búsqueda
    Privacidad
    Condiciones
    Preferencias
  </div>
</footer></code>```

Body:
I'm making a copy of the page of Google as a school project and i'm trying to set up the background color of the last part of the footer but it's only filling the color around the letters, how I can fill the whole part of background there?

p {
  padding: 15px 30px;
  font-size: 15px;
  border-bottom: 1px solid #f2f2f2;
  background-color: #f2f2f2;
  color: #70757a;
  display: block;
}

.izq,
.der {
  font-size: 14px;
  color: #70757a;
  margin-block-end: 10px;
  background-color: #f2f2f2;
}

.izq {
  margin-left: 40px;
  float: left;
}

.der {
  margin-right: 40px;
  float: right;
}

México

Sobre Google
    Publicidad
    Negocios
    Cómo funciona la Búsqueda
    Privacidad
    Condiciones
    Preferencias

Body:
Use inline-block with background-color to footer

footer {
      display: inline-block;
      width:100%;
      background: #bbb;
    }

This one makes it responsive to fill all background of content,even if it stacks below,as no specific height is gave

p {
  padding: 15px 30px;
  font-size: 15px;
  background-color: #bbb;
  color: #70757a;
  display: block;
  margin-block-end: 0px;
}
.izq, .der {
  font-size: 14px;
  color: #70757a;
  margin-block-end: 10px;
}
.izq {
  margin-left: 40px;
  float:left;
}
.der {
  margin-right: 40px;
  float: right;
}
footer {
  display: inline-block;
  width:100%;
  background: #bbb;
}

<footer>
  <div id="asdf"><p>México</p></div>
  <div id="abajo">
    <a href="https://about.google/?utm_source=google-MX&utm_medium=referral&utm_campaign=hp-footer&fg=1" class="izq">Sobre Google</a>
    <a href="https://ads.google.com/intl/es-419_mx/home/?subid=ww-ww-et-g-awa-a-g_hpafoot1_1!o2&utm_source=google.com&utm_medium=referral&utm_campaign=google_hpafooter&fg=1" class="izq">Publicidad</a>
    <a href="https://smallbusiness.withgoogle.com/intl/es-419_mx/?subid=ww-ww-et-g-awa-a-g_hpbfoot1_1!o2&utm_source=google&utm_medium=ep&utm_campaign=google_hpbfooter&utm_content=google_hpbfooter&gmbsrc=ww-ww-et-gs-z-gmb-s-z-u~sb-g4sb_srvcs-u&c=MX#!/" class="izq">Negocios</a>
    <a href="https://www.google.com/search/howsearchworks/?fg=1" class="izq">Cómo funciona la Búsqueda</a>
    <a href="https://policies.google.com/privacy?hl=es-419&fg=1" class="der">Privacidad</a>
    <a href="https://policies.google.com/terms?hl=es-419&fg=1" class="der">Condiciones</a>
    <a href="" class="der">Preferencias</a>
  </div>
</footer>


来源: stackexchange

答:
We can do this using a sequence table trick.  Inner join your current table to a sequence on the condition that the quantity be greater than or equal to the sequence value.  For example:

SELECT t1.ID, t1.ProductFK, 1 AS Quantity, t1.Price
FROM yourTable t1
INNER JOIN (SELECT 1 AS Quantity UNION ALL SELECT 2 UNION ALL SELECT 3) t2
    ON t1.Quantity >= t2.Quantity
ORDER BY t1.ID;
```

Demo

ContentLicense: CC BY-SA 4.0

Title: SQL query for below data

Body:
For input, When quantity value greater then 1, convert in a new row with value 1 for quantity column.

INPUT
ID         ProductFK         Quantity       Price
------------------------------------------------
10         1                  2           100
11         2                  3           150
12         1                  1           120

OUTPUT
ID        ProductFK         Quantity        Price
------------------------------------------------
10        1                   1          100
10        1                   1          100
11        2                   1          150
11        2                   1          150
11        2                   1          150
12        1                   1          120

Body:
We can do this using a sequence table trick.  Inner join your current table to a sequence on the condition that the quantity be greater than or equal to the sequence value.  For example:

SELECT t1.ID, t1.ProductFK, 1 AS Quantity, t1.Price
FROM yourTable t1
INNER JOIN (SELECT 1 AS Quantity UNION ALL SELECT 2 UNION ALL SELECT 3) t2
    ON t1.Quantity >= t2.Quantity
ORDER BY t1.ID;

Demo


问:
Conda refuse to install packages from requirements.txt just because of a few outliers, how to fix it?
I'm using requirements.txt to manage my python dependency:

```<code>six
tqdm
future
numpy
brine

scipy
matplotlib

# birdseye
shapely

git+https://github.com/tribbloid/jupyerlab-desktop.git#subdirectory=python
jupytext

# pyre-check
# deprecated

torch >= 1.2.0
# tensorboard
# opencv >= 4.0.0

# prototypes
git+https://github.com/pytorch/vision.git@v0.4.0#egg=torchvision
tb-nightly
</code>```

My environment is a conda env on python 3.7. I was trying to use a few command to install these packages, but when I run:

```<code>conda install --file requirements.txt
</code>```

I got the following error message:

```<code>$ conda install --file ./requirements.txt
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - tb-nightly
  - //github.com/tribbloid/jupyerlab-desktop.git
  - torch[version='>=1.2.0']
  - //github.com/pytorch/vision.git@v0.4.0
  - brine

Current channels:

  - https://conda.anaconda.org/conda-forge/linux-64
  - https://conda.anaconda.org/conda-forge/noarch
  - https://repo.anaconda.com/pkgs/main/linux-64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/linux-64
  - https://repo.anaconda.com/pkgs/r/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

</code>```

It appears that conda refuse to install any of them simply because it can't find 3 packages! (they are on PyPI) What's the point of this design and what should I do to fix it?

My end goal is to use conda if possible, and fallback to pip if they are only on PyPI, the entire process should be reproducible and fully automated.

答:
I thought to try only after installing keras and tensorflow via pip so I can't say 100% that it would've worked for those as well, but everything else in my req file (+50 modules) installed with this command on Win11 in Anaconda Powershell while in the active environment.

conda install -c conda-forge --file requirements.txt

I still don't know why I needed to do this.  Also, I tried another req file that I didn't have a problem with weeks prior.  It also failed as the OP states.  I don't know what I may have done (not done) to cause this.  Perhaps missing a conda update or server down.

Body:
I'm using requirements.txt to manage my python dependency:

six
tqdm
future
numpy
brine

scipy
matplotlib

# birdseye
shapely

git+https://github.com/tribbloid/jupyerlab-desktop.git#subdirectory=python
jupytext

# pyre-check
# deprecated

torch >= 1.2.0
# tensorboard
# opencv >= 4.0.0

# prototypes
git+https://github.com/pytorch/vision.git@v0.4.0#egg=torchvision
tb-nightly

My environment is a conda env on python 3.7. I was trying to use a few command to install these packages, but when I run:

conda install --file requirements.txt

I got the following error message:

$ conda install --file ./requirements.txt
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - tb-nightly
  - //github.com/tribbloid/jupyerlab-desktop.git
  - torch[version='>=1.2.0']
  - //github.com/pytorch/vision.git@v0.4.0
  - brine

Current channels:

  - https://conda.anaconda.org/conda-forge/linux-64
  - https://conda.anaconda.org/conda-forge/noarch
  - https://repo.anaconda.com/pkgs/main/linux-64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/linux-64
  - https://repo.anaconda.com/pkgs/r/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

It appears that conda refuse to install any of them simply because it can't find 3 packages! (they are on PyPI) What's the point of this design and what should I do to fix it?

My end goal is to use conda if possible, and fallback to pip if they are only on PyPI, the entire process should be reproducible and fully automated.


问:
how to import and use spark-dynamodb in my pyspark code
I am trying to write data from a json file to dynamodb. came across spark-dynamodb

how do i import this package in the pyspark script?

答:
The page you linked (GitHub spark-dynamodb) to reads:

Note: When running from pyspark shell, you can add the library as:

pyspark --packages com.audienceproject:spark-dynamodb_<spark-scala-version>:<version>

Does that answer your question?


问:
How to base64 encode a SHA256 hex character string
Hi I need help to get a base64 encoded column, what I got is a sha256 hashed column, I suppose to get 44 characters, but when I try this in python

[base64.b64encode(x.encode('utf-8')).decode() for x in xxx['yyy']]

it returns 88 character, anyone can help with this? Basically I want to achieve the steps showing in the pictures below in Python, thanks!

答:
The step in the first image consist of a few substeps:

a text is entered, but that is just the character representation of a UTF-8 encoding

sha256 hashing is applied to that bytes string

the resulting digest byte sequence is rendered in its hexadecimal representation

So:

```<code>from hashlib import sha256

s = 'user@example.com'

h = sha256()
h.update(s.encode('utf-8'))  # specifying encoding, optional as this is the default
hex_string = h.digest().hex()
print(hex_string)
</code>```

The second image seems to suggest it takes that hex representation as text again, and base64 encodes it - but really it takes the byte string represented by the hex string and encodes that.

So, starting with the hex string:

decode the hex to bytes (reconstructing the digest bytes)

encode the bytes using base64 into an ascii bytes string

decode that resulting bytes string into characters for printing

```<code>from base64 import b64encode

digest_again = bytes.fromhex(hex_string)
b64bytes = b64encode(digest_again)
# no real need to specify 'ascii', the relevant code points overlap with UTF-8:
result = b64bytes.decode('ascii')
print(result)
</code>```

Put together:

```<code>from hashlib import sha256
from base64 import b64encode

s = 'user@example.com'

h = sha256()
h.update(s.encode())
print(h.digest().hex())

b64bytes = b64encode(h.digest())
print(b64bytes.decode())
</code>```

Output:

```<code>b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514
tMmiiTI7IaAcPpQPFQ65uMVCWH8av9jw4cwf/F5HVRQ=
</code>```

Why your code didn't work:

```<code>base64.b64encode('user@example.com'.encode('utf-8')).decode()  # superfluous utf-8
</code>```

This:

encodes the characters 'user@example.com' into bytes using UTF-8

encodes that byte string using base64

decodes the resulting byte string into a character string

Nowhere does it apply SHA256 hashing, nor does it create a hex representation, if you were expecting that. The end result doesn't match because it is the text representation of the base64 encoding of the original text's UTF-8 encoding, not the digest of its SHA256 hash.

Or perhaps I misunderstood and you already had the hex encoding, but you're putting that in as a string:

```<code>x = 'b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514'
base64.b64encode(x.encode()).decode()
</code>```

That does indeed result in a 88 character base64 encoding, because you're not encoding the bytes, you're encoding the hex representation. That would have to be this instead:

```<code>x = 'b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514'
base64.b64encode(bytes.fromhex(x)).decode()
</code>```

... and perhaps that is the answer you were looking for.

Body:
The step in the first image consist of a few substeps:

a text is entered, but that is just the character representation of a UTF-8 encoding

sha256 hashing is applied to that bytes string

the resulting digest byte sequence is rendered in its hexadecimal representation

So:

from hashlib import sha256

s = 'user@example.com'

h = sha256()
h.update(s.encode('utf-8'))  # specifying encoding, optional as this is the default
hex_string = h.digest().hex()
print(hex_string)

The second image seems to suggest it takes that hex representation as text again, and base64 encodes it - but really it takes the byte string represented by the hex string and encodes that.

So, starting with the hex string:

decode the hex to bytes (reconstructing the digest bytes)

encode the bytes using base64 into an ascii bytes string

decode that resulting bytes string into characters for printing

from base64 import b64encode

digest_again = bytes.fromhex(hex_string)
b64bytes = b64encode(digest_again)
# no real need to specify 'ascii', the relevant code points overlap with UTF-8:
result = b64bytes.decode('ascii')
print(result)

Put together:

from hashlib import sha256
from base64 import b64encode

s = 'user@example.com'

h = sha256()
h.update(s.encode())
print(h.digest().hex())

b64bytes = b64encode(h.digest())
print(b64bytes.decode())

Output:

b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514
tMmiiTI7IaAcPpQPFQ65uMVCWH8av9jw4cwf/F5HVRQ=

Why your code didn't work:

base64.b64encode('user@example.com'.encode('utf-8')).decode()  # superfluous utf-8

This:

encodes the characters 'user@example.com' into bytes using UTF-8

encodes that byte string using base64

decodes the resulting byte string into a character string

Nowhere does it apply SHA256 hashing, nor does it create a hex representation, if you were expecting that. The end result doesn't match because it is the text representation of the base64 encoding of the original text's UTF-8 encoding, not the digest of its SHA256 hash.

Or perhaps I misunderstood and you already had the hex encoding, but you're putting that in as a string:

x = 'b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514'
base64.b64encode(x.encode()).decode()

That does indeed result in a 88 character base64 encoding, because you're not encoding the bytes, you're encoding the hex representation. That would have to be this instead:

x = 'b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514'
base64.b64encode(bytes.fromhex(x)).decode()

... and perhaps that is the answer you were looking for.


问:
Creating a vertical color gradient for a geom_bar plot
I have searched and searched, but I cant seem to find an elegant way of doing this!

I have a dataset Data consisting of Data$x (dates) and Data$y (numbers from 0 to 1)

I want to plot them in a bar-chart:

```<code>ggplot(Data) + geom_bar(aes(x = x, y = y, fill = y, stat = "identity")) +
   scale_fill_gradient2(low = "red", high = "green", mid = "yellow", midpoint = 0.90)
</code>```

The result looks like this

However, I wanted to give each bar a gradient in the vertical direction ranging from 0 (red) to y (greener depending on y). Is there any way of doing this smoothly?

I have tried to see if I could impose a picture on the graph as a hack, but I can't impose it on the bars only except in a super super ugly way.

答:
Found a less hacky way to do this when answering Change ggplot bar chart fill colors

library(tidyverse)

df <- data.frame(value = c(20, 50, 90),
                 group = c(1, 2, 3))

df_expanded <- df %>%
  rowwise() %>%
  summarise(group = group,
            value = list(0:value)) %>%
  unnest(cols = value)

df_expanded %>%
  ggplot() +
  geom_tile(aes(
    x = group,
    y = value,
    fill = value,
    width = 0.9
  )) +
  coord_flip() +
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")
```

ContentLicense: CC BY-SA 3.0

Body:
I have searched and searched, but I cant seem to find an elegant way of doing this!

I have a dataset Data consisting of Data$x (dates) and Data$y (numbers from 0 to 1)

I want to plot them in a bar-chart:

ggplot(Data) + geom_bar(aes(x = x, y = y, fill = y, stat = "identity")) +
   scale_fill_gradient2(low = "red", high = "green", mid = "yellow", midpoint = 0.90)

The result looks like this

However, I wanted to give each bar a gradient in the vertical direction ranging from 0 (red) to y (greener depending on y). Is there any way of doing this smoothly?

I have tried to see if I could impose a picture on the graph as a hack, but I can't impose it on the bars only except in a super super ugly way.


问:
Why doesn't &String automatically become &str in some cases?
In this toy example I'd like to map the items from a HashMap<String, String> with a helper function. There are two versions defined, one that takes arguments of the form &String and another with &str. Only the &String one compiles. I had thought that String always dereferences to &str but that doesn't seem to be the case here. What's the difference between a &String and a &str?

use std::collections::HashMap;

// &String works
fn process_item_1(key_value: (&String, &String)) -> String {
    let mut result = key_value.0.to_string();
    result.push_str(", ");
    result.push_str(key_value.1);
    result
}

// &str doesn't work (type mismatch in fn arguments)
fn process_item_2(key_value: (&str, &str)) -> String {
    let mut result = key_value.0.to_string();
    result.push_str(", ");
    result.push_str(key_value.1);
    result
}

fn main() {
    let mut map: HashMap<String, String> = HashMap::new();
    map.insert("a".to_string(), "b".to_string());

    for s in map.iter().map(process_item_2) {  // <-- compile error on this line
        println!("{}", s);
    }
}
```
<p>Here's the error for reference:</p>
```error[E0631]: type mismatch in function arguments
  --> src/main.rs:23:29
   |
12 | fn process_item_2(key_value: (&str, &str)) -> String {
   | ---------------------------------------------------- found signature of `for<'r, 's> fn((&'r str, &'s str)) -> _`
...
23 |     for s in map.iter().map(process_item_2) {
   |                             ^^^^^^^^^^^^^^ expected signature of `fn((&String, &String)) -> _`

```

Thanks for your help with a beginner Rust question!

答:
It goes even stranger than that:

map.iter().map(|s| process_item_2(s)) // Does not work
map.iter().map(|(s1, s2)| process_item_2((s1, s2))) // Works
```

The point is that Rust never performs any expensive coercion. Converting &String to &str is cheap: you just take the data pointer and length. But converting (&String, &String) to (&str, &str) is no so cheap anymore: you have to take the data+length of the first string, then of the second string, then concatnate them together (and also, if it was done for tuple, what about (((&String, &String, &String), &String), (&String, &String))? And it was probably done then for arrays too, so what about &[&String; 10_000]?) That's why the first closure fails. The second closure, however, destruct the tuple and rebuild it. That means that instead of coercing a tuple, we coerce &String twice, and build a tuple from the results. That's fine.

The version without the closure is even more expensive: since you're passing a  function directly to map(), and map produces &String, someone needs to convert this to &str! In order to do that, the compiler would have to introduce a shim - a small function that does that works: it takes (&String, &String) and calls process_item_2() with the (&String, &String) coerced to (&str, &str). This is a hidden cost, so Rust (almost) never creates shims. This is why it wouldn't work even for &String and not just for (&String, &String). And why |v| f(v) is not always the same as f - the first one performs coercions, while the second doesn't.

Body:
In this toy example I'd like to map the items from a HashMap<String, String> with a helper function. There are two versions defined, one that takes arguments of the form &String and another with &str. Only the &String one compiles. I had thought that String always dereferences to &str but that doesn't seem to be the case here. What's the difference between a &String and a &str?

use std::collections::HashMap;

// &String works
fn process_item_1(key_value: (&String, &String)) -> String {
    let mut result = key_value.0.to_string();
    result.push_str(", ");
    result.push_str(key_value.1);
    result
}

// &str doesn't work (type mismatch in fn arguments)
fn process_item_2(key_value: (&str, &str)) -> String {
    let mut result = key_value.0.to_string();
    result.push_str(", ");
    result.push_str(key_value.1);
    result
}

fn main() {
    let mut map: HashMap<String, String> = HashMap::new();
    map.insert("a".to_string(), "b".to_string());

    for s in map.iter().map(process_item_2) {  // <-- compile error on this line
        println!("{}", s);
    }
}

Here's the error for reference:

error[E0631]: type mismatch in function arguments
  --> src/main.rs:23:29
   |
12 | fn process_item_2(key_value: (&str, &str)) -> String {
   | ---------------------------------------------------- found signature of `for<'r, 's> fn((&'r str, &'s str)) -> _`
...
23 |     for s in map.iter().map(process_item_2) {
   |                             ^^^^^^^^^^^^^^ expected signature of `fn((&String, &String)) -> _`

Thanks for your help with a beginner Rust question!

Body:
It goes even stranger than that:

map.iter().map(|s| process_item_2(s)) // Does not work
map.iter().map(|(s1, s2)| process_item_2((s1, s2))) // Works

The point is that Rust never performs any expensive coercion. Converting &String to &str is cheap: you just take the data pointer and length. But converting (&String, &String) to (&str, &str) is no so cheap anymore: you have to take the data+length of the first string, then of the second string, then concatnate them together (and also, if it was done for tuple, what about (((&String, &String, &String), &String), (&String, &String))? And it was probably done then for arrays too, so what about &[&String; 10_000]?) That's why the first closure fails. The second closure, however, destruct the tuple and rebuild it. That means that instead of coercing a tuple, we coerce &String twice, and build a tuple from the results. That's fine.

The version without the closure is even more expensive: since you're passing a  function directly to map(), and map produces &String, someone needs to convert this to &str! In order to do that, the compiler would have to introduce a shim - a small function that does that works: it takes (&String, &String) and calls process_item_2() with the (&String, &String) coerced to (&str, &str). This is a hidden cost, so Rust (almost) never creates shims. This is why it wouldn't work even for &String and not just for (&String, &String). And why |v| f(v) is not always the same as f - the first one performs coercions, while the second doesn't.


问:
Use js to append an ul to an li
yeah you read it right i'm trying to append an ul element in an existing li element and create a sub list. I'm using code from codepen (https://codepen.io/Pestov/pen/AvQmxv) to make a genealogy tree and i would like to create dynamically the tree. For this, i have to create a sub ul element in a previously created li, then had two li to that sub ul.

----EDIT----
My problem is: HierarchyRequestError: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.
Js seems to think that my ul is my parent but in fact it's a new sub ul.

Here's my code:

```<code><div class="tree" id="tree"></div>

function launchTree(){
    var div = document.getElementById("tree");
  var ul = document.createElement("ul");
  var li = document.createElement("li");
  var a = document.createElement("a");
  //create the main ul element
  ul.setAttribute("id", "main_ul");
  div.appendChild(ul)
  //put my first parent
  li.setAttribute("id", "AC_Lila_li");
  a.setAttribute("data-content", "AC Lila");
  a.setAttribute("id", "AC_Lila_a");

  ul.appendChild(li);
  li.appendChild(a);
  //create my sub ul to put childs !!!! here's the problem!!!
  ul.setAttribute("id", "AC_Lila_ul");
  li.appendChild(ul)
  //create my first child
  li.setAttribute("id", "Queen_Elisa_li");
  a.setAttribute("data-content", "Queen Elisa");
  a.setAttribute("id", "Queen_Elisa_a");

  ul.appendChild(li);
  li.appendChild(a);
  //create my second child
  li.setAttribute("id", "Wendy_li");
  a.setAttribute("data-content", "Wendy");
  a.setAttribute("id", "Wendy_a");

  ul.appendChild(li);
  li.appendChild(a);

}
</code>```

I hope i'm clear of what i wanted to do and thanks for your help!

答:
It was so simple, in fact, ul was always the same so i had to define my variables again. Here's the new code:</p>
```<code>function debut(){
    var div = document.getElementById("tree");
  var ul = document.createElement("ul");
  var li = document.createElement("li");
  var a = document.createElement("a");

  ul.setAttribute("id", "main_ul");
  div.appendChild(ul)

  li.setAttribute("id", "AC_Lila_li");
  a.textContent = "AC Lila";
  a.setAttribute("id", "AC_Lila_a");

  ul.appendChild(li);
  li.appendChild(a);

  var ul = document.createElement("ul");

  ul.setAttribute("id", "AC_Lila_ul");
  li.appendChild(ul)

  var li = document.createElement("li");
  var a = document.createElement("a");

  li.setAttribute("id", "Queen_Elisa_li");
  a.setAttribute("onclick","descend_click();");
  a.textContent = "Queen Elisa";
  a.setAttribute("id", "Queen_Elisa_a");

  ul.appendChild(li);
  li.appendChild(a);

  var li = document.createElement("li");
  var a = document.createElement("a");

  li.setAttribute("id", "Wendy_li");
  a.setAttribute("onclick","descend_click();");
  a.textContent = "Wendy";
  a.setAttribute("id", "Wendy_a");

  ul.appendChild(li);
  li.appendChild(a);

}
</code>```

Title: Use js to append an ul to an li

Body:
yeah you read it right i'm trying to append an ul element in an existing li element and create a sub list. I'm using code from codepen (https://codepen.io/Pestov/pen/AvQmxv) to make a genealogy tree and i would like to create dynamically the tree. For this, i have to create a sub ul element in a previously created li, then had two li to that sub ul.

----EDIT----
My problem is: HierarchyRequestError: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.
Js seems to think that my ul is my parent but in fact it's a new sub ul.

Here's my code:

function launchTree(){
    var div = document.getElementById("tree");
  var ul = document.createElement("ul");
  var li = document.createElement("li");
  var a = document.createElement("a");
  //create the main ul element
  ul.setAttribute("id", "main_ul");
  div.appendChild(ul)
  //put my first parent
  li.setAttribute("id", "AC_Lila_li");
  a.setAttribute("data-content", "AC Lila");
  a.setAttribute("id", "AC_Lila_a");

  ul.appendChild(li);
  li.appendChild(a);
  //create my sub ul to put childs !!!! here's the problem!!!
  ul.setAttribute("id", "AC_Lila_ul");
  li.appendChild(ul)
  //create my first child
  li.setAttribute("id", "Queen_Elisa_li");
  a.setAttribute("data-content", "Queen Elisa");
  a.setAttribute("id", "Queen_Elisa_a");

  ul.appendChild(li);
  li.appendChild(a);
  //create my second child
  li.setAttribute("id", "Wendy_li");
  a.setAttribute("data-content", "Wendy");
  a.setAttribute("id", "Wendy_a");

  ul.appendChild(li);
  li.appendChild(a);

}

I hope i'm clear of what i wanted to do and thanks for your help!

Body:
It was so simple, in fact, ul was always the same so i had to define my variables again. Here's the new code:

function debut(){
    var div = document.getElementById("tree");
  var ul = document.createElement("ul");
  var li = document.createElement("li");
  var a = document.createElement("a");

  ul.setAttribute("id", "main_ul");
  div.appendChild(ul)

  li.setAttribute("id", "AC_Lila_li");
  a.textContent = "AC Lila";
  a.setAttribute("id", "AC_Lila_a");

  ul.appendChild(li);
  li.appendChild(a);

  var ul = document.createElement("ul");

  ul.setAttribute("id", "AC_Lila_ul");
  li.appendChild(ul)

  var li = document.createElement("li");
  var a = document.createElement("a");

  li.setAttribute("id", "Queen_Elisa_li");
  a.setAttribute("onclick","descend_click();");
  a.textContent = "Queen Elisa";
  a.setAttribute("id", "Queen_Elisa_a");

  ul.appendChild(li);
  li.appendChild(a);

  var li = document.createElement("li");
  var a = document.createElement("a");

  li.setAttribute("id", "Wendy_li");
  a.setAttribute("onclick","descend_click();");
  a.textContent = "Wendy";
  a.setAttribute("id", "Wendy_a");

  ul.appendChild(li);
  li.appendChild(a);

}


问:
How to keep elements not flooding from Div Flex tag when using overflow-x?
I've been trying to put elements inside a flex row div and I found out that I need to put overflow-x as "scroll" so it works fine on small screens. However, that did not fix the problem but made it worse

This is the HTML code:

```
<p>Here is the CSS code:</p>
<pre class="lang-css prettyprint-override"><code>.section{
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    overflow-x: scroll;
    gap: 5px;
    width: 80%;
    height: 150px;
    border: 1px solid black;
    margin: 0 auto;
    padding: 0;
}

.element{
    width: 100px;
    height: 100px;
    background-color: gray;
    min-width: 100px;
}
</code>```

As shown in the photo above that when I did inspect using Google Chrome, I found out that elements go out of the scrolling box. The photo only shows the first element but it's the same for all of them which is such a problem when there are other things on the same page.

答:
Do any of these examples do what you are looking for?

Overflow visible (default)

Overflow hidden

Overflow hidden with flex wrap

Overflow auto (elements scroll horizontally within the section)

Overflow auto with flex wrap (elements scroll vertically within the section)

.section{
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    gap: 5px;
    width: 80%;
    height: 150px;
    border: 1px solid black;
    margin: 1em auto;
    padding: 0;
}

.element{
    width: 100px;
    height: 100px;
    background-color: gray;
    min-width: 100px;
    color: white;
    padding: 1em;
    box-sizing: border-box;
}

.s2 {
    overflow: hidden;
}
.s3 {
    overflow: hidden;
    flex-wrap: wrap;
}
.s4 {
    overflow: auto;
}
.s5 {
    overflow: auto;
    flex-wrap: wrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>1. Overflow visible (default)</p>
<div class="section s1">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div>
<p>2. Overflow hidden</p>
<div class="section s2">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div>
<p>3. Overflow hidden with flex wrap</p>
<div class="section s3">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div>
<p>4. Overflow auto (elements scroll horizontally within the section)</p>
<div class="section s4">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div>
<p>5. Overflow auto with flex wrap (elements scroll vertically within the section)</p>
<div class="section s5">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div></code>```

Body:
I've been trying to put elements inside a flex row div and I found out that I need to put overflow-x as "scroll" so it works fine on small screens. However, that did not fix the problem but made it worse

This is the HTML code:

Here is the CSS code:

.section{
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    overflow-x: scroll;
    gap: 5px;
    width: 80%;
    height: 150px;
    border: 1px solid black;
    margin: 0 auto;
    padding: 0;
}

.element{
    width: 100px;
    height: 100px;
    background-color: gray;
    min-width: 100px;
}

As shown in the photo above that when I did inspect using Google Chrome, I found out that elements go out of the scrolling box. The photo only shows the first element but it's the same for all of them which is such a problem when there are other things on the same page.

Body:
Do any of these examples do what you are looking for?

Overflow visible (default)

Overflow hidden

Overflow hidden with flex wrap

Overflow auto (elements scroll horizontally within the section)

Overflow auto with flex wrap (elements scroll vertically within the section)

.section{
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    gap: 5px;
    width: 80%;
    height: 150px;
    border: 1px solid black;
    margin: 1em auto;
    padding: 0;
}

.element{
    width: 100px;
    height: 100px;
    background-color: gray;
    min-width: 100px;
    color: white;
    padding: 1em;
    box-sizing: border-box;
}

.s2 {
    overflow: hidden;
}
.s3 {
    overflow: hidden;
    flex-wrap: wrap;
}
.s4 {
    overflow: auto;
}
.s5 {
    overflow: auto;
    flex-wrap: wrap;
}

<p>1. Overflow visible (default)</p>
<div class="section s1">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div>
<p>2. Overflow hidden</p>
<div class="section s2">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div>
<p>3. Overflow hidden with flex wrap</p>
<div class="section s3">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div>
<p>4. Overflow auto (elements scroll horizontally within the section)</p>
<div class="section s4">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div>
<p>5. Overflow auto with flex wrap (elements scroll vertically within the section)</p>
<div class="section s5">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
        <div class="element">7</div>
        <div class="element">8</div>
        <div class="element">9</div>
        <div class="element">10</div>
        <div class="element">11</div>
</div>


问:
Bootstrap 5 tabs arent changing on screen sizes 577px and below
I am able to toggle across the tabs on larger devices but on the smaller devices, it does not work. There are also no errors in the console. The tab is also wrapped in a div that has a z-index of -1. I need it to have a z-index of -1 so that when I scroll up it goes under another div. If I remove the z-index from the wrapper I am able to click the tabs.

I cannot add a higher z-index to the div I'd like these tab items to scroll under because a dropdown list from the navbar will be hidden behind it.

```<code><ul class="nav nav-tabs innerTab" id="profileTab" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#personal" type="button"
            role="tab" aria-controls="personal" aria-selected="true">Personal Information</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="account-tab" data-bs-toggle="tab" data-bs-target="#account" type="button"
            role="tab" aria-controls="account" aria-selected="false">Account
            Information</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="kyc-tab" data-bs-toggle="tab" data-bs-target="#kyc" type="button" role="tab"
            aria-controls="kyc" aria-selected="false">
            Documents</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="password-tab" data-bs-toggle="tab" data-bs-target="#password" type="button"
            role="tab" aria-controls="password" aria-selected="false">Password change</button>
    </li>
</ul>

<div class="tab-content" id="profileTabContent">
    <div class="tab-pane show active" id="personal" role="tabpanel" aria-labelledby="personal-tab">
        P
    </div>
    <div class="tab-pane" id="account" role="tabpanel" aria-labelledby="account-tab">
        A
    </div>
    <div class="tab-pane" id="kyc" role="tabpanel" aria-labelledby="kyc-tab">K
    </div>
    <div class="tab-pane" id="password" role="tabpanel" aria-labelledby="password-tab">P
    </div>
</div>
</code>```

答: Did u tried wrap or change containers into "label", may be need add them display: block; and remove some padding/margin to keep your layout</p>

Body:
I am able to toggle across the tabs on larger devices but on the smaller devices, it does not work. There are also no errors in the console. The tab is also wrapped in a div that has a z-index of -1. I need it to have a z-index of -1 so that when I scroll up it goes under another div. If I remove the z-index from the wrapper I am able to click the tabs.

I cannot add a higher z-index to the div I'd like these tab items to scroll under because a dropdown list from the navbar will be hidden behind it.

        <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#personal" type="button"
            role="tab" aria-controls="personal" aria-selected="true">Personal Information</button>

        <button class="nav-link" id="account-tab" data-bs-toggle="tab" data-bs-target="#account" type="button"
            role="tab" aria-controls="account" aria-selected="false">Account
            Information</button>

        <button class="nav-link" id="kyc-tab" data-bs-toggle="tab" data-bs-target="#kyc" type="button" role="tab"
            aria-controls="kyc" aria-selected="false">
            Documents</button>

        <button class="nav-link" id="password-tab" data-bs-toggle="tab" data-bs-target="#password" type="button"
            role="tab" aria-controls="password" aria-selected="false">Password change</button>

        P

        A

K

P


问:
momentjs datetime format on frontend with angular
I'm using currently moment.js in my project. I want to remove "T" and +02:00. There must be a date and time only. But if I use the .format() method of moment.js I get the default datetime.

I want to format this datetime:

from ' 2022-02-11T04:20:13+02:00 ' to ' 2022-02-11 04:20:13 '

back

```<code>import * as moment from 'moment';

date_times: any;
constructor() {
this.date_times =  moment().format('YYYY-MM-DD HH:mm:ss');
}
</code>```

front

```<code> <ion-item>
  <ion-label>Select date & time</ion-label>
  <ion-datetime displayFormat="D MMM YYYY H:mm A" (ionChange)="showdate()" [(ngModel)]="date_times"></ion-datetime>
</ion-item>

{{date_times }}
</code>```

答:
moment().format('YYYY-MM-DD HH:mm:ss') will give you the format you want but since you are using date_times as the ngModel of <ion-datetime> component, its value has been changed after you initialized the value in the constructor().

You can format date_times when you print it out by using Pipe like this:

my-datetime-format.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
  name: 'myDateTimeFormat'
})
export class myDateTimeFormatPipe implements PipeTransform {
  transform(value: string): string {
    return moment(value).format('YYYY-MM-DD HH:mm:ss');
  }
}
```
<p><strong>In template</strong>:</p>
<pre class="lang-js prettyprint-override"><code>{{ date_times | myDateTimeFormat }}
</code>```

Body:
I'm using currently moment.js in my project. I want to remove "T" and +02:00. There must be a date and time only. But if I use the .format() method of moment.js I get the default datetime.

I want to format this datetime:

from ' 2022-02-11T04:20:13+02:00 ' to ' 2022-02-11 04:20:13 '

back

import * as moment from 'moment';

date_times: any;
constructor() {
this.date_times =  moment().format('YYYY-MM-DD HH:mm:ss');
}

front

 <ion-item>
  <ion-label>Select date & time</ion-label>
  <ion-datetime displayFormat="D MMM YYYY H:mm A" (ionChange)="showdate()" [(ngModel)]="date_times"></ion-datetime>
</ion-item>

{{date_times }}

Body:
moment().format('YYYY-MM-DD HH:mm:ss') will give you the format you want but since you are using date_times as the ngModel of <ion-datetime> component, its value has been changed after you initialized the value in the constructor().

You can format date_times when you print it out by using Pipe like this:

my-datetime-format.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
  name: 'myDateTimeFormat'
})
export class myDateTimeFormatPipe implements PipeTransform {
  transform(value: string): string {
    return moment(value).format('YYYY-MM-DD HH:mm:ss');
  }
}

In template:

{{ date_times | myDateTimeFormat }}


问:
Why do I get a negative number when subtracting pointers?
The following program gives -1, but I expected it to print 1:

```<code>#include <iostream>
int main()
{
    int a[] = {0, 1};
    int* p = a;
    int* p2 = a+1;

    std::cout << p - p2 << std::endl;
    system("PAUSE");
    return 0;
}
</code>```

If I swap the subtraction around like this:

```<code>std::cout << p2 - p << std::endl;
</code>```

Then I get exactly 1.

The answer to Pointer subtraction confusion says that if we subtract pointer from pointer, we get the amount of blocks of memory lying between them, and I don't see that this can be negative.

I'm expecting to get exactly the same result for p - p2 and p2 - p.

答: Maybe think about it this way. Subtracting two pointers such as p1 - p2 yields the number that, when added to p2 yields p1</p>

Body:
The following program gives -1, but I expected it to print 1:

#include <iostream>
int main()
{
    int a[] = {0, 1};
    int* p = a;
    int* p2 = a+1;

    std::cout << p - p2 << std::endl;
    system("PAUSE");
    return 0;
}

If I swap the subtraction around like this:

std::cout << p2 - p << std::endl;

Then I get exactly 1.

The answer to Pointer subtraction confusion says that if we subtract pointer from pointer, we get the amount of blocks of memory lying between them, and I don't see that this can be negative.

I'm expecting to get exactly the same result for p - p2 and p2 - p.


问:
Tab replaced to space automatically in Delphi11
I'm using delphi 11.0(28.0.42600.6491).
Typing some tabs in code editor, and after a short pause, typing any character.
Then, I found tabs are replaced to space automatically.

And it seems to be happened when input character after already exists line.
My problem is like GIF image(animated).

I don't want that. tabs must be tabs strictly.
Is there any setting or way to do that?

答:
The IDE Settings "Use tab character" and "Keep trailing blanks". Note you would also need to uncheck "Cursor through tabs" to see the cursor jump otherwise it will go space by space through tabs.

The "Keep trailing blanks" setting is really "Keep trailing whitespace" and deletes any tabs and spaces at the end of lines after a short delay.  The cursor stays past the end of the line so if you type something it then puts in spaces.


问:
Return both OUT parameters and a rowset
I would like to return both output parametrs and a rowset.

In DB2, I can accomplish this with the following, and opening a cursor before the stored procedure ended:

```<code>CREATE PROCEDURE rqstprtl.getInfo (
    IN  id  BIGINT,
    OUT var1    CHAR(6),
    OUT var2    BIGINT
)
DYNAMIC RESULT SETS 1
</code>```

I'm unsure how to accomplish the same thing with PostgreSQL functions. My understanding is that functions have a return type of record (or no return type) for functions that have output parameters, but I would also need a return type of setof record to return the rowset.

答:
You can use a refcursor instead, so one OUT parameter should be a refcursor type.

Pavel

Title: Return both OUT parameters and a rowset

Body:
I would like to return both output parametrs and a rowset.

In DB2, I can accomplish this with the following, and opening a cursor before the stored procedure ended:

CREATE PROCEDURE rqstprtl.getInfo (
    IN  id  BIGINT,
    OUT var1    CHAR(6),
    OUT var2    BIGINT
)
DYNAMIC RESULT SETS 1

I'm unsure how to accomplish the same thing with PostgreSQL functions. My understanding is that functions have a return type of record (or no return type) for functions that have output parameters, but I would also need a return type of setof record to return the rowset.


问:
SQL date conversion to mm/dd/yyyy hh:mm
Can't seem to find answer to what seems like a simple question. I have a date that is returned
2022-02-07 18:53:36.000 I need to convert that date to mm/dd/yyyy hh:mm.
Is that possible?

答: select convert(varchar, getdate(), 13);</p>

Title: SQL date conversion to mm/dd/yyyy hh:mm

Body: select convert(varchar, getdate(), 13);


问:
inserting formula and drag down based on other column
I try to surf the internet and try all the possible answer but still got the 1004 error application or object defined error

here's my code:

```<code> Sub Status()
Sheets(1).Range("D6").FormulaR1C1 = "=IFERROR(VLOOKUP(RC3,'Form Capex HRGA'!R6C3:R2000C12,4,0),IFERROR(VLOOKUP(RC3,'Form Capex HRGA'!R6C5:R2000C12,2,0),IFERROR(VLOOKUP(RC3,'Form Capex IT'!R6C3:R2000C12,4,0),IFERROR(VLOOKUP(RC3,'Form Capex IT'!R6C5:R2000C12,2,0),IFERROR(VLOOKUP(RC3,'Form Capex LDD'!R6C3:R2000C12,4,0),IFERROR(VLOOKUP(RC3,'Form Capex LDD'!R6C5:R2000C12,2,0),IFERROR(VLOOKUP(RC3,'Form Capex" & _
        "C3:R2000C12,4,0),VLOOKUP(RC3,'Form Capex NPD'!R6C5:R2000C12,2,0))))))))"
Selection.AutoFill Destination:=Range("d6:d" & Range("c" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select
End Sub
</code>```

the code should insert d6 with formula and fill down based on column C because column C is not always in same amount (sometimes it gets 100 or more or perhaps less) so I insert the code below the formula.

When I try to run it, the formula part always been highlighted. Any idea what my mistake is? please help correct my code

thank you

答:
just found my mistake

thanks to Chris (on the comment) that my formula is not complete

for the mistake of autofill, I use this code

lr = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row

Sheets(1).Range("D6:S6").Autofill Range("D6:S" & lr)

Body:
I try to surf the internet and try all the possible answer but still got the 1004 error application or object defined error

here's my code:

 Sub Status()
Sheets(1).Range("D6").FormulaR1C1 = "=IFERROR(VLOOKUP(RC3,'Form Capex HRGA'!R6C3:R2000C12,4,0),IFERROR(VLOOKUP(RC3,'Form Capex HRGA'!R6C5:R2000C12,2,0),IFERROR(VLOOKUP(RC3,'Form Capex IT'!R6C3:R2000C12,4,0),IFERROR(VLOOKUP(RC3,'Form Capex IT'!R6C5:R2000C12,2,0),IFERROR(VLOOKUP(RC3,'Form Capex LDD'!R6C3:R2000C12,4,0),IFERROR(VLOOKUP(RC3,'Form Capex LDD'!R6C5:R2000C12,2,0),IFERROR(VLOOKUP(RC3,'Form Capex" & _
        "C3:R2000C12,4,0),VLOOKUP(RC3,'Form Capex NPD'!R6C5:R2000C12,2,0))))))))"
Selection.AutoFill Destination:=Range("d6:d" & Range("c" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select
End Sub

the code should insert d6 with formula and fill down based on column C because column C is not always in same amount (sometimes it gets 100 or more or perhaps less) so I insert the code below the formula.

When I try to run it, the formula part always been highlighted. Any idea what my mistake is? please help correct my code

thank you


问:
Edit/Modify Uri referenced file using FileOutputStream Android
I am using ActivityResultLauncher to fetch uri of a file. Now I want to modify that file using fileoutputStream but can't, since fileoutputstream need path string. Here is a code that I am using to get File Uri:

```<code>ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // There are no request codes
                    Intent data = result.getData();
                    Uri uri = data.getData();//this gets me URI

                }
            }
      });

public void openFileChooser()
{
    Intent data = new Intent(Intent.ACTION_GET_CONTENT);
    data.addCategory(Intent.CATEGORY_OPENABLE);
    data.setType("*/*");
    data = Intent.createChooser(data, "Choose a file");
    Intent intent = Intent.createChooser(data, "Choose a file");
    someActivityResultLauncher.launch(intent);
}
</code>```

The code works perfect for picking and reading file. But I am not able to use below mentioned function to write same file using:

```<code>static void writeToFile(String path,String data,Context context) {
    try {
        FileOutputStream output = null;
        output = new FileOutputStream(path, false);
        output.write(data.getBytes());
        output.close();
        Toast.makeText(getApplicationContext(),"SAVED",Toast.LENGTH_LONG).show();
    }
    catch (IOException e) {
        Toast.makeText(getApplicationContext(),"File write failed: " + e.toString(),Toast.LENGTH_LONG).show();
    }
}
</code>```

I have tried uri.getPath() but it is returning /document/msf:21. That is some complicated uri string and can't be used as file path. I have also been trying to use realPath functions mentioned in stackflow and other forums but do not find it working (they may work but they are depending upon API levels that making them not reliable).  So, what actually want to ask:

1- Is there any other way to pick file to get actual path?

2- If there is no way to pick path, how can I write to File using direct Uri? and not using getpath or path string.

3- Is there a way to use fileoutstream with Uri in this scenario where Uri is only available?

Thanks

答:
You need to pass it through input stream amd buffer reader with output stream.

Try this on start intent

```<code>Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_TITLE, "JWI.pdf");
startActivityForResult(intent, CREATE_FILE);
</code>```

Try this on activity result

```<code>try {
uri = _data.getData();
muri = uri.toString();
t.edit().putString("Uri", muri).commit();

final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
getContentResolver().takePersistableUriPermission(uri, takeFlags);

DocumentFile doc = DocumentFile.fromSingleUri(this, uri);
boolean doo = doc.exists();
if (!doo) {
DocumentFile f = doc.createFile("pdf/plain", "JAMZ.pdf");}

ContentResolver cr = getContentResolver(); OutputStream output =
cr.openOutputStream(uri);
java.io.InputStream asset = getAssets().open("JWI.pdf");

final byte[] buffer = new byte[1024];

int size;

while ((size = asset.read(buffer)) != -1) {

output.write(buffer, 0, size);

}

asset.close();

output.close();
} catch (Exception e) {}}}
</code>```

Body:
I am using ActivityResultLauncher to fetch uri of a file. Now I want to modify that file using fileoutputStream but can't, since fileoutputstream need path string. Here is a code that I am using to get File Uri:

ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // There are no request codes
                    Intent data = result.getData();
                    Uri uri = data.getData();//this gets me URI

                }
            }
      });

public void openFileChooser()
{
    Intent data = new Intent(Intent.ACTION_GET_CONTENT);
    data.addCategory(Intent.CATEGORY_OPENABLE);
    data.setType("*/*");
    data = Intent.createChooser(data, "Choose a file");
    Intent intent = Intent.createChooser(data, "Choose a file");
    someActivityResultLauncher.launch(intent);
}

The code works perfect for picking and reading file. But I am not able to use below mentioned function to write same file using:

static void writeToFile(String path,String data,Context context) {
    try {
        FileOutputStream output = null;
        output = new FileOutputStream(path, false);
        output.write(data.getBytes());
        output.close();
        Toast.makeText(getApplicationContext(),"SAVED",Toast.LENGTH_LONG).show();
    }
    catch (IOException e) {
        Toast.makeText(getApplicationContext(),"File write failed: " + e.toString(),Toast.LENGTH_LONG).show();
    }
}

I have tried uri.getPath() but it is returning /document/msf:21. That is some complicated uri string and can't be used as file path. I have also been trying to use realPath functions mentioned in stackflow and other forums but do not find it working (they may work but they are depending upon API levels that making them not reliable).  So, what actually want to ask:

1- Is there any other way to pick file to get actual path?

2- If there is no way to pick path, how can I write to File using direct Uri? and not using getpath or path string.

3- Is there a way to use fileoutstream with Uri in this scenario where Uri is only available?

Thanks

Body:
You need to pass it through input stream amd buffer reader with output stream.

Try this on start intent

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_TITLE, "JWI.pdf");
startActivityForResult(intent, CREATE_FILE);

Try this on activity result

try {
uri = _data.getData();
muri = uri.toString();
t.edit().putString("Uri", muri).commit();

final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
getContentResolver().takePersistableUriPermission(uri, takeFlags);

DocumentFile doc = DocumentFile.fromSingleUri(this, uri);
boolean doo = doc.exists();
if (!doo) {
DocumentFile f = doc.createFile("pdf/plain", "JAMZ.pdf");}

ContentResolver cr = getContentResolver(); OutputStream output =
cr.openOutputStream(uri);
java.io.InputStream asset = getAssets().open("JWI.pdf");

final byte[] buffer = new byte[1024];

int size;

while ((size = asset.read(buffer)) != -1) {

output.write(buffer, 0, size);

}

asset.close();

output.close();
} catch (Exception e) {}}}


问:
Get column from a two dimensional array
How can I retrieve a column from a 2-dimensional array and not a single entry?
I'm doing this because I want to search for a string in one of the columns only so if there is another way to accomplish this please tell me.

I'm using the array defined this way:

```<code>var array=[];
</code>```

At the end the size of this array is 20(col)x3(rows) and I need to read the first row and check the existence of some phrase in it.

答:
There is also a way involved using .bind().

```<code>function getColumn(twoDArr,columnIndex){
    function getCol(value){
       return [value[columnIndex]]
    }
    return twoDArr.map(getCol.bind(columnIndex));
}
</code>```

Title: Get column from a two dimensional array

Body:
How can I retrieve a column from a 2-dimensional array and not a single entry?
I'm doing this because I want to search for a string in one of the columns only so if there is another way to accomplish this please tell me.

I'm using the array defined this way:

var array=[];

At the end the size of this array is 20(col)x3(rows) and I need to read the first row and check the existence of some phrase in it.

Body:
There is also a way involved using .bind().

function getColumn(twoDArr,columnIndex){
    function getCol(value){
       return [value[columnIndex]]
    }
    return twoDArr.map(getCol.bind(columnIndex));
}


问:
How to set Routes Group in Go Fiber V2 from separated file?
I  want to make seperate files for each sub main routes. I am using go 1.17

main.go

```<code>package main

import (
    "rolling_glory_go/routes"

    "github.com/gofiber/fiber/v2"
)

func main() {
    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
        err := c.SendString("Hello golang!")
        return err
    })

    routes.R_login(app.Group("/login"))
    routes.R_users(app.Group("/users"))

    app.Listen(":3000")
}
</code>```

I want to import routes from r_login.go and r_users.go so i could manage many routes from different files and not put many routes from single file in main.go. I got an error like this.

```<code>.\main.go:17:26: cannot use app.Group("/login") (type fiber.Router) as type *fiber.Group in argument to routes.R_login: need type assertion
.\main.go:18:26: cannot use app.Group("/users") (type fiber.Router) as type *fiber.Group in argument to routes.R_users: need type assertion

</code>```

My Structure Folder

r_login.go

```<code>package routes

import "github.com/gofiber/fiber/v2"

func R_login(router *fiber.Group) {
    router.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("respond with a resource")
    })
}
</code>```

r_users.go

```<code>package routes

import "github.com/gofiber/fiber/v2"

func R_users(router *fiber.Group) {
    router.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("respond with a resource")
    })
}

</code>```

How to fix this ?

答:
As you have app.Group("/login") which of type fiber.Router
, just modify R_login to have it accept this type.

```<code>package routes

import "github.com/gofiber/fiber/v2"

func R_login(router fiber.Router) {
    router.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("respond with a resource")
    })
}
</code>```

Body:
I  want to make seperate files for each sub main routes. I am using go 1.17

main.go

package main

import (
    "rolling_glory_go/routes"

    "github.com/gofiber/fiber/v2"
)

func main() {
    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
        err := c.SendString("Hello golang!")
        return err
    })

    routes.R_login(app.Group("/login"))
    routes.R_users(app.Group("/users"))

    app.Listen(":3000")
}

I want to import routes from r_login.go and r_users.go so i could manage many routes from different files and not put many routes from single file in main.go. I got an error like this.

.\main.go:17:26: cannot use app.Group("/login") (type fiber.Router) as type *fiber.Group in argument to routes.R_login: need type assertion
.\main.go:18:26: cannot use app.Group("/users") (type fiber.Router) as type *fiber.Group in argument to routes.R_users: need type assertion

My Structure Folder

r_login.go

package routes

import "github.com/gofiber/fiber/v2"

func R_login(router *fiber.Group) {
    router.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("respond with a resource")
    })
}

r_users.go

package routes

import "github.com/gofiber/fiber/v2"

func R_users(router *fiber.Group) {
    router.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("respond with a resource")
    })
}

How to fix this ?

Body:
As you have app.Group("/login") which of type fiber.Router
, just modify R_login to have it accept this type.

package routes

import "github.com/gofiber/fiber/v2"

func R_login(router fiber.Router) {
    router.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("respond with a resource")
    })
}


问:
ODBC connection to ACCDB in web.config
Want to connect to ACCDB file as an ODBC (rather than OleDb) data source in ASP.NET but struggling with the connection string. As I plan to deploy the web app from Visual Studio 2019 to Azure, I need something that can make the journey.

Here's what I tried from connectionstrings.com (I discovered not all of those strings are up to date or necessarily convenient for insertion to web.config):

```<code>Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\mydatabase.accdb;Uid=Admin;Pwd=;
</code>```

This returns keyword not supported: driver from IIS Express where I'm doing development.

答:
Hum, that looks ok:

I would suggest this:

```<code>Driver={Microsoft Access Driver (*.mdb, *.accdb)};
dbq=C:\test\test44.accdb;driverid=25;fil=MS Access;
maxbuffersize=2048;maxscanrows=8;pagetimeout=5;safetransactions=0;
threads=3;uid=admin;usercommitsync=Yes
</code>```

the above is what the connection builder in Visual Studio spits out.
and you have Dbq - carefull - caps I believe matters - so try dbq.

Next up:
HUGE HUGE elephant in the room.

are you using a x32 bit driver, or the x64 bit one? YOU MUST match your project bit size (code compile) settings to the driver (YOU MUST!!!).

So this:

you MUST set and force your project to run as x32 bits. (or perhaps install the x64 bit version of Access drivers. AND BE careful. If you are running the x64 bit versions of the drivers, and use Test connection with Visual Studio? It will always fail since VS runs as a x32 bit applcation. you MUST RUN the applcation to test the connection - NOT use test connection with VS connection builders (you might not be using them, but if you are, just trying to save you a day of work wasted).

so, create a x32 config project. And thus this now:

And I assume your sample connection using c: or "root" of the drive is a JUST a example, since most windows now don't allow a file to be used directly from c: root location.

Title: ODBC connection to ACCDB in web.config

Body:
Want to connect to ACCDB file as an ODBC (rather than OleDb) data source in ASP.NET but struggling with the connection string. As I plan to deploy the web app from Visual Studio 2019 to Azure, I need something that can make the journey.

Here's what I tried from connectionstrings.com (I discovered not all of those strings are up to date or necessarily convenient for insertion to web.config):

Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\mydatabase.accdb;Uid=Admin;Pwd=;

This returns keyword not supported: driver from IIS Express where I'm doing development.

Body:
Hum, that looks ok:

I would suggest this:

Driver={Microsoft Access Driver (*.mdb, *.accdb)};
dbq=C:\test\test44.accdb;driverid=25;fil=MS Access;
maxbuffersize=2048;maxscanrows=8;pagetimeout=5;safetransactions=0;
threads=3;uid=admin;usercommitsync=Yes

the above is what the connection builder in Visual Studio spits out.
and you have Dbq - carefull - caps I believe matters - so try dbq.

Next up:
HUGE HUGE elephant in the room.

are you using a x32 bit driver, or the x64 bit one? YOU MUST match your project bit size (code compile) settings to the driver (YOU MUST!!!).

So this:

you MUST set and force your project to run as x32 bits. (or perhaps install the x64 bit version of Access drivers. AND BE careful. If you are running the x64 bit versions of the drivers, and use Test connection with Visual Studio? It will always fail since VS runs as a x32 bit applcation. you MUST RUN the applcation to test the connection - NOT use test connection with VS connection builders (you might not be using them, but if you are, just trying to save you a day of work wasted).

so, create a x32 config project. And thus this now:

And I assume your sample connection using c: or "root" of the drive is a JUST a example, since most windows now don't allow a file to be used directly from c: root location.


问:
Handling the "IndexError: string index out of range" error
I have the following string my_string:

```<code>my_string = 'A15B27C32D72A7B14C9D31'
</code>```

I split this string into chunks by the character A:

```<code>chunks = ['A' + elem for elem in my_string.split('A') if elem != '']

chunks
['A15B27C32D72', 'A7B14C9D31']
</code>```

I'd like to be able to check whether there is a number associated with the "D" character of each chunk.  To do this, I use:

```<code>for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])
</code>```

(Technically, this isn't correct since it won't catch cases whereby the number isn't a single digit.)

Now, let's change my_string to:

```<code>my_string = 'A15B27C32DA7B14C9D31'

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']
chunks
['A15B27C32D', 'A7B14C9D31']
</code>```

(notice that D in the first chunk doesn't have an associated number)

If I run the following:

```<code>for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])
</code>```

I get:

```<code>IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8844/1838165888.py in <module>
      1 for elem in chunks:
----> 2     if elem[elem.find('D') + 1].isdigit() is False:
      3         print('no number associated with D')
      4     else:
      5         print('the number associated with D is', elem[elem.find('D') +1])

IndexError: string index out of range
</code>```

To fix this, I can use try/except.

I can also use the following:

```<code>for elem in chunks:
    if elem[-1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

no number associated with D
the number associated with D is 3
</code>```

But, both of these approaches feel somewhat hacky.

Is there a more elegant and idiomatic way to handle the string index out of range error?

Thanks!

答:
I'd use split again with an int conversion inside a try/except to validate that the thing after the D is a number.

```<code>>>> my_string = 'A15B27C32D72A7B14C9D31'
>>> for elem in filter(bool, my_string.split("A")):
...     try:
...         print(f"the number associated with D is {int(elem.split('D')[-1])}")
...     except ValueError:
...         print("no number associated with D")
...
the number associated with D is 72
the number associated with D is 31
</code>```

Body:
I have the following string my_string:

my_string = 'A15B27C32D72A7B14C9D31'

I split this string into chunks by the character A:

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']

chunks
['A15B27C32D72', 'A7B14C9D31']

I'd like to be able to check whether there is a number associated with the "D" character of each chunk.  To do this, I use:

for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

(Technically, this isn't correct since it won't catch cases whereby the number isn't a single digit.)

Now, let's change my_string to:

my_string = 'A15B27C32DA7B14C9D31'

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']
chunks
['A15B27C32D', 'A7B14C9D31']

(notice that D in the first chunk doesn't have an associated number)

If I run the following:

for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

I get:

IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8844/1838165888.py in <module>
      1 for elem in chunks:
----> 2     if elem[elem.find('D') + 1].isdigit() is False:
      3         print('no number associated with D')
      4     else:
      5         print('the number associated with D is', elem[elem.find('D') +1])

IndexError: string index out of range

To fix this, I can use try/except.

I can also use the following:

for elem in chunks:
    if elem[-1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

no number associated with D
the number associated with D is 3

But, both of these approaches feel somewhat hacky.

Is there a more elegant and idiomatic way to handle the string index out of range error?

Thanks!

Body:
I'd use split again with an int conversion inside a try/except to validate that the thing after the D is a number.

>>> my_string = 'A15B27C32D72A7B14C9D31'
>>> for elem in filter(bool, my_string.split("A")):
...     try:
...         print(f"the number associated with D is {int(elem.split('D')[-1])}")
...     except ValueError:
...         print("no number associated with D")
...
the number associated with D is 72
the number associated with D is 31


问:
React Native expo-location: How to make the background location service update more often?
I'm building a sports app with Expo / React Native and trying to figure out a good way to track user location while the app is in the background. I have built a solution with expo-location (https://docs.expo.io/versions/latest/sdk/location/#locationstartlocationupdatesasynctaskname-options) which successfully receives location updates, and I even managed to send the location updates to the UI with the help of an EventEmitter.

Now the problem here is, the Expo Location task keeps the location updates deferred for a VERY long time (like 12 minutes) before sending a location update to the UI. This is despite setting all the relevant options to zero or very small.

I would love to use Expo Location because I got it mostly working, but unbelievably it seems that the library lacks an option/tool to force the background task to send updates often enough (like once in 5 seconds).

I would be grateful if anyone had a solution to really making the Expo background location send updates often enough. Now it sends updates "when I feel like it", about once in 5 or 12 minutes, despite setting all the relevant options and parameters I found in the documentation.

I already came to the conclusion that Expo background location is practically broken and I should switch to another location library (https://github.com/mauron85/react-native-background-geolocation). However I'm using Expo managed workflow and installing this mauron85 location library (otherwise really promising) doesn't work, because it requires setting manually dependencies --> I need to eject from Expo managed workflow --> ejecting breaks my project structure in a way I don't know how to solve. Really frustrating!

Relevant parts of my code:

top part:

```<code>import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
import EventEmitter from 'EventEmitter'

const locationEmitter = new EventEmitter();

const BACKGROUND_LOCATION_TRACKER = 'BACKGROUND_LOCATION_TRACKER'
const LOCATION_UPDATE = 'LOCATION_UPDATE'
</code>```

componentDidMount after requesting location permissions:

```<code>await Location.startLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKER, {
            accuracy: LocationAccuracy.BestForNavigation,
            timeInterval: 0,  // all set to 0 to make it update as often as possible!!! doesn't help
            distanceInterval: 0,
            deferredUpdatesInterval: 0,
            deferredUpdatesDistance: 0,
            showsBackgroundLocationIndicator: true,
            foregroundService: {
                notificationTitle: 'title',
                notificationBody: 'recording',
                notificationColor: '#008000',
            },
            // pausesUpdatesAutomatically: true,

        });

    locationEmitter.on(LOCATION_UPDATE, (locationData) => {
        console.log('locationEmitter locationUpdate fired! locationData: ', locationData);
        let coordinatesAmount = locationData.newRouteCoordinates.length - 1;
        this.setState({
            latitude: locationData.newRouteCoordinates[coordinatesAmount - 1].latitude,
            longitude: locationData.newRouteCoordinates[coordinatesAmount - 1].longitude,
            routeCoordinates: this.state.routeCoordinates.concat(locationData.newRouteCoordinates)
        })
    })
</code>```

define location task:

```<code>TaskManager.defineTask(BACKGROUND_LOCATION_TRACKER, async ({ data, error }) => {
    if (error) {
        console.error(error);
        return;
    }

    if (data) {
        const { locations } = data;
        console.log('backgroundLocationTracker received new locations: ', locations)

        // const [location] = locations;
        const locationsLength = locations.length;

        const newRouteCoordinates = [];
        // const totalNewDistance = 0.0;

        for (i = 0; i < locationsLength; i++) {
            const { latitude, longitude } = locations[i].coords;
            const tempCoords = {
                latitude,
                longitude,
            };
            newRouteCoordinates.push(tempCoords);
            // totalNewDistance += GLOBAL.screen1.calcDistance(newRouteCoordinates[i], newRouteCoordinates[i - 1])
        };

        console.log('backgroundLocationTracker: latitude ', locations[locationsLength - 1].coords.latitude,
            ', longitude: ', locations[locationsLength - 1].coords.longitude, ', routeCoordinates: ', newRouteCoordinates,
            ', prevLatLng: ', newRouteCoordinates[locationsLength - 1]);

        let locationData = { newRouteCoordinates }

        locationEmitter.emit(LOCATION_UPDATE, locationData)

    }

});
</code>```

As I said, it all WORKS (!) in the sense that I do get location updates from the background to the UI. The only problem here is that I can't figure out how to make the background task send location updates more often! It just keeps collecting a huge batch of 50+ location updates for even 10+ minutes before it bothers to send them to the UI!

All help appreciated, thanks.

答:
I thought I would have to eject from expo too, but I changed my options and now it updates just as I intended.
The problem was the acuracy, I switched to "best for navigation" just as your example and it worked.
Here is my options, I think you should try to define some milisseconds, don't leave interval at 0 and don't set distance interval nor defered distance:</p>
```<code>{accuracy: Location.Accuracy.BestForNavigation,
            timeInterval: 1000,
            showsBackgroundLocationIndicator: true,
            foregroundService:{
                notificationTitle: "Covid Tracker",
                notificationBody: "Rastreando sua localização",
                notificationColor: "#AA1111"
            },
            deferredUpdatesInterval: 100
        }
</code>```

Body:
I'm building a sports app with Expo / React Native and trying to figure out a good way to track user location while the app is in the background. I have built a solution with expo-location (https://docs.expo.io/versions/latest/sdk/location/#locationstartlocationupdatesasynctaskname-options) which successfully receives location updates, and I even managed to send the location updates to the UI with the help of an EventEmitter.

Now the problem here is, the Expo Location task keeps the location updates deferred for a VERY long time (like 12 minutes) before sending a location update to the UI. This is despite setting all the relevant options to zero or very small.

I would love to use Expo Location because I got it mostly working, but unbelievably it seems that the library lacks an option/tool to force the background task to send updates often enough (like once in 5 seconds).

I would be grateful if anyone had a solution to really making the Expo background location send updates often enough. Now it sends updates "when I feel like it", about once in 5 or 12 minutes, despite setting all the relevant options and parameters I found in the documentation.

I already came to the conclusion that Expo background location is practically broken and I should switch to another location library (https://github.com/mauron85/react-native-background-geolocation). However I'm using Expo managed workflow and installing this mauron85 location library (otherwise really promising) doesn't work, because it requires setting manually dependencies --> I need to eject from Expo managed workflow --> ejecting breaks my project structure in a way I don't know how to solve. Really frustrating!

Relevant parts of my code:

top part:

import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
import EventEmitter from 'EventEmitter'

const locationEmitter = new EventEmitter();

const BACKGROUND_LOCATION_TRACKER = 'BACKGROUND_LOCATION_TRACKER'
const LOCATION_UPDATE = 'LOCATION_UPDATE'

componentDidMount after requesting location permissions:

await Location.startLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKER, {
            accuracy: LocationAccuracy.BestForNavigation,
            timeInterval: 0,  // all set to 0 to make it update as often as possible!!! doesn't help
            distanceInterval: 0,
            deferredUpdatesInterval: 0,
            deferredUpdatesDistance: 0,
            showsBackgroundLocationIndicator: true,
            foregroundService: {
                notificationTitle: 'title',
                notificationBody: 'recording',
                notificationColor: '#008000',
            },
            // pausesUpdatesAutomatically: true,

        });

    locationEmitter.on(LOCATION_UPDATE, (locationData) => {
        console.log('locationEmitter locationUpdate fired! locationData: ', locationData);
        let coordinatesAmount = locationData.newRouteCoordinates.length - 1;
        this.setState({
            latitude: locationData.newRouteCoordinates[coordinatesAmount - 1].latitude,
            longitude: locationData.newRouteCoordinates[coordinatesAmount - 1].longitude,
            routeCoordinates: this.state.routeCoordinates.concat(locationData.newRouteCoordinates)
        })
    })

define location task:

TaskManager.defineTask(BACKGROUND_LOCATION_TRACKER, async ({ data, error }) => {
    if (error) {
        console.error(error);
        return;
    }

    if (data) {
        const { locations } = data;
        console.log('backgroundLocationTracker received new locations: ', locations)

        // const [location] = locations;
        const locationsLength = locations.length;

        const newRouteCoordinates = [];
        // const totalNewDistance = 0.0;

        for (i = 0; i < locationsLength; i++) {
            const { latitude, longitude } = locations[i].coords;
            const tempCoords = {
                latitude,
                longitude,
            };
            newRouteCoordinates.push(tempCoords);
            // totalNewDistance += GLOBAL.screen1.calcDistance(newRouteCoordinates[i], newRouteCoordinates[i - 1])
        };

        console.log('backgroundLocationTracker: latitude ', locations[locationsLength - 1].coords.latitude,
            ', longitude: ', locations[locationsLength - 1].coords.longitude, ', routeCoordinates: ', newRouteCoordinates,
            ', prevLatLng: ', newRouteCoordinates[locationsLength - 1]);

        let locationData = { newRouteCoordinates }

        locationEmitter.emit(LOCATION_UPDATE, locationData)

    }

});

As I said, it all WORKS (!) in the sense that I do get location updates from the background to the UI. The only problem here is that I can't figure out how to make the background task send location updates more often! It just keeps collecting a huge batch of 50+ location updates for even 10+ minutes before it bothers to send them to the UI!

All help appreciated, thanks.

Body:
I thought I would have to eject from expo too, but I changed my options and now it updates just as I intended.
The problem was the acuracy, I switched to "best for navigation" just as your example and it worked.
Here is my options, I think you should try to define some milisseconds, don't leave interval at 0 and don't set distance interval nor defered distance:

{accuracy: Location.Accuracy.BestForNavigation,
            timeInterval: 1000,
            showsBackgroundLocationIndicator: true,
            foregroundService:{
                notificationTitle: "Covid Tracker",
                notificationBody: "Rastreando sua localização",
                notificationColor: "#AA1111"
            },
            deferredUpdatesInterval: 100
        }


问:
How do I get and store an initial value of a property of a UIView?
I have a UIView laid out and constrained in main.storyboard, and have an IBOutlet connecting it to its corresponding ViewController class in ViewController.swift.

I need to manipulate the position of the view in various different functions, and to do this I need to be able to access the value of the initial y-position of the view. I tried to do this using

```<code>public let inputRest = self.userInputView.frame.origin.y
</code>```

in the body of the ViewController class. However, this gives me the error Cannot use instance member 'userInputView' within property initializer; property initializers run before 'self' is available.

How do I store properties of instance members in variables in order to call them in a function? Is there a way to declare this variable in viewDidLoad() and access it in other functions?

Thanks for the help.

答:
You cannot declare it as a class level property because it won't be created until the ViewController is instantiated. I think what you want to do is as follows.

```<code>//instantiate with an initial value of 0.0
public var inputRest : CGFloat = 0.0

override func viewDidLoad() {
    super.viewDidLoad()

    //you can do this here, because the userInputView will have been created
    self.inputRest = self.userInputView.frame.origin.y
}
</code>```

This is an inherent limitation of ViewControllers which are instantiated from a storyboard not being able to have let properties which can only be defined once. There are ways around this by overwriting the constructor used to create the view controller from the coder, but it's a lot of work, not easy to read, and very much a lot of work for nothing.

Body:
I have a UIView laid out and constrained in main.storyboard, and have an IBOutlet connecting it to its corresponding ViewController class in ViewController.swift.

I need to manipulate the position of the view in various different functions, and to do this I need to be able to access the value of the initial y-position of the view. I tried to do this using

public let inputRest = self.userInputView.frame.origin.y

in the body of the ViewController class. However, this gives me the error Cannot use instance member 'userInputView' within property initializer; property initializers run before 'self' is available.

How do I store properties of instance members in variables in order to call them in a function? Is there a way to declare this variable in viewDidLoad() and access it in other functions?

Thanks for the help.

Body:
You cannot declare it as a class level property because it won't be created until the ViewController is instantiated. I think what you want to do is as follows.

//instantiate with an initial value of 0.0
public var inputRest : CGFloat = 0.0

override func viewDidLoad() {
    super.viewDidLoad()

    //you can do this here, because the userInputView will have been created
    self.inputRest = self.userInputView.frame.origin.y
}

This is an inherent limitation of ViewControllers which are instantiated from a storyboard not being able to have let properties which can only be defined once. There are ways around this by overwriting the constructor used to create the view controller from the coder, but it's a lot of work, not easy to read, and very much a lot of work for nothing.


答:
Here is the code</p>
```<code>my_string = 'A15B27C32DA7B14C9D31'
chunk = ['A' + elem for elem in s.split('A') if elem != '']

for elem in chunk:
    num = elem[(elem.find('D') + 1):]

    if num == '' or not num.isdigit():
        print('no number associated with D')
    else:
        print('the number associated with D is', num)
</code>```

Title: Handling the "IndexError: string index out of range" error

Body:
Here is the code

my_string = 'A15B27C32DA7B14C9D31'
chunk = ['A' + elem for elem in s.split('A') if elem != '']

for elem in chunk:
    num = elem[(elem.find('D') + 1):]

    if num == '' or not num.isdigit():
        print('no number associated with D')
    else:
        print('the number associated with D is', num)


问:
Bash: No such file or directory?
I try to use an executable script (wkhtmltopdf) on a Linux shared webserver (Debian, 64bit). I am pretty sure that I compiled everything correct, but whenever I want to execute the file I get as an response :

```<code>> ./wkhtmltopdf -H
-bash: ./wkhtmltopdf: No such file or directory
</code>```

To be sure that the file is there, here the ls output :

```<code>> ls
wkhtmltoimage  wkhtmltopdf
</code>```

Furthermore I tested the file command on it, which outputs the following :

```<code>> file wkhtmltopdf
wkhtmltopdf: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, stripped
</code>```

My question is now :

Why does bash tells me that there is no 'file or directory', when there obviously is one?

My first guess would be that the shared server does not allow to execute binary files? But shouldn't it then be a problem of permissions, with a different bash output?

Edit :

```<code>> id
uid=2725674(p8907906) gid=600(ftpusers) groups=600(ftpusers)

> ls -l wkhtmltopdf
-rwxrwxrwx 1 p8907906 ftpusers 39745960 Jan 20 09:33 wkhtmltopdf

> ls -ld
drwx---r-x 2 p8907906 ftpusers 44 Jan 28 21:02 .
</code>```

答:
I ran into this issue on my raspberry pi 4 running aarch64 alpine 3.13. Using the answer provided by @vkersten, I was able to determine that I was missing /lib/ld-linux-aarch64.so.1.

I resolved this by installing gcompat with apk add gcompat.

Title: Bash: No such file or directory?

Body:
I try to use an executable script (wkhtmltopdf) on a Linux shared webserver (Debian, 64bit). I am pretty sure that I compiled everything correct, but whenever I want to execute the file I get as an response :

> ./wkhtmltopdf -H
-bash: ./wkhtmltopdf: No such file or directory

To be sure that the file is there, here the ls output :

> ls
wkhtmltoimage  wkhtmltopdf

Furthermore I tested the file command on it, which outputs the following :

> file wkhtmltopdf
wkhtmltopdf: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, stripped

My question is now :

Why does bash tells me that there is no 'file or directory', when there obviously is one?

My first guess would be that the shared server does not allow to execute binary files? But shouldn't it then be a problem of permissions, with a different bash output?

Edit :

> id
uid=2725674(p8907906) gid=600(ftpusers) groups=600(ftpusers)

> ls -l wkhtmltopdf
-rwxrwxrwx 1 p8907906 ftpusers 39745960 Jan 20 09:33 wkhtmltopdf

> ls -ld
drwx---r-x 2 p8907906 ftpusers 44 Jan 28 21:02 .


问:
How to print a single line from a dictonary in python 3
Beginner here writing a code in IDLE that goes like this. I need it to prompt the user to enter a stall number. Then tell the user the animal, food type, and feeding time associated with that stall. This is the code I have to accompany this.

```<code>stalls = {101: 'Zebras',
          102: 'Elephants',
          103: 'Geese',
          104: 'Sheep',
          105: 'Turtle',
          106: 'Cheetah',
          107: 'Giraffe',
          108: 'Capybara',
          109: 'Monkeys',
          110: 'Turkey',
          111: 'Guinea Pigs',
          112: 'Possum',
          113: 'Goats',
          114: 'Lions',
          115: 'Tigers'}

food_types = {101: 'Grass',
              102: 'Vegetables',
              103: 'Worms',
              104: 'Grass',
              105: 'Vegetables',
              106: 'Meat',
              107: 'Vegetables',
              108: 'Vegetables',
              109: 'Fruit',
              110: 'Worms',
              111: 'Fruit',
              112: 'Worms',
              113: 'Grass',
              114: 'Meat',
              115: 'Meat'}

feeding_times = {101: '0730',
                 102: '0900',
                 103: '0845',
                 104: '0930',
                 105: '0745',
                 106: '0805',
                 107: '0800',
                 108: '0808',
                 109: '0953',
                 110: '0738',
                 111: '0747',
                 112: '2000',
                 113: '1005',
                 114: '0923',
                 115: '0843'}

stall_choice =  input (int("Which animal are you looking for? Please enter stall number. "))
</code>```

If I input 111, I am expecting an output of something like "stall number 111 eats Fruit at 0747"
How do I print a dictionary by specific line? I am aware there are other ways of creating a program like this but I am getting some practice with the use of dictionaries. Thank you!

答:
Use dictionary[key]. Also, it's int(input()), not input(int()). Take a look below:

```<code># Define dictionaries
stall_choice = int(input('...'))
print(f"stall number {stall_choice} (which is {stalls[stall_choice]}), eats {food_types[stall_choice]} at time {feeding_times[stall_choice]}")
</code>```

Here, I've used f-strings, but you could also use .format().

Output:

```<code>stall number 111 (which is Guinea Pigs), eats Fruit at time 0747
</code>```

Body:
Beginner here writing a code in IDLE that goes like this. I need it to prompt the user to enter a stall number. Then tell the user the animal, food type, and feeding time associated with that stall. This is the code I have to accompany this.

stalls = {101: 'Zebras',
          102: 'Elephants',
          103: 'Geese',
          104: 'Sheep',
          105: 'Turtle',
          106: 'Cheetah',
          107: 'Giraffe',
          108: 'Capybara',
          109: 'Monkeys',
          110: 'Turkey',
          111: 'Guinea Pigs',
          112: 'Possum',
          113: 'Goats',
          114: 'Lions',
          115: 'Tigers'}

food_types = {101: 'Grass',
              102: 'Vegetables',
              103: 'Worms',
              104: 'Grass',
              105: 'Vegetables',
              106: 'Meat',
              107: 'Vegetables',
              108: 'Vegetables',
              109: 'Fruit',
              110: 'Worms',
              111: 'Fruit',
              112: 'Worms',
              113: 'Grass',
              114: 'Meat',
              115: 'Meat'}

feeding_times = {101: '0730',
                 102: '0900',
                 103: '0845',
                 104: '0930',
                 105: '0745',
                 106: '0805',
                 107: '0800',
                 108: '0808',
                 109: '0953',
                 110: '0738',
                 111: '0747',
                 112: '2000',
                 113: '1005',
                 114: '0923',
                 115: '0843'}

stall_choice =  input (int("Which animal are you looking for? Please enter stall number. "))

If I input 111, I am expecting an output of something like "stall number 111 eats Fruit at 0747"
How do I print a dictionary by specific line? I am aware there are other ways of creating a program like this but I am getting some practice with the use of dictionaries. Thank you!

Body:
Use dictionary[key]. Also, it's int(input()), not input(int()). Take a look below:

# Define dictionaries
stall_choice = int(input('...'))
print(f"stall number {stall_choice} (which is {stalls[stall_choice]}), eats {food_types[stall_choice]} at time {feeding_times[stall_choice]}")

Here, I've used f-strings, but you could also use .format().

Output:

stall number 111 (which is Guinea Pigs), eats Fruit at time 0747