问:
The matrix is not continuous, thus its number of rows can not be changed at OpenCvSharp.Internal.NativeMethods

I'm getting the above said error when comparing the two faces in opencvsharp, is there any other solution or need to change something in my code.

```<code>CascadeClassifier classifier = new CascadeClassifier("haarcascade_frontalface_default.xml");
        Mat image1 = Cv2.ImRead(filePath1, ImreadModes.Color);
        Mat image2 = Cv2.ImRead(filePath2, ImreadModes.Color);

        Rect[] faces1 = classifier.DetectMultiScale(image1);
        Rect[] faces2 = classifier.DetectMultiScale(image2);

        FaceRecognizer recognizer = EigenFaceRecognizer.Create();

        // Train the recognizer with the first face
        Mat face1 = new Mat(image1, faces1[0]);
        image1.PushBack(image1);
        image2.PushBack(image2);
        recognizer.Train(new Mat[] { face1 }, new int[] { 0 });

        // Predict the label of the second face
        Mat face2 = new Mat(image2, faces2[0]);
        var prediction = recognizer.Predict(face2);

        if (prediction == 0)
        {
            Console.WriteLine("The two faces match.");
        }
        else
        {
            Console.WriteLine("The two faces do not match.");
        }
</code>```

want to compare the two images with faces similar where

Body:
I'm getting the above said error when comparing the two faces in opencvsharp, is there any other solution or need to change something in my code.

CascadeClassifier classifier = new CascadeClassifier("haarcascade_frontalface_default.xml");
        Mat image1 = Cv2.ImRead(filePath1, ImreadModes.Color);
        Mat image2 = Cv2.ImRead(filePath2, ImreadModes.Color);

        Rect[] faces1 = classifier.DetectMultiScale(image1);
        Rect[] faces2 = classifier.DetectMultiScale(image2);

        FaceRecognizer recognizer = EigenFaceRecognizer.Create();

        // Train the recognizer with the first face
        Mat face1 = new Mat(image1, faces1[0]);
        image1.PushBack(image1);
        image2.PushBack(image2);
        recognizer.Train(new Mat[] { face1 }, new int[] { 0 });

        // Predict the label of the second face
        Mat face2 = new Mat(image2, faces2[0]);
        var prediction = recognizer.Predict(face2);

        if (prediction == 0)
        {
            Console.WriteLine("The two faces match.");
        }
        else
        {
            Console.WriteLine("The two faces do not match.");
        }

want to compare the two images with faces similar where


来源: stackexchange

问:
Module with name based on variable in Android.bp
modules sometimes use variables like $(TARGET_BOARD_PLATFORM) in their module name.
How can I do this in Android.bp
For example：

```<code>LOCAL_MODULE := gralloc.$(TARGET_BOARD_PLATFORM)
...
include $(BUILD_SHARED_LIBRARY)
</code>```

In google best_practices，the suggestion is to override by system property.
I tried, but it does not work.

In Android.bp:

```<code>cc_library {
    name: "gralloc.acme",
    ...
}
</code>```

In device/xxx.mk

```<code>PRODUCT_PACKAGES += gralloc.acme
PRODUCT_PROPERTY_OVERRIDES += ro.hardware.gralloc=acme
</code>```

ContentLicense: CC BY-SA 4.0

Body:
modules sometimes use variables like $(TARGET_BOARD_PLATFORM) in their module name.
How can I do this in Android.bp
For example：

LOCAL_MODULE := gralloc.$(TARGET_BOARD_PLATFORM)
...
include $(BUILD_SHARED_LIBRARY)

In google best_practices，the suggestion is to override by system property.
I tried, but it does not work.

In Android.bp:

cc_library {
    name: "gralloc.acme",
    ...
}

In device/xxx.mk

PRODUCT_PACKAGES += gralloc.acme
PRODUCT_PROPERTY_OVERRIDES += ro.hardware.gralloc=acme


问:
interacting with buttons in QDialog do not work when launched from a MainWindow in pyqt6
I have been struggling to solve this problem within my pyqt program, I am making a program where the user can use their controllers as a mouse in python. However I am stuck in this part where the user can map individual controls with their corresponding keys window. To be more specific, whenever I launch this Dialog: "controllerMapping.py" in my mainWindow/app, any buttons and interactions with the dialog do not work. However when run "controllerMapping.py" directly as a standalone window, everything seems to work?

Here's the code for the MainWindow invokking controllerMapping.py:

```<code>def summon_controllerMapping(self):
    # TODO: UNRESPONSIVE AS HELL
    self.cm = QtWidgets.QDialog()
    ui = controllerMapping.Ui_Dialog()
    ui.setupUi(self.cm)
    self.cm.show()
</code>```

And here's the entire code for controllerMapping.py, I used the pyqt-designer to create the widget then added my own methods to hook for the buttons.

```<code>from PyQt6 import QtCore, QtGui, QtWidgets
import editMapping
import init_db
import mapping

preset_columns = init_db.get_table_columns("presets")
controls_columns = init_db.get_table_columns("mapping")
keybind_data = init_db.get_table_data("mapping")

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(500, 500)
        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(130, 440, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.desc_lbl = QtWidgets.QLabel(Dialog)
        self.desc_lbl.setGeometry(QtCore.QRect(30, 30, 431, 16))
        self.desc_lbl.setObjectName("desc_lbl")
        self.mapping_table = QtWidgets.QTableWidget(Dialog)
        self.mapping_table.setGeometry(QtCore.QRect(30, 70, 441, 291))
        self.mapping_table.setObjectName("mapping_table")
        self.mapping_table.setColumnCount(0)
        self.mapping_table.setRowCount(0)
        self.edit_btn = QtWidgets.QPushButton(Dialog)
        self.edit_btn.setGeometry(QtCore.QRect(390, 360, 81, 24))
        self.edit_btn.setObjectName("edit_btn")
        self.selected_preset_lbl = QtWidgets.QLabel(Dialog)
        self.selected_preset_lbl.setGeometry(QtCore.QRect(30, 400, 91, 21))
        self.selected_preset_lbl.setObjectName("selected_preset_lbl")
        self.presets_list = QtWidgets.QComboBox(Dialog)
        self.presets_list.setGeometry(QtCore.QRect(130, 400, 161, 22))
        self.presets_list.setObjectName("presets_list")
        self.refresh_btn = QtWidgets.QPushButton(Dialog)
        self.refresh_btn.setGeometry(QtCore.QRect(30, 360, 81, 24))
        self.refresh_btn.setObjectName("refresh_btn")

        self.retranslateUi(Dialog)
        self.buttonBox.accepted.connect(Dialog.accept) # type: ignore
        self.buttonBox.rejected.connect(Dialog.reject) # type: ignore
        QtCore.QMetaObject.connectSlotsByName(Dialog)

        self.presets_list.setCurrentIndex(-1)
        self.populate_mapping_table()
        self.populate_presets_list()
        self.bind_btn()

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.desc_lbl.setText(_translate("Dialog", "Map Controls: Here is a list of controller buttons and their respective mapping"))
        self.edit_btn.setText(_translate("Dialog", "Edit"))
        self.selected_preset_lbl.setText(_translate("Dialog", "Selected Preset:"))
        self.refresh_btn.setText(_translate("Dialog", "Refresh"))

    def bind_btn(self):
        self.edit_btn.clicked.connect(self.summon_editMapping)
        self.presets_list.currentTextChanged.connect(self.set_new_preset)

    def summon_editMapping(self):
        self.em = QtWidgets.QDialog()
        ui = editMapping.Ui_Dialog()
        ui.setupUi(self.em)
        self.em.show()

    def populate_mapping_table(self):
        print("mapping table")
        column_cnt = len(preset_columns) + 1
        keybinds_cnt = len(controls_columns) + 1

        self.mapping_table.setColumnCount(column_cnt)
        self.mapping_table.setRowCount(keybinds_cnt)

        self.mapping_table.setItem(0, 0, QtWidgets.QTableWidgetItem("CONTROLS"))
        for column, preset in enumerate(preset_columns):
            self.mapping_table.setItem(0, column+1, QtWidgets.QTableWidgetItem(preset))

        for row, controller in enumerate(controls_columns):
            self.mapping_table.setItem(row+1, 0, QtWidgets.QTableWidgetItem(controller))

        for column, keybinds in enumerate(keybind_data):
            for row, keybind in enumerate(keybinds):
                self.mapping_table.setItem(row+1, column+1, QtWidgets.QTableWidgetItem(keybind))

    def populate_presets_list(self):
        print("presets")
        for preset in preset_columns:
            self.presets_list.addItem(preset)

    def set_new_preset(self):
        print("Hello world")
        """selected_preset = self.presets_list.currentText()
        print(selected_preset)

        db = "databases/controls.db"
        conn = sqlite3.connect(db)

        for column in init_db.get_table_columns("presets"):
            init_db.update_data("presets", column, False)

        init_db.update_data("presets", selected_preset, True)

        r = init_db.get_table_data("presets")
        print(r)

        conn.close()"""

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec())
</code>```

I tried using putting print statements in the self.bind_btn() function, to no avail they did not work.
Every function except for self. Every method seems to be working fine except for self.bind_btn()

Body:
I have been struggling to solve this problem within my pyqt program, I am making a program where the user can use their controllers as a mouse in python. However I am stuck in this part where the user can map individual controls with their corresponding keys window. To be more specific, whenever I launch this Dialog: "controllerMapping.py" in my mainWindow/app, any buttons and interactions with the dialog do not work. However when run "controllerMapping.py" directly as a standalone window, everything seems to work?

Here's the code for the MainWindow invokking controllerMapping.py:

def summon_controllerMapping(self):
    # TODO: UNRESPONSIVE AS HELL
    self.cm = QtWidgets.QDialog()
    ui = controllerMapping.Ui_Dialog()
    ui.setupUi(self.cm)
    self.cm.show()

And here's the entire code for controllerMapping.py, I used the pyqt-designer to create the widget then added my own methods to hook for the buttons.

from PyQt6 import QtCore, QtGui, QtWidgets
import editMapping
import init_db
import mapping

