问:
Google.Protobuff timestamp.proto in c#
I have successfully compiled my .proto file with google.proto.Timestamp and generated the .cs file with protoc. The only problem i am having is initialization in my c# code.

I have tried the following:

.proto File

```<code>message teststamp
{
    string Name = 1 ;
    string address = 2;
    google.protobuf.Timestamp _timeStamp = 3;
}
</code>```

C# File

```<code>teststamp test = new teststamp();
test.Name = "Test";
test.address = "Test_Test_TEST"
//Example 2 : POSIX
test._timeStamp.Seconds = DateTime.Now.Second;
test._timeStamp.Nanos = DateTime.Now.Second*1000 ;
</code>```

The above is compiling without errors but giving me this error: Object reference not set to an instance of an object .I have tried few other approaches but due to less help it is unable to fix the error.

Please help me out in this issue

Thanks

答:
Full example for anyone.
More info Official documentation about Google.Protobuf.WellKnownTypes.Timestamp

Proto

```<code>syntax = "proto3";

option csharp_namespace = "Test";
import "google/protobuf/timestamp.proto";

package OnlineGrpc;
service OnlineGrpcService {
  rpc SendMessage(SendMessageRequest) returns (SendMessageResponse);
}
message SendMessageRequest{
    google.protobuf.Timestamp requestDate = 1;
}

message SendMessageResponse{
    google.protobuf.Timestamp responseDate = 1;
}
</code>```

C# send request

```<code>var request = new SendMessageRequest();
request.requestDate = DateTime.Now.ToTimestamp();
request.requestDate = DateTimeOffset.Now.ToTimestamp();
</code>```

C# read response

```<code>var response = new SendMessageResponse();
DateTimeOffset dateOffset = response.responseDate.ToDateTimeOffset();
DateTime date = response.responseDate.ToDateTime();
</code>```

Title: Google.Protobuff timestamp.proto in c#

Body:
I have successfully compiled my .proto file with google.proto.Timestamp and generated the .cs file with protoc. The only problem i am having is initialization in my c# code.

I have tried the following:

.proto File

message teststamp
{
    string Name = 1 ;
    string address = 2;
    google.protobuf.Timestamp _timeStamp = 3;
}

C# File

teststamp test = new teststamp();
test.Name = "Test";
test.address = "Test_Test_TEST"
//Example 2 : POSIX
test._timeStamp.Seconds = DateTime.Now.Second;
test._timeStamp.Nanos = DateTime.Now.Second*1000 ;

The above is compiling without errors but giving me this error: Object reference not set to an instance of an object .I have tried few other approaches but due to less help it is unable to fix the error.

Please help me out in this issue

Thanks

Body:
Full example for anyone.
More info Official documentation about Google.Protobuf.WellKnownTypes.Timestamp

Proto

syntax = "proto3";

option csharp_namespace = "Test";
import "google/protobuf/timestamp.proto";

package OnlineGrpc;
service OnlineGrpcService {
  rpc SendMessage(SendMessageRequest) returns (SendMessageResponse);
}
message SendMessageRequest{
    google.protobuf.Timestamp requestDate = 1;
}

message SendMessageResponse{
    google.protobuf.Timestamp responseDate = 1;
}

C# send request

var request = new SendMessageRequest();
request.requestDate = DateTime.Now.ToTimestamp();
request.requestDate = DateTimeOffset.Now.ToTimestamp();

C# read response

var response = new SendMessageResponse();
DateTimeOffset dateOffset = response.responseDate.ToDateTimeOffset();
DateTime date = response.responseDate.ToDateTime();


来源: stackexchange

问:
change div order in html
I have a htm file with this htm codes :

```<code><div id="masthead">
    <div id="logo">
        #logo<br />
        #logo<br />
        #logo</div>
    <div id="header">
        #header<br />
        #header<br />
        #header</div>
</div>
<div id="container">
    <div id="right_col">
        #right_col<br />
        #right_col<br />
        #right_col<br />
        #right_col<br />
        #right_col</div>
    <div id="top_banner">
        #top_banner<br />
        #top_banner<br />
        #top_banner<br />
        #top_banner</div>
    <div id="left_col">
        #left_col<br />
        #left_col<br />
        #left_col<br />
        #left_col<br />
        #left_col</div>
    <div id="page_content">
        #page_content<br />
        #page_content<br />
        #page_content<br />
        #page_content</div>
</div>
<div id="footer">
    #footer <br />
    #footer <br />
    #footer <br />
    #footer </div>
</code>```

and have a css file for it :

```<code>/* CSS layout */
body {
    margin: 0;
    padding: 0;
    background-color:silver;
    font-family:tahoma;
}

#masthead {
    min-width: 1000px;
}

#logo {
    float: right;
    background-color:lime;
    width: 250px;
}

#header {
    margin-right:250px;
    background-color:aqua;
}

#container {
    clear: both;
    min-width: 1000px;
}

#left_col {
    float: left;
    width: 200px;
    background-color:fuchsia;

}

#right_col {
    float: right;
    width: 200px;
    background-color:orange;
    }

#page_content {
    margin-left: 200px;
    margin-right: 200px;
    background-color:red;

}

#top_banner {
    margin-right: 200px;
    background-color:maroon;

}

#footer {
    clear: both;
    background-color:yellow;
}
</code>```

my html file style load correctly . but now I need that change html code and move left_col and page_content divs . I need that left_col load after page_content in html .

this is new order of this 2 divs.

```<code>    <div id="page_content">
    #page_content<br />
    #page_content<br />
    #page_content<br />
    #page_content</div>
        <div id="left_col">
    #left_col<br />
    #left_col<br />
    #left_col<br />
    #left_col<br />
    #left_col</div>
</code>```

but now my html pages doesn't load correctly and left_col load like this image :

http://i56.tinypic.com/2z9cn6q.png

答: Have a look at this fiddle:http://jsfiddle.net/anish/FzfwG/</p>

ContentLicense: CC BY-SA 3.0

Title: change div order in html

Body:
I have a htm file with this htm codes :

        #logo

        #logo

        #logo

        #header

        #header

        #header

        #right_col

        #right_col

        #right_col

        #right_col

        #right_col

        #top_banner

        #top_banner

        #top_banner

        #top_banner

        #left_col

        #left_col

        #left_col

        #left_col

        #left_col

        #page_content

        #page_content

        #page_content

        #page_content

    #footer

    #footer

    #footer

    #footer

and have a css file for it :

/* CSS layout */
body {
    margin: 0;
    padding: 0;
    background-color:silver;
    font-family:tahoma;
}

#masthead {
    min-width: 1000px;
}

#logo {
    float: right;
    background-color:lime;
    width: 250px;
}

#header {
    margin-right:250px;
    background-color:aqua;
}

#container {
    clear: both;
    min-width: 1000px;
}

#left_col {
    float: left;
    width: 200px;
    background-color:fuchsia;

}

#right_col {
    float: right;
    width: 200px;
    background-color:orange;
    }

#page_content {
    margin-left: 200px;
    margin-right: 200px;
    background-color:red;

}

#top_banner {
    margin-right: 200px;
    background-color:maroon;

}

#footer {
    clear: both;
    background-color:yellow;
}

my html file style load correctly . but now I need that change html code and move left_col and page_content divs . I need that left_col load after page_content in html .

this is new order of this 2 divs.

    #page_content

    #page_content

    #page_content

    #page_content

    #left_col

    #left_col

    #left_col

    #left_col

    #left_col

but now my html pages doesn't load correctly and left_col load like this image :

http://i56.tinypic.com/2z9cn6q.png


问:
Python CSV: Unable to upload file. Index Error("String index out of range")
I am trying to import a file using Python: I understand why I've got this error but don't manage to correct it. The code tries to access a blank line and return an out of range error message. How could I correct this?</p>

```<code>file_data = csv_file.read().decode("utf-8")
print("1")
lines = file_data.split("\n")
#loop over the lines and save them in db. If error , store as string and then display
for line in lines:
    if not line:
        continue
    line = line.strip()
    print(line)
    # following line may not be used, as line is a String, just access as an array
    #b = line.split()
    print(line[0])
    print("2")
    fields = line.split(",")
    data_dict = {}
    data_dict["project_name"] = fields[0]
</code>```

答:
You check if the line is empty with

```<code>if not line:
    continue
</code>```

And after that you strip it

```<code>line = line.strip()
</code>```

But when you strip it, the line can become empty, which you don't check for.

Fix the order of those lines, so you have:

```<code>line = line.strip()
if not line:
    continue
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to import a file using Python: I understand why I've got this error but don't manage to correct it. The code tries to access a blank line and return an out of range error message. How could I correct this?

file_data = csv_file.read().decode("utf-8")
print("1")
lines = file_data.split("\n")
#loop over the lines and save them in db. If error , store as string and then display
for line in lines:
    if not line:
        continue
    line = line.strip()
    print(line)
    # following line may not be used, as line is a String, just access as an array
    #b = line.split()
    print(line[0])
    print("2")
    fields = line.split(",")
    data_dict = {}
    data_dict["project_name"] = fields[0]

Body:
You check if the line is empty with

if not line:
    continue

And after that you strip it

line = line.strip()

But when you strip it, the line can become empty, which you don't check for.

Fix the order of those lines, so you have:

line = line.strip()
if not line:
    continue


问:
Call Oracle stored procedure from Select statement?
I have an Oracle stored procedure that gets 2 parameters and returns 2 parameters (status and message).

I am making changes to this legacy application capable of only executing select statements,

My question is it possible to wrap the stored procedure with some function or other stored procedure or a view, or any other object I might not no about, so can I execute the stored procedure using simple a select statement?

Correct execution code will be something like:

```<code>DECLARE
  PRINTER_ID VARCHAR2(200);
  O_STATUS VARCHAR2(200);
  O_MESSAGE VARCHAR2(200);
BEGIN
  PRINTER_ID := '551555115';
  IMPL_XEROX_PRINTER_CHECK(    PRINTER_ID => PRINTER_ID,    O_STATUS => O_STATUS,    O_MESSAGE => O_MESSAGE  );
  DBMS_OUTPUT.PUT_LINE('O_STATUS = ' || O_STATUS);
  DBMS_OUTPUT.PUT_LINE('O_MESSAGE = ' || O_MESSAGE);
END;
</code>```

What I am trying to get is something like:

```<code>Select O_STATUS,O_MESSAGE from IMPL_XEROX_PRINTER_CHECk_WRAPPER where PRINTER_ID = '551555115';
</code>```

The thing is that the SP is inserting some data to a temporary table...
this is the table:

```<code> CREATE TABLE "TEST_PRNT_DATA"    ( "COLUMN1" VARCHAR2(20 BYTE),    "COLUMN2" VARCHAR2(20 BYTE),    "COLUMN3" VARCHAR2(20 BYTE)   )
</code>```

/

This is the stored procedure:

```<code>CREATE OR REPLACE PROCEDURE IMPL_XEROX_PRINTER_CHECK
(
  PRINTER_ID IN VARCHAR2

, O_STATUS  OUT VARCHAR2
, O_MESSAGE OUT VARCHAR2
)  AS
    PROC_STATUS         VARCHAR2(10);
    PROC_ERROR_MESSAGE  VARCHAR2(4000);

    rand_num number;
