问:
samtools calmd is pretty slow
I am using "samtools calmd" to add MD tag back to BAM file. The size of original BAM is around 50Gb (whole genome sequence by using pacbio HIFI reads). The issue that I encountered is that the speed of "calmd" is incredibly slow! The jobs have already run 12 hours, and only 600MB BAM with MD tag are generated. In this way, 50GB BAM will take 30days to be finished!

Here is the code I used to add MD tag (very normal):

```<code>rule addMDTag:
    input:
        rules.pbmm2_alignment.output
    output:
        strBAMDir + "/pbmm2/v37/{wcReadsType}/Tmp/rawReads{readsIndex}.MD.bam"
    params:
        ref = strRef
    threads:
        16
    log:
        strBAMDir + "/pbmm2/v37/{wcReadsType}/Log/rawReads{readsIndex}.MD.log"
    benchmark:
        strBAMDir + "/pbmm2/v37/{wcReadsType}/Benchmark/rawReads{readsIndex}.MD.benchmark.txt"
    shell:
        "samtools calmd -@ {threads} {input} {params.ref} -bAr > {output}"
</code>```

The version of samtools I used is v1.10.

BTW, I use 16 cores to run calmd, however, it looks like the samtools is still using 1 core to run it:

```<code>top - 11:44:53 up 47 days, 20:35,  1 user,  load average: 2.00, 2.01, 2.00
Tasks: 1723 total,   3 running, 1720 sleeping,   0 stopped,   0 zombie
Cpu(s):  2.8%us,  0.3%sy,  0.0%ni, 96.8%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:  529329180k total, 232414724k used, 296914456k free,    84016k buffers
Swap: 12582908k total,    74884k used, 12508024k free, 227912476k cached

   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 93137 lix33     20   0  954m 151m 2180 R 100.2  0.0 659:04.13 samtools
</code>```

May I know how to make calmd be much faster? Or is there any other tool that can do the same job more efficiently?

Thanks so much

答:
After the collaboration with samtools maintenance team, this issue has been solved.
The calmd will be super slow if the bam was unsorted. Therefore, always make sure the BAM has been sorted before run calmd.

See the details below:

```<code>Are your files name sorted, and does your reference have more than one entry?
If so calmd will be switching between references all the time,
which means it may be doing a lot of reference loading and not much MD calculation.

You may find it goes a lot faster if you position-sort the input, and then run it through calmd.
</code>```

Title: samtools calmd is pretty slow

Body:
I am using "samtools calmd" to add MD tag back to BAM file. The size of original BAM is around 50Gb (whole genome sequence by using pacbio HIFI reads). The issue that I encountered is that the speed of "calmd" is incredibly slow! The jobs have already run 12 hours, and only 600MB BAM with MD tag are generated. In this way, 50GB BAM will take 30days to be finished!

Here is the code I used to add MD tag (very normal):

rule addMDTag:
    input:
        rules.pbmm2_alignment.output
    output:
        strBAMDir + "/pbmm2/v37/{wcReadsType}/Tmp/rawReads{readsIndex}.MD.bam"
    params:
        ref = strRef
    threads:
        16
    log:
        strBAMDir + "/pbmm2/v37/{wcReadsType}/Log/rawReads{readsIndex}.MD.log"
    benchmark:
        strBAMDir + "/pbmm2/v37/{wcReadsType}/Benchmark/rawReads{readsIndex}.MD.benchmark.txt"
    shell:
        "samtools calmd -@ {threads} {input} {params.ref} -bAr > {output}"

The version of samtools I used is v1.10.

BTW, I use 16 cores to run calmd, however, it looks like the samtools is still using 1 core to run it:

top - 11:44:53 up 47 days, 20:35,  1 user,  load average: 2.00, 2.01, 2.00
Tasks: 1723 total,   3 running, 1720 sleeping,   0 stopped,   0 zombie
Cpu(s):  2.8%us,  0.3%sy,  0.0%ni, 96.8%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:  529329180k total, 232414724k used, 296914456k free,    84016k buffers
Swap: 12582908k total,    74884k used, 12508024k free, 227912476k cached

   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 93137 lix33     20   0  954m 151m 2180 R 100.2  0.0 659:04.13 samtools

May I know how to make calmd be much faster? Or is there any other tool that can do the same job more efficiently?

Thanks so much

Body:
After the collaboration with samtools maintenance team, this issue has been solved.
The calmd will be super slow if the bam was unsorted. Therefore, always make sure the BAM has been sorted before run calmd.

See the details below:

Are your files name sorted, and does your reference have more than one entry?
If so calmd will be switching between references all the time,
which means it may be doing a lot of reference loading and not much MD calculation.

You may find it goes a lot faster if you position-sort the input, and then run it through calmd.


来源: stackexchange

问:
How to give Grid Items of a React Grid layout a reference
Im trying to have a dynamic array of references. These references would come from the Grid items, that are being mapped from a list to the Grid Layout-Element.

This is my code:

```<code><GridLayout
                        layout = {layout}
                        onLayoutChange={(currentLayout) => {onLayoutChange(currentLayout)}}
                        onDragStop={currentLayout => onDragStop(currentLayout)}
                        onDropDragOver={onDropDragOver}
                        onDrop={(currentLayout,item,_event) => onDrop(item,_event)}
                        onResizeStart={(layout, oldItem, newItem, placeholder, event, element) => {setConfigValues(oldItem.i)}}
                        onResize={(layout, oldItem, newItem, placeholder, event, element) => onResize(oldItem)}
                        style={canvasBoxStyle}
                        ref={gridRef}
                        {...gridLayoutProps}
            >
                {layout.map((layoutElement) =>
                    <div
                        style={{zIndex:getAttributesById(layoutElement.i).attributes.zIndex}}
                        key={parseInt(layoutElement.i)}
                        data-grid={layoutElement}
                        ref={(ref) => elementRefs.current.push(ref)}
                        onClick={() => {setConfigValues(layoutElement.i)}}
                    >
                        {createElement(layoutElement)}
                    </div>

                )}
            </GridLayout>
</code>```

It seems like the "ref"-attribute gets ignored from react, because none of the grid items refs are being pushed into the refs-array

```<code>const elementRefs = useRef([]);
</code>```

The ref-attribute works just fine for the "GirdLayout"-Element.

I dont know what im doing wrong i tried many stuff. I need the refs of each grid item to get the width and height of each of them.

答:
I think pushing the ref for every component render is not a good idea because that could create a big array with repeated elements in case of re-renders.

You could solve this problem by creating some sort of map of refs. For instance, the following code works fine for me:

```<code>import React, { useRef, useEffect } from "react";

const data = ["a", "b", "c", "d"];

export default function App() {
  const refs = useRef([]);

  useEffect(() => {
    console.log(refs);
  }, []);

  return (
    <div className="App">
      {data.map((d, i) => (
        <p key={i} ref={(ref) => (refs.current[i] = ref)}>
          {d}
        </p>
      ))}
    </div>
  );
}

</code>```

That answer is based on other answer from Jorge Pirela: https://stackoverflow.com/a/70885503/7159312

May not be the most optimal way of doing that.

ContentLicense: CC BY-SA 4.0

Body:
Im trying to have a dynamic array of references. These references would come from the Grid items, that are being mapped from a list to the Grid Layout-Element.

This is my code:

<GridLayout
                        layout = {layout}
                        onLayoutChange={(currentLayout) => {onLayoutChange(currentLayout)}}
                        onDragStop={currentLayout => onDragStop(currentLayout)}
                        onDropDragOver={onDropDragOver}
                        onDrop={(currentLayout,item,_event) => onDrop(item,_event)}
                        onResizeStart={(layout, oldItem, newItem, placeholder, event, element) => {setConfigValues(oldItem.i)}}
                        onResize={(layout, oldItem, newItem, placeholder, event, element) => onResize(oldItem)}
                        style={canvasBoxStyle}
                        ref={gridRef}
                        {...gridLayoutProps}
            >
                {layout.map((layoutElement) =>

 elementRefs.current.push(ref)}
                        onClick={() => {setConfigValues(layoutElement.i)}}
                    >
                        {createElement(layoutElement)}

                )}
            </GridLayout>

It seems like the "ref"-attribute gets ignored from react, because none of the grid items refs are being pushed into the refs-array

const elementRefs = useRef([]);

The ref-attribute works just fine for the "GirdLayout"-Element.

I dont know what im doing wrong i tried many stuff. I need the refs of each grid item to get the width and height of each of them.

Body:
I think pushing the ref for every component render is not a good idea because that could create a big array with repeated elements in case of re-renders.

You could solve this problem by creating some sort of map of refs. For instance, the following code works fine for me:

import React, { useRef, useEffect } from "react";

const data = ["a", "b", "c", "d"];

export default function App() {
  const refs = useRef([]);

  useEffect(() => {
    console.log(refs);
  }, []);

  return (
    <div className="App">
      {data.map((d, i) => (
        <p key={i} ref={(ref) => (refs.current[i] = ref)}>
          {d}
        </p>
      ))}
    </div>
  );
}

That answer is based on other answer from Jorge Pirela: https://stackoverflow.com/a/70885503/7159312

May not be the most optimal way of doing that.


问:
Making a http request using a session token to log in a website on python
Firstly, the objective is to make a http request every certain time, but there is a problem: the login screen.

In short, i tried to make a request to the link firefaucet.win/start with this code below

```<code>import requests
requests.get('https://firefaucet.win/start')
</code>```

This request returns to the login page, because to use this website you need to have a account.
 Doing by the common way, making a POST request with the auth is out of question, because the login is followed by a captcha box. I figured out another way to log in, that is using my own session token, that i got on the cookies of my browser. But this is the point, I don't know how to log in using just the session token.

答:
I read a lot on the requests lib docs and the answer is just make a request session object and make the request using the cookies kwarg, that is default to None. Just by reading that the session token is kept in a cookie named "session" on the browser, I achieved the objective just by putting the session token inside the "session" cookie like the code below:</p>
```<code>import requests
obj = requests.Session()
response = obj.request(
    'get',
    'https://firefaucet.win/start',
    cookies={
        'session': 'session token here'
    }
)
print(response)
</code>```

Body:
Firstly, the objective is to make a http request every certain time, but there is a problem: the login screen.

In short, i tried to make a request to the link firefaucet.win/start with this code below

import requests
requests.get('https://firefaucet.win/start')

This request returns to the login page, because to use this website you need to have a account.
 Doing by the common way, making a POST request with the auth is out of question, because the login is followed by a captcha box. I figured out another way to log in, that is using my own session token, that i got on the cookies of my browser. But this is the point, I don't know how to log in using just the session token.

