问:
label text is not updated but only last line updated the label in pyqt5
I am making a project on pyqt5. now, its work is to click on one button "Click and Say" which call speech function in which label is updating and we say and it recognize it.
the code is here.

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
import urllib
import speech_recognition as sr
import time

def connected(host='http://google.com'):
    try:
        urllib.request.urlopen(host)
        return True
    except:
        return False

class Ui_Function(object):
    def setupUi(self, Function):
        Function.setObjectName("Function")
        Function.resize(737, 600)
        self.centralwidget = QtWidgets.QWidget(Function)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(50, 70, 601, 31))
        self.lineEdit.setObjectName("lineEdit")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(50, 30, 151, 17))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(320, 120, 67, 17))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(60, 150, 251, 21))
        self.label_3.setObjectName("label_3")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(60, 180, 101, 25))
        self.pushButton.setObjectName("pushButton")

        self.pushButton.clicked.connect(self.speech)

        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(60, 320, 601, 231))
        self.textEdit.setObjectName("textEdit")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(60, 290, 141, 21))
        self.label_4.setObjectName("label_4")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(570, 110, 89, 25))
        self.pushButton_2.setObjectName("pushButton_2")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(60, 220, 241, 21))
        self.label_5.setObjectName("label_5")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(400, 180, 251, 31))
        self.comboBox.setObjectName("comboBox")
        Function.setCentralWidget(self.centralwidget)

        self.retranslateUi(Function)
        QtCore.QMetaObject.connectSlotsByName(Function)

    def retranslateUi(self, Function):
        _translate = QtCore.QCoreApplication.translate
        Function.setWindowTitle(_translate("Function", "MainWindow"))
        self.label.setText(_translate("Function", "Enter the Book Name:"))
        self.label_2.setText(_translate("Function", "OR"))
        self.label_3.setText(_translate("Function", "Write the Book Name by your Voice:"))
        self.pushButton.setText(_translate("Function", "Click and Say"))
        self.label_4.setText(_translate("Function", "Recommendations:"))
        self.pushButton_2.setText(_translate("Function", "Clear"))
        self.label_5.setText(_translate("Function", "TextLabel"))

    def speech(self):
        if connected():
            r = sr.Recognizer()
            with sr.Microphone() as source:
                r.adjust_for_ambient_noise(source)
                self.label_5.setText("Listening...")
                self.label_5.adjustSize()
                time.sleep(1)
    # read the audio data from the default microphone
                audio_data = r.listen(source,timeout=5)
                self.label_5.setText("Time over")
                time.sleep(1)
                self.label_5.setText("Recognizing...")
                time.sleep(1)
    # convert speech to text
                text = r.recognize_google(audio_data ,language='en-UK', show_all=True)
                try:
                    self.label_5.setText("You said:" )
                    list1=[]
                    self.comboBox.clear()
                    if (len(text)>0):
                        print(len(text["alternative"]))
                        for x in range(0,len(text["alternative"])):
                            list1.append(text["alternative"][x]["transcript"])
                        self.comboBox.addItems(list1)

                    else:
                        time.sleep(1)
                        self.label_5.setText("\tNothing")
                except LookupError:
                    time.sleep(1)
                    self.label_5.setText("Could not Understand Value")

                except sr.UnknownValueError:
                    time.sleep(1)
                    self.label_5.setText("Voice Recognition could not understand audio")

                except sr.RequestError as e:
                    time.sleep(1)
                    self.label_5.setText("Voice Recognition could not request results ; {0}".format(e))
        else:
            time.sleep(1)
            self.label_5.setText("NO Internet Connection. \nCheck your Internet Connection")
        time.sleep(1)
        self.label_5.setText("Completed")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Function = QtWidgets.QMainWindow()
    ui = Ui_Function()
    ui.setupUi(Function)
    Function.show()
    sys.exit(app.exec_())
</code>```

This code listens and recognize the word. but the only problem is that all labels are not updating in speech function. Only the last one which contains "completed" is updated.
The flow of program is click on button and then it calls speech function which is listening, recognizing with updation of labels.
I have even add time.sleep(1) before every updation. Any help will be appreciated. I am new to PYqt5.

答:
Tasks that consume a lot of time should not be executed in the GUI thread, instead you must execute it in another thread and send the information through signals.

from PyQt5 import QtCore, QtGui, QtWidgets
import urllib
import speech_recognition as sr
import threading
import time

def connected(host="http://google.com"):
    try:
        urllib.request.urlopen(host)
        return True
    except:
        return False

class Ui_Function(object):
    def setupUi(self, Function):
        Function.setObjectName("Function")
        Function.resize(737, 600)
        self.centralwidget = QtWidgets.QWidget(Function)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(50, 70, 601, 31))
        self.lineEdit.setObjectName("lineEdit")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(50, 30, 151, 17))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(320, 120, 67, 17))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(60, 150, 251, 21))
        self.label_3.setObjectName("label_3")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(60, 180, 101, 25))
        self.pushButton.setObjectName("pushButton")

        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(60, 320, 601, 231))
        self.textEdit.setObjectName("textEdit")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(60, 290, 141, 21))
        self.label_4.setObjectName("label_4")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(570, 110, 89, 25))
        self.pushButton_2.setObjectName("pushButton_2")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(60, 220, 241, 21))
        self.label_5.setObjectName("label_5")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(400, 180, 251, 31))
        self.comboBox.setObjectName("comboBox")
        Function.setCentralWidget(self.centralwidget)

        self.retranslateUi(Function)
        QtCore.QMetaObject.connectSlotsByName(Function)

    def retranslateUi(self, Function):
        _translate = QtCore.QCoreApplication.translate
        Function.setWindowTitle(_translate("Function", "MainWindow"))
        self.label.setText(_translate("Function", "Enter the Book Name:"))
        self.label_2.setText(_translate("Function", "OR"))
        self.label_3.setText(
            _translate("Function", "Write the Book Name by your Voice:")
        )
        self.pushButton.setText(_translate("Function", "Click and Say"))
        self.label_4.setText(_translate("Function", "Recommendations:"))
        self.pushButton_2.setText(_translate("Function", "Clear"))
        self.label_5.setText(_translate("Function", "TextLabel"))

class SpeechWorker(QtCore.QObject):
    messageChanged = QtCore.pyqtSignal(str)
    itemsChanged = QtCore.pyqtSignal(list)

    def speech(self):
        threading.Thread(target=self._speech, daemon=True).start()

    def _speech(self):
        if connected():
            r = sr.Recognizer()
            with sr.Microphone() as source:
                r.adjust_for_ambient_noise(source)
                self.messageChanged.emit("Listening...")
                time.sleep(1)
                # read the audio data from the default microphone
                audio_data = r.listen(source, timeout=5)
                self.messageChanged.emit("Time over")
                time.sleep(1)
                self.messageChanged.emit("Recognizing...")
                time.sleep(1)
                # convert speech to text
                text = r.recognize_google(audio_data, language="en-UK", show_all=True)
                try:
                    self.messageChanged.emit("You said:")
                    self.itemsChanged.emit([])
                    list1 = []
                    if len(text) > 0:
                        print(len(text["alternative"]))
                        for x in range(0, len(text["alternative"])):
                            list1.append(text["alternative"][x]["transcript"])
                        self.itemsChanged.emit(list1)
                    else:
                        time.sleep(1)
                        self.messageChanged.emit("\tNothing")

                except LookupError:
                    time.sleep(1)
                    self.messageChanged.emit("Could not Understand Value")

                except sr.UnknownValueError:
                    time.sleep(1)
                    self.messageChanged.emit(
                        "Voice Recognition could not understand audio"
                    )

                except sr.RequestError as e:
                    time.sleep(1)
                    self.messageChanged.emit(
                        "Voice Recognition could not request results ; {0}".format(e)
                    )
        else:
            time.sleep(1)
            self.messageChanged.emit(
                "NO Internet Connection. \nCheck your Internet Connection"
            )
        time.sleep(1)
        self.messageChanged.emit("Completed")

class Function(QtWidgets.QMainWindow, Ui_Function):
    def __init__(self, parent=None):
        super(Function, self).__init__(parent)
        self.setupUi(self)

        self.worker = SpeechWorker()
        self.worker.messageChanged.connect(self.updateMessage)
        self.worker.itemsChanged.connect(self.updateItems)

        self.pushButton.clicked.connect(self.worker.speech)

    @QtCore.pyqtSlot(str)
    def updateMessage(self, message):
        self.label_5.setText(message)
        self.label_5.adjustSize()

    @QtCore.pyqtSlot(list)
    def updateItems(self, items):
        self.comboBox.clear()
        self.comboBox.addItems(items)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Function()
    w.show()
    sys.exit(app.exec_())
```

Body:
I am making a project on pyqt5. now, its work is to click on one button "Click and Say" which call speech function in which label is updating and we say and it recognize it.
the code is here.

from PyQt5 import QtCore, QtGui, QtWidgets
import urllib
import speech_recognition as sr
import time

def connected(host='http://google.com'):
    try:
        urllib.request.urlopen(host)
        return True
    except:
        return False

