问:
How do I find the mean value of a dictionary of dictionaries?
New to coding and don't have my friend to help me atm. My current question - I have a dictionary of dictionaries with a mixture of values and 'masked'. I need to find the mean of all of the values that are not masked. Below is the code that I've created in order to get a dictionary of observations:

```<code>path_2 = "/Volumes/TRANSEND/Thesis Files/Utqiagvik Obs Ceilometer/"

#fn = '/Volumes/TRANSEND/Thesis Files/Oliktok Obs/oli30smplcmask1zwangM1.c1.20191001.000006.custom.nc'
#sd = nc.Dataset(fn)

obs = {} # largest dictionary with all of the days and then observations. Pass through a day and an hour to get an obs

for file in os.listdir(path_2):

    obs_day = {} # secondary dictionary for each day. Includes all the hours. Pass through an hour to get an obs
    index = hour = 0

    hour_indices = []

# or file == "OliktokObs.py" add back in if you go back to oliktok
    if file == "OliktokObs.py" or file == ".DS_Store" or file == "nsaceilC1.b1.20190930.000000.custom.nc" or file == "nsaceilC1.b1.20191103.000013.custom.nc":
        prev_file = file
        continue

    fn = "/Volumes/TRANSEND/Thesis Files/Utqiagvik Obs Ceilometer/" + file

    sd = nc.Dataset(fn)

# This creates a preamble to be able to extract the day from the filename
    preamble_3 = 'b1.'
    index_3 = file.index(preamble_3)
    obs_date = file[index_3 + len(preamble_3) : index_3 + len(preamble_3) + 8]

# This adds the observations for each hour into the corresponding dictionary. Averages the cloud base ten minutes before and ten minutes after the hour.
    for time in sd['time']:

        if int(time) % 3600 < 30 and hour != 24:
            clear_count = 0
            hour_indices.append(index)
            average_value = []
            if hour == 0:
                sd_prev = nc.Dataset("/Volumes/TRANSEND/Thesis Files/Utqiagvik Obs Ceilometer/" + prev_file)
                for i in range(20):
                    if not np.ma.is_masked(sd_prev['first_cbh'][len(sd_prev['first_cbh']) - 20 + i]):
                        average_value.append(sd_prev['first_cbh'][len(sd_prev['first_cbh']) - 20 + i])
                    if not np.ma.is_masked(sd['first_cbh'][i]):
                        average_value.append(sd['first_cbh'][i])
            else:
                for i in range(40):
                    if not np.ma.is_masked(sd['first_cbh'][index - 20 + i]):
                        average_value.append(sd['first_cbh'][index - 20 + i])

            if len(average_value) < 20: # wtf does this line/chunk of code mean i totally forgot
                obs_day[hour] = np.ma.masked
            else:
                obs_day[hour] = np.asarray(average_value).mean()

            #print("Day: " + str(obs_date) + ", Hour: " + str(hour) +  ", Cloud Base: " + str(sd['cloud_base'][index]*1000))
            hour += 1

        index += 1

    obs[obs_date] = obs_day
    prev_file = file

print(obs)
</code>```

And below is a sample of what is output. I have output for every day of Oct 2019:

```<code>    {'20191001': {0: 163.0, 1: 271.75, 2: 1933.0, 3: 393.0, 4: 726.5, 5: 808.91895, 6: 639.4595, 7: 634.25, 8: 763.8461, 9: 745.64105, 10: 537.75, 11: 539.25, 12: 561.75, 13: 563.25, 14: 387.75, 15: 325.25, 16: 324.25, 17: 444.75, 18: 444.25, 19: 286.0, 20: 282.5, 21: 249.25, 22: 253.25, 23: 691.94446},
     '20191002': {0: masked, 1: masked, 2: 668.0, 3: 668.0, 4: 907.0, 5: 907.75, 6: 849.0, 7: 846.0, 8: 718.5, 9: 721.5, 10: 832.25, 11: 831.5, 12: 5189.048, 13: 5122.0, 14: 5680.0, 15: 5677.5, 16: 665.1852, 17: 664.61536, 18: masked, 19: masked, 20: masked, 21: masked, 22: masked, 23: masked},
     '20191003': {0: 96.5, 1: 89.52381, 2: 77.57576, 3: 77.57576, 4: masked, 5: masked, 6: masked, 7: masked, 8: masked, 9: masked, 10: masked, 11: masked, 12: masked, 13: masked, 14: masked, 15: masked, 16: 80.26316, 17: 80.789474, 18: 79.375, 19: 79.09091, 20: 103.25, 21: 102.25, 22: masked, 23: masked}}
</code>```

The largest dictionary is called 'obs' and I pass through a date to get the corresponding dictionary for that day. The secondary dictionary is called 'obs_day' and I pass through a forecast hour to get the cloud base height for that hour on that day.

My goal is to try to calculate the average of all of the values that are not masked so that I can see what the average cloud base height is for the entire month (when there is a cloud base). Are there any suggestions of how average all of the values that are not masked?

I've tried:

```<code>    for date in obs:
        res = statistics.mean(list(obs_day.values()))
        print(res)
</code>```

And gotten:

```<code>    AttributeError                            Traceback (most recent call last)
    Input In [11], in <cell line: 1>()
          1 for date in obs:
    ----> 2     res = statistics.mean(list(obs_day.values()))
          3     print(res)

    AttributeError: 'str' object has no attribute 'values'
</code>```

I've also just tried

```<code>res = {day: statistics.mean(v for v in data.values() if v != "masked") for day, data in obs.items()}
</code>```

and gotten

```<code>StatisticsError                           Traceback (most recent call last)
Input In [5], in <cell line: 1>()
----> 1 res = {day: statistics.mean(v for v in data.values() if v != "masked") for day, data in obs.items()}

Input In [5], in <dictcomp>(.0)
----> 1 res = {day: statistics.mean(v for v in data.values() if v != "masked") for day, data in obs.items()}

File ~/miniconda3/lib/python3.9/statistics.py:315, in mean(data)
    313 n = len(data)
    314 if n < 1:
--> 315     raise StatisticsError('mean requires at least one data point')
    316 T, total, count = _sum(data)
    317 assert count == n

StatisticsError: mean requires at least one data point
</code>```

Body:
New to coding and don't have my friend to help me atm. My current question - I have a dictionary of dictionaries with a mixture of values and 'masked'. I need to find the mean of all of the values that are not masked. Below is the code that I've created in order to get a dictionary of observations:

path_2 = "/Volumes/TRANSEND/Thesis Files/Utqiagvik Obs Ceilometer/"

#fn = '/Volumes/TRANSEND/Thesis Files/Oliktok Obs/oli30smplcmask1zwangM1.c1.20191001.000006.custom.nc'
#sd = nc.Dataset(fn)

obs = {} # largest dictionary with all of the days and then observations. Pass through a day and an hour to get an obs

for file in os.listdir(path_2):

    obs_day = {} # secondary dictionary for each day. Includes all the hours. Pass through an hour to get an obs
    index = hour = 0

    hour_indices = []

# or file == "OliktokObs.py" add back in if you go back to oliktok
    if file == "OliktokObs.py" or file == ".DS_Store" or file == "nsaceilC1.b1.20190930.000000.custom.nc" or file == "nsaceilC1.b1.20191103.000013.custom.nc":
        prev_file = file
        continue

    fn = "/Volumes/TRANSEND/Thesis Files/Utqiagvik Obs Ceilometer/" + file

    sd = nc.Dataset(fn)

# This creates a preamble to be able to extract the day from the filename
    preamble_3 = 'b1.'
    index_3 = file.index(preamble_3)
    obs_date = file[index_3 + len(preamble_3) : index_3 + len(preamble_3) + 8]

# This adds the observations for each hour into the corresponding dictionary. Averages the cloud base ten minutes before and ten minutes after the hour.
    for time in sd['time']:

        if int(time) % 3600 < 30 and hour != 24:
            clear_count = 0
            hour_indices.append(index)
            average_value = []
            if hour == 0:
                sd_prev = nc.Dataset("/Volumes/TRANSEND/Thesis Files/Utqiagvik Obs Ceilometer/" + prev_file)
                for i in range(20):
                    if not np.ma.is_masked(sd_prev['first_cbh'][len(sd_prev['first_cbh']) - 20 + i]):
                        average_value.append(sd_prev['first_cbh'][len(sd_prev['first_cbh']) - 20 + i])
                    if not np.ma.is_masked(sd['first_cbh'][i]):
                        average_value.append(sd['first_cbh'][i])
            else:
                for i in range(40):
                    if not np.ma.is_masked(sd['first_cbh'][index - 20 + i]):
                        average_value.append(sd['first_cbh'][index - 20 + i])

            if len(average_value) < 20: # wtf does this line/chunk of code mean i totally forgot
                obs_day[hour] = np.ma.masked
            else:
                obs_day[hour] = np.asarray(average_value).mean()

            #print("Day: " + str(obs_date) + ", Hour: " + str(hour) +  ", Cloud Base: " + str(sd['cloud_base'][index]*1000))
            hour += 1

        index += 1

    obs[obs_date] = obs_day
    prev_file = file

print(obs)

And below is a sample of what is output. I have output for every day of Oct 2019:

    {'20191001': {0: 163.0, 1: 271.75, 2: 1933.0, 3: 393.0, 4: 726.5, 5: 808.91895, 6: 639.4595, 7: 634.25, 8: 763.8461, 9: 745.64105, 10: 537.75, 11: 539.25, 12: 561.75, 13: 563.25, 14: 387.75, 15: 325.25, 16: 324.25, 17: 444.75, 18: 444.25, 19: 286.0, 20: 282.5, 21: 249.25, 22: 253.25, 23: 691.94446},
     '20191002': {0: masked, 1: masked, 2: 668.0, 3: 668.0, 4: 907.0, 5: 907.75, 6: 849.0, 7: 846.0, 8: 718.5, 9: 721.5, 10: 832.25, 11: 831.5, 12: 5189.048, 13: 5122.0, 14: 5680.0, 15: 5677.5, 16: 665.1852, 17: 664.61536, 18: masked, 19: masked, 20: masked, 21: masked, 22: masked, 23: masked},
     '20191003': {0: 96.5, 1: 89.52381, 2: 77.57576, 3: 77.57576, 4: masked, 5: masked, 6: masked, 7: masked, 8: masked, 9: masked, 10: masked, 11: masked, 12: masked, 13: masked, 14: masked, 15: masked, 16: 80.26316, 17: 80.789474, 18: 79.375, 19: 79.09091, 20: 103.25, 21: 102.25, 22: masked, 23: masked}}

The largest dictionary is called 'obs' and I pass through a date to get the corresponding dictionary for that day. The secondary dictionary is called 'obs_day' and I pass through a forecast hour to get the cloud base height for that hour on that day.