Body:
I read a lot on the requests lib docs and the answer is just make a request session object and make the request using the cookies kwarg, that is default to None. Just by reading that the session token is kept in a cookie named "session" on the browser, I achieved the objective just by putting the session token inside the "session" cookie like the code below:

import requests
obj = requests.Session()
response = obj.request(
    'get',
    'https://firefaucet.win/start',
    cookies={
        'session': 'session token here'
    }
)
print(response)


问:
How to chain multiple dispatch actions one after the other in redux?
Im trying to chain multiple dispatch actions one for the other, by this order:

1.updateCart(dispatch,cartProducts ,loggedUser) - with redux-thunk.

after finishing fetching data, im dispatching actions by order:

2.dispatch(logoutReset()))

3.dispatch(logoutSuccess()))

4.then a refresh - window.location.reload())

but doesnt wait for dispatch to finish first before moving on so it keeps messing up.
i have tried many ways, with await or promises but didn't succeed.

i would like to learn from you guys, how to do it properly.

Component Navbar:

```<code>const handleLogout = async() => {
        try{
            await  updateCart(dispatch,cartProducts ,loggedUser)
            .then( ()=> dispatch(logoutReset()))
            .then( ()=> dispatch(logoutSuccess()))
            .then( ()=> window.location.reload());
        }catch(err){
                console.log(err)
        }
    };
</code>```

Actions (updateCart) redux-thunk:

```<code>export const updateCart = async (dispatch, selectedProduct, loggedUser) => {

  dispatch({ type: ActionTypes.UPDATE_CART });

  try {
   await userRequest.put(`carts/` + loggedUser.id, {
      userId: loggedUser.id,
      products: selectedProduct
    })
  } catch (error) {
    console.log(error.response)
    dispatch(returnErrors(error.response.data, error.response.status));
  }
};
</code>```

答:
I have found a solution, posing if anyone will need it some day.

If you want to do something after dispatch finish, just put useEffect and the parameter that is updated after the dispatch, so after the dispatch and update you can do what you need to do.
very simple approach

```<code>const handleAddClick = () => {
   dispatch(addToCart({selectedProduct:item,quantity}))
}
</code>```

so after dispatch is finished cartProducts is updated.

```<code>useEffect(() => {
 updateCart(dispatch,cartProducts ,loggedUser)
}, [cartProducts])

</code>```

Body:
Im trying to chain multiple dispatch actions one for the other, by this order:

1.updateCart(dispatch,cartProducts ,loggedUser) - with redux-thunk.

after finishing fetching data, im dispatching actions by order:

2.dispatch(logoutReset()))

3.dispatch(logoutSuccess()))

4.then a refresh - window.location.reload())

but doesnt wait for dispatch to finish first before moving on so it keeps messing up.
i have tried many ways, with await or promises but didn't succeed.

i would like to learn from you guys, how to do it properly.

Component Navbar:

const handleLogout = async() => {
        try{
            await  updateCart(dispatch,cartProducts ,loggedUser)
            .then( ()=> dispatch(logoutReset()))
            .then( ()=> dispatch(logoutSuccess()))
            .then( ()=> window.location.reload());
        }catch(err){
                console.log(err)
        }
    };

Actions (updateCart) redux-thunk:

export const updateCart = async (dispatch, selectedProduct, loggedUser) => {

  dispatch({ type: ActionTypes.UPDATE_CART });

  try {
   await userRequest.put(`carts/` + loggedUser.id, {
      userId: loggedUser.id,
      products: selectedProduct
    })
  } catch (error) {
    console.log(error.response)
    dispatch(returnErrors(error.response.data, error.response.status));
  }
};

Body:
I have found a solution, posing if anyone will need it some day.

If you want to do something after dispatch finish, just put useEffect and the parameter that is updated after the dispatch, so after the dispatch and update you can do what you need to do.
very simple approach

const handleAddClick = () => {
   dispatch(addToCart({selectedProduct:item,quantity}))
}

so after dispatch is finished cartProducts is updated.

useEffect(() => {
 updateCart(dispatch,cartProducts ,loggedUser)
}, [cartProducts])


问:
How to put two concat queries into the same table as two columns
I've just started using MySQL and I can't find the answer to this anywhere maybe because it doesn't exist?

I want to put these two together in one table as two columns

```<code>SELECT CONCAT(Name, ' ',Category) as Pet_Name_and_Category
FROM Animal

SELECT CONCAT(firstname, ' ',lastname) as Customer_Name
From PetCustomer
</code>```

So the table I want would look something like:

```<code>Gary, Snail               Spongebob Squarepants

Sandy, Squirrel           Patrick Star
</code>```

Where those are two separate columns in the same table.

答:
If you need to use CONCAT twice for the same table, regardless of the condition, you can use this:

```<code>SELECT
    CONCAT(TitleOfCourtesy, ' ', FirstName, ' ', LastName) AS NameEmployee,
    CONCAT(PostalCode, ' ', Country, ' ', Region, ' ', City, ' ', [Address]) AS FullAddress
FROM Employees
WHERE 1=1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've just started using MySQL and I can't find the answer to this anywhere maybe because it doesn't exist?

I want to put these two together in one table as two columns

SELECT CONCAT(Name, ' ',Category) as Pet_Name_and_Category
FROM Animal

SELECT CONCAT(firstname, ' ',lastname) as Customer_Name
From PetCustomer

So the table I want would look something like:

Gary, Snail               Spongebob Squarepants

Sandy, Squirrel           Patrick Star

Where those are two separate columns in the same table.

Body:
If you need to use CONCAT twice for the same table, regardless of the condition, you can use this:

SELECT
    CONCAT(TitleOfCourtesy, ' ', FirstName, ' ', LastName) AS NameEmployee,
    CONCAT(PostalCode, ' ', Country, ' ', Region, ' ', City, ' ', [Address]) AS FullAddress
FROM Employees
WHERE 1=1


问:
Building for x86 and x64 platform with CMake with Xcode and Visual studio
I started using CMake pretty recently.
It is a really easy script language but there are many tricks to learn and tutorials on the cmake website is not much help.

Basically I want to build my project for

Windows (using visual studio 2010) x86 and x64

Mac os (using Xcode 4) x86 and x64

Dependending on the OS and plateforme I want to link certain libraries.

I figured out for Windows that I can use WIN32 or WIN64 to set this up.
But I can't find the equivalence for mac os.
Can someone point me in the right direction?

答:
```<code>if (APPLE)
....
endif(APPLE)
</code>```

more information:
http://cmake.org/Wiki/CMake_Useful_Variables#System_.26_Compiler_Information

Body:
if (APPLE)
....
endif(APPLE)

more information:
http://cmake.org/Wiki/CMake_Useful_Variables#System_.26_Compiler_Information


答:
Might as well turn my comment into an answer:

```<code>def my_saving_plan(P0,i,goal):
    P = [P0]
    while P[-1] < goal:
        P.append((1+i)*P[-1])
        print(P)
    return len(P) - 1

print(my_saving_plan(1000, 0.07, 2000))
</code>```

From my comment:
You have an off-by-one error in your append line. n is already the last element, and using n-1 will be one behind that, thus causing duplication.

You could also use while P[-1] < goal instead of for. Index -1 always refers to the last element. You don't need n or years at all.

Title: Why is my program calculating the compound interest twice

Body:
I want to calculate the time it takes for the compound interest to reach a certain goal by using Pn=(1+i)Pn−1.
What I have done is:

def my_saving_plan(P0,i,goal):
    P = [P0]
    years = 0
    for n in range(0,10000):
        if P[n] < goal:
            P.append((1+i)*P[n-1])
            years += 1
            print(P)
        elif P[n] >= goal:
            return years
print(my_saving_plan(1000, 0.07, 2000))

But What I get from that is the number of compound interest twice. So for this example what I get is:

    [1000, 1070.0, 1070.0, 1144.9, 1144.9, 1225.0430000000001,
1225.0430000000001, 1310.7960100000003, 1310.7960100000003,
1402.5517307000005, 1402.5517307000005, 1500.7303518490005,
1500.7303518490005, 1605.7814764784307, 1605.7814764784307,
 1718.186179831921, 1718.186179831921, 1838.4592124201556,
1838.4592124201556, 1967.1513572895667, 1967.1513572895667,
2104.8519522998363]
    21

Also I was wondering if there is a way to use a while loop instead of putting a ridiculous number in the for loop.

Body:
Might as well turn my comment into an answer:

def my_saving_plan(P0,i,goal):
    P = [P0]
    while P[-1] < goal:
        P.append((1+i)*P[-1])
        print(P)
    return len(P) - 1

print(my_saving_plan(1000, 0.07, 2000))

From my comment:
You have an off-by-one error in your append line. n is already the last element, and using n-1 will be one behind that, thus causing duplication.

You could also use while P[-1] < goal instead of for. Index -1 always refers to the last element. You don't need n or years at all.


问:
Docker Container port access
I have created an image from an existing dotnet application I can run locally.

in my docker file I have
EXPOSE 5000

In the docker compose:
ports: [5000:5000]

I start the container using the command:
docker run -d -p 5000:5000 --name my-reports my-reports:latest

running the docker ps  command :

```<code>     NAMES
106c4929c0d6   my-reports:latest   "dotnet my-reports"   8 minutes ago   Up 8 minutes   0.0.0.0:5000->5000/tcp   my-reports
</code>```

The output of the entrypoint:

```<code>info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\app
</code>```

netstat shows:

```<code>C:\app>netstat -a

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    0.0.0.0:135            106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:5985           106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:47001          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49152          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49153          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49154          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49155          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49160          106c4929c0d6:0         LISTENING
  TCP    127.0.0.1:5000         106c4929c0d6:0         LISTENING
