问:
R, dplyr split dataframe by string in columns
I've seen examples here that show how to split a dataframe using column index ranges but how do I split my dataframe with dplyr using strings found in the column? I've purposely created my dataframes so the columns have certain strings in them for future splitting.

Example data:

```<code>Site   A_Argas   A_Arachnicea   A_Brus   B_Burkoll   B_Brielle  B_Bact
 1       10        0              0         0           0         0
 2       0         0              0         10          22        123
 3       1         2              3         88          12        546
</code>```

I want to split this dataframe up based on strings such as "A_" or "B_" and assign them to new  dataframes.

For example the output would be:

```<code> dataframeA
 Site   A_Argas   A_Arachnicea   A_Brus
 1       10        0              0
 2       0         0              0
 3       1         2              3

 dataframeB
 Site   B_Burkoll   B_Brielle  B_Bact
  1       0           0         0
  2      10          22        123
  3      88          12        546
</code>```

Because this data is not in long format, I can't seem to figure how to change my old code that I used to split the longform dataframes (for a different analysis).

```<code>dataframeA <- data %>% filter("GroupID" == "Arachnids") # where "A_" in column headers signify arachnid species
dataframeB <- data %>% filter("GroupID" == "Bacteria") # where all "B_" in the column headers are bacterial species
</code>```

答:
We may use split.default for this in base R, remove the first column ('Site'), split the data into a list of dataframe by removing the substring from the _ (using trimws), cbind the first column in the list of data.frames and change the list name

```<code>lst1 <- split.default(data[-1], trimws(names(data)[-1], whitespace = "_.*"))

lst2 <- Map(cbind, Site = data['Site'], lst1)
names(lst2) <- paste0("dataframe", names(lst1))
</code>```

-output

```<code>> lst2
$dataframeA
  Site A_Argas A_Arachnicea A_Brus
1    1      10            0      0
2    2       0            0      0
3    3       1            2      3

$dataframeB
  Site B_Burkoll B_Brielle B_Bact
1    1         0         0      0
2    2        10        22    123
3    3        88        12    546
</code>```

It may be better to keep it in a list and access the elements as

```<code>lst2[["dataframeA"]]
lst2$dataframeA
</code>```

