问:
How do I stop a thread (QRunnable) when clicking on a button?
I read this article about Threading in PyQt and tried to implement it into my own program. I am now able to start a thread, but when I close the window I think the other thread keeps running. I also can't use ctrl+c to interrupt the program. So how do I stop this my thread, that sends the notifications? Here's my code: </p>

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QRunnable, pyqtSlot, QThreadPool
import notify2
import time

class StartTimer(QRunnable):
    '''
    StartTimer thread
    '''

    def __init__(self, minutes):
        super(StartTimer, self).__init__()
        self.minutes = minutes

    @pyqtSlot()
    def run(self):
        notify2.init('Break Timer')
        notification = notify2.Notification(
            'Success!', 'Break Timer has been started.')
        notification.show()

        self.start = True

        while self.start:
            time.sleep(self.minutes * 60)

            notify2.init('Break Timer')
            notification = notify2.Notification(
                'Pause for 1 minute', 'Move and see away from the screen!')
            notification.show()

        time.sleep(5)

class Ui_break_timer_ui(object):

    def __init__(self):
        self.threadpool = QThreadPool()
        self.start = False

    def start_btn_pressed(self):
        self.start_timer = StartTimer(self.spinBox_minutes.value())
        self.threadpool.start(self.start_timer)

    def stop_timer(self):
        notify2.init('Break Timer')
        notification = notify2.Notification(
            'Program ended', 'You will receive no further notifications.')
        notification.show()

        self.start = False

    def setupUi(self, break_timer_ui):
        break_timer_ui.setObjectName("break_timer_ui")
        break_timer_ui.setWindowIcon(QtGui.QIcon('icon.png'))
        break_timer_ui.resize(596, 412)
        self.centralwidget = QtWidgets.QWidget(break_timer_ui)
        self.centralwidget.setObjectName("centralwidget")
        self.btn_start = QtWidgets.QPushButton(self.centralwidget)
        self.btn_start.setGeometry(QtCore.QRect(490, 350, 88, 34))
        self.btn_start.setObjectName("btn_start")
        self.btn_stop = QtWidgets.QPushButton(self.centralwidget)
        self.btn_stop.setGeometry(QtCore.QRect(390, 350, 88, 34))
        self.btn_stop.setObjectName("btn_stop")
        self.label_set_interval = QtWidgets.QLabel(self.centralwidget)
        self.label_set_interval.setGeometry(QtCore.QRect(20, 20, 91, 18))
        self.label_set_interval.setObjectName("label_set_interval")
        self.spinBox_minutes = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBox_minutes.setGeometry(QtCore.QRect(20, 50, 52, 32))
        self.spinBox_minutes.setMinimum(1)
        self.spinBox_minutes.setMaximum(240)
        self.spinBox_minutes.setProperty("value", 30)
        self.spinBox_minutes.setObjectName("spinBox_minutes")
        self.label_minutes = QtWidgets.QLabel(self.centralwidget)
        self.label_minutes.setGeometry(QtCore.QRect(80, 60, 58, 18))
        self.label_minutes.setObjectName("label_minutes")
        break_timer_ui.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(break_timer_ui)
        self.statusbar.setObjectName("statusbar")
        break_timer_ui.setStatusBar(self.statusbar)

        self.btn_stop.clicked.connect(lambda _: self.stop_timer())

        self.btn_start.clicked.connect(lambda _: self.start_btn_pressed())

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

    def retranslateUi(self, break_timer_ui):
        _translate = QtCore.QCoreApplication.translate
        break_timer_ui.setWindowTitle(
            _translate("break_timer_ui", "Break Timer"))
        self.btn_start.setText(_translate("break_timer_ui", "Start"))
        self.btn_stop.setText(_translate("break_timer_ui", "Stop"))
        self.label_set_interval.setText(
            _translate("break_timer_ui", "Set interval"))
        self.label_minutes.setText(_translate("break_timer_ui", "minutes"))

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

答:
QRunnable is more for run-and-done code (even if it's long running) than it is for a persistent background thread.

Few things you want to do.  First, look at https://doc.qt.io/qt-5/qthread.html.  What you want to do is make your background task a QObject, give it a run() slot, and connect the thread.started to the worker.run.  That's what will kick the process off.  You need to do the ugly two-part way, not just subclass QThread, because you want the thread to have its own event loop.

You've still got a problem where you've got a LONG sleep, and that sleep call blocks the entire thread, so you can't cancel it for minutes.  Have your worker.run() create a QTimer (so it's in the thread event loop not the main GUI event loop), and use that QTimer to signal another slot on your worker that it's time to wake up.  Now there's no long sleep() blocking, just events.  Which means that when you call thread.quit() it will emit finished (which you can connect to your worker for any shutdown actions) and then stop the thread regardless of how much time is left on the timer.

All that said, if all you were trying to do here is what you're doing here, you could just use a QTimer in the main thread and avoid the whole multithreading thing entirely, but I assume this was just a demo of some grander scheme.

Body:
I read this article about Threading in PyQt and tried to implement it into my own program. I am now able to start a thread, but when I close the window I think the other thread keeps running. I also can't use ctrl+c to interrupt the program. So how do I stop this my thread, that sends the notifications? Here's my code:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QRunnable, pyqtSlot, QThreadPool
import notify2
import time

class StartTimer(QRunnable):
    '''
    StartTimer thread
    '''

    def __init__(self, minutes):
        super(StartTimer, self).__init__()
        self.minutes = minutes

    @pyqtSlot()
    def run(self):
        notify2.init('Break Timer')
        notification = notify2.Notification(
            'Success!', 'Break Timer has been started.')
        notification.show()

        self.start = True

        while self.start:
            time.sleep(self.minutes * 60)

            notify2.init('Break Timer')
            notification = notify2.Notification(
                'Pause for 1 minute', 'Move and see away from the screen!')
            notification.show()

        time.sleep(5)

class Ui_break_timer_ui(object):

    def __init__(self):
        self.threadpool = QThreadPool()
        self.start = False

    def start_btn_pressed(self):
        self.start_timer = StartTimer(self.spinBox_minutes.value())
        self.threadpool.start(self.start_timer)

    def stop_timer(self):
        notify2.init('Break Timer')
        notification = notify2.Notification(
            'Program ended', 'You will receive no further notifications.')
        notification.show()

        self.start = False

    def setupUi(self, break_timer_ui):
        break_timer_ui.setObjectName("break_timer_ui")
        break_timer_ui.setWindowIcon(QtGui.QIcon('icon.png'))
        break_timer_ui.resize(596, 412)
        self.centralwidget = QtWidgets.QWidget(break_timer_ui)
        self.centralwidget.setObjectName("centralwidget")
        self.btn_start = QtWidgets.QPushButton(self.centralwidget)
        self.btn_start.setGeometry(QtCore.QRect(490, 350, 88, 34))
        self.btn_start.setObjectName("btn_start")
        self.btn_stop = QtWidgets.QPushButton(self.centralwidget)
        self.btn_stop.setGeometry(QtCore.QRect(390, 350, 88, 34))
        self.btn_stop.setObjectName("btn_stop")
        self.label_set_interval = QtWidgets.QLabel(self.centralwidget)
        self.label_set_interval.setGeometry(QtCore.QRect(20, 20, 91, 18))
        self.label_set_interval.setObjectName("label_set_interval")
        self.spinBox_minutes = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBox_minutes.setGeometry(QtCore.QRect(20, 50, 52, 32))
        self.spinBox_minutes.setMinimum(1)
        self.spinBox_minutes.setMaximum(240)
        self.spinBox_minutes.setProperty("value", 30)
        self.spinBox_minutes.setObjectName("spinBox_minutes")
        self.label_minutes = QtWidgets.QLabel(self.centralwidget)
        self.label_minutes.setGeometry(QtCore.QRect(80, 60, 58, 18))
        self.label_minutes.setObjectName("label_minutes")
        break_timer_ui.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(break_timer_ui)
        self.statusbar.setObjectName("statusbar")
        break_timer_ui.setStatusBar(self.statusbar)

        self.btn_stop.clicked.connect(lambda _: self.stop_timer())

        self.btn_start.clicked.connect(lambda _: self.start_btn_pressed())

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

    def retranslateUi(self, break_timer_ui):
        _translate = QtCore.QCoreApplication.translate
        break_timer_ui.setWindowTitle(
            _translate("break_timer_ui", "Break Timer"))
        self.btn_start.setText(_translate("break_timer_ui", "Start"))
        self.btn_stop.setText(_translate("break_timer_ui", "Stop"))
        self.label_set_interval.setText(
            _translate("break_timer_ui", "Set interval"))
        self.label_minutes.setText(_translate("break_timer_ui", "minutes"))

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


来源: stackexchange

问:
Can we give a Sequence Id for rows in Spark?
I am new to spark and I have around 10000 rows in a datafile to read

```<code>SparkSession sessionSpark = SparkSession
            .builder()
            .config(sparkConf)
            .getOrCreate();

Dataset<Row> dataset = sessionSpark.read.parquet("s3://databucket/files/")

</code>```

I have a usecase to add a row number to every row in the dataset , the row number should start from 1 to 10000 (since the file has 10000 records ) , is it possible to assign a row number and we know spark shuffles the data but let's say even after rerunning the same file twice from the application , the row number generated should be the same , is it possible to do ?

答:
Not in Java as I do not specialize in that, but in Scala. Should be easy enough to convert for you. Just an example I have using DS with case classes:

