问:
VB.NET Combo Box with multiple fields to select from
I'm porting an Access database I wrote over to VB.NET and while I've used Access for 25 years, I've used VB.NET for 2 days so I'm unclear what the capabilities are.

In my Access form, I have a Combo Box which allows the user to select a part record from a table. Using Access I can show multiple columns to the user making a selection - PartID, Description, notes, whatever. However once the part is selected and the combo box is closed, I show only the unique part ID.  The other columns help the user choose but make the form look really cluttered.

In my VB.NET form, I set the ValueMember to the PartID. But I only know how to set the DisplayMember to a single field. I created a composite field "PartID | Description | Notes" but then that's what appears even after the selection is made.

Is it possible in VB.NET to show one thing when the box is open and another thing once the selection has been made?

```<code>    qry = "SELECT PartID, cast(PartID as string) & " | " & [partName] AS PartString
            FROM [Part_List]
            GROUP BY PartID, cast(PartID as string) & " | " & [partName]
            ORDER BY PartID;"
    cmd = New SqlCommand(qry, conn)
    adapter = New SqlDataAdapter(cmd)
    Dim tblPN As New DataTable()
    adapter.Fill(tblPN)

    ChoosePartNum.DataSource = tblPN
    ChoosePartNum.DisplayMember = "PartString"
    ChoosePartNum.ValueMember = "PartID"
    ChoosePartNum.SelectedIndex = -1
</code>```

答:
I see what you are trying to do. I was doing that in MS Access too but it was more than 20 years ago.

I agree with Jimi. From a design point of view, trying to reproduce Access-like features in a new environment is not a great idea.

Users are familiar with Winforms controls and have certain expectations in term of UI layout and consistency. If you are building a new UI from scratch you should take the opportunity to redesign it and modernize it. Don't just carry 25-year old habits over. Especially if you are not the only user of that application, because you don't want people to think that your coding methods are stuck in the 20th century...

Is it possible in VB.NET to show one thing when the box is open and
  another thing once the selection has been made?

If you really want to achieve this behavior you need to use combo box events. The two events you need would be DropDownClosed and DropDown.

Here is how it can be done:

```<code>  Private Sub ComboBox1_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.DropDown
        With Me.ChoosePartNum
            .DisplayMember = "composite field"
        End With
    End Sub

    Private Sub ComboBox1_DropDownClosed(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.DropDownClosed
        With Me.ChoosePartNum
            .DisplayMember = "PartID"
        End With
    End Sub
</code>```

The trick is to change the DisplayMember property whenever the combo box is folded/unfolded by the user. The underlying value remains the same.

I don't know if you require autocomplete from keyboard or have other needs. A treeview or listview sound like obvious alternatives. But you said you want a 'compact' control. Here you go.

Body:
I'm porting an Access database I wrote over to VB.NET and while I've used Access for 25 years, I've used VB.NET for 2 days so I'm unclear what the capabilities are.

In my Access form, I have a Combo Box which allows the user to select a part record from a table. Using Access I can show multiple columns to the user making a selection - PartID, Description, notes, whatever. However once the part is selected and the combo box is closed, I show only the unique part ID.  The other columns help the user choose but make the form look really cluttered.

In my VB.NET form, I set the ValueMember to the PartID. But I only know how to set the DisplayMember to a single field. I created a composite field "PartID | Description | Notes" but then that's what appears even after the selection is made.

Is it possible in VB.NET to show one thing when the box is open and another thing once the selection has been made?

    qry = "SELECT PartID, cast(PartID as string) & " | " & [partName] AS PartString
            FROM [Part_List]
            GROUP BY PartID, cast(PartID as string) & " | " & [partName]
            ORDER BY PartID;"
    cmd = New SqlCommand(qry, conn)
    adapter = New SqlDataAdapter(cmd)
    Dim tblPN As New DataTable()
    adapter.Fill(tblPN)

    ChoosePartNum.DataSource = tblPN
    ChoosePartNum.DisplayMember = "PartString"
    ChoosePartNum.ValueMember = "PartID"
    ChoosePartNum.SelectedIndex = -1

Body:
I see what you are trying to do. I was doing that in MS Access too but it was more than 20 years ago.

I agree with Jimi. From a design point of view, trying to reproduce Access-like features in a new environment is not a great idea.

Users are familiar with Winforms controls and have certain expectations in term of UI layout and consistency. If you are building a new UI from scratch you should take the opportunity to redesign it and modernize it. Don't just carry 25-year old habits over. Especially if you are not the only user of that application, because you don't want people to think that your coding methods are stuck in the 20th century...

Is it possible in VB.NET to show one thing when the box is open and
  another thing once the selection has been made?

If you really want to achieve this behavior you need to use combo box events. The two events you need would be DropDownClosed and DropDown.

Here is how it can be done:

  Private Sub ComboBox1_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.DropDown
        With Me.ChoosePartNum
            .DisplayMember = "composite field"
        End With
    End Sub

    Private Sub ComboBox1_DropDownClosed(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.DropDownClosed
        With Me.ChoosePartNum
            .DisplayMember = "PartID"
        End With
    End Sub

The trick is to change the DisplayMember property whenever the combo box is folded/unfolded by the user. The underlying value remains the same.

I don't know if you require autocomplete from keyboard or have other needs. A treeview or listview sound like obvious alternatives. But you said you want a 'compact' control. Here you go.


来源: stackexchange

问:
JavaFX BarChart xAxis labels bad positioning
I have the following Controller for my window:

```<code>package window;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;

import java.util.Map;
import java.util.SortedMap;

public class StatisticsController {

    @FXML
    private BarChart<?, ?> barChartHistogram;

    private SortedMap<String, Integer> _points;

    @FXML
    private CategoryAxis xAxis;
    @FXML
    private NumberAxis yAxis;

    public void onLoad(SortedMap<String, Integer> points) {
        xAxis.setLabel("Numer indeksu");
        yAxis.setLabel("Ilość punktów");
        //barChartHistogram.setBarGap(0);
        XYChart.Series series1 = new XYChart.Series();
        int a = 10;
        series1.getData().add(new XYChart.Data("Tom", 10));
        series1.getData().add(new XYChart.Data("Andrew", 7));
        series1.getData().add(new XYChart.Data("Patrick", 5));

        /*for (Map.Entry<String, Integer> p: points.entrySet()) {
            series1.getData().add(new XYChart.Data<>(Integer.toString(a), p.getValue()));
            a += 10;
        }*/
        barChartHistogram.getData().addAll(series1);
        _points = points;
    }

}
</code>```

The .fxml file for this window:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.chart.BarChart?>
<?import javafx.scene.chart.CategoryAxis?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="700.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="window.StatisticsController">
   <children>
      <BarChart fx:id="barChartHistogram" layoutX="12.0" layoutY="14.0" prefHeight="372.0" prefWidth="1500.0">
        <xAxis>
          <CategoryAxis side="BOTTOM" fx:id="xAxis" />
        </xAxis>
        <yAxis>
          <NumberAxis fx:id="yAxis" side="LEFT" />
        </yAxis>
      </BarChart>
   </children>
</AnchorPane>
```

Everything works perfectly except one thing:

As you can see the x axis label works fine, but the x axis labels (I mean like column names), which should be Tom, Andrew and Patrick are placed in exact same position (through this mess you can actually read Patrick) a the 0 position of x axis. Where is the problem? Should I make some changes to the UI or something?

答:
This is fun , but i was facing the same problem with java11 https://youtu.be/2ZKzWciKtIc?t=36 , after  my chart data was loaded the category labels never show. After few tries i decided to set the chart data in a timeline and after it finish set the category labels manually.</p>

```<code>Duration duration = Duration.millis(300);
Platform.runLater(()->{
    Timeline timeline = new Timeline(
        new KeyFrame(duration,event -> {
            barChart.getData().clear();
            barChart.getData().add(series1);
            barChart.getData().addAll(series2);
            //Clear all bofore to evitate Exceptions
            catAxis.getCategories().clear();
        })
    );
    timeline.setCycleCount(1);
    timeline.setOnFinished(event -> {
    //Set animated as false, so if true all labels will be one in top of the others
    barChart.setAnimated(false);
    //The trick that worked forr me
    catAxis.getCategories().addAll(lists);
});
timeline.play();  });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following Controller for my window:

package window;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;

import java.util.Map;
import java.util.SortedMap;

public class StatisticsController {

    @FXML
    private BarChart<?, ?> barChartHistogram;

    private SortedMap<String, Integer> _points;

    @FXML
    private CategoryAxis xAxis;
    @FXML
    private NumberAxis yAxis;

    public void onLoad(SortedMap<String, Integer> points) {
        xAxis.setLabel("Numer indeksu");
        yAxis.setLabel("Ilość punktów");
        //barChartHistogram.setBarGap(0);
        XYChart.Series series1 = new XYChart.Series();
        int a = 10;
        series1.getData().add(new XYChart.Data("Tom", 10));
        series1.getData().add(new XYChart.Data("Andrew", 7));
        series1.getData().add(new XYChart.Data("Patrick", 5));

        /*for (Map.Entry<String, Integer> p: points.entrySet()) {
            series1.getData().add(new XYChart.Data<>(Integer.toString(a), p.getValue()));
            a += 10;
        }*/
        barChartHistogram.getData().addAll(series1);
        _points = points;
    }

}

The .fxml file for this window:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.chart.BarChart?>
<?import javafx.scene.chart.CategoryAxis?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="700.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="window.StatisticsController">
   <children>
      <BarChart fx:id="barChartHistogram" layoutX="12.0" layoutY="14.0" prefHeight="372.0" prefWidth="1500.0">
        <xAxis>
          <CategoryAxis side="BOTTOM" fx:id="xAxis" />
        </xAxis>
        <yAxis>
          <NumberAxis fx:id="yAxis" side="LEFT" />
        </yAxis>
      </BarChart>
   </children>
</AnchorPane>

Everything works perfectly except one thing:

As you can see the x axis label works fine, but the x axis labels (I mean like column names), which should be Tom, Andrew and Patrick are placed in exact same position (through this mess you can actually read Patrick) a the 0 position of x axis. Where is the problem? Should I make some changes to the UI or something?

Body:
This is fun , but i was facing the same problem with java11 https://youtu.be/2ZKzWciKtIc?t=36 , after  my chart data was loaded the category labels never show. After few tries i decided to set the chart data in a timeline and after it finish set the category labels manually.

Duration duration = Duration.millis(300);
Platform.runLater(()->{
    Timeline timeline = new Timeline(
        new KeyFrame(duration,event -> {
            barChart.getData().clear();
            barChart.getData().add(series1);
            barChart.getData().addAll(series2);
            //Clear all bofore to evitate Exceptions
            catAxis.getCategories().clear();
        })
    );
    timeline.setCycleCount(1);
    timeline.setOnFinished(event -> {
    //Set animated as false, so if true all labels will be one in top of the others
    barChart.setAnimated(false);
    //The trick that worked forr me
    catAxis.getCategories().addAll(lists);
});
timeline.play();  });

ContentLicense: CC BY-SA 4.0


问:
add start from constraint to a column in mysql
hey i am creating an application for invoicing(computer generated bill).
i have a table sales_log where ref no. column is set to auto_increment.i didnt assign the start value. i mean if the ref no. of 1st bill is 101 then i should automatically get 102..103...etc for the rest...i just dont know how to alter the table constraint and set a starting value for that column.
here is the description of my table</p>

```<code>mysql> desc sales_log;
+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| date     | date    | YES  |     | NULL    |                |
| item_id  | int(11) | YES  | MUL | NULL    |                |
| C_Id     | int(11) | YES  | MUL | NULL    |                |
| Quantity | double  | YES  |     | NULL    |                |
| Ref      | int(11) | NO   | PRI | NULL    | auto_increment |
| price    | double  | YES  |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+
</code>```

答:
See http://dev.mysql.com/doc/refman/5.5/en/example-auto-increment.html

To start with an AUTO_INCREMENT value
  other than 1, you can set that value
  with CREATE TABLE or ALTER TABLE, like
  this:

```<code>ALTER TABLE sales_log AUTO_INCREMENT = 101;
</code>```

Body:
hey i am creating an application for invoicing(computer generated bill).
i have a table sales_log where ref no. column is set to auto_increment.i didnt assign the start value. i mean if the ref no. of 1st bill is 101 then i should automatically get 102..103...etc for the rest...i just dont know how to alter the table constraint and set a starting value for that column.
here is the description of my table

mysql> desc sales_log;
+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| date     | date    | YES  |     | NULL    |                |
| item_id  | int(11) | YES  | MUL | NULL    |                |
| C_Id     | int(11) | YES  | MUL | NULL    |                |
| Quantity | double  | YES  |     | NULL    |                |
| Ref      | int(11) | NO   | PRI | NULL    | auto_increment |
| price    | double  | YES  |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+

Body:
See http://dev.mysql.com/doc/refman/5.5/en/example-auto-increment.html

To start with an AUTO_INCREMENT value
  other than 1, you can set that value
  with CREATE TABLE or ALTER TABLE, like
  this:

ALTER TABLE sales_log AUTO_INCREMENT = 101;


问:
Primitive Recursive Functions Excercise in Haskell
For a functional programming excercise I am required to apply primitive recursive functions in haskell. However I do not quite understand yet the definition (and application) of this type of functions.

We are presented the data type Nat to be used, its constructor is:
data Nat = Zero | Succ Nat

To my understanding this means that the type "Nat" can be either a Zero or a Natural Succesor.

Then we have a recursor:

```<code>recNat :: a -> (Nat -> a -> a) -> Nat -> a
recNat a _ Zero = a
recNat a h (Succ n) = h n (recNat a h n)
</code>```

Which I understand is meant to apply recursion to a function?

And I've also been given an example of an addition function using the recursor:

```<code>addR :: Nat -> Nat -> Nat
addR m n = recNat n (\ _ y -> Succ y) m
</code>```

But I don't get how it works, it uses the recNat function with the given two Nats, and also uses an anonymous function as input for recNat ( that is the part I'm not sure what it does! )