</code>```

But I get timeouts trying to access the port from my machine via localhost:5000

答:
Your problem is that your app listens on localhost. This is only available inside the container.

You need to make your app listen on the public network interface. Most easy achieved by using 0.0.0.0 as IP, which makes it listen on all interfaces.

In your case, make the app listen on 0.0.0.0:5000.

Title: Docker Container port access

Body:
I have created an image from an existing dotnet application I can run locally.

in my docker file I have
EXPOSE 5000

In the docker compose:
ports: [5000:5000]

I start the container using the command:
docker run -d -p 5000:5000 --name my-reports my-reports:latest

running the docker ps  command :

     NAMES
106c4929c0d6   my-reports:latest   "dotnet my-reports"   8 minutes ago   Up 8 minutes   0.0.0.0:5000->5000/tcp   my-reports

The output of the entrypoint:

info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\app

netstat shows:

C:\app>netstat -a

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    0.0.0.0:135            106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:5985           106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:47001          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49152          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49153          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49154          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49155          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49160          106c4929c0d6:0         LISTENING
  TCP    127.0.0.1:5000         106c4929c0d6:0         LISTENING

But I get timeouts trying to access the port from my machine via localhost:5000


问:
Some beginner Objective-C/iPhone questions
I'm just starting out (reading up a lot for the past couple of days). Here's some questions that I have stacked up, hopefully someone can answer them.

1. the (self != nil) check in initializer code. Why do it? To prevent accidental access to some "run-only-once" code that's wrapped up in there? Where from could this accidental access come from? Doing such checks suggest that I don't have control over what's going on.

```
- (id)init {
    self = [super init]
    if (self != nil) {
    // Code..
    }
    return self;
}
```

2. How is it that you don't have to free up anything that static methods return? (or this is the idea I've got)

3. How is str = @"Hi there!" different from

```str = [[NSString alloc] initWithString:@"Hi there!"];```

As I understand, you have to release str in aquired with second method, but not with first? If so, when does the first one get released? Which one is preferable (not minding the typing length)?

4. What is autorelease, if iphone has no garbage collection? I've noticed something called "an autorelease pool" being created in main.m. Is [myObject autorelease]; a way of adding myObject to the nearest wrapping "autorelease pool", which will release it? Basically, some magic to avoid releasing it yourself? Why use it?

Well, thats it for now. Thanks for any answers!

答:
If self is nil after the super initialisation then you're probably out of memory. Your only reasonable course of action is to return nil and hope things get handled gracefully further up the stack.

Static methods aren't allowed allocate on the heap, therefore there's nothing to free.

In the first instance, the string is compiled into the data segment of your app and cannot be freed. In the second instance, you are allocating memory from the heap and copying your static string (from the data segment) into it.

It's simple garbage collection. As to why to use it, the simple answer is don't. It's not recommended to use autorelease on the iPhone due to limited resources.

OwnerDisplayName: Karolis

ContentLicense: CC BY-SA 2.5

Body:
I'm just starting out (reading up a lot for the past couple of days). Here's some questions that I have stacked up, hopefully someone can answer them.

1. the (self != nil) check in initializer code. Why do it? To prevent accidental access to some "run-only-once" code that's wrapped up in there? Where from could this accidental access come from? Doing such checks suggest that I don't have control over what's going on.

- (id)init {
    self = [super init]
    if (self != nil) {
    // Code..
    }
    return self;
}

2. How is it that you don't have to free up anything that static methods return? (or this is the idea I've got)

3. How is str = @"Hi there!" different from

str = [[NSString alloc] initWithString:@"Hi there!"];

As I understand, you have to release str in aquired with second method, but not with first? If so, when does the first one get released? Which one is preferable (not minding the typing length)?

4. What is autorelease, if iphone has no garbage collection? I've noticed something called "an autorelease pool" being created in main.m. Is [myObject autorelease]; a way of adding myObject to the nearest wrapping "autorelease pool", which will release it? Basically, some magic to avoid releasing it yourself? Why use it?

Well, thats it for now. Thanks for any answers!

OwnerDisplayName: edoloughlin


问:
How to update state in React App when something happens on server side
I have a small react app I've built that displays different entries in my mongoDB and then has filters, so it only shows what you're looking for.

In order to get the entries I have a js listener listening to an outside source and then adding them to MongoDB. Then I have my React App send a get request to my express app, which pulls the data from MongoDB and updates state on each refresh and grab all the entries.

I want the state to update everytime a new entry is added to MongoDB, so the user doesn't have to refresh and gets real time data.

Is there anyway I can call the useEffect function from the server side file or is there some way I can detect inside the react app when new data is added?

答: you could simply do a call on pageload to get the current data, then do subsequent calls on a set time interval and compare the length of the new call with the current calls, only saving data if there is a difference.</p>


问:
Object destructuring: Assign null values in one line
Assuming I have an object like this

```<code>foo = {
    a: 1,
    b: 2,
    c: 3
};
</code>```

I would destructure it this way

```<code>const {a, b, c} = foo;
</code>```

However, what, if the keys a, b and c do not exist?

```<code>foo = null;
</code>```

This won't work then

```<code>const {a, b, c} = foo;
</code>```

I would have to do something like

```<code>let a, b, c;

if(foo) {
    a = foo.a;
    b = foo.b;
    c = foo.c;
};
</code>```

Is there a way to do this in one line? Something like

```<code> const {a, b, c} = foo ? foo : null; // this is not working
</code>```

null is not an object. (evaluating '_ref2.a')

答:
What about destructuring default parameters?
If foo could be undefined set  = foo || {} in destructuring to avoid exception

let foo = {};
const {a = null, b = null, c = null} = foo;

console.log('a:', a);
console.log('b:', b);
console.log('c:', c);```

Body:
Assuming I have an object like this

foo = {
    a: 1,
    b: 2,
    c: 3
};

I would destructure it this way

const {a, b, c} = foo;

However, what, if the keys a, b and c do not exist?

foo = null;

This won't work then

const {a, b, c} = foo;

I would have to do something like

let a, b, c;

if(foo) {
    a = foo.a;
    b = foo.b;
    c = foo.c;
};

Is there a way to do this in one line? Something like

 const {a, b, c} = foo ? foo : null; // this is not working

null is not an object. (evaluating '_ref2.a')


答:
It will work like you might expect, the variables a b and c will be created with the value of undefined. this is the fallback when also trying to access a property which doesn't exist on a certain object.

const foo = {};
console.log(foo.a); // undefined

const {a, b, c} = foo;

console.log(a); // undefined
console.log(b); // undefined

console.log(d); // Uncaught ReferenceError: d is not defined```

Title: Object destructuring: Assign null values in one line


问:
What is a virtualenv, and why should I use one?
I am trying to install a Python package with this command

```<code>pip install <name of package>
</code>```

I'm getting permission errors and I'm not sure why.  I could run it with sudo, but someone told me that was a bad idea, and I should use a virtualenv instead.

What is a virtualenv?  What does it do for me?

答:
I am going to break your question into two parts.

What is a virtualenv?

Python has its own way of downloading, storing, and resolving site packages. But Python can not differentiate between different versions in the site-package directory. Packages will be installed in one of the directories, whose name can be found by running the site.getsitepackages() commands.

```<code>>>> import site
>>> site.getsitepackages()
</code>```

This means package_v2.0.1 and package_v3.0.1 have to be in the same directory with the same name i.e. package, which is obviously not possible. Now, you may ask why we would need the same package with different versions on our system. This is because multiple projects may require different versions of Python packages or even different Python versions themselves. So there was a need to have something which will resolve these conflicts and Virtualenv came into the picture to solve this issue.

What does it do for me?

It isolates the environment for Python projects so that each project can have its own dependencies.

Body:
I am trying to install a Python package with this command

pip install <name of package>

I'm getting permission errors and I'm not sure why.  I could run it with sudo, but someone told me that was a bad idea, and I should use a virtualenv instead.

What is a virtualenv?  What does it do for me?

Body:
I am going to break your question into two parts.

What is a virtualenv?

Python has its own way of downloading, storing, and resolving site packages. But Python can not differentiate between different versions in the site-package directory. Packages will be installed in one of the directories, whose name can be found by running the site.getsitepackages() commands.

>>> import site
>>> site.getsitepackages()

This means package_v2.0.1 and package_v3.0.1 have to be in the same directory with the same name i.e. package, which is obviously not possible. Now, you may ask why we would need the same package with different versions on our system. This is because multiple projects may require different versions of Python packages or even different Python versions themselves. So there was a need to have something which will resolve these conflicts and Virtualenv came into the picture to solve this issue.

What does it do for me?

It isolates the environment for Python projects so that each project can have its own dependencies.


问:
Spring not picking up value defined in properties file
I have a class with inject attributes like so:

```<code>@RestController
public class MyController {

    private final String myValue;

    @Autowired
    public MyController(
        @Value("${config.myValue}") String myValue) {
        this.myValue = myValue;
    }

    @PostMapping("/dostuff")
    public String dostuff(@RequestBody String message) {
      // stuff
    }
}
</code>```

And then I have a config file defined inside src/main/resources/application.yml like so:

```<code>config:
  myValue: "some value"
</code>```

But my IntelliJ (and cmd) tell me the value is not found:

```<code> Could not resolve placeholder 'config.myValue' in value "${config.myValue}"
</code>```