```<code>import org.apache.spark.sql.functions._
import org.apache.spark.sql.{Encoder, Encoders}
import spark.implicits._

// Gen some example data via DF, can come from files, ordering in those files assumed. I.e. no need to sort.
val df = Seq(
  ("1 February"), ("n"), ("c"), ("b"),
  ("2 February"), ("hh"), ("www"), ("e"),
  ("3 February"), ("y"), ("s"), ("j"),
  ("1 March"), ("c"), ("b"), ("x"),
  ("1 March"), ("c"), ("b"), ("x"),
  ("2 March"), ("c"), ("b"), ("x"),
  ("3 March"), ("c"), ("b"), ("x"), ("y"), ("z")
           ).toDF("line")

// Define Case Classes to avoid Row aspects on df --> rdd --> to DF.
case class X(line: String)
case class Xtra(key: Long, line: String)

// Add the Seq Num using zipWithIndex. Then convert back, but will have a struct to deal wit.
// You can avoid the struct if using Row and such. But general idea should be clear.
val rdd = df.as[X].rdd.zipWithIndex().map{case (v,k) => (k,v)}
val ds = rdd.toDF("key", "line").as[Xtra]
ds.show(100,false)
</code>```

returns:

```<code>+---+------------+
|key|line        |
+---+------------+
|0  |[1 February]|
|1  |[n]         |
|2  |[c]         |
...
</code>```

The answers to-date do not meet the needs as question provide but if only 10K rows then the single partition is not an issue. Although for 10K rows one has to ask a few questions.

If you don't mind Row, here is another approach:

```<code>import org.apache.spark.sql.Row
import org.apache.spark.sql.types.{StructField,StructType,IntegerType, ArrayType, LongType}

val df = sc.parallelize(Seq((1.0, 2.0), (0.0, -1.0), (3.0, 4.0), (6.0, -2.3))).toDF("x", "y")
val newSchema = StructType(df.schema.fields ++ Array(StructField("rowid", LongType, false)))

val rddWithId = df.rdd.zipWithIndex
val dfZippedWithId =  spark.createDataFrame(rddWithId.map{ case (row, index) => Row.fromSeq(row.toSeq ++ Array(index))}, newSchema)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to spark and I have around 10000 rows in a datafile to read

SparkSession sessionSpark = SparkSession
            .builder()
            .config(sparkConf)
            .getOrCreate();

Dataset<Row> dataset = sessionSpark.read.parquet("s3://databucket/files/")

I have a usecase to add a row number to every row in the dataset , the row number should start from 1 to 10000 (since the file has 10000 records ) , is it possible to assign a row number and we know spark shuffles the data but let's say even after rerunning the same file twice from the application , the row number generated should be the same , is it possible to do ?

Body:
Not in Java as I do not specialize in that, but in Scala. Should be easy enough to convert for you. Just an example I have using DS with case classes:

import org.apache.spark.sql.functions._
import org.apache.spark.sql.{Encoder, Encoders}
import spark.implicits._

// Gen some example data via DF, can come from files, ordering in those files assumed. I.e. no need to sort.
val df = Seq(
  ("1 February"), ("n"), ("c"), ("b"),
  ("2 February"), ("hh"), ("www"), ("e"),
  ("3 February"), ("y"), ("s"), ("j"),
  ("1 March"), ("c"), ("b"), ("x"),
  ("1 March"), ("c"), ("b"), ("x"),
  ("2 March"), ("c"), ("b"), ("x"),
  ("3 March"), ("c"), ("b"), ("x"), ("y"), ("z")
           ).toDF("line")

// Define Case Classes to avoid Row aspects on df --> rdd --> to DF.
case class X(line: String)
case class Xtra(key: Long, line: String)

// Add the Seq Num using zipWithIndex. Then convert back, but will have a struct to deal wit.
// You can avoid the struct if using Row and such. But general idea should be clear.
val rdd = df.as[X].rdd.zipWithIndex().map{case (v,k) => (k,v)}
val ds = rdd.toDF("key", "line").as[Xtra]
ds.show(100,false)

returns:

+---+------------+
|key|line        |
+---+------------+
|0  |[1 February]|
|1  |[n]         |
|2  |[c]         |
...

The answers to-date do not meet the needs as question provide but if only 10K rows then the single partition is not an issue. Although for 10K rows one has to ask a few questions.

If you don't mind Row, here is another approach:

import org.apache.spark.sql.Row
import org.apache.spark.sql.types.{StructField,StructType,IntegerType, ArrayType, LongType}

val df = sc.parallelize(Seq((1.0, 2.0), (0.0, -1.0), (3.0, 4.0), (6.0, -2.3))).toDF("x", "y")
val newSchema = StructType(df.schema.fields ++ Array(StructField("rowid", LongType, false)))

val rddWithId = df.rdd.zipWithIndex
val dfZippedWithId =  spark.createDataFrame(rddWithId.map{ case (row, index) => Row.fromSeq(row.toSeq ++ Array(index))}, newSchema)


问:
Why do undefined constants evaluate to true?
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

```<code><?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>
</code>```

The above example prints 'Huh?'

Thanks so much for your help! :)

答:
From the manual:

If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs "CONSTANT").

Basically, if WHATEVER_THIS_ISNT_DEFINED isn't defined, PHP interprets it as "WHATEVER_THIS_ISNT_DEFINED".  Non-empty strings evaluate to true, so your expression will always pass (unless WHATEVER_THIS_ISNT_DEFINED is defined and set to a falsey value.)

This is, frankly, stupid behaviour. It was implemented, I believe, to allow things like $foo[bar] to work when the programmer should have used $foo['bar']. It's illogical behaviour like this that makes people think PHP isn't a real programming language.

The way to test whether a constant is defined is with defined.

ContentLicense: CC BY-SA 3.0

Body:
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

<?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>

The above example prints 'Huh?'

Thanks so much for your help! :)


问:
How to properly handle the case when Cosmos DB emulator is not running?
I have a few Unit Tests (C#) that initialize a database and two collections with random data for the testing in the Cosmos DB emulator. My problem is that when I have not already started the emulator (or if I close it when the tests are running) the tests just hang.

My goal is to get an error message when something like this happens, instead of waiting blindly. Can this be done and how?

My tests get stuck in the following command:

```<code>DocumentClient
    .CreateDatabaseIfNotExistsAsync(ValidCosmoConfig.Database)
    .GetAwaiter()
    .GetResult();
</code>```

答:
When I try connecting to the emulator when it isn't running I see a Microsoft.Azure.Cosmos.CosmosException thrown with message
"Response status code does not indicate success: InternalServerError (500); Substatus: 0; ActivityId: 00000000-0000-0000-0000-000000000000; Reason: (No connection could be made because the target machine actively refused it.);".

The inner exception is a System.Net.Sockets.SocketException (message "No connection could be made because the target machine actively refused it.").

Depending on your unit testing library it may be possible, in the case of this error to completely abort when this case is detected.

Body:
I have a few Unit Tests (C#) that initialize a database and two collections with random data for the testing in the Cosmos DB emulator. My problem is that when I have not already started the emulator (or if I close it when the tests are running) the tests just hang.

My goal is to get an error message when something like this happens, instead of waiting blindly. Can this be done and how?

My tests get stuck in the following command:

DocumentClient
    .CreateDatabaseIfNotExistsAsync(ValidCosmoConfig.Database)
    .GetAwaiter()
    .GetResult();


答:
You can try to merge the tables? Try this to see if it gives you what you need?

df <- df %>% distinct(sub_date)
answer <- merge(periods, df, all = TRUE)

Title: Full Join in dplyr

Body:
I have a dataframe looking like:

library(tidyverse)
df <- tibble::tribble(
        ~sub_date, ~period,
        "2019-01",       1,
        "2019-01",       2,
        "2019-01",       3,
        "2019-02",       1,
        "2019-02",       2,
        "2019-03",       1,
        "2019-03",       2,
        "2019-03",       3,
        "2019-03",       4
        )

  sub_date period
  <chr>     <dbl>
1 2019-01       1
2 2019-01       2
3 2019-01       3
4 2019-02       1
5 2019-02       2
6 2019-03       1
7 2019-03       2
8 2019-03       3
9 2019-03       4

and another:

period <- tibble::tribble(
            ~period, ~forecast,
                  1,        10,
                  2,        20,
                  3,        30,
                  4,        40,
                  5,        50,
                  6,        60,
                  7,        70
            )

  period forecast
   <dbl>    <dbl>
1      1       10
2      2       20
3      3       30
4      4       40
5      5       50
6      6       60
7      7       70

I am struggling to join them in a way that in df I can fill the missing periods in the table period, aka the number of rows in period X the different sub_date in df.

as follows:

df_output <- tibble::tribble(
               ~sub_date, ~period, ~forecast,
               "2019-01",       1,        10,
               "2019-01",       2,        20,
               "2019-01",       3,        30,
               "2019-01",       4,        40,
               "2019-01",       5,        50,
               "2019-01",       6,        60,
               "2019-01",       7,        70,
               "2019-02",       1,        10,
               "2019-02",       2,        20,
               "2019-02",       3,        30,
               "2019-02",       4,        40,
               "2019-02",       5,        50,
               "2019-02",       6,        60,
               "2019-02",       7,        70,
               "2019-03",       1,        10,
               "2019-03",       2,        20,
               "2019-03",       3,        30,
               "2019-03",       4,        40,
               "2019-03",       5,        50,
               "2019-03",       6,        60,
               "2019-03",       7,        70
               )

# A tibble: 21 x 3
   sub_date period forecast
   <chr>     <dbl>    <dbl>
 1 2019-01       1       10
 2 2019-01       2       20
 3 2019-01       3       30
 4 2019-01       4       40
 5 2019-01       5       50
 6 2019-01       6       60
 7 2019-01       7       70
 8 2019-02       1       10
 9 2019-02       2       20
10 2019-02       3       30
# … with 11 more rows

I assumed it was a full join but I don't get the desired result.

Any help?


问:
Do not include drawableLeft when aligning items
I have Two textViews, one under another, like this:

and this is how it looks from code

```<code>   <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/ic_some_sign"
        android:text="Some text in here" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="June 2015" />
