问:
How to find all the parent nodes of each node in a directed acyclic graph?
For the directed acyclic graph given by the following python code I want to find out all the parent node of each node of the DAG. Please help! For example, node 6,7 and 8 are the parent nodes of node 9. I have to make a function where I have to access all the parent node of each node and act according to my problem. Note: The code was taken from geeksforgeeks</p>
```<code>class Graph:
    # Constructor to construct a graph
    def __init__(self, edges, n):

        # A list of lists to represent an adjacency list
        self.adjList = [None] * n

        # allocate memory for the adjacency list
        for i in range(n):
            self.adjList[i] = []

        # add edges to the directed graph
        for (src, dest, weight) in edges:
            # allocate node in adjacency list from src to dest
            self.adjList[src].append((dest, weight))

# Function to print adjacency list representation of a graph
def printGraph(graph):
    for src in range(len(graph.adjList)):
        # print current vertex and all its neighboring vertices
        for (dest, weight) in graph.adjList[src]:
            new_graph[src].append(dest)
            print(f'({src} —> {dest}, {weight}) ', end='')
        print()

# Input: Edges in a weighted digraph (as per the above diagram)
# Edge (x, y, w) represents an edge from `x` to `y` having weight `w`
edges = [(0, 1, 18), (0, 2, 12), (0, 3, 9), (0, 4, 11), (0, 5, 14),
          (1, 7, 19), (1, 8, 16), (2, 6, 23), (3, 7, 27), (3, 8, 23),
        (4, 8, 13), (5, 7, 15), (6, 9, 17), (7, 9, 11), (8, 9, 13)]

# No. of vertices (labelled from 1 to 10)
n = 10

# construct a graph from a given list of edges
graph = Graph(edges, n)
new_graph = [[] for i in range(n)]
# print adjacency list representation of the graph
printGraph(graph)
</code>```

答:
You can use a similar structure as the printGraph function which iterates over all edges. We then can check for each edge if it leads to our child node. If so, we found a parent node. These parent nodes are stored and returned. Here is an example implementation of the function:

```<code># Function to find all parents of a node
def getParent(graph, node):
    # collect parents as a set in order to avoid duplicate entries
    parents = set()
    for src in range(len(graph.adjList)):
        # Iterate over all edges from src node
        for (dest, weight) in graph.adjList[src]:
            # if destiontion is our needed child add source as parent
            if dest == node:
                parents.add(src)

    # Return all parents as a list
    return list(parents)
</code>```

Call it like this to find the parents of node 9:

```<code># Input: Edges in a weighted digraph (as per the above diagram)
# Edge (x, y, w) represents an edge from `x` to `y` having weight `w`
edges = [(0, 1, 18), (0, 2, 12), (0, 3, 9), (0, 4, 11), (0, 5, 14),
          (1, 7, 19), (1, 8, 16), (2, 6, 23), (3, 7, 27), (3, 8, 23),
        (4, 8, 13), (5, 7, 15), (6, 9, 17), (7, 9, 11), (8, 9, 13)]

# No. of vertices (labelled from 1 to 10)
n = 10

# construct a graph from a given list of edges
graph = Graph(edges, n)
print(getParent(graph, 9))
</code>```

Output are the parents of node 9 as a list:

```<code>[8, 6, 7]
</code>```

Body:
For the directed acyclic graph given by the following python code I want to find out all the parent node of each node of the DAG. Please help! For example, node 6,7 and 8 are the parent nodes of node 9. I have to make a function where I have to access all the parent node of each node and act according to my problem. Note: The code was taken from geeksforgeeks

class Graph:
    # Constructor to construct a graph
    def __init__(self, edges, n):

        # A list of lists to represent an adjacency list
        self.adjList = [None] * n

        # allocate memory for the adjacency list
        for i in range(n):
            self.adjList[i] = []

        # add edges to the directed graph
        for (src, dest, weight) in edges:
            # allocate node in adjacency list from src to dest
            self.adjList[src].append((dest, weight))

# Function to print adjacency list representation of a graph
def printGraph(graph):
    for src in range(len(graph.adjList)):
        # print current vertex and all its neighboring vertices
        for (dest, weight) in graph.adjList[src]:
            new_graph[src].append(dest)
            print(f'({src} —> {dest}, {weight}) ', end='')
        print()

# Input: Edges in a weighted digraph (as per the above diagram)
# Edge (x, y, w) represents an edge from `x` to `y` having weight `w`
edges = [(0, 1, 18), (0, 2, 12), (0, 3, 9), (0, 4, 11), (0, 5, 14),
          (1, 7, 19), (1, 8, 16), (2, 6, 23), (3, 7, 27), (3, 8, 23),
        (4, 8, 13), (5, 7, 15), (6, 9, 17), (7, 9, 11), (8, 9, 13)]

# No. of vertices (labelled from 1 to 10)
n = 10

# construct a graph from a given list of edges
graph = Graph(edges, n)
new_graph = [[] for i in range(n)]
# print adjacency list representation of the graph
printGraph(graph)

Body:
You can use a similar structure as the printGraph function which iterates over all edges. We then can check for each edge if it leads to our child node. If so, we found a parent node. These parent nodes are stored and returned. Here is an example implementation of the function:

# Function to find all parents of a node
def getParent(graph, node):
    # collect parents as a set in order to avoid duplicate entries
    parents = set()
    for src in range(len(graph.adjList)):
        # Iterate over all edges from src node
        for (dest, weight) in graph.adjList[src]:
            # if destiontion is our needed child add source as parent
            if dest == node:
                parents.add(src)

    # Return all parents as a list
    return list(parents)

Call it like this to find the parents of node 9:

# Input: Edges in a weighted digraph (as per the above diagram)
# Edge (x, y, w) represents an edge from `x` to `y` having weight `w`
edges = [(0, 1, 18), (0, 2, 12), (0, 3, 9), (0, 4, 11), (0, 5, 14),
          (1, 7, 19), (1, 8, 16), (2, 6, 23), (3, 7, 27), (3, 8, 23),
        (4, 8, 13), (5, 7, 15), (6, 9, 17), (7, 9, 11), (8, 9, 13)]

# No. of vertices (labelled from 1 to 10)
n = 10

# construct a graph from a given list of edges
graph = Graph(edges, n)
print(getParent(graph, 9))

Output are the parents of node 9 as a list:

[8, 6, 7]


来源: stackexchange

问:
Execute multiple independent jobs continuously
I have a set of jobs which are independent of each other. Hence each of these jobs can be run concurrently using goroutines. Note that once a single job completes, it should wait for few seconds and start again (applies to all the jobs) and this goes on in a loop until the Go API service stops. Also note that all these jobs execute the same goroutine (makes a REST call). What would be the best pattern to implement this in Go. Please note that I would also want to wait for currently executing jobs to complete before my service shuts down.</p>

答:
You want to implement worker pools. Here is the simple way to create pools of worker. You can customize worker method and jobs type according to your requirement.</p>
```<code>package main

import (
    "fmt"
    "sync"
)

type Jobs struct {
    ID string
    // or anything you want to add
}

func main() {

    jobs := make(Jobs)

    var wg sync.WaitGroup
    numWorker := 16
    for i := 0; i < numWorker; i++ {
        wg.Add(1)
        go func() {
            worker(jobs)
            wg.Done()
        }()
    }

    tasks := []Jobs{}
    // inset your task here
    for _, i := range tasks {
        jobs <- i
    }
    close(jobs)
    wg.Wait()
}

func worker(jobs chan Jobs) {

    for job := range jobs {

        // do whatever you want to do
        doSomething(job)

    }
}

func doSomething(job Jobs) {
    fmt.Println(job)
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
You want to implement worker pools. Here is the simple way to create pools of worker. You can customize worker method and jobs type according to your requirement.

package main

import (
    "fmt"
    "sync"
)

type Jobs struct {
    ID string
    // or anything you want to add
}

func main() {

    jobs := make(Jobs)

    var wg sync.WaitGroup
    numWorker := 16
    for i := 0; i < numWorker; i++ {
        wg.Add(1)
        go func() {
            worker(jobs)
            wg.Done()
        }()
    }

    tasks := []Jobs{}
    // inset your task here
    for _, i := range tasks {
        jobs <- i
    }
    close(jobs)
    wg.Wait()
}

func worker(jobs chan Jobs) {

    for job := range jobs {

        // do whatever you want to do
        doSomething(job)

    }
}

func doSomething(job Jobs) {
    fmt.Println(job)
}


问:
How memory allocation of variables or data in a program are done by compiler and OS
Want to get an overview on a few things about how exactly the memory for a variable is allocated.

In C programming,
Taking the context of "auto" variables, which are allocated on the stack section, I have the following question:

Does the compiler generate a logical address for the variables? If yes, then how? Won't the compiler need OS permission to generate or assign such addresses? If no, then is there some sort of indication or instruction that the compiler puts in the code segment asking the OS to allocate memory when running the executable?

Now taking the context of heap allocated variables,

Is the heap of the same size for all programs? If not, then does the executable consist of a header or something that tells the OS how much heap space it needs for dynamic allocation?

I'd be grateful if someone provides the answer or shares any related content/links that explains this.

答:
A method typically used in operating systems is that, when a program is starting, there is a piece (or collection) of software used that loads the program. The program loader reads the executable file and sets up memory for the program.

Part of the executable file says what size stack should be allocated for it. Most often, this is set by default when linking the program. (It is 8 MiB for macOS, 2 MiB for Linux, and 1 MiB for Windows.) However, it can be changed by asking the linker to set a different size.

The program loader calls operating system routines to request virtual memory be mapped. It does this for the stack and for other parts of the program, such as the code sections (the parts of memory that contain, mostly, the executable instructions of the program), and the initialized and uninitialized data. When it starts the program, it tells the program where the stack starts by putting that address into a designated register (or similar means).

One of the processor registers is used as a stack pointer; it points to address within the memory allocated for the stack that is the current top of stack. When the compiler arranges to use stack space for objects, it generates instructions that adjust the stack pointer. The addresses for the objects are calculated relative to the stack pointer. If a function needs 128 bytes of data, the compiler generates an instruction that subtracts 128 from the stack pointer. (This may occur in multiple steps, such as “call” and “push” instructions that make some changes to the stack pointer plus an additional “subtract” instruction that finishes the changes.) Then the addresses of all the objects in this stack frame are calculated as offsets from the value of the stack pointer. For example, by taking the stack pointer and adding 40, we calculate the address of the object that has been assigned to be 40 bytes higher than the top of the stack.

(There is some confusion about the wording of directions here because stacks commonly grow from high addresses to low addresses. The program loader may allocate some chunk of memory from, say, address 12300000016 to 12400000016. The stack pointer will start at 12400000016. Subtracting 128 will make it 123FFFF8016. Then 123FFFFA816 is an address that is 40 bytes “higher” than 123FFFF8016 in the address space, but the “top of stack” is below that. That is because the term “top of stack” refers to the model of physically stacking things on top of each other, with the latest thing on top.)

The so-called “heap” is not the same size of all programs. In typical implementations, the memory management routines call system routines to request more virtual memory when they need it.

Note that “heap” is properly a word for a general data structure. Heaps may be used to organize things other than available memory, and the memory management routine keep track of available memory using data structures other than heaps. When referring to memory allocated via the memory management routines, you can call it “dynamically allocated memory.” It may also be shortened to “allocated memory,” but that can be confusing in some situations since all memory that has been reserved for some use is allocated memory.


问:
HotChocolate (GraphQL) it is impossible include nested object without query calling
```<code>// Parent entity
public class Parent
{
   public int Id {get; set;}
   public int CurrencyId {get; set;}
   public virtual Currency Currency {get; set;}
}
// Currency Entity
public class Currency
{
  public int Id {get; set;}
  public string Name {get; set;}
  public virtual ICollection<Parent> Parents {get; set;}
}