class Ui_Function(object):
    def setupUi(self, Function):
        Function.setObjectName("Function")
        Function.resize(737, 600)
        self.centralwidget = QtWidgets.QWidget(Function)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(50, 70, 601, 31))
        self.lineEdit.setObjectName("lineEdit")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(50, 30, 151, 17))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(320, 120, 67, 17))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(60, 150, 251, 21))
        self.label_3.setObjectName("label_3")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(60, 180, 101, 25))
        self.pushButton.setObjectName("pushButton")

        self.pushButton.clicked.connect(self.speech)

        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(60, 320, 601, 231))
        self.textEdit.setObjectName("textEdit")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(60, 290, 141, 21))
        self.label_4.setObjectName("label_4")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(570, 110, 89, 25))
        self.pushButton_2.setObjectName("pushButton_2")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(60, 220, 241, 21))
        self.label_5.setObjectName("label_5")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(400, 180, 251, 31))
        self.comboBox.setObjectName("comboBox")
        Function.setCentralWidget(self.centralwidget)

        self.retranslateUi(Function)
        QtCore.QMetaObject.connectSlotsByName(Function)

    def retranslateUi(self, Function):
        _translate = QtCore.QCoreApplication.translate
        Function.setWindowTitle(_translate("Function", "MainWindow"))
        self.label.setText(_translate("Function", "Enter the Book Name:"))
        self.label_2.setText(_translate("Function", "OR"))
        self.label_3.setText(_translate("Function", "Write the Book Name by your Voice:"))
        self.pushButton.setText(_translate("Function", "Click and Say"))
        self.label_4.setText(_translate("Function", "Recommendations:"))
        self.pushButton_2.setText(_translate("Function", "Clear"))
        self.label_5.setText(_translate("Function", "TextLabel"))

    def speech(self):
        if connected():
            r = sr.Recognizer()
            with sr.Microphone() as source:
                r.adjust_for_ambient_noise(source)
                self.label_5.setText("Listening...")
                self.label_5.adjustSize()
                time.sleep(1)
    # read the audio data from the default microphone
                audio_data = r.listen(source,timeout=5)
                self.label_5.setText("Time over")
                time.sleep(1)
                self.label_5.setText("Recognizing...")
                time.sleep(1)
    # convert speech to text
                text = r.recognize_google(audio_data ,language='en-UK', show_all=True)
                try:
                    self.label_5.setText("You said:" )
                    list1=[]
                    self.comboBox.clear()
                    if (len(text)>0):
                        print(len(text["alternative"]))
                        for x in range(0,len(text["alternative"])):
                            list1.append(text["alternative"][x]["transcript"])
                        self.comboBox.addItems(list1)

                    else:
                        time.sleep(1)
                        self.label_5.setText("\tNothing")
                except LookupError:
                    time.sleep(1)
                    self.label_5.setText("Could not Understand Value")

                except sr.UnknownValueError:
                    time.sleep(1)
                    self.label_5.setText("Voice Recognition could not understand audio")

                except sr.RequestError as e:
                    time.sleep(1)
                    self.label_5.setText("Voice Recognition could not request results ; {0}".format(e))
        else:
            time.sleep(1)
            self.label_5.setText("NO Internet Connection. \nCheck your Internet Connection")
        time.sleep(1)
        self.label_5.setText("Completed")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Function = QtWidgets.QMainWindow()
    ui = Ui_Function()
    ui.setupUi(Function)
    Function.show()
    sys.exit(app.exec_())

This code listens and recognize the word. but the only problem is that all labels are not updating in speech function. Only the last one which contains "completed" is updated.
The flow of program is click on button and then it calls speech function which is listening, recognizing with updation of labels.
I have even add time.sleep(1) before every updation. Any help will be appreciated. I am new to PYqt5.


来源: stackexchange

问:
Woocommerce Product Page: how to change position of 'short description', 'price' and 'variation description'
In a Woocommerce Product Page: how to change position of 'short description', 'price' and 'variation description'?

I need to put the 'Product short description' above the 'Price' and the 'Variation Description' just below the Price.

This is what I have right now:

And this is what I need:

答:
If you look at https://github.com/woocommerce/woocommerce/blob/3.8.0/templates/content-single-product.php#L47 you'll see that the product summary is constructed using hooks with different priorities.

&

https://github.com/woocommerce/woocommerce/blob/3.8.0/templates/single-product/add-to-cart/variable.php#L65

so you can just swap the values

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );

add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 10 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 20 );

function move() {
    remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation', 10 );
    add_action( 'woocommerce_before_variations_form', 'woocommerce_single_variation', 10 );
}
add_action( 'woocommerce_before_add_to_cart_form', 'move' );
```

ContentLicense: CC BY-SA 4.0


问:
how to add check symbol in excel cell SXSSFSheet java
I need to put a check symbol in this cell if the condition met. Here's my sample code:

```<code>private SXSSFWorkbook RepWkBook = null;
private SXSSFSheet RepSheet = null;
private int RepRowNum = 0;
private ResultSet RepResult = null;
private Row RepRow = null;

    RepSheet = RepWkBook.createSheet(reportType);
    RepRowNum = 0;
    Row row = RepSheet.createRow(RepRowNum++);
    CellStyle cellStyle = RepWkBook.createCellStyle();
    Font font = RepWkBook.createFont();
    font.setBold(true);
    cellStyle.setFont(font);cell = RepRow.createCell(col++);

        boolean isMOBhigherThanArea = RepResult.getString("IS_MOB_HIGHER_THAN_AREA").equalsIgnoreCase("1");

        char st = '\u2713';

        if(isMOBhigherThanArea && (!areaStr.equalsIgnoreCase("No Data") || !mobStr.equalsIgnoreCase("No Data"))) {
            cell.setCellValue(st);}
</code>```

I already used

UTF-16 - feff2713

UTF-16BE - 2713

UTF-16LE - 1327

UTF-8 - e29c93

click here for sample output
SAMPLE EXPECTED OUTPUT

Area | MOB Target | Area Result | MOB > Area

City |     85%    |       80%   |     ✔

答:
The only way that I can think of doing that is formatting your cell with a symbolic font, as Windings, and use the proper character for the check symbol in this font.
So your code would be something like:</p>

```<code>Font font = RepWkBook.createFont();
font.setBold(true);