</code>```

What I want is to move red circle out of alignment, so two views would be aligned only by text.

so it would look like this:

I can add an ImageVIew and it would do the trick, but I'm curious if there is any other way.

Thanks

答:
You can use two linear layouts. One for red circle and text views. Another for two text views.</p>

```<code> <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

  <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <ImageView
            android:layout_width="20dp"
            android:layout_height="20dp"
            app:srcCompat="@drawable/ic_red_circle"
            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Some text in here" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="June 2015" />

        </LinearLayout>

    </LinearLayout>

   </RelativeLayout>
</code>```

Body:
I have Two textViews, one under another, like this:

and this is how it looks from code

   <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/ic_some_sign"
        android:text="Some text in here" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="June 2015" />

What I want is to move red circle out of alignment, so two views would be aligned only by text.

so it would look like this:

I can add an ImageVIew and it would do the trick, but I'm curious if there is any other way.

Thanks

Body:
You can use two linear layouts. One for red circle and text views. Another for two text views.

 <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

  <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <ImageView
            android:layout_width="20dp"
            android:layout_height="20dp"
            app:srcCompat="@drawable/ic_red_circle"
            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Some text in here" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="June 2015" />

        </LinearLayout>

    </LinearLayout>

   </RelativeLayout>


问:
Remove Spacing or Padding in android Spinner
I'm using android spinner and edittext from support lib v21. I would like to align text to left the same like edittext as shown in figure. But, deafult spinner include spacing or padding. So, I would like to remove it to align text to left. Please help how to remove it.

答:
This Kotlin code is a little bit more succinct than the getView override in another answer.
It makes it a bit more clear in fewer lines that it is mostly just doing what super does, except that it also overrides setPaddingfor the left value.

```<code>override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
    return super.getView(position, convertView, parent).apply {
        setPadding(0, paddingTop, paddingRight, paddingBottom)
    }
}
</code>```

Here is my full fragment code that uses a data binding object for the complete spinner array adapter override, which also does a selected item and an alternating background color in getDropDownView:

```<code>binding.editSpinner.apply {
    this.context ?: return@apply
    this.adapter = object : ArrayAdapter<Any>(
        requireContext(),
        android.R.layout.simple_spinner_dropdown_item,
        SpinnerTypeValues.values().map { it.text }
    ) {
        override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
            return super.getDropDownView(position, convertView, parent).also {
                when {
                    position == this@apply.selectedItemPosition -> it.setBackgroundColor( Color.rgb(245, 212, 119) )
                    position % 2 == 0 -> it.setBackgroundColor(Color.rgb(240, 240, 240))
                    else -> it.setBackgroundColor(Color.rgb(214, 235, 189))
                }
            }
        }
        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            return super.getView(position, convertView, parent).apply {
                setPadding(0, paddingTop, paddingRight, paddingBottom)
            }
        }
    }
    this.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {}
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            viewModel.saveSpinnerSelection(position)
        }
    }
}
</code>```

Body:
This Kotlin code is a little bit more succinct than the getView override in another answer.
It makes it a bit more clear in fewer lines that it is mostly just doing what super does, except that it also overrides setPaddingfor the left value.

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
    return super.getView(position, convertView, parent).apply {
        setPadding(0, paddingTop, paddingRight, paddingBottom)
    }
}

Here is my full fragment code that uses a data binding object for the complete spinner array adapter override, which also does a selected item and an alternating background color in getDropDownView:

binding.editSpinner.apply {
    this.context ?: return@apply
    this.adapter = object : ArrayAdapter<Any>(
        requireContext(),
        android.R.layout.simple_spinner_dropdown_item,
        SpinnerTypeValues.values().map { it.text }
    ) {
        override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
            return super.getDropDownView(position, convertView, parent).also {
                when {
                    position == this@apply.selectedItemPosition -> it.setBackgroundColor( Color.rgb(245, 212, 119) )
                    position % 2 == 0 -> it.setBackgroundColor(Color.rgb(240, 240, 240))
                    else -> it.setBackgroundColor(Color.rgb(214, 235, 189))
                }
            }
        }
        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            return super.getView(position, convertView, parent).apply {
                setPadding(0, paddingTop, paddingRight, paddingBottom)
            }
        }
    }
    this.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {}
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            viewModel.saveSpinnerSelection(position)
        }
    }
}


问:
Mongoose: automatically embed field upon create?
Say I have one model, Book, and another model, Genre. When I create the book, I'd like to be able to pass a Genre ID and have the model automatically fetch and embed the document. For example:

const bookSchema = new Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: String,
    required: true,
  },
  genre: {
    type: ObjectId,
    required: true,
  }
});

const genreSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
});
```

<p>Then I'd like to be create a book as follows:</p>

<pre class="lang-js prettyprint-override"><code>const Book = await Book.create({
  title: 'Lord of the Rings',
  author: 'J. R. R. Tolkien',
  genre: '5d6ede6a0ba62570afcedd3a',
});
</code>```

That would create a book and automatically embed the genre document from the given ID. Is there a way to do that from within the schema, or would I have to wrap it in additional logic?

答:
If I understand your question correctly I think what you're looking for is populate. https://mongoosejs.com/docs/populate.html

It would change your schema to look like the following

```<code>const bookSchema = new Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: String,
    required: true,
  },
  genre: {
    type: Schema.Types.ObjectId,
    ref: 'Genre',
    required: true,
  }
});

const genreSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
});
</code>```

When you get your book you can reference the genre by doing this

```<code>Book.find()
  .populate('genre')
</code>```

Hopefully, that answered your question!

Body:
Say I have one model, Book, and another model, Genre. When I create the book, I'd like to be able to pass a Genre ID and have the model automatically fetch and embed the document. For example:

const bookSchema = new Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: String,
    required: true,
  },
  genre: {
    type: ObjectId,
    required: true,
  }
});

const genreSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
});

Then I'd like to be create a book as follows:

const Book = await Book.create({
  title: 'Lord of the Rings',
  author: 'J. R. R. Tolkien',
  genre: '5d6ede6a0ba62570afcedd3a',
});

That would create a book and automatically embed the genre document from the given ID. Is there a way to do that from within the schema, or would I have to wrap it in additional logic?

Body:
If I understand your question correctly I think what you're looking for is populate. https://mongoosejs.com/docs/populate.html

It would change your schema to look like the following

const bookSchema = new Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: String,
    required: true,
  },
  genre: {
    type: Schema.Types.ObjectId,
    ref: 'Genre',
    required: true,
  }
});

const genreSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
});

When you get your book you can reference the genre by doing this

Book.find()
  .populate('genre')

Hopefully, that answered your question!


问:
Connection Mongo with Robot 3t
I tried to connect to Mongodb with Robot 3t on 5000 port.
But when I tried to connect me I have an error and I don't understand why.

I hope that someone could help me...
this is my configuration

This is my error

答:
Have you start MongoDB service at 5000 port if not so connect it to 27017 port.
MongoDB service has default port i.e. 27017</p>

Title: Connection Mongo with Robot 3t


问:
Error running Stern to look at microk8s logs
I’m getting an error when running stern  as it didn’t have a config file. I gave it the .kube/config file but this errors, “..signed by an unknown authority” I need to generate a new config file for Stern to run on microk8s.kubectrl but can’t find anything.</p>

答: I did that, the issues turns out to be that Stern does not like my self signed certs.</p>


问:
Calculate total number of orders in different statuses
I want to create simple dashboard where I want to show the number of orders in different statuses. The  statuses can be New/Cancelled/Finished/etc

Where should I implement these criteria? If I add filter in the Cube Browser then it applies for the whole dashboard. Should I do that in KPI? Or should I add calculated column with 1/0 values?

My expected output is something like:

```<code>--------------------------------------
| Total | New | Finished | Cancelled |
--------------------------------------
| 1000  | 100 |    800   |   100     |
--------------------------------------
</code>```

答:
I'd use measures for that, something like:</p>

```<code>CountTotal = COUNT('Orders'[OrderID])
CountNew = CALCULATE(COUNT('Orders'[OrderID]), 'Orders'[Status] = "New")
CountFinished = CALCULATE(COUNT('Orders'[OrderID]), 'Orders'[Status] = "Finished")
CountCancelled = CALCULATE(COUNT('Orders'[OrderID]), 'Orders'[Status] = "Cancelled")
</code>```

Body:
I want to create simple dashboard where I want to show the number of orders in different statuses. The  statuses can be New/Cancelled/Finished/etc

Where should I implement these criteria? If I add filter in the Cube Browser then it applies for the whole dashboard. Should I do that in KPI? Or should I add calculated column with 1/0 values?

My expected output is something like:

--------------------------------------
| Total | New | Finished | Cancelled |
--------------------------------------
| 1000  | 100 |    800   |   100     |
--------------------------------------

Body:
I'd use measures for that, something like:

CountTotal = COUNT('Orders'[OrderID])
CountNew = CALCULATE(COUNT('Orders'[OrderID]), 'Orders'[Status] = "New")
CountFinished = CALCULATE(COUNT('Orders'[OrderID]), 'Orders'[Status] = "Finished")
CountCancelled = CALCULATE(COUNT('Orders'[OrderID]), 'Orders'[Status] = "Cancelled")


问:
How to automate this process?
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}
</code>```

In the Terminal, after getting the html file converted, I write:

```<code>script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt
</code>```

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.

答:
Try replacing line 6 (my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");) with this:

```<code>my $tree = HTML::TreeBuilder->new;
$tree->parse_file("chpt15Intro.htm");
</code>```

The CPAN docs for HTML::TreeBuilder don't mention what the return value of parse_file is, if any, but I suspect that it's not the instance that the method was called on. This means that after the call, your $tree variable isn't anything meaningful.

Title: How to automate this process?

Body:
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}

In the Terminal, after getting the html file converted, I write:

script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.

