问:
The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services. at FirebaseAppError
I am learning to use Firebase Cloud Function and I am following Firebase's official tutorial video for Learn JavaScript Promises (Pt.1)

When I run a local server and  go to the HTTP link I get

Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.

I tried finding the solution but couldn't find anywhere. I got some vaguely related question but for javascript and my code is in typescript. I did add the suggested syntax in both .js and .ts file

```<code>admin.initializeApp(functions.config().firebase);
</code>```

But still, I get the same error

Here is my index.tcs.

```<code>import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

// Start writing Firebase Functions
// https://firebase.google.com/docs/functions/typescript

export const getVoucher = functions.https.onRequest((request, response) => {
    const promise = admin.firestore().doc('/voucher/Eg2AtnGmKmX8Y0vBZiBG').get()
    const p2 = promise.then(snapshot=>{
        const data = snapshot.data()
        response.send(data)
    })
    p2.catch(error => {
        //Handlle the error
        console.log('error: '+error)
        response.status(500).send(error)
    })
});
</code>```

The function works as intended when deployed to firebase tho.

答:
There is a performance argument to have the admin initializeApp within the function and not global scope.

You keep a global boolean var that you can use to decide whether your specific function needs to initialize.

Here's a great YouTube video on this topic by Firebase that's well worth a watch: https://www.youtube.com/watch?v=v3eG9xpzNXM

Example:

GLOBAL:

```<code>let isSpecificFunctionAdminInitialised = false;
</code>```

WITHIN FUNCTION:

```<code>const admin = require("firebase-admin");
if (!isSpecificFunctionAdminInitialised) {
  admin.initializeApp(functions.config().firebase);
  isSpecificFunctionAdminInitialised = true;
}
</code>```

Body:
I am learning to use Firebase Cloud Function and I am following Firebase's official tutorial video for Learn JavaScript Promises (Pt.1)

When I run a local server and  go to the HTTP link I get

Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.

I tried finding the solution but couldn't find anywhere. I got some vaguely related question but for javascript and my code is in typescript. I did add the suggested syntax in both .js and .ts file

admin.initializeApp(functions.config().firebase);

But still, I get the same error

Here is my index.tcs.

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

// Start writing Firebase Functions
// https://firebase.google.com/docs/functions/typescript

export const getVoucher = functions.https.onRequest((request, response) => {
    const promise = admin.firestore().doc('/voucher/Eg2AtnGmKmX8Y0vBZiBG').get()
    const p2 = promise.then(snapshot=>{
        const data = snapshot.data()
        response.send(data)
    })
    p2.catch(error => {
        //Handlle the error
        console.log('error: '+error)
        response.status(500).send(error)
    })
});

The function works as intended when deployed to firebase tho.

Body:
There is a performance argument to have the admin initializeApp within the function and not global scope.

You keep a global boolean var that you can use to decide whether your specific function needs to initialize.

Here's a great YouTube video on this topic by Firebase that's well worth a watch: https://www.youtube.com/watch?v=v3eG9xpzNXM

Example:

GLOBAL:

let isSpecificFunctionAdminInitialised = false;

WITHIN FUNCTION:

const admin = require("firebase-admin");
if (!isSpecificFunctionAdminInitialised) {
  admin.initializeApp(functions.config().firebase);
  isSpecificFunctionAdminInitialised = true;
}


来源: stackexchange

问:
Pairing list elements with indexes
Given a list of elements, I need to turn each element into a pair of the index number and the element. There are several ways to do it; this is the most concise I have found so far:

```<code>List.mapi (fun i x->i,x) xs
</code>```

But is there a more concise/idiomatic way to do it? For example, does F# have some built-in function to turn two elements into a pair, some equivalent of the C++ make_pair?

答:
Eight Ways to Write Indexed

As there is more than one way to do it (TIMTOWTDI) it is always good to learn about different approaches and it different pros and cons. Remember that there is never only one way to solve something. Here some examples you can learn from if you try to understand them.

1. The List Comprehension

```<code>let indexed1 xs =
    let mutable idx = 0
    [ for x in xs do
        yield idx,x
        idx <- idx + 1 ]
</code>```

2. Ziping It!

```<code>let indexed2 xs =
    List.zip
        (List.init (List.length xs) id)
         xs
</code>```

3. Recursion

```<code>let indexed3 xs =
    let rec cata idx xs =
        match xs with
        | []    -> []
        | x::xs -> (idx,x) :: cata (idx+1) xs
    cata 0 xs
</code>```

4. Tail-Recursion

```<code>let indexed4 xs =
    let rec loop idx result xs =
        match xs with
        | []    -> result
        | x::xs -> loop (idx+1) ((idx,x) :: result) xs
    List.rev (loop 0 [] xs)
</code>```

5. Folding it

```<code>let indexed5 xs =
    let mutable idx = -1
    List.fold (fun state x ->
        idx <- idx + 1
        (idx,x) :: state
    ) [] xs
    |> List.rev
</code>```

6. Folding without mutable

```<code>let indexed6 xs =
    List.fold (fun (idx,state) x ->
        (idx+1), (idx,x) :: state
    ) (0,[]) xs
    |> snd
    |> List.rev
</code>```

7. Folding it Backwards

```<code>let indexed7 xs =
    let lastIdx = List.length xs - 1
    List.foldBack (fun x (idx,xs) ->
        (idx-1), ((idx,x) :: xs)
    ) xs (lastIdx,[])
    |> snd
</code>```

8. Arraying it

```<code>let indexed8 xs =
    let arr = Array.ofList xs
    let mutable result = []
    for idx=(arr.Length - 1) downto 0 do
        result <- (idx,arr.[idx]) :: result
    result
</code>```

ContentLicense: CC BY-SA 4.0

Title: Pairing list elements with indexes

Body:
Given a list of elements, I need to turn each element into a pair of the index number and the element. There are several ways to do it; this is the most concise I have found so far:

List.mapi (fun i x->i,x) xs

But is there a more concise/idiomatic way to do it? For example, does F# have some built-in function to turn two elements into a pair, some equivalent of the C++ make_pair?

Body:
Eight Ways to Write Indexed

As there is more than one way to do it (TIMTOWTDI) it is always good to learn about different approaches and it different pros and cons. Remember that there is never only one way to solve something. Here some examples you can learn from if you try to understand them.

1. The List Comprehension

let indexed1 xs =
    let mutable idx = 0
    [ for x in xs do
        yield idx,x
        idx <- idx + 1 ]

2. Ziping It!

let indexed2 xs =
    List.zip
        (List.init (List.length xs) id)
         xs

3. Recursion

let indexed3 xs =
    let rec cata idx xs =
        match xs with
        | []    -> []
        | x::xs -> (idx,x) :: cata (idx+1) xs
    cata 0 xs

4. Tail-Recursion

let indexed4 xs =
    let rec loop idx result xs =
        match xs with
        | []    -> result
        | x::xs -> loop (idx+1) ((idx,x) :: result) xs
    List.rev (loop 0 [] xs)

5. Folding it

let indexed5 xs =
    let mutable idx = -1
    List.fold (fun state x ->
        idx <- idx + 1
        (idx,x) :: state
    ) [] xs
    |> List.rev

6. Folding without mutable

let indexed6 xs =
    List.fold (fun (idx,state) x ->
        (idx+1), (idx,x) :: state
    ) (0,[]) xs
    |> snd
    |> List.rev

7. Folding it Backwards

let indexed7 xs =
    let lastIdx = List.length xs - 1
    List.foldBack (fun x (idx,xs) ->
        (idx-1), ((idx,x) :: xs)
    ) xs (lastIdx,[])
    |> snd

8. Arraying it

let indexed8 xs =
    let arr = Array.ofList xs
    let mutable result = []
    for idx=(arr.Length - 1) downto 0 do
        result <- (idx,arr.[idx]) :: result
    result


问:
Is there a way to change the color of text on hover with inline css?
I have the code below for my nav bar. I want the text in the "Download Freebies" item to change color when the mouse is hovered over it. I am only editing an existing template and there's some css already written for it in the style sheet (for "single-freebie" and "freebie-box"). What can I add (and where) to make the text "Download Freebies" change color to blue when the mouse is hovered over it.

PS: I've already tried the ":hover" and maybe one or two other "solutions" I found online. The color isn't changing and the border of the "Download Freebies" instead jumps upwards or sideways when hovered. I know I am doing something wrong but can't figure out what it is. I am happy to post more code if you specifically request anything you want to look at for me.

```<code><div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                        <ul class="nav navbar-nav navbar-right">
                            <li ><a href="index.html">Home</a></li>
                            <li><a href="about.html">About</a></li>
                            <li><a href="./index.html#download-freebies">Download Freebies</a></li>
                            <li><div class="single-freebie">
                            <a href="upload-resources.html" class="freebie-box">Upload resources</a></li>
                            <li>
                            </li>
                        </ul><!-- / ul -->
                    </div><!-- /.navbar-collapse -->
</code>```

答:
You can use this or you can use JavaScript. I think both will meet your needs.

Home

About
  ```

Body:
I have the code below for my nav bar. I want the text in the "Download Freebies" item to change color when the mouse is hovered over it. I am only editing an existing template and there's some css already written for it in the style sheet (for "single-freebie" and "freebie-box"). What can I add (and where) to make the text "Download Freebies" change color to blue when the mouse is hovered over it.

PS: I've already tried the ":hover" and maybe one or two other "solutions" I found online. The color isn't changing and the border of the "Download Freebies" instead jumps upwards or sideways when hovered. I know I am doing something wrong but can't figure out what it is. I am happy to post more code if you specifically request anything you want to look at for me.

Home

About

Download Freebies

                            Upload resources

Body:
You can use this or you can use JavaScript. I think both will meet your needs.

<li ><a href="index.html"
   onMouseOver="this.style.color='#000'"
   onMouseOut="this.style.color='#333'">Home</a></li>
<li><a href="about.html"
   onMouseOver="this.style.color='#000'"
   onMouseOut="this.style.color='#333'">About</a></li>


问:
Interaction.author isn't defined but I already defined "interaction"
Code::

```<code>fs.writeFile("./logs.txt", `Hug command executed by ${interaction.author}`, function(err) {
            if(err) {
                return console.log(err)
            }
            console.log("The file has been saved!");
        });
</code>```

logs.txt:
Logs.txt file

Console:
Command prompt

Yes I did define interaction when making the slash command "async execute(interaction){
rest of code
}"

答:
interaction.author does not exist

Instead you should use interaction.user

Your code will look like

fs.writeFile("./logs.txt", `Hug command executed by ${interaction.user}`, function(err) {
            if(err) {
                return console.log(err)
            }
            console.log("The file has been saved!");
        });
```