Why is my defined value not being recognized? (I tried renaming file to application-default.yml and application.properties but that didn't help either)

答:
Could you please try renaming file as application.properties and define property like below and check if it works?
config.myValue = some value</p>

Body:
I have a class with inject attributes like so:

@RestController
public class MyController {

    private final String myValue;

    @Autowired
    public MyController(
        @Value("${config.myValue}") String myValue) {
        this.myValue = myValue;
    }

    @PostMapping("/dostuff")
    public String dostuff(@RequestBody String message) {
      // stuff
    }
}

And then I have a config file defined inside src/main/resources/application.yml like so:

config:
  myValue: "some value"

But my IntelliJ (and cmd) tell me the value is not found:

 Could not resolve placeholder 'config.myValue' in value "${config.myValue}"

Why is my defined value not being recognized? (I tried renaming file to application-default.yml and application.properties but that didn't help either)


问:
Most efficient way to merge two large python dictionaries, Results and Relationships to be written to an excel file
I've been working on a webscraper which runs asynchronously to substantially improve speed. Because of the way scraper works, it writes two pieces of information for a url which it scrapes. These are stored in two dictionaries:

```<code># {url1: [parent1, parent2, parent3], url2: [parent1, parent2, parent3]...}
relationships = dict()
# {url1: [page, redirect, content_type...], url2: [page, redirect, content_type...]}
url_results = dict()
</code>```

The first dictionary, relationships, tracks each occurrence of the key url within a parent url
The second dictionary stores the resulting information I need from each url scraped.

This is all necessary for how I'm handling async threading and memorization, and works really nice. The problem lies in writing these results to an excel report. These dictionaries are getting to thousands of keys in size and merging them together is very slow.

The end result is that for each parent value for a url in relationships dict, a line is written in my excel sheet

parent
url
page
redirect
content type
etc

parent1
url1
page
redirect
content_type
etc...

parent1
url2
page
redirect
content_type
etc...

parent1
url3
page
redirect
content_type
etc...

parent2
url1
page
redirect
content_type
etc...

parent2
url2
page
redirect
content_type
etc...

parent2
url3
page
redirect
content_type
etc...

Here's the method I'm currently using to merge these dictionaries together like this:

```<code>partent_result_df = pd.DataFrame(columns=["Parent", "URL", "Page", "Redirect", "Content-type", "Source", "Status"])
location = 1
for i, key in enumerate(RELATIONSHIPS):
    # result_arr =  [Item, Redirect, Content_type, Source, Status]
    try:
        result_arr = URL_RESULTS[key]
    except:
        result_arr = [None, None, None, None, "Not Yet Accessed"]
    parents_urls = RELATIONSHIPS[key]
    for parent in parents_urls:
        partent_result_df.loc[location] = [parent, key, *result_arr]
        location += 1
return partent_result_df
</code>```

I'm looking for a way to make this merge much faster if at all possible. It's currently taking quite a lot of time to write this report, almost as much as the scrape itself, and I think I'm missing something that could help speed up this process.

I'd appreciate any help finding a better way to do this. Sorry for the information overkill, and thank you greatly for any help!

答:
Given Something like:

```<code>relationships = {
    "url1": ["parent1", "parent2", "parent3"],
    "url2": ["parent1", "parent2", "parent3"]
}

url_results = {
    "url1": ["page", "redirect", "content_type"],
    "url2": ["page", "redirect", "content_type"]
}
</code>```

One could use a comprehension and load this data into pandas then persist it to excel like:

import pandas
print(pandas.DataFrame(
    [parent, rk] + url_results.get(rk, [])
    for rk, rv in relationships.items()
    for parent in rv
))
```
<p>Giving you a table:</p>
```         0     1     2         3             4
0  parent1  url1  page  redirect  content_type
1  parent2  url1  page  redirect  content_type
2  parent3  url1  page  redirect  content_type
3  parent1  url2  page  redirect  content_type
4  parent2  url2  page  redirect  content_type
5  parent3  url2  page  redirect  content_type
```
<p>But if the ultimate objective was to persist it to a file, I would skip pandas and stream the results to a CSV:</p>
<pre class="lang-py prettyprint-override"><code>import csv
with open("./out.csv", "w", encoding="utf-8", newline="") as file_out:
    writer = csv.writer(file_out)
    writer.writerow(["parent", "url", "page", "redirect", "content_type"])
    writer.writerows(
        [parent, rk] + url_results.get(rk, [])
        for rk, rv in relationships.items()
        for parent in rv
    )
</code>```

Giving you a csv file like:

```<code>parent,url,page,redirect,content_type
parent1,url1,page,redirect,content_type
parent2,url1,page,redirect,content_type
parent3,url1,page,redirect,content_type
parent1,url2,page,redirect,content_type
parent2,url2,page,redirect,content_type
parent3,url2,page,redirect,content_type
</code>```

Body:
I've been working on a webscraper which runs asynchronously to substantially improve speed. Because of the way scraper works, it writes two pieces of information for a url which it scrapes. These are stored in two dictionaries:

# {url1: [parent1, parent2, parent3], url2: [parent1, parent2, parent3]...}
relationships = dict()
# {url1: [page, redirect, content_type...], url2: [page, redirect, content_type...]}
url_results = dict()

The first dictionary, relationships, tracks each occurrence of the key url within a parent url
The second dictionary stores the resulting information I need from each url scraped.

This is all necessary for how I'm handling async threading and memorization, and works really nice. The problem lies in writing these results to an excel report. These dictionaries are getting to thousands of keys in size and merging them together is very slow.

The end result is that for each parent value for a url in relationships dict, a line is written in my excel sheet

parent
url
page
redirect
content type
etc

parent1
url1
page
redirect
content_type
etc...

parent1
url2
page
redirect
content_type
etc...

parent1
url3
page
redirect
content_type
etc...

parent2
url1
page
redirect
content_type
etc...

parent2
url2
page
redirect
content_type
etc...

parent2
url3
page
redirect
content_type
etc...

Here's the method I'm currently using to merge these dictionaries together like this:

partent_result_df = pd.DataFrame(columns=["Parent", "URL", "Page", "Redirect", "Content-type", "Source", "Status"])
location = 1
for i, key in enumerate(RELATIONSHIPS):
    # result_arr =  [Item, Redirect, Content_type, Source, Status]
    try:
        result_arr = URL_RESULTS[key]
    except:
        result_arr = [None, None, None, None, "Not Yet Accessed"]
    parents_urls = RELATIONSHIPS[key]
    for parent in parents_urls:
        partent_result_df.loc[location] = [parent, key, *result_arr]
        location += 1
return partent_result_df

I'm looking for a way to make this merge much faster if at all possible. It's currently taking quite a lot of time to write this report, almost as much as the scrape itself, and I think I'm missing something that could help speed up this process.

I'd appreciate any help finding a better way to do this. Sorry for the information overkill, and thank you greatly for any help!

Body:
Given Something like:

relationships = {
    "url1": ["parent1", "parent2", "parent3"],
    "url2": ["parent1", "parent2", "parent3"]
}

url_results = {
    "url1": ["page", "redirect", "content_type"],
    "url2": ["page", "redirect", "content_type"]
}

One could use a comprehension and load this data into pandas then persist it to excel like:

import pandas
print(pandas.DataFrame(
    [parent, rk] + url_results.get(rk, [])
    for rk, rv in relationships.items()
    for parent in rv
))

Giving you a table:

         0     1     2         3             4
0  parent1  url1  page  redirect  content_type
1  parent2  url1  page  redirect  content_type
2  parent3  url1  page  redirect  content_type
3  parent1  url2  page  redirect  content_type
4  parent2  url2  page  redirect  content_type
5  parent3  url2  page  redirect  content_type

But if the ultimate objective was to persist it to a file, I would skip pandas and stream the results to a CSV:

import csv
with open("./out.csv", "w", encoding="utf-8", newline="") as file_out:
    writer = csv.writer(file_out)
    writer.writerow(["parent", "url", "page", "redirect", "content_type"])
    writer.writerows(
        [parent, rk] + url_results.get(rk, [])
        for rk, rv in relationships.items()
        for parent in rv
    )

Giving you a csv file like:

parent,url,page,redirect,content_type
parent1,url1,page,redirect,content_type
parent2,url1,page,redirect,content_type
parent3,url1,page,redirect,content_type
parent1,url2,page,redirect,content_type
parent2,url2,page,redirect,content_type
parent3,url2,page,redirect,content_type


问:
C# ListView and RightToLeft
I need to view english text in a listview with the RightToLeft property set to "true".

When I put brackets in the text it seems to be reversed.

If I try to write "Stack(Overflow)" I will see "(Stack(Overflow".

Is there a way to fix this?

this is a part of my code:

```<code>                    Item = (ListViewItem) myList.Items.Add(id, myString, iconIndex);
                    MyListView.SetSubItemText(Item, 1, s1);
                    MyListView.SetSubItemText(Item, 2, s2);
                    MyListView.SetSubItemText(Item, 3, s3);
                    MyListView.SetSubItemText(Item, 4, s4);
</code>```

答:
This strongly depends on the version of Windows you use, list view is implemented as a native control in Windows, the ListView class is only a managed wrapper for it.  The right-to-left rendering behavior has changed across different versions.

In general, you should only ever set RightToLeft to Yes when you localized your user interface to a language that requires right-to-left rendering of text.  Hebrew or Arabic.  Getting unusual behavior with strings in another language is not unexpected.  If your intent was to get different alignment using that property then you'll have to find an alternative.  Like OwnerDraw or ColumnHeader.TextAlign

Title: C# ListView and RightToLeft

Body:
I need to view english text in a listview with the RightToLeft property set to "true".

When I put brackets in the text it seems to be reversed.

If I try to write "Stack(Overflow)" I will see "(Stack(Overflow".

Is there a way to fix this?

this is a part of my code:

                    Item = (ListViewItem) myList.Items.Add(id, myString, iconIndex);
                    MyListView.SetSubItemText(Item, 1, s1);
                    MyListView.SetSubItemText(Item, 2, s2);
                    MyListView.SetSubItemText(Item, 3, s3);
                    MyListView.SetSubItemText(Item, 4, s4);


问:
Type hinting on Python subclasses
The List[Geometry] type hint on the code below does not cause self.items.append(line) to complain because line is a Line which is subclass of Geometry.

The same type hint causes the item.is_horizontal on the last line to say Unresolved attribute reference 'is_horizontal' for class 'Geometry'.

I think this happens because the is_horizontal property exists only in one of the subclasses of Geometry.

What is the correct way to avoid this warning?

With List[Union[Geometry, Line, Circle]] the warning goes away, but I'm not sure this is the correct solution. Listing a set of classes is not like saying <Geometry> and all subclasses.

class Geometry:
    is_circle = is_line = False

class Line(Geometry):
    is_line = True          # property on Geometry and subclasses
    is_horizontal = True    # property only on Line

class Circle(Geometry):
    is_circle = True        # property on Geometry and subclasses
    radius = 10             # property only on Line

class Geometries:
    def __init__(self):
        self.items: List[Geometry] = []

    def add_line(self, line: Line):
        self.items.append(line)

    def horizontal_lines(self):
        return [item for item in self.items if item.is_line and item.is_horizontal]
```

答:
Since items has a static type of List[Geometry], the type checker cannot make any assumptions about what attributes a list element has beyond what is statically defined in Geometry. Since is_horizontal is not an attribute of all instances of Geometry, an access like item.is_horizontal is forbidden.

However, you can assert that item is really a Line based on runtime knowledge using cast. cast(Line, item) is a no-op at runtime, but the type checker treats it as meaning "whatever type item is, cast will return an instance of Line.

Given some more realistic definitions of Geometry, Line, and Circle,

```<code>from typing import cast, List

class Geometry:
    ...

class Line(Geometry):
    def __init__(self, slope, y_intercept):
        ...

    @property
    def is_horizontal(self):
        return self.slope == 0

    ...

class Circle(Geometry):
    def __init__(self, radius, center):
        self.radius = radius
        self.center = center

    ...
</code>```

you can define Geometries (and in particular, Geometries.horizontal_lines) like so:

```<code>class Geometries:
    def __init__(self):
        self.items: List[Geometry] = []

    def add_line(self, line: Line):
        self.items.append(line)

    def horizontal_lines(self) -> List[Line]:
        return [item for item in self.items
                     if isinstance(item, Line)
                        and cast(Line, item).is_horizontal]
</code>```

Various static type-checkers may make the call to cast optional. For example, they could infer that given isinstance(x, y) and z, if isinstance returns True then the static type of x can be assumed to be y in z, regardless of any previous type hints regarding the static type of x. (If it were to return False, then z is dead code and needn't be checked at all.)

Title: Type hinting on Python subclasses

Body:
Since items has a static type of List[Geometry], the type checker cannot make any assumptions about what attributes a list element has beyond what is statically defined in Geometry. Since is_horizontal is not an attribute of all instances of Geometry, an access like item.is_horizontal is forbidden.

However, you can assert that item is really a Line based on runtime knowledge using cast. cast(Line, item) is a no-op at runtime, but the type checker treats it as meaning "whatever type item is, cast will return an instance of Line.

Given some more realistic definitions of Geometry, Line, and Circle,

from typing import cast, List

class Geometry:
    ...

class Line(Geometry):
    def __init__(self, slope, y_intercept):
        ...

    @property
    def is_horizontal(self):
        return self.slope == 0

    ...

class Circle(Geometry):
    def __init__(self, radius, center):
        self.radius = radius
        self.center = center

    ...

you can define Geometries (and in particular, Geometries.horizontal_lines) like so:

class Geometries:
    def __init__(self):
        self.items: List[Geometry] = []

    def add_line(self, line: Line):
        self.items.append(line)

    def horizontal_lines(self) -> List[Line]:
        return [item for item in self.items
                     if isinstance(item, Line)
                        and cast(Line, item).is_horizontal]

Various static type-checkers may make the call to cast optional. For example, they could infer that given isinstance(x, y) and z, if isinstance returns True then the static type of x can be assumed to be y in z, regardless of any previous type hints regarding the static type of x. (If it were to return False, then z is dead code and needn't be checked at all.)


问:
Prevent nesting when function used to define tuple
I'm trying to define a tuple, but part of what I want to go into the tuple will be the output of a function. This output ends up being nested, which I do not want.

```<code>def do_thingy():
    # Example of a fucntion that does things
    return(["c", "d"],["e","f"])

my_tuple = (["a", "b"], do_thingy())
print(my_tuple)

# Returns: (['a', 'b'], (['c', 'd'], ['e', 'f']))
# I want: (['a', 'b'], ['c', 'd'], ['e', 'f'])
</code>```

I've tried a lot of jiggery-pokery but cannot get the result I desire. As an example:

```<code>def do_thingy():
    return[["c", "d"],["e","f"]]
my_tuple = tuple([["a", "b"] + do_thingy()])
print(my_tuple)
</code>```

For various reasons I'm trying to keep this to just one line. Not in the least because I'm rewriting this script to make it more readable and easy to modify. If that's not possible I suppose I can put the solution in a function.

答:
I will just type my comment here as an answer for completeness:

```<code>def do_thingy():
    return (["c", "d"],["e","f"])
my_tuple = (["a", "b"], *do_thingy())
print(my_tuple)
</code>```

The "*" is known as an unpacking operator I believe.

Output:

```<code>(['a', 'b'], ['c', 'd'], ['e', 'f'])
</code>```

Body:
I'm trying to define a tuple, but part of what I want to go into the tuple will be the output of a function. This output ends up being nested, which I do not want.

def do_thingy():
    # Example of a fucntion that does things
    return(["c", "d"],["e","f"])

my_tuple = (["a", "b"], do_thingy())
print(my_tuple)

# Returns: (['a', 'b'], (['c', 'd'], ['e', 'f']))
# I want: (['a', 'b'], ['c', 'd'], ['e', 'f'])

I've tried a lot of jiggery-pokery but cannot get the result I desire. As an example:

def do_thingy():
    return[["c", "d"],["e","f"]]
my_tuple = tuple([["a", "b"] + do_thingy()])
print(my_tuple)

For various reasons I'm trying to keep this to just one line. Not in the least because I'm rewriting this script to make it more readable and easy to modify. If that's not possible I suppose I can put the solution in a function.

Body:
I will just type my comment here as an answer for completeness:

def do_thingy():
    return (["c", "d"],["e","f"])
my_tuple = (["a", "b"], *do_thingy())
print(my_tuple)

The "*" is known as an unpacking operator I believe.

Output:

(['a', 'b'], ['c', 'd'], ['e', 'f'])


问:
Python3.10, Text Doesn't Show On Pygame Window
I am trying to make a app where you enter in the minute value then a timer pops up on a window. The timer isnt appearing. I am using python 3.10. I'm new to python so please if you can fix it, please include the source code.</p>
```<code>import pygame
import time
import sys

pygame.init()

q = True
WIDTH = 800
HEIGHT = 600

clock = pygame.time.Clock()

myFont = pygame.font.SysFont("monospace", 35)

def countdown(t):
    t *= 60
    while t:
        min, sec = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(min, sec)
#
        screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption('PyTimerTwo,  By: ChanceMeteor515')
        screen.fill((0, 0, 0))
        text = str(timer)
        label = myFont.render(text, 1, (255, 255, 255))
        screen.blit(label, (WIDTH - 200, HEIGHT - 40))
#
    print("\nTime's Up")
    time.sleep(5400)

t = input("Enter Time In Minutes:")
countdown(int(t))

while q:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_h:
                pygame.mouse.set_visible(0)
            elif event.key == pygame.K_ESCAPE:
                sys.exit()

    clock.tick(120)
    pygame.display.update()
</code>```

答:
In your countdown function, you forgot to update the display with pygame.display.update() and you also forgot to add an event loop, so you won't be able to close the window. If you add these, the timer will appear.

Modified Code:

```<code>import pygame
import time
import sys

pygame.init()

q = True
WIDTH = 800
HEIGHT = 600

clock = pygame.time.Clock()

myFont = pygame.font.SysFont("monospace", 35)

def countdown(t):
    t *= 60
    while t:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        min, sec = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(min, sec)
#
        screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption('PyTimerTwo,  By: ChanceMeteor515')
        screen.fill((0, 0, 0))
        text = str(timer)
        label = myFont.render(text, True, (255, 255, 255))
        screen.blit(label, (WIDTH - 200, HEIGHT - 40))

        pygame.display.update()
#
    print("\nTime's Up")
    time.sleep(5400)

t = input("Enter Time In Minutes:")
countdown(int(t))

while q:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_h:
                pygame.mouse.set_visible(False)
            elif event.key == pygame.K_ESCAPE:
                sys.exit()

    clock.tick(120)
    pygame.display.update()
</code>```

Body:
I am trying to make a app where you enter in the minute value then a timer pops up on a window. The timer isnt appearing. I am using python 3.10. I'm new to python so please if you can fix it, please include the source code.

import pygame
import time
import sys

pygame.init()

q = True
WIDTH = 800
HEIGHT = 600

clock = pygame.time.Clock()

myFont = pygame.font.SysFont("monospace", 35)

def countdown(t):
    t *= 60
    while t:
        min, sec = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(min, sec)
#
        screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption('PyTimerTwo,  By: ChanceMeteor515')
        screen.fill((0, 0, 0))
        text = str(timer)
        label = myFont.render(text, 1, (255, 255, 255))
        screen.blit(label, (WIDTH - 200, HEIGHT - 40))
#
    print("\nTime's Up")
    time.sleep(5400)

t = input("Enter Time In Minutes:")
countdown(int(t))

while q:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_h:
                pygame.mouse.set_visible(0)
            elif event.key == pygame.K_ESCAPE:
                sys.exit()

    clock.tick(120)
    pygame.display.update()

Body:
In your countdown function, you forgot to update the display with pygame.display.update() and you also forgot to add an event loop, so you won't be able to close the window. If you add these, the timer will appear.

Modified Code:

import pygame
import time
import sys

pygame.init()

q = True
WIDTH = 800
HEIGHT = 600

clock = pygame.time.Clock()

myFont = pygame.font.SysFont("monospace", 35)

def countdown(t):
    t *= 60
    while t:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        min, sec = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(min, sec)
#
        screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption('PyTimerTwo,  By: ChanceMeteor515')
        screen.fill((0, 0, 0))
        text = str(timer)
        label = myFont.render(text, True, (255, 255, 255))
        screen.blit(label, (WIDTH - 200, HEIGHT - 40))

        pygame.display.update()
#
    print("\nTime's Up")
    time.sleep(5400)

t = input("Enter Time In Minutes:")
countdown(int(t))

while q:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_h:
                pygame.mouse.set_visible(False)
            elif event.key == pygame.K_ESCAPE:
                sys.exit()

    clock.tick(120)
    pygame.display.update()


问:
Convert buffer to blob and set it to FormData in Nodejs
Assume I have two servers both run on NodeJS. First receive a file using Multer and convert it to buffer as output, then convert it to blob and put it to form-data and post it via NodeJS https.request to second server. What I cannot handle is how to convert buffer to blob in NodeJS. Any help will be appreciated.</p>

答: If you use formdata-node, it's got it's own Blob class.</p>


问:
Save fitted and predicted values to data frame in r
I am trying to extract the fitted and predicted values from the different classes of the object. But when I save them to a column in a data frame I got a column with NA. I tried to fix that by making the fitted value numeric, a data frame. But when it comes to saving the values in a data frame I still got the NA or errors. Adjusting the number of rows did neither helped.

This is my code:
library(forecast)

```<code>#generate time series
b=sin(runif(10, min=0, max=100))
plot(b,type="l")
#initiate data frame for fitted values
df1= data.frame(matrix(ncol =3, nrow=10))
colnames(df1)=c("month","Fit1", "Fit2", "Fit3")

#initiate data frame for predicted values
df2= data.frame(matrix(ncol =3, nrow=4))
colnames(df1)=c("month","Pred1", "Pred2","Pred3" )

#find model for time series
model_1= arima(b)
model_2=naive(b)
model_3=HoltWinters(ts(b, frequency=4))

#store fitted values in data frame
df1[,1]=1:10
df1[,2]=model_1$fitted
df1[,3]=model_2$fitted
df1[,4]=model_3$xhat

#find short term predicted values for 4 periods
Predictedmodel_1= forecast(model_1, 4)#
Predictedmodel_2= forecast(model_2, 4)#
Predictedmodel_3= forecast(model_3, 4)#

#store predicted values in data frame
df2[,1]=11:14
df2[,2]=Predictedmodel_1$fitted
df2[,3]=Predictedmodel_2$fitted
df2[,4]=Predictedmodel_3$fitted
</code>```

Can somebody help me pls?

答:
HoltWinters() works better for me, although it gives me sometimes the next warning message:

```<code>optimization difficulties: ERROR: ABNORMAL_TERMINATION_IN_LNSRCH
</code>```

But I found some advise and it seems to work.

Thank you also for that tictoc suggestion!

Body:
I am trying to extract the fitted and predicted values from the different classes of the object. But when I save them to a column in a data frame I got a column with NA. I tried to fix that by making the fitted value numeric, a data frame. But when it comes to saving the values in a data frame I still got the NA or errors. Adjusting the number of rows did neither helped.

This is my code:
library(forecast)

#generate time series
b=sin(runif(10, min=0, max=100))
plot(b,type="l")
#initiate data frame for fitted values
df1= data.frame(matrix(ncol =3, nrow=10))
colnames(df1)=c("month","Fit1", "Fit2", "Fit3")

#initiate data frame for predicted values
df2= data.frame(matrix(ncol =3, nrow=4))
colnames(df1)=c("month","Pred1", "Pred2","Pred3" )

#find model for time series
model_1= arima(b)
model_2=naive(b)
model_3=HoltWinters(ts(b, frequency=4))

#store fitted values in data frame
df1[,1]=1:10
df1[,2]=model_1$fitted
df1[,3]=model_2$fitted
df1[,4]=model_3$xhat

#find short term predicted values for 4 periods
Predictedmodel_1= forecast(model_1, 4)#
Predictedmodel_2= forecast(model_2, 4)#
Predictedmodel_3= forecast(model_3, 4)#

#store predicted values in data frame
df2[,1]=11:14
df2[,2]=Predictedmodel_1$fitted
df2[,3]=Predictedmodel_2$fitted
df2[,4]=Predictedmodel_3$fitted

Can somebody help me pls?

Body:
HoltWinters() works better for me, although it gives me sometimes the next warning message:

optimization difficulties: ERROR: ABNORMAL_TERMINATION_IN_LNSRCH

But I found some advise and it seems to work.

Thank you also for that tictoc suggestion!


问:
Regular expression for recognizing url
I want to create a Regex for url in order to get all links from input string.
The Regex should recognize the following formats of the url address:

http(s)://www.webpage.com

http(s)://webpage.com

www.webpage.com

and also the more complicated urls like:
 - http://www.google.pl/#sclient=psy&hl=pl&site=&source=hp&q=regex+url&pbx=1&oq=regex+url&aq=f&aqi=g1&aql=&gs_sm=e&gs_upl=1582l3020l0l3199l9l6l0l0l0l0l255l1104l0.2.3l5l0&bav=on.2,or.r_gc.r_pw.&fp=30a1604d4180f481&biw=1680&bih=935

I have the following one

```<code>((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)
</code>```

but it does not recognize the following pattern: www.webpage.com. Can someone please help me to create an appropriate Regex?

EDIT:
It should works to find an appropriate link and moreover place a link in an appropriate index like this:

```<code>private readonly Regex RE_URL = new Regex(@"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", RegexOptions.Multiline);
foreach (Match match in (RE_URL.Matches(new_text)))
            {
                // Copy raw string from the last position up to the match
                if (match.Index != last_pos)
                {
                    var raw_text = new_text.Substring(last_pos, match.Index - last_pos);
                    text_block.Inlines.Add(new Run(raw_text));
                }

                // Create a hyperlink for the match
                var link = new Hyperlink(new Run(match.Value))
                {
                    NavigateUri = new Uri(match.Value)
                };
                link.Click += OnUrlClick;

                text_block.Inlines.Add(link);

                // Update the last matched position
                last_pos = match.Index + match.Length;
            }
</code>```

答:
I don't know why your result in match is only http:// but I cleaned your regex a bit

```<code>((?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)[\w\d:#@%/;$()~_?\+,\-=\\.&]+)
</code>```

(?:) are non capturing groups, that means there is only one capturing group left and this contains the complete matched string.

(?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.) The link has now to start with something fom the first list followed by an optional www. or with an www.

[\w\d:#@%/;$()~_?\+,\-=\\.&] I added a comma to the list (otherwise your long example does not match) escaped the - (you were creating a character range) and unescaped the . (not needed in a character class.

See this here on Regexr, a useful tool to test regexes.

But URL matching is not a simple task, please see this question here

Title: Regular expression for recognizing url

Body:
I want to create a Regex for url in order to get all links from input string.
The Regex should recognize the following formats of the url address:

http(s)://www.webpage.com

http(s)://webpage.com

www.webpage.com

and also the more complicated urls like:
 - http://www.google.pl/#sclient=psy&hl=pl&site=&source=hp&q=regex+url&pbx=1&oq=regex+url&aq=f&aqi=g1&aql=&gs_sm=e&gs_upl=1582l3020l0l3199l9l6l0l0l0l0l255l1104l0.2.3l5l0&bav=on.2,or.r_gc.r_pw.&fp=30a1604d4180f481&biw=1680&bih=935

I have the following one

((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)

but it does not recognize the following pattern: www.webpage.com. Can someone please help me to create an appropriate Regex?

EDIT:
It should works to find an appropriate link and moreover place a link in an appropriate index like this:

private readonly Regex RE_URL = new Regex(@"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", RegexOptions.Multiline);
foreach (Match match in (RE_URL.Matches(new_text)))
            {
                // Copy raw string from the last position up to the match
                if (match.Index != last_pos)
                {
                    var raw_text = new_text.Substring(last_pos, match.Index - last_pos);
                    text_block.Inlines.Add(new Run(raw_text));
                }

                // Create a hyperlink for the match
                var link = new Hyperlink(new Run(match.Value))
                {
                    NavigateUri = new Uri(match.Value)
                };
                link.Click += OnUrlClick;

                text_block.Inlines.Add(link);

                // Update the last matched position
                last_pos = match.Index + match.Length;
            }

Body:
I don't know why your result in match is only http:// but I cleaned your regex a bit

((?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)[\w\d:#@%/;$()~_?\+,\-=\\.&]+)

(?:) are non capturing groups, that means there is only one capturing group left and this contains the complete matched string.

(?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.) The link has now to start with something fom the first list followed by an optional www. or with an www.

[\w\d:#@%/;$()~_?\+,\-=\\.&] I added a comma to the list (otherwise your long example does not match) escaped the - (you were creating a character range) and unescaped the . (not needed in a character class.

See this here on Regexr, a useful tool to test regexes.

But URL matching is not a simple task, please see this question here


问:
How can I set the IP address value from a URL onto an input field in HTML?
I am loading an 'index.html' page where the URL might be http://127.0.0.1:5000/?ip_address=192.168.2.36.

The variable ip_address can change when I get to index.html.

I have a form with a submit button that should send the value of ip_address to the controller. My goal is to, be default, set the input field box with the variable ip_address and leave it greyed out, so the user only hits the button.

Is there a way I can get that variable from the URL?

答:
The following example displays the client's IP address in a text field and sends it to the server. A possibly used proxy or load balancer is taken into account. However, the display of the correct address is not guaranteed.

If an IP address is already specified in the URL, this will be used to fill in the text field.

```<code>from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    ip_address = request.args.get('ip_address',
        request.headers.get('X-Forwarded-For', request.remote_addr).split(', ')[0])
    return render_template('index.html', **locals())
</code>```
```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>
    <form method="get">
      <input type="text" name="ip_address" value="{{ip_address}}" />
      <input type="submit" />
    </form>
  </body>
</html>
</code>```

Body:
The following example displays the client's IP address in a text field and sends it to the server. A possibly used proxy or load balancer is taken into account. However, the display of the correct address is not guaranteed.

If an IP address is already specified in the URL, this will be used to fill in the text field.

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    ip_address = request.args.get('ip_address',
        request.headers.get('X-Forwarded-For', request.remote_addr).split(', ')[0])
    return render_template('index.html', **locals())

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>
    <form method="get">
      <input type="text" name="ip_address" value="{{ip_address}}" />
      <input type="submit" />
    </form>
  </body>
</html>


问:
Webpack does not save images when a relative image URL is created by Javascript but saves them when the same relative imageURL is in the HTML
When I create an HTML file and I use an image with a relative path, webpack does a good job of saving the file in the dist/images folder as it's instructed to.

However when my JS script adds the same relative image URL then webpack can't seem to find the image and hence I guess is not able to save the image in the dist/images folder

So my question is

Am I doing something wrong in the code below? (I've double checked the paths to the images and even used the original paths in the JS to ensure it's not the path that's wrong)

OR

As the image are loaded by javascript, does this mean that webpack does not save images that are not loaded in the inital HTML file? (I hope this is not true...)

Any advise would be appreciated.

This is my 'template' section in the HTML

```<code>
            <template>
              <div class="card product">
                <div class="card__header">
                  <figure class="product__image">
                    <picture>
                      <img
                        src="./assets/images/product/eyeglass/luxury/chopard/chopard-schf11s.jpg"
                        alt=""
                      />
                    </picture>
                  </figure>
                </div>
                <div class="card__body">
                  <h4 class="product__brand">Chopard</h4>
                  <p class="product__name">Name of the product</p>
                  <!-- <p class="product__description">Description of the product</p> -->
                  <div class="product__rating" data-rating="05">
                    <span class="material-icons" data-rating="05"
                      >star star star star star</span
                    >
                    <span class="product__votes" data-votes="100"
                      >from 100 reviews</span
                    >
                  </div>
                </div>
                <div class="card__footer">
                  <div class="product__price-old">
                    <span class="product__price-delete"
                      ><span class="product__price-inactive">$120</span></span
                    >
                    <span class="product__price">$120</span>
                  </div>
                  <button>Buy Now</button>
                </div>
              </div>
            </template>

</code>```

and this is my JS

```<code>
const cardTemplate = document.querySelector("template");
const cards = document.querySelector(".cards");

// deleted the text where the productObject was created to save space

export function displayProductCards() {
  console.log(cards);
  productObjects.forEach((product) => {
    const card = cardTemplate.content.cloneNode(true).children[0];

    const productName = card.querySelector(".product__name");
    const productBrand = card.querySelector(".product__brand");
    const productImage = card.querySelector(".product__image>picture>img");
    // const productDescription = card.querySelector(".product__description");
    const productPrice = card.querySelector(".product__price");
    const productRating = card.querySelector(
      ".product__rating>span.material-icons"
    );
    const productVotes = card.querySelector(".product__votes");

    // const imgUrl = `./assets/images/product/${product.category.toLowerCase()}/${product.subCategory.toLowerCase()}/${
    //   product.brandShortname
    // }/${product.image}`;

    const imgUrl = `./assets/images/product/eyeglass/luxury/chopard/chopard-schf11s.jpg`;

    productName.textContent = product.name;
    productBrand.textContent = product.brand;
    productImage.src = imgUrl;
    productPrice.textContent = product.price;
    productRating.setAttribute("data-rating", product.rating);
    productRating.textContent = setRating(product.rating);
    productVotes.textContent = `from ${product.votes} votes`;

    cards.appendChild(card);
  });
}

function setRating(x) {
  let stars = "";
  for (let i = 0; i < +x; i++) {
    stars += "star ";
  }

  return stars.trim();
}

</code>```

and this is my webpack config file

```<code>
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  mode: "development",
  entry: "./src/main.js",
  output: {
    publicPath: "",
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
    assetModuleFilename: "./images/[name][ext][query]",
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
    }),
    new MiniCssExtractPlugin({ filename: "[name].css" }),
  ],
  module: {
    rules: [
      {
        test: /\.s?css$/,
        // use: ["style-loader", "css-loader", "sass-loader"],
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
      {
        test: /\.html$/,
        use: ["html-loader"],
      },
      {
        test: /\.(svg|png|jpg|jpeg|gif)$/,
        type: "asset/resource",
      },
    ],
  },
};

</code>```

答:
This answer is mainly for me in the future if I run into this issue again and for those like me who might be on the same learning path sometime in the future.

So my understanding was that webpack would automatically save all images in the dist/images folder as I had defined in webpack config file

```<code>  output: {
    publicPath: "",
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
    assetModuleFilename: "./images/[name][ext][query]",
  },

</code>```

However what I was doing in the JS file was simulating a fetch action where I'd get JSON data and populate the src attribute of all images in the product cards. Expecting these images to be stored in the dist/images folder does not seem logical now in hindsight so basically my expectation was not right. If webpack were to really store all such images in the dist/images folder it would be a huge folder each time I would dynamically fetch a JSON to show all my images on the online store.

So firstly my expectations were not logical and secondly I missed out on this message that was displayed when webpack-dev-server was run ..

```<code><i> [webpack-dev-server] Content not from webpack is served from '/Applications/MAMP/htdocs/sunshyn-optical-store/public' directory

</code>```

So basically the reason for my images to not show up on the displayed site on localhost was NOT because the images were not being stored in the dist/images folder (which anyways should not be stored there) but because the public path for all relative images was a public folder path that webpack was generating.

So I created a public folder and added the assets folder in the public folder and the missing link was fixed. The images showed up fine.

So when expecting to see images that are dynamically updated on the html, ensure that the path exists either by providing absolute paths or ensuring that the relative path is in relation to the public folder.

Body:
When I create an HTML file and I use an image with a relative path, webpack does a good job of saving the file in the dist/images folder as it's instructed to.

However when my JS script adds the same relative image URL then webpack can't seem to find the image and hence I guess is not able to save the image in the dist/images folder

So my question is

Am I doing something wrong in the code below? (I've double checked the paths to the images and even used the original paths in the JS to ensure it's not the path that's wrong)

OR

As the image are loaded by javascript, does this mean that webpack does not save images that are not loaded in the inital HTML file? (I hope this is not true...)

Any advise would be appreciated.

This is my 'template' section in the HTML

            <template>

                    <picture>

                    </picture>

Chopard

Name of the product

                    star star star star star
                    from 100 reviews

                    $120
                    $120

                  <button>Buy Now</button>

            </template>

and this is my JS

const cardTemplate = document.querySelector("template");
const cards = document.querySelector(".cards");

// deleted the text where the productObject was created to save space

export function displayProductCards() {
  console.log(cards);
  productObjects.forEach((product) => {
    const card = cardTemplate.content.cloneNode(true).children[0];

    const productName = card.querySelector(".product__name");
    const productBrand = card.querySelector(".product__brand");
    const productImage = card.querySelector(".product__image>picture>img");
    // const productDescription = card.querySelector(".product__description");
    const productPrice = card.querySelector(".product__price");
    const productRating = card.querySelector(
      ".product__rating>span.material-icons"
    );
    const productVotes = card.querySelector(".product__votes");

    // const imgUrl = `./assets/images/product/${product.category.toLowerCase()}/${product.subCategory.toLowerCase()}/${
    //   product.brandShortname
    // }/${product.image}`;

    const imgUrl = `./assets/images/product/eyeglass/luxury/chopard/chopard-schf11s.jpg`;

    productName.textContent = product.name;
    productBrand.textContent = product.brand;
    productImage.src = imgUrl;
    productPrice.textContent = product.price;
    productRating.setAttribute("data-rating", product.rating);
    productRating.textContent = setRating(product.rating);
    productVotes.textContent = `from ${product.votes} votes`;

    cards.appendChild(card);
  });
}

function setRating(x) {
  let stars = "";
  for (let i = 0; i < +x; i++) {
    stars += "star ";
  }

  return stars.trim();
}

and this is my webpack config file

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  mode: "development",
  entry: "./src/main.js",
  output: {
    publicPath: "",
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
    assetModuleFilename: "./images/[name][ext][query]",
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
    }),
    new MiniCssExtractPlugin({ filename: "[name].css" }),
  ],
  module: {
    rules: [
      {
        test: /\.s?css$/,
        // use: ["style-loader", "css-loader", "sass-loader"],
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
      {
        test: /\.html$/,
        use: ["html-loader"],
      },
      {
        test: /\.(svg|png|jpg|jpeg|gif)$/,
        type: "asset/resource",
      },
    ],
  },
};