So my main issue is what does this do in the function exactly > \ _ y -> Succ y

I'm suppossed to apply this same recursor (RecNat) to apply other operations to Nat, but I'm stuck still trying to understand the example!

答:
Roughly, recNat x f n computes

```<code>f (n-1) (f (n-2) (f (n-3) (... (f 0 x))))
</code>```

So, it applies f to x for n times, each time also passing a "counter" as the first argument of f.

In your case \_ y -> ... ignores the "counter" argument. Hence

```<code>addR m n = recNat n (\ _ y -> Succ y) m
</code>```

can be read as "to compute m+n, apply m times the function Succ to n". This effectively computes ((n+1)+1)+1... where there are m ones in the sum.

You can try to compute the product of two naturals in a similar way. Use \_ y -> ... and express multiplication as repeated addition. You'll need to use the already-defined addR for that.

Additional hint: after multiplication, if you want to compute the predecessor n-1, then the "counter" argument will be very handy, so don't discard that and use \x y -> ... instead. After that, you can derive (truncated) subtraction as repeated predecessor.

Body:
For a functional programming excercise I am required to apply primitive recursive functions in haskell. However I do not quite understand yet the definition (and application) of this type of functions.

We are presented the data type Nat to be used, its constructor is:
data Nat = Zero | Succ Nat

To my understanding this means that the type "Nat" can be either a Zero or a Natural Succesor.

Then we have a recursor:

recNat :: a -> (Nat -> a -> a) -> Nat -> a
recNat a _ Zero = a
recNat a h (Succ n) = h n (recNat a h n)

Which I understand is meant to apply recursion to a function?

And I've also been given an example of an addition function using the recursor:

addR :: Nat -> Nat -> Nat
addR m n = recNat n (\ _ y -> Succ y) m

But I don't get how it works, it uses the recNat function with the given two Nats, and also uses an anonymous function as input for recNat ( that is the part I'm not sure what it does! )

So my main issue is what does this do in the function exactly > \ _ y -> Succ y

I'm suppossed to apply this same recursor (RecNat) to apply other operations to Nat, but I'm stuck still trying to understand the example!

Body:
Roughly, recNat x f n computes

f (n-1) (f (n-2) (f (n-3) (... (f 0 x))))

So, it applies f to x for n times, each time also passing a "counter" as the first argument of f.

In your case \_ y -> ... ignores the "counter" argument. Hence

addR m n = recNat n (\ _ y -> Succ y) m

can be read as "to compute m+n, apply m times the function Succ to n". This effectively computes ((n+1)+1)+1... where there are m ones in the sum.

You can try to compute the product of two naturals in a similar way. Use \_ y -> ... and express multiplication as repeated addition. You'll need to use the already-defined addR for that.

Additional hint: after multiplication, if you want to compute the predecessor n-1, then the "counter" argument will be very handy, so don't discard that and use \x y -> ... instead. After that, you can derive (truncated) subtraction as repeated predecessor.


问:
How to get PromiseValue in XMLHttpRequest. JSON
How to get array that is located on PromiseValue instead of getting Promise {<pending>}
While I'm using .then(data => console.log(data)) I'm getting array in console log.
However, I need to get an array to place it on the html page so I changet code to .then(data => data) and started to get Promise {<pending>}

```<code>const baseUrl = 'http://localhost:3000';

function sendRequest(method, url, data = null) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open(method, url);

        xhr.responseType = 'json';
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = () => {
            if (xhr.status >= 400) {
                reject(xhr.response);
            } else {
                resolve(xhr.response);
            }
        }

        xhr.onerror = () => {
            reject(xhr.response);
        }

        xhr.send(JSON.stringify(data));
    });
}

let getData = sendRequest('GET', baseUrl + '/users')
.then(data => data)
.catch(err => console.log(err));

console.log(getData);
</code>```

Thanks in advance.

答:
sendRequest() will execute async. This means that the script continues, even though the data is not loaded. So the last line console.log(getData) will already happen before any of the data is loaded.

This is what promises can be used for:

```<code>sendRequest('GET', baseUrl + '/users')
    .then(function(data){
        // The response can only be processed in the .then part.
        // You can, however, call other functions with the fetched data
        console.log(data);
    })
    .catch(err => console.log(err));

</code>```

Another option would be to use async and await. But this does not work in older browsers.

```<code>function async sendRequest(method, url, data = null) {
// your current xhr code
}

let getData = await sendRequest('GET', baseUrl + '/users');
console.log(getData);
</code>```

Body:
How to get array that is located on PromiseValue instead of getting Promise {<pending>}
While I'm using .then(data => console.log(data)) I'm getting array in console log.
However, I need to get an array to place it on the html page so I changet code to .then(data => data) and started to get Promise {<pending>}

const baseUrl = 'http://localhost:3000';

function sendRequest(method, url, data = null) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open(method, url);

        xhr.responseType = 'json';
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = () => {
            if (xhr.status >= 400) {
                reject(xhr.response);
            } else {
                resolve(xhr.response);
            }
        }

        xhr.onerror = () => {
            reject(xhr.response);
        }

        xhr.send(JSON.stringify(data));
    });
}

let getData = sendRequest('GET', baseUrl + '/users')
.then(data => data)
.catch(err => console.log(err));

console.log(getData);

Thanks in advance.

Body:
sendRequest() will execute async. This means that the script continues, even though the data is not loaded. So the last line console.log(getData) will already happen before any of the data is loaded.

This is what promises can be used for:

sendRequest('GET', baseUrl + '/users')
    .then(function(data){
        // The response can only be processed in the .then part.
        // You can, however, call other functions with the fetched data
        console.log(data);
    })
    .catch(err => console.log(err));

Another option would be to use async and await. But this does not work in older browsers.

function async sendRequest(method, url, data = null) {
// your current xhr code
}

let getData = await sendRequest('GET', baseUrl + '/users');
console.log(getData);


问:
public and source folders don't come in create-react-app
react-app the command it won't work and it won't create the Public and the Source folder that is weird. I've tried many times and even with yarn it still won't work! Please tell me why this is happening thanks</p>

答:
try this in your command line tool:

```<code>npx create-react-app test
</code>```

It will create a React-App-template in a folder  called "test". It will include all the folders and features you are looking for.

Body:
try this in your command line tool:

npx create-react-app test

It will create a React-App-template in a folder  called "test". It will include all the folders and features you are looking for.


问:
Paypal Change Address Field Style
I'm using WordPress Express Checkout plugin for my Wordpress Website in while paying from Credit or Debit Card button small form shows address filed with the country flag, can I change this flag to a country dropdown list using Css or Jquery?