BEGIN

     dbms_output.put_line('IMPL_XEROX_PRINTER_CHECK ');
     select round(dbms_random.value(1,10)) into rand_num     from dual;

     insert into TEST_PRNT_DATA values(1,2,3);

    IF rand_num < 5 THEN
            PROC_STATUS  := 'TRUE';
            O_STATUS:= 'TRUE';
            PROC_ERROR_MESSAGE := 'ALL IS GOOD';
            O_MESSAGE:= 'ALL IS GOOD';
    ELSE
            PROC_STATUS  := 'FALSE';
            O_STATUS:= 'FALSE';
            PROC_ERROR_MESSAGE := 'SOMTHING WENT WRONG!!! ';
            O_MESSAGE:= 'SOMTHING WENT WRONG!!! ';
    END IF;

END IMPL_XEROX_PRINTER_CHECK;
</code>```

答:
Based on a combination of a couple of Alex's answers (sys.odcivarchar2list collections and with functions) here are a couple variations on the themes:

The first one returns a single row as with most examples by using a pivot in the last query:

```<code>with function wrap(printer_id in varchar2) return sys.odcivarchar2list as
  status sys.odcivarchar2list;
begin
  status := new sys.odcivarchar2list();
  status.extend(2);
  impl_xerox_printer_check(printer_id, status(1), status(2));
  return status;
end;
t1 as (
select rownum r, column_value
  from wrap('551555115')
)
select *
  from t1
  pivot (max(column_value)
         for r in ( 1 as status
                  , 2 as message));
/
</code>```

Sample Output:

```<code>STATUS   MESSAGE
-------- -------------------------
FALSE    SOMTHING WENT WRONG!!!
</code>```

This second example demonstrates using CROSS APPLY to get the status of multiple printers at one time:

```<code>with function wrap(printer_id in varchar2) return sys.odcivarchar2list as
  status sys.odcivarchar2list;
begin
  status := new sys.odcivarchar2list();
  status.extend(2);
  impl_xerox_printer_check(printer_id, status(1), status(2));
  return status;
end;
printers as (
  select dbms_random.string('X',10) printer from dual connect by level <=5
), t1 as (
select printer, mod(rownum-1,2) r,  w.*
  from printers
  cross apply wrap(printers.printer) w
)
select *
  from t1
  pivot (max(column_value) for r in (0 as status, 1 as message));
/
</code>```

Sample Output:

```<code>PRINTER    STATUS   MESSAGE
---------- -------- -------------------------
M6N6MZ5NG6 TRUE     ALL IS GOOD
4H2WKK52V7 TRUE     ALL IS GOOD
6MB7B9FRWV TRUE     ALL IS GOOD
389KALS4U9 FALSE    SOMTHING WENT WRONG!!!
6Y1ACVUHY6 TRUE     ALL IS GOOD
</code>```

Body:
I have an Oracle stored procedure that gets 2 parameters and returns 2 parameters (status and message).

I am making changes to this legacy application capable of only executing select statements,

My question is it possible to wrap the stored procedure with some function or other stored procedure or a view, or any other object I might not no about, so can I execute the stored procedure using simple a select statement?

Correct execution code will be something like:

DECLARE
  PRINTER_ID VARCHAR2(200);
  O_STATUS VARCHAR2(200);
  O_MESSAGE VARCHAR2(200);
BEGIN
  PRINTER_ID := '551555115';
  IMPL_XEROX_PRINTER_CHECK(    PRINTER_ID => PRINTER_ID,    O_STATUS => O_STATUS,    O_MESSAGE => O_MESSAGE  );
  DBMS_OUTPUT.PUT_LINE('O_STATUS = ' || O_STATUS);
  DBMS_OUTPUT.PUT_LINE('O_MESSAGE = ' || O_MESSAGE);
END;

What I am trying to get is something like:

Select O_STATUS,O_MESSAGE from IMPL_XEROX_PRINTER_CHECk_WRAPPER where PRINTER_ID = '551555115';

The thing is that the SP is inserting some data to a temporary table...
this is the table:

 CREATE TABLE "TEST_PRNT_DATA"    ( "COLUMN1" VARCHAR2(20 BYTE),    "COLUMN2" VARCHAR2(20 BYTE),    "COLUMN3" VARCHAR2(20 BYTE)   )

/

This is the stored procedure:

CREATE OR REPLACE PROCEDURE IMPL_XEROX_PRINTER_CHECK
(
  PRINTER_ID IN VARCHAR2

, O_STATUS  OUT VARCHAR2
, O_MESSAGE OUT VARCHAR2
)  AS
    PROC_STATUS         VARCHAR2(10);
    PROC_ERROR_MESSAGE  VARCHAR2(4000);

    rand_num number;
BEGIN

     dbms_output.put_line('IMPL_XEROX_PRINTER_CHECK ');
     select round(dbms_random.value(1,10)) into rand_num     from dual;

     insert into TEST_PRNT_DATA values(1,2,3);

    IF rand_num < 5 THEN
            PROC_STATUS  := 'TRUE';
            O_STATUS:= 'TRUE';
            PROC_ERROR_MESSAGE := 'ALL IS GOOD';
            O_MESSAGE:= 'ALL IS GOOD';
    ELSE
            PROC_STATUS  := 'FALSE';
            O_STATUS:= 'FALSE';
            PROC_ERROR_MESSAGE := 'SOMTHING WENT WRONG!!! ';
            O_MESSAGE:= 'SOMTHING WENT WRONG!!! ';
    END IF;

END IMPL_XEROX_PRINTER_CHECK;

Body:
Based on a combination of a couple of Alex's answers (sys.odcivarchar2list collections and with functions) here are a couple variations on the themes:

The first one returns a single row as with most examples by using a pivot in the last query:

with function wrap(printer_id in varchar2) return sys.odcivarchar2list as
  status sys.odcivarchar2list;
begin
  status := new sys.odcivarchar2list();
  status.extend(2);
  impl_xerox_printer_check(printer_id, status(1), status(2));
  return status;
end;
t1 as (
select rownum r, column_value
  from wrap('551555115')
)
select *
  from t1
  pivot (max(column_value)
         for r in ( 1 as status
                  , 2 as message));
/

Sample Output:

STATUS   MESSAGE
-------- -------------------------
FALSE    SOMTHING WENT WRONG!!!

This second example demonstrates using CROSS APPLY to get the status of multiple printers at one time:

with function wrap(printer_id in varchar2) return sys.odcivarchar2list as
  status sys.odcivarchar2list;
begin
  status := new sys.odcivarchar2list();
  status.extend(2);
  impl_xerox_printer_check(printer_id, status(1), status(2));
  return status;
end;
printers as (
  select dbms_random.string('X',10) printer from dual connect by level <=5
), t1 as (
select printer, mod(rownum-1,2) r,  w.*
  from printers
  cross apply wrap(printers.printer) w
)
select *
  from t1
  pivot (max(column_value) for r in (0 as status, 1 as message));
/

Sample Output:

PRINTER    STATUS   MESSAGE
---------- -------- -------------------------
M6N6MZ5NG6 TRUE     ALL IS GOOD
4H2WKK52V7 TRUE     ALL IS GOOD
6MB7B9FRWV TRUE     ALL IS GOOD
389KALS4U9 FALSE    SOMTHING WENT WRONG!!!
6Y1ACVUHY6 TRUE     ALL IS GOOD


问:
static IDisposable dictionary pattern
I have a situation like below in a web application. I just wanted to check that it is a good pattern. Could something happen that meant my dictionary was corrupt (some members were disposed and some not, for example)? Have I implemented this idea correctly? </p>

```<code>static IDictionary<string, IDisposable>() _map;

Application_Start()
{
    if (_map == null)
    {
         _map = new IDictionary<string, IDisposable>();
         _map.Add(...);
         _map.Add(...);
    }
}

Application_End
{
    if (_map != null)
    {
        foreach (var m in _map)
        {
            m.Value.Dispose();
        }
        _map = null;
    }
}
</code>```

答:
In addition to what other people have said, there's nothing stopping someone calling Dispose on one of the objects in your dictionary - so it'd be pretty easy for you to have a mix of disposed and undisposed objects.

Of course, if you implement IDisposable properly (i.e. the object checks if it's been disposed) then it might not (but probably will) matter if objects are disposed prematurely...

I can't see that it makes much sense to do this, disposing things as the application ends won't really buy you anything as you're past the point of caring about holding onto unmanaged resources. IDisposable is more about releasing unmanaged resources as soon as possible. Greater minds might correct me, but I'm pretty sure once your application is unloaded, unmanaged resources are freed by the OS anyway.

Title: static IDisposable dictionary pattern

Body:
I have a situation like below in a web application. I just wanted to check that it is a good pattern. Could something happen that meant my dictionary was corrupt (some members were disposed and some not, for example)? Have I implemented this idea correctly?

static IDictionary<string, IDisposable>() _map;

Application_Start()
{
    if (_map == null)
    {
         _map = new IDictionary<string, IDisposable>();
         _map.Add(...);
         _map.Add(...);
    }
}

Application_End
{
    if (_map != null)
    {
        foreach (var m in _map)
        {
            m.Value.Dispose();
        }
        _map = null;
    }
}


问:
angular-material change checkbox color
I'm using checkbox of angular-material2. Currently the default color of checkbox is coming as purple color.

Looks like they have changed default color of checkbox from "primary" to accent.

Is there a way to get "primary"(green) color instead of purple without overriding css.

I tried giving color="primary" to  but that didn't worked.

Code : <md-checkbox></md-checkbox>

Import statement:

```<code>import {MdCheckbox} from '@angular2-material/checkbox';
</code>```

Plunker http://plnkr.co/edit/sFC0kfdzj7fxtUC3GXdr?p=preview

答:
This solution works well for me

.mat-checkbox-ripple .mat-ripple-element,
.mat-checkbox-checked.mat-accent .mat-checkbox-background {
  background-color: $your-color !important;
}
```

Title: angular-material change checkbox color

Body:
I'm using checkbox of angular-material2. Currently the default color of checkbox is coming as purple color.

Looks like they have changed default color of checkbox from "primary" to accent.

Is there a way to get "primary"(green) color instead of purple without overriding css.

I tried giving color="primary" to  but that didn't worked.

Code : <md-checkbox></md-checkbox>

Import statement:

import {MdCheckbox} from '@angular2-material/checkbox';

Plunker http://plnkr.co/edit/sFC0kfdzj7fxtUC3GXdr?p=preview


问:
Qt SQLite no query or parameter count mismatch
Juggling between receiving 2 different errors.

```<code>void summary::on_pushButton_saveSummary_clicked()
{
    if(db.open())
    {
        query.exec("insert or replace into [PN:"+partNum+" CN:"+chargeNum+"](total, defects, rust) values(1, 2, 3)");
        if (!query.exec())
        {
        qDebug() << query.lastError();
        qDebug() << query.exec()<<endl;
        }
     }
    else
    {
        qDebug() << db.lastError();
    }
}
</code>```

