答:
I think for each number in your example, you want to consider that a separate list item. You want to consider each list item as separate sentences wherever there is semi-colon. Then you want to look for the first occurrence of a keyword in that each list item. That becomes the target keyword for that list item. You then want to count the first occurrence only of that target keyword in each sentence within each list item:

```<code>  library(dplyr)
  library(stringr)
# I modified your example sentences to include "section 201" twice in sentence 2 in list item #1 to show it will only count once in that sentence
# I modified the order of your keywords, otherwise solar will be detected first in all sentences
  sentences <- list("The section 201 solar trade case on cells and modules; Issues relating to section 201 section 201 tariffs on imported goods", "Solar panels, Tawian tariffs, trade", "Trade issues impacting the solar industry")
  keywords <- c("section 201", "solar", "solar panels")
# Go through by each list item
  lapply(sentences, function(sentence){
# For each list item, sentences, split into separate sentences by ;
# Also I changed each sentence to lowercase, otherwise solar != Solar
    str_split(tolower(sentence), ";") -> split_string
# Apply each keyword and detect if the keyword is in the list_item using str_detect from stringr
    sapply(keywords, function(keyword) str_detect(split_string, keyword)) -> output
# Output is the keywords that are in each list item
# Choose the first occurrence of a keyword: keywords[output == T][1]
# Detect in each sentence if the keyword is included, then sum the number of occurrences for each list item. Name as the keyword that was detected
      setNames(str_detect(split_string[[1]], keywords[output == T][1]) %>% sum(), keywords[output == T][1])
})
</code>```

Gives a list, with the first occurring keyword identified and the number of first occurrences of that keyword in each sentence within list item:

```<code>[[1]]
section 201
          2

[[2]]
solar
    1

[[3]]
solar
    1
</code>```

Title: Text column in R - Trying to count the keywords sequentially

Body:
I am working on a dataset that has a text column. The text has many sentences separated by a semi-colon ';'. I am trying to get a word count in a new column in dataframe for words that match my keyword. However, in one sentence, if there are repeated keywords, they should be considered only once.

For instance -

The section 201 solar trade case on cells and modules; Issues relating to section 201 tariffs on imported goods

Solar panels, Tawian tariffs, trade

Trade issues impacting the solar industry

are the text in one column of the dataframe.
My keywords include solar, solar panels, section 201

I want to count the words in each sentence that match my keywords but if both or all words are there in the sentence, then it is counted only once. Word counts should only consider keywords in different sentences. If one sentence doesn't have a specific keyword, then move towards finding the second keyword.

My output should be -
word_count
2 (as section 201 is mentioned in both sentences, we do not search for solar because the first word in the keyword list matched)
1 (as only solar word is there)
1 (as only solar word is there)

Please suggest a way to resolve this issue. It is a crucial part of my research work. Thanks.

Kind Regards,
Preety

Body:
I think for each number in your example, you want to consider that a separate list item. You want to consider each list item as separate sentences wherever there is semi-colon. Then you want to look for the first occurrence of a keyword in that each list item. That becomes the target keyword for that list item. You then want to count the first occurrence only of that target keyword in each sentence within each list item:

  library(dplyr)
  library(stringr)
# I modified your example sentences to include "section 201" twice in sentence 2 in list item #1 to show it will only count once in that sentence
# I modified the order of your keywords, otherwise solar will be detected first in all sentences
  sentences <- list("The section 201 solar trade case on cells and modules; Issues relating to section 201 section 201 tariffs on imported goods", "Solar panels, Tawian tariffs, trade", "Trade issues impacting the solar industry")
  keywords <- c("section 201", "solar", "solar panels")
# Go through by each list item
  lapply(sentences, function(sentence){
# For each list item, sentences, split into separate sentences by ;
# Also I changed each sentence to lowercase, otherwise solar != Solar
    str_split(tolower(sentence), ";") -> split_string
# Apply each keyword and detect if the keyword is in the list_item using str_detect from stringr
    sapply(keywords, function(keyword) str_detect(split_string, keyword)) -> output
# Output is the keywords that are in each list item
# Choose the first occurrence of a keyword: keywords[output == T][1]
# Detect in each sentence if the keyword is included, then sum the number of occurrences for each list item. Name as the keyword that was detected
      setNames(str_detect(split_string[[1]], keywords[output == T][1]) %>% sum(), keywords[output == T][1])
})

Gives a list, with the first occurring keyword identified and the number of first occurrences of that keyword in each sentence within list item:

[[1]]
section 201
          2

[[2]]
solar
    1

[[3]]
solar
    1


来源: stackexchange

问:
numpy.dot for dimensions > 2
I am trying to understand how dot product works for dimensions more than 2.

The documentation says:

If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last # axis of a and the second-to-last axis of b:

```<code>dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
</code>```

I don't understand this rule -- where does it come from? Why is it the last axis of a and the second-to-last axis of b?

答:
Standard matrix multiplication definition:

Which is equivalent to:

```<code>dot(a, b)[i,j] = sum(a[i,:] * b[:,j])
</code>```

When including more dimensions, we still sum over the last axis of a and second-last axis of b.

```<code>dot(a, b)[a1,a2,..., b1,b2,..., i,j] = sum(
    a[a1,a2,...,i,:] *
    b[b1,b2,...,:,j]
)
</code>```

In some sense, the additional dimensions for a and b can each be imagined as a "multi-dimensional array" of many matrices. And dot performs as many standard matrix multiplications as it can with the two "multi-dimensional arrays" of many matrices.

ContentLicense: CC BY-SA 4.0

Title: numpy.dot for dimensions > 2

Body:
I am trying to understand how dot product works for dimensions more than 2.

The documentation says:

If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last # axis of a and the second-to-last axis of b:

dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

I don't understand this rule -- where does it come from? Why is it the last axis of a and the second-to-last axis of b?

Body:
Standard matrix multiplication definition:

Which is equivalent to:

dot(a, b)[i,j] = sum(a[i,:] * b[:,j])

When including more dimensions, we still sum over the last axis of a and second-last axis of b.

dot(a, b)[a1,a2,..., b1,b2,..., i,j] = sum(
    a[a1,a2,...,i,:] *
    b[b1,b2,...,:,j]
)

In some sense, the additional dimensions for a and b can each be imagined as a "multi-dimensional array" of many matrices. And dot performs as many standard matrix multiplications as it can with the two "multi-dimensional arrays" of many matrices.


问:
How do you call an instance with one parameter?
```<code>public void remove(String name, int population, double area, String continent) {
    /* Make a new country object for removing */
    Country removeCountry = new Country(name, population, area, continent);

    /* Linear Search for the instance we want to remove */
    for (int i = 0; i < size; i++) {
        if (removeCountry.equals(catalogue[i])) {
            catalogue[i] = catalogue[size - 1];
            catalogue[size - 1] = null;
            size--;
        }
    }
}
</code>```

Okay so this is in a different class and I want to replace line 1 with,

```<code>public void remove(String name)
</code>```

but I can't because on the third line, I have to replace population and area with a value, for the continent, I could just replace it with "" and it would work.

```<code>Country removeCountry = new Country(name, [value], [value], "");
</code>```

In the main class, I want to be able to input this code,

```<code>myCountry.remove("Canada");
</code>```

So basically, I want to somehow override my primitive type parameters by I don't know how.

答:
In case you really want to be able to create an instance of Country using only one parameter, you could overload its constructor:

```<code>public class Country
...
    public Country(String name) {
        this(name, -1, -1, null);
    }
...
</code>```

And then in your remove() method you could just do:

```<code>public void remove(String name) {
    /* Make a new country object for removing */
    Country removeCountry = new Country(name);
    ...
</code>```

This is assuming that the equals() method of the Country class compares only its name field.

Explanation

In java, the same class can have multiple constructors with different parameters. This is called "constructor overloading".

What this(name, -1, -1, null) does is that when you instantiate using this single-parameter constructor, it will in turn call the existing four-parameter constructor during instantiation, passing on its name argument.

Body:
public void remove(String name, int population, double area, String continent) {
    /* Make a new country object for removing */
    Country removeCountry = new Country(name, population, area, continent);

    /* Linear Search for the instance we want to remove */
    for (int i = 0; i < size; i++) {
        if (removeCountry.equals(catalogue[i])) {
            catalogue[i] = catalogue[size - 1];
            catalogue[size - 1] = null;
            size--;
        }
    }
}

Okay so this is in a different class and I want to replace line 1 with,

public void remove(String name)

but I can't because on the third line, I have to replace population and area with a value, for the continent, I could just replace it with "" and it would work.

Country removeCountry = new Country(name, [value], [value], "");

In the main class, I want to be able to input this code,

myCountry.remove("Canada");

So basically, I want to somehow override my primitive type parameters by I don't know how.

Body:
In case you really want to be able to create an instance of Country using only one parameter, you could overload its constructor:

public class Country
...
    public Country(String name) {
        this(name, -1, -1, null);
    }
...

And then in your remove() method you could just do:

public void remove(String name) {
    /* Make a new country object for removing */
    Country removeCountry = new Country(name);
    ...

This is assuming that the equals() method of the Country class compares only its name field.

Explanation

In java, the same class can have multiple constructors with different parameters. This is called "constructor overloading".

What this(name, -1, -1, null) does is that when you instantiate using this single-parameter constructor, it will in turn call the existing four-parameter constructor during instantiation, passing on its name argument.


问:
I have a windows phone 7 application how do I make sure it supports fast task switching?
What do I need as a developer to be sure my apps support fast task switching?

Ideally, I'm looking for like a developer check list of dos and don'ts.

I did search, but everything I found made me feel like I was missing something, tended to be more marketing instead of developer steps and technical details.

Thanks!

答:
Most of the work for FAS is handled for you automatically. The main thing to keep in mind is what Tombstoning means to your application.  When resuming via FAS, the intent is that you don't have to un-tombstone anything, so there's usually no need to restore view model state, or anything like that.  There are a couple of places for which you will need to write code - here's a quick  checklist.

PhoneApplicationPage.OnNavigatingFrom - Experiment with the controls you're using to make sure that FAS restores the data that was there for you. For example - the TextBox control correctly remembers everything you had put into it, but the MediaElement doesn't remember the video or where it's playback head was positioned.

PhoneApplicationPage.OnNavigatedTo - Anything that you saved off in OnNavigatingFrom needs to be re-applied here in OnNavigatedTo. For example - reloading the video source into the MediaElement, repositioning the video and starting it back up again.

Application.Activated - The event args for this event now contain a property called IsApplicationInstancePreserved.  This property returns TRUE when the application is coming back through FAS, or FALSE when the application is coming back from Tombstoning. So you'd have code something like this:

```<code>private void Application_Activated(object sender, ActivatedEventArgs e)
{
    if (!e.IsApplicationInstancePreserved)
    {
        RestoreStateFromTombstone();
    }
}

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
    SaveStateForTombstone();
}
</code>```

That's the essentials. I haven't done any real stress testing yet on the FAS infrastructure to see where it breaks, but this has served me well for the experimenting I've done so far.

For more information, there's a short video from the MIX11 conference called Get Ready for Fast Application Switching presented by Adina Trufinescu that gives more details on FAS which definitely helped me get started.

/chris

ContentLicense: CC BY-SA 3.0

Body:
Most of the work for FAS is handled for you automatically. The main thing to keep in mind is what Tombstoning means to your application.  When resuming via FAS, the intent is that you don't have to un-tombstone anything, so there's usually no need to restore view model state, or anything like that.  There are a couple of places for which you will need to write code - here's a quick  checklist.

PhoneApplicationPage.OnNavigatingFrom - Experiment with the controls you're using to make sure that FAS restores the data that was there for you. For example - the TextBox control correctly remembers everything you had put into it, but the MediaElement doesn't remember the video or where it's playback head was positioned.

PhoneApplicationPage.OnNavigatedTo - Anything that you saved off in OnNavigatingFrom needs to be re-applied here in OnNavigatedTo. For example - reloading the video source into the MediaElement, repositioning the video and starting it back up again.

Application.Activated - The event args for this event now contain a property called IsApplicationInstancePreserved.  This property returns TRUE when the application is coming back through FAS, or FALSE when the application is coming back from Tombstoning. So you'd have code something like this:

private void Application_Activated(object sender, ActivatedEventArgs e)
{
    if (!e.IsApplicationInstancePreserved)
    {
        RestoreStateFromTombstone();
    }
}

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
    SaveStateForTombstone();
}

