问:
Pulling data using Cloud Firestore ODM
I have this database schema:

And in my repository, i am pulling data like this and I am not sure this is the most efficient way of doing it.
I basically assign every subcollection defined in Entity class(for example Subject) a stream...
Could you please suggest, what is the correct way of doing this? Thank you.

```<code>@LazySingleton(as: ISubjectRepository)
class SubjectRepository implements ISubjectRepository{

  final FirebaseFirestore _firestore;

  SubjectRepository(this._firestore);

  @override
  Stream<Either<SubjectFailure, List<Subject.Subject>>> watchAll() async* {

    yield*  subjectsRef
        //snapshots() returns a stream of QuerySnapshot
        .snapshots()
        //list
        .map((snapshot){
          // to domain
            return right<SubjectFailure, List<Subject.Subject>>(
              snapshot.docs.map<Subject.Subject>((SubjectQueryDocumentSnapshot subjectQueryDocumentSnapshot){
                CategoryCollectionReference categoryCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories;

                // fill subject with category
                Stream<List<Category>> categories = categoryCollectionReference
                    .snapshots()
                    .map((CategoryQuerySnapshot categoryQuerySnapshot){

                      return categoryQuerySnapshot.docs.map<Category>((CategoryQueryDocumentSnapshot categoryQueryDocumentSnapshot){

                        SubcategoryCollectionReference subcategoryCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories;

                        // fill category with subcategories
                        Stream<List<Subcategory>> subcategories = subcategoryCollectionReference
                          .snapshots()
                          .map((SubcategoryQuerySnapshot subcategoryQuerySnapshot){
                            return subcategoryQuerySnapshot.docs.map<Subcategory>((SubcategoryQueryDocumentSnapshot subcategoryQueryDocumentSnapshot){

                              print('INSIDE REPOSITORY');

                              ArticleCollectionReference articleCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories.doc(subcategoryQueryDocumentSnapshot.id).articles;

                              // fill subcategory with articles
                              Stream<List<Article>> articles = articleCollectionReference
                                .snapshots()
                                .map((ArticleQuerySnapshot articleQuerySnapshot){

                                  print('completings articles');

                                  return articleQuerySnapshot.docs.map<Article>((ArticleQueryDocumentSnapshot articleQueryDocumentSnapshot){
                                    return articleQueryDocumentSnapshot.data;
                                  }).toList();
                                });

                              QuestionSectionCollectionReference questionSectionCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories.doc(subcategoryQueryDocumentSnapshot.id).questionsections;

                              // fill subcategory with question sections
                              Stream<List<QuestionSection>> questionSections = questionSectionCollectionReference
                                  .snapshots()
                                  .map((QuestionSectionQuerySnapshot questionSectionQuerySnapshot){

                                    print('completing question section');

                                    return questionSectionQuerySnapshot.docs.map<QuestionSection>((QuestionSectionQueryDocumentSnapshot questionSectionQueryDocumentSnapshot){
                                    // fill question section with questions
                                    QuestionCollectionReference questionCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories.doc(subcategoryQueryDocumentSnapshot.id).questionsections.doc(questionSectionQueryDocumentSnapshot.id).questions;
                                    Stream<List<Question>> questions = questionCollectionReference
                                      .snapshots()
                                      .map((QuestionQuerySnapshot questionQuerySnapshot){

                                        print('completing questions');

                                        return questionQuerySnapshot.docs.map<Question>((QuestionQueryDocumentSnapshot questionQueryDocumentSnapshot){
                                          // fill question with options
                                          OptionCollectionReference optionCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories.doc(subcategoryQueryDocumentSnapshot.id).questionsections.doc(questionSectionQueryDocumentSnapshot.id).questions.doc(questionQueryDocumentSnapshot.id).options;
                                          Stream<List<Option.Option>> options = optionCollectionReference
                                            .snapshots()
                                            .map((OptionQuerySnapshot optionQuerySnapshot){
                                              return optionQuerySnapshot.docs.map<Option.Option>((OptionQueryDocumentSnapshot optionQueryDocumentSnapshot){
                                                return optionQueryDocumentSnapshot.data;
                                              }).toList();
                                            });

                                          Question completedQuestion = questionQueryDocumentSnapshot.data;

                                          // some try to push correct options length into question
                                          // int correctOptionsLength = questionQueryDocumentSnapshot.data.options.where((Option.Option option) {
                                          //   return option.correct;
                                          // }).length;

                                          completedQuestion.options = options;

                                          return completedQuestion;

                                        }).toList();
                                      });

                                    QuestionSection completedQuestionSection = questionSectionQueryDocumentSnapshot.data;

                                    print('RETURNING COMPLETED QUESTION SECTION');

                                    completedQuestionSection.questions = questions;

                                    print(completedQuestionSection.questions.isEmpty);

                                    return completedQuestionSection;
                                }).toList();
                              });

                              // assign uncompleted Subcategory
                              Subcategory completedSubcategory = subcategoryQueryDocumentSnapshot.data;
                              // assign fields to complete Subcategory
                              completedSubcategory.articles = articles;
                              completedSubcategory.questionSections = questionSections;

                              return completedSubcategory;
                            }).toList();
                          });

                        // return completed category
                        var completedCategory = categoryQueryDocumentSnapshot.data;
                        completedCategory.subcategories = subcategories;
                        return completedCategory;
                      }).toList();
                    });

                Subject.Subject completedSubject = subjectQueryDocumentSnapshot.data;
                completedSubject.categories = categories;

                return completedSubject;
                // used previously, outdated
                // return Subject.fromJson(doc.data() as Map<String, dynamic>);
            }).toList()
          );
        }).onErrorReturnWith((error, stackTrace) {
            print(error);
            print(stackTrace);
            // todo implement onError functionality and null check !
            if (error is FirebaseException && error.message!.contains('PERMISSION_DENIED')) {
                return left(const SubjectFailure.insufficientPermission());
            } else {
            return left(const SubjectFailure.unexpected());
            }
        });
  }
}
</code>```

The model/entity:

```<code>part 'subject.g.dart';

@JsonSerializable(explicitToJson: true)
class Subject{

  Subject({required this.title, required this.titleUI});

  final String title;

  final String titleUI;

  // added later
  @JsonKey(ignore: true)
  late Stream<List<Category>> categories;

  // final IconData icon;

  factory Subject.fromJson(Map<String, Object?> json) => _$SubjectFromJson(json);

  Map<String, Object?> toJson() => _$SubjectToJson(this);
}

@Collection<Subject>('MSubjects')
@Collection<Category>('MSubjects/*/categories')
@Collection<Subcategory>('MSubjects/*/categories/*/subcategories')
@Collection<Article>('MSubjects/*/categories/*/subcategories/*/articles')
@Collection<QuestionSection>('MSubjects/*/categories/*/subcategories/*/questionsections')
@Collection<Question>('MSubjects/*/categories/*/subcategories/*/questionsections/*/questions')
@Collection<Option>('MSubjects/*/categories/*/subcategories/*/questionsections/*/questions/*/options')
final subjectsRef = SubjectCollectionReference();
</code>```

Title: Pulling data using Cloud Firestore ODM

Body:
I have this database schema:

And in my repository, i am pulling data like this and I am not sure this is the most efficient way of doing it.
I basically assign every subcollection defined in Entity class(for example Subject) a stream...
Could you please suggest, what is the correct way of doing this? Thank you.

@LazySingleton(as: ISubjectRepository)
class SubjectRepository implements ISubjectRepository{

  final FirebaseFirestore _firestore;

  SubjectRepository(this._firestore);