instead of creating multiple objects (although can be created with list2env

```<code>list2env(lst2, .GlobalEnv)
</code>```

With tidyverse, we could loop over the substring of the column names and select the relevant columns with map

```<code>library(purrr)
library(dplyr)
library(stringr)
str_remove(names(data)[-1] , "_.*") %>%
   unique %>%
   map(~ data %>%
   select(Site, starts_with(.x)))
</code>```

-output

```<code>[[1]]
  Site A_Argas A_Arachnicea A_Brus
1    1      10            0      0
2    2       0            0      0
3    3       1            2      3

[[2]]
  Site B_Burkoll B_Brielle B_Bact
1    1         0         0      0
2    2        10        22    123
3    3        88        12    546
</code>```

data

```<code>data <- structure(list(Site = 1:3, A_Argas = c(10L, 0L, 1L), A_Arachnicea = c(0L,
0L, 2L), A_Brus = c(0L, 0L, 3L), B_Burkoll = c(0L, 10L, 88L),
    B_Brielle = c(0L, 22L, 12L), B_Bact = c(0L, 123L, 546L)),
class = "data.frame", row.names = c(NA,
-3L))
</code>```

Body:
I've seen examples here that show how to split a dataframe using column index ranges but how do I split my dataframe with dplyr using strings found in the column? I've purposely created my dataframes so the columns have certain strings in them for future splitting.

Example data:

Site   A_Argas   A_Arachnicea   A_Brus   B_Burkoll   B_Brielle  B_Bact
 1       10        0              0         0           0         0
 2       0         0              0         10          22        123
 3       1         2              3         88          12        546

I want to split this dataframe up based on strings such as "A_" or "B_" and assign them to new  dataframes.

For example the output would be:

 dataframeA
 Site   A_Argas   A_Arachnicea   A_Brus
 1       10        0              0
 2       0         0              0
 3       1         2              3

 dataframeB
 Site   B_Burkoll   B_Brielle  B_Bact
  1       0           0         0
  2      10          22        123
  3      88          12        546

Because this data is not in long format, I can't seem to figure how to change my old code that I used to split the longform dataframes (for a different analysis).

dataframeA <- data %>% filter("GroupID" == "Arachnids") # where "A_" in column headers signify arachnid species
dataframeB <- data %>% filter("GroupID" == "Bacteria") # where all "B_" in the column headers are bacterial species

Body:
We may use split.default for this in base R, remove the first column ('Site'), split the data into a list of dataframe by removing the substring from the _ (using trimws), cbind the first column in the list of data.frames and change the list name

lst1 <- split.default(data[-1], trimws(names(data)[-1], whitespace = "_.*"))

lst2 <- Map(cbind, Site = data['Site'], lst1)
names(lst2) <- paste0("dataframe", names(lst1))

-output

> lst2
$dataframeA
  Site A_Argas A_Arachnicea A_Brus
1    1      10            0      0
2    2       0            0      0
3    3       1            2      3

$dataframeB
  Site B_Burkoll B_Brielle B_Bact
1    1         0         0      0
2    2        10        22    123
3    3        88        12    546

It may be better to keep it in a list and access the elements as

lst2[["dataframeA"]]
lst2$dataframeA

instead of creating multiple objects (although can be created with list2env

list2env(lst2, .GlobalEnv)

With tidyverse, we could loop over the substring of the column names and select the relevant columns with map

library(purrr)
library(dplyr)
library(stringr)
str_remove(names(data)[-1] , "_.*") %>%
   unique %>%
   map(~ data %>%
   select(Site, starts_with(.x)))

-output

[[1]]
  Site A_Argas A_Arachnicea A_Brus
1    1      10            0      0
2    2       0            0      0
3    3       1            2      3

[[2]]
  Site B_Burkoll B_Brielle B_Bact
1    1         0         0      0
2    2        10        22    123
3    3        88        12    546

data

data <- structure(list(Site = 1:3, A_Argas = c(10L, 0L, 1L), A_Arachnicea = c(0L,
0L, 2L), A_Brus = c(0L, 0L, 3L), B_Burkoll = c(0L, 10L, 88L),
    B_Brielle = c(0L, 22L, 12L), B_Bact = c(0L, 123L, 546L)),
class = "data.frame", row.names = c(NA,
-3L))


来源: stackexchange

问:
Can't get Table Data from Site After the Page Loads
I'm trying to obtain the 2nd table on the following website. I've tried BS4, Pandas, and now selenium, but I can't obtain the table for the life of me.

The table data doesn't load until after the page comes up.

There is a dictionary on the 'view source' page with the info, but its seems like every element on that page is 'line-content', so its makes it difficult to obtain only the desired table info.

What is the best way to collect the table data?

```<code>from ast import Return
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
import time

path = 'C:\Program Files (x86)\chromedriver.exe'

driver = webdriver.Chrome(path)

driver.get('https://www.linestarapp.com/Ownership/Sport/NFL/Site/DraftKings/PID/295')

time.sleep(5)
driver.maximize_window()

time.sleep(5)

players = driver.find_elements_by_class_name('playerRow').text
print(players)
</code>```

答:
Another solution to your problem might be to query for the second table by id, and only later get the table row elements.</p>
```<code>from selenium import webdriver

driver = webdriver.Chrome("C:\Program Files (x86)\chromedriver.exe")

driver.get('https://www.linestarapp.com/Ownership/Sport/NFL/Site/DraftKings/PID/295')

driver.maximize_window()

# the first table has id projectedTournament
secondTable = driver.find_element_by_id("tableTournament")

players = secondTable.find_elements_by_class_name('playerRow')
for playerRowElement in players:
    for playerColumn in playerRowElement.find_elements_by_tag_name("td"):
        print(playerColumn.text)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to obtain the 2nd table on the following website. I've tried BS4, Pandas, and now selenium, but I can't obtain the table for the life of me.

The table data doesn't load until after the page comes up.

There is a dictionary on the 'view source' page with the info, but its seems like every element on that page is 'line-content', so its makes it difficult to obtain only the desired table info.

What is the best way to collect the table data?

from ast import Return
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
import time

path = 'C:\Program Files (x86)\chromedriver.exe'

driver = webdriver.Chrome(path)

driver.get('https://www.linestarapp.com/Ownership/Sport/NFL/Site/DraftKings/PID/295')

time.sleep(5)
driver.maximize_window()

time.sleep(5)

players = driver.find_elements_by_class_name('playerRow').text
print(players)

Body:
Another solution to your problem might be to query for the second table by id, and only later get the table row elements.

from selenium import webdriver

driver = webdriver.Chrome("C:\Program Files (x86)\chromedriver.exe")

driver.get('https://www.linestarapp.com/Ownership/Sport/NFL/Site/DraftKings/PID/295')

driver.maximize_window()

# the first table has id projectedTournament
secondTable = driver.find_element_by_id("tableTournament")

players = secondTable.find_elements_by_class_name('playerRow')
for playerRowElement in players:
    for playerColumn in playerRowElement.find_elements_by_tag_name("td"):
        print(playerColumn.text)


问:
Regex for CSS Selectors - PHP
Does anyone know what the most robust regex would be to select all selectors from a css declaration?  Below is CSS code for non-standard CSS that would be a good test case.  </p>

```<code>.somenormalstyledeclaration
{
    width:100%;
    height:100%;
    background-image: url(images/fallback-gradient.png);
}
.somenormalstyle1, .somenormalstyle2
{
    width:100%;
    height:100%;
    background-image: url(images/fallback-gradient.png);
}
.gradient-bg
{
   background-color: #1a82f7;
   background-image: url(images/fallback-gradient.png);
   background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#2F2727), to(#1a82f7));
   background-image: -webkit-linear-gradient(top, #2F2727, #1a82f7);
   background-image:    -moz-linear-gradient(top, #2F2727, #1a82f7);
   background-image:     -ms-linear-gradient(top, #2F2727, #1a82f7);
   background-image:      -o-linear-gradient(top, #2F2727, #1a82f7);
}

@-webkit-keyframes bounce_circle
{
    0%
    {
        opacity:0.3;
    }
    50%
    {
        opacity:1;
        background-color:#111
    }
    100%
    {
        opacity:0.3;
    }
}
</code>```

答:
This should work mostly. It's a few steps, but not as good as a full parser.

Replace all newlines with a space character

Assuming you never use strings including { or }, you can replace /\{[^\}]\}/ with a ,

Split all the text into an array on each , and ; character

Trim all whitespace from the beginning and end of each selector

Every element of the array should be a selector or an "at-rule" (i.e. @charset utf-8;).

I have probably missed some other edge cases, but this should work as a quick-and-dirty solution for most cases.

ContentLicense: CC BY-SA 3.0

Title: Regex for CSS Selectors - PHP

Body:
Does anyone know what the most robust regex would be to select all selectors from a css declaration?  Below is CSS code for non-standard CSS that would be a good test case.

.somenormalstyledeclaration
{
    width:100%;
    height:100%;
    background-image: url(images/fallback-gradient.png);
}
.somenormalstyle1, .somenormalstyle2
{
    width:100%;
    height:100%;
    background-image: url(images/fallback-gradient.png);
}
.gradient-bg
{
   background-color: #1a82f7;
   background-image: url(images/fallback-gradient.png);
   background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#2F2727), to(#1a82f7));
   background-image: -webkit-linear-gradient(top, #2F2727, #1a82f7);
   background-image:    -moz-linear-gradient(top, #2F2727, #1a82f7);
   background-image:     -ms-linear-gradient(top, #2F2727, #1a82f7);
   background-image:      -o-linear-gradient(top, #2F2727, #1a82f7);
}

@-webkit-keyframes bounce_circle
{
    0%
    {
        opacity:0.3;
    }
    50%
    {
        opacity:1;
        background-color:#111
    }
    100%
    {
        opacity:0.3;
    }
}


问:
React doesn't call useEffect on firebase (v9) auth update
I'm uploading a user profile image into firebase storage, then updating the photoURL value of the auth user with updateProfile(). After that I want the user to be updated without manually refreshing the page. I've been trying this for days now and the issue gets more weird every time I try to debug it.

The interesting thing is the user object seems to be already updated when I log it with console.log(currentUser) after the then promise of updateProfile() is fulfilled. So the new photoURL is already present in the currentUser object. But it seems to not call a state update or console.log("!!!!currentAuthUserUpdate", user);. So the user image wouldn't refresh in my page.

I even tried it with doing a useEffect with the currentUser as a dependency but it wasn't fired. Still, the currentUser object changed when logging it after updateProfile()

Updating the profile, UpdateUserImage.tsx:

```<code>import { useAuth } from "../../contexts/AuthContext";

const { currentUser } = useAuth();

// updating the user profile
updateProfile(currentUser, { photoURL })
</code>```

AuthContext.tsx:

```<code>import { auth } from "./../firebase/firebase";

const [currentUser, setCurrentUser] = useState(null);

const auth = getAuth(app);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      console.log("!!!!currentAuthUserUpdate", user);

      // I tried setting the user as a custom new object: const userData = { ...user };
      setCurrentUser(user);
    });
    return unsubscribe;
  }, []);
</code>```

firebase.js

```<code>import { getAuth } from "firebase/auth";

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export {
  auth
};
</code>```

What I tried additionally: (But this wouldn't work as the user is already updated without a state refresh from react, so it's trying to replace the same object)

```<code>const reloadUser = async () => {
    try {
      const res = await currentUser.reload();
      const user = auth.currentUser;
      console.log("currentUser:", user);

      setCurrentUser(auth.currentUser);

      console.log("res", res);
    } catch (err) {
      console.log(err);
    }
  };
</code>```

答:
Using useStates are good for re-rendering components. However going into utilizing useRefs are best for updating the actual variable and will not cause a re-render of the component.

Declare it like:const currentUser = useRef(null)

Update it like: currentUser.current = updatedUserData

Use in code like: currentUser.current.photoURL

Body:
I'm uploading a user profile image into firebase storage, then updating the photoURL value of the auth user with updateProfile(). After that I want the user to be updated without manually refreshing the page. I've been trying this for days now and the issue gets more weird every time I try to debug it.

The interesting thing is the user object seems to be already updated when I log it with console.log(currentUser) after the then promise of updateProfile() is fulfilled. So the new photoURL is already present in the currentUser object. But it seems to not call a state update or console.log("!!!!currentAuthUserUpdate", user);. So the user image wouldn't refresh in my page.

I even tried it with doing a useEffect with the currentUser as a dependency but it wasn't fired. Still, the currentUser object changed when logging it after updateProfile()

Updating the profile, UpdateUserImage.tsx:

import { useAuth } from "../../contexts/AuthContext";

const { currentUser } = useAuth();

// updating the user profile
updateProfile(currentUser, { photoURL })

AuthContext.tsx:

import { auth } from "./../firebase/firebase";

const [currentUser, setCurrentUser] = useState(null);

const auth = getAuth(app);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      console.log("!!!!currentAuthUserUpdate", user);

      // I tried setting the user as a custom new object: const userData = { ...user };
      setCurrentUser(user);
    });
    return unsubscribe;
  }, []);

firebase.js

import { getAuth } from "firebase/auth";

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export {
  auth
};

What I tried additionally: (But this wouldn't work as the user is already updated without a state refresh from react, so it's trying to replace the same object)

const reloadUser = async () => {
    try {
      const res = await currentUser.reload();
      const user = auth.currentUser;
      console.log("currentUser:", user);

      setCurrentUser(auth.currentUser);

      console.log("res", res);
    } catch (err) {
      console.log(err);
    }
  };


问:
Element type is invalid: expected a string (for built-in components) or a class/function. SSR with nodejs, react, react-router-dom
Sandbox: https://codesandbox.io/s/focused-dream-ko68k?file=/server/server.js

Error

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
at ReactDOMServerRenderer.render (C:\Users\Gp\Desktop\testingg\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:4053:17)
at ReactDOMServerRenderer.read (C:\Users\Gp\Desktop\testingg\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:3690:29)
at Object.renderToString (C:\Users\Gp\Desktop\testingg\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:4298:27)
at C:\Users\Gp\Desktop\testingg\server/server.js:16:30
at Layer.handle [as handle_request] (C:\Users\Gp\Desktop\testingg\server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Gp\Desktop\testingg\server\node_modules\express\lib\router\index.js:323:13)
at C:\Users\Gp\Desktop\testingg\server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\Gp\Desktop\testingg\server\node_modules\express\lib\router\index.js:341:12)
at next (C:\Users\Gp\Desktop\testingg\server\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\Users\Gp\Desktop\testingg\server\node_modules\express\lib\middleware\init.js:40:5)

Code
React/index.js
react/src/index.js

React/App.js
react/src/App.js

Server/index.js -- node_module to node_modules. but it still doesn't work.
server/index.js

Server/server.js
Server/server.js

File Structure
file structure

Please help I'm stuck for 2 days now and have no idea on what's wrong. I'm trying to server side render my react application but it doesn't wanna work.

答: May be unrelated, but I've noticed a node_module instead of node_modules in server/index.js .


问:
Bokeh TextInput show the title and input box in the same line
I'd like to display the title for TextInput inline with the input box, but by default, it displays on 2 separate lines.

The code below creates a TextInput box in a Jupyter Notebook, but it shows the Title above the box. How can I make the title display on the same line as the input box?

```<code>from bokeh.layouts import column, row
from bokeh.models.widgets import Slider, TextInput
from bokeh.plotting import ColumnDataSource, figure, output_file, show, reset_output, output_notebook

reset_output()
output_notebook()

layout = row([TextInput(title='my label:', value='something')])

show(layout)
</code>```

Current Output:

Desired Output:

答:
You can do this in a more proper way by making a directory app rather than a script app. Directory apps can have custom templates where you can say

{% extends base %}

{% block postamble %}
  <link href="app/static/bokeh.css" rel="stylesheet">
{% endblock %}
```
<p>And then you can do</p>
<pre class="lang-css prettyprint-override"><code>.bk-root .horizontal .bk-input-group {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}
.bk-root .horizontal .bk-input-group label {
    flex: 0 0 200px;
}
</code>```

And make a component with

css_classes=["horizontal"]
```
<p>Of course you can also make everything horizontal, or add a <code>theme.yaml</code> with</p>
<pre class="lang-yaml prettyprint-override"><code>attrs:
  InputWidget:
    default_size: 500
    css_classes: ["horizontal"]

</code>```

Body:
I'd like to display the title for TextInput inline with the input box, but by default, it displays on 2 separate lines.

The code below creates a TextInput box in a Jupyter Notebook, but it shows the Title above the box. How can I make the title display on the same line as the input box?

from bokeh.layouts import column, row
from bokeh.models.widgets import Slider, TextInput
from bokeh.plotting import ColumnDataSource, figure, output_file, show, reset_output, output_notebook

reset_output()
output_notebook()

layout = row([TextInput(title='my label:', value='something')])

show(layout)

Current Output:

Desired Output:

Body:
You can do this in a more proper way by making a directory app rather than a script app. Directory apps can have custom templates where you can say

{% extends base %}

{% block postamble %}
  <link href="app/static/bokeh.css" rel="stylesheet">
{% endblock %}

And then you can do

.bk-root .horizontal .bk-input-group {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}
.bk-root .horizontal .bk-input-group label {
    flex: 0 0 200px;
}

And make a component with

css_classes=["horizontal"]

Of course you can also make everything horizontal, or add a theme.yaml with

attrs:
  InputWidget:
    default_size: 500
    css_classes: ["horizontal"]


问:
How to know my Google Cloud Identity from the command line?
I'm running Python code on my computer that makes calls to Google Cloud Platform. I'm trying to know if my application is using my own credentials or service account keys to get authorizations on GCP.

On AWS, I could use aws sts get-caller-identity to know who the caller is (IAM user or IAM role).

Is there a GCP equivalent, something like gcloud whoami, that I could run from the command line or from my Python code itself to know the identity used by my application?

答: Use the command gcloud auth list in your cli to view the active credentials account.


问:
How to access attributes [e.g. time] of terra raster in R?
I have a raster that is read and cropped from a netcdf4 file. The raster looks like this:

```<code>> library(terra)

> ncr1
class       : SpatRaster
dimensions  : 341, 745, 3  (nrow, ncol, nlyr)
resolution  : 1000, 1000  (x, y)
extent      : 1369250, 2114250, -674500, -333500  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=lcc +lat_0=42.5 +lon_0=-100 +lat_1=25 +lat_2=60 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs
source      : memory
names       :    vp_1,    vp_2,    vp_3
min values  :  174.03,  195.29,  393.66
max values  :  516.43,  606.79, 1047.61
time        : 2009-01-01 12:00:00 to 2009-01-03 12:00:00

> dput(ncr1@ptr$time)
c(1230811200, 1230897600, 1230984000)

</code>```

As part of the processing I want to do, I want to use the time attribute (I'm not sure if that's the right adjective for that component) as a vector input with my process, such as how doy is used in meteor::hourlyFromDailyRelH() : hourlyFromDailyRelh(relh, tmin, tmax, doy, latitude). I don't know how to call the attribute programatically. It looks like I can use ncr@ptr$time, but it seems like that's the wrong way to do it, based on this question at least. For example:

```<code>> library(lubridate)
> pdays <- yday(as_datetime(ncr1@ptr$time))
> pdays
[1] 1 2 3
</code>```

is wrong? I mean it seems to work, but if there is a more appropriate function in R (or terra) for getting the @ptr$time part, I don't know what it is. I tried terra::cats() and using getSlots(), but those are wrong.

答:
I guess you are looking for the following:

terra::time(ncr1)
```

Body:
I have a raster that is read and cropped from a netcdf4 file. The raster looks like this:

> library(terra)

> ncr1
class       : SpatRaster
dimensions  : 341, 745, 3  (nrow, ncol, nlyr)
resolution  : 1000, 1000  (x, y)
extent      : 1369250, 2114250, -674500, -333500  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=lcc +lat_0=42.5 +lon_0=-100 +lat_1=25 +lat_2=60 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs
source      : memory
names       :    vp_1,    vp_2,    vp_3
min values  :  174.03,  195.29,  393.66
max values  :  516.43,  606.79, 1047.61
time        : 2009-01-01 12:00:00 to 2009-01-03 12:00:00

> dput(ncr1@ptr$time)
c(1230811200, 1230897600, 1230984000)

As part of the processing I want to do, I want to use the time attribute (I'm not sure if that's the right adjective for that component) as a vector input with my process, such as how doy is used in meteor::hourlyFromDailyRelH() : hourlyFromDailyRelh(relh, tmin, tmax, doy, latitude). I don't know how to call the attribute programatically. It looks like I can use ncr@ptr$time, but it seems like that's the wrong way to do it, based on this question at least. For example:

> library(lubridate)
> pdays <- yday(as_datetime(ncr1@ptr$time))
> pdays
[1] 1 2 3

is wrong? I mean it seems to work, but if there is a more appropriate function in R (or terra) for getting the @ptr$time part, I don't know what it is. I tried terra::cats() and using getSlots(), but those are wrong.


问:
Set image changes when I move from one fragment to another, How to keep it forever even when I restart the app?
please help I could not add code, it is throwing error , I'm new.</p>
```<code>ActivityResultLauncher<Intent> picActivityResultLauncher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == Activity.RESULT_OK) {
                Intent data = result.getData();
                // your operation....
                Uri pic = data.getData();
                profile.setImageURI(pic);
            }
        }
    }
</code>```

答:
It depends on the device's android version. If it's 10 or lower than that, then you can simply save the file path in the Sharedpreference so you can access it later and load the image from there (You can do it in android 10 with requestLegacyExternalStorage of course or you can go with the 2nd option which I provided below).

But, if you're writing the code for android 11 or higher, then there are only three standard ways to do it.

1. Using SAF (Storage Access Framework) :-

You can get the storage access permission of that perticular folder everytime you pick an image from there. But this is not the best option when your app is doing it multiple times. (what if it's photo editor app or social media or something like that?!)

2. Manage all files permission :-

You can go with the All files access permission but it's also too much for the small task and you also have to give clarification to google play when your  app has that permission. So it's also the very last option.

3. Accessing from internal app directories - THE BEST WAY! :-

You can go with this option with almost every app!
All you have to do is just take read storage permission, access the file using file descriptor, write it to the internal app directory (it can be either external files directory or cache directory), then you'll have a lifetime access of the image. You can save the path to Sharedpreference and access it anytime.

If you want to save edited image to the gallery then it will also be easy because you already have both read and write permission to that image saved in internal app directory.

That's it. I know the answer is lengthy but it's worth it. :)

Body:
please help I could not add code, it is throwing error , I'm new.

ActivityResultLauncher<Intent> picActivityResultLauncher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == Activity.RESULT_OK) {
                Intent data = result.getData();
                // your operation....
                Uri pic = data.getData();
                profile.setImageURI(pic);
            }
        }
    }