You can also get the tag/username by adding .tag, .username

Read docs to help yourself out

Body:
Code::

fs.writeFile("./logs.txt", `Hug command executed by ${interaction.author}`, function(err) {
            if(err) {
                return console.log(err)
            }
            console.log("The file has been saved!");
        });

logs.txt:
Logs.txt file

Console:
Command prompt

Yes I did define interaction when making the slash command "async execute(interaction){
rest of code
}"

Body:
interaction.author does not exist

Instead you should use interaction.user

Your code will look like

fs.writeFile("./logs.txt", `Hug command executed by ${interaction.user}`, function(err) {
            if(err) {
                return console.log(err)
            }
            console.log("The file has been saved!");
        });

You can also get the tag/username by adding .tag, .username

Read docs to help yourself out


问:
useState Hook inside loop or conditional statement
I was reading the updated react docs whose link is here there is statement related to useState

If you want to useState in a condition or a loop, extract a new
component and put it there.

But what I know by the rules of hooks is that you cannot use hooks inside loops, conditions, or nested functions which is mentioned in the docs here

So can someone give an example of the first sentence, because they didn't gave an example or there.

My question is can we call hooks inside loops and conditional statements ?

答:
```<code>const Input = ()=>{
 const [value, setValue]= useState()
 return <input
             onChange={(e)=>setValue(e)}
             value={value} */ Don't mutate state /*
      />
}

</code>```

We should not be mutating state. React needs to compare it's virtual DOM to the current DOM to determine what to re-render. Futhermore, react hooks are asynchronous, meaning that value may not be updated to e at the point you try and assign to value. This was already achieved with setValue(e).

Body:
const Input = ()=>{
 const [value, setValue]= useState()
 return <input
             onChange={(e)=>setValue(e)}
             value={value} */ Don't mutate state /*
      />
}

We should not be mutating state. React needs to compare it's virtual DOM to the current DOM to determine what to re-render. Futhermore, react hooks are asynchronous, meaning that value may not be updated to e at the point you try and assign to value. This was already achieved with setValue(e).


问:
How to call masterpage function in a usercontrol page?
I want to call masterpage public function on usercontrol cs page.

whether this user control is called on the master page.

My user control is on the master page and i want to calling this master page function in this usercontrol.

答:
Why don't you create an event in the User control and subscribe that event in the Master page. Invoke the master page function in the event handler.

UserControl

```<code>public event void DoSomething(object o, EventArgs e);
</code>```

Master Page

```<code>UserControl.DoSomething += (o, e)=>
{
//Invoke Master Page function.
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Why don't you create an event in the User control and subscribe that event in the Master page. Invoke the master page function in the event handler.

UserControl

public event void DoSomething(object o, EventArgs e);

Master Page

UserControl.DoSomething += (o, e)=>
{
//Invoke Master Page function.
};


问:
Align types in type annotation Python
I want the arguments of a function to be a list and a Callable that can be called upon the type of list elements, i.e.:

import typing as tp

def foo(list_: list[T], func_: tp.Callable[[T], tp.Any]):
    func_(list_[0])
```

I don't care what the type T is, I only care if func_ can be called upon T.
Is there a way to annotate the function and not require a specific type of list elements?

答:
You need to make T a TypeVar:

```<code>from typing import Callable, TypeVar

T = TypeVar("T")
U = TypeVar("U")

def foo(arr: list[T], func: Callable[[T], U]) -> None:
    func(arr[0])
</code>```

Within a given call to foo, the arr and func arguments must have the same T:

```<code>foo(["asdf", "foo"], lambda x: x.replace("a", "b"))  # ok
foo([1, 2, 3], lambda x: x + 1)                      # ok
foo([1, 2, 3], lambda x: x.replace("foo", "bar"))    # error
</code>```

I suggest using another TypeVar as a placeholder for the return value because Any can easily lead to uncaught errors in the future, whereas a TypeVar with no bound will error if you make bad assumptions about what it supports:

```<code>def foo(arr: list[T], func: Callable[[T], Any]) -> None:
    x = func(arr[0]) + 2  # ok  (danger!)
</code>```
```<code>def foo(arr: list[T], func: Callable[[T], U]) -> None:
    x = func(arr[0]) + 2  # error  (good!)
</code>```

If you intend for func to always be a function that returns None, just specify None instead of either U or Any.

Title: Align types in type annotation Python

Body:
I want the arguments of a function to be a list and a Callable that can be called upon the type of list elements, i.e.:

import typing as tp

def foo(list_: list[T], func_: tp.Callable[[T], tp.Any]):
    func_(list_[0])

I don't care what the type T is, I only care if func_ can be called upon T.
Is there a way to annotate the function and not require a specific type of list elements?

Body:
You need to make T a TypeVar:

from typing import Callable, TypeVar

T = TypeVar("T")
U = TypeVar("U")

def foo(arr: list[T], func: Callable[[T], U]) -> None:
    func(arr[0])

Within a given call to foo, the arr and func arguments must have the same T:

foo(["asdf", "foo"], lambda x: x.replace("a", "b"))  # ok
foo([1, 2, 3], lambda x: x + 1)                      # ok
foo([1, 2, 3], lambda x: x.replace("foo", "bar"))    # error

I suggest using another TypeVar as a placeholder for the return value because Any can easily lead to uncaught errors in the future, whereas a TypeVar with no bound will error if you make bad assumptions about what it supports:

def foo(arr: list[T], func: Callable[[T], Any]) -> None:
    x = func(arr[0]) + 2  # ok  (danger!)

def foo(arr: list[T], func: Callable[[T], U]) -> None:
    x = func(arr[0]) + 2  # error  (good!)

If you intend for func to always be a function that returns None, just specify None instead of either U or Any.


问:
How to train AI to create familiar sounding, randomly generated names?
I am very new to python and I'd like to ask for an advice on how to, where to start, what to learn.
I've got this fantasy name generator (joining randomly picked letters), which every now and then creates a name which is acceptable, what I'd like to do though is to train an AI to generate names which aren't lets say just consonants, ultimately being able to generate human, elvish, dwarfish etc names.

I'd appreciate any advice in this matter.

Edit:

My idea is: I get a string of letters, if they resemble a name, I approve it, if not - reject. It creates a dataset of True/False values, which can be used in machine learning, at least that's what I am hoping for, as I said, I am new to programming.
Again, I don't mind learning, but where do I begin?

答:
Single characters are not really a good fit for this, as there are combinatorial restrictions as to which letters can be combined to larger sequences. It is much easier to not have single letters, but instead move on to bi-grams, tri-grams, or syllables. It doesn't really matter what you choose, as long as they can combine freely.

You need to come up with an inventory of elements which comply with the rules of your language; you can collect those from text samples in the language you are aiming for.

In the simplest case, get a list of names like the ones you want to generate, and collect three-letter sequences from that, preferably with their frequency count. Or simply make some up:
For example, if you have a language with a syllablic structure where you always have a consonant followed by a vowel, then by combining elements which are a consonant followed by a vowel you will always end up with valid names.

Then pick 2 to 5 (or however long you want your names to be) elements randomly from that inventory, perhaps guided by their frequency.
You could also add in a filter to remove those with unsuitable letter combinations (at the element boundaries) afterwards. Or go through the element list and remove invalid ones (eg any ending in 'q' -- either drop them, or add a 'u' to them).

Depending on what inventory you're using, you can simulate different languages/cultures for your names, as languages differ in their phonological structures.


问:
How to concatenate arrays in Snowflake with distinct values?
I have a MERGE scenario with an ARRAY_AGG() function in the main script. Once I have a match I'd like to combine the arrays from the source and target table but don't want to add existing values. I've looked at using ARRAY_CAT() but it doesn't return the expected output

This is the query:

```<code>SELECT
  ARRAY_CAT(ARRAY_CONSTRUCT('VALUE 1', 'VALUE 2'), ARRAY_CONSTRUCT('VALUE 1', 'VALUE 3')) arr_col
</code>```

But this returns:

ARR_COL

[  "VALUE 1",  "VALUE 2",  "VALUE 1",  "VALUE 3" ]

And what I need is :

ARR_COL

[  "VALUE 1",  "VALUE 2", "VALUE 3" ]

Is there an easy way to achieve this except converting to string, removing the dups with regex then splitting to array?

答:
I've created an UDF in the end that allows me to do this as a scalar function

// Distinct Concatenate
create or replace function array_dcat(array1 variant, array2 variant)
    returns variant
    language javascript
    comment = 'Returns a distinct concatenation of two arrays'
as
$$
     return Array.from(new Set([...ARRAY1,...ARRAY2]));
$$
;
```
<p>I used if as follows</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
  ARRAY_CONSTRUCT('VALUE 1', 'VALUE 2') arr1,
  ARRAY_CONSTRUCT('VALUE 1', 'VALUE 3') arr2,
  ARRAY_CAT(arr1, arr2) sn_array_cat,
  ARRAY_DCAT(arr1, arr2) udf_array_dcat;
</code>```

And returns

ARR1
ARR2
SN_ARRAY_CAT
UDF_ARRAY_CAT

[   "VALUE 1",   "VALUE 2" ]
[   "VALUE 1",   "VALUE 3" ]
[   "VALUE 1",   "VALUE 2",   "VALUE 1",   "VALUE 3" ]
[   "VALUE 1",   "VALUE 2",   "VALUE 3" ]

Body:
I have a MERGE scenario with an ARRAY_AGG() function in the main script. Once I have a match I'd like to combine the arrays from the source and target table but don't want to add existing values. I've looked at using ARRAY_CAT() but it doesn't return the expected output

This is the query:

SELECT
  ARRAY_CAT(ARRAY_CONSTRUCT('VALUE 1', 'VALUE 2'), ARRAY_CONSTRUCT('VALUE 1', 'VALUE 3')) arr_col

But this returns:

ARR_COL

[  "VALUE 1",  "VALUE 2",  "VALUE 1",  "VALUE 3" ]

And what I need is :

ARR_COL

[  "VALUE 1",  "VALUE 2", "VALUE 3" ]

Is there an easy way to achieve this except converting to string, removing the dups with regex then splitting to array?

Body:
I've created an UDF in the end that allows me to do this as a scalar function

// Distinct Concatenate
create or replace function array_dcat(array1 variant, array2 variant)
    returns variant
    language javascript
    comment = 'Returns a distinct concatenation of two arrays'
as
$$
     return Array.from(new Set([...ARRAY1,...ARRAY2]));
$$
;

I used if as follows

SELECT
  ARRAY_CONSTRUCT('VALUE 1', 'VALUE 2') arr1,
  ARRAY_CONSTRUCT('VALUE 1', 'VALUE 3') arr2,
  ARRAY_CAT(arr1, arr2) sn_array_cat,
  ARRAY_DCAT(arr1, arr2) udf_array_dcat;