My goal is to try to calculate the average of all of the values that are not masked so that I can see what the average cloud base height is for the entire month (when there is a cloud base). Are there any suggestions of how average all of the values that are not masked?

I've tried:

    for date in obs:
        res = statistics.mean(list(obs_day.values()))
        print(res)

And gotten:

    AttributeError                            Traceback (most recent call last)
    Input In [11], in <cell line: 1>()
          1 for date in obs:
    ----> 2     res = statistics.mean(list(obs_day.values()))
          3     print(res)

    AttributeError: 'str' object has no attribute 'values'

I've also just tried

res = {day: statistics.mean(v for v in data.values() if v != "masked") for day, data in obs.items()}

and gotten

StatisticsError                           Traceback (most recent call last)
Input In [5], in <cell line: 1>()
----> 1 res = {day: statistics.mean(v for v in data.values() if v != "masked") for day, data in obs.items()}

Input In [5], in <dictcomp>(.0)
----> 1 res = {day: statistics.mean(v for v in data.values() if v != "masked") for day, data in obs.items()}

File ~/miniconda3/lib/python3.9/statistics.py:315, in mean(data)
    313 n = len(data)
    314 if n < 1:
--> 315     raise StatisticsError('mean requires at least one data point')
    316 T, total, count = _sum(data)
    317 assert count == n

StatisticsError: mean requires at least one data point


来源: stackexchange

问:
Is there an efficient way to import binary data from mysql database to Postgresql?
I can use mysqldump and psql to import common data into the postgresql database. However, binary data is blob in mysql and bytea in postgresql. Import cannot be done using mysqldump and psql tools.</p>

ContentLicense: CC BY-SA 4.0


问:
Problem with test keys of a snapshot.value
I have this solution that works, but I don’t want to take any risks with import problems in Firebase. I want to verify that the [Nom], [Prenom], [Club], [Cat], [License] and [Selected] keys exist in dtlSnapdict. I couldn’t find a solution that worked
Do you have an idea
Thank you very much for your help
Best regards
Georges</p>
```<code> if let snapDict = snapshot.value as? [String:AnyObject]{

    for dtlSnapdict in snapDict as [String:AnyObject]{
        self.contenuliste.removeAll()
        self.nom = dtlSnapdict.value["Nom"] as! String
        self.prenom = dtlSnapdict.value["Prenom"] as! String
        self.club = dtlSnapdict.value["Club"] as! Int
        self.cat = dtlSnapdict.value["Cat"] as! String
        self.licence = dtlSnapdict.value["Licence"] as! Int
        self.selected = dtlSnapdict.value["Selected"] as! String
</code>```