That's the essentials. I haven't done any real stress testing yet on the FAS infrastructure to see where it breaks, but this has served me well for the experimenting I've done so far.

For more information, there's a short video from the MIX11 conference called Get Ready for Fast Application Switching presented by Adina Trufinescu that gives more details on FAS which definitely helped me get started.

/chris


问:
Need injection token for something provided in root
I have a service that is used throughout my app to do admin functions.
Normally all I have to do to use it is add it to the list of parameters of a constructor.

like so

```<code>constructor(private adminService: AdminService) { }
</code>```

Which is exactly what is shown in the angular.io documentation

However I needed to use it a bit earlier on, like right after authentication and I am getting a weird error that I have no idea how to resolved based on the documentation.

The error message

```<code> No suitable injection token for parameter 'adminService' of class 'LandingLayoutComponent'
</code>```

admin.service.ts

```<code>    @Injectable({
      providedIn: 'root'
    })
    export class AdminService {}
    constructor(private httpService: ApplicationHttpClient) { }
</code>```

app.module.ts

```<code>@NgModule({
  declarations: [
    AppComponent,
    LandingLayoutComponent,
  ],
  imports: [],
  providers: [
    ApplicationHttpClient,
  ],
  bootstrap: [AppComponent]
})
</code>```

Update, shared module does it differently.

```<code>providers: [
  {
    provide: ApplicationHttpClient,
    useFactory: applicationHttpClientCreator,
    deps: [HttpClient, AuthenticationService, ProgressBarService]
  }],
</code>```

答: I'm curious as to what your ApplicationHttpClient looks like. Does it use the HttpClient class? If so, then you probably should also include the HttpClientModule in your Application Module.

Body:
I have a service that is used throughout my app to do admin functions.
Normally all I have to do to use it is add it to the list of parameters of a constructor.

like so

constructor(private adminService: AdminService) { }

Which is exactly what is shown in the angular.io documentation

However I needed to use it a bit earlier on, like right after authentication and I am getting a weird error that I have no idea how to resolved based on the documentation.

The error message

 No suitable injection token for parameter 'adminService' of class 'LandingLayoutComponent'

admin.service.ts

    @Injectable({
      providedIn: 'root'
    })
    export class AdminService {}
    constructor(private httpService: ApplicationHttpClient) { }

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    LandingLayoutComponent,
  ],
  imports: [],
  providers: [
    ApplicationHttpClient,
  ],
  bootstrap: [AppComponent]
})

Update, shared module does it differently.

providers: [
  {
    provide: ApplicationHttpClient,
    useFactory: applicationHttpClientCreator,
    deps: [HttpClient, AuthenticationService, ProgressBarService]
  }],


问:
NameError: free variable 'csv' referenced before assignment in enclosing scope
I'm new in Python and it might be a noob question, I've tried to google and search for the solution but I failed to understand, please be kind and if anyone could guide me through this?

I'm trying to callback my function in another function :

```<code>import csv
#import other libraries

#.......................................

def suara():
    fs = 44100
    seconds = 2
    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
    print("Memulai: Silahkan berbicara sekarang!")
    sd.wait()
    print("Selesai")
    write((os.path.join('data', 'recordings', 'test', '0_login.wav')), fs, myrecording)

    CREATE_CSV_FILES = True

    # Defines the names of the CSV files
    TRAIN_CSV_FILE = "train.csv"
    TEST_CSV_FILE = "test.csv"

    def extractWavFeatures(soundFilesFolder, csvFileName):
        print("The features of the files in the folder "+soundFilesFolder+" will be saved to "+csvFileName)
        header = 'filename chroma_stft rmse spectral_centroid spectral_bandwidth rolloff zero_crossing_rate'
        for i in range(1, 21):
            header += f' mfcc{i}'
        header += ' label'
        header = header.split()
        print('CSV Header: ', header)
        file = open(csvFileName, 'w', newline='')
        #with file:
        writer = csv.writer(file)
        writer.writerow(header)
        genres = '1 2 3 4 5 6 7 8 9 0'.split()
        for filename in os.listdir(soundFilesFolder):
            number = f'{soundFilesFolder}/{filename}'
            # print(number)
            y, sr = librosa.load(number, mono=True, duration=30)
            # remove leading and trailing silence
            y, index = librosa.effects.trim(y)
            chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr)
            rmse = librosa.feature.rms(y=y)
            spec_cent = librosa.feature.spectral_centroid(y=y, sr=sr)
            spec_bw = librosa.feature.spectral_bandwidth(y=y, sr=sr)
            rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr)
            zcr = librosa.feature.zero_crossing_rate(y)
            mfcc = librosa.feature.mfcc(y=y, sr=sr)
            to_append = f'{filename} {np.mean(chroma_stft)} {np.mean(rmse)} {np.mean(spec_cent)} {np.mean(spec_bw)} {np.mean(rolloff)} {np.mean(zcr)}'
            for e in mfcc:
                to_append += f' {np.mean(e)}'
            writer.writerow(to_append.split())
        file.close()
        print("End of extractWavFeatures")

#........................................................
</code>```

I tried to call back this function in here :

```<code>def access(option):
    global name
    if(option=="login"):
        name = input("Masukkan ID: ")
        password = input("Masukkan Password: ")
        login(name,password)
    else:
        suara()

def begin():
    global option
    print("="*45)
    print(" |  Selamat datang  |")
    print("-"*45)
    print("Ketik 'login' jika anda ingin membuka pintu via nama dan password")
    print("Ketik 'suara' jika anda inin membuka pintu via suara")
    print("="*45)
    option = input("slahkan masukkan (login/suara): ")
    if(option!="login" and option!="suara"):
        begin()

begin()
access(option)
</code>```

But I got the following error :

```<code>(cloning2) C:\Users\thosiba\speaker-recognition>C:/Users/thosiba/Anaconda3/envs/cloning2/python.exe c:/Users/thosiba/speaker-recognition/login2.py
=============================================
 |  Selamat datang  |
---------------------------------------------
Ketik 'login' jika anda ingin membuka pintu via nama dan password
Ketik 'suara' jika anda inin membuka pintu via suara
=============================================
slahkan masukkan (login/suara): suara
Memulai: Silahkan berbicara sekarang!
Selesai
The features of the files in the folder C:/Users/thosiba/speaker-recognition/data/recordings/train will be saved to train.csv
CSV Header:  ['filename', 'chroma_stft', 'rmse', 'spectral_centroid', 'spectral_bandwidth', 'rolloff', 'zero_crossing_rate', 'mfcc1', 'mfcc2', 'mfcc3', 'mfcc4', 'mfcc5', 'mfcc6', 'mfcc7', 'mfcc8', 'mfcc9', 'mfcc10', 'mfcc11', 'mfcc12', 'mfcc13', 'mfcc14', 'mfcc15', 'mfcc16', 'mfcc17', 'mfcc18', 'mfcc19', 'mfcc20', 'label']
Traceback (most recent call last):
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 236, in <module>
    access(option)
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 221, in access
    suara()
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 79, in suara
    extractWavFeatures("C:/Users/thosiba/speaker-recognition/data/recordings/train", TRAIN_CSV_FILE)
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 55, in extractWavFeatures
    writer = csv.writer(file)
NameError: free variable 'csv' referenced before assignment in enclosing scope
</code>```

I'm pretty sure it's related to calling the function or marking it down as global but I really don't understand how to work around it in this case. I'm sorry for the long question because I don't know how to explain better.

答: If you're naming a variable csv anywhere in your file (even below the line of the error), that would cause this error. Try changing the name of that variable to something else.

Body:
I'm new in Python and it might be a noob question, I've tried to google and search for the solution but I failed to understand, please be kind and if anyone could guide me through this?

I'm trying to callback my function in another function :

import csv
#import other libraries

#.......................................

def suara():
    fs = 44100
    seconds = 2
    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
    print("Memulai: Silahkan berbicara sekarang!")
    sd.wait()
    print("Selesai")
    write((os.path.join('data', 'recordings', 'test', '0_login.wav')), fs, myrecording)

    CREATE_CSV_FILES = True

    # Defines the names of the CSV files
    TRAIN_CSV_FILE = "train.csv"
    TEST_CSV_FILE = "test.csv"

    def extractWavFeatures(soundFilesFolder, csvFileName):
        print("The features of the files in the folder "+soundFilesFolder+" will be saved to "+csvFileName)
        header = 'filename chroma_stft rmse spectral_centroid spectral_bandwidth rolloff zero_crossing_rate'
        for i in range(1, 21):
            header += f' mfcc{i}'
        header += ' label'
        header = header.split()
        print('CSV Header: ', header)
        file = open(csvFileName, 'w', newline='')
        #with file:
        writer = csv.writer(file)
        writer.writerow(header)
        genres = '1 2 3 4 5 6 7 8 9 0'.split()
        for filename in os.listdir(soundFilesFolder):
            number = f'{soundFilesFolder}/{filename}'
            # print(number)
            y, sr = librosa.load(number, mono=True, duration=30)
            # remove leading and trailing silence
            y, index = librosa.effects.trim(y)
            chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr)
            rmse = librosa.feature.rms(y=y)
            spec_cent = librosa.feature.spectral_centroid(y=y, sr=sr)
            spec_bw = librosa.feature.spectral_bandwidth(y=y, sr=sr)
            rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr)
            zcr = librosa.feature.zero_crossing_rate(y)
            mfcc = librosa.feature.mfcc(y=y, sr=sr)
            to_append = f'{filename} {np.mean(chroma_stft)} {np.mean(rmse)} {np.mean(spec_cent)} {np.mean(spec_bw)} {np.mean(rolloff)} {np.mean(zcr)}'
            for e in mfcc:
                to_append += f' {np.mean(e)}'
            writer.writerow(to_append.split())
        file.close()
        print("End of extractWavFeatures")