  @override
  Stream<Either<SubjectFailure, List<Subject.Subject>>> watchAll() async* {

    yield*  subjectsRef
        //snapshots() returns a stream of QuerySnapshot
        .snapshots()
        //list
        .map((snapshot){
          // to domain
            return right<SubjectFailure, List<Subject.Subject>>(
              snapshot.docs.map<Subject.Subject>((SubjectQueryDocumentSnapshot subjectQueryDocumentSnapshot){
                CategoryCollectionReference categoryCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories;

                // fill subject with category
                Stream<List<Category>> categories = categoryCollectionReference
                    .snapshots()
                    .map((CategoryQuerySnapshot categoryQuerySnapshot){

                      return categoryQuerySnapshot.docs.map<Category>((CategoryQueryDocumentSnapshot categoryQueryDocumentSnapshot){

                        SubcategoryCollectionReference subcategoryCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories;

                        // fill category with subcategories
                        Stream<List<Subcategory>> subcategories = subcategoryCollectionReference
                          .snapshots()
                          .map((SubcategoryQuerySnapshot subcategoryQuerySnapshot){
                            return subcategoryQuerySnapshot.docs.map<Subcategory>((SubcategoryQueryDocumentSnapshot subcategoryQueryDocumentSnapshot){

                              print('INSIDE REPOSITORY');

                              ArticleCollectionReference articleCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories.doc(subcategoryQueryDocumentSnapshot.id).articles;

                              // fill subcategory with articles
                              Stream<List
> articles = articleCollectionReference
                                .snapshots()
                                .map((ArticleQuerySnapshot articleQuerySnapshot){

                                  print('completings articles');

                                  return articleQuerySnapshot.docs.map
((ArticleQueryDocumentSnapshot articleQueryDocumentSnapshot){
                                    return articleQueryDocumentSnapshot.data;
                                  }).toList();
                                });

                              QuestionSectionCollectionReference questionSectionCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories.doc(subcategoryQueryDocumentSnapshot.id).questionsections;

                              // fill subcategory with question sections
                              Stream<List<QuestionSection>> questionSections = questionSectionCollectionReference
                                  .snapshots()
                                  .map((QuestionSectionQuerySnapshot questionSectionQuerySnapshot){

                                    print('completing question section');

                                    return questionSectionQuerySnapshot.docs.map<QuestionSection>((QuestionSectionQueryDocumentSnapshot questionSectionQueryDocumentSnapshot){
                                    // fill question section with questions
                                    QuestionCollectionReference questionCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories.doc(subcategoryQueryDocumentSnapshot.id).questionsections.doc(questionSectionQueryDocumentSnapshot.id).questions;
                                    Stream<List<Question>> questions = questionCollectionReference
                                      .snapshots()
                                      .map((QuestionQuerySnapshot questionQuerySnapshot){

                                        print('completing questions');

                                        return questionQuerySnapshot.docs.map<Question>((QuestionQueryDocumentSnapshot questionQueryDocumentSnapshot){
                                          // fill question with options
                                          OptionCollectionReference optionCollectionReference = subjectsRef.doc(subjectQueryDocumentSnapshot.data.title).categories.doc(categoryQueryDocumentSnapshot.id).subcategories.doc(subcategoryQueryDocumentSnapshot.id).questionsections.doc(questionSectionQueryDocumentSnapshot.id).questions.doc(questionQueryDocumentSnapshot.id).options;
                                          Stream<List<Option.Option>> options = optionCollectionReference
                                            .snapshots()
                                            .map((OptionQuerySnapshot optionQuerySnapshot){
                                              return optionQuerySnapshot.docs.map<Option.Option>((OptionQueryDocumentSnapshot optionQueryDocumentSnapshot){
                                                return optionQueryDocumentSnapshot.data;
                                              }).toList();
                                            });

                                          Question completedQuestion = questionQueryDocumentSnapshot.data;

                                          // some try to push correct options length into question
                                          // int correctOptionsLength = questionQueryDocumentSnapshot.data.options.where((Option.Option option) {
                                          //   return option.correct;
                                          // }).length;

                                          completedQuestion.options = options;

                                          return completedQuestion;

                                        }).toList();
                                      });

                                    QuestionSection completedQuestionSection = questionSectionQueryDocumentSnapshot.data;

                                    print('RETURNING COMPLETED QUESTION SECTION');

                                    completedQuestionSection.questions = questions;

                                    print(completedQuestionSection.questions.isEmpty);

                                    return completedQuestionSection;
                                }).toList();
                              });

                              // assign uncompleted Subcategory
                              Subcategory completedSubcategory = subcategoryQueryDocumentSnapshot.data;
                              // assign fields to complete Subcategory
                              completedSubcategory.articles = articles;
                              completedSubcategory.questionSections = questionSections;

                              return completedSubcategory;
                            }).toList();
                          });

                        // return completed category
                        var completedCategory = categoryQueryDocumentSnapshot.data;
                        completedCategory.subcategories = subcategories;
                        return completedCategory;
                      }).toList();
                    });

                Subject.Subject completedSubject = subjectQueryDocumentSnapshot.data;
                completedSubject.categories = categories;

                return completedSubject;
                // used previously, outdated
                // return Subject.fromJson(doc.data() as Map<String, dynamic>);
            }).toList()
          );
        }).onErrorReturnWith((error, stackTrace) {
            print(error);
            print(stackTrace);
            // todo implement onError functionality and null check !
            if (error is FirebaseException && error.message!.contains('PERMISSION_DENIED')) {
                return left(const SubjectFailure.insufficientPermission());
            } else {
            return left(const SubjectFailure.unexpected());
            }
        });
  }
}

The model/entity:

part 'subject.g.dart';

@JsonSerializable(explicitToJson: true)
class Subject{

  Subject({required this.title, required this.titleUI});

  final String title;

  final String titleUI;

  // added later
  @JsonKey(ignore: true)
  late Stream<List<Category>> categories;

  // final IconData icon;

  factory Subject.fromJson(Map<String, Object?> json) => _$SubjectFromJson(json);

  Map<String, Object?> toJson() => _$SubjectToJson(this);
}

@Collection<Subject>('MSubjects')
@Collection<Category>('MSubjects/*/categories')
@Collection<Subcategory>('MSubjects/*/categories/*/subcategories')
@Collection
('MSubjects/*/categories/*/subcategories/*/articles')
@Collection<QuestionSection>('MSubjects/*/categories/*/subcategories/*/questionsections')
@Collection<Question>('MSubjects/*/categories/*/subcategories/*/questionsections/*/questions')
@Collection<Option>('MSubjects/*/categories/*/subcategories/*/questionsections/*/questions/*/options')
final subjectsRef = SubjectCollectionReference();


来源: stackexchange

问:
I need help for my basic drag and drop program
I have put together a program for me and my friends to use while playing D&D and the basic premise is that the user can upload an image of the map they want to use and then they can upload an image of the character they want to use and drang drop the character around the map. I have only set it up to take one charecter for now just until I get it working properly.

The problem I am encountering is when I run it the drag isDragging flag is remaining false, so it seems that the dragStart is not starting so the drag is not working at all.

Code Posted Below -

```<code><html>
<head>
  <style>
    /* style the map and character elements */
    #map {
      width: 100%;
      height: 100%;
      border: 1px solid black;
      position: relative;
    }
    #map-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
      position: absolute;
    }
    #character {
      width: 50px;
      height: 50px;
      border: 1px solid black;
      position: relative;
    }
    #character-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
      position: absolute;
    }
  </style>
</head>
<body>
  <!-- create the map and character elements -->
  <div id="map">
    <img id="map-image" src="#" alt="map image">
    <div id="character">
      <img id="character-image" src="#" alt="character image">
    </div>
  </div>
  <form id="upload-form">
    <input type="file" id="upload-map-input" accept="image/*">
    <input type="file" id="upload-character-input" accept="image/*">
  </form>
  <script>
    // get the map and character elements
    const map = document.getElementById('map');
    const mapImage = document.getElementById('map-image');
    const character = document.getElementById('character');
    const characterImage = document.getElementById('character-image');
    const uploadForm = document.getElementById('upload-form');
    const uploadMapInput = document.getElementById('upload-map-input');
    const uploadCharacterInput = document.getElementById('upload-character-input');

    let isDragging = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    let xOffset = 0;
    let yOffset = 0;

    character.addEventListener("mousedown", dragStart);
    character.addEventListener("mouseup", dragEnd);
    character.addEventListener("mousemove", drag);

    uploadMapInput.addEventListener("change", uploadMap);
    uploadCharacterInput.addEventListener("change", uploadCharacter);

    function dragStart(e) {
      initialX = e.clientX - xOffset;
      initialY = e.clientY - yOffset;

      if (e.target === character) {
        isDragging = true;
      }
    }

    function dragEnd(e) {
      initialX = currentX;
      initialY = currentY;

      isDragging = false;
    }

    function drag(e) {
        console.log(isDragging);
      if (isDragging) {
        e.preventDefault();
        currentX = e.clientX - initialX;
        currentY = e.clientY - initialY;

        xOffset = currentX;
        yOffset = currentY;

        setTranslate(currentX, currentY, character);
      }
    }

    function setTranslate(xPos, yPos, el) {
      el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
    }

    function uploadMap(e) {
      const file = e.target.files[0];

      if (file) {
        const reader = new FileReader();

        reader.onloadend = function() {
          mapImage.src = reader.result;
        }
        reader.readAsDataURL(file);
      }
    }

    function uploadCharacter(e) {
      const file = e.target.files[0];

      if (file) {
        const reader = new FileReader();

        reader.onloadend = function() {
          characterImage.src = reader.result;
        }
        reader.readAsDataURL(file);
      }
    }
  </script>
</body>
</html>

</code>```

Any help is appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I have put together a program for me and my friends to use while playing D&D and the basic premise is that the user can upload an image of the map they want to use and then they can upload an image of the character they want to use and drang drop the character around the map. I have only set it up to take one charecter for now just until I get it working properly.

The problem I am encountering is when I run it the drag isDragging flag is remaining false, so it seems that the dragStart is not starting so the drag is not working at all.

Code Posted Below -

  <form id="upload-form">
    <input type="file" id="upload-map-input" accept="image/*">
    <input type="file" id="upload-character-input" accept="image/*">
  </form>

Any help is appreciated.


问:
'php' is not recognized as an internal or external command, operable program or batch file, although environment path is set
When I run php -v I get 'php' is not recognized as an internal or external command, operable program or batch file.. Problem is that I set an environment variable, so im not sure what else could be wrong. I have WAMP installed and have three php versions on it 8.0.26, 8.1.13 and 8.2.0.

Environment variable path:

C:\wamp64\bin\php\php8.0.26

This is where I added the variable:

https://gyazo.com/7453dd9bb6dd4b44927c8a33916fd0dc

Result of echo %Path%

```<code>C:\Users\[MyName]>echo %Path%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Azure Data Studio\bin;C:\Program Files\nodejs\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\dotnet\;C:\ProgramData\ComposerSetup\bin;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;C:\Program Files\Git\cmd;C:\Program Files\PowerShell\7\;C:\wamp64\bin\php\php8.0.26;C:\Users\[MyName]\AppData\Local\Microsoft\WindowsApps;C:\Users\[MyName]\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\[MyName]\.dotnet\tools;C:\Program Files\Azure Data Studio\bin;C:\Users\[MyName]\AppData\Roaming\npm;C:\Program Files\heroku\bin;C:\Users\[MyName]\AppData\Roaming\Composer\vendor\bin;C:\Users\[MyName]\AppData\Local\GitHubDesktop\bin;
</code>```

result of dir C:\wamp64\bin\php\php8.0.26

```<code>C:\Users\[MyName]>dir C:\wamp64\bin\php\php8.0.26
The system cannot find the path specified.
</code>```

Body:
When I run php -v I get 'php' is not recognized as an internal or external command, operable program or batch file.. Problem is that I set an environment variable, so im not sure what else could be wrong. I have WAMP installed and have three php versions on it 8.0.26, 8.1.13 and 8.2.0.

Environment variable path:

C:\wamp64\bin\php\php8.0.26

This is where I added the variable:

https://gyazo.com/7453dd9bb6dd4b44927c8a33916fd0dc

Result of echo %Path%