Font wingDingFont = RepWkBook.createFont();
wingDingFont.setBold(true);
wingDingFont.setFontName("Wingdings);

cell = RepRow.createCell(col++);

boolean isMOBhigherThanArea = RepResult.getString("IS_MOB_HIGHER_THAN_AREA").equalsIgnoreCase("1");

if(isMOBhigherThanArea && (!areaStr.equalsIgnoreCase("No Data") || !mobStr.equalsIgnoreCase("No Data"))) {
    String st = "ü";
    cellStyle.setFont(wingDingFont);
    cell.setCellValue(st);
} else {
    cellStyle.setFont(font);
}
</code>```

Body:
I need to put a check symbol in this cell if the condition met. Here's my sample code:

private SXSSFWorkbook RepWkBook = null;
private SXSSFSheet RepSheet = null;
private int RepRowNum = 0;
private ResultSet RepResult = null;
private Row RepRow = null;

    RepSheet = RepWkBook.createSheet(reportType);
    RepRowNum = 0;
    Row row = RepSheet.createRow(RepRowNum++);
    CellStyle cellStyle = RepWkBook.createCellStyle();
    Font font = RepWkBook.createFont();
    font.setBold(true);
    cellStyle.setFont(font);cell = RepRow.createCell(col++);

        boolean isMOBhigherThanArea = RepResult.getString("IS_MOB_HIGHER_THAN_AREA").equalsIgnoreCase("1");

        char st = '\u2713';

        if(isMOBhigherThanArea && (!areaStr.equalsIgnoreCase("No Data") || !mobStr.equalsIgnoreCase("No Data"))) {
            cell.setCellValue(st);}

I already used

UTF-16 - feff2713

UTF-16BE - 2713

UTF-16LE - 1327

UTF-8 - e29c93

click here for sample output
SAMPLE EXPECTED OUTPUT

Area | MOB Target | Area Result | MOB > Area

City |     85%    |       80%   |     ✔

Body:
The only way that I can think of doing that is formatting your cell with a symbolic font, as Windings, and use the proper character for the check symbol in this font.
So your code would be something like:

Font font = RepWkBook.createFont();
font.setBold(true);

Font wingDingFont = RepWkBook.createFont();
wingDingFont.setBold(true);
wingDingFont.setFontName("Wingdings);

cell = RepRow.createCell(col++);

boolean isMOBhigherThanArea = RepResult.getString("IS_MOB_HIGHER_THAN_AREA").equalsIgnoreCase("1");

if(isMOBhigherThanArea && (!areaStr.equalsIgnoreCase("No Data") || !mobStr.equalsIgnoreCase("No Data"))) {
    String st = "ü";
    cellStyle.setFont(wingDingFont);
    cell.setCellValue(st);
} else {
    cellStyle.setFont(font);
}


问:
REST API: JSON objects in URL to get custom JSON
I am using the cs-cart rest API to create an android app. My problem is that i want categories as needed for example the parent category has an id "0", so i want just that category, can i edit URL to get only the categories whose parent_id: "0"

http://www.example.com/api/categories

I also tried URL encoding with different online tools, neither worked.

it's the JSON i am getting right now, i need the specific parent_id.

```<code>{
    "categories": [
        {
            "category_id": "735",
            "parent_id": "755",
            "id_path": "60/755/735",
            "category": "Clocks",
            "position": "0",
            "status": "A",
            "product_count": "1",
            "seo_name": "watches",
            "seo_path": "60/755"
        },
        {
            "category_id": "682",
            "parent_id": "295",
            "id_path": "217/295/682",
            "category": "360° Video Camera",
            "position": "0",
            "status": "A",
            "product_count": "514",
            "seo_name": "360-video-camera",
            "seo_path": "217/295"
        },
        {
            "category_id": "413",
            "parent_id": "0",
            "id_path": "413",
            "category": " Apparel",
            "position": "0",
            "status": "A",
            "product_count": "2",
            "seo_name": "apparel",
            "seo_path": ""
        },
        {
            "category_id": "359",
            "parent_id": "217",
            "id_path": "217/359",
            "category": "Computers ",
            "position": "0",
            "status": "A",
            "product_count": "25",
            "seo_name": "computer-cables",
            "seo_path": "217"
        },
        {
            "category_id": "357",
            "parent_id": "344",
            "id_path": "217/344/357",
            "category": "Chargers",
            "position": "0",
            "status": "A",
            "product_count": "1154",
            "seo_name": "network-media-converters",
            "seo_path": "217/344"
        },
        {
            "category_id": "355",
            "parent_id": "344",
            "id_path": "217/344/355",
            "category": "Cellphones",
            "position": "0",
            "status": "A",
            "product_count": "1469",
            "seo_name": "gateways-controllers",
            "seo_path": "217/344"
        },
        {
            "category_id": "345",
            "parent_id": "344",
            "id_path": "217/344/345",
            "category": "Bluetooth Accessories",
            "position": "0",
            "status": "A",
            "product_count": "1052",
            "seo_name": "network-antennas",
            "seo_path": "217/344"
        },
        {
            "category_id": "298",
            "parent_id": "295",
            "id_path": "217/295/298",
            "category": "Camera Accessories",
            "position": "0",
            "status": "A",
            "product_count": "507",
            "seo_name": "camera-accessories",
            "seo_path": "217/295"
        },
        {
            "category_id": "296",
            "parent_id": "295",
            "id_path": "217/295/296",
            "category": "Camcorders",
            "position": "0",
            "status": "A",
            "product_count": "504",
            "seo_name": "camcorders",
            "seo_path": "217/295"
        },
        {
            "category_id": "295",
            "parent_id": "217",
            "id_path": "217/295",
            "category": "Cameras & Camcorders",
            "position": "0",
            "status": "A",
            "product_count": "0",
            "seo_name": "cameras-and-camcorders",
            "seo_path": "217"
        },
        {
            "category_id": "271",
            "parent_id": "218",
            "id_path": "217/218/271",
            "category": "Audio Amplifiers",
            "position": "0",
            "status": "A",
            "product_count": "1003",
            "seo_name": "audio-amplifiers",
            "seo_path": "217/218"
        },
        {
            "category_id": "238",
            "parent_id": "218",
            "id_path": "217/218/238",
            "category": "Bluetooth Music Receivers",
            "position": "0",
            "status": "A",
            "product_count": "519",
            "seo_name": "bluetooth-music-receivers",
            "seo_path": "217/218"
        },
        {
            "category_id": "218",
            "parent_id": "217",
            "id_path": "217/218",
            "category": "Audio & Home Theatre",
            "position": "0",
            "status": "A",
            "product_count": "1",
            "seo_name": "audio-and-home-theatre",
            "seo_path": "217"
        },
        {
            "category_id": "188",
            "parent_id": "779",
            "id_path": "776/779/188",
            "category": "Baby Furniture",
            "position": "0",
            "status": "A",
            "product_count": "430",
            "seo_name": "baby-furniture",
            "seo_path": "776/779"
        },
        {
            "category_id": "185",
            "parent_id": "779",
            "id_path": "776/779/185",
            "category": "Baby Travel",
            "position": "0",
            "status": "A",
            "product_count": "494",
            "seo_name": "baby-travel",
            "seo_path": "776/779"
        },
        {
            "category_id": "169",
            "parent_id": "779",
            "id_path": "776/779/169",
            "category": "Baby Bathing & Potting",
            "position": "0",
            "status": "A",
            "product_count": "405",
            "seo_name": "baby-bathing-and-potting",
            "seo_path": "776/779"
        },
        {
            "category_id": "109",
            "parent_id": "108",
            "id_path": "101/108/109",
            "category": "BD/DVD Movies",
            "position": "0",
            "status": "A",
            "product_count": "0",
            "seo_name": "bd-dvd-movies",
            "seo_path": "101/108"
        },
        {
            "category_id": "90",
            "parent_id": "85",
            "id_path": "60/85/90",
            "category": "Cups & Mugs",
            "position": "0",
            "status": "A",
            "product_count": "504",
            "seo_name": "cups-and-mugs",
            "seo_path": "60/85"
        },
        {
            "category_id": "83",
            "parent_id": "69",
            "id_path": "60/69/83",
            "category": "Ceiling Lights",
            "position": "0",
            "status": "A",
            "product_count": "592",
            "seo_name": "ceiling-lighting",
            "seo_path": "60/69"
        },
        {
            "category_id": "70",
            "parent_id": "69",
            "id_path": "60/69/70",
            "category": " Bulbs & Tubes ",
            "position": "0",
            "status": "A",
            "product_count": "504",
            "seo_name": "bulbs",
            "seo_path": "60/69"
        }
    ],
    "params": {
        "category_id": 0,
        "visible": false,
        "current_category_id": 0,
        "simple": false,
        "plain": true,
        "limit": 0,
        "item_ids": "",
        "group_by_level": false,
        "get_images": false,
        "category_delimiter": "/",
        "get_frontend_urls": false,
        "max_nesting_level": null,
        "get_company_name": false,
        "items_per_page": 20,
        "page": 1,
        "except_id": 414,
        "sort_order": "asc",
        "sort_by": "position",
        "sort_order_rev": "desc",
        "total_items": "557"
    }
}
</code>```

答:
If you want to get only the categories whose parent_id is 0 in your API call, please use the URL:

```<code>http://www.example.com/api/categories?category_id=0&visible=true
</code>```

Of course, any other id can be used instead of 0, just make sure you add the &visible=true parameter.

Body:
I am using the cs-cart rest API to create an android app. My problem is that i want categories as needed for example the parent category has an id "0", so i want just that category, can i edit URL to get only the categories whose parent_id: "0"

http://www.example.com/api/categories

I also tried URL encoding with different online tools, neither worked.

it's the JSON i am getting right now, i need the specific parent_id.

{
    "categories": [
        {
            "category_id": "735",
            "parent_id": "755",
            "id_path": "60/755/735",
            "category": "Clocks",
            "position": "0",
            "status": "A",
            "product_count": "1",
            "seo_name": "watches",
            "seo_path": "60/755"
        },
        {
            "category_id": "682",
            "parent_id": "295",
            "id_path": "217/295/682",
            "category": "360° Video Camera",
            "position": "0",
            "status": "A",
            "product_count": "514",
            "seo_name": "360-video-camera",
            "seo_path": "217/295"
        },
        {
            "category_id": "413",
            "parent_id": "0",
            "id_path": "413",
            "category": " Apparel",
            "position": "0",
            "status": "A",
            "product_count": "2",
            "seo_name": "apparel",
            "seo_path": ""
        },
        {
            "category_id": "359",
            "parent_id": "217",
            "id_path": "217/359",
            "category": "Computers ",
            "position": "0",
            "status": "A",
            "product_count": "25",
            "seo_name": "computer-cables",
            "seo_path": "217"
        },
        {
            "category_id": "357",
            "parent_id": "344",
            "id_path": "217/344/357",
            "category": "Chargers",
            "position": "0",
            "status": "A",
            "product_count": "1154",
            "seo_name": "network-media-converters",
            "seo_path": "217/344"
        },
        {
            "category_id": "355",
            "parent_id": "344",
            "id_path": "217/344/355",
            "category": "Cellphones",
            "position": "0",
            "status": "A",
            "product_count": "1469",
            "seo_name": "gateways-controllers",
            "seo_path": "217/344"
        },
        {
            "category_id": "345",
            "parent_id": "344",
            "id_path": "217/344/345",
            "category": "Bluetooth Accessories",
            "position": "0",
            "status": "A",
            "product_count": "1052",
            "seo_name": "network-antennas",
            "seo_path": "217/344"
        },
        {
            "category_id": "298",
            "parent_id": "295",
            "id_path": "217/295/298",
            "category": "Camera Accessories",
            "position": "0",
            "status": "A",
            "product_count": "507",
            "seo_name": "camera-accessories",
            "seo_path": "217/295"
        },
        {
            "category_id": "296",
            "parent_id": "295",
            "id_path": "217/295/296",
            "category": "Camcorders",
            "position": "0",
            "status": "A",
            "product_count": "504",
            "seo_name": "camcorders",
            "seo_path": "217/295"
        },
        {
            "category_id": "295",
            "parent_id": "217",
            "id_path": "217/295",
            "category": "Cameras & Camcorders",
            "position": "0",
            "status": "A",
            "product_count": "0",
            "seo_name": "cameras-and-camcorders",
            "seo_path": "217"
        },
        {
            "category_id": "271",
            "parent_id": "218",
            "id_path": "217/218/271",
            "category": "Audio Amplifiers",
            "position": "0",
            "status": "A",
            "product_count": "1003",
            "seo_name": "audio-amplifiers",
            "seo_path": "217/218"
        },
        {
            "category_id": "238",
            "parent_id": "218",
            "id_path": "217/218/238",
            "category": "Bluetooth Music Receivers",
            "position": "0",
            "status": "A",
            "product_count": "519",
            "seo_name": "bluetooth-music-receivers",
            "seo_path": "217/218"
        },
        {
            "category_id": "218",
            "parent_id": "217",
            "id_path": "217/218",
            "category": "Audio & Home Theatre",
            "position": "0",
            "status": "A",
            "product_count": "1",
            "seo_name": "audio-and-home-theatre",
            "seo_path": "217"
        },
        {
            "category_id": "188",
            "parent_id": "779",
            "id_path": "776/779/188",
            "category": "Baby Furniture",
            "position": "0",
            "status": "A",
            "product_count": "430",
            "seo_name": "baby-furniture",
            "seo_path": "776/779"
        },
        {
            "category_id": "185",
            "parent_id": "779",
            "id_path": "776/779/185",
            "category": "Baby Travel",
            "position": "0",
            "status": "A",
            "product_count": "494",
            "seo_name": "baby-travel",
            "seo_path": "776/779"
        },
        {
            "category_id": "169",
            "parent_id": "779",
            "id_path": "776/779/169",
            "category": "Baby Bathing & Potting",
            "position": "0",
            "status": "A",
            "product_count": "405",
            "seo_name": "baby-bathing-and-potting",
            "seo_path": "776/779"
        },
        {
            "category_id": "109",
            "parent_id": "108",
            "id_path": "101/108/109",
            "category": "BD/DVD Movies",
            "position": "0",
            "status": "A",
            "product_count": "0",
            "seo_name": "bd-dvd-movies",
            "seo_path": "101/108"
        },
        {
            "category_id": "90",
            "parent_id": "85",
            "id_path": "60/85/90",
            "category": "Cups & Mugs",
            "position": "0",
            "status": "A",
            "product_count": "504",
            "seo_name": "cups-and-mugs",
            "seo_path": "60/85"
        },
        {
            "category_id": "83",
            "parent_id": "69",
            "id_path": "60/69/83",
            "category": "Ceiling Lights",
            "position": "0",
            "status": "A",
            "product_count": "592",
            "seo_name": "ceiling-lighting",
            "seo_path": "60/69"
        },
        {
            "category_id": "70",
            "parent_id": "69",
            "id_path": "60/69/70",
            "category": " Bulbs & Tubes ",
            "position": "0",
            "status": "A",
            "product_count": "504",
            "seo_name": "bulbs",
            "seo_path": "60/69"
        }
    ],
    "params": {
        "category_id": 0,
        "visible": false,
        "current_category_id": 0,
        "simple": false,
        "plain": true,
        "limit": 0,
        "item_ids": "",
        "group_by_level": false,
        "get_images": false,
        "category_delimiter": "/",
        "get_frontend_urls": false,
        "max_nesting_level": null,
        "get_company_name": false,
        "items_per_page": 20,
        "page": 1,
        "except_id": 414,
        "sort_order": "asc",
        "sort_by": "position",
        "sort_order_rev": "desc",
        "total_items": "557"
    }
}

Body:
If you want to get only the categories whose parent_id is 0 in your API call, please use the URL:

http://www.example.com/api/categories?category_id=0&visible=true

Of course, any other id can be used instead of 0, just make sure you add the &visible=true parameter.


问:
GHC linker cannot find lHSsemigroups
I'm attempting to compile a Haskell project on Windows with profiling enabled, using the following command.

```<code>ghc --make -O -prof -fprof-auto game_dangerous.hs
</code>```

I develop the project myself and the same source code compiled and linked fine without profiling.  As expected (from previous experience) I ran into a number of errors of the form:

```<code>Could not find module `Data.Vector.Mutable'
Perhaps you haven't installed the profiling libraries for package `vector-0.12.0.2'?
</code>```

I proceeded to iteratively reinstall packages based on the errors encountered using for example:

```<code>cabal install -p vector --reinstall
</code>```

Cabal kept giving me warnings about possibly breaking packages with the reinstalls but I pressed on as (as far as I could see) every package that could be broken was going to get reinstalled itself as I moved through the tree of dependencies.  Also, I've previously followed the same process on another machine and it worked fine.  After reinstalling all the required packages my project now compiles but the linker fails with this error:

```<code>C://Program Files//Haskell Platform//8.6.3//mingw//bin/ld.exe: cannot find -lHSsemigroups-0.18.5-8pPnWqWrcWhEagTFf5Pnk2_p
collect2.exe: error: ld returned 1 exit status
`gcc.exe' failed in phase `Linker'. (Exit code: 1)
</code>```

However, the build does complete successfully without profiling enabled.  Does anyone know what may have gone wrong and how to fix the issue?  Thanks in advance.

Steven

答:
I would try making a .cabal file for your program, where you explicitly specify the cabal packages your program depends on and use cabal v2-build to compile your program. It will warn you about missing dependencies of your program until you include them all in build-depends section of the .cabal file. You only need to include the dependencies of your program, not the dependencies of the dependencies. After that you can add cabal.project.local to enable profiling and maybe something else. It should be enough to run cabal v2-build to build your program and packages it depends on with profiling(and other options in the cabal.project.local) enabled.

You need to have profiling enabled in the packages used by your program to support profiling in it. Cabal v2 builds allows you to have multiple instances of the same package. Those instances are different because different flags and options have been used to build them.

It is possible to achieve the same result using a separate package database for your program. That is using ghc-pkg with --package-db option.

Another option is to use stack. It will solve the same issues, but differently at the cost of more space and some performance penalties in ghc(compared to ghc built from source which can be used with cabal).

Title: GHC linker cannot find lHSsemigroups

Body:
I'm attempting to compile a Haskell project on Windows with profiling enabled, using the following command.

ghc --make -O -prof -fprof-auto game_dangerous.hs

I develop the project myself and the same source code compiled and linked fine without profiling.  As expected (from previous experience) I ran into a number of errors of the form:

Could not find module `Data.Vector.Mutable'
Perhaps you haven't installed the profiling libraries for package `vector-0.12.0.2'?

I proceeded to iteratively reinstall packages based on the errors encountered using for example:

cabal install -p vector --reinstall

Cabal kept giving me warnings about possibly breaking packages with the reinstalls but I pressed on as (as far as I could see) every package that could be broken was going to get reinstalled itself as I moved through the tree of dependencies.  Also, I've previously followed the same process on another machine and it worked fine.  After reinstalling all the required packages my project now compiles but the linker fails with this error:

C://Program Files//Haskell Platform//8.6.3//mingw//bin/ld.exe: cannot find -lHSsemigroups-0.18.5-8pPnWqWrcWhEagTFf5Pnk2_p
collect2.exe: error: ld returned 1 exit status
`gcc.exe' failed in phase `Linker'. (Exit code: 1)

However, the build does complete successfully without profiling enabled.  Does anyone know what may have gone wrong and how to fix the issue?  Thanks in advance.

Steven


问:
Notifications not showing android API 29
Ok, guys, idk why but notifications is not showing, on phone with API 29. On Api 21 for example everything is ok. Yes, I tried to read other posts on SO and found there nothing usefull, tried all advices from those posts too.

Min sdk 24, max sdk - 29 in gradle

receiver in manifest:

```<code><receiver android:name=".ui.more_content.receivers.RemindersReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED"/>
                <action android:name="android.intent.action.PACKAGE_REMOVED"/>
                <data android:scheme="package"/>
            </intent-filter>
        </receiver>
</code>```

Receiver class:

```<code>class RemindersReceiver: BroadcastReceiver() {

    override fun onReceive(p0: Context?, p1: Intent?) {
        // Идентификатор уведомления
        if(p1?.action.equals("android.intent.action.PACKAGE_ADDED")||p1?.action.equals("android.intent.action.PACKAGE_REMOVED")
            ||p1?.action.equals("android.intent.action.PACKAGE_UPDATED")) {
            showNotificationWith("qwqwdqwqs", p0)
        }
    }

    private fun showNotificationWith(message: String, context: Context?) {
        val channelId = "com.example.notif.channelId"
        val channelName = "App status"
        val contentTitle = "Title"
        val notificationManager =
            context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val activityIntent = Intent()
        val contentIntent: PendingIntent = PendingIntent.getActivity(
            context,
            0, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT
        )

        val largeIcon: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.info)
        val notificationBuilder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.info)
            .setContentTitle(contentTitle)
            .setContentText("asdasdasdasdas")
            .setStyle(
                NotificationCompat.BigTextStyle()
                    .bigText(context.getString(R.string.long_dummy_text))
                    .setBigContentTitle("Big content title")
                    .setSummaryText("Summary is this Text")
            )
            .setLargeIcon(largeIcon)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setColor(Color.RED)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val importance = NotificationManager.IMPORTANCE_HIGH
            val notificationChannel = NotificationChannel(channelId, channelName, importance)
            notificationBuilder.setChannelId(channelName)

            notificationManager.createNotificationChannel(notificationChannel)
            notificationManager.notify(
                message.hashCode(), notificationBuilder
                    .setContentIntent(contentIntent).setAutoCancel(true).build()
            )

        } else {
            notificationManager
                .notify(
                message.hashCode(), notificationBuilder
                    .setContentIntent(contentIntent).setAutoCancel(true).build()
            )
        }
    }
}
</code>```

Appreciate any help, thx in a forward

答: Those broadcasts have not been delivered to manifest-registered receivers since Android 8.0.</p>

Body:
Ok, guys, idk why but notifications is not showing, on phone with API 29. On Api 21 for example everything is ok. Yes, I tried to read other posts on SO and found there nothing usefull, tried all advices from those posts too.

Min sdk 24, max sdk - 29 in gradle

receiver in manifest:

<receiver android:name=".ui.more_content.receivers.RemindersReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED"/>
                <action android:name="android.intent.action.PACKAGE_REMOVED"/>
                <data android:scheme="package"/>
            </intent-filter>
        </receiver>

Receiver class:

class RemindersReceiver: BroadcastReceiver() {

    override fun onReceive(p0: Context?, p1: Intent?) {
        // Идентификатор уведомления
        if(p1?.action.equals("android.intent.action.PACKAGE_ADDED")||p1?.action.equals("android.intent.action.PACKAGE_REMOVED")
            ||p1?.action.equals("android.intent.action.PACKAGE_UPDATED")) {
            showNotificationWith("qwqwdqwqs", p0)
        }
    }

    private fun showNotificationWith(message: String, context: Context?) {
        val channelId = "com.example.notif.channelId"
        val channelName = "App status"
        val contentTitle = "Title"
        val notificationManager =
            context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val activityIntent = Intent()
        val contentIntent: PendingIntent = PendingIntent.getActivity(
            context,
            0, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT
        )

        val largeIcon: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.info)
        val notificationBuilder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.info)
            .setContentTitle(contentTitle)
            .setContentText("asdasdasdasdas")
            .setStyle(
                NotificationCompat.BigTextStyle()
                    .bigText(context.getString(R.string.long_dummy_text))
                    .setBigContentTitle("Big content title")
                    .setSummaryText("Summary is this Text")
            )
            .setLargeIcon(largeIcon)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setColor(Color.RED)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val importance = NotificationManager.IMPORTANCE_HIGH
            val notificationChannel = NotificationChannel(channelId, channelName, importance)
            notificationBuilder.setChannelId(channelName)

            notificationManager.createNotificationChannel(notificationChannel)
            notificationManager.notify(
                message.hashCode(), notificationBuilder
                    .setContentIntent(contentIntent).setAutoCancel(true).build()
            )

        } else {
            notificationManager
                .notify(
                message.hashCode(), notificationBuilder
                    .setContentIntent(contentIntent).setAutoCancel(true).build()
            )
        }
    }
}

