问:
Django Unable to rollback with try-exception block for atomic transactions
One of my view in Django executes save operations on 6-7 tables. I want these transactions to be atomic I,e if the 5th or 6th transaction fail I want to rollback all the previous saves.
The view contains a try-except block to handle the exceptions raised.

It looks something like this:

```<code>@transaction.atomic
def my_view(request):
    sid = transaction.savepoint()
    try:
        Table1.save()
        Table2.save()
        Table3.save()
        Table4.save()
        Table5.save()
        Table6.save()
        Table7.save()  # This might fail. In case of failure I want to rollback saves from Table1 to Table6

        transaction.savepoint_commit(sid)
    except Exception as e:
        print(str(e))
        transaction.savepoint_rollback(sid)
        return JsonResponse({"Status": 0, "Data": str(e)})
</code>```

I've tried the above and Table7.save() has failed and Table1 to Table6 rollback has not happened.
I want to return the JSON response as {"Status": 0, Data: "Error That occurred"} in all the cases.
I don't want to re-raise the exception in except block as done in This link

What should I do to return a proper JSONResponse and rollback everything in case of failure?

答:
As suggested in the link:

transaction.atomic will execute a transaction on the database if your
  view produces a response without errors. Because you're catching the
  exception yourself, it appears to Django that your view executed just
  fine. If you catch the exception, you need to handle it yourself

An alternative approach is to use transaction.atomic inside with (as context manager), which will ensure a commit or rollback (again suggested on the same link and also explained here)

```<code>def my_view(request):
    try:
        with transaction.atomic():
            Table1.save()
            Table2.save()
            Table3.save()
            Table4.save()
            Table5.save()
            Table6.save()
            Table7.save()  # This might fail. In case of failure I want to rollback saves from Table1 to Table6

    except Exception as e:
        print(str(e))
        return JsonResponse({"Status": 0, "Data": str(e)})
</code>```

Body:
One of my view in Django executes save operations on 6-7 tables. I want these transactions to be atomic I,e if the 5th or 6th transaction fail I want to rollback all the previous saves.
The view contains a try-except block to handle the exceptions raised.

It looks something like this:

@transaction.atomic
def my_view(request):
    sid = transaction.savepoint()
    try:
        Table1.save()
        Table2.save()
        Table3.save()
        Table4.save()
        Table5.save()
        Table6.save()
        Table7.save()  # This might fail. In case of failure I want to rollback saves from Table1 to Table6

        transaction.savepoint_commit(sid)
    except Exception as e:
        print(str(e))
        transaction.savepoint_rollback(sid)
        return JsonResponse({"Status": 0, "Data": str(e)})

I've tried the above and Table7.save() has failed and Table1 to Table6 rollback has not happened.
I want to return the JSON response as {"Status": 0, Data: "Error That occurred"} in all the cases.
I don't want to re-raise the exception in except block as done in This link

What should I do to return a proper JSONResponse and rollback everything in case of failure?

Body:
As suggested in the link:

transaction.atomic will execute a transaction on the database if your
  view produces a response without errors. Because you're catching the
  exception yourself, it appears to Django that your view executed just
  fine. If you catch the exception, you need to handle it yourself

An alternative approach is to use transaction.atomic inside with (as context manager), which will ensure a commit or rollback (again suggested on the same link and also explained here)

def my_view(request):
    try:
        with transaction.atomic():
            Table1.save()
            Table2.save()
            Table3.save()
            Table4.save()
            Table5.save()
            Table6.save()
            Table7.save()  # This might fail. In case of failure I want to rollback saves from Table1 to Table6

    except Exception as e:
        print(str(e))
        return JsonResponse({"Status": 0, "Data": str(e)})


来源: stackexchange

问:
How to change only error message color of input form-control
I am trying to style my first website.
I am using Bootstrap 4 and the jquery validation plugin and I am doing a form right now. I have two problems:
First, I only want to change the color of the error message below my input, but my styling changes the input text size/color and the error message text size/color, how can I only change error text below an input?

Second question is, where in my code do I change the Bootstrap form control state, depending on valid or not?

This is my code so far:

$('document').ready(function(){

    $('#registration_form').validate({
        rules: {
            username: {
                required: true,
                maxlength: 10,
                minlength: 3
            },
            email: {
                required: true,
                email: true
            },
            email_con: {
                required: true,
                equalTo: "#email"
            },
            password: {
                required: true,
                minlength: 7
            },
            password_con: {
                required: true,
                equalTo: "#password"
            },
            formCheck: {
                required: true
            },
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>        .error{
          color: red;
          font-Size: 13px;
        }</code>```

Email* :

<input class="form-control" type="email" name="email" id="email" placeholder="name@mail.com">

```

答:
There are classes to deal with validaiton when it comes to bootstrap usage. Try like this </p>

```<code><div class="container">
<p class="h1">Register</p>

<form class="needs-validation" novalidate>
<div class="form-group">
  <label for="email">E-mail</label>
  <input type="email" class="form-control" id="email"
         placeholder="E-mail" required>
  <div class="valid-feedback">
    Looks good!
  </div>
  <div class="invalid-feedback">
    The e-mail is required!
  </div>
</div>

<div class="form-group">
  <label for="password">Password</label>
  <input type="password" class="form-control" id="password"
         placeholder="Password" required minlength="6">
  <div class="valid-feedback">
    Great!
  </div>
  <div class="invalid-feedback">
    The password must contain at least 6 characters!
  </div>
</div>

<div class="form-group mt-3">
  <button class="btn btn-primary" type="submit">Register!</button>
</div>
</form>
</div>

<script>
(function() {
window.addEventListener('load', function() {
  var forms = document.getElementsByClassName('needs-validation');

  var validation = Array.prototype.filter.call(forms, function(form) {
    form.addEventListener('submit', function(event) {
      if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
      }
      form.classList.add('was-validated');
    }, false);
  });
}, false);
})();
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to style my first website.
I am using Bootstrap 4 and the jquery validation plugin and I am doing a form right now. I have two problems:
First, I only want to change the color of the error message below my input, but my styling changes the input text size/color and the error message text size/color, how can I only change error text below an input?

Second question is, where in my code do I change the Bootstrap form control state, depending on valid or not?

This is my code so far:

$('document').ready(function(){

    $('#registration_form').validate({
        rules: {
            username: {
                required: true,
                maxlength: 10,
                minlength: 3
            },
            email: {
                required: true,
                email: true
            },
            email_con: {
                required: true,
                equalTo: "#email"
            },
            password: {
                required: true,
                minlength: 7
            },
            password_con: {
                required: true,
                equalTo: "#password"
            },
            formCheck: {
                required: true
            },
        }
    });
});

        .error{
          color: red;
          font-Size: 13px;
        }

Email* :

<input class="form-control" type="email" name="email" id="email" placeholder="name@mail.com">

Body:
There are classes to deal with validaiton when it comes to bootstrap usage. Try like this

<div class="container">
<p class="h1">Register</p>

<form class="needs-validation" novalidate>
<div class="form-group">
  <label for="email">E-mail</label>
  <input type="email" class="form-control" id="email"
         placeholder="E-mail" required>
  <div class="valid-feedback">
    Looks good!
  </div>
  <div class="invalid-feedback">
    The e-mail is required!
  </div>
</div>

<div class="form-group">
  <label for="password">Password</label>
  <input type="password" class="form-control" id="password"
         placeholder="Password" required minlength="6">
  <div class="valid-feedback">
    Great!
  </div>
  <div class="invalid-feedback">
    The password must contain at least 6 characters!
  </div>
</div>

<div class="form-group mt-3">
  <button class="btn btn-primary" type="submit">Register!</button>
</div>
</form>
</div>

<script>
(function() {
window.addEventListener('load', function() {
  var forms = document.getElementsByClassName('needs-validation');

  var validation = Array.prototype.filter.call(forms, function(form) {
    form.addEventListener('submit', function(event) {
      if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
      }
      form.classList.add('was-validated');
    }, false);
  });
}, false);
})();
</script>


问:
Inferring a True Dual Port RAM (Xilinx and Intel compatible) in Verilog
I tried to write my own true dual-port memory module, hoping that it would infer as a BRAM:

```<code>module dp_async_ram (clk, rst, rd0, rd1, wr0, wr1, in1, in0, out1,out0, addr0, addr1);
  parameter DEPTH = 16;
  parameter WIDTH = 8;
  parameter ADDR = 4;

  input clk, rst;
  input rd0, rd1;
  input wr0, wr1;
  input [WIDTH-1:0] in0, in1;
  input [ADDR-1:0] addr0, addr1;

  output [WIDTH-1:0] out0, out1;

  //Define Memory
  logic [WIDTH-1:0] mem [0:DEPTH-1];
  logic [WIDTH-1:0] data0, data1;

  //Write Logic
  always_ff @ (posedge clk) begin
      if (wr0 && ~rd0)
        mem[addr0] <= in0;
      if (wr1 && ~rd1)
        mem[addr1] <= in1;
      if (rd0 && ~wr0)
        data0 <= mem[addr0];
      if (rd1 && ~wr1)
        data1 <= mem[addr1];
  end

  //Read Logic
  assign out0 = (rd0 && (!wr0))? data0: {WIDTH{1'bz}}; //High Impedance Mode here
  assign out1 = (rd0 && (!wr0))? data1: {WIDTH{1'bz}};

endmodule // dp_async_ram
</code>```

After running synthesis in Vivado, in the report says the following:

```<code> WARNING: [Synth 8-4767] Trying to implement RAM 'mem_reg' in registers. Block RAM or DRAM implementation is not possible; see log for reasons.
Reason is one or more of the following :
    1: RAM has multiple writes via different ports in same process. If RAM inferencing intended, write to one port per process.
    2: Unable to determine number of words or word size in RAM.
    3: No valid read/write found for RAM.
RAM "mem_reg" dissolved into registers
</code>```

Number 1 Strikes me the most since this implies there is no way to code a portable true dual port BRAM. I was wondering if I am wrong with this or if I should just use ip generation. Thanks

答:
I don't think #1 means that you can't do multiple writes--just that you can't do them from the same process. Try splitting them up:

```<code>always_ff @ (posedge clk) begin
    if (wr0 && ~rd0)
        mem[addr0] <= in0;
    if (rd0 && ~wr0)
        data0 <= mem[addr0];
end
always_ff @ (posedge clk) begin
    if (wr1 && ~rd1)
        mem[addr1] <= in1;
    if (rd1 && ~wr1)
        data1 <= mem[addr1];
end
</code>```

For more information on how to infer things in Vivado, look in the 'UG901 Vivado Synthesis' doc. For TDP BRAM, look under "RAM HDL Coding Techniques".

Alternately, if you don't mind being locked in to Xilinx, you can use the xpm_memory_tdpram module.

Body:
I tried to write my own true dual-port memory module, hoping that it would infer as a BRAM:

module dp_async_ram (clk, rst, rd0, rd1, wr0, wr1, in1, in0, out1,out0, addr0, addr1);
  parameter DEPTH = 16;
  parameter WIDTH = 8;
  parameter ADDR = 4;

  input clk, rst;
  input rd0, rd1;
  input wr0, wr1;
  input [WIDTH-1:0] in0, in1;
  input [ADDR-1:0] addr0, addr1;

  output [WIDTH-1:0] out0, out1;

  //Define Memory
  logic [WIDTH-1:0] mem [0:DEPTH-1];
  logic [WIDTH-1:0] data0, data1;

  //Write Logic
  always_ff @ (posedge clk) begin
      if (wr0 && ~rd0)
        mem[addr0] <= in0;
      if (wr1 && ~rd1)
        mem[addr1] <= in1;
      if (rd0 && ~wr0)
        data0 <= mem[addr0];
      if (rd1 && ~wr1)
        data1 <= mem[addr1];
  end

  //Read Logic
  assign out0 = (rd0 && (!wr0))? data0: {WIDTH{1'bz}}; //High Impedance Mode here
  assign out1 = (rd0 && (!wr0))? data1: {WIDTH{1'bz}};

endmodule // dp_async_ram

After running synthesis in Vivado, in the report says the following:

 WARNING: [Synth 8-4767] Trying to implement RAM 'mem_reg' in registers. Block RAM or DRAM implementation is not possible; see log for reasons.
Reason is one or more of the following :
    1: RAM has multiple writes via different ports in same process. If RAM inferencing intended, write to one port per process.
    2: Unable to determine number of words or word size in RAM.
    3: No valid read/write found for RAM.
RAM "mem_reg" dissolved into registers

Number 1 Strikes me the most since this implies there is no way to code a portable true dual port BRAM. I was wondering if I am wrong with this or if I should just use ip generation. Thanks

Body:
I don't think #1 means that you can't do multiple writes--just that you can't do them from the same process. Try splitting them up:

always_ff @ (posedge clk) begin
    if (wr0 && ~rd0)
        mem[addr0] <= in0;
    if (rd0 && ~wr0)
        data0 <= mem[addr0];
end
always_ff @ (posedge clk) begin
    if (wr1 && ~rd1)
        mem[addr1] <= in1;
    if (rd1 && ~wr1)
        data1 <= mem[addr1];
end

For more information on how to infer things in Vivado, look in the 'UG901 Vivado Synthesis' doc. For TDP BRAM, look under "RAM HDL Coding Techniques".

Alternately, if you don't mind being locked in to Xilinx, you can use the xpm_memory_tdpram module.


问:
Getting dailyLimitExceededUnreg message during development of my app
I'm building an app that uses Google APIs (Drive and Sheets). I'm currently writing code to utilize refresh tokens. So, I'm actually generating unauthorized (401 error) requests on purpose to test my code. Until... I hit this daily unauthorized limit. I'm not sure what I can do. What does "Continued use requires signup." actually mean? Signup for what? Do I need to register my app? Do I have to signup for Google Cloud billing? Any way to avoid this while developing an app?

(Note - I can successfully call the APIs before I hit this limit - when I started working on refresh token processing, so it's nothing related to how I'm generating requests - also I see the same thing in POSTMan).

Any help appreciated...

答:
Daily Limit for Unauthenticated Use Exceeded. Continued use requires
  signup

This error message usually indicates that you are trying to perform requests without an authorization token or API key.

It is intended behavior from Google's side to avoid abuse.

If you intentionally induce this situation, you have to wait until the next day for your quota to be reset, see here.


问:
Angular2 - Focusing a textbox on component load
I am developing a component in Angular2 (Beta 8). The component has a textbox and a dropdown. I would like to set the focus in textbox as soon as component is loaded or on change event of dropdown. How would I achieve this in angular2. Following is Html for the component.

    <form role="form" class="form-horizontal ">

                Name

                    <input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />

                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />

                Person

                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
                    </select>

    </form>

```

答:
you can use $ (jquery) :

```<code><div>
    <form role="form" class="form-horizontal ">
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>
                <div class="col-md-7 col-sm-7">
                    <input id="txtname`enter code here`" type="text" [(ngModel)]="person.Name" class="form-control" />

                </div>
                <div class="col-md-2 col-sm-2">
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />
                </div>
            </div>
        </div>
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>
                <div class="col-md-7 col-sm-7">
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
                    </select>
                </div>
            </div>
        </div>
    </form>
</div>
</code>```

then in ts :

```<code>    declare var $: any;

    @Component({
      selector: 'app-my-comp',
      templateUrl: './my-comp.component.html',
      styleUrls: ['./my-comp.component.css']
    })
    export class MyComponent  {

    @ViewChild('loadedComponent', { read: ElementRef, static: true }) loadedComponent: ElementRef<HTMLElement>;

    setFocus() {
    const elem = this.loadedComponent.nativeElement.querySelector('#txtname');
          $(elem).focus();
    }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you can use $ (jquery) :

<div>
    <form role="form" class="form-horizontal ">
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>
                <div class="col-md-7 col-sm-7">
                    <input id="txtname`enter code here`" type="text" [(ngModel)]="person.Name" class="form-control" />

                </div>
                <div class="col-md-2 col-sm-2">
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />
                </div>
            </div>
        </div>
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>
                <div class="col-md-7 col-sm-7">
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
                    </select>
                </div>
            </div>
        </div>
    </form>
</div>

then in ts :

    declare var $: any;

    @Component({
      selector: 'app-my-comp',
      templateUrl: './my-comp.component.html',
      styleUrls: ['./my-comp.component.css']
    })
    export class MyComponent  {

    @ViewChild('loadedComponent', { read: ElementRef, static: true }) loadedComponent: ElementRef<HTMLElement>;

    setFocus() {
    const elem = this.loadedComponent.nativeElement.querySelector('#txtname');
          $(elem).focus();
    }
    }


问:
MenuBar Not Showing for Simple QMainWindow Code, Qt Creator Mac OS
I have been having problems adding a menu item to the built in menu bar in a Qt desktop application. I copied the code provided in the QMainWindow class reference documentation for creating a menu to a very simple application. Unfortunately, it did not show up when the code was run. I am simply trying to add a “File” menu to the menu bar. I am running Mac OSX 10.9.3 and Qt Creator 5.3.1.

The screenshots of my code are below. I tried both the uncommented and commented code in the mainwindow.cpp source.

mainwindow.cpp

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //myMenuBar = menuBar();
    //fileMenu = myMenuBar -> addMenu(tr("&File"));

    fileMenu = menuBar() -> addMenu(tr("&File"));

    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
</code>```

mainwindow.h

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QMenuBar* myMenuBar;
    QMenu* fileMenu;
};

#endif //MAINWINDOW_H
</code>```

main.cpp

```<code>#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
</code>```

ComeOnMenuBar.pro

```<code>#-------------------------------------------------
#
# Project created by QtCreator 2014-08-12T02:28:33
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = ComeOnMenuBar
TEMPLATE = app

SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui
</code>```

Any help would be really appreciated! Thank you!

Note: I know using setNativeMenuBar(false) works, but I would like the mac os native menu bar to work: the one that is displayed in the top-most left corner.

答:
In order for OS X to gain control over the menu bar, you need to create the menu bar without a parent widget. This means in the mainwindow.cpp file typically, you'd have to create your menu bar in code.

This is my code that also puts in the About and Preferences menu items in the PROGRAM menu drop down as is standard on a mac:

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    this->aboutAction = new QAction(0);
    this->aboutAction->setMenuRole(QAction::AboutRole);
    this->aboutWindow = new About();
    this->preferencesAction = new QAction(0);
    this->preferencesAction->setMenuRole(QAction::PreferencesRole);
    this->preferencesWindow = new Preferences();
    this->mainMenuBar = new QMenuBar(0);  // 0 explicitly states to create it with no parent
    this->mainMenu = new QMenu(0);        // Same here
    this->mainMenuBar->addMenu(this->mainMenu);
    this->mainMenu->addAction(this->aboutAction);
    this->mainMenu->addAction(this->preferencesAction);
    this->setMenuBar(this->mainMenuBar);
    // ...
}
</code>```

Preferences and About are classes that handle their respective windows and code isn't included.

You will need to remove the menu bar in the mainwindow ui form that gets automatically generated.

Body:
I have been having problems adding a menu item to the built in menu bar in a Qt desktop application. I copied the code provided in the QMainWindow class reference documentation for creating a menu to a very simple application. Unfortunately, it did not show up when the code was run. I am simply trying to add a “File” menu to the menu bar. I am running Mac OSX 10.9.3 and Qt Creator 5.3.1.

The screenshots of my code are below. I tried both the uncommented and commented code in the mainwindow.cpp source.

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //myMenuBar = menuBar();
    //fileMenu = myMenuBar -> addMenu(tr("&File"));

    fileMenu = menuBar() -> addMenu(tr("&File"));

    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QMenuBar* myMenuBar;
    QMenu* fileMenu;
};

#endif //MAINWINDOW_H

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

ComeOnMenuBar.pro

#-------------------------------------------------
#
# Project created by QtCreator 2014-08-12T02:28:33
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = ComeOnMenuBar
TEMPLATE = app

SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

Any help would be really appreciated! Thank you!

Note: I know using setNativeMenuBar(false) works, but I would like the mac os native menu bar to work: the one that is displayed in the top-most left corner.

Body:
In order for OS X to gain control over the menu bar, you need to create the menu bar without a parent widget. This means in the mainwindow.cpp file typically, you'd have to create your menu bar in code.

This is my code that also puts in the About and Preferences menu items in the PROGRAM menu drop down as is standard on a mac:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    this->aboutAction = new QAction(0);
    this->aboutAction->setMenuRole(QAction::AboutRole);
    this->aboutWindow = new About();
    this->preferencesAction = new QAction(0);
    this->preferencesAction->setMenuRole(QAction::PreferencesRole);
    this->preferencesWindow = new Preferences();
    this->mainMenuBar = new QMenuBar(0);  // 0 explicitly states to create it with no parent
    this->mainMenu = new QMenu(0);        // Same here
    this->mainMenuBar->addMenu(this->mainMenu);
    this->mainMenu->addAction(this->aboutAction);
    this->mainMenu->addAction(this->preferencesAction);
    this->setMenuBar(this->mainMenuBar);
    // ...
}

Preferences and About are classes that handle their respective windows and code isn't included.

You will need to remove the menu bar in the mainwindow ui form that gets automatically generated.


问:
Alias Reference Date_Diff Days. Need to Parse or create temp table with dates?
Below I have the tables and query which output the below

Table1

```<code>EmployeeID | StartDateTimestamp | CohortID | CohortName
---------- | ------------------ | -------- | ----------
1          | 20080101 01:30:00  | 1        | Peanut
1          | 20090204 01:01:00  | 2        | Apple
2          | 20190107 05:52:14  | 1        | Peanut
3          | 20190311 02:35:26  | 2        | Apple
</code>```

Employee

```<code>EmployeeID | HireStartName | StartDateTimestamp2
---------- | ------------- | -------------------
1          | HiredStart    | 20080501 01:30:00
1          | DeferredStart | 20090604 01:01:00
2          | HiredStart    | 20190115 05:52:14
3          | HiredStart    | 20190330 02:35:26
</code>```

Query

```<code>select
    t.cohortid,
    min(e.startdatetimestamp2) first,
    max(e.startdatetimestamp2) last

from table1 t
inner join employee e on e.employeeid = t.employeeid
group by t.cohort_id
</code>```

Output

```<code>ID | FIRST            | LAST
1  |20190106 12:00:05 |20180214 03:45:12
2  |20180230 01:45:23 |20180315 01:45:23
</code>```

My attempt:

```<code>SELECT DATE_DIFF(first, last, Day), ID, max(datecolumn1) first, min(datecolumn1) last
</code>```

Error: Unrecognized name.
How do I enter the reference alias first and last in a Date_Diff?
Do I need to derive a table?

Clarity: Trying to avoid inputting in the dates, since I am looking to find the date diff of both first and last columns for as many rows as there is data.

This answer has been discussed here: Date Difference between consecutive rows

DateDiff has deprecated, and now it is Date_Diff (first, last, day)

Then I tried:

```<code>SELECT ID, DATE_DIFF(PARSE_DATE('%y%m%d',t.first), PARSE_DATE('%y%m%d',t.last), DAY) days
FROM table
</code>```

Failed to parse input string "20180125 01:00:05"

Tried this

```<code>SELECT CohortID, date_diff(first,last,day) as days
FROM (select cohortid,min(startdatetimestamp2) first,
max(startdatetimestamp2) last
FROM employee
JOIN table1 on table1.employeeid = employee.employeeid
group by cohortid)

</code>```

I get days not found on either side of join

答:
Regarding your first question about using aliases in a query, there are some restriction where to use them, specially in the FROM, GROUP BY and ORDER BY statements. I encourage you to have a look here to check these restrictions.

About your main issue, obtaining the date difference between two dates. I would like to point that your timestamp data, in both of your tables, are actually considered as DATETIME format in BigQuery. Therefore, you should use DATETIME builtin functions to get the desired results.

The below query uses the data you provided to obtain the aimed output.

```<code>WITH
  data AS
  (
  SELECT
    t.cohortid AS ID,
    PARSE_DATETIME('%Y%m%d %H:%M:%S', MIN(e.startdatetimestamp2)) AS first,
    PARSE_DATETIME('%Y%m%d %H:%M:%S', MAX(e.startdatetimestamp2)) AS last
  FROM
    `test-proj-261014.sample.table1` t
  INNER JOIN
    `test-proj-261014.sample.employee` e
  ON
    e.employeeid = t.employeeid
  GROUP BY t.cohortid
  )
SELECT
  ID,
  first,
  last,
  DATETIME_DIFF(last, first, DAY ) AS diff_days
FROM
  data
</code>```

And the output:

Notice that I created a temp table to format the fields StartDateTimestamp and StartDateTimestamp2, using the PARSE_DATETIME(). Afterwards, I used the DATETIME_DIFF() method to obtain the difference in days between the two fields.

Body:
Below I have the tables and query which output the below

Table1

EmployeeID | StartDateTimestamp | CohortID | CohortName
---------- | ------------------ | -------- | ----------
1          | 20080101 01:30:00  | 1        | Peanut
1          | 20090204 01:01:00  | 2        | Apple
2          | 20190107 05:52:14  | 1        | Peanut
3          | 20190311 02:35:26  | 2        | Apple

Employee

EmployeeID | HireStartName | StartDateTimestamp2
---------- | ------------- | -------------------
1          | HiredStart    | 20080501 01:30:00
1          | DeferredStart | 20090604 01:01:00
2          | HiredStart    | 20190115 05:52:14
3          | HiredStart    | 20190330 02:35:26

Query

select
    t.cohortid,
    min(e.startdatetimestamp2) first,
    max(e.startdatetimestamp2) last

from table1 t
inner join employee e on e.employeeid = t.employeeid
group by t.cohort_id

Output

ID | FIRST            | LAST
1  |20190106 12:00:05 |20180214 03:45:12
2  |20180230 01:45:23 |20180315 01:45:23

My attempt:

SELECT DATE_DIFF(first, last, Day), ID, max(datecolumn1) first, min(datecolumn1) last

Error: Unrecognized name.
How do I enter the reference alias first and last in a Date_Diff?
Do I need to derive a table?

Clarity: Trying to avoid inputting in the dates, since I am looking to find the date diff of both first and last columns for as many rows as there is data.

This answer has been discussed here: Date Difference between consecutive rows

DateDiff has deprecated, and now it is Date_Diff (first, last, day)

Then I tried:

SELECT ID, DATE_DIFF(PARSE_DATE('%y%m%d',t.first), PARSE_DATE('%y%m%d',t.last), DAY) days
FROM table

Failed to parse input string "20180125 01:00:05"

Tried this

SELECT CohortID, date_diff(first,last,day) as days
FROM (select cohortid,min(startdatetimestamp2) first,
max(startdatetimestamp2) last
FROM employee
JOIN table1 on table1.employeeid = employee.employeeid
group by cohortid)

I get days not found on either side of join

Body:
Regarding your first question about using aliases in a query, there are some restriction where to use them, specially in the FROM, GROUP BY and ORDER BY statements. I encourage you to have a look here to check these restrictions.

About your main issue, obtaining the date difference between two dates. I would like to point that your timestamp data, in both of your tables, are actually considered as DATETIME format in BigQuery. Therefore, you should use DATETIME builtin functions to get the desired results.

The below query uses the data you provided to obtain the aimed output.

WITH
  data AS
  (
  SELECT
    t.cohortid AS ID,
    PARSE_DATETIME('%Y%m%d %H:%M:%S', MIN(e.startdatetimestamp2)) AS first,
    PARSE_DATETIME('%Y%m%d %H:%M:%S', MAX(e.startdatetimestamp2)) AS last
  FROM
    `test-proj-261014.sample.table1` t
  INNER JOIN
    `test-proj-261014.sample.employee` e
  ON
    e.employeeid = t.employeeid
  GROUP BY t.cohortid
  )
SELECT
  ID,
  first,
  last,
  DATETIME_DIFF(last, first, DAY ) AS diff_days
FROM
  data

And the output:

Notice that I created a temp table to format the fields StartDateTimestamp and StartDateTimestamp2, using the PARSE_DATETIME(). Afterwards, I used the DATETIME_DIFF() method to obtain the difference in days between the two fields.


问:
Creating wrapper component
I want to create a wrapper component like this:

Wrapper Component:

```<code>class WrapperComponent extends Component {

  render() {
    return (
      <Image source={someImage}>
          <App />
      </Image>);
  }
}
</code>```

App:

```<code>class App extends Component {

  render() {
    return (
      <WrapperComponent>
        <Text>Some text</Text>
      </WrapperComponent>
  }
}
</code>```

I want to use this for the default things like a background image. Is there a way to do this? Sorry I am new in this language.

答:
As per official docs 'Composition vs Inheritance' the Inheritance approach is not recommended. So, you can create AwesomeWrapper.js with the content:

```<code>import React from 'react';
import { Image } from 'react-native';

export const AwesomeWrapper = (props) => {
  return (
    <Image source={props.imageSource}>
      {props.children}
    </Image>
  );
}
</code>```

and then use in your code like

```<code>    <AwesomeWrapper imageSource="...">
       ...
    </AwesomeWrapper>
</code>```

Title: Creating wrapper component

Body:
I want to create a wrapper component like this:

Wrapper Component:

class WrapperComponent extends Component {

  render() {
    return (
      <Image source={someImage}>
          <App />
      </Image>);
  }
}

App:

class App extends Component {

  render() {
    return (
      <WrapperComponent>
        <Text>Some text</Text>
      </WrapperComponent>
  }
}

I want to use this for the default things like a background image. Is there a way to do this? Sorry I am new in this language.

Body:
As per official docs 'Composition vs Inheritance' the Inheritance approach is not recommended. So, you can create AwesomeWrapper.js with the content:

import React from 'react';
import { Image } from 'react-native';

export const AwesomeWrapper = (props) => {
  return (
    <Image source={props.imageSource}>
      {props.children}
    </Image>
  );
}

and then use in your code like

    <AwesomeWrapper imageSource="...">
       ...
    </AwesomeWrapper>


问:
Vuex Module Decorators: Access vuex module from this.$store does not register the module
In my project, I created a small vuex module using vuex-module-decorators. But when trying to access it directly from this.$store or $store in the template part, it does not trigger the registration.

Here is an example:

```<code>// exampleModule.ts
import { Module, getModule, Mutation, VuexModule } from 'vuex-module-decorators';
import store from '@/store';

@Module({
  dynamic: true,
  namespaced: true,
  name: 'example',
  stateFactory: true,
  store,
})
class Example extends VuexModule {
  private work: boolean = false;

  get isWorking() {
    return this.work;
  }

  @Mutation
  setWorking(status: boolean) {
    this.work = status;
  }
}

export default getModule(Example);

// App.vue
<template>

  <div>
    first attempt: {{ $store.getters['example/isWorking'] }} // this is not working
    second attempt: {{ isWorking }} // this is not working too
  </div>
</template>

<script lang="ts">
  import Vue from 'vue';

  export default Vue.extend({
    computed: {
      isWorking() {
        return this.$store.getters['example/isWorking'];
      }
    }
  });
</script>
</code>```

The only way I get to to actually register the module and to make it work, is to import it directly in the component, like this:

```<code>
<script lang="ts">
  import Vue from 'vue';
  import exampleModule from '@/store/modules/example/exampleModule';

  export default Vue.extend({
    computed: {
      isWorking() {
        return exampleModule.isWorking;
      }
    }
  });
</script>
</code>```

Am I missing something here ? Is this the wanted behavior ? Thanks.

Btw, i opened an issue on their github repository, but i still don't have any answers, so here i am

https://github.com/championswimmer/vuex-module-decorators/issues/190

答:
Also make sure that you imported the module in the index.ts file of your store and ({ namespaced }) is set to true in your module. (something you already did)

Example folder structure:

```<code>/store
└── /modules
    └── Example.ts
    └── Other.ts
    └── Products.ts
    └── ...
└── index.ts
</code>```

index.ts

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import { Example } from './modules/Example'
import { Other } from './modules/Other'
import { Products } from './modules/Products'

export default new Vuex.Store({
  modules: {
    Example,
    Other, // Another module.
    Products // Another module.
  }
})
```

<p>Example.ts</p>

<pre class="lang-js prettyprint-override"><code>import { Module, VuexModule, Mutation } from 'vuex-module-decorators'

@Module({ namespaced: true })
export class Example extends VuexModule {
  work = false // You don't need to specify with work: boolean as TS will know the type by itself.

  @Mutation
  setWorking(status: boolean) {
    this.work = status
  }

  get isWorking() {
    return this.work
  }
}
</code>```

App.vue

<template>

    first attempt: {{ $store.getters['Example/isWorking'] }}

</template>
```

Body:
In my project, I created a small vuex module using vuex-module-decorators. But when trying to access it directly from this.$store or $store in the template part, it does not trigger the registration.

Here is an example:

// exampleModule.ts
import { Module, getModule, Mutation, VuexModule } from 'vuex-module-decorators';
import store from '@/store';

@Module({
  dynamic: true,
  namespaced: true,
  name: 'example',
  stateFactory: true,
  store,
})
class Example extends VuexModule {
  private work: boolean = false;

  get isWorking() {
    return this.work;
  }

  @Mutation
  setWorking(status: boolean) {
    this.work = status;
  }
}

export default getModule(Example);

// App.vue
<template>

    first attempt: {{ $store.getters['example/isWorking'] }} // this is not working
    second attempt: {{ isWorking }} // this is not working too

</template>

The only way I get to to actually register the module and to make it work, is to import it directly in the component, like this:

Am I missing something here ? Is this the wanted behavior ? Thanks.

Btw, i opened an issue on their github repository, but i still don't have any answers, so here i am

https://github.com/championswimmer/vuex-module-decorators/issues/190

Body:
Also make sure that you imported the module in the index.ts file of your store and ({ namespaced }) is set to true in your module. (something you already did)

Example folder structure:

/store
└── /modules
    └── Example.ts
    └── Other.ts
    └── Products.ts
    └── ...
└── index.ts

index.ts

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import { Example } from './modules/Example'
import { Other } from './modules/Other'
import { Products } from './modules/Products'

export default new Vuex.Store({
  modules: {
    Example,
    Other, // Another module.
    Products // Another module.
  }
})

Example.ts

import { Module, VuexModule, Mutation } from 'vuex-module-decorators'

@Module({ namespaced: true })
export class Example extends VuexModule {
  work = false // You don't need to specify with work: boolean as TS will know the type by itself.

  @Mutation
  setWorking(status: boolean) {
    this.work = status
  }

  get isWorking() {
    return this.work
  }
}

App.vue

<template>
  <div>
    first attempt: {{ $store.getters['Example/isWorking'] }}
  </div>
</template>


问:
Django - how to select unique values in col
I have a little problem with Django which I can't manage to solve.
Suppose that I have models like this:

```<code>class Game(models.Model):
# some attributes here

class Score(models.Model):
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
val = models.IntegerField()
#...
</code>```

Now, I want to keep in DB all the scores from last games, but when it comes to show their values on page I want to choose only the best score for chosen player in each game.
How do I do that? Or maybe I have to change Score model?

答:
Since you are trying to do this for the display, I'd probably make it into a template filter...

```<code>@register.filter
def highest_score(user, game):
  scores = Score.objects.filter(game=game, user=user).order_by("val")
  return scores[0]
</code>```

You'd need some error checking in there, obviously. For instance, you'll want to make sure that the "scores" queryset actually has results in it.

But, then you can use it in a template like this:

```<code><p>{{ user }}'s top score: {{ user|highest_score:game }}</p>
</code>```

Body:
I have a little problem with Django which I can't manage to solve.
Suppose that I have models like this:

class Game(models.Model):
# some attributes here

class Score(models.Model):
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
val = models.IntegerField()
#...

Now, I want to keep in DB all the scores from last games, but when it comes to show their values on page I want to choose only the best score for chosen player in each game.
How do I do that? Or maybe I have to change Score model?

Body:
Since you are trying to do this for the display, I'd probably make it into a template filter...

@register.filter
def highest_score(user, game):
  scores = Score.objects.filter(game=game, user=user).order_by("val")
  return scores[0]

You'd need some error checking in there, obviously. For instance, you'll want to make sure that the "scores" queryset actually has results in it.

But, then you can use it in a template like this:

<p>{{ user }}'s top score: {{ user|highest_score:game }}</p>


问:
WiX remove default IIS website before creating a new one
I created a WiX package for my website, and it works fine, except that my newly created website doesn't start after installation. That's because my website is registered to use *:80. IIS by default has a website setup with the same binding.

Is there a way to remove default website (or at least stop it) before creating my new website binding? I can't seem to find any information for this on the internet, but it seems like a common problem.

答:
I found how to do this, I thought I'd put an answer for any weary travelers:

```<code><CustomAction Id="RegisterCommand"
              Property="RegisterPowerShellProperty"
                                Execute="immediate"
                                Value=""C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy ByPass -NoLog -InputFormat None -NoProfile -command "Remove-IISSite -Name 'Default Web Site' -Confirm:$false""/>
<CustomAction Id="RegisterPowerShellProperty"
              BinaryKey="WixCA"
              DllEntry="CAQuietExec64"
              Execute="deferred"
              Return="check"
              Impersonate="no" />

<InstallExecuteSequence>
        <Custom Action="RegisterCommand" After="CostFinalize">NOT Installed</Custom>
       <Custom Action="RegisterPowerShellProperty" After="InstallFiles">NOT  Installed</Custom>
</InstallExecuteSequence>
</code>```

My answer was based off this article:  here

Body:
I found how to do this, I thought I'd put an answer for any weary travelers:

<CustomAction Id="RegisterCommand"
              Property="RegisterPowerShellProperty"
                                Execute="immediate"
                                Value="&quot;C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe&quot; -ExecutionPolicy ByPass -NoLog -InputFormat None -NoProfile -command &quot;Remove-IISSite -Name 'Default Web Site' -Confirm:$false&quot;"/>
<CustomAction Id="RegisterPowerShellProperty"
              BinaryKey="WixCA"
              DllEntry="CAQuietExec64"
              Execute="deferred"
              Return="check"
              Impersonate="no" />

<InstallExecuteSequence>
        <Custom Action="RegisterCommand" After="CostFinalize">NOT Installed</Custom>
       <Custom Action="RegisterPowerShellProperty" After="InstallFiles">NOT  Installed</Custom>
</InstallExecuteSequence>

My answer was based off this article:  here


问:
Swagger documentation for Spring Pageable interface
I have developed a microservice using Spring Boot. The documentation for the REST API is made with Swagger. Some REST resources make use of Spring concepts to provide pagination for free. Below is an example:

```<code>@RequestMapping(value = "/buckets", method = GET)
public PagedResources list(Pageable pageable, PagedResourcesAssembler assembler) {
    return bucketService.listBuckets(pageable, assembler);
}
</code>```

If I open the Swagger page, the following form is available for the resource:

The issue I have is that the pageable parameter is detected with content-type application/json and I don't know how to pass a value to change the page size for example. All values seem to be ignored.

Is it possible to pass the query parameters as JSON object? or is it possible to configure Swagger to generate independent query parameter fields for getters contained by the Pageable interface?

Please note that I am using Springfox with Gradle:

```<code>compile 'io.springfox:springfox-spring-web:2.3.1'
compile 'io.springfox:springfox-swagger2:2.3.1'
compile 'io.springfox:springfox-swagger-ui:2.3.1'
</code>```

答:
Here is the version of the annotation that was integrated into springdoc-openapi-data-rest for OpenAPI v3:

```<code>@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Parameter(in = ParameterIn.QUERY
        , description = "Zero-based page index (0..N)"
        , name = "page"
        , content = @Content(schema = @Schema(type = "integer", defaultValue = "0")))
@Parameter(in = ParameterIn.QUERY
        , description = "The size of the page to be returned"
        , name = "size"
        , content = @Content(schema = @Schema(type = "integer", defaultValue = "20")))
@Parameter(in = ParameterIn.QUERY
        , description = "Sorting criteria in the format: property(,asc|desc). "
        + "Default sort order is ascending. " + "Multiple sort criteria are supported."
        , name = "sort"
        , content = @Content(array = @ArraySchema(schema = @Schema(type = "string"))))
public @interface PageableAsQueryParam {

}
</code>```

See https://springdoc.github.io/springdoc-openapi-demos/faq.html#how-can-i-map-pageable-spring-date-commons-object-to-correct-url-parameter-in-swagger-ui

Body:
I have developed a microservice using Spring Boot. The documentation for the REST API is made with Swagger. Some REST resources make use of Spring concepts to provide pagination for free. Below is an example:

@RequestMapping(value = "/buckets", method = GET)
public PagedResources list(Pageable pageable, PagedResourcesAssembler assembler) {
    return bucketService.listBuckets(pageable, assembler);
}

If I open the Swagger page, the following form is available for the resource:

The issue I have is that the pageable parameter is detected with content-type application/json and I don't know how to pass a value to change the page size for example. All values seem to be ignored.

Is it possible to pass the query parameters as JSON object? or is it possible to configure Swagger to generate independent query parameter fields for getters contained by the Pageable interface?

Please note that I am using Springfox with Gradle:

compile 'io.springfox:springfox-spring-web:2.3.1'
compile 'io.springfox:springfox-swagger2:2.3.1'
compile 'io.springfox:springfox-swagger-ui:2.3.1'

Body:
Here is the version of the annotation that was integrated into springdoc-openapi-data-rest for OpenAPI v3:

@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Parameter(in = ParameterIn.QUERY
        , description = "Zero-based page index (0..N)"
        , name = "page"
        , content = @Content(schema = @Schema(type = "integer", defaultValue = "0")))
@Parameter(in = ParameterIn.QUERY
        , description = "The size of the page to be returned"
        , name = "size"
        , content = @Content(schema = @Schema(type = "integer", defaultValue = "20")))
@Parameter(in = ParameterIn.QUERY
        , description = "Sorting criteria in the format: property(,asc|desc). "
        + "Default sort order is ascending. " + "Multiple sort criteria are supported."
        , name = "sort"
        , content = @Content(array = @ArraySchema(schema = @Schema(type = "string"))))
public @interface PageableAsQueryParam {

}

See https://springdoc.github.io/springdoc-openapi-demos/faq.html#how-can-i-map-pageable-spring-date-commons-object-to-correct-url-parameter-in-swagger-ui


问:
How to get an array of character (A-z, no numbers) from a given string?
I need a java regex to answer my question.

this is my code:

```<code>char[] array = s.split("regex");
</code>```

答:
As you said in your comment below your question, what you really want, is to get the individual characters of that given string, which can be achieved by the toCharArray() method in the String class.

String s = "ABCDEfghi1234";
char[] chars = s.toCharArray();
```

<p>If you also need to limit the resulting chars to a defined set of characters, you have to remove all others from the string first, which can be done with a simple regex-replace.</p>

<pre class="lang-java prettyprint-override"><code>String s = "ABCDEfghi1234_.,-DSsf";
s = s.replaceAll("[^A-Za-z]", "");
char[] chars = s.toCharArray();
</code>```

The split method you used is normally used to split strings at defined positions, e.g. if you want to split a sentence, separated by spaces.

String sentence = "The quick brown fox jumps over the lazy dog";
String[] words = sentence.split("\\s");
// words now contains the extracted words of the sentence
// words[0] == "The"
// words[1] == "quick"
// ...
```

Body:
I need a java regex to answer my question.

this is my code:

char[] array = s.split("regex");

Body:
As you said in your comment below your question, what you really want, is to get the individual characters of that given string, which can be achieved by the toCharArray() method in the String class.

String s = "ABCDEfghi1234";
char[] chars = s.toCharArray();

If you also need to limit the resulting chars to a defined set of characters, you have to remove all others from the string first, which can be done with a simple regex-replace.

String s = "ABCDEfghi1234_.,-DSsf";
s = s.replaceAll("[^A-Za-z]", "");
char[] chars = s.toCharArray();

The split method you used is normally used to split strings at defined positions, e.g. if you want to split a sentence, separated by spaces.

String sentence = "The quick brown fox jumps over the lazy dog";
String[] words = sentence.split("\\s");
// words now contains the extracted words of the sentence
// words[0] == "The"
// words[1] == "quick"
// ...


问:
Keep browser open while developing a test in Testcafe
How to keep the browser window open after a test executes in Testcafe?

There was a question on the forum here that brought me to a live Testcafe version, but it seems to be deprecated.

I wish to keep the browser window open to see the elements while I'm developing the test.

Update:

This is my config file:

```<code>{
  "name": "testcafe-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "testcafe": "^1.8.2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "testcafe chrome tests/",
    "testcafe": "testcafe"
  },
  "author": "mmrse",
  "license": "ISC"
}
</code>```

I tried starting the tests from the command line with

```<code>E:\testcafe-demo> npm run testcafe chrome demo.testcafe.ts --live
</code>```

and with

```<code>E:\testcafe-demo> npm test chrome demo.testcafe.ts --live
</code>```

but the result is always the same - after the test is finished, the browser is closed and there is no indication "live" mode was being activated.

答:
Features from TestCafe Live were integrated into the main TestCafe product.

See Live Mode for more information.

Make sure to add the --live argument into your script:

```<code>  "scripts": {
    "test": "testcafe chrome tests/ --live",
    "testcafe": "testcafe"
  },
</code>```

And run your tests using npm run test.

Here's another example:

screeshot.js

```<code>import { Selector } from 'testcafe';

fixture `My fixture`
    .page `http://devexpress.github.io/testcafe/example/`;

test('Take a screenshot of a fieldset', async t => {
    await t
        .typeText('#developer-name', 'Peter Parker')
        .click('#submit-button')
        .takeScreenshot({
            path:     'my-fixture/thank-you-page1.png',
            fullPage: true
        });
});
</code>```

Command-line arguments:

```<code>testcafe chrome screenshot.js --live
</code>```

Output:

```<code>Using locally installed version of TestCafe.

Live mode is enabled.
TestCafe now watches source files and reruns
the tests once the changes are saved.

You can use the following keys in the terminal:
'Ctrl+S' - stops the test run;
'Ctrl+R' - restarts the test run;
'Ctrl+W' - enables/disables watching files;
'Ctrl+C' - quits live mode and closes the browsers.

Watching the following files:
  c:\Temp\screenshot.js
 Running tests in:
 - Chrome 79.0.3945.130 / Windows 10

 My fixture
 √ Take a screenshot of a fieldset (screenshots: c:\Temp\screenshots\my-fixture\thank-you-page1.png)

 1 passed (5s)

Make changes to the source files or press Ctrl+R to restart the test run.
</code>```

Body:
How to keep the browser window open after a test executes in Testcafe?

There was a question on the forum here that brought me to a live Testcafe version, but it seems to be deprecated.

I wish to keep the browser window open to see the elements while I'm developing the test.

Update:

This is my config file:

{
  "name": "testcafe-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "testcafe": "^1.8.2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "testcafe chrome tests/",
    "testcafe": "testcafe"
  },
  "author": "mmrse",
  "license": "ISC"
}

I tried starting the tests from the command line with

E:\testcafe-demo> npm run testcafe chrome demo.testcafe.ts --live

and with

E:\testcafe-demo> npm test chrome demo.testcafe.ts --live

but the result is always the same - after the test is finished, the browser is closed and there is no indication "live" mode was being activated.

Body:
Features from TestCafe Live were integrated into the main TestCafe product.

See Live Mode for more information.

Make sure to add the --live argument into your script:

  "scripts": {
    "test": "testcafe chrome tests/ --live",
    "testcafe": "testcafe"
  },

And run your tests using npm run test.

Here's another example:

screeshot.js

import { Selector } from 'testcafe';

fixture `My fixture`
    .page `http://devexpress.github.io/testcafe/example/`;

test('Take a screenshot of a fieldset', async t => {
    await t
        .typeText('#developer-name', 'Peter Parker')
        .click('#submit-button')
        .takeScreenshot({
            path:     'my-fixture/thank-you-page1.png',
            fullPage: true
        });
});

Command-line arguments:

testcafe chrome screenshot.js --live

Output:

Using locally installed version of TestCafe.

Live mode is enabled.
TestCafe now watches source files and reruns
the tests once the changes are saved.

You can use the following keys in the terminal:
'Ctrl+S' - stops the test run;
'Ctrl+R' - restarts the test run;
'Ctrl+W' - enables/disables watching files;
'Ctrl+C' - quits live mode and closes the browsers.

Watching the following files:
  c:\Temp\screenshot.js
 Running tests in:
 - Chrome 79.0.3945.130 / Windows 10

 My fixture
 √ Take a screenshot of a fieldset (screenshots: c:\Temp\screenshots\my-fixture\thank-you-page1.png)

 1 passed (5s)

Make changes to the source files or press Ctrl+R to restart the test run.


问:
How to modify parent public member variable from child member function?
programming beginner here. I've been trying to figure this out myself for a while,
Can anyone tell me why this prints 5 and not 8? As far as I know this should work I've tried pass by reference and using pointers but as I'm still a bit of a noob perhaps I haven't quite got it yet so if anyone could help me out and point me in the right direction id appreciate it.
Cheers.</p>

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

class classA {
  public:
    int a = 5;

    void print(){
      cout << a << endl;
    }
};

 class classB : public classA {
   public:
     int one;
     void modify (){
       cin >> one;
       if (one == 1){
         a =+ 3;
       }
     }
 };

int main()
{

    cout << "Hi, push '1'" << endl;
    classA printobj;
    classB modifyobj;
    modifyobj.modify();
    printobj.print();

    return 0;
}
</code>```

答: Thanks all, I knew it would be something simple, I have a lot to learn haha!</p>

Body:
programming beginner here. I've been trying to figure this out myself for a while,
Can anyone tell me why this prints 5 and not 8? As far as I know this should work I've tried pass by reference and using pointers but as I'm still a bit of a noob perhaps I haven't quite got it yet so if anyone could help me out and point me in the right direction id appreciate it.
Cheers.

#include <iostream>
using namespace std;

class classA {
  public:
    int a = 5;

    void print(){
      cout << a << endl;
    }
};

 class classB : public classA {
   public:
     int one;
     void modify (){
       cin >> one;
       if (one == 1){
         a =+ 3;
       }
     }
 };

int main()
{

    cout << "Hi, push '1'" << endl;
    classA printobj;
    classB modifyobj;
    modifyobj.modify();
    printobj.print();

    return 0;
}


问:
how to use excel sum formula in php phpspreadsheet?
I am using PhpSpreasdheet php library. I have done almost everything i want to sum the particular column and want to show total of that column.. See My output is coming below:-

My expected output like below:-

I have tried below code:-

```<code>$spreadsheet = new Spreadsheet();
$Excel_writer = new Xlsx($spreadsheet);
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();

$activeSheet->setCellValue('A1', 'Location');
$activeSheet->setCellValue('B1', 'Media Vehicle');
$activeSheet->setCellValue('C1', 'Dimension');
$activeSheet->setCellValue('D1', 'Amount');

$spreadsheet->getActiveSheet()->setAutoFilter('A1:D1');
    $locations = DB::table('locations')->get();
    $locations = json_decode(json_encode($locations),true);
    $i = 2;
    foreach($locations as $location){
        $activeSheet->setCellValue('A'.$i , $location['location']);
        $activeSheet->setCellValue('B'.$i , $location['media_vehicle']);
        $activeSheet->setCellValue('C'.$i , $location['dimension']);
        $activeSheet->setCellValue('D'.$i , $location['amount']);
        $i++;
    }

    $samplepath = storage_path('/excels/sampleExcel'.str_random(5).'.xlsx');
    $Excel_writer->save($samplepath);
    echo 'saved'; die;
</code>```

I want the total of amount column. I want to make dynamic. if in future it will be 10 rows so it will calculate 10 rows of amount column count.

答:
In phpspreadsheet you can use Excel formulas.
All you need is the range of numbers you want to sum.</p>

```<code>$SUMRANGE = 'D2:D'.$i;
$activeSheet->setCellValue('D'.$i , '=SUM($SUMRANGE)');
</code>```

Body:
I am using PhpSpreasdheet php library. I have done almost everything i want to sum the particular column and want to show total of that column.. See My output is coming below:-

My expected output like below:-

I have tried below code:-

$spreadsheet = new Spreadsheet();
$Excel_writer = new Xlsx($spreadsheet);
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();

$activeSheet->setCellValue('A1', 'Location');
$activeSheet->setCellValue('B1', 'Media Vehicle');
$activeSheet->setCellValue('C1', 'Dimension');
$activeSheet->setCellValue('D1', 'Amount');

$spreadsheet->getActiveSheet()->setAutoFilter('A1:D1');
    $locations = DB::table('locations')->get();
    $locations = json_decode(json_encode($locations),true);
    $i = 2;
    foreach($locations as $location){
        $activeSheet->setCellValue('A'.$i , $location['location']);
        $activeSheet->setCellValue('B'.$i , $location['media_vehicle']);
        $activeSheet->setCellValue('C'.$i , $location['dimension']);
        $activeSheet->setCellValue('D'.$i , $location['amount']);
        $i++;
    }

    $samplepath = storage_path('/excels/sampleExcel'.str_random(5).'.xlsx');
    $Excel_writer->save($samplepath);
    echo 'saved'; die;

I want the total of amount column. I want to make dynamic. if in future it will be 10 rows so it will calculate 10 rows of amount column count.

Body:
In phpspreadsheet you can use Excel formulas.
All you need is the range of numbers you want to sum.

$SUMRANGE = 'D2:D'.$i;
$activeSheet->setCellValue('D'.$i , '=SUM($SUMRANGE)');


问:
Find the last match with Java regex matcher
I'm trying to get the last result of a match without having to cycle through .find()

Here's my code:

```<code>String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("num ([0-9]+)");
Matcher m = p.matcher(in);

if (m.find()) {
     in = m.group(1);
}
</code>```

That will give me the first result.  How do I find the LAST match without cycling through a potentially huge list?

答:
just use \Z - end of string mach</p>

```<code>String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("num ([0-9]+)\\Z");
Matcher m = p.matcher(in);

if (m.find()) {
     in = m.group(1);
}
</code>```

Body:
I'm trying to get the last result of a match without having to cycle through .find()

Here's my code:

String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("num ([0-9]+)");
Matcher m = p.matcher(in);

if (m.find()) {
     in = m.group(1);
}

That will give me the first result.  How do I find the LAST match without cycling through a potentially huge list?

Body:
just use \Z - end of string mach

String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("num ([0-9]+)\\Z");
Matcher m = p.matcher(in);

if (m.find()) {
     in = m.group(1);
}


问:
Lotus Notes and xul files
How can I open xul forms in Lotes Notes (8.5.2)? I read this, but I still don't understand.</p>

答:
Wolfgang's post shows how to generate a XUL form blending in data from a Lotus Notes database.  You can create a Page in Notes and insert any text content that you'd like output to a browser.  In this case the content-type of the page is set to application/vnd.mozilla.xul+xml

When that Notes database is on a Domino server, and you visit that page in your browser, you will be opening a XUL form.  Since XUL only works on Mozilla-based browsers (i.e Firefox 3.5), other browsers will prompt you to download the content.  When you do visit with the Mozilla browser you'll see the XUL form (presumably.  None of my browsers support it)

Firefox 4 has done away with Remote XUL support, BTW, so this isn't a good technology to get to wrapped up in.  (although the same could be said for Notes?  Ouch.)

If you'd like to test your browser using a working example, check out Jake Howlett's blog post on XUL and follow the link to his demo.

Title: Lotus Notes and xul files


问:
Adding polylines to map error Failed resolution of: Ljava/time/ZonedDateTime
I am trying to add polylines to a map between the current location and a marker added dynamically to the map. The way it should work it's when the InfoWindow from the marker it's pressed, a dialog asking if you wanna travel to that point opens, and when the "Yes" option is pressed, it should add the polyline to that point.

OnInfoWindowClick :

```<code>public void onInfoWindowClick(final Marker marker1) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Doriți să mergeți la această alertă?")
            .setCancelable(true)
            .setPositiveButton("Da", new DialogInterface.OnClickListener() {
                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    ScoateMarkerRute();
                    markerSelectat=marker1;
                    layout_confirmare.setVisibility(GONE);
                    layout_validare.setVisibility(GONE);
                    calculateDirections(marker1);
                    dialog.dismiss();
                }
            })
            .setNegativeButton("Nu", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}
</code>```

calculateDirections(); :

```<code>private void calculateDirections(Marker marker){
    Log.d(TAG, "calculateDirections: calculating directions.");

    com.google.maps.model.LatLng destinatie = new com.google.maps.model.LatLng(
            marker.getPosition().latitude,
            marker.getPosition().longitude
    );
    DirectionsApiRequest directions = new DirectionsApiRequest(mGeoApiContext);

    directions.alternatives(true);
    directions.origin(
            new com.google.maps.model.LatLng(
                    locatie_user.latitude,
                    locatie_user.longitude
            )
    );
    Log.d(TAG, "calculateDirections: destination: " + destinatie.toString());
    directions.destination(destinatie).setCallback(new PendingResult.Callback<DirectionsResult>() {
        @Override
        public void onResult(DirectionsResult result) {
            Log.d(TAG, "calculateDirections: routes: " + result.routes[0].toString());
            Log.d(TAG, "calculateDirections: duration: " + result.routes[0].legs[0].duration);
            Log.d(TAG, "calculateDirections: distance: " + result.routes[0].legs[0].distance.inMeters);
            Log.d(TAG, "calculateDirections: geocodedWayPoints: " + result.geocodedWaypoints[0].toString());
            addPolylinesToMap(result);
        }

        @Override
        public void onFailure(Throwable e) {
            Log.e(TAG, "calculateDirections: Failed to get directions: " + e.getMessage() );

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

addPolylinesToMap :

```<code>private void addPolylinesToMap(final DirectionsResult result){
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "run: result routes: " + result.routes.length);
            if(mPolylinesData.size()>0){
                for(PolylineData polylineData: mPolylinesData){
                    polylineData.getPolyline().remove();
                }
                mPolylinesData.clear();
                mPolylinesData= new ArrayList<>();
            }
            for(DirectionsRoute route: result.routes){
                Log.d(TAG, "run: leg: " + route.legs[0].toString());
                List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());

                List<LatLng> newDecodedPath = new ArrayList<>();

                // This loops through all the LatLng coordinates of ONE polyline.
                for(com.google.maps.model.LatLng latLng: decodedPath){
                Log.d(TAG, "run: latlng: " + latLng.toString());

                newDecodedPath.add(new LatLng(
                            latLng.lat,
                            latLng.lng
                    ));
                }
                Polyline polyline = mMap.addPolyline(new PolylineOptions().addAll(newDecodedPath));
                polyline.setColor(ContextCompat.getColor(Harta.this, R.color.scope_systems_gri));
                polyline.setWidth(25);
                polyline.setClickable(true);
                polyline.setTag("A");
                mPolylinesData.add(new PolylineData(polyline, route.legs[0]));
                onPolylineClick(polyline);
                zoomRoute(polyline.getPoints());
                markerSelectat.setVisible(false);
            }
        }
    });
}
</code>```

When I implemented this method of adding polylines, I used a map full of markers and actually worked. When I changed and added only 1 marker, the app kept crashing with the error :

```<code>> > java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/ZonedDateTime;
>         at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:241)
>         at com.google.maps.internal.OkHttpPendingResult.onResponse(OkHttpPendingResult.java:207)
>         at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
>         at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
>         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
>         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
>         at java.lang.Thread.run(Thread.java:761)
>      Caused by: java.lang.ClassNotFoundException: Didn't find class "java.time.ZonedDateTime" on path: DexPathList[[zip file
> "/data/app/com.example.aplicatieprimarie-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.aplicatieprimarie-2/lib/x86,
> /system/lib, /vendor/lib]]
>         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
>         at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:241)
>         at com.google.maps.internal.OkHttpPendingResult.onResponse(OkHttpPendingResult.java:207)
>         at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
>         at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
>         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
>         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
>         at java.lang.Thread.run(Thread.java:761)
</code>```

EDIT: added build.gradle

I have updated:
-'com.google.android.libraries.places:places-compat:2.1.0' to 'com.google.android.libraries.places:places-compat:2.1.1'
and now after syncing, when I try to run I get the following error:

Caused by: com.android.tools.r8.utils.AbortException: Error: null, Cannot fit requested classes in a single dex file (# methods: 66003 > 65536)

build.gradle(app):

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.aplicatieprimarie"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.facebook.android:facebook-android-sdk:5.9.0'
    implementation "com.google.android.gms:play-services-location:17.0.0"
    implementation 'de.hdodenhof:circleimageview:3.0.1'
    implementation 'com.github.bumptech.glide:glide:4.10.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
    implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.2.1'
    implementation 'androidx.navigation:navigation-ui:2.2.1'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.libraries.places:places-compat:2.2.0'
    implementation 'androidx.biometric:biometric:1.0.1'
    implementation 'com.google.maps:google-maps-services:0.10.2'
    implementation 'org.slf4j:slf4j-simple:1.7.25'
}
</code>```

答:
According documentation of Google Maps Services, this is not designed for android.

The Java Client for Google Maps Services is designed for use in server
applications. This library is not intended for use inside of an
Android app, due to the potential for loss of API keys.

Requirements

Java 1.8 or later.

A Google Maps API key.

You need java.time to handle Time Zone API. As a workaround you can use below dependency which is Backport of java.time package API

```<code>implementation group: 'com.github.seratch', name: 'java-time-backport', version: '1.0.0'
</code>```

Body:
I am trying to add polylines to a map between the current location and a marker added dynamically to the map. The way it should work it's when the InfoWindow from the marker it's pressed, a dialog asking if you wanna travel to that point opens, and when the "Yes" option is pressed, it should add the polyline to that point.

OnInfoWindowClick :

public void onInfoWindowClick(final Marker marker1) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Doriți să mergeți la această alertă?")
            .setCancelable(true)
            .setPositiveButton("Da", new DialogInterface.OnClickListener() {
                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    ScoateMarkerRute();
                    markerSelectat=marker1;
                    layout_confirmare.setVisibility(GONE);
                    layout_validare.setVisibility(GONE);
                    calculateDirections(marker1);
                    dialog.dismiss();
                }
            })
            .setNegativeButton("Nu", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

calculateDirections(); :

private void calculateDirections(Marker marker){
    Log.d(TAG, "calculateDirections: calculating directions.");

    com.google.maps.model.LatLng destinatie = new com.google.maps.model.LatLng(
            marker.getPosition().latitude,
            marker.getPosition().longitude
    );
    DirectionsApiRequest directions = new DirectionsApiRequest(mGeoApiContext);

    directions.alternatives(true);
    directions.origin(
            new com.google.maps.model.LatLng(
                    locatie_user.latitude,
                    locatie_user.longitude
            )
    );
    Log.d(TAG, "calculateDirections: destination: " + destinatie.toString());
    directions.destination(destinatie).setCallback(new PendingResult.Callback<DirectionsResult>() {
        @Override
        public void onResult(DirectionsResult result) {
            Log.d(TAG, "calculateDirections: routes: " + result.routes[0].toString());
            Log.d(TAG, "calculateDirections: duration: " + result.routes[0].legs[0].duration);
            Log.d(TAG, "calculateDirections: distance: " + result.routes[0].legs[0].distance.inMeters);
            Log.d(TAG, "calculateDirections: geocodedWayPoints: " + result.geocodedWaypoints[0].toString());
            addPolylinesToMap(result);
        }

        @Override
        public void onFailure(Throwable e) {
            Log.e(TAG, "calculateDirections: Failed to get directions: " + e.getMessage() );

        }
    });
}

addPolylinesToMap :

private void addPolylinesToMap(final DirectionsResult result){
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "run: result routes: " + result.routes.length);
            if(mPolylinesData.size()>0){
                for(PolylineData polylineData: mPolylinesData){
                    polylineData.getPolyline().remove();
                }
                mPolylinesData.clear();
                mPolylinesData= new ArrayList<>();
            }
            for(DirectionsRoute route: result.routes){
                Log.d(TAG, "run: leg: " + route.legs[0].toString());
                List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());

                List<LatLng> newDecodedPath = new ArrayList<>();

                // This loops through all the LatLng coordinates of ONE polyline.
                for(com.google.maps.model.LatLng latLng: decodedPath){
                Log.d(TAG, "run: latlng: " + latLng.toString());

                newDecodedPath.add(new LatLng(
                            latLng.lat,
                            latLng.lng
                    ));
                }
                Polyline polyline = mMap.addPolyline(new PolylineOptions().addAll(newDecodedPath));
                polyline.setColor(ContextCompat.getColor(Harta.this, R.color.scope_systems_gri));
                polyline.setWidth(25);
                polyline.setClickable(true);
                polyline.setTag("A");
                mPolylinesData.add(new PolylineData(polyline, route.legs[0]));
                onPolylineClick(polyline);
                zoomRoute(polyline.getPoints());
                markerSelectat.setVisible(false);
            }
        }
    });
}

When I implemented this method of adding polylines, I used a map full of markers and actually worked. When I changed and added only 1 marker, the app kept crashing with the error :

> > java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/ZonedDateTime;
>         at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:241)
>         at com.google.maps.internal.OkHttpPendingResult.onResponse(OkHttpPendingResult.java:207)
>         at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
>         at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
>         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
>         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
>         at java.lang.Thread.run(Thread.java:761)
>      Caused by: java.lang.ClassNotFoundException: Didn't find class "java.time.ZonedDateTime" on path: DexPathList[[zip file
> "/data/app/com.example.aplicatieprimarie-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.aplicatieprimarie-2/lib/x86,
> /system/lib, /vendor/lib]]
>         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
>         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
>         at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:241)
>         at com.google.maps.internal.OkHttpPendingResult.onResponse(OkHttpPendingResult.java:207)
>         at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
>         at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
>         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
>         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
>         at java.lang.Thread.run(Thread.java:761)

EDIT: added build.gradle

I have updated:
-'com.google.android.libraries.places:places-compat:2.1.0' to 'com.google.android.libraries.places:places-compat:2.1.1'
and now after syncing, when I try to run I get the following error:

Caused by: com.android.tools.r8.utils.AbortException: Error: null, Cannot fit requested classes in a single dex file (# methods: 66003 > 65536)

build.gradle(app):

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.aplicatieprimarie"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.facebook.android:facebook-android-sdk:5.9.0'
    implementation "com.google.android.gms:play-services-location:17.0.0"
    implementation 'de.hdodenhof:circleimageview:3.0.1'
    implementation 'com.github.bumptech.glide:glide:4.10.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
    implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.2.1'
    implementation 'androidx.navigation:navigation-ui:2.2.1'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.libraries.places:places-compat:2.2.0'
    implementation 'androidx.biometric:biometric:1.0.1'
    implementation 'com.google.maps:google-maps-services:0.10.2'
    implementation 'org.slf4j:slf4j-simple:1.7.25'
}

Body:
According documentation of Google Maps Services, this is not designed for android.

The Java Client for Google Maps Services is designed for use in server
applications. This library is not intended for use inside of an
Android app, due to the potential for loss of API keys.

Requirements

Java 1.8 or later.

A Google Maps API key.

You need java.time to handle Time Zone API. As a workaround you can use below dependency which is Backport of java.time package API

implementation group: 'com.github.seratch', name: 'java-time-backport', version: '1.0.0'


问:
Using docker-compose in azure app service
I got my mean stack code working in a docker-compose configuration. If I run docker-compose up on my pc, then I can login to my app successfully on localhost If go to app service and click on docker-compose preview option and upload my docker-compose.yml file. After deploying it, when I click on the URL for the app I get application error and I'm not sure why. Perhaps I have to change something in my files to make it work in different environment? I appreciate any help with this!

I read somewhere that I don't have to provide username,password, or url details if using ACR in same subscription, which it is. So if that's the case, then authentication isn't the issue.

The frontend docker image and backend docker image are located in the azure container registry. I'm pointing to the registry when I setup docker in app service
The docker logs from azure say

```<code>2020-02-19 15:08:20.257 INFO  - Starting multi-container app, configuration =

2020-02-19 15:08:22.806 ERROR - Pull image threw Exception: Object reference not set to an instance of an object.
2020-02-19 15:08:22.806 ERROR - Pulling docker image  failed:
2020-02-19 15:08:22.806 ERROR - Image pull failed: Verify docker image configuration and credentials (if using private repository)
2020-02-19 15:08:22.806 ERROR - multi-container unit was not started successfully
2020-02-19 15:08:22.831 INFO  - Container logs from testinggc_backend_0_250edca0 =
2020-02-19 15:08:28.902 INFO  - Stoping site testinggc because it failed during startup.
2020-02-19 15:08:30.129 INFO  - Starting multi-container app, configuration =

</code>```

frontend Dockerfile

```<code>FROM node

MAINTAINER Phil

WORKDIR /src

COPY . .

RUN npm install

RUN npm install -g @angular/cli

EXPOSE 4200

CMD ng serve --host 0.0.0.0 --port 4200
</code>```

backend Dockerfile

```<code>FROM node:10.16.3

MAINTAINER Phil

WORKDIR /src

COPY . /src

RUN npm install

RUN npm install -g nodemon

EXPOSE 3000

CMD ["npm", "run", "start"]
</code>```

docker-compose.yml

```<code>
version: '3'
services:
    backend:
        build: ./backend
        ports:
            - "3000:3000"
    frontend:
        build: ./frontend
        ports:
            - "4200:80"

</code>```

答:
For this issue, the problem is the property build of the docker-compose that does not support in Azure App Service. You can get more details about the support options in Docker Compose options.

So the solution for you is to create the image locally yourself and then push them to a docker registry, for example, the Azure Container Registry. Finally, you need to change the build into image. Then deploy it to Azure App Service and it would work fine.

Body:
I got my mean stack code working in a docker-compose configuration. If I run docker-compose up on my pc, then I can login to my app successfully on localhost If go to app service and click on docker-compose preview option and upload my docker-compose.yml file. After deploying it, when I click on the URL for the app I get application error and I'm not sure why. Perhaps I have to change something in my files to make it work in different environment? I appreciate any help with this!

I read somewhere that I don't have to provide username,password, or url details if using ACR in same subscription, which it is. So if that's the case, then authentication isn't the issue.

The frontend docker image and backend docker image are located in the azure container registry. I'm pointing to the registry when I setup docker in app service
The docker logs from azure say

2020-02-19 15:08:20.257 INFO  - Starting multi-container app, configuration =

2020-02-19 15:08:22.806 ERROR - Pull image threw Exception: Object reference not set to an instance of an object.
2020-02-19 15:08:22.806 ERROR - Pulling docker image  failed:
2020-02-19 15:08:22.806 ERROR - Image pull failed: Verify docker image configuration and credentials (if using private repository)
2020-02-19 15:08:22.806 ERROR - multi-container unit was not started successfully
2020-02-19 15:08:22.831 INFO  - Container logs from testinggc_backend_0_250edca0 =
2020-02-19 15:08:28.902 INFO  - Stoping site testinggc because it failed during startup.
2020-02-19 15:08:30.129 INFO  - Starting multi-container app, configuration =

frontend Dockerfile

FROM node

MAINTAINER Phil

WORKDIR /src

COPY . .

RUN npm install

RUN npm install -g @angular/cli

EXPOSE 4200

CMD ng serve --host 0.0.0.0 --port 4200

backend Dockerfile

FROM node:10.16.3

MAINTAINER Phil

WORKDIR /src

COPY . /src

RUN npm install

RUN npm install -g nodemon

EXPOSE 3000

CMD ["npm", "run", "start"]

docker-compose.yml

version: '3'
services:
    backend:
        build: ./backend
        ports:
            - "3000:3000"
    frontend:
        build: ./frontend
        ports:
            - "4200:80"


问:
Bash exit in if statement in a for loop
I am trying to do a for loop in Bash and exit on an if statement but I realised it will break the code before finishing the loop.

```<code>#!/bin/bash

for node in $(ps -ef | awk <something>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    exit 1;

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    exit 2;

  else
    echo "OK!";
    exit 0;
  fi
done
</code>```

My second option is to set a variable instead of the exit outside the loop but then I realised it will override each node status:

```<code>#!/bin/bash

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    status="warning"

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    status="critical"

  else
    echo "OK!";
    status="ok"
  fi
done

if [[ status == "warning" ]]; then
  exit 1;
elif [[ status == "critical" ]]; then
  exit 2;
elif [[ status == "ok" ]]; then
  exit 0;
fi
</code>```

How do I exit properly on each node?

答:
Use continue operator, from man bash

```<code>...
       continue [n]
              Resume the next iteration of the enclosing for, while, until, or select loop.  If n is specified, resume at the nth enclosing loop.  n must be
              ≥ 1.  If n is greater than the number of enclosing loops, the last enclosing loop (the ``top-level'' loop) is resumed.  The return value is  0
              unless n is not greater than or equal to 1.
</code>```

Or break if you need to exit from loop

```<code>...
       break [n]
              Exit  from within a for, while, until, or select loop.  If n is specified, break n levels.  n must be ≥ 1.  If n is greater than the number of
              enclosing loops, all enclosing loops are exited.  The return value is 0 unless n is not greater than or equal to 1.
</code>```

Title: Bash exit in if statement in a for loop

Body:
I am trying to do a for loop in Bash and exit on an if statement but I realised it will break the code before finishing the loop.

#!/bin/bash

for node in $(ps -ef | awk <something>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    exit 1;

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    exit 2;

  else
    echo "OK!";
    exit 0;
  fi
done

My second option is to set a variable instead of the exit outside the loop but then I realised it will override each node status:

#!/bin/bash

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    status="warning"

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    status="critical"

  else
    echo "OK!";
    status="ok"
  fi
done

if [[ status == "warning" ]]; then
  exit 1;
elif [[ status == "critical" ]]; then
  exit 2;
elif [[ status == "ok" ]]; then
  exit 0;
fi

How do I exit properly on each node?

Body:
Use continue operator, from man bash

...
       continue [n]
              Resume the next iteration of the enclosing for, while, until, or select loop.  If n is specified, resume at the nth enclosing loop.  n must be
              ≥ 1.  If n is greater than the number of enclosing loops, the last enclosing loop (the ``top-level'' loop) is resumed.  The return value is  0
              unless n is not greater than or equal to 1.

Or break if you need to exit from loop

...
       break [n]
              Exit  from within a for, while, until, or select loop.  If n is specified, break n levels.  n must be ≥ 1.  If n is greater than the number of
              enclosing loops, all enclosing loops are exited.  The return value is 0 unless n is not greater than or equal to 1.


问:
How to read multiple directories which have different number of files into tensorflow dataset
My tensorflow version is 1.15, and my directory tree is depicted below.

```<code>root
|
|---scene1
|     |
|     |--img1.npy
|     |--img2.npy
|     |--cam.txt
|     |--poses.txt
|
|---scene2
|     |
|     |--img1.npy
|     |--img2.npy
|     |--img3.npy
|     |--cam.txt
|     |--poses.txt
</code>```

Each scene folder contains different number of images(in npy format), but exactly one cam.txt and one poses.txt. I have tried that using numpy.genfromtxt and numpy.load to read files in each scene folder into tensor, then using

ds = tf.data.Dataset.from_tensors to create dataset for each scene, finally using ds.concatenate to concatenate these datasets. This method works, but waste a lot of time when the number of scene folders goes huge. Is there any better way to handle the problem?

答:
I recently ran into a similar problem.

When dealing with very large datasets, Python generators are a good option to go:

[Generators] are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed).

Tensorflow's Dataset class supports them with the static from_generator method (also available with TF 1.15):

import pathlib
import numpy as np
import tensorflow as tf

def scene_generator():
    base_dir = pathlib.Path('path/to/root/')
    scenes = tf.data.Dataset.list_files(str(base_dir / '*'))
    for s in scenes:
        scene_dir = pathlib.Path(s.numpy().decode('utf-8'))
        images = scene_dir / '*.npy'
        data = []
        for i in images:
            with np.load(i) as image:
                features = [image['x1'], image['x2']] # ...
                data.append(features)
        cam   = np.genfromtxt(scene_dir / 'cam.txt')
        poses = np.genfromtxt(scene_dir / 'poses.txt')

        yield data, [cam, poses]

types = (tf.float32, tf.float32)
shapes = (tf.TensorShape([None]), tf.TensorShape([2, None]))
train_data = tf.data.Dataset.from_generator(scene_generator,
    output_types=types,
    output_shapes=shapes)
```

Body:
My tensorflow version is 1.15, and my directory tree is depicted below.

root
|
|---scene1
|     |
|     |--img1.npy
|     |--img2.npy
|     |--cam.txt
|     |--poses.txt
|
|---scene2
|     |
|     |--img1.npy
|     |--img2.npy
|     |--img3.npy
|     |--cam.txt
|     |--poses.txt

Each scene folder contains different number of images(in npy format), but exactly one cam.txt and one poses.txt. I have tried that using numpy.genfromtxt and numpy.load to read files in each scene folder into tensor, then using

ds = tf.data.Dataset.from_tensors to create dataset for each scene, finally using ds.concatenate to concatenate these datasets. This method works, but waste a lot of time when the number of scene folders goes huge. Is there any better way to handle the problem?


问:
How to play a transparent Video in Android?
I have a video with a transparent background that I want to use in my Android project.
I found this library but it's too old and the performance is not so good.
How can I achieve my goal?</p>

答:
You can use videoview like this;

```<code> <VideoView
            android:id="@+id/video_background"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/bottom_navigation_bar"
            app:layout_constraintEnd_toEndOf="parent"
            android:background="@color/transparent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
</code>```

in your activity;

```<code>videoBackgroundView = findViewById(R.id.video_background)
val path = "android.resource://com.example.xxxxx" + "/" + R.raw.video
videoBackgroundView?.setVideoPath(path)
videoBackgroundView?.setOnPreparedListener { mp ->
    mp.isLooping = true
    videoBackgroundView?.start()
}
</code>```

Body:
You can use videoview like this;

 <VideoView
            android:id="@+id/video_background"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/bottom_navigation_bar"
            app:layout_constraintEnd_toEndOf="parent"
            android:background="@color/transparent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

in your activity;

videoBackgroundView = findViewById(R.id.video_background)
val path = "android.resource://com.example.xxxxx" + "/" + R.raw.video
videoBackgroundView?.setVideoPath(path)
videoBackgroundView?.setOnPreparedListener { mp ->
    mp.isLooping = true
    videoBackgroundView?.start()
}