Body:
This answer is mainly for me in the future if I run into this issue again and for those like me who might be on the same learning path sometime in the future.

So my understanding was that webpack would automatically save all images in the dist/images folder as I had defined in webpack config file

  output: {
    publicPath: "",
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
    assetModuleFilename: "./images/[name][ext][query]",
  },

However what I was doing in the JS file was simulating a fetch action where I'd get JSON data and populate the src attribute of all images in the product cards. Expecting these images to be stored in the dist/images folder does not seem logical now in hindsight so basically my expectation was not right. If webpack were to really store all such images in the dist/images folder it would be a huge folder each time I would dynamically fetch a JSON to show all my images on the online store.

So firstly my expectations were not logical and secondly I missed out on this message that was displayed when webpack-dev-server was run ..

<i> [webpack-dev-server] Content not from webpack is served from '/Applications/MAMP/htdocs/sunshyn-optical-store/public' directory

So basically the reason for my images to not show up on the displayed site on localhost was NOT because the images were not being stored in the dist/images folder (which anyways should not be stored there) but because the public path for all relative images was a public folder path that webpack was generating.

So I created a public folder and added the assets folder in the public folder and the missing link was fixed. The images showed up fine.

So when expecting to see images that are dynamically updated on the html, ensure that the path exists either by providing absolute paths or ensuring that the relative path is in relation to the public folder.


