问:
Running model failed: Invalid argument: Only additions of two arguments supported. Num inputs: 4
I was about to build a image semantic segmentation ios app. So I build the graph using the network architecture of deeplab, however,

I got this error :

```<code>Running model failed: Invalid argument: Only additions of two arguments supported. Num inputs: 4
     [[Node: fc1_voc12 = AddN[N=4, T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](fc1_voc12_c0/BiasAdd, fc1_voc12_c1/BiasAdd, fc1_voc12_c2/BiasAdd, fc1_voc12_c3/BiasAdd)]]
</code>```

The error occurs since iOS TensorFlow API does not support Add more than 2 tensors, while I got 4 tensors add together in the computing graph. Could anyone give some hints about how to implement it in another way?

答: Instead of tf.add_n([a, b, c, d]) use tf.add(a, tf.add(b, tf.add(c, d)))

Body:
I was about to build a image semantic segmentation ios app. So I build the graph using the network architecture of deeplab, however,

I got this error :

Running model failed: Invalid argument: Only additions of two arguments supported. Num inputs: 4
     [[Node: fc1_voc12 = AddN[N=4, T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](fc1_voc12_c0/BiasAdd, fc1_voc12_c1/BiasAdd, fc1_voc12_c2/BiasAdd, fc1_voc12_c3/BiasAdd)]]

The error occurs since iOS TensorFlow API does not support Add more than 2 tensors, while I got 4 tensors add together in the computing graph. Could anyone give some hints about how to implement it in another way?


来源: stackexchange

问:
Choosing a data structure
Different Data structures are used according to requirement but how would I know which data structure should I use? I just want to know how to choose an appropriate data structure ? Thanks</p>