问:
How to pass two or more dataframes from a module to main script
Edit with @RJ Adriaansen update:
I'm trying to pull two or more dataframes from a module so that I can use the data in the main script.
I only get 4 empty dataframes returned from the df_make module.

The main and df_make codes are below.

Any advice would be great thanks.

```<code>import pandas as pd
import df_make

df_trn = pd.DataFrame()
df_trn_trk = pd.DataFrame()
df_jky = pd.DataFrame()
df_jky_code = pd.DataFrame()

def main():

df_make.jky_trn(df_trn, df_trn_trk, df_jky, df_jky_code)
#df_make.jky_trn([df_trn])

print(df_trn)
print(df_trn_trk)
print(df_jky)
print(df_jky_code)

if __name__ == '__main__':
main()

import pandas as pd

#def jky_trn(df_trn):
def jky_trn(df_trn, df_trn_trk, df_jky, df_jky_code):

#global df_trn
#global df_trn_trk
#global df_jky
#global df_jky_code

path = (r"C:\Users\chris\Documents\UKHR\PythonSand\PY_Scripts\StackOF")
xls_tbl = "\Racecards.xlsx"
xls_link = path + xls_tbl

df1 = pd.read_excel(xls_link, usecols=["Jockey","Course","RaceDesc"])
df2 = pd.read_excel(xls_link, usecols=["Trainer","Course","RaceDesc"])

df1 = df1.drop_duplicates(subset=["Jockey","Course","RaceDesc"])
df1 = df1.dropna()          # Remove rows with NaN

df1['Course'] = df1['Course'].str.replace(' \(AW\)', '')    #Replace (AW) in Course
df2['Course'] = df2['Course'].str.replace(' \(AW\)', '')

df_jky = df1[['Jockey']].copy()
df_jky_code = df1[['Jockey', 'Course']].copy()
df_jky = df_jky.drop_duplicates()
df_jky_code = df_jky_code.drop_duplicates()

df_trn = df2[['Trainer']].copy()
df_trn_trk = df2[['Trainer', 'Course']].copy()
df_trn = df_trn.drop_duplicates()
df_trn_trk = df_trn_trk.drop_duplicates()

#print(df_jky_code)
#print(df_trn_trk)

return df_jky, df_jky_code, df_trn, df_trn_trk
</code>```

答:
So, it turns out that I needed to refer to the dataframes as a tuple item in the main script e.g. df_jt = df_make.jky_trn()

The new main script code is:

```<code>import pandas as pd
</code>```

import df_make

def main():