Paypal Address Field Image:

答:
No, you can't. Those credit card fields in your image render in a double-nested PayPal iframe that you have no control over.

The default billing country of the buyer will be set based on their locale ( top of chrome://settings/languages or equivalent , or if set on the SDK line )

Title: Paypal Change Address Field Style


问:
Is there a TQDM like module for creating progress bars for recursion?
I am writing a branch and bound algorithm in python and I am trying to efficiently display the progress.  The algorithm uses recursion and I couldn't figure out any way to make it iterative.  I am wondering if there is a tqdm like module for recursive functions or at least a way to implement a progress bar with recursive functions?  For example, if I was writing an iterative factorial function in python with the tqdm module I would do this:

import tqdm

def factorial(n):
    end_product = 1
    for i in tqdm(range(1, n)):
        end_product *= i
    return end_product
```

<p>How would I implement a progress bar on a recursive function like this:</p>

<pre class="lang-py prettyprint-override"><code>def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

progress_bar(factorial(1000))
</code>```

答:
One solution is initialize progress bar with total= parameter and then call .update() method in each call of recursion.

Something along the lines of this:

```<code>from time import sleep
from tqdm import tqdm

def factorial(n, bar):
    bar.update(1)
    sleep(0.01)  # slow-down things a little bit
    if n == 1:
        return 1
    else:
        return n * factorial(n-1, bar)

n = 500
bar = tqdm(total=n)
factorial(n, bar=bar)
</code>```

Body:
I am writing a branch and bound algorithm in python and I am trying to efficiently display the progress.  The algorithm uses recursion and I couldn't figure out any way to make it iterative.  I am wondering if there is a tqdm like module for recursive functions or at least a way to implement a progress bar with recursive functions?  For example, if I was writing an iterative factorial function in python with the tqdm module I would do this:

import tqdm

def factorial(n):
    end_product = 1
    for i in tqdm(range(1, n)):
        end_product *= i
    return end_product

How would I implement a progress bar on a recursive function like this:

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

progress_bar(factorial(1000))

Body:
One solution is initialize progress bar with total= parameter and then call .update() method in each call of recursion.

Something along the lines of this:

from time import sleep
from tqdm import tqdm

def factorial(n, bar):
    bar.update(1)
    sleep(0.01)  # slow-down things a little bit
    if n == 1:
        return 1
    else:
        return n * factorial(n-1, bar)

n = 500
bar = tqdm(total=n)
factorial(n, bar=bar)


问:
How can I emulate PUT/DELETE for Rails and GWT?
I would like to make my application somewhat REST compliant.  I am using Rails on the backend and GWT on the frontend.  I would like to do updates and deletes.  I realize I can do something like mydomain.com/:id/delete (GET) and accomplish the same thing.  However, as I stated previously, I would like to have a REST compliant backend.  Thus, I want to do mydomain.com/:id (DELETE) and have it implicitly call my delete method.

Now, it's my understanding that if a browser (my browser is GWT RequestBuilder) doesn't support DELETE/GET, Rails somehow accomplishes this task with a POST and some other url parameter.  So, how can I accomplish this with a GWT RequestBuilder?

答:
Like @skrat said, the _method=PUT workaround doesn't work for any kind of body where Content-Type is not x-www-form-urlencoded, e.g. XML or JSON. Luckily, there is a header workaround as well:

https://zcox.wordpress.com/2009/06/17/override-the-http-request-method-in-jersey/

So to update a REST resource, just do a POST to its address and add the header X-HTTP-Method-Override: PUT. Rails will interpret this as a PUT to the address.

OwnerDisplayName: JP


问:
Swift Core Data : enums in Core Data
I am trying to implement a core data model which effectively mirrors a view model I use when extracting info from a specific API. I have most of it sorted but am struggling with one attribute.  The attribute in question is:

```<code>enum UnitType: String, Codable {
    case psi
    case kPa
    case litre
    case usg = "gallon"
    case kmph = "km/hour"
    case mph = "miles/hour"
    case celsius
    case fahrenheit
    case kgpmcubed = "kgpercubicmeter"
    case lbspusg = "lbsperusg"
    case lbspftcubed = "lbspercubicfeet"
    case apidensity
    case kg = "kilogram"
    case lbs = "pound"
}
</code>```

I need to be able to set an enum value here as the view controller uses this UnitType property for various calculations based on this enum. How can I create an enum using core data? Essentially I need to be able to set this value like this:

```<code>MyEntity.unitType = viewModel.UnitType
</code>```

答:
You can't store the enum type as such in CoreData, but you can store it's rawValue. Since your enum has a rawValue of String type you can store it's rawValue and convert back to enum by using the enum's init method, like this:

coreDataModel.unitType = viewModel.unitType.rawValue
```

<p>and:</p>

<pre class="lang-swift prettyprint-override"><code>viewModel.unitType = UnitType(rawValue: coreDataModel.unitType)
</code>```

Note: When converting from rawValue to enum type it would be optional because the String could be anything and could not match with any of the case provided in the enum. Hence, it would be required to provide a default value.

Title: Swift Core Data : enums in Core Data

Body:
I am trying to implement a core data model which effectively mirrors a view model I use when extracting info from a specific API. I have most of it sorted but am struggling with one attribute.  The attribute in question is:

enum UnitType: String, Codable {
    case psi
    case kPa
    case litre
    case usg = "gallon"
    case kmph = "km/hour"
    case mph = "miles/hour"
    case celsius
    case fahrenheit
    case kgpmcubed = "kgpercubicmeter"
    case lbspusg = "lbsperusg"
    case lbspftcubed = "lbspercubicfeet"
    case apidensity
    case kg = "kilogram"
    case lbs = "pound"
}

I need to be able to set an enum value here as the view controller uses this UnitType property for various calculations based on this enum. How can I create an enum using core data? Essentially I need to be able to set this value like this:

MyEntity.unitType = viewModel.UnitType

Body:
You can't store the enum type as such in CoreData, but you can store it's rawValue. Since your enum has a rawValue of String type you can store it's rawValue and convert back to enum by using the enum's init method, like this:

coreDataModel.unitType = viewModel.unitType.rawValue

and:

viewModel.unitType = UnitType(rawValue: coreDataModel.unitType)

Note: When converting from rawValue to enum type it would be optional because the String could be anything and could not match with any of the case provided in the enum. Hence, it would be required to provide a default value.


答:
Unfortunately you can't save enums in CoreData.

You can have a String variable in your model:

```<code>class MyEntity: NSManagedObject {
    @NSManaged public var unitType: String
}
</code>```

And then you can convert it to your UnitType on the go.

```<code>myEntity.unitType = viewModel.UnitType.rawValue

viewModel.unitType = UnitType(rawValue: myEntity.unitType)!

</code>```

Title: Swift Core Data : enums in Core Data

Body:
Unfortunately you can't save enums in CoreData.

You can have a String variable in your model:

class MyEntity: NSManagedObject {
    @NSManaged public var unitType: String
}

And then you can convert it to your UnitType on the go.

myEntity.unitType = viewModel.UnitType.rawValue

viewModel.unitType = UnitType(rawValue: myEntity.unitType)!


问:
using css to duplicate html elements
I've been handing a design for a webpage which I'm trying to implement correctly.  This design contains navigation elements which are partially or entirely duplicated all over the page - in particular, links to the main 3 categories for navigation are present on the page no less than 4 times.

I'm no web design expert, but I don't like the idea of having the same content duplicated in the html.  Can I use CSS so that my html contains a single list of navigation links in a sane format, but the standard browser view contains multiple partial duplicates?

(Also, assuming this is possible, is it a good idea?  or would I be better just getting used to the idea that my html is going to contain the same links 4 times?)

EDIT: Actually generating the nav links is not an issue; I was looking to clean up the output html

OwnerDisplayName: akaDruid

ContentLicense: CC BY-SA 2.5

Title: using css to duplicate html elements

LastEditorDisplayName: akaDruid

Body:
It's possible using ::before and ::after.
However, it can only display text (not HTML elements). If it could display HTML elements, then there would be a major security risk...

I could possibly inject a <script> element inside the page, with malicious JavaScript for example.

If CSS was capable of this, then CSS Userscript extensions such as Stylish could be dangerous.


问:
force to change parent component's state by triggering action from child component
I have a functional component and fetch some data in order to populate my state like this:

const [data, setdata] = useState([]);
  useEffect(() => {
    async function fetchData() {
      const res = await fetch("http://localhost:3000/data", {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      res
        .json()
        .then((res) => setdata(res))
        .catch((err) => console.log(err));
    }

    fetchData();
  }, [setdata]);
```

<p>Now I have several buttons that trigger new fetch and those fetch change the data in the server that's why I watch <code>setdata</code> inside the useEffect.</p>

<pre class="lang-js prettyprint-override"><code>async function postOne() {
    const res = await fetch("http://localhost:3000/data", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    res
      .json()
      .then((res) => setdata(res))
      .catch((err) => console.log(err));
  }
async function deleteOne(id) {
    const res = await fetch("http://localhost:3000/data/${id}", {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    res
      .json()
      .then((res) => setdata(res))
      .catch((err) => console.log(err));
  }
</code>```

Now if any child component needs to use deleteOne or others then I have to pass them as props. which causes nested prop drilling. So I was wondering is there any better approach to solve this problem? I was thinking to separate all those fetching functions into a utils/API file and call them only when they need but the only problem I face than how to reassign the parent state (without using setData)

Ok, I can pass any parameter to those methods. Then it might be thought I can easily externalize them, NO. why? when you click any button in the child component and change the data to the server, your parent component will not aware of it(because it didn't re-render hence useEffect didn't trigger) and it still holds the previously fetched data. Which creates the problem. Is the problem clear now?

答:
Well if your code has no relation with your component or its prop, you could just externalize it in another file, a static class would do the job I think.

Here is an example ons tackblitz and here is the code :

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import {MyService} from './MyService';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p>
          Start editing to see some magic happen :)
        </p>
        <button onClick={() => MyService.deleteOne()}>Delete one</button>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
</code>```

MyService.js (Or .ts if you use it):

```<code>export class MyService {
  static deleteOne() {
    console.log('deleted !');
  }
}
</code>```

Body:
I have a functional component and fetch some data in order to populate my state like this:

const [data, setdata] = useState([]);
  useEffect(() => {
    async function fetchData() {
      const res = await fetch("http://localhost:3000/data", {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      res
        .json()
        .then((res) => setdata(res))
        .catch((err) => console.log(err));
    }

    fetchData();
  }, [setdata]);

Now I have several buttons that trigger new fetch and those fetch change the data in the server that's why I watch setdata inside the useEffect.

async function postOne() {
    const res = await fetch("http://localhost:3000/data", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    res
      .json()
      .then((res) => setdata(res))
      .catch((err) => console.log(err));
  }
async function deleteOne(id) {
    const res = await fetch("http://localhost:3000/data/${id}", {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    res
      .json()
      .then((res) => setdata(res))
      .catch((err) => console.log(err));
  }

Now if any child component needs to use deleteOne or others then I have to pass them as props. which causes nested prop drilling. So I was wondering is there any better approach to solve this problem? I was thinking to separate all those fetching functions into a utils/API file and call them only when they need but the only problem I face than how to reassign the parent state (without using setData)

Ok, I can pass any parameter to those methods. Then it might be thought I can easily externalize them, NO. why? when you click any button in the child component and change the data to the server, your parent component will not aware of it(because it didn't re-render hence useEffect didn't trigger) and it still holds the previously fetched data. Which creates the problem. Is the problem clear now?

Body:
Well if your code has no relation with your component or its prop, you could just externalize it in another file, a static class would do the job I think.

Here is an example ons tackblitz and here is the code :

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import {MyService} from './MyService';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p>
          Start editing to see some magic happen :)
        </p>
        <button onClick={() => MyService.deleteOne()}>Delete one</button>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

MyService.js (Or .ts if you use it):

export class MyService {
  static deleteOne() {
    console.log('deleted !');
  }
}


问:
multi-select drop-down results shows Array
im using multi select drop down list im able to select the list i want to update in my database but when i see the results it shows "Array" Instead Of the Selection.

```<code> <select class="selectpicker" multiple data-live-search="true" name="Attendedby" ng-model="Attendedby">
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Relish</option>
</select>
</code>```

```<code>$('select').selectpicker();
</code>```

i dont know why my results display Array, please help

Here is my php

```<code>        if($form_data->action == 'Edit')
        {
            $data = array(
                ':Attendedby' =>    $Attendedby,
                ':EndDate'    =>    $EndDate,
                ':Status'     =>    $Status,
                ':Remarks'    =>    $Remarks,
                ':id'         =>    $form_data->id
            );
            $query = "
            UPDATE cov9
            SET Attendedby = :Attendedby, EndDate = :EndDate, Status = :Status, Remarks = :Remarks
            WHERE id = :id
            ";

            $statement = $connect->prepare($query);
            if($statement->execute($data))
            {
                $message = 'Data Edited';
            }
        }
    }
</code>```

答:
First of all you need to edit the name of the select to Attendedby[] as it expects multiple values and then use something like this to get multiple data into one column:

```<code>$Attendedby = implode(', ', $_POST['Attendedby']);
</code>```

source

Body:
im using multi select drop down list im able to select the list i want to update in my database but when i see the results it shows "Array" Instead Of the Selection.

 <select class="selectpicker" multiple data-live-search="true" name="Attendedby" ng-model="Attendedby">
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Relish</option>
</select>

$('select').selectpicker();

i dont know why my results display Array, please help

Here is my php

        if($form_data->action == 'Edit')
        {
            $data = array(
                ':Attendedby' =>    $Attendedby,
                ':EndDate'    =>    $EndDate,
                ':Status'     =>    $Status,
                ':Remarks'    =>    $Remarks,
                ':id'         =>    $form_data->id
            );
            $query = "
            UPDATE cov9
            SET Attendedby = :Attendedby, EndDate = :EndDate, Status = :Status, Remarks = :Remarks
            WHERE id = :id
            ";

            $statement = $connect->prepare($query);
            if($statement->execute($data))
            {
                $message = 'Data Edited';
            }
        }
    }

Body:
First of all you need to edit the name of the select to Attendedby[] as it expects multiple values and then use something like this to get multiple data into one column:

$Attendedby = implode(', ', $_POST['Attendedby']);

source


问:
How to click the element if the value of the id attribute starts with numbers using Selenium in IE11
I checked the existing answers and it looks like there is no answered question regarding this.

Here it is: selenium 32 bit driver, IE 11, windows 10 64bit.
I need to find the elements with the unique static id = 0idMenuTitle or 1idMenuTitle

HTML code

SPAN onmouseover="if(this.style.backgroundColor !=BgColorON)this.style.backgroundColor = BgColorOVER;" onmouseout="if(this.style.backgroundColor !=BgColorON)this.style.backgroundColor = BgColorOFF;" id=1idMenuTitle class=clsMenuTitle style="MAX-WIDTH: none; MIN-WIDTH: auto; MIN-HEIGHT: auto; MAX-HEIGHT: none; BACKGROUND-COLOR: #cccc" minmax_bound="true" width="100%">menu1

I'm using the following:

```<code>driver.findElement(By.id("0idMenuTitle")).click();
</code>```

and have the error

```<code>org.openqa.selenium.NoSuchElementException: Unable to find element with css selector == #\31 idMenuTitle
</code>```

I'm trying to find with the partial id

```<code>driver.findElement(By.cssSelector("[id*=MenuTitle]")).click();
</code>```

but got

```<code>org.openqa.selenium.ElementNotInteractableException: Element is not displayed
</code>```

I tried with Xpath as well, the same errors.
There is no issue if I'm using FF or GC but I must use IE11, no choice.
There is no problem to find the elements with id that does not start with numbers...

Any idea please?

Update

I'm trying to find the element by id starting with 0, but selenium shows the error regarding css selector (?) and the id #\31 (???)

答:
The reason you are getting Element is not displayed because item is not visible on the page while interacting.Induce WebDriverWait() and wait for elementToBeClickable()

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("[id*='MenuTitle']"))).click();
</code>```

Hope this will helps.

Body:
I checked the existing answers and it looks like there is no answered question regarding this.

Here it is: selenium 32 bit driver, IE 11, windows 10 64bit.
I need to find the elements with the unique static id = 0idMenuTitle or 1idMenuTitle

HTML code

SPAN onmouseover="if(this.style.backgroundColor !=BgColorON)this.style.backgroundColor = BgColorOVER;" onmouseout="if(this.style.backgroundColor !=BgColorON)this.style.backgroundColor = BgColorOFF;" id=1idMenuTitle class=clsMenuTitle style="MAX-WIDTH: none; MIN-WIDTH: auto; MIN-HEIGHT: auto; MAX-HEIGHT: none; BACKGROUND-COLOR: #cccc" minmax_bound="true" width="100%">menu1

I'm using the following:

driver.findElement(By.id("0idMenuTitle")).click();

and have the error

org.openqa.selenium.NoSuchElementException: Unable to find element with css selector == #\31 idMenuTitle

I'm trying to find with the partial id

driver.findElement(By.cssSelector("[id*=MenuTitle]")).click();

but got

org.openqa.selenium.ElementNotInteractableException: Element is not displayed

I tried with Xpath as well, the same errors.
There is no issue if I'm using FF or GC but I must use IE11, no choice.
There is no problem to find the elements with id that does not start with numbers...

Any idea please?

Update

I'm trying to find the element by id starting with 0, but selenium shows the error regarding css selector (?) and the id #\31 (???)

Body:
The reason you are getting Element is not displayed because item is not visible on the page while interacting.Induce WebDriverWait() and wait for elementToBeClickable()

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("[id*='MenuTitle']"))).click();