preset_columns = init_db.get_table_columns("presets")
controls_columns = init_db.get_table_columns("mapping")
keybind_data = init_db.get_table_data("mapping")

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(500, 500)
        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(130, 440, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.desc_lbl = QtWidgets.QLabel(Dialog)
        self.desc_lbl.setGeometry(QtCore.QRect(30, 30, 431, 16))
        self.desc_lbl.setObjectName("desc_lbl")
        self.mapping_table = QtWidgets.QTableWidget(Dialog)
        self.mapping_table.setGeometry(QtCore.QRect(30, 70, 441, 291))
        self.mapping_table.setObjectName("mapping_table")
        self.mapping_table.setColumnCount(0)
        self.mapping_table.setRowCount(0)
        self.edit_btn = QtWidgets.QPushButton(Dialog)
        self.edit_btn.setGeometry(QtCore.QRect(390, 360, 81, 24))
        self.edit_btn.setObjectName("edit_btn")
        self.selected_preset_lbl = QtWidgets.QLabel(Dialog)
        self.selected_preset_lbl.setGeometry(QtCore.QRect(30, 400, 91, 21))
        self.selected_preset_lbl.setObjectName("selected_preset_lbl")
        self.presets_list = QtWidgets.QComboBox(Dialog)
        self.presets_list.setGeometry(QtCore.QRect(130, 400, 161, 22))
        self.presets_list.setObjectName("presets_list")
        self.refresh_btn = QtWidgets.QPushButton(Dialog)
        self.refresh_btn.setGeometry(QtCore.QRect(30, 360, 81, 24))
        self.refresh_btn.setObjectName("refresh_btn")

        self.retranslateUi(Dialog)
        self.buttonBox.accepted.connect(Dialog.accept) # type: ignore
        self.buttonBox.rejected.connect(Dialog.reject) # type: ignore
        QtCore.QMetaObject.connectSlotsByName(Dialog)

        self.presets_list.setCurrentIndex(-1)
        self.populate_mapping_table()
        self.populate_presets_list()
        self.bind_btn()

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.desc_lbl.setText(_translate("Dialog", "Map Controls: Here is a list of controller buttons and their respective mapping"))
        self.edit_btn.setText(_translate("Dialog", "Edit"))
        self.selected_preset_lbl.setText(_translate("Dialog", "Selected Preset:"))
        self.refresh_btn.setText(_translate("Dialog", "Refresh"))

    def bind_btn(self):
        self.edit_btn.clicked.connect(self.summon_editMapping)
        self.presets_list.currentTextChanged.connect(self.set_new_preset)

    def summon_editMapping(self):
        self.em = QtWidgets.QDialog()
        ui = editMapping.Ui_Dialog()
        ui.setupUi(self.em)
        self.em.show()

    def populate_mapping_table(self):
        print("mapping table")
        column_cnt = len(preset_columns) + 1
        keybinds_cnt = len(controls_columns) + 1

        self.mapping_table.setColumnCount(column_cnt)
        self.mapping_table.setRowCount(keybinds_cnt)

        self.mapping_table.setItem(0, 0, QtWidgets.QTableWidgetItem("CONTROLS"))
        for column, preset in enumerate(preset_columns):
            self.mapping_table.setItem(0, column+1, QtWidgets.QTableWidgetItem(preset))

        for row, controller in enumerate(controls_columns):
            self.mapping_table.setItem(row+1, 0, QtWidgets.QTableWidgetItem(controller))

        for column, keybinds in enumerate(keybind_data):
            for row, keybind in enumerate(keybinds):
                self.mapping_table.setItem(row+1, column+1, QtWidgets.QTableWidgetItem(keybind))

    def populate_presets_list(self):
        print("presets")
        for preset in preset_columns:
            self.presets_list.addItem(preset)

    def set_new_preset(self):
        print("Hello world")
        """selected_preset = self.presets_list.currentText()
        print(selected_preset)

        db = "databases/controls.db"
        conn = sqlite3.connect(db)

        for column in init_db.get_table_columns("presets"):
            init_db.update_data("presets", column, False)

        init_db.update_data("presets", selected_preset, True)

        r = init_db.get_table_data("presets")
        print(r)

        conn.close()"""

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec())

I tried using putting print statements in the self.bind_btn() function, to no avail they did not work.
Every function except for self. Every method seems to be working fine except for self.bind_btn()


问:
Execute a python script that is on my Bitbucket via Jenkins
I have a python script that is configured on the Jenkins Job. The job is getting built successfully but I am not able to see the changes that the code should reflect- it should generate certain reports.
I have scheduled the job for every day but I cannot see that the python script is running.
There are multiple modules in my bitbucket repo. The code works completely fine when I run it on my local system.

I need help regarding how should my job also execute the script- since the code is built in such a way that it should generated reports as and when the job is run

I can build the job successfully.
I tried using Execute Shell feature but the job is failing then.


问:
import Base64UploadAdapter (Image Upload) throw duplicate modules error in react
duplicate module error

I tried this solution, but somehow not working, version are same


问:
how solve this primitive value issue of hl7 parsing using HAPI. the hl7 version is 2.6
ca.uhn.hl7v2.model.DataTypeException: ca.uhn.hl7v2.validation.ValidationException: Validation failed: Primitive value '455657' requires to be empty because it is withdrawn from the current HL7 version and should not be used at PID-13

PID|1||dd^^^^||7686786M|gh71^^States^^^|Ni|455657|4543|003|S|hhh|130^^^EclipsyN|34-4569||||||0||UNKNOWN|||

this is my PID of hl7 with version 2.6


问:
Exiting application in flutter
I have used SystemNavigator.pop(); to exit the application programmatically in flutter after I exit the app it stays in background when I reopen it in some phone(Android) the app restart but in some it just continues from the exit screen until I manually termite it from the background why so????

I am trying to figure out the proper App exiting method in flutter, The App exit method systemNavigaor.pop() behaves differently for different phone (Android)

Title: Exiting application in flutter


问:
Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference at com.example.newsapp.MainActivity$1.onResponse
I have this android News app code from a YouTube video GeeksForGeeks.

Wrote the same code but getting this error:

Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference at com.example.newsapp.MainActivity$1.onResponse

Please help me to solve this error.
Here is the code:

MainActivity.java

package com.example.newsapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity implements CategoryRVAdapter.CategorClickInterface{

    //3cd3cc2c4be045caa48e900fc41032b1

    private RecyclerView newsRV,categoryRV;
    private ProgressBar loadingPB;
    private ArrayList<Articles> articlesArrayList;
    private ArrayList<CategoryRVModal> categoryRVModalArrayList;
    private CategoryRVAdapter categoryRVAdapter;
    private NewsRVAdapter newsRVAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        newsRV = findViewById(R.id.idRVNews);
        categoryRV = findViewById(R.id.idRVCategories);
        loadingPB = findViewById(R.id.idPBLoading);
        articlesArrayList = new ArrayList<>();
        categoryRVModalArrayList = new ArrayList<>();
        newsRVAdapter = new NewsRVAdapter(articlesArrayList,this);
        categoryRVAdapter = new CategoryRVAdapter(categoryRVModalArrayList,this,this::onCategoryClick);
        newsRV.setLayoutManager(new LinearLayoutManager(this));
        newsRV.setAdapter(newsRVAdapter);
        categoryRV.setAdapter(categoryRVAdapter);
        getCategories();
        getNews("All");
        newsRVAdapter.notifyDataSetChanged();
    }

    private void getCategories() {
        categoryRVModalArrayList.add(new CategoryRVModal("All","https://plus.unsplash.com/premium_photo-1665311515438-a8e9c0eda3d3?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTl8fG91dGRvb3J8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Technology","https://images.unsplash.com/photo-1488590528505-98d2b5aba04b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8dGVjaG5vbG9neXxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Science","https://plus.unsplash.com/premium_photo-1661284886645-1e21653e252a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTN8fHNjaWVuY2V8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Sports","https://images.unsplash.com/photo-1517649763962-0c623066013b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fHNwb3J0fGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("General","https://images.unsplash.com/photo-1670516537787-22e2d8de641f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyMnx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Business","https://images.unsplash.com/photo-1460925895917-afdab827c52f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NDB8fGJ1c2luZXNzfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Entertainment","https://images.unsplash.com/photo-1603190287605-e6ade32fa852?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8ZW50ZXJ0YWlubWVudHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Health","https://images.unsplash.com/photo-1535914254981-b5012eebbd15?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTh8fGhlYWx0aHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVAdapter.notifyDataSetChanged();
    }

    private void getNews(String category){
        loadingPB.setVisibility(View.VISIBLE);
        articlesArrayList.clear();

        String categoryURL = "https://newsapi.org/v2/top-headlines/sources?category=" + category + "&apiKey=3cd3cc2c4be045caa48e900fc41032b1";
        String url = "https://newsapi.org/v2/top-headlines?country=in&excludeDomains=stackoverflow.com&shortBy=publishedAt&language=en&apiKey=3cd3cc2c4be045caa48e900fc41032b1";
        String BASE_URL = "https://newsapi.org/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
        Call<NewsModal> call;
        if (category.equals("All")){
            call = retrofitAPI.getAllNews(url);
        }else {
            call = retrofitAPI.getNewsByCategory(categoryURL);
        }

        call.enqueue(new Callback<NewsModal>() {
            @Override
            public void onResponse(Call<NewsModal> call, Response<NewsModal> response) {
                NewsModal newsModal = response.body();
                loadingPB.setVisibility(View.GONE);
                ArrayList<Articles> articles = newsModal.getArticles();
                for (int i=0; i < articles.size(); i++) {
                    articlesArrayList.add(new Articles(articles.get(i).getTitle(),articles.get(i).getDescription(),articles.get(i).getUrlToImage(),articles.get(i).getUrl(),articles.get(i).getContent()));
                }
                newsRVAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<NewsModal> call, Throwable t) {
                Toast.makeText(MainActivity.this, "Fail to get news", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onCategoryClick(int position) {
        String category = categoryRVModalArrayList.get(position).getCategory();
        getNews(category);
    }
}
```
<p><strong>NewsModal.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package com.example.newsapp;

import java.util.ArrayList;

public class NewsModal {

    private int totalResults;
    private String status;
    private ArrayList<Articles> articles;

    public NewsModal(int totalResults, String status, ArrayList<Articles> articles) {
        this.totalResults = totalResults;
        this.status = status;
        this.articles = articles;
    }

    public int getTotalResults() {
        return totalResults;
    }

    public void setTotalResults(int totalResults) {
        this.totalResults = totalResults;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public ArrayList<Articles> getArticles() {
        return articles;
    }

    public void setArticles(ArrayList<Articles> articles) {
        this.articles = articles;
    }
}
</code>```

Articles.java

package com.example.newsapp;

public class Articles {

    private String title;
    private String description;
    private String urlToImage;
    private String url;
    private String content;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrlToImage() {
        return urlToImage;
    }

    public void setUrlToImage(String urlToImage) {
        this.urlToImage = urlToImage;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Articles(String title, String description, String urlToImage, String url, String content) {
        this.title = title;
        this.description = description;
        this.urlToImage = urlToImage;
        this.url = url;
        this.content = content;
    }
}
```

The error is on MainActivity.java:84 at for loop not getting the size of articles or not getting the value from newsModal.getArticles() don't know what is the real cause for this error.

Body:
I have this android News app code from a YouTube video GeeksForGeeks.

Wrote the same code but getting this error:

Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference at com.example.newsapp.MainActivity$1.onResponse

Please help me to solve this error.
Here is the code:

MainActivity.java

package com.example.newsapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity implements CategoryRVAdapter.CategorClickInterface{

    //3cd3cc2c4be045caa48e900fc41032b1

    private RecyclerView newsRV,categoryRV;
    private ProgressBar loadingPB;
    private ArrayList<Articles> articlesArrayList;
    private ArrayList<CategoryRVModal> categoryRVModalArrayList;
    private CategoryRVAdapter categoryRVAdapter;
    private NewsRVAdapter newsRVAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        newsRV = findViewById(R.id.idRVNews);
        categoryRV = findViewById(R.id.idRVCategories);
        loadingPB = findViewById(R.id.idPBLoading);
        articlesArrayList = new ArrayList<>();
        categoryRVModalArrayList = new ArrayList<>();
        newsRVAdapter = new NewsRVAdapter(articlesArrayList,this);
        categoryRVAdapter = new CategoryRVAdapter(categoryRVModalArrayList,this,this::onCategoryClick);
        newsRV.setLayoutManager(new LinearLayoutManager(this));
        newsRV.setAdapter(newsRVAdapter);
        categoryRV.setAdapter(categoryRVAdapter);
        getCategories();
        getNews("All");
        newsRVAdapter.notifyDataSetChanged();
    }

    private void getCategories() {
        categoryRVModalArrayList.add(new CategoryRVModal("All","https://plus.unsplash.com/premium_photo-1665311515438-a8e9c0eda3d3?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTl8fG91dGRvb3J8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Technology","https://images.unsplash.com/photo-1488590528505-98d2b5aba04b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8dGVjaG5vbG9neXxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Science","https://plus.unsplash.com/premium_photo-1661284886645-1e21653e252a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTN8fHNjaWVuY2V8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Sports","https://images.unsplash.com/photo-1517649763962-0c623066013b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fHNwb3J0fGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("General","https://images.unsplash.com/photo-1670516537787-22e2d8de641f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyMnx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Business","https://images.unsplash.com/photo-1460925895917-afdab827c52f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NDB8fGJ1c2luZXNzfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Entertainment","https://images.unsplash.com/photo-1603190287605-e6ade32fa852?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8ZW50ZXJ0YWlubWVudHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVModalArrayList.add(new CategoryRVModal("Health","https://images.unsplash.com/photo-1535914254981-b5012eebbd15?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTh8fGhlYWx0aHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60"));
        categoryRVAdapter.notifyDataSetChanged();
    }

    private void getNews(String category){
        loadingPB.setVisibility(View.VISIBLE);
        articlesArrayList.clear();

        String categoryURL = "https://newsapi.org/v2/top-headlines/sources?category=" + category + "&apiKey=3cd3cc2c4be045caa48e900fc41032b1";
        String url = "https://newsapi.org/v2/top-headlines?country=in&excludeDomains=stackoverflow.com&shortBy=publishedAt&language=en&apiKey=3cd3cc2c4be045caa48e900fc41032b1";
        String BASE_URL = "https://newsapi.org/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
        Call<NewsModal> call;
        if (category.equals("All")){
            call = retrofitAPI.getAllNews(url);
        }else {
            call = retrofitAPI.getNewsByCategory(categoryURL);
        }

        call.enqueue(new Callback<NewsModal>() {
            @Override
            public void onResponse(Call<NewsModal> call, Response<NewsModal> response) {
                NewsModal newsModal = response.body();
                loadingPB.setVisibility(View.GONE);
                ArrayList<Articles> articles = newsModal.getArticles();
                for (int i=0; i < articles.size(); i++) {
                    articlesArrayList.add(new Articles(articles.get(i).getTitle(),articles.get(i).getDescription(),articles.get(i).getUrlToImage(),articles.get(i).getUrl(),articles.get(i).getContent()));
                }
                newsRVAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<NewsModal> call, Throwable t) {
                Toast.makeText(MainActivity.this, "Fail to get news", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onCategoryClick(int position) {
        String category = categoryRVModalArrayList.get(position).getCategory();
        getNews(category);
    }
}

NewsModal.java

package com.example.newsapp;

import java.util.ArrayList;

public class NewsModal {

    private int totalResults;
    private String status;
    private ArrayList<Articles> articles;

    public NewsModal(int totalResults, String status, ArrayList<Articles> articles) {
        this.totalResults = totalResults;
        this.status = status;
        this.articles = articles;
    }

    public int getTotalResults() {
        return totalResults;
    }

    public void setTotalResults(int totalResults) {
        this.totalResults = totalResults;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public ArrayList<Articles> getArticles() {
        return articles;
    }

    public void setArticles(ArrayList<Articles> articles) {
        this.articles = articles;
    }
}

Articles.java

package com.example.newsapp;

public class Articles {

    private String title;
    private String description;
    private String urlToImage;
    private String url;
    private String content;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrlToImage() {
        return urlToImage;
    }

    public void setUrlToImage(String urlToImage) {
        this.urlToImage = urlToImage;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Articles(String title, String description, String urlToImage, String url, String content) {
        this.title = title;
        this.description = description;
        this.urlToImage = urlToImage;
        this.url = url;
        this.content = content;
    }
}

The error is on MainActivity.java:84 at for loop not getting the size of articles or not getting the value from newsModal.getArticles() don't know what is the real cause for this error.


问:
VS 2022 for SSIS not showing checkbox against properties to export
I have installed VS 2022 with SSIS extension. I am able to work with SSIS packages in VS 2022 & run them.

I want to export some properties to XML configuration (package configuration). However, it is not showing the checkbox against properties as shown in image. It is also not allowing me to select the checkbox at the task level.

Why are the checkboxes missing against properties, any idea?


Title: Ansible win_shell printing wrong output

Body:
Ansible win_shell/win_command prints logo output instead of actual output of the command:

- name: get Ps1 files
      win_shell: get-ChildItem -path $testFolder -Filter *.ps1 -Recurse -File -Name -Depth 0
      register: ps1_files
      args:
        executable: powershell

Should print a list of *.ps1 folders but instead prints wrong output (command works when running directly on powershell on the server):

"msg": {
2022-12-22T02:30:46.455812-0500 info:         "changed": true,
2022-12-22T02:30:46.455867-0500 info:         "cmd": "get-ChildItem -path $realProcessesFolder -Filter *.ps1 -Recurse -File -Name -Depth 0",
2022-12-22T02:30:46.455917-0500 info:         "delta": "0:00:00.954839",
2022-12-22T02:30:46.455969-0500 info:         "end": "2022-12-22 07:30:46.385668",
2022-12-22T02:30:46.456017-0500 info:         "failed": false,
2022-12-22T02:30:46.456065-0500 info:         "rc": 0,
2022-12-22T02:30:46.456115-0500 info:         "start": "2022-12-22 07:30:45.430828",
2022-12-22T02:30:46.456165-0500 info:         "stderr": "",
2022-12-22T02:30:46.456237-0500 info:         "stderr_lines": [],
2022-12-22T02:30:46.456289-0500 info:         "stdout": "\r\n\r\nComputerName  : SL143312\r\nBuilddate     : 2019-Aug-26 13:43:8\r\nProfile       : Standard Application Server\r\nOS            : Windows Server 2016 Standard Edition\r\nMachineType   : VMware Virtual Platform\r\nModel         : VMware, Inc.\r\nServerAppCode : TVP0\r\n\r\n\r\n\r\n",
2022-12-22T02:30:46.456343-0500 info:         "stdout_lines": [
2022-12-22T02:30:46.456393-0500 info:             "",
2022-12-22T02:30:46.456445-0500 info:             "",
2022-12-22T02:30:46.456504-0500 info:             "ComputerName  : SL143312",
2022-12-22T02:30:46.456556-0500 info:             "Builddate     : 2019-Aug-26 13:43:8",
2022-12-22T02:30:46.456615-0500 info:             "Profile       : Standard Application Server",
2022-12-22T02:30:46.456663-0500 info:             "OS            : Windows Server 2016 Standard Edition",
2022-12-22T02:30:46.456718-0500 info:             "MachineType   : VMware Virtual Platform",
2022-12-22T02:30:46.456767-0500 info:             "Model         : VMware, Inc.",
2022-12-22T02:30:46.456816-0500 info:             "ServerAppCode : TT00",
2022-12-22T02:30:46.456866-0500 info:             "",
2022-12-22T02:30:46.456916-0500 info:             "",
2022-12-22T02:30:46.456977-0500 info:             ""
2022-12-22T02:30:46.457027-0500 info:         ]
2022-12-22T02:30:46.457079-0500 info:     }

This looks to me more like a logo.
I have used also the win_command module with nologo and came up with same result:

win_command: powershell -noninteractive -nologo -command  "get-ChildItem -path $env:realProcessesFolder -Filter *.ps1 -Recurse -File -Name -Depth 0"

It would be great if you would have any suggestions.
Many thanks!


问:
Is there any way to connect my google calendar to google colab?
I created a project using the Google Cloud Console and created an OAuth screen. But when I used Python in colab to access the calendar, I got an error message that I don't have a proper redirect uri. Is there any way to bypass accessing my Google Calendar with my login credentials rather than using an access token </p>


问:
How to Pass from value to DataTable in onClick button?
I have two buttons, when clicked, they will send 0001 or 0002 respectively

I try to receive value from oSearch

It succeeds, but only shows the value of the first click

For example:

I click the first button first, and 0001 will appear in the search bar. After closing the window, click the second button, and 0001 will appear in the search bar instead of 0002.

If I click the second button first, 0002 will appear in the search bar. After closing the window, click the first button, and 0002 will appear in the search bar instead of 0001.

It cannot display the corresponding value according to the button I clicked

getvalue is what I use to get the value passed by the button

How can I adjust it so that I can click which button so that the corresponding value will appear in the search bar?

Thanks for your help

```<code>jBPM('#modal-table').DataTable({
    "retrieve": true,
    "searching": true,
    "paging": false,
    "ordering": true,
    //"destroy": true,
    "columnDefs":[
    {
        "targets":[2],
        "searchable":false
    }
    ],
    "oSearch": {"sSearch": getvalue}
});
</code>```

Body:
I have two buttons, when clicked, they will send 0001 or 0002 respectively

I try to receive value from oSearch

It succeeds, but only shows the value of the first click

For example:

I click the first button first, and 0001 will appear in the search bar. After closing the window, click the second button, and 0001 will appear in the search bar instead of 0002.

If I click the second button first, 0002 will appear in the search bar. After closing the window, click the first button, and 0002 will appear in the search bar instead of 0001.

It cannot display the corresponding value according to the button I clicked

getvalue is what I use to get the value passed by the button

How can I adjust it so that I can click which button so that the corresponding value will appear in the search bar?

Thanks for your help

jBPM('#modal-table').DataTable({
    "retrieve": true,
    "searching": true,
    "paging": false,
    "ordering": true,
    //"destroy": true,
    "columnDefs":[
    {
        "targets":[2],
        "searchable":false
    }
    ],
    "oSearch": {"sSearch": getvalue}
});


问:
I don't know why there are diferent numbers in the same variable
I was trying to assign in a 2D vector a random number between 0 and 10, but I kept having numbers above 10, (was an error of having different sizes of row and column), but searching I wanted to know if it was my fault or rand (wow mine), I changed the error, but i noticed that the random number assigned to "a" was different both times I printed.

```<code>int main()
{
    srand(time(NULL));

    int column = LENGTH/2-2;
    int row =WIDTH/2-2;
    int map[row][column];

    for (int i = 0 ; i <= row ; i++){
        for (int j = 0 ; j <= column ; j++){
            int a =randint(11);
            printf("%d ",a);
            map[i][j]= a;
        };
        printf("\n");
    };
    printf("----------------------------------------------------------------------------\n");
    for (int i = 0 ; i <= row ; i++){
        for (int j = 0 ; j <= column ; j++){
            printf("%d ", map[i][j]);
        };
        printf("\n");
    };
</code>```

results

Body:
I was trying to assign in a 2D vector a random number between 0 and 10, but I kept having numbers above 10, (was an error of having different sizes of row and column), but searching I wanted to know if it was my fault or rand (wow mine), I changed the error, but i noticed that the random number assigned to "a" was different both times I printed.

int main()
{
    srand(time(NULL));

    int column = LENGTH/2-2;
    int row =WIDTH/2-2;
    int map[row][column];

    for (int i = 0 ; i <= row ; i++){
        for (int j = 0 ; j <= column ; j++){
            int a =randint(11);
            printf("%d ",a);
            map[i][j]= a;
        };
        printf("\n");
    };
    printf("----------------------------------------------------------------------------\n");
    for (int i = 0 ; i <= row ; i++){
        for (int j = 0 ; j <= column ; j++){
            printf("%d ", map[i][j]);
        };
        printf("\n");
    };

results


问:
flutter widgets to pdf file or word document
is there a any way to convert flutter widget into PDF document or word file. when we convert widget image and than image to PDF file text is not selectable.

i want to save flutter widget in PDF or any document document or excel


问:
How to run a script residing in an image when running AWS EMR spark-submit from Lambda?
I have been provided a container image with a script and supporting files inside residing in /opt/spark/work-dir.
Example:

test-job.py

test-config.json

dataset/set1/* (This consist of more files and subfolders)

dataset/set2/* (This also consist of more files and subfolders)

I have a Lambda that will trigger the spark-submit and using "local:///" to reference the script.
The spark-submit section looks like this:

```<code>        Steps=[
            {
                'Name': flowname,
                'ActionOnFailure': 'TERMINATE_CLUSTER',
                'HadoopJarStep': {
                        'Jar': 'command-runner.jar',
                        'Args': [
                            'spark-submit',
                            '--master', 'yarn',
                            '--name', 'my-test-job',
                            '--deploy-mode', 'cluster',
                            '--driver-memory', '4G',
                            '--conf', 'spark.sql.adaptive.enabled=true',
                            '--conf', 'spark.sql.shuffle.partitions=72',
                            '--conf', 'spark.default.parallelism=20',
                            "--conf", 'spark.executorEnv.YARN_CONTAINER_RUNTIME_TYPE=docker',
                            "--conf", 'spark.executorEnv.YARN_CONTAINER_RUNTIME_DOCKER_IMAGE='+DOCKER_IMAGE,
                            "--conf", 'spark.executorEnv.PYSPARK_PYTHON=/usr/local/bin/python3',
                            "--conf", 'spark.yarn.appMasterEnv.YARN_CONTAINER_RUNTIME_TYPE=docker',
                            "--conf", 'spark.yarn.appMasterEnv.YARN_CONTAINER_RUNTIME_DOCKER_IMAGE='+DOCKER_IMAGE,
                            "--conf", 'spark.yarn.appMasterEnv.PYSPARK_PYTHON=/usr/local/bin/python3',
                            "--conf", 'spark.yarn.appMasterEnv.PYSPARK_DRIVER_PYTHON=/usr/local/bin/python3',
                            '--files', 'local:///opt/spark/work-dir/test-job.py',
                            '--py-files', 's3://resource_bucket/addon_files/lib.zip',
                            '--jars', 'local:///opt/spark/work-dir/jars/dep.jar',
                            'local:///opt/spark/work-dir/test-job.py',
                            '--config_filepath', 'test-config.json',
                            '--set1', 'dataset/set1',
                            '--set2', 'dataset/set2',
                        ]
                }
            }
        ],
</code>```

However, there will be an error when it runs.

```<code>/usr/local/bin/python3: can't open file '/mnt1/yarn/usercache/hadoop/appcache/application_1672297290926_0001/container_1672297290926_0001_02_000001/test-job.py': [Errno 2] No such file or directory
</code>```

Is there any way to overcome this?

For the record, the image is provided by another team so ideally, I do not want to make any changes to it besides bootstrapping. In addition, I would also want to use the files already packaged in the image so that I do not have to maintain my own copy.

Thanks in advance for any input / feedback.

Body:
I have been provided a container image with a script and supporting files inside residing in /opt/spark/work-dir.
Example:

test-job.py

test-config.json

dataset/set1/* (This consist of more files and subfolders)

dataset/set2/* (This also consist of more files and subfolders)

I have a Lambda that will trigger the spark-submit and using "local:///" to reference the script.
The spark-submit section looks like this:

        Steps=[
            {
                'Name': flowname,
                'ActionOnFailure': 'TERMINATE_CLUSTER',
                'HadoopJarStep': {
                        'Jar': 'command-runner.jar',
                        'Args': [
                            'spark-submit',
                            '--master', 'yarn',
                            '--name', 'my-test-job',
                            '--deploy-mode', 'cluster',
                            '--driver-memory', '4G',
                            '--conf', 'spark.sql.adaptive.enabled=true',
                            '--conf', 'spark.sql.shuffle.partitions=72',
                            '--conf', 'spark.default.parallelism=20',
                            "--conf", 'spark.executorEnv.YARN_CONTAINER_RUNTIME_TYPE=docker',
                            "--conf", 'spark.executorEnv.YARN_CONTAINER_RUNTIME_DOCKER_IMAGE='+DOCKER_IMAGE,
                            "--conf", 'spark.executorEnv.PYSPARK_PYTHON=/usr/local/bin/python3',
                            "--conf", 'spark.yarn.appMasterEnv.YARN_CONTAINER_RUNTIME_TYPE=docker',
                            "--conf", 'spark.yarn.appMasterEnv.YARN_CONTAINER_RUNTIME_DOCKER_IMAGE='+DOCKER_IMAGE,
                            "--conf", 'spark.yarn.appMasterEnv.PYSPARK_PYTHON=/usr/local/bin/python3',
                            "--conf", 'spark.yarn.appMasterEnv.PYSPARK_DRIVER_PYTHON=/usr/local/bin/python3',
                            '--files', 'local:///opt/spark/work-dir/test-job.py',
                            '--py-files', 's3://resource_bucket/addon_files/lib.zip',
                            '--jars', 'local:///opt/spark/work-dir/jars/dep.jar',
                            'local:///opt/spark/work-dir/test-job.py',
                            '--config_filepath', 'test-config.json',
                            '--set1', 'dataset/set1',
                            '--set2', 'dataset/set2',
                        ]
                }
            }
        ],

However, there will be an error when it runs.

/usr/local/bin/python3: can't open file '/mnt1/yarn/usercache/hadoop/appcache/application_1672297290926_0001/container_1672297290926_0001_02_000001/test-job.py': [Errno 2] No such file or directory

Is there any way to overcome this?

For the record, the image is provided by another team so ideally, I do not want to make any changes to it besides bootstrapping. In addition, I would also want to use the files already packaged in the image so that I do not have to maintain my own copy.

Thanks in advance for any input / feedback.


问:
Getting error 'Property 'accounts' does not exist on type 'typeof google'' when using Google identity services with react
I am trying to implement authentication using Google in react as below.

```<code>  useEffect(() => {
    /* global google */
    google.accounts.id.initialize({
      client_id:
        "62032923843-508a2loa4eef8eo8kjma93m6iqekbdp.apps.googleusercontent.com",
      callback: handleCallBackResponse,
    });
    google.accounts.id.renderButton(
      document.getElementById("logInWithGoogleDiv"),
      { theme: "outline", size: "large" }
    );
  }, []);

</code>```

I am unfortunately getting the error Property 'accounts' does not exist on type 'typeof google'. . I have google maps package installed in my project too.

I tried disabling Eslint for that line causing the error but that didnt fix it.
Partaining that i have a few questions,

Is there an npm package to handle google identity services authentication in a react way. Currently everything other than the error is fine but i was wondering if there was a simpler way than running vanilla Js code inside useeffect.

Is there a way i can customize my renderButton to fit my own personal style? Googles is fine but is there a way to implement something more consistent with my brand

How can i get rid of the typescript error?

Body:
I am trying to implement authentication using Google in react as below.

  useEffect(() => {
    /* global google */
    google.accounts.id.initialize({
      client_id:
        "62032923843-508a2loa4eef8eo8kjma93m6iqekbdp.apps.googleusercontent.com",
      callback: handleCallBackResponse,
    });
    google.accounts.id.renderButton(
      document.getElementById("logInWithGoogleDiv"),
      { theme: "outline", size: "large" }
    );
  }, []);

I am unfortunately getting the error Property 'accounts' does not exist on type 'typeof google'. . I have google maps package installed in my project too.

I tried disabling Eslint for that line causing the error but that didnt fix it.
Partaining that i have a few questions,

Is there an npm package to handle google identity services authentication in a react way. Currently everything other than the error is fine but i was wondering if there was a simpler way than running vanilla Js code inside useeffect.

Is there a way i can customize my renderButton to fit my own personal style? Googles is fine but is there a way to implement something more consistent with my brand

How can i get rid of the typescript error?


问:
Is it possible to use native ads android plugin in unity?
Actually, I have to add native ads in my game using android plugin. how i can use my game native ads layout in android studio.

I added native ads script in android studio and make module(.aar file). I imported .aar file inside my unity game but i dont know how to show native ads in unity through android studio.


问:
how avoid 401 error everytime with axios?
I have a project with react and an java spring boot api. For connect to the api, after SignIn with google login, i do this :

```<code>import axios from 'axios'
import { useNavigate } from 'react-router-dom';
import { signInRoute } from '../../routing';

export function SignInGetService() {
    axios.get(process.env.REACT_APP_API_SERVER_URL + '/url', {})
        .then(response => { });
}

export async function SignInPostService(token) {
    return await axios.post(process.env.REACT_APP_API_SERVER_URL + '/mySignInUrl', { "token": token })
        .then(response => {
            axios.defaults.headers.common['X-AUTH-TOKEN'] = response.data['data'];
            return response.data['data']
        }).catch(function(error) {
            if(error.response.status == 500){
            window.localStorage.removeItem('userFromStorage');
            window.location.reload()
            }
        });
}
</code>```

in app.tsx my code is :

```<code>interface AuthContextType {
  user: any;
  signin: (userMail: string, callback: VoidFunction, userObject: Object) => void;
  signout: (callback: VoidFunction) => void;
}

let AuthContext = React.createContext<AuthContextType>(null!);

function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<any>(window.localStorage.getItem('userFromStorage'));

  let signin = (newUserMail: string, callback: VoidFunction, newUserObject: Object) => {
    return fakeAuthProvider.signin(() => {
      setUser(JSON.stringify(newUserMail));
      window.localStorage.setItem('userFromStorage', JSON.stringify(newUserMail));
      callback();
    });
  };

  let signout = (callback: VoidFunction) => {
    return fakeAuthProvider.signout(() => {
      setUser(null);
      window.localStorage.removeItem('userFromStorage');
      callback();
    });
  };
  const value = { user, signin, signout };
  const [isLoading, setIsLoading] = useState(true)
  if (user != null) {
    let r = SignInPostService(JSON.parse(user).token).then(() => {
      setIsLoading(false)
    })

  }
  if (user != null && isLoading == false) {
    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
  }
  if (user == null) {
    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;

  }
}

export function useAuth() {
  return React.useContext(AuthContext);
}

function RequireAuth({ children }: { children: JSX.Element }) {
  let auth = useAuth();
  let location = useLocation();
  if (!auth.user) {
    return <Navigate to="/SignIn" state={{ from: location }} replace />;
  }

  return children;
}

</code>```

So after this, normally everytime I do a request my X-AUTH-TOKEN is suppose to be well set.
And actually it's work. But sometimes, not often but enough for being annoying, I have an 401 error.
And If I refresh the 401 error disappear.
Do you know where it can come from ?
Thank you all.

I expect that the X-AUTH-TOKEN is set everytime.

Body:
I have a project with react and an java spring boot api. For connect to the api, after SignIn with google login, i do this :

import axios from 'axios'
import { useNavigate } from 'react-router-dom';
import { signInRoute } from '../../routing';

export function SignInGetService() {
    axios.get(process.env.REACT_APP_API_SERVER_URL + '/url', {})
        .then(response => { });
}

export async function SignInPostService(token) {
    return await axios.post(process.env.REACT_APP_API_SERVER_URL + '/mySignInUrl', { "token": token })
        .then(response => {
            axios.defaults.headers.common['X-AUTH-TOKEN'] = response.data['data'];
            return response.data['data']
        }).catch(function(error) {
            if(error.response.status == 500){
            window.localStorage.removeItem('userFromStorage');
            window.location.reload()
            }
        });
}

in app.tsx my code is :

interface AuthContextType {
  user: any;
  signin: (userMail: string, callback: VoidFunction, userObject: Object) => void;
  signout: (callback: VoidFunction) => void;
}

let AuthContext = React.createContext<AuthContextType>(null!);

function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<any>(window.localStorage.getItem('userFromStorage'));

  let signin = (newUserMail: string, callback: VoidFunction, newUserObject: Object) => {
    return fakeAuthProvider.signin(() => {
      setUser(JSON.stringify(newUserMail));
      window.localStorage.setItem('userFromStorage', JSON.stringify(newUserMail));
      callback();
    });
  };

  let signout = (callback: VoidFunction) => {
    return fakeAuthProvider.signout(() => {
      setUser(null);
      window.localStorage.removeItem('userFromStorage');
      callback();
    });
  };
  const value = { user, signin, signout };
  const [isLoading, setIsLoading] = useState(true)
  if (user != null) {
    let r = SignInPostService(JSON.parse(user).token).then(() => {
      setIsLoading(false)
    })

  }
  if (user != null && isLoading == false) {
    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
  }
  if (user == null) {
    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;

  }
}

export function useAuth() {
  return React.useContext(AuthContext);
}

function RequireAuth({ children }: { children: JSX.Element }) {
  let auth = useAuth();
  let location = useLocation();
  if (!auth.user) {
    return <Navigate to="/SignIn" state={{ from: location }} replace />;
  }

  return children;
}

So after this, normally everytime I do a request my X-AUTH-TOKEN is suppose to be well set.
And actually it's work. But sometimes, not often but enough for being annoying, I have an 401 error.
And If I refresh the 401 error disappear.
Do you know where it can come from ?
Thank you all.

I expect that the X-AUTH-TOKEN is set everytime.


问:
What is the change in mongoose version 5 & 6 for model function
```<code>import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document, Schema as MongooseSchema, model } from "mongoose";

export type BookDocument = Book & Document;

@Schema()
export class Book {
  _id: MongooseSchema.Types.ObjectId;

  @Prop({ required: true, unique: true })
  name: string;
}

export const BookSchema = SchemaFactory.createForClass(Book);

export const BookModel = model<BookDocument>("Book", BookSchema);

</code>```

Here, using mongoose version 6.0.2 & BookSchema is giving error. But in version 5.0.2 it is working file. @nesjs/mongoose version in 9.2.1 . What is the issue behind this version changes?

Expected BookSchema will work perfectly for mongoose version 6

Body:
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document, Schema as MongooseSchema, model } from "mongoose";

export type BookDocument = Book & Document;

@Schema()
export class Book {
  _id: MongooseSchema.Types.ObjectId;

  @Prop({ required: true, unique: true })
  name: string;
}

export const BookSchema = SchemaFactory.createForClass(Book);

export const BookModel = model<BookDocument>("Book", BookSchema);

Here, using mongoose version 6.0.2 & BookSchema is giving error. But in version 5.0.2 it is working file. @nesjs/mongoose version in 9.2.1 . What is the issue behind this version changes?

Expected BookSchema will work perfectly for mongoose version 6


问:
While loop thats dependent on a boolean from scanner runs twice(java)
I have this code, its supposed to ask the user for input and stop when the user inputs false.
If its not, it is supposed to do different things based on what they enter.

```<code>//ask the user if they want to view the average
System.out.println("Do you want to view the average of your data? please answer with true or false?");
currentAnswer = scan.nextBoolean();
if(currentAnswer){
    System.out.println("If yes, please type in one of the following(type false to exit)\n calories - protein - weight - rating");

}
String option;
/***

This is where the problem is. The code prints "Please type in one of the following....." twice instead of once, otherwise it works as intended.

*/
while(currentAnswer){
    option = scan.nextLine();
    switch (option) {
        case "calories": System.out.println(dataAverage("calories"));
        break;
        case "protein": System.out.println(dataAverage("protein"));
            break;
        case "rating": System.out.println(dataAverage("rating"));
            break;
        case "weight": System.out.println(dataAverage("weight"));
            break;
        case "false": currentAnswer = false;
        break;

    }

        System.out.println(" Please type in one of the following(type false to exit)\n calories - protein - weight - rating");

}
</code>```

I tried a do while loop, but the problem is still there. Any ideas?

Body:
I have this code, its supposed to ask the user for input and stop when the user inputs false.
If its not, it is supposed to do different things based on what they enter.

//ask the user if they want to view the average
System.out.println("Do you want to view the average of your data? please answer with true or false?");
currentAnswer = scan.nextBoolean();
if(currentAnswer){
    System.out.println("If yes, please type in one of the following(type false to exit)\n calories - protein - weight - rating");

}
String option;
/***

This is where the problem is. The code prints "Please type in one of the following....." twice instead of once, otherwise it works as intended.

*/
while(currentAnswer){
    option = scan.nextLine();
    switch (option) {
        case "calories": System.out.println(dataAverage("calories"));
        break;
        case "protein": System.out.println(dataAverage("protein"));
            break;
        case "rating": System.out.println(dataAverage("rating"));
            break;
        case "weight": System.out.println(dataAverage("weight"));
            break;
        case "false": currentAnswer = false;
        break;

    }

        System.out.println(" Please type in one of the following(type false to exit)\n calories - protein - weight - rating");

}

I tried a do while loop, but the problem is still there. Any ideas?


问:
ElasticSearch not running on raspberry pi
I am trying to install and run elasticsearch on my raspberry pi and when I execute the command sudo service elasticsearch restart I don't see elasticsearch running and when I check the status using the command sudo service elasticsearch status I see the below response

```<code>Dec 28 23:15:32 raspberrypi systemd[1]: Starting LSB: Starts elasticsearch...
Dec 28 23:15:32 raspberrypi elasticsearch[21031]: [warning] /etc/init.d/elasticsearch: JVM flavor 'sun6' not understood
Dec 28 23:15:32 raspberrypi elasticsearch[21031]: [warning] /etc/init.d/elasticsearch: No java runtime was found
Dec 28 23:15:32 raspberrypi systemd[1]: Started LSB: Starts elasticsearch.
</code>```

I have below java version installed on my raspberry pi

```<code>root@raspberrypi:/home/pi# java --version
openjdk 11.0.11 2021-04-20
OpenJDK Runtime Environment (build 11.0.11+9-post-Raspbian-1deb10u1)
OpenJDK Server VM (build 11.0.11+9-post-Raspbian-1deb10u1, mixed mode)
</code>```

Not sure if the issue is with Java version or elasticsearch version . Also on hitting curl localhost:9200 I get connection refused error. And on executing below ./bin/elasticsearch --version I receive the error

```<code>root@raspberrypi:/usr/share/elasticsearch# ./bin/elasticsearch --version
Option requires an argument: '--version'.
Unrecognized VM option 'UseParNewGC'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
</code>```

Note : I am using Java 11 , is that a issue ?

Body:
I am trying to install and run elasticsearch on my raspberry pi and when I execute the command sudo service elasticsearch restart I don't see elasticsearch running and when I check the status using the command sudo service elasticsearch status I see the below response

Dec 28 23:15:32 raspberrypi systemd[1]: Starting LSB: Starts elasticsearch...
Dec 28 23:15:32 raspberrypi elasticsearch[21031]: [warning] /etc/init.d/elasticsearch: JVM flavor 'sun6' not understood
Dec 28 23:15:32 raspberrypi elasticsearch[21031]: [warning] /etc/init.d/elasticsearch: No java runtime was found
Dec 28 23:15:32 raspberrypi systemd[1]: Started LSB: Starts elasticsearch.

I have below java version installed on my raspberry pi

root@raspberrypi:/home/pi# java --version
openjdk 11.0.11 2021-04-20
OpenJDK Runtime Environment (build 11.0.11+9-post-Raspbian-1deb10u1)
OpenJDK Server VM (build 11.0.11+9-post-Raspbian-1deb10u1, mixed mode)

Not sure if the issue is with Java version or elasticsearch version . Also on hitting curl localhost:9200 I get connection refused error. And on executing below ./bin/elasticsearch --version I receive the error

root@raspberrypi:/usr/share/elasticsearch# ./bin/elasticsearch --version
Option requires an argument: '--version'.
Unrecognized VM option 'UseParNewGC'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Note : I am using Java 11 , is that a issue ?


问:
Firebase RealTime Database: When I remove a value from a database, why it creates a download steam from the Realtime Database?
I am trying to remove a value in the RTDB as below:

```<code>FirebaseDatabase
            .getInstance()
            .getReference()
            .child(userId)
            .child(key)
            .child("2")
            .setValue(null);
</code>```

I understand the upload is 0B as I am setting a "null" value. But why there is a 47B download Bytes which is referring to the length of my path?

Since download bandwidth will be charged by Firebase, I would like to understand more.

Body:
I am trying to remove a value in the RTDB as below:

FirebaseDatabase
            .getInstance()
            .getReference()
            .child(userId)
            .child(key)
            .child("2")
            .setValue(null);

I understand the upload is 0B as I am setting a "null" value. But why there is a 47B download Bytes which is referring to the length of my path?

Since download bandwidth will be charged by Firebase, I would like to understand more.


问:
org.openqa.selenium.WebDriverException: java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:23027
I am using selenium api version 3.141.59 to screen scrap an Internet bank webpage from my Spring Boot application. I am using chrome-driver version: 108.0.5359.71. While waiting for the visibility of an element by Xpath, I am getting the below error. Any help on this issue will be highly appreciated.

error in console:

```<code>org.openqa.selenium.WebDriverException: java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:23027
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'xxx-xxxxxx', ip: 'xxx.xxx.xxx.xxx', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '11.0.9'
Driver info: driver.version: RemoteWebDriver
</code>```

code to get visibility of an element:

```<code>wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class=\"mob-control\"]"))).getText().split(" ")[2]
</code>```

build.gradle extract for selenium version:

```<code>compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.+'
</code>```

My Spring Boot application is waiting for the visibility of an element in web page. If it finds the element, then it should go through the next set of actions in the code otherwise it is expected to throw timeout exception or ElementNotFoundException. However, in actual I am getting the exception as mentioned above.

Body:
I am using selenium api version 3.141.59 to screen scrap an Internet bank webpage from my Spring Boot application. I am using chrome-driver version: 108.0.5359.71. While waiting for the visibility of an element by Xpath, I am getting the below error. Any help on this issue will be highly appreciated.

error in console:

org.openqa.selenium.WebDriverException: java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:23027
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'xxx-xxxxxx', ip: 'xxx.xxx.xxx.xxx', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '11.0.9'
Driver info: driver.version: RemoteWebDriver

code to get visibility of an element:

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class=\"mob-control\"]"))).getText().split(" ")[2]

build.gradle extract for selenium version:

compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.+'

My Spring Boot application is waiting for the visibility of an element in web page. If it finds the element, then it should go through the next set of actions in the code otherwise it is expected to throw timeout exception or ElementNotFoundException. However, in actual I am getting the exception as mentioned above.


问:
Folders in azure storage account are not deleted even after all blobs of the folders are deleted
I have a blob container in Azure called UploadedFiles.
It has folders and the folder has some blobs.
Even after all the blobs are deleted,the folder is still visible.
How that folder will disappear?

```<code>CloudBlobDirectory directory = GetContainerHandle(eContainer).GetDirectoryReference(strVirtualDirectory);

foreach (CloudBlockBlob blockBlob in directory.ListBlobs()) {
    blockBlob.Delete();
}
</code>```

Body:
I have a blob container in Azure called UploadedFiles.
It has folders and the folder has some blobs.
Even after all the blobs are deleted,the folder is still visible.
How that folder will disappear?

CloudBlobDirectory directory = GetContainerHandle(eContainer).GetDirectoryReference(strVirtualDirectory);

foreach (CloudBlockBlob blockBlob in directory.ListBlobs()) {
    blockBlob.Delete();
}


问:
How can I download a file which return via an API - facing Deserialising error byte[] to string
I want to generate a pdf and download using a POST API.
I am working on .net blazor webAssembly.

My endpoint return a pdf file.

```<code>     public async Task<IResult> HandleAsync(ServicePlanModel model)
        {
            model = await servicePlanService!.SaveNewServicePlanAsync(model);
            var pdf = templateGenerator!.FileGenartor(model);
            return Results.File(pdf, "application/pdf", $"agreement.pdf");
        }
</code>```

in the blazor component

I tried like this

```<code><MudButton Variant="Variant.Filled" Disabled="planOfService.ServicePlanBudgetTypeModel.SupportItems == null" Class="rounded-pill"  OnClick="@(async () => await generateServiceAgreement())">Generate New Agreement</MudButton>

</code>```
```<code> private async Task generateServiceAgreement() {
 await httpService.HttpPost<string>("service-plan", this.ServicePlanModel);
}
</code>```

But I got below error

```<code>Unhandled exception rendering component: '%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
System.Text.Json.JsonException: '%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
---> System.Text.Json.JsonReaderException: '%' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
  at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
</code>```

Body:
I want to generate a pdf and download using a POST API.
I am working on .net blazor webAssembly.

My endpoint return a pdf file.

     public async Task<IResult> HandleAsync(ServicePlanModel model)
        {
            model = await servicePlanService!.SaveNewServicePlanAsync(model);
            var pdf = templateGenerator!.FileGenartor(model);
            return Results.File(pdf, "application/pdf", $"agreement.pdf");
        }

in the blazor component

I tried like this

<MudButton Variant="Variant.Filled" Disabled="planOfService.ServicePlanBudgetTypeModel.SupportItems == null" Class="rounded-pill"  OnClick="@(async () => await generateServiceAgreement())">Generate New Agreement</MudButton>

 private async Task generateServiceAgreement() {
 await httpService.HttpPost<string>("service-plan", this.ServicePlanModel);
}

But I got below error

Unhandled exception rendering component: '%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
System.Text.Json.JsonException: '%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
---> System.Text.Json.JsonReaderException: '%' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
  at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)


问:
System.Runtime.InteropServices.COMException (0x80010108)
I try to find out our machine is connected with private or public network.
So, I have used the below code in C# to identify the connected networks name.

```<code>IEnumerable<INetwork> = NetworkListManager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast<INetwork>();
</code>```

But while executing this code I am getting below exception

System.Runtime.InteropServices.COMException (0x80010108): The object invoked has disconnected from its clients

Why am I getting this exception and how do I resolve this?

Body:
I try to find out our machine is connected with private or public network.
So, I have used the below code in C# to identify the connected networks name.

IEnumerable<INetwork> = NetworkListManager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast<INetwork>();

But while executing this code I am getting below exception

System.Runtime.InteropServices.COMException (0x80010108): The object invoked has disconnected from its clients

Why am I getting this exception and how do I resolve this?


问:
numpy where on a 2d or 3d dimension with multiple values
I'm trying to find if a3 contains output_color, and if so get index of where it is.

```<code>a3 = np.array([[1, 2, 1, 2, 3, 4, 5, 6, 7, 8,
                   9, 9, 9, 9, 9, 9, 9, 9]])

output_color = [1]

img = np.where(np.all(a3 == output_color, axis=0, keepdims=True))

print (img)
</code>```

above code has no problem if its a single value

```<code>result
(array([0, 0], dtype=int64), array([0, 2], dtype=int64))
</code>```

but how do I get the index with multiple values like

```<code>a3 = np.array([[1, 2, 1, 2, 3, 4, 5, 6, 7, 8,
               9, 9, 9, 9, 9, 9, 9, 9]])

output_color = np.array([[1,2,1,2,3]])

img = np.where(np.all(a3 == output_color, axis=0, keepdims=True))
</code>```

my desired result will be

```<code>result
array([0], dtype=int64))
</code>```

Body:
I'm trying to find if a3 contains output_color, and if so get index of where it is.

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

output_color = [1]

img = np.where(np.all(a3 == output_color, axis=0, keepdims=True))

print (img)

above code has no problem if its a single value

result
(array([0, 0], dtype=int64), array([0, 2], dtype=int64))

but how do I get the index with multiple values like

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

output_color = np.array([[1,2,1,2,3]])

img = np.where(np.all(a3 == output_color, axis=0, keepdims=True))

my desired result will be

result
array([0], dtype=int64))


问:
Multithreading where the each thread determines when to begin the next thread
I have almost no knowledge of multithreading, but a problem I am working on right now perhaps is a good opportunity to get started on learning concurrency and parallelism. I am hoping to get some pedagogical advice directed towards my specific problem.

The Abstract Problem

In abstract, I would like to write a program with N tasks such that

N is predetermined.

Some partial information computed by the n-th task is enough for the (n+1)-th task to start. However, we don't know beforehand how much partial information is enough. The n-th task is responsible for determining that.

So what I am hoping for is to have N threads, and the important point is that the n-th thread figures out during runtime when the (n+1)-th thread can begin. Can this be achieved with multithreading? I am familiar with Java and C++. What tools/libraries should I look into to begin with?

The Concrete Problem

The sieve of Eratosthenes is an algorithm for finding prime numbers up to a given upper limit by successively finding composite numbers as multiples of known primes. Most composite numbers have more than one prime factor and will be found multiple times. So looking for multiples of 2 and 3 in parallel can cause data race. However, the algorithm can be modified so that each composite number is found exactly once. Suppose we want to find all primes between 2 and K.

Mark 2 as prime and mark all multiples of 2 as composite. We have marked all the numbers whose smallest prime factor is 2.

The smallest unmarked number is 3. So 3 is the next prime number after 2. Multiply 3 with all numbers less than K/3 that are left unmarked after step 1. The products are all the numbers whose smallest prime factor is 3. Mark these numbers.

The smallest unmarked number is now 5. So 5 is the next prime after 2 and 3. Multiply 5 with all the numbers less than K/5 that are left unmarked after step 2 and we find all the numbers whose smallest prime factor is 5. Mark these numbers.

Repeat until we have reached floor(sqrt(K)).

Note that, for instance, step 3 can begin while step 2 is running. Early on in step 2 we find 5 as the smallest unmarked number and hence the next prime number. Therefore, once all numbers less than K/5 have been marked during step 2, we then know step 3 can begin. Step 3 will not interfere with step 1 or 2 because each composite number is found exactly once.


问:
Unexpected version discrepancy with VSCode, pip, venv and terminal
I'm using the current version of VSCode on Ubuntu 22.04.1, Python 3.11.1 and venv. I installed many packages and never seen this problem before. In this environment:

I installed a package with pip install clipspy, which completed successfully and pip lists the package as clipspy                 1.0.0. Running a test script inside VSCode produces:

```<code>(.venv) paul@desktop:~/work/arc/code$  cd /home/paul/work/arc/code ; /usr/bin/env /home/paul/work/arc/code/.venv/bin/python /home/paul/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 36033 -- /home/paul/work/arc/code/clips-0.py
Traceback (most recent call last):
  File "/home/paul/work/arc/code/clips-0.py", line 1, in <module>
    import clips
ModuleNotFoundError: No module named 'clips'
(.venv) paul@desktop:~/work/arc/code$ python3 --version
Python 3.11.1
</code>```

Strangely, when I open a terminal and activate the same virtual environment with Python 3.10.6

```<code>(.venv) paul@desktop:~/work/arc/code$ python3 clips-0.py
Hello John Doe
(.venv) paul@desktop:~/work/arc/code$ python3 --version
Python 3.10.6
</code>```

It runs fine. It fails with Python 3.11.1, though. Can someone explain what is happening here? How can I make this module run with Python 3.11?

I created a new VSCode project and venv, repeated the installation and it works as expected now. The previous project had well over 100 modules installed. Is it likely that venv environment got corrupted somehow?

Body:
I'm using the current version of VSCode on Ubuntu 22.04.1, Python 3.11.1 and venv. I installed many packages and never seen this problem before. In this environment:

I installed a package with pip install clipspy, which completed successfully and pip lists the package as clipspy                 1.0.0. Running a test script inside VSCode produces:

(.venv) paul@desktop:~/work/arc/code$  cd /home/paul/work/arc/code ; /usr/bin/env /home/paul/work/arc/code/.venv/bin/python /home/paul/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 36033 -- /home/paul/work/arc/code/clips-0.py
Traceback (most recent call last):
  File "/home/paul/work/arc/code/clips-0.py", line 1, in <module>
    import clips
ModuleNotFoundError: No module named 'clips'
(.venv) paul@desktop:~/work/arc/code$ python3 --version
Python 3.11.1

Strangely, when I open a terminal and activate the same virtual environment with Python 3.10.6

(.venv) paul@desktop:~/work/arc/code$ python3 clips-0.py
Hello John Doe
(.venv) paul@desktop:~/work/arc/code$ python3 --version
Python 3.10.6

It runs fine. It fails with Python 3.11.1, though. Can someone explain what is happening here? How can I make this module run with Python 3.11?

I created a new VSCode project and venv, repeated the installation and it works as expected now. The previous project had well over 100 modules installed. Is it likely that venv environment got corrupted somehow?


问:
I'm unable to change the symbol in the grid and to keep on adding the changes to it
I am supposed to show the change in the symbol in the grid according to the coordinates given by coords and the particular colour name - colour_name which is a symbol passed in to set colour function. it needs to save the moves throughout instead a move on a new grid every time. Can I know what I need to do in order to get the expected output

```<code>from string import ascii_uppercase as letters
class Board():
    points = {'E': '.', 'B': '@', 'W': 'O'}

    # Constructor
    def __init__(self, size=19):
        self.size = size

        assert (self.size > 1 and self.size < 27), "Illegal board size: must be between 2 and 26."  # raising the assertation error if not within the ranges

    # Methods
    #TASK 01-----------------------
    def __str__(self):
        column_names = letters[:self.size] #The alphabetical letter column coordinates
        row_numbers = reversed(range(1, self.size + 1)) #The numerical character row coordinates
        empty_row = ' '.join([self.points.get('E')] * self.size) #the creation of a empty line
        print('   ' + ' '.join(column_names))

        for i in row_numbers:
            arr=print(str(i).rjust(2), empty_row)  #using the rjust to pad strings with space
        return (str(Board))

    def get_size(self):
        return self.size
    #upto this part completely done

    def set_colour(self, coords, colour_name):
        self.coords = coords #takes in the coordinates of the move
        self.colour_name = colour_name #takes in the colour change

        colour_change = self.colour_name  # assigning the colour changed to
        colour__change = "'" + colour_change + "'"  # to make it 'B' or 'W'

        # Assertation errors--------------------------------
        assert (self.colour_name == 'E' or self.colour_name == 'B' or colour_name == 'W'), "invalid colour name"  # assertation error regarding colour name
        assert (len(self.coords) == 2 or len(self.coords) == 3), "invalid coordinates"  # assertation error regarding coordinates

        move = self.coords #takes in the coordinates of the move

        alphabetical_coord = move[0]  # assigning the alphabetical coordinate to a seperate variable

        numerical_coord = move[1:len(move)]  # assigning the numerical coordinate to a seperate variable

        # AssertionError-----------------------------
        assert (int(ord(alphabetical_coord)) > 64 and int(ord(alphabetical_coord)) < 91), "row out of range"
        assert (int(numerical_coord) > 0 and int(numerical_coord) < 27), "column out of range"
        # ------------------------------------------------------------------------------------------------
        play = True
        while play == True: #While loop for the creation of the board by creating strings of the symbols
            self.move = list(move) #converting the coordinates into a list

            for i in self.arr:  # using the loop to create the grid with the numerical characters

                self.arr[-int(numerical_coord)][self.column_names.index(alphabetical_coord)] = self.points.get(str(colour_change))    #arr

            return str(Board)

b = Board(9)
print(b)
b = Board(5)
print(b)
print(b.get_size())
b.set_colour("B1", "W")
b.set_colour("C1", "B")
b.set_colour("D1", "B")
</code>```

I'm unable to get the function set colour to work and it doesn't give the required output

```<code>   A B C D E
 5 . . . . .
 4 . . . . .
 3 . . . . .
 2 . . . . .
 1 . O @ @ .

B
</code>```

in the initial method i did

```<code>from string import ascii_uppercase as letters
class Board():

#A dictionary created for the colours and the specific symbols
points = {'E': '.', 'B': '@', 'W': 'O'}

#Constructor--------------------------------------
   def __init__(self, size=19,from_strings=str):
    self.size = size
    # self.from_strings=from_strings

    #Assertation error
    assert (self.size > 1 and self.size < 27), "Illegal board size: must be between 2 and 26."  # raising the assertation error if not within the ranges
   def __str__(self):
    from string import ascii_uppercase as letters  # importing the alphabetical letters as uppercase
    a_letters = list(letters[:self.size])  # getting the alphabetical letters based on the number of columns
    num = iter(range(1, (self.size + 1)))  # getting the numrical characters based on the number of rows
    arr = [[self.points.get('E') for i in range(self.size)] for i in
           range(self.size)]  # creating an array of the empyty spots

    # arr = [['.' for i in range(self.size)] for i in range(self.size)]  # creating an array of the empyty spots
    print('  ' + ' '.join(a_letters))  # to adjust the space with the alphabetical letters with the rest of the grid
    for i in arr:  # using the loop to create the grid with the numerical characters
        print(-(next(num) - (self.size + 1)), end=' ')  # to make the numbers descend

        print(' '.join(i))
    return str(Board)

def get_size(self):  # returns the size of the board
    return self.size

def set_colour(self, coords, colour_name):
    self.coords = coords  # takes in the coordinates of the move
    self.colour_name = colour_name  # takes in the colour change

    colour_change = self.colour_name  # assigning the colour changed to
    colour__change = "'" + colour_change + "'"  # to make it 'B' or 'W'
    self.coords = coords #takes in the coordinates
    self.colour_name = colour_name #takes in the colour change

    # Assertation errors--------------------------------
    move = self.coords #takes in the coordinates of the move

    alphabetical_coord = move[0]  # assigning the alphabetical coordinate to a seperate variable

    numerical_coord = move[1:len(move)]  # assigning the numerical coordinate to a seperate variable

    # AssertionError-----------------------------
    assert (int(ord(alphabetical_coord)) > 64 and int(ord(alphabetical_coord)) < 91), "row out of range"
    assert (int(numerical_coord) > 0 and int(numerical_coord) < 27), "column out of range"
    # ------------------------------------------------------------------------------------------------
    colour_change = self.colour_name  # assigning the colour changed to
    colour__change = "'" + colour_change + "'" #to make it 'B' or 'W'

    # Draw the grid------------------------------------------------------------------------------------

    from string import ascii_uppercase as letters  # importing the alphabetical letters as uppercase
    a_letters = list(letters[:self.size])  # getting the alphabetical letters based on the number of columns
    num = iter(range(1, (self.size + 1)))  # getting the numerical characters based on the number of rows
    arr = [[self.points.get('E') for i in range(self.size)] for i in
          range(self.size)]  # creating an array of the empyty spots
    play = True
    while play == True: #While loop for the creation of the board by creating strings of the symbols
        move = self.coords
        move = list(move) #converting the coordinates into a list
        print('  ' + ' '.join(a_letters))  # to adjust the space with the alphabetical letters with the rest of the grid
        for i in arr:  # using the loop to create the grid with the numerical characters
            print(-(next(num) - (self.size + 1)), end=' ')  # to make the numbers descend
            print(' '.join(i))
          arr[-int(numerical_coord)][a_letters.index(alphabetical_coord)] = self.points.get(str(colour_change))

        return str(Board)
</code>```

The following output comes but it doesn't update on the same board

```<code>                  A B C D E
                5 . . . . .
                4 . . . . .
                3 . . . . .
                2 . . . . .
                1 . O . . .

                 A B C D E
               5 . . . . .
               4 . . . . .
               3 . . . . .
               2 . . . . .
               1 . . @ . .

                 A B C D E
               5 . . . . .
               4 . . . . .
               3 . . . . .
               2 . . . . .
               1 . . . @ .
</code>```

Can I know what kind of a change I need to do for the modified program to show the output as required and on the same grid instead of separate grids?

Body:
I am supposed to show the change in the symbol in the grid according to the coordinates given by coords and the particular colour name - colour_name which is a symbol passed in to set colour function. it needs to save the moves throughout instead a move on a new grid every time. Can I know what I need to do in order to get the expected output

from string import ascii_uppercase as letters
class Board():
    points = {'E': '.', 'B': '@', 'W': 'O'}

    # Constructor
    def __init__(self, size=19):
        self.size = size

        assert (self.size > 1 and self.size < 27), "Illegal board size: must be between 2 and 26."  # raising the assertation error if not within the ranges

    # Methods
    #TASK 01-----------------------
    def __str__(self):
        column_names = letters[:self.size] #The alphabetical letter column coordinates
        row_numbers = reversed(range(1, self.size + 1)) #The numerical character row coordinates
        empty_row = ' '.join([self.points.get('E')] * self.size) #the creation of a empty line
        print('   ' + ' '.join(column_names))

        for i in row_numbers:
            arr=print(str(i).rjust(2), empty_row)  #using the rjust to pad strings with space
        return (str(Board))

    def get_size(self):
        return self.size
    #upto this part completely done

    def set_colour(self, coords, colour_name):
        self.coords = coords #takes in the coordinates of the move
        self.colour_name = colour_name #takes in the colour change

        colour_change = self.colour_name  # assigning the colour changed to
        colour__change = "'" + colour_change + "'"  # to make it 'B' or 'W'

        # Assertation errors--------------------------------
        assert (self.colour_name == 'E' or self.colour_name == 'B' or colour_name == 'W'), "invalid colour name"  # assertation error regarding colour name
        assert (len(self.coords) == 2 or len(self.coords) == 3), "invalid coordinates"  # assertation error regarding coordinates

        move = self.coords #takes in the coordinates of the move

        alphabetical_coord = move[0]  # assigning the alphabetical coordinate to a seperate variable

        numerical_coord = move[1:len(move)]  # assigning the numerical coordinate to a seperate variable

        # AssertionError-----------------------------
        assert (int(ord(alphabetical_coord)) > 64 and int(ord(alphabetical_coord)) < 91), "row out of range"
        assert (int(numerical_coord) > 0 and int(numerical_coord) < 27), "column out of range"
        # ------------------------------------------------------------------------------------------------
        play = True
        while play == True: #While loop for the creation of the board by creating strings of the symbols
            self.move = list(move) #converting the coordinates into a list

            for i in self.arr:  # using the loop to create the grid with the numerical characters

                self.arr[-int(numerical_coord)][self.column_names.index(alphabetical_coord)] = self.points.get(str(colour_change))    #arr

            return str(Board)

b = Board(9)
print(b)
b = Board(5)
print(b)
print(b.get_size())
b.set_colour("B1", "W")
b.set_colour("C1", "B")
b.set_colour("D1", "B")

I'm unable to get the function set colour to work and it doesn't give the required output

   A B C D E
 5 . . . . .
 4 . . . . .
 3 . . . . .
 2 . . . . .
 1 . O @ @ .

B

in the initial method i did

from string import ascii_uppercase as letters
class Board():

#A dictionary created for the colours and the specific symbols
points = {'E': '.', 'B': '@', 'W': 'O'}

#Constructor--------------------------------------
   def __init__(self, size=19,from_strings=str):
    self.size = size
    # self.from_strings=from_strings

    #Assertation error
    assert (self.size > 1 and self.size < 27), "Illegal board size: must be between 2 and 26."  # raising the assertation error if not within the ranges
   def __str__(self):
    from string import ascii_uppercase as letters  # importing the alphabetical letters as uppercase
    a_letters = list(letters[:self.size])  # getting the alphabetical letters based on the number of columns
    num = iter(range(1, (self.size + 1)))  # getting the numrical characters based on the number of rows
    arr = [[self.points.get('E') for i in range(self.size)] for i in
           range(self.size)]  # creating an array of the empyty spots

    # arr = [['.' for i in range(self.size)] for i in range(self.size)]  # creating an array of the empyty spots
    print('  ' + ' '.join(a_letters))  # to adjust the space with the alphabetical letters with the rest of the grid
    for i in arr:  # using the loop to create the grid with the numerical characters
        print(-(next(num) - (self.size + 1)), end=' ')  # to make the numbers descend

        print(' '.join(i))
    return str(Board)

def get_size(self):  # returns the size of the board
    return self.size

def set_colour(self, coords, colour_name):
    self.coords = coords  # takes in the coordinates of the move
    self.colour_name = colour_name  # takes in the colour change

    colour_change = self.colour_name  # assigning the colour changed to
    colour__change = "'" + colour_change + "'"  # to make it 'B' or 'W'
    self.coords = coords #takes in the coordinates
    self.colour_name = colour_name #takes in the colour change

    # Assertation errors--------------------------------
    move = self.coords #takes in the coordinates of the move

    alphabetical_coord = move[0]  # assigning the alphabetical coordinate to a seperate variable

    numerical_coord = move[1:len(move)]  # assigning the numerical coordinate to a seperate variable

    # AssertionError-----------------------------
    assert (int(ord(alphabetical_coord)) > 64 and int(ord(alphabetical_coord)) < 91), "row out of range"
    assert (int(numerical_coord) > 0 and int(numerical_coord) < 27), "column out of range"
    # ------------------------------------------------------------------------------------------------
    colour_change = self.colour_name  # assigning the colour changed to
    colour__change = "'" + colour_change + "'" #to make it 'B' or 'W'

    # Draw the grid------------------------------------------------------------------------------------

    from string import ascii_uppercase as letters  # importing the alphabetical letters as uppercase
    a_letters = list(letters[:self.size])  # getting the alphabetical letters based on the number of columns
    num = iter(range(1, (self.size + 1)))  # getting the numerical characters based on the number of rows
    arr = [[self.points.get('E') for i in range(self.size)] for i in
          range(self.size)]  # creating an array of the empyty spots
    play = True
    while play == True: #While loop for the creation of the board by creating strings of the symbols
        move = self.coords
        move = list(move) #converting the coordinates into a list
        print('  ' + ' '.join(a_letters))  # to adjust the space with the alphabetical letters with the rest of the grid
        for i in arr:  # using the loop to create the grid with the numerical characters
            print(-(next(num) - (self.size + 1)), end=' ')  # to make the numbers descend
            print(' '.join(i))
          arr[-int(numerical_coord)][a_letters.index(alphabetical_coord)] = self.points.get(str(colour_change))

        return str(Board)

The following output comes but it doesn't update on the same board

                  A B C D E
                5 . . . . .
                4 . . . . .
                3 . . . . .
                2 . . . . .
                1 . O . . .

                 A B C D E
               5 . . . . .
               4 . . . . .
               3 . . . . .
               2 . . . . .
               1 . . @ . .

                 A B C D E
               5 . . . . .
               4 . . . . .
               3 . . . . .
               2 . . . . .
               1 . . . @ .

Can I know what kind of a change I need to do for the modified program to show the output as required and on the same grid instead of separate grids?


问:
The React website is not loading the content entered on ReactDOM.render()
I am beginner to react, and tried to create a simple react page that displayed Hello World. The "Hello World" is not loading.

index.html :

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React Practice</title>
</head>

<body>
    <div class="root">
        <script src="../src/index.js" type="text/JSX"></script>
    </div>
</body>
</html>
</code>```

index.js :

```<code>import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
<h1>Hello World</h1>,
document.getElementById('root')
);

</code>```

I expected "Hello World" but it is not showing that.

Body:
I am beginner to react, and tried to create a simple react page that displayed Hello World. The "Hello World" is not loading.

index.html :

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React Practice</title>

index.js :

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(

Hello World
,
document.getElementById('root')
);

I expected "Hello World" but it is not showing that.