#........................................................

I tried to call back this function in here :

def access(option):
    global name
    if(option=="login"):
        name = input("Masukkan ID: ")
        password = input("Masukkan Password: ")
        login(name,password)
    else:
        suara()

def begin():
    global option
    print("="*45)
    print(" |  Selamat datang  |")
    print("-"*45)
    print("Ketik 'login' jika anda ingin membuka pintu via nama dan password")
    print("Ketik 'suara' jika anda inin membuka pintu via suara")
    print("="*45)
    option = input("slahkan masukkan (login/suara): ")
    if(option!="login" and option!="suara"):
        begin()

begin()
access(option)

But I got the following error :

(cloning2) C:\Users\thosiba\speaker-recognition>C:/Users/thosiba/Anaconda3/envs/cloning2/python.exe c:/Users/thosiba/speaker-recognition/login2.py
=============================================
 |  Selamat datang  |
---------------------------------------------
Ketik 'login' jika anda ingin membuka pintu via nama dan password
Ketik 'suara' jika anda inin membuka pintu via suara
=============================================
slahkan masukkan (login/suara): suara
Memulai: Silahkan berbicara sekarang!
Selesai
The features of the files in the folder C:/Users/thosiba/speaker-recognition/data/recordings/train will be saved to train.csv
CSV Header:  ['filename', 'chroma_stft', 'rmse', 'spectral_centroid', 'spectral_bandwidth', 'rolloff', 'zero_crossing_rate', 'mfcc1', 'mfcc2', 'mfcc3', 'mfcc4', 'mfcc5', 'mfcc6', 'mfcc7', 'mfcc8', 'mfcc9', 'mfcc10', 'mfcc11', 'mfcc12', 'mfcc13', 'mfcc14', 'mfcc15', 'mfcc16', 'mfcc17', 'mfcc18', 'mfcc19', 'mfcc20', 'label']
Traceback (most recent call last):
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 236, in <module>
    access(option)
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 221, in access
    suara()
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 79, in suara
    extractWavFeatures("C:/Users/thosiba/speaker-recognition/data/recordings/train", TRAIN_CSV_FILE)
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 55, in extractWavFeatures
    writer = csv.writer(file)
NameError: free variable 'csv' referenced before assignment in enclosing scope

I'm pretty sure it's related to calling the function or marking it down as global but I really don't understand how to work around it in this case. I'm sorry for the long question because I don't know how to explain better.


问:
VSIX Installer "This Extension is not installable on any currently installed products."
I found many similar problems while looking for a solution, but in every other case, the problem appeared to be that the user was using the wrong version of visual studio.

2/6/2022 12:29:06 AM - Microsoft VSIX Installer

2/6/2022 12:29:06 AM - -------------------------------------------

2/6/2022 12:29:06 AM - vsixinstaller.exe version:

2/6/2022 12:29:06 AM - 17.0.5226-preview5

2/6/2022 12:29:06 AM - -------------------------------------------

2/6/2022 12:29:06 AM - Command line parameters:

2/6/2022 12:29:06 AM - C:\Program Files (x86)\Microsoft Visual Studio\Installer\resources\app\ServiceHub\Services\Microsoft.VisualStudio.Setup.Service\VSIXInstaller.exe,C:\Users\Foster\Downloads\VersionChanger.vsix

2/6/2022 12:29:06 AM - -------------------------------------------

2/6/2022 12:29:06 AM - Microsoft VSIX Installer

2/6/2022 12:29:06 AM - -------------------------------------------

2/6/2022 12:29:06 AM - Initializing Install...

2/6/2022 12:29:06 AM - Extension Details...

2/6/2022 12:29:06 AM -  Identifier         : VersionChanger.315c8ff9-932e-4b23-b9d8-0fcd23bdb0be

2/6/2022 12:29:06 AM -  Name               : Version Changer

2/6/2022 12:29:06 AM -  Author             : DSoft Developments

2/6/2022 12:29:06 AM -  Version            : 2.3.2

2/6/2022 12:29:06 AM -  Description        : Visual Studio extension that allows you to change the version number of all projects in a solution in a easy to user interface.

2/6/2022 12:29:06 AM -  Locale             : en-US

2/6/2022 12:29:06 AM -  MoreInfoURL        : https://visualstudiogallery.msdn.microsoft.com/554c35ef-fe76-4138-b60e-a44b72ade70e\
2/6/2022 12:29:06 AM -  InstalledByMSI     : False

2/6/2022 12:29:06 AM -  SupportedFrameworkVersionRange : [4.6,)

2/6/2022 12:29:06 AM -

2/6/2022 12:29:06 AM -  SignatureState     : Unsigned

2/6/2022 12:29:06 AM -  Supported Products :

2/6/2022 12:29:06 AM -      Microsoft.VisualStudio.Community

2/6/2022 12:29:06 AM -          Version : [15.0,17.0)

2/6/2022 12:29:06 AM -          ProductArchitecture : x86

2/6/2022 12:29:06 AM -      Microsoft.VisualStudio.Pro

2/6/2022 12:29:06 AM -          Version : [15.0,17.0)

2/6/2022 12:29:06 AM -          ProductArchitecture : x86

2/6/2022 12:29:06 AM -      Microsoft.VisualStudio.Enterprise

2/6/2022 12:29:06 AM -          Version : [15.0,17.0)

2/6/2022 12:29:06 AM -          ProductArchitecture : x86

2/6/2022 12:29:06 AM -

2/6/2022 12:29:06 AM -  References         :

2/6/2022 12:29:06 AM -  Prerequisites      :

2/6/2022 12:29:06 AM -      -------------------------------------------------------

2/6/2022 12:29:06 AM -      Identifier   : Microsoft.VisualStudio.Component.CoreEditor

2/6/2022 12:29:06 AM -      Name         : Visual Studio core editor

2/6/2022 12:29:06 AM -      Version      : [15.0,)

2/6/2022 12:29:06 AM -
2/6/2022 12:29:06 AM - Signature Details...

2/6/2022 12:29:06 AM -  Extension is not signed.

2/6/2022 12:29:06 AM -
2/6/2022 12:29:06 AM - Searching for applicable products...

2/6/2022 12:29:06 AM - Found installed product - Global Location

2/6/2022 12:29:06 AM - Found installed product - Visual Studio Community 2022

2/6/2022 12:29:06 AM - VSIXInstaller.NoApplicableSKUsException: This extension is not installable on any currently installed products.
at VSIXInstaller.ExtensionService.GetInstallableDataImpl(IInstallableExtension extension, String extensionPackParentName, Boolean isRepairSupported, IStateData stateData, IEnumerable1& skuData)\ at VSIXInstaller.ExtensionService.GetInstallableData(String vsixPath, String extensionPackParentName, Boolean isRepairSupported, IStateData stateData, IEnumerable1& skuData)

at VSIXInstaller.ExtensionPackService.IsExtensionPack(IStateData stateData, Boolean isRepairSupported)

at VSIXInstaller.ExtensionPackService.ExpandExtensionPackToInstall(IStateData stateData, Boolean isRepairSupported)

at VSIXInstaller.App.Initialize(Boolean isRepairSupported)

at VSIXInstaller.App.Initialize()

at System.Threading.Tasks.Task`1.InnerInvoke()

at System.Threading.Tasks.Task.Execute()

--- End of stack trace from previous location where exception was thrown ---

at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)\

as far as I can tell, I am using the correct version. I just installed Visual Studio for the first time, and the version I downloaded appears to be 17.0 according to Microsoft's website. I've tried reinstalling, repairing, and restarting my computer but nothing has worked.

EDIT: I installed VS 2019 and It seems to have fixed my issue for now, but I would still prefer to be using VS 2022; is the version wrong afterall in a way I can't see?

答:
The extension you installed works with Visual Studio 2017, 2019, and from the stack trace:

Found installed product - Visual Studio Community 2022

So either install visual studio 2017/2019, or use this version, which works with visual studio 2022.


问:
Create a new df in pandas from existing one?
I am doing a project on movies data.

The sample dataset looks like :

The column genres have 21 unique values.

I want to create a new table/dataframe so that the table will contains the average ratings for the each genres for every user, like

I got the list of genres using the code below:

```<code>def split(sent):
    return (sent.split())

new_genres=set()

for i in range(len(genres)):
    a=split(genres[i])
    for g in a:
        new_genres.add(g)

new_genres
</code>```

答:
We can start by using the assign method to get each genre in rows like so :

>>> df = df.assign(genre=df['genres'].str.split(' ')).explode('genre')
>>> df
    userId  id      rating  genres                  genre
0   1       110     1.0     Drama Mystery Romance   Drama
0   1       110     1.0     Drama Mystery Romance   Mystery
0   1       110     1.0     Drama Mystery Romance   Romance
1   1       147     4.5     Drama                   Drama
2   1       858     5.0     Comedy Drama Romance    Comedy
2   1       858     5.0     Comedy Drama Romance    Drama
2   1       858     5.0     Comedy Drama Romance    Romance
3   1       1246    5.0     Drama                   Drama
4   1       1968    4.0     Drama Comedy Romance    Drama
4   1       1968    4.0     Drama Comedy Romance    Comedy
4   1       1968    4.0     Drama Comedy Romance    Romance
5   270896  48780   5.0     Forein                  Forein
6   270896  49530   4.0     Action Thriller Scifi   Action
6   270896  49530   4.0     Action Thriller Scifi   Thriller
6   270896  49530   4.0     Action Thriller Scifi   Scifi
7   270896  54001   4.0     Drama                   Drama
8   270896  54503   4.0     Action Forein           Action
8   270896  54503   4.0     Action Forein           Forein
9   270896  58559   5.0     Drama                   Drama
```
<p>Then we <code>groupby</code> <code>userId</code> and <code>genre</code> to get the <code>mean</code> of <code>rating</code>:</p>
<pre class="lang-py prettyprint-override"><code>>>> df_grouped = df.groupby(['userId', 'genre'])['rating'].mean()
>>> df_grouped
userId  genre
1       Comedy      4.500000
        Drama       3.900000
        Mystery     1.000000
        Romance     3.333333