C:\Users\[MyName]>echo %Path%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Azure Data Studio\bin;C:\Program Files\nodejs\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\dotnet\;C:\ProgramData\ComposerSetup\bin;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;C:\Program Files\Git\cmd;C:\Program Files\PowerShell\7\;C:\wamp64\bin\php\php8.0.26;C:\Users\[MyName]\AppData\Local\Microsoft\WindowsApps;C:\Users\[MyName]\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\[MyName]\.dotnet\tools;C:\Program Files\Azure Data Studio\bin;C:\Users\[MyName]\AppData\Roaming\npm;C:\Program Files\heroku\bin;C:\Users\[MyName]\AppData\Roaming\Composer\vendor\bin;C:\Users\[MyName]\AppData\Local\GitHubDesktop\bin;

result of dir C:\wamp64\bin\php\php8.0.26

C:\Users\[MyName]>dir C:\wamp64\bin\php\php8.0.26
The system cannot find the path specified.


问:
Manual ARIMA forecasting in python
I'm trying to make manual ARIMA prediction
using the following parameters:

fitted parameters using ARIMA python

How can I write the manual prediction formula using the above parameters?

I'm trying to make manual prediction to compare it with the prediction result of python forecast function.

Title: Manual ARIMA forecasting in python


问:
I am unable to create a new column with name 'Tidy_Tweets' where I have to convert String to integer for vectorizing it

def remove_pattern(text, pattern_regex):
    r = re.findall(pattern_regex, text)
    for i in r:
        text = re.sub(i, '', text)

    return text

Tidy_tweets = int('Tweets')
```
<p>Then this is the error I am getting.</p>
```ValueError: invalid literal for int() with base 10: 'Tweets'
```

After this I want to vectorize it.

Body:
def remove_pattern(text, pattern_regex):
    r = re.findall(pattern_regex, text)
    for i in r:
        text = re.sub(i, '', text)

    return text

Tidy_tweets = int('Tweets')

Then this is the error I am getting.

ValueError: invalid literal for int() with base 10: 'Tweets'

After this I want to vectorize it.


问:
How can I search for the first blank row in a google sheet
I need to write in an android kodular app script a command line to sum an entire colum and put the result in the first below blank row. I am creating an app for android and the user introduces values that fills cells in columns. After the user complete his job, the program should make the sum of each column and put the result in the cells on the botom of the columns... for each column... Apreciate your help.</p>


问:
The given role or permission should use guard Spatie permissions?
I use this code to create a role and assign it:

```<code>$role = \Spatie\Permission\Models\Role::create(['name' => 'doctor']);
$doctor = \App\Models\Doctor::find(1);
$doctor->assignRole($role);
</code>```

But I got the error:

"message": "The given role or permission should use guard `` instead
of sanctum."

Inside auth.php, there is:

```<code>'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],
</code>```

How to fix that?

Body:
I use this code to create a role and assign it:

$role = \Spatie\Permission\Models\Role::create(['name' => 'doctor']);
$doctor = \App\Models\Doctor::find(1);
$doctor->assignRole($role);

But I got the error:

"message": "The given role or permission should use guard `` instead
of sanctum."

Inside auth.php, there is:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],

How to fix that?


问:
Deployment issues with railway
due to the new pricing of heroku I decided to switch from heroku to railway. At first I encountered a cors header error but then I added
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') to my settings.py file. The error stopped occurring but now I'm facing a new error

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Server Error</title>
</code>```

and the title of the error is response status is 503.

I've set Debug to False, I've added the url to the list of Allowed hosts and I've also added corsheaders to installed apps and the cors middleware. Any help with go a long way.

Title: Deployment issues with railway

Body:
due to the new pricing of heroku I decided to switch from heroku to railway. At first I encountered a cors header error but then I added
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') to my settings.py file. The error stopped occurring but now I'm facing a new error

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Server Error</title>

and the title of the error is response status is 503.

I've set Debug to False, I've added the url to the list of Allowed hosts and I've also added corsheaders to installed apps and the cors middleware. Any help with go a long way.


问:
Python event handler with arguments is executed on declaration(and not with firing events)
When declaring event-handlers in python, this works and react on buttonclicks like it suppose to be

```<code>btn1=tk.Button(master=f, text='<<', command=self.btn_pic_prev)
</code>```

In this case, the method is executed on declaration-time, but not when button-events are fired.

```<code>btn1=tk.Button(master=f, text='<<', command=self.btn_pic_prev())
</code>```

or

```<code>btn1=tk.Button(master=f, text='<<', command=self.btn_pic_prev(arg))
</code>```

Why is that?

How to pass arguments to a method/eventhandler in python?

Body:
When declaring event-handlers in python, this works and react on buttonclicks like it suppose to be

btn1=tk.Button(master=f, text='<<', command=self.btn_pic_prev)

In this case, the method is executed on declaration-time, but not when button-events are fired.

btn1=tk.Button(master=f, text='<<', command=self.btn_pic_prev())

or

btn1=tk.Button(master=f, text='<<', command=self.btn_pic_prev(arg))

Why is that?

How to pass arguments to a method/eventhandler in python?


问:
Specific Question about why a function has been placed inside an object
So I've been working through Freecodecamp's courses. I've come across this piece of code in an example:

```<code>const person = {
  name: "Taylor",
  sayHello: function() {
    return `Hello! My name is ${this.name}.`;
  }
};
</code>```

In this situation, why has "sayHello" been made a function? Why not simply write:

```<code>    sayHello: `Hello! My name is ${this.name}.`
</code>```

Wouldn't that return the same thing?

Apologies for any common sense mistakes here, I'm pretty new to all of this.

Body:
So I've been working through Freecodecamp's courses. I've come across this piece of code in an example:

const person = {
  name: "Taylor",
  sayHello: function() {
    return `Hello! My name is ${this.name}.`;
  }
};

In this situation, why has "sayHello" been made a function? Why not simply write:

    sayHello: `Hello! My name is ${this.name}.`

Wouldn't that return the same thing?

Apologies for any common sense mistakes here, I'm pretty new to all of this.


问:
How to change where vitejs puts its HTML files?
I want to change where vite produces its HTML files, but I have not been able to figure it out yet. By default, the files for an html page get compiled into these file locations:

```<code>/dist/src/pages/index.js
/dist/src/pages/index.html
</code>```

The locations above are produced by this vite.config.ts:

```<code>import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path, { resolve } from "path";
import manifest from "./src/manifest";
import makeManifest from "./build-utils/rollup-plugins/make-manifest";

const root = resolve(__dirname, "src");
const pagesDir = resolve(root, "pages");
const assetsDir = resolve(root, "assets");
const outDir = resolve(__dirname, "dist");
// const publicDir = resolve(__dirname, "src", "public");
const publicDir = resolve(__dirname, "src", "copied-to-dist-on-compile");

const isDev = process.env.__DEV__ === "true";
const isProduction = !isDev;

export default defineConfig({
  resolve: {
    alias: {
      "@src": root,
      "@assets": path.resolve(root, "assets"),
      "@pages": path.resolve(root, "pages"),
      "@utils": path.resolve(root, "utils")
    },
  },
  plugins: [
    react(),
    makeManifest(manifest),
  ],
  publicDir,
  build: {
    outDir,
    assetsDir,
    minify: isProduction,
    reportCompressedSize: isProduction,

    rollupOptions: {
      input: {
        devtools: resolve(pagesDir, "devtools", "index.html"),
        panel: resolve(pagesDir, "panel", "index.html"),
        content: resolve(pagesDir, "content", "index.ts"),
        background: resolve(pagesDir, "background", "index.ts"),
        contentStyle: resolve(pagesDir, "content", "style.scss"),
        popup: resolve(pagesDir, "popup", "index.html"),
        newtab: resolve(pagesDir, "newtab", "index.html"),
        options: resolve(pagesDir, "options", "index.html"),
      },
      watch: {
        include: ["src/**", "vite.config.ts"],
        exclude: ["node_modules/**", "src/**/*.spec.ts"],
      },
      output: {
        entryFileNames: "src/pages/[name]/index.js",
        chunkFileNames: isDev
          ? "assets/js/[name].js"
          : "assets/js/[name].[hash].js",
        assetFileNames: (assetInfo) => {
          const { dir, name: _name } = path.parse(assetInfo.name);
          const assetFolder = dir.split("/").at(-1);
          const name = assetFolder + firstUpperCase(_name);
          return `assets/[ext]/${name}.chunk.[ext]`;
        },
      },
    },
  },
});

function firstUpperCase(str: string) {
  const firstAlphabet = new RegExp(/( |^)[a-z]/, "g");
  return str.toLowerCase().replace(firstAlphabet, (L) => L.toUpperCase());
}
</code>```

I want to change the compilation so that the output goes to:

```<code>/dist/pages/index.js
/dist/pages/index.html
</code>```

If I change the entryFileNames string to be "pages/[name]/index.js", then the JS file locations get moved, but the HTML locations stay the same. Not sure how to move the HTML files right now but I really want to.

Any tips? Thanks.

Body:
I want to change where vite produces its HTML files, but I have not been able to figure it out yet. By default, the files for an html page get compiled into these file locations:

/dist/src/pages/index.js
/dist/src/pages/index.html

The locations above are produced by this vite.config.ts:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path, { resolve } from "path";
import manifest from "./src/manifest";
import makeManifest from "./build-utils/rollup-plugins/make-manifest";

const root = resolve(__dirname, "src");
const pagesDir = resolve(root, "pages");
const assetsDir = resolve(root, "assets");
const outDir = resolve(__dirname, "dist");
// const publicDir = resolve(__dirname, "src", "public");
const publicDir = resolve(__dirname, "src", "copied-to-dist-on-compile");

const isDev = process.env.__DEV__ === "true";
const isProduction = !isDev;