// Query
[UseDbContext(typeof(AppDbContext))]
[UseFirstOrDefault]
[UseProjection]
[UseFiltering]
[UseSorting]
public IQueryable<Parent> GetParents([ScopedService] AppDbContext context, int id)
{
  return context.Set<Parent>().Where(x => x.id == id);
}

public class ParentType : ObjectType<Parent>
{
   protected override void Configure(IObjectTypeDescriptor<Parent> descriptor)
    {
        descriptor.Field("currencyName")
            .ResolveWith<Resolvers>(t => t.GetCurrencyName(default!));
    }

    private class Resolvers
    {
        public string GetCurrencyName([Parent] Parent parent)
        {
            return parent?.Currency?.Name;
        }
    }
}
</code>```

And when I call it's with graphql query with currency object.

```<code>    query{
     parents(id: 1){
      id
      currencyName
      currency{
       name
      }
     }
    }

//Result
{
  "data": {
    "parents": {
      "id": 1,
      "currency": {
        "name": "USD"
      },
      "currencyName": "USD"
    }
  }
}
</code>```

Result currencyName is not null. And when I call it's without currency object.

```<code>       query{
         parents(id: 1){
          id
          currencyName
         }
        }
// Result
{
  "data": {
    "parents": {
      "Id": 1,
      "currencyName": null
    }
  }
}
</code>```

And result currencyName is null. It is impossible include nested object like currency from code ?
I want get currency Name without calling currency object in graphql query.

答: No this is currently not possible as the property you access is only resolved if the nested class is selected</p>

Body:
// Parent entity
public class Parent
{
   public int Id {get; set;}
   public int CurrencyId {get; set;}
   public virtual Currency Currency {get; set;}
}
// Currency Entity
public class Currency
{
  public int Id {get; set;}
  public string Name {get; set;}
  public virtual ICollection<Parent> Parents {get; set;}
}

// Query
[UseDbContext(typeof(AppDbContext))]
[UseFirstOrDefault]
[UseProjection]
[UseFiltering]
[UseSorting]
public IQueryable<Parent> GetParents([ScopedService] AppDbContext context, int id)
{
  return context.Set<Parent>().Where(x => x.id == id);
}

public class ParentType : ObjectType<Parent>
{
   protected override void Configure(IObjectTypeDescriptor<Parent> descriptor)
    {
        descriptor.Field("currencyName")
            .ResolveWith<Resolvers>(t => t.GetCurrencyName(default!));
    }

    private class Resolvers
    {
        public string GetCurrencyName([Parent] Parent parent)
        {
            return parent?.Currency?.Name;
        }
    }
}

And when I call it's with graphql query with currency object.

    query{
     parents(id: 1){
      id
      currencyName
      currency{
       name
      }
     }
    }

//Result
{
  "data": {
    "parents": {
      "id": 1,
      "currency": {
        "name": "USD"
      },
      "currencyName": "USD"
    }
  }
}

Result currencyName is not null. And when I call it's without currency object.

       query{
         parents(id: 1){
          id
          currencyName
         }
        }
// Result
{
  "data": {
    "parents": {
      "Id": 1,
      "currencyName": null
    }
  }
}

And result currencyName is null. It is impossible include nested object like currency from code ?
I want get currency Name without calling currency object in graphql query.


问:
API call inside a JavaScript function present in a feature file
I tried my best but could not find information on calling an API inside the Javascript function when dealing with automation in Karate. Now, I might get suggestions to call the API outside the function and then do operations inside the function. However, my use case is such that I have to call the API inside the function only. Is there a way to do this?
One approach is to create a Java file and then write the code in java. However, I specifically want to know if there is any way to call an API inside a JS function in a FEATURE FILE itself.</p>

答:
First, these kinds of "clever" tests are not recommended, please read this to understand why: https://stackoverflow.com/a/54126724/143475

If you still want to do this, read on.

First - most of the time, this kind of need can be achieved by doing a call to a second feature file:

```<code>* if (condition) karate.call('first.feature')
</code>```

Finally, this is an experimental and un-documented feature in Karate, but there is a JS API to perform HTTP requests:

```<code>* eval
"""
var http = karate.http('https://httpbin.org');
http.path('anything');
var response = http.get().body;
karate.log('response:', response);
"""
</code>```

It is a "fluent API" so you can do everything in one-line:

```<code>var body = karate.http('https://httpbin.org/get').get().body;
</code>```

If you need details, read the source-code of the HttpRequestBuilder and Response classes in the Karate project.

Body:
First, these kinds of "clever" tests are not recommended, please read this to understand why: https://stackoverflow.com/a/54126724/143475

If you still want to do this, read on.

First - most of the time, this kind of need can be achieved by doing a call to a second feature file:

* if (condition) karate.call('first.feature')

Finally, this is an experimental and un-documented feature in Karate, but there is a JS API to perform HTTP requests:

* eval
"""
var http = karate.http('https://httpbin.org');
http.path('anything');
var response = http.get().body;
karate.log('response:', response);
"""

It is a "fluent API" so you can do everything in one-line:

var body = karate.http('https://httpbin.org/get').get().body;

If you need details, read the source-code of the HttpRequestBuilder and Response classes in the Karate project.


问:
How do I check whether a SQLite database file exists using Java?
I get the name of database file from a user, and I want to check if that file already exists. If it does exist, I want to show an error message to user, but I don't know how to check if the file exists. </p>

```<code>public static void databaseConnect(String dbName) throws Exception
{
  if (/*same name exists*/) // How do I check this?
  {
    System.out.print("This database name already exists");
  }
  else
  {
    Class.forName("SQLite.JDBCDriver").newInstance();
    conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
    stat = conn.createStatement();
  }
}
</code>```

答:
Something like this?</p>

```<code>public boolean databaseExist()
{
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I get the name of database file from a user, and I want to check if that file already exists. If it does exist, I want to show an error message to user, but I don't know how to check if the file exists.

public static void databaseConnect(String dbName) throws Exception
{
  if (/*same name exists*/) // How do I check this?
  {
    System.out.print("This database name already exists");
  }
  else
  {
    Class.forName("SQLite.JDBCDriver").newInstance();
    conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
    stat = conn.createStatement();
  }
}

Body:
Something like this?

public boolean databaseExist()
{
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}


问:
How to write a removeError rest destructure function in typescript
I want to write a function which can remove a key with a certain name from an object (use case is in react where i want to set new error state when a field is focussed

This is how i write it in javascript

```<code>removeError = (fieldName) => {
    const { error } = this.state;
    if (error) {
      const { [fieldName]: ommited, ...rest } = error;
      this.setState({ error: rest });
    }
  };
</code>```

If i write it in typescript - how to write this line:

```<code>const { [fieldName]: ommited, ...rest } = error;
</code>```

答:
For you to do this, the type of the error object in state will have to have all of its properties be optional, like this:

interface ExampleState {
    error?: {       // <== This doesn't have to be optional, but from your code it is
        a?: string; // ***
        b?: string; // *** These have to be optional
        c?: string; // ***
    }
}
```
<p>(You could also use <code>Record<string, string></code> or similar for <code>Error</code>, but it wouldn't be as typesafe.)</p>
<p>Then the definition uses <code>keyof ExampleState["error"]</code> to give the right type to <code>fieldName</code>, and the rest is pretty much as you had it (I fixed the spelling of "omitted"):</p>
<pre class="lang-typescript prettyprint-override"><code>removeError = (fieldName: keyof ExampleState["error"]) => {
    this.setState(({error}) => {
        if (error) {
            const { [fieldName]: omitted, ...rest } = error;
            return { error: rest };
        }
        return null;
    });
};
</code>```

Notice that since we're setting state based on existing state, it's best to use the callback form of setState

Playground link

Body:
I want to write a function which can remove a key with a certain name from an object (use case is in react where i want to set new error state when a field is focussed

This is how i write it in javascript

removeError = (fieldName) => {
    const { error } = this.state;
    if (error) {
      const { [fieldName]: ommited, ...rest } = error;
      this.setState({ error: rest });
    }
  };

If i write it in typescript - how to write this line:

const { [fieldName]: ommited, ...rest } = error;

Body:
For you to do this, the type of the error object in state will have to have all of its properties be optional, like this:

interface ExampleState {
    error?: {       // <== This doesn't have to be optional, but from your code it is
        a?: string; // ***
        b?: string; // *** These have to be optional
        c?: string; // ***
    }
}

(You could also use Record<string, string> or similar for Error, but it wouldn't be as typesafe.)

Then the definition uses keyof ExampleState["error"] to give the right type to fieldName, and the rest is pretty much as you had it (I fixed the spelling of "omitted"):

removeError = (fieldName: keyof ExampleState["error"]) => {
    this.setState(({error}) => {
        if (error) {
            const { [fieldName]: omitted, ...rest } = error;
            return { error: rest };
        }
        return null;
    });
};

Notice that since we're setting state based on existing state, it's best to use the callback form of setState

<a href="https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wG4BYAKCuADsYkpN0k4BRADxXABskBlGCgZwA3lTiS4jHFAD8ALjFSVAelVwAPAF5tcACoALYAGc4AEwhITtAOTxDKAG6sYEOACNWEMDGARaFB4AGk8AVywcPABPCDCoODQIc1ZgeFMJFSkURTgTGCg6AHNSOHU4ACoqzKzPXPzC2hKyjSqKg0NrVkcXODdPb19-QJ4arLR6guLS8raxgF8qRepKNB4UEzNObjA+aQ4GWnMzZHQYADoAYVxIWiR6TVF50O3eASEGAD4xMaIQCBcbCgsjgegAFJhgEgeOYAHLcJBKADWSFimHYXDegmESAA2vgZNB8ABdACUoO+4kotUkMGMJnOJiQMGxDDBYNEhKg83J2kpYxpcGA6LBXPJVMFgqStHyylxkOhcIRxKUuDSDHMoXO2qIsvmoOkwOgFGpktqRBg8Voyi5Sl18HmJrNkmWzrgFqtcFoYR4PCdNJ5-pdJuWQA" rel="nofollow noreferrer">Playground link


问:
How to increment a cell in AG Grid React tabel?
Pretty new with AG Grid library and stuck on updating the cells.

In reality, I need to do the task with dates, but just to keep it simple, I'll explain my problem with simple numbers.
I have

Start, which is 1.

Stop, which is already defined

End

Duration, which is already defined

My goal

Start = Duration + End

End = Start + Stop

Here is what I have so far

Desired result

Sandbox Link and code below

```<code>import React from "react";
import { AgGridReact } from "ag-grid-react";
import "./styles.css";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
  const start = 1;
  const [gridApi, setGridApi] = React.useState(null);
  const [gridColumnApi, setGridColumnApi] = React.useState(null);

  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
      //valueGetter: (params) => console.log(params)
    },
    {
      headerName: "start",
      field: "start",
      valueGetter: (params) => {
        if (params.node.rowIndex !== 0) {
          return params.getValue("end") + params.data.duration;
        } else {
          return start;
        }
      }
    },
    { headerName: "stop", field: "stop" },
    {
      headerName: "end",
      colId: "end",
      valueGetter: (params) => {
        return params.data.start + params.data.stop;
      }
    },
    {
      headerName: "duration",
      field: "duration",
      colId: "duration"
    }
  ];
  const rowData = React.useMemo(
    () => [
      {
        name: "John",
        stop: 10
      },
      {
        name: "David",
        stop: 15
      },
      {
        name: "Dan",
        stop: 20
      }
    ],
    []
  );

  const durationArray = [5, 8, 6];
  const rowDataWithStart = React.useMemo(() => {
    if (durationArray) {
      return (
        rowData &&
        rowData.map((row, i) => ({
          ...row,
          start: start,
          duration: durationArray[i]
        }))
      );
    }
  }, [start, rowData, durationArray]);

  const defaultColDef = {
    flex: 1,
    editable: true
  };
  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
  };

  return (
    <div className="App">
      <h1 align="center">React-App</h1>
      <div className="ag-theme-alpine">
        <AgGridReact
          columnDefs={columnDefs}
          rowData={rowDataWithStart}
          defaultColDef={defaultColDef}
          domLayout={"autoHeight"}
          onGridReady={onGridReady}
        ></AgGridReact>
      </div>
    </div>
  );
}

export default App;

</code>```

Any help will be appreciated

答:
you can use valueGetter for this. I have modified the valueGetter in you code

```<code>  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
      //valueGetter: (params) => console.log(params)
    },
    {
      field: "start",
      valueGetter: ({ data }) => {
        const end = data.stop + data.start
        return data.duration + end;
      }
    },
    { field: "stop" },
    {
      field: "end",
      valueGetter: ({ data }) => {
        return data.start + data.stop
      }
    },
    {
      headerName: "duration",
      field: "duration"
    }
  ];
</code>```

Body:
Pretty new with AG Grid library and stuck on updating the cells.

In reality, I need to do the task with dates, but just to keep it simple, I'll explain my problem with simple numbers.
I have

Start, which is 1.

Stop, which is already defined

End

Duration, which is already defined

My goal

Start = Duration + End

End = Start + Stop

Here is what I have so far

Desired result

Sandbox Link and code below

import React from "react";
import { AgGridReact } from "ag-grid-react";
import "./styles.css";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
  const start = 1;
  const [gridApi, setGridApi] = React.useState(null);
  const [gridColumnApi, setGridColumnApi] = React.useState(null);

  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
      //valueGetter: (params) => console.log(params)
    },
    {
      headerName: "start",
      field: "start",
      valueGetter: (params) => {
        if (params.node.rowIndex !== 0) {
          return params.getValue("end") + params.data.duration;
        } else {
          return start;
        }
      }
    },
    { headerName: "stop", field: "stop" },
    {
      headerName: "end",
      colId: "end",
      valueGetter: (params) => {
        return params.data.start + params.data.stop;
      }
    },
    {
      headerName: "duration",
      field: "duration",
      colId: "duration"
    }
  ];
  const rowData = React.useMemo(
    () => [
      {
        name: "John",
        stop: 10
      },
      {
        name: "David",
        stop: 15
      },
      {
        name: "Dan",
        stop: 20
      }
    ],
    []
  );

  const durationArray = [5, 8, 6];
  const rowDataWithStart = React.useMemo(() => {
    if (durationArray) {
      return (
        rowData &&
        rowData.map((row, i) => ({
          ...row,
          start: start,
          duration: durationArray[i]
        }))
      );
    }
  }, [start, rowData, durationArray]);

  const defaultColDef = {
    flex: 1,
    editable: true
  };
  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
  };

  return (

React-App

        <AgGridReact
          columnDefs={columnDefs}
          rowData={rowDataWithStart}
          defaultColDef={defaultColDef}
          domLayout={"autoHeight"}
          onGridReady={onGridReady}
        ></AgGridReact>

  );
}