270896  Action      4.000000
        Drama       4.500000
        Forein      4.500000
        Scifi       4.000000
        Thriller    4.000000
Name: rating, dtype: float64
</code>```

To finish, we can use unstack to get the expected result :

>>> df_grouped.unstack(level=-1).fillna(0)
genre   Action  Comedy  Drama   Forein  Mystery     Romance     Scifi   Thriller
userId
1       0.0     4.5     3.9     0.0     1.0         3.333333    0.0     0.0
270896  4.0     0.0     4.5     4.5     0.0         0.000000    4.0     4.0
```
<p>UPDATE :</p>
<p>If you want to add the missing <code>genre</code> given in your list, we can do the following :</p>
<pre class="lang-py prettyprint-override"><code>>>> cols = ['Action',
...         'Adventure',
...         'Animation',
...         'Crime',
...         'Documentary',
...         'Family',
...         'Fantasy',
...         'History',
...         'Horror',
...         'Comedy',
...         'Drama',
...         'Forein',
...         'Mystery',
...         'Romance',
...         'Scifi',
...         'Thriller']
>>> df_res = df_res.reindex(df_res.columns.union(cols, sort=False), axis=1, fill_value=0)
>>> df_res
genre   Action  Comedy  Drama   Forein  Mystery     Romance     Scifi   Thriller    Adventure   Animation   Crime   Documentary     Family  Fantasy     History     Horror
userId
1       0.0     4.5     3.9     0.0     1.0         3.333333    0.0     0.0         0           0           0       0               0       0           0           0
270896  4.0     0.0     4.5     4.5     0.0         0.000000    4.0     4.0         0           0           0       0               0       0           0           0
</code>```

Body:
I am doing a project on movies data.

The sample dataset looks like :

The column genres have 21 unique values.

I want to create a new table/dataframe so that the table will contains the average ratings for the each genres for every user, like

I got the list of genres using the code below:

def split(sent):
    return (sent.split())

new_genres=set()

for i in range(len(genres)):
    a=split(genres[i])
    for g in a:
        new_genres.add(g)

new_genres

Body:
We can start by using the assign method to get each genre in rows like so :

>>> df = df.assign(genre=df['genres'].str.split(' ')).explode('genre')
>>> df
    userId  id      rating  genres                  genre
0   1       110     1.0     Drama Mystery Romance   Drama
0   1       110     1.0     Drama Mystery Romance   Mystery
0   1       110     1.0     Drama Mystery Romance   Romance
1   1       147     4.5     Drama                   Drama
2   1       858     5.0     Comedy Drama Romance    Comedy
2   1       858     5.0     Comedy Drama Romance    Drama
2   1       858     5.0     Comedy Drama Romance    Romance
3   1       1246    5.0     Drama                   Drama
4   1       1968    4.0     Drama Comedy Romance    Drama
4   1       1968    4.0     Drama Comedy Romance    Comedy
4   1       1968    4.0     Drama Comedy Romance    Romance
5   270896  48780   5.0     Forein                  Forein
6   270896  49530   4.0     Action Thriller Scifi   Action
6   270896  49530   4.0     Action Thriller Scifi   Thriller
6   270896  49530   4.0     Action Thriller Scifi   Scifi
7   270896  54001   4.0     Drama                   Drama
8   270896  54503   4.0     Action Forein           Action
8   270896  54503   4.0     Action Forein           Forein
9   270896  58559   5.0     Drama                   Drama

Then we groupby userId and genre to get the mean of rating:

>>> df_grouped = df.groupby(['userId', 'genre'])['rating'].mean()
>>> df_grouped
userId  genre
1       Comedy      4.500000
        Drama       3.900000
        Mystery     1.000000
        Romance     3.333333
270896  Action      4.000000
        Drama       4.500000
        Forein      4.500000
        Scifi       4.000000
        Thriller    4.000000
Name: rating, dtype: float64

To finish, we can use unstack to get the expected result :

>>> df_grouped.unstack(level=-1).fillna(0)
genre   Action  Comedy  Drama   Forein  Mystery     Romance     Scifi   Thriller
userId
1       0.0     4.5     3.9     0.0     1.0         3.333333    0.0     0.0
270896  4.0     0.0     4.5     4.5     0.0         0.000000    4.0     4.0

UPDATE :

If you want to add the missing genre given in your list, we can do the following :

>>> cols = ['Action',
...         'Adventure',
...         'Animation',
...         'Crime',
...         'Documentary',
...         'Family',
...         'Fantasy',
...         'History',
...         'Horror',
...         'Comedy',
...         'Drama',
...         'Forein',
...         'Mystery',
...         'Romance',
...         'Scifi',
...         'Thriller']
>>> df_res = df_res.reindex(df_res.columns.union(cols, sort=False), axis=1, fill_value=0)
>>> df_res
genre   Action  Comedy  Drama   Forein  Mystery     Romance     Scifi   Thriller    Adventure   Animation   Crime   Documentary     Family  Fantasy     History     Horror
userId
1       0.0     4.5     3.9     0.0     1.0         3.333333    0.0     0.0         0           0           0       0               0       0           0           0
270896  4.0     0.0     4.5     4.5     0.0         0.000000    4.0     4.0         0           0           0       0               0       0           0           0


问:
How to stretch this button in flutter?
I am learning flutter, and faced this issue:

I want the equal button to stretch to the left and cover the whole green area as shown in the picture.

The equal button is in one column and the other four buttons are in another column. And in turn, both of these columns are in a row. i.e

```<code>Column:
  Row:
    Column 1:
      Equal-Button // If I warp it in expended, it goes out of sight.
    Column 2:
      the other four buttons
</code>```

What is the proper way to fix it, not just hacks. How would you do it?

Here is the whole code:
Github Gist

答:
Assuming both the = button and / button are in a Row widget you could wrap the = button in a Expanded widget forcing it to take all available space along it MainAxis.
Here's a quick example:

```<code>class Sample extends StatelessWidget {
  const Sample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(child: Container(color: Colors.red, height: 50)),
        Container(
          height: 50,
          width: 100,
          color: Colors.green,
          margin: const EdgeInsets.symmetric(horizontal: 10),
        )
      ],
    );
  }
}
</code>```

Title: How to stretch this button in flutter?

Body:
I am learning flutter, and faced this issue:

I want the equal button to stretch to the left and cover the whole green area as shown in the picture.

The equal button is in one column and the other four buttons are in another column. And in turn, both of these columns are in a row. i.e

Column:
  Row:
    Column 1:
      Equal-Button // If I warp it in expended, it goes out of sight.
    Column 2:
      the other four buttons

What is the proper way to fix it, not just hacks. How would you do it?

Here is the whole code:
Github Gist

Body:
Assuming both the = button and / button are in a Row widget you could wrap the = button in a Expanded widget forcing it to take all available space along it MainAxis.
Here's a quick example:

class Sample extends StatelessWidget {
  const Sample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(child: Container(color: Colors.red, height: 50)),
        Container(
          height: 50,
          width: 100,
          color: Colors.green,
          margin: const EdgeInsets.symmetric(horizontal: 10),
        )
      ],
    );
  }
}


问:
Order of output for log.d?
I connected my android app to google's realtime database. (This is for school and I'm very, very new at all of this app development stuff.) And I was wondering why my log.d() method outputs it's contents to the logcat in the wrong order. I don't think it's a major issue and I can probably work around it but I'm just curious about why it executes like this or if it's something wrong with my code I have to fix.

Resident Page:

```<code>public class ResidentPage extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        ....
        basicReadWrite();
        MethodsFromOtherClass.output();

        return view;
    }

    ...

    public void basicReadWrite(){
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("second message");

        myRef.setValue("Hello again, World!");

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String value = dataSnapshot.getValue(String.class);
                Log.d("ResidentPage", "Value is: " + value);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                Log.w("ResidentPage", "Failed to read value.", error.toException());
            }
        });
    }
}
</code>```

Methods from other class:

```<code>public class MethodsFromOtherClass {
    public static void output(){
        Log.d("ResidentPage", "Called from another class");
    }
}
</code>```

Logcat:

```<code>D/ResidentPage: Called from another class
D/ResidentPage: Value is: Hello again, World!
</code>```

答: They aren't happening in the wrong order.  Your code is asynchronous.  The ValueEventListener is called after the data is gathered on a background thread.  So they can happen in any order-  it would be a race condition between which one gets called first. (In more practical terms, the "Called from another class" will almost always happen first in the code above because there's little enough code on that thread that it's unlikely the other thread will be scheduled and run before the main thread gets there, but you may see it happen once in a while).</p>

Title: Order of output for log.d?

Body:
I connected my android app to google's realtime database. (This is for school and I'm very, very new at all of this app development stuff.) And I was wondering why my log.d() method outputs it's contents to the logcat in the wrong order. I don't think it's a major issue and I can probably work around it but I'm just curious about why it executes like this or if it's something wrong with my code I have to fix.

Resident Page:

public class ResidentPage extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        ....
        basicReadWrite();
        MethodsFromOtherClass.output();

        return view;
    }

    ...

    public void basicReadWrite(){
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("second message");

        myRef.setValue("Hello again, World!");

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String value = dataSnapshot.getValue(String.class);
                Log.d("ResidentPage", "Value is: " + value);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                Log.w("ResidentPage", "Failed to read value.", error.toException());
            }
        });
    }
}

Methods from other class:

public class MethodsFromOtherClass {
    public static void output(){
        Log.d("ResidentPage", "Called from another class");
    }
}

Logcat:

D/ResidentPage: Called from another class
D/ResidentPage: Value is: Hello again, World!


问:
Why doesn't my code use the correct animation?
I had a functioning fighting game written in Python with movement, frame data, attacks (that didn't work) but no gravity. I'm trying to rewrite it with Godot, but I'm really lost.

I had a system of implementing frame data into my attacks so I could actually transition from idle to attacks and vice versa easily. Right now, my issue is I want to attack and play that animation, but it keeps constantly playing the idle animation. I want to get this one thing working before I start doing hitboxes and collision stuff. Here is my code:

extends KinematicBody2D

export var walking_speed = 100
export var falling_speed = 0
var time = 0
onready var anim = $Sprite
var state = "Idle"

func _ready():
    set_physics_process(true)
    set_process(true)
    $AnimationTree.active = true

func gravity():
    pass

func _physics_process(delta):
    time += delta
    print(time)
    # If you press both A and D, you will stop entirely
    if Input.is_action_pressed("ui_left") and Input.is_action_pressed("ui_right"):
        walking_speed == 0
        $AnimationTree.set("parameters/Neutral/current", 0)
    #if you press A or D, you will move left or right accordingly
    elif Input.is_action_pressed("ui_left"):
        move_and_collide(Vector2(-walking_speed * delta, 0))
        anim.flip_h = true
        $AnimationTree.set("parameters/Neutral/current", 1)
    elif Input.is_action_pressed("ui_right"):
        move_and_collide(Vector2(walking_speed * delta, 0))
        anim.flip_h = false
        $AnimationTree.set("parameters/Neutral/current", 1)
    else:
        walking_speed = walking_speed

    if Input.is_action_just_pressed("Horizontal"):
        $AnimationTree.set("parameters/Neutral/current", 2)

```