And returns

ARR1
ARR2
SN_ARRAY_CAT
UDF_ARRAY_CAT

[   "VALUE 1",   "VALUE 2" ]
[   "VALUE 1",   "VALUE 3" ]
[   "VALUE 1",   "VALUE 2",   "VALUE 1",   "VALUE 3" ]
[   "VALUE 1",   "VALUE 2",   "VALUE 3" ]


问:
How to sort the nested object data in react-native
```<code>    {
    "lion":{
    "age_in_years":"10",
    "name":"king",
    "country":"africa"
    },

    "elephant":{
    "age_in_years":"15",
    "name":"hero",
    "country":"usa"
    },

    "racoon":{
    "age_in_years":"5",
    "name":"thanos",
    "country":"syria"
    },
   }
</code>```

This is the data I'm getting through a web socket in react-native. I want to sort it in ascending order based on the "age_in_years". So the oldest animal's data should be shown at top and  the youngest data at the last.

答:
You sould better work with an array insted of object as below, first map it into array and parse the age_in_years and sort it.

```<code>const obj2Array = Object.entries(<YourObject>).map(([key, value]) => ({...value, _id: key, age_in_years: parseInt(value.age_in_years)}));
const sorted = obj2Array.sort((a, b) => a.age_in_years - b.age_in_years);
</code>```

Then you can use .reduce if  you want the object back, nevertheless you can use the sorted array to render it.

Body:
    {
    "lion":{
    "age_in_years":"10",
    "name":"king",
    "country":"africa"
    },

    "elephant":{
    "age_in_years":"15",
    "name":"hero",
    "country":"usa"
    },

    "racoon":{
    "age_in_years":"5",
    "name":"thanos",
    "country":"syria"
    },
   }

This is the data I'm getting through a web socket in react-native. I want to sort it in ascending order based on the "age_in_years". So the oldest animal's data should be shown at top and  the youngest data at the last.

Body:
You sould better work with an array insted of object as below, first map it into array and parse the age_in_years and sort it.

const obj2Array = Object.entries(<YourObject>).map(([key, value]) => ({...value, _id: key, age_in_years: parseInt(value.age_in_years)}));
const sorted = obj2Array.sort((a, b) => a.age_in_years - b.age_in_years);

Then you can use .reduce if  you want the object back, nevertheless you can use the sorted array to render it.


问:
Is there an R function that will allow me to create a dummy variable based on a date being within a range?
I have high frequency data in the following form, 'yyyy-mm-dd hh:mm:ss' in Column A, there are no set intervals for this column. There is also another column of high frequency data in the same form, in Column B. Column B is in 5 minute intervals. I want to generate a dummy variable that equals 1 if the date in the Column A is equal to another cell in Column B, or alternatively it is between two of these timestamps.

For example, I have the timestamp 2018-01-01 09:12:00 in Column A, and in Column B I have the two timestamps 2018-01-01 09:10:00 followed by 2018-01-01 09:15:00. In this case, the dummy variable would equal 1 as the timestamp in column A falls between these two dates. The associated dummy variable would be in the same row as the first timestamp in Column B, 2018-01-01 09:10:00.

Body:
library(tidyverse)
library(lubridate)

data <- tibble(
  Col_A = structure(c(1514935860, 1514936280, 1514946120, 1515090600, 1515090600, 1515095040), tzone = "UTC", class = c("POSIXct", "POSIXt")),
  Col_B = structure(c(1517564040, 1517564340, 1517564640, 1517564940, 1517565240, 1517565540), tzone = "UTC", class = c("POSIXct", "POSIXt"))
)

data %>%
  mutate(a_in_b = Col_A  <= max(data$Col_B) & Col_A >= min(data$Col_B))


问:
Can't use .indexof on JSON string because it has no method 'indexof' javascript
I have some JSON parsed, but I would like to take a link I get from the JSON, find an identifier in the link that makes it different (e.g. www.foo.com/IDENTIFIER/home), and have that identifier as a string to plug into another function that uses the identifier.

Here's the code where I try to use indexOf to find the preidentifier path index so I can then get the index of the identifier after it (that code hasn't been written yet because I'm stuck here). This also uses JSONP.

```<code>$.jsonp({
    "url": "http://foo.com&callback=?",
    "data": {
    "alt": "json-in-script"
    },
    "success": function (data) {
        var link = data[0].link;
        var jsonText = JSON.stringify(link);

        // the below code returns string
        console.log('jsonText string?'+typeof jsonText);

        // the below code returns that this method has no object indexOf
        var index = jsonText.indexof("pre-identifier-path/");

    },
    "error": function () {
    }
});
</code>```

Thank you for your time, sorry if this a tad confusing.

答: The function is indexOf() i.e. capital O - it is case sensitive.

Body:
I have some JSON parsed, but I would like to take a link I get from the JSON, find an identifier in the link that makes it different (e.g. www.foo.com/IDENTIFIER/home), and have that identifier as a string to plug into another function that uses the identifier.

Here's the code where I try to use indexOf to find the preidentifier path index so I can then get the index of the identifier after it (that code hasn't been written yet because I'm stuck here). This also uses JSONP.

$.jsonp({
    "url": "http://foo.com&callback=?",
    "data": {
    "alt": "json-in-script"
    },
    "success": function (data) {
        var link = data[0].link;
        var jsonText = JSON.stringify(link);

        // the below code returns string
        console.log('jsonText string?'+typeof jsonText);

        // the below code returns that this method has no object indexOf
        var index = jsonText.indexof("pre-identifier-path/");

    },
    "error": function () {
    }
});

Thank you for your time, sorry if this a tad confusing.


问:
Return asynchronous data from an angular method
I am fairly new to angular and am still trying to wrap my head around doing things the angular + httpClient + rxjs way. I am trying to write the rxjs equivalent of the following:

```<code>
async onButtonClick = () => {
    const processedBooks = await this.getAndProcessBooks();
    await myGenericHttpClient.post('/api/something', processedBooks);
}

async getAndProcessBooks = () => {
    const books = await myGenericHttpClient.get('/api/books');

    const processedBooks = books.map(book => {
        return book.read = true;
    });

    return books;
};

</code>```

My understanding of rxjs is i need to use angular's httpClient to make the request then subscribe to the response:

```<code>getAndProcessBooks = () => {
    return httpClient.get('/api/books').subscribe(books => {
        return books;
    });
};

</code>```

However, the problem is getAndProcessBooks returns a subscription, not an array of books so I'm not sure how this method can return the data that I need. Any help or direction to resources would be appreciated!

答:
You could just take the observable and use it directly.

unprocessedBooks$: Observable<any>;

getAndProcessBooks() {
    unprocessedBooks$ = httpClient.get('/api/books').pipe(data => {return data;});
};

```
<p>And in html</p>
<pre class="lang-html prettyprint-override"><code><div>{{ unprocessedBooks$ | async}}</div>
</code>```

Body:
I am fairly new to angular and am still trying to wrap my head around doing things the angular + httpClient + rxjs way. I am trying to write the rxjs equivalent of the following:

async onButtonClick = () => {
    const processedBooks = await this.getAndProcessBooks();
    await myGenericHttpClient.post('/api/something', processedBooks);
}

async getAndProcessBooks = () => {
    const books = await myGenericHttpClient.get('/api/books');

    const processedBooks = books.map(book => {
        return book.read = true;
    });

    return books;
};

My understanding of rxjs is i need to use angular's httpClient to make the request then subscribe to the response:

getAndProcessBooks = () => {
    return httpClient.get('/api/books').subscribe(books => {
        return books;
    });
};

However, the problem is getAndProcessBooks returns a subscription, not an array of books so I'm not sure how this method can return the data that I need. Any help or direction to resources would be appreciated!

Body:
You could just take the observable and use it directly.

unprocessedBooks$: Observable<any>;

getAndProcessBooks() {
    unprocessedBooks$ = httpClient.get('/api/books').pipe(data => {return data;});
};

And in html

<div>{{ unprocessedBooks$ | async}}</div>


问:
Iterate through non public member data
Running the risk of being shouted down for lack of examples but I'm trying to access all of the property names/values from a list of non public members of an object:

Tried this which returns null:

```<code>var temp = (cbBasket).GetType().GetProperties().ToDictionary(p => p.Name, p => p.GetValue(cbBasket));
</code>```

And this which returns the type but not the value + plus the list contained over 90 key value pairs so I doubt if this is correct (!)

```<code>            Type myBasket = cbBasket.GetType();
            var myMemberInfo = myBasket.GetMembers();

            for (int i = 0; 1 < myMemberInfo.Length; i++)
            {
                var zString = myMemberInfo[i].Name + " " + myMemberInfo[i].MemberType;
            }
</code>```

Any help would be greatly appreciated.
Thanks,
C

答:
Looking through the source code, it seems you want something like this:</p>
```<code>ChargeBee.Api.Params parameters = cbBasket.Params();
var dict = (Dictionary<string, object>)typeof(ChargeBee.Api.Params)
    .GetField("m_dict", BindingFlags.Instance | BindingFlags.NonPublic)
    .GetValue(parameters);
</code>```

Title: Iterate through non public member data

Body:
Running the risk of being shouted down for lack of examples but I'm trying to access all of the property names/values from a list of non public members of an object:

Tried this which returns null:

var temp = (cbBasket).GetType().GetProperties().ToDictionary(p => p.Name, p => p.GetValue(cbBasket));

And this which returns the type but not the value + plus the list contained over 90 key value pairs so I doubt if this is correct (!)

            Type myBasket = cbBasket.GetType();
            var myMemberInfo = myBasket.GetMembers();

            for (int i = 0; 1 < myMemberInfo.Length; i++)
            {
                var zString = myMemberInfo[i].Name + " " + myMemberInfo[i].MemberType;
            }

Any help would be greatly appreciated.
Thanks,
C

Body:
Looking through the source code, it seems you want something like this:

ChargeBee.Api.Params parameters = cbBasket.Params();
var dict = (Dictionary<string, object>)typeof(ChargeBee.Api.Params)
    .GetField("m_dict", BindingFlags.Instance | BindingFlags.NonPublic)
    .GetValue(parameters);


问:
Angular multiple HTTP posts to same API with different request body sends the same request
I have a few graphs of resident care plan, and I use the same component for each graph, that calls the same API, but with different input data. I have a datepicker in a parent component and when this date is updated I want to update all the graphs. Each graph component should call the API with same date and different id, but the calls are being made all equals.

I have a parent component with children components on an *ngFor:

```<code><div *ngFor="let data of selectedItems">
    <app-care-plan-graph
        [careData]="data"
        [dateInput]="dateInput">
    </app-care-plan-graph>
</div>
</code>```