Body:
I have this solution that works, but I don’t want to take any risks with import problems in Firebase. I want to verify that the [Nom], [Prenom], [Club], [Cat], [License] and [Selected] keys exist in dtlSnapdict. I couldn’t find a solution that worked
Do you have an idea
Thank you very much for your help
Best regards
Georges

 if let snapDict = snapshot.value as? [String:AnyObject]{

    for dtlSnapdict in snapDict as [String:AnyObject]{
        self.contenuliste.removeAll()
        self.nom = dtlSnapdict.value["Nom"] as! String
        self.prenom = dtlSnapdict.value["Prenom"] as! String
        self.club = dtlSnapdict.value["Club"] as! Int
        self.cat = dtlSnapdict.value["Cat"] as! String
        self.licence = dtlSnapdict.value["Licence"] as! Int
        self.selected = dtlSnapdict.value["Selected"] as! String


问:
I'm having a problem updating state from a listener call back
i'm adding a chat feature to our site using GetStream's chat.  I'm trying to create a count badge on a button similar to FB, Twitter, IG, etc that displays the total of unread messages.   GetStream has an event listener to support this.  It's working, but it's not consistent.  If a user gets a new message, it shows the new badge and count.  But, if I navigate to any view other than the chat window, my count goes away.  If I hit refresh, it comes back.  Then... if I navigate around, it stays.   However, if I get a 2nd message, the count updates to 2, but if I navigate around, it's still at 1 until I refresh, and then it shows 2.  Also, it should reset to 0 after navigating to the chat.  It does not.. but if I refresh, it does.   So, clearly, I'm not updating state properly.   Can someone smarter than me tell me what I'm doing wrong?  Oh... and I'm using this as a hook, but I could move this code into the component if needed.  Here's the gist:</p>
```<code>const useUnreadMessagesCount = () => {
    const { user } = useAuth()
    const { client: chatClient } = useChatContext()
    const [unreadCount, setUnreadCount] = useState<any>()
    const { token } = useStreamToken()

    useEffect(() => {
        async function init() {
            // set state initially because it appers that client.on events only happen a new event.
            if (user != null) {
                const response: any = await chatClient.connectUser({ id: user.uid }, token)
                setUnreadCount(response.me.total_unread_count)
            }

            // update state when a new event occures.
            chatClient.on((event) => {
                console.log("HERE")
                if (event.unread_channels !== undefined) {
                    console.log("COUNT: ", event.total_unread_count)
                    setUnreadCount(event.total_unread_count)
                }
            })
        }

        init()

        // @ts-ignore
        chatClient.on("user.presence.changed", init())

        return () => {
            // @ts-ignore
            chatClient.off("user.presence.changed", init())
        }
    }, [chatClient])

    return unreadCount
}

export default useUnreadMessagesCount
</code>```

Body:
i'm adding a chat feature to our site using GetStream's chat.  I'm trying to create a count badge on a button similar to FB, Twitter, IG, etc that displays the total of unread messages.   GetStream has an event listener to support this.  It's working, but it's not consistent.  If a user gets a new message, it shows the new badge and count.  But, if I navigate to any view other than the chat window, my count goes away.  If I hit refresh, it comes back.  Then... if I navigate around, it stays.   However, if I get a 2nd message, the count updates to 2, but if I navigate around, it's still at 1 until I refresh, and then it shows 2.  Also, it should reset to 0 after navigating to the chat.  It does not.. but if I refresh, it does.   So, clearly, I'm not updating state properly.   Can someone smarter than me tell me what I'm doing wrong?  Oh... and I'm using this as a hook, but I could move this code into the component if needed.  Here's the gist:

const useUnreadMessagesCount = () => {
    const { user } = useAuth()
    const { client: chatClient } = useChatContext()
    const [unreadCount, setUnreadCount] = useState<any>()
    const { token } = useStreamToken()

    useEffect(() => {
        async function init() {
            // set state initially because it appers that client.on events only happen a new event.
            if (user != null) {
                const response: any = await chatClient.connectUser({ id: user.uid }, token)
                setUnreadCount(response.me.total_unread_count)
            }

            // update state when a new event occures.
            chatClient.on((event) => {
                console.log("HERE")
                if (event.unread_channels !== undefined) {
                    console.log("COUNT: ", event.total_unread_count)
                    setUnreadCount(event.total_unread_count)
                }
            })
        }

        init()

        // @ts-ignore
        chatClient.on("user.presence.changed", init())

        return () => {
            // @ts-ignore
            chatClient.off("user.presence.changed", init())
        }
    }, [chatClient])

    return unreadCount
}

export default useUnreadMessagesCount


问:
Is this my approach wrong can help me for better approach because my half test cases are fail?
```<code>let count=0
    let flag=true
   for(let I=0;I<N;I++&&flag===true){
       if(array[I]<=K){
           count++
       }
       else{
           flag=false
           count++
           break;
       }
   }
   flag=false;
   console.log(count)
</code>```

`Noddy has an exam in which each question has a difficulty level in the form of an Integer. Now, Noddy can only solve the problems that have difficulty level less than or equal to X. Now the rules are-

The score of the student is equal to the maximum number of answers he/she has attempted without skipping a question.

The student is allowed to skip just "one" question that will not be counted in the continuity of the questions.

Note- Assume the student knows the solution to the problem he/she attempts and always starts the paper from the first question.

Given the number of Questions, N, the maximum difficulty level of the problem Noddy can solve, X, and the difficulty level of each question in the form of an array

Determine the maximum score that Noddy can score?`

`

```<code>N=7
K=6
array=4 3 7 6 7 2 2
</code>```

`

Can you give me some better approach because they can't be pass all the testcases

Body:
let count=0
    let flag=true
   for(let I=0;I<N;I++&&flag===true){
       if(array[I]<=K){
           count++
       }
       else{
           flag=false
           count++
           break;
       }
   }
   flag=false;
   console.log(count)

`Noddy has an exam in which each question has a difficulty level in the form of an Integer. Now, Noddy can only solve the problems that have difficulty level less than or equal to X. Now the rules are-

The score of the student is equal to the maximum number of answers he/she has attempted without skipping a question.

The student is allowed to skip just "one" question that will not be counted in the continuity of the questions.

Note- Assume the student knows the solution to the problem he/she attempts and always starts the paper from the first question.

Given the number of Questions, N, the maximum difficulty level of the problem Noddy can solve, X, and the difficulty level of each question in the form of an array

Determine the maximum score that Noddy can score?`

`

N=7
K=6
array=4 3 7 6 7 2 2

`

Can you give me some better approach because they can't be pass all the testcases


问:
Variable state updated when there is multiple call in Graphql Nodejs
I am facing one problem. My application is not able to hold the variable state when concurrent request comes. Latest value replace the old value and as a result application behaves in wrong way.

I have an graphql application(Apolo server) in nodejs and acting as api gateway. This graphql application is responsible for fetching data from a third party api. To serve one api request, multiple third party api are being executed internally, and d output of one api is input of another api and return the api response to upstream. Another java application executing graphql api and java application is running in multihreading.

As it is running in multithreading, variable is getting updated with the latest value of args.

For example
index.js

```<code>const resolvers={
Query:{
        customerData:(_, args)=>customer.customerData(_,args)
      },
Customer:
     {
       id:parent=>customer.id(parent),
   name:parent=>customer.name(parent),
     }
}
</code>```

Utility.js

```<code>exports.typeDefs=gql`
type Query {
    customer(traceId: String,offset:Int, limit: Int,customerId:String):[Customer]
}
</code>```

Customer.js

```<code>    var instructorEnrollments= async function(_, args){
    var traceId=‘Ç’+args.traceId;
    var customerId = args.const;
    /////Business logic-----------------
    Api call 1 new Promise().then(val) {
       Api call 2 with val new Promise ().then(val1) {
          Api cal 3 with val1
       }

    }
}
</code>```

In multithreading mode, java application used to call 100 request to the graphql server. Problem is value of customerId updated with the value of last call.

For example, I received customerId value as 100, when data fetching is in progress for 100, then new call for 101 arrive, at that time customerId updated with 101.

I want to what is wrong with me… How I solve this problem.
Any help is appreciated

Body:
I am facing one problem. My application is not able to hold the variable state when concurrent request comes. Latest value replace the old value and as a result application behaves in wrong way.

I have an graphql application(Apolo server) in nodejs and acting as api gateway. This graphql application is responsible for fetching data from a third party api. To serve one api request, multiple third party api are being executed internally, and d output of one api is input of another api and return the api response to upstream. Another java application executing graphql api and java application is running in multihreading.

As it is running in multithreading, variable is getting updated with the latest value of args.

For example
index.js

const resolvers={
Query:{
        customerData:(_, args)=>customer.customerData(_,args)
      },
Customer:
     {
       id:parent=>customer.id(parent),
   name:parent=>customer.name(parent),
     }
}

Utility.js

exports.typeDefs=gql`
type Query {
    customer(traceId: String,offset:Int, limit: Int,customerId:String):[Customer]
}

Customer.js

    var instructorEnrollments= async function(_, args){
    var traceId=‘Ç’+args.traceId;
    var customerId = args.const;
    /////Business logic-----------------
    Api call 1 new Promise().then(val) {
       Api call 2 with val new Promise ().then(val1) {
          Api cal 3 with val1
       }

    }
}

In multithreading mode, java application used to call 100 request to the graphql server. Problem is value of customerId updated with the value of last call.

For example, I received customerId value as 100, when data fetching is in progress for 100, then new call for 101 arrive, at that time customerId updated with 101.

I want to what is wrong with me… How I solve this problem.
Any help is appreciated


问:
Is this a "correct" approach to multiprocessing in Python?
I am trying to understand multiprocessing in Python. I've made a simple task to try this, generate a number of random tan(a) values and put them in a list. I just need some validation on my progress, is the code example a "correct" way of doing this task? Is there a better way in Python?</p>
```<code>from typing import List
from math import sin, cos, sqrt
from multiprocessing import Pool as ThreadPool
import random
import time

JOBS = int(1e8)
BATCHES: int = 10

def verify_result(result: List[int]) -> bool:
    if len(result) < JOBS:
        print(f"Too few results! ({len(result)}/{JOBS})")
        return False
    for r in result:
        if not isinstance(r, float):
            print(f"Wrong type for result element ({type(r)} != float)")
            return False
    return True

def calculate(_=None) -> float:
    a: float = sqrt( random.uniform(0, 1000) )
    return sin(a) / cos(a)

def sequential(n: int) -> List[float]:
    return [ calculate() for _ in range(n) ]

def concurrent(n: int) -> List[float]:
    pool = ThreadPool(BATCHES)
    result = [ None for _ in range(JOBS) ]
    result = list(pool.map(calculate, result))
    return result

if __name__ == "__main__":
    print("Python Runtimes:")

    # Concurrent timed
    start = time.time()
    res = concurrent(JOBS)
    duration = time.time() - start
    print(f"Concurrent: {duration} s (STATUS: {'Success' if verify_result(res) else 'Failure'})")

    # sequential timed
    start = time.time()
    res = sequential(JOBS)
    duration = time.time() - start
    print(f"Sequential: {duration} s (STATUS: {'Success' if verify_result(res) else 'Failure'})")
</code>```

Body:
I am trying to understand multiprocessing in Python. I've made a simple task to try this, generate a number of random tan(a) values and put them in a list. I just need some validation on my progress, is the code example a "correct" way of doing this task? Is there a better way in Python?

from typing import List
from math import sin, cos, sqrt
from multiprocessing import Pool as ThreadPool
import random
import time

JOBS = int(1e8)
BATCHES: int = 10

def verify_result(result: List[int]) -> bool:
    if len(result) < JOBS:
        print(f"Too few results! ({len(result)}/{JOBS})")
        return False
    for r in result:
        if not isinstance(r, float):
            print(f"Wrong type for result element ({type(r)} != float)")
            return False
    return True

def calculate(_=None) -> float:
    a: float = sqrt( random.uniform(0, 1000) )
    return sin(a) / cos(a)

def sequential(n: int) -> List[float]:
    return [ calculate() for _ in range(n) ]

def concurrent(n: int) -> List[float]:
    pool = ThreadPool(BATCHES)
    result = [ None for _ in range(JOBS) ]
    result = list(pool.map(calculate, result))
    return result

if __name__ == "__main__":
    print("Python Runtimes:")

    # Concurrent timed
    start = time.time()
    res = concurrent(JOBS)
    duration = time.time() - start
    print(f"Concurrent: {duration} s (STATUS: {'Success' if verify_result(res) else 'Failure'})")

    # sequential timed
    start = time.time()
    res = sequential(JOBS)
    duration = time.time() - start
    print(f"Sequential: {duration} s (STATUS: {'Success' if verify_result(res) else 'Failure'})")


问:
Started tooling around with python recently but still extremely new to it could use some advice
I have been trying make a program that would pull dividend yield data mostly off others posts combined with trial and error and some help from ChatGPT, here is what I have thus far

```<code># Import yfinance package
import yfinance as yf

# Set the start and end date
start_date = '1990-01-01'
end_date = '2021-07-12'

# Set the ticker
ticker = 'AMZN'

# Get the data
ticker_data = yf.Ticker(ticker)
data = ticker_data.download(start=start_date, end=end_date)

# Print 5 rows
data.tail()

# Import matplotlib for plotting
import matplotlib.pyplot as plt  # **

# Define the label for the title of the figure
plt.title("Adjusted Close Price of {}".format(ticker), fontsize=16)

# Plot the adjusted close price
data['Adj Close'].plot(figsize=(10, 7))

# Define the label for the title of the figure
plt.title("Adjusted Close Price of %s" % ticker, fontsize=16)

# Define the labels for x-axis and y-axis
plt.ylabel('Price', fontsize=14)
plt.xlabel('Year', fontsize=14)

# Plot the grid lines
plt.grid(which="major", color='k', linestyle='-.', linewidth=0.5)

# Show the plot
plt.show()

</code>```

I get this error:

```<code> line 16, in <module>
    data.tail()
AttributeError: 'NoneType' object has no attribute 'tail'
</code>```

I also have a weak code warning on line 19. I put stars next to it in a comment so its easier to view.

How can I fix these issues?

Body:
I have been trying make a program that would pull dividend yield data mostly off others posts combined with trial and error and some help from ChatGPT, here is what I have thus far

# Import yfinance package
import yfinance as yf

# Set the start and end date
start_date = '1990-01-01'
end_date = '2021-07-12'

# Set the ticker
ticker = 'AMZN'

# Get the data
ticker_data = yf.Ticker(ticker)
data = ticker_data.download(start=start_date, end=end_date)

# Print 5 rows
data.tail()

# Import matplotlib for plotting
import matplotlib.pyplot as plt  # **

# Define the label for the title of the figure
plt.title("Adjusted Close Price of {}".format(ticker), fontsize=16)

# Plot the adjusted close price
data['Adj Close'].plot(figsize=(10, 7))

# Define the label for the title of the figure
plt.title("Adjusted Close Price of %s" % ticker, fontsize=16)

# Define the labels for x-axis and y-axis
plt.ylabel('Price', fontsize=14)
plt.xlabel('Year', fontsize=14)

# Plot the grid lines
plt.grid(which="major", color='k', linestyle='-.', linewidth=0.5)

# Show the plot
plt.show()

I get this error:

 line 16, in <module>
    data.tail()
AttributeError: 'NoneType' object has no attribute 'tail'

I also have a weak code warning on line 19. I put stars next to it in a comment so its easier to view.

How can I fix these issues?


问:
Android SQLite: a deferred transaction acquires some lock without any queries
```<code>SQLiteDatabase db = helper.getReadableDatabase();
db.execSQL("BEGIN DEFERRED");
Thread thread = new Thread(() -> {
  db.execSQL("BEGIN DEFERRED");
  db.execSQL("END");
});
thread.start();
try {
  thread.join();
} catch (InterruptedException e) {
}
db.execSQL("END");
</code>```

I expect the 2 transactions run simultaneously but thread.join() never returns.
Could someone explain why?
(Tested on Android 12 emulator)

Edit:

```<code>import sqlite3
import threading

def begin_transaction():
  con = sqlite3.connect("test.db")
  con.execute("BEGIN DEFERRED")
  con.execute("END")
  con.close()

con = sqlite3.connect("test.db")
con.execute("BEGIN DEFERRED")
thread = threading.Thread(target=begin_transaction)
thread.start()
thread.join()
con.execute("END")
con.close()
</code>```

This is an equivalent code in Python, which works properly.
What is the difference between the two?

Body:
SQLiteDatabase db = helper.getReadableDatabase();
db.execSQL("BEGIN DEFERRED");
Thread thread = new Thread(() -> {
  db.execSQL("BEGIN DEFERRED");
  db.execSQL("END");
});
thread.start();
try {
  thread.join();
} catch (InterruptedException e) {
}
db.execSQL("END");

I expect the 2 transactions run simultaneously but thread.join() never returns.
Could someone explain why?
(Tested on Android 12 emulator)

Edit:

import sqlite3
import threading

def begin_transaction():
  con = sqlite3.connect("test.db")
  con.execute("BEGIN DEFERRED")
  con.execute("END")
  con.close()

con = sqlite3.connect("test.db")
con.execute("BEGIN DEFERRED")
thread = threading.Thread(target=begin_transaction)
thread.start()
thread.join()
con.execute("END")
con.close()

This is an equivalent code in Python, which works properly.
What is the difference between the two?


问:
Apps using Apple ID not appearing in settings on iphone 6s
I need to stop using Apple ID to sign into my app. The option to do this appears in system settings on my iPhone 11 Pro MAx and my tester's iPhone 8. It doesn't appear on an iPhone 6s Plus.

So my question is: Is this a feature that only appears in phones newer than 6s and/or 7? Or am I not doing something on the 6s to make it appear?


问:
Popup Menu text translation of "What's This"
Where and how can I override the "What's This" text of the popup menu, which shows up, when pressing the RMB on a QT dialog control?</p>


问:
How to make the preprocessing layers part of the CNN model?
My goal is to make the preprocessing layers part of the CNN model.

This is because some images have different size (258,320) and (322,480) and I would like to resize it both when training and predicting.

So, I am following the docs.

The problem is:

when I tried to do seq_1.summary() it throws error This model has not yet been built. Build the model first by calling build() or by calling the model on a batch of data.

The solution is to do seq_1.build(input_shape=(None,150,150,3)). But this does not solve the problem because now the model expects the input to be 150,150,3 instead of 258,320 or 322,480.

after running build method, I tried to do seq_1.fit(x=X_train, y=y_train, callbacks=callbacks).

It throws error

```<code>ValueError: Data cardinality is ambiguous:
  x sizes: 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 322, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 322, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258,
...
258, 258
  y sizes: 9773
</code>```

The code

```<code>callbacks = [
    # Stop training when a monitored metric has stopped improving
    EarlyStopping(
        monitor='val_loss', patience=20, min_delta=0.0001, mode='min',
        restore_best_weights=True),
    # Reduce learning rate when a metric has stopped improving.
    ReduceLROnPlateau(
        monitor='val_loss', factor=0.2,
        # We believe RreduceLROnPlateau should have less patience than EarlyStopping
        patience=10, min_delta=0.0001, min_lr=0.001),
    # Callback that streams epoch results to a CSV file
    CSVLogger('./results/train.log'),
    # Callback to save the Keras model or model weights at some frequency.
    ModelCheckpoint(filepath="seq_1.h5", monitor='val_loss', save_best_only=True)
]

resize_and_rescale = tf.keras.Sequential([
    tf.keras.layers.Resizing(150,150),
    tf.keras.layers.Rescaling(1./255)
])

data_augmentation = tf.keras.Sequential([
    tf.keras.layers.RandomFlip(mode="horizontal_and_vertical"),
    # tf.keras.layers.RandomRotation(0.2)
])

img_shape = (150, 150, 3)

seq_1 = tf.keras.Sequential([
    # standardize images.
    resize_and_rescale,

    # Data augmentation is inactive at test time so input images will only be
    # augmented during calls to seq_1.fit
    data_augmentation,

    # we are not sure how more filters help to classify image
    # but our philosophy are these:
    # 1. first layer extract features (edges, noise, etc) from raw image,
    # which is noisy (a image contain object that is not relevant)
    # 2. second layer combine features (some edges) to get a shape e.g circle
    # 3. we believe 2 layers are enough to create features.
    Conv2D(
        # strides=1, so it overlap itself and takes advantage of correlation
        # to create a shape.
        filters=32, kernel_size=(3,3), strides=1,
        activation='relu', input_shape=img_shape, use_bias=True),
    # pool_size=(2,2), strides=2,
    # so it does not overlap itself.
    MaxPooling2D(pool_size=(2,2), strides=2),

    Conv2D(
        filters=64, kernel_size=(3,3), activation='relu', strides=1,
        input_shape=img_shape, use_bias=True),
    MaxPooling2D(pool_size=(2,2), strides=2),

    Flatten(),

    Dense(units=len(df_b['kind'].unique()), activation='relu'),

    # softmax makes it easier to interpret (if we use threshold tuning)
    # we will use argmax to classify.
    # but, argmax can't be used for backpropagation because the derivative is 0
    Activation(activation='softmax')
])

seq_1.summary()
</code>```

The code to train

```<code>seq_1.compile(
    optimizer='adam',
    loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
    # reference: https://datascience.stackexchange.com/questions/41921/sparse-categorical-crossentropy-vs-categorical-crossentropy-keras-accuracy
    metrics=[tf.metrics.CategoricalAccuracy()]
)

seq_1.fit(x=X_train, y=y_train, callbacks=callbacks)
</code>```

EDIT

Code to load images

```<code>def load_images(df):
    paths = df['path'].values
    X = []

    for path in paths:
        raw = tf.io.read_file(path)
        img = tf.image.decode_png(raw, channels=3)
        X.append(img)

    y = df['kind'].cat.codes

    return X, y
</code>```

Body:
My goal is to make the preprocessing layers part of the CNN model.

This is because some images have different size (258,320) and (322,480) and I would like to resize it both when training and predicting.

So, I am following the docs.

The problem is:

when I tried to do seq_1.summary() it throws error This model has not yet been built. Build the model first by calling build() or by calling the model on a batch of data.

The solution is to do seq_1.build(input_shape=(None,150,150,3)). But this does not solve the problem because now the model expects the input to be 150,150,3 instead of 258,320 or 322,480.

after running build method, I tried to do seq_1.fit(x=X_train, y=y_train, callbacks=callbacks).

It throws error

ValueError: Data cardinality is ambiguous:
  x sizes: 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 322, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 322, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258, 258,
...
258, 258
  y sizes: 9773

The code

callbacks = [
    # Stop training when a monitored metric has stopped improving
    EarlyStopping(
        monitor='val_loss', patience=20, min_delta=0.0001, mode='min',
        restore_best_weights=True),
    # Reduce learning rate when a metric has stopped improving.
    ReduceLROnPlateau(
        monitor='val_loss', factor=0.2,
        # We believe RreduceLROnPlateau should have less patience than EarlyStopping
        patience=10, min_delta=0.0001, min_lr=0.001),
    # Callback that streams epoch results to a CSV file
    CSVLogger('./results/train.log'),
    # Callback to save the Keras model or model weights at some frequency.
    ModelCheckpoint(filepath="seq_1.h5", monitor='val_loss', save_best_only=True)
]

resize_and_rescale = tf.keras.Sequential([
    tf.keras.layers.Resizing(150,150),
    tf.keras.layers.Rescaling(1./255)
])

data_augmentation = tf.keras.Sequential([
    tf.keras.layers.RandomFlip(mode="horizontal_and_vertical"),
    # tf.keras.layers.RandomRotation(0.2)
])

img_shape = (150, 150, 3)

seq_1 = tf.keras.Sequential([
    # standardize images.
    resize_and_rescale,

    # Data augmentation is inactive at test time so input images will only be
    # augmented during calls to seq_1.fit
    data_augmentation,

    # we are not sure how more filters help to classify image
    # but our philosophy are these:
    # 1. first layer extract features (edges, noise, etc) from raw image,
    # which is noisy (a image contain object that is not relevant)
    # 2. second layer combine features (some edges) to get a shape e.g circle
    # 3. we believe 2 layers are enough to create features.
    Conv2D(
        # strides=1, so it overlap itself and takes advantage of correlation
        # to create a shape.
        filters=32, kernel_size=(3,3), strides=1,
        activation='relu', input_shape=img_shape, use_bias=True),
    # pool_size=(2,2), strides=2,
    # so it does not overlap itself.
    MaxPooling2D(pool_size=(2,2), strides=2),

    Conv2D(
        filters=64, kernel_size=(3,3), activation='relu', strides=1,
        input_shape=img_shape, use_bias=True),
    MaxPooling2D(pool_size=(2,2), strides=2),

    Flatten(),

    Dense(units=len(df_b['kind'].unique()), activation='relu'),

    # softmax makes it easier to interpret (if we use threshold tuning)
    # we will use argmax to classify.
    # but, argmax can't be used for backpropagation because the derivative is 0
    Activation(activation='softmax')
])

seq_1.summary()

The code to train

seq_1.compile(
    optimizer='adam',
    loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
    # reference: https://datascience.stackexchange.com/questions/41921/sparse-categorical-crossentropy-vs-categorical-crossentropy-keras-accuracy
    metrics=[tf.metrics.CategoricalAccuracy()]
)

seq_1.fit(x=X_train, y=y_train, callbacks=callbacks)

EDIT

Code to load images

def load_images(df):
    paths = df['path'].values
    X = []

    for path in paths:
        raw = tf.io.read_file(path)
        img = tf.image.decode_png(raw, channels=3)
        X.append(img)

    y = df['kind'].cat.codes

    return X, y


问:
How to understand KITTI extrinsic Tr values?
I am working with the KITTI Odometry data and I find that the calib.txt file contains the Tr field which as I understand is the transform from the velodyne frame to cam0 (reference). A sample from sequence 00 is as follows:

4.276802385584e-04 -9.999672484946e-01 -8.084491683471e-03 -1.198459927713e-02
-7.210626507497e-03 8.081198471645e-03 -9.999413164504e-01 -5.403984729748e-02
9.999738645903e-01 4.859485810390e-04 -7.206933692422e-03 -2.921968648686e-01

I understand this a homogeneous transform matrix with the last row not provided.  Now what I don't understand is why the translation values (-1.198459927713e-02,-5.403984729748e-02,-2.921968648686e-01) negated. The same is the case with Tr values in other calib.txt file in other sequences.

If I try to calculate the values by hand (based on geometric locations of kitti sensor setup), I end up with the following:

velo2cam0

```<code>[[ 0.0000, -1.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, -1.0000, 0.0800],
[ 1.0000, 0.0000, 0.0000, 0.2700],
[ 0.0000, 0.0000, 0.0000, 1.0000]
</code>```

and for velo2cam2 its:

```<code>[[ 0.0000, -1.0000, 0.0000, -0.0600],
[ 0.0000, 0.0000, -1.0000, 0.0800],
[ 1.0000, 0.0000, 0.0000, 0.2700],
[ 0.0000, 0.0000, 0.0000, 1.0000]
</code>```

So I cant understand the need for negating the translation values.

Body:
I am working with the KITTI Odometry data and I find that the calib.txt file contains the Tr field which as I understand is the transform from the velodyne frame to cam0 (reference). A sample from sequence 00 is as follows:

4.276802385584e-04 -9.999672484946e-01 -8.084491683471e-03 -1.198459927713e-02
-7.210626507497e-03 8.081198471645e-03 -9.999413164504e-01 -5.403984729748e-02
9.999738645903e-01 4.859485810390e-04 -7.206933692422e-03 -2.921968648686e-01

I understand this a homogeneous transform matrix with the last row not provided.  Now what I don't understand is why the translation values (-1.198459927713e-02,-5.403984729748e-02,-2.921968648686e-01) negated. The same is the case with Tr values in other calib.txt file in other sequences.

If I try to calculate the values by hand (based on geometric locations of kitti sensor setup), I end up with the following:

velo2cam0

[[ 0.0000, -1.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, -1.0000, 0.0800],
[ 1.0000, 0.0000, 0.0000, 0.2700],
[ 0.0000, 0.0000, 0.0000, 1.0000]

and for velo2cam2 its:

[[ 0.0000, -1.0000, 0.0000, -0.0600],
[ 0.0000, 0.0000, -1.0000, 0.0800],
[ 1.0000, 0.0000, 0.0000, 0.2700],
[ 0.0000, 0.0000, 0.0000, 1.0000]

So I cant understand the need for negating the translation values.


问:
discord.player ffmpeg process 12040 successfully terminated with return code of 1
code:

```<code>@client.tree.command()
async def play(interaction: Interaction, url: str):
    global voice
    channel = interaction.user.voice.channel
    voice = get(client.voice_clients, Guild=interaction.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
        await interaction.response.send_message(f"error")
    else:
        voice = await channel.connect()
        await interaction.response.send_message(f"joined")
    voice.play(discord.FFmpegPCMAudio(executable="C:/ffmpeg/bin/ffmpeg.exe", source = url))
</code>```

error:

```<code>2022-12-10 19:32:48 INFO     discord.voice_client Connecting to voice...
2022-12-10 19:32:48 INFO     discord.voice_client Starting voice handshake... (connection attempt 1)
2022-12-10 19:32:48 INFO     discord.voice_client Voice handshake complete. Endpoint found russia9326.discord.media
2022-12-10 19:32:50 INFO     discord.player ffmpeg process 12040 successfully terminated with return code of 1.
</code>```

initially there was an error that ffmpeg was not found, I downloaded it separately, indicated the path to it and now it's coming out like this

Body:
code:

@client.tree.command()
async def play(interaction: Interaction, url: str):
    global voice
    channel = interaction.user.voice.channel
    voice = get(client.voice_clients, Guild=interaction.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
        await interaction.response.send_message(f"error")
    else:
        voice = await channel.connect()
        await interaction.response.send_message(f"joined")
    voice.play(discord.FFmpegPCMAudio(executable="C:/ffmpeg/bin/ffmpeg.exe", source = url))

error:

2022-12-10 19:32:48 INFO     discord.voice_client Connecting to voice...
2022-12-10 19:32:48 INFO     discord.voice_client Starting voice handshake... (connection attempt 1)
2022-12-10 19:32:48 INFO     discord.voice_client Voice handshake complete. Endpoint found russia9326.discord.media
2022-12-10 19:32:50 INFO     discord.player ffmpeg process 12040 successfully terminated with return code of 1.

initially there was an error that ffmpeg was not found, I downloaded it separately, indicated the path to it and now it's coming out like this


问:
laravel7 : Fetch data from sessions table using a key
I am trying to store sessions in database and fetch data from sessions table. For that i did

I have changed SESSION_DRIVER=database in .env file.

My code is as below to set session data

```<code>$userdata=Login::check_valid_token($token);
if(isset($userdata->username) && $userdata->username<>'')
 {
  Session::flush();
  session()->put('userdata',(array)$userdata);
 }
</code>```

An entry has been created in sessions table as

I have tried to fetch session data as below

```<code>$session_data=session()->get('userdata');
echo "```";print_r($session_data);exit;
```
<hr />
<p>Its outputting as empty array, I need the session data fetched from database. Can someone suggest this.</p>
<p>Note : I am using my laravel application in incognito mode as iframe below</p>
```
```

Body:
I am trying to store sessions in database and fetch data from sessions table. For that i did

I have changed SESSION_DRIVER=database in .env file.

My code is as below to set session data

$userdata=Login::check_valid_token($token);
if(isset($userdata->username) && $userdata->username<>'')
 {
  Session::flush();
  session()->put('userdata',(array)$userdata);
 }

An entry has been created in sessions table as

I have tried to fetch session data as below

$session_data=session()->get('userdata');
echo "
";print_r($session_data);exit;

Its outputting as empty array, I need the session data fetched from database. Can someone suggest this.

Note : I am using my laravel application in incognito mode as iframe below


问:
How to delete follow id base on both user_id and following_user_id using Django Rest Framework?
Okay, here's the thing I'm already able to create userfollowing relationship based on both the current user(user_id) and the user that is being followed (following_user_id).
But what I want to do is to be able to delete a specific user_id and following_user_id following relationship by the id that was generated when the relationship was first established.

Here's my code for better understanding.

Thanks in advance for your help, which I will really appreciate.

My UserFollowing Model

```<code>class UserFollowing(models.Model):
user_id = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    related_name="following")
following_user_id = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    related_name="followers")

created = models.DateTimeField(auto_now_add=True)

class Meta:
    constraints = [
        models.UniqueConstraint(fields=['user_id','following_user_id'],  name="unique_followers")
    ]

    ordering = ["-created"]

def __str__(self):
    return f"{self.user_id.name} follows {self.following_user_id.name}"
</code>```

My UserFollowing Views

```<code>class UserFollowingView(generics.ListCreateAPIView):
# permission_classes = (IsAuthenticatedOrReadOnly,)
  serializer_class = UserFollowingSerializer
  queryset = UserFollowing.objects.all()

class DeleteFollowView(generics.RetrieveDestroyAPIView):
# permission_classes = (IsAuthenticatedOrReadOnly,)
  serializer_class = UserFollowingSerializer
  queryset = UserFollowing.objects.all()
</code>```

Body:
Okay, here's the thing I'm already able to create userfollowing relationship based on both the current user(user_id) and the user that is being followed (following_user_id).
But what I want to do is to be able to delete a specific user_id and following_user_id following relationship by the id that was generated when the relationship was first established.

Here's my code for better understanding.

Thanks in advance for your help, which I will really appreciate.

My UserFollowing Model

class UserFollowing(models.Model):
user_id = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    related_name="following")
following_user_id = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    related_name="followers")

created = models.DateTimeField(auto_now_add=True)

class Meta:
    constraints = [
        models.UniqueConstraint(fields=['user_id','following_user_id'],  name="unique_followers")
    ]

    ordering = ["-created"]

def __str__(self):
    return f"{self.user_id.name} follows {self.following_user_id.name}"

My UserFollowing Views

class UserFollowingView(generics.ListCreateAPIView):
# permission_classes = (IsAuthenticatedOrReadOnly,)
  serializer_class = UserFollowingSerializer
  queryset = UserFollowing.objects.all()

class DeleteFollowView(generics.RetrieveDestroyAPIView):
# permission_classes = (IsAuthenticatedOrReadOnly,)
  serializer_class = UserFollowingSerializer
  queryset = UserFollowing.objects.all()


问:
Ingress nginx on Kind cluster on Windows 10 throws Unknown desc = failed to pull and unpack image
I run Kind on my windows machine and use the following configuration for my local nodes

```<code>kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
  - role: control-plane
    kubeadmConfigPatches:
      - |
        kind: InitConfiguration
        nodeRegistration:
          kubeletExtraArgs:
            node-labels: "ingress-ready=true"
    extraPortMappings:
      - containerPort: 80
        hostPort: 80
        protocol: TCP
      - containerPort: 443
        hostPort: 443
        protocol: TCP
  - role: worker
  - role: worker
  - role: worker
</code>```

Afer running

```<code>kind create cluster --name dev --config .\kind-cluster.yaml
</code>```

I can see that the nodes were created succesfully

```<code>kubectl get nodes -owide
NAME                STATUS   ROLES           AGE     VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION                       CONTAINER-RUNTIME
dev-control-plane   Ready    control-plane   2m28s   v1.25.3   172.19.0.5    <none>        Ubuntu 22.04.1 LTS   5.10.102.1-microsoft-standard-WSL2   containerd://1.6.9
dev-worker          Ready    <none>          111s    v1.25.3   172.19.0.3    <none>        Ubuntu 22.04.1 LTS   5.10.102.1-microsoft-standard-WSL2   containerd://1.6.9
dev-worker2         Ready    <none>          2m3s    v1.25.3   172.19.0.2    <none>        Ubuntu 22.04.1 LTS   5.10.102.1-microsoft-standard-WSL2   containerd://1.6.9
dev-worker3         Ready    <none>          110s    v1.25.3   172.19.0.4    <none>        Ubuntu 22.04.1 LTS   5.10.102.1-microsoft-standard-WSL2   containerd://1.6.9
</code>```

As a next step I am trying to create ingress by running

```<code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/
static/provider/kind/deploy.yaml
</code>```

The output seems to be fine

```<code>namespace/ingress-nginx created
serviceaccount/ingress-nginx created
serviceaccount/ingress-nginx-admission created
role.rbac.authorization.k8s.io/ingress-nginx created
role.rbac.authorization.k8s.io/ingress-nginx-admission created
clusterrole.rbac.authorization.k8s.io/ingress-nginx created
clusterrole.rbac.authorization.k8s.io/ingress-nginx-admission created
rolebinding.rbac.authorization.k8s.io/ingress-nginx created
rolebinding.rbac.authorization.k8s.io/ingress-nginx-admission created
clusterrolebinding.rbac.authorization.k8s.io/ingress-nginx created
clusterrolebinding.rbac.authorization.k8s.io/ingress-nginx-admission created
configmap/ingress-nginx-controller created
service/ingress-nginx-controller created
service/ingress-nginx-controller-admission created
deployment.apps/ingress-nginx-controller created
job.batch/ingress-nginx-admission-create created
job.batch/ingress-nginx-admission-patch created
ingressclass.networking.k8s.io/nginx created
validatingwebhookconfiguration.admissionregistration.k8s.io/ingress-nginx-admission created
</code>```

If I run

```<code>kubectl get pods -n ingress-nginx -owide
NAME                                       READY   STATUS              RESTARTS   AGE   IP           NODE                NOMINATED NODE   READINESS GATES
ingress-nginx-admission-create-5s2x5       0/1     ErrImagePull        0          34s   10.244.1.2   dev-worker2         <none>           <none>
ingress-nginx-admission-patch-h7px4        0/1     ErrImagePull        0          34s   10.244.2.2   dev-worker          <none>           <none>
ingress-nginx-controller-6bccc5966-xqcqc   0/1     ContainerCreating   0          34s   <none>       dev-control-plane   <none>           <none>
</code>```

In Lens, I can see the following error message on worker nodes

```<code>Failed to pull image "registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20220916-gd32f8c343@sha256:39c5b2e3310dc4264d638ad28d9d1d96c4cbb2b2dcfb52368fe4e3c63f61e10f": rpc error: code = Unknown desc = failed to pull and unpack image "registry.k8s.io/ingress-nginx/kube-webhook-certgen@sha256:39c5b2e3310dc4264d638ad28d9d1d96c4cbb2b2dcfb52368fe4e3c63f61e10f": failed to resolve reference "registry.k8s.io/ingress-nginx/kube-webhook-certgen@sha256:39c5b2e3310dc4264d638ad28d9d1d96c4cbb2b2dcfb52368fe4e3c63f61e10f": failed to do request: Head "https://registry.k8s.io/v2/ingress-nginx/kube-webhook-certgen/manifests/sha256:39c5b2e3310dc4264d638ad28d9d1d96c4cbb2b2dcfb52368fe4e3c63f61e10f": x509: certificate signed by unknown authority
</code>```

While on control panel node, the error is different

```<code>Unable to attach or mount volumes: unmounted volumes=[webhook-cert], unattached volumes=[webhook-cert kube-api-access-6hfr9]: timed out waiting for the condition
</code>```

and

```<code>MountVolume.SetUp failed for volume "webhook-cert" : secret "ingress-nginx-admission" not found
</code>```

Trying to figure out what would be the root cause.

Body:
I run Kind on my windows machine and use the following configuration for my local nodes

kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
  - role: control-plane
    kubeadmConfigPatches:
      - |
        kind: InitConfiguration
        nodeRegistration:
          kubeletExtraArgs:
            node-labels: "ingress-ready=true"
    extraPortMappings:
      - containerPort: 80
        hostPort: 80
        protocol: TCP
      - containerPort: 443
        hostPort: 443
        protocol: TCP
  - role: worker
  - role: worker
  - role: worker

Afer running

kind create cluster --name dev --config .\kind-cluster.yaml

I can see that the nodes were created succesfully

kubectl get nodes -owide
NAME                STATUS   ROLES           AGE     VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION                       CONTAINER-RUNTIME
dev-control-plane   Ready    control-plane   2m28s   v1.25.3   172.19.0.5    <none>        Ubuntu 22.04.1 LTS   5.10.102.1-microsoft-standard-WSL2   containerd://1.6.9
dev-worker          Ready    <none>          111s    v1.25.3   172.19.0.3    <none>        Ubuntu 22.04.1 LTS   5.10.102.1-microsoft-standard-WSL2   containerd://1.6.9
dev-worker2         Ready    <none>          2m3s    v1.25.3   172.19.0.2    <none>        Ubuntu 22.04.1 LTS   5.10.102.1-microsoft-standard-WSL2   containerd://1.6.9
dev-worker3         Ready    <none>          110s    v1.25.3   172.19.0.4    <none>        Ubuntu 22.04.1 LTS   5.10.102.1-microsoft-standard-WSL2   containerd://1.6.9

As a next step I am trying to create ingress by running

kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/
static/provider/kind/deploy.yaml

The output seems to be fine

namespace/ingress-nginx created
serviceaccount/ingress-nginx created
serviceaccount/ingress-nginx-admission created
role.rbac.authorization.k8s.io/ingress-nginx created
role.rbac.authorization.k8s.io/ingress-nginx-admission created
clusterrole.rbac.authorization.k8s.io/ingress-nginx created
clusterrole.rbac.authorization.k8s.io/ingress-nginx-admission created
rolebinding.rbac.authorization.k8s.io/ingress-nginx created
rolebinding.rbac.authorization.k8s.io/ingress-nginx-admission created
clusterrolebinding.rbac.authorization.k8s.io/ingress-nginx created
clusterrolebinding.rbac.authorization.k8s.io/ingress-nginx-admission created
configmap/ingress-nginx-controller created
service/ingress-nginx-controller created
service/ingress-nginx-controller-admission created
deployment.apps/ingress-nginx-controller created
job.batch/ingress-nginx-admission-create created
job.batch/ingress-nginx-admission-patch created
ingressclass.networking.k8s.io/nginx created
validatingwebhookconfiguration.admissionregistration.k8s.io/ingress-nginx-admission created

If I run

kubectl get pods -n ingress-nginx -owide
NAME                                       READY   STATUS              RESTARTS   AGE   IP           NODE                NOMINATED NODE   READINESS GATES
ingress-nginx-admission-create-5s2x5       0/1     ErrImagePull        0          34s   10.244.1.2   dev-worker2         <none>           <none>
ingress-nginx-admission-patch-h7px4        0/1     ErrImagePull        0          34s   10.244.2.2   dev-worker          <none>           <none>
ingress-nginx-controller-6bccc5966-xqcqc   0/1     ContainerCreating   0          34s   <none>       dev-control-plane   <none>           <none>

In Lens, I can see the following error message on worker nodes

Failed to pull image "registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20220916-gd32f8c343@sha256:39c5b2e3310dc4264d638ad28d9d1d96c4cbb2b2dcfb52368fe4e3c63f61e10f": rpc error: code = Unknown desc = failed to pull and unpack image "registry.k8s.io/ingress-nginx/kube-webhook-certgen@sha256:39c5b2e3310dc4264d638ad28d9d1d96c4cbb2b2dcfb52368fe4e3c63f61e10f": failed to resolve reference "registry.k8s.io/ingress-nginx/kube-webhook-certgen@sha256:39c5b2e3310dc4264d638ad28d9d1d96c4cbb2b2dcfb52368fe4e3c63f61e10f": failed to do request: Head "https://registry.k8s.io/v2/ingress-nginx/kube-webhook-certgen/manifests/sha256:39c5b2e3310dc4264d638ad28d9d1d96c4cbb2b2dcfb52368fe4e3c63f61e10f": x509: certificate signed by unknown authority

While on control panel node, the error is different

Unable to attach or mount volumes: unmounted volumes=[webhook-cert], unattached volumes=[webhook-cert kube-api-access-6hfr9]: timed out waiting for the condition

and

MountVolume.SetUp failed for volume "webhook-cert" : secret "ingress-nginx-admission" not found

Trying to figure out what would be the root cause.


问:
How to filter by date in django-sphinx?
I'm trying to filter by date the queryset that Django-sphinx returns but I am always getting the queryset unfiltered.

This is the snippet:

```<code>date_start  = form.cleaned_data['date_start']
date_end    = form.cleaned_data['date_end']

results = Story.search.query(query).filter(date__range=(date_start, date_end))
</code>```

The proof:

```<code>results = Story.search.query(query)

import sys
print>>sys.stderr, "Results before date filtering:"
for i in results:
    print>>sys.stderr, i.date

print>>sys.stderr, "Date start"
print>>sys.stderr, date_start
print>>sys.stderr, date_start.__class__

print>>sys.stderr, "Date end"
print>>sys.stderr, date_end
print>>sys.stderr, date_end.__class__

fresults = results.filter(date__range=(date_start,date_end))

print>>sys.stderr, "Results after date filtering:"
for j in fresults:
    print>>sys.stderr, j.date
    print>>sys.stderr, date_start<=j.date and "OK" or "Error"
    print>>sys.stderr, j.date<=date_end and "OK" or "Error"
</code>```

Output:

```<code>Results before date filtering:
2011-09-16 01:46:10

Date start
2011-09-08 00:00:00
<type 'datetime.datetime'>

Date end
2011-09-09 00:00:00
<type 'datetime.datetime'>

Results after date filtering:
2011-09-16 01:46:10
OK
Error
</code>```

As you can see, after filtering, still returns an entry dated September 16, which is a later date of September 9 (date_end variable).

Title: How to filter by date in django-sphinx?

Body:
I'm trying to filter by date the queryset that Django-sphinx returns but I am always getting the queryset unfiltered.

This is the snippet:

date_start  = form.cleaned_data['date_start']
date_end    = form.cleaned_data['date_end']

results = Story.search.query(query).filter(date__range=(date_start, date_end))

The proof:

results = Story.search.query(query)

import sys
print>>sys.stderr, "Results before date filtering:"
for i in results:
    print>>sys.stderr, i.date

print>>sys.stderr, "Date start"
print>>sys.stderr, date_start
print>>sys.stderr, date_start.__class__

print>>sys.stderr, "Date end"
print>>sys.stderr, date_end
print>>sys.stderr, date_end.__class__

fresults = results.filter(date__range=(date_start,date_end))

print>>sys.stderr, "Results after date filtering:"
for j in fresults:
    print>>sys.stderr, j.date
    print>>sys.stderr, date_start<=j.date and "OK" or "Error"
    print>>sys.stderr, j.date<=date_end and "OK" or "Error"

Output:

Results before date filtering:
2011-09-16 01:46:10

Date start
2011-09-08 00:00:00
<type 'datetime.datetime'>

Date end
2011-09-09 00:00:00
<type 'datetime.datetime'>

Results after date filtering:
2011-09-16 01:46:10
OK
Error

As you can see, after filtering, still returns an entry dated September 16, which is a later date of September 9 (date_end variable).


问:
How do I install lxml package?
Error Message in Command Prompt

I'm using PyCharm and tried to install in File->Settings->Project Interpreter and adding it this way and got the following error:

PyCharm Error

Unsure how to troubleshoot this. Any advice?

Tried pip installing lxml in command prompt as received the following error:

Title: How do I install lxml package?


问:
Can't convert wdsl file to c# class
I've an issue with wdsl files.
I used to work with salesforce and other webservice, I used the wdsl tool from windows to convert the wsdl file to c# classes.

Today I've to connect other webservice, when I try the wdsl file with soapui, there's no problem buth when I try to convert it with wsdl I get this error :

( sorry it's a french to english translation )

... can't import the link ( or bind ) from the namespace

impossible to import the operation

the syntax of the operation lireEtudiant from the namespace is not valid. Link(or bind) soap : missing operation.

I tried to find what that error means but the answers are less clear than the message to me.
May you help me ?
I can share the wsdl file, it's public there's available on the internet.

Title: Can't convert wdsl file to c# class


问:
How do I get the localized date format for a given locale?
Is there a standard way in Javascript to get the localized date format for a given locale?

Here are some examples of what I'm looking for:

fr-FR -> jj/mm/aaaa

en-US -> mm/dd/yyyy

de-DE -> TT.mm.jjjj

etc.

I got those examples by looking at the placeholder of an <input type="date" /> after changing my browser's locale. So it appears the browser has this data somewhere. Is there a standard JS API or library that makes it accessible?

What I got so far

I can get the non-localized date format by using Intl.DateTimeFormat's formatToParts API.

function getDateFormat(locale) {
  return new Intl.DateTimeFormat(locale, {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  })
    .formatToParts(new Date())
    .reduce((acc, part) => {
      const { type, value } = part;
      if (type === "year") {
        return acc + "YYYY";
      } else if (type === "month") {
        return acc + "MM";
      } else if (type === "day") {
        return acc + "DD";
      } else {
        return acc + value;
      }
    }, "");
}
```

This implementation does not account for the placeholder variations related to the locale (for locale fr-FR, "aaaa" should be used instead of "YYYY", etc.). Currently, I have to perform the mapping myself to get the localized version, which I'd like to avoid.

Body:
Is there a standard way in Javascript to get the localized date format for a given locale?

Here are some examples of what I'm looking for:

fr-FR -> jj/mm/aaaa

en-US -> mm/dd/yyyy

de-DE -> TT.mm.jjjj

etc.

I got those examples by looking at the placeholder of an <input type="date" /> after changing my browser's locale. So it appears the browser has this data somewhere. Is there a standard JS API or library that makes it accessible?

What I got so far

I can get the non-localized date format by using Intl.DateTimeFormat's formatToParts API.

function getDateFormat(locale) {
  return new Intl.DateTimeFormat(locale, {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  })
    .formatToParts(new Date())
    .reduce((acc, part) => {
      const { type, value } = part;
      if (type === "year") {
        return acc + "YYYY";
      } else if (type === "month") {
        return acc + "MM";
      } else if (type === "day") {
        return acc + "DD";
      } else {
        return acc + value;
      }
    }, "");
}

This implementation does not account for the placeholder variations related to the locale (for locale fr-FR, "aaaa" should be used instead of "YYYY", etc.). Currently, I have to perform the mapping myself to get the localized version, which I'd like to avoid.


问:
How can I send verification email on Django when user update email id using signals.py
how can I send verification emails on django using signals.py when a user updates the email id on the Custom profile model?

This is my signals.py for updating the User model. I want to send a confirmation email when the user updates their email id.

```<code>@receiver(post_save, sender=models.Profile_user)
def update_auth_user_model_handler(sender, instance, created, **kwargs):
    if created:
        return
    user_instance = instance.user
    user_instance.first_name = instance.first_name
    user_instance.last_name = instance.last_name
    user_instance.email = instance.email
    user_instance.save()
</code>```

I want to send confirmation email to the new email when an user updates his email id before saving it to the User model on Django

Body:
how can I send verification emails on django using signals.py when a user updates the email id on the Custom profile model?

This is my signals.py for updating the User model. I want to send a confirmation email when the user updates their email id.

@receiver(post_save, sender=models.Profile_user)
def update_auth_user_model_handler(sender, instance, created, **kwargs):
    if created:
        return
    user_instance = instance.user
    user_instance.first_name = instance.first_name
    user_instance.last_name = instance.last_name
    user_instance.email = instance.email
    user_instance.save()

I want to send confirmation email to the new email when an user updates his email id before saving it to the User model on Django


问:
Pass GA4 Client ID to website form when using GTM on site
I am trying to pass a user's client_id to a form on our checkout page so that I can use it with the Measurement Protocol later.  I am doing so with this script:

```<code>    $(document).ready(function () {
        const ga_textbox = document.querySelector("div.chkQuestions > input");
        ga_textbox.value = "test";
        gtag("get", "G-XXXXXXXXXX", "client_id", (client_id) => {
            ga_textbox.value = client_id;
        });
    });
</code>```

This loads the test text info the form, but not the client_id because we are not using gtag.js on our pages.  We are using this Google Tag Manager snippet:

```<code>    (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX');
</code>```

How can we get the client_id, but still use the GTM snippet on our site?

Body:
I am trying to pass a user's client_id to a form on our checkout page so that I can use it with the Measurement Protocol later.  I am doing so with this script:

    $(document).ready(function () {
        const ga_textbox = document.querySelector("div.chkQuestions > input");
        ga_textbox.value = "test";
        gtag("get", "G-XXXXXXXXXX", "client_id", (client_id) => {
            ga_textbox.value = client_id;
        });
    });

This loads the test text info the form, but not the client_id because we are not using gtag.js on our pages.  We are using this Google Tag Manager snippet:

    (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX');

How can we get the client_id, but still use the GTM snippet on our site?


问:
React alert message showing up twice in my useEffect/setTimeout thing
For some reason with this code the alert is displayed twice.  Why is this?  All people with similar issues seem to be using React in strict mode.  How do I turn off strict mode if its somehow on by default for me.  And if that's not the issue, what is?</p>
```<code>    import React from "react";
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

function Main()
{
    const [count, setCount] = useState(20);

    //setInterval(setCount(count - 1), 1000);

     useEffect(() => {
    setTimeout(() => {
      setCount((count) => count > 0 ? count - 1 : alert("boom"));
    }, 1000);
  });
    return(
<div> {count} </div>
)
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Main />);
</code>```

Body:
For some reason with this code the alert is displayed twice.  Why is this?  All people with similar issues seem to be using React in strict mode.  How do I turn off strict mode if its somehow on by default for me.  And if that's not the issue, what is?

    import React from "react";
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

function Main()
{
    const [count, setCount] = useState(20);

    //setInterval(setCount(count - 1), 1000);

     useEffect(() => {
    setTimeout(() => {
      setCount((count) => count > 0 ? count - 1 : alert("boom"));
    }, 1000);
  });
    return(

 {count}

)
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render();


问:
How to manage different kinds of models with spatie/laravel-medialibrary?
I want to use the library "spatie/laravel-medialibrary" to manage the medias of my models.

The problem I have is that I have models with integer keys, some models with string keys, and some models with uuid keys.

But the table "media" is only for integer models (see the column "model_id").

Is it possible to have different media tables regarding the types of the keys ?


问:
Missing required parameter for my route name
One of the routes configured in the "home" of my page is not working.

My web.php:

```<code>Route::get('/', [HomeController::class,'index'])->name('home');

Route::get('/post/{red:slug}', [PostRedController::class,'index'])
    ->name('red');

Route::get('/post/{green:slug}', [PostGreenController::class,'index'])
    ->name('green');
</code>```

My HomeController:

```<code>class HomeController extends Controller
{
    public function index()
    {
        return view('home',
    [
        'red' = PostRed::limit(10)->orderby('id', 'desc')->get();
        'red_images' = PostRedImage::limit(2)->get();
        'green' = PostGreen::limit(5)->orderby('id', 'desc')->get();
        ]);
    }
}
</code>```

My home view

```<code>@for ($i = 0; $i < $red->count(); $i++)
    <div>
        <a href="{{ route('red', $red->slice($i, 1)->first()?->slug) }}"</a>
    </div>

    <div>
        <a href="{{ route('green', $green->slice($i, 1)->first()?->slug) }}"</a>
    </div>
@endfor
</code>```

When I have to load the home, it shows the message

```<code>Missing required parameter for [Route: green] [URI: post/{green}] [Missing parameter: green].
</code>```

The "red" route works.

That way it doesn't give an error, but it doesn't have the link to the post.

```<code>@for ($i = 0; $i < $red->count(); $i++)
    <div>
        <a href="{{ route('red', $red->slice($i, 1)->first()?->slug) }}"</a>
        <a href="#0"</a>
    </div>
@endfor
</code>```

I want to open GreenPost also using slug.

Body:
One of the routes configured in the "home" of my page is not working.

My web.php:

Route::get('/', [HomeController::class,'index'])->name('home');

Route::get('/post/{red:slug}', [PostRedController::class,'index'])
    ->name('red');

Route::get('/post/{green:slug}', [PostGreenController::class,'index'])
    ->name('green');

My HomeController:

class HomeController extends Controller
{
    public function index()
    {
        return view('home',
    [
        'red' = PostRed::limit(10)->orderby('id', 'desc')->get();
        'red_images' = PostRedImage::limit(2)->get();
        'green' = PostGreen::limit(5)->orderby('id', 'desc')->get();
        ]);
    }
}

My home view

@for ($i = 0; $i < $red->count(); $i++)

        slice($i, 1)->first()?->slug) }}"

        slice($i, 1)->first()?->slug) }}"