export default App;

Any help will be appreciated

Body:
you can use valueGetter for this. I have modified the valueGetter in you code

  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
      //valueGetter: (params) => console.log(params)
    },
    {
      field: "start",
      valueGetter: ({ data }) => {
        const end = data.stop + data.start
        return data.duration + end;
      }
    },
    { field: "stop" },
    {
      field: "end",
      valueGetter: ({ data }) => {
        return data.start + data.stop
      }
    },
    {
      headerName: "duration",
      field: "duration"
    }
  ];


问:
Regex - Find all matching words that don't begin with a specific prefix
How would I construct a regular expression to find all words that end in a string but don't begin with a string?

e.g. Find all words that end in 'friend' that don't start with the word 'girl' in the following sentence:

"A boyfriend and girlfriend gained a friend when they asked to befriend them"

The items in bold should match. The word 'girlfriend' should not.

答:
In my case I needed to exclude some words that have a given prefix from regex matching result

the text was query-string params

```<code>?=&sysNew=false&sysStart=true&sysOffset=4&Question=1
</code>```

the prefix is sys and I dont the words that have sys in them

the key to solve the issue was with word boundary \b

```<code>\b(?!sys)\w+\b
</code>```

then I added that part in the bigger regex for query-string

```<code>(\b(?!sys)\w+\b)=(\w+)
</code>```

Body:
In my case I needed to exclude some words that have a given prefix from regex matching result

the text was query-string params

?=&sysNew=false&sysStart=true&sysOffset=4&Question=1

the prefix is sys and I dont the words that have sys in them

the key to solve the issue was with word boundary \b

\b(?!sys)\w+\b

then I added that part in the bigger regex for query-string

(\b(?!sys)\w+\b)=(\w+)


问:
Using 3rd party Apps in Django, some questions
I am new to Django.

I have some doubts about installing 3rd party Apps in Django.

A specific example. The "django-registration" App in https://bitbucket.org/ubernostrum/django-registration/src. Reading the instructions the doc tell us to install this app with PIP(pip install django-registration), doing this the App will be installed in Python Site-packages, right?

My question is: The App must to be installed in that way? Why not put the 'django-registration' folder in our Project as an App?

PS: This is a starter Django Question.

Best Regards,

答:
The App must to be installed in that way?

No.

As long as python can find it (ie: it's on the PYTHONPATH) you can put it any place you like.

Why not put the 'django-registration' folder in our Project as an App?

Why not indeed?  If you plan on modifying it substantially that's perhaps quite reasonable.  If you aren't, then keeping it separate will keep it plain as to what is your code and what is not; and ease the updates to either.


问:
How to get maximum value from the Collection (for example ArrayList)?
There is an ArrayList which stores integer values. I need to find the maximum value in this list. E.g. suppose the arrayList stored values are : 10, 20, 30, 40, 50 and the max
 value would be 50.

What is the efficient way to find the maximum value?

@Edit : I just found one solution for which I am not very sure

```<code>ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(100); /* add(200), add(250) add(350) add(150) add(450)*/

Integer i = Collections.max(arrayList)
</code>```

and this returns the highest value.

Another way to compare the each value e.g. selection sort or binary sort algorithm

答:
They're many ways to find the maximum. But there will be no noticeable difference in performance unless the collection is huge.

```<code>List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

System.out.println(
        integers.stream().max(Integer::compare).get()
);
System.out.println(
        integers.stream().mapToInt(Integer::intValue).max().getAsInt()
);
System.out.println(
        integers.stream().max(Comparator.comparing(i -> i)).get()
);
System.out.println(
        integers.stream().reduce((a, b) -> a > b ? a : b).get()
);
System.out.println(
        integers.stream().reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b)
);
</code>```

The max method expects a Comparator as a parameter.

The reduce method expects a BinaryOperator as a parameter.

Body:
There is an ArrayList which stores integer values. I need to find the maximum value in this list. E.g. suppose the arrayList stored values are : 10, 20, 30, 40, 50 and the max
 value would be 50.

What is the efficient way to find the maximum value?

@Edit : I just found one solution for which I am not very sure

ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(100); /* add(200), add(250) add(350) add(150) add(450)*/

Integer i = Collections.max(arrayList)

and this returns the highest value.

Another way to compare the each value e.g. selection sort or binary sort algorithm

Body:
They're many ways to find the maximum. But there will be no noticeable difference in performance unless the collection is huge.

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

System.out.println(
        integers.stream().max(Integer::compare).get()
);
System.out.println(
        integers.stream().mapToInt(Integer::intValue).max().getAsInt()
);
System.out.println(
        integers.stream().max(Comparator.comparing(i -> i)).get()
);
System.out.println(
        integers.stream().reduce((a, b) -> a > b ? a : b).get()
);
System.out.println(
        integers.stream().reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b)
);

The max method expects a Comparator as a parameter.

The reduce method expects a BinaryOperator as a parameter.