Body:
Try replacing line 6 (my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");) with this:

my $tree = HTML::TreeBuilder->new;
$tree->parse_file("chpt15Intro.htm");

The CPAN docs for HTML::TreeBuilder don't mention what the return value of parse_file is, if any, but I suspect that it's not the instance that the method was called on. This means that after the call, your $tree variable isn't anything meaningful.


问:
Python Output Snowflake Connector To CSV
I currently am trying to print the output of a snowflake connector query and write it to csv, but I'm having issues doing this. Currently, my code example looks like:

```<code>query = '''SELECT TOP 10 * FROM TABLE;'''

conn = snowflake.connector.connect(user='XXXX',
                                   password='XXXX',
                                   account='XXXX')

query_output = conn.cursor().execute(query)
</code>```

Is there a way for me to print the output of the query, like maybe print(query_output) and then also write it to csv like query_output.to_csv(path)?

答:
You can use this to print the results. To save it in csv, just save the results in a dataframe using for loop and then use df.to_csv</p>

```<code>    cursor.execute(query)
    sql_result = cursor.fetchall()
    print(sql_result)     ## just print the results or use the for loop below to print the results row by row
    for row in sql_result:
        print(row)
</code>```

Body:
I currently am trying to print the output of a snowflake connector query and write it to csv, but I'm having issues doing this. Currently, my code example looks like:

query = '''SELECT TOP 10 * FROM TABLE;'''

conn = snowflake.connector.connect(user='XXXX',
                                   password='XXXX',
                                   account='XXXX')

query_output = conn.cursor().execute(query)

Is there a way for me to print the output of the query, like maybe print(query_output) and then also write it to csv like query_output.to_csv(path)?

Body:
You can use this to print the results. To save it in csv, just save the results in a dataframe using for loop and then use df.to_csv

    cursor.execute(query)
    sql_result = cursor.fetchall()
    print(sql_result)     ## just print the results or use the for loop below to print the results row by row
    for row in sql_result:
        print(row)


问:
VerifyError: Verifier rejected class ... 'this' arg must be initialized
after third-party library upgrade I got a new crash on app launch:

```<code>java.lang.VerifyError: Verifier rejected class ly.img.android.e: void ly.img.android.e.<init>(java.lang.String, boolean) failed to verify: void ly.img.android.e.<init>(java.lang.String, boolean): [0x5C] 'this' arg must be initialized (declaration of 'ly.img.android.e' appears in base.apk!classes2.dex)
    at ly.img.android.b.<clinit>(Unknown Source:46)
    at ly.img.android.c.b(Unknown Source:0)
    at ly.img.android.PESDK.initSDK(Unknown Source:0)
    at ly.img.android.IMGLYAutoInit.onCreate(IMGLYAutoInit.java:41)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:2092)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:2066)
    at android.app.ActivityThread.installProvider(ActivityThread.java:6983)
    at android.app.ActivityThread.installContentProviders(ActivityThread.java:6528)
</code>```

Yes, I know that there are a lot of similar problems there but I didn't find any solution or advise for me.

So, maybe someone there can provide hint or advise for me what's wrong there. Thanks

答:
Others were also facing this kind of issue, I think this can help you! ⛅

java.lang.VerifyError: Verifier rejected class ly.img.android.e: void ly.img.android.e.<init>(java.lang.String, boolean) failed to verify: void ly.img.android.e.<init>(java.lang.String, boolean): [0x5C] 'this' arg must be initialized (declaration of 'ly.img.android.e' appears in base.apk!classes2.dex)

But according to a GitHub thread they found a solution to this problem

https://github.com/CleverTap/clevertap-android-sdk/issues/15#issuecomment-454842450

The fix for this issue is available for AGP(Android Gradle Plugin) 3.3 (and 3.4) by setting an explicit dependency detailed below.
  After AGP 3.3.1 is released, remove the pinned version to allow you to pick up new D8/R8 releases again.

For AGP 3.3 amend your top-level build.gradle file with:

```<code>buildscript {
    repositories {
        maven {
            url "http://storage.googleapis.com/r8-releases/raw" // ADD THIS.
        }
    }
    dependencies {
        classpath 'com.android.tools:r8:1.3.52'  // ADD THIS. Must be before the Gradle Plugin for Android.
        classpath 'com.android.tools.build:gradle:3.3'
    }
}
</code>```

For AGP 3.4 the r8 version should be 1.4.25

Body:
after third-party library upgrade I got a new crash on app launch:

java.lang.VerifyError: Verifier rejected class ly.img.android.e: void ly.img.android.e.<init>(java.lang.String, boolean) failed to verify: void ly.img.android.e.<init>(java.lang.String, boolean): [0x5C] 'this' arg must be initialized (declaration of 'ly.img.android.e' appears in base.apk!classes2.dex)
    at ly.img.android.b.<clinit>(Unknown Source:46)
    at ly.img.android.c.b(Unknown Source:0)
    at ly.img.android.PESDK.initSDK(Unknown Source:0)
    at ly.img.android.IMGLYAutoInit.onCreate(IMGLYAutoInit.java:41)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:2092)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:2066)
    at android.app.ActivityThread.installProvider(ActivityThread.java:6983)
    at android.app.ActivityThread.installContentProviders(ActivityThread.java:6528)

Yes, I know that there are a lot of similar problems there but I didn't find any solution or advise for me.

So, maybe someone there can provide hint or advise for me what's wrong there. Thanks

Body:
Others were also facing this kind of issue, I think this can help you! ⛅

java.lang.VerifyError: Verifier rejected class ly.img.android.e: void ly.img.android.e.<init>(java.lang.String, boolean) failed to verify: void ly.img.android.e.<init>(java.lang.String, boolean): [0x5C] 'this' arg must be initialized (declaration of 'ly.img.android.e' appears in base.apk!classes2.dex)

But according to a GitHub thread they found a solution to this problem

https://github.com/CleverTap/clevertap-android-sdk/issues/15#issuecomment-454842450

The fix for this issue is available for AGP(Android Gradle Plugin) 3.3 (and 3.4) by setting an explicit dependency detailed below.
  After AGP 3.3.1 is released, remove the pinned version to allow you to pick up new D8/R8 releases again.

For AGP 3.3 amend your top-level build.gradle file with:

buildscript {
    repositories {
        maven {
            url "http://storage.googleapis.com/r8-releases/raw" // ADD THIS.
        }
    }
    dependencies {
        classpath 'com.android.tools:r8:1.3.52'  // ADD THIS. Must be before the Gradle Plugin for Android.
        classpath 'com.android.tools.build:gradle:3.3'
    }
}

For AGP 3.4 the r8 version should be 1.4.25


问:
Flutter Accidentaly deleted pubspec.yaml file, getting "Target of URI doesn't exist" error
I deleted pubspec.yaml by accident, but I put it back to the app folder, but I cannot build my app. Im constantly getting "Target of URI doesn't exist" error. Running flutter pub get works fine but doesn't help.</p>

答:
Answer:

Make sure while you don't have any additional copies of .packages and pubspec.lock files. Its best to just delete all .packages and pubspec.lock files and leave just pubspec.yaml and then run flutter pub get


问:
Django and bootstrap, why my widget does not work?
I have the following html's boostrap code:

```<code> <div class="input-group date col-2" id="datetimepicker1" data-target-input="nearest">
    {{form.data_contabile|as_crispy_field}}
 <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
 <div class="input-group-text"><i class="far fa-clock"></i></div>
 </div>
 </div>

    <script>
      $(function () {
        $("#datetimepicker1").datetimepicker({
          format: 'DD/MM/YYYY',
        });
      });
    </script>
</code>```

And in my form the following code:

```<code>class MaterialeForm(forms.ModelForm):

class Meta:
    model = Materiale
    fields = "__all__"
    exclude = ['iva_amount']
    widgets = {'data_contabile': forms.DateTimeInput(attrs={ 'type':'text',
                                                             'class':'form-control datetimepicker-input',
                                                             'data-target': '#datetimepicker1'})}
</code>```

and finally my models:

```<code>class Materiale(models.Model):
    data_contabile=models.DateField('Data di acquisto', default="GG/MM/YYYY")
</code>```

But the layout are the following:

Where is the error?

答:
Acc to the datetimepicker documentation here you should call datetimepicker function on the id of element and not data-target of your element. Either you change your Model Form attributes like this:

```<code>class Meta:
model = Materiale
fields = "__all__"
exclude = ['iva_amount']
widgets = {'data_contabile': forms.DateTimeInput(attrs={ 'type':'text',
                                                         'class':'form-control datetimepicker-input',
                                                         'id': 'datetimepicker1'})}
</code>```

This should work like this

or

You can change your can change your selector to call datetimepicker jquery function on element with data-target attribute like this:

```<code>$('[data-target=#datetimepicker1]').datetimepicker({
      format: 'DD/MM/YYYY',
    });
</code>```

Either way this should work.

Body:
I have the following html's boostrap code:

    {{form.data_contabile|as_crispy_field}}

And in my form the following code:

class MaterialeForm(forms.ModelForm):

class Meta:
    model = Materiale
    fields = "__all__"
    exclude = ['iva_amount']
    widgets = {'data_contabile': forms.DateTimeInput(attrs={ 'type':'text',
                                                             'class':'form-control datetimepicker-input',
                                                             'data-target': '#datetimepicker1'})}

and finally my models:

class Materiale(models.Model):
    data_contabile=models.DateField('Data di acquisto', default="GG/MM/YYYY")

But the layout are the following:

Where is the error?

Body:
Acc to the datetimepicker documentation here you should call datetimepicker function on the id of element and not data-target of your element. Either you change your Model Form attributes like this:

class Meta:
model = Materiale
fields = "__all__"
exclude = ['iva_amount']
widgets = {'data_contabile': forms.DateTimeInput(attrs={ 'type':'text',
                                                         'class':'form-control datetimepicker-input',
                                                         'id': 'datetimepicker1'})}

This should work like this

or

You can change your can change your selector to call datetimepicker jquery function on element with data-target attribute like this:

$('[data-target=#datetimepicker1]').datetimepicker({
      format: 'DD/MM/YYYY',
    });

Either way this should work.