@endfor

When I have to load the home, it shows the message

Missing required parameter for [Route: green] [URI: post/{green}] [Missing parameter: green].

The "red" route works.

That way it doesn't give an error, but it doesn't have the link to the post.

@for ($i = 0; $i < $red->count(); $i++)

        slice($i, 1)->first()?->slug) }}"
        <a href="#0"

@endfor

I want to open GreenPost also using slug.


问:
Clipped View overlapping issue - SwiftUI
Anything placed before a clipped View is not accessible. Can anybody tell me how to handle this issue?
Run the following code and you will not able to click the button before Ellipse. This is because Ellipse is clipped but still overlapping the button.

```<code>import SwiftUI

struct TestUIView: View {

    var body: some View {
        VStack {

            Button {
                print("Top button tapped..")
            } label: {
                Text("This Button not clickable")
            }

            Ellipse()
                .fill(Color.purple)
                .aspectRatio(CGSize(width: 3, height: 4), contentMode: .fill)
                .frame(width: 200, height: 200)
                .border(Color(white: 0.75))
                .clipped()

            Button {
                print("Bottom button tapped..")
            } label: {
                Text("Toggle")
            }

        }
    }
}

struct TestUIView_Previews: PreviewProvider {
    static var previews: some View {
        TestUIView()
    }
}
</code>```