问:
Is there a way to get the Amazon State Language JSON representation of a State Machine created within AWS CDK
My CDK infrastructure (a typescript file) has a lambda that will create a new State Machine when it runs. To do so it needs the Amazon State Langauge JSON representation of the machine I want to create. I have created the State Machine within my AWS infrastructure typescript file, since many of the states reference lambdas or dynamoDB tables within this infrastructure.

My question is, given a CDK State Machine (Here is the CDK documentation for it, also here is the documentation for the Step Function's Chain class which basically represents the ASL JSON in CDK) can you generate the ASL JSON representation? In my case it is so I can pass this ASL JSON into one of my lambda's environments.

Based on the documentation it doesn't seem like this is possible which is weird to me since you can just look on the AWS Console, click on your state machine, then click the "definition" tab and see the ASL JSON. There must be some way to access this within the CDK infrastructure where the state machine is defined and created.

答:
Yes, you can pass the L2 StateMachine's generated JSON definition to a Lambda at synth-time.  The definition is exposed on its L1 CfnStateMachine child construct.  Use escape hatch syntax to get a reference to the CfnStateMachine.  Pass its stringified definition to the Lambda as an environment variable.

// MyStack.ts

const sm = new sfn.StateMachine(this, 'StateMachine', {definition: new sfn.Succeed(this, 'SuccessTask'),});
const cfnSm = sm.node.defaultChild as sfn.CfnStateMachine;  // cast to L1 type

if (!cfnSm.definitionString) throw new Error('CfnStateMachine definitionString must be defined');

new lambda.Function(this, 'MyFunction', {
  // ...
  environment: { SM_DEFINITION: cfnSm.definitionString,},
});
```

Notes:

Alternatively, Lambda can fetch the definition at run-time using the DescribeStateMachine API

The stringified JSON definition is available post-synth (for testing, etc.) in the synthesised stack template in the cdk.out dir.

Body:
Yes, you can pass the L2 StateMachine's generated JSON definition to a Lambda at synth-time.  The definition is exposed on its L1 CfnStateMachine child construct.  Use escape hatch syntax to get a reference to the CfnStateMachine.  Pass its stringified definition to the Lambda as an environment variable.

// MyStack.ts

const sm = new sfn.StateMachine(this, 'StateMachine', {definition: new sfn.Succeed(this, 'SuccessTask'),});
const cfnSm = sm.node.defaultChild as sfn.CfnStateMachine;  // cast to L1 type

if (!cfnSm.definitionString) throw new Error('CfnStateMachine definitionString must be defined');

new lambda.Function(this, 'MyFunction', {
  // ...
  environment: { SM_DEFINITION: cfnSm.definitionString,},
});

Notes:

Alternatively, Lambda can fetch the definition at run-time using the DescribeStateMachine API

The stringified JSON definition is available post-synth (for testing, etc.) in the synthesised stack template in the cdk.out dir.


问:
save and reuse computed data in widget build: flutter
The question is how to prevent calls that compute data in build.

Example (a simplistic one)

```<code>for (var map in something)
...
child: Row(
  children: [
    Text(getActualDate(map['days'])),
    Text(getActualDate(map['days']))
  ],
),
...
</code>```

Here the getActualDate function has been called and the result available. How can I save and reuse that result and not call getActualDate again?

答: By using state management, like provider</p>

Body:
The question is how to prevent calls that compute data in build.

Example (a simplistic one)

for (var map in something)
...
child: Row(
  children: [
    Text(getActualDate(map['days'])),
    Text(getActualDate(map['days']))
  ],
),
...

Here the getActualDate function has been called and the result available. How can I save and reuse that result and not call getActualDate again?


问:
PHP Session variable not being set, possibly because subdomain on different server?
I've got a newly set up dev server of a site I built. The dev server sits at a completely different Box and IP.

The dev site is a complete copy of the live site minus updates to paths and databases. The address is dev.mysite.com as opposed to just mysite.com.

The live site has a number of subdomains attached to it that change skins based on the subdomain, but nothing else is changed. When I try to log in to the dev site, it won't set the Session variable for the login. Any thoughts on this would be greatly appreciated.

答:
Before testing the live site you should test and ensure that the dev site works. In your question it sounds a bit the other way round. Anyway, I see two options here:

conflicting cookies

missing server configuration on the dev site

From your question it's hard to say which of those two applies (even not even something else). You should concentrate to get your dev site to work, ignoring your life site. That means, you access the dev site with a complete different browser from a complete different box (if possible) and from a complete different internet connection (if even possible). That should help you to isolate the problem and more easily find out what is going on. Then get sessions to work on the dev site. After it works, you can start to test your live site.


答:
Some background first

In C programming, Taking the context of "auto" variables, which are allocated on the stack section ...

To understand my answer, you first need to know how the stack works.

Imagine you write the following function:

```<code>int myFunction()
{
    return function1() + function2() + function3();
}
</code>```

Unfortunately, you do not use C as programming language but you use a programming language that neither supports local variables nor return values. (This is how most CPUs work internally.)

You may return a value from a function in a global variable:

```<code>function1()
{
    result = 1234; // instead of: return 1234;
}
</code>```

And your program may now look the following way if you use a global variable instead of local ones:

```<code>int a;

myFunction()
{
    function1();
    a = result;
    function2();
    a += result;
    function3();
    result += a;
}
</code>```

Unfortunately, one of the three functions (e.g. function3()) may call myFunction() (so the function is called recursively) and the variable a is overwritten when calling function3().

To solve this problem, you may define an array for local variables (myvars[]) and a variable named mypos. In the example, the elements 0...mypos in myvars[] are used; the elements (mypos+1)...(MAX_LOCALS-1) are free:

```<code>int myvars[MAX_LOCALS];
int mypos;
...
myFunction()
{
    function1();
    mypos++;
    myvars[mypos] = result;
    function2();
    myvars[mypos] += result;
    function3();
    result += myvars[mypos];
    mypos--;
}
</code>```

By changing the value of mypos from 10 to 11 (as an example), your program indicates that the element mypos[11] is now in use and that the functions being called shall store their data in elements mypos[x] with x>=12.

Exactly this is how the stack is working.

Typically, the "variable" mypos is not a variable but a CPU register named "stack pointer". (However, there are a few historic CPUs where an ordinary variable was used for this!)

The actual answers

Does the compiler generate a logical address for the variables?

In the example above, the compiler will perform a mypos+=3 if there are 3 local variables. Let's say they are named a, b and c.

The compiler simply replaces a by myvars[mypos-2], b by myvars[mypos-1] and c by myvars[mypos].

On most CPUs, the stack pointer (named mypos in the example) is not an index into an array but already a pointer (comparable to int * mypos;), so the compiler would replace a by *(mypos-2) instead of myvars[mypos-2] in the example.

For global variables, the compiler simply counts the number of bytes needed for all global variables. In the simplest case, it chooses a range of memory of the same size (e.g. 0x10000...0x10123) and places the variables there.

Won't the compiler need OS permission to generate or assign such addresses?

No.

The "stack" (in the example this is the array myvars[]) is already provided by the OS and the stack pointer (mypos in the example) is also set to a correct value by the OS before the program is started.

Your program knows that the elements myvars[x] with x>mypos can be used.

For global variables, the information about the range used by global variables (e.g. 0x10000...0x10123) is stored in the executable file. The OS must ensure that this memory range can be used by the program. (For example by configuring the MMU accordingly.)

If this is not possible, the OS will simply refuse to start the program with an error message.

... asking the OS to allocate memory when running the executable?

For variables on the stack:

There may be operating systems where this is done.

However, in most cases, the program will simply crash with a "stack overflow" if too much stack is needed. In the example, this would mean: The program crashes if an elements myvars[x] with x>=MAX_LOCALS is accessed.

Now taking the context of heap allocated variables ...

Please first note that global variables are not stored on the heap.

The heap is used for data allocated using malloc() and similar functions (new in C++ for example).

Under many operating systems, malloc() calls an operating system function - so it is actually the operating system that allocates memory on the heap.

... and if there is not enough space, the OS (and malloc()) will return NULL.

Title: How memory allocation of variables or data in a program are done by compiler and OS

Body:
Want to get an overview on a few things about how exactly the memory for a variable is allocated.

In C programming,
Taking the context of "auto" variables, which are allocated on the stack section, I have the following question:

Does the compiler generate a logical address for the variables? If yes, then how? Won't the compiler need OS permission to generate or assign such addresses? If no, then is there some sort of indication or instruction that the compiler puts in the code segment asking the OS to allocate memory when running the executable?

Now taking the context of heap allocated variables,

Is the heap of the same size for all programs? If not, then does the executable consist of a header or something that tells the OS how much heap space it needs for dynamic allocation?

I'd be grateful if someone provides the answer or shares any related content/links that explains this.

Body:
Some background first

In C programming, Taking the context of "auto" variables, which are allocated on the stack section ...

To understand my answer, you first need to know how the stack works.

Imagine you write the following function:

int myFunction()
{
    return function1() + function2() + function3();
}

Unfortunately, you do not use C as programming language but you use a programming language that neither supports local variables nor return values. (This is how most CPUs work internally.)

You may return a value from a function in a global variable:

function1()
{
    result = 1234; // instead of: return 1234;
}

And your program may now look the following way if you use a global variable instead of local ones:

int a;

myFunction()
{
    function1();
    a = result;
    function2();
    a += result;
    function3();
    result += a;
}

Unfortunately, one of the three functions (e.g. function3()) may call myFunction() (so the function is called recursively) and the variable a is overwritten when calling function3().

To solve this problem, you may define an array for local variables (myvars[]) and a variable named mypos. In the example, the elements 0...mypos in myvars[] are used; the elements (mypos+1)...(MAX_LOCALS-1) are free:

int myvars[MAX_LOCALS];
int mypos;
...
myFunction()
{
    function1();
    mypos++;
    myvars[mypos] = result;
    function2();
    myvars[mypos] += result;
    function3();
    result += myvars[mypos];
    mypos--;
}

By changing the value of mypos from 10 to 11 (as an example), your program indicates that the element mypos[11] is now in use and that the functions being called shall store their data in elements mypos[x] with x>=12.

Exactly this is how the stack is working.

Typically, the "variable" mypos is not a variable but a CPU register named "stack pointer". (However, there are a few historic CPUs where an ordinary variable was used for this!)

The actual answers

Does the compiler generate a logical address for the variables?

In the example above, the compiler will perform a mypos+=3 if there are 3 local variables. Let's say they are named a, b and c.

The compiler simply replaces a by myvars[mypos-2], b by myvars[mypos-1] and c by myvars[mypos].

On most CPUs, the stack pointer (named mypos in the example) is not an index into an array but already a pointer (comparable to int * mypos;), so the compiler would replace a by *(mypos-2) instead of myvars[mypos-2] in the example.

For global variables, the compiler simply counts the number of bytes needed for all global variables. In the simplest case, it chooses a range of memory of the same size (e.g. 0x10000...0x10123) and places the variables there.

Won't the compiler need OS permission to generate or assign such addresses?

No.

The "stack" (in the example this is the array myvars[]) is already provided by the OS and the stack pointer (mypos in the example) is also set to a correct value by the OS before the program is started.

Your program knows that the elements myvars[x] with x>mypos can be used.

For global variables, the information about the range used by global variables (e.g. 0x10000...0x10123) is stored in the executable file. The OS must ensure that this memory range can be used by the program. (For example by configuring the MMU accordingly.)

If this is not possible, the OS will simply refuse to start the program with an error message.

... asking the OS to allocate memory when running the executable?

For variables on the stack:

There may be operating systems where this is done.

However, in most cases, the program will simply crash with a "stack overflow" if too much stack is needed. In the example, this would mean: The program crashes if an elements myvars[x] with x>=MAX_LOCALS is accessed.

Now taking the context of heap allocated variables ...

Please first note that global variables are not stored on the heap.

The heap is used for data allocated using malloc() and similar functions (new in C++ for example).

Under many operating systems, malloc() calls an operating system function - so it is actually the operating system that allocates memory on the heap.

... and if there is not enough space, the OS (and malloc()) will return NULL.


问:
stimulus.js live update field outside of controller
On a rails 6 installation, I have the following:

Controller:

```<code># app/controllers/foo_controller.rb
def bar
  @items = [["firstname", "{{ FIRSTNAME }}"], ["lastname", "{{ LASTNAME }}"], ["company", "{{ COMPANY }}"]]
end
</code>```

View:

```<code># app/views/foo/bar.html.erb
<p>Quia <span data-field="firstname">{{ FIRSTNAME }}</span> quibusd <span data-field="firstname">{{ FIRSTNAME }}</span> am sint culpa velit necessi <span data-field="lastname">{{ LASTNAME }}</span> tatibus  s impedit recusandae modi dolorem  <span data-field="company">{{ COMPANY }}</span> aut illo ducimus unde quo u <span data-field="firstname">{{ FIRSTNAME }}</span> tempore voluptas.</p>

<% @items.each do |variable, placeholder| %>
<div data-controller="hello">
  <input
  type="text"
  data-hello-target="name"
  data-action="hello#greet"
  data-field="<%= variable %>"
  value="<%= placeholder %>">
</div>
<% end %>
</code>```

and the relevant stimulus code (vanilla JS):

```<code>//app/javascript/controllers/hello_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "name" ]

  greet() {
    var elements = document.body.querySelectorAll('[data-field="' + this.nameTarget.dataset.field + '"]');
    for (var i = 0; i < elements.length; i++) {
      elements[i].innerText = this.nameTarget.value;
    };
  }
}
</code>```

Now, as you might have guessed, the idea is to generate one <input> field per item from the @items hash, pre-filled with the relevant value and "linked" with a , which it updates on value change. So far, everything works.

Here's my issue though. This part is plain old dirty vanilla js, which doesn't feel too 'stimulusy':

```<code>var elements = document.body.querySelectorAll('[data-field="' + this.nameTarget.dataset.field + '"]');
for (var i = 0; i < elements.length; i++) {
  elements[i].innerText = this.nameTarget.value;
};
</code>```

Surely there's some way to improve this. Any suggestion as to how to refactor this code in a more elegant way would be most welcome.

答:
An approach would be to have two controllers, one for the 'thing that will change the content' (let's call this content) and another for the 'thing that will show any updated content somewhere else' (let's call this output).

Once you set up two controllers, it becomes a bit easier to reason about them as being discrete. One does something when a value updates from user interaction and the other should so something when it knows about an updated value.

Stimulus recommends cross controller coordination with events. JavaScript event passing is a powerful, browser native, way to communicate across elements in the DOM.

First, let's start with the simplest case in HTML only

In general, it is good to think about the HTML first, irrespective of how the content is generated on the server side as it will help you solve one problem at a time.

As an aside, I do not write Ruby and this question would be easier to parse if it only had the smallest viable HTML to reproduce the question.

Below we have two div elements, one sits above and is meant to show the name value inside the h1 tag and the email in the p tag.

The second div  contains a two input tags and these are where the user will update the value.

I have hard-coded the 'initial' data as this would come from the server in the first HTML render.

output#updateLabel"
  >

      Hello
      Joe

      Email:
      joe@joe.co

    <input
      type="text"
      data-action="content#update"
      data-content-field-param="name"
      value="Joe"
    />
    <input
      type="text"
      data-action="content#update"
      data-content-field-param="email"
      value="joe@joe.co"
    />

```
<h2>Second - walk through the event flow</h2>
<ul>
<li>Once an <code>input</code> is updated, it will fire the <code>conten#update</code> event on change.</li>
<li>The <code>data-content-field-param</code> is an Action Parameter that will be available inside the <code>event.params</code> given to the class method <code>update</code> on the <code>content</code> controller.</li>
<li>This way, the <strong>one</strong> class method has knowledge of the element that has changed (via the event) and the field 'name' to give this when passing the information on.</li>
<li>The <code>output</code> controller has a separate action to 'listen' for an event called <code>content:updated</code> and it will listen for this event globally (at the <code>window</code>) and then call its own method <code>updateLabel</code> with the received event.</li>
<li>The <code>output</code> controller has targets with the name <code>item</code> and each one has the mapping of what 'field' it should referent in a simple <code>data-field</code> attribute.</li>
</ul>
<h2>Third - create the controllers</h2>
<ul>
<li>Below, the <code>ContentController</code> has a single <code>update</code> method that will receive any fired input element's change event.</li>
<li>The value can be gathered from the event's <code>currentTarget</code> and the field can be gathered via the <code>event.params.field</code>.</li>
<li>Then a new event is fired with the <code>this.dispatch</code> method, we give it a name  of <code>updated</code> and Stimulus will automatically append the class name <code>content</code> giving the event name <code>content:updated</code>. As per docs - https://stimulus.hotwired.dev/reference/controllers#cross-controller-coordination-with-events</li>
<li>The <code>OutputController</code> has a target of name <code>item</code> and then a method <code>updateLabel</code></li>
<li><code>updateLabel</code> will receive the event and 'pull out' the detail given to it from the <code>ContentController</code>'s dispatch.</li>
<li>Finally, <code>updateLabel</code> will go through each of the <code>itemTargets</code> and see if any have the matching field name on that element's dataset and then update the <code>innerText</code> when a match is found. This also means you could have multiple 'name' placeholders throughout this controller's scoped HTML.</li>
</ul>
<pre class="lang-js prettyprint-override"><code>class ContentController extends Controller {
  update(event) {
    const field = event.params.field;
    const value = event.currentTarget.value;
    this.dispatch('updated', { detail: { field, value } });
  }
}