```<code>df_jt = df_make.jky_trn()

print(df_jt[0])
print(df_jt[1])
print(df_jt[2])
print(df_jt[3])

</code>```

if name == 'main':
main()

Body:
Edit with @RJ Adriaansen update:
I'm trying to pull two or more dataframes from a module so that I can use the data in the main script.
I only get 4 empty dataframes returned from the df_make module.

The main and df_make codes are below.

Any advice would be great thanks.

import pandas as pd
import df_make

df_trn = pd.DataFrame()
df_trn_trk = pd.DataFrame()
df_jky = pd.DataFrame()
df_jky_code = pd.DataFrame()

def main():

df_make.jky_trn(df_trn, df_trn_trk, df_jky, df_jky_code)
#df_make.jky_trn([df_trn])

print(df_trn)
print(df_trn_trk)
print(df_jky)
print(df_jky_code)

if __name__ == '__main__':
main()

import pandas as pd

#def jky_trn(df_trn):
def jky_trn(df_trn, df_trn_trk, df_jky, df_jky_code):

#global df_trn
#global df_trn_trk
#global df_jky
#global df_jky_code

path = (r"C:\Users\chris\Documents\UKHR\PythonSand\PY_Scripts\StackOF")
xls_tbl = "\Racecards.xlsx"
xls_link = path + xls_tbl

df1 = pd.read_excel(xls_link, usecols=["Jockey","Course","RaceDesc"])
df2 = pd.read_excel(xls_link, usecols=["Trainer","Course","RaceDesc"])

df1 = df1.drop_duplicates(subset=["Jockey","Course","RaceDesc"])
df1 = df1.dropna()          # Remove rows with NaN

df1['Course'] = df1['Course'].str.replace(' \(AW\)', '')    #Replace (AW) in Course
df2['Course'] = df2['Course'].str.replace(' \(AW\)', '')

df_jky = df1[['Jockey']].copy()
df_jky_code = df1[['Jockey', 'Course']].copy()
df_jky = df_jky.drop_duplicates()
df_jky_code = df_jky_code.drop_duplicates()

df_trn = df2[['Trainer']].copy()
df_trn_trk = df2[['Trainer', 'Course']].copy()
df_trn = df_trn.drop_duplicates()
df_trn_trk = df_trn_trk.drop_duplicates()

#print(df_jky_code)
#print(df_trn_trk)

return df_jky, df_jky_code, df_trn, df_trn_trk

Body:
So, it turns out that I needed to refer to the dataframes as a tuple item in the main script e.g. df_jt = df_make.jky_trn()

The new main script code is:

import pandas as pd

import df_make

def main():

df_jt = df_make.jky_trn()

print(df_jt[0])
print(df_jt[1])
print(df_jt[2])
print(df_jt[3])

if name == 'main':
main()


问:
Is it possible to pass multiple side inputs in apache beam Java
I am curious to know if it's possible to pass multiple side-inputs in apache beam.

For example, I have a customer dataset, where I have zipcode, and city -– these two columns will be used to do a lookup with postcode table to find state for zipcode lookup and country name from city lookup.

Is it possible to do in a single pardo, where .withsideInputs will have two pcollections, zipcode and city? Or do I need to do in two steps?

答: Yes, you can, just use ParDo.SingleOutput.withSideInputs(Iterable) or ParDo.SingleOutput.withSideInputs(Map) for that.</p>


问:
Github isn't displaying my embedded images in my Jupiter Notebook
I uploaded a Jupyter notebook to GitHub with some screenshots that I embedded into markdown cells using the following format:

```<code>![Step1](Images/Step1.png)
</code>```

However, when trying to view the notebook on GitHub, none of the embedded images appear. Is there something I can do to mend this?

I do not want users to have to run a Python code block to display the image. They are screenshots of different steps in a "getting started" guide I made, so I want them to appear in Markdown cells.

答:
This is just a shot in the dark, but does your relative filepath need to point to the root directory? Like this:

```<code>![Step1](./Images/Step1.png)
</code>```

That's my best guess.

Body:
I uploaded a Jupyter notebook to GitHub with some screenshots that I embedded into markdown cells using the following format:

![Step1](Images/Step1.png)

However, when trying to view the notebook on GitHub, none of the embedded images appear. Is there something I can do to mend this?

I do not want users to have to run a Python code block to display the image. They are screenshots of different steps in a "getting started" guide I made, so I want them to appear in Markdown cells.

Body:
This is just a shot in the dark, but does your relative filepath need to point to the root directory? Like this:

![Step1](./Images/Step1.png)

That's my best guess.


答:
One base R option might be to grep for the columns starting with A_ and B_, then to subset your original data frame.

a_names <- grep("^A_", names(data), value=TRUE)
dataframeA <- data[ , c("Site", a_names)]
b_names <- grep("^B_", names(data), value=TRUE)
dataframeB <- data[ , c("Site", b_names)]
```

Title: R, dplyr split dataframe by string in columns


问:
read_csv a MultiIndex DataFrame: problem when the first row is empty
After a long calculation I have finally obtained my DataFrame with MultiIndex columns:

```<code>columns = pd.MultiIndex.from_product([[0, 1], [0, 1]])
df = pd.DataFrame(np.ones((2, 4))], columns=columns)
df
Out[14]:
     0         1
     0    1    0    1
0  1.0  1.0  1.0  1.0
1  1.0  1.0  1.0  1.0
</code>```

I now save it to a csv file, and read it back later on with no problem.

```<code>df.to_csv("asd.csv")
df = pd.read_csv("asd.csv", header=[0, 1], index_col=[0])
df
Out[15]:
     0         1
     0    1    0    1
0  1.0  1.0  1.0  1.0
1  1.0  1.0  1.0  1.0
</code>```

Repeating the same process with a DataFrame whose first row is filled with NaNs...

```<code>columns= pd.MultiIndex.from_product([[0, 1], [0, 1]])
df = pd.DataFrame([np.full(4, np.nan), np.ones(4)], columns=columns)
df
Out[16]:
     0         1
     0    1    0    1
0  NaN  NaN  NaN  NaN
1  1.0  1.0  1.0  1.0
</code>```

... gives the following undesired result:

```<code>df.to_csv("asd.csv")
df = pd.read_csv("asd.csv", header=[0, 1], index_col=[0])
df
Out[17]:
     0         1
     0    1    0    1
0
1  1.0  1.0  1.0  1.0
</code>```

Inspecting the index shows that what should be the first row is actually interpreted as the row's name.

```<code>df.index
Out[18]: Int64Index([1], dtype='int64', name='0')
</code>```

Any ideas about how to solve this?

答:
You could do the following when saving to csv:

```<code>df.to_csv("asd.csv",na_rep='NULL')
</code>```

This will return the following result:

```<code>Out[9]:
     0         1
     0    1    0    1
0  NaN  NaN  NaN  NaN
1  1.0  1.0  1.0  1.0
</code>```

Body:
After a long calculation I have finally obtained my DataFrame with MultiIndex columns:

columns = pd.MultiIndex.from_product([[0, 1], [0, 1]])
df = pd.DataFrame(np.ones((2, 4))], columns=columns)
df
Out[14]:
     0         1
     0    1    0    1
0  1.0  1.0  1.0  1.0
1  1.0  1.0  1.0  1.0

I now save it to a csv file, and read it back later on with no problem.

df.to_csv("asd.csv")
df = pd.read_csv("asd.csv", header=[0, 1], index_col=[0])
df
Out[15]:
     0         1
     0    1    0    1
0  1.0  1.0  1.0  1.0
1  1.0  1.0  1.0  1.0

Repeating the same process with a DataFrame whose first row is filled with NaNs...

columns= pd.MultiIndex.from_product([[0, 1], [0, 1]])
df = pd.DataFrame([np.full(4, np.nan), np.ones(4)], columns=columns)
df
Out[16]:
     0         1
     0    1    0    1
0  NaN  NaN  NaN  NaN
1  1.0  1.0  1.0  1.0

... gives the following undesired result:

df.to_csv("asd.csv")
df = pd.read_csv("asd.csv", header=[0, 1], index_col=[0])
df
Out[17]:
     0         1
     0    1    0    1
0
1  1.0  1.0  1.0  1.0

Inspecting the index shows that what should be the first row is actually interpreted as the row's name.

df.index
Out[18]: Int64Index([1], dtype='int64', name='0')

Any ideas about how to solve this?

Body:
You could do the following when saving to csv:

df.to_csv("asd.csv",na_rep='NULL')

This will return the following result:

Out[9]:
     0         1
     0    1    0    1
0  NaN  NaN  NaN  NaN
1  1.0  1.0  1.0  1.0


问:
Is there a way to access the "previous row" value in a SELECT statement?
I need to calculate the difference of a column between two lines of a table. Is there any way I can do this directly in SQL? I'm using Microsoft SQL Server 2008.

I'm looking for something like this:

```<code>SELECT value - (previous.value) FROM table
</code>```

Imagining that the "previous" variable reference the latest selected row. Of course with a select like that I will end up with n-1 rows selected in a table with n rows, that's not a probably, actually is exactly what I need.

Is that possible in some way?

答:
SQL has no built in notion of order, so you need to order by some column for this to be meaningful. Something like this:

```<code>select t1.value - t2.value from table t1, table t2
where t1.primaryKey = t2.primaryKey - 1
</code>```

If you know how to order things but not how to get the previous value given the current one (EG, you want to order alphabetically) then I don't know of a way to do that in standard SQL, but most SQL implementations will have extensions to do it.

Here is a way for SQL server that works if you can order rows such that each one is distinct:

```<code>select  rank() OVER (ORDER BY id) as 'Rank', value into temp1 from t