export default defineConfig({
  resolve: {
    alias: {
      "@src": root,
      "@assets": path.resolve(root, "assets"),
      "@pages": path.resolve(root, "pages"),
      "@utils": path.resolve(root, "utils")
    },
  },
  plugins: [
    react(),
    makeManifest(manifest),
  ],
  publicDir,
  build: {
    outDir,
    assetsDir,
    minify: isProduction,
    reportCompressedSize: isProduction,

    rollupOptions: {
      input: {
        devtools: resolve(pagesDir, "devtools", "index.html"),
        panel: resolve(pagesDir, "panel", "index.html"),
        content: resolve(pagesDir, "content", "index.ts"),
        background: resolve(pagesDir, "background", "index.ts"),
        contentStyle: resolve(pagesDir, "content", "style.scss"),
        popup: resolve(pagesDir, "popup", "index.html"),
        newtab: resolve(pagesDir, "newtab", "index.html"),
        options: resolve(pagesDir, "options", "index.html"),
      },
      watch: {
        include: ["src/**", "vite.config.ts"],
        exclude: ["node_modules/**", "src/**/*.spec.ts"],
      },
      output: {
        entryFileNames: "src/pages/[name]/index.js",
        chunkFileNames: isDev
          ? "assets/js/[name].js"
          : "assets/js/[name].[hash].js",
        assetFileNames: (assetInfo) => {
          const { dir, name: _name } = path.parse(assetInfo.name);
          const assetFolder = dir.split("/").at(-1);
          const name = assetFolder + firstUpperCase(_name);
          return `assets/[ext]/${name}.chunk.[ext]`;
        },
      },
    },
  },
});

function firstUpperCase(str: string) {
  const firstAlphabet = new RegExp(/( |^)[a-z]/, "g");
  return str.toLowerCase().replace(firstAlphabet, (L) => L.toUpperCase());
}

I want to change the compilation so that the output goes to:

/dist/pages/index.js
/dist/pages/index.html

If I change the entryFileNames string to be "pages/[name]/index.js", then the JS file locations get moved, but the HTML locations stay the same. Not sure how to move the HTML files right now but I really want to.

Any tips? Thanks.


问:
Excel: Return 4th Value , given 3 columns
So one Table need to find in another sheet Table and match
Date , Type and a fixed word "RPE" , if so show me the number in  the row

Table i.e

data
type
metric
value

02/10/2000
bike
RPE
4

11/05/2021
row
null
null

04/08/2022
run
Time
50

etc....

Table how will pull data , In other words, it searches only for the "RPE" metric, which coincides with the "Type" and "Date" and places the value .

Those that  have a "a blankl cell" value, or are of a different metric than "RPE", are ignored.

data
type
RPE

02/10/2000
bike
4

My actual formula

```<code>=SUMPRODUCT(--('[Ciclicos Tabela.xlsx]Ciclico tabela (2)'!$C$2:$C$9236=B2);--('[Ciclicos Tabela.xlsx]Ciclico tabela (2)'!$B$2:$B$9236=A2);--('[Ciclicos Tabela.xlsx]Ciclico tabela (2)'!$D$2:$D$9236="RPE");'[Ciclicos Tabela.xlsx]Ciclico tabela (2)'!$E$2:$E$9236)
</code>```

I tried already

With If´s , VLOOCKUP and INDEX/MACTH, all without success.

UPDATE

I tried another two formulas both without success:

```<code>=INDEX('Ciclicos Tabela.xlsx'!Table1[@Valor];MATCH(1;('Ciclicos Tabela.xlsx'!Table1[@Date]=B:B)*('Ciclicos Tabela.xlsx'!Table1[@Type]=A:A)*('Ciclicos Tabela.xlsx'!Table1[@Metrica]="RPE");0))
</code>```
```<code>=IFERROR(INDEX(;MATCH(1;('[Ciclicos Tabela.xlsx]Ciclico tabela'!C12=B12)*('[Ciclicos Tabela.xlsx]Ciclico tabela'!B12=A12)*('[Ciclicos Tabela.xlsx]Ciclico tabela'!D12="RPE");0);4);"")
</code>```

Body:
So one Table need to find in another sheet Table and match
Date , Type and a fixed word "RPE" , if so show me the number in  the row

Table i.e

data
type
metric
value

02/10/2000
bike
RPE
4

11/05/2021
row
null
null

04/08/2022
run
Time
50

etc....

Table how will pull data , In other words, it searches only for the "RPE" metric, which coincides with the "Type" and "Date" and places the value .

Those that  have a "a blankl cell" value, or are of a different metric than "RPE", are ignored.

data
type
RPE

02/10/2000
bike
4

My actual formula

=SUMPRODUCT(--('[Ciclicos Tabela.xlsx]Ciclico tabela (2)'!$C$2:$C$9236=B2);--('[Ciclicos Tabela.xlsx]Ciclico tabela (2)'!$B$2:$B$9236=A2);--('[Ciclicos Tabela.xlsx]Ciclico tabela (2)'!$D$2:$D$9236="RPE");'[Ciclicos Tabela.xlsx]Ciclico tabela (2)'!$E$2:$E$9236)

I tried already

With If´s , VLOOCKUP and INDEX/MACTH, all without success.

UPDATE

I tried another two formulas both without success:

=INDEX('Ciclicos Tabela.xlsx'!Table1[@Valor];MATCH(1;('Ciclicos Tabela.xlsx'!Table1[@Date]=B:B)*('Ciclicos Tabela.xlsx'!Table1[@Type]=A:A)*('Ciclicos Tabela.xlsx'!Table1[@Metrica]="RPE");0))

=IFERROR(INDEX(;MATCH(1;('[Ciclicos Tabela.xlsx]Ciclico tabela'!C12=B12)*('[Ciclicos Tabela.xlsx]Ciclico tabela'!B12=A12)*('[Ciclicos Tabela.xlsx]Ciclico tabela'!D12="RPE");0);4);"")


问:
Python lambda in a loop ends up using last index value not the index value that was set
Using the for loop index in a lambda:function(index) causes the function to use the value that index reaches to, not the value that it was set to.

Using Python 3.9.6

```<code>command_list = []
for i in range(2):
    print(i)
    command_list.append(lambda:print(i))
command_list[0]()
command_list[1]()
</code>```

Causes the result:

```<code>0
1
1
1
</code>```

But what I needed/expected to get:

```<code>0
1
0
1
</code>```

How can I get the expected result?

Body:
Using the for loop index in a lambda:function(index) causes the function to use the value that index reaches to, not the value that it was set to.

Using Python 3.9.6

command_list = []
for i in range(2):
    print(i)
    command_list.append(lambda:print(i))
command_list[0]()
command_list[1]()

Causes the result:

0
1
1
1

But what I needed/expected to get:

0
1
0
1

How can I get the expected result?


问:
"double free detected in tcache 2"
I writed this code.
Every letter got by getchar coming into a sequence of instances of structs... Than I make it free.
Three scenario of work:

I press only Enter so the sequence is empty. Everything's fine.

I write line by line, and everything's fine

But somehow if I writed a non-empty line (like in sc.2) and then I just press Enter (like in sc.1) I got this error and app's crash:

free(): double free detected in tcache 2

```<code> #include <stdio.h>

 #include <stdlib.h>

 struct foo {

     char c;

     struct foo* p;

 };

 struct foo* set_foo()
 {

     char c;

     struct foo* f;
     struct foo* sf;

     if ((c = getchar()) != '\n' && c != EOF) {
         f = malloc(sizeof(struct foo));
         f->c = c;
         sf = f;

         while ((c = getchar()) != '\n' && c != EOF) {
             f->p = malloc(sizeof(struct foo));
             f->p->c = c;
             f = f->p;
         }
     }

     return sf;
 }

 void free_foo(struct foo* f)
 {

     struct foo* sf;
     while (f != NULL) {
         sf = f;
         f = f->p;
         if (sf != NULL) {
             free(sf);
         }
     }
 }

 int main(int argc, char* argv[])
 {

     while (1) {
         struct foo* f;

         f = set_foo();

         free_foo(f);
     }

     return 0;
 }
</code>```

Why double free. I even check it by comparing with NULL and free() only when it's not NULL.

Title: "double free detected in tcache 2"

Body:
I writed this code.
Every letter got by getchar coming into a sequence of instances of structs... Than I make it free.
Three scenario of work:

I press only Enter so the sequence is empty. Everything's fine.

I write line by line, and everything's fine

But somehow if I writed a non-empty line (like in sc.2) and then I just press Enter (like in sc.1) I got this error and app's crash:

free(): double free detected in tcache 2

 #include <stdio.h>

 #include <stdlib.h>

 struct foo {

     char c;

     struct foo* p;

 };

 struct foo* set_foo()
 {

     char c;

     struct foo* f;
     struct foo* sf;

     if ((c = getchar()) != '\n' && c != EOF) {
         f = malloc(sizeof(struct foo));
         f->c = c;
         sf = f;

         while ((c = getchar()) != '\n' && c != EOF) {
             f->p = malloc(sizeof(struct foo));
             f->p->c = c;
             f = f->p;
         }
     }

     return sf;
 }

 void free_foo(struct foo* f)
 {

     struct foo* sf;
     while (f != NULL) {
         sf = f;
         f = f->p;
         if (sf != NULL) {
             free(sf);
         }
     }
 }

 int main(int argc, char* argv[])
 {

     while (1) {
         struct foo* f;

         f = set_foo();

         free_foo(f);
     }

     return 0;
 }

Why double free. I even check it by comparing with NULL and free() only when it's not NULL.


问:
Step 2 in loop makes code much more slower. any one know why or I am i doing something wrong?
```<code>     println(measureNanoTime {
        println(isPrime2(999999999)) // O(n) ==> time is 182800
    }
    )

    println(measureNanoTime {
        println(isPrime3(999999999)) // O(n/2) using step 2 ==> time is 6528700
    }
    )

    println(measureNanoTime {
        println(isPrime4(999999999)) // O(n/2) using while loop ==> time is 11401

    }
    )

fun isPrime2(n: Int): Boolean {
    if (n == 2) return true
    if (n < 2 || n % 2 == 0) return false

    for (i in 3 until n) {
        if (n % i == 0) return false
    }
    return true

}

fun isPrime3(n: Int): Boolean {
    if (n == 2) return true
    if (n < 2 || n % 2 == 0) return false

    for (i in 3 until n step 2) {
        if (n % i == 0) return false
    }
    return true

}

fun isPrime4(n: Int): Boolean {
    if (n == 2) return true
    if (n < 2 || n % 2 == 0) return false

    var i = 3;
    while (i < n) {
        if (n % i == 0) return false
        i += 2
    }
    return true

}
</code>```