class OutputController extends Controller {
  static targets = ['item'];

  updateLabel(event) {
    const { field, value } = event.detail;

    this.itemTargets.forEach((element) => {
      if (element.dataset.field === field) {
        element.innerText = value;
      }
    });
  }
}

</code>```

Body:
On a rails 6 installation, I have the following:

Controller:

# app/controllers/foo_controller.rb
def bar
  @items = [["firstname", "{{ FIRSTNAME }}"], ["lastname", "{{ LASTNAME }}"], ["company", "{{ COMPANY }}"]]
end

View:

# app/views/foo/bar.html.erb

Quia {{ FIRSTNAME }} quibusd {{ FIRSTNAME }} am sint culpa velit necessi {{ LASTNAME }} tatibus  s impedit recusandae modi dolorem  {{ COMPANY }} aut illo ducimus unde quo u {{ FIRSTNAME }} tempore voluptas.

<% @items.each do |variable, placeholder| %>

  <input
  type="text"
  data-hello-target="name"
  data-action="hello#greet"
  data-field="<%= variable %>"
  value="<%= placeholder %>">

<% end %>

and the relevant stimulus code (vanilla JS):

//app/javascript/controllers/hello_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "name" ]

  greet() {
    var elements = document.body.querySelectorAll('[data-field="' + this.nameTarget.dataset.field + '"]');
    for (var i = 0; i < elements.length; i++) {
      elements[i].innerText = this.nameTarget.value;
    };
  }
}

Now, as you might have guessed, the idea is to generate one <input> field per item from the @items hash, pre-filled with the relevant value and "linked" with a , which it updates on value change. So far, everything works.

Here's my issue though. This part is plain old dirty vanilla js, which doesn't feel too 'stimulusy':

var elements = document.body.querySelectorAll('[data-field="' + this.nameTarget.dataset.field + '"]');
for (var i = 0; i < elements.length; i++) {
  elements[i].innerText = this.nameTarget.value;
};

Surely there's some way to improve this. Any suggestion as to how to refactor this code in a more elegant way would be most welcome.

Body:
An approach would be to have two controllers, one for the 'thing that will change the content' (let's call this content) and another for the 'thing that will show any updated content somewhere else' (let's call this output).

Once you set up two controllers, it becomes a bit easier to reason about them as being discrete. One does something when a value updates from user interaction and the other should so something when it knows about an updated value.

Stimulus recommends cross controller coordination with events. JavaScript event passing is a powerful, browser native, way to communicate across elements in the DOM.

First, let's start with the simplest case in HTML only

In general, it is good to think about the HTML first, irrespective of how the content is generated on the server side as it will help you solve one problem at a time.

As an aside, I do not write Ruby and this question would be easier to parse if it only had the smallest viable HTML to reproduce the question.

Below we have two div elements, one sits above and is meant to show the name value inside the h1 tag and the email in the p tag.

The second div  contains a two input tags and these are where the user will update the value.

I have hard-coded the 'initial' data as this would come from the server in the first HTML render.

<body>
  <div
    class="container"
    data-controller="output"
    data-action="content:updated@window->output#updateLabel"
  >
    <h1 class="title">
      Hello
      <span data-output-target="item" data-field="name">Joe</span>
    </h1>
    <p>
      Email:
      <span data-output-target="item" data-field="email">joe@joe.co</span>
    </p>
  </div>
  <div data-controller="content">
    <input
      type="text"
      data-action="content#update"
      data-content-field-param="name"
      value="Joe"
    />
    <input
      type="text"
      data-action="content#update"
      data-content-field-param="email"
      value="joe@joe.co"
    />
  </div>
</body>

Second - walk through the event flow

Once an input is updated, it will fire the conten#update event on change.

The data-content-field-param is an Action Parameter that will be available inside the event.params given to the class method update on the content controller.

This way, the one class method has knowledge of the element that has changed (via the event) and the field 'name' to give this when passing the information on.

The output controller has a separate action to 'listen' for an event called content:updated and it will listen for this event globally (at the window) and then call its own method updateLabel with the received event.

The output controller has targets with the name item and each one has the mapping of what 'field' it should referent in a simple data-field attribute.

Third - create the controllers

Below, the ContentController has a single update method that will receive any fired input element's change event.

The value can be gathered from the event's currentTarget and the field can be gathered via the event.params.field.

Then a new event is fired with the this.dispatch method, we give it a name  of updated and Stimulus will automatically append the class name content giving the event name content:updated. As per docs - https://stimulus.hotwired.dev/reference/controllers#cross-controller-coordination-with-events

The OutputController has a target of name item and then a method updateLabel

updateLabel will receive the event and 'pull out' the detail given to it from the ContentController's dispatch.

Finally, updateLabel will go through each of the itemTargets and see if any have the matching field name on that element's dataset and then update the innerText when a match is found. This also means you could have multiple 'name' placeholders throughout this controller's scoped HTML.

class ContentController extends Controller {
  update(event) {
    const field = event.params.field;
    const value = event.currentTarget.value;
    this.dispatch('updated', { detail: { field, value } });
  }
}

class OutputController extends Controller {
  static targets = ['item'];

  updateLabel(event) {
    const { field, value } = event.detail;

    this.itemTargets.forEach((element) => {
      if (element.dataset.field === field) {
        element.innerText = value;
      }
    });
  }
}


问:
How to make mobile menu full-width
I cannot figure out, how to make mobile menu full-width. When I click on hamburger menu, it opens up, but it's only like regular dropdown.I tried many ways to change it, but can't figure it out.

Here is the link: https://dev.povoden.cz/

答: Add style position: static to class "et_pb_menu_inner_container" and "et_pb_column--with-menu"

Title: How to make mobile menu full-width


问:
How to optimize the time complexity when looping over two arrays
I have 2 sorted arrays of application names in the user's Android device. I now need to log an event if one array contains at least one item of the other array.

Here is my code:

```<code>  appsArray = ["cred","cult","hotstar","netflix","prime","splitwise","spotify"];
  _apps = [...]; // Apps in user's mobile

  bool _isQualityUser() {
    var result = '';
    for (var app in _apps) {
      result = appsArray.singleWhere((el) => app.appName.contains(el));
    }
    return result.isNotEmpty;
  }