The above gives error: QSqlError("", "Unable to fetch row", "No query")

While:

```<code>void summary::on_pushButton_saveSummary_clicked()
{
    if(db.open())
    {
        qDebug() << "db open";
        int a = 3;
        int b = 1;
        int c = 3;

        query.prepare("insert into [PN:"+partNum+" CN:"+chargeNum+"](total, defects, rust) values(:total, :defects, :rust)");
        query.bindValue(":total", a);
        query.bindValue(":defects", b);
        query.bindValue(":rust", c);

        if (!query.exec())
        {
        qDebug() << query.lastError();
        qDebug() << query.exec()<<endl;
        }
    }
    else
    {
        qDebug() << db.lastError();
    }
}
</code>```

Yields: QSqlError("", "Parameter count mismatch", "")

The Constructor has:

```<code>db.setDatabaseName("/home/igraves/Databases/testdb");
db.open();
QString partNum = "134345";
QString chargeNum = "3452";
query.prepare("create table if not exists [PN:"+partNum+" CN:"+chargeNum+"](total int, defects int, rust int)");
query.exec();
</code>```

The table is being create, I can see it. So I am guessing syntax? Although it is as the Qt wiki writes it...

Edit:
Adding some .h stuff

```<code>    QString partNum;
    QString chargeNum;
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    QSqlQuery query;
</code>```

Answer: It was my QString variables being temporary, after the constructor was done, they went out of scope. Changed my .h

```<code>QString partNum = "124124";
QString chargeNum = "234234";
</code>```

答:
I see at least the following errors:

You do not set the database path.

Do not open the database when creating the table.

"134345" and "3452" are being assigned to temporary variables instead of class members

Considering the above, the following must be in the constructor:

partNum = "134345";
chargeNum = "3452";
db.setDatabaseName("/path/of/database.db");
if(db.open())
    query.exec(QString("create table if not exists [PN:%1 CN:%2](total int, defects int, rust int)")
               .arg(partNum)
               .arg(chargeNum));
```

Body:
Juggling between receiving 2 different errors.

void summary::on_pushButton_saveSummary_clicked()
{
    if(db.open())
    {
        query.exec("insert or replace into [PN:"+partNum+" CN:"+chargeNum+"](total, defects, rust) values(1, 2, 3)");
        if (!query.exec())
        {
        qDebug() << query.lastError();
        qDebug() << query.exec()<<endl;
        }
     }
    else
    {
        qDebug() << db.lastError();
    }
}

The above gives error: QSqlError("", "Unable to fetch row", "No query")

While:

void summary::on_pushButton_saveSummary_clicked()
{
    if(db.open())
    {
        qDebug() << "db open";
        int a = 3;
        int b = 1;
        int c = 3;

        query.prepare("insert into [PN:"+partNum+" CN:"+chargeNum+"](total, defects, rust) values(:total, :defects, :rust)");
        query.bindValue(":total", a);
        query.bindValue(":defects", b);
        query.bindValue(":rust", c);

        if (!query.exec())
        {
        qDebug() << query.lastError();
        qDebug() << query.exec()<<endl;
        }
    }
    else
    {
        qDebug() << db.lastError();
    }
}

Yields: QSqlError("", "Parameter count mismatch", "")

The Constructor has:

db.setDatabaseName("/home/igraves/Databases/testdb");
db.open();
QString partNum = "134345";
QString chargeNum = "3452";
query.prepare("create table if not exists [PN:"+partNum+" CN:"+chargeNum+"](total int, defects int, rust int)");
query.exec();

The table is being create, I can see it. So I am guessing syntax? Although it is as the Qt wiki writes it...

Edit:
Adding some .h stuff

    QString partNum;
    QString chargeNum;
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    QSqlQuery query;

Answer: It was my QString variables being temporary, after the constructor was done, they went out of scope. Changed my .h

QString partNum = "124124";
QString chargeNum = "234234";


问:
Request.auth.metadata in security rules?
I have a Firebase project where I'd like for users to be able to see when other users created their profiles. My initial hope was that I could use "user.metadata.creationTime" on the frontend to pass the date into the user's extra info document and verify that it is correct by having "request.resource.data.datecreated == request.auth.metadata.creationTime" as a Database Rule, but it looks like it is not possible according to the documentation.

Is there any way I can verify that the creation date is correct on the backend?

More info edit: Below is the code that is being triggered when a user creates a new account on my profile. The three values are displayed publicly. I'm creating a niche gear for sale page so being able to see when a user first created their account could be helpful when deciding if a seller is sketchy. I don't want someone to be able to make it seem like they have been around for longer than they have been.

```<code>    db.collection('users').doc(user.uid).set({
        username: "Username-156135",
        bio: "Add a bio",
        created: user.metadata.creationTime
    });
</code>```

Firestore rules:

```<code> match /users/{id} {
  allow get;
  allow create, update: if request.resource.data.username is string &&
    request.resource.data.bio is string &&
    request.resource.data.created == request.auth.metadata.creationTime;
}
</code>```

答:
user.metadata.creationTime, according to the API documentation is a string with no documented format.  I suggest not using it.  In fact, what you're trying to do seems impossible since that value isn't available in the API documentation for request.auth.

What I suggest you do instead is use a Firebase Auth onCreate trigger with Cloud Functions to automatically create that document with the current time as a proper timestamp.  Then, in security rules, I wouldn't even give the user the ability to change that field, so you can be sure it was only ever set accurately by the trigger.  You might be interested in this solution overall.

Body:
I have a Firebase project where I'd like for users to be able to see when other users created their profiles. My initial hope was that I could use "user.metadata.creationTime" on the frontend to pass the date into the user's extra info document and verify that it is correct by having "request.resource.data.datecreated == request.auth.metadata.creationTime" as a Database Rule, but it looks like it is not possible according to the documentation.

Is there any way I can verify that the creation date is correct on the backend?

More info edit: Below is the code that is being triggered when a user creates a new account on my profile. The three values are displayed publicly. I'm creating a niche gear for sale page so being able to see when a user first created their account could be helpful when deciding if a seller is sketchy. I don't want someone to be able to make it seem like they have been around for longer than they have been.

    db.collection('users').doc(user.uid).set({
        username: "Username-156135",
        bio: "Add a bio",
        created: user.metadata.creationTime
    });

Firestore rules:

 match /users/{id} {
  allow get;
  allow create, update: if request.resource.data.username is string &&
    request.resource.data.bio is string &&
    request.resource.data.created == request.auth.metadata.creationTime;
}


问:
Filter Gallery based on text in label
I'm struggling with this for days now.

I've made a PowerApp in which a Document Library is shown from SharePoint in a Gallery. In this list there's a label which contains the data from a multiple selection in SharePoint.

SharePoint Multiple selection

The values are shown in a label using the formula below:

```<code>Concat(ThisItem.'Behandelende Afdeling';Value & ", ")
</code>```

This works fine, as you're able to see in this capture: List in PowerApps

In this case, 'Klantenteam Groen' is returned.

Now, I want to filter the Gallery in order to show just the items which contain "Inkoop" in the label. So, for example, if the label is "Klantenteam Groen, Inkoop, Order Afgerond" it should be shown in the list, but if it doesn't contain the "Inkoop" part is should not be shown.

Do you guys have any ideas?

Many thanks in advance!

Kelsey.

The names:

- Label which returns the multiple values: Txt_BehandelendeAfd

- Name of the gallery: BrowseGallery1

- Name of the SharePoint Document Library: Orderproces

- Name of the Multiple Selection option: 'Behandelende Afdeling'

答:
Can you share the current formula on the items property of your Gallery?
The changes should be made on this formula.

If it hasn't been modified, I believe you should have something like

SortByColumns(Filter(Orderproces, StartsWith(Title, TextSearchBox1.Text)), "Title", If(SortDescending1, Descending, Ascending))

You can modify it to something like

SortByColumns(Filter(Orderproces, StartsWith(Title, TextSearchBox1.Text) || TextSearchBox1.Text in 'Behandelende Afdeling'), "Title", If(SortDescending1, Descending, Ascending))

Title: Filter Gallery based on text in label

Body:
I'm struggling with this for days now.

I've made a PowerApp in which a Document Library is shown from SharePoint in a Gallery. In this list there's a label which contains the data from a multiple selection in SharePoint.

SharePoint Multiple selection

The values are shown in a label using the formula below:

Concat(ThisItem.'Behandelende Afdeling';Value & ", ")

This works fine, as you're able to see in this capture: List in PowerApps

In this case, 'Klantenteam Groen' is returned.

Now, I want to filter the Gallery in order to show just the items which contain "Inkoop" in the label. So, for example, if the label is "Klantenteam Groen, Inkoop, Order Afgerond" it should be shown in the list, but if it doesn't contain the "Inkoop" part is should not be shown.

Do you guys have any ideas?

Many thanks in advance!

Kelsey.

The names:

- Label which returns the multiple values: Txt_BehandelendeAfd

- Name of the gallery: BrowseGallery1

- Name of the SharePoint Document Library: Orderproces

- Name of the Multiple Selection option: 'Behandelende Afdeling'


问:
Nativescript Vue Image stretch aspectFill not working
I am working on a Nativescript-vue app, and am having a strange problem with the Image component not sizing correctly.

I am trying to use stretch="aspectFill" to correctly size an image for a component. It works initially when live previewing in the ios simulator, but when you next render the component it reduces size to fit the space rather than aspectFill. My component code is below.

```<code> <StackLayout>
    <Image :src="promo.image" stretch="aspectFill" height="200" />
    <StackLayout class="promocontainer" row="1" padding="0">
      <GridLayout columns="*,*" class="region">
        <Label col="0" :text="promo.region" />
        <Label col="1" :text="'$' + promo.price" textAlignment="right" />
      </GridLayout>
      <Label :text="promo.inclusions_heading" class="heading" />
      <Label :text="promo.heading" padding="10" textWrap="true" class="tagline" />
      <Label :text="promo.introText" padding="10" textWrap="true" class="text" />
    </StackLayout>
  </StackLayout>
</code>```

When you change the strech option, the live preview in ios show the intended behavior as shown below

When interacting with the app, navigating away from this page and back, or previewing on a physical ios device, the image is show as below, instead of the intended aspect filled image as above.

I am hoping someone has run into this before and might be able to assist with working out a solution.

答:
The component was being added to a ListView, which was causing the rendering issues above. I resolved this by instead wrapping the components in a ScrollView and StackLayout. This solved the stretch rendering issue straight away.

Original code with stretch bug:

```<code><ListView for="promo in promos" @itemTap="onPromoTap">
   <v-template>
      <PromoListItem :promo="promo" />
   </v-template>
</ListView>
</code>```

Solution:

```<code><ScrollView>
    <StackLayout>
        <PromoListItem margin="10" v-for="promo in promos" :key="promo.heading" :promo="promo" />
    </StackLayout>