问:
Error: Invalid Value (Sequelize date format) on query in where clause
Using mysql in where clause gives me invalid error, my model is

```<code>Error: Invalid value { created_at: { [Symbol(gte)]: '2022-12-31T00:00:00.000Z' } }
</code>```
```<code>Job.init({},{sequelize, tableName: 'jobs', timestamps: false, modelName: 'Job'});
</code>```

Query used for this

```<code>Job.findAll({
    ....
    ....
    where: {
        created_at: {
            [Op.gte]: '2022-12-31T00:00:00.000Z'
        }
    }
})
</code>```

Used the following as well

```<code>Job.findAll({
    ....
    ....
    where: {
        created_at: {
            [Op.gte]: '2022-12-31 00:00:00'
        }
    }
})
</code>```

i want to get all details by passed date but not able to do so

Body:
Using mysql in where clause gives me invalid error, my model is

Error: Invalid value { created_at: { [Symbol(gte)]: '2022-12-31T00:00:00.000Z' } }

Job.init({},{sequelize, tableName: 'jobs', timestamps: false, modelName: 'Job'});

Query used for this

Job.findAll({
    ....
    ....
    where: {
        created_at: {
            [Op.gte]: '2022-12-31T00:00:00.000Z'
        }
    }
})

Used the following as well

Job.findAll({
    ....
    ....
    where: {
        created_at: {
            [Op.gte]: '2022-12-31 00:00:00'
        }
    }
})

i want to get all details by passed date but not able to do so


问:
Find the Greatest Common Divisor
Here is the question.
Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution.

The inputs x and y are always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1.

Here is my solution.

function mygcd(x, y) {
  //your code here

  let gcd = [];

  let lowestNum;
  let bigestNum;

  //detect the lowest and bigest numbers
  if (x < y) {
    lowestNum = x;
    bigestNum = y;
  } else if (x > y) {
    lowestNum = y
    bigestNum = x;
  } else {
    lowestNum = x
  }

  //check if the bigest num has a modolo == 0
  //else loop the lowest num and push in the array
  if (bigestNum % lowestNum === 0) {
    return gcd += lowestNum;
  } else {
    let arrNum = []
    for (let i = 1; i < lowestNum; i++) {
      // console.log(i)
      arrNum.push(i)
    }

    //loop the array backwards
    for (i = arrNum.length - 1; i >= 1; i--) {
      if (lowestNum % arrNum[i] === 0 && bigestNum % arrNum[i] === 0) {
        console.log(arrNum[i])
        if (gcd !== 0) {
          return
        } else {
          //          gcd += arrNum[i]
          let vals = gcd.push(arrNum[i])
          console.log(typeof(vals))
        }
      }
    }
  }
  console.log(gcd)
  return gcd[0];
}

console.log(mygcd(30, 12))```
</div>
</div>
</p>
<p>The above solution works for the test cases i tried it for, but the issue is that it returns the correct divisor and undefined.</p>
<p>This is what my logs look like</p>
```6
undefined
6
undefined
```
<p>The test cases</p>
<p>test:
Log</p>
```6
expected undefined to equal 6
```
<p>so it gets undefined instead of 6 or the correct divisor.</p>
<p>I also tired a different recursive approach below.
Note: This works well.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function mygcd(x, y) {
  if (!x) return y
  if (!y) return x

  return mygcd(y, x % y)
}
console.log(mygcd(30, 12))
console.log(mygcd(8, 12))</code>```

But i am curious to understand why my original solution breaks. Any help would be really appreciated.

Thanks

Title: Find the Greatest Common Divisor

Body:
Here is the question.
Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution.

The inputs x and y are always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1.

Here is my solution.

function mygcd(x, y) {
  //your code here

  let gcd = [];

  let lowestNum;
  let bigestNum;

  //detect the lowest and bigest numbers
  if (x < y) {
    lowestNum = x;
    bigestNum = y;
  } else if (x > y) {
    lowestNum = y
    bigestNum = x;
  } else {
    lowestNum = x
  }

  //check if the bigest num has a modolo == 0
  //else loop the lowest num and push in the array
  if (bigestNum % lowestNum === 0) {
    return gcd += lowestNum;
  } else {
    let arrNum = []
    for (let i = 1; i < lowestNum; i++) {
      // console.log(i)
      arrNum.push(i)
    }

    //loop the array backwards
    for (i = arrNum.length - 1; i >= 1; i--) {
      if (lowestNum % arrNum[i] === 0 && bigestNum % arrNum[i] === 0) {
        console.log(arrNum[i])
        if (gcd !== 0) {
          return
        } else {
          //          gcd += arrNum[i]
          let vals = gcd.push(arrNum[i])
          console.log(typeof(vals))
        }
      }
    }
  }
  console.log(gcd)
  return gcd[0];
}

console.log(mygcd(30, 12))

The above solution works for the test cases i tried it for, but the issue is that it returns the correct divisor and undefined.

This is what my logs look like

6
undefined
6
undefined

The test cases

test:
Log

6
expected undefined to equal 6

so it gets undefined instead of 6 or the correct divisor.

I also tired a different recursive approach below.
Note: This works well.

function mygcd(x, y) {
  if (!x) return y
  if (!y) return x

  return mygcd(y, x % y)
}
console.log(mygcd(30, 12))
console.log(mygcd(8, 12))

But i am curious to understand why my original solution breaks. Any help would be really appreciated.

Thanks


问:
The system cannot find the path specified. ; No such process [Op:ReadFile]

I looked for different ways to solve this error... Even though I am not an advanced programmer I am trying to learn how to use machine learning. I am working in vs code(.ipynb file, tf(python 3.10.8)) using all extensions, TensorFlow installed(2.10.0). Please help if you know the answer, but not the reinstalling tenser one, since I have already tried it.
code
error
error

Then I put it in c: where the packages were installed and got the next thing: error2

If you need any additional information, please ask.


问:
Debounce/delay TinyMCE Blazor
How do I setup a debounce/delay to prevent Blazor updating model on every keystroke?

I have looked through TinyMCE docs but that feature seems to be deprecated. Somehow it seems deprecating something this important is unlikely, what's more likely is that I can't find it.

My current TinyMCE config

```<code>new Dictionary<string, object>{
        {"menubar", false },
       {"toolbar", "undo redo styleselect forecolor bold italic alignleft aligncenter alignright alignjustify outdent indent" },
        {"toolbar_location", "top" },
        {"toolbar_mode", "scrolling" },
        {"statusbar",false },
        {"placeholder", "Type here..."},
        { "content_style", "body { margin: 0px 3px 0px 13px; line-height:0.9; }  "},
        { "height", "110"}
      }
</code>```

Editor call

<TinyMCE.Blazor.Editor @bind-Value=Value ScriptSrc="/js/tinymce/tinymce.min.js" Conf="@config" Inline="@Inline" />

Title: Debounce/delay TinyMCE Blazor

Body:
How do I setup a debounce/delay to prevent Blazor updating model on every keystroke?

I have looked through TinyMCE docs but that feature seems to be deprecated. Somehow it seems deprecating something this important is unlikely, what's more likely is that I can't find it.

My current TinyMCE config

new Dictionary<string, object>{
        {"menubar", false },
       {"toolbar", "undo redo styleselect forecolor bold italic alignleft aligncenter alignright alignjustify outdent indent" },
        {"toolbar_location", "top" },
        {"toolbar_mode", "scrolling" },
        {"statusbar",false },
        {"placeholder", "Type here..."},
        { "content_style", "body { margin: 0px 3px 0px 13px; line-height:0.9; }  "},
        { "height", "110"}
      }

Editor call

<TinyMCE.Blazor.Editor @bind-Value=Value ScriptSrc="/js/tinymce/tinymce.min.js" Conf="@config" Inline="@Inline" />


问:
Can someone explain the difference between <<extends>> and <<includes>> relationships?
I am confused of how to use the <<includes>> and <<extends>> relationships. I would appreciate it if someone could help me understand it.

For example there is this relationship and I don't know if it is correct or not:

```<code>Buying ticket ----------> Selling ticket
               includes
</code>```

Also if you can give me an exmple of both scenarios I would appreciate it.

Body:
I am confused of how to use the <<includes>> and <<extends>> relationships. I would appreciate it if someone could help me understand it.

For example there is this relationship and I don't know if it is correct or not:

Buying ticket ----------> Selling ticket
               includes

Also if you can give me an exmple of both scenarios I would appreciate it.


问:
How can i pass 8 arguments to assembly x64 procedure from C#
I have to pass 8 arguments to procedure.

I have tried passing directly 8 arguments but im getting object reference not set to instance an object. I tried passing one big structure as a pointer with 8 params in it but i cannot read 6th,7th and 8th argument, and tied passing 2 structures as pointers but cannot read 3 from 4 arguments from 2nd structure

c#

```<code>public unsafe struct Pointers
    {
        public int* intputArray;
        public int width;
        public int* outputArray;
        public int height;
        public int* gx;
        public int startY;
        public int* gy;
        public int endY;

    }

unsafe
        {
            fixed (Pointers* strc=&structToASM) {
                fixed (int* ptr3 = &gx[0], ptr4 = &gy[0], ptr = &input[0], ptr2 = &output[0]) {

                        structToASM.intputArray = ptr;
                        structToASM.outputArray = ptr2;
                        structToASM.gx = ptr3;
                        structToASM.gy = ptr4;
                        structToASM.width = 1;
                        structToASM.height = 2; //dummy values
                        structToASM.startY = 3;
                        structToASM.endY = 1;

                        ProcessRows(strc);

                }
            }
        }
</code>```
```<code>    .code

ProcessRows proc
mov r8,[rcx];input
mov r15d,[rcx+8];width
mov r9,[rcx+16];output
mov r13d,[rcx+24];height
mov r10, [rcx+32];gx
mov r12d,[rcx+48];start ; here i got from presentation from university that next arg is +48 not 40
mov r11,[rcx+56];gy
mov esi, [rcx+64];end

xor r14,r14
loop_:
movups xmm0, [r8 + r14 * 4]

movups xmm1,[r10+20]
addps xmm0,xmm1

movups [r9 + r14*4],xmm0
inc r14

cmp r14, r12 ; here im checking if value is loaded it should exit loop, i can get values from width, height not from start, and end
jne loop_

ret
ProcessRows endp
End
</code>```