问:
List sieve of eratosthenes
here a program that find a primary numbers in array from n to 2n. it works properly, but something must be otherwise:
In this program, the sieve is superimposed on the array: the elements are replaced by zeros. It should be wrong: no arrays. First, form a list of all the numbers one by one in the link list. Then remove from the list those links that contain multiples. At the end, print what is left. IDK how can i do this without arrays.</p>

```<code>#include <iostream>
using namespace std;

struct node
{
    int num;
    node* next, * prev;
};

class List  // list
{
    node* head, * tail;
public:
    List() :head(NULL), tail(NULL) {};
    void Print();
    void Add(int num);
};

void List::Print() //print list
{
    node* temp = head;

    while (temp != NULL)
    {
        cout << temp->num << " ";
        temp = temp->next;
    }
    cout << endl;
}

void List::Add(int num)  //add to list
{
    node* temp = new node;
    temp->next = NULL;
    temp->num = num;
    if (head!=NULL)
    {
        temp->prev = tail;
        tail->next = temp;
        tail = temp;
    }
    else
    {
        temp->prev = NULL;
        head = tail = temp;
    }
}

int main()
{

    List list;
    int n, num;
        cout << "Enter N :  "; cin >> n;
        n = abs(n);
    int* simp = new int[2 * n];
    // eratosphene's sieve
    for (int i = 0; i < 2 * n; i++) {
        simp[i] = i;
    }
    simp[1] = 0;
    for (int l = 2; l < 2 * n; l++) {
        if (simp[l] != 0) {
            for (int j = l * 2; j < 2 * n; j += l) {
                simp[j] = 0;
            }
        }
    }
    for (int i = n; i < 2 * n; i++) {
        if (simp[i]) {
            num = simp[i];
            list.Add(num);
        }
    }
    cout << "Prime numbers of the list:\n";
    list.Print();
    return 0;
}
</code>```

答:
No, nothing wrong with your program, but it's just lost some efficiency of the sieve of eratosthenes. The problem is your sieve inner loop and outer loop bounds should look as follows.

```<code>// upper bound = sqrt(2 * n) rather than (2 * n)

// l < (2 * n) -----> [ l*l < 2 * n is same as l < sqrt(2 * n) ]
for (int l = 2; l*l < 2 * n; l++) {
    if (simp[l] != 0) {

        // lower bound = l * l rather than (2 * l)
        for (int j = l * l; j < 2 * n; j += l) {
            simp[j] = 0;
        }
    }
}
</code>```

For the inner loop as (2*l) always less than (l*l) except case of 2 (2 * l) = (l * l) so no difference, but just useless iterations.

Title: List sieve of eratosthenes

Body:
here a program that find a primary numbers in array from n to 2n. it works properly, but something must be otherwise:
In this program, the sieve is superimposed on the array: the elements are replaced by zeros. It should be wrong: no arrays. First, form a list of all the numbers one by one in the link list. Then remove from the list those links that contain multiples. At the end, print what is left. IDK how can i do this without arrays.

#include <iostream>
using namespace std;

struct node
{
    int num;
    node* next, * prev;
};

class List  // list
{
    node* head, * tail;
public:
    List() :head(NULL), tail(NULL) {};
    void Print();
    void Add(int num);
};

void List::Print() //print list
{
    node* temp = head;

    while (temp != NULL)
    {
        cout << temp->num << " ";
        temp = temp->next;
    }
    cout << endl;
}

void List::Add(int num)  //add to list
{
    node* temp = new node;
    temp->next = NULL;
    temp->num = num;
    if (head!=NULL)
    {
        temp->prev = tail;
        tail->next = temp;
        tail = temp;
    }
    else
    {
        temp->prev = NULL;
        head = tail = temp;
    }
}

int main()
{

    List list;
    int n, num;
        cout << "Enter N :  "; cin >> n;
        n = abs(n);
    int* simp = new int[2 * n];
    // eratosphene's sieve
    for (int i = 0; i < 2 * n; i++) {
        simp[i] = i;
    }
    simp[1] = 0;
    for (int l = 2; l < 2 * n; l++) {
        if (simp[l] != 0) {
            for (int j = l * 2; j < 2 * n; j += l) {
                simp[j] = 0;
            }
        }
    }
    for (int i = n; i < 2 * n; i++) {
        if (simp[i]) {
            num = simp[i];
            list.Add(num);
        }
    }
    cout << "Prime numbers of the list:\n";
    list.Print();
    return 0;
}

Body:
No, nothing wrong with your program, but it's just lost some efficiency of the sieve of eratosthenes. The problem is your sieve inner loop and outer loop bounds should look as follows.

// upper bound = sqrt(2 * n) rather than (2 * n)

// l < (2 * n) -----> [ l*l < 2 * n is same as l < sqrt(2 * n) ]
for (int l = 2; l*l < 2 * n; l++) {
    if (simp[l] != 0) {

        // lower bound = l * l rather than (2 * l)
        for (int j = l * l; j < 2 * n; j += l) {
            simp[j] = 0;
        }
    }
}

For the inner loop as (2*l) always less than (l*l) except case of 2 (2 * l) = (l * l) so no difference, but just useless iterations.


问:
Creating a list or tuple out of one word-per-line in vim
I come across the following pattern quite frequently, where I have to copy-paste a bunch of items (usually in excel) into something like a SQL query and often the simplest way to do this is copy-paste the data into vim and then run a macro/command on it to format it. Here is an example of input data:

This involves three steps for me:

Delete empty lines: :g!/\S/d

Add quotes around it and a , separator: :% s/\v(\S+)/"\1",

Put it onto one line and add a wrapping [...] or (...): ggVG (select all), J (condense-all), 0i(CTRL-o$)

Is there a way I can put all this into a function or macro, or what's the best way that I could take the above input and enter some keyboard shortcut, such as ⌘s and it formats everything in the above way?

While it might seem overkill, this is something that I can do pretty easily and quickly (without really thinking) in an editor like TextMate where I can use a multi-cursor.

答:
So what's the problem? Put this stuff into your vimrc and you're done.</p>

```<code>function s:do_stuff() abort
    %join
    s/\S\+/"&",/g
    s/^/(
    s/$/)
endfunction

nnoremap <silent><leader>s :call <SID>do_stuff()<CR>
</code>```

Body:
So what's the problem? Put this stuff into your vimrc and you're done.

function s:do_stuff() abort
    %join
    s/\S\+/"&",/g
    s/^/(
    s/$/)
endfunction

nnoremap <silent><leader>s :call <SID>do_stuff()<CR>


问:
CodeIgniter Api login
I am trying the build login script but when it run shows me that message:

Message: Too few arguments to function Cliente::login(), 0 passed in
C:\wamp64\www\apiuthomi\system\core\CodeIgniter.php on line 532 and exactly 2 expected
Filename: C:\wamp64\www\apiuthomi\application\controllers\Cliente.php
    This is my code

```<code>public function login($username, $password){
    if($this->access_app()){
            //$this->db->where('email', $email);
            //$this->db->or_where('username', $username);
            $dataform = $this->input->post();
            $this->load->database();
            $this->db->where('username', $username);
            $this->db->where('password', $password);
            $query = $this->db->get("cliente");
            if($query->num_rows()==0){
                $this->output->set_status_header(401, "nao existe");
            echo json_encode(array("code" => 401, "message" => "Nao existe"));
            }else{
                echo json_encode($query->row());
            }
}
</code>```

答:
The error basically tells you that you have not sent any parameters to the function login().

You should send it with login('username', 'password') variables, otherwise it fails.
You can resolve this by adding default values to the variables:

```<code>public function login($username = '', $password = ''){
</code>```

In that case if you do not provide the variables it would assume they are empty (equal to empty string).

Title: CodeIgniter Api login

Body:
I am trying the build login script but when it run shows me that message:

Message: Too few arguments to function Cliente::login(), 0 passed in
C:\wamp64\www\apiuthomi\system\core\CodeIgniter.php on line 532 and exactly 2 expected
Filename: C:\wamp64\www\apiuthomi\application\controllers\Cliente.php
    This is my code

public function login($username, $password){
    if($this->access_app()){
            //$this->db->where('email', $email);
            //$this->db->or_where('username', $username);
            $dataform = $this->input->post();
            $this->load->database();
            $this->db->where('username', $username);
            $this->db->where('password', $password);
            $query = $this->db->get("cliente");
            if($query->num_rows()==0){
                $this->output->set_status_header(401, "nao existe");
            echo json_encode(array("code" => 401, "message" => "Nao existe"));
            }else{
                echo json_encode($query->row());
            }
}

Body:
The error basically tells you that you have not sent any parameters to the function login().

You should send it with login('username', 'password') variables, otherwise it fails.
You can resolve this by adding default values to the variables:

public function login($username = '', $password = ''){

In that case if you do not provide the variables it would assume they are empty (equal to empty string).


问:
TypeError: Cannot read property 'forEach' of undefined Javascript
Following is the code in which I am getting Cannot read property 'forEach' of undefined.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )```
</div>
</div>
</p>

<p>Let me know what I am doing wrong here, though if I do -</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function print2(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )</code>```

this is working fine.

答:
Since there's no semicolon after the function, the snippet gets interpreted as the following:

```<code>const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x => print2(x, 20) )
</code>```

Which means that it's trying to index into the function. Add a semicolon either after the function, or before the array literal:

```<code>const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )
</code>```

or

```<code>const print2 = function(x, y) {
  console.log(x*y)
}

;[1,2,3,4].forEach( x => print2(x, 20) )
</code>```

More about Javascript's automatic semicolon insertion here: What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Body:
Following is the code in which I am getting Cannot read property 'forEach' of undefined.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

Let me know what I am doing wrong here, though if I do -

function print2(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

this is working fine.

Body:
Since there's no semicolon after the function, the snippet gets interpreted as the following:

const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x => print2(x, 20) )

Which means that it's trying to index into the function. Add a semicolon either after the function, or before the array literal:

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )

or

const print2 = function(x, y) {
  console.log(x*y)
}

;[1,2,3,4].forEach( x => print2(x, 20) )

More about Javascript's automatic semicolon insertion here: What are the rules for JavaScript's automatic semicolon insertion (ASI)?


问:
CMake can't find protobuf when compiling Google's protobuf example
I am trying to solve this problem for 2 days now with no luck. I've read an endless number of threads allover the web and tried a lot of suggestions but so far with no luck.

I'm doing this on Windows 10 with VS2017 and most recent VS Code installed. I installed protobuf with vcpkg install protobuf:

The package protobuf:x64-windows provides CMake targets:

```<code>find_package(protobuf CONFIG REQUIRED)
target_link_libraries(main PRIVATE protobuf::libprotoc protobuf::libprotobuf protobuf::libprotobuf-lite)
</code>```

I downloaded Google's example code and extracted it on my drive. The .PROTO file compiles without a problem:

```<code>d:\protobuf-3.12.2\examples>protoc -I=d:\protobuf-3.12.2\examples --cpp_out=d:\protobuf-3.12.2\examples d:\protobuf-3.12.2\examples\addressbook.proto
</code>```

and creates the two files "addressbook.pb.cc" and "addressbook.pb.h" as expected.

Now when I try to compile the project in Visual Studio Code it constantly fails no matter how I modify the CMakeLists.txt file. As mentioned I went through dozens of threads regarding this problem and tried a lot with no luck.

Update 29.05.2020

I checked that protobuf is installed just once and indeed the demo package also included a full protobuf installation. I removed this extra demo package and un-/installed protobuf with vcpgk. I then compiled the .proto file with protoc (which is in my path) and got the two files "addressbook.pb.cc" and "addressbook.pb.h".

Then I tried to compile the project again, this time using the CMakeLists.txt that came with the demo.

The relevant part seems to be right in the beginning:

```<code># Minimum CMake required
cmake_minimum_required(VERSION 2.8.12)
# Project
project(protobuf-examples)
# Find required protobuf package
find_package(protobuf CONFIG REQUIRED)
if(protobuf_VERBOSE)
  message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}")
endif()
set(CMAKE_INCLUDE_CURRENT_DIR TRUE)
</code>```

Compiling this gives me:

```<code>[main] Building folder: examples
[main] Configuring folder: examples
[cms-client] Configuring using the "Visual Studio 15 2017" CMake generator with platform "x64" and toolset "host=x64"
[cmake] Selecting Windows SDK version 10.0.17763.0 to target Windows
...
[cmake] CMake Error at CMakeLists.txt:8 (find_package):
[cmake]   Could not find a package configuration file provided by "protobuf" with any
[cmake]   of the following names:
[cmake]
[cmake]     protobufConfig.cmake
[cmake]     protobuf-config.cmake
[cmake]
[cmake]   Add the installation prefix of "protobuf" to CMAKE_PREFIX_PATH or set
[cmake]   "protobuf_DIR" to a directory containing one of the above files.  If
[cmake]   "protobuf" provides a separate development package or SDK, be sure it has
[cmake]   been installed.
[cmake]
[cmake]
[cmake] Configuring incomplete, errors occurred!
[cmake] See also "d:/vcpkg/buildtrees/protobuf/src/v3.12.0-8ba83cbbdb/examples/build/CMakeFiles/CMakeOutput.log".
[cms-driver] Error during CMake configure: [cmake-server] Configuration failed.
</code>```

The file protobuf-config.cmake can be found multiple times in the protobuf folder:

D:\vcpkg\buildtrees\protobuf\<BUILDCFG>\share\protobuf\protobuf-config.cmake

D:\vcpkg\installed\<BUILDCFG>\share\protobuf\protobuf-config.cmake

D:\vcpkg\packages\<BUILDCFG>\share\protobuf\protobuf-config.cmake

What could be the cause that CMake can't locate these files?

答:
Fair warning I am no expert.

I ran in to a similar problem in my own build trying to get Boost working and I think it has to do with your environment variables and how you have your Visual Studio setup. While you are setting crucial things such as

```<code>SET(PROTOBUF_INCLUDE_DIR "d:/vcpkg/packages/protobuf_x64-windows/include/")
</code>```

The actual find_package(protobuf CONFIG REQUIRED) throws these settings out the window. Once it finds that config file it only cares about what the config file is finding, I think this is the cause of how your first MESSAGE has the right one, and then your 2nd one doesn't find one.

Are you positive you only have one installation of protobuf on your machine?

It appears to be finding this "used as include directory in directory D:/protobuf-3.12.2/examples"

yet you are trying to find "D:/vcpkg/packages/protobuf_x64-windows" no?

Try adding a "-DCMAKE_PREFIX_PATH="d:/vcpkg/packages/protobuf_x64-windows" to your CMake options in Visual Studio

Good luck and sorry if this doesn't help, I'm relatively new to programming but its worth a try.

Body:
I am trying to solve this problem for 2 days now with no luck. I've read an endless number of threads allover the web and tried a lot of suggestions but so far with no luck.

I'm doing this on Windows 10 with VS2017 and most recent VS Code installed. I installed protobuf with vcpkg install protobuf:

The package protobuf:x64-windows provides CMake targets:

find_package(protobuf CONFIG REQUIRED)
target_link_libraries(main PRIVATE protobuf::libprotoc protobuf::libprotobuf protobuf::libprotobuf-lite)

I downloaded Google's example code and extracted it on my drive. The .PROTO file compiles without a problem:

d:\protobuf-3.12.2\examples>protoc -I=d:\protobuf-3.12.2\examples --cpp_out=d:\protobuf-3.12.2\examples d:\protobuf-3.12.2\examples\addressbook.proto

and creates the two files "addressbook.pb.cc" and "addressbook.pb.h" as expected.

Now when I try to compile the project in Visual Studio Code it constantly fails no matter how I modify the CMakeLists.txt file. As mentioned I went through dozens of threads regarding this problem and tried a lot with no luck.

Update 29.05.2020

I checked that protobuf is installed just once and indeed the demo package also included a full protobuf installation. I removed this extra demo package and un-/installed protobuf with vcpgk. I then compiled the .proto file with protoc (which is in my path) and got the two files "addressbook.pb.cc" and "addressbook.pb.h".

Then I tried to compile the project again, this time using the CMakeLists.txt that came with the demo.

The relevant part seems to be right in the beginning:

# Minimum CMake required
cmake_minimum_required(VERSION 2.8.12)
# Project
project(protobuf-examples)
# Find required protobuf package
find_package(protobuf CONFIG REQUIRED)
if(protobuf_VERBOSE)
  message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}")
endif()
set(CMAKE_INCLUDE_CURRENT_DIR TRUE)

Compiling this gives me:

[main] Building folder: examples
[main] Configuring folder: examples
[cms-client] Configuring using the "Visual Studio 15 2017" CMake generator with platform "x64" and toolset "host=x64"
[cmake] Selecting Windows SDK version 10.0.17763.0 to target Windows
...
[cmake] CMake Error at CMakeLists.txt:8 (find_package):
[cmake]   Could not find a package configuration file provided by "protobuf" with any
[cmake]   of the following names:
[cmake]
[cmake]     protobufConfig.cmake
[cmake]     protobuf-config.cmake
[cmake]
[cmake]   Add the installation prefix of "protobuf" to CMAKE_PREFIX_PATH or set
[cmake]   "protobuf_DIR" to a directory containing one of the above files.  If
[cmake]   "protobuf" provides a separate development package or SDK, be sure it has
[cmake]   been installed.
[cmake]
[cmake]
[cmake] Configuring incomplete, errors occurred!
[cmake] See also "d:/vcpkg/buildtrees/protobuf/src/v3.12.0-8ba83cbbdb/examples/build/CMakeFiles/CMakeOutput.log".
[cms-driver] Error during CMake configure: [cmake-server] Configuration failed.

The file protobuf-config.cmake can be found multiple times in the protobuf folder:

D:\vcpkg\buildtrees\protobuf\<BUILDCFG>\share\protobuf\protobuf-config.cmake

D:\vcpkg\installed\<BUILDCFG>\share\protobuf\protobuf-config.cmake

D:\vcpkg\packages\<BUILDCFG>\share\protobuf\protobuf-config.cmake

What could be the cause that CMake can't locate these files?

Body:
Fair warning I am no expert.

I ran in to a similar problem in my own build trying to get Boost working and I think it has to do with your environment variables and how you have your Visual Studio setup. While you are setting crucial things such as

SET(PROTOBUF_INCLUDE_DIR "d:/vcpkg/packages/protobuf_x64-windows/include/")

The actual find_package(protobuf CONFIG REQUIRED) throws these settings out the window. Once it finds that config file it only cares about what the config file is finding, I think this is the cause of how your first MESSAGE has the right one, and then your 2nd one doesn't find one.

Are you positive you only have one installation of protobuf on your machine?

It appears to be finding this "used as include directory in directory D:/protobuf-3.12.2/examples"

yet you are trying to find "D:/vcpkg/packages/protobuf_x64-windows" no?

Try adding a "-DCMAKE_PREFIX_PATH="d:/vcpkg/packages/protobuf_x64-windows" to your CMake options in Visual Studio

Good luck and sorry if this doesn't help, I'm relatively new to programming but its worth a try.


问:
Does TUniQuery (UniDac TUniQuery) Last and First methods jump directly or do a record by record scroll
I have a program that must set up a more less complex screen after the user goes to a certain record in a dataset (TUniQuery). The user can jump on many ways: a combobox, search box and finally a DbNavigator. Going from the first to the last record takes forever. After following program execution I discovered that pressing the last button on the DBNavigator causes each record on the dataset to be visited, and so, on each one, the screen is uselessly built. Same from any record going to the first or last. It was my understanding, that such methods (First and Last) will do a direct jump. Maybe is a particular behavior on the Unidac components, but I can´t find any reference nor property to modify it. Currently, I´m planning to set a flag on the BeforeScroll event, but since AfterScroll also happens after each one, I can´t learn when the dataset has ended scrolling. I can´t neither find any reference on Delphi documentation that simply states