Appreciate any help, thx in a forward


问:
Select variables with different names
I have some DF’s with different variable names, but they have the same content. Unfortunately, my files have no pattern, but I am now trying to standardize them. For example, I have these 4 DF’s and I would like to select only one variable:

```<code>KEY_WIN <- c(123,456,789)
COUNTRY <- c("USA","FRANCE","MEXICO")
DF1 <- data.frame(KEY_WIN,COUNTRY)

KEY_WINN <- c(12,55,889)
FOOD <- c("RICE","TOMATO","MANGO")
CAR <- c("BMW","FERRARI","TOYOTA")
DF2 <- data.frame(KEY_WINN,FOOD,CAR)

ID <- c(555,698,33)
CITY <- c("NYC","LONDON","PARIS")
DF3 <- data.frame(ID,CITY)

NUMBER <- c(3,436,1000)
OCEAN <- c("PACIFIC","ATLANTIC","INDIAN")
DF4 <- data.frame(NUMBER,OCEAN)
</code>```

I would like to create a routine to select only the variables KEY_WIN, KEY_WINN, ID, NUMBER. My expected result would be:

```<code>DF_FINAL<- data.frame(KEY=c(123,456,789, 12,55,889, 555,698,33, 3,436,1000))
</code>```

How would I select only those variables?