And from each CarePlanGraphComponent I make an API post call:

```<code>  @Input() careData: {careAdlId:any};
  @Input() dateInput: GetAdlEventRequest;
  constructor(private residentService: ResidentService) { }
  ngOnInit() {
    this.getAdlEvents(this.dateInput);
  }
  getAdlEvents(body: GetAdlEventRequest) {
    body.careAdlId = this.careData.careAdlId;
    console.log("calling get adl events: ", body);
    this.residentService.getAdlEvents(body).then((response: ApiResponseModel) => {
      // handle response
    })
  }
</code>```

The service call is a common http post:

```<code>  getAdlEvents(body): Observable<any> {
    return this.http.post(this.residentsBaseUrl + 'getAdlEvents', body);
  }

</code>```

On parent component I use ViewChildren to access to the carePlanGraph components and call the method getAdlEvents() on update of the view

```<code>  @ViewChildren(CarePlanGraphComponent) graphComponents: QueryList<any>;
.
.
.
  ngOnInit() {
    this.form.valueChanges.subscribe(data => {
      this.dateInput= {
        startDate: data.startDate,
        endDate: data.endDate
      };
      this.graphComponents.forEach(element => {
        element.getAdlEvents(this.selectedInputs);
      });
    })
  }
</code>```

Everything works fine up to the console.log before making the API post, but the post is being made allways with same request body, no matter that the console log shows that it has different ids.
I can see in the network tab that the payload its the same, here are some images of an example, in the console you can see that there are two different bodys, one with id 60 and other with id 61, but both API post were made with payload with id 61:
1st payload:
1st payload

2nd payload:
2nd payload

Any help on understanding this problem will be appreciated, for now I will move the Api posts to the parent component and use concatMap so that the post are made sequentially, and pass the data to the children, but I would really like to understand why this way is not working.

答:
The reason this is happening is that you're calling the request really with the same body.

Objects in Javascript are passed as a reference to the same obejcts.

Since you pass the object as a body to the API call in the first Graph and then modify the same object in the second Graph, it results in the same api call.

Best thing you can do is copy the body request each time you make the call. This is easily achieved via the spread operator (...).

```<code>  getAdlEvents(body: GetAdlEventRequest) {
    // copy the body and add care id
    body = {...body, careAdlId: this.careData.careAdlId};
    console.log("calling get adl events: ", body);
    this.residentService.getAdlEvents(body).then((response: ApiResponseModel) => {
      // handle response
    })
  }
</code>```

Body:
I have a few graphs of resident care plan, and I use the same component for each graph, that calls the same API, but with different input data. I have a datepicker in a parent component and when this date is updated I want to update all the graphs. Each graph component should call the API with same date and different id, but the calls are being made all equals.

I have a parent component with children components on an *ngFor:

    <app-care-plan-graph
        [careData]="data"
        [dateInput]="dateInput">
    </app-care-plan-graph>

And from each CarePlanGraphComponent I make an API post call:

  @Input() careData: {careAdlId:any};
  @Input() dateInput: GetAdlEventRequest;
  constructor(private residentService: ResidentService) { }
  ngOnInit() {
    this.getAdlEvents(this.dateInput);
  }
  getAdlEvents(body: GetAdlEventRequest) {
    body.careAdlId = this.careData.careAdlId;
    console.log("calling get adl events: ", body);
    this.residentService.getAdlEvents(body).then((response: ApiResponseModel) => {
      // handle response
    })
  }

The service call is a common http post:

  getAdlEvents(body): Observable<any> {
    return this.http.post(this.residentsBaseUrl + 'getAdlEvents', body);
  }

On parent component I use ViewChildren to access to the carePlanGraph components and call the method getAdlEvents() on update of the view

  @ViewChildren(CarePlanGraphComponent) graphComponents: QueryList<any>;
.
.
.
  ngOnInit() {
    this.form.valueChanges.subscribe(data => {
      this.dateInput= {
        startDate: data.startDate,
        endDate: data.endDate
      };
      this.graphComponents.forEach(element => {
        element.getAdlEvents(this.selectedInputs);
      });
    })
  }

Everything works fine up to the console.log before making the API post, but the post is being made allways with same request body, no matter that the console log shows that it has different ids.
I can see in the network tab that the payload its the same, here are some images of an example, in the console you can see that there are two different bodys, one with id 60 and other with id 61, but both API post were made with payload with id 61:
1st payload:
1st payload

2nd payload:
2nd payload

Any help on understanding this problem will be appreciated, for now I will move the Api posts to the parent component and use concatMap so that the post are made sequentially, and pass the data to the children, but I would really like to understand why this way is not working.

Body:
The reason this is happening is that you're calling the request really with the same body.

Objects in Javascript are passed as a reference to the same obejcts.

Since you pass the object as a body to the API call in the first Graph and then modify the same object in the second Graph, it results in the same api call.

Best thing you can do is copy the body request each time you make the call. This is easily achieved via the spread operator (...).

  getAdlEvents(body: GetAdlEventRequest) {
    // copy the body and add care id
    body = {...body, careAdlId: this.careData.careAdlId};
    console.log("calling get adl events: ", body);
    this.residentService.getAdlEvents(body).then((response: ApiResponseModel) => {
      // handle response
    })
  }


问:
APP CONNECT BUG VERSIONS - 2022 - UPDATED! Flutter & iOS & Android
Why is there this bug in AppConnect?

When uploading a version 1.0.5, I enter TestFlight and it is seen loading version 1.0.5.

but when I refresh the page, it shows me up to version 1.0.3:

答: It is not a bug. AppStore Connect is processing the archive you sent to TestFlight. Sometimes it's a long process (can take also 30/40 minutes). When processing is completed, the archive will be shown and will be clickable.</p>


问:
ESLint ES6 Redux global-required Unexpected require();

I have this problem with ESLint and can't soulve on my own, those stores are separated for each enviroement as you can see on the screenshot, how could I fix that to make ESLint happy and I to learn a new thing?

答:
This is the way I did in 2022 without changing the rule</p>
```<code><div :style="{backgroundImage: 'url(' + bg + ')'}" </div>
<script>
import bgImg from './assets/images/lg_bg.jpg';
export default {
    data() {
      return {
        bg: bgImg,
    };
  },
}
</script>
</code>```

Body:
This is the way I did in 2022 without changing the rule

<div :style="{backgroundImage: 'url(' + bg + ')'}" </div>
<script>
import bgImg from './assets/images/lg_bg.jpg';
export default {
    data() {
      return {
        bg: bgImg,
    };
  },
}
</script>


问:
Python class decorator arguments
I'm trying to pass optional arguments to my class decorator in python.
Below the code I currently have:

```<code>class Cache(object):
    def __init__(self, function, max_hits=10, timeout=5):
        self.function = function
        self.max_hits = max_hits
        self.timeout = timeout
        self.cache = {}

    def __call__(self, *args):
        # Here the code returning the correct thing.

@Cache
def double(x):
    return x * 2

@Cache(max_hits=100, timeout=50)
def double(x):
    return x * 2
</code>```

The second decorator with arguments to overwrite the default one (max_hits=10, timeout=5 in my __init__ function), is not working and I got the exception TypeError: __init__() takes at least 2 arguments (3 given). I tried many solutions and read articles about it, but here I still can't make it work.

Any idea to resolve this? Thanks!

答:
```<code>class myclass2:
 def __init__(self,arg):
  self.arg=arg
  print("call to init")
 def __call__(self,func):
  print("call to __call__ is made")
  self.function=func
  def myfunction(x,y,z):
   return x+y+z+self.function(x,y,z)
  self.newfunction=myfunction
  return self.newfunction
 @classmethod
 def prints(cls,arg):
  cls.prints_arg=arg
  print("call to prints is made")
  return cls(arg)

@myclass2.prints("x")
def myfunction1(x,y,z):
 return x+y+z
print(myfunction1(1,2,3))

remember it goes like this:
first call return object get second argument
usually if applicable it goes like argument,function,old function arguments
</code>```

Title: Python class decorator arguments

Body:
I'm trying to pass optional arguments to my class decorator in python.
Below the code I currently have:

class Cache(object):
    def __init__(self, function, max_hits=10, timeout=5):
        self.function = function
        self.max_hits = max_hits
        self.timeout = timeout
        self.cache = {}

    def __call__(self, *args):
        # Here the code returning the correct thing.

@Cache
def double(x):
    return x * 2

@Cache(max_hits=100, timeout=50)
def double(x):
    return x * 2

The second decorator with arguments to overwrite the default one (max_hits=10, timeout=5 in my __init__ function), is not working and I got the exception TypeError: __init__() takes at least 2 arguments (3 given). I tried many solutions and read articles about it, but here I still can't make it work.

Any idea to resolve this? Thanks!


问:
Git: pull --rebase without fetching
When I go to a branch I usually use git pull --rebase which will do a fetch from remote and then will rebase my commits on to the fetched branch. Which is fine. I like it very much because it keeps the history simple and linear.

There are situations where I know I don't want to fetch, because I just did it one minute ago. And me making a bad assumption of this has a very little impact. My fetch is very slow (approximately 20 seconds) because of the repository size. So I want to avoid it.

Let's call the branch in question MyBranch

Thing that works but I consider it being error prone:

```<code>$ git rebase orign/MyBranch
</code>```

I think it is error prone because I have to remember and type in (with the help of auto completion) the name of the current branch. Compared to my intent this is just an opportunity to make mistakes.

I could write a shell script that determines the name of the current branch and then issues this command properly. But I wouldn't do it if there were a simpler solution.

So it would be ideal if I could have a git pull --rebase --no-fetch functionality without making helper scripts.

答: As stated in the 1st comment (by @jonrsharpe) just do git rebase.

Title: Git: pull --rebase without fetching

Body:
When I go to a branch I usually use git pull --rebase which will do a fetch from remote and then will rebase my commits on to the fetched branch. Which is fine. I like it very much because it keeps the history simple and linear.

There are situations where I know I don't want to fetch, because I just did it one minute ago. And me making a bad assumption of this has a very little impact. My fetch is very slow (approximately 20 seconds) because of the repository size. So I want to avoid it.

Let's call the branch in question MyBranch

Thing that works but I consider it being error prone:

$ git rebase orign/MyBranch

I think it is error prone because I have to remember and type in (with the help of auto completion) the name of the current branch. Compared to my intent this is just an opportunity to make mistakes.

I could write a shell script that determines the name of the current branch and then issues this command properly. But I wouldn't do it if there were a simpler solution.

So it would be ideal if I could have a git pull --rebase --no-fetch functionality without making helper scripts.