</code>```

I'm looking for an optimized solution for it. If anyone can help with that.

答:
this approach finds similar strings in O(n):

void main() {
  List<String> list1 = ["bc", "ab", "abb", "bb", "aa", "ff"];
  List<String> list2 = ["ab", "bb", "abc", "cb", "bc", "fg", "ff"];

  list1.sort();
  list2.sort();

  int index1 = 0;
  int index2 = 0;
  while (true) {
    if (list1[index1] == list2[index2]) {
      print(list1[index1]);
      index1 += 1;
      index2 += 1;
    } else if (list1[index1].compareTo(list2[index2]) < 0) {
      index1 += 1;
    } else {
      index2 += 1;
    }
    if (index1 == list1.length || index2 == list2.length) break;
  }
}

```

Body:
I have 2 sorted arrays of application names in the user's Android device. I now need to log an event if one array contains at least one item of the other array.

Here is my code:

  appsArray = ["cred","cult","hotstar","netflix","prime","splitwise","spotify"];
  _apps = [...]; // Apps in user's mobile

  bool _isQualityUser() {
    var result = '';
    for (var app in _apps) {
      result = appsArray.singleWhere((el) => app.appName.contains(el));
    }
    return result.isNotEmpty;
  }

I'm looking for an optimized solution for it. If anyone can help with that.


答:
You can use the following way.

.et_mobile_menu {
  position: fixed; /* Instead of absolute */
  top: 90px !important; /* Adjust it to set the top value */
}```

Title: How to make mobile menu full-width

Body:
I cannot figure out, how to make mobile menu full-width. When I click on hamburger menu, it opens up, but it's only like regular dropdown.I tried many ways to change it, but can't figure it out.

Here is the link: https://dev.povoden.cz/


问:
How does Unity3D use PhysX without requiring the PhysX runtime?
When I looked at using PhysX, one had to install a runtime a bit like installing .NET. However I note Unity3D employs PhysX and Unity3D plugin installation is fairly simple and doesn't appear to add 3rd-party components. How is this possible?</p>

答:
As a partner, they presumably would have access to special builds or even source code for PhysX, allowing Unity to link in or bundle with PhysX directly. Just because a core technology is distributed one way (say the end-user run-time or nVidia drivers), doesn't mean that that's the only way.

Also keep in mind, PhysX doesn't require hardware acceleration and can act as a software physics engine by itself.


问:
Bootstrap 5 background color is having opacity
I'm trying to create a OR divider, but in bootstrap 5 its not working correctly which is working properly in bootstrap 4. In my project bootstrap 5 is being used. Background color of text is having some opacity.

HTML:

```<code><div class="or-line-block pt-2">
    <h6 class="text-center m-0"><span class="or-txt px-2">OR</span></h6>
    <hr class="or-line">
</div>
</code>```

CSS:

```<code>.or-txt{
    background-color: white;
}
.or-line{
    margin-top: -10px;
    border-color: rgba(#333, 0.1);
}
</code>```

In Bootstrap 4:

In Bootstrap 5:

What is the issue. Please help

答:
It might work better to use ::before and ::after pseudo elements.

CSS

```<code>   .or-line::before{
      content: "---------"
   }

   .or-line::after{
      content: "---------"
   }
</code>```

Insert anything in the content sections and it will appear before and after the work OR.

HTML

```<code> <h6 class="or-line">OR</h6>
</code>```

Body:
I'm trying to create a OR divider, but in bootstrap 5 its not working correctly which is working properly in bootstrap 4. In my project bootstrap 5 is being used. Background color of text is having some opacity.

HTML:

OR

CSS:

.or-txt{
    background-color: white;
}
.or-line{
    margin-top: -10px;
    border-color: rgba(#333, 0.1);
}

In Bootstrap 4:

In Bootstrap 5:

What is the issue. Please help

Body:
It might work better to use ::before and ::after pseudo elements.

CSS

   .or-line::before{
      content: "---------"
   }

   .or-line::after{
      content: "---------"
   }

Insert anything in the content sections and it will appear before and after the work OR.

HTML

 <h6 class="or-line">OR</h6>


问:
Selecting rows in Pandas using multiple intervals (pd.Interval range objects)
I need to use pd.Interval to select records across multiple bin ranges.

```<code>df = pd.DataFrame({'my_col': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]})
df['my_col_bin'] = pd.cut(x=df['my_col'], bins=[0, 3, 6, 9, 12], right=False, include_lowest=True)
</code>```

```<code>    my_col  my_col_bin
0   1   [0, 3)
1   2   [0, 3)
2   3   [3, 6)
3   4   [3, 6)
4   5   [3, 6)
5   6   [6, 9)
6   7   [6, 9)
7   8   [6, 9)
8   9   [9, 12)
9   10  [9, 12)
10  11  [9, 12)
</code>```

For example, I would like to select all records that fall into range [3, 12). I would like to get the following output using single pd.Interval range, without specifying condition for each interval individually:

```<code>2   3   [3, 6)
3   4   [3, 6)
4   5   [3, 6)
5   6   [6, 9)
6   7   [6, 9)
7   8   [6, 9)
8   9   [9, 12)
9   10  [9, 12)
10  11  [9, 12)
</code>```

I tried the following, which didn't work.

```<code>df[df['my_col_bin'] == pd.Interval(3, 12, closed='left')]
</code>```

The following selection works on a single interval, but it appears that pd.Interval doesn't support multiple ranges.

```<code>df[df['my_col_bin'] == pd.Interval(3, 6, closed='left')]
</code>```

Is it possible to select range across the bins without explicitly specifying each interval condition? Is there a succinct way to perform the selection without filtering for each interval individually?

答:
You can try:</p>
```<code># transform in IntervalArray

df['my_col_bin']=pd.arrays.IntervalArray(df['my_col_bin'])

# # simply filter based in pd.Interval

df[df['my_col_bin'].array.overlaps(pd.Interval(3, 12,
 closed='left'))]
</code>```

Body:
I need to use pd.Interval to select records across multiple bin ranges.

df = pd.DataFrame({'my_col': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]})
df['my_col_bin'] = pd.cut(x=df['my_col'], bins=[0, 3, 6, 9, 12], right=False, include_lowest=True)

    my_col  my_col_bin
0   1   [0, 3)
1   2   [0, 3)
2   3   [3, 6)
3   4   [3, 6)
4   5   [3, 6)
5   6   [6, 9)
6   7   [6, 9)
7   8   [6, 9)
8   9   [9, 12)
9   10  [9, 12)
10  11  [9, 12)

For example, I would like to select all records that fall into range [3, 12). I would like to get the following output using single pd.Interval range, without specifying condition for each interval individually:

2   3   [3, 6)
3   4   [3, 6)
4   5   [3, 6)
5   6   [6, 9)
6   7   [6, 9)
7   8   [6, 9)
8   9   [9, 12)
9   10  [9, 12)
10  11  [9, 12)

I tried the following, which didn't work.

df[df['my_col_bin'] == pd.Interval(3, 12, closed='left')]

The following selection works on a single interval, but it appears that pd.Interval doesn't support multiple ranges.

df[df['my_col_bin'] == pd.Interval(3, 6, closed='left')]

Is it possible to select range across the bins without explicitly specifying each interval condition? Is there a succinct way to perform the selection without filtering for each interval individually?

Body:
You can try:

# transform in IntervalArray

df['my_col_bin']=pd.arrays.IntervalArray(df['my_col_bin'])

# # simply filter based in pd.Interval

df[df['my_col_bin'].array.overlaps(pd.Interval(3, 12,
 closed='left'))]


问:
Javascript Regex for YouTube video and shorts id
I want to return the video id from the video url of YouTube even for Shorts.

But I have got pattern which works for some few url which do not includes Shorts

^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*

Edit:
It should work for the following urls:

```<code>http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI
</code>```

Thank You

答:
This should work on the provided examples

```<code>(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))
</code>```

https://regex101.com/r/5JhmpW/1
The actual video id should be the third capture group in each match.

Group1: Url up to the last part

Group2: The last part of the url which receives the videoId as parameter

Group3: Either the last part in the url (which is the videoId in the "/v/" , "/embed/", "/user/", "/shorts/" and "youtu.be/" variants ), or the videoId parameter (in the case of watch)

You can use it in javascript like this:

```<code>let data = `http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI`;
let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
let videoIds = [...data.matchAll(regex)].map(x => x[3]);
</code>```

Or if you only expect one url at a time:

```<code>function getVideoId(url) {
    let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
    return regex.exec(url)[3];
}
</code>```

keep in mind regex in javascript aren't stateless, running the same regex multiple times will cause it to iterate through the matches in the text (and eventually return NULL once it has reached the end), which is why the regex is re initialized on every call in this case. If no matches are found, it will also return null.

Body:
I want to return the video id from the video url of YouTube even for Shorts.

But I have got pattern which works for some few url which do not includes Shorts

^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*

Edit:
It should work for the following urls:

http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI

Thank You

Body:
This should work on the provided examples

(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))

https://regex101.com/r/5JhmpW/1
The actual video id should be the third capture group in each match.

Group1: Url up to the last part

Group2: The last part of the url which receives the videoId as parameter

Group3: Either the last part in the url (which is the videoId in the "/v/" , "/embed/", "/user/", "/shorts/" and "youtu.be/" variants ), or the videoId parameter (in the case of watch)

You can use it in javascript like this:

let data = `http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI`;
let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
let videoIds = [...data.matchAll(regex)].map(x => x[3]);

Or if you only expect one url at a time:

function getVideoId(url) {
    let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
    return regex.exec(url)[3];
}

keep in mind regex in javascript aren't stateless, running the same regex multiple times will cause it to iterate through the matches in the text (and eventually return NULL once it has reached the end), which is why the regex is re initialized on every call in this case. If no matches are found, it will also return null.


问:
Google Drive API: the get() method on drive_service.files().list() documented?
In this link there a get method in Python:

```<code>response = drive_service.files().list(q="mimeType='image/jpeg'",
                                          spaces='drive',
                                          fields='nextPageToken, files(id, name)',
                                          pageToken=page_token).execute()
    for file in response.get('files', []):