Please guide how to handle this issue.
Thanks

Body:
Anything placed before a clipped View is not accessible. Can anybody tell me how to handle this issue?
Run the following code and you will not able to click the button before Ellipse. This is because Ellipse is clipped but still overlapping the button.

import SwiftUI

struct TestUIView: View {

    var body: some View {
        VStack {

            Button {
                print("Top button tapped..")
            } label: {
                Text("This Button not clickable")
            }

            Ellipse()
                .fill(Color.purple)
                .aspectRatio(CGSize(width: 3, height: 4), contentMode: .fill)
                .frame(width: 200, height: 200)
                .border(Color(white: 0.75))
                .clipped()

            Button {
                print("Bottom button tapped..")
            } label: {
                Text("Toggle")
            }

        }
    }
}

struct TestUIView_Previews: PreviewProvider {
    static var previews: some View {
        TestUIView()
    }
}

Please guide how to handle this issue.
Thanks


问:
Cannot read properties of null (reading 'useReducer') when I build my next.js application in Server Side Render page
I just build a next.js application in that I use react context and react reducer to authenticate users and this is my context code:

```<code>import React from "react";
import { createContext, useContext, useReducer } from "react";
import { authConstants } from "./constants";

const Store = createContext();

const reducer = (state, action) => {
  switch (action.type) {
    case authConstants.LOGIN_REQUEST: {
      return {
        ...state,
        user: {
          ...state.user,
          authenticating: true,
        },
      };
    }
    case authConstants.LOGIN_SUCCESS: {
      return {
        ...state,
        user: {
          ...action.payload.user,
          authenticating: false,
          authenticated: true,
        },
      };
    }
    case authConstants.LOGIN_FAILURE: {
      return {
        ...state,
        user: {
          ...state.user,
          authenticating: false,
          authenticated: false,
          error: action.payload,
        },
      };
    }
    default: {
      return state;
    }
  }
};

export const StoreProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, {
    user: {
      authenticated: false,
      authenticating: true,
      error: null,
    },
  });
  return <Store.Provider value={[state, dispatch]}>{children}</Store.Provider>;
};

export const useStore = () => useContext(Store);
</code>```