Call Last to make the last record in the dataset active

答:
Following the source code I found this:

Short answer: Yes, a TDataset jumps directly to the first and last records when possible but...

Long answer: Delphi has internal data events (DB unit, TDataEvent) that are broadcasted so data aware controls can update properly. Methods like Next, Prior and many others use function MoveBy, which generates a Before/AfterScroll events and also internal events. MoveBy may fetch some extra rows if needed. Let's say you have twenty rows fetched from a thirty rows dataset. Your current record is fifteen. You call MoveBy(2). As expected, your new record is seventeen. In this case the following occurs:

BeforeScroll

ActiveRecord is incremented twice (in a loop) but no rows are fetched

internal DataEvent: deDataSetScroll

AfterScroll

Note that no program events occur while scrolling. BeforeScroll occurs on record fifteen and AfterScroll on seventeen.

Now, same scenario, but this time MoveBy(10) is called. Five rows are already fetched (20 - 15) and five more need to be retrieved. In this case the sequence is:

BeforeScroll

ActiveRecord is incremented by five (in a loop) but no rows are fetched

Active record is incremented by five, in the same loop. On each cycle, a record is fetched (no program events occur)

internal DataEvent: deDataSetChange

AfterScroll

Every thing runs fine. The problem raises with the Last method that does not use MoveBy and assumes that records were always fetched:

```<code>procedure TDataSet.Last;
begin
  CheckBiDirectional;
  CheckBrowseMode;
  DoBeforeScroll;
  ClearBuffers;
  try
    InternalLast;
    GetPriorRecord;
    GetPriorRecords;
  finally
    FEOF := True;
    DataEvent(deDataSetChange, 0);  // Problem! Causes TJvDBSearchComboBox to retrieve all records (again)
    DoAfterScroll;
  end;
end;
</code>```

As you can see, Last method always broadcast a deDataSetChange event even when all records have been fetched. In my particular case of four records, the user presses the last button of a TDBNavigator which in turn calls Last method. The event deDataSetChange is broadcasted, and then a TJvDBSearchComboBox (from JVCL library) reacts to this event by visiting each row with a "while not eof...next" loop to update its contents, and generating Before/AfterScroll events.

I love Delphi, but is one of the things I don´t like about datasets. There is no way for a program to learn if certain data event was triggered due to a user action, or the program itself. I have suggested in Delphi presentations, for a way to travel through a dataset without events been triggered (as MoveBy does) and then, components like TJvDBSearchComboBox could use it, or at least a flag or the like in the dataset that could be turned on before starting to visit each record. Also, Last should check if records were indeed retrieved.

Some will says that's easy to implement by myself, and it is indeed when your code scrolls through the dataset. But in the case of a TDBNavigator and TJvDBSearchComboBox I have no control over them. Some other will say don´t use JVCL, There's no easy answer here. Also, FYI, First method exhibits the same behaviour.

Body:
Following the source code I found this:

Short answer: Yes, a TDataset jumps directly to the first and last records when possible but...

Long answer: Delphi has internal data events (DB unit, TDataEvent) that are broadcasted so data aware controls can update properly. Methods like Next, Prior and many others use function MoveBy, which generates a Before/AfterScroll events and also internal events. MoveBy may fetch some extra rows if needed. Let's say you have twenty rows fetched from a thirty rows dataset. Your current record is fifteen. You call MoveBy(2). As expected, your new record is seventeen. In this case the following occurs:

BeforeScroll

ActiveRecord is incremented twice (in a loop) but no rows are fetched

internal DataEvent: deDataSetScroll

AfterScroll

Note that no program events occur while scrolling. BeforeScroll occurs on record fifteen and AfterScroll on seventeen.

Now, same scenario, but this time MoveBy(10) is called. Five rows are already fetched (20 - 15) and five more need to be retrieved. In this case the sequence is:

BeforeScroll

ActiveRecord is incremented by five (in a loop) but no rows are fetched

Active record is incremented by five, in the same loop. On each cycle, a record is fetched (no program events occur)

internal DataEvent: deDataSetChange

AfterScroll

Every thing runs fine. The problem raises with the Last method that does not use MoveBy and assumes that records were always fetched:

procedure TDataSet.Last;
begin
  CheckBiDirectional;
  CheckBrowseMode;
  DoBeforeScroll;
  ClearBuffers;
  try
    InternalLast;
    GetPriorRecord;
    GetPriorRecords;
  finally
    FEOF := True;
    DataEvent(deDataSetChange, 0);  // Problem! Causes TJvDBSearchComboBox to retrieve all records (again)
    DoAfterScroll;
  end;
end;

As you can see, Last method always broadcast a deDataSetChange event even when all records have been fetched. In my particular case of four records, the user presses the last button of a TDBNavigator which in turn calls Last method. The event deDataSetChange is broadcasted, and then a TJvDBSearchComboBox (from JVCL library) reacts to this event by visiting each row with a "while not eof...next" loop to update its contents, and generating Before/AfterScroll events.

I love Delphi, but is one of the things I don´t like about datasets. There is no way for a program to learn if certain data event was triggered due to a user action, or the program itself. I have suggested in Delphi presentations, for a way to travel through a dataset without events been triggered (as MoveBy does) and then, components like TJvDBSearchComboBox could use it, or at least a flag or the like in the dataset that could be turned on before starting to visit each record. Also, Last should check if records were indeed retrieved.

Some will says that's easy to implement by myself, and it is indeed when your code scrolls through the dataset. But in the case of a TDBNavigator and TJvDBSearchComboBox I have no control over them. Some other will say don´t use JVCL, There's no easy answer here. Also, FYI, First method exhibits the same behaviour.


答:
You're missing semicolon after FunctionExpression.

```<code>const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )
</code>```

change to

```<code>const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )
</code>```

and it works.

Title: TypeError: Cannot read property 'forEach' of undefined Javascript

Body:
You're missing semicolon after FunctionExpression.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

change to

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )

and it works.


问:
MySQL licensing and GPL
As far as I know, when I build a desktop/server app using any GPL code like MySQL I will have to release the source code of my software under the GPL.

If I want to develop a web-app using MySQL, my code will link against the MySQL libraries. Must I release the sourcecode of my webapp in this situation to be in accordance with the GPL?

答:
MySQL uses dual licensing. As they put it - if you're free, we're free.

So, if you use, as far as I know, MySQL JDBC Connector only - you should have license or GPL your code.

ContentLicense: CC BY-SA 2.5

Title: MySQL licensing and GPL

LastEditorDisplayName: Roger Pate

OwnerDisplayName: emirc


问:
Property 'then' does not exist on type 'DialogRef<TwoButtonPreset>'.ts(2339)
Hi i'm trying to run this code on Angular 6 after updating from angular2-modal to ngx-modialog

```<code>this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
            .open()
            .then(( d ) => d.result
            .then(( r ) => {...});
</code>```

but after compiling i get this error :

```<code>Property 'then' does not exist on type 'DialogRef<TwoButtonPreset>'.ts(2339)
</code>```

I tried this but same error

```<code>...
dialog: DialogRef<TwoButtonPreset>;
...
let dialog = this.modal.confirm() .showClose(true)
.title(this.translator.instant('common.message.confirm.delete'))
.keyboard(27)
.okBtn(this.translator.instant('common.text.yes'))
.cancelBtn(this.translator.instant('common.text.no'))
.message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
.open()
.then(( d ) => d.result
...
</code>```

I also tried that but getting ; expected

```<code>this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
            .open()
            .result => {...};
</code>```

Here's my package.json :

```<code>{
  "name": "frontend6",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.1.0",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "@ngx-translate/core": "^12.1.2",
    "@ngx-translate/http-loader": "^4.0.0",
    "@types/alertify": "^0.3.29",
    "@types/file-saver": "0.0.1",
    "@types/highcharts": "^5.0.25",
    "@types/jquery": "2.0.47",
    "@types/openlayers": "4.6.9",
    "ag-grid": "7.1.0",
    "ag-grid-ng2": "7.1.2",
    "angular-tree-component": "^3.7.3",
    "angular2-google-maps": "0.17.0",
    "angular2-infinite-scroll": "^0.3.4",
    "angular2-text-mask": "2.1.0",
    "angular2-toaster": "^8.0.0",
    "angular2-tree-component": "2.0.0",
    "animate.css": "^3.7.2",
    "bootstrap": "3.3.7",
    "chart.js": "^2.7.3",
    "chroma-js": "^1.3.7",
    "codemirror": "5.22.0",
    "core-js": "^2.5.4",
    "easy-pie-chart": "2.1.7",
    "file-saver": "1.3.3",
    "flot": "0.8.0-alpha",
    "font-awesome": "4.7.0",
    "fullcalendar": "3.1.0",
    "highcharts": "^6.2.0",
    "highcharts-stock": "^0.1.7",
    "jqcloud2": "2.0.2",
    "jquery": "^3.5.1",
    "jquery-slimscroll": "1.3.8",
    "jquery-sparkline": "2.4.0",
    "jquery.browser": "0.1.0",
    "jquery.flot.tooltip": "0.9.0",
    "jspdf": "1.3.5",
    "jspdf-autotable": "2.3.2",
    "lodash": "^4.17.15",
    "modernizr": "^3.11.1",
    "moment": "^2.25.3",
    "mydatepicker": "1.10.2",
    "ng2-bootstrap": "1.1.16-11",
    "ng2-charts": "^1.6.0",
    "ng2-data-table": "1.0.0",
    "ng2-dnd": "2.1.1",
    "ng2-file-upload": "1.1.4-2",
    "ng2-img-cropper": "0.7.7",
    "ng2-select": "1.1.2",
    "ng2-table": "1.3.2",
    "ng2-tag-input": "0.7.0",
    "ng2-validation": "3.1.3",
    "ngx-modialog": "^5.0.1",
    "openlayers": "3.20.1",
    "rxjs": "~6.2.0",
    "rxjs-tslint": "^0.1.8",
    "screenfull": "3.0.2",
    "simple-line-icons": "2.4.1",
    "spinkit": "1.2.5",
    "summernote": "0.8.2",
    "ts-helpers": "1.1.1",
    "weather-icons": "1.3.2",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-builders/jest": "^7.2.3",
    "@angular-devkit/build-angular": "~0.8.0",
    "@angular/cli": "~6.2.9",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/codemirror": "0.0.37",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/moment": "2.13.0",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-read-json": "1.1.0",
    "karma-remap-istanbul": "0.2.1",
    "loaders.css": "0.1.2",
    "napa": "2.3.0",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.0.2",
    "typescript": "^2.4.2",
    "webdriver-manager": "10.2.5",
    "webpack": "^4.11.1",
    "webpack-dev-server": "2.1.0-beta.9"
  }
}
</code>```