答:
You need to research which data structures are used to meet which requirements (there's nobody here that is going to go through the time to spell out every option for you and tell you exactly when to use it).

Once you know the details, you should be able to (with a decent amount of certainty) pick the appropriate Data Structure for your needs.

ContentLicense: CC BY-SA 2.5

Title: Choosing a data structure


问:
How to find the indexes of 10% of the highest samples in a vector in Matlab?
I have a vector with real numbers only. The length of the vector is 5000 samples. I would like to find the indexes of the 10% of the highest samples (meaning 500 samples in total). Any idea of how to do that in Matlab?</p>

答:
This will do the job:

```<code>x = 1:100;
v = prctile(x,90);
res = find(x>v)
</code>```

I put 90 in v because you were looking for the top 10%, that is, the 90-th percentile. The x above is just an example, you can replace it with your x.

ContentLicense: CC BY-SA 3.0

Body:
This will do the job:

x = 1:100;
v = prctile(x,90);
res = find(x>v)

I put 90 in v because you were looking for the top 10%, that is, the 90-th percentile. The x above is just an example, you can replace it with your x.


问:
laravel ajax request params yields null
I am new to laravel framework and started following the laravel tasks tutorial.
I am trying to pass via ajax request the name of the task in order to save it in the database.

front end:

```<code>var taskdata= {
    "name": $("#new_task").val()
};

//console.log(JSON.stringify(taskdata));

$.ajax({
    url: '/task',
    type: 'POST',
    data: taskdata,
    contentType: 'json',
    processData: false,
    success: function(result) {
        alert("success");
    }
});
</code>```

server side:

```<code>Route::post('/task', function (Request $request) {

    //die(var_dump($request->json("name")));

    $validator = Validator::make(json_decode($request->getContent(), true), [
        'name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return redirect('/')
            ->withInput()
            ->withErrors($validator);
    }

    $task = new \App\Task;
    $task->name = $request->name;
    $task->save();

    return redirect('/');
});
</code>```

答:
When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

Hence you could change your controller method to

```<code>Route::post('/task', function (Request $request) {

    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return $validator->errors()->all();
    }

    $task = new \App\Task;
    $task->name = $request->name;
    $task->save();

    return url("/");
});
</code>```

and your ajax method as

```<code>var taskdata= {
    "name": $("#new_task").val(),
    "_token" : "{{ csrf_token() }}"
};

$.ajax({
    url: '/task',
    type: 'POST',
    data: taskdata,
    contentType: 'json',
    success: function(result) {
        console.log(result); // The url
    },
    error: function (data) {
        console.log(data.responseJSON); // Here you could see the error
    }
});
</code>```

Title: laravel ajax request params yields null

Body:
I am new to laravel framework and started following the laravel tasks tutorial.
I am trying to pass via ajax request the name of the task in order to save it in the database.

front end:

var taskdata= {
    "name": $("#new_task").val()
};

//console.log(JSON.stringify(taskdata));

$.ajax({
    url: '/task',
    type: 'POST',
    data: taskdata,
    contentType: 'json',
    processData: false,
    success: function(result) {
        alert("success");
    }
});

server side:

Route::post('/task', function (Request $request) {

    //die(var_dump($request->json("name")));

    $validator = Validator::make(json_decode($request->getContent(), true), [
        'name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return redirect('/')
            ->withInput()
            ->withErrors($validator);
    }

    $task = new \App\Task;
    $task->name = $request->name;
    $task->save();

    return redirect('/');
});

Body:
When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

Hence you could change your controller method to

Route::post('/task', function (Request $request) {

    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return $validator->errors()->all();
    }

    $task = new \App\Task;
    $task->name = $request->name;
    $task->save();

    return url("/");
});

and your ajax method as

var taskdata= {
    "name": $("#new_task").val(),
    "_token" : "{{ csrf_token() }}"
};

$.ajax({
    url: '/task',
    type: 'POST',
    data: taskdata,
    contentType: 'json',
    success: function(result) {
        console.log(result); // The url
    },
    error: function (data) {
        console.log(data.responseJSON); // Here you could see the error
    }
});


问:
Make Dropdown menu Disappear
I have a code from W3schools, in which we get dropdown menu after clicked on a button.

Dropdown menu don't disappear when we click anywhere else.
I have surfed a bit but it seems confusing as am new to js.

It would be much helpful if anyone could suggest how do we make it disappear?

Code Link

答:
```<code><script>
// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("myBtn").onclick = function() {
  myFunction()
};
document.getElementById("myBtn").onblur = function() {
  myFunction();
};

/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}
</script>
</code>```

Title: Make Dropdown menu Disappear


问:
Why Gerrit is unable to create branch by itself?
Following this answer and my own question, I have a simple (hope so) question.

If I'm pushing a particular branch, with all required refs properly set:

```<code>git checkout 82-blah-blah
git push origin HEAD:refs/for/82-blah-blah
</code>```

Why do I always get:

```<code>! [remote rejected] HEAD -> refs/for/82-blah-blah (branch 82-blah-blah not found)
</code>```

and I always have to go to Gerrit's UI and create that branch manually?

Isn't that an obvious step, that Gerrit could simply automate? Or am I missing something?

答:
Let say new branch is "myNewBranch"

```<code>git checkout master
git push origin HEAD:myNewBranch
</code>```

After commit some changes to push the new commit:

```<code>git push origin myNewBranch
</code>```

Works for me. But..

Do not know why can not push the same commit to master after that and the other way around - if I have opened PR for review in master, can not push the same commit to the "myNewBranch". To do it had to abandon the PR to master and then cherry-pick the commit to the new local branch and then push to the remote "myNewBranch"

Good luck!

Body:
Following this answer and my own question, I have a simple (hope so) question.

If I'm pushing a particular branch, with all required refs properly set:

git checkout 82-blah-blah
git push origin HEAD:refs/for/82-blah-blah

Why do I always get:

! [remote rejected] HEAD -> refs/for/82-blah-blah (branch 82-blah-blah not found)

and I always have to go to Gerrit's UI and create that branch manually?

Isn't that an obvious step, that Gerrit could simply automate? Or am I missing something?

Body:
Let say new branch is "myNewBranch"

git checkout master
git push origin HEAD:myNewBranch

After commit some changes to push the new commit:

git push origin myNewBranch

Works for me. But..

Do not know why can not push the same commit to master after that and the other way around - if I have opened PR for review in master, can not push the same commit to the "myNewBranch". To do it had to abandon the PR to master and then cherry-pick the commit to the new local branch and then push to the remote "myNewBranch"

Good luck!


问:
Check if two dictionaries are disjoint
Is there an easier/faster way to find out if two dictionaries are disjoint than calculating their intersection?

For the intersection I found this answer, so the disjoint-test would look like this:

```<code>def dicts_disjoint(a, b):
    keys_a = set(a.keys())
    keys_b = set(b.keys())
    intersection = keys_a & keys_b
    return not len(intersection)
</code>```

However I think this is inefficient since it always calculates the whole intersection (no short-circuit quit).

Any better ideas?

答:
Don't convert to a set; a dict_keys object already supports isdisjoint.

```<code>d1.keys().isdisjoint(d2)
</code>```

Title: Check if two dictionaries are disjoint

Body:
Is there an easier/faster way to find out if two dictionaries are disjoint than calculating their intersection?

For the intersection I found this answer, so the disjoint-test would look like this:

def dicts_disjoint(a, b):
    keys_a = set(a.keys())
    keys_b = set(b.keys())
    intersection = keys_a & keys_b
    return not len(intersection)

However I think this is inefficient since it always calculates the whole intersection (no short-circuit quit).

Any better ideas?

Body:
Don't convert to a set; a dict_keys object already supports isdisjoint.

d1.keys().isdisjoint(d2)


问:
Python array dimensions
I'm currently learning numpy and I find 'Array Dimensions' . Can anyone explain to me what are array dimensions ? How to find out the dimensions of an array ?
Thank you ,</p>

答:
You can print a tuple of the dimensions of an array like so:

```<code>print array.shape
</code>```

Let's say it was (2,3). Your array might be: [[1,2,3],[3,2,1]]
So basically the first dimension is the number of elements in the outer part, then the second is the number of elements in an inner part, and so on...

Title: Python array dimensions

Body:
You can print a tuple of the dimensions of an array like so:

print array.shape

Let's say it was (2,3). Your array might be: [[1,2,3],[3,2,1]]
So basically the first dimension is the number of elements in the outer part, then the second is the number of elements in an inner part, and so on...


问:
JavaFx Canvas only resizes in height but not in width
I have started programming this app for ploting temperature data, when the screen gets resized, the canvas should resize as well. It initializes correctly but when I want to resize the window, the draw() method will only resize the height, according to the stackpanes height value it is bound to but it will ignore the width entirely. The Listener won't even fire. This I find very strange. Also I have to set the minSize for the StackPane, otherwise nothing will be draw at all. I'm not using FXML.

Does anybody have any ideas?

Edit I changed line 58 from setRight() to setCenter, as mentioned in the solution from InternetUnexplorer. But I was still curious about why it is so, so I did some research. I found this in the internet:

Top/Bottom area: Can shrink/expand horizontally and keep the height
unchanged.

Left/Right area: Can shrink/expand vertically and keep the    length
unchanged.

Center area: Can shrink/expand in both directions.

http://o7planning.org/en/10629/javafx-borderpane-layout-tutorial

Here my main class:

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class main extends Application {

    @Override
    public void start(Stage mainStage) throws Exception {
        TempViewerWindow view = new TempViewerWindow();
        ReadData controller = new ReadData(view);
        controller.selectAll();

        mainStage.setScene(new Scene(view));
        //mainStage.setMinWidth(500);
        //mainStage.setMinHeight(400);
        mainStage.setTitle("Temperature Viewer");
        mainStage.show();
    }

    public static void main(String[] args) {

        launch(args);

    }

}
</code>```

And here my view class:

```<code>import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

public class TempViewerWindow extends BorderPane {

    public TableView<TempData> tableView;
    public Canvas canvas;
    public GraphicsContext gc;
    public StackPane holder;

    public TempViewerWindow() {
        tableView = new TableView<>();
        TableColumn<TempData, String> col_date = new TableColumn<>("Date");
        TableColumn<TempData, Float> col_temperature = new TableColumn<>("Temperature");

        col_date.setCellValueFactory(e -> e.getValue()
                                           .dateProperty());
        col_temperature.setCellValueFactory(e -> e.getValue()
                                                  .temperatureProperty()
                                                  .asObject());

        tableView.getColumns()
                 .addAll(col_date, col_temperature);

        setLeft(tableView);

        holder = new StackPane();
        holder.setMinSize(400, 400); // must be here for some reason

        canvas = new Canvas();

        gc = canvas.getGraphicsContext2D();

        canvas.widthProperty()
              .bind(holder.widthProperty()
                          .subtract(10));
        canvas.heightProperty()
              .bind(holder.heightProperty()
                          .subtract(10));

        canvas.widthProperty()
              .addListener(observable -> redraw(gc));
        canvas.heightProperty()
              .addListener(observable -> redraw(gc));

        holder.getChildren()
              .add(canvas);

        setCenter(holder); //here was the bug

    }

    private void redraw(GraphicsContext gc) {
        gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
        gc.setFill(Color.WHITE);
        gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
        System.out.println("redraw!");

    }

}
</code>```

答:
Your canvas is being placed in the right of your BorderPane, when you should be placing it in the center.

If you change line 54 of TempViewerWindow from setRight(holder) to setCenter(holder), the scaling works properly.

Body:
I have started programming this app for ploting temperature data, when the screen gets resized, the canvas should resize as well. It initializes correctly but when I want to resize the window, the draw() method will only resize the height, according to the stackpanes height value it is bound to but it will ignore the width entirely. The Listener won't even fire. This I find very strange. Also I have to set the minSize for the StackPane, otherwise nothing will be draw at all. I'm not using FXML.

Does anybody have any ideas?

Edit I changed line 58 from setRight() to setCenter, as mentioned in the solution from InternetUnexplorer. But I was still curious about why it is so, so I did some research. I found this in the internet:

Top/Bottom area: Can shrink/expand horizontally and keep the height
unchanged.

Left/Right area: Can shrink/expand vertically and keep the    length
unchanged.

Center area: Can shrink/expand in both directions.

http://o7planning.org/en/10629/javafx-borderpane-layout-tutorial

Here my main class:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class main extends Application {

    @Override
    public void start(Stage mainStage) throws Exception {
        TempViewerWindow view = new TempViewerWindow();
        ReadData controller = new ReadData(view);
        controller.selectAll();

        mainStage.setScene(new Scene(view));
        //mainStage.setMinWidth(500);
        //mainStage.setMinHeight(400);
        mainStage.setTitle("Temperature Viewer");
        mainStage.show();
    }

    public static void main(String[] args) {

        launch(args);

    }

}

And here my view class:

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

public class TempViewerWindow extends BorderPane {

    public TableView<TempData> tableView;
    public Canvas canvas;
    public GraphicsContext gc;
    public StackPane holder;

    public TempViewerWindow() {
        tableView = new TableView<>();
        TableColumn<TempData, String> col_date = new TableColumn<>("Date");
        TableColumn<TempData, Float> col_temperature = new TableColumn<>("Temperature");

        col_date.setCellValueFactory(e -> e.getValue()
                                           .dateProperty());
        col_temperature.setCellValueFactory(e -> e.getValue()
                                                  .temperatureProperty()
                                                  .asObject());

        tableView.getColumns()
                 .addAll(col_date, col_temperature);

        setLeft(tableView);

        holder = new StackPane();
        holder.setMinSize(400, 400); // must be here for some reason

        canvas = new Canvas();

        gc = canvas.getGraphicsContext2D();

        canvas.widthProperty()
              .bind(holder.widthProperty()
                          .subtract(10));
        canvas.heightProperty()
              .bind(holder.heightProperty()
                          .subtract(10));

        canvas.widthProperty()
              .addListener(observable -> redraw(gc));
        canvas.heightProperty()
              .addListener(observable -> redraw(gc));

        holder.getChildren()
              .add(canvas);

        setCenter(holder); //here was the bug

    }

    private void redraw(GraphicsContext gc) {
        gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
        gc.setFill(Color.WHITE);
        gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
        System.out.println("redraw!");

    }

}


问:
Changing DataGridView Column Width automatically
I have a DataGridView with 3 columns, and I want to set their widths to adjust automatically according to the text inside the cells, while filling the whole DataGridView space. If I use the following code:

```<code>dgvAcionamentosCadastrados.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
</code>```

The columns adjust to the size of the text inside, but no longer fill the whole DataGridView space. If I use this other piece of code instead:

```<code>dgvAcionamentosCadastrados.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
</code>```

The opposite happens. Any ideas?

答:
After the data has been inserted into the grid, try setting the width of each column of the grid to autosize:

```<code>for (int i=0;i<dataGridView1.Columns.Count;i++)
{
    dataGridView1.Columns[i].Width = -2;
}
</code>```

https://msdn.microsoft.com/en-us/library/system.windows.forms.columnheader.width.aspx

Body:
I have a DataGridView with 3 columns, and I want to set their widths to adjust automatically according to the text inside the cells, while filling the whole DataGridView space. If I use the following code:

dgvAcionamentosCadastrados.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

The columns adjust to the size of the text inside, but no longer fill the whole DataGridView space. If I use this other piece of code instead:

dgvAcionamentosCadastrados.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

The opposite happens. Any ideas?

Body:
After the data has been inserted into the grid, try setting the width of each column of the grid to autosize:

for (int i=0;i<dataGridView1.Columns.Count;i++)
{
    dataGridView1.Columns[i].Width = -2;
}

https://msdn.microsoft.com/en-us/library/system.windows.forms.columnheader.width.aspx


问:
jQuery draggable changing css "top" value
I have a table with two columns; names and items (represented by images).

```<code><table>
  <tr>
    <td class='name'>bob</td> <td class='items'><img src='thing1.gif' class='item'></td>
  </tr>
  <tr>
    <td class='name'>joe</td> <td class='items'><img src='thing2.gif' class='item'></td>
  </tr>
</table>
</code>```

I would like to have the user be able to drag the images from one row to another (i.e., move "thing2.gif" from joe to bob). I accomplished this with jQuery as follows:

```<code>// initialize these as draggable
$(".item").draggable({
    revert: "invalid",
    ghosting: true,
    opacity: 0.5,
});

$(".items").droppable({
    accept: ".item",
    activeClass: "drop_active",
    drop: function( event, ui ) {
        $(this).append(ui.draggable);
    }
});
</code>```

The problem I'm encountering is that after the move, each img seems to have a acquired a new css attribute: top: ±X;, where X represents how much the image was moved vertically. I.e., if I had dragged the image up for pixels before dropping it, it would have an attribute top: -40px. This would have the effect of making it be displayed 40 pixels above it's new row. Does anyone know how to correct for this? Or, can anyone suggest a better way to do this?

答:
For those coming form google.. you might also add:</p>

```<code>.ui-draggable-dragging{
    top:0 !important;
}
</code>```

Body:
I have a table with two columns; names and items (represented by images).

    bob

    joe

I would like to have the user be able to drag the images from one row to another (i.e., move "thing2.gif" from joe to bob). I accomplished this with jQuery as follows:

// initialize these as draggable
$(".item").draggable({
    revert: "invalid",
    ghosting: true,
    opacity: 0.5,
});

$(".items").droppable({
    accept: ".item",
    activeClass: "drop_active",
    drop: function( event, ui ) {
        $(this).append(ui.draggable);
    }
});

The problem I'm encountering is that after the move, each img seems to have a acquired a new css attribute: top: ±X;, where X represents how much the image was moved vertically. I.e., if I had dragged the image up for pixels before dropping it, it would have an attribute top: -40px. This would have the effect of making it be displayed 40 pixels above it's new row. Does anyone know how to correct for this? Or, can anyone suggest a better way to do this?

Body:
For those coming form google.. you might also add:

.ui-draggable-dragging{
    top:0 !important;
}


问:
Why is php strtotime() not working on a date?
This is the code I have used. Why can't it understand this date?</p>

```<code>strtotime('FRI OCT 14TH 2016'); //returns Thursday 01 01 1970
</code>```

答:
As Neat mentioned in a comment:

Because thats not a supported format, Date Formats.

Looking at the PHP documentation for Date Formats, the first row in the table describes the suffixes supported on dates (see the screenshot below). Notice that the letters are all lower-case.

.

Thus as was mentioned in comments, use lower-case letters for the suffixes.

```<code>strtotime('FRI OCT 14th 2016');
</code>```

See a demonstration of this change in this playground example.

Body:
This is the code I have used. Why can't it understand this date?

strtotime('FRI OCT 14TH 2016'); //returns Thursday 01 01 1970

Body:
As Neat mentioned in a comment:

Because thats not a supported format, Date Formats.

Looking at the PHP documentation for Date Formats, the first row in the table describes the suffixes supported on dates (see the screenshot below). Notice that the letters are all lower-case.

.

Thus as was mentioned in comments, use lower-case letters for the suffixes.

strtotime('FRI OCT 14th 2016');

See a demonstration of this change in this playground example.


问:
How to apply rolling functions in a group by object in pandas
I'm having difficulty to solve a look-back or roll-over problem in dataframe or perhaps in groupby.

The following is a simple example of the dataframe I have:

```<code>              fruit    amount
   20140101   apple     3
   20140102   apple     5
   20140102   orange    10
   20140104   banana    2
   20140104   apple     10
   20140104   orange    4
   20140105   orange    6
   20140105   grape     1
   …
   20141231   apple     3
   20141231   grape     2
</code>```

I need to calculate the average value of 'amount' of each fruit in the previous 3 days for everyday, and create the following data frame:

```<code>              fruit     average_in_last 3 days
   20140104   apple      4
   20140104   orange     10
   ...
</code>```

For example on 20140104, the previous 3 days are 20140101, 20140102 and 20140103 (note the date in the data frame is not continuous and 20140103 does not exist), the average amount of apple is (3+5)/2 = 4 and orange is 10/1=10, the rest is 0.

The sample data frame is very simple but the actual data frame is much more complicated and larger. Hope someone can shed some light on this, thank you in advance!

答:
Assuming we have a data frame like that in the beginning, </p>

```<code>>>> df
             fruit  amount
2017-06-01   apple       1
2017-06-03   apple      16
2017-06-04   apple      12
2017-06-05   apple       8
2017-06-06   apple      14
2017-06-08   apple       1
2017-06-09   apple       4
2017-06-02  orange      13
2017-06-03  orange       9
2017-06-04  orange       9
2017-06-05  orange       2
2017-06-06  orange      11
2017-06-07  orange       6
2017-06-08  orange       3
2017-06-09  orange       3
2017-06-10  orange      13
2017-06-02   grape      14
2017-06-03   grape      16
2017-06-07   grape       4
2017-06-09   grape      15
2017-06-10   grape       5

>>> dates = [i.date() for i in pd.date_range('2017-06-01', '2017-06-10')]

>>> temp = (df.groupby('fruit')['amount']
    .apply(lambda x: x.reindex(dates)  # fill in the missing dates for each group)
                      .fillna(0)   # fill each missing group with 0
                      .rolling(3)
                      .sum()) # do a rolling sum
    .reset_index()
    .rename(columns={'amount': 'sum_of_3_days',
                     'level_1': 'date'}))  # rename date index to date col

>>> temp.head()
   fruit        date  amount
0  apple  2017-06-01     NaN
1  apple  2017-06-02     NaN
2  apple  2017-06-03    17.0
3  apple  2017-06-04    28.0
4  apple  2017-06-05    36.0

# converts the date index into date column
>>> df = df.reset_index().rename(columns={'index': 'date'})
>>> df.merge(temp, on=['fruit', 'date'])
>>> df
          date   fruit  amount  sum_of_3_days
0   2017-06-01   apple       1                NaN
1   2017-06-03   apple      16               17.0
2   2017-06-04   apple      12               28.0
3   2017-06-05   apple       8               36.0
4   2017-06-06   apple      14               34.0
5   2017-06-08   apple       1               15.0
6   2017-06-09   apple       4                5.0
7   2017-06-02  orange      13                NaN
8   2017-06-03  orange       9               22.0
9   2017-06-04  orange       9               31.0
10  2017-06-05  orange       2               20.0
11  2017-06-06  orange      11               22.0
12  2017-06-07  orange       6               19.0
13  2017-06-08  orange       3               20.0
14  2017-06-09  orange       3               12.0
15  2017-06-10  orange      13               19.0
16  2017-06-02   grape      14                NaN
17  2017-06-03   grape      16               30.0
18  2017-06-07   grape       4                4.0
19  2017-06-09   grape      15               19.0
20  2017-06-10   grape       5               20.0
</code>```

Body:
I'm having difficulty to solve a look-back or roll-over problem in dataframe or perhaps in groupby.

The following is a simple example of the dataframe I have:

              fruit    amount
   20140101   apple     3
   20140102   apple     5
   20140102   orange    10
   20140104   banana    2
   20140104   apple     10
   20140104   orange    4
   20140105   orange    6
   20140105   grape     1
   …
   20141231   apple     3
   20141231   grape     2

I need to calculate the average value of 'amount' of each fruit in the previous 3 days for everyday, and create the following data frame:

              fruit     average_in_last 3 days
   20140104   apple      4
   20140104   orange     10
   ...

For example on 20140104, the previous 3 days are 20140101, 20140102 and 20140103 (note the date in the data frame is not continuous and 20140103 does not exist), the average amount of apple is (3+5)/2 = 4 and orange is 10/1=10, the rest is 0.

The sample data frame is very simple but the actual data frame is much more complicated and larger. Hope someone can shed some light on this, thank you in advance!

Body:
Assuming we have a data frame like that in the beginning,

>>> df
             fruit  amount
2017-06-01   apple       1
2017-06-03   apple      16
2017-06-04   apple      12
2017-06-05   apple       8
2017-06-06   apple      14
2017-06-08   apple       1
2017-06-09   apple       4
2017-06-02  orange      13
2017-06-03  orange       9
2017-06-04  orange       9
2017-06-05  orange       2
2017-06-06  orange      11
2017-06-07  orange       6
2017-06-08  orange       3
2017-06-09  orange       3
2017-06-10  orange      13
2017-06-02   grape      14
2017-06-03   grape      16
2017-06-07   grape       4
2017-06-09   grape      15
2017-06-10   grape       5

>>> dates = [i.date() for i in pd.date_range('2017-06-01', '2017-06-10')]

>>> temp = (df.groupby('fruit')['amount']
    .apply(lambda x: x.reindex(dates)  # fill in the missing dates for each group)
                      .fillna(0)   # fill each missing group with 0
                      .rolling(3)
                      .sum()) # do a rolling sum
    .reset_index()
    .rename(columns={'amount': 'sum_of_3_days',
                     'level_1': 'date'}))  # rename date index to date col

>>> temp.head()
   fruit        date  amount
0  apple  2017-06-01     NaN
1  apple  2017-06-02     NaN
2  apple  2017-06-03    17.0
3  apple  2017-06-04    28.0
4  apple  2017-06-05    36.0

# converts the date index into date column
>>> df = df.reset_index().rename(columns={'index': 'date'})
>>> df.merge(temp, on=['fruit', 'date'])
>>> df
          date   fruit  amount  sum_of_3_days
0   2017-06-01   apple       1                NaN
1   2017-06-03   apple      16               17.0
2   2017-06-04   apple      12               28.0
3   2017-06-05   apple       8               36.0
4   2017-06-06   apple      14               34.0
5   2017-06-08   apple       1               15.0
6   2017-06-09   apple       4                5.0
7   2017-06-02  orange      13                NaN
8   2017-06-03  orange       9               22.0
9   2017-06-04  orange       9               31.0
10  2017-06-05  orange       2               20.0
11  2017-06-06  orange      11               22.0
12  2017-06-07  orange       6               19.0
13  2017-06-08  orange       3               20.0
14  2017-06-09  orange       3               12.0
15  2017-06-10  orange      13               19.0
16  2017-06-02   grape      14                NaN
17  2017-06-03   grape      16               30.0
18  2017-06-07   grape       4                4.0
19  2017-06-09   grape      15               19.0
20  2017-06-10   grape       5               20.0


问:
Positioning circle directly behind objects
How would I get the circular arrow behind the 7 items I have created. Similar to what shows in this picture: http://imgur.com/Zz6HqWZ I cant get it to work for some reason. Does anyone have any idea on how to achieve this? Anything helps, cheers.

.container .row {text-align:center; position:relative;}
.center {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left:-35px;
}

.circle {
  display:inline-block;
  background-color:#006850;
  width:85px;
  height:85px;
  border-width:3px;
  border-style:solid;
  border-color:#fefefe;
  border-radius:50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom:-15px;
}

.invisible {
  visibility:hidden;
  display:inline-block;
  background-color:#1f497d;
  width:130px;
  height:65px;
  border-width:3px;
  border-style:solid;
  border-color:#d6d6d6;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color:#d0d3d8;
  width: 200px;
  height: 200px;
  border: 17px solid;
  border-radius: 50%;
  position: relative;
}
.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 50px;
  background: #fff;
  position: absolute;
  bottom: 0;
  top: 0;
  right: -22px;
  margin: auto;
}
.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  bottom: 106px;
  right: -25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="invisible"></div>
    <div class="circle"></div>
    <div class="invisible"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="arrow"></div>
</div></code>```

答:
As suggested you have to change the position of .arrow and change it's z-index to -1 to get that back. No need to rotate that circle instead change positioning of pseudo selector :before and :after.

.container .row {
  text-align: center;
  position: relative;
}

.center {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left: -35px;
}

.row {
  position: relative;
}

.circle {
  display: inline-block;
  background-color: #006850;
  width: 85px;
  height: 85px;
  border-width: 3px;
  border-style: solid;
  border-color: #fefefe;
  border-radius: 50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom: -15px;
}

.invisible {
  visibility: hidden;
  display: inline-block;
  background-color: #1f497d;
  width: 130px;
  height: 65px;
  border-width: 3px;
  border-style: solid;
  border-color: #d6d6d6;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color: #d0d3d8;
  width: 250px;
  height: 250px;
  border: 17px solid;
  border-radius: 50%;
  position: absolute;
  top: 15px;
  left: 50%;
  transform: translate(-50%, 0);
  z-index: -1;
}

.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 30px;
  position: absolute;
  bottom: 0;
  top: -10px;
  left: 55px;
  background: #fff;
  transform: rotate(-120deg);
}