and I use a layout component to check the session and redirect unauthenticated users with this code:

```<code>import { getSession } from "next-auth/react";
import { useEffect } from "react";
import { useStore } from "../../client/context";
import { authConstants } from "../../client/context/constants";
import { getValue } from "../../utils/common";
import { useRouter } from "next/router";

const Layout = ({ children }) => {
  const [state, dispatch] = useStore();
  const router = useRouter();

  const authFunction = async () => {
    const authenticated = getValue(state, ["user", "authenticated"], false);
    if (!authenticated) {
      dispatch({ type: authConstants.LOGIN_REQUEST });
      const session = await getSession();
      if (session) {
        dispatch({ type: authConstants.LOGIN_SUCCESS, payload: session });
      } else {
        dispatch({
          type: authConstants.LOGIN_FAILURE,
          payload: session,
        });
        router.replace("/auth/login");
      }
    }
  };

  useEffect(() => {
    authFunction();
  }, []);
  return children;
};

export default Layout;
</code>```

and this is my _app.js

```<code>import { StoreProvider } from "../client/context";
import { createContext, useContext, useReducer } from "react";
import Layout from "../components/Layout/Layout";
import "../styles/globals.css";

function MyApp({ Component, pageProps }) {
  return (
    <StoreProvider>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </StoreProvider>
  );
}

export default MyApp;
</code>```