The base app was on Angular 2 i was able to upgrade it to Angular 4 now I'm going for Angular 6

答:
you need to reference the dialogRef itself,</p>

```<code>dialogRef.result
        .then( result => alert(`The result is: ${result}`) );
</code>```

Body:
Hi i'm trying to run this code on Angular 6 after updating from angular2-modal to ngx-modialog

this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("
" + this.translator.instant('common.message.confirm.deleteAll') + "
")
            .open()
            .then(( d ) => d.result
            .then(( r ) => {...});

but after compiling i get this error :

Property 'then' does not exist on type 'DialogRef<TwoButtonPreset>'.ts(2339)

I tried this but same error

...
dialog: DialogRef<TwoButtonPreset>;
...
let dialog = this.modal.confirm() .showClose(true)
.title(this.translator.instant('common.message.confirm.delete'))
.keyboard(27)
.okBtn(this.translator.instant('common.text.yes'))
.cancelBtn(this.translator.instant('common.text.no'))
.message("
" + this.translator.instant('common.message.confirm.deleteAll') + "
")
.open()
.then(( d ) => d.result
...

I also tried that but getting ; expected

this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("
" + this.translator.instant('common.message.confirm.deleteAll') + "
")
            .open()
            .result => {...};

Here's my package.json :

{
  "name": "frontend6",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.1.0",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "@ngx-translate/core": "^12.1.2",
    "@ngx-translate/http-loader": "^4.0.0",
    "@types/alertify": "^0.3.29",
    "@types/file-saver": "0.0.1",
    "@types/highcharts": "^5.0.25",
    "@types/jquery": "2.0.47",
    "@types/openlayers": "4.6.9",
    "ag-grid": "7.1.0",
    "ag-grid-ng2": "7.1.2",
    "angular-tree-component": "^3.7.3",
    "angular2-google-maps": "0.17.0",
    "angular2-infinite-scroll": "^0.3.4",
    "angular2-text-mask": "2.1.0",
    "angular2-toaster": "^8.0.0",
    "angular2-tree-component": "2.0.0",
    "animate.css": "^3.7.2",
    "bootstrap": "3.3.7",
    "chart.js": "^2.7.3",
    "chroma-js": "^1.3.7",
    "codemirror": "5.22.0",
    "core-js": "^2.5.4",
    "easy-pie-chart": "2.1.7",
    "file-saver": "1.3.3",
    "flot": "0.8.0-alpha",
    "font-awesome": "4.7.0",
    "fullcalendar": "3.1.0",
    "highcharts": "^6.2.0",
    "highcharts-stock": "^0.1.7",
    "jqcloud2": "2.0.2",
    "jquery": "^3.5.1",
    "jquery-slimscroll": "1.3.8",
    "jquery-sparkline": "2.4.0",
    "jquery.browser": "0.1.0",
    "jquery.flot.tooltip": "0.9.0",
    "jspdf": "1.3.5",
    "jspdf-autotable": "2.3.2",
    "lodash": "^4.17.15",
    "modernizr": "^3.11.1",
    "moment": "^2.25.3",
    "mydatepicker": "1.10.2",
    "ng2-bootstrap": "1.1.16-11",
    "ng2-charts": "^1.6.0",
    "ng2-data-table": "1.0.0",
    "ng2-dnd": "2.1.1",
    "ng2-file-upload": "1.1.4-2",
    "ng2-img-cropper": "0.7.7",
    "ng2-select": "1.1.2",
    "ng2-table": "1.3.2",
    "ng2-tag-input": "0.7.0",
    "ng2-validation": "3.1.3",
    "ngx-modialog": "^5.0.1",
    "openlayers": "3.20.1",
    "rxjs": "~6.2.0",
    "rxjs-tslint": "^0.1.8",
    "screenfull": "3.0.2",
    "simple-line-icons": "2.4.1",
    "spinkit": "1.2.5",
    "summernote": "0.8.2",
    "ts-helpers": "1.1.1",
    "weather-icons": "1.3.2",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-builders/jest": "^7.2.3",
    "@angular-devkit/build-angular": "~0.8.0",
    "@angular/cli": "~6.2.9",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/codemirror": "0.0.37",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/moment": "2.13.0",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-read-json": "1.1.0",
    "karma-remap-istanbul": "0.2.1",
    "loaders.css": "0.1.2",
    "napa": "2.3.0",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.0.2",
    "typescript": "^2.4.2",
    "webdriver-manager": "10.2.5",
    "webpack": "^4.11.1",
    "webpack-dev-server": "2.1.0-beta.9"
  }
}

The base app was on Angular 2 i was able to upgrade it to Angular 4 now I'm going for Angular 6

Body:
you need to reference the dialogRef itself,

dialogRef.result
        .then( result => alert(`The result is: ${result}`) );


问:
How to remove unnecessary single quotation marks (') from column names in a R data frame?
unfortunately I have got colnames, which all have additional single quotation marks like here:

```<code>x <- data.frame(c(11,21,31),c(12,22,32),c(13,23,33))
colnames(x) <- c("'A'","'B'","'C'")
</code>```

So my question is, if I can get rid of those "'" for my entire data frame?
Preferably not retyping the colnames, and using tidyR code?
Thanks!

答:
```<code>library(stringr)

colnames(x) <- str_remove_all(colnames(x), "'")
</code>```

That should do it

```<code>library(dplyr)
library(stringr)
    x %>%
       rename_all(~str_remove_all(., "'"))
</code>```

If you want a pipe

Body:
unfortunately I have got colnames, which all have additional single quotation marks like here:

x <- data.frame(c(11,21,31),c(12,22,32),c(13,23,33))
colnames(x) <- c("'A'","'B'","'C'")

So my question is, if I can get rid of those "'" for my entire data frame?
Preferably not retyping the colnames, and using tidyR code?
Thanks!

Body:
library(stringr)

colnames(x) <- str_remove_all(colnames(x), "'")

That should do it

library(dplyr)
library(stringr)
    x %>%
       rename_all(~str_remove_all(., "'"))

If you want a pipe


问:
Laravel: Tricky redirection after login
My app first does a request into a web service to get the user from an ERP.
If the users exist on ERP database, I do register him into my database so I can access later.
Because of the WS routine my code looks like:

```<code>public function login(Request $request)
    {
        $credentials = $this->credentials($request);
        $login = $credentials[$this->username()];
        $cpfCnpjHigienizado = str_replace('-', '', str_replace('/', '', (str_replace('.', '', $request->cpfCnpj))));
        $credenciais = User::where('cpfCnpj', '=', $cpfCnpjHigienizado)->first();
        if ($credenciais) { // Se já estiver cadastro, vai pra home
            return redirect(route('home'));
        } else {
        // do the Soap connection
}
</code>```

Ok, so if the user is registered on my DB, goes to homepage and doesn't need to do the heavy Soap connection again.

This is working fine.
Now the project need to send an email to a pre-registered user like:

```<code>@component('mail::button', ['url' => env('APP_URL') .'/SobeDocsFiadorCadastrado/'. $fiador->id ])
Clique para iniciar
@endcomponent
</code>```

Now, this user should login first, then goes to the email's URL. But, he goes to the homepage instead.
How can I make this works? Am I doing something wrong?

Thanks in advance

答:
This's how to redirect to another route by name of the route and passing email as parameter:

```<code>return redirect()->route('new_route_name', ['email' => 'set email here']);
</code>```

Check this for more info:
https://laravel.com/docs/7.x/redirects

Title: Laravel: Tricky redirection after login

Body:
My app first does a request into a web service to get the user from an ERP.
If the users exist on ERP database, I do register him into my database so I can access later.
Because of the WS routine my code looks like:

public function login(Request $request)
    {
        $credentials = $this->credentials($request);
        $login = $credentials[$this->username()];
        $cpfCnpjHigienizado = str_replace('-', '', str_replace('/', '', (str_replace('.', '', $request->cpfCnpj))));
        $credenciais = User::where('cpfCnpj', '=', $cpfCnpjHigienizado)->first();
        if ($credenciais) { // Se já estiver cadastro, vai pra home
            return redirect(route('home'));
        } else {
        // do the Soap connection
}

Ok, so if the user is registered on my DB, goes to homepage and doesn't need to do the heavy Soap connection again.

This is working fine.
Now the project need to send an email to a pre-registered user like:

@component('mail::button', ['url' => env('APP_URL') .'/SobeDocsFiadorCadastrado/'. $fiador->id ])
Clique para iniciar
@endcomponent

Now, this user should login first, then goes to the email's URL. But, he goes to the homepage instead.
How can I make this works? Am I doing something wrong?

Thanks in advance

Body:
This's how to redirect to another route by name of the route and passing email as parameter:

return redirect()->route('new_route_name', ['email' => 'set email here']);

Check this for more info:
https://laravel.com/docs/7.x/redirects