select t1.value - t2.value from temp1 t1, temp1 t2
where t1.Rank = t2.Rank - 1

drop table temp1
</code>```

If you need to break ties, you can add as many columns as necessary to the ORDER BY.

OwnerDisplayName: Augusto Radtke

Body:
I need to calculate the difference of a column between two lines of a table. Is there any way I can do this directly in SQL? I'm using Microsoft SQL Server 2008.

I'm looking for something like this:

SELECT value - (previous.value) FROM table

Imagining that the "previous" variable reference the latest selected row. Of course with a select like that I will end up with n-1 rows selected in a table with n rows, that's not a probably, actually is exactly what I need.

Is that possible in some way?

Body:
SQL has no built in notion of order, so you need to order by some column for this to be meaningful. Something like this:

select t1.value - t2.value from table t1, table t2
where t1.primaryKey = t2.primaryKey - 1

If you know how to order things but not how to get the previous value given the current one (EG, you want to order alphabetically) then I don't know of a way to do that in standard SQL, but most SQL implementations will have extensions to do it.

Here is a way for SQL server that works if you can order rows such that each one is distinct:

select  rank() OVER (ORDER BY id) as 'Rank', value into temp1 from t

select t1.value - t2.value from temp1 t1, temp1 t2
where t1.Rank = t2.Rank - 1

drop table temp1

If you need to break ties, you can add as many columns as necessary to the ORDER BY.

ContentLicense: CC BY-SA 2.5


问:
Fetch - get HTML text as a response
I have a problem. I have rate-limit that returns HTML:

```<code>const Limiter = rateLimit({
  windowMs: 5 * 60 * 1000,
  message: "Too many requests created from this IP, please try again later.",
  max: 10
})
</code>```

And I have fetch request in Client side that gets that Message:

```<code>      const body = { email, password }

      const res = await fetch("http://localhost:5000/api/auth/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(body)
      })

      const parseRes = await res.json()

      if(parseRes.JwtToken) {
        localStorage.setItem("JwtToken", parseRes.JwtToken)

        setAuth(true)
        toast.success("Login successfuly")
      } else {
        setAuth(false)
        toast.error(parseRes)
      }
</code>```

My problem here is that when I get json object back it displays on the screen. But when I get that message object it does nothing. It just shows that failure 429 in the console. My question here is how can I get/display that HTML that returns normally like I would get an JSON object.

答:
So before you parse the JSON check the status</p>
```<code>if (!res.ok) {
  /* handle the error */
  return;
}
const parseRes = await res.json()
</code>```

Title: Fetch - get HTML text as a response

Body:
I have a problem. I have rate-limit that returns HTML:

const Limiter = rateLimit({
  windowMs: 5 * 60 * 1000,
  message: "Too many requests created from this IP, please try again later.",
  max: 10
})

And I have fetch request in Client side that gets that Message:

      const body = { email, password }

      const res = await fetch("http://localhost:5000/api/auth/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(body)
      })

      const parseRes = await res.json()

      if(parseRes.JwtToken) {
        localStorage.setItem("JwtToken", parseRes.JwtToken)

        setAuth(true)
        toast.success("Login successfuly")
      } else {
        setAuth(false)
        toast.error(parseRes)
      }

My problem here is that when I get json object back it displays on the screen. But when I get that message object it does nothing. It just shows that failure 429 in the console. My question here is how can I get/display that HTML that returns normally like I would get an JSON object.

Body:
So before you parse the JSON check the status

if (!res.ok) {
  /* handle the error */
  return;
}
const parseRes = await res.json()


问:
How to subtract columns of one dataframe to that of another in python and store the result and both columns in a new dataframe
I’ve 2 data frames which have one common column ‘X’ having all the unique values. I want to subtract each column of data frame 1 to that of data frame 2 which have similar names.
dataframe 1

X
bar A
bar B

A1
48.0
1235

A2
53.0
4567

dataframe 2

X
par A
par B

A2
74.0
8342

A1
63.0
6531

Desired result:

X
bar A
par A
Difference
Status

A1
48.0
63.0
15.0
Ok

A2
53.0
74.0
21.0
Ok

To be noted that Difference here refers to barA - parA I.e subtraction.
and this kind of data frames are required for each column
There are 20 columns in my data frames. The status column gets not ok when value is less Than 0.

I’m thinking of writing a for loop to perform this but unable to start. If anyone can help in this. Ps I’m working on python.

答:
Yes you can merge on column "X" to create a single dataframe with all values, then iterate through the columns and append calculated dataframes to a list.

Something like:

```<code>df = pd.merge(left=df1, right=df2, on='X', how='inner')
output_frames = []
letters = [i[-1] for i in df.columns if not i == 'X'] #Get letters in your columns
letters = list(set(letters)) #Get list of letters with single element
for letter in letters:
    newdf = df.loc[:, ['X'] + [i for i in df.columns if i.endswith(letter)]]
    newdf['Difference'] = newdf[f'par {letter}'] - newdf[f'bar {letter}']
    newdf['Status'] = newdf.apply(lambda x: 'OK' if x.Difference >= 0 else 'NOT OK', axis=1)
    output_frames.append(newdf)
</code>```

Then view output:

```<code>for df in newdf:
    print(df)
</code>```

Or better still, merge the outputs:

```<code>df = pd.concat(output_frames, axis=1)
</code>```

Body:
Yes you can merge on column "X" to create a single dataframe with all values, then iterate through the columns and append calculated dataframes to a list.

Something like:

df = pd.merge(left=df1, right=df2, on='X', how='inner')
output_frames = []
letters = [i[-1] for i in df.columns if not i == 'X'] #Get letters in your columns
letters = list(set(letters)) #Get list of letters with single element
for letter in letters:
    newdf = df.loc[:, ['X'] + [i for i in df.columns if i.endswith(letter)]]
    newdf['Difference'] = newdf[f'par {letter}'] - newdf[f'bar {letter}']
    newdf['Status'] = newdf.apply(lambda x: 'OK' if x.Difference >= 0 else 'NOT OK', axis=1)
    output_frames.append(newdf)

Then view output:

for df in newdf:
    print(df)

Or better still, merge the outputs:

df = pd.concat(output_frames, axis=1)


问:
How to run a command with arguments in Laravel Vapor
I Just started testing Laravel Vapor, everything working well except I'm using filament package which it needs to run a command to create admin user, the command is working locally on my computer and I have a user now, but in production when I execute the command (./vendor/bin/vapor command production) and then the command that creates the user (php artisan make:filament-user). vapor not giving any input to enter my name and my email address. So is there anyway to give arguments for commands in vapor? or is there anyway to give the these arguments with the command? thank you

答:
simple, just use your command by command line in the console or inside vapor page, menu commands in your project, example:

php artisan <command_name> '<arguments_parameters>'

my job command with argument:
php artisan metric:consolidate '2022-01-29 00:00' (job name with date start argument).


问:
.net desktop app installation
I am creating a  C# .Net 4.0 desktop application for a client.  When I sent him the .msi files it requires administration privileges when trying to install.  I realize the reason why is because I am installing the application into the "Program Files" directory.

Is there a way to install an application into an area on the users machine that doesn't require them to install as Administrator?

I'm using .Net 4.0

答:
Not sure whether this will solve the "requires Administrator" problem, but you can change the target folder for your installation in "File System" view of your setup project:

Right-click on the setup project in the solution explorer and choose View / File System.

Select "Application Folder".

In Properties, change the DefaultLocation.

Also it is usually a good idea to distribute setup.exe alongside *.msi, so any missing prerequisites may be installed automatically.

Title: .net desktop app installation


问:
AttributeError: 'NoneType' object has no attribute 'get_member'
So this is my code:

```<code>class Rostercheck(commands.Cog, name='Rostercheck'):
    def __init__(self, bot):
        self.bot = bot
        self.roster = {
            "sast" : {"roster": "PLACEHOLDER", "discordid_range":'PLACEHOLDER'}
        }
        self.guild_metadata = {"sast": PLACEHOLDER}
        self.channel_metadata = {
            "sast": {"roster_check": PLACEHOLDER}
        }
        self.check_discord_members.start()

    async def send_message(self, content, channel=None):
        try:
            await channel.send(content)
        except Exception as e:
            print(f"Encountered exception: {e}")

    async def get_roster_sheet(self, dept_name):
        scopes = ['https://www.googleapis.com/auth/spreadsheets']
        service_account_file = './keys.json'
        creds = service_account.Credentials.from_service_account_file(service_account_file, scopes=scopes)
        service = build('sheets', 'v4', credentials=creds)
        my_dept_roster = self.roster.get(dept_name)
        sheet = service.spreadsheets()
        return sheet.values().get(spreadsheetId=my_dept_roster.get("roster"),range=my_dept_roster.get("discordid_range")).execute()

    @tasks.loop(seconds=100)
    async def check_discord_members(self):
        print("yo")
        for dept_name in self.roster.keys():
            print(dept_name)
            google_sheet = await self.get_roster_sheet(dept_name)
            print(google_sheet)
            for value_list in google_sheet.get("values"):
                print(value_list)
                if len(value_list) != 1 or value_list is None or "Discord ID" in value_list:
                    continue
                value = value_list[0]
                print(value)
                discord_server = self.bot.get_guild(self.guild_metadata.get(dept_name))
                print(discord_server)
                discord_member = discord_server.get_member(int(re.sub("[^0-9]", "", value)))
                print(discord_member)
                if discord_member is None:
                    my_chan = self.bot.get_channel(id=self.channel_metadata.get(dept_name).get("roster_check"))
                    print(my_chan)
                    await self.send_message(f"{value} - <@{value}> is not within the {dept_name} roster, are you sure they are still in your department?", my_chan)