Hope this will helps.


问:
Convert integer to character int j2me
I want to convert the integer into char.

Example:-

```<code>char c;
for(int i=0;i<10;i++){
    system.out.println(" char==="+c);
}
</code>```

I want to print the c as 0,1,2,3,4.....
I had tried :-

```<code>c=(char)i; --gives error
c=97-i; -----gives a,b,c
</code>```

Title: Convert integer to character int j2me

Body:
I want to convert the integer into char.

Example:-

char c;
for(int i=0;i<10;i++){
    system.out.println(" char==="+c);
}

I want to print the c as 0,1,2,3,4.....
I had tried :-

c=(char)i; --gives error
c=97-i; -----gives a,b,c

Body:
Character.forDigit()

http://download.oracle.com/javase/6/docs/api/java/lang/Character.html


问:
How to recolor multiple pixels in image - Python
I tried this script for replacing the single color of the image. I need to recolor similar colors in image. For example, I have a blue, slate blue. I want to recolor both of these colors with red. But as I mentioned below, I cannot do that. It can be in PIL or OpenCV library in python.

Source of this code: Change specific RGB color pixels to another color, in image file

```<code>import numpy as np
from PIL import Image

image = Image.open('wall.jpg')
data = np.array(im)

r1, g1, b1 = 81, 90, 103 # Original value
r2, g2, b2 = 255, 0, 0 # Value that we want to replace it with

red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]

im = Image.fromarray(data)
im.show()
</code>```

答:
From what I understand by your ' similar color '  is that you need to convert the blue color and its variants to red. I will give you a solution to do this in OpenCV. It is easier to segment colors in the HSV colorspace instead of RGB to create a mask of where the colors are present in that range using cv2.inRange.

After creating a mask as its values are 255 and 0, I divide it by 255 to convert it 1s and 0s followed by converting it to boolean. Then like you showed in your question wherever the mask is true the new color is placed. The code:

```<code>import cv2
import numpy as np

img = cv2.imread('2.jpg')
res = img.copy()
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_green = np.array([40,50,50])
upper_green = np.array([80,255,255])
r2, g2, b2 = 255, 0, 0

mask = cv2.inRange(hsv, lower_green, upper_green)

mask = mask/255
mask = mask.astype(np.bool)
res[:,:,:3][mask] = [b2, g2, r2] # opencv uses BGR

cv2.imshow('image', img)
cv2.imshow('Result', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

I converted the green color as blue was very less in this image. You can use [100, 50, 50] as your lower range and [130, 255, 255] as your upper range.

Body:
I tried this script for replacing the single color of the image. I need to recolor similar colors in image. For example, I have a blue, slate blue. I want to recolor both of these colors with red. But as I mentioned below, I cannot do that. It can be in PIL or OpenCV library in python.

Source of this code: Change specific RGB color pixels to another color, in image file

import numpy as np
from PIL import Image

image = Image.open('wall.jpg')
data = np.array(im)

r1, g1, b1 = 81, 90, 103 # Original value
r2, g2, b2 = 255, 0, 0 # Value that we want to replace it with

red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]

im = Image.fromarray(data)
im.show()

Body:
From what I understand by your ' similar color '  is that you need to convert the blue color and its variants to red. I will give you a solution to do this in OpenCV. It is easier to segment colors in the HSV colorspace instead of RGB to create a mask of where the colors are present in that range using cv2.inRange.

After creating a mask as its values are 255 and 0, I divide it by 255 to convert it 1s and 0s followed by converting it to boolean. Then like you showed in your question wherever the mask is true the new color is placed. The code:

import cv2
import numpy as np

img = cv2.imread('2.jpg')
res = img.copy()
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_green = np.array([40,50,50])
upper_green = np.array([80,255,255])
r2, g2, b2 = 255, 0, 0

mask = cv2.inRange(hsv, lower_green, upper_green)

mask = mask/255
mask = mask.astype(np.bool)
res[:,:,:3][mask] = [b2, g2, r2] # opencv uses BGR

cv2.imshow('image', img)
cv2.imshow('Result', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

I converted the green color as blue was very less in this image. You can use [100, 50, 50] as your lower range and [130, 255, 255] as your upper range.


问:
How to get the content of a json output
I have this json

```<code>Print_r($send);

    {"status":"INSUFFICIENT_APIBALANCE"}
</code>```

and I have this

```<code>$send = var_dump(json_decode($send));
</code>```

Now am trying to do this

```<code>   if ($send->status == "INSUFFICIENT_APIBALANCE"){

     echo "Recharge Now";
}else echo "testing";
</code>```

But am not getting the expected result, please help

答:
Remove var_dump():

$send = json_decode($send);
```

Title: How to get the content of a json output

Body:
I have this json

Print_r($send);

    {"status":"INSUFFICIENT_APIBALANCE"}

and I have this

$send = var_dump(json_decode($send));

Now am trying to do this

   if ($send->status == "INSUFFICIENT_APIBALANCE"){

     echo "Recharge Now";
}else echo "testing";

But am not getting the expected result, please help


问:
A-Frame : How to open a dynamically created a-link in a _blank page
this is specific to A-Frame.

I'm creating an a-link from javascript code:

```<code>var alinkEl = document.createElement('a-link');
alinkEl.setAttribute('href', 'http://www.facebook.com/share.php?u=https://.../' + folder + fileName);
</code>```

This does not work:

```<code>alinkEl.setAttribute('target', '_blank');
</code>```

Any hint?

答: Make sure you have placed an  element to trigger the click event.

Body:
this is specific to A-Frame.

I'm creating an a-link from javascript code:

var alinkEl = document.createElement('a-link');
alinkEl.setAttribute('href', 'http://www.facebook.com/share.php?u=https://.../' + folder + fileName);

This does not work:

alinkEl.setAttribute('target', '_blank');

Any hint?

Body: Make sure you have placed an <a-cursor> element to trigger the click event.


问:
How can I pass POST parameters in a URL?
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like >, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like href="https://stackoverflow.com/questions/6210900/how-to-pass-post-parameters-in-a-url#comment7231173_6210900">Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"

答:
No, you cannot do that. I invite you to read a POST definition.

Or this page: HTTP, request methods

Body:
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like <a href="process_user.php?user=<user>>, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"


问:
Sentiment analysis in realtime feed using NTLk
I would like to know if its feasible analyse headlines news  (using NTLK /sentiment vader) in realtime/streaming news.

Below the code that feed my system of news (headlines)

```<code>import praw
import time

reddit = praw.Reddit(client_id='xxxx',
client_secret='MLK5gKaEM2FxxxxxxxxI', user_agent='testing_api')

  # must be edited to properly authenticate
subreddit = reddit.subreddit('worldnews')
seen_submissions = set()

while True:
    for submission in subreddit.new(limit=10):
        if submission.fullname not in seen_submissions:
            seen_submissions.add(submission.fullname)
            print('{} {}\n'.format(submission.title, submission.url))
    time.sleep(60)  # sleep for a minute (60 seconds)
</code>```

Using  SentimentIntensityAnalyzer  I built:

```<code>from IPython import display
import math
from pprint import pprint
import pandas as pd
import numpy as np
import nltk
nltk.download('vader_lexicon')
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='darkgrid', context='talk', palette='Dark2')

import praw

reddit = praw.Reddit(client_id='xxxx',
client_secret='MLK5gKaEM2FxxxxxxxxI', user_agent='testing_api')
subreddit = reddit.subreddit('worldnews')

headlines = set()

while True:
  for submission in subreddit.new(limit=10):
   if submission.title not in headlines:
       headlines.add(submission.title)
time.sleep(60)  # sleep for a minute (60 seconds)

from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA

sia = SIA()
results = []

for line in headlines:
    pol_score = sia.polarity_scores(line)
    pol_score['headline'] = line
    results.append(pol_score)

pprint(results[], width=100)
</code>```

I can´t see anything displayed in the console... I'm expecting to see something like (in realtime)

```<code> {'compound': -0.5267,
  'headline': 'Report: Nearly Half of Americans Breathing Unhealthy Air',
  'neg': 0.327,
  'neu': 0.673,
  'pos': 0.0},
 {'compound': -0.0754,
  'headline': 'The Implications of Trump Derangement Syndrome | Even now, vehement Trump '
              'supporters seem to believe that most criticism of the president is explained by '
              'widespread TDS.',
  'neg': 0.11,
  'neu': 0.791,
  'pos': 0.1}]
</code>```

答:
It doesn't look like you included a complete example.  You still need to call polarity_scores() and add it to your data structure.

For example, if you were to use a dictionary:

```<code>reddit = praw.Reddit( ... )
sub = reddit.subreddit('worldnews')
analyzer = SentimentIntensityAnalyzer()

results = {}
posts = sub.new(limit=10)
for post in posts:
    title = post.title
    if title in results:
        # skip title if previously encountered
        continue

    score = analyzer.polarity_scores(title)
    results[title] = score
    results[title]['headline'] = title

</code>```

You could also make the query and loop more efficient by searching by date or just keeping track of the timestamp on the last post seen and short circuiting a loop for the other posts and use the original set() like you started with.

```<code>results = set()

...

    if post.created > last_date:
        break

    last_date = post.created
    score = analyzer.polarity_scores(post.title)
    score['headline'] = post.title
    results.add(score)

</code>```

You might find this tutorial helpful to get more detail about building a system like that:
https://www.codeproject.com/Articles/5269358/Introducing-NLTK-for-Natural-Language-Processing-w

Body:
I would like to know if its feasible analyse headlines news  (using NTLK /sentiment vader) in realtime/streaming news.

Below the code that feed my system of news (headlines)

import praw
import time

reddit = praw.Reddit(client_id='xxxx',
client_secret='MLK5gKaEM2FxxxxxxxxI', user_agent='testing_api')

  # must be edited to properly authenticate
subreddit = reddit.subreddit('worldnews')
seen_submissions = set()

while True:
    for submission in subreddit.new(limit=10):
        if submission.fullname not in seen_submissions:
            seen_submissions.add(submission.fullname)
            print('{} {}\n'.format(submission.title, submission.url))
    time.sleep(60)  # sleep for a minute (60 seconds)

Using  SentimentIntensityAnalyzer  I built:

from IPython import display
import math
from pprint import pprint
import pandas as pd
import numpy as np
import nltk
nltk.download('vader_lexicon')
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='darkgrid', context='talk', palette='Dark2')

import praw

reddit = praw.Reddit(client_id='xxxx',
client_secret='MLK5gKaEM2FxxxxxxxxI', user_agent='testing_api')
subreddit = reddit.subreddit('worldnews')

headlines = set()

while True:
  for submission in subreddit.new(limit=10):
   if submission.title not in headlines:
       headlines.add(submission.title)
time.sleep(60)  # sleep for a minute (60 seconds)

from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA

sia = SIA()
results = []

for line in headlines:
    pol_score = sia.polarity_scores(line)
    pol_score['headline'] = line
    results.append(pol_score)

pprint(results[], width=100)

I can´t see anything displayed in the console... I'm expecting to see something like (in realtime)

 {'compound': -0.5267,
  'headline': 'Report: Nearly Half of Americans Breathing Unhealthy Air',
  'neg': 0.327,
  'neu': 0.673,
  'pos': 0.0},
 {'compound': -0.0754,
  'headline': 'The Implications of Trump Derangement Syndrome | Even now, vehement Trump '
              'supporters seem to believe that most criticism of the president is explained by '
              'widespread TDS.',
  'neg': 0.11,
  'neu': 0.791,
  'pos': 0.1}]

Body:
It doesn't look like you included a complete example.  You still need to call polarity_scores() and add it to your data structure.

For example, if you were to use a dictionary:

reddit = praw.Reddit( ... )
sub = reddit.subreddit('worldnews')
analyzer = SentimentIntensityAnalyzer()

results = {}
posts = sub.new(limit=10)
for post in posts:
    title = post.title
    if title in results:
        # skip title if previously encountered
        continue

    score = analyzer.polarity_scores(title)
    results[title] = score
    results[title]['headline'] = title

You could also make the query and loop more efficient by searching by date or just keeping track of the timestamp on the last post seen and short circuiting a loop for the other posts and use the original set() like you started with.

results = set()

...

    if post.created > last_date:
        break

    last_date = post.created
    score = analyzer.polarity_scores(post.title)
    score['headline'] = post.title
    results.add(score)

You might find this tutorial helpful to get more detail about building a system like that:
https://www.codeproject.com/Articles/5269358/Introducing-NLTK-for-Natural-Language-Processing-w


问:
R12/timeout error deploying multi-page dash app to heroku
Trying to learn the ropes of Dash and have made this toy dashboard to display solutions to the heat equation. The single page version deployed to heroku works fine but I'm getting this timeout error with the multi-page version (see logs below). It works fine locally.

I made what I understand to be the necessary changes to get it to deploy properly, namely to change the procfile from app:server to index:server and then import app.server into index.

I tried assigning the server in index versus importing from app and tried adding this line (server.secret_key = os.environ.get('secret_key', 'secret')) that popped up in a few posts I found of people with similar problems.