.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  top: 0px;
  left: 40px;
  transform: rotate(-120deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="invisible"></div>
    <div class="circle"></div>
    <div class="invisible"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="arrow"></div>
</div></code>```

Body:
As suggested you have to change the position of .arrow and change it's z-index to -1 to get that back. No need to rotate that circle instead change positioning of pseudo selector :before and :after.

.container .row {
  text-align: center;
  position: relative;
}

.center {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left: -35px;
}

.row {
  position: relative;
}

.circle {
  display: inline-block;
  background-color: #006850;
  width: 85px;
  height: 85px;
  border-width: 3px;
  border-style: solid;
  border-color: #fefefe;
  border-radius: 50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom: -15px;
}

.invisible {
  visibility: hidden;
  display: inline-block;
  background-color: #1f497d;
  width: 130px;
  height: 65px;
  border-width: 3px;
  border-style: solid;
  border-color: #d6d6d6;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color: #d0d3d8;
  width: 250px;
  height: 250px;
  border: 17px solid;
  border-radius: 50%;
  position: absolute;
  top: 15px;
  left: 50%;
  transform: translate(-50%, 0);
  z-index: -1;
}

.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 30px;
  position: absolute;
  bottom: 0;
  top: -10px;
  left: 55px;
  background: #fff;
  transform: rotate(-120deg);
}

.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  top: 0px;
  left: 40px;
  transform: rotate(-120deg);
}

<div class="container">
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="invisible"></div>
    <div class="circle"></div>
    <div class="invisible"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="arrow"></div>
</div>


问:
Does Android really exist on other platforms than ARM?
I want to port an aplication written in C++ to android. Converting the application from C++ to Java will take a lot of work that I would prefer to use on making the application better for that platform instead of fixing convertion bugs and solving refactoring problems.

The NDK seems a good route to take but actually I don't want to miss a platform(if it is a considerable % of the market) just because the NDK doesn't or won't support it.

Android claims to support MIPS, ARM, X86 and others ... but actually all the implementations I have seen are only on ARM (or arm compatible).
I checked that on this site:
http://www.pdadb.net/

Would it be a bad desision to use the NDK?

Are there any non ARM devices that run or will run Android?

Where can I find more information about this?

Thanks in advance!

答:
Would it be a bad desision to use the NDK?

For algorithms, the NDK is fine. For games, the NDK is fine. For implementing an ordinary app, the NDK will not be terribly helpful.

Are there any non ARM devices that run or will run Android?

Google TV runs on x86 (Atom).


问:
How to get all the products? MySQL, PHP
How to get all the products? With the return, I get only one row...
I would like to type a loop to get all the values of the MySQL table "listaprodotti"?

```<code>     public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($username, $id_prodotto, $nome_prodotto, $categoria, $quantita);
    $stmt->fetch();
    $prodotti = array();

    $prodotti['username'] = $username;
    $prodotti['id_prodotto'] = $id_prodotto;
    $prodotti['nome_prodotto'] = $nome_prodotto;
    $prodotti['categoria'] = $categoria;
    $prodotti['quantita'] = $quantita;

    return $prodotti;

   }

   }