def setup(bot):
    bot.add_cog(Rostercheck(bot))
</code>```

I had it print each step of the process, but it breaks right at the print(discord_server) and it gives the error: AttributeError: 'NoneType' object has no attribute 'get_member'

The code is supposed to read discordid from a google sheet, and check if those discordids are still in that specific discord server.

The get_guild, get_member, and get_channel are just being really weird and I am not sure if it is because the code is in a cog causing it to just break as or if there is another issue but I have ensured everything outside of the code is working.

答:
It's most likely a cache issue as Dominik said and since get_guild() gets the guild from the cache and doesn't make an API call it returns None. So instead using fetch_guild() should solve this issue.

discord_server = self.bot.fetch_guild(self.guild_metadata.get(dept_name))
```
<hr/>
If this doesn't work another issue might be the guild ID being a string in which case you will need to parse it into an integer first.
<pre class="lang-py prettyprint-override"><code>discord_server = self.bot.fetch_guild(int(self.guild_metadata.get(dept_name)))
</code>```

Body:
So this is my code:

class Rostercheck(commands.Cog, name='Rostercheck'):
    def __init__(self, bot):
        self.bot = bot
        self.roster = {
            "sast" : {"roster": "PLACEHOLDER", "discordid_range":'PLACEHOLDER'}
        }
        self.guild_metadata = {"sast": PLACEHOLDER}
        self.channel_metadata = {
            "sast": {"roster_check": PLACEHOLDER}
        }
        self.check_discord_members.start()

    async def send_message(self, content, channel=None):
        try:
            await channel.send(content)
        except Exception as e:
            print(f"Encountered exception: {e}")

    async def get_roster_sheet(self, dept_name):
        scopes = ['https://www.googleapis.com/auth/spreadsheets']
        service_account_file = './keys.json'
        creds = service_account.Credentials.from_service_account_file(service_account_file, scopes=scopes)
        service = build('sheets', 'v4', credentials=creds)
        my_dept_roster = self.roster.get(dept_name)
        sheet = service.spreadsheets()
        return sheet.values().get(spreadsheetId=my_dept_roster.get("roster"),range=my_dept_roster.get("discordid_range")).execute()

    @tasks.loop(seconds=100)
    async def check_discord_members(self):
        print("yo")
        for dept_name in self.roster.keys():
            print(dept_name)
            google_sheet = await self.get_roster_sheet(dept_name)
            print(google_sheet)
            for value_list in google_sheet.get("values"):
                print(value_list)
                if len(value_list) != 1 or value_list is None or "Discord ID" in value_list:
                    continue
                value = value_list[0]
                print(value)
                discord_server = self.bot.get_guild(self.guild_metadata.get(dept_name))
                print(discord_server)
                discord_member = discord_server.get_member(int(re.sub("[^0-9]", "", value)))
                print(discord_member)
                if discord_member is None:
                    my_chan = self.bot.get_channel(id=self.channel_metadata.get(dept_name).get("roster_check"))
                    print(my_chan)
                    await self.send_message(f"{value} - <@{value}> is not within the {dept_name} roster, are you sure they are still in your department?", my_chan)

def setup(bot):
    bot.add_cog(Rostercheck(bot))

I had it print each step of the process, but it breaks right at the print(discord_server) and it gives the error: AttributeError: 'NoneType' object has no attribute 'get_member'

The code is supposed to read discordid from a google sheet, and check if those discordids are still in that specific discord server.

The get_guild, get_member, and get_channel are just being really weird and I am not sure if it is because the code is in a cog causing it to just break as or if there is another issue but I have ensured everything outside of the code is working.

Body:
It's most likely a cache issue as Dominik said and since get_guild() gets the guild from the cache and doesn't make an API call it returns None. So instead using fetch_guild() should solve this issue.

discord_server = self.bot.fetch_guild(self.guild_metadata.get(dept_name))

If this doesn't work another issue might be the guild ID being a string in which case you will need to parse it into an integer first.

discord_server = self.bot.fetch_guild(int(self.guild_metadata.get(dept_name)))


问:
Difference between await Task and await Func<Task>()
I have a program which needs to run a number of async tasks in parallel. The main difference between two implements, Task1() and Task2():

Task1() saves the FTask of type Func<Task> and later await Task.WhenAny(FTask()),

Task2() saves the Task produced by Task.Run() and later await Task.WhenAny(Task).

I think they should be equivalent, but Task1() does not work properly, however Task2() does work.

The flow of this program is:
If there are available task contexts in the free queue, dequeue one and setup it up with an async task; when async task finished put the context back to the free queue.

The problem is Task1() which saves Func<Task> does not work, it seems the async task has more than one instances running.

The complete code is:

```<code>static async Task Task1()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task1 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.FTask = async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            };

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));
    Console.WriteLine($"-------- Task1 finished --------");
}

static async Task Task2()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task2 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = Task.Run(async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            });

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task2 finished --------");
}

public class TaskCtx
{
    public int Token;
    public int Delay1;
    public int Delay2;
    public Func<Task> FTask;
    public Task Task;

    public TaskCtx()
    {
        FTask = async () => await Task.CompletedTask;
        Task = Task.CompletedTask;
    }
}
</code>```

The output of Task1():

-------- Task1 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[0] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1   <-- [1] is running and got the ticket
[4] submit
[4] start
[1] start               <-- another [1] starts ???
[2] start
[3] start
[2] wait ticket: 1
[1] wait ticket: 1
[1] acquire ticket: 1
[4] wait ticket: 1
[3] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[2] acquire ticket: 2
[1] release ticket: 2
[3] acquire ticket: 3
[3] acquire ticket: 3
[5] submit
[6] submit
[4] start
[6] start
[2] start
[3] start
[2] wait ticket: 3
[4] wait ticket: 3
[6] wait ticket: 3
[3] wait ticket: 3
[3] acquire ticket: 3
[2] release ticket: 3
[4] acquire ticket: 4
[2] release ticket: 3
[4] acquire ticket: 4
[3] release ticket: 5
[6] acquire ticket: 6
[3] release ticket: 5
[3] release ticket: 7
[4] release ticket: 8
[4] release ticket: 8
[6] release ticket: 10
```
<p>The output of <code>Task2()</code>:</p>
<pre class="lang-none prettyprint-override"><code>-------- Task2 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] wait ticket: 0
[0] acquire ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] submit
[4] start
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] submit
[5] start
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task2 finished --------
</code>```

UPDATE:
I make another implement, by use a normal async function, not anonymous function:

```<code>static async Task Task3()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    Ticket ticket = new Ticket(0);

    Console.WriteLine($"-------- Task3 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = RunTask3Async(x, ticket, qFree);

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task3 finished --------");
}

static async Task RunTask3Async(TaskCtx x, Ticket ticket, Queue<TaskCtx> qFree)
{
    Console.WriteLine($"[{x.Token}] start");
    await Task.Delay(x.Delay1);

    Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
    while (ticket.ticket != x.Token)
    {
        await Task.Yield(); // yield and wait other task increases the ticket
    }

    Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
    await Task.Delay(x.Delay2);
    Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
    ticket.ticket++;

    qFree.Enqueue(x);
}

public class Ticket
{
    public int ticket;

    public Ticket(int t)
    {
        ticket = t;
    }

    public override string ToString()
    {
        return $"{ticket}";
    }
}
</code>```

Task3() also works, the output is:

-------- Task3 start --------
[0] start
[0] submit
[1] start
[1] submit
[2] start
[2] submit
[3] start
[3] submit
[0] wait ticket: 0
[3] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] start
[4] submit
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] start
[5] submit
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task3 finished --------
```
<p>UPDATE2:
I tried to minimal the example but the following code does not have this problem.</p>
<pre class="lang-c# prettyprint-override"><code>var FTasks = Enumerable.Range(0, 8).Select(i => async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
}).ToArray();

await Task.WhenAll(FTasks.Select(x => x()));

Console.WriteLine("----------------");

var Tasks = Enumerable.Range(0, 8).Select(i => Task.Run(async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
})).ToArray();