答:
There are multiple ways I would imagine you could approach this.

First, you could put your data frames in a list:

```<code>listofDF <- list(DF1, DF2, DF3, DF4)
</code>```

Then, you could bind_rows to add the data frames together, and then coalesce to merge into one column.

```<code>library(tidyverse)

bind_rows(listofDF) %>%
  mutate(KEY = coalesce(KEY_WIN, KEY_WINN, ID, NUMBER)) %>%
  select(KEY)

    KEY
1   123
2   456
3   789
4    12
5    55
6   889
7   555
8   698
9    33
10    3
11  436
12 1000
</code>```

If you knew that the first column was always your KEY column, you could simply do:

```<code>KEY = unlist(lapply(listofDF, "[[", 1))
</code>```

This would extract the first column from all of your data frames:

```<code> [1]  123  456  789   12   55  889  555  698   33    3  436 1000
</code>```

Title: Select variables with different names

Body:
I have some DF’s with different variable names, but they have the same content. Unfortunately, my files have no pattern, but I am now trying to standardize them. For example, I have these 4 DF’s and I would like to select only one variable:

KEY_WIN <- c(123,456,789)
COUNTRY <- c("USA","FRANCE","MEXICO")
DF1 <- data.frame(KEY_WIN,COUNTRY)

KEY_WINN <- c(12,55,889)
FOOD <- c("RICE","TOMATO","MANGO")
CAR <- c("BMW","FERRARI","TOYOTA")
DF2 <- data.frame(KEY_WINN,FOOD,CAR)

ID <- c(555,698,33)
CITY <- c("NYC","LONDON","PARIS")
DF3 <- data.frame(ID,CITY)

NUMBER <- c(3,436,1000)
OCEAN <- c("PACIFIC","ATLANTIC","INDIAN")
DF4 <- data.frame(NUMBER,OCEAN)

I would like to create a routine to select only the variables KEY_WIN, KEY_WINN, ID, NUMBER. My expected result would be:

DF_FINAL<- data.frame(KEY=c(123,456,789, 12,55,889, 555,698,33, 3,436,1000))

How would I select only those variables?

Body:
There are multiple ways I would imagine you could approach this.

First, you could put your data frames in a list:

listofDF <- list(DF1, DF2, DF3, DF4)

Then, you could bind_rows to add the data frames together, and then coalesce to merge into one column.

library(tidyverse)

bind_rows(listofDF) %>%
  mutate(KEY = coalesce(KEY_WIN, KEY_WINN, ID, NUMBER)) %>%
  select(KEY)

    KEY
1   123
2   456
3   789
4    12
5    55
6   889
7   555
8   698
9    33
10    3
11  436
12 1000

If you knew that the first column was always your KEY column, you could simply do:

KEY = unlist(lapply(listofDF, "[[", 1))

This would extract the first column from all of your data frames:

 [1]  123  456  789   12   55  889  555  698   33    3  436 1000


问:
How to define a certain time for the getch() function in C?
I am trying to have the function getch() of the C language in Windows to work only for a few seconds.</p>

```<code>#include <stdio.h>
#include <windows.h>
int main()
{
    int v1, v2;
    v1=getch();//I want this getch to only be activated for a few seconds
    printf("Example");//That to activate the next function, even if the person reading this programm doesn't click in any key
    return 0;
}
</code>```

答:
you need to use the ncurse library and call:

initscr or newterm to initialize the screen

timeout with a positive delay. Otherwise, it will not be blocking.

Read more here

Body:
I am trying to have the function getch() of the C language in Windows to work only for a few seconds.

#include <stdio.h>
#include <windows.h>
int main()
{
    int v1, v2;
    v1=getch();//I want this getch to only be activated for a few seconds
    printf("Example");//That to activate the next function, even if the person reading this programm doesn't click in any key
    return 0;
}


问:
Intercepting a form submition into a pop-up window with jquery
I'm using a pop-up window to upload images to imageshack provider using their api.

My goal is, in the main window, to get the returned xml from the form upload inside the pop-up window (in order to get the thumb and image links of the uploaded image) and insert this data into some hidden fields in the main window.

edit
My iter is:

The user click a button on my site (example.com)

I open a pop-up with a form inside (example.com/form.html) via window.open

The form's action goes to Imageshack api url

The user upload the image, the form is submitted, imageshack api return some xml.

I need to get that xml in the main window, parse it to get the original image and thumbnail url, then close the pop-up.

This becose i dont like my user to have to copy'n'paste the html from imageshack into a field on my site... its just for convenience.

So, how can I detect when the form gets submitted, and how do I get the returned xml?

p.s: im using imageshack to low tmy servers bandwith and cpu usage for images, so i cant upload the image on my server and then store on imageshack (via server-side languages)

答: After many try, with all possible tricks&hacks, what i was looking for is not possible, due to browser's security policy.</p>

ContentLicense: CC BY-SA 3.0


问:
Toad for Oracle, No valid Oracle clients found. You need at least one 64-bit client properly configured
I get this error when I launch Toad for Oracle.

```<code>No valid Oracle clients found. You need at least one 64-bit client properly configured.
</code>```

This has been happening since I upgraded the Oracle Client to Oracle 12c from 11g.

Here is what I have done so far to try to resolve it based on internet research:

I checked the path variable, it's currently set to C:\xyz\Oracle\ora12.1\client_2\bin, and there is an Oracle installation at this path.

I checked the TNS_ADMIN variable, it is currently set to C:\xyz\Oracle\ora12.1\client_2\network\admin. This also appears to be valid and correct, there is a tnsnames.ora file under this path.

SQL Plus works without issues, and Oracle SQL Developer also works without issues.

Is there anything else I can try to resolve this issue? Unfortunately, uninstalling and reinstalling Toad is not an option at this point as I do not have access to a new setup.

答:
The issue is due to not having the Oracle Database installed on your computer.

You can download the database here: https://www.oracle.com/database/technologies/appdev/xe.html

Once the zip file is downloaded and extracted, run setup.exe. Once that is complete, the Oracle DB will be installed on your machine and the error will no longer appear.

Body:
I get this error when I launch Toad for Oracle.

No valid Oracle clients found. You need at least one 64-bit client properly configured.

This has been happening since I upgraded the Oracle Client to Oracle 12c from 11g.

Here is what I have done so far to try to resolve it based on internet research:

I checked the path variable, it's currently set to C:\xyz\Oracle\ora12.1\client_2\bin, and there is an Oracle installation at this path.