</code>```

That's what I get

```<code>     "prodotti":
   {"username":"anto","id_prodotto":57,"nome_prodotto":"xxx",
       "categoria":"xxx","quantita":"2"}}
</code>```

All this must be called with Swift 3 as an NSDictionary.

UPDATE

How do I get the values as an NSDictionary in Swift 3 ?

PHP CODE

```<code>  public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $i=0;
    $prodotti = array();
    while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $prodotti[$i]['username'] = $row['username'];
        $prodotti[$i]['id_prodotto'] = $row['id_prodotto'];
        $prodotti[$i]['nome_prodotto'] = $row['nome_prodotto'];
        $prodotti[$i]['categoria'] = $row['categoria'];
        $prodotti[$i]['quantita'] = $row['quantita'];
        $i++;
    }
     return $prodotti;
    }

    }
</code>```

SWIFT CODE

```<code>   import Alamofire
   import UIKit
    import AVFoundation

   class LoginController1: UIViewController {

//The login script url make sure to write the ip instead of localhost
//you can get the ip using ifconfig command in terminal
let URL_USER_LOGIN = "http://.............../login.php"

//the defaultvalues to store user data
let defaultValues = UserDefaults.standard

//the connected views
//don't copy instead connect the views using assistant editor
@IBOutlet weak var labelMessage: UILabel!
@IBOutlet weak var username: UITextField!

@IBOutlet weak var password: UITextField!

//the button action function
@IBAction func buttonLogin(_ sender: UIButton) {

    //getting the username and password
    let parameters: Parameters=[
        "username":username.text!,
        "password":password.text!
    ]

    //making a post request
    Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
        {
            response in
            //printing response
            print(response)

            //getting the json value from the server
            if let result = response.result.value {
                let jsonData = result as! NSDictionary

                //if there is no error
                if(!(jsonData.value(forKey: "error") as! Bool)){

                    //getting the user from response
                    let user = jsonData.value(forKey: "user") as! NSDictionary

                    //getting user values
                    let userId = user.value(forKey: "id") as! Int
                    let userName = user.value(forKey: "username") as! String
                    let userEmail = user.value(forKey: "email") as! String
                    let userNome = user.value(forKey: "nome") as! String
                    let userCognome = user.value(forKey: "cognome") as! String
                    let userTelefono = user.value(forKey: "telefono") as! String

                    //saving user values to defaults
                    self.defaultValues.set(userId, forKey: "userid")
                    self.defaultValues.set(userName, forKey: "username")
                    self.defaultValues.set(userEmail, forKey: "useremail")
                    self.defaultValues.set(userNome, forKey: "usernome")
                    self.defaultValues.set(userCognome, forKey: "usercognome")
                    self.defaultValues.set(userTelefono, forKey: "usertelefono")

                    ///prende i valori dei prodotti dalla cella legata a quel username
                    let prodotti = jsonData.value(forKey: "row") as! NSDictionary

                    let prodottiNome_prodotto = prodotti.value(forKey: "nome_prodotto") as! String
                    let prodottiCategoria = prodotti.value(forKey: "categoria") as! String
                    let prodottiQuantita = prodotti.value(forKey: "quantita") as! String

                    //saving i valori di questo username

                    self.defaultValues.set(prodottiNome_prodotto, forKey: "nome_prodotto")
                    self.defaultValues.set(prodottiCategoria, forKey: "categoria")
                    self.defaultValues.set(prodottiQuantita, forKey: "quantita")

                    //Go to the HomeViewController if the login is sucessful
                    let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
                    self.navigationController?.pushViewController(ProfiloController, animated: true)

                    self.dismiss(animated: false, completion: nil)

                    }else{
                                            //error message in case of invalid credential
                    let alertController = UIAlertController(title: "Error", message: "Username e password sbagliati", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)

                    self.present(alertController, animated: true, completion: nil)
                    }
            }
                }
}

override func viewDidLoad() {
    super.viewDidLoad()
    if defaultValues.string(forKey: "username") != nil{
        let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
        self.navigationController?.pushViewController(ProfiloController, animated: true)

    }
}

    var player: AVPlayer?
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    let tap = UITapGestureRecognizer(target: self, action: #selector(LoginController1.dismissKeyboard))
    view.addGestureRecognizer(tap)
    let path = Bundle.main.path(forResource: "introoiphone 7 plus", ofType: "mp4")
    player = AVPlayer(url: URL(fileURLWithPath: path!))
    player!.actionAtItemEnd = AVPlayerActionAtItemEnd.none;
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.insertSublayer(playerLayer, at: 0)
    NotificationCenter.default.addObserver(self, selector: #selector(LoginController1.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player!.currentItem)
    player!.seek(to: kCMTimeZero)
    player!.play()

}

func playerItemDidReachEnd() {
    player!.seek(to: kCMTimeZero)
}

func dismissKeyboard(tap: UITapGestureRecognizer) {
    print("Keyboard Dismiss Again")
    view.endEditing(true)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
 }

  }
</code>```

答:
You need to use fetchAll instead of fetch.

http://php.net/manual/en/pdostatement.fetchall.php

```<code>$stmt->fetchAll();
</code>```

Title: How to get all the products? MySQL, PHP

Body:
How to get all the products? With the return, I get only one row...
I would like to type a loop to get all the values of the MySQL table "listaprodotti"?

     public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($username, $id_prodotto, $nome_prodotto, $categoria, $quantita);
    $stmt->fetch();
    $prodotti = array();

    $prodotti['username'] = $username;
    $prodotti['id_prodotto'] = $id_prodotto;
    $prodotti['nome_prodotto'] = $nome_prodotto;
    $prodotti['categoria'] = $categoria;
    $prodotti['quantita'] = $quantita;

    return $prodotti;

   }

   }

That's what I get

     "prodotti":
   {"username":"anto","id_prodotto":57,"nome_prodotto":"xxx",
       "categoria":"xxx","quantita":"2"}}

All this must be called with Swift 3 as an NSDictionary.

UPDATE

How do I get the values as an NSDictionary in Swift 3 ?

PHP CODE

  public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $i=0;
    $prodotti = array();
    while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $prodotti[$i]['username'] = $row['username'];
        $prodotti[$i]['id_prodotto'] = $row['id_prodotto'];
        $prodotti[$i]['nome_prodotto'] = $row['nome_prodotto'];
        $prodotti[$i]['categoria'] = $row['categoria'];
        $prodotti[$i]['quantita'] = $row['quantita'];
        $i++;
    }
     return $prodotti;
    }

    }

SWIFT CODE

   import Alamofire
   import UIKit
    import AVFoundation

   class LoginController1: UIViewController {

//The login script url make sure to write the ip instead of localhost
//you can get the ip using ifconfig command in terminal
let URL_USER_LOGIN = "http://.............../login.php"

//the defaultvalues to store user data
let defaultValues = UserDefaults.standard

//the connected views
//don't copy instead connect the views using assistant editor
@IBOutlet weak var labelMessage: UILabel!
@IBOutlet weak var username: UITextField!

@IBOutlet weak var password: UITextField!

//the button action function
@IBAction func buttonLogin(_ sender: UIButton) {

    //getting the username and password
    let parameters: Parameters=[
        "username":username.text!,
        "password":password.text!
    ]

    //making a post request
    Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
        {
            response in
            //printing response
            print(response)

            //getting the json value from the server
            if let result = response.result.value {
                let jsonData = result as! NSDictionary

                //if there is no error
                if(!(jsonData.value(forKey: "error") as! Bool)){

                    //getting the user from response
                    let user = jsonData.value(forKey: "user") as! NSDictionary

                    //getting user values
                    let userId = user.value(forKey: "id") as! Int
                    let userName = user.value(forKey: "username") as! String
                    let userEmail = user.value(forKey: "email") as! String
                    let userNome = user.value(forKey: "nome") as! String
                    let userCognome = user.value(forKey: "cognome") as! String
                    let userTelefono = user.value(forKey: "telefono") as! String

                    //saving user values to defaults
                    self.defaultValues.set(userId, forKey: "userid")
                    self.defaultValues.set(userName, forKey: "username")
                    self.defaultValues.set(userEmail, forKey: "useremail")
                    self.defaultValues.set(userNome, forKey: "usernome")
                    self.defaultValues.set(userCognome, forKey: "usercognome")
                    self.defaultValues.set(userTelefono, forKey: "usertelefono")

                    ///prende i valori dei prodotti dalla cella legata a quel username
                    let prodotti = jsonData.value(forKey: "row") as! NSDictionary

                    let prodottiNome_prodotto = prodotti.value(forKey: "nome_prodotto") as! String
                    let prodottiCategoria = prodotti.value(forKey: "categoria") as! String
                    let prodottiQuantita = prodotti.value(forKey: "quantita") as! String

                    //saving i valori di questo username

                    self.defaultValues.set(prodottiNome_prodotto, forKey: "nome_prodotto")
                    self.defaultValues.set(prodottiCategoria, forKey: "categoria")
                    self.defaultValues.set(prodottiQuantita, forKey: "quantita")

                    //Go to the HomeViewController if the login is sucessful
                    let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
                    self.navigationController?.pushViewController(ProfiloController, animated: true)

                    self.dismiss(animated: false, completion: nil)

                    }else{
                                            //error message in case of invalid credential
                    let alertController = UIAlertController(title: "Error", message: "Username e password sbagliati", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)

                    self.present(alertController, animated: true, completion: nil)
                    }
            }
                }
}

override func viewDidLoad() {
    super.viewDidLoad()
    if defaultValues.string(forKey: "username") != nil{
        let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
        self.navigationController?.pushViewController(ProfiloController, animated: true)

    }
}

    var player: AVPlayer?
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    let tap = UITapGestureRecognizer(target: self, action: #selector(LoginController1.dismissKeyboard))
    view.addGestureRecognizer(tap)
    let path = Bundle.main.path(forResource: "introoiphone 7 plus", ofType: "mp4")
    player = AVPlayer(url: URL(fileURLWithPath: path!))
    player!.actionAtItemEnd = AVPlayerActionAtItemEnd.none;
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.insertSublayer(playerLayer, at: 0)
    NotificationCenter.default.addObserver(self, selector: #selector(LoginController1.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player!.currentItem)
    player!.seek(to: kCMTimeZero)
    player!.play()

}

func playerItemDidReachEnd() {
    player!.seek(to: kCMTimeZero)
}

func dismissKeyboard(tap: UITapGestureRecognizer) {
    print("Keyboard Dismiss Again")
    view.endEditing(true)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
 }

  }

Body:
You need to use fetchAll instead of fetch.

http://php.net/manual/en/pdostatement.fetchall.php

$stmt->fetchAll();


问:
When we `import { foo }`, why can't we `export foo` but have to `export { foo }`?
I wonder why after we

```<code>import { foo } from "some/path";
</code>```

we don't

```<code>export foo;
</code>```

as usual, but have to

```<code>export { foo };
</code>```

in order to be able to export it?

The reason is that we usually export a "named" export by

```<code>export const bar = 123;

const wah = 234;
export wah;
</code>```

and they export without a { }.

答:
No. export foo; or export wah; are not usual. They just don't work.

You usually create a named export using either

```<code>export const wah = 234;
</code>```

or

```<code>const wah = 234;
export { wah }
</code>```

or

```<code>const bar = 234;
export { bar as wah }
</code>```

Btw, you can also directly do

```<code>export { foo } from "some/path";
</code>```

Body:
I wonder why after we

import { foo } from "some/path";

we don't

export foo;

as usual, but have to

export { foo };

in order to be able to export it?

The reason is that we usually export a "named" export by

export const bar = 123;

const wah = 234;
export wah;

and they export without a { }.

Body:
No. export foo; or export wah; are not usual. They just don't work.

You usually create a named export using either

export const wah = 234;

or

const wah = 234;
export { wah }

or

const bar = 234;
export { bar as wah }

Btw, you can also directly do

export { foo } from "some/path";


问:
Why is KNN slow with custom metric?
I work with data set consists about 200k objects. Every object has 4 features. I classifies them by K nearest neighbors (KNN) with euclidean metric. Process is finished during about 20 seconds.

Lately I've got a reason to use custom metric. Probably it will make better results. I've implemented custom metric and KNN has become to work more than one hour. I didn't wait for finishing of it.

I assumed that a reason of this issue is my metric. I replace my code by return 1. KNN still worked more than one hour. I assumed that a reason is algorithm Ball Tree, but KNN with it and euclidean metric works during about 20 seconds.

Right now I have no idea what's wrong. I use Python 3 and sklearn 0.17.1. Here process can't be finished with custom metric. I also tried algorithm brute but it has same effect. Upgrade and downgrade of scikit-learn have no effect. Implementing classification by custom metric on Python 2 has no positive effect too. I implemented this metric (just return 1) on Cython, it has same effect.

def custom_metric(x: np.ndarray, y: np.ndarray) -> float:
    return 1

clf = KNeighborsClassifier(n_jobs=1, metric=custom_metric)
clf.fit(X, Y)
```

Can I boost classification process by KNN with custom metric?

Sorry if my english is not clear.

答:
Sklearn is optimized and use cython and several process to run as fast as possible. Writing pure python code especially when it is called several times is the cause that slows your code. I recommend that you write your custom metric using cython.
You have a tutorial that you can follow right here : https://blog.sicara.com/https-medium-com-redaboumahdi-speed-sklearn-algorithms-custom-metrics-using-cython-de92e5a325c</p>

Title: Why is KNN slow with custom metric?

Body:
I work with data set consists about 200k objects. Every object has 4 features. I classifies them by K nearest neighbors (KNN) with euclidean metric. Process is finished during about 20 seconds.

Lately I've got a reason to use custom metric. Probably it will make better results. I've implemented custom metric and KNN has become to work more than one hour. I didn't wait for finishing of it.

I assumed that a reason of this issue is my metric. I replace my code by return 1. KNN still worked more than one hour. I assumed that a reason is algorithm Ball Tree, but KNN with it and euclidean metric works during about 20 seconds.

Right now I have no idea what's wrong. I use Python 3 and sklearn 0.17.1. Here process can't be finished with custom metric. I also tried algorithm brute but it has same effect. Upgrade and downgrade of scikit-learn have no effect. Implementing classification by custom metric on Python 2 has no positive effect too. I implemented this metric (just return 1) on Cython, it has same effect.

def custom_metric(x: np.ndarray, y: np.ndarray) -> float:
    return 1

clf = KNeighborsClassifier(n_jobs=1, metric=custom_metric)
clf.fit(X, Y)

Can I boost classification process by KNN with custom metric?

Sorry if my english is not clear.


问:
Selenuim IDE - Check an input relative to a  at the same level
First time here :)