</ScrollView>
</code>```

It looks like ListView calculates it's item sizing differently, and is not compatible with Image stretch, at least when there is other content involved.

Body:
I am working on a Nativescript-vue app, and am having a strange problem with the Image component not sizing correctly.

I am trying to use stretch="aspectFill" to correctly size an image for a component. It works initially when live previewing in the ios simulator, but when you next render the component it reduces size to fit the space rather than aspectFill. My component code is below.

 <StackLayout>
    <Image :src="promo.image" stretch="aspectFill" height="200" />
    <StackLayout class="promocontainer" row="1" padding="0">
      <GridLayout columns="*,*" class="region">

      </GridLayout>

    </StackLayout>
  </StackLayout>

When you change the strech option, the live preview in ios show the intended behavior as shown below

When interacting with the app, navigating away from this page and back, or previewing on a physical ios device, the image is show as below, instead of the intended aspect filled image as above.

I am hoping someone has run into this before and might be able to assist with working out a solution.

Body:
The component was being added to a ListView, which was causing the rendering issues above. I resolved this by instead wrapping the components in a ScrollView and StackLayout. This solved the stretch rendering issue straight away.

Original code with stretch bug:

<ListView for="promo in promos" @itemTap="onPromoTap">
   <v-template>
      <PromoListItem :promo="promo" />
   </v-template>
</ListView>

Solution:

<ScrollView>
    <StackLayout>
        <PromoListItem margin="10" v-for="promo in promos" :key="promo.heading" :promo="promo" />
    </StackLayout>
</ScrollView>

It looks like ListView calculates it's item sizing differently, and is not compatible with Image stretch, at least when there is other content involved.


问:
problem with ColdFusion cfqueryparam and a complicated query
I have a query where I am inserting ~300 records using one insert query.  For each record, I have to do replaces and operations on the data.  I just found out I have to use cfqueryparam now because one of the records is a CLOB and is reaching a large size.  I was using a string to form the query and placing the string in the cfquery tag. Now I can't do that because you have to use PreserveSingleQuotes to put a string var in a cfquery tag and you can't use PreserveSingleQuotes with cfqueryparam.  So is my best option to do all the operations and looping inside the cfquery tag?  Will it be able to handle that?  Or will I have to do 1000 separate insert statements?  Is there a better idea?  thanks.</p>

答:
If you're only doing PreserveSingleQuotes, then the above answer works.

If you're doing complex manipulation, then do your operations on your data outside of cfquery and store your good values into an array.

Inside the cfquery, loop through the array and put the values into cfqueryparam.


问:
Dynamic nested serializer field Django REST Framework
I am trying to have a serializer of a Parent model, with a nested serializer as a field, being different regarding another string field.

For example, if the registry_type field is equal to intra I want to use _IntraRegistrySerializer to serialize/deserialize the registry_data field, but if registry_type is equal to slack, I want to use _SlackRegistrySerializer for the same field.

I managed to have the serialization working doing this:

class RegistrySerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if isinstance(instance, IntraRegistry):
            data["registry_type"] = "intra"
            data["registry_data"] = _IntraRegistrySerializer(instance=instance).data
        if isinstance(instance, SlackRegistry):
            data["registry_type"] = "slack"
            data["registry_data"] = _SlackRegistrySerializer(instance=instance).data
        return data

    class Meta:
        # `Registry` being the parent model of both `IntraRegistry` and `SlackRegistry`
        model = Registry
        fields = ["id", "description"]
```

But it only does half of what I would like to do.

I tried overloading methods, using SerializerMethodField, and even though I keep on searching and reading the doc I can't manage to find a solution.

答:
This does seem like a good SerializerMethodField case:

class RegistrySerializer(serializers.ModelSerializer):
    registry_type = serializers.SerializerMethodField()
    registry_data = serializers.SerializerMethodField()

    def get_registry_type(self, obj):
        if isinstance(instance, IntraRegistry):
            return "intra"
        if isinstance(instance, SlackRegistry):
            return "slack"

    def get_registry_data(self, obj):
        if isinstance(instance, IntraRegistry):
            return _IntraRegistrySerializer(instance=obj, context=self.context).data
        if isinstance(instance, SlackRegistry):
            return _SlackRegistrySerializer(instance=obj, context=self.context).data

    class Meta:
        # `Registry` being the parent model of both `IntraRegistry` and `SlackRegistry`
        model = Registry
        fields = ["id", "description", "registry_type", "registry_data"]
```

The above is the implementation of the serializer method fields and should work since both of the registries inherit from Registry.

You may still need to tweak it to your needs. One difference compared to the current implementation is that the registry_type and registry_data will now always be present. They'll be null if this is a Registry object type or some other child type not handled here.

Body:
I am trying to have a serializer of a Parent model, with a nested serializer as a field, being different regarding another string field.

For example, if the registry_type field is equal to intra I want to use _IntraRegistrySerializer to serialize/deserialize the registry_data field, but if registry_type is equal to slack, I want to use _SlackRegistrySerializer for the same field.

I managed to have the serialization working doing this:

class RegistrySerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if isinstance(instance, IntraRegistry):
            data["registry_type"] = "intra"
            data["registry_data"] = _IntraRegistrySerializer(instance=instance).data
        if isinstance(instance, SlackRegistry):
            data["registry_type"] = "slack"
            data["registry_data"] = _SlackRegistrySerializer(instance=instance).data
        return data

    class Meta:
        # `Registry` being the parent model of both `IntraRegistry` and `SlackRegistry`
        model = Registry
        fields = ["id", "description"]

But it only does half of what I would like to do.

I tried overloading methods, using SerializerMethodField, and even though I keep on searching and reading the doc I can't manage to find a solution.

Body:
This does seem like a good SerializerMethodField case:

class RegistrySerializer(serializers.ModelSerializer):
    registry_type = serializers.SerializerMethodField()
    registry_data = serializers.SerializerMethodField()

    def get_registry_type(self, obj):
        if isinstance(instance, IntraRegistry):
            return "intra"
        if isinstance(instance, SlackRegistry):
            return "slack"

    def get_registry_data(self, obj):
        if isinstance(instance, IntraRegistry):
            return _IntraRegistrySerializer(instance=obj, context=self.context).data
        if isinstance(instance, SlackRegistry):
            return _SlackRegistrySerializer(instance=obj, context=self.context).data

    class Meta:
        # `Registry` being the parent model of both `IntraRegistry` and `SlackRegistry`
        model = Registry
        fields = ["id", "description", "registry_type", "registry_data"]

The above is the implementation of the serializer method fields and should work since both of the registries inherit from Registry.

You may still need to tweak it to your needs. One difference compared to the current implementation is that the registry_type and registry_data will now always be present. They'll be null if this is a Registry object type or some other child type not handled here.


问:
matplotlib: place legend labels where each trace intercepts the right-hand y-axis
I have multiple lines plotted on an xy scatter plot

There are more than the number of colours in my palette, which means the colours start cycling.

I have played with using other palettes but the visibility suffers.

An idea I would like to explore now is to add the legend labels at the point where each line intercepts the right-hand y-axis.

Something like this:

Is this possible to achieve with matplotlib and/or seaborn?

答:
Quick one, with use of the other answer to this question

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

names = ['foo', 'bar', 'foobar']
N_size = 100
fig, ax = plt.subplots(1, 1)
df = pd.DataFrame(map(lambda x: pd.Series(np.cumsum(np.random.rand(N_size) - 0.5), name=x), names)).T
df.plot(ax=ax)
ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())
ax2.set_yticks([df[col].iloc[-1] for col in df.columns])
ax2.set_yticklabels(df.columns)
plt.show()
```


问:
SequelizeConnectionRefusedError JSON MySQL
Hey there I am trying to have a /create function on my REST server. I work on C9.io

```<code>var express = require("express")
var bodyParser = require("body-parser")
var cors = require("cors")
var Sequelize = require("sequelize")
var util = require("util")

var app  = express()
app.use(bodyParser.json())
 app.use(cors())

var sequelize = new Sequelize('authordb','root','',{
dialect : 'mysql',
port : 3305
})

var Author = sequelize.define('author',{
name : Sequelize.STRING,
email : {
    type : Sequelize.STRING,
    validate : {
        isEmail : true
    }
 }
 })

 var Message = sequelize.define('message',{
subject : Sequelize.STRING,
content : Sequelize.STRING
 })

Author.hasMany(Message, {onDelete : 'cascade'})
Message.belongsTo(Author)

  app.get('/create', function(req,res){
sequelize.sync()
    .complete(function(err){
        if (err){
            console.log(err)
        }
        else{
            res.status(201).send('created all')
        }
    })
  })

 app.post('/authors',function(req,res){
var author = req.body
Author.create(author)
    .complete(function(err){
        if (err){
            console.log(err)
        }
        else{
            res.status(201).send('created author')
        }
    })
   })

app.get('/authors/:id',function(req,res){
Author.find({
    where : {
        id : req.params.id
    },
    attributes : ['id','name','email']
})
.complete(function(err,authorDAO){
        if (err){
            console.log(err)
        }
        else{
            // console.log(authorDAO)
            // util.inspect(authorDAO)
            var author = authorDAO.dataValues
            res.status(200).send(author)
        }
  })
   })

   app.put('/authors/:id',function(req,res){
   var newValues = req.body
    Author.find({
    where : {
        id : req.params.id
    }
   })
.success(function(authorDAO) {
    authorDAO.email = newValues.email
    authorDAO.name = newValues.name
    authorDAO.save(['email','name'])
        .success(function(){
            res.status(202).send('modified author')
        })
 })
    })

    app.delete('/authors/:id',function(req,res){
   Author.find({
    where : {
        id : req.params.id
    }
 })
.success(function(authorDAO) {
    authorDAO.destroy()
        .success(function(){
            res.status(202).send('deleted author')
        })
  })

    })

  app.post('/authors/:id/messages',function(req, res) {
var message = req.body
Author.find({
    where : {
        id : req.params.id
    }
})
.success(function(authorDAO){
    Message.create(message)
        .success(function(messageDAO){
            authorDAO.addMessage(messageDAO)
                .success(function(){
                    res.status(201).send('create message')
                })
        })
     })
   })

   app.get('/authors/:id/messages',function(req, res) {
   Author.find({
    where : {
        id : req.params.id
    },
    include : {model : Message, as : 'messages'}
    })
  .success(function(authorDAO) {
    var messages = authorDAO.dataValues.messages
    res.status(200).send(messages)
   })
    })

  app.listen(8080)
</code>```

The error is :

{ [SequelizeConnectionRefusedError: connect ECONNREFUSED]
  name: 'SequelizeConnectionRefusedError',
  message: 'connect ECONNREFUSED',
  parent:
   { [Error: connect ECONNREFUSED]
     code: 'ECONNREFUSED',
     errno: 'ECONNREFUSED',
     syscall: 'connect',
     fatal: true },
  original:
   { [Error: connect ECONNREFUSED]
     code: 'ECONNREFUSED',
     errno: 'ECONNREFUSED',
     syscall: 'connect',
     fatal: true } }