问:
Regex to split text with hyphen points
Suppose that we have the following string:

'We need the list fo the following products: - Abcd efgh ejklm - Efgh-ij sklrm, defasad - KLMNNOP/QRS dasfdssa eadsd'

I want a regex that return:

```<code>- Abcd efgh, ejklm
- Efgh-ij sklrm, defasad
- KLMNNOP/QRS dasfdssa eadsd
</code>```

I write this one that works correctly but it cuts if we have a composed word.

```<code>import re
regx = '-\s[\w\s\/?,;!:#&@]*' # start with hyphen + space + mix of different characters
z = re.findall(regx, 'We need the list fo the following products: - Abcd - Efgh-ij - KLMNNOP/QRS')
for p in z:
    print(p)

- Abcd efgh, ejklm
- Efgh
- KLMNNOP/QRS dasfdssa eadsd
</code>```

答:
You could repeat matching either the current character class, or only a hyphen followed by word characters

```<code>-\s(?:[\w\s/?,;!:#&@]+|-\w+)+
</code>```

See a regex demo and a Python demo.

If you don't want to match empty parts, you can change the quantifier for the character class to + to match 1 or more times.

Example

```<code>import re
regx = '-\s(?:[\w\s/?,;!:#&@]+|-\w+)+'
z = re.findall(regx, 'We need the list fo the following products: - Abcd efgh ejklm - Efgh-ij sklrm, defasad - KLMNNOP/QRS dasfdssa eadsd')
for p in z:
    print(p)
</code>```