This code is basically just a mishmash of a bunch of tutorials of things I was told to do (Like for instance, I was told not use AnimatedSprite and instead use AnimationTree, but it seems the code is a lot more complicated and is just giving me the same problems as last time). If you need me to, I can also post my Python code as well, but it's a giant mess with no comments on it at all.

答:
You can make animations with AnimatedSprite. You have my blessing. AnimatedSprite is there to be used. And "I was told so" is not a good reason not to.

Also, AnimatedSprite vs AnimationPlayer and AnimationTree is not an either or. Yes, there are somethings for which you would need AnimationPlayer and AnimationTree, however you can always have the AnimationPlayer trigger an AnimatedSprite animation. In fact, AnimationPlayer can call any method (and AnimationTree will control the AnimationPlayer). Thus, any work done with AnimatedSprite is not wasted.

Calling set_physics_process will enable or disable _physics_process. And similarly set_process enables or disables _process. However, if you have a the method then it is enabled by default. Thus, you only need to enable them if you disabled them.

We can compress a lot of your _physics_process code:

```<code>func _physics_process(_delta:float) -> void:
    var walking_speed := (
        Input.get_action_strength("ui_right") -
        Input.get_action_strength("ui_left")
    )
    anim.flip_h = walking_speed < 0
    var velocity := Vector2(walking_speed, 0)
    move_and_collide(velocity * delta)
</code>```

The line anim.flip_h = walking_speed < 0 will be setting flip_h to true when walking_speed is negative, and to false otherwise.

And we are setting walking_speed based on get_action_strength will return a number between 0 and 1 that represents how strongly the action is pressed. Which also means that if they are mapped to a joystick or similar, this gives you sensitivity support.

If you prefer to not have that sensitivity, sign will do:

```<code>    var walking_speed := sign(
        Input.get_action_strength("ui_right") -
        Input.get_action_strength("ui_left")
    )
</code>```

With KinematicBody2D you would have to handle gravity. Basically give it some downwards velocity.

```<code>var gravitational_acceleration := 100 # pixels per second squared
var falling_speed := 0

func _physics_process(_delta:float) -> void:
    falling_speed += gravitational_acceleration * delta
    var walking_speed := (
        Input.get_action_strength("ui_right") -
        Input.get_action_strength("ui_left")
    )
    anim.flip_h = walking_speed < 0
    var velocity := Vector2(walking_speed, falling_speed)
    move_and_collide(velocity * delta)
</code>```

However, it is better to implement gravity with move_and_slide:

```<code>var gravitational_acceleration := 100 # pixels per second squared
var falling_speed := 0

func _physics_process(_delta:float) -> void:
    falling_speed += gravitational_acceleration * delta
    var walking_speed := (
        Input.get_action_strength("ui_right") -
        Input.get_action_strength("ui_left")
    )
    anim.flip_h = walking_speed < 0
    var velocity := Vector2(walking_speed, falling_speed)
    velocity = move_and_slide(velocity)
    falling_speed = velocity.y
</code>```

I have removed the multiplication with delta at the end because move_and_slide does that internally. That is, it takes a velocity not a displacement.

This way the falling_speed will not keep growing out of control.

You can also add an up vector (so Godot knows what is a ceiling, what is a floor, and what is a wall), and then you can check is_on_ceiling, is_on_floor and is_on_wall.

Also, you can tell move_and_slide that the floor_max_angle is 0, so it does not slide (nothing counts as a slope, only perfectly horizontal floors are floors), if that is what you want.

And, of course, the animation.

If you are going to use an AnimationTree, I suggest to set the root as an AnimationNodeStateMachine. Then, from code, you can get the state machine playback object, like this:

```<code>var state_machine = $AnimationTree.get("parameters/playback")
</code>```

You can tell it you want it to go to a different state, like this:

```<code>state_machine.travel("name_of_some_state")
</code>```

And you can ask it what the current state is with:

```<code>var state:String = state_machine.get_current_node()
</code>```

You can, for example have an "idle" state in your state machine, and an "attacking" state in your state machine, with a transition from "idle" to "attacking", and another transition from "attacking" to "idle", but that one set to transition "at the end". You can, of course, have other states. Then use the current state (from get_current_node) to figure out what the player can do.

With an AnimationPlayer you can check what is the current_animation and is_playing; you can also connect the "animation_finished" signal. With an AnimatedSrite you can check what is the current animation and whether or not it is playing; you can also connect the "animation_finished" signal.