I also added some print statements to index and it doesn't seem like the server ever makes it inside.

github link: https://github.com/mackwn/dashdiffeq

Below is my logs from Heroku from right after I get the 'build succeded' message:

```<code>2020-05-22T12:49:23.000000+00:00 app[api]: Build succeeded
2020-05-22T12:49:31.741895+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2020-05-22T12:49:39.870656+00:00 app[web.1]: [2020-05-22 12:49:39 +0000] [4] [INFO] Shutting down: Master
2020-05-22T12:49:39.924058+00:00 heroku[web.1]: Error R12 (Exit timeout) -> At least one process failed to exit within 30 seconds of SIGTERM
2020-05-22T12:49:39.927273+00:00 heroku[web.1]: Stopping remaining processes with SIGKILL
2020-05-22T12:49:40.109385+00:00 heroku[web.1]: Process exited with status 137
2020-05-22T12:50:48.940059+00:00 app[web.1]: [2020-05-22 12:50:48 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:10)
2020-05-22T12:50:48.940250+00:00 app[web.1]: [2020-05-22 12:50:48 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:11)
2020-05-22T12:50:48.981714+00:00 app[web.1]: [2020-05-22 12:50:48 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-05-22T12:50:49.199462+00:00 app[web.1]: [2020-05-22 12:50:49 +0000] [11] [INFO] Worker exiting (pid: 11)
.....(this kind of keeps going on until I try to load a page)
2020-05-22T12:55:22.232394+00:00 app[web.1]: [2020-05-22 12:55:22 +0000] [4] [DEBUG] 2 workers
2020-05-22T12:56:22.333270+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/" host=dashdiffeq410.herokuapp.com request_id=22145128-27cc-4397-a615-9916c6cfc286 fwd="71.142.111.162" dyno=web.1 connect=1ms service=30001ms status=503 bytes=0 protocol=https
2020-05-22T12:56:52.575355+00:00 app[web.1]: [2020-05-22 12:56:52 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:100)
2020-05-22T12:56:52.575554+00:00 app[web.1]: [2020-05-22 12:56:52 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:101)
2020-05-22T12:56:52.673002+00:00 app[web.1]: [2020-05-22 12:56:52 +0000] [100] [INFO] Worker exiting (pid: 100)
2020-05-22T12:56:52.784718+00:00 app[web.1]: [2020-05-22 12:56:52 +0000] [101] [INFO] Worker exiting (pid: 101)
2020-05-22T12:56:53.206573+00:00 app[web.1]: [2020-05-22 12:56:53 +0000] [118] [INFO] Booting worker with pid: 118
2020-05-22T12:56:53.279766+00:00 app[web.1]: [2020-05-22 12:56:53 +0000] [4] [DEBUG] 1 workers
2020-05-22T12:56:53.284164+00:00 app[web.1]: [2020-05-22 12:56:53 +0000] [119] [INFO] Booting worker with pid: 119
2020-05-22T12:56:53.313027+00:00 app[web.1]: [2020-05-22 12:56:53 +0000] [4] [DEBUG] 2 workers
2020-05-22T12:56:54.373035+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/favicon.ico" host=dashdiffeq410.herokuapp.com request_id=2cb221f7-3c14-4397-b0b1-e596037a17ed fwd="71.142.111.162" dyno=web.1 connect=1ms service=30000ms status=503 bytes=0 protocol=https
2020-05-22T12:58:23.565869+00:00 app[web.1]: [2020-05-22 12:58:23 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:118)
2020-05-22T12:58:23.572088+00:00 app[web.1]: [2020-05-22 12:58:23 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:119)
</code>```

答: Found the problem. Running the function for solving the differential equation was taking too long on the server which caused the timeout. The development server didn't care how long it took to run the math to generate the plot. Solve the problem by only letting users select inputs that would not cause time outs and would also make sure the page was reasonably responsive. </p>

Body:
Trying to learn the ropes of Dash and have made this toy dashboard to display solutions to the heat equation. The single page version deployed to heroku works fine but I'm getting this timeout error with the multi-page version (see logs below). It works fine locally.

I made what I understand to be the necessary changes to get it to deploy properly, namely to change the procfile from app:server to index:server and then import app.server into index.

I tried assigning the server in index versus importing from app and tried adding this line (server.secret_key = os.environ.get('secret_key', 'secret')) that popped up in a few posts I found of people with similar problems.

I also added some print statements to index and it doesn't seem like the server ever makes it inside.

github link: https://github.com/mackwn/dashdiffeq

Below is my logs from Heroku from right after I get the 'build succeded' message:

2020-05-22T12:49:23.000000+00:00 app[api]: Build succeeded
2020-05-22T12:49:31.741895+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2020-05-22T12:49:39.870656+00:00 app[web.1]: [2020-05-22 12:49:39 +0000] [4] [INFO] Shutting down: Master
2020-05-22T12:49:39.924058+00:00 heroku[web.1]: Error R12 (Exit timeout) -> At least one process failed to exit within 30 seconds of SIGTERM
2020-05-22T12:49:39.927273+00:00 heroku[web.1]: Stopping remaining processes with SIGKILL
2020-05-22T12:49:40.109385+00:00 heroku[web.1]: Process exited with status 137
2020-05-22T12:50:48.940059+00:00 app[web.1]: [2020-05-22 12:50:48 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:10)
2020-05-22T12:50:48.940250+00:00 app[web.1]: [2020-05-22 12:50:48 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:11)
2020-05-22T12:50:48.981714+00:00 app[web.1]: [2020-05-22 12:50:48 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-05-22T12:50:49.199462+00:00 app[web.1]: [2020-05-22 12:50:49 +0000] [11] [INFO] Worker exiting (pid: 11)
.....(this kind of keeps going on until I try to load a page)
2020-05-22T12:55:22.232394+00:00 app[web.1]: [2020-05-22 12:55:22 +0000] [4] [DEBUG] 2 workers
2020-05-22T12:56:22.333270+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/" host=dashdiffeq410.herokuapp.com request_id=22145128-27cc-4397-a615-9916c6cfc286 fwd="71.142.111.162" dyno=web.1 connect=1ms service=30001ms status=503 bytes=0 protocol=https
2020-05-22T12:56:52.575355+00:00 app[web.1]: [2020-05-22 12:56:52 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:100)
2020-05-22T12:56:52.575554+00:00 app[web.1]: [2020-05-22 12:56:52 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:101)
2020-05-22T12:56:52.673002+00:00 app[web.1]: [2020-05-22 12:56:52 +0000] [100] [INFO] Worker exiting (pid: 100)
2020-05-22T12:56:52.784718+00:00 app[web.1]: [2020-05-22 12:56:52 +0000] [101] [INFO] Worker exiting (pid: 101)
2020-05-22T12:56:53.206573+00:00 app[web.1]: [2020-05-22 12:56:53 +0000] [118] [INFO] Booting worker with pid: 118
2020-05-22T12:56:53.279766+00:00 app[web.1]: [2020-05-22 12:56:53 +0000] [4] [DEBUG] 1 workers
2020-05-22T12:56:53.284164+00:00 app[web.1]: [2020-05-22 12:56:53 +0000] [119] [INFO] Booting worker with pid: 119
2020-05-22T12:56:53.313027+00:00 app[web.1]: [2020-05-22 12:56:53 +0000] [4] [DEBUG] 2 workers
2020-05-22T12:56:54.373035+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/favicon.ico" host=dashdiffeq410.herokuapp.com request_id=2cb221f7-3c14-4397-b0b1-e596037a17ed fwd="71.142.111.162" dyno=web.1 connect=1ms service=30000ms status=503 bytes=0 protocol=https
2020-05-22T12:58:23.565869+00:00 app[web.1]: [2020-05-22 12:58:23 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:118)
2020-05-22T12:58:23.572088+00:00 app[web.1]: [2020-05-22 12:58:23 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:119)


问:
add start from constraint to a column in mysql
hey i am creating an application for invoicing(computer generated bill).
i have a table sales_log where ref no. column is set to auto_increment.i didnt assign the start value. i mean if the ref no. of 1st bill is 101 then i should automatically get 102..103...etc for the rest...i just dont know how to alter the table constraint and set a starting value for that column.
here is the description of my table</p>

```<code>mysql> desc sales_log;
+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| date     | date    | YES  |     | NULL    |                |
| item_id  | int(11) | YES  | MUL | NULL    |                |
| C_Id     | int(11) | YES  | MUL | NULL    |                |
| Quantity | double  | YES  |     | NULL    |                |
| Ref      | int(11) | NO   | PRI | NULL    | auto_increment |
| price    | double  | YES  |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+
</code>```

答:
To set the AUTO_INCREMENT back to 1 (for example), execute this:</p>

```<code>ALTER TABLE sales_log AUTO_INCREMENT = 1
</code>```

Body:
hey i am creating an application for invoicing(computer generated bill).
i have a table sales_log where ref no. column is set to auto_increment.i didnt assign the start value. i mean if the ref no. of 1st bill is 101 then i should automatically get 102..103...etc for the rest...i just dont know how to alter the table constraint and set a starting value for that column.
here is the description of my table

mysql> desc sales_log;
+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| date     | date    | YES  |     | NULL    |                |
| item_id  | int(11) | YES  | MUL | NULL    |                |
| C_Id     | int(11) | YES  | MUL | NULL    |                |
| Quantity | double  | YES  |     | NULL    |                |
| Ref      | int(11) | NO   | PRI | NULL    | auto_increment |
| price    | double  | YES  |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+

Body:
To set the AUTO_INCREMENT back to 1 (for example), execute this:

ALTER TABLE sales_log AUTO_INCREMENT = 1


问:
Nginx Ingress - 502 Bad Gateway - failed (111: Connection refused) while connecting to upstream - Kubernetes
I am receiving the following error from the ingress-nginx-controller, which ultimately gives me the 502 Bad Gateway. I can port forward into my nodejs service without error.

2020/05/30 21:31:12 [error] 485#485: *18798 connect() failed (111: Connection refused) while connecting to upstream, client: 177.183.249.235, server: _, request: "GET /favicon.ico HTTP/1.1", upstream: "http://10.244.0.249:3000/favicon.ico", host: "167.172.15.8", referrer: "http://167.172.15.8/"

I am using Pulumi and the following is the defined service:

```<code>export const frontendService = new k8s.core.v1.Service(config.appNameFrontend, {
  metadata: {
    namespace: namespace.metadata.name,
    labels: {
      app: config.appNameFrontend,
      service: config.appNameFrontend
    }
  },
  spec: {
    ports: [{
      name: "http",
      port: 80,
      targetPort: 3000
    }],
    selector: {
      app: config.appNameFrontend
    }
  }
})
`
</code>```

The deployment:

```<code>const frontendDeployment = new k8s.apps.v1.Deployment(`${config.appNameFrontend}-${config.version}`, {
  metadata: {
    namespace: namespace.metadata.name,
    labels: {
      app: config.appNameFrontend,
      version: config.version,
    },
  },
  spec: {
    replicas: 1,
    selector: {
      matchLabels: {
        app: config.appNameFrontend,
        version: config.version
      }
    },
    template: {
      metadata: {
        labels: {
          app: config.appNameFrontend,
          version: config.version
        }
      },
      spec: {
        serviceAccountName: frontendServiceAccount.metadata.name,
        containers: [{
          name: config.appNameFrontend,
          image: "registry.digitalocean.com/connecttv/connecttv-frontend:latest",
          imagePullPolicy: "Always",
          resources: {
            limits: {
              cpu: "1000m"
            },
            requests: {
              cpu: "100m"
            }
          },
          ports: [{
            containerPort: 3000
          }]
        }],
        restartPolicy: "Always",
        imagePullSecrets: [{
          name: pulumi.interpolate`${imagePullSecret.metadata.name}`
        }]
      }
    }
  }
})
</code>```

and finally the ingress:

```<code>const frontendIngress = new k8s.networking.v1beta1.Ingress(`frontend-ingress-${config.projectName}-v1`, {
  metadata: {
    namespace: namespace.metadata.name,
    annotations: {
      "kubernetes.io/ingress.class": "nginx"
    }
  },
  spec: {
    rules: [
      {
        http: {
          paths: [
            {
              path: "/",
              backend: {
                serviceName: frontendService.metadata.name,
                servicePort: frontendService.spec.ports[0].port,
              },
            }
          ],
        },
      },
    ],
  },
});
</code>```

Any ideas what would be causing this?

I used the 0.32.0 version to install nginx ingress (digitalocean).

However, i modified the deploy.yaml to externalTrafficPolicy: Cluster from local.

答: Fixed. Always check your dockerfile! It was set to listen to localhost only!!!!

Body:
I am receiving the following error from the ingress-nginx-controller, which ultimately gives me the 502 Bad Gateway. I can port forward into my nodejs service without error.

2020/05/30 21:31:12 [error] 485#485: *18798 connect() failed (111: Connection refused) while connecting to upstream, client: 177.183.249.235, server: _, request: "GET /favicon.ico HTTP/1.1", upstream: "http://10.244.0.249:3000/favicon.ico", host: "167.172.15.8", referrer: "http://167.172.15.8/"

I am using Pulumi and the following is the defined service:

export const frontendService = new k8s.core.v1.Service(config.appNameFrontend, {
  metadata: {
    namespace: namespace.metadata.name,
    labels: {
      app: config.appNameFrontend,
      service: config.appNameFrontend
    }
  },
  spec: {
    ports: [{
      name: "http",
      port: 80,
      targetPort: 3000
    }],
    selector: {
      app: config.appNameFrontend
    }
  }
})
`

The deployment:

const frontendDeployment = new k8s.apps.v1.Deployment(`${config.appNameFrontend}-${config.version}`, {
  metadata: {
    namespace: namespace.metadata.name,
    labels: {
      app: config.appNameFrontend,
      version: config.version,
    },
  },
  spec: {
    replicas: 1,
    selector: {
      matchLabels: {
        app: config.appNameFrontend,
        version: config.version
      }
    },
    template: {
      metadata: {
        labels: {
          app: config.appNameFrontend,
          version: config.version
        }
      },
      spec: {
        serviceAccountName: frontendServiceAccount.metadata.name,
        containers: [{
          name: config.appNameFrontend,
          image: "registry.digitalocean.com/connecttv/connecttv-frontend:latest",
          imagePullPolicy: "Always",
          resources: {
            limits: {
              cpu: "1000m"
            },
            requests: {
              cpu: "100m"
            }
          },
          ports: [{
            containerPort: 3000
          }]
        }],
        restartPolicy: "Always",
        imagePullSecrets: [{
          name: pulumi.interpolate`${imagePullSecret.metadata.name}`
        }]
      }
    }
  }
})

and finally the ingress:

const frontendIngress = new k8s.networking.v1beta1.Ingress(`frontend-ingress-${config.projectName}-v1`, {
  metadata: {
    namespace: namespace.metadata.name,
    annotations: {
      "kubernetes.io/ingress.class": "nginx"
    }
  },
  spec: {
    rules: [
      {
        http: {
          paths: [
            {
              path: "/",
              backend: {
                serviceName: frontendService.metadata.name,
                servicePort: frontendService.spec.ports[0].port,
              },
            }
          ],
        },
      },
    ],
  },
});

Any ideas what would be causing this?

I used the 0.32.0 version to install nginx ingress (digitalocean).

However, i modified the deploy.yaml to externalTrafficPolicy: Cluster from local.


问:
How to create sh script which will run SQL file on CentOS without sqlplus lib
I'd need to create a sh script, which will connect to Oracle DB and then execute a SQL file.
The problem is that sqlplus is not installed on that Cent-OS machine and most probably it won't be installed either.
Is there a way how to do this?</p>

答:
You can’t. You need to install oracle client which include sqlplus or sqlloader.
Or you can use Python and library Cx_Oracle, but you still need sqlclient to connect to database.
If you don’t want to install oracle client, you can use external table to load data to database or some etl tool.</p>


问:
Uncaught TypeError: Cannot read property '$bvModal' of undefined vue
I'm guessing this isn't scoped properly in my function, when I try to call
this.$bvModal.show("signinModal") to show my modal I get this error:

```<code>Uncaught TypeError: Cannot read property '$bvModal' of undefined
</code>```

I know that $bvModal should be scoped to the component and I'm not using any arrow functions so I don't see where my issue is coming from, is there a way to get around this in vue that I'm missing?

```<code><template>
  <div class="container">

    <b-modal id="signinModal" @hidden="signinUser($event)" :no-close-on-backdrop="true">
      <input id="email" v-model="email" placeholder="email">
      <input id="pass" v-model="password" placeholder="password">
    </b-modal>

    <form v-on:submit.prevent class="cube" v-if="modalShow == false">
       <div>
         <input id="title" v-model="title" placeholder="title">
       </div>

       <div>
         <textarea id="body" v-model="body" placeholder="body"></textarea>
       </div>

       <div>
         <b-button id ="postbtn" @click="addpost($event)" variant="outline-success">Publish</b-button>
       </div>
    </form>
  </div>
</template>

<script>
const {fb,db} = require('../../fireconfig.js')

export default {
  name: 'AddPost',
  data:function(){
    return{
        title: '',
        body: '',
        modalShow: true,
        email: '',
        password: ''
    }
  },
  mounted(){
    this.$bvModal.show("signinModal")
  },

  methods:{
    signinUser:function(e){
      e.preventDefault()
      fb.auth()
        .signInWithEmailAndPassword(this.email, this.password)
        .catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;

          if (errorCode === 'auth/wrong-password' || errorCode === 'auth/invalid-email') {
            alert('password or email incorrect',errorCode,errorMessage);
            this.$bvModal.show("signinModal") //---------------ERROR THROWN HERE

         } else {
            console.log('user successfully authenticated')
         }
      });
    },

    addpost(event){
      event.preventDefault()
      try {
        let data = {
           title: this.title,
           body: this.body
        }

        db.collection('articles').doc(this.title).set(data)
        console.log('uploaded data to db')
      } catch(err) {
        console.log('there was an error',err)
      }
    },
  }
}
</script>

</code>```

答:
Make your function to an arrow functions in your catch, it will reference this with the vue component.

```<code>signinUser:function(e){
    e.preventDefault()
   fb.auth().signInWithEmailAndPassword(this.email, this.password)
          .catch( error => {
              // Handle Errors here.
              var errorCode = error.code;
              var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password' || errorCode === 'auth/invalid-email') {
              alert('password or email incorrect',errorCode,errorMessage);
              this.$bvModal.show("signinModal") //---------------ERROR THROWN HERE

            } else {
              console.log('user successfully authenticated')

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

Body:
I'm guessing this isn't scoped properly in my function, when I try to call
this.$bvModal.show("signinModal") to show my modal I get this error:

Uncaught TypeError: Cannot read property '$bvModal' of undefined

I know that $bvModal should be scoped to the component and I'm not using any arrow functions so I don't see where my issue is coming from, is there a way to get around this in vue that I'm missing?

<template>

      <input id="email" v-model="email" placeholder="email">
      <input id="pass" v-model="password" placeholder="password">

    <form v-on:submit.prevent class="cube" v-if="modalShow == false">

         <input id="title" v-model="title" placeholder="title">

         <textarea id="body" v-model="body" placeholder="body"></textarea>

         Publish

    </form>

</template>

Body:
Make your function to an arrow functions in your catch, it will reference this with the vue component.

signinUser:function(e){
    e.preventDefault()
   fb.auth().signInWithEmailAndPassword(this.email, this.password)
          .catch( error => {
              // Handle Errors here.
              var errorCode = error.code;
              var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password' || errorCode === 'auth/invalid-email') {
              alert('password or email incorrect',errorCode,errorMessage);
              this.$bvModal.show("signinModal") //---------------ERROR THROWN HERE

            } else {
              console.log('user successfully authenticated')

            }
    });
  },


问:
Raw Image Python 4 Dimensions
A raw image in Python has four dimensions.
For an Image I have a shape like that:
5182 3444 1 7 </p>

<p>I gues the first two dimensions are for height and width but what does the 1 and the 7 stand for?
Can somoene explain, please? </p>

答:
I'm guessing you're using an ML framework such as PyTorch, because they load images with 4 dimensions. Those 4 dimensions from the outside in are:

n_samples / batch_size: GPUs are efficient for processing many images in parallel, so you are expected so feed in a whole batch of say 32 distinct images.

n_channels: Color (RGB) images have 3 values per pixel; red, green, blue; these are channels.

height

width

See also this question.

Title: Raw Image Python 4 Dimensions

Body:
A raw image in Python has four dimensions.
For an Image I have a shape like that:
5182 3444 1 7

I gues the first two dimensions are for height and width but what does the 1 and the 7 stand for?
Can somoene explain, please?


问:
Phoenix/Elixir: tips when to create a new Context
I've started a number of Phoenix projects, but I always find it challenging to properly define Contexts. I've often ended up creating "sub-Contexts" within Contexts, which I think is fine, but it's never perfect.

My question is what tips do people have for defining Phoenix Contexts? or some sort of litmus test for where to draw lines between Contexts.

As an example:

I have an app that integrates with Slack's API, and uses Google's Map API to look up timezone/location information, and uses Stripe for payments.

I started with a Slack Context, but quickly found that I was mixing Slack API logic with my app's actual business logic.

I put all Google Maps stuff under a Google Context

I put all Stripe stuff under a Payments Context

At this point I'm basically separating context by the third-party tool, but ended up with an overly bloated Slack Context. It's also challenging to reframe one's perspective and redefine Contexts once an app has already been established.

答:
Quick links for reference

BoundedContext by Martin Fowler (bliki)

Domain Driven Design Distilled by Vaughn Vernon (book)

Designing Elixir Systems With OTP by James Edward Gray, II and Bruce Tate (book)

Preface

I'll start off by saying that I don't like that we are calling the notion of grouping modules that deal with the same domain problems "Phoenix contexts" because Phoenix is a web framework and these contexts are dealing with the business logic (aka. core functions) of your application.
That said, I am glad that they (Phoenix) are spreading the word about better, more scalable software architecture.

What are contexts

The way Phoenix docs describe them is "Contexts are dedicated modules that expose and group related functionality".
This describes contexts from a code point of view, but it doesn't describe contexts conceptually. To get a clearer picture of what a (bounded) context is, I suggest checking out BoundedContext by Martin Fowler. In short, they are a way to design and architecture your software so that modules that deal with a specific domain or part of a domain remain encapsulated within a bubble, where they speak their own language which everyone dealing with this problem is familiar with.

Your problem

You mentioned that you created a Slack context, but you ended up mixing the Slack API logic with your business logic.

You are not alone in being confused by this. I am working with a company where I am part of the hiring pipeline. Basically I assess the task assignments submitted by candidates applying for a job and this is one of the most common designs that I encounter.

The problem is that you are thinking about contexts solely in one dimension. You are solely thinking of how to group modules by their similarity in a domain - I like to think of this as "horizontal" grouping.

The trick is to also group modules by their similarity in terms of your application itself aka. which layer of the application the code is dealing with.

What are layers

Layers are a way to group modules that are similar in what tasks they are doing in terms of your application architecture. For instance, you can have "business logic" (core, immutable functions) layer, a layer of modules that are dealing with external services (HTTP requests, Slack libraries, Dropbox libraries, ...), a layer of modules that are dealing with application state and lifecycle (GenServers, Supervisors, ...), a layer of modules that are dealing with worker processes and routines (workers modules, ...) etc.

A great resource on layers and how to structure your application that these layers connect to each other as best as possible is Designing Elixir Systems With OTP by James Edward Gray, II and Bruce Tate.

This type of grouping is more "vertical" aka. grouping by layers.

You know you have some logic that deals with Slack, so you create a Slack context. You know you have some Google logic, so you create a Google context. Then you also have your main business logic, so you create a Timezones (for example) context.

Notice the difference between the three contexts - Timezones is pretty much a business logic context. We know that some fancy date-time calculations are happening there and that's it. But with Slack and Google it gets more tricky. There might be HTTP requests, some vendor specific error handling, mapping, filtering, reducing etc.

How to combine contexts and layers

It's a difficult question to answer this for you because in order to create good contexts I would have to be a domain expert in datetime manipulation, where we search for optimal meeting times (according to your app, When to chat). Similarily, to be able to create appropriate modules in appropriate layers I would have to know a bit more what your application is doing from a technical point of view.

I will try, however, to guess what it COULD be doing, just so I can give you an example.

The layers

I think the first and most important layer is of course your business logic layer.
This is where your secret sauce is. Your magic date manipulation where you calculate the best meeting times. Your modules for this layer can exist in lib/when_to_chat/

The second layer we will need is the web layer. I am assuming your application exploses some sort of a REST API for other services to call. This is where Phoenix lives basically. The controllers, views, templates, channels etc.; this layer can be at lib/when_to_chat_web/ (as per Phoenix convention)

The third layer we need is the services layer. This is where your Slack, Stripe, Google maps integrations are. Here you are making HTTP requests, using libraries that call external services, handling timeouts etc.; the modules for this layer can reside in lib/when_to_chat_services/ for example

Another layer you might need is the database/storage layer. If you are using Ecto and you are persisting some data, all the queries and schemas, validations etc. should reside in this specific layer. The directory for this layer could be lib/when_to_chat_storage/

This is just from the top of my head when I was thinking about what your code might be doing. Maybe you need another layer to deal with GenServers and Supervisors and such.

The contexts

Now for the contexts. Remember that contexts group your modules by what they do, and layers group them by how they do it.
This also means that you might have different contexts in different layers. For instance, if you think about it, Slack is a service that we are integrating. It makes sense to have a Slack context in the service layer, but not in the business logic layer.

So first off, in the business logic layer you could have 3 contexts:
 - timezones <- this is your core magic (example function: find_best_time_for_users(user))
 - payments <- this is where you calculate invoices, discounts etc. (example function: process_payment(user, amount, selected_provider)
 - notifications <- this is where you push messages or raise alerts etc. (example function notify_via_slack(user, notification)

Next, in the web layer, you have the standard Phoenix stuff, which we will skip here.

After that, in the services layer, you might have the 3 contexts: slack, stripe and google_maps. Inside of them, you deal with some data importing/exporting, but not any core calculation logic.

Finally, in the storage layer, you could have an accounts context for storing user info and a payments context for dealing with payment queries, tables, schemas, etc..

So how does it all look?

Your project might end up looking something like this:

Of course this is as much art as it is science. The lines are not super clear and sometimes layers do leak a bit from one to another. The good thing is that with years of experience we learn and improve so refactors are always making our code better!

For even more info on how to design your applications so that they focus on business I suggest checking out Domain Driven Design Distilled by Vaughn Vernon.

Final note: my answer is not some sort of standardized way of dealing with software architecture. It's a mix of teachings from the linked references and my own ideas. Feel free to experiment and figure out what works for you and your team!


问:
Netbeans doesn't show php 7
I just downloaded xampp(7.0.8) from xampp download page and installed with no error but when I create a new project in Netbeans it shows only 5.4 as the highest php version whereas what I have is php7. I tried with xampp 5.6.23 and still Netbeans did not show php5.6.

What's happening? How can I make Netbeans show php7 or php5.6 . I have xampp for both versions.

答:
Unfortunately the Netbeans still doesn't support some PHP7 syntax features like the typed properties.
E.g.

```<code>   Class Foo { public int $bar }
</code>```

shows a syntax error hint because of the "INT" attribute of $bar property despite that is allowed by PHP7

Other e.g.

```<code>public function foo(?int $bar){}
</code>```

also shows syntax error due to the question mark.

I wish they will publish an update or even a pack.

Title: Netbeans doesn't show php 7

Body:
Unfortunately the Netbeans still doesn't support some PHP7 syntax features like the typed properties.
E.g.

   Class Foo { public int $bar }

shows a syntax error hint because of the "INT" attribute of $bar property despite that is allowed by PHP7

Other e.g.

public function foo(?int $bar){}

also shows syntax error due to the question mark.

I wish they will publish an update or even a pack.


问:
Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
I am parsing a string to a float in Java.

But it throws this exception. I am quite confused with thisproblem since "0.353" is obviously a number which should be parsed by the parseFloat() method.

Did I miss something? Appreciate your help!

```<code>            String FitMappath = PathofFile.path+"FitnessMap.txt";
            FileInputStream in = new FileInputStream(FitMappath);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //Read File Line By Line
            String line;

            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");            //Split into three elements
                float fitness = Float.parseFloat(parts[2]);// String to float
            }