Body:
I have to pass 8 arguments to procedure.

I have tried passing directly 8 arguments but im getting object reference not set to instance an object. I tried passing one big structure as a pointer with 8 params in it but i cannot read 6th,7th and 8th argument, and tied passing 2 structures as pointers but cannot read 3 from 4 arguments from 2nd structure

c#

public unsafe struct Pointers
    {
        public int* intputArray;
        public int width;
        public int* outputArray;
        public int height;
        public int* gx;
        public int startY;
        public int* gy;
        public int endY;

    }

unsafe
        {
            fixed (Pointers* strc=&structToASM) {
                fixed (int* ptr3 = &gx[0], ptr4 = &gy[0], ptr = &input[0], ptr2 = &output[0]) {

                        structToASM.intputArray = ptr;
                        structToASM.outputArray = ptr2;
                        structToASM.gx = ptr3;
                        structToASM.gy = ptr4;
                        structToASM.width = 1;
                        structToASM.height = 2; //dummy values
                        structToASM.startY = 3;
                        structToASM.endY = 1;

                        ProcessRows(strc);

                }
            }
        }

    .code

ProcessRows proc
mov r8,[rcx];input
mov r15d,[rcx+8];width
mov r9,[rcx+16];output
mov r13d,[rcx+24];height
mov r10, [rcx+32];gx
mov r12d,[rcx+48];start ; here i got from presentation from university that next arg is +48 not 40
mov r11,[rcx+56];gy
mov esi, [rcx+64];end

xor r14,r14
loop_:
movups xmm0, [r8 + r14 * 4]

movups xmm1,[r10+20]
addps xmm0,xmm1

movups [r9 + r14*4],xmm0
inc r14

cmp r14, r12 ; here im checking if value is loaded it should exit loop, i can get values from width, height not from start, and end
jne loop_

ret
ProcessRows endp
End


问:
Unable to simply install and use datatable editor (laravel 9/npm)
I end up posting this message because I spent my entire day trying to get the datatable editor to work but without success.

I'm on a brand new install of laravel 9 that I haven't installed anything on. I just set up datatable on USER table and it's ok.

But when i want to use datatable editor (I bought the license today) i have this two error in the console :smile:

app-e6e82434.js:45 jQuery.Deferred exception: $.fn.dataTable.Editor is not a constructor TypeError: $.fn.dataTable.Editor is not a constructor
at HTMLDocument. (http://test88.test/users:67:75)
at Q (http://test88.test/build/assets/app-e6e82434.js:45:31424)
at ae (http://test88.test/build/assets/app-e6e82434.js:45:31749) undefined>

Uncaught TypeError: $.fn.dataTable.Editor is not a constructor
at HTMLDocument. (users:67:75)
at Q (app-e6e82434.js:45:31424)
at ae (app-e6e82434.js:45:31749)>

I installed datatable editor via npm then ran the script so that it puts the files in the right place as shown in the doc
but I have the impression that it does not take into account my files or that it considers that I do not have a license.

I installed the debug script but the link it sends me always gives a 404. The debug script crashes when I'm on the page that tries to display the table of users and when I'm on a classic page it shows me that everything is ok except that datatable editor is not loaded.

I think I've tried everything to load this damn script but I can't. Anyone have any idea what the problem is?

I try to make datatable editor running


问:
How can add my payment button in my customize dialog box?
I am working in android. i want to add paypal button in my custom button. i have created both, custom dialog and paypal button. But these both are in different actitvity. please suggest me what should i do for this.

This is my class to create custom dialog.:-

```<code>package com.pericent.musicapp;

import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class CustomizeDialog extends Dialog implements OnClickListener {
    Button close;
    String TAG="CustomizeDialog";
    TextView text_view_artist_name;
    TextView text_view_song_title;
    TextView text_view_price;

    public CustomizeDialog(Context context,String title_of_song,String artist_of_song,float price_of_song){
        super(context);
        /** It will hide the title */
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.paypal_custom_dialog);
        Log.v(TAG, "i am gooing to perform close");

        text_view_song_title=(TextView)findViewById(R.id.Paypal_TextView_songName);

        text_view_artist_name=(TextView)findViewById(R.id.Paypal_TextView_byArtist);

        text_view_price=(TextView)findViewById(R.id.Paypal_TextView_songPrice);

        text_view_song_title.setText("Title : "+title_of_song);

        text_view_artist_name.setText("Artist : "+artist_of_song);

        close = (Button) findViewById(R.id.paypal_close);

        text_view_price.setText("Price : "+price_of_song);
        close.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Log.v(TAG, "i am closing tag");
        if (v == close)
            dismiss();
    }

}
</code>```

and this is the custom dialog box which is created by above code:-

Now i want to add my paypal button in this custom dialog box. please suggest me what should i do for this. this is my code for creating the  paypal button:-

```<code>package com.pericent;
import java.math.BigDecimal;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.PayPalAdvancedPayment;
import com.paypal.android.MEP.PayPalInvoiceData;
import com.paypal.android.MEP.PayPalInvoiceItem;
import com.paypal.android.MEP.PayPalReceiverDetails;

public class MypaypalActivity extends Activity implements OnClickListener{

    @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout mLinLay= new LinearLayout(this);
        setContentView(R.layout.main);
        PayPal pp = PayPal.initWithAppID(this, "APP-80W284485P519543T", PayPal.ENV_SANDBOX);

        LinearLayout layoutSimplePayment = new LinearLayout(this);
        layoutSimplePayment.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        layoutSimplePayment.setOrientation(LinearLayout.VERTICAL);
        CheckoutButton launchSimplePayment = pp.getCheckoutButton(this, PayPal.BUTTON_118x24, CheckoutButton.TEXT_PAY);

        launchSimplePayment.setOnClickListener( this);
        layoutSimplePayment.addView(launchSimplePayment);
        mLinLay.addView(layoutSimplePayment);

        setContentView(mLinLay);
    }

    public void onClick(View v) {
        PayPalPayment payment = new PayPalPayment();
        payment.setSubtotal(new BigDecimal("2.25"));
        payment.setCurrencyType("USD");
        payment.setRecipient("kuntal_1316186174_biz@gmail.com");
        payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);

        Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);
        startActivityForResult(checkoutIntent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
        case Activity.RESULT_OK:
            break;

        case Activity.RESULT_CANCELED:
            break;

        case PayPalActivity.RESULT_FAILURE:
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
</code>```

Thank you in advance...

ContentLicense: CC BY-SA 3.0

Body:
I am working in android. i want to add paypal button in my custom button. i have created both, custom dialog and paypal button. But these both are in different actitvity. please suggest me what should i do for this.

This is my class to create custom dialog.:-

package com.pericent.musicapp;

import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class CustomizeDialog extends Dialog implements OnClickListener {
    Button close;
    String TAG="CustomizeDialog";
    TextView text_view_artist_name;
    TextView text_view_song_title;
    TextView text_view_price;

    public CustomizeDialog(Context context,String title_of_song,String artist_of_song,float price_of_song){
        super(context);
        /** It will hide the title */
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.paypal_custom_dialog);
        Log.v(TAG, "i am gooing to perform close");

        text_view_song_title=(TextView)findViewById(R.id.Paypal_TextView_songName);

        text_view_artist_name=(TextView)findViewById(R.id.Paypal_TextView_byArtist);

        text_view_price=(TextView)findViewById(R.id.Paypal_TextView_songPrice);

        text_view_song_title.setText("Title : "+title_of_song);

        text_view_artist_name.setText("Artist : "+artist_of_song);

        close = (Button) findViewById(R.id.paypal_close);

        text_view_price.setText("Price : "+price_of_song);
        close.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Log.v(TAG, "i am closing tag");
        if (v == close)
            dismiss();
    }

}

and this is the custom dialog box which is created by above code:-

Now i want to add my paypal button in this custom dialog box. please suggest me what should i do for this. this is my code for creating the  paypal button:-

package com.pericent;
import java.math.BigDecimal;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.PayPalAdvancedPayment;
import com.paypal.android.MEP.PayPalInvoiceData;
import com.paypal.android.MEP.PayPalInvoiceItem;
import com.paypal.android.MEP.PayPalReceiverDetails;

public class MypaypalActivity extends Activity implements OnClickListener{

    @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout mLinLay= new LinearLayout(this);
        setContentView(R.layout.main);
        PayPal pp = PayPal.initWithAppID(this, "APP-80W284485P519543T", PayPal.ENV_SANDBOX);

        LinearLayout layoutSimplePayment = new LinearLayout(this);
        layoutSimplePayment.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        layoutSimplePayment.setOrientation(LinearLayout.VERTICAL);
        CheckoutButton launchSimplePayment = pp.getCheckoutButton(this, PayPal.BUTTON_118x24, CheckoutButton.TEXT_PAY);

        launchSimplePayment.setOnClickListener( this);
        layoutSimplePayment.addView(launchSimplePayment);
        mLinLay.addView(layoutSimplePayment);

        setContentView(mLinLay);
    }

    public void onClick(View v) {
        PayPalPayment payment = new PayPalPayment();
        payment.setSubtotal(new BigDecimal("2.25"));
        payment.setCurrencyType("USD");
        payment.setRecipient("kuntal_1316186174_biz@gmail.com");
        payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);

        Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);
        startActivityForResult(checkoutIntent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
        case Activity.RESULT_OK:
            break;

        case Activity.RESULT_CANCELED:
            break;

        case PayPalActivity.RESULT_FAILURE:
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

Thank you in advance...


问:
I have an error in installing django-socketio in windows virtualenv
I have a problem in installing django socket io, i changed django version to 3.2 and still the error
image of the error</p>


问:
Where are I2P address books stored?
I2P uses address books to store site addresses for Eepsites. There are several options for this including local addressbook, router addressbook and private addressbook.

I am curious about this for the purposes of forensics as a novice to I2P, where are these different address books stored?

Title: Where are I2P address books stored?


问:
LSTM model is producing really bad results for multiclass text classification for imbalanced small dataset
I am training a LSTM model on my current dataset to predict the multiclass categories - there are 18 mutually exclusive categories and the dataset has ~ 500 rows only (a really small dataset). I am handling the class imbalance using the following:

```<code>from sklearn.utils import class_weight
class_weights = list(class_weight.compute_class_weight('balanced',
                                                   classes = np.unique(df['categories']),
                                                   y = df['categories']))
weights = {}
for index, weight in enumerate(class_weights):
  weights[index] = weight
</code>```

Post this I am building my LSTM model and have been evaluating this model using PRC in tf.metrics as this is an imbalanced target classification problem

```<code>METRICS = [ tf.metrics.AUC(name='prc', curve='PR'), # precision-recall curve]
model = Sequential()
model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X.shape[1]))
model.add(SpatialDropout1D(0.2))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(18, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',  metrics=METRICS)
print(model.summary())
</code>```

and finally:

```<code>  history = model.fit(X_train,
                y_train,
                batch_size=10,
                epochs=10,
                verbose=1,
                class_weight=weights,
                validation_data=(X_test,y_test))
</code>```

Now when I look at the results, the training prc is coming out to be really high whereas my val_prc is really low. An example with 10 epochs:

```<code>   Epoch 1/10
   30/30 [==============================] - 5s 174ms/step - loss: 2.9951 - prc: 0.0682 -
   val_loss: 2.8865 - val_prc: 0.0639
   Epoch 2/10
   30/30 [==============================] - 5s 169ms/step - loss: 2.9556 - prc: 0.0993 -
   val_loss: 2.8901 - val_prc: 0.0523
   .....
   Epoch 8/10
   30/30 [==============================] - 6s 189ms/step - loss: 1.2494 - prc: 0.6415 -
   val_loss: 3.0662 - val_prc: 0.0728
   Epoch 9/10
   30/30 [==============================] - 6s 210ms/step - loss: 0.9237 - prc: 0.8302 -
   val_loss: 3.0624 - val_prc: 0.1006
   Epoch 10/10
   30/30 [==============================] - 6s 184ms/step - loss: 0.7452 - prc: 0.9017 -
   val_loss: 3.5035 - val_prc: 0.0821
</code>```

My questions are:

Is the evaluation metric correct that I am using considering it is an imbalanced class problem?

Am I treating the imbalance correctly with the code that I have written in the first place and most importantly, am I using this correct in the model.fit() ?

How can I resolve this? Is there any alternative approach that you can suggest?

Body:
I am training a LSTM model on my current dataset to predict the multiclass categories - there are 18 mutually exclusive categories and the dataset has ~ 500 rows only (a really small dataset). I am handling the class imbalance using the following:

from sklearn.utils import class_weight
class_weights = list(class_weight.compute_class_weight('balanced',
                                                   classes = np.unique(df['categories']),
                                                   y = df['categories']))
weights = {}
for index, weight in enumerate(class_weights):
  weights[index] = weight

Post this I am building my LSTM model and have been evaluating this model using PRC in tf.metrics as this is an imbalanced target classification problem

METRICS = [ tf.metrics.AUC(name='prc', curve='PR'), # precision-recall curve]
model = Sequential()
model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X.shape[1]))
model.add(SpatialDropout1D(0.2))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(18, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',  metrics=METRICS)
print(model.summary())

and finally:

  history = model.fit(X_train,
                y_train,
                batch_size=10,
                epochs=10,
                verbose=1,
                class_weight=weights,
                validation_data=(X_test,y_test))

Now when I look at the results, the training prc is coming out to be really high whereas my val_prc is really low. An example with 10 epochs:

   Epoch 1/10
   30/30 [==============================] - 5s 174ms/step - loss: 2.9951 - prc: 0.0682 -
   val_loss: 2.8865 - val_prc: 0.0639
   Epoch 2/10
   30/30 [==============================] - 5s 169ms/step - loss: 2.9556 - prc: 0.0993 -
   val_loss: 2.8901 - val_prc: 0.0523
   .....
   Epoch 8/10
   30/30 [==============================] - 6s 189ms/step - loss: 1.2494 - prc: 0.6415 -
   val_loss: 3.0662 - val_prc: 0.0728
   Epoch 9/10
   30/30 [==============================] - 6s 210ms/step - loss: 0.9237 - prc: 0.8302 -
   val_loss: 3.0624 - val_prc: 0.1006
   Epoch 10/10
   30/30 [==============================] - 6s 184ms/step - loss: 0.7452 - prc: 0.9017 -
   val_loss: 3.5035 - val_prc: 0.0821

My questions are:

Is the evaluation metric correct that I am using considering it is an imbalanced class problem?

Am I treating the imbalance correctly with the code that I have written in the first place and most importantly, am I using this correct in the model.fit() ?

How can I resolve this? Is there any alternative approach that you can suggest?


问:
Plot a function with modulo conditions in matplotlib
I'm trying to plot a function whose output f(x) depends on floor(x)%3. However, when I tried plotting it using matplotlib, I got this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I understand that it's because x is an array and so floor(x)%3 doesn't really mean anything. However, is there a way to make python treat x like a single number and not an array?

Here is the code:

```<code>from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

def f(x):
   if np.floor(x / 3) % 3 == 1:
       return -x + 2 + 4 * np.floor(x/3)
   elif np.floor(x / 3) % 3 == 2:
       return x - 2 * np.floor((x + 1) / 3)
   elif np.floor(x / 3) % 3 == 0:
       return x - 2 * np.floor(x / 3)

x = np.linspace(-10, 10, 100)

plt.plot(x, f(x), color='blue')

plt.show()
</code>```

Any help will be appreciated, thanks in advance!

Body:
I'm trying to plot a function whose output f(x) depends on floor(x)%3. However, when I tried plotting it using matplotlib, I got this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I understand that it's because x is an array and so floor(x)%3 doesn't really mean anything. However, is there a way to make python treat x like a single number and not an array?

Here is the code:

from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

def f(x):
   if np.floor(x / 3) % 3 == 1:
       return -x + 2 + 4 * np.floor(x/3)
   elif np.floor(x / 3) % 3 == 2:
       return x - 2 * np.floor((x + 1) / 3)
   elif np.floor(x / 3) % 3 == 0:
       return x - 2 * np.floor(x / 3)

x = np.linspace(-10, 10, 100)

plt.plot(x, f(x), color='blue')

plt.show()

Any help will be appreciated, thanks in advance!


问:
Extract Locoscript data
I need to extract the data from Locoscript files.I have a computer running Windows XP so I can read the data. Can you help? Thanks.

I have tried opening in WordPad and Excel. I can read the text, but there are too many extra characters and no formatting. I have a lot of data to extract so it is impractical to delete all of the additional characters. The Text Import Wizard doesn't seem to help.

Title: Extract Locoscript data


问:
Axios Spy not being called correct number of times in Jest
I have a React context I am testing that runs a single function to check for an application update. The checkForUpdate function looks like this:

```<code> async function checkForUpdate() {
    if (isPlatform('capacitor')) {
      const maintanenceURL =
        'https://example.com/maintenance.json';
      const updateURL =
        'https://example.com/update.json';

      try {
        const maintanenceFetch: AxiosResponse<MaintanenceDataInterface> =
          await axios.get(maintanenceURL);
        console.log('maintain', maintanenceFetch);

        if (maintanenceFetch.data.enabled) {
          setUpdateMessage(maintanenceFetch.data.msg);
          return;
        }

        const updateFetch: AxiosResponse<UpdateDataInterface> = await axios.get(
          updateURL
        );
        console.log('updateFetch', updateFetch);

        if (updateFetch.data.enabled) {
          const capApp = await App.getInfo();
          const capAppVersion = capApp.version;

          console.log('Thi is a thinkg', capAppVersion);

          if (isPlatform('android')) {
            console.log('hi');
            const { currentAndroid, majorMsg, minorMsg } = updateFetch.data;
            const idealVersionArr = currentAndroid.split('.');
            const actualVersionArr = capAppVersion.split('.');

            if (idealVersionArr[0] !== actualVersionArr[0]) {
              setUpdateMessage(majorMsg);
              setUpdateAvailable(true);
              return;
            }

            if (idealVersionArr[1] !== actualVersionArr[1]) {
              setUpdateMessage(minorMsg);
              setUpdateAvailable(true);
              return;
            }
          } else {
            const { currentIos, majorMsg, minorMsg } = updateFetch.data;
            const idealVersionArr = currentIos.split('.');
            const actualVersionArr = capAppVersion.split('.');

            if (idealVersionArr[0] !== actualVersionArr[0]) {
              setUpdateMessage(majorMsg);
              setUpdateAvailable(true);
              return;
            }

            if (idealVersionArr[1] !== actualVersionArr[1]) {
              setUpdateMessage(minorMsg);
              setUpdateAvailable(true);
              return;
            }
          }
        }
      } catch (err) {
        console.log('Error in checkForUpdate', err);
      }
    }
  }
</code>```

For some reason, in my test I wrote to test this, my axiosSpy only shows that it has been called 1 time instead of the expected 2 times. The console logs I posted for both get requests run as well. I cannot figure out what I am doing wrong.

Here is the test:

```<code>it.only('should render the update page if the fetch call to update bucket is enabled and returns a different major version', async () => {
      const isPlatformSpy = jest.spyOn(ionicReact, 'isPlatform');
      isPlatformSpy.mockReturnValueOnce(true).mockReturnValueOnce(true);

      const appSpy = jest.spyOn(App, 'getInfo');
      appSpy.mockResolvedValueOnce({
        version: '0.8.0',
        name: 'test',
        build: '123',
        id: 'r132-132',
      });

      const axiosSpy = jest.spyOn(axios, 'get');
      axiosSpy
        .mockResolvedValueOnce({
          data: {
            enabled: false,
            msg: {
              title: 'App maintenance',
              msg: 'We are currently solving an issue where users cannot open the app. This should be solved by end of day 12/31/2022! Thank you for your patience ',
              btn: 'Ok',
              type: 'maintenance',
            },
          },
        })
        .mockResolvedValueOnce({
          data: {
            current: '1.0.0',
            currentAndroid: '1.0.0',
            currentIos: '2.0.0',
            enabled: true,
            majorMsg: {
              title: 'Important App update',
              msg: 'Please update your app to the latest version to continue using it. If you are on iPhone, go to the app store and search MO Gas Tax Back to update your app. The button below does not work but will in the current update!',
              btn: 'Download',
              type: 'major',
            },
            minorMsg: {
              title: 'App update available',
              msg: "There's a new version available, would you like to get it now?",
              btn: 'Download',
              type: 'minor',
            },
          },
        });

      customRender(<UpdateChild />);

      expect(axiosSpy).toHaveBeenCalledTimes(2);
    });
</code>```

Body:
I have a React context I am testing that runs a single function to check for an application update. The checkForUpdate function looks like this:

 async function checkForUpdate() {
    if (isPlatform('capacitor')) {
      const maintanenceURL =
        'https://example.com/maintenance.json';
      const updateURL =
        'https://example.com/update.json';

      try {
        const maintanenceFetch: AxiosResponse<MaintanenceDataInterface> =
          await axios.get(maintanenceURL);
        console.log('maintain', maintanenceFetch);

        if (maintanenceFetch.data.enabled) {
          setUpdateMessage(maintanenceFetch.data.msg);
          return;
        }

        const updateFetch: AxiosResponse<UpdateDataInterface> = await axios.get(
          updateURL
        );
        console.log('updateFetch', updateFetch);

        if (updateFetch.data.enabled) {
          const capApp = await App.getInfo();
          const capAppVersion = capApp.version;

          console.log('Thi is a thinkg', capAppVersion);

          if (isPlatform('android')) {
            console.log('hi');
            const { currentAndroid, majorMsg, minorMsg } = updateFetch.data;
            const idealVersionArr = currentAndroid.split('.');
            const actualVersionArr = capAppVersion.split('.');

            if (idealVersionArr[0] !== actualVersionArr[0]) {
              setUpdateMessage(majorMsg);
              setUpdateAvailable(true);
              return;
            }

            if (idealVersionArr[1] !== actualVersionArr[1]) {
              setUpdateMessage(minorMsg);
              setUpdateAvailable(true);
              return;
            }
          } else {
            const { currentIos, majorMsg, minorMsg } = updateFetch.data;
            const idealVersionArr = currentIos.split('.');
            const actualVersionArr = capAppVersion.split('.');

            if (idealVersionArr[0] !== actualVersionArr[0]) {
              setUpdateMessage(majorMsg);
              setUpdateAvailable(true);
              return;
            }

            if (idealVersionArr[1] !== actualVersionArr[1]) {
              setUpdateMessage(minorMsg);
              setUpdateAvailable(true);
              return;
            }
          }
        }
      } catch (err) {
        console.log('Error in checkForUpdate', err);
      }
    }
  }

For some reason, in my test I wrote to test this, my axiosSpy only shows that it has been called 1 time instead of the expected 2 times. The console logs I posted for both get requests run as well. I cannot figure out what I am doing wrong.

Here is the test:

it.only('should render the update page if the fetch call to update bucket is enabled and returns a different major version', async () => {
      const isPlatformSpy = jest.spyOn(ionicReact, 'isPlatform');
      isPlatformSpy.mockReturnValueOnce(true).mockReturnValueOnce(true);

      const appSpy = jest.spyOn(App, 'getInfo');
      appSpy.mockResolvedValueOnce({
        version: '0.8.0',
        name: 'test',
        build: '123',
        id: 'r132-132',
      });

      const axiosSpy = jest.spyOn(axios, 'get');
      axiosSpy
        .mockResolvedValueOnce({
          data: {
            enabled: false,
            msg: {
              title: 'App maintenance',
              msg: 'We are currently solving an issue where users cannot open the app. This should be solved by end of day 12/31/2022! Thank you for your patience ',
              btn: 'Ok',
              type: 'maintenance',
            },
          },
        })
        .mockResolvedValueOnce({
          data: {
            current: '1.0.0',
            currentAndroid: '1.0.0',
            currentIos: '2.0.0',
            enabled: true,
            majorMsg: {
              title: 'Important App update',
              msg: 'Please update your app to the latest version to continue using it. If you are on iPhone, go to the app store and search MO Gas Tax Back to update your app. The button below does not work but will in the current update!',
              btn: 'Download',
              type: 'major',
            },
            minorMsg: {
              title: 'App update available',
              msg: "There's a new version available, would you like to get it now?",
              btn: 'Download',
              type: 'minor',
            },
          },
        });

      customRender(<UpdateChild />);

      expect(axiosSpy).toHaveBeenCalledTimes(2);
    });


问:
Publishing from R Markdown to Wordpress
The blogs that are dedicated to answering this question all seem either out of date, or don't get me all the way there.

I've created a .rmd file that I would like to upload to my Wordpress blog as a post.  I've installed packages below and used code I have found from different blogs to try to accomplish this.

```<code>library(RWordPress)
library(knitr)
options(WordPressLogin = c(wp.user_id= wp.password), WordPressURL = 'https://vizandknowthings.com/')
knit2wp('Gambling.rmd', title = 'How to publish with R Markdown in
  WordPress', categories=c('R'),mt_keywords = c('knitr', 'wordpress'),
  wp_post_thumbnail=postThumbnail$id,publish=FALSE)
</code>```

The error it returns with is: Errors in file(con,"r") : cannot open the connection. I haven't been able to figure out what the issue is, if this looks familiar to anyone.

Title: Publishing from R Markdown to Wordpress

Body:
The blogs that are dedicated to answering this question all seem either out of date, or don't get me all the way there.

I've created a .rmd file that I would like to upload to my Wordpress blog as a post.  I've installed packages below and used code I have found from different blogs to try to accomplish this.

library(RWordPress)
library(knitr)
options(WordPressLogin = c(wp.user_id= wp.password), WordPressURL = 'https://vizandknowthings.com/')
knit2wp('Gambling.rmd', title = 'How to publish with R Markdown in
  WordPress', categories=c('R'),mt_keywords = c('knitr', 'wordpress'),
  wp_post_thumbnail=postThumbnail$id,publish=FALSE)

The error it returns with is: Errors in file(con,"r") : cannot open the connection. I haven't been able to figure out what the issue is, if this looks familiar to anyone.


问:
disable space after colon
Is it possible to disable the automatic addition of spaces after colons in CSS?</p>

Title: disable space after colon


问:
Incrementing an additional string per loop
I'm trying write a program that keeps printing a random fish emoji from a list, and each time it does, it'll print an additional fish on the same line. For example, the first printed line will have 1 fish, then the next line will have 2, then 3, and so on.

I have this code so far:

```<code>import random
import time

#
#
#

fish = ['', '', ''];

while 1 == 1 :
    print(random.choice(fish));
    time.sleep(.1)
</code>```

This prints a single fish per line. How can I make it print additional fish on the same line?

Body:
I'm trying write a program that keeps printing a random fish emoji from a list, and each time it does, it'll print an additional fish on the same line. For example, the first printed line will have 1 fish, then the next line will have 2, then 3, and so on.

I have this code so far:

import random
import time

#
#
#

fish = ['', '', ''];

while 1 == 1 :
    print(random.choice(fish));
    time.sleep(.1)

This prints a single fish per line. How can I make it print additional fish on the same line?


问:
Installing OpenMPI 4.1.4 on RHEL 9.1
I am trying to install OpenMPI on a new install of RHEL 9.1, and keep getting this error while using mock:

```<code>RPM build errors:
error: Bad exit status from /var/tmp/rpm-tmp.6QyYma (%build)
    Macro expanded in comment on line 708: %{install_in_opt}, then we're instaling OMPI to

    Bad exit status from /var/tmp/rpm-tmp.6QyYma (%build)
</code>```

Full output here. Generated from $ mock -r rhel-9-x86_64 rebuild openmpi-4.1.4-1.src.rpm. Not sure if it changes things, but I did do $ mock -r rhel-9-x86_64 --init beforehand as well.

I got a src.rpm from the OpenMPI download page, and because I did not know how to install it, used this and this, as well as the epel docs to help me along the process. I changed any rhel or epel 7 references to 9, and during installation/initialization for mock, everything seemed to work alright (as far as I could tell).

Coming from Ubuntu, I previously used the deprecated mpif90 to compile mpi stuff, but I believe I was able to install that using a package. I now want to use mpifort. Is there a better/different way to install the mpifort compiler wrapper, or a problem with my installation process? Is it not supported currently, and should I install legacy support of some kind?

Title: Installing OpenMPI 4.1.4 on RHEL 9.1

Body:
I am trying to install OpenMPI on a new install of RHEL 9.1, and keep getting this error while using mock:

RPM build errors:
error: Bad exit status from /var/tmp/rpm-tmp.6QyYma (%build)
    Macro expanded in comment on line 708: %{install_in_opt}, then we're instaling OMPI to

    Bad exit status from /var/tmp/rpm-tmp.6QyYma (%build)

Full output here. Generated from $ mock -r rhel-9-x86_64 rebuild openmpi-4.1.4-1.src.rpm. Not sure if it changes things, but I did do $ mock -r rhel-9-x86_64 --init beforehand as well.

I got a src.rpm from the OpenMPI download page, and because I did not know how to install it, used this and this, as well as the epel docs to help me along the process. I changed any rhel or epel 7 references to 9, and during installation/initialization for mock, everything seemed to work alright (as far as I could tell).

Coming from Ubuntu, I previously used the deprecated mpif90 to compile mpi stuff, but I believe I was able to install that using a package. I now want to use mpifort. Is there a better/different way to install the mpifort compiler wrapper, or a problem with my installation process? Is it not supported currently, and should I install legacy support of some kind?