await Task.WhenAll(Tasks);
</code>```

答:
As others have noted, the main difference between Task and Func<Task> is that the first one represents an operation (that has already started), and the second one represents a delegate that starts an operation. This is the same logic as for any T and Func<T>.

So, the question of "why are these run more than once?" is answered by looking in your Task1:

```<code>        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));
</code>```

Every time your code calls FTask(), it's starting a new asynchronous operation. So each call to Task.WhenAny will start all the tasks in the taskPool, and the final call to Task.WhenAll will start all the tasks in taskPool again.

Body:
I have a program which needs to run a number of async tasks in parallel. The main difference between two implements, Task1() and Task2():

Task1() saves the FTask of type Func<Task> and later await Task.WhenAny(FTask()),

Task2() saves the Task produced by Task.Run() and later await Task.WhenAny(Task).

I think they should be equivalent, but Task1() does not work properly, however Task2() does work.

The flow of this program is:
If there are available task contexts in the free queue, dequeue one and setup it up with an async task; when async task finished put the context back to the free queue.

The problem is Task1() which saves Func<Task> does not work, it seems the async task has more than one instances running.

The complete code is:

static async Task Task1()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task1 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.FTask = async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            };

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));
    Console.WriteLine($"-------- Task1 finished --------");
}

static async Task Task2()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task2 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = Task.Run(async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            });

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task2 finished --------");
}

public class TaskCtx
{
    public int Token;
    public int Delay1;
    public int Delay2;
    public Func<Task> FTask;
    public Task Task;

    public TaskCtx()
    {
        FTask = async () => await Task.CompletedTask;
        Task = Task.CompletedTask;
    }
}

The output of Task1():

-------- Task1 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[0] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1   <-- [1] is running and got the ticket
[4] submit
[4] start
[1] start               <-- another [1] starts ???
[2] start
[3] start
[2] wait ticket: 1
[1] wait ticket: 1
[1] acquire ticket: 1
[4] wait ticket: 1
[3] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[2] acquire ticket: 2
[1] release ticket: 2
[3] acquire ticket: 3
[3] acquire ticket: 3
[5] submit
[6] submit
[4] start
[6] start
[2] start
[3] start
[2] wait ticket: 3
[4] wait ticket: 3
[6] wait ticket: 3
[3] wait ticket: 3
[3] acquire ticket: 3
[2] release ticket: 3
[4] acquire ticket: 4
[2] release ticket: 3
[4] acquire ticket: 4
[3] release ticket: 5
[6] acquire ticket: 6
[3] release ticket: 5
[3] release ticket: 7
[4] release ticket: 8
[4] release ticket: 8
[6] release ticket: 10

The output of Task2():

-------- Task2 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] wait ticket: 0
[0] acquire ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] submit
[4] start
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] submit
[5] start
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task2 finished --------

UPDATE:
I make another implement, by use a normal async function, not anonymous function:

static async Task Task3()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    Ticket ticket = new Ticket(0);

    Console.WriteLine($"-------- Task3 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = RunTask3Async(x, ticket, qFree);

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task3 finished --------");
}

static async Task RunTask3Async(TaskCtx x, Ticket ticket, Queue<TaskCtx> qFree)
{
    Console.WriteLine($"[{x.Token}] start");
    await Task.Delay(x.Delay1);

    Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
    while (ticket.ticket != x.Token)
    {
        await Task.Yield(); // yield and wait other task increases the ticket
    }

    Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
    await Task.Delay(x.Delay2);
    Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
    ticket.ticket++;

    qFree.Enqueue(x);
}

public class Ticket
{
    public int ticket;

    public Ticket(int t)
    {
        ticket = t;
    }

    public override string ToString()
    {
        return $"{ticket}";
    }
}

Task3() also works, the output is:

-------- Task3 start --------
[0] start
[0] submit
[1] start
[1] submit
[2] start
[2] submit
[3] start
[3] submit
[0] wait ticket: 0
[3] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] start
[4] submit
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] start
[5] submit
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task3 finished --------

UPDATE2:
I tried to minimal the example but the following code does not have this problem.

var FTasks = Enumerable.Range(0, 8).Select(i => async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
}).ToArray();

await Task.WhenAll(FTasks.Select(x => x()));

Console.WriteLine("----------------");

var Tasks = Enumerable.Range(0, 8).Select(i => Task.Run(async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
})).ToArray();

await Task.WhenAll(Tasks);

Body:
As others have noted, the main difference between Task and Func<Task> is that the first one represents an operation (that has already started), and the second one represents a delegate that starts an operation. This is the same logic as for any T and Func<T>.

So, the question of "why are these run more than once?" is answered by looking in your Task1:

        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));

Every time your code calls FTask(), it's starting a new asynchronous operation. So each call to Task.WhenAny will start all the tasks in the taskPool, and the final call to Task.WhenAll will start all the tasks in taskPool again.


问:
Anchor tags to jump halfway down a page in NetSuite (SuiteCommerce Advanced)
Does NetSuite SuiteCommerce not support anchor tags? I want to include some links at the top of my page that let the viewer jump down to that category (on the same page).  I know I have my code set up properly, but all that happens is that it tries to open a new page with no content on it:

https://www.prospectfastener.com/product-interchange

答:
Using Anchor Tags with NetSuite SuiteCommerce

Bundled together a few answers from other Backbone related questions.  This can be used in custom extensions or it can be placed in to SMT CMS HTML Content as an inline script.

Tested with SC 2022.1

// This breaks the function out of the try/catch for use on page
var scrollToAnchorFn = null;
// SB env keeps doubling loading inline scripts for testing
// This tests/sets its own property on the window to test against for that
if (typeof window.anchorSet === 'undefined') {
  try {
    window.anchorSet = true;
    // Call scrollToAnchor with anchor ID whenever you want to jump between points on a page
    const scrollToAnchor = (anchorId) => {
      try {
        var aTag = $(anchorId);
        $('html,body').animate({
            scrollTop: aTag.offset().top
          },
          'slow',
        );
      } catch (err) {
        console.error(err);
      }
    };

    const initAnchorScroll = () => {
      // Test if jQuery is loaded yet, if not set timeout and repeat fn
      if (window.jQuery) {
        // Check if document is already loaded and ready, run code now if dom is ready
        if (document.readyState === 'complete')
          return scrollToAnchor(PageHash);
        // Before images or styling is finished loading, move to part of dom requested which is ready
        return $(document).ready(() => {
          scrollToAnchor(PageHash);
        });
      }
      setTimeout(function() {
        initAnchorScroll();
      }, 50);
    };

    // Get our page hash
    //  const PageHash = window.location.hash;
    // Snippet demo hash
    const PageHash = '#testAnchor';

    // Initialize on page load if hash detected in url
    // Since hashes return the #,
    // we want a length greater than 1 to ensure there is an id
    if (PageHash.length > 1) initAnchorScroll();
    scrollToAnchorFn = scrollToAnchor;
  } catch (err) {
    console.error(err);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fillerDiv {
  height: 100vh;
  width: 1000vw;
  background-color: #fedd00;
}

#testAnchor {
  background-color: #4285f4;
  color: #ffffff;
}</code>```

this is test content down the page with anchor ID.
    Go to Next Anchor

Second anchor tag