I want to check the input when the text between  is 0139160695.
I tried by using :

```<code> Click
//td[text()='0139160695']/ancestor::input[starts-with(@name,'intervsList') and @value='off']
</code>```

it gives me element not found but when i use following or preceding it works correctly by checking the previous or next checkbox.

```<code>     <tbody id="yui_3_17_2_1_1499263991011_37905" class="pure-datatable-data">
 <tr id="yui_3_17_2_1_1499263991011_37600" class="pure-datatable-even" data-yui3-record="workOrder_949">

   <td class="pure-datatable-col-selected pure-datatable-cell ">
     <input style="display:none" name="intervsList(58283128)" value="off" type="checkbox">
   </td>

   <td id="yui_3_17_2_1_1499263991011_37980" class="pure-datatable-col-site pure-datatable-cell ">
     0139160695
    <i class="right icon icon-history etech-workorderlist-history-action" title="Historique"></i>
   </td>

<tr> </tr>
<tr> </tr>
</code>```

答:
For understanding this, you have to understand the concept of ancestor, parent, following and preceding.

ancestor: It gives you all the ancestor elements. We use ancestor when we have to find an element on the basis of the parent element. In your example, ancestor elements will be tr,tbody, table and others.

parent: It gives you the parent element. In your example, parent element will be tr

This expression is incorrect:

ancestor::input[starts-with(@name,'intervsList') and @value='off']

as input is not the ancestor for td.

XPath which can be used:

//td[normalize-space()='0139160695']/parent::tr/td/input[@type='checkbox']

Title: Selenuim IDE - Check an input relative to a <td> at the same level

Body:
First time here :)

I want to check the input when the text between  is 0139160695.
I tried by using :

 Click
//td[text()='0139160695']/ancestor::input[starts-with(@name,'intervsList') and @value='off']

it gives me element not found but when i use following or preceding it works correctly by checking the previous or next checkbox.

     <input style="display:none" name="intervsList(58283128)" value="off" type="checkbox">

     0139160695