Body:
I had a functioning fighting game written in Python with movement, frame data, attacks (that didn't work) but no gravity. I'm trying to rewrite it with Godot, but I'm really lost.

I had a system of implementing frame data into my attacks so I could actually transition from idle to attacks and vice versa easily. Right now, my issue is I want to attack and play that animation, but it keeps constantly playing the idle animation. I want to get this one thing working before I start doing hitboxes and collision stuff. Here is my code:

extends KinematicBody2D

export var walking_speed = 100
export var falling_speed = 0
var time = 0
onready var anim = $Sprite
var state = "Idle"

func _ready():
    set_physics_process(true)
    set_process(true)
    $AnimationTree.active = true

func gravity():
    pass

func _physics_process(delta):
    time += delta
    print(time)
    # If you press both A and D, you will stop entirely
    if Input.is_action_pressed("ui_left") and Input.is_action_pressed("ui_right"):
        walking_speed == 0
        $AnimationTree.set("parameters/Neutral/current", 0)
    #if you press A or D, you will move left or right accordingly
    elif Input.is_action_pressed("ui_left"):
        move_and_collide(Vector2(-walking_speed * delta, 0))
        anim.flip_h = true
        $AnimationTree.set("parameters/Neutral/current", 1)
    elif Input.is_action_pressed("ui_right"):
        move_and_collide(Vector2(walking_speed * delta, 0))
        anim.flip_h = false
        $AnimationTree.set("parameters/Neutral/current", 1)
    else:
        walking_speed = walking_speed

    if Input.is_action_just_pressed("Horizontal"):
        $AnimationTree.set("parameters/Neutral/current", 2)

This code is basically just a mishmash of a bunch of tutorials of things I was told to do (Like for instance, I was told not use AnimatedSprite and instead use AnimationTree, but it seems the code is a lot more complicated and is just giving me the same problems as last time). If you need me to, I can also post my Python code as well, but it's a giant mess with no comments on it at all.

Body:
You can make animations with AnimatedSprite. You have my blessing. AnimatedSprite is there to be used. And "I was told so" is not a good reason not to.

Also, AnimatedSprite vs AnimationPlayer and AnimationTree is not an either or. Yes, there are somethings for which you would need AnimationPlayer and AnimationTree, however you can always have the AnimationPlayer trigger an AnimatedSprite animation. In fact, AnimationPlayer can call any method (and AnimationTree will control the AnimationPlayer). Thus, any work done with AnimatedSprite is not wasted.

Calling set_physics_process will enable or disable _physics_process. And similarly set_process enables or disables _process. However, if you have a the method then it is enabled by default. Thus, you only need to enable them if you disabled them.

We can compress a lot of your _physics_process code:

func _physics_process(_delta:float) -> void:
    var walking_speed := (
        Input.get_action_strength("ui_right") -
        Input.get_action_strength("ui_left")
    )
    anim.flip_h = walking_speed < 0
    var velocity := Vector2(walking_speed, 0)
    move_and_collide(velocity * delta)

The line anim.flip_h = walking_speed < 0 will be setting flip_h to true when walking_speed is negative, and to false otherwise.

And we are setting walking_speed based on get_action_strength will return a number between 0 and 1 that represents how strongly the action is pressed. Which also means that if they are mapped to a joystick or similar, this gives you sensitivity support.

If you prefer to not have that sensitivity, sign will do:

    var walking_speed := sign(
        Input.get_action_strength("ui_right") -
        Input.get_action_strength("ui_left")
    )

With KinematicBody2D you would have to handle gravity. Basically give it some downwards velocity.

var gravitational_acceleration := 100 # pixels per second squared
var falling_speed := 0

func _physics_process(_delta:float) -> void:
    falling_speed += gravitational_acceleration * delta
    var walking_speed := (
        Input.get_action_strength("ui_right") -
        Input.get_action_strength("ui_left")
    )
    anim.flip_h = walking_speed < 0
    var velocity := Vector2(walking_speed, falling_speed)
    move_and_collide(velocity * delta)

However, it is better to implement gravity with move_and_slide:

var gravitational_acceleration := 100 # pixels per second squared
var falling_speed := 0

func _physics_process(_delta:float) -> void:
    falling_speed += gravitational_acceleration * delta
    var walking_speed := (
        Input.get_action_strength("ui_right") -
        Input.get_action_strength("ui_left")
    )
    anim.flip_h = walking_speed < 0
    var velocity := Vector2(walking_speed, falling_speed)
    velocity = move_and_slide(velocity)
    falling_speed = velocity.y

I have removed the multiplication with delta at the end because move_and_slide does that internally. That is, it takes a velocity not a displacement.

This way the falling_speed will not keep growing out of control.

You can also add an up vector (so Godot knows what is a ceiling, what is a floor, and what is a wall), and then you can check is_on_ceiling, is_on_floor and is_on_wall.

Also, you can tell move_and_slide that the floor_max_angle is 0, so it does not slide (nothing counts as a slope, only perfectly horizontal floors are floors), if that is what you want.

And, of course, the animation.

If you are going to use an AnimationTree, I suggest to set the root as an AnimationNodeStateMachine. Then, from code, you can get the state machine playback object, like this:

var state_machine = $AnimationTree.get("parameters/playback")

You can tell it you want it to go to a different state, like this:

state_machine.travel("name_of_some_state")

And you can ask it what the current state is with:

var state:String = state_machine.get_current_node()

You can, for example have an "idle" state in your state machine, and an "attacking" state in your state machine, with a transition from "idle" to "attacking", and another transition from "attacking" to "idle", but that one set to transition "at the end". You can, of course, have other states. Then use the current state (from get_current_node) to figure out what the player can do.

With an AnimationPlayer you can check what is the current_animation and is_playing; you can also connect the "animation_finished" signal. With an AnimatedSrite you can check what is the current animation and whether or not it is playing; you can also connect the "animation_finished" signal.


问:
Variable Independent of setState
So say I have a Map and somewhere in my code and I want to save its current state. I set Map Two equal to Map One and go on changing the value of Map One hoping to keep the values of Map Two the same for reference. If I call setState(() {}) after I change Map One it seems to update all values of Map Two as well. This is not what I want. I want to set Map Two and not update until I want to save Map One's state again. It's tough to demonstrate this problem in my code without dumping the whole thing so I'll try to illustrate what I'm talking about below. Just ignore that this code won't actually run, this is the idea. The values of Map Two would be used in a widget but for the sake of example, the value is just being printed. This code would theoretically print foo. I want it to print start. In my mind, there should be something like const or final that I'm just missing that sets a variable and doesn't make it relative.</p>
```<code>Map mapOne = {
  'start' : 'start',
  'end' : 'end'
};
late Map mapTwo;

main() {
  mapTwo = mapOne;
  mapOne = {
    'start' : 'foo',
    'end' : 'foo'
  };

  setState(() {});

  print(mapTwo['start']);
}
</code>```

答:
When you're assigning map one to map two, you're basically setting map one and map two to reference the same object. So to achieve what you want you can do this:

```<code>mapTwo = Map.from(mapOne);
</code>```

Here is an example to verify:

```<code>void main() async {
  final a = {'a': 'b'};
  final b = Map.from(a);
  b['a'] = 'c';
  print(a);
  print(b);
}
</code>```

Title: Variable Independent of setState

Body:
So say I have a Map and somewhere in my code and I want to save its current state. I set Map Two equal to Map One and go on changing the value of Map One hoping to keep the values of Map Two the same for reference. If I call setState(() {}) after I change Map One it seems to update all values of Map Two as well. This is not what I want. I want to set Map Two and not update until I want to save Map One's state again. It's tough to demonstrate this problem in my code without dumping the whole thing so I'll try to illustrate what I'm talking about below. Just ignore that this code won't actually run, this is the idea. The values of Map Two would be used in a widget but for the sake of example, the value is just being printed. This code would theoretically print foo. I want it to print start. In my mind, there should be something like const or final that I'm just missing that sets a variable and doesn't make it relative.

Map mapOne = {
  'start' : 'start',
  'end' : 'end'
};
late Map mapTwo;

main() {
  mapTwo = mapOne;
  mapOne = {
    'start' : 'foo',
    'end' : 'foo'
  };

  setState(() {});

  print(mapTwo['start']);
}

Body:
When you're assigning map one to map two, you're basically setting map one and map two to reference the same object. So to achieve what you want you can do this:

mapTwo = Map.from(mapOne);

Here is an example to verify:

void main() async {
  final a = {'a': 'b'};
  final b = Map.from(a);
  b['a'] = 'c';
  print(a);
  print(b);
}


问:
How to override the vue component props with condition check?
What's the recommended way to override/extends a component?
E.g. I want to override the vuetify component VTextField:

```<code><script>
import { VTextField } from 'vuetify/lib/components';

export default {
  name: 'RTextField',
  extends: VTextField,
  props: {
    outlined: {
      default: true,
    },
    hideDetails: {
      default: true,
    },
  },
};
</script>
</code>```

Above I used the extends to override some default props values.

I want to ask how to conditional set the value for hideDetails, for example based on a specific prop value hint, if there is a hint prop in RTextField, and the hideDetails should be set to false

```<code>`<r-text-field hint="xxx detail description">`
</code>```

答:
Instead of extending, you can wrap VTextField, that way you have complete control over the props and how they should be forwarded to the wrapped component.

Untested:

<template>
  <v-text-field
    :outlined="outlined"
    :hide-details="$attrs.hint ? false : hideDetails"
    v-bind="$attrs"
    v-on="$listeners"
  />
</template>
```
<pre class="lang-js prettyprint-override"><code>import { VTextField } from 'vuetify/lib/components'

export default {
  name: 'RTextField',

  components: {
    VTextField,
  },

  // We'll pass attrs as props via v-bind
  inheritAttrs: false,

  props: {
    outlined: {
      type: Boolean,
      default: true,
    },
    hideDetails: {
      type: Boolean,
      default: true,
    },
  },
}
</code>```

Body:
What's the recommended way to override/extends a component?
E.g. I want to override the vuetify component VTextField:

Above I used the extends to override some default props values.

I want to ask how to conditional set the value for hideDetails, for example based on a specific prop value hint, if there is a hint prop in RTextField, and the hideDetails should be set to false

`<r-text-field hint="xxx detail description">`

Body:
Instead of extending, you can wrap VTextField, that way you have complete control over the props and how they should be forwarded to the wrapped component.

Untested:

<template>
  <v-text-field
    :outlined="outlined"
    :hide-details="$attrs.hint ? false : hideDetails"
    v-bind="$attrs"
    v-on="$listeners"
  />
</template>

import { VTextField } from 'vuetify/lib/components'

export default {
  name: 'RTextField',

  components: {
    VTextField,
  },

  // We'll pass attrs as props via v-bind
  inheritAttrs: false,

  props: {
    outlined: {
      type: Boolean,
      default: true,
    },
    hideDetails: {
      type: Boolean,
      default: true,
    },
  },
}


问:
How to delete records in mysql using csv INFILE method
I have a massive records to delete in the database i've got the csv file that determines how which records needs to be deleted from the table.

I am trying to use INFILE method of sql.

I've previously used this method to insert rows into the database i am also trying to use this method to delete from the table instead of running loop in the python it is because it is very fast.

Table structure

csv file

```<code>info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
</code>```

What i want.

I want to run match the link from csv and link from table and delete that record permanently.

Delete query that i've run.

```<code>DELETE records DATA LOCAL INFILE '/Users/dharmendra/Desktop/aws/node.js/download/xvideos.com-deleted-full.csv' INTO TABLE csv FIELDS TERMINATED BY '|' LINES TERMINATED BY '\n' IGNORE 0 ROWS (link);
</code>```

I've looked for this solution over the internet but i have't got the solution yet.

答:
Can't do it in a single query.  Try for 3, something like this:

```<code>CREATE TEMPORARY TABLE t (...);
LOAD DATA INFILE INTO t (...)...;
DELETE FROM records JOIN t ON ...;
</code>```

If you will be deleting millions of rows, it will take a long time.  If "time" matters, there are faster ways we can discuss.

Body:
I have a massive records to delete in the database i've got the csv file that determines how which records needs to be deleted from the table.

I am trying to use INFILE method of sql.

I've previously used this method to insert rows into the database i am also trying to use this method to delete from the table instead of running loop in the python it is because it is very fast.

Table structure

csv file

info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link
info|link

What i want.

I want to run match the link from csv and link from table and delete that record permanently.

Delete query that i've run.

DELETE records DATA LOCAL INFILE '/Users/dharmendra/Desktop/aws/node.js/download/xvideos.com-deleted-full.csv' INTO TABLE csv FIELDS TERMINATED BY '|' LINES TERMINATED BY '\n' IGNORE 0 ROWS (link);

I've looked for this solution over the internet but i have't got the solution yet.

Body:
Can't do it in a single query.  Try for 3, something like this:

CREATE TEMPORARY TABLE t (...);
LOAD DATA INFILE INTO t (...)...;
DELETE FROM records JOIN t ON ...;

If you will be deleting millions of rows, it will take a long time.  If "time" matters, there are faster ways we can discuss.


问:
How to append np.array?
I have an np.array d1 of (3,6), and an np.array a4 of (6,).

How can I combine the two np.arrays to form an np.array d2 of (4,6)?

My code is as follows:

```<code>import numpy as np
a1=np.array(range(6))
a2=a1+2
a3=a2+3
a4=a3+4
d1=np.array([a1,a2,a3])
d1.shape
</code>```
```<code>Out[44]: (3, 6)
</code>```
```<code>d2=np.array([a1,a2,a3,a4])
d2.shape
d2
</code>```
```<code>Out[45]: (4, 6)
Out[46]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 2,  3,  4,  5,  6,  7],
       [ 5,  6,  7,  8,  9, 10],
       [ 9, 10, 11, 12, 13, 14]])
</code>```

How to get d2 from d1 and a4?

I tried np.insert and np.append, but maybe my usage is wrong and I didn't get the correct result.

答:
a4 is a 1D array, so you can expand it</p>
```<code>import numpy as np

d1 = np.array([[ 0,  1,  2,  3,  4,  5],
               [ 2,  3,  4,  5,  6,  7],
               [ 5,  6,  7,  8,  9, 10]])

a4 = np.array(np.arange(9,15))

d2 = np.concatenate((d1, np.expand_dims(a4,0)), 0)

print(d2)
</code>```

Title: How to append np.array?

Body:
I have an np.array d1 of (3,6), and an np.array a4 of (6,).

How can I combine the two np.arrays to form an np.array d2 of (4,6)?

My code is as follows:

import numpy as np
a1=np.array(range(6))
a2=a1+2
a3=a2+3
a4=a3+4
d1=np.array([a1,a2,a3])
d1.shape

Out[44]: (3, 6)

d2=np.array([a1,a2,a3,a4])
d2.shape
d2

Out[45]: (4, 6)
Out[46]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 2,  3,  4,  5,  6,  7],
       [ 5,  6,  7,  8,  9, 10],
       [ 9, 10, 11, 12, 13, 14]])

How to get d2 from d1 and a4?

I tried np.insert and np.append, but maybe my usage is wrong and I didn't get the correct result.

Body:
a4 is a 1D array, so you can expand it

import numpy as np

d1 = np.array([[ 0,  1,  2,  3,  4,  5],
               [ 2,  3,  4,  5,  6,  7],
               [ 5,  6,  7,  8,  9, 10]])

a4 = np.array(np.arange(9,15))

d2 = np.concatenate((d1, np.expand_dims(a4,0)), 0)

print(d2)


问:
Extract value from jsr223 sampler
enter image description here

enter image description here

How to extract maxValue_max from jsr223 sampler to the next request?
I see that the sampler determines the maximum value, how now to extract and use it?

答:
You do have the value written into a JMeter Variable already, you can just call ${maxValue_max} where required and the variable will be resolved to its respective value.

Or if you prefer Groovy scripting you can use __groovy() function like:

You might also want to call SampleResult.setIgnore() function somewhere in your script so the JSR223 Sampler won't appear in the test results or just switch to JSR223 Post-Processor.

Check out Top 8 JMeter Java Classes You Should Be Using with Groovy for more information on this SampleResult and other JMeter API shorthands available for the JSR223 Test Elements

Title: Extract value from jsr223 sampler


问:
Redshift Spectrum - Referencing an external table in a CTE?
I'm trying to make some data available via Redshift Spectrum to our reporting platform. I chose Spectrum because it offers lower latency to our data lake vs a batched ETL process.