For some reason I need to use server-side render in my Login page to get base HTTP authentication from the user :(/pages/auth/login/index.js)

```<code>export async function getServerSideProps(ctx) {
  const { req, res } = ctx;

  const response = await httpAuthCheck(req, res);

  return {
    props: {},
  };
}
</code>```

and in my middleware, I check base HTTP authentication and redirect the user if there is no base authentication:

```<code>import { NextRequest, NextResponse } from "next/server";

export const config = {
  matcher: "/auth/:path*",
};

export function middleware(req) {
  const basicAuth = req.headers.get("authorization");
  const url = req.nextUrl;

  if (basicAuth) {
    return NextResponse.next();
  } else {
    return NextResponse.rewrite(url.origin + "/auth/login");
  }
}
</code>```

my problem is hear everything works fine and perfectly without any error in the developer mode of next.js but when  I build my application, it is built completely without any error, but when I open my login page with the Server Side Render function I got this error and my server gets down:

```<code>TypeError: Cannot read properties of null (reading 'useReducer')
    at exports.useReducer (C:\Users\parha\Desktop\nexttest\test\node_modules\react\cjs\react.production.min.js:25:274)
    at StoreProvider (C:\Users\parha\Desktop\nexttest\test\.next\server\pages\_app.js:78:61)
    at renderWithHooks (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5471:16)
    at renderIndeterminateComponent (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5544:15)
    at renderElement (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5759:7)
    at renderNodeDestructive (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5898:11)
    at renderIndeterminateComponent (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5598:7)
    at renderElement (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5759:7)
    at renderNodeDestructive (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5898:11)
    at renderIndeterminateComponent (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5598:7)
</code>```