问:
SELECT list is not in GROUP BY clause and contains nonaggregated column 'explore.ratings.id'
What I'm trying to do is selecting the trips , then group them by rate.

note: ratings is a polymorphic relationship

given we have 2 models :

```<code>trips
  id => int
  price => float
  city_id => uint
........

ratings:
  id => int
  ratable_id => int
  ratable_type=> varchar
  rate => small-int
......
</code>```

and here how am trying to do it:

```<code>\App\Models\Trip::where('price','>=','100')->with(['ratings' => function ($query) {
        $query->groupBy('ratings.rate');
    }])->get();
</code>```

and Whoops!:

"SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1
  of SELECT list is not in GROUP BY clause and contains nonaggregated
  column 'explore.ratings.id' which is not functionally dependent on
  columns in GROUP BY clause; this is incompatible with
  sql_mode=only_full_group_by (SQL: select * from ratings where
  ratings.ratable_id in (1, 2) and ratings.ratable_type =
  App\Models\Trip group by ratings.rate)

答: in your config -> database.php set  'strict' => false,</p>

Body:
What I'm trying to do is selecting the trips , then group them by rate.

note: ratings is a polymorphic relationship

given we have 2 models :

trips
  id => int
  price => float
  city_id => uint
........

ratings:
  id => int
  ratable_id => int
  ratable_type=> varchar
  rate => small-int
......

and here how am trying to do it:

\App\Models\Trip::where('price','>=','100')->with(['ratings' => function ($query) {
        $query->groupBy('ratings.rate');
    }])->get();

and Whoops!:

"SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1
  of SELECT list is not in GROUP BY clause and contains nonaggregated
  column 'explore.ratings.id' which is not functionally dependent on
  columns in GROUP BY clause; this is incompatible with
  sql_mode=only_full_group_by (SQL: select * from ratings where
  ratings.ratable_id in (1, 2) and ratings.ratable_type =
  App\Models\Trip group by ratings.rate)


问:
Counter doesn't work when click on Checkbox (JavaScript)
I have a problem with my JavaScript Code...
I'm developing a "ToDo-List", where you can add and remove Elements all of these things are already working but I also like to have an "counter" which shows the number (length) of all unchecked checkboxes.

I have created a button with JS:

```<code>   let btn = document.createElement("button");
   btn.classList.add("destroy");
</code>```

and I already have saved the right place for show the number (length) for the unchecked checkboxes:

```<code>let counter = document.getElementsByClassName("todo-count");
</code>```

and then i wrote code to show me the unclicked boxes:

```<code>for(let btn of buttons) {
                if(btn.classList.contains("destroy")) {
                    btn.addEventListener("click", function() {
                        btn.parentElement.parentElement.remove();

                        for(let counts of counter) {
                            let parsed = parseInt(counts.innerText);
                            counts.innerText = parsed - 1;
                        }

                    })
                }
            }
</code>```

As already mentioned, adding elements already works, but as soon as I add e.g. 5 elements and the first element (which, like all other elements, also has a checkbox) is calculated as minus 5 instead of minus 1...

答:
Just count the checked checkboxes, do not try to maintain the state.

function updateCounts() {

  const allCheckboxes = document.querySelectorAll(".my-class");
  const checkedCheckboxes = document.querySelectorAll(".my-class:checked");

  console.log("Checked count:", checkedCheckboxes.length);
  console.log("Unchecked count:", allCheckboxes.length - checkedCheckboxes.length);

}

updateCounts();

document.querySelector("form").addEventListener("change", updateCounts);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="checkbox" class="my-class">
  <input type="checkbox" class="my-class">
  <input type="checkbox" class="my-class">
  <input type="checkbox" class="my-class">
</form></code>```

Body:
I have a problem with my JavaScript Code...
I'm developing a "ToDo-List", where you can add and remove Elements all of these things are already working but I also like to have an "counter" which shows the number (length) of all unchecked checkboxes.

I have created a button with JS:

   let btn = document.createElement("button");
   btn.classList.add("destroy");

and I already have saved the right place for show the number (length) for the unchecked checkboxes:

let counter = document.getElementsByClassName("todo-count");

and then i wrote code to show me the unclicked boxes:

for(let btn of buttons) {
                if(btn.classList.contains("destroy")) {
                    btn.addEventListener("click", function() {
                        btn.parentElement.parentElement.remove();

                        for(let counts of counter) {
                            let parsed = parseInt(counts.innerText);
                            counts.innerText = parsed - 1;
                        }

                    })
                }
            }

As already mentioned, adding elements already works, but as soon as I add e.g. 5 elements and the first element (which, like all other elements, also has a checkbox) is calculated as minus 5 instead of minus 1...

Body:
Just count the checked checkboxes, do not try to maintain the state.

function updateCounts() {

  const allCheckboxes = document.querySelectorAll(".my-class");
  const checkedCheckboxes = document.querySelectorAll(".my-class:checked");

  console.log("Checked count:", checkedCheckboxes.length);
  console.log("Unchecked count:", allCheckboxes.length - checkedCheckboxes.length);

}

updateCounts();

document.querySelector("form").addEventListener("change", updateCounts);

<form>
  <input type="checkbox" class="my-class">
  <input type="checkbox" class="my-class">
  <input type="checkbox" class="my-class">
  <input type="checkbox" class="my-class">
</form>


问:
Horizontal Pod Autoscaler (HPA) on Google Kubernetes Engine (GKE) using Backend Latency from an Ingress LoadBalancer via Stackdriver External Metric
I'm trying to configure a Horizontal Pod Autoscaler (HPA) on Google Kubernetes Engine (GKE) using External Metrics from an Ingress LoadBalancer, basing the configuration on instructions such as

https://cloud.google.com/kubernetes-engine/docs/tutorials/external-metrics-autoscaling
and
https://blog.doit-intl.com/autoscaling-k8s-hpa-with-google-http-s-load-balancer-rps-stackdriver-metric-92db0a28e1ea

With an HPA like

```<code>apiVersion: autoscaling/v2beta1
kind: HorizontalPodAutoscaler
metadata:
  name: my-api
  namespace: production
spec:
  minReplicas: 1
  maxReplicas: 20
  metrics:
  - external:
      metricName: loadbalancing.googleapis.com|https|request_count
      metricSelector:
        matchLabels:
          resource.labels.forwarding_rule_name: k8s-fws-production-lb-my-api--63e2a8ddaae70
      targetAverageValue: "1"
    type: External
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: my-api

</code>```

the autoscaler does kick in when the request count rises - but placing heavy load on the service, like 100 simultaneous requests per second, doesn't increase the external metric request_count much beyond 6 RPS, while the observed backend_latencies metric in Stackdriver does increase significantly; so I'd like to utilise that metric by adding to the HPA configuration, like so:

```<code>  - external:
      metricName: loadbalancing.googleapis.com|https|backend_latencies
      metricSelector:
        matchLabels:
          resource.labels.forwarding_rule_name: k8s-fws-production-lb-my-api--63e2a8ddaae70
      targetValue: "3000"
    type: External
</code>```

but that results in the error:

...unable to fetch metrics from external metrics API: googleapi: Error 400: Field aggregation.perSeriesAligner had an invalid value of "ALIGN_RATE": The aligner cannot be applied to metrics with kind DELTA and value type DISTRIBUTION., badRequest

which can be observed with the command

```<code>$ kubectl describe hpa -n production
</code>```

or by visiting

http://localhost:8080/apis/external.metrics.k8s.io/v1beta1/namespaces/default/loadbalancing.googleapis.com%7Chttps%7Cbackend_latencies

after setting up a proxy with

```<code>$ kubectl proxy --port=8080
</code>```

Are https/backend_latencies or https/total_latencies not supported as External Stackdriver Metrics in an HPA configuration for GKE?

答:
Maybe someone would find this helpful, though the question is old.

My working config looks like next:

```<code>  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 95
  - type: External
    external:
      metric:
       name: loadbalancing.googleapis.com|https|backend_latencies
       selector:
         matchLabels:
           resource.labels.backend_name: frontend
           metric.labels.proxy_continent: Europe
           reducer: REDUCE_PERCENTILE_95
      target:
        type: Value
        value: "79.5"
</code>```

type: Value used because it's the only way to not divide the metric value by the replica number.

reducer: REDUCE_PERCENTILE_95 used to work only with a single value of the distribution (source).

Also, I edited custom-metrics-stackdriver-adapter deployment to look like this:

```<code>  - image: gcr.io/gke-release/custom-metrics-stackdriver-adapter:v0.12.2-gke.0
    imagePullPolicy: Always
    name: pod-custom-metrics-stackdriver-adapter
    command:
    - /adapter
    - --use-new-resource-model=true
    - --fallback-for-container-metrics=true
    - --enable-distribution-support=true