问:
Choosing a data structure
Different Data structures are used according to requirement but how would I know which data structure should I use? I just want to know how to choose an appropriate data structure ? Thanks</p>

答:
It's hard to answer without knowing what parts of the decision are giving you trouble.

For the most part, you want the smallest and simplest data structure that will hold the data you need to store.

Was there one particular case that was giving you trouble?

Title: Choosing a data structure


问:
Join relatively small table with large table in Spark 2.1
I am currently working on updating a table based on its existence on another table:

Ex:

Dataset A (relatively small, 300k of rows): DepartmentId, EmployeeId, Salary, Error

Dataset B (relatively huge, millions of rows): DepartmentId, EmployeeId, Salary

The logic is:
1. If A's (DepartmentId, EmployeeId) pair exists in B, then update A's salary with B's salary
2. Otherwise, write a message to A's error field

The solution I have now is doing a left outer join on A with B. Is there any other better practices for this type of problem?

Thank you in advance!

答:
For better performance, you can use broadcast hash join as mention here by @Ram Ghadiyaram

The broadcasted dataframe will be distributed in all the partition which increases the performance in joining.

DataFrame join optimization - Broadcast Hash Join

Hope this helps!


问:
VS C# Button with Mailto function - it needs to open Outlook's new mail window
What I am trying to do:

A user clicks a button on a ASP.net page and it opens a Outlook 'new mail' window.
That's all.

My Problem:

With this -->

```<code>     using Outlook = Outlook = Microsoft.Office.Interop.Outlook;

    OutlookApp outlookApp = new OutlookApp();
    MailItem mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

    mailItem.Subject = "Test";
    mailItem.HTMLBody = "<html><body>This is the message body</body></html>";

    mailItem.Display(false);
</code>```

And several other code I've tried, I am getting security errors on my IIS web server - Access is denied. But on localhost Outlook opens fine.

I looked all over, and everyone suggests that NETWORKSERVICE should be the user that has full security rights. Did that. And after reading a bit more, People are suggesting to not try and open Outlook over a web server for several reasons. So I decided to leave Interops.Outlook.

Then I also tried the following, which again works on my localhost, but when published to the web server does not respond when the button is clicked. It literally does nothing.

```<code>    string subject = "Test subject";
    string emailTag = string.Format("mailto:someone@test.com?subject={0}", subject);
    System.Diagnostics.Process.Start(emailTag);
</code>```

Thanks

答:
You can use hyperlink to open the default email client from website.

Email

To display a hyperlink as button you can CSS like below:

.button {
  font: bold 11px Arial;
  text-decoration: none;
  background-color: #EEEEEE;
  color: #333333;
  padding: 2px 6px 2px 6px;
  border-top: 1px solid #CCCCCC;
  border-right: 1px solid #333333;
  border-bottom: 1px solid #333333;
  border-left: 1px solid #CCCCCC;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Email</code>```

If you are using bootstrap then it would be more easy. simply apply role attribute to show link as button:

```<code><a role='button' href='mailto:mailto:someone@test.com?subject={0}'>Email</a>
</code>```

Body:
What I am trying to do:

A user clicks a button on a ASP.net page and it opens a Outlook 'new mail' window.
That's all.

My Problem:

With this -->

     using Outlook = Outlook = Microsoft.Office.Interop.Outlook;

    OutlookApp outlookApp = new OutlookApp();
    MailItem mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

    mailItem.Subject = "Test";
    mailItem.HTMLBody = "This is the message body";

    mailItem.Display(false);

And several other code I've tried, I am getting security errors on my IIS web server - Access is denied. But on localhost Outlook opens fine.

I looked all over, and everyone suggests that NETWORKSERVICE should be the user that has full security rights. Did that. And after reading a bit more, People are suggesting to not try and open Outlook over a web server for several reasons. So I decided to leave Interops.Outlook.

Then I also tried the following, which again works on my localhost, but when published to the web server does not respond when the button is clicked. It literally does nothing.

    string subject = "Test subject";
    string emailTag = string.Format("mailto:someone@test.com?subject={0}", subject);
    System.Diagnostics.Process.Start(emailTag);

Thanks

Body:
You can use hyperlink to open the default email client from website.

<a class='button' href='mailto:mailto:someone@test.com?subject={0}'>Email</a>

To display a hyperlink as button you can CSS like below:

.button {
  font: bold 11px Arial;
  text-decoration: none;
  background-color: #EEEEEE;
  color: #333333;
  padding: 2px 6px 2px 6px;
  border-top: 1px solid #CCCCCC;
  border-right: 1px solid #333333;
  border-bottom: 1px solid #333333;
  border-left: 1px solid #CCCCCC;
}

<a class='button' href='mailto:mailto:someone@test.com?subject={0}'>Email</a>

If you are using bootstrap then it would be more easy. simply apply role attribute to show link as button:

<a role='button' href='mailto:mailto:someone@test.com?subject={0}'>Email</a>


问:
Play Google Drive Video in JW Player And Get Direct Link For Google Drive Video
I want to PLay google drive videos in JW player in my website .I know it is possible because a lot of websites doing this e.g fmovies

Is there any API or piece of code through which i can achieve this URL for google drive video
https://redirector.googlevideo.com/videoplayback?id=4d0be5bc491e2dd7&itag=18&source=webdrive&requiressl=yes&ttl=transient&pl=21&mime=video/mp4&ipbits=0&sparams=api,expire,id,ip,ipbits,itag,mime,mm,mn,ms,mv,pl,requiressl,source,ttl&api=FsxSHTiLgbCln6EzpdilVgW6JQxNqam8I5YPHEFLs3E=&cms_redirect=yes&expire=1499015322&ip=37.187.148.42&mm=30&mn=sn-25ge7ney&ms=nxu&mt=1499000741&mv=m&signature=658276E5F00AAFD155876EC75453507DE10DDEDB.7FAD65986F21E14B5FAFB6E145252310F86A10B6&key=cms1&app=storage

I already tried juicy API but its not working for me

答:
If you just want to stream a video from Google drive then this can be done - you can see a working example here:

https://sourcey.com/html5-video-streaming-from-google-drive/

You can see exactly how it is coded by right clicking and inspecting in your browser

<video controls="controls" style="margin-bottom:20px;width:590px">
         <source src="https://drive.google.com/uc?export=download&id=0B0JMGMGgxp9WMEdWb1hyQUhlOWs" type="video/mp4">
</video>
```

To create a signed URL for Google cloud storage programatically you need to follow their instructions at the link below - I have not copied or summarised them here as, if the similar AWS mechanism is anything to go by, the approach can change often and it is best to always check the latest official documentation:

https://cloud.google.com/storage/docs/access-control/create-signed-urls-program

Body:
I want to PLay google drive videos in JW player in my website .I know it is possible because a lot of websites doing this e.g fmovies

Is there any API or piece of code through which i can achieve this URL for google drive video
<a href="https://redirector.googlevideo.com/videoplayback?id=4d0be5bc491e2dd7&itag=18&source=webdrive&requiressl=yes&ttl=transient&pl=21&mime=video/mp4&ipbits=0&sparams=api,expire,id,ip,ipbits,itag,mime,mm,mn,ms,mv,pl,requiressl,source,ttl&api=FsxSHTiLgbCln6EzpdilVgW6JQxNqam8I5YPHEFLs3E=&cms_redirect=yes&expire=1499015322&ip=37.187.148.42&mm=30&mn=sn-25ge7ney&ms=nxu&mt=1499000741&mv=m&signature=658276E5F00AAFD155876EC75453507DE10DDEDB.7FAD65986F21E14B5FAFB6E145252310F86A10B6&key=cms1&app=storage" rel="nofollow noreferrer">https://redirector.googlevideo.com/videoplayback?id=4d0be5bc491e2dd7&itag=18&source=webdrive&requiressl=yes&ttl=transient&pl=21&mime=video/mp4&ipbits=0&sparams=api,expire,id,ip,ipbits,itag,mime,mm,mn,ms,mv,pl,requiressl,source,ttl&api=FsxSHTiLgbCln6EzpdilVgW6JQxNqam8I5YPHEFLs3E=&cms_redirect=yes&expire=1499015322&ip=37.187.148.42&mm=30&mn=sn-25ge7ney&ms=nxu&mt=1499000741&mv=m&signature=658276E5F00AAFD155876EC75453507DE10DDEDB.7FAD65986F21E14B5FAFB6E145252310F86A10B6&key=cms1&app=storage

I already tried juicy API but its not working for me

Body:
If you just want to stream a video from Google drive then this can be done - you can see a working example here:

https://sourcey.com/html5-video-streaming-from-google-drive/

You can see exactly how it is coded by right clicking and inspecting in your browser

<video controls="controls" style="margin-bottom:20px;width:590px">
         <source src="https://drive.google.com/uc?export=download&amp;id=0B0JMGMGgxp9WMEdWb1hyQUhlOWs" type="video/mp4">
</video>

To create a signed URL for Google cloud storage programatically you need to follow their instructions at the link below - I have not copied or summarised them here as, if the similar AWS mechanism is anything to go by, the approach can change often and it is best to always check the latest official documentation:

https://cloud.google.com/storage/docs/access-control/create-signed-urls-program


问:
Show most recent topic in forum category with PHP MySQL JOINS
I'm currently making a forum section in my website and I have a categories page that show the different categories that you can post in, in a table. One column of this table is a "Most recent topic" column. The table is made up of a while loop, running through each category in my categories database table. My issue is, the while loop keeps outputting EVERY topic and just reuses categories that it has already shown.
Here is the code:

```<code>$sql = "SELECT categories.cat_id, categories.cat_name, categories.cat_description, topics.topic_id, topics.topic_subject, topics.topic_date, topics.topic_cat FROM categories LEFT JOIN topics ON topics.topic_cat = categories.cat_id";
$query = $DB_con->prepare($sql);
$query->execute();

if (!$query) {
    echo 'No categories found.';
} else {
    echo '<table class="table">
        <tr>
            <th>Category</th>
            <th>Last Topic</th>
        </tr>';

    while($catRow = $query->fetch(PDO::FETCH_ASSOC)) {
        echo '<tr>';
            echo '<td>';
                echo '<h3><a href="category.php?id=' . $catRow['cat_id'] . '">' . $catRow['cat_name'] . '</a></h3>' . $catRow['cat_description'];
            echo '</td>';
            echo '<td>';
                echo '<a href="topic.php?id=' . $catRow['topic_id'] . '">' . $catRow['topic_subject'] . '</a> on ' . substr($catRow['topic_date'],0,-8);
            echo '</td>';
        echo '</tr>';
    }
    echo '</table>';

}
?>
</code>```

As I said before, the table keeps showing the same category multiple times, so that it can show me every topic that has been posted. I only want each category displayed once with the most recent topic in that category.

I hope somebody can help me. Let me know if it's not clear enough. Thanks.

答:
If I understood correctly your question, maybe you should change your query:

Updated:

```<code>SELECT categories.cat_id
    ,categories.cat_name
    ,categories.cat_description
        ,topics.topic_id
        ,topics.topic_subject
    ,T1.topic_date
    ,T1.topic_cat
FROM categories
LEFT JOIN (SELECT  topic_cat, MAX(topic_date) AS topic_date
           FROM topics
           GROUP BY topic_cat) AS T1 ON T1.topic_cat = categories.cat_id
LEFT JOIN topics ON T1.topic_cat = topics.topic_cat AND T1.topic_date=topics.topic_date
</code>```

Body:
I'm currently making a forum section in my website and I have a categories page that show the different categories that you can post in, in a table. One column of this table is a "Most recent topic" column. The table is made up of a while loop, running through each category in my categories database table. My issue is, the while loop keeps outputting EVERY topic and just reuses categories that it has already shown.
Here is the code:

$sql = "SELECT categories.cat_id, categories.cat_name, categories.cat_description, topics.topic_id, topics.topic_subject, topics.topic_date, topics.topic_cat FROM categories LEFT JOIN topics ON topics.topic_cat = categories.cat_id";
$query = $DB_con->prepare($sql);
$query->execute();

if (!$query) {
    echo 'No categories found.';
} else {
    echo '

            Category
            Last Topic

';

    while($catRow = $query->fetch(PDO::FETCH_ASSOC)) {
        echo '
';
            echo '';
                echo '
' . $catRow['cat_name'] . '
' . $catRow['cat_description'];
            echo '	';
            echo '';
                echo '' . $catRow['topic_subject'] . ' on ' . substr($catRow['topic_date'],0,-8);
            echo '	';
        echo '
';
    }
    echo '
';

}
?>

As I said before, the table keeps showing the same category multiple times, so that it can show me every topic that has been posted. I only want each category displayed once with the most recent topic in that category.

I hope somebody can help me. Let me know if it's not clear enough. Thanks.

Body:
If I understood correctly your question, maybe you should change your query:

Updated:

SELECT categories.cat_id
    ,categories.cat_name
    ,categories.cat_description
        ,topics.topic_id
        ,topics.topic_subject
    ,T1.topic_date
    ,T1.topic_cat
FROM categories
LEFT JOIN (SELECT  topic_cat, MAX(topic_date) AS topic_date
           FROM topics
           GROUP BY topic_cat) AS T1 ON T1.topic_cat = categories.cat_id
LEFT JOIN topics ON T1.topic_cat = topics.topic_cat AND T1.topic_date=topics.topic_date


问:
Coroutine doesn't work in Unity
I need to make a screenshot in Unity. I did it the next way:

```<code>public void Capture(){
    StartCoroutine(CaptureScreenshot());
}

private IEnumerator CaptureScreenshot(){
    GameObject canvas = GameObject.Find("Canvas");
    canvas.SetActive(false); // hide all buttons
    yield return new WaitForEndOfFrame();

    string timestamp = DateTime.Now.ToString("dd_MMMM_hh_mm_ss_tt");
    Application.CaptureScreenshot("screenshot" + timestamp + ".png");
    Debug.Log("Screenshot was captured.");
    yield return new WaitForEndOfFrame();

    canvas.SetActive(true); // restore all buttons
    yield return null;
}
</code>```

When I invoke Capture(), canvas hides but neither screenshot takes nor text logs.

What is wrong with this code? Thanks for response.

答:
Because your script is running on a object in the canvas when you do canvas.SetActive(false); that also disables the script, preventing the coroutine from continuing from yield return new WaitForEndOfFrame();.

Move the script to a game object that does not live on the canvas and it should solve the problem.

Title: Coroutine doesn't work in Unity

Body:
I need to make a screenshot in Unity. I did it the next way:

public void Capture(){
    StartCoroutine(CaptureScreenshot());
}

private IEnumerator CaptureScreenshot(){
    GameObject canvas = GameObject.Find("Canvas");
    canvas.SetActive(false); // hide all buttons
    yield return new WaitForEndOfFrame();

    string timestamp = DateTime.Now.ToString("dd_MMMM_hh_mm_ss_tt");
    Application.CaptureScreenshot("screenshot" + timestamp + ".png");
    Debug.Log("Screenshot was captured.");
    yield return new WaitForEndOfFrame();

    canvas.SetActive(true); // restore all buttons
    yield return null;
}

When I invoke Capture(), canvas hides but neither screenshot takes nor text logs.

What is wrong with this code? Thanks for response.


问:
java derby Error connecting to server localhost 1527
I want to connect derby DB to Java application. I have downloaded all the jars, set a classpath as a java directory and downloaded Derby.What I get now is:

```<code>java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
</code>```

Can anyone help me:what does it actually mean, and what can I do now?I guess there might be a problem with Database_url variable, but I don't know how to set it propely.

```<code>private static final String protocol = "jdbc:derby:";

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
    final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
    try {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        System.out.println("Loaded the client driver.");
    } catch (Exception err) {
        System.err.println("Unable to load the client driver.");
        err.printStackTrace(System.err);
        System.exit(0);
    }
    String dbName = "BookDatabase";
    Connection conn = null;
    try {
        System.out.println(
                "Connecting to and creating the database...");
        conn = DriverManager.getConnection(DATABASE_URL);
        System.out.println("Database created.");
        Statement s = (Statement) conn.createStatement();
        s.execute("CREATE TABLE names" +
                "(author varchar(50), author_id " +
                "int, url varchar(80))");
        System.out.println("Created 'names' table.");
        System.out.println("Inserting authors.");
        s.execute("INSERT INTO names " +
                "VALUES ('Adams, Douglas', 1," +
                "'http://www.douglasadams.com')");
        s.execute("INSERT INTO names " +
                "VALUES ('Simmons, Dan', 2, 'http://www.dansimmons.com')");
        s.execute("INSERT INTO names " +
                "VALUES ('Stephenson, Neal', 3, " +
                "'http://www.nealstephenson.com')");
        System.out.println("Authors inserted.");
        conn.close();
    } catch (SQLException err) {
        System.err.println("SQL error.");
        err.printStackTrace(System.err);
        System.exit(0);
    }

}
</code>```

答:
Given your error (Connection refused: connect) it seems that the database server has not been started. Apache Derby has two operation modes: client/server and embedded. Each mode uses different drivers (and have different JDBC URL syntax).

The ClientDriver is used for client/server mode (which works as a traditional RDMS), so you need to start the Derby DB Server as a different Java process:

```<code>java -cp derby.jar;derbynet.jar;derbyclient.jar;derbytools.jar org.apache.derby.drda.NetworkServerControl start
</code>```

(and java ... NetworkServerControl stop in order to shutdown the database process).

Another alternative is starting the DB in embedded mode (the database and the client both run in the same JVM, but no other process can connect to the database at the same time).

The embedded mode uses org.apache.derby.jdbc.EmbeddedDriver and the datasource URL has the form jdbc:derby:firstdb;create=true.
See this example, which is explained in Activity 3: Run a JDBC program using the embedded driver of the Getting Started with Derby guide.
Note that in embedded mode, some additional steps must be executed in order to properly shutdown the database before exiting the JVM.

Body:
I want to connect derby DB to Java application. I have downloaded all the jars, set a classpath as a java directory and downloaded Derby.What I get now is:

java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.

Can anyone help me:what does it actually mean, and what can I do now?I guess there might be a problem with Database_url variable, but I don't know how to set it propely.

private static final String protocol = "jdbc:derby:";

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
    final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
    try {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        System.out.println("Loaded the client driver.");
    } catch (Exception err) {
        System.err.println("Unable to load the client driver.");
        err.printStackTrace(System.err);
        System.exit(0);
    }
    String dbName = "BookDatabase";
    Connection conn = null;
    try {
        System.out.println(
                "Connecting to and creating the database...");
        conn = DriverManager.getConnection(DATABASE_URL);
        System.out.println("Database created.");
        Statement s = (Statement) conn.createStatement();
        s.execute("CREATE TABLE names" +
                "(author varchar(50), author_id " +
                "int, url varchar(80))");
        System.out.println("Created 'names' table.");
        System.out.println("Inserting authors.");
        s.execute("INSERT INTO names " +
                "VALUES ('Adams, Douglas', 1," +
                "'http://www.douglasadams.com')");
        s.execute("INSERT INTO names " +
                "VALUES ('Simmons, Dan', 2, 'http://www.dansimmons.com')");
        s.execute("INSERT INTO names " +
                "VALUES ('Stephenson, Neal', 3, " +
                "'http://www.nealstephenson.com')");
        System.out.println("Authors inserted.");
        conn.close();
    } catch (SQLException err) {
        System.err.println("SQL error.");
        err.printStackTrace(System.err);
        System.exit(0);
    }

}

Body:
Given your error (Connection refused: connect) it seems that the database server has not been started. Apache Derby has two operation modes: client/server and embedded. Each mode uses different drivers (and have different JDBC URL syntax).

The ClientDriver is used for client/server mode (which works as a traditional RDMS), so you need to start the Derby DB Server as a different Java process:

java -cp derby.jar;derbynet.jar;derbyclient.jar;derbytools.jar org.apache.derby.drda.NetworkServerControl start

(and java ... NetworkServerControl stop in order to shutdown the database process).

Another alternative is starting the DB in embedded mode (the database and the client both run in the same JVM, but no other process can connect to the database at the same time).

The embedded mode uses org.apache.derby.jdbc.EmbeddedDriver and the datasource URL has the form jdbc:derby:firstdb;create=true.
See this example, which is explained in Activity 3: Run a JDBC program using the embedded driver of the Getting Started with Derby guide.
Note that in embedded mode, some additional steps must be executed in order to properly shutdown the database before exiting the JVM.


问:
How to use required validation on <input type="file"> in angular 4
Text input are working properly. I used same for file but its not working.</p>

```<code><input type="text" name="title" #title="ngModel" ngModel required class="form-control" placeholder="Title Here">
<div *ngIf="title.errors && (title.dirty || title.touched)">
    <span class="help-block error" [hidden]="!title.errors.required"> Title
      is Required
    </span>
</div>
<input type="file" #image="ngModel" (change)="fileEvent($event)"
name="image" ngModel>
</code>```

答:
If you want just to show/hide error message depend on selected file</p>

```<code>@Component({
  selector: 'my-app',
  template: `
    <div>
       <input type="file" (change)="onChange($event)" name="image">
      <div *ngIf="!fileSelected">
      <span class="help-block error" [hidden]="!fileSelected">
        File is Required
      </span>
     </div>
    </div>
  `,
})
export class AppComponent {
  onChange(event) {
    var files = event.srcElement.files;
    console.log(files);
    this.fileSelected = files.length>0;
  }
}
</code>```

Body:
Text input are working properly. I used same for file but its not working.

<input type="text" name="title" #title="ngModel" ngModel required class="form-control" placeholder="Title Here">

     Title
      is Required

<input type="file" #image="ngModel" (change)="fileEvent($event)"
name="image" ngModel>

Body:
If you want just to show/hide error message depend on selected file

@Component({
  selector: 'my-app',
  template: `
    <div>
       <input type="file" (change)="onChange($event)" name="image">
      <div *ngIf="!fileSelected">
      <span class="help-block error" [hidden]="!fileSelected">
        File is Required
      </span>
     </div>
    </div>
  `,
})
export class AppComponent {
  onChange(event) {
    var files = event.srcElement.files;
    console.log(files);
    this.fileSelected = files.length>0;
  }
}


问:
Mount a volume in docker-compose conditionally
I have a docker-compose.yml configuration. In one of the containers there is a Tomcat server and it has some default .war file deployed in webapps directory.

I want to have an ability to pass (override) the war archive to be deployed by some which resides on the host machine. I think the best would be to have ability somehow switch / override starting docker-compose: as a default, I want to run the webapp (war file) which is inside the container, but I want to have a possibility to mount a directory from my host (for example during development / debugging) if need be.

Currently, I have the following line in my docker-compose.yml, which is commented out if I need the default.

```<code>volumes:
# By default, there is the latest version of the application already present in the container
# If you want to provider the container with your own .war file, uncomment the following line
# - ./application/webapps:/usr/local/tomcat/webapps
</code>```

Is there a better way how to achieve that?

答:
Instead of (not) mounting a volume commenting out that line, I would use https://docs.docker.com/compose/extends/#example-use-case to run a service extension that specifies a volume.

I do this to tackle two different problems:

I don't specify a volume when the docker image is meant to run in production and has all the necessary files bundled in it.

I specify a volume during development, to check live changes.

ContentLicense: CC BY-SA 4.0

Body:
I have a docker-compose.yml configuration. In one of the containers there is a Tomcat server and it has some default .war file deployed in webapps directory.

I want to have an ability to pass (override) the war archive to be deployed by some which resides on the host machine. I think the best would be to have ability somehow switch / override starting docker-compose: as a default, I want to run the webapp (war file) which is inside the container, but I want to have a possibility to mount a directory from my host (for example during development / debugging) if need be.

Currently, I have the following line in my docker-compose.yml, which is commented out if I need the default.

volumes:
# By default, there is the latest version of the application already present in the container
# If you want to provider the container with your own .war file, uncomment the following line
# - ./application/webapps:/usr/local/tomcat/webapps

Is there a better way how to achieve that?


问:
Store huge std::map, mostly on disk
I've got a C++ program that's likely to generate a HUGE amount of data -- billions of binary records of varying sizes, most probably less than 256 bytes but a few stretching to several K. Most of the records will seldom be looked at by the program after they're created, but some will be accessed and modified regularly. There's no way to tell which are which when they're created.

Considering the volume of data, there's no way I can store it all in memory. But as the data only needs to be indexed and accessed by its number (a 64-bit integer), I don't want the overhead of a full-fledged database program. Ideally I'd like to treat it as an std::map with its data stored on disk until requested.

Is there an already-written library that will do what I'm looking for, or do I need to write it myself?

EDIT: After some thought, I realized that Rob Walker's answer had a valid point: I'd be hard-pressed to get anywhere near the same kind of data integrity out of a home-brew class that I'd get from a real database.

Although BerkeleyDB (as suggested by RHM) looks like it would do exactly what we're looking for, the dual-licensing is a headache that we don't want to deal with. When we're done with the code and can prove that it would benefit noticeably from BerkeleyDB (which it probably would), we'll reexamine the issue.

I did look at Ferruccio's suggestion of stxxl, but I wasn't able to tell how it would handle the program being interrupted and restarted (maybe with changes). With that much data, I'd hate to just scrap what it had already completed and start over every time, if some of the data could be saved.

So we've decided to use an SQLite database, at least for the initial development. Thanks to everyone who answered or voted.

答: I've used Gigabase http://www.garret.ru/gigabase.html, in several projects, it has a neat C++ interface, I've worked with millions of records without problems, it support rollback. It has MIT like license, also the author is very fast to answer questions and fix bugs.</p>

OwnerDisplayName: Head Geek

Title: Store huge std::map, mostly on disk

LastEditorDisplayName: Head Geek

OwnerDisplayName: xhantt


问:
Add preview actions to peek
For some reason this won't work.

I am trying to add preview actions to my peeked view controller. This view controller is created programmatically and does not actually exist in a file.

I have a regular ViewController, and I cannot override func previewActionItems() -> [UIPreviewActionItems]

It simply does not show up, and it won't compile because it's got nothing to override.

All tutorials I have found are from Swift 2, and I am using Swift 3

答:
In Swift 3, previewActionItems became an overridable variable. Try this:

```<code>override var previewActionItems: [UIPreviewActionItem] {
    return ...
}
</code>```

Title: Add preview actions to peek

Body:
In Swift 3, previewActionItems became an overridable variable. Try this:

override var previewActionItems: [UIPreviewActionItem] {
    return ...
}


问:
Operating on arrays using Unsigned Values
I have been generating a C function from Matlab Coder environnement in order to implement it in an other software called MAX/MSP.
I'm trying to make sense of it, thanks to my poor level in C programming, and there is some syntax elements I can't understand: the use of unsigned values like 0U or 1U to pass arrays.

The next example doesn't do anything. Pasting the entire code wouldn't help much, unless you think so.

```<code>void function1(const double A[49], double B[50])
{
  function2( (double *)&A[0U] );
}

static void function2(const double A[])
{

}
</code>```

While doing some math, Matlab wrote something like:

```<code>b = 2;
f[1U] += b;
</code>```

I don't understand the use of unsigned value either...

Thanks a lot!

答:
The U suffix is obviously not necessary here. It can be useful to force unsigned arithmetics in certain situations, with surprising side effects:

```<code>if (-1 < 1U) {
    printf("surprise!\n");
}
</code>```

In some rare occasions, it is necessary to avoid some type changes. On many current architectures, the following comparisons hold and the type of 2147483648 is different from that of 2147483648U is more than just signedness:

For example, on 32-bit linux and 32- and 64-bit windows:

```<code>sizeof(2147483648) == sizeof(long long)  // 8 bytes
sizeof(2147483648U) == sizeof(unsigned)  // 4 bytes
</code>```

On many embedded systems with 16-bit ints:

```<code>sizeof(2147483648) == sizeof(long long)       // 8 bytes
sizeof(2147483648U) == sizeof(unsigned long)  // 4 bytes
sizeof(32768) == sizeof(long)                 // 4 bytes
sizeof(32768U) == sizeof(unsigned int)        // 2 bytes
</code>```

Depending on implementation details, array index values can exceed the range of both type int and type unsigned, and pointer offset values can be even larger.  Just specifying U is no guarantee of anything.

Body:
I have been generating a C function from Matlab Coder environnement in order to implement it in an other software called MAX/MSP.
I'm trying to make sense of it, thanks to my poor level in C programming, and there is some syntax elements I can't understand: the use of unsigned values like 0U or 1U to pass arrays.

The next example doesn't do anything. Pasting the entire code wouldn't help much, unless you think so.

void function1(const double A[49], double B[50])
{
  function2( (double *)&A[0U] );
}

static void function2(const double A[])
{

}

While doing some math, Matlab wrote something like:

b = 2;
f[1U] += b;

I don't understand the use of unsigned value either...

Thanks a lot!

Body:
The U suffix is obviously not necessary here. It can be useful to force unsigned arithmetics in certain situations, with surprising side effects:

if (-1 < 1U) {
    printf("surprise!\n");
}

In some rare occasions, it is necessary to avoid some type changes. On many current architectures, the following comparisons hold and the type of 2147483648 is different from that of 2147483648U is more than just signedness:

For example, on 32-bit linux and 32- and 64-bit windows:

sizeof(2147483648) == sizeof(long long)  // 8 bytes
sizeof(2147483648U) == sizeof(unsigned)  // 4 bytes

On many embedded systems with 16-bit ints:

sizeof(2147483648) == sizeof(long long)       // 8 bytes
sizeof(2147483648U) == sizeof(unsigned long)  // 4 bytes
sizeof(32768) == sizeof(long)                 // 4 bytes
sizeof(32768U) == sizeof(unsigned int)        // 2 bytes

Depending on implementation details, array index values can exceed the range of both type int and type unsigned, and pointer offset values can be even larger.  Just specifying U is no guarantee of anything.