```

答:
Just installed MAMP 5.7

Settings are no longer available, but connection made when using default MAMP mySQL port of 8889. Happy days!

Body:
Hey there I am trying to have a /create function on my REST server. I work on C9.io

var express = require("express")
var bodyParser = require("body-parser")
var cors = require("cors")
var Sequelize = require("sequelize")
var util = require("util")

var app  = express()
app.use(bodyParser.json())
 app.use(cors())

var sequelize = new Sequelize('authordb','root','',{
dialect : 'mysql',
port : 3305
})

var Author = sequelize.define('author',{
name : Sequelize.STRING,
email : {
    type : Sequelize.STRING,
    validate : {
        isEmail : true
    }
 }
 })

 var Message = sequelize.define('message',{
subject : Sequelize.STRING,
content : Sequelize.STRING
 })

Author.hasMany(Message, {onDelete : 'cascade'})
Message.belongsTo(Author)

  app.get('/create', function(req,res){
sequelize.sync()
    .complete(function(err){
        if (err){
            console.log(err)
        }
        else{
            res.status(201).send('created all')
        }
    })
  })

 app.post('/authors',function(req,res){
var author = req.body
Author.create(author)
    .complete(function(err){
        if (err){
            console.log(err)
        }
        else{
            res.status(201).send('created author')
        }
    })
   })

app.get('/authors/:id',function(req,res){
Author.find({
    where : {
        id : req.params.id
    },
    attributes : ['id','name','email']
})
.complete(function(err,authorDAO){
        if (err){
            console.log(err)
        }
        else{
            // console.log(authorDAO)
            // util.inspect(authorDAO)
            var author = authorDAO.dataValues
            res.status(200).send(author)
        }
  })
   })

   app.put('/authors/:id',function(req,res){
   var newValues = req.body
    Author.find({
    where : {
        id : req.params.id
    }
   })
.success(function(authorDAO) {
    authorDAO.email = newValues.email
    authorDAO.name = newValues.name
    authorDAO.save(['email','name'])
        .success(function(){
            res.status(202).send('modified author')
        })
 })
    })

    app.delete('/authors/:id',function(req,res){
   Author.find({
    where : {
        id : req.params.id
    }
 })
.success(function(authorDAO) {
    authorDAO.destroy()
        .success(function(){
            res.status(202).send('deleted author')
        })
  })

    })

  app.post('/authors/:id/messages',function(req, res) {
var message = req.body
Author.find({
    where : {
        id : req.params.id
    }
})
.success(function(authorDAO){
    Message.create(message)
        .success(function(messageDAO){
            authorDAO.addMessage(messageDAO)
                .success(function(){
                    res.status(201).send('create message')
                })
        })
     })
   })

   app.get('/authors/:id/messages',function(req, res) {
   Author.find({
    where : {
        id : req.params.id
    },
    include : {model : Message, as : 'messages'}
    })
  .success(function(authorDAO) {
    var messages = authorDAO.dataValues.messages
    res.status(200).send(messages)
   })
    })

  app.listen(8080)

The error is :

{ [SequelizeConnectionRefusedError: connect ECONNREFUSED]
  name: 'SequelizeConnectionRefusedError',
  message: 'connect ECONNREFUSED',
  parent:
   { [Error: connect ECONNREFUSED]
     code: 'ECONNREFUSED',
     errno: 'ECONNREFUSED',
     syscall: 'connect',
     fatal: true },
  original:
   { [Error: connect ECONNREFUSED]
     code: 'ECONNREFUSED',
     errno: 'ECONNREFUSED',
     syscall: 'connect',
     fatal: true } }


问:
Playback and listen to recording device in FMOD
Is it possible to simultaneously playback the recording device by using the FMOD api? This functionality would be the same to what Windows offers in the recording device properties where you can enable "listen to this device" for certain recording devices. If this isn't possible via FMOD, is there another API more suited for this functionality?</p>

答:
You can achieve this with FMOD by simply recording with looping set to true, then play the recorded sound as looping also. Providing you separate your recordStart call and your playSound call by some time (say 10ms) the play cursor and the record cursor will follow each other and you will get realtime playback.

There is an example of this with the "recording" example that ships in the FMOD API for most platforms and there is a more advanced example on the Windows platform that shows adding realtime effects to a live recorded sound.


问:
In Flutter, is it possible to set my MaterialApp's themeData to use uppercase as default for all Text Values?
I am working on an app that uses Uppercase texts in all screens, I think it is production effective if I can add something like this:

```<code>...
return MaterialApp(
      title: '***',
      theme: ThemeData(
        primaryColor: Color(0xFF101639),
        textTheme: Theme.of(context).textTheme.copyWith(
              body1: TextStyle(
                color: Colors.white,
                //*****{uppercase should be set here.. where it can take effects in all parts of the app}
              ),
            ),
      ),
      home: HomePage(),
    );
...
</code>```

Unfortunately, I don't know how to do this in this way, another effective method will be accepted. Thanks.
AN APPLICATION EXAMPLE THAT USES MOSTLY UPPERCASE

答:
I don't think it's possible to set that in the theme, but what you can do is create this custom widget:

```<code>import 'package:flutter/material.dart';

class UpperCaseText extends Text {
  UpperCaseText(
    String data, {
    Key key,
    TextStyle style,
    StrutStyle strutStyle,
    TextAlign textAlign,
    TextDirection textDirection,
    Locale locale,
    bool softWrap,
    TextOverflow overflow,
    double textScaleFactor,
    int maxLines,
    String semanticsLabel,
    TextWidthBasis textWidthBasis,
  }) : super(
          data.toUpperCase(),
          key: key,
          style: style,
          strutStyle: strutStyle,
          textAlign: textAlign,
          textDirection: textDirection,
          locale: locale,
          softWrap: softWrap,
          overflow: overflow,
          textScaleFactor: textScaleFactor,
          maxLines: maxLines,
          semanticsLabel: semanticsLabel,
          textWidthBasis: textWidthBasis,
        );
}
</code>```

And use it everywhere you want upper case text instead of the Text widget.

Body:
I am working on an app that uses Uppercase texts in all screens, I think it is production effective if I can add something like this:

...
return MaterialApp(
      title: '***',
      theme: ThemeData(
        primaryColor: Color(0xFF101639),
        textTheme: Theme.of(context).textTheme.copyWith(
              body1: TextStyle(
                color: Colors.white,
                //*****{uppercase should be set here.. where it can take effects in all parts of the app}
              ),
            ),
      ),
      home: HomePage(),
    );
...

Unfortunately, I don't know how to do this in this way, another effective method will be accepted. Thanks.
AN APPLICATION EXAMPLE THAT USES MOSTLY UPPERCASE

Body:
I don't think it's possible to set that in the theme, but what you can do is create this custom widget:

import 'package:flutter/material.dart';

class UpperCaseText extends Text {
  UpperCaseText(
    String data, {
    Key key,
    TextStyle style,
    StrutStyle strutStyle,
    TextAlign textAlign,
    TextDirection textDirection,
    Locale locale,
    bool softWrap,
    TextOverflow overflow,
    double textScaleFactor,
    int maxLines,
    String semanticsLabel,
    TextWidthBasis textWidthBasis,
  }) : super(
          data.toUpperCase(),
          key: key,
          style: style,
          strutStyle: strutStyle,
          textAlign: textAlign,
          textDirection: textDirection,
          locale: locale,
          softWrap: softWrap,
          overflow: overflow,
          textScaleFactor: textScaleFactor,
          maxLines: maxLines,
          semanticsLabel: semanticsLabel,
          textWidthBasis: textWidthBasis,
        );
}

And use it everywhere you want upper case text instead of the Text widget.


问:
SQL First and Last Occurrences - Group By forcing me to group everything in select
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>```

Learning on the go. My query below will list out all the EmployeeID's and not just the first Cohort ID and last Cohort ID. Group by forces me to group StartDateTimestamp2 with employeeid and it still lists all employee ID's, and does not look like intended result below.

Ideally, the (first occurrences) result should be:

```<code>CohortID | StartDateTimestamp2
-------- | -------------------
1        | 20080501 01:30:00
2        | 20190115 05:52:14
</code>```

My Query Below

```<code>SELECT firsttable.Cohortid,
       employeetable.StartDateTimestamp2
FROM   Table1 firsttable
INNER JOIN Employee employeetable ON employeetable.employeeid = firsttable.employeeid
</code>```

The actual question:
Use first instance of CohortName to determine the start date of each cohort

Result:

```<code>Cohort ID | StartDateTimesstamp2
</code>```

答:
For this dataset, simple aggregation should do it:

```<code>select cohortID, min(StartDateTimestamp) StartDateTimestamp2
from table1
group by cohortID
</code>```

Or, possibly:

```<code>select
    t.cohortid,
    min(e.startdatetimestamp2) startdatetimestamp2
from table1 t
inner join employee e on e.employeeid = t.employeeid
group by t.cohort_id
</code>```

Body:
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

Learning on the go. My query below will list out all the EmployeeID's and not just the first Cohort ID and last Cohort ID. Group by forces me to group StartDateTimestamp2 with employeeid and it still lists all employee ID's, and does not look like intended result below.

Ideally, the (first occurrences) result should be:

CohortID | StartDateTimestamp2
-------- | -------------------
1        | 20080501 01:30:00
2        | 20190115 05:52:14

My Query Below

SELECT firsttable.Cohortid,
       employeetable.StartDateTimestamp2
FROM   Table1 firsttable
INNER JOIN Employee employeetable ON employeetable.employeeid = firsttable.employeeid

The actual question:
Use first instance of CohortName to determine the start date of each cohort

Result:

Cohort ID | StartDateTimesstamp2

Body:
For this dataset, simple aggregation should do it:

select cohortID, min(StartDateTimestamp) StartDateTimestamp2
from table1
group by cohortID

Or, possibly:

select
    t.cohortid,
    min(e.startdatetimestamp2) startdatetimestamp2
from table1 t
inner join employee e on e.employeeid = t.employeeid
group by t.cohort_id


问:
Do I need to transfer ownership *back* to the transfer queue on next transfer?
I'm planning on using one of the vulkan synchronization examples as reference for how to handle infrequently updated uniform buffers.  Specifically I was looking at this one:

```<code>vkBeginCommandBuffer(...);

// Submission guarantees the host write being complete, as per
// https://www.khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#synchronization-submission-host-writes
// So no need for a barrier before the transfer

// Copy the staging buffer contents to the vertex buffer
VkBufferCopy vertexCopyRegion = {
    .srcOffset = stagingMemoryOffset,
    .dstOffset = vertexMemoryOffset,
    .size      = vertexDataSize};

vkCmdCopyBuffer(
    commandBuffer,
    stagingBuffer,
    vertexBuffer,
    1,
    &vertexCopyRegion);

// If the graphics queue and transfer queue are the same queue
if (isUnifiedGraphicsAndTransferQueue)
{
    // If there is a semaphore signal + wait between this being submitted and
    // the vertex buffer being used, then skip this pipeline barrier.

    // Pipeline barrier before using the vertex data
    // Note that this can apply to all buffers uploaded in the same way, so
    // ideally batch all copies before this.
    VkMemoryBarrier memoryBarrier = {
        ...
        .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
        .dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT};

    vkCmdPipelineBarrier(
        ...
        VK_PIPELINE_STAGE_TRANSFER_BIT ,      // srcStageMask
        VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,   // dstStageMask
        1,                                    // memoryBarrierCount
        &memoryBarrier,                       // pMemoryBarriers
        ...);

    vkEndCommandBuffer(...);

    vkQueueSubmit(unifiedQueue, ...);
}
else
{
    // Pipeline barrier to start a queue ownership transfer after the copy
    VkBufferMemoryBarrier bufferMemoryBarrier = {
        ...
        .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
        .dstAccessMask = 0,
        .srcQueueFamilyIndex = transferQueueFamilyIndex,
        .dstQueueFamilyIndex = graphicsQueueFamilyIndex,
        .buffer = vertexBuffer,
        ...};

    vkCmdPipelineBarrier(
        ...
        VK_PIPELINE_STAGE_TRANSFER_BIT ,      // srcStageMask
        VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, // dstStageMask
        1,                                    // bufferMemoryBarrierCount
        &bufferMemoryBarrier,                 // pBufferMemoryBarriers
        ...);

    vkEndCommandBuffer(...);

    // Ensure a semaphore is signalled here which will be waited on by the graphics queue.
    vkQueueSubmit(transferQueue, ...);

    // Record a command buffer for the graphics queue.
    vkBeginCommandBuffer(...);

    // Pipeline barrier before using the vertex buffer, after finalising the ownership transfer
    VkBufferMemoryBarrier bufferMemoryBarrier = {
        ...
        .srcAccessMask = 0,
        .dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT,
        .srcQueueFamilyIndex = transferQueueFamilyIndex,
        .dstQueueFamilyIndex = graphicsQueueFamilyIndex,
        .buffer = vertexBuffer,
        ...};

    vkCmdPipelineBarrier(
        ...
        VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,    // srcStageMask
        VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,   // dstStageMask
        ...
        1,                                    // bufferMemoryBarrierCount
        &bufferMemoryBarrier,                 // pBufferMemoryBarriers
        ...);

    vkEndCommandBuffer(...);

    vkQueueSubmit(graphicsQueue, ...);
}
</code>```

In this example, I simplify it to mean:

```<code>map updated buffer which is host coherent
perform transfer in transfer queue to device local memory
    make sure to put a buffer memory barrier to handle the queue ownership transfer
perform normal draw commands
    make sure to put a buffer memory barrier to handle receiving of buffer in queue ownership
</code>```

Must I then give back the ability for the transfer queue to copy that data again?  None of the examples seem to mention it, but I could have missed it.  I can't really see how adding another buffer barrier would work for the same draw command buffer as it would stall on the next submission even if I didn't have anything to transfer, so would I just need to submit another command buffer just for queue ownership transfer before I submit my next transfer operation?

ie

```<code>//begin with transfer ownership
submit(copy)
submit(ownership to graphics)
submit(draw)
submit(ownership to transfer)
submit(copy)
submit(ownership to graphics)
submit(draw)
submit(draw)
submit(draw)
submit(ownership to transfer)
submit(copy)
submit(ownership to graphics)
submit(draw)
</code>```

If that is the case, I'm unsure of how to handle the semaphore signaling between draw and transfer, and copy and draw. At the beginning it is easy, but then it gets strange because of multiple i nflight frames, as there would be no dependency between draw submits. Basically I guess I would need to set what ever the most recent draw command I submitted to have a semaphore to signal the transfer of ownership, which would signal the copy, which would signal the ownership of graphics, and if it was on a separate thread I would then check if this copy was submitted, and require a wait on the ownership of graphics transfer and resetting the copy submitted check.  But I'm not sure what happens to the next frame which doesn't have this dependency, and could finish before what would chronologically be the previous frame?

答:
You can use a Resource on any queue family (without a transfer) as long as you do not mind that the data becomes undefined. You still need a Semaphore to make sure there is no memory hazard.

Ye olde spec:

NOTE

If an application does not need the contents of a resource to remain valid when transferring from one queue family to another, then the ownership transfer should be skipped.

Examples do not mention it, because they are only examples.

As for synchronization (which is a separate problem from QFOT), a semaphore signal which is part of vkQueueSubmit covers everything previously in submission order. So when you submit the copy you would let it wait on the Semaphore that the last draw submitted has signaled. That means that draw and any previous draw on that queue is finished, before the copy can start on the other queue.

Then you signal a semaphore by the copy, and wait on it on the first next draw you submit. That means the copy finished writing, before the draw (and any subsequent draw) reads it on the graphics queue.

e.g.:

```<code>submit(copy, release ownership from tranfer, semaphore signal)
submit(semaphore wait, acquire ownership to graphics, draw)
submit(draw)
submit(draw)
submit(draw)
submit(draw)
submit(draw, semaphore signal)
submit(semaphore wait, copy, release ownership from tranfer, semaphore signal)
submit(semaphore wait, acquire ownership to graphics, draw)
submit(draw)
submit(draw)
etc

</code>```

Though note the above approach practically serializes the two kinds of accesses, so it might be suboptimal. Employing double-buffering (or generally N-buffering) can be better. If you have more buffers, you could start copying into one without worying it is already used by something else. That means a copy can happen in paralel with a draw, which would be great.

Body:
I'm planning on using one of the vulkan synchronization examples as reference for how to handle infrequently updated uniform buffers.  Specifically I was looking at this one:

vkBeginCommandBuffer(...);

// Submission guarantees the host write being complete, as per
// https://www.khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#synchronization-submission-host-writes
// So no need for a barrier before the transfer

// Copy the staging buffer contents to the vertex buffer
VkBufferCopy vertexCopyRegion = {
    .srcOffset = stagingMemoryOffset,
    .dstOffset = vertexMemoryOffset,
    .size      = vertexDataSize};

vkCmdCopyBuffer(
    commandBuffer,
    stagingBuffer,
    vertexBuffer,
    1,
    &vertexCopyRegion);

// If the graphics queue and transfer queue are the same queue
if (isUnifiedGraphicsAndTransferQueue)
{
    // If there is a semaphore signal + wait between this being submitted and
    // the vertex buffer being used, then skip this pipeline barrier.

    // Pipeline barrier before using the vertex data
    // Note that this can apply to all buffers uploaded in the same way, so
    // ideally batch all copies before this.
    VkMemoryBarrier memoryBarrier = {
        ...
        .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
        .dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT};

    vkCmdPipelineBarrier(
        ...
        VK_PIPELINE_STAGE_TRANSFER_BIT ,      // srcStageMask
        VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,   // dstStageMask
        1,                                    // memoryBarrierCount
        &memoryBarrier,                       // pMemoryBarriers
        ...);

    vkEndCommandBuffer(...);

    vkQueueSubmit(unifiedQueue, ...);
}
else
{
    // Pipeline barrier to start a queue ownership transfer after the copy
    VkBufferMemoryBarrier bufferMemoryBarrier = {
        ...
        .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
        .dstAccessMask = 0,
        .srcQueueFamilyIndex = transferQueueFamilyIndex,
        .dstQueueFamilyIndex = graphicsQueueFamilyIndex,
        .buffer = vertexBuffer,
        ...};

    vkCmdPipelineBarrier(
        ...
        VK_PIPELINE_STAGE_TRANSFER_BIT ,      // srcStageMask
        VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, // dstStageMask
        1,                                    // bufferMemoryBarrierCount
        &bufferMemoryBarrier,                 // pBufferMemoryBarriers
        ...);

    vkEndCommandBuffer(...);

    // Ensure a semaphore is signalled here which will be waited on by the graphics queue.
    vkQueueSubmit(transferQueue, ...);

    // Record a command buffer for the graphics queue.
    vkBeginCommandBuffer(...);

    // Pipeline barrier before using the vertex buffer, after finalising the ownership transfer
    VkBufferMemoryBarrier bufferMemoryBarrier = {
        ...
        .srcAccessMask = 0,
        .dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT,
        .srcQueueFamilyIndex = transferQueueFamilyIndex,
        .dstQueueFamilyIndex = graphicsQueueFamilyIndex,
        .buffer = vertexBuffer,
        ...};

    vkCmdPipelineBarrier(
        ...
        VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,    // srcStageMask
        VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,   // dstStageMask
        ...
        1,                                    // bufferMemoryBarrierCount
        &bufferMemoryBarrier,                 // pBufferMemoryBarriers
        ...);

    vkEndCommandBuffer(...);

    vkQueueSubmit(graphicsQueue, ...);
}

In this example, I simplify it to mean:

map updated buffer which is host coherent
perform transfer in transfer queue to device local memory
    make sure to put a buffer memory barrier to handle the queue ownership transfer
perform normal draw commands
    make sure to put a buffer memory barrier to handle receiving of buffer in queue ownership

Must I then give back the ability for the transfer queue to copy that data again?  None of the examples seem to mention it, but I could have missed it.  I can't really see how adding another buffer barrier would work for the same draw command buffer as it would stall on the next submission even if I didn't have anything to transfer, so would I just need to submit another command buffer just for queue ownership transfer before I submit my next transfer operation?

ie

//begin with transfer ownership
submit(copy)
submit(ownership to graphics)
submit(draw)
submit(ownership to transfer)
submit(copy)
submit(ownership to graphics)
submit(draw)
submit(draw)
submit(draw)
submit(ownership to transfer)
submit(copy)
submit(ownership to graphics)
submit(draw)

If that is the case, I'm unsure of how to handle the semaphore signaling between draw and transfer, and copy and draw. At the beginning it is easy, but then it gets strange because of multiple i nflight frames, as there would be no dependency between draw submits. Basically I guess I would need to set what ever the most recent draw command I submitted to have a semaphore to signal the transfer of ownership, which would signal the copy, which would signal the ownership of graphics, and if it was on a separate thread I would then check if this copy was submitted, and require a wait on the ownership of graphics transfer and resetting the copy submitted check.  But I'm not sure what happens to the next frame which doesn't have this dependency, and could finish before what would chronologically be the previous frame?

Body:
You can use a Resource on any queue family (without a transfer) as long as you do not mind that the data becomes undefined. You still need a Semaphore to make sure there is no memory hazard.

Ye olde spec:

NOTE

If an application does not need the contents of a resource to remain valid when transferring from one queue family to another, then the ownership transfer should be skipped.

Examples do not mention it, because they are only examples.

As for synchronization (which is a separate problem from QFOT), a semaphore signal which is part of vkQueueSubmit covers everything previously in submission order. So when you submit the copy you would let it wait on the Semaphore that the last draw submitted has signaled. That means that draw and any previous draw on that queue is finished, before the copy can start on the other queue.

Then you signal a semaphore by the copy, and wait on it on the first next draw you submit. That means the copy finished writing, before the draw (and any subsequent draw) reads it on the graphics queue.

e.g.:

submit(copy, release ownership from tranfer, semaphore signal)
submit(semaphore wait, acquire ownership to graphics, draw)
submit(draw)
submit(draw)
submit(draw)
submit(draw)
submit(draw, semaphore signal)
submit(semaphore wait, copy, release ownership from tranfer, semaphore signal)
submit(semaphore wait, acquire ownership to graphics, draw)
submit(draw)
submit(draw)
etc

Though note the above approach practically serializes the two kinds of accesses, so it might be suboptimal. Employing double-buffering (or generally N-buffering) can be better. If you have more buffers, you could start copying into one without worying it is already used by something else. That means a copy can happen in paralel with a draw, which would be great.


问:
Decrease the size of Twitter Feed
I have been trying to decrease the size of my Twitter feed in order to make it look nice and place other components on the same page for my Vue.js page. How do I half the size of the feed and place it in a border? Thank you.

export default {
  data() {
    return { //returning data
    }
  },
  mounted() {
    let twitterScript = document.createElement('script')
    twitterScript.setAttribute('src', 'https://platform.twitter.com/widgets.js')
    document.head.appendChild(twitterScript)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
      <div class="flex-box mt-3">

      </div>
</template></code>```

答:
According to their docs, you need to include a limit to the number of Tweets displayed.  For example, to display only three Tweets, you indicate it like so:</p>

```<code><a class="twitter-timeline"
  href="https://twitter.com/TwitterDev"
  data-tweet-limit="3"><!-- adjust this number to your liking -->

    Tweets by @TwitterDev
</a>
</code>```

Title: Decrease the size of Twitter Feed

Body:
I have been trying to decrease the size of my Twitter feed in order to make it look nice and place other components on the same page for my Vue.js page. How do I half the size of the feed and place it in a border? Thank you.

export default {
  data() {
    return { //returning data
    }
  },
  mounted() {
    let twitterScript = document.createElement('script')
    twitterScript.setAttribute('src', 'https://platform.twitter.com/widgets.js')
    document.head.appendChild(twitterScript)
  }
}

<template>

</template>

Body:
According to their docs, you need to include a limit to the number of Tweets displayed.  For example, to display only three Tweets, you indicate it like so:

<a class="twitter-timeline"
  href="https://twitter.com/TwitterDev"
  data-tweet-limit="3"><!-- adjust this number to your liking -->

    Tweets by @TwitterDev
</a>


问:
Async variable stored in $rootScope not available in other controllers
I am using Angular 1.x for my stack and when I make an API call and store the response in the $rootScope, it is not accessible in other controllers' view.

My controller:

```<code>angularApp.controller('mainController', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http){

  var checkIfAuthenticated = function(){
    return $http.get('/api/isAuthenticated');
  };

  checkIfAuthenticated()
  .then(function(res) {
    if(res.status===200){
        console.log("Success");
        $rootScope.userLoggedIn = true;
    }
  })
}]);
</code>```

Now, in another controller's view I use it like this:

```<code><div ng-if="userLoggedIn" class="py-1 pl-1 pr-1">
  <span><b>Message Board</b></span>
  <div class="form-control" readonly id="lockTextbox">Show something</div>
</div>
</code>```

The problem is, the API call /api/isAuthenticated does provide the right response (status 200) but the ng-view gets it wrong.

I am sure this is to do with $rootScope.userLoggedIn being a response from an async call (as I get Success in my console) but how do I solve it?

Thanks in advance!

EDIT

After I posted the question, I noticed that in the mainController's view, the ng-if logic doesn't work either. What is very strange is that when I open up the browser's debug console, it starts working! I think this is just an async issue but I don't know how to solve it. How do I tell the view that the variable is on it's way?

答:
Working Example

The below demo shows the $rootScope variable available in both controllers after being set from a promise delayed by two seconds.

angular.module("app",[])
.controller('mainController', function($scope, $rootScope, $timeout) {
  var checkIfAuthenticated = function(){
    return $timeout(function() {
        return { status: 200 };
    }, 2000);
  };
  checkIfAuthenticated()
  .then(function(res) {
    if(res.status===200){
        console.log("Success");
        $rootScope.userLoggedIn = true;
    }
  })
})
.controller('otherController', function($scope) {
  console.log("other controller");
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
  <fieldset ng-controller="mainController">
     MAIN Controller userLoggedIn={{userLoggedIn}}<br>
     <div ng-if="userLoggedIn">
        Message Board - Show something
     </div>
  </fieldset>
  <fieldset ng-controller="otherController">
     OTHER Controller userLoggedIn={{userLoggedIn}}
     <div ng-if="userLoggedIn">
        Message Board - Show something
     </div>
  </fieldset>
</body></code>```

Body:
I am using Angular 1.x for my stack and when I make an API call and store the response in the $rootScope, it is not accessible in other controllers' view.

My controller:

angularApp.controller('mainController', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http){

  var checkIfAuthenticated = function(){
    return $http.get('/api/isAuthenticated');
  };

  checkIfAuthenticated()
  .then(function(res) {
    if(res.status===200){
        console.log("Success");
        $rootScope.userLoggedIn = true;
    }
  })
}]);

Now, in another controller's view I use it like this:

  Message Board

Show something

The problem is, the API call /api/isAuthenticated does provide the right response (status 200) but the ng-view gets it wrong.

I am sure this is to do with $rootScope.userLoggedIn being a response from an async call (as I get Success in my console) but how do I solve it?

Thanks in advance!

EDIT

After I posted the question, I noticed that in the mainController's view, the ng-if logic doesn't work either. What is very strange is that when I open up the browser's debug console, it starts working! I think this is just an async issue but I don't know how to solve it. How do I tell the view that the variable is on it's way?

Body:
Working Example

The below demo shows the $rootScope variable available in both controllers after being set from a promise delayed by two seconds.

angular.module("app",[])
.controller('mainController', function($scope, $rootScope, $timeout) {
  var checkIfAuthenticated = function(){
    return $timeout(function() {
        return { status: 200 };
    }, 2000);
  };
  checkIfAuthenticated()
  .then(function(res) {
    if(res.status===200){
        console.log("Success");
        $rootScope.userLoggedIn = true;
    }
  })
})
.controller('otherController', function($scope) {
  console.log("other controller");
})

<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
  <fieldset ng-controller="mainController">
     MAIN Controller userLoggedIn={{userLoggedIn}}<br>
     <div ng-if="userLoggedIn">
        Message Board - Show something
     </div>
  </fieldset>
  <fieldset ng-controller="otherController">
     OTHER Controller userLoggedIn={{userLoggedIn}}
     <div ng-if="userLoggedIn">
        Message Board - Show something
     </div>
  </fieldset>
</body>


问:
How can I make XSLT work in chrome?
I have an XML document here that is served with a corresponding XSL file. The transformation is left to be executed client-side, without JavaScript.

This works fine in IE (shock horror), but in Google Chrome, just displays the document's text nodes.

I know that it is possible to do client-side XSL in Chrome, as I have seen examples of it, but I am yet to be able to replicate this success myself

What am I doing wrong?