Output

```<code>- Abcd efgh ejklm
- Efgh-ij sklrm, defasad
- KLMNNOP/QRS dasfdssa eadsd
</code>```

Or a bit broader match instead of only word characters:

```<code>-\s(?:[\w\s/?,;!:#&@]+|-[\w/?,;!:#&@]+)+
</code>```

Title: Regex to split text with hyphen points

Body:
Suppose that we have the following string:

'We need the list fo the following products: - Abcd efgh ejklm - Efgh-ij sklrm, defasad - KLMNNOP/QRS dasfdssa eadsd'

I want a regex that return:

- Abcd efgh, ejklm
- Efgh-ij sklrm, defasad
- KLMNNOP/QRS dasfdssa eadsd

I write this one that works correctly but it cuts if we have a composed word.

import re
regx = '-\s[\w\s\/?,;!:#&@]*' # start with hyphen + space + mix of different characters
z = re.findall(regx, 'We need the list fo the following products: - Abcd - Efgh-ij - KLMNNOP/QRS')
for p in z:
    print(p)

- Abcd efgh, ejklm
- Efgh
- KLMNNOP/QRS dasfdssa eadsd

Body:
You could repeat matching either the current character class, or only a hyphen followed by word characters

-\s(?:[\w\s/?,;!:#&@]+|-\w+)+

See a regex demo and a Python demo.

If you don't want to match empty parts, you can change the quantifier for the character class to + to match 1 or more times.

Example

import re
regx = '-\s(?:[\w\s/?,;!:#&@]+|-\w+)+'
z = re.findall(regx, 'We need the list fo the following products: - Abcd efgh ejklm - Efgh-ij sklrm, defasad - KLMNNOP/QRS dasfdssa eadsd')
for p in z:
    print(p)

Output

- Abcd efgh ejklm
- Efgh-ij sklrm, defasad
- KLMNNOP/QRS dasfdssa eadsd

Or a bit broader match instead of only word characters:

-\s(?:[\w\s/?,;!:#&@]+|-[\w/?,;!:#&@]+)+


答:
Using a while loop you can just keep track of the current value of the savings and in each step compare if the current value already reached the goal:</p>
```<code>def my_saving_plan(P0, i, goal):
    current_value = P0
    P = [P0]
    years = 0
    while current_value < goal:
        years += 1
        current_value *= (1 + i)
        P.append(current_value)
    print(P)

    return years
</code>```

Body:
I want to calculate the time it takes for the compound interest to reach a certain goal by using Pn=(1+i)Pn−1.
What I have done is:

def my_saving_plan(P0,i,goal):
    P = [P0]
    years = 0
    for n in range(0,10000):
        if P[n] < goal:
            P.append((1+i)*P[n-1])
            years += 1
            print(P)
        elif P[n] >= goal:
            return years
print(my_saving_plan(1000, 0.07, 2000))

But What I get from that is the number of compound interest twice. So for this example what I get is:

    [1000, 1070.0, 1070.0, 1144.9, 1144.9, 1225.0430000000001,
1225.0430000000001, 1310.7960100000003, 1310.7960100000003,
1402.5517307000005, 1402.5517307000005, 1500.7303518490005,
1500.7303518490005, 1605.7814764784307, 1605.7814764784307,
 1718.186179831921, 1718.186179831921, 1838.4592124201556,
1838.4592124201556, 1967.1513572895667, 1967.1513572895667,
2104.8519522998363]
    21

Also I was wondering if there is a way to use a while loop instead of putting a ridiculous number in the for loop.

Body:
Using a while loop you can just keep track of the current value of the savings and in each step compare if the current value already reached the goal:

def my_saving_plan(P0, i, goal):
    current_value = P0
    P = [P0]
    years = 0
    while current_value < goal:
        years += 1
        current_value *= (1 + i)
        P.append(current_value)
    print(P)

    return years


问:
How to apply updateItem to multiple/all items in Ngxs?
I need an alternative to change the same attribute, with the same value, for all items in an array in Ngxs.

I tried to use updateItem(() => true, patch({ ... })), but it doesn't work because the first function, () => true, just returns the first match and ends up updating only a single item.

The following is a simplified example of what I tried to do:

import { State, Action, StateContext } from '@ngxs/store';
import { patch, append, removeItem, insertItem, updateItem } from '@ngxs/store/operators';

export interface AnimalsStateModel {
  others: { /*...*/ }[];
  rabbits: Rabbit[];
}

export interface Rabbit {
  name: string,
  alive: boolean,
}

export class ChangeRabbitAlive {
  static readonly type = '[Animals] Change rabbit alive';
  constructor(public payload: { name: string; alive: boolean }) {}
}

export class ChangeAllRabbitsDead {
  static readonly type = '[Animals] Change all rabbits dead';
  constructor(public payload: { }) {}
}

@State<AnimalsStateModel>({
  name: 'animals',
  defaults: {
    others: [ /*...*/ ],
    rabbits: [
      { name: 'Michael', alive: true },
      { name: 'John', alive: true },
      { name: 'Jimmy', alive: true },
      { name: 'Jake', alive: true },
      { name: 'Alan', alive: true },
    ]
  }
})
export class AnimalsState {

  @Action(ChangeRabbitAlive)
  changeRabbitAlive(ctx: StateContext<AnimalsStateModel>, { payload }: ChangeRabbitAlive) {
    ctx.setState(
      patch({
        rabbits: updateItem<Rabbit>(rabbit => rabbit.name === payload.name, patch({ alive: payload.alive }))
      })
    );
  }

  @Action(ChangeAllRabbitsDead)
  changeAllRabbitsDead(ctx: StateContext<AnimalsStateModel>, { payload }: ChangeAllRabbitsDead) {
    const isAlive = { alive: false };
    ctx.setState(
      patch({
        //rabbits: updateItem<Rabbit>(name => true, patch({ alive: false }))// Type 'boolean' is not assignable to type 'false'
        rabbits: updateItem<Rabbit>(() => true, patch(isAlive))
      })
    );
  }
}
```

Is there any way to kill all the rabbits at once?

Extra: If you could explain why the error "Type 'boolean' is not assignable to type 'false'" occurs in that situation, that would also be appreciated.

答:
Not sure if it is the prettiest way of doing it, but conceptually:</p>
```<code>let state2 = {
  ...state,
  rabbits: state.rabbits.map(x => {
    return {
      name: x.name,
      alive: false
    }
  })
}
</code>```

Body:
I need an alternative to change the same attribute, with the same value, for all items in an array in Ngxs.

I tried to use updateItem(() => true, patch({ ... })), but it doesn't work because the first function, () => true, just returns the first match and ends up updating only a single item.

The following is a simplified example of what I tried to do:

import { State, Action, StateContext } from '@ngxs/store';
import { patch, append, removeItem, insertItem, updateItem } from '@ngxs/store/operators';

export interface AnimalsStateModel {
  others: { /*...*/ }[];
  rabbits: Rabbit[];
}

export interface Rabbit {
  name: string,
  alive: boolean,
}

export class ChangeRabbitAlive {
  static readonly type = '[Animals] Change rabbit alive';
  constructor(public payload: { name: string; alive: boolean }) {}
}

export class ChangeAllRabbitsDead {
  static readonly type = '[Animals] Change all rabbits dead';
  constructor(public payload: { }) {}
}

@State<AnimalsStateModel>({
  name: 'animals',
  defaults: {
    others: [ /*...*/ ],
    rabbits: [
      { name: 'Michael', alive: true },
      { name: 'John', alive: true },
      { name: 'Jimmy', alive: true },
      { name: 'Jake', alive: true },
      { name: 'Alan', alive: true },
    ]
  }
})
export class AnimalsState {

  @Action(ChangeRabbitAlive)
  changeRabbitAlive(ctx: StateContext<AnimalsStateModel>, { payload }: ChangeRabbitAlive) {
    ctx.setState(
      patch({
        rabbits: updateItem<Rabbit>(rabbit => rabbit.name === payload.name, patch({ alive: payload.alive }))
      })
    );
  }

  @Action(ChangeAllRabbitsDead)
  changeAllRabbitsDead(ctx: StateContext<AnimalsStateModel>, { payload }: ChangeAllRabbitsDead) {
    const isAlive = { alive: false };
    ctx.setState(
      patch({
        //rabbits: updateItem<Rabbit>(name => true, patch({ alive: false }))// Type 'boolean' is not assignable to type 'false'
        rabbits: updateItem<Rabbit>(() => true, patch(isAlive))
      })
    );
  }
}

Is there any way to kill all the rabbits at once?

Extra: If you could explain why the error "Type 'boolean' is not assignable to type 'false'" occurs in that situation, that would also be appreciated.

Body:
Not sure if it is the prettiest way of doing it, but conceptually:

let state2 = {
  ...state,
  rabbits: state.rabbits.map(x => {
    return {
      name: x.name,
      alive: false
    }
  })
}


问:
Php how to convert a date time string in French back to its equivalent in English UTC
I have this date time string vendredi 11 février 2022 à 20:19:56 heure normale d’Europe centrale stored in my database.

Now I'm trying to convert it back to its equivalent in English UTC date time.

In order to process it, I tried strtotime:

$datetime = 'vendredi 11 février 2022 à 20:19:56 heure normale d’Europe centrale';

$tsparis = strtotime($datetime . ' Europe/Paris');

var_dump($tsparis);
```

This shows bool(false). How can I parse this string back to a timestamp.

答:
You can use IntlDateFormatter to parse dates from strings as well as format them to strings.

In this case, passing a locale of 'fr_FR', and date and time formats of "full" should be enough:

```<code>$datetime = 'vendredi 11 février 2022 à 20:19:56 heure normale d’Europe centrale';

$parser = new IntlDateFormatter(
    'fr_FR',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL
);
$tsparis = $parser->parse($datetime);

var_dump($tsparis);
</code>```

Gives int(1644607196); see online demo

This gives you a standard Unix timestamp, which you can process using whatever you want to generate a new output.

Body:
I have this date time string vendredi 11 février 2022 à 20:19:56 heure normale d’Europe centrale stored in my database.

Now I'm trying to convert it back to its equivalent in English UTC date time.

In order to process it, I tried strtotime:

$datetime = 'vendredi 11 février 2022 à 20:19:56 heure normale d’Europe centrale';

$tsparis = strtotime($datetime . ' Europe/Paris');

var_dump($tsparis);

This shows bool(false). How can I parse this string back to a timestamp.

Body:
You can use IntlDateFormatter to parse dates from strings as well as format them to strings.

In this case, passing a locale of 'fr_FR', and date and time formats of "full" should be enough:

$datetime = 'vendredi 11 février 2022 à 20:19:56 heure normale d’Europe centrale';

$parser = new IntlDateFormatter(
    'fr_FR',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL
);
$tsparis = $parser->parse($datetime);

var_dump($tsparis);

Gives int(1644607196); see online demo

This gives you a standard Unix timestamp, which you can process using whatever you want to generate a new output.


问:
A rule from .eslintrc.json isn't being respected, but the same rule in an eslint comment is
The rule "react-redux/useSelector-prefer-selectors" isn't being respected when I put it in my .eslintrc.json, but other rules are. However, when I put

```<code>/* eslint react-redux/useSelector-prefer-selectors: "off" */
</code>```

At the top of the offending file, the error goes away.

My .eslintrc.json file (In my root directory):

```<code>{
  "env": {
    "browser": true,
    "commonjs": true,
    "es2020": true,
    "node": false
  },
  "extends": [
    "airbnb",
    "react-app",
    "airbnb/hooks",
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:react-hooks/recommended",
    "plugin:react-redux/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": 12,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "plugins": [
    "react",
    "react-redux"
  ],
  "rules": {
    "indent": [
      "warn",
      "tab"
    ],
    "no-tabs": "off",
    "no-unused-vars": "warn",
    "consistent-return": "warn",
    "no-mixed-spaces-and-tabs": 0,
    "react/prop-types": 0,
    "unused-imports/no-unused-imports": "off",
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn",
    "react-redux/useSelector-prefer-selectors": "off",
    "react/jsx-indent": "off",
    "react/jsx-filename-extension": "off",
    "react/jsx-no-useless-fragment": "warn"
  }
}
</code>```

答:
Figured it out thanks to a comment by @guiwme5. While I don't use vscode, I do use WebStorm - and it seems they both have the same issue - they don't reload .eslintrc.* files when they change.

So if you stumble across this trying to figure out why your IDE isn't respecting your eslint rules, try restarting the IDE.

Body:
The rule "react-redux/useSelector-prefer-selectors" isn't being respected when I put it in my .eslintrc.json, but other rules are. However, when I put

/* eslint react-redux/useSelector-prefer-selectors: "off" */

At the top of the offending file, the error goes away.

My .eslintrc.json file (In my root directory):

{
  "env": {
    "browser": true,
    "commonjs": true,
    "es2020": true,
    "node": false
  },
  "extends": [
    "airbnb",
    "react-app",
    "airbnb/hooks",
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:react-hooks/recommended",
    "plugin:react-redux/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": 12,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "plugins": [
    "react",
    "react-redux"
  ],
  "rules": {
    "indent": [
      "warn",
      "tab"
    ],
    "no-tabs": "off",
    "no-unused-vars": "warn",
    "consistent-return": "warn",
    "no-mixed-spaces-and-tabs": 0,
    "react/prop-types": 0,
    "unused-imports/no-unused-imports": "off",
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn",
    "react-redux/useSelector-prefer-selectors": "off",
    "react/jsx-indent": "off",
    "react/jsx-filename-extension": "off",
    "react/jsx-no-useless-fragment": "warn"
  }
}