</code>```

The thing is this key enable-distribution-support=true, which enables working with distribution kind of metrics.

Body:
I'm trying to configure a Horizontal Pod Autoscaler (HPA) on Google Kubernetes Engine (GKE) using External Metrics from an Ingress LoadBalancer, basing the configuration on instructions such as

https://cloud.google.com/kubernetes-engine/docs/tutorials/external-metrics-autoscaling
and
https://blog.doit-intl.com/autoscaling-k8s-hpa-with-google-http-s-load-balancer-rps-stackdriver-metric-92db0a28e1ea

With an HPA like

apiVersion: autoscaling/v2beta1
kind: HorizontalPodAutoscaler
metadata:
  name: my-api
  namespace: production
spec:
  minReplicas: 1
  maxReplicas: 20
  metrics:
  - external:
      metricName: loadbalancing.googleapis.com|https|request_count
      metricSelector:
        matchLabels:
          resource.labels.forwarding_rule_name: k8s-fws-production-lb-my-api--63e2a8ddaae70
      targetAverageValue: "1"
    type: External
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: my-api

the autoscaler does kick in when the request count rises - but placing heavy load on the service, like 100 simultaneous requests per second, doesn't increase the external metric request_count much beyond 6 RPS, while the observed backend_latencies metric in Stackdriver does increase significantly; so I'd like to utilise that metric by adding to the HPA configuration, like so:

  - external:
      metricName: loadbalancing.googleapis.com|https|backend_latencies
      metricSelector:
        matchLabels:
          resource.labels.forwarding_rule_name: k8s-fws-production-lb-my-api--63e2a8ddaae70
      targetValue: "3000"
    type: External

but that results in the error:

...unable to fetch metrics from external metrics API: googleapi: Error 400: Field aggregation.perSeriesAligner had an invalid value of "ALIGN_RATE": The aligner cannot be applied to metrics with kind DELTA and value type DISTRIBUTION., badRequest

which can be observed with the command

$ kubectl describe hpa -n production

or by visiting

http://localhost:8080/apis/external.metrics.k8s.io/v1beta1/namespaces/default/loadbalancing.googleapis.com%7Chttps%7Cbackend_latencies

after setting up a proxy with

$ kubectl proxy --port=8080

Are https/backend_latencies or https/total_latencies not supported as External Stackdriver Metrics in an HPA configuration for GKE?

Body:
Maybe someone would find this helpful, though the question is old.

My working config looks like next:

  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 95
  - type: External
    external:
      metric:
       name: loadbalancing.googleapis.com|https|backend_latencies
       selector:
         matchLabels:
           resource.labels.backend_name: frontend
           metric.labels.proxy_continent: Europe
           reducer: REDUCE_PERCENTILE_95
      target:
        type: Value
        value: "79.5"

type: Value used because it's the only way to not divide the metric value by the replica number.

reducer: REDUCE_PERCENTILE_95 used to work only with a single value of the distribution (source).

Also, I edited custom-metrics-stackdriver-adapter deployment to look like this:

  - image: gcr.io/gke-release/custom-metrics-stackdriver-adapter:v0.12.2-gke.0
    imagePullPolicy: Always
    name: pod-custom-metrics-stackdriver-adapter
    command:
    - /adapter
    - --use-new-resource-model=true
    - --fallback-for-container-metrics=true
    - --enable-distribution-support=true

The thing is this key enable-distribution-support=true, which enables working with distribution kind of metrics.


问:
Output of this javascript and the reason
```<code>function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();
</code>```

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

答:
So the code you posted outputs 1 2. Yet the code:

```<code>function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
getCtr()();
getCtr()();
</code>```

outputs only 1 1!

The difference is that if you save a reference to getCtr() by using the var ctr = getCtr();, you create what is called a closure.

So the difference between calling getCtr()() and ctr() is that ctr has i defined in its scope, and that scope is saved thanks to var ctr = getCtr();. Because the reference is saved, the function inside of ctr is able to always act on the same variable.

Body:
function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

Body:
So the code you posted outputs 1 2. Yet the code:

function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
getCtr()();
getCtr()();

outputs only 1 1!

The difference is that if you save a reference to getCtr() by using the var ctr = getCtr();, you create what is called a closure.

So the difference between calling getCtr()() and ctr() is that ctr has i defined in its scope, and that scope is saved thanks to var ctr = getCtr();. Because the reference is saved, the function inside of ctr is able to always act on the same variable.


答:
I would not use a .h file nor a .c file.

The .h extension indicates that the file is intended for possible inclusion in several translation units. This is not the case.

The .c extension indicates that the file is the main file of a translation unit. Some IDEs will automatically build it separately if found within the project folder.

Hence, (almost) any extension which is not .h or .c would be better, e.g. .inc. The .c file needing coeffs would then include it as follows:

```<code>#include "coeffs.inc"
</code>```

I would recommend putting the entire definition of coeffs in the file because the initializer list and the dimensions of the coeffs array are tightly coupled.

If coeffs is needed in several translation units, then of course it should be declared as extern in a .h file and the definition/initialization could then be in a separate .c file. However, in this case where coeffs is static (private within a single translation unit), the above approach is better so that it is clear that the array is local to the translation unit.

Title: Move large static array into a separate file: .c or .h?

Body:
I've got a large pre-calculated 4D array written in C:

static float coeffs[257][4][8][2] =
{
 {
  { { +0.999778485478688f, +0.021047089441095f }, { +1.000000000000000f, -0.000000000000000f }, { +0.999778485478688f, -0.021047089441095f }, { +0.999556987314086f, -0.029762881439599f }, { +0.999778485478688f, -0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, +0.021047089441095f }, { +0.999556987314086f, +0.029762881439599f },  },
  { { +0.999778485478688f, +0.021047089441095f }, { +0.999556987314086f, +0.029762881439599f }, { +0.999778485478688f, +0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, -0.021047089441095f }, { +0.999556987314086f, -0.029762881439599f }, { +0.999778485478688f, -0.021047089441095f }, { +1.000000000000000f, -0.000000000000000f },  },
  { { +0.999778485478688f, -0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, +0.021047089441095f }, { +0.999556987314086f, +0.029762881439599f }, { +0.999778485478688f, +0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, -0.021047089441095f }, { +0.999556987314086f, -0.029762881439599f },  },
  { { +0.999778485478688f, -0.021047089441095f }, { +0.999556987314086f, -0.029762881439599f }, { +0.999778485478688f, -0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f }, { +0.999778485478688f, +0.021047089441095f }, { +0.999556987314086f, +0.029762881439599f }, { +0.999778485478688f, +0.021047089441095f }, { +1.000000000000000f, +0.000000000000000f },  },
  },

 .
 .
 .
 },
}

It's about 1500 lines, so I would like to move it into a separate file.

The array should be static as it is used only in a single C file.

The question is, should such static arrays be moved into a header file and then included as #include "coeffs.h", or should they be a separate C file included as #include "coeffs.c"? Does it matter?

Body:
I would not use a .h file nor a .c file.

The .h extension indicates that the file is intended for possible inclusion in several translation units. This is not the case.

The .c extension indicates that the file is the main file of a translation unit. Some IDEs will automatically build it separately if found within the project folder.

Hence, (almost) any extension which is not .h or .c would be better, e.g. .inc. The .c file needing coeffs would then include it as follows:

#include "coeffs.inc"

I would recommend putting the entire definition of coeffs in the file because the initializer list and the dimensions of the coeffs array are tightly coupled.

If coeffs is needed in several translation units, then of course it should be declared as extern in a .h file and the definition/initialization could then be in a separate .c file. However, in this case where coeffs is static (private within a single translation unit), the above approach is better so that it is clear that the array is local to the translation unit.


问:
Frequently repeated try/except in Python
Firstly, I'm not sure if my approach is proper, so I'm open to a variety of suggestions.

If try/except statements are frequently repeated in code, are there any good ways to shorten them or avoid fully writing them out?

```<code>try:
    # Do similar thing
    os.remove('/my/file')
except OSError, e:
    # Same exception handing
    pass

try:
    # Do similar thing
    os.chmod('/other/file', 0700)
except OSError, e:
    #Same exception handling
    pass
</code>```

For example, for one line actions you could define a exception handling wrapper and then pass a lambda function:

```<code>def may_exist(func):
    "Work with file which you are not sure if exists."""
    try:
        func()
    except OSError, e:
        # Same exception handling
        pass

may_exist(lambda: os.remove('/my/file'))
may_exist(lambda: os.chmod('/other/file', 0700))
</code>```

Does this 'solution' just make things less clear? Should I just fully write out all the try/except statements?

答:
It would probably be cleaner to make may_exist a decorator:

```<code>from functools import wraps
def may_exist(func):
   @wraps(func):
   def wrapper(*args, **kwds):
       try:
           return func(*args, **kwds)
       except OSError:
           pass
   return wrapper