I checked the TNS_ADMIN variable, it is currently set to C:\xyz\Oracle\ora12.1\client_2\network\admin. This also appears to be valid and correct, there is a tnsnames.ora file under this path.

SQL Plus works without issues, and Oracle SQL Developer also works without issues.

Is there anything else I can try to resolve this issue? Unfortunately, uninstalling and reinstalling Toad is not an option at this point as I do not have access to a new setup.


问:
Pattern Layout to abbreviate the name of all logger components except the 2 rightmost
The following are my favorite patterns

%c{2} - which displays the corresponding number of rightmost logger
  name components. So a logger with a name like "org.apache.commons.Foo"
  is displayed as "commons.Foo".

and

%c{1.} - which abbreviates the name based on the pattern. So a logger
  with a name like "org.apache.commons.Foo" is displayed as "o.a.c.Foo".

Is there a way to combine the two. I want to abbreviate the name of all logger components except the 2 rightmost. Such that "org.apache.commons.Foo" is displayed as "o.a.commons.Foo".

Is it possible to do this using the pattern layout or in any other easy way?

答:
Yes and no. NameAbbreviator.java handles creating the abbreviation of the name. It has a getAbbreviator method that returns one of 3 implementations -

NoOp - returns the string as is.

MaxElement - returns the last n elements.

Pattern - This uses the pattern to break up the string into fragments, formatting each according to the pattern. If you specify 1.2 then the first character of the first item will be printed and 2 characters of each following item will be printed up to the final token, which is never abbreviated. A special case is if the pattern contains a "*". That indicates that everything that follows should be printed as is.

So the answer to your question is that you could use the following patterns:

1.* - would print o.apache.commons.Foo

1.1.* - would print o.a.commons.Foo

As you can see this isn't very helpful when package names have different lengths. I would suggest you create a Jira issue for this. Patches and pull requests are welcome!


问:
How can I delete the Kubernetes dashboard from kube-system?
I can not remove kubernetes-dashboard from Minikube. I tried deleting the deployment "deployment.apps/kubernetes-dashboard" multiple times. But it gets recreated automatically in a few seconds.

I am using the following command to delete the deployment:

kubectl delete deployment.apps/kubernetes-dashboard -n kube-system

I even tried to edit the deployment by setting the replica count to zero. But even it gets reset automatically after a few seconds.

The same thing happens for nginx-ingress deployment in kube-system.

答:
Try the below command:

```<code>kubectl delete -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-rc5/aio/deploy/recommended.yaml
</code>```

Body:
Try the below command:

kubectl delete -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-rc5/aio/deploy/recommended.yaml


问:
PostgresSql instal user cannot login?
I'm new to PostgresSql (version 11), and want to connect to it (perform createdb.exe etc).
However, the Windows logged on user "me" is asked for a password, I used my windows password, my installer password and the password for a super user of the database but none of them work.
What can this be ?.</p>

答:
my installer password and the password for a super user of the database

Aren't those the same thing?  How did the super user password get set, if not from the installer?

Did you try to login as the superuser's PostgreSQL account?  psql -U postgres -h 127.0.0.1, for example.  You can't use a super user's password to login as a different user, like "me" (not even if "me" is also a superuser).

Title: PostgresSql instal user cannot login?


问:
Flutter/Dart won't display FutureBuilder snapshot when resolved
I'm attempting to set a field value from SharedPreferences like so:

```<code>FutureBuilder<String>(
              future: _getUsername(),
              initialData: 'Bruh',
              builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                print(snapshot);
                print(snapshot.data);
                print(snapshot.hasData);
                return snapshot.hasData ? TextFormField(initialValue: snapshot.data, onChanged: _setUsername) : TextFormField();
              }
            ),
</code>```

This is the _getUsername() future I'm using:

```<code>Future<String> _getUsername() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('username') ?? 'hmm';
return "Fine";
}
</code>```

And this is the console output:

```<code>Reloaded 0 of 567 libraries in 352ms.
I/flutter (28961): AsyncSnapshot<String>(ConnectionState.done, tesy, null)
I/flutter (28961): tesy
I/flutter (28961): true
</code>```

As you can see, L2 of the output shows 'tesy', which is the value in SharedPreferences, but I only ever see 'Bruh' in the text field (the initial value).

In all the examples I can find, 'Bruh' would be displayed (extremely) briefly (if at all) before 'tesy' is then displayed in the input box. Where am I going wrong?

答:
Try change

```<code>TextFormField(initialValue: snapshot.data, onChanged: _setUsername)
</code>```

To

```<code>TextFormField(key: UniqueKey(), initialValue: snapshot.data, onChanged: _setUsername)
</code>```

This is because TextFormField is "Stateful" and the widget tree doesn't detect the change, puting a unique key, does the job that you want, another option is update value using an TextEditingrController.

Body:
I'm attempting to set a field value from SharedPreferences like so:

FutureBuilder<String>(
              future: _getUsername(),
              initialData: 'Bruh',
              builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                print(snapshot);
                print(snapshot.data);
                print(snapshot.hasData);
                return snapshot.hasData ? TextFormField(initialValue: snapshot.data, onChanged: _setUsername) : TextFormField();
              }
            ),

This is the _getUsername() future I'm using:

Future<String> _getUsername() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('username') ?? 'hmm';
return "Fine";
}

And this is the console output:

Reloaded 0 of 567 libraries in 352ms.
I/flutter (28961): AsyncSnapshot<String>(ConnectionState.done, tesy, null)
I/flutter (28961): tesy
I/flutter (28961): true

As you can see, L2 of the output shows 'tesy', which is the value in SharedPreferences, but I only ever see 'Bruh' in the text field (the initial value).

In all the examples I can find, 'Bruh' would be displayed (extremely) briefly (if at all) before 'tesy' is then displayed in the input box. Where am I going wrong?

Body:
Try change

TextFormField(initialValue: snapshot.data, onChanged: _setUsername)

To

TextFormField(key: UniqueKey(), initialValue: snapshot.data, onChanged: _setUsername)

This is because TextFormField is "Stateful" and the widget tree doesn't detect the change, puting a unique key, does the job that you want, another option is update value using an TextEditingrController.


问:
Pass fetch data to components using useState React Native
I am new to React Native. Actually this is my first app.

I have been trying to pass data from Fetch to components, but no luck there. I have researched Google up and down, left and right, tried million things, but still no go.

This is my App.js

```<code>import React, {useState, useEffect} from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';

import Header from './parts/header';
// import BigNews from './parts/big-news';
import Index from './screens/index.js';

const authorization = { authorization: '1234aa' };

export default function App() {
  const [fetchApiData, setApiData] = useState();

  useEffect(() =>
  fetch('https://example.com/get-app-home.php', {
    method: 'POST', // or 'PUT'
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(authorization),
  })
  .then(res => res.json())
  .then(res => {
    this.setState({ setApiData: res })
  })
  .catch(() => this.setState({ hasErrors: true }))
  );
  return (
    <View style={styles.viewport}>
      <Header />
      <ScrollView style={styles.contentHolder}>
        <Index content={fetchApiData}/>
      </ScrollView>
    </View>
);

}
</code>```

And this is my index.js file

```<code>import React from 'react';
import { View, Text } from 'react-native';

import BigNews from '../parts/big-news';
import SmallNews from '../parts/small-news';
import Colors from '../constants/colors'

const Index = props => {

    return (
      <View>
        <BigNews
        image={props.content.first.image}
        pretitle={props.content.first.pretitle}
        title={props.content.first.title}
        introduction={props.content.first.introduction}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>
      </View>
    );
}
export default Index;
</code>```

I am constantly getting TypeError: undefined is not an object (evaluating 'props.content.first')

I tried million ways, but most of the times this is the error that I see. If I do console.log of state I get either undefined or empty.

答:
In your Index component, the content prop is initially undefined as you don't pass any value (often referred to as "initial state") to the useState function in your App component.

Instead, try:

```<code>const [ fetchApiData, setApiData ] = useState({
    first: {},
    second: {}
});
</code>```

Note that I've populated the initial state with the first and second items, because trying to access the elements further down the tree (image, pretitle, etc,) will still throw an error.

Body:
I am new to React Native. Actually this is my first app.

I have been trying to pass data from Fetch to components, but no luck there. I have researched Google up and down, left and right, tried million things, but still no go.

This is my App.js

import React, {useState, useEffect} from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';

import Header from './parts/header';
// import BigNews from './parts/big-news';
import Index from './screens/index.js';

const authorization = { authorization: '1234aa' };

export default function App() {
  const [fetchApiData, setApiData] = useState();

  useEffect(() =>
  fetch('https://example.com/get-app-home.php', {
    method: 'POST', // or 'PUT'
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(authorization),
  })
  .then(res => res.json())
  .then(res => {
    this.setState({ setApiData: res })
  })
  .catch(() => this.setState({ hasErrors: true }))
  );
  return (
    <View style={styles.viewport}>

      <ScrollView style={styles.contentHolder}>
        <Index content={fetchApiData}/>
      </ScrollView>
    </View>
);

}

And this is my index.js file

import React from 'react';
import { View, Text } from 'react-native';

import BigNews from '../parts/big-news';
import SmallNews from '../parts/small-news';
import Colors from '../constants/colors'

const Index = props => {

    return (
      <View>
        <BigNews
        image={props.content.first.image}
        pretitle={props.content.first.pretitle}
        title={props.content.first.title}
        introduction={props.content.first.introduction}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>
      </View>
    );
}
export default Index;