One of the queries I have looks like this

```<code>with txns as (select * from spectrum_table where ...)
select field1, field2, ...
from txns t1
left join txns t2 on t2.id = t1.id
left join txns t3 on t3.id = t1.id
where...
</code>```

Intuitively, this should cache the Spectrum query output in-memory with the CTE, and make it available to query later in query without hitting S3 a second (or third) time.

However, I checked the explain plan, and with each join the number of "S3 Seq Scan"s goes up by one. So it appears to do the Spectrum scan each time the CTE is queried.

Questions:

Is this actually happening? Or is the explain plan wrong? The run-time of this query doesn't appear to increase linearly with the number of joins, so it's hard to tell.

If it is happening, what other options are there to achieve this sort of result? Other than manually creating a temp table (this will be accessed by a reporting tool, so I'd prefer to avoid allowing explicit write access or requiring multiple statements to get the data)

Thanks!

答:
Yes this is really happening.  CTE references are not reused - this is due to the possibility that different data will be used in the different references.  Applying where clauses at table scan is an important performance feature.

You could look into using a materialized view but I expect that you are dynamically applying the where clauses in the CTE so this may not match you need.  If it was me I'd want to understand why the triple self-join.  Seems like there may be a better way to construct the query but it is just a gut feel.

Body:
I'm trying to make some data available via Redshift Spectrum to our reporting platform. I chose Spectrum because it offers lower latency to our data lake vs a batched ETL process.

One of the queries I have looks like this

with txns as (select * from spectrum_table where ...)
select field1, field2, ...
from txns t1
left join txns t2 on t2.id = t1.id
left join txns t3 on t3.id = t1.id
where...

Intuitively, this should cache the Spectrum query output in-memory with the CTE, and make it available to query later in query without hitting S3 a second (or third) time.

However, I checked the explain plan, and with each join the number of "S3 Seq Scan"s goes up by one. So it appears to do the Spectrum scan each time the CTE is queried.

Questions:

Is this actually happening? Or is the explain plan wrong? The run-time of this query doesn't appear to increase linearly with the number of joins, so it's hard to tell.

If it is happening, what other options are there to achieve this sort of result? Other than manually creating a temp table (this will be accessed by a reporting tool, so I'd prefer to avoid allowing explicit write access or requiring multiple statements to get the data)

Thanks!


问:
Is a public instance behind a Load Balancer that much less secure than a private instance behind a NAT Gateway? Due to what risks?
I want to understand the relative security gained when comparing a private instance protected behind a NAT Gateway and a public instance that only accepts connections from its Load Balancer.

How (due to what specific risks) is the latter less secure than the former?

To be upfront, my motivation is to understand how to minimize cost for acceptable security in my AWS network infrastructure. NAT Gateways add cost, and I want to be convinced the costs are necessary before springing for them.

I'm starting from AWS's reference three-tier architecture for a VPC where:

a public subnet hosts a Load Balancer (for incoming connections) and a NAT Gateway (for outgoing), which both must have Public IPs

a private subnet for application instances, which only have Private IPs and communicate out via the earlier NAT gateway

a protected subnet for data (out of scope for this question)

I get how eliminating its public IP protects an instance from unsolicited external connections.

But: Can't I do the same by configuring the security group for an instance with a public IP (which is necessary to use the internet gateway directly) to only accept incoming connections from its load balancer?

I want to understand: Is there a sufficiently secure alternative network architecture which does away with NAT Gateways (or NAT instances — basically, NAT Tax)? Is there a sufficiently secure two-tier architecture?

For example, how much less secure (due to what specific risks) would this two-tier architecture be?

a public subnet hosts a Load Balancer and application instances, and instance security groups only accept connections from the Load Balancer

a private subnet hosts data, and only connects with application instances

Thanks for your time. I'm new to AWS (and StackOverflow) and am looking forward to learn more.

答:
Setting instances in a public subnet with security group (SG) allowing incoming connections from a SG of a ALB or CLB is often good enough.

Placing instances in a private subnet and using NAT is still better, as its much easier to accidentally change SG of instances in a public subnet and allow direct internet access, then to move instances from private to public subnets.

Also NAT gives you one static public IP for all your instances in a private subnet. This often is impotent if you work with external API which requires single IP to whitelist.


问:
How to sync iCal of iPhone Os and google calendar?
I have made event Calendar using EKEventKit,
Now I want to add my iphone ical event to google calendar and vise-versa.
Is it Possible to do this ??</p>

答:
While I can't offer sample code I can offer a high-level solution.

Google Calendar has a public API available here.
Google is also kind enough to offer code to log into Google services here.

If you're familiar with JSON (or you search through stackoverflow) you'll see how you can send events to and from Google Calendar.
Best of luck!


问:
Why does Visual Studio compile my HTTP server app to run on port 5001 when I set it to 443/80?
Is there a separate place from launchsettings.json I need to set the applicationUrl?

Here's the launch setting

```<code>"applicationUrl": "https://127.0.0.1:443;http://127.0.0.1:80"
</code>```

Here's a picture of the app when running inside Visual Studio

Here's a picture of it running from the compiled exe (release & debug)

答:
The config file launchSettings.json is only honored in a few places, such as

Debug from Visual Studio

dotnet run

So if you find it ignored, you know clearly that's by design and you should use other ways to configure Kestrel ports,

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0#url-prefixes

Body:
Is there a separate place from launchsettings.json I need to set the applicationUrl?

Here's the launch setting

"applicationUrl": "https://127.0.0.1:443;http://127.0.0.1:80"

Here's a picture of the app when running inside Visual Studio

Here's a picture of it running from the compiled exe (release & debug)


问:
React with Redux Saga - How to get data back from axios call
I'm workign with React + Redux + Saga and what I have done so far works perfectly but I need to send data back after a (succeful call).

 dispatch to route => sends back an ID =>  gets the ID

But it doesn't do it.

Route (express server):

```<code>axios.post( ...

return res.json(resAlbum);
</code>```

My saga :

```<code>  function* postSpotifyAlbum(obj) {
      obj = {
        method: "POST",
        url: BASEurl,
        params: {
          token: obj.payload.token,
          albumCode: obj.payload.albumCode,
          albumGenres: obj.payload.albumGenres,
          userCode: obj.payload.userCode,
        },
      };

      try {
        const spotifyCategories = yield call(axios, axiosCall(obj));
        yield put({
          type: "POST_SPOTIFY_ALBUMS_SUCCESS",
          payload: JSON.parse(spotifyCategories.data),
        });
        return spotifyCategories.data;
      } catch (error) {
        console.log(error);
        yield put({ type: "POST_SPOTIFY_ALBUMS_ERROR", payload: error });
      }
    }
</code>```

Component:

```<code>const res = await dispatch(postSpotifyAlbums(obj));
</code>```

if I console log the res I just get back Obj I just sent.

Question:

Is there any way to send something back from SAGA?

i.e. res gives me just inserted obj

Or there's no way so then I need to make a second call to the reducer to give me back the just inserted obj?

I repeat, everythig wortks perfectly from the dispatch till the reducer (I ommited to be shorter) I just would like to see if I can expand my SAGA knowledge

答:
Not Sure if you are still looking for the solution or not, but here's my implementation of the code.
Flow goes like this.

We make dispatch request from our component

redux dispatches action called "INITIATE_TRANSACTION".

redux saga intercepts the action and starts making api call based on that

API call is successful and "INITIATE_TRANSACTION_SUCCESS" is dispatched with the api's value.

Now Saga returns value from the axios to the actual calling function from where the step 1 dispatch was called.

Here's the code.

// store.js

import {middleware as thunkMiddleware} from 'redux-saga-thunk';
const middlewares = [thunkMiddleware];
const sagaMiddleware = createSagaMiddleware();
middlewares.push(sagaMiddleware);
if (process.env.NODE_ENV === `development`) {
  const {logger} = require(`redux-logger`);

  middlewares.push(logger);
}

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  white: ['errors'],
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const store = configureStore({
  reducer: persistedReducer,
  middleware: middlewares,
  devTools: process.env.NODE_ENV === `development` ? true : false,
});

// Payment.js(or any of your component)

const handleBtnClick = async (type, value) => {
    console.log('btn click type', type, route.params, value);
    switch (type) {
      case 'pay':
        try {
          let orderId = 'OD_' + moment().format('YYYYMMDDHHmmss');
          // Here we are dispatching action "INITIATE_TRANSACTION" to redux saga.
          // Step 1.
          const response = await props.initiatePayment({
            orderId,
            orderAmount: 10,
            orderCurrency: 'INR',
          });

          console.log('response', response.data.cftoken);
          }catch (error){
          console.log('error', error)
          }
          break;
}

// Middleware used is redux-saga-thunk, which basically implements functionality of thunk in redux saga. so meta: {thunk: true} waits for the whole execution to finish and then continues.
// Step 2
export const initiatePayment = data => ({
  type: INITIATE_TRANSACTION,
  data,
  meta: {thunk: true},
});

//Step 3
// Here post is just a custom function for api call, onError and onSuccess are the handler functions and safe is the wrapper method which basically implements try catch logic and handles errors for us without repeating much of the code.

// paymentSaga.js
function* initiateTransactionSaga({data, meta}) {
  const response = yield call(post, API.INITIATE_TRANSACTION, data);
  return response; //Step 4....
}

export default function* paymentSaga() {
  yield takeLatest(
    INITIATE_TRANSACTION,
    safe(onError, initiateTransactionSaga, onSuccess), //onSuccess required if you want values to be returned to step 1
  );
}

// axiosApi.js

export async function post(url, data, config = {}) {
  console.log('url data config', url, data, config);
  return axiosApi
    .post(url, {...data}, {...config})
    .then(response => response.data);
}

// Sagahelper.js

/**
 * @param handler --- Error handler function. In our case, onError Function
 * @param saga --- Actual Saga function. in our case Api is called and data is returned
 * @param success --- success redux action dispatch function -- in our case, if we need to pass response coming from api to the actual calling function( something like props.viewingItem(data)), then pass it here, otherwise leave it blank
 * @
 */

export const safe = (
  handler: any = null,
  saga: any,
  success: any = null,
  ...args: any
) =>
  function* (action: any) {
    try {
      console.log('action in safe===', action, success);
      const res1 = yield call(saga, ...args, action);
      // Success wrapper. if you pass onSuccess method, then only this part will be executed. If you do not want the values to be returned from redux-saga to your component function call, then i suggest you skip it.
      if (success) {
        yield call(success, res1, action.type, action.meta);
        return res1; //This line returns value to the component function( to step 1)
      }
    } catch (err) {
      yield call(handler, ...args, err, action.type, action.meta);
    }
  };

export function* onError(err: any, type: any, meta: any) {
  console.log('type onError', type);
  yield put({
    type: type + '_ERROR',
    payload: err,
    error: true,
    meta,
  });

  // Do something with the error msg. like show alert, etc...
  return err;
}

export function* onSuccess(response: any, type: any, meta: any) {
  console.log('type onError', response);
  yield put({
    type: type + '_SUCCESS',
    payload: response,
    error: false,
    meta,
  });
  // Do something with the success msg. like show alert, etc...
  return response;
}```

You can find detailed information over here.
https://medium.com/@dhavaljavia.p/redux-saga-return-values-from-saga-to-your-component-using-redux-saga-thunk-17ad6e9e81ef

Body:
I'm workign with React + Redux + Saga and what I have done so far works perfectly but I need to send data back after a (succeful call).

 dispatch to route => sends back an ID =>  gets the ID

But it doesn't do it.

Route (express server):

axios.post( ...

return res.json(resAlbum);

My saga :

  function* postSpotifyAlbum(obj) {
      obj = {
        method: "POST",
        url: BASEurl,
        params: {
          token: obj.payload.token,
          albumCode: obj.payload.albumCode,
          albumGenres: obj.payload.albumGenres,
          userCode: obj.payload.userCode,
        },
      };

      try {
        const spotifyCategories = yield call(axios, axiosCall(obj));
        yield put({
          type: "POST_SPOTIFY_ALBUMS_SUCCESS",
          payload: JSON.parse(spotifyCategories.data),
        });
        return spotifyCategories.data;
      } catch (error) {
        console.log(error);
        yield put({ type: "POST_SPOTIFY_ALBUMS_ERROR", payload: error });
      }
    }

Component:

const res = await dispatch(postSpotifyAlbums(obj));

if I console log the res I just get back Obj I just sent.

Question:

Is there any way to send something back from SAGA?

i.e. res gives me just inserted obj

Or there's no way so then I need to make a second call to the reducer to give me back the just inserted obj?

I repeat, everythig wortks perfectly from the dispatch till the reducer (I ommited to be shorter) I just would like to see if I can expand my SAGA knowledge

Body:
Not Sure if you are still looking for the solution or not, but here's my implementation of the code.
Flow goes like this.

We make dispatch request from our component

redux dispatches action called "INITIATE_TRANSACTION".

redux saga intercepts the action and starts making api call based on that

API call is successful and "INITIATE_TRANSACTION_SUCCESS" is dispatched with the api's value.

Now Saga returns value from the axios to the actual calling function from where the step 1 dispatch was called.

Here's the code.

// store.js

import {middleware as thunkMiddleware} from 'redux-saga-thunk';
const middlewares = [thunkMiddleware];
const sagaMiddleware = createSagaMiddleware();
middlewares.push(sagaMiddleware);
if (process.env.NODE_ENV === `development`) {
  const {logger} = require(`redux-logger`);

  middlewares.push(logger);
}

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  white: ['errors'],
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const store = configureStore({
  reducer: persistedReducer,
  middleware: middlewares,
  devTools: process.env.NODE_ENV === `development` ? true : false,
});

// Payment.js(or any of your component)

const handleBtnClick = async (type, value) => {
    console.log('btn click type', type, route.params, value);
    switch (type) {
      case 'pay':
        try {
          let orderId = 'OD_' + moment().format('YYYYMMDDHHmmss');
          // Here we are dispatching action "INITIATE_TRANSACTION" to redux saga.
          // Step 1.
          const response = await props.initiatePayment({
            orderId,
            orderAmount: 10,
            orderCurrency: 'INR',
          });

          console.log('response', response.data.cftoken);
          }catch (error){
          console.log('error', error)
          }
          break;
}

// Middleware used is redux-saga-thunk, which basically implements functionality of thunk in redux saga. so meta: {thunk: true} waits for the whole execution to finish and then continues.
// Step 2
export const initiatePayment = data => ({
  type: INITIATE_TRANSACTION,
  data,
  meta: {thunk: true},
});

//Step 3
// Here post is just a custom function for api call, onError and onSuccess are the handler functions and safe is the wrapper method which basically implements try catch logic and handles errors for us without repeating much of the code.

// paymentSaga.js
function* initiateTransactionSaga({data, meta}) {
  const response = yield call(post, API.INITIATE_TRANSACTION, data);
  return response; //Step 4....
}

export default function* paymentSaga() {
  yield takeLatest(
    INITIATE_TRANSACTION,
    safe(onError, initiateTransactionSaga, onSuccess), //onSuccess required if you want values to be returned to step 1
  );
}

// axiosApi.js

export async function post(url, data, config = {}) {
  console.log('url data config', url, data, config);
  return axiosApi
    .post(url, {...data}, {...config})
    .then(response => response.data);
}

// Sagahelper.js

/**
 * @param handler --- Error handler function. In our case, onError Function
 * @param saga --- Actual Saga function. in our case Api is called and data is returned
 * @param success --- success redux action dispatch function -- in our case, if we need to pass response coming from api to the actual calling function( something like props.viewingItem(data)), then pass it here, otherwise leave it blank
 * @
 */

export const safe = (
  handler: any = null,
  saga: any,
  success: any = null,
  ...args: any
) =>
  function* (action: any) {
    try {
      console.log('action in safe===', action, success);
      const res1 = yield call(saga, ...args, action);
      // Success wrapper. if you pass onSuccess method, then only this part will be executed. If you do not want the values to be returned from redux-saga to your component function call, then i suggest you skip it.
      if (success) {
        yield call(success, res1, action.type, action.meta);
        return res1; //This line returns value to the component function( to step 1)
      }
    } catch (err) {
      yield call(handler, ...args, err, action.type, action.meta);
    }
  };

export function* onError(err: any, type: any, meta: any) {
  console.log('type onError', type);
  yield put({
    type: type + '_ERROR',
    payload: err,
    error: true,
    meta,
  });

  // Do something with the error msg. like show alert, etc...
  return err;
}

export function* onSuccess(response: any, type: any, meta: any) {
  console.log('type onError', response);
  yield put({
    type: type + '_SUCCESS',
    payload: response,
    error: false,
    meta,
  });
  // Do something with the success msg. like show alert, etc...
  return response;
}

You can find detailed information over here.
https://medium.com/@dhavaljavia.p/redux-saga-return-values-from-saga-to-your-component-using-redux-saga-thunk-17ad6e9e81ef


问:
Opposite of PreventDefault for links and drop-down selector?
I have a jquery click event for a bunch of links and one drop-down selector in my MVC view and I preventDefault on them before doing the event, because most of them redirect to a view (the redirect stops my jquery code doesn't it?). After all of my callbacks in my click event, I would like the links and drop-down selector to do their default event so it doesn't just sit on the page like nothing has happened.

Is there an easy way to get all of the links/drop-down to return to default and then programatically click them in jquery? I've tried $(this).click() and $(this).submit() and e.click() and e.submit() with no luck.

Here is my code

```<code> $("input,a,select").not("#SubmitButton").click(function (e) {
        e.preventDefault();
        console.log("prevented default");
        deletePreview($(this));
    });
    function deletePreview(button) {
        console.log("clicked");
        //Delete Offer from DB
        $.post('@Url.Content("~/")Offer/DeleteJoAnnOffer/?offerId=' + offerID, function (data) {
              console.log("finished deleting");
              if (button.attr('id') == "CancelButton") {
                 window.location.href = '@Url.Content("~/")Offer/CreateJoAnn/';
              } else {

                  //DO DEFAULT ACTION HERE

              }
       });
    };
</code>```

[EDIT]: One more question: If I don't use preventDefault(), my jquery event executes (well the initial part because my console logs "clicked"), but I cannot confirm if the jquery posts are actually executing because the console refreshes on the new page.

答: I think in your case you don't need to call the preventDefault, because your event handler will be executed first. (Maybe in the if you could call it when you want to navigate somewhere else.)</p>

Body:
I have a jquery click event for a bunch of links and one drop-down selector in my MVC view and I preventDefault on them before doing the event, because most of them redirect to a view (the redirect stops my jquery code doesn't it?). After all of my callbacks in my click event, I would like the links and drop-down selector to do their default event so it doesn't just sit on the page like nothing has happened.

Is there an easy way to get all of the links/drop-down to return to default and then programatically click them in jquery? I've tried $(this).click() and $(this).submit() and e.click() and e.submit() with no luck.

Here is my code

 $("input,a,select").not("#SubmitButton").click(function (e) {
        e.preventDefault();
        console.log("prevented default");
        deletePreview($(this));
    });
    function deletePreview(button) {
        console.log("clicked");
        //Delete Offer from DB
        $.post('@Url.Content("~/")Offer/DeleteJoAnnOffer/?offerId=' + offerID, function (data) {
              console.log("finished deleting");
              if (button.attr('id') == "CancelButton") {
                 window.location.href = '@Url.Content("~/")Offer/CreateJoAnn/';
              } else {

                  //DO DEFAULT ACTION HERE

              }
       });
    };

[EDIT]: One more question: If I don't use preventDefault(), my jquery event executes (well the initial part because my console logs "clicked"), but I cannot confirm if the jquery posts are actually executing because the console refreshes on the new page.


问:
SpeechRecognizer: isRecognitionAvailable() vs isOnDeviceRecognitionAvailable()
isRecognitionAvailable() -
Added in API level 8

Checks whether a speech recognition service is available on the system. If this method returns false, SpeechRecognizer#createSpeechRecognizer(Context) will fail.

isOnDeviceRecognitionAvailable() -
Added in API level 31

Checks whether an on-device speech recognition service is available on the system. If this method returns false, SpeechRecognizer#createOnDeviceSpeechRecognizer(Context) will fail.

I want to build Speech to text feature in one of my apps. I'm unable to understand the difference between isRecognitionAvailable() and isOnDeviceRecognitionAvailable(). I need help with checking whether Speech recognition is available on the phone or not. Please help me out, thanks in advance.

答:
Speech recognition can happen locally (on the phone) or remotely (on some server somewhere on the internet).  isOnDeviceRecognitionAvailable returns true if there is a speech recognizer that doesn't need the internet available.  isRecognitionAvailable will return true if any speech recognizer, local or remote, exists.

Why would you not want to use a remote solution?  It's likely slower, and there are privacy issues (their recorded speech would be sent to the cloud).  So there's applications where it isn't appropriate to use.  Thus why the two functions exist-  so you can make that choice.


问:
ssl.SSLCertVerificationError Windows 10
I'm developing with python 3.9.6.
I encounter this error...

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)`

Someone help me ?

Thanks

答:
Your question needs a bit more context but try this:</p>
```<code>import ssl
ssl._create_default_https_context = ssl._create_unverified_context
</code>```

Title: ssl.SSLCertVerificationError Windows 10

Body:
Your question needs a bit more context but try this:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context