</code>```

Then you can either do:

```<code>may_exist(os.remove)('/my/file')
may_exist(os.chmod)('/other/file', 0700)
</code>```

for a one-off call, or:

```<code>remove_if_exists = may_exist(os.remove)
...
remove_if_exists('somefile')
</code>```

if you use it a lot.

Body:
Firstly, I'm not sure if my approach is proper, so I'm open to a variety of suggestions.

If try/except statements are frequently repeated in code, are there any good ways to shorten them or avoid fully writing them out?

try:
    # Do similar thing
    os.remove('/my/file')
except OSError, e:
    # Same exception handing
    pass

try:
    # Do similar thing
    os.chmod('/other/file', 0700)
except OSError, e:
    #Same exception handling
    pass

For example, for one line actions you could define a exception handling wrapper and then pass a lambda function:

def may_exist(func):
    "Work with file which you are not sure if exists."""
    try:
        func()
    except OSError, e:
        # Same exception handling
        pass

may_exist(lambda: os.remove('/my/file'))
may_exist(lambda: os.chmod('/other/file', 0700))

Does this 'solution' just make things less clear? Should I just fully write out all the try/except statements?

Body:
It would probably be cleaner to make may_exist a decorator:

from functools import wraps
def may_exist(func):
   @wraps(func):
   def wrapper(*args, **kwds):
       try:
           return func(*args, **kwds)
       except OSError:
           pass
   return wrapper

Then you can either do:

may_exist(os.remove)('/my/file')
may_exist(os.chmod)('/other/file', 0700)

for a one-off call, or:

remove_if_exists = may_exist(os.remove)
...
remove_if_exists('somefile')

if you use it a lot.


问:
Jetpack Compose + Navigation - Nested navigation with BottomNavBar
I'm trying to implement the following screen flow using Jetpack Compose + Jetpack Navigation:

Navigation concept

Actually, i am able to code two singles cases:

SplashScreen --> HomeScreen (with no BottomNavBar)

HomeScreen (with BottomNavBar) --> Tabs

I'm not able to code the whole problem. In fact, i have an issue with the management of the NavHost. In the first case (SplashScreen -> HomeScreen) i need to call the NavHost at a high scope:

```<code>class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        MyAppTheme {
            //init the Navigation Controller for screen navigation
            val navController = rememberNavController()

            //setup the Navigation Graph
            SetupNavGraph(navController)
</code>```

while in the second case i need to call it in the innerPadding scope of the Scaffold composable:

```<code>fun MainScreen(navController: NavHostController) {

    Scaffold(
        bottomBar = {
            BottomNavBar(navController)
        }
    ) { //innerPadding scope
        //setup the Navigation Graph
        SetupNavGraph(navController)
    }
}
</code>```

Please assume that SetupNavGraph() function works as intended (call NavHost to generate the navigation tree)

I tried to use two NavHost without success.

If i setup the NavHost in setContent() i'm able to load the splashscreen and move to an empty BottomNavBar screen. If i click on the BottomNavElements i'm able to navigate to the child tabs (in the example above "Favorite","Music","Places", "News") but the BottomNavBar disappears

I cannot setup NavHost in the innerPadding scope because this is loaded only after switching to the main screen (in the example above "Favorite Tab" + BottomBarNav)

The only workaround i found is generating the BottomNavBar composable in each of the BottomNav child tabs, but this generates a visible transition effect that i would like to avoid and, generally, doesn't seem a good practice.

答:
Ok, i found a solution. This are the steps to achieve the desired result:

Create two different NavGraph, one for Splash->MainScreen and the other for the BottomNavBar

```<code>const val ROOT_ROUTE = "root"

@Composable
fun SetupRootNavGraph(navController: NavHostController) {
    NavHost(
        navController = navController,
        startDestination = Screen.FirstScreen.route,
        route = ROOT_ROUTE
    ) {
        composable(Screen.FirstScreen.route) { FirstScreen(navController)}
        composable(Screen.SecondScreen.route) { MainScreen(navController)}
    }
}
</code>```
```<code>const val BOTTOM_BAR_ROUTE = "bottomBar"

@Composable
fun SetupNavGraphBottomBar(navController: NavHostController) {
    NavHost(
        navController = navController,
        startDestination = BottomBarScreen.FirstElement.route,
        route = BOTTOM_BAR_ROUTE
    ) {
        composable(BottomBarScreen.FirstElement.route) { FirstElementScreen() }
        composable(BottomBarScreen.SecondElement.route) { SecondElementScreen() }
        composable(BottomBarScreen.ThirdElement.route) { ThirdElementScreen() }
    }
}
</code>```

Init the NavController and the RootNavGraph after setContent() in your MainActivity. This will be in charge of the SplashScreen -> MainScreen navigation tree.

```<code>class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyAppTheme {

                //init the Navigation Controller for screen navigation
                val navController = rememberNavController()

                //setup the Root Navigation Graph
                SetupRootNavGraph(navController)
            }
        }
    }
}
</code>```

Re-init the NavController in the Screen where you have your BottomNavBar ("MainScreen" in the example) and the assign to it the BottomNavGraph in the innerPadding scope.

```<code>@Composable
fun MainScreen(navController: NavHostController) {

    //Re-initialize the NavController to set a new NavGraph
    val navControllerBottomBar = rememberNavController()

    Scaffold(
        bottomBar = {
            BottomNavBar(navControllerBottomBar)
        }
    ) {
        //setup the Navigation Graph
        SetupNavGraphBottomBar(navControllerBottomBar, user)
    }
}
</code>```

And this will work like charm! Of course you will need to structure your BottomNavBar in order to manage the navigation as documented on Official docs

Body:
I'm trying to implement the following screen flow using Jetpack Compose + Jetpack Navigation:

Navigation concept

Actually, i am able to code two singles cases:

SplashScreen --> HomeScreen (with no BottomNavBar)

HomeScreen (with BottomNavBar) --> Tabs

I'm not able to code the whole problem. In fact, i have an issue with the management of the NavHost. In the first case (SplashScreen -> HomeScreen) i need to call the NavHost at a high scope:

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        MyAppTheme {
            //init the Navigation Controller for screen navigation
            val navController = rememberNavController()

            //setup the Navigation Graph
            SetupNavGraph(navController)

while in the second case i need to call it in the innerPadding scope of the Scaffold composable:

fun MainScreen(navController: NavHostController) {

    Scaffold(
        bottomBar = {
            BottomNavBar(navController)
        }
    ) { //innerPadding scope
        //setup the Navigation Graph
        SetupNavGraph(navController)
    }
}

Please assume that SetupNavGraph() function works as intended (call NavHost to generate the navigation tree)

I tried to use two NavHost without success.

If i setup the NavHost in setContent() i'm able to load the splashscreen and move to an empty BottomNavBar screen. If i click on the BottomNavElements i'm able to navigate to the child tabs (in the example above "Favorite","Music","Places", "News") but the BottomNavBar disappears

I cannot setup NavHost in the innerPadding scope because this is loaded only after switching to the main screen (in the example above "Favorite Tab" + BottomBarNav)

The only workaround i found is generating the BottomNavBar composable in each of the BottomNav child tabs, but this generates a visible transition effect that i would like to avoid and, generally, doesn't seem a good practice.

Body:
Ok, i found a solution. This are the steps to achieve the desired result:

Create two different NavGraph, one for Splash->MainScreen and the other for the BottomNavBar

const val ROOT_ROUTE = "root"

@Composable
fun SetupRootNavGraph(navController: NavHostController) {
    NavHost(
        navController = navController,
        startDestination = Screen.FirstScreen.route,
        route = ROOT_ROUTE
    ) {
        composable(Screen.FirstScreen.route) { FirstScreen(navController)}
        composable(Screen.SecondScreen.route) { MainScreen(navController)}
    }
}

const val BOTTOM_BAR_ROUTE = "bottomBar"

@Composable
fun SetupNavGraphBottomBar(navController: NavHostController) {
    NavHost(
        navController = navController,
        startDestination = BottomBarScreen.FirstElement.route,
        route = BOTTOM_BAR_ROUTE
    ) {
        composable(BottomBarScreen.FirstElement.route) { FirstElementScreen() }
        composable(BottomBarScreen.SecondElement.route) { SecondElementScreen() }
        composable(BottomBarScreen.ThirdElement.route) { ThirdElementScreen() }
    }
}

Init the NavController and the RootNavGraph after setContent() in your MainActivity. This will be in charge of the SplashScreen -> MainScreen navigation tree.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyAppTheme {

                //init the Navigation Controller for screen navigation
                val navController = rememberNavController()

                //setup the Root Navigation Graph
                SetupRootNavGraph(navController)
            }
        }
    }
}

Re-init the NavController in the Screen where you have your BottomNavBar ("MainScreen" in the example) and the assign to it the BottomNavGraph in the innerPadding scope.

@Composable
fun MainScreen(navController: NavHostController) {

    //Re-initialize the NavController to set a new NavGraph
    val navControllerBottomBar = rememberNavController()

    Scaffold(
        bottomBar = {
            BottomNavBar(navControllerBottomBar)
        }
    ) {
        //setup the Navigation Graph
        SetupNavGraphBottomBar(navControllerBottomBar, user)
    }
}

And this will work like charm! Of course you will need to structure your BottomNavBar in order to manage the navigation as documented on Official docs


问:
Can I write a DTO which extracts both query and params vars in nestjs
I'm making an api which looks like:

http://example.com/story/:storyId/analytics?from={date}&to={date}

The storyId is part of the path, but from and to are query parameters.

I've got a DTO, like this:

class GetStoryAnalyticsDTO {
  storyId: string
  from: Date
  to: Date
}
```
<p>(validators omitted for brevity)</p>
<p>And I'm using it like this in my controler:</p>
<pre class="lang-js prettyprint-override"><code>@Get()
getStoryAnalytics(@Query() query: GetStoryAnalyticsRequestDto): Promise<MyResponse> {...}
</code>```

But, (obviously!), this only extracts the from and to parameters.

Is there any way to extract both from the query and the path to get all the vars in one dto?

If not, it's not a massive hassle - I can just add @Param storyId: string to the controller and it's all good :)

答:
You could make a custom decorator like @QueryParam() that pulls together req.query and req.params. It could look something like this:

export const QueryParam = createParamDecorator((data: unknown, context: ExecutionContext) => {
  const req = context.switchToHttp().getRequest();
  return { ...req.query, ...req.params };
});
```

And just make sure to add validateCustomDecorators on the ValidationPipe if you want it to auto validate for you. Otherwise, you're good to start using it.

Body:
I'm making an api which looks like:

http://example.com/story/:storyId/analytics?from={date}&to={date}

The storyId is part of the path, but from and to are query parameters.

I've got a DTO, like this:

class GetStoryAnalyticsDTO {
  storyId: string
  from: Date
  to: Date
}

(validators omitted for brevity)

And I'm using it like this in my controler:

@Get()
getStoryAnalytics(@Query() query: GetStoryAnalyticsRequestDto): Promise<MyResponse> {...}

But, (obviously!), this only extracts the from and to parameters.

Is there any way to extract both from the query and the path to get all the vars in one dto?

If not, it's not a massive hassle - I can just add @Param storyId: string to the controller and it's all good :)

Body:
You could make a custom decorator like @QueryParam() that pulls together req.query and req.params. It could look something like this:

export const QueryParam = createParamDecorator((data: unknown, context: ExecutionContext) => {
  const req = context.switchToHttp().getRequest();
  return { ...req.query, ...req.params };
});

And just make sure to add validateCustomDecorators on the ValidationPipe if you want it to auto validate for you. Otherwise, you're good to start using it.


答:
Would something like this work:</p>

```<code>def may_exist(func, *func_args):
    try:
        func(*func_args)
    except OSError as e:
        pass
</code>```

Title: Frequently repeated try/except in Python

Body:
Would something like this work:

def may_exist(func, *func_args):
    try:
        func(*func_args)
    except OSError as e:
        pass


问:
create a function using data masking in R
inorder to do a paired analysis i need to write a function that sums integer counts. The total number required to be summed is specified in the corresponding "Yrs_Before" and "Yrs_After" columns in "df".  Is there a way i can avoid writing "fm_after" with just one function? Is this a variable masking for "Yrs_Before", "Yrs_After","Before.Yr_1...n+1" and "After.Yr_1...n+1" columns?

data frame

```<code>set.seed(123)
(df=data.frame(
  Yrs_Before=sample(1:8, 3),
  Yrs_After=sample(1:8, 3),
  Before.Yr_1=sample(1:8, 3),
  Before.Yr_2=sample(1:8, 3),
  Before.Yr_3=sample(1:8, 3),
  Before.Yr_4=sample(1:8, 3),
  Before.Yr_5=sample(1:8, 3),
  Before.Yr_6=sample(1:8, 3),
  Before.Yr_7=sample(1:8, 3),
  Before.Yr_8=sample(1:8, 3),
  After.Yr_1=sample(1:8, 3),
  After.Yr_2=sample(1:8, 3),
  After.Yr_3=sample(1:8, 3),
  After.Yr_4=sample(1:8, 3),
  After.Yr_5=sample(1:8, 3),
  After.Yr_6=sample(1:8, 3),
  After.Yr_7=sample(1:8, 3),
  After.Yr_8=sample(1:8, 3)

))
</code>```

function sums the corresponding rows based on the number of years in the before period.

```<code>fm=function(data,Yrs_Before){
  data |> dplyr::mutate(sums=
  ifelse(
  Yrs_Before == 1, rowSums(across(Before.Yr_1)),
  ifelse(
    Yrs_Before == 2, rowSums(across(Before.Yr_1:Before.Yr_2)),
    ifelse(
      Yrs_Before == 3, rowSums(across(Before.Yr_1:Before.Yr_3)),
      ifelse(
        Yrs_Before == 4, rowSums(across(Before.Yr_1:Before.Yr_4)),
        ifelse(
          Yrs_Before == 5, rowSums(across(Before.Yr_1:Before.Yr_5)),
          ifelse(
            Yrs_Before == 6, rowSums(across(Before.Yr_1:Before.Yr_6)),
            ifelse(
              Yrs_Before == 7, rowSums(across(Before.Yr_1:Before.Yr_7)),
              ifelse(
                Yrs_Before == 8, rowSums(across(Before.Yr_1:Before.Yr_8)),"")))))))))
}

</code>```

output

```<code>
fm(df,Yrs_Before)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   23
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   33
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7   11

</code>```

duplicated function with variable name changed to "After"