I am constantly getting TypeError: undefined is not an object (evaluating 'props.content.first')

I tried million ways, but most of the times this is the error that I see. If I do console.log of state I get either undefined or empty.

Body:
In your Index component, the content prop is initially undefined as you don't pass any value (often referred to as "initial state") to the useState function in your App component.

Instead, try:

const [ fetchApiData, setApiData ] = useState({
    first: {},
    second: {}
});

Note that I've populated the initial state with the first and second items, because trying to access the elements further down the tree (image, pretitle, etc,) will still throw an error.


问:
React project fails to use node modules in a git submodule
I have a Javascript (typescript) project that I am using as a git submodule in a react project (also typescript).

This all works fine... until I make use of any node module in the git submodule. I tried using, for example, the node modules "moment" and "faker", but I am almost certain that it does not have anything to do with these specific node modules.

Importing for example "moment" in the submodule:

```<code>import moment from 'moment';
</code>```

using it:

```<code>moment().format('DD/MM/YYYY');
</code>```

and running the main react project leads to this error:

```<code>Failed to compile.

./src/project_core/node_modules/moment/moment.js
  Line 5:37:  'define' is not defined  no-undef
  Line 5:50:  'define' is not defined  no-undef
</code>```

Removing moment().format('DD/MM/YYYY'); solves it.

If I just run some tests directly in the submodule and make use of for example "moment", it always works. I can use the node modules. It looks like something goes wrong once the main project uses the node modules in the git submodule.

This is how my react project looks like. As you can see the submodule project_core is added in the src folder of the main project.

```<code>├── build
│   ├── assets
│   └── static
│       ├── css
│       └── js
├── node_modules
├── public
│   └── assets
└── src
    ├── project_core
    │   ├── node_modules
    │   ├── src
    │   └── tests
    ├── ui
    ├── api
    └── utils
</code>```

I know... I read everywhere that using git submodules is not recommended. I, however, just want to experiment with git submodules to learn from it.

答: It looks like you have a node module inside a node module. This probably confuses your bundler and produces the import errors. Try removing the package.json and node_modules from your project core subdirectory and see if the imports work correctly. If you want to make your core directory a library think about actually having it as a npm dependency instead of a submodule. You could still reference a git commit hash in the dependency.</p>

Body:
I have a Javascript (typescript) project that I am using as a git submodule in a react project (also typescript).

This all works fine... until I make use of any node module in the git submodule. I tried using, for example, the node modules "moment" and "faker", but I am almost certain that it does not have anything to do with these specific node modules.

Importing for example "moment" in the submodule:

import moment from 'moment';

using it:

moment().format('DD/MM/YYYY');

and running the main react project leads to this error:

Failed to compile.

./src/project_core/node_modules/moment/moment.js
  Line 5:37:  'define' is not defined  no-undef
  Line 5:50:  'define' is not defined  no-undef

Removing moment().format('DD/MM/YYYY'); solves it.

If I just run some tests directly in the submodule and make use of for example "moment", it always works. I can use the node modules. It looks like something goes wrong once the main project uses the node modules in the git submodule.

This is how my react project looks like. As you can see the submodule project_core is added in the src folder of the main project.

├── build
│   ├── assets
│   └── static
│       ├── css
│       └── js
├── node_modules
├── public
│   └── assets
└── src
    ├── project_core
    │   ├── node_modules
    │   ├── src
    │   └── tests
    ├── ui
    ├── api
    └── utils

I know... I read everywhere that using git submodules is not recommended. I, however, just want to experiment with git submodules to learn from it.


问:
Install gdal==2.3.3 into a venv with pip
I am using anaconda with python 3.7.4 and I am working on VScode. I am currently creating a Flask webapp mostly with bokeh, that I am deploying on google app engine(gcloud). In order to work with GIS I need to install geopandas which will require gdal, fiona, rtree, shapely, pyproj, numpy, among few others. I am working in a virtual environment so I can install the .whl files directly with pip install [file.whl] and it will work locally with no problem. I also created the environment variable for gdal_data and added it to he PATH variable as well. So I have been trying to deploy the app since I installed geopandas and google is trowing me an error of gdal-config not found. I tried to dig into it with my low knowledge with dependencies and deployment. What I figured out was the following:

conda will superseded gdal 3.0.4 and install gdal 2.3.3
pip does not have this version and that when it comes to problem.
As long as I understood it google will use my requirements.txt to install the libraries I am using in my virtual environment into their cloud environment, so an error will be thrown once pip will not find the gdal 2.3.3 version that I will pass to my requirements.txt and the one I installed it manually.
Also fiona that is one of pillars of the wheel to build GIS plots is not compatible to the gdal version that conda is insisting to superseded.

I have read a lot and spend a good amount of time dealing with this error. There are a lot of info mostly for Linux, but I could not find anything to help me out.

If someone out there could help me that would be appreciated.

答:
I had the same issue when installing gdal:

...
      main.gdal_config_error: [Errno 2] No such file or directory: 'gdal-config': 'gdal-config' ...

The problem is that the underlying docker container does not have the required C libraries for running this version of gdal. So you cannot use the default app engine environment for running your application.

The solution is then to create a custom runtime (i.e. docker container) to run your app engine instance. There is another stackoverflow post which explains how to exactly do this.

The most important step is to include:

```<code>sudo apt-get install gdal-bin python-gdal
</code>```

Body:
I had the same issue when installing gdal:

...
      main.gdal_config_error: [Errno 2] No such file or directory: 'gdal-config': 'gdal-config' ...

The problem is that the underlying docker container does not have the required C libraries for running this version of gdal. So you cannot use the default app engine environment for running your application.

The solution is then to create a custom runtime (i.e. docker container) to run your app engine instance. There is another stackoverflow post which explains how to exactly do this.

The most important step is to include:

sudo apt-get install gdal-bin python-gdal


问:
Discord.js support channel
I want to create an if variable which checks if a user joins a certain channel, if they do then I'll keep doing my program.

What I have tried so far is different things like:

client.on('channel', async channel => {
    if (channel.member.join(channel => channel.id === `672920107457970177`)) {
        working.send("did it work??")
    }
})
```

But I am pretty sure that my whole script is wrong; I only started using discord.js a few weeks ago.

答:
You can use Client's voiceStateUpdate event. It will return 2 GuildMember values. The old one and the updated one.

```<code>Client.on("voiceStateUpdate", (oldMember, newMember) => {
    if (!oldMember.voiceChannel && newMember.voiceChannel) {
        console.log("oldMember channel doesn't exist. newMember channel exist. User joined a voice channel.")
    } else if (!newMember.voiceChannel) {
        console.log("newMember voice channel doesn't exist. User left a voice channel.")
    }
})
</code>```

You need to do these checks because voiceStatusUpdate is fired whenever the voice status updates (e.g. defean, mute, channel move etc.)

To check if the user joined a certain channel, just check the ID:

```<code>Client.on("voiceStateUpdate", (oldMember, newMember) => {
    if (!oldMember.voiceChannel && newMember.voiceChannel && newMember.voiceChannelID == "CHANNEL ID") {
        console.log(`User joined ${newMember.voiceChannel.name}!`)
    }
})
</code>```

Title: Discord.js support channel

Body:
I want to create an if variable which checks if a user joins a certain channel, if they do then I'll keep doing my program.

What I have tried so far is different things like:

client.on('channel', async channel => {
    if (channel.member.join(channel => channel.id === `672920107457970177`)) {
        working.send("did it work??")
    }
})

But I am pretty sure that my whole script is wrong; I only started using discord.js a few weeks ago.

Body:
You can use Client's voiceStateUpdate event. It will return 2 GuildMember values. The old one and the updated one.

Client.on("voiceStateUpdate", (oldMember, newMember) => {
    if (!oldMember.voiceChannel && newMember.voiceChannel) {
        console.log("oldMember channel doesn't exist. newMember channel exist. User joined a voice channel.")
    } else if (!newMember.voiceChannel) {
        console.log("newMember voice channel doesn't exist. User left a voice channel.")
    }
})

You need to do these checks because voiceStatusUpdate is fired whenever the voice status updates (e.g. defean, mute, channel move etc.)

To check if the user joined a certain channel, just check the ID:

Client.on("voiceStateUpdate", (oldMember, newMember) => {
    if (!oldMember.voiceChannel && newMember.voiceChannel && newMember.voiceChannelID == "CHANNEL ID") {
        console.log(`User joined ${newMember.voiceChannel.name}!`)
    }
})


问:
zsh: Heroku toolbelt not found anymore
I recently switched to zsh, pretty happy about that. Except that the heroku toolbelt doesn't work anymore ...

Here is what I have when I type heroku -v :

```<code>/usr/lib/ruby/1.9.1/rubygems/dependency.rb:247:in `to_specs': Could not find heroku (>= 0) amongst [actionmailer-3.2.13, actionpack-3.2.13, activemodel-3.2.13, activerecord-3.2.13, activeresource-3.2.13, activesupport-3.2.13, arel-3.0.2, bcrypt-ruby-3.0.1, bootstrap-sass-2.3.1.0, builder-3.0.4, bundler-1.3.5, climate_control-0.0.3, cocaine-0.5.1, coffee-rails-3.2.2, coffee-script-2.2.0, coffee-script-source-1.6.2, daemons-1.1.9, devise-2.2.3, erubis-2.7.0, eventmachine-1.0.3, execjs-1.4.0, faraday-0.8.7, haml-3.1.4, hashie-1.2.0, hike-1.2.2, httpauth-0.2.0, i18n-0.6.1, journey-1.0.4, jquery-rails-2.2.1, json-1.7.7, jwt-0.1.8, mail-2.5.3, mime-types-1.23, mime-types-1.22, multi_json-1.7.3, multi_json-1.7.2, multipart-post-1.2.0, oauth2-0.8.1, omniauth-1.1.3, omniauth-facebook-1.4.1, omniauth-oauth2-1.1.1, orm_adapter-0.4.0, paperclip-3.4.1, pg-0.15.1, polyglot-0.3.3, rack-1.4.5, rack-cache-1.2, rack-ssl-1.3.3, rack-test-0.6.2, rails-3.2.13, railties-3.2.13, rake-10.0.4, rdoc-3.12.2, rubygems-bundler-1.1.1, rvm-1.11.3.7, sass-3.2.9, sass-rails-3.2.6, sprockets-2.2.2, thin-1.5.1, thor-0.18.1, tilt-1.4.1, tilt-1.3.7, treetop-1.4.12, tzinfo-0.3.37, uglifier-2.1.0, warden-1.2.1] (Gem::LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/dependency.rb:256:in `to_spec'
    from /usr/lib/ruby/1.9.1/rubygems.rb:1231:in `gem'
    from /usr/local/bin/heroku:22:in `<main>'