```

Old Answer

I'm going to assume not, but I'd be happy to be wrong.

Note: Anchor Tags are not supported by Content Delivery.

NetSuite Applications Suite -- Understanding Content Delivery

Body:
Using Anchor Tags with NetSuite SuiteCommerce

Bundled together a few answers from other Backbone related questions.  This can be used in custom extensions or it can be placed in to SMT CMS HTML Content as an inline script.

Tested with SC 2022.1

// This breaks the function out of the try/catch for use on page
var scrollToAnchorFn = null;
// SB env keeps doubling loading inline scripts for testing
// This tests/sets its own property on the window to test against for that
if (typeof window.anchorSet === 'undefined') {
  try {
    window.anchorSet = true;
    // Call scrollToAnchor with anchor ID whenever you want to jump between points on a page
    const scrollToAnchor = (anchorId) => {
      try {
        var aTag = $(anchorId);
        $('html,body').animate({
            scrollTop: aTag.offset().top
          },
          'slow',
        );
      } catch (err) {
        console.error(err);
      }
    };

    const initAnchorScroll = () => {
      // Test if jQuery is loaded yet, if not set timeout and repeat fn
      if (window.jQuery) {
        // Check if document is already loaded and ready, run code now if dom is ready
        if (document.readyState === 'complete')
          return scrollToAnchor(PageHash);
        // Before images or styling is finished loading, move to part of dom requested which is ready
        return $(document).ready(() => {
          scrollToAnchor(PageHash);
        });
      }
      setTimeout(function() {
        initAnchorScroll();
      }, 50);
    };

    // Get our page hash
    //  const PageHash = window.location.hash;
    // Snippet demo hash
    const PageHash = '#testAnchor';

    // Initialize on page load if hash detected in url
    // Since hashes return the #,
    // we want a length greater than 1 to ensure there is an id
    if (PageHash.length > 1) initAnchorScroll();
    scrollToAnchorFn = scrollToAnchor;
  } catch (err) {
    console.error(err);
  }
}

.fillerDiv {
  height: 100vh;
  width: 1000vw;
  background-color: #fedd00;
}

#testAnchor {
  background-color: #4285f4;
  color: #ffffff;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="container">
  <div class="fillerDiv"></div>
  <div id="testAnchor">this is test content down the page with anchor ID.
    <a href="#" onclick="scrollToAnchorFn('#testAnchor2');">Go to Next Anchor</a></div>
  <div class="fillerDiv "></div>
  <div id="testAnchor2">Second anchor tag</div>
  <div class="fillerDiv "></div>
</div>

Old Answer

I'm going to assume not, but I'd be happy to be wrong.

Note: Anchor Tags are not supported by Content Delivery.

NetSuite Applications Suite -- Understanding Content Delivery


问:
"How do you want to open this file?" when running kubectl or minikube commands
I am trying to run some kubectl commands like

```<code>kubectl get nodes
kubectl get pods
</code>```

or to start a minikube cluster with minikube start, but whatever command I run from Windows Powershell, instead of getting a proper output I get whe Windows window asking me "How do you want to open this file?".
I have tried uninstalling and re-installing minikube, kubernetes-cli and Docker, but I had no luck. How can I solve?

答:
Try in PowerShell:
PS C:> Set-Alias -Name kubectl -Value kubectl.exe

Or
Download kubectl.exe
https://kubernetes.io/docs/tasks/tools/install-kubectl-windows/

then put into C:\windows\system32
Since that path is already registered in system Env Variables it should work.

If you prefer a different path, create/put the file there and set up a System Environment variable PATH

Body:
I am trying to run some kubectl commands like

kubectl get nodes
kubectl get pods

or to start a minikube cluster with minikube start, but whatever command I run from Windows Powershell, instead of getting a proper output I get whe Windows window asking me "How do you want to open this file?".
I have tried uninstalling and re-installing minikube, kubernetes-cli and Docker, but I had no luck. How can I solve?


问:
Regex: Only returns message string - That's starts with messages and string between parent message curly brace
I want to get all the message data only. Such that it should look for message and all the data between curly braces of the parent message. With the below code, I am getting service details too along with message which I don't want. Any suggestion on this experts thanks in advance.

```<code>String data = "/**\r\n" +
        " * file\r\n" +
        " */\r\n" +
        "syntax = \"proto3\";\r\n" +
        "package demo;\r\n" +
        "\r\n" +
        "import \"envoyproxy/protoc-gen-validate/validate/validate.proto\";\r\n" +
        "import \"google/api/annotations.proto\";\r\n" +
        "import \"google/protobuf/wrappers.proto\";\r\n" +
        "import \"protoc-gen-swagger/options/annotations.proto\";\r\n" +
        "\r\n" +
        "option go_package = \"bitbucket.com;\r\n" +
        "option java_multiple_files = true;\r\n" +
        "\r\n" +
        "schemes: HTTPS;\r\n" +
        "consumes: \"application/json\";\r\n" +
        "produces: \"application/json\";\r\n" +
        "responses: {\r\n" +
        "key:\r\n" +
        "    \"404\";\r\n" +
        "value: {\r\n" +
        "description:\r\n" +
        "    \"not exist.\";\r\n" +
        "schema: {\r\n" +
        "json_schema: {\r\n" +
        "type:\r\n" +
        "    STRING;\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "responses: {\r\n" +
        "key:\r\n" +
        "    \"401\";\r\n" +
        "value: {\r\n" +
        "description:\r\n" +
        "    \"Wrong user.\";\r\n" +
        "schema: {\r\n" +
        "json_schema: {\r\n" +
        "type:\r\n" +
        "    STRING;\r\n" +
        "};\r\n" +
        "example: {\r\n" +
        "value:\r\n" +
        "    '{ \"message\": \"wrong user.\" }'\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "\r\n" +
        "message message1 {\r\n" +
        "    message message2 {\r\n" +
        "        enum Enum {\r\n" +
        "            UNKNOWN = 0;    \r\n" +
        "        }\r\n" +
        "    }\r\n" +
        "    string id = 1;\r\n" +
        "    string name = 3;\r\n" +
        "    string account = 4;\r\n" +
        "}\r\n" +
        "\r\n" +
        "message User{\r\n" +
        "   string firstName = 1 ;\r\n" +
        "   string lastName  = 2 ;\r\n" +
        "   string middleName  = 3 [(validate.rules).repeated = { min_items: 0 }];\r\n" +
        "}\r\n" +
        "\r\n" +
        "service Userlogin{\r\n" +
        "   rpc Login(User) returns (APIResponse);\r\n" +
        "}";
List<String> allmsg = Arrays.asList(data.replaceAll("(?sm)\\A.*?(?=message)", "").split("\\R+(?=message)"));

</code>```

I am expecting response like below in my array list of string with size 2.

allMsg.get(0) should be

```<code>message message1 {
    message message2 {
        enum Enum {
            UNKNOWN = 0;
        }
    }
    string id = 1;
    string name = 3;
    string account = 4;
}

</code>```

allMsg.get(1) should be

```<code>message User{
    string firstName = 1 ;
    string lastName  = 2 ;
    string middleName  = 3 [(validate.rules).repeated = { min_items: 0 }];
}
</code>```

答:
You should see you other question.

```<code>Pattern.compile("(?s)^message(.(?!message|service))*");
</code>```

If message can appear after message

"message message1 {\r\n" +

You must adapt the regex.

Body:
I want to get all the message data only. Such that it should look for message and all the data between curly braces of the parent message. With the below code, I am getting service details too along with message which I don't want. Any suggestion on this experts thanks in advance.

String data = "/**\r\n" +
        " * file\r\n" +
        " */\r\n" +
        "syntax = \"proto3\";\r\n" +
        "package demo;\r\n" +
        "\r\n" +
        "import \"envoyproxy/protoc-gen-validate/validate/validate.proto\";\r\n" +
        "import \"google/api/annotations.proto\";\r\n" +
        "import \"google/protobuf/wrappers.proto\";\r\n" +
        "import \"protoc-gen-swagger/options/annotations.proto\";\r\n" +
        "\r\n" +
        "option go_package = \"bitbucket.com;\r\n" +
        "option java_multiple_files = true;\r\n" +
        "\r\n" +
        "schemes: HTTPS;\r\n" +
        "consumes: \"application/json\";\r\n" +
        "produces: \"application/json\";\r\n" +
        "responses: {\r\n" +
        "key:\r\n" +
        "    \"404\";\r\n" +
        "value: {\r\n" +
        "description:\r\n" +
        "    \"not exist.\";\r\n" +
        "schema: {\r\n" +
        "json_schema: {\r\n" +
        "type:\r\n" +
        "    STRING;\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "responses: {\r\n" +
        "key:\r\n" +
        "    \"401\";\r\n" +
        "value: {\r\n" +
        "description:\r\n" +
        "    \"Wrong user.\";\r\n" +
        "schema: {\r\n" +
        "json_schema: {\r\n" +
        "type:\r\n" +
        "    STRING;\r\n" +
        "};\r\n" +
        "example: {\r\n" +
        "value:\r\n" +
        "    '{ \"message\": \"wrong user.\" }'\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "}\r\n" +
        "\r\n" +
        "message message1 {\r\n" +
        "    message message2 {\r\n" +
        "        enum Enum {\r\n" +
        "            UNKNOWN = 0;    \r\n" +
        "        }\r\n" +
        "    }\r\n" +
        "    string id = 1;\r\n" +
        "    string name = 3;\r\n" +
        "    string account = 4;\r\n" +
        "}\r\n" +
        "\r\n" +
        "message User{\r\n" +
        "   string firstName = 1 ;\r\n" +
        "   string lastName  = 2 ;\r\n" +
        "   string middleName  = 3 [(validate.rules).repeated = { min_items: 0 }];\r\n" +
        "}\r\n" +
        "\r\n" +
        "service Userlogin{\r\n" +
        "   rpc Login(User) returns (APIResponse);\r\n" +
        "}";
List<String> allmsg = Arrays.asList(data.replaceAll("(?sm)\\A.*?(?=message)", "").split("\\R+(?=message)"));

I am expecting response like below in my array list of string with size 2.

allMsg.get(0) should be

message message1 {
    message message2 {
        enum Enum {
            UNKNOWN = 0;
        }
    }
    string id = 1;
    string name = 3;
    string account = 4;
}

allMsg.get(1) should be

message User{
    string firstName = 1 ;
    string lastName  = 2 ;
    string middleName  = 3 [(validate.rules).repeated = { min_items: 0 }];
}

Body:
You should see you other question.

Pattern.compile("(?s)^message(.(?!message|service))*");

If message can appear after message

"message message1 {\r\n" +

You must adapt the regex.


问:
How to align a picture,name and the post with css like facebook does?
I am trying to align  a full name,picture and the post just like they do in most social networks (linked-in or facebook).But i cant align them the well.Can anybody please try to fill the gaps with necessary css commands?Thank you in advance.

```<code><div>
 <span class="picture"> <img src="/assets/images/rails.png"/></span>
  <a  href="#" class="user-name">user-full-name</a>
 <span class="post"></span>
 </div>
</code>```

css

```<code> .picture{height:40px;
         width:40px;
         }

  .user-name{
         margin-bottom:35px;
            }
   .post{     }
</code>```

答:
span.picture {
    display: block;
    float: left;
    margin-right: 10px;
}
```

Body:
I am trying to align  a full name,picture and the post just like they do in most social networks (linked-in or facebook).But i cant align them the well.Can anybody please try to fill the gaps with necessary css commands?Thank you in advance.

  user-full-name

css

 .picture{height:40px;
         width:40px;
         }

  .user-name{
         margin-bottom:35px;
            }
   .post{     }