</code>```

I guess the get() method will get a list of files, and if none, it will return an empty list, but where is this documented? The API doc does not have it. It simply says:

```<code>Returns:
  An object of the form:
...
</code>```

It did not document any method.

答:
files.list method returns a file list response

```<code>{
  "kind": "drive#fileList",
  "nextPageToken": string,
  "incompleteSearch": boolean,
  "files": [
    files Resource
  ]
}
</code>```

File list response contains a list of any file resources returned by the request.  If there are not returned the files will be an empty list.

By default it does not return a full file resource object a number of fields are null.

```<code> {
   "kind": "drive#file",
   "id": "1x8-vD-XEA5Spf3qp8x2wltablGF22Lpwup8VtxNY",
   "name": "Experts Activity Dump go/ExpertsActivities",
   "mimeType": "application/vnd.google-apps.spreadsheet"
  },
</code>```

The way around that is to add an optional param of fields=* and then you will get a full file resource object back.  This can result in a very large request though.

The file.get method returns a the file resources for that file id that is requested.  So you have to pass it a file.id of the file you want to request.

Background info Original release.

In the original release of the Google drive v3. File.list did not work with fields=* it only worked only returned the default fields leaving everything else null. This force us to use a File.get on every file that we need the full response back for.  This has been since fixed making it easer and requiring only a single call to the api to get all the properties of the object populated.

The question remains if this was a bug in the beginning or working as intended and they patched it to stop eating all our quota.

Body:
In this link there a get method in Python:

response = drive_service.files().list(q="mimeType='image/jpeg'",
                                          spaces='drive',
                                          fields='nextPageToken, files(id, name)',
                                          pageToken=page_token).execute()
    for file in response.get('files', []):

I guess the get() method will get a list of files, and if none, it will return an empty list, but where is this documented? The API doc does not have it. It simply says:

Returns:
  An object of the form:
...

It did not document any method.

Body:
files.list method returns a file list response

{
  "kind": "drive#fileList",
  "nextPageToken": string,
  "incompleteSearch": boolean,
  "files": [
    files Resource
  ]
}

File list response contains a list of any file resources returned by the request.  If there are not returned the files will be an empty list.

By default it does not return a full file resource object a number of fields are null.

 {
   "kind": "drive#file",
   "id": "1x8-vD-XEA5Spf3qp8x2wltablGF22Lpwup8VtxNY",
   "name": "Experts Activity Dump go/ExpertsActivities",
   "mimeType": "application/vnd.google-apps.spreadsheet"
  },

The way around that is to add an optional param of fields=* and then you will get a full file resource object back.  This can result in a very large request though.

The file.get method returns a the file resources for that file id that is requested.  So you have to pass it a file.id of the file you want to request.

Background info Original release.

In the original release of the Google drive v3. File.list did not work with fields=* it only worked only returned the default fields leaving everything else null. This force us to use a File.get on every file that we need the full response back for.  This has been since fixed making it easer and requiring only a single call to the api to get all the properties of the object populated.

The question remains if this was a bug in the beginning or working as intended and they patched it to stop eating all our quota.


问:
Listening of bloc getting called multiple times
I have this code for listening to bloc on my screen.

```<code>late MyBloc myBloc;