```<code>
fm_after=function(data,Yrs_After){
  data |> dplyr::mutate(sums=
                   ifelse(
                     Yrs_After == 1, rowSums(across(After.Yr_1)),
                     ifelse(
                       Yrs_After == 2, rowSums(across(After.Yr_1:After.Yr_2)),
                       ifelse(
                         Yrs_After == 3, rowSums(across(After.Yr_1:After.Yr_3)),
                         ifelse(
                           Yrs_After == 4, rowSums(across(After.Yr_1:After.Yr_4)),
                           ifelse(
                             Yrs_After == 5, rowSums(across(After.Yr_1:After.Yr_5)),
                             ifelse(
                               Yrs_After == 6, rowSums(across(After.Yr_1:After.Yr_6)),
                               ifelse(
                                 Yrs_After == 7, rowSums(across(After.Yr_1:After.Yr_7)),
                                 ifelse(
                                   Yrs_After == 8, rowSums(across(After.Yr_1:After.Yr_8)),"")))))))))
}

</code>```

output

```<code>fm_after(df,Yrs_After)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   21
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   20
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7    6

</code>```

UPDATE:

As recommended,  the following tidyverse function was used for counting Before.Yr and After.Yr crash counts.

```<code>sums=function(data,crashes,yrs){
data %>%
  dplyr::rowwise() %>%
    dplyr::transmute(sum = cumsum(c_across(matches(.data[[crashes]])))[.data[[yrs]]])
}
</code>```

however an  error was returned.

```<code>> sums(df,"Before.Yr","Yrs_Before")
Error: Problem with `mutate()` column `sum`.
ℹ `sum = cumsum(c_across(matches(.data[["Before.Yr"]])))[.data[["Yrs_Before"]]]`.
x Column `Before.Yr` not found in `.data`
ℹ The error occurred in row 1.
Run `rlang::last_error()` to see where the error occurred.
</code>```

suggestions for fixing the error?

答:
We may do this by pivoting to long format

```<code>library(dplyr)
library(tidyr)
library(stringr)
df %>%
  mutate(rn = row_number()) %>%
  pivot_longer(cols = -c(rn, Yrs_Before, Yrs_After)) %>%
   mutate(yrs = as.numeric(str_extract(name, "\\d+$"))) %>%
  group_by(rn, grp = str_extract(name, "\\w+")) %>%
  summarise(Sum = if(cur_group()$grp == 'Before')
   sum(value[yrs <= Yrs_Before], na.rm = TRUE)  else
   sum(value[yrs <= Yrs_After], na.rm = TRUE), .groups = 'drop') %>%
  pivot_wider(names_from = grp, values_from = Sum) %>%
  select(-rn) %>%
  bind_cols(df, .)
</code>```

-output

```<code> Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1
1          7         6           2           5           6           3           3           1           3           1          4
2          8         3           6           4           1           5           1           8           2           6          6
3          3         2           3           6           2           8           4           5           7           3          1
  After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 After Before
1          3          4          5          1          4          3          2    21     23
2          7          7          7          2          5          6          5    20     33
3          5          2          1          3          7          1          7     6     11
</code>```

It can be wrapped in a function with just input data

```<code>fm <- function(data) {
  data %>%
  mutate(rn = row_number()) %>%
  pivot_longer(cols = -c(rn, Yrs_Before, Yrs_After)) %>%
   mutate(yrs = as.numeric(str_extract(name, "\\d+$"))) %>%
  group_by(rn, grp = str_extract(name, "\\w+")) %>%
  summarise(Sum = if(cur_group()$grp == 'Before')
   sum(value[yrs <= Yrs_Before], na.rm = TRUE)  else
   sum(value[yrs <= Yrs_After], na.rm = TRUE), .groups = 'drop') %>%
  pivot_wider(names_from = grp, values_from = Sum) %>%
  select(-rn) %>%
  bind_cols(df, .)
  }
</code>```

-testing

```<code>> fm(df)
  Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1
1          7         6           2           5           6           3           3           1           3           1          4
2          8         3           6           4           1           5           1           8           2           6          6
3          3         2           3           6           2           8           4           5           7           3          1
  After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 After Before
1          3          4          5          1          4          3          2    21     23
2          7          7          7          2          5          6          5    20     33
3          5          2          1          3          7          1          7     6     11
</code>```

Body:
inorder to do a paired analysis i need to write a function that sums integer counts. The total number required to be summed is specified in the corresponding "Yrs_Before" and "Yrs_After" columns in "df".  Is there a way i can avoid writing "fm_after" with just one function? Is this a variable masking for "Yrs_Before", "Yrs_After","Before.Yr_1...n+1" and "After.Yr_1...n+1" columns?

data frame

set.seed(123)
(df=data.frame(
  Yrs_Before=sample(1:8, 3),
  Yrs_After=sample(1:8, 3),
  Before.Yr_1=sample(1:8, 3),
  Before.Yr_2=sample(1:8, 3),
  Before.Yr_3=sample(1:8, 3),
  Before.Yr_4=sample(1:8, 3),
  Before.Yr_5=sample(1:8, 3),
  Before.Yr_6=sample(1:8, 3),
  Before.Yr_7=sample(1:8, 3),
  Before.Yr_8=sample(1:8, 3),
  After.Yr_1=sample(1:8, 3),
  After.Yr_2=sample(1:8, 3),
  After.Yr_3=sample(1:8, 3),
  After.Yr_4=sample(1:8, 3),
  After.Yr_5=sample(1:8, 3),
  After.Yr_6=sample(1:8, 3),
  After.Yr_7=sample(1:8, 3),
  After.Yr_8=sample(1:8, 3)

))

function sums the corresponding rows based on the number of years in the before period.

fm=function(data,Yrs_Before){
  data |> dplyr::mutate(sums=
  ifelse(
  Yrs_Before == 1, rowSums(across(Before.Yr_1)),
  ifelse(
    Yrs_Before == 2, rowSums(across(Before.Yr_1:Before.Yr_2)),
    ifelse(
      Yrs_Before == 3, rowSums(across(Before.Yr_1:Before.Yr_3)),
      ifelse(
        Yrs_Before == 4, rowSums(across(Before.Yr_1:Before.Yr_4)),
        ifelse(
          Yrs_Before == 5, rowSums(across(Before.Yr_1:Before.Yr_5)),
          ifelse(
            Yrs_Before == 6, rowSums(across(Before.Yr_1:Before.Yr_6)),
            ifelse(
              Yrs_Before == 7, rowSums(across(Before.Yr_1:Before.Yr_7)),
              ifelse(
                Yrs_Before == 8, rowSums(across(Before.Yr_1:Before.Yr_8)),"")))))))))
}

output

fm(df,Yrs_Before)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   23
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   33
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7   11

duplicated function with variable name changed to "After"

fm_after=function(data,Yrs_After){
  data |> dplyr::mutate(sums=
                   ifelse(
                     Yrs_After == 1, rowSums(across(After.Yr_1)),
                     ifelse(
                       Yrs_After == 2, rowSums(across(After.Yr_1:After.Yr_2)),
                       ifelse(
                         Yrs_After == 3, rowSums(across(After.Yr_1:After.Yr_3)),
                         ifelse(
                           Yrs_After == 4, rowSums(across(After.Yr_1:After.Yr_4)),
                           ifelse(
                             Yrs_After == 5, rowSums(across(After.Yr_1:After.Yr_5)),
                             ifelse(
                               Yrs_After == 6, rowSums(across(After.Yr_1:After.Yr_6)),
                               ifelse(
                                 Yrs_After == 7, rowSums(across(After.Yr_1:After.Yr_7)),
                                 ifelse(
                                   Yrs_After == 8, rowSums(across(After.Yr_1:After.Yr_8)),"")))))))))
}

output

fm_after(df,Yrs_After)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   21
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   20
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7    6

UPDATE:

As recommended,  the following tidyverse function was used for counting Before.Yr and After.Yr crash counts.

sums=function(data,crashes,yrs){
data %>%
  dplyr::rowwise() %>%
    dplyr::transmute(sum = cumsum(c_across(matches(.data[[crashes]])))[.data[[yrs]]])
}

however an  error was returned.

> sums(df,"Before.Yr","Yrs_Before")
Error: Problem with `mutate()` column `sum`.
ℹ `sum = cumsum(c_across(matches(.data[["Before.Yr"]])))[.data[["Yrs_Before"]]]`.
x Column `Before.Yr` not found in `.data`
ℹ The error occurred in row 1.
Run `rlang::last_error()` to see where the error occurred.

suggestions for fixing the error?

Body:
We may do this by pivoting to long format

library(dplyr)
library(tidyr)
library(stringr)
df %>%
  mutate(rn = row_number()) %>%
  pivot_longer(cols = -c(rn, Yrs_Before, Yrs_After)) %>%
   mutate(yrs = as.numeric(str_extract(name, "\\d+$"))) %>%
  group_by(rn, grp = str_extract(name, "\\w+")) %>%
  summarise(Sum = if(cur_group()$grp == 'Before')
   sum(value[yrs <= Yrs_Before], na.rm = TRUE)  else
   sum(value[yrs <= Yrs_After], na.rm = TRUE), .groups = 'drop') %>%
  pivot_wider(names_from = grp, values_from = Sum) %>%
  select(-rn) %>%
  bind_cols(df, .)

-output

 Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1
1          7         6           2           5           6           3           3           1           3           1          4
2          8         3           6           4           1           5           1           8           2           6          6
3          3         2           3           6           2           8           4           5           7           3          1
  After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 After Before
1          3          4          5          1          4          3          2    21     23
2          7          7          7          2          5          6          5    20     33
3          5          2          1          3          7          1          7     6     11

It can be wrapped in a function with just input data

fm <- function(data) {
  data %>%
  mutate(rn = row_number()) %>%
  pivot_longer(cols = -c(rn, Yrs_Before, Yrs_After)) %>%
   mutate(yrs = as.numeric(str_extract(name, "\\d+$"))) %>%
  group_by(rn, grp = str_extract(name, "\\w+")) %>%
  summarise(Sum = if(cur_group()$grp == 'Before')
   sum(value[yrs <= Yrs_Before], na.rm = TRUE)  else
   sum(value[yrs <= Yrs_After], na.rm = TRUE), .groups = 'drop') %>%
  pivot_wider(names_from = grp, values_from = Sum) %>%
  select(-rn) %>%
  bind_cols(df, .)
  }

-testing

> fm(df)
  Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1
1          7         6           2           5           6           3           3           1           3           1          4
2          8         3           6           4           1           5           1           8           2           6          6
3          3         2           3           6           2           8           4           5           7           3          1
  After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 After Before
1          3          4          5          1          4          3          2    21     23
2          7          7          7          2          5          6          5    20     33
3          5          2          1          3          7          1          7     6     11