</code>```

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:110)
    at java.base/java.lang.Float.parseFloat(Float.java:549)
    at DelFitnessCalculation.<init>(DelFitnessCalculation.java:66)
    at Main.main(Main.java:49)
```

<p>First three lines of my input file:</p>

```Q0085   ATP6    0.353
YDR034C-A   YDR034C-A   0.359
tORF13  tORF13  0.360
```

答:
Place this:

```<code>System.out.println("parts[2]=" + parts[2]);
</code>```

between the two lines of code that you shared. I think you will find what you're looking for, which is the cause of your error.

Body:
I am parsing a string to a float in Java.

But it throws this exception. I am quite confused with thisproblem since "0.353" is obviously a number which should be parsed by the parseFloat() method.

Did I miss something? Appreciate your help!

            String FitMappath = PathofFile.path+"FitnessMap.txt";
            FileInputStream in = new FileInputStream(FitMappath);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //Read File Line By Line
            String line;

            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");            //Split into three elements
                float fitness = Float.parseFloat(parts[2]);// String to float
            }

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:110)
    at java.base/java.lang.Float.parseFloat(Float.java:549)
    at DelFitnessCalculation.<init>(DelFitnessCalculation.java:66)
    at Main.main(Main.java:49)

First three lines of my input file:

Q0085   ATP6    0.353
YDR034C-A   YDR034C-A   0.359
tORF13  tORF13  0.360

Body:
Place this:

System.out.println("parts[2]=" + parts[2]);

between the two lines of code that you shared. I think you will find what you're looking for, which is the cause of your error.


问:
mod_rewrite GUI?
Anyone have a graphical tool for developing mod_rewrite rules.

Ideally it would display a pipeline of rewrites and then when given an instance of a uri would show the transforms as the get applied.

It's always a pain to get them setup just right so any way of making it easier would help.

答:
I am not aware of any such tool. The way I've addressed this problem was through a set of unit tests that are checking the correctness of my rules. If you want to have your tests always in synch with the config, you'll have to configure your tests to read the load the rules directly from the config file.

./alex

OwnerDisplayName: Allain Lalonde

Title: mod_rewrite GUI?

OwnerDisplayName: alexpopescu