and this happened just when I run my build application with next start and just happened when I use
getServerSideProps function on any page of my application.
Please help me!!

I try a lot of things but none of them is working for me!

Body:
I just build a next.js application in that I use react context and react reducer to authenticate users and this is my context code:

import React from "react";
import { createContext, useContext, useReducer } from "react";
import { authConstants } from "./constants";

const Store = createContext();

const reducer = (state, action) => {
  switch (action.type) {
    case authConstants.LOGIN_REQUEST: {
      return {
        ...state,
        user: {
          ...state.user,
          authenticating: true,
        },
      };
    }
    case authConstants.LOGIN_SUCCESS: {
      return {
        ...state,
        user: {
          ...action.payload.user,
          authenticating: false,
          authenticated: true,
        },
      };
    }
    case authConstants.LOGIN_FAILURE: {
      return {
        ...state,
        user: {
          ...state.user,
          authenticating: false,
          authenticated: false,
          error: action.payload,
        },
      };
    }
    default: {
      return state;
    }
  }
};

export const StoreProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, {
    user: {
      authenticated: false,
      authenticating: true,
      error: null,
    },
  });
  return <Store.Provider value={[state, dispatch]}>{children}</Store.Provider>;
};

export const useStore = () => useContext(Store);

and I use a layout component to check the session and redirect unauthenticated users with this code:

import { getSession } from "next-auth/react";
import { useEffect } from "react";
import { useStore } from "../../client/context";
import { authConstants } from "../../client/context/constants";
import { getValue } from "../../utils/common";
import { useRouter } from "next/router";

const Layout = ({ children }) => {
  const [state, dispatch] = useStore();
  const router = useRouter();

  const authFunction = async () => {
    const authenticated = getValue(state, ["user", "authenticated"], false);
    if (!authenticated) {
      dispatch({ type: authConstants.LOGIN_REQUEST });
      const session = await getSession();
      if (session) {
        dispatch({ type: authConstants.LOGIN_SUCCESS, payload: session });
      } else {
        dispatch({
          type: authConstants.LOGIN_FAILURE,
          payload: session,
        });
        router.replace("/auth/login");
      }
    }
  };

  useEffect(() => {
    authFunction();
  }, []);
  return children;
};

export default Layout;

and this is my _app.js

import { StoreProvider } from "../client/context";
import { createContext, useContext, useReducer } from "react";
import Layout from "../components/Layout/Layout";
import "../styles/globals.css";

function MyApp({ Component, pageProps }) {
  return (
    <StoreProvider>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </StoreProvider>
  );
}

export default MyApp;

For some reason I need to use server-side render in my Login page to get base HTTP authentication from the user :(/pages/auth/login/index.js)

export async function getServerSideProps(ctx) {
  const { req, res } = ctx;

  const response = await httpAuthCheck(req, res);

  return {
    props: {},
  };
}

and in my middleware, I check base HTTP authentication and redirect the user if there is no base authentication:

import { NextRequest, NextResponse } from "next/server";

export const config = {
  matcher: "/auth/:path*",
};

export function middleware(req) {
  const basicAuth = req.headers.get("authorization");
  const url = req.nextUrl;

  if (basicAuth) {
    return NextResponse.next();
  } else {
    return NextResponse.rewrite(url.origin + "/auth/login");
  }
}

my problem is hear everything works fine and perfectly without any error in the developer mode of next.js but when  I build my application, it is built completely without any error, but when I open my login page with the Server Side Render function I got this error and my server gets down:

TypeError: Cannot read properties of null (reading 'useReducer')
    at exports.useReducer (C:\Users\parha\Desktop\nexttest\test\node_modules\react\cjs\react.production.min.js:25:274)
    at StoreProvider (C:\Users\parha\Desktop\nexttest\test\.next\server\pages\_app.js:78:61)
    at renderWithHooks (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5471:16)
    at renderIndeterminateComponent (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5544:15)
    at renderElement (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5759:7)
    at renderNodeDestructive (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5898:11)
    at renderIndeterminateComponent (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5598:7)
    at renderElement (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5759:7)
    at renderNodeDestructive (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5898:11)
    at renderIndeterminateComponent (C:\Users\parha\AppData\Roaming\npm\node_modules\next\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5598:7)

and this happened just when I run my build application with next start and just happened when I use
getServerSideProps function on any page of my application.
Please help me!!

I try a lot of things but none of them is working for me!


问:
Error "Plugin with id 'com.android.application' not found."
I'm using Gradle version 7.0.2 for Android Development.
When I want to sync my Android project, it always gives this error:

```<code>* What went wrong:
A problem occurred evaluating project ':app'.
> Plugin with id 'com.android.application' not found.
</code>```

Please tell me how to fix it.

This is the project build.gradle file:

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.2'
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

And this is the module build.gradle file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 15

    defaultConfig {
        applicationId "localhost.my"
        minSdkVersion 15
        targetSdkVersion 15
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildToolsVersion '25.0.1'
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.1.0'
    implementation 'androidx.navigation:navigation-ui:2.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}
</code>```

I used different repositories including mavenCentral() and jcenter(). I expected a successful sync, but I just failed.

Body:
I'm using Gradle version 7.0.2 for Android Development.
When I want to sync my Android project, it always gives this error:

* What went wrong:
A problem occurred evaluating project ':app'.
> Plugin with id 'com.android.application' not found.

Please tell me how to fix it.

This is the project build.gradle file:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.2'
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And this is the module build.gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 15

    defaultConfig {
        applicationId "localhost.my"
        minSdkVersion 15
        targetSdkVersion 15
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildToolsVersion '25.0.1'
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.1.0'
    implementation 'androidx.navigation:navigation-ui:2.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

I used different repositories including mavenCentral() and jcenter(). I expected a successful sync, but I just failed.


问:
Github double-counting commits published to two separate remotes
Earlier this year I worked on a project and pushed my commits to a remote private repository on Github, initially set up by a separate party (under an organization). That party's sole contribution to the repository was setting it up and adding an initial README.MD. All other commits were my own.

Recently, I set up my own private repository on Github and pushed all my commits to it as well (since I didn't have full control over the other party's repository). All the pushed commits have the same author and data across the two repositories.

But now my contributions for the project are being double-counted on the contributions calendar heat map shown on my Github profile page. For instance, it lists 90 contributions on Dec 7 (whereas I had 45 prior to the push).

Is there any way for me to prevent the double-counting without changing the visibility of the repositories?

I looked up what GitHub documentation I could find, but all I could find was the option of hiding private contributions altogether (not an option for me at the moment), and troubleshooting steps related to commits NOT being counted at all.


问:
How to install psrchive on windows?
As given in the website https://psrchive.sourceforge.net/manuals/python/, I have downloaded the psrchive folder from github, and now is not sure what to do for installation. Can someone explain it to me how to install it, as I am not making sense of what is written in the instructions.

I'm not sure how to install psrchive for use in python.

Title: How to install psrchive on windows?


问:
Is it possible to devise a Python function that "knows" if it's executed inside an if-then block?
Is there any way to devise a Python function that checks whether it's executed inside an if-then block? Specifically, it would do this:

```<code>if cond_is_true:
     is_inside_if1 = check_if_inside_if_block()  # evaluate to True

is_inside_if2 = check_if_inside_if_block()  # evaluate to False
</code>```

In this case, is_inside_if1 would be True, and is_inside_if2 would be False. Is this even possible or is there no magic dark enough to do this? I know it's possible for a function that checks the scope in which it is executed, but I don't know if this also applies to if-then blocks.

On an analogous note, is there a way to have a function or object that knows whether it's being called inside the cond_is_true statement?

My use case is that I'm designing a Python package that takes arbitrary neural network models and tries to deduce the computational graph of the model without changing any of the code, and some of this scope-inspection dark magic might end up being necessary for this process to be exhaustive.

Body:
Is there any way to devise a Python function that checks whether it's executed inside an if-then block? Specifically, it would do this:

if cond_is_true:
     is_inside_if1 = check_if_inside_if_block()  # evaluate to True

is_inside_if2 = check_if_inside_if_block()  # evaluate to False

In this case, is_inside_if1 would be True, and is_inside_if2 would be False. Is this even possible or is there no magic dark enough to do this? I know it's possible for a function that checks the scope in which it is executed, but I don't know if this also applies to if-then blocks.

On an analogous note, is there a way to have a function or object that knows whether it's being called inside the cond_is_true statement?

My use case is that I'm designing a Python package that takes arbitrary neural network models and tries to deduce the computational graph of the model without changing any of the code, and some of this scope-inspection dark magic might end up being necessary for this process to be exhaustive.