@override
  void initState() {
    print('inside init state');
    super.initState();
    myBloc = BlocProvider.of<MyBloc>(context);
    myBloc.stream.listen((state) {
      if (state is MyAddCompletedState) {
        print('listening to bloc');
      }
    }
}
</code>```

If I add an event, it will print listening to bloc once. If I go to another screen and return to this same screen, it will print listening to bloc twice. It seems like the first listen I did was still active. Next, I tried to close the bloc on my dispose thinking that it would stop the first listen. So that when I come back to the screen it will have a fresh listen but it will have an error: Bad state: Cannot add new events after calling close. I tried to research about this and some mention to dispose the bloc but it doesn't have that syntax anymore. Please help on how to properly close or stop it from listening once I have change screen. Thanks!

```<code>//this is found on my screen
late MyBloc myBloc;

@override
  void initState() {
    print('inside init state');
    super.initState();
    myBloc = BlocProvider.of<MyBloc>(context);
    myBloc.stream.listen((state) {
      if (state is MyAddCompletedState) {
        print('listening to bloc');
      }
    }
}

  @override
  void dispose() {
    myBloc.close();
    // myBloc.dispose(); --> I saw some tutorial to use this but it doesn't work
    super.dispose();
  }
</code>```

This is on my main.dart:

```<code>    return FutureBuilder(
        future: InitFirst.instance.initialize(),
        builder: (context, AsyncSnapshot snapshot) {
          return MultiBlocProvider(
            providers: [
              BlocProvider<MyBloc>(
                create: (context) => MyBloc(
                  authenticationRepository: authenticationRepository,
                  userDataRepository: userDataRepository,
                ),
              ),
            ...
</code>```

This is the part where I trigger the event. After this event run, the stream.listen will get triggered. But it will be triggered multiple times every time I visit the my screen.

```<code>    myBloc.add(MyAddEvent(
        selectedName,
        selectedCount);
</code>```

Additional note: this event is triggering an update in Firebase which I need to check if it got completed that is why I do the stream.listen.

答:
If the Stream used in Bloc keeps getting called when not in use, you may want to consider terminating the Stream with cancel() in your dispose() override. Try this

late MyBloc myBloc;
late StreamSubscription mSub;

@override
void initState() {
  print('inside init state');
  super.initState();
  myBloc = BlocProvider.of<MyBloc>(context);
  mSub = myBloc.stream.listen((state) {
    if (state is MyAddCompletedState) {
      print('listening to bloc');
    }
  }
}

@override
void dispose() {
  mSub.cancel();

  super.dispose();
}
```

Body:
I have this code for listening to bloc on my screen.

late MyBloc myBloc;

@override
  void initState() {
    print('inside init state');
    super.initState();
    myBloc = BlocProvider.of<MyBloc>(context);
    myBloc.stream.listen((state) {
      if (state is MyAddCompletedState) {
        print('listening to bloc');
      }
    }
}

If I add an event, it will print listening to bloc once. If I go to another screen and return to this same screen, it will print listening to bloc twice. It seems like the first listen I did was still active. Next, I tried to close the bloc on my dispose thinking that it would stop the first listen. So that when I come back to the screen it will have a fresh listen but it will have an error: Bad state: Cannot add new events after calling close. I tried to research about this and some mention to dispose the bloc but it doesn't have that syntax anymore. Please help on how to properly close or stop it from listening once I have change screen. Thanks!

//this is found on my screen
late MyBloc myBloc;

@override
  void initState() {
    print('inside init state');
    super.initState();
    myBloc = BlocProvider.of<MyBloc>(context);
    myBloc.stream.listen((state) {
      if (state is MyAddCompletedState) {
        print('listening to bloc');
      }
    }
}

  @override
  void dispose() {
    myBloc.close();
    // myBloc.dispose(); --> I saw some tutorial to use this but it doesn't work
    super.dispose();
  }

This is on my main.dart:

    return FutureBuilder(
        future: InitFirst.instance.initialize(),
        builder: (context, AsyncSnapshot snapshot) {
          return MultiBlocProvider(
            providers: [
              BlocProvider<MyBloc>(
                create: (context) => MyBloc(
                  authenticationRepository: authenticationRepository,
                  userDataRepository: userDataRepository,
                ),
              ),
            ...

This is the part where I trigger the event. After this event run, the stream.listen will get triggered. But it will be triggered multiple times every time I visit the my screen.

    myBloc.add(MyAddEvent(
        selectedName,
        selectedCount);

Additional note: this event is triggering an update in Firebase which I need to check if it got completed that is why I do the stream.listen.


问:
Next.js on Vercel, is server code on single Lambda?
I found this quote on the Vercel website:

When using Next.js, Vercel optimizes Serverless Function output for server-rendered pages and API Routes. All functions will be created inside the same bundle (or in multiple chunks if greater than 50mb). This helps reduce cold starts since the bundled function is more likely warm

But is this also true for getServerSideProps?

I have a small project with an API and another page that loads the data with getServerSideProps. When the first API is done. I would except the next page with the getServerSideProps would be fast, but that also seems to have a cold boot.
The second time everything is fast.

答:
Based on the two following comments from Vercel in related GitHub discussions:

One thing to note — in Vercel (a recent update), Next.js SSR pages and
pages/api routes get bundled into two separate Lambdas (λ), so you
should not have to worry about the Serverless Function limit.

Source: https://github.com/vercel/vercel/discussions/5093#discussioncomment-57628

API Routes will all be bundled, each SSR page will also be bundled -
both of these will be creating another function should they exceed
maximum capacity (50MB) although this is handled a little before the
limit to avoid it being too close.

Source: https://github.com/vercel/vercel/discussions/5458#discussioncomment-614662

My understanding is that in your scenario the API route (or any other API routes you may have) will be bundled into one function, and getServerSideProps into another function. If either exceeds the 50MB size limit then an additional function would be created.

What you're experiencing seems to be expected. The API route and getServerSideProps would be a different functions, thus having separate cold boots.


问:
Is there a way to reference the function you are inside of in C?
I am writing a function that just looks up values inside of a table. Is it possible to call that function inside of itself? I've seen stuff about this and self and don't really understand it.

答:
Yes, you can. It's called recursion.

```<code>void foo(){
   foo(); //This is legal.
}
</code>```

Of course you need to return from it to avoid infinite recursive calls. Failing to return will cause a stack overflow. Here's a better example:

```<code>void foo(int n){
    if (n == 0)
        return;
    foo(--n);
}
</code>```

Body:
Yes, you can. It's called recursion.

void foo(){
   foo(); //This is legal.
}

Of course you need to return from it to avoid infinite recursive calls. Failing to return will cause a stack overflow. Here's a better example:

void foo(int n){
    if (n == 0)
        return;
    foo(--n);
}


问:
How to successfully change Postgresql data folder
enter code hereI followed the instructions here and although it seems successful and Postgres starts up I get the following error:

I would greatly appreciate any help to figure this out.

below is the output of /var/log/postgresql/postgresql-12-main.log

```<code>    pg_ctl: directory "/mnt/postgres_data" is not a database cluster directory
2022-02-05 17:15:54.321 UTC [9484] LOG:  starting PostgreSQL 12.9 (Ubuntu 12.9-0ubuntu0.20.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0>
2022-02-05 17:15:54.322 UTC [9484] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2022-02-05 17:15:54.341 UTC [9484] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2022-02-05 17:15:54.380 UTC [9485] LOG:  database system was shut down at 2022-02-05 17:04:32 UTC
2022-02-05 17:15:54.393 UTC [9484] LOG:  database system is ready to accept connections
2022-02-05 17:29:39.339 UTC [9484] LOG:  received fast shutdown request
2022-02-05 17:29:39.340 UTC [9484] LOG:  aborting any active transactions
2022-02-05 17:29:39.347 UTC [9484] LOG:  background worker "logical replication launcher" (PID 9491) exited with exit code 1
2022-02-05 17:29:39.352 UTC [9486] LOG:  shutting down
2022-02-05 17:29:39.372 UTC [9484] LOG:  database system is shut down
2022-02-05 19:44:20.272 UTC [1236] LOG:  starting PostgreSQL 12.9 (Ubuntu 12.9-0ubuntu0.20.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0>
2022-02-05 19:44:20.285 UTC [1236] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2022-02-05 19:44:20.287 UTC [1236] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2022-02-05 19:44:20.376 UTC [1237] LOG:  database system was shut down at 2022-02-05 17:29:39 UTC
2022-02-05 19:44:20.447 UTC [1236] LOG:  database system is ready to accept connections
2022-02-05 19:47:33.160 UTC [1236] LOG:  received smart shutdown request
2022-02-05 19:47:33.163 UTC [1236] LOG:  background worker "logical replication launcher" (PID 1243) exited with exit code 1
2022-02-05 19:47:33.165 UTC [1238] LOG:  shutting down
2022-02-05 19:47:33.213 UTC [1236] LOG:  database system is shut down
</code>```

The only line I changed in postgresql.conf is the one below.  The 'mnt/postgres_data/main' folder is on a Truenas server.  The permissions are below too.

```<code>bigdaddy@weatherserver:/etc/postgresql/12/main$ ls -al /mnt
total 82
drwxr-xr-x  4 root     root     4096 Feb  4 19:18 .
drwxr-xr-x 19 root     root     4096 Feb  4 19:09 ..
drwxrwxr-x  7 media    media      38 Jan 29 14:28 Documents
drwx------  3 postgres postgres    4 Feb  5 19:54 postgres_data

#------------------------------------------------------------------------------
# FILE LOCATIONS
#------------------------------------------------------------------------------

# The default values of these variables are driven from the -D command-line
# option or PGDATA environment variable, represented here as ConfigDir.

#data_directory = '/var/lib/postgresql/12/main'         # use data in another directory
data_directory = '/mnt/postgres_data/main'
</code>```

答:
When you initially install postgres on Ubuntu it starts a cluster that it calls main.  It is essentially a default cluster.  It has a fixed directory of
/var/lib/postgresql/12/main and /etc/postgresql/12/main
The 12 is the version number for postgres.  The default location for the postgresql.conf files are in the folder of the instance under the following.
/etc/postgresql/12/…..
It is here that you set the behaviour of each instance.  I wanted to add a storage location that was on the Truenas server.  To do this required the following command as the postgres user.

```<code>pg_createcluster –datadir=/mnt/postgres_data 12 <instance name>
</code>```

Again the 12 represents the version of postgres you have installed.  You can have several versions of postgres and do this for all of those different versions.
There are a bunch of other pg_ commands that you can use too.

```<code>pg_lsclusters – lists the clusters that are installed and whether they are active or not.
</code>```

You can start and stop individual clusters with the following command

```<code> systemctl stop postgresql@12-main
</code>```

Where the 12 is again the postgresql version number and main the name of the cluster.  Main is the name of the default cluster created.
Everything I found on line indicated that I could move the contents of the main cluster to the new storage location.  That didn’t work.  I think now the reason it didn’t was because there are 2 folders.
/var/lib/postgresql/12/main and /etc/postgresql/12/main
The video below got me going in the right direction.
Be sure to note that the new clusters are assigned a different port number.  This is what is used to connect to the cluster over the same IP address.
pg_lsclusters lists the port number for each cluster.  By default each successive cluster is given the next port, i.e. 5432+1 for the next cluster.

Managing the instance/cluster

Ubuntu manpage pg_createcluster

Body:
enter code hereI followed the instructions here and although it seems successful and Postgres starts up I get the following error:

I would greatly appreciate any help to figure this out.

below is the output of /var/log/postgresql/postgresql-12-main.log

    pg_ctl: directory "/mnt/postgres_data" is not a database cluster directory
2022-02-05 17:15:54.321 UTC [9484] LOG:  starting PostgreSQL 12.9 (Ubuntu 12.9-0ubuntu0.20.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0>
2022-02-05 17:15:54.322 UTC [9484] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2022-02-05 17:15:54.341 UTC [9484] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2022-02-05 17:15:54.380 UTC [9485] LOG:  database system was shut down at 2022-02-05 17:04:32 UTC
2022-02-05 17:15:54.393 UTC [9484] LOG:  database system is ready to accept connections
2022-02-05 17:29:39.339 UTC [9484] LOG:  received fast shutdown request
2022-02-05 17:29:39.340 UTC [9484] LOG:  aborting any active transactions
2022-02-05 17:29:39.347 UTC [9484] LOG:  background worker "logical replication launcher" (PID 9491) exited with exit code 1
2022-02-05 17:29:39.352 UTC [9486] LOG:  shutting down
2022-02-05 17:29:39.372 UTC [9484] LOG:  database system is shut down
2022-02-05 19:44:20.272 UTC [1236] LOG:  starting PostgreSQL 12.9 (Ubuntu 12.9-0ubuntu0.20.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0>
2022-02-05 19:44:20.285 UTC [1236] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2022-02-05 19:44:20.287 UTC [1236] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2022-02-05 19:44:20.376 UTC [1237] LOG:  database system was shut down at 2022-02-05 17:29:39 UTC
2022-02-05 19:44:20.447 UTC [1236] LOG:  database system is ready to accept connections
2022-02-05 19:47:33.160 UTC [1236] LOG:  received smart shutdown request
2022-02-05 19:47:33.163 UTC [1236] LOG:  background worker "logical replication launcher" (PID 1243) exited with exit code 1
2022-02-05 19:47:33.165 UTC [1238] LOG:  shutting down
2022-02-05 19:47:33.213 UTC [1236] LOG:  database system is shut down

The only line I changed in postgresql.conf is the one below.  The 'mnt/postgres_data/main' folder is on a Truenas server.  The permissions are below too.

bigdaddy@weatherserver:/etc/postgresql/12/main$ ls -al /mnt
total 82
drwxr-xr-x  4 root     root     4096 Feb  4 19:18 .
drwxr-xr-x 19 root     root     4096 Feb  4 19:09 ..
drwxrwxr-x  7 media    media      38 Jan 29 14:28 Documents
drwx------  3 postgres postgres    4 Feb  5 19:54 postgres_data

#------------------------------------------------------------------------------
# FILE LOCATIONS
#------------------------------------------------------------------------------

# The default values of these variables are driven from the -D command-line
# option or PGDATA environment variable, represented here as ConfigDir.

#data_directory = '/var/lib/postgresql/12/main'         # use data in another directory
data_directory = '/mnt/postgres_data/main'

Body:
When you initially install postgres on Ubuntu it starts a cluster that it calls main.  It is essentially a default cluster.  It has a fixed directory of
/var/lib/postgresql/12/main and /etc/postgresql/12/main
The 12 is the version number for postgres.  The default location for the postgresql.conf files are in the folder of the instance under the following.
/etc/postgresql/12/…..
It is here that you set the behaviour of each instance.  I wanted to add a storage location that was on the Truenas server.  To do this required the following command as the postgres user.

pg_createcluster –datadir=/mnt/postgres_data 12 <instance name>

Again the 12 represents the version of postgres you have installed.  You can have several versions of postgres and do this for all of those different versions.
There are a bunch of other pg_ commands that you can use too.

pg_lsclusters – lists the clusters that are installed and whether they are active or not.

You can start and stop individual clusters with the following command

 systemctl stop postgresql@12-main

Where the 12 is again the postgresql version number and main the name of the cluster.  Main is the name of the default cluster created.
Everything I found on line indicated that I could move the contents of the main cluster to the new storage location.  That didn’t work.  I think now the reason it didn’t was because there are 2 folders.
/var/lib/postgresql/12/main and /etc/postgresql/12/main
The video below got me going in the right direction.
Be sure to note that the new clusters are assigned a different port number.  This is what is used to connect to the cluster over the same IP address.
pg_lsclusters lists the port number for each cluster.  By default each successive cluster is given the next port, i.e. 5432+1 for the next cluster.

Managing the instance/cluster

Ubuntu manpage pg_createcluster