</code>```

I tried to reinstall the toolbelt since I read about it, but same result happen.

I compared bash and zsh $PATHs but they seem to contain the same pointers to heroku folders :

Bash:

```<code>/usr/local/heroku/bin:/home/augustin/.rvm/gems/ruby-1.9.3-p392/bin:/home/augustin/.rvm/gems/ruby-1.9.3-p392@global/bin:/home/augustin/.rvm/rubies/ruby-1.9.3-p392/bin:/home/augustin/.rvm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/usr/local/heroku/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/home/augustin/.rvm/bin:/home/augustin/.rvm/bin
</code>```

Zsh:

```<code>/home/augustin/.rvm/gems/ruby-1.9.3-p392/bin:/home/augustin/.rvm/gems/ruby-1.9.3-p392@global/bin:/home/augustin/.rvm/rubies/ruby-1.9.3-p392/bin:/home/augustin/.rvm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/usr/local/heroku/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/home/augustin/.rvm/bin
</code>```

I have read about installing heroku gem since I have ruby errors, but I also read it's depreciated since the toolbelt exists: https://github.com/robbyrussell/oh-my-zsh/issues/1401

So where is the problem?

I'm pretty new to Ruby, I still don't understand everything about rvms and I have the feeling my error is linked to it.

Finally, here is my .zshrc file, which I think could help too.

```<code># Path to your oh-my-zsh configuration.
ZSH=$HOME/.oh-my-zsh

# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
#ZSH_THEME="robbyrussell"
#ZSH_THEME="muse"
ZSH_THEME="ys"

# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"

# Set to this to use case-sensitive completion
# CASE_SENSITIVE="true"

# Comment this out to disable bi-weekly auto-update checks
# DISABLE_AUTO_UPDATE="true"

# Uncomment to change how often before auto-updates occur? (in days)
# export UPDATE_ZSH_DAYS=13

# Uncomment following line if you want to disable colors in ls
# DISABLE_LS_COLORS="true"

# Uncomment following line if you want to disable autosetting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment following line if you want to disable command autocorrection
# DISABLE_CORRECTION="true"

# Uncomment following line if you want red dots to be displayed while waiting for completion
# COMPLETION_WAITING_DOTS="true"

# Uncomment following line if you want to disable marking untracked files under
# VCS as dirty. This makes repository status check for large repositories much,
# much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails rails3 git textmate ruby lighthouse)

source $HOME/.aliases

plugins=(git ruby rails rails3 rvm heroku)

source $ZSH/oh-my-zsh.sh

# [[ -s "$HOME/.rvm/scripts/rvm" ]] && . “$HOME/.rvm/scripts/rvm”
if [[ -s $HOME/.rvm/scripts/rvm ]] ; then source $HOME/.rvm/scripts/rvm ; fi

# Customize to your needs...
export PATH=$PATH:/usr/local/heroku/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/home/augustin/.rvm/bin
</code>```

Great thanks in advance.

答:
just put in you terminal :</p>

```<code>sudo snap install --classic heroku
</code>```

Title: zsh: Heroku toolbelt not found anymore

Body:
I recently switched to zsh, pretty happy about that. Except that the heroku toolbelt doesn't work anymore ...

Here is what I have when I type heroku -v :

/usr/lib/ruby/1.9.1/rubygems/dependency.rb:247:in `to_specs': Could not find heroku (>= 0) amongst [actionmailer-3.2.13, actionpack-3.2.13, activemodel-3.2.13, activerecord-3.2.13, activeresource-3.2.13, activesupport-3.2.13, arel-3.0.2, bcrypt-ruby-3.0.1, bootstrap-sass-2.3.1.0, builder-3.0.4, bundler-1.3.5, climate_control-0.0.3, cocaine-0.5.1, coffee-rails-3.2.2, coffee-script-2.2.0, coffee-script-source-1.6.2, daemons-1.1.9, devise-2.2.3, erubis-2.7.0, eventmachine-1.0.3, execjs-1.4.0, faraday-0.8.7, haml-3.1.4, hashie-1.2.0, hike-1.2.2, httpauth-0.2.0, i18n-0.6.1, journey-1.0.4, jquery-rails-2.2.1, json-1.7.7, jwt-0.1.8, mail-2.5.3, mime-types-1.23, mime-types-1.22, multi_json-1.7.3, multi_json-1.7.2, multipart-post-1.2.0, oauth2-0.8.1, omniauth-1.1.3, omniauth-facebook-1.4.1, omniauth-oauth2-1.1.1, orm_adapter-0.4.0, paperclip-3.4.1, pg-0.15.1, polyglot-0.3.3, rack-1.4.5, rack-cache-1.2, rack-ssl-1.3.3, rack-test-0.6.2, rails-3.2.13, railties-3.2.13, rake-10.0.4, rdoc-3.12.2, rubygems-bundler-1.1.1, rvm-1.11.3.7, sass-3.2.9, sass-rails-3.2.6, sprockets-2.2.2, thin-1.5.1, thor-0.18.1, tilt-1.4.1, tilt-1.3.7, treetop-1.4.12, tzinfo-0.3.37, uglifier-2.1.0, warden-1.2.1] (Gem::LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/dependency.rb:256:in `to_spec'
    from /usr/lib/ruby/1.9.1/rubygems.rb:1231:in `gem'
    from /usr/local/bin/heroku:22:in `'

I tried to reinstall the toolbelt since I read about it, but same result happen.

I compared bash and zsh $PATHs but they seem to contain the same pointers to heroku folders :

Bash:

/usr/local/heroku/bin:/home/augustin/.rvm/gems/ruby-1.9.3-p392/bin:/home/augustin/.rvm/gems/ruby-1.9.3-p392@global/bin:/home/augustin/.rvm/rubies/ruby-1.9.3-p392/bin:/home/augustin/.rvm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/usr/local/heroku/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/home/augustin/.rvm/bin:/home/augustin/.rvm/bin

Zsh:

/home/augustin/.rvm/gems/ruby-1.9.3-p392/bin:/home/augustin/.rvm/gems/ruby-1.9.3-p392@global/bin:/home/augustin/.rvm/rubies/ruby-1.9.3-p392/bin:/home/augustin/.rvm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/usr/local/heroku/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/home/augustin/.rvm/bin

I have read about installing heroku gem since I have ruby errors, but I also read it's depreciated since the toolbelt exists: https://github.com/robbyrussell/oh-my-zsh/issues/1401

So where is the problem?

I'm pretty new to Ruby, I still don't understand everything about rvms and I have the feeling my error is linked to it.

Finally, here is my .zshrc file, which I think could help too.

# Path to your oh-my-zsh configuration.
ZSH=$HOME/.oh-my-zsh

# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
#ZSH_THEME="robbyrussell"
#ZSH_THEME="muse"
ZSH_THEME="ys"

# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"

# Set to this to use case-sensitive completion
# CASE_SENSITIVE="true"

# Comment this out to disable bi-weekly auto-update checks
# DISABLE_AUTO_UPDATE="true"

# Uncomment to change how often before auto-updates occur? (in days)
# export UPDATE_ZSH_DAYS=13

# Uncomment following line if you want to disable colors in ls
# DISABLE_LS_COLORS="true"

# Uncomment following line if you want to disable autosetting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment following line if you want to disable command autocorrection
# DISABLE_CORRECTION="true"

# Uncomment following line if you want red dots to be displayed while waiting for completion
# COMPLETION_WAITING_DOTS="true"

# Uncomment following line if you want to disable marking untracked files under
# VCS as dirty. This makes repository status check for large repositories much,
# much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails rails3 git textmate ruby lighthouse)

source $HOME/.aliases

plugins=(git ruby rails rails3 rvm heroku)

source $ZSH/oh-my-zsh.sh

# [[ -s "$HOME/.rvm/scripts/rvm" ]] && . “$HOME/.rvm/scripts/rvm”
if [[ -s $HOME/.rvm/scripts/rvm ]] ; then source $HOME/.rvm/scripts/rvm ; fi

# Customize to your needs...
export PATH=$PATH:/usr/local/heroku/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/google/google_appengine:/home/augustin/.rvm/bin

Great thanks in advance.

Body:
just put in you terminal :

sudo snap install --classic heroku