答:
Well it does not work if the XML file (starting by the standard PI:

```<code><?xml-stylesheet type="text/xsl" href="..."?>
</code>```

for referencing the XSL stylesheet) is served as "application/xml". In that case, Chrome will still download the referenced XSL stylesheet, but nothing will be rendered, as it will silently change the document types from "application/xml" into "Document" (!??) and "text/xsl" into "Stylesheet" (!??), and then will attempt to render the XML document as if it was an HTML(5) document, without running first its XSLT processor. And Nothing at all will be displayed in the screen (whose content will continue to show the previous page from which the XML page was referenced, and will continue spinning the icon, as if the document was never completely loaded.

You can perfectly use the Chrome console, that shows that all resources are loaded, but they are incorrectly interpreted.

So yes, Chrome currently only render XML files (with its optional leading XSL stylesheet declaration), only if it is served as "text/xml", but not as "application/xml" as it should for client-side rendered XML with an XSL declaration.

For XML files served as "text/xml" or "application/xml" and that do not contain an XSL stylesheet declaration, Chrome should still use a default stylesheet to render it as a DOM tree, or at least as its text source. But it does not, and here again it attempts to render it as if it was HTML, and bugs immediately on many scripts (including a default internal one) that attempt to access to "document.body" for handling onLoad events and inject some javascript handler in it.

An example of site that does not work as expected (the Common Lisp documentation) in Chrome, but works in IE which supports client-side XSLT:

http://common-lisp.net/project/bknr/static/lmman/toc.html

This index page above is displayed correctly, but all links will drive to XML documents with a basic XSL declaration to an existing XSL stylesheet document, and you can wait indefinitely, thinking that the chapters have problems to be downloaded. All you can do to read the docuemntation is to open the console and read the source code in the Resources tab.

ContentLicense: CC BY-SA 2.5

Title: How can I make XSLT work in chrome?

Body:
Well it does not work if the XML file (starting by the standard PI:

<?xml-stylesheet type="text/xsl" href="..."?>

for referencing the XSL stylesheet) is served as "application/xml". In that case, Chrome will still download the referenced XSL stylesheet, but nothing will be rendered, as it will silently change the document types from "application/xml" into "Document" (!??) and "text/xsl" into "Stylesheet" (!??), and then will attempt to render the XML document as if it was an HTML(5) document, without running first its XSLT processor. And Nothing at all will be displayed in the screen (whose content will continue to show the previous page from which the XML page was referenced, and will continue spinning the icon, as if the document was never completely loaded.

You can perfectly use the Chrome console, that shows that all resources are loaded, but they are incorrectly interpreted.

So yes, Chrome currently only render XML files (with its optional leading XSL stylesheet declaration), only if it is served as "text/xml", but not as "application/xml" as it should for client-side rendered XML with an XSL declaration.

For XML files served as "text/xml" or "application/xml" and that do not contain an XSL stylesheet declaration, Chrome should still use a default stylesheet to render it as a DOM tree, or at least as its text source. But it does not, and here again it attempts to render it as if it was HTML, and bugs immediately on many scripts (including a default internal one) that attempt to access to "document.body" for handling onLoad events and inject some javascript handler in it.

An example of site that does not work as expected (the Common Lisp documentation) in Chrome, but works in IE which supports client-side XSLT:

http://common-lisp.net/project/bknr/static/lmman/toc.html

This index page above is displayed correctly, but all links will drive to XML documents with a basic XSL declaration to an existing XSL stylesheet document, and you can wait indefinitely, thinking that the chapters have problems to be downloaded. All you can do to read the docuemntation is to open the console and read the source code in the Resources tab.


问:
Compute sum Odoo
I have made a custom module budget with the field Value. I would like to sum all the values for the budgets I've made today

```<code>    def value_budget_day(self):
    for budget in self:
        # Encontrar si hoy es el mismo dia que se creo un presupuesto
        c_date = datetime.strftime(budget.create_date, "%Y-%m-%d %H:%M:%S")
        t_date = datetime.strftime(budget.today, "%Y-%m-%d %H:%M:%S")
        create_day = c_date[:10]
        today_day = t_date[:10]

        if create_day == today_day:
            # Sumar todos los valores de los presupuestos de ese día
           total = 0.0
           for val in budget:
               total += val.value
           budget.today_value = total

        else:
            budget.today_value = 35
</code>```

In my code the values are not sum

答:
```<code>def value_budget_day(self):
    total = 0
    for budget in self:
        # Encontrar si hoy es el mismo dia que se creo un presupuesto
        c_date = datetime.strftime(budget.create_date, "%Y-%m-%d %H:%M:%S")
        t_date = datetime.strftime(budget.today, "%Y-%m-%d %H:%M:%S")
        create_day = c_date[:10]
        today_day = t_date[:10]

        if create_day == today_day:
            # Sumar todos los valores de los presupuestos de ese día
            total += budget.value
            budget.today_value = total

        else:
            budget.today_value = 0

today_value = fields.Float(compute='value_budget_day')
</code>```

Title: Compute sum Odoo

Body:
I have made a custom module budget with the field Value. I would like to sum all the values for the budgets I've made today

    def value_budget_day(self):
    for budget in self:
        # Encontrar si hoy es el mismo dia que se creo un presupuesto
        c_date = datetime.strftime(budget.create_date, "%Y-%m-%d %H:%M:%S")
        t_date = datetime.strftime(budget.today, "%Y-%m-%d %H:%M:%S")
        create_day = c_date[:10]
        today_day = t_date[:10]

        if create_day == today_day:
            # Sumar todos los valores de los presupuestos de ese día
           total = 0.0
           for val in budget:
               total += val.value
           budget.today_value = total

        else:
            budget.today_value = 35

In my code the values are not sum


问:
How to get specific query value from string?
I would like to get myInfo value from the below-given string test:

```<code>public class Test {
    public static void main(String[] args) {

        String test = "{q=code=in=(100,110,120,100);product=in=(393,393);ID==33323323, myInfo==test, offset=0, limit=200}";
    }
}
</code>```

Expected output:

```<code>test
</code>```

How to split and get the required value?

答:
One of the possible solutions for this task will be using Pattern class.

Here is code demo:

```<code>public class RegexDemo {
    public static void main(String[] args) {
        String test = "{q=code=in=(100,110,120,100);product=in=(393,393);ID==33323323, myInfo==test, offset=0, limit=200}";

        printMyInfoValue(test);
    }

    private static void printMyInfoValue(String test) {
        Pattern pattern = Pattern.compile("\\s+myInfo==(\\w+)");
        Matcher matcher = pattern.matcher(test);

        if (matcher.find()) {
            System.out.printf("My Info value: %s\n", matcher.group(1).trim());
        }
    }
}
</code>```

Output:

test

At regex, we are checking if myInfo is presented in a text. If yes just group the results with parenthesis ().

For group with index 0 group(0) we will have full regex value:

myInfo==test

For 1 group group(1) only value:

test

It is exactly what we are looking for.

If no myInfo key is presented for input text -> no printing result.

Body:
I would like to get myInfo value from the below-given string test:

public class Test {
    public static void main(String[] args) {

        String test = "{q=code=in=(100,110,120,100);product=in=(393,393);ID==33323323, myInfo==test, offset=0, limit=200}";
    }
}

Expected output:

test

How to split and get the required value?

Body:
One of the possible solutions for this task will be using Pattern class.

Here is code demo:

public class RegexDemo {
    public static void main(String[] args) {
        String test = "{q=code=in=(100,110,120,100);product=in=(393,393);ID==33323323, myInfo==test, offset=0, limit=200}";

        printMyInfoValue(test);
    }

    private static void printMyInfoValue(String test) {
        Pattern pattern = Pattern.compile("\\s+myInfo==(\\w+)");
        Matcher matcher = pattern.matcher(test);

        if (matcher.find()) {
            System.out.printf("My Info value: %s\n", matcher.group(1).trim());
        }
    }
}

Output:

test

At regex, we are checking if myInfo is presented in a text. If yes just group the results with parenthesis ().

For group with index 0 group(0) we will have full regex value:

myInfo==test

For 1 group group(1) only value:

test

It is exactly what we are looking for.

If no myInfo key is presented for input text -> no printing result.


问:
Changing NA values in a column to preceding values until other binary number appears
I have a data that looks like this:

```<code>SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:01   NA
3   1/27/20 18:02   1
4   1/27/20 18:03   NA
5   1/27/20 18:04   0
6   1/27/20 18:05   1
7   1/27/20 18:06   NA
8   1/27/20 18:07   NA
9   1/27/20 18:08   0
</code>```

Basically, my question is how can I change the NA value to its presiding value?  I mean for NA in row 2, the answer would be the same as earlier row number 1 i.e. 0. For NAs at row 7 and 8, the answer would be that of row 6 which is 1. For NA at row 4, the value would be replaced by the number in row 3, which is 1.

Is it possible to program like that?

I would be thankful if anyone could help.

Thanks.

答:
You could try</p>

```<code>while(any(is.na(df$MOTOR))
{
  na_entries <- which(is.na(df$MOTOR))
  df$MOTOR[na_entries] <- df$MOTOR[na_entries - 1]
}
</code>```

Body:
I have a data that looks like this:

SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:01   NA
3   1/27/20 18:02   1
4   1/27/20 18:03   NA
5   1/27/20 18:04   0
6   1/27/20 18:05   1
7   1/27/20 18:06   NA
8   1/27/20 18:07   NA
9   1/27/20 18:08   0

Basically, my question is how can I change the NA value to its presiding value?  I mean for NA in row 2, the answer would be the same as earlier row number 1 i.e. 0. For NAs at row 7 and 8, the answer would be that of row 6 which is 1. For NA at row 4, the value would be replaced by the number in row 3, which is 1.

Is it possible to program like that?

I would be thankful if anyone could help.

Thanks.

Body:
You could try

while(any(is.na(df$MOTOR))
{
  na_entries <- which(is.na(df$MOTOR))
  df$MOTOR[na_entries] <- df$MOTOR[na_entries - 1]
}


问:
How to access Activity UI from my class?
I have an activity which creates an object instance of my class:

```<code>file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (TextView)findViewById(R.id.myView);
    ...
    Points myPoints new Points();
    ...
}
--------------------------------------------------------------

file Points.java:
private class Points {
    ...
    HOW TO USE myView HERE ???
    ...
}
--------------------------------------------------------------
</code>```

How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?

答:
You can pass the main Activity's context (using Points(getApplicationContext());) to the class as a constructor parameter.  You could also pass the specific UI elements you want to manipulate.

A better way to do it, however, may be to have Points not know about the Activity.  Have your Activity call Points methods and take the necessary actions based on the method output.

Body:
I have an activity which creates an object instance of my class:

file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (TextView)findViewById(R.id.myView);
    ...
    Points myPoints new Points();
    ...
}
--------------------------------------------------------------

file Points.java:
private class Points {
    ...
    HOW TO USE myView HERE ???
    ...
}
--------------------------------------------------------------

How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?


问:
Kusto: remove non-matching rows when using the parse operator
I'm querying azure log analytics using Kusto, and extracting fields with the parse operator, then keeping only the records which parsed correctly:

```<code>traces
| parse message with "Search found " people " people in " groupCount " groups"
| where people != "" and groupCount != ""
| order by n desc
</code>```

Is there a more terse way of parsing and dropping non-matching rows? If I am parsing out a lot of columns from a set of logs, maybe containing partial matches, this connascence between the parse and where gets fiddly.

By comparison, in SumoLogic, the parse operator automatically drops all rows which don't match a parsed pattern, which makes for really tidy pipelines:

```<code>*
| parse "Search found * people in * groups" as people, groupCount
| order by n desc
</code>```

答:
There's now a built in operator that will do this: parse-where

https://learn.microsoft.com/en-us/azure/kusto/query/parsewhereoperator

It has syntax just like parse, but will omit from its output any records which didn't match the parse pattern.

So the query:

```<code>traces
| parse message with "Search found " people " people in " groupCount " groups"
| where people != "" and groupCount != ""
| order by n desc
</code>```

becomes:

```<code>traces
| parse-where message with "Search found " people " people in " groupCount " groups"
| order by n desc
</code>```

Body:
I'm querying azure log analytics using Kusto, and extracting fields with the parse operator, then keeping only the records which parsed correctly:

traces
| parse message with "Search found " people " people in " groupCount " groups"
| where people != "" and groupCount != ""
| order by n desc

Is there a more terse way of parsing and dropping non-matching rows? If I am parsing out a lot of columns from a set of logs, maybe containing partial matches, this connascence between the parse and where gets fiddly.

By comparison, in SumoLogic, the parse operator automatically drops all rows which don't match a parsed pattern, which makes for really tidy pipelines:

*
| parse "Search found * people in * groups" as people, groupCount
| order by n desc

Body:
There's now a built in operator that will do this: parse-where

https://learn.microsoft.com/en-us/azure/kusto/query/parsewhereoperator

It has syntax just like parse, but will omit from its output any records which didn't match the parse pattern.

So the query:

traces
| parse message with "Search found " people " people in " groupCount " groups"
| where people != "" and groupCount != ""
| order by n desc

becomes:

traces
| parse-where message with "Search found " people " people in " groupCount " groups"
| order by n desc


问:
Aerospike - WARN Failed to connect to peer errors in AQL
When I try to run AQL I get a spam of the errors in my console below.

```<code>WARN Failed to connect to peer 192.168.12.51 3000. AEROSPIKE_ERR_TIMEOUT , 192.168.12.51:3000
WARN Failed to connect to peer **ANOTHER IP HERE**. AEROSPIKE_ERR_CLIENT Invalid proto type: 84 Expected: 1, **ANOTHER IP HERE**
WARN Failed to connect to peer 192.168.12.51 3000. AEROSPIKE_ERR_CONNECTION Socket write error: 113, 192.168.12.51:3000
***ABOVE 3 ERRORS KEEP REPEATING***

</code>```

My local IP is NOT 192.168.12.51

From the looks of it, someone else is also running aerospike locally, and my machine is trying to connect to it.

I am unable to type any commands in AQL.

How do we stop this behaviour?

答: run your aerospike on a different port? in config change from 3000 to say 3030?  then, all tools, aql etc, you just have to specify -p 3030 on the command line to go to the correct port.</p>

Body:
When I try to run AQL I get a spam of the errors in my console below.

WARN Failed to connect to peer 192.168.12.51 3000. AEROSPIKE_ERR_TIMEOUT , 192.168.12.51:3000
WARN Failed to connect to peer **ANOTHER IP HERE**. AEROSPIKE_ERR_CLIENT Invalid proto type: 84 Expected: 1, **ANOTHER IP HERE**
WARN Failed to connect to peer 192.168.12.51 3000. AEROSPIKE_ERR_CONNECTION Socket write error: 113, 192.168.12.51:3000
***ABOVE 3 ERRORS KEEP REPEATING***

My local IP is NOT 192.168.12.51

From the looks of it, someone else is also running aerospike locally, and my machine is trying to connect to it.

I am unable to type any commands in AQL